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

216 lines
7.9 KiB
Kotlin
Raw Normal View History

2020-08-29 13:09:54 +00:00
package com.insanusmokrassar.SauceNaoAPI
2019-02-20 12:18:01 +00:00
2020-08-29 13:09:54 +00:00
import com.insanusmokrassar.SauceNaoAPI.exceptions.TooManyRequestsException
import com.insanusmokrassar.SauceNaoAPI.exceptions.sauceNaoAPIException
import com.insanusmokrassar.SauceNaoAPI.models.*
import com.insanusmokrassar.SauceNaoAPI.utils.*
2019-02-20 12:18:01 +00:00
import io.ktor.client.HttpClient
2019-08-19 08:13:43 +00:00
import io.ktor.client.features.ClientRequestException
import io.ktor.client.request.*
2020-08-29 13:09:54 +00:00
import io.ktor.client.request.forms.MultiPartFormDataContent
import io.ktor.client.request.forms.formData
2020-08-13 05:17:11 +00:00
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.readText
2019-12-12 18:47:52 +00:00
import io.ktor.http.*
2020-08-13 05:17:11 +00:00
import io.ktor.utils.io.core.Input
2019-08-19 08:13:43 +00:00
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
2019-03-21 04:25:23 +00:00
import kotlinx.serialization.json.Json
2020-08-29 13:09:54 +00:00
import kotlin.coroutines.Continuation
import kotlin.coroutines.suspendCoroutine
2019-02-20 12:18:01 +00:00
private const val API_TOKEN_FIELD = "api_key"
private const val OUTPUT_TYPE_FIELD = "output_type"
private const val URL_FIELD = "url"
2019-12-12 18:47:52 +00:00
private const val FILE_FIELD = "file"
private const val FILENAME_FIELD = "filename"
2019-02-20 12:18:01 +00:00
private const val DB_FIELD = "db"
private const val DBMASK_FIELD = "dbmask"
private const val DBMASKI_FIELD = "dbmaski"
private const val RESULTS_COUNT_FIELD = "numres"
private const val MINIMAL_SIMILARITY_FIELD = "minsim"
private const val SEARCH_URL = "https://saucenao.com/search.php"
2020-08-22 17:00:07 +00:00
val defaultSauceNaoParser = Json {
allowSpecialFloatingPointValues = true
allowStructuredMapKeys = true
ignoreUnknownKeys = true
useArrayPolymorphism = true
}
2019-02-20 12:18:01 +00:00
data class SauceNaoAPI(
2019-12-13 16:51:16 +00:00
private val apiToken: String? = null,
2019-02-20 12:18:01 +00:00
private val outputType: OutputType = JsonOutputType,
2020-08-22 17:00:07 +00:00
private val client: HttpClient = HttpClient(),
private val searchUrl: String = SEARCH_URL,
2020-08-22 17:00:07 +00:00
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
private val parser: Json = defaultSauceNaoParser
2020-08-29 13:09:54 +00:00
) : SauceCloseable {
2019-08-19 08:13:43 +00:00
private val requestsChannel = Channel<Pair<Continuation<SauceNaoAnswer>, HttpRequestBuilder>>(Channel.UNLIMITED)
2019-10-12 06:30:02 +00:00
private val timeManager = TimeManager(scope)
private val quotaManager = RequestQuotaManager(scope)
2019-08-19 08:13:43 +00:00
2019-12-13 18:29:12 +00:00
val limitsState: LimitsState
get() = quotaManager.limitsState
2019-10-12 06:30:02 +00:00
private val requestsJob = scope.launch {
for ((callback, requestBuilder) in requestsChannel) {
2019-10-12 06:32:17 +00:00
quotaManager.getQuota()
launch {
2019-10-12 06:30:02 +00:00
try {
2019-10-12 06:32:17 +00:00
val answer = makeRequest(requestBuilder)
callback.resumeWith(Result.success(answer))
quotaManager.updateQuota(answer.header, timeManager)
} catch (e: TooManyRequestsException) {
2019-12-13 18:21:12 +00:00
quotaManager.happenTooManyRequests(timeManager, e)
requestsChannel.send(callback to requestBuilder)
2019-10-12 06:32:17 +00:00
} catch (e: Exception) {
try {
callback.resumeWith(Result.failure(e))
} catch (e: IllegalStateException) { // may happen when already resumed and api was closed
// do nothing
}
2019-08-19 08:13:43 +00:00
}
}
}
}
2019-02-20 12:18:01 +00:00
suspend fun request(
url: String,
resultsCount: Int? = null,
minSimilarity: Float? = null
): SauceNaoAnswer? = makeRequest(
2019-12-12 18:47:52 +00:00
url.asSauceRequestSubject,
resultsCount = resultsCount,
minSimilarity = minSimilarity
)
suspend fun request(
mediaInput: Input,
2020-08-22 17:00:07 +00:00
mimeType: ContentType,
2019-12-12 18:47:52 +00:00
resultsCount: Int? = null,
minSimilarity: Float? = null
): SauceNaoAnswer? = makeRequest(
mediaInput.asSauceRequestSubject(mimeType),
2019-02-20 12:18:01 +00:00
resultsCount = resultsCount,
minSimilarity = minSimilarity
)
suspend fun requestByDb(
url: String,
db: Int,
resultsCount: Int? = null,
minSimilarity: Float? = null
): SauceNaoAnswer? = makeRequest(
2019-12-12 18:47:52 +00:00
url.asSauceRequestSubject,
2019-02-20 12:18:01 +00:00
db = db,
resultsCount = resultsCount,
minSimilarity = minSimilarity
)
suspend fun requestByMask(
url: String,
dbmask: Int,
resultsCount: Int? = null,
minSimilarity: Float? = null
): SauceNaoAnswer? = makeRequest(
2019-12-12 18:47:52 +00:00
url.asSauceRequestSubject,
2019-02-20 12:18:01 +00:00
dbmask = dbmask,
resultsCount = resultsCount,
minSimilarity = minSimilarity
)
suspend fun requestByMaskI(
url: String,
dbmaski: Int,
resultsCount: Int? = null,
minSimilarity: Float? = null
): SauceNaoAnswer? = makeRequest(
2019-12-12 18:47:52 +00:00
url.asSauceRequestSubject,
2019-02-20 12:18:01 +00:00
dbmaski = dbmaski,
resultsCount = resultsCount,
minSimilarity = minSimilarity
)
2019-08-19 08:13:43 +00:00
private suspend fun makeRequest(
builder: HttpRequestBuilder
): SauceNaoAnswer {
return try {
2020-08-13 05:17:11 +00:00
val call = client.request<HttpResponse>(builder)
val answerText = call.readText()
2019-10-12 06:30:02 +00:00
timeManager.addTimeAndClear()
2020-08-22 17:00:07 +00:00
parser.decodeFromString(
2019-10-12 10:28:27 +00:00
SauceNaoAnswerSerializer,
2019-08-19 08:13:43 +00:00
answerText
)
} catch (e: ClientRequestException) {
2019-12-13 18:21:12 +00:00
throw e.sauceNaoAPIException()
2019-08-19 08:13:43 +00:00
}
}
2019-02-20 12:18:01 +00:00
private suspend fun makeRequest(
2019-12-12 18:47:52 +00:00
request: SauceRequestSubject,
2019-02-20 12:18:01 +00:00
db: Int? = null,
dbmask: Int? = null,
dbmaski: Int? = null,
resultsCount: Int? = null,
minSimilarity: Float? = null
): SauceNaoAnswer? {
2019-08-19 08:13:43 +00:00
return suspendCoroutine<SauceNaoAnswer> {
requestsChannel.offer(
it to HttpRequestBuilder().apply {
url(searchUrl)
2019-12-12 18:47:52 +00:00
2019-12-13 16:51:16 +00:00
apiToken ?.also { parameter(API_TOKEN_FIELD, it) }
2019-08-19 08:13:43 +00:00
parameter(OUTPUT_TYPE_FIELD, outputType.typeCode)
db ?.also { parameter(DB_FIELD, it) }
dbmask ?.also { parameter(DBMASK_FIELD, it) }
dbmaski ?.also { parameter(DBMASKI_FIELD, it) }
resultsCount ?.also { parameter(RESULTS_COUNT_FIELD, it) }
minSimilarity ?.also { parameter(MINIMAL_SIMILARITY_FIELD, it) }
2019-12-12 18:47:52 +00:00
when (request) {
is UrlSauceRequestSubject -> {
parameter(URL_FIELD, request.url)
}
is InputRequestSubject -> {
val mimeType = request.mimeType
method = HttpMethod.Post
body = MultiPartFormDataContent(formData {
appendInput(
FILE_FIELD,
Headers.build {
append(HttpHeaders.ContentType, mimeType.toString())
val fakeFilename = "filename=file" + when (mimeType) {
ContentType.Image.GIF -> ".gif"
ContentType.Image.JPEG -> ".jpeg"
ContentType.Image.PNG -> ".png"
ContentType.Image.SVG -> ".svg"
else -> throw IllegalArgumentException(
"Currently supported formats for uploading in sauce: gif, jpeg, png, svg"
)
}
append(HttpHeaders.ContentDisposition, "filename=$fakeFilename")
},
block = request::input
)
})
}
}
2019-08-19 08:13:43 +00:00
}
2019-02-20 12:18:01 +00:00
)
}
}
2019-08-19 08:13:43 +00:00
override fun close() {
requestsChannel.close()
client.close()
2019-10-12 06:30:02 +00:00
requestsJob.cancel()
timeManager.close()
quotaManager.close()
2019-08-19 08:13:43 +00:00
}
2019-02-20 12:18:01 +00:00
}