TheCitadelofRicks/src/main/kotlin/org/mosad/thecitadelofricks/hsoparser/TimetableLinkListParser.kt

87 lines
2.9 KiB
Kotlin

/**
* TheCitadelofRicks
*
* Copyright 2019-2020 <seil0@mosad.xyz>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
package org.mosad.thecitadelofricks.hsoparser
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.mosad.thecitadelofricks.Course
import org.mosad.thecitadelofricks.Room
import org.slf4j.LoggerFactory
import java.net.SocketTimeoutException
sealed class TimetableLinkListParser<T> {
private var logger: org.slf4j.Logger = LoggerFactory.getLogger(TimetableLinkListParser::class.java)
abstract fun constructValue(key: String, link: String): T
abstract val blacklist: List<String>
abstract val liClass: String
/**
* return a list of all elements at listURL
* @param listURL the url to the list page
* @return a ArrayList<T> with all links or null if the request was not successful
*/
fun getLinks(listURL: String): HashMap<String, T>? {
val linkList = HashMap<String, T>()
try {
val courseHTML = Jsoup.connect(listURL).get()
courseHTML
.select("ul.index-group")
.select("li.$liClass")
.select("a[href]")
.filter{ it: Element -> !blacklist.contains(it.text()) }
.forEach {
linkList[it.text()] = constructValue(
it.text(),
it.attr("href").replace("http:", "https:")
)
}
logger.info("successfully retrieved link List")
} catch (ex: SocketTimeoutException) {
logger.warn("timeout from hs-offenburg.de, updating on next attempt!")
return null
} catch (gex: Exception) {
logger.error("general TimetableLinkListParser error", gex)
return null
}
return linkList
}
}
class CourseListParser : TimetableLinkListParser<Course>() {
override fun constructValue(key: String, link: String) = Course(key, link)
override val blacklist = emptyList<String>()
override val liClass = "Class"
}
class RoomListParser : TimetableLinkListParser<Room>() {
override fun constructValue(key: String, link: String) = Room(key, link)
override val blacklist = listOf("STÜBER SYSTEMS")
override val liClass = "Room"
}