SauceNaoAPI/src/commonMain/kotlin/com/insanusmokrassar/SauceNaoAPI/exceptions/TooManyRequestsException.kt

36 lines
1.6 KiB
Kotlin
Raw Normal View History

2020-08-29 13:09:54 +00:00
package com.insanusmokrassar.SauceNaoAPI.exceptions
2019-08-19 08:13:43 +00:00
2020-08-29 13:09:54 +00:00
import com.insanusmokrassar.SauceNaoAPI.additional.LONG_TIME_RECALCULATING_MILLIS
import com.insanusmokrassar.SauceNaoAPI.additional.SHORT_TIME_RECALCULATING_MILLIS
2019-12-13 18:21:12 +00:00
import com.soywiz.klock.TimeSpan
2019-08-19 08:13:43 +00:00
import io.ktor.client.features.ClientRequestException
2020-08-13 05:17:11 +00:00
import io.ktor.client.statement.readText
2019-08-19 08:13:43 +00:00
import io.ktor.http.HttpStatusCode.Companion.TooManyRequests
2020-08-13 05:17:11 +00:00
import io.ktor.utils.io.errors.IOException
2019-08-19 08:13:43 +00:00
2019-12-13 18:21:12 +00:00
internal suspend fun ClientRequestException.sauceNaoAPIException(): Exception {
2020-08-22 17:00:07 +00:00
val response = response ?: return this
2019-12-13 18:21:12 +00:00
return when (response.status) {
TooManyRequests -> {
val answerContent = response.readText()
when {
answerContent.contains("daily limit") -> TooManyRequestsLongException(answerContent)
else -> TooManyRequestsShortException(answerContent)
}
}
else -> this
}
2019-08-19 08:13:43 +00:00
}
2020-08-22 17:00:07 +00:00
sealed class TooManyRequestsException(message: String, cause: Throwable? = null) : IOException(message, cause) {
2019-12-13 18:21:12 +00:00
abstract val answerContent: String
abstract val waitTime: TimeSpan
}
2020-08-22 17:00:07 +00:00
class TooManyRequestsShortException(override val answerContent: String) : TooManyRequestsException("Too many requests were sent in the short period") {
2019-12-13 18:21:12 +00:00
override val waitTime: TimeSpan = SHORT_TIME_RECALCULATING_MILLIS
}
2020-08-22 17:00:07 +00:00
class TooManyRequestsLongException(override val answerContent: String) : TooManyRequestsException("Too many requests were sent in the long period") {
2019-12-13 18:21:12 +00:00
override val waitTime: TimeSpan = LONG_TIME_RECALCULATING_MILLIS
}