mirror of
https://github.com/InsanusMokrassar/SauceNaoAPI.git
synced 2024-09-28 21:26:07 +00:00
Compare commits
68 Commits
Author | SHA1 | Date | |
---|---|---|---|
a61211e24a | |||
caa2fb9b58 | |||
915cb09e37 | |||
930523f69a | |||
773415f579 | |||
21803cb321 | |||
c6643dbdbc | |||
58beceebf1 | |||
0acf4a88f4 | |||
ed48b3e4aa | |||
1ed123596c | |||
76a0dbdf27 | |||
33775f3304 | |||
f7ca2bda89 | |||
9efade9daf | |||
e4d1ff7fa9 | |||
e0b5f5d410 | |||
adec37b9e5 | |||
8e042c6399 | |||
0564ed1d75 | |||
f9d98ec7d7 | |||
67519da545 | |||
6028ec7774 | |||
e29cad7bae | |||
473a5a735a | |||
0229697dd3 | |||
47161eb4ff | |||
e6024b223c | |||
5f8e410531 | |||
7727d2400e | |||
eec32de472 | |||
ae9a7baf50 | |||
bcc36dbfb7 | |||
cf8ec46513 | |||
9c25b08296 | |||
962d079f46 | |||
a84f31f888 | |||
14006652ee | |||
29aa1271a6 | |||
d2edd43a09 | |||
c31793ab38 | |||
d19bb48384 | |||
b21c3f1ac9 | |||
5ddc13eca0 | |||
8b180850da | |||
e65a171e65 | |||
31f32a7069 | |||
5b299fb1c1 | |||
5038fb4240 | |||
96f520700f | |||
2a4296ff7d | |||
2f34ab7ad1 | |||
798c4097ed | |||
c1df04fd09 | |||
8cc0426dc5 | |||
9cc929adf6 | |||
85567956ed | |||
db154f4202 | |||
bfdbee356a | |||
62580f6649 | |||
0b79f27b38 | |||
8543917da7 | |||
be858d3e60 | |||
90e090ca78 | |||
66414ff8df | |||
d0c143dcd6 | |||
3ee0d0de7d | |||
d04ee03043 |
7
.github/workflows/build_and_publish.yml
vendored
7
.github/workflows/build_and_publish.yml
vendored
@ -16,8 +16,13 @@ jobs:
|
|||||||
mv gradle.properties.tmp gradle.properties
|
mv gradle.properties.tmp gradle.properties
|
||||||
- name: Build
|
- name: Build
|
||||||
run: ./gradlew build
|
run: ./gradlew build
|
||||||
|
- name: Publish to Gitea
|
||||||
|
continue-on-error: true
|
||||||
|
run: ./gradlew publishAllPublicationsToGiteaRepository
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||||
- name: Publish
|
- name: Publish
|
||||||
run: ./gradlew publishAllPublicationsToGithubPackagesRepository --no-parallel -x signJsPublication -x signJvmPublication -x signKotlinMultiplatformPublication
|
run: ./gradlew publishAllPublicationsToGithubPackagesRepository --no-parallel
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
env:
|
env:
|
||||||
GITHUBPACKAGES_USER: ${{ github.actor }}
|
GITHUBPACKAGES_USER: ${{ github.actor }}
|
||||||
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -8,3 +8,4 @@ settings.xml
|
|||||||
.gradle/
|
.gradle/
|
||||||
build/
|
build/
|
||||||
out/
|
out/
|
||||||
|
kotlin-js-store/
|
||||||
|
95
CHANGELOG.md
95
CHANGELOG.md
@ -1,5 +1,100 @@
|
|||||||
# SauceNaoAPI Changelog
|
# SauceNaoAPI Changelog
|
||||||
|
|
||||||
|
## 0.17.2
|
||||||
|
|
||||||
|
* Versions:
|
||||||
|
* `Coroutines`: `1.7.3`
|
||||||
|
* `Ktor`: `2.3.4`
|
||||||
|
* `MicroUtils`: `0.19.9`
|
||||||
|
|
||||||
|
## 0.17.1
|
||||||
|
|
||||||
|
* Versions:
|
||||||
|
* `Coroutines`: `1.7.2`
|
||||||
|
* `Ktor`: `2.3.2`
|
||||||
|
* `MicroUtils`: `0.19.7`
|
||||||
|
|
||||||
|
## 0.17.0
|
||||||
|
|
||||||
|
* Versions:
|
||||||
|
* `Kotlin`: `1.8.22`
|
||||||
|
* `Serialization`: `1.5.1`
|
||||||
|
* `Ktor`: `2.3.1`
|
||||||
|
* `MicroUtils`: `0.19.2`
|
||||||
|
* `Klock`: `4.0.3`
|
||||||
|
|
||||||
|
## 0.16.0
|
||||||
|
|
||||||
|
Add `MicroUtils` as used micro utils
|
||||||
|
|
||||||
|
* Versions:
|
||||||
|
* `Kotlin`: `1.8.21`
|
||||||
|
* `Ktor`: `2.3.0`
|
||||||
|
|
||||||
|
## 0.15.1
|
||||||
|
|
||||||
|
* Versions:
|
||||||
|
* `Ktor`: `2.2.4`
|
||||||
|
|
||||||
|
## 0.15.0
|
||||||
|
|
||||||
|
* Versions:
|
||||||
|
* `Kotlin`: `1.8.10`
|
||||||
|
* `Serialization`: `1.5.0`
|
||||||
|
* `Ktor`: `2.2.3`
|
||||||
|
|
||||||
|
## 0.14.0
|
||||||
|
|
||||||
|
* `LimitStatus` is `Comparable<LimitStatus>` since this update
|
||||||
|
* `Limits` is `Comparable<Limits>` since this update
|
||||||
|
* Main API has been changed
|
||||||
|
|
||||||
|
## 0.13.0
|
||||||
|
|
||||||
|
* Versions:
|
||||||
|
* `Kotlin`: `1.7.20` -> `1.7.22`
|
||||||
|
* `Serialization`: `1.4.0` -> `1.4.1`
|
||||||
|
* `Klock`: `3.2.0` -> `3.4.0`
|
||||||
|
* `Ktor`: `2.1.2` -> `2.2.1`
|
||||||
|
* Now it is possible to subscribe onto API limits changes
|
||||||
|
|
||||||
|
## 0.12.2
|
||||||
|
|
||||||
|
* Versions:
|
||||||
|
* `Kotlin`: `1.7.10` -> `1.7.20`
|
||||||
|
* `Serialization`: `1.4.0-RC` -> `1.4.0`
|
||||||
|
* `Klock`: `3.0.0` -> `3.2.0`
|
||||||
|
* `Ktor`: `2.1.0` -> `2.1.2`
|
||||||
|
|
||||||
|
## 0.12.1
|
||||||
|
|
||||||
|
* Versions:
|
||||||
|
* `Ktor`: `2.0.3` -> `2.1.0`
|
||||||
|
|
||||||
|
## 0.11.1
|
||||||
|
|
||||||
|
* Versions updates:
|
||||||
|
* `Ktor`: `2.0.1` -> `2.0.3`
|
||||||
|
* `Coroutines`: `1.6.1` -> `1.6.4`
|
||||||
|
|
||||||
|
## 0.11.0
|
||||||
|
|
||||||
|
* Versions updates:
|
||||||
|
* `Kotlin`: `1.6.10` -> `1.6.21`
|
||||||
|
* `Serialization`: `1.3.2` -> `1.3.3`
|
||||||
|
* `Klock`: `2.6.3` -> `2.7.0`
|
||||||
|
* `Ktor`: `1.6.8` -> `2.0.1`
|
||||||
|
|
||||||
|
## 0.10.1
|
||||||
|
|
||||||
|
* Versions updates:
|
||||||
|
* `Klock`: `2.6.2` -> `2.6.3`
|
||||||
|
* `Ktor`: `1.6.7` -> `1.6.8`
|
||||||
|
|
||||||
|
## 0.10.0
|
||||||
|
|
||||||
|
Migration onto libs versions toml
|
||||||
|
|
||||||
## 0.9.1
|
## 0.9.1
|
||||||
|
|
||||||
* Versions updates:
|
* Versions updates:
|
||||||
|
18
build.gradle
18
build.gradle
@ -28,11 +28,19 @@ repositories {
|
|||||||
}
|
}
|
||||||
|
|
||||||
kotlin {
|
kotlin {
|
||||||
jvm()
|
jvm {
|
||||||
|
compilations.main {
|
||||||
|
kotlinOptions {
|
||||||
|
jvmTarget = "1.8"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
js(IR) {
|
js(IR) {
|
||||||
browser()
|
browser()
|
||||||
nodejs()
|
nodejs()
|
||||||
}
|
}
|
||||||
|
linuxX64()
|
||||||
|
mingwX64()
|
||||||
|
|
||||||
|
|
||||||
sourceSets {
|
sourceSets {
|
||||||
@ -44,6 +52,9 @@ kotlin {
|
|||||||
api libs.kt.serialization
|
api libs.kt.serialization
|
||||||
api libs.klock
|
api libs.klock
|
||||||
api libs.ktor.client
|
api libs.ktor.client
|
||||||
|
api libs.microutils.common
|
||||||
|
api libs.microutils.ktor.common
|
||||||
|
api libs.microutils.mimetypes
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
commonTest {
|
commonTest {
|
||||||
@ -65,3 +76,8 @@ kotlin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
targetCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
}
|
||||||
|
@ -19,7 +19,7 @@ if (new File(projectDir, "secret.gradle").exists()) {
|
|||||||
owner "InsanusMokrassar"
|
owner "InsanusMokrassar"
|
||||||
repo "${rootProject.name}"
|
repo "${rootProject.name}"
|
||||||
|
|
||||||
tagName "${project.version}"
|
tagName "v${project.version}"
|
||||||
releaseName "${project.version}"
|
releaseName "${project.version}"
|
||||||
targetCommitish "${project.version}"
|
targetCommitish "${project.version}"
|
||||||
|
|
||||||
|
@ -1,3 +1,3 @@
|
|||||||
kotlin.code.style=official
|
kotlin.code.style=official
|
||||||
|
|
||||||
library_version=0.10.0
|
library_version=0.17.2
|
||||||
|
@ -1,13 +1,15 @@
|
|||||||
[versions]
|
[versions]
|
||||||
|
|
||||||
kt = "1.6.10"
|
kt = "1.8.22"
|
||||||
kt-serialization = "1.3.2"
|
kt-serialization = "1.5.1"
|
||||||
kt-coroutines = "1.6.0"
|
kt-coroutines = "1.7.3"
|
||||||
|
|
||||||
klock = "2.6.2"
|
klock = "4.0.3"
|
||||||
ktor = "1.6.7"
|
ktor = "2.3.4"
|
||||||
|
|
||||||
gh-release = "2.2.12"
|
microutils = "0.19.9"
|
||||||
|
|
||||||
|
gh-release = "2.4.1"
|
||||||
|
|
||||||
[libraries]
|
[libraries]
|
||||||
|
|
||||||
@ -20,6 +22,10 @@ klock = { module = "com.soywiz.korlibs.klock:klock", version.ref = "klock" }
|
|||||||
ktor-client = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
|
ktor-client = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
|
||||||
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
|
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
|
||||||
|
|
||||||
|
microutils-common = { module = "dev.inmo:micro_utils.common", version.ref = "microutils" }
|
||||||
|
microutils-ktor-common = { module = "dev.inmo:micro_utils.ktor.common", version.ref = "microutils" }
|
||||||
|
microutils-mimetypes = { module = "dev.inmo:micro_utils.mime_types", version.ref = "microutils" }
|
||||||
|
|
||||||
buildscript-kt-gradle = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kt" }
|
buildscript-kt-gradle = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kt" }
|
||||||
buildscript-kt-serialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kt" }
|
buildscript-kt-serialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kt" }
|
||||||
buildscript-gh-release = { module = "com.github.breadmoirai:github-release", version.ref = "gh-release" }
|
buildscript-gh-release = { module = "com.github.breadmoirai:github-release", version.ref = "gh-release" }
|
||||||
|
2
gradle/wrapper/gradle-wrapper.properties
vendored
2
gradle/wrapper/gradle-wrapper.properties
vendored
@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
|
|||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -42,20 +42,40 @@ publishing {
|
|||||||
maven {
|
maven {
|
||||||
name = "GithubPackages"
|
name = "GithubPackages"
|
||||||
url = uri("https://maven.pkg.github.com/InsanusMokrassar/SauceNaoAPI")
|
url = uri("https://maven.pkg.github.com/InsanusMokrassar/SauceNaoAPI")
|
||||||
|
|
||||||
credentials {
|
credentials {
|
||||||
username = project.hasProperty('GITHUBPACKAGES_USER') ? project.property('GITHUBPACKAGES_USER') : System.getenv('GITHUBPACKAGES_USER')
|
username = project.hasProperty('GITHUBPACKAGES_USER') ? project.property('GITHUBPACKAGES_USER') : System.getenv('GITHUBPACKAGES_USER')
|
||||||
password = project.hasProperty('GITHUBPACKAGES_PASSWORD') ? project.property('GITHUBPACKAGES_PASSWORD') : System.getenv('GITHUBPACKAGES_PASSWORD')
|
password = project.hasProperty('GITHUBPACKAGES_PASSWORD') ? project.property('GITHUBPACKAGES_PASSWORD') : System.getenv('GITHUBPACKAGES_PASSWORD')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (project.hasProperty('GITEA_TOKEN') || System.getenv('GITEA_TOKEN') != null) {
|
||||||
|
maven {
|
||||||
|
name = "Gitea"
|
||||||
|
url = uri("https://git.inmo.dev/api/packages/InsanusMokrassar/maven")
|
||||||
|
|
||||||
|
credentials(HttpHeaderCredentials) {
|
||||||
|
name = "Authorization"
|
||||||
|
value = project.hasProperty('GITEA_TOKEN') ? project.property('GITEA_TOKEN') : System.getenv('GITEA_TOKEN')
|
||||||
|
}
|
||||||
|
|
||||||
|
authentication {
|
||||||
|
header(HttpHeaderAuthentication)
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ((project.hasProperty('SONATYPE_USER') || System.getenv('SONATYPE_USER') != null) && (project.hasProperty('SONATYPE_PASSWORD') || System.getenv('SONATYPE_PASSWORD') != null)) {
|
if ((project.hasProperty('SONATYPE_USER') || System.getenv('SONATYPE_USER') != null) && (project.hasProperty('SONATYPE_PASSWORD') || System.getenv('SONATYPE_PASSWORD') != null)) {
|
||||||
maven {
|
maven {
|
||||||
name = "sonatype"
|
name = "sonatype"
|
||||||
url = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/")
|
url = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/")
|
||||||
|
|
||||||
credentials {
|
credentials {
|
||||||
username = project.hasProperty('SONATYPE_USER') ? project.property('SONATYPE_USER') : System.getenv('SONATYPE_USER')
|
username = project.hasProperty('SONATYPE_USER') ? project.property('SONATYPE_USER') : System.getenv('SONATYPE_USER')
|
||||||
password = project.hasProperty('SONATYPE_PASSWORD') ? project.property('SONATYPE_PASSWORD') : System.getenv('SONATYPE_PASSWORD')
|
password = project.hasProperty('SONATYPE_PASSWORD') ? project.property('SONATYPE_PASSWORD') : System.getenv('SONATYPE_PASSWORD')
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1 +1 @@
|
|||||||
{"licenses":[{"id":"Apache-2.0","title":"Apache Software License 2.0","url":"https://github.com/InsanusMokrassar/SauceNaoAPI/blob/master/LICENSE"}],"mavenConfig":{"name":"SauceNao API","description":"SauceNao API library","url":"https://insanusmokrassar.github.io/${project.name}","vcsUrl":"https://github.com/insanusmokrassar/${project.name}.git","developers":[{"id":"InsanusMokrassar","name":"Ovsyannikov Alexey","eMail":"ovsyannikov.alexey95@gmail.com"}],"repositories":[{"name":"GithubPackages","url":"https://maven.pkg.github.com/InsanusMokrassar/SauceNaoAPI"},{"name":"sonatype","url":"https://oss.sonatype.org/service/local/staging/deploy/maven2/"}],"gpgSigning":{"type":"dev.inmo.kmppscriptbuilder.core.models.GpgSigning.Optional"}}}
|
{"licenses":[{"id":"Apache-2.0","title":"Apache Software License 2.0","url":"https://github.com/InsanusMokrassar/SauceNaoAPI/blob/master/LICENSE"}],"mavenConfig":{"name":"SauceNao API","description":"SauceNao API library","url":"https://insanusmokrassar.github.io/${project.name}","vcsUrl":"https://github.com/insanusmokrassar/${project.name}.git","developers":[{"id":"InsanusMokrassar","name":"Ovsyannikov Alexey","eMail":"ovsyannikov.alexey95@gmail.com"}],"repositories":[{"name":"GithubPackages","url":"https://maven.pkg.github.com/InsanusMokrassar/SauceNaoAPI"},{"name":"Gitea","url":"https://git.inmo.dev/api/packages/InsanusMokrassar/maven","credsType":{"type":"dev.inmo.kmppscriptbuilder.core.models.MavenPublishingRepository.CredentialsType.HttpHeaderCredentials","headerName":"Authorization","headerValueProperty":"GITEA_TOKEN"}},{"name":"sonatype","url":"https://oss.sonatype.org/service/local/staging/deploy/maven2/"}],"gpgSigning":{"type":"dev.inmo.kmppscriptbuilder.core.models.GpgSigning.Optional"}}}
|
@ -1,22 +1,22 @@
|
|||||||
package dev.inmo.saucenaoapi
|
package dev.inmo.saucenaoapi
|
||||||
|
|
||||||
|
import dev.inmo.micro_utils.common.MPPFile
|
||||||
|
import dev.inmo.micro_utils.ktor.common.input
|
||||||
import dev.inmo.saucenaoapi.exceptions.TooManyRequestsException
|
import dev.inmo.saucenaoapi.exceptions.TooManyRequestsException
|
||||||
import dev.inmo.saucenaoapi.exceptions.sauceNaoAPIException
|
import dev.inmo.saucenaoapi.exceptions.sauceNaoAPIException
|
||||||
import dev.inmo.saucenaoapi.models.*
|
import dev.inmo.saucenaoapi.models.*
|
||||||
import dev.inmo.saucenaoapi.utils.*
|
import dev.inmo.saucenaoapi.utils.*
|
||||||
import io.ktor.client.HttpClient
|
import io.ktor.client.HttpClient
|
||||||
import io.ktor.client.features.ClientRequestException
|
import io.ktor.client.plugins.ClientRequestException
|
||||||
import io.ktor.client.request.*
|
import io.ktor.client.request.*
|
||||||
import io.ktor.client.request.forms.MultiPartFormDataContent
|
import io.ktor.client.request.forms.MultiPartFormDataContent
|
||||||
import io.ktor.client.request.forms.formData
|
import io.ktor.client.request.forms.formData
|
||||||
import io.ktor.client.statement.HttpResponse
|
import io.ktor.client.statement.bodyAsText
|
||||||
import io.ktor.client.statement.readText
|
|
||||||
import io.ktor.http.*
|
import io.ktor.http.*
|
||||||
import io.ktor.utils.io.core.Input
|
import io.ktor.utils.io.core.Input
|
||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import kotlin.coroutines.*
|
|
||||||
|
|
||||||
private const val API_TOKEN_FIELD = "api_key"
|
private const val API_TOKEN_FIELD = "api_key"
|
||||||
private const val OUTPUT_TYPE_FIELD = "output_type"
|
private const val OUTPUT_TYPE_FIELD = "output_type"
|
||||||
@ -24,6 +24,7 @@ private const val URL_FIELD = "url"
|
|||||||
private const val FILE_FIELD = "file"
|
private const val FILE_FIELD = "file"
|
||||||
private const val FILENAME_FIELD = "filename"
|
private const val FILENAME_FIELD = "filename"
|
||||||
private const val DB_FIELD = "db"
|
private const val DB_FIELD = "db"
|
||||||
|
private const val DBS_FIELD = "dbs[]"
|
||||||
private const val DBMASK_FIELD = "dbmask"
|
private const val DBMASK_FIELD = "dbmask"
|
||||||
private const val DBMASKI_FIELD = "dbmaski"
|
private const val DBMASKI_FIELD = "dbmaski"
|
||||||
private const val RESULTS_COUNT_FIELD = "numres"
|
private const val RESULTS_COUNT_FIELD = "numres"
|
||||||
@ -40,26 +41,34 @@ val defaultSauceNaoParser = Json {
|
|||||||
|
|
||||||
data class SauceNaoAPI(
|
data class SauceNaoAPI(
|
||||||
private val apiToken: String? = null,
|
private val apiToken: String? = null,
|
||||||
private val outputType: dev.inmo.saucenaoapi.OutputType = dev.inmo.saucenaoapi.JsonOutputType,
|
|
||||||
private val client: HttpClient = HttpClient(),
|
private val client: HttpClient = HttpClient(),
|
||||||
private val searchUrl: String = SEARCH_URL,
|
private val searchUrl: String = SEARCH_URL,
|
||||||
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
|
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
|
||||||
private val parser: Json = defaultSauceNaoParser
|
private val parser: Json = defaultSauceNaoParser
|
||||||
) : SauceCloseable {
|
) : SauceCloseable {
|
||||||
private val requestsChannel = Channel<Pair<Continuation<SauceNaoAnswer>, HttpRequestBuilder>>(Channel.UNLIMITED)
|
private val requestsChannel = Channel<Pair<CompletableDeferred<SauceNaoAnswer>, HttpRequestBuilder>>(Channel.UNLIMITED)
|
||||||
private val timeManager = TimeManager(scope)
|
private val subscope = CoroutineScope(scope.coroutineContext + SupervisorJob(scope.coroutineContext.job)).also {
|
||||||
private val quotaManager = RequestQuotaManager(scope)
|
it.coroutineContext.job.invokeOnCompletion {
|
||||||
|
requestsChannel.close(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private val timeManager = TimeManager(subscope)
|
||||||
|
private val quotaManager = RequestQuotaManager(subscope)
|
||||||
|
|
||||||
val limitsState: LimitsState
|
val limitsState: LimitsState by quotaManager::limitsState
|
||||||
get() = quotaManager.limitsState
|
val longQuotaFlow by quotaManager::longQuotaFlow
|
||||||
|
val shortQuotaFlow by quotaManager::shortQuotaFlow
|
||||||
|
val longMaxQuotaFlow by quotaManager::longMaxQuotaFlow
|
||||||
|
val shortMaxQuotaFlow by quotaManager::shortMaxQuotaFlow
|
||||||
|
val limitsStateFlow by quotaManager::limitsStateFlow
|
||||||
|
|
||||||
private val requestsJob = scope.launch {
|
private val requestsJob = subscope.launch {
|
||||||
for ((callback, requestBuilder) in requestsChannel) {
|
for ((callback, requestBuilder) in requestsChannel) {
|
||||||
quotaManager.getQuota()
|
quotaManager.getQuota()
|
||||||
launch {
|
launch {
|
||||||
try {
|
try {
|
||||||
val answer = makeRequest(requestBuilder)
|
val answer = makeRequest(requestBuilder)
|
||||||
callback.resume(answer)
|
callback.complete(answer)
|
||||||
|
|
||||||
quotaManager.updateQuota(answer.header, timeManager)
|
quotaManager.updateQuota(answer.header, timeManager)
|
||||||
} catch (e: TooManyRequestsException) {
|
} catch (e: TooManyRequestsException) {
|
||||||
@ -67,7 +76,7 @@ data class SauceNaoAPI(
|
|||||||
requestsChannel.send(callback to requestBuilder)
|
requestsChannel.send(callback to requestBuilder)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
try {
|
try {
|
||||||
callback.resumeWithException(e)
|
callback.completeExceptionally(e)
|
||||||
} catch (e: IllegalStateException) { // may happen when already resumed and api was closed
|
} catch (e: IllegalStateException) { // may happen when already resumed and api was closed
|
||||||
// do nothing
|
// do nothing
|
||||||
}
|
}
|
||||||
@ -80,65 +89,203 @@ data class SauceNaoAPI(
|
|||||||
url: String,
|
url: String,
|
||||||
resultsCount: Int? = null,
|
resultsCount: Int? = null,
|
||||||
minSimilarity: Float? = null
|
minSimilarity: Float? = null
|
||||||
): SauceNaoAnswer? = makeRequest(
|
): SauceNaoAnswer = makeRequest(
|
||||||
url.asSauceRequestSubject,
|
url.asSauceRequestSubject,
|
||||||
resultsCount = resultsCount,
|
resultsCount = resultsCount,
|
||||||
minSimilarity = minSimilarity
|
minSimilarity = minSimilarity
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param db search a specific index number or all without needing to generate a bitmask.
|
||||||
|
* @param dbs search one or more specific index number, set more than once to search multiple.
|
||||||
|
*/
|
||||||
|
suspend fun requestByDBs(
|
||||||
|
url: String,
|
||||||
|
db: Int? = null,
|
||||||
|
dbs: Array<Int>? = null,
|
||||||
|
resultsCount: Int? = null,
|
||||||
|
minSimilarity: Float? = null
|
||||||
|
): SauceNaoAnswer = makeRequest(
|
||||||
|
url.asSauceRequestSubject,
|
||||||
|
db = db,
|
||||||
|
dbs = dbs,
|
||||||
|
resultsCount = resultsCount,
|
||||||
|
minSimilarity = minSimilarity
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mask Mask for selecting specific indexes to ENABLE. dbmask=8191 will search all of the first 14 indexes. If intending to search all databases, the db=999 option is more appropriate.
|
||||||
|
* @param excludedMask Mask for selecting specific indexes to DISABLE. dbmaski=8191 would search only indexes higher than the first 14. This is ideal when attempting to disable only certain indexes, while allowing future indexes to be included by default.
|
||||||
|
*
|
||||||
|
* Bitmask Note: Index numbers start with 0. Even though pixiv is labeled as index 5, it would be controlled with the 6th bit position, which has a decimal value of 32 when set.
|
||||||
|
* db=<index num or 999 for all>
|
||||||
|
*/
|
||||||
|
suspend fun requestByMasks(
|
||||||
|
url: String,
|
||||||
|
mask: Int?,
|
||||||
|
excludedMask: Int? = null,
|
||||||
|
resultsCount: Int? = null,
|
||||||
|
minSimilarity: Float? = null
|
||||||
|
): SauceNaoAnswer = makeRequest(
|
||||||
|
url.asSauceRequestSubject,
|
||||||
|
dbmask = mask,
|
||||||
|
dbmaski = excludedMask,
|
||||||
|
resultsCount = resultsCount,
|
||||||
|
minSimilarity = minSimilarity
|
||||||
|
)
|
||||||
|
|
||||||
suspend fun request(
|
suspend fun request(
|
||||||
mediaInput: Input,
|
mediaInput: Input,
|
||||||
mimeType: ContentType,
|
mimeType: ContentType,
|
||||||
resultsCount: Int? = null,
|
resultsCount: Int? = null,
|
||||||
minSimilarity: Float? = null
|
minSimilarity: Float? = null
|
||||||
): SauceNaoAnswer? = makeRequest(
|
): SauceNaoAnswer = makeRequest(
|
||||||
mediaInput.asSauceRequestSubject(mimeType),
|
mediaInput.asSauceRequestSubject(mimeType),
|
||||||
resultsCount = resultsCount,
|
resultsCount = resultsCount,
|
||||||
minSimilarity = minSimilarity
|
minSimilarity = minSimilarity
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param db search a specific index number or all without needing to generate a bitmask.
|
||||||
|
* @param dbs search one or more specific index number, set more than once to search multiple.
|
||||||
|
*/
|
||||||
|
suspend fun requestByDBs(
|
||||||
|
mediaInput: Input,
|
||||||
|
mimeType: ContentType,
|
||||||
|
db: Int? = null,
|
||||||
|
dbs: Array<Int>? = null,
|
||||||
|
resultsCount: Int? = null,
|
||||||
|
minSimilarity: Float? = null
|
||||||
|
): SauceNaoAnswer = makeRequest(
|
||||||
|
mediaInput.asSauceRequestSubject(mimeType),
|
||||||
|
db = db,
|
||||||
|
dbs = dbs,
|
||||||
|
resultsCount = resultsCount,
|
||||||
|
minSimilarity = minSimilarity
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mask Mask for selecting specific indexes to ENABLE. dbmask=8191 will search all of the first 14 indexes. If intending to search all databases, the db=999 option is more appropriate.
|
||||||
|
* @param excludedMask Mask for selecting specific indexes to DISABLE. dbmaski=8191 would search only indexes higher than the first 14. This is ideal when attempting to disable only certain indexes, while allowing future indexes to be included by default.
|
||||||
|
*
|
||||||
|
* Bitmask Note: Index numbers start with 0. Even though pixiv is labeled as index 5, it would be controlled with the 6th bit position, which has a decimal value of 32 when set.
|
||||||
|
* db=<index num or 999 for all>
|
||||||
|
*/
|
||||||
|
suspend fun requestByMasks(
|
||||||
|
mediaInput: Input,
|
||||||
|
mimeType: ContentType,
|
||||||
|
mask: Int?,
|
||||||
|
excludedMask: Int? = null,
|
||||||
|
resultsCount: Int? = null,
|
||||||
|
minSimilarity: Float? = null
|
||||||
|
): SauceNaoAnswer = makeRequest(
|
||||||
|
mediaInput.asSauceRequestSubject(mimeType),
|
||||||
|
dbmask = mask,
|
||||||
|
dbmaski = excludedMask,
|
||||||
|
resultsCount = resultsCount,
|
||||||
|
minSimilarity = minSimilarity
|
||||||
|
)
|
||||||
|
|
||||||
|
suspend fun request(
|
||||||
|
file: MPPFile,
|
||||||
|
resultsCount: Int? = null,
|
||||||
|
minSimilarity: Float? = null
|
||||||
|
): SauceNaoAnswer = request(
|
||||||
|
file.input(),
|
||||||
|
file.contentType,
|
||||||
|
resultsCount,
|
||||||
|
minSimilarity
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param db search a specific index number or all without needing to generate a bitmask.
|
||||||
|
* @param dbs search one or more specific index number, set more than once to search multiple.
|
||||||
|
*/
|
||||||
|
suspend fun requestByDBs(
|
||||||
|
file: MPPFile,
|
||||||
|
db: Int? = null,
|
||||||
|
dbs: Array<Int>? = null,
|
||||||
|
resultsCount: Int? = null,
|
||||||
|
minSimilarity: Float? = null
|
||||||
|
): SauceNaoAnswer = requestByDBs(
|
||||||
|
file.input(),
|
||||||
|
file.contentType,
|
||||||
|
db,
|
||||||
|
dbs,
|
||||||
|
resultsCount,
|
||||||
|
minSimilarity
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mask Mask for selecting specific indexes to ENABLE. dbmask=8191 will search all of the first 14 indexes. If intending to search all databases, the db=999 option is more appropriate.
|
||||||
|
* @param excludedMask Mask for selecting specific indexes to DISABLE. dbmaski=8191 would search only indexes higher than the first 14. This is ideal when attempting to disable only certain indexes, while allowing future indexes to be included by default.
|
||||||
|
*
|
||||||
|
* Bitmask Note: Index numbers start with 0. Even though pixiv is labeled as index 5, it would be controlled with the 6th bit position, which has a decimal value of 32 when set.
|
||||||
|
* db=<index num or 999 for all>
|
||||||
|
*/
|
||||||
|
suspend fun requestByMasks(
|
||||||
|
file: MPPFile,
|
||||||
|
mask: Int?,
|
||||||
|
excludedMask: Int? = null,
|
||||||
|
resultsCount: Int? = null,
|
||||||
|
minSimilarity: Float? = null
|
||||||
|
): SauceNaoAnswer = requestByMasks(
|
||||||
|
file.input(),
|
||||||
|
file.contentType,
|
||||||
|
mask,
|
||||||
|
excludedMask,
|
||||||
|
resultsCount,
|
||||||
|
minSimilarity
|
||||||
|
)
|
||||||
|
|
||||||
|
@Deprecated("Renamed", ReplaceWith("requestByDBs(url, db, null, resultsCount, minSimilarity)"))
|
||||||
suspend fun requestByDb(
|
suspend fun requestByDb(
|
||||||
url: String,
|
url: String,
|
||||||
db: Int,
|
db: Int,
|
||||||
resultsCount: Int? = null,
|
resultsCount: Int? = null,
|
||||||
minSimilarity: Float? = null
|
minSimilarity: Float? = null
|
||||||
): SauceNaoAnswer? = makeRequest(
|
): SauceNaoAnswer = requestByDBs(
|
||||||
url.asSauceRequestSubject,
|
url,
|
||||||
db = db,
|
db,
|
||||||
resultsCount = resultsCount,
|
null,
|
||||||
minSimilarity = minSimilarity
|
resultsCount,
|
||||||
|
minSimilarity
|
||||||
)
|
)
|
||||||
|
|
||||||
suspend fun requestByMask(
|
@Deprecated("Renamed", ReplaceWith("requestByMasks(url, dbmask, null, resultsCount, minSimilarity)"))
|
||||||
|
suspend fun request(
|
||||||
url: String,
|
url: String,
|
||||||
dbmask: Int,
|
dbmask: Int,
|
||||||
resultsCount: Int? = null,
|
resultsCount: Int? = null,
|
||||||
minSimilarity: Float? = null
|
minSimilarity: Float? = null
|
||||||
): SauceNaoAnswer? = makeRequest(
|
): SauceNaoAnswer = requestByMasks(
|
||||||
url.asSauceRequestSubject,
|
url,
|
||||||
dbmask = dbmask,
|
dbmask,
|
||||||
resultsCount = resultsCount,
|
null,
|
||||||
minSimilarity = minSimilarity
|
resultsCount,
|
||||||
|
minSimilarity
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@Deprecated("Renamed", ReplaceWith("requestByMasks(url, null, dbmaski, resultsCount, minSimilarity)"))
|
||||||
suspend fun requestByMaskI(
|
suspend fun requestByMaskI(
|
||||||
url: String,
|
url: String,
|
||||||
dbmaski: Int,
|
dbmaski: Int,
|
||||||
resultsCount: Int? = null,
|
resultsCount: Int? = null,
|
||||||
minSimilarity: Float? = null
|
minSimilarity: Float? = null
|
||||||
): SauceNaoAnswer? = makeRequest(
|
): SauceNaoAnswer = requestByMasks(
|
||||||
url.asSauceRequestSubject,
|
url,
|
||||||
dbmaski = dbmaski,
|
null,
|
||||||
resultsCount = resultsCount,
|
dbmaski,
|
||||||
minSimilarity = minSimilarity
|
resultsCount,
|
||||||
|
minSimilarity
|
||||||
)
|
)
|
||||||
|
|
||||||
private suspend fun makeRequest(
|
private suspend fun makeRequest(
|
||||||
builder: HttpRequestBuilder
|
builder: HttpRequestBuilder
|
||||||
): SauceNaoAnswer {
|
): SauceNaoAnswer {
|
||||||
return try {
|
return try {
|
||||||
val call = client.request<HttpResponse>(builder)
|
val call = client.request(builder)
|
||||||
val answerText = call.readText()
|
val answerText = call.bodyAsText()
|
||||||
timeManager.addTimeAndClear()
|
timeManager.addTimeAndClear()
|
||||||
parser.decodeFromString(
|
parser.decodeFromString(
|
||||||
SauceNaoAnswerSerializer,
|
SauceNaoAnswerSerializer,
|
||||||
@ -152,33 +299,38 @@ data class SauceNaoAPI(
|
|||||||
private suspend fun makeRequest(
|
private suspend fun makeRequest(
|
||||||
request: SauceRequestSubject,
|
request: SauceRequestSubject,
|
||||||
db: Int? = null,
|
db: Int? = null,
|
||||||
|
dbs: Array<Int>? = null,
|
||||||
dbmask: Int? = null,
|
dbmask: Int? = null,
|
||||||
dbmaski: Int? = null,
|
dbmaski: Int? = null,
|
||||||
resultsCount: Int? = null,
|
resultsCount: Int? = null,
|
||||||
minSimilarity: Float? = null
|
minSimilarity: Float? = null
|
||||||
): SauceNaoAnswer? {
|
): SauceNaoAnswer {
|
||||||
return suspendCoroutine<SauceNaoAnswer> {
|
val deferred = CompletableDeferred<SauceNaoAnswer>()
|
||||||
requestsChannel.trySend(
|
|
||||||
it to HttpRequestBuilder().apply {
|
|
||||||
url(searchUrl)
|
|
||||||
|
|
||||||
apiToken ?.also { parameter(API_TOKEN_FIELD, it) }
|
requestsChannel.trySend(
|
||||||
parameter(OUTPUT_TYPE_FIELD, outputType.typeCode)
|
deferred to HttpRequestBuilder().apply {
|
||||||
db ?.also { parameter(DB_FIELD, it) }
|
url(searchUrl)
|
||||||
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) }
|
|
||||||
|
|
||||||
when (request) {
|
apiToken ?.also { parameter(API_TOKEN_FIELD, it) }
|
||||||
is UrlSauceRequestSubject -> {
|
parameter(OUTPUT_TYPE_FIELD, JsonOutputType.typeCode)
|
||||||
parameter(URL_FIELD, request.url)
|
db ?.also { parameter(DB_FIELD, it) }
|
||||||
}
|
dbs ?.forEach { parameter(DBS_FIELD, it) }
|
||||||
is InputRequestSubject -> {
|
dbmask ?.also { parameter(DBMASK_FIELD, it) }
|
||||||
val mimeType = request.mimeType
|
dbmaski ?.also { parameter(DBMASKI_FIELD, it) }
|
||||||
|
resultsCount ?.also { parameter(RESULTS_COUNT_FIELD, it) }
|
||||||
|
minSimilarity ?.also { parameter(MINIMAL_SIMILARITY_FIELD, it) }
|
||||||
|
|
||||||
method = HttpMethod.Post
|
when (request) {
|
||||||
body = MultiPartFormDataContent(formData {
|
is UrlSauceRequestSubject -> {
|
||||||
|
parameter(URL_FIELD, request.url)
|
||||||
|
}
|
||||||
|
is InputRequestSubject -> {
|
||||||
|
val mimeType = request.mimeType
|
||||||
|
|
||||||
|
method = HttpMethod.Post
|
||||||
|
setBody(
|
||||||
|
MultiPartFormDataContent(
|
||||||
|
formData {
|
||||||
appendInput(
|
appendInput(
|
||||||
FILE_FIELD,
|
FILE_FIELD,
|
||||||
Headers.build {
|
Headers.build {
|
||||||
@ -197,19 +349,18 @@ data class SauceNaoAPI(
|
|||||||
},
|
},
|
||||||
block = request::input
|
block = request::input
|
||||||
)
|
)
|
||||||
})
|
}
|
||||||
}
|
)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
}
|
||||||
}
|
)
|
||||||
|
|
||||||
|
return deferred.await()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun close() {
|
override fun close() {
|
||||||
requestsChannel.close()
|
subscope.cancel()
|
||||||
client.close()
|
|
||||||
requestsJob.cancel()
|
|
||||||
timeManager.close()
|
|
||||||
quotaManager.close()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
package dev.inmo.saucenaoapi.additional
|
package dev.inmo.saucenaoapi.additional
|
||||||
|
|
||||||
import com.soywiz.klock.TimeSpan
|
import korlibs.time.TimeSpan
|
||||||
|
|
||||||
typealias AccountType = Int
|
typealias AccountType = Int
|
||||||
const val defaultAccountType: AccountType = 1 // "basic"
|
const val defaultAccountType: AccountType = 1 // "basic"
|
||||||
|
@ -29,15 +29,27 @@ val Header.accountInfo
|
|||||||
data class LimitStatus(
|
data class LimitStatus(
|
||||||
val remain: Int = Int.MAX_VALUE,
|
val remain: Int = Int.MAX_VALUE,
|
||||||
val limit: Int = Int.MAX_VALUE
|
val limit: Int = Int.MAX_VALUE
|
||||||
)
|
) : Comparable<LimitStatus> {
|
||||||
|
override fun compareTo(other: LimitStatus): Int = when {
|
||||||
|
limit == other.limit && remain == other.remain -> 0
|
||||||
|
else -> remain.compareTo(other.remain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
data class Limits(
|
data class Limits(
|
||||||
val short: LimitStatus = LimitStatus(),
|
val short: LimitStatus = LimitStatus(),
|
||||||
val long: LimitStatus = LimitStatus()
|
val long: LimitStatus = LimitStatus()
|
||||||
)
|
) : Comparable<Limits> {
|
||||||
|
override fun compareTo(other: Limits): Int = when {
|
||||||
|
long == other.long && short == other.short -> 0
|
||||||
|
else -> short.remain.compareTo(other.short.remain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
data class AccountInfo(
|
data class AccountInfo(
|
||||||
val accountType: AccountType = defaultAccountType,
|
val accountType: AccountType = defaultAccountType,
|
||||||
val userId: UserId? = null,
|
val userId: UserId? = null,
|
||||||
val limits: Limits = Limits()
|
val limits: Limits = Limits()
|
||||||
)
|
) : Comparable<AccountInfo> {
|
||||||
|
override fun compareTo(other: AccountInfo): Int = limits.compareTo(other.limits)
|
||||||
|
}
|
||||||
|
@ -1,17 +1,17 @@
|
|||||||
package dev.inmo.saucenaoapi.exceptions
|
package dev.inmo.saucenaoapi.exceptions
|
||||||
|
|
||||||
|
import korlibs.time.TimeSpan
|
||||||
import dev.inmo.saucenaoapi.additional.LONG_TIME_RECALCULATING_MILLIS
|
import dev.inmo.saucenaoapi.additional.LONG_TIME_RECALCULATING_MILLIS
|
||||||
import dev.inmo.saucenaoapi.additional.SHORT_TIME_RECALCULATING_MILLIS
|
import dev.inmo.saucenaoapi.additional.SHORT_TIME_RECALCULATING_MILLIS
|
||||||
import com.soywiz.klock.TimeSpan
|
import io.ktor.client.plugins.ClientRequestException
|
||||||
import io.ktor.client.features.ClientRequestException
|
import io.ktor.client.statement.bodyAsText
|
||||||
import io.ktor.client.statement.readText
|
|
||||||
import io.ktor.http.HttpStatusCode.Companion.TooManyRequests
|
import io.ktor.http.HttpStatusCode.Companion.TooManyRequests
|
||||||
import io.ktor.utils.io.errors.IOException
|
import io.ktor.utils.io.errors.IOException
|
||||||
|
|
||||||
internal suspend fun ClientRequestException.sauceNaoAPIException(): Exception {
|
internal suspend fun ClientRequestException.sauceNaoAPIException(): Exception {
|
||||||
return when (response.status) {
|
return when (response.status) {
|
||||||
TooManyRequests -> {
|
TooManyRequests -> {
|
||||||
val answerContent = response.readText()
|
val answerContent = response.bodyAsText()
|
||||||
when {
|
when {
|
||||||
answerContent.contains("daily limit") -> TooManyRequestsLongException(answerContent)
|
answerContent.contains("daily limit") -> TooManyRequestsLongException(answerContent)
|
||||||
else -> TooManyRequestsShortException(answerContent)
|
else -> TooManyRequestsShortException(answerContent)
|
||||||
|
@ -8,4 +8,6 @@ data class LimitsState(
|
|||||||
val maxLongQuota: Int,
|
val maxLongQuota: Int,
|
||||||
val knownShortQuota: Int,
|
val knownShortQuota: Int,
|
||||||
val knownLongQuota: Int
|
val knownLongQuota: Int
|
||||||
)
|
) : Comparable<LimitsState> {
|
||||||
|
override fun compareTo(other: LimitsState): Int = knownShortQuota.compareTo(other.knownShortQuota)
|
||||||
|
}
|
||||||
|
26
src/commonMain/kotlin/dev/inmo/saucenaoapi/utils/MPPFile.kt
Normal file
26
src/commonMain/kotlin/dev/inmo/saucenaoapi/utils/MPPFile.kt
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
package dev.inmo.saucenaoapi.utils
|
||||||
|
|
||||||
|
import dev.inmo.micro_utils.common.MPPFile
|
||||||
|
import dev.inmo.micro_utils.common.filename
|
||||||
|
import dev.inmo.micro_utils.ktor.common.input
|
||||||
|
import dev.inmo.micro_utils.mime_types.KnownMimeTypes
|
||||||
|
import dev.inmo.micro_utils.mime_types.getMimeType
|
||||||
|
import io.ktor.http.ContentType
|
||||||
|
import io.ktor.utils.io.core.Input
|
||||||
|
|
||||||
|
@Deprecated(
|
||||||
|
"MPPFile from microutils is preferable since 0.16.0",
|
||||||
|
ReplaceWith("MPPFile", "dev.inmo.micro_utils.common.MPPFile")
|
||||||
|
)
|
||||||
|
typealias MPPFile = MPPFile
|
||||||
|
|
||||||
|
@Deprecated(
|
||||||
|
"input() from microutils is preferable since 0.16.0",
|
||||||
|
ReplaceWith("this.input()", "dev.inmo.micro_utils.ktor.common.input")
|
||||||
|
)
|
||||||
|
val MPPFile.input: Input
|
||||||
|
get() = input()
|
||||||
|
val MPPFile.contentType: ContentType
|
||||||
|
get() = ContentType.parse(
|
||||||
|
getMimeType(stringWithExtension = filename.extension) ?.raw ?: KnownMimeTypes.Any.raw
|
||||||
|
)
|
@ -1,26 +1,47 @@
|
|||||||
package dev.inmo.saucenaoapi.utils
|
package dev.inmo.saucenaoapi.utils
|
||||||
|
|
||||||
|
import korlibs.time.DateTime
|
||||||
import dev.inmo.saucenaoapi.additional.LONG_TIME_RECALCULATING_MILLIS
|
import dev.inmo.saucenaoapi.additional.LONG_TIME_RECALCULATING_MILLIS
|
||||||
import dev.inmo.saucenaoapi.additional.SHORT_TIME_RECALCULATING_MILLIS
|
import dev.inmo.saucenaoapi.additional.SHORT_TIME_RECALCULATING_MILLIS
|
||||||
import dev.inmo.saucenaoapi.exceptions.TooManyRequestsException
|
import dev.inmo.saucenaoapi.exceptions.TooManyRequestsException
|
||||||
import dev.inmo.saucenaoapi.exceptions.TooManyRequestsLongException
|
import dev.inmo.saucenaoapi.exceptions.TooManyRequestsLongException
|
||||||
import dev.inmo.saucenaoapi.models.Header
|
import dev.inmo.saucenaoapi.models.Header
|
||||||
import dev.inmo.saucenaoapi.models.LimitsState
|
import dev.inmo.saucenaoapi.models.LimitsState
|
||||||
import com.soywiz.klock.DateTime
|
|
||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
import kotlin.coroutines.suspendCoroutine
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.merge
|
||||||
import kotlin.math.max
|
import kotlin.math.max
|
||||||
import kotlin.math.min
|
import kotlin.math.min
|
||||||
|
|
||||||
internal class RequestQuotaManager (
|
internal class RequestQuotaManager (
|
||||||
scope: CoroutineScope
|
scope: CoroutineScope
|
||||||
) : SauceCloseable {
|
) {
|
||||||
private var longQuota = 1
|
private val _longQuotaFlow = MutableStateFlow(1)
|
||||||
private var shortQuota = 1
|
private val _shortQuotaFlow = MutableStateFlow(1)
|
||||||
private var longMaxQuota = 1
|
private val _longMaxQuotaFlow = MutableStateFlow(1)
|
||||||
private var shortMaxQuota = 1
|
private val _shortMaxQuotaFlow = MutableStateFlow(1)
|
||||||
|
private var longQuota by _longQuotaFlow::value
|
||||||
|
private var shortQuota by _shortQuotaFlow::value
|
||||||
|
private var longMaxQuota by _longMaxQuotaFlow::value
|
||||||
|
private var shortMaxQuota by _shortMaxQuotaFlow::value
|
||||||
|
|
||||||
|
val longQuotaFlow = _longQuotaFlow.asStateFlow()
|
||||||
|
val shortQuotaFlow = _shortQuotaFlow.asStateFlow()
|
||||||
|
val longMaxQuotaFlow = _longMaxQuotaFlow.asStateFlow()
|
||||||
|
val shortMaxQuotaFlow = _shortMaxQuotaFlow.asStateFlow()
|
||||||
|
val limitsStateFlow = merge(
|
||||||
|
longQuotaFlow, shortQuotaFlow, longMaxQuotaFlow, shortMaxQuotaFlow
|
||||||
|
).map { _ ->
|
||||||
|
LimitsState(
|
||||||
|
shortMaxQuota,
|
||||||
|
longMaxQuota,
|
||||||
|
shortQuota,
|
||||||
|
longQuota
|
||||||
|
)
|
||||||
|
}
|
||||||
val limitsState: LimitsState
|
val limitsState: LimitsState
|
||||||
get() = LimitsState(
|
get() = LimitsState(
|
||||||
shortMaxQuota,
|
shortMaxQuota,
|
||||||
@ -35,6 +56,10 @@ internal class RequestQuotaManager (
|
|||||||
for (callback in quotaActions) {
|
for (callback in quotaActions) {
|
||||||
callback()
|
callback()
|
||||||
}
|
}
|
||||||
|
}.also {
|
||||||
|
it.invokeOnCompletion {
|
||||||
|
quotaActions.close(it)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun updateQuota(
|
private suspend fun updateQuota(
|
||||||
@ -83,21 +108,16 @@ internal class RequestQuotaManager (
|
|||||||
)
|
)
|
||||||
|
|
||||||
suspend fun getQuota() {
|
suspend fun getQuota() {
|
||||||
return suspendCoroutine {
|
val job = Job()
|
||||||
lateinit var callback: suspend () -> Unit
|
lateinit var callback: suspend () -> Unit
|
||||||
callback = suspend {
|
callback = suspend {
|
||||||
if (longQuota > 0 && shortQuota > 0) {
|
if (longQuota > 0 && shortQuota > 0) {
|
||||||
it.resumeWith(Result.success(Unit))
|
job.complete()
|
||||||
} else {
|
} else {
|
||||||
quotaActions.send(callback)
|
quotaActions.send(callback)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
quotaActions.trySend(callback)
|
|
||||||
}
|
}
|
||||||
}
|
quotaActions.trySend(callback)
|
||||||
|
return job.join()
|
||||||
override fun close() {
|
|
||||||
quotaJob.cancel()
|
|
||||||
quotaActions.close()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,12 +6,13 @@ interface SauceCloseable {
|
|||||||
fun close()
|
fun close()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun <T> SauceCloseable.use(block: (SauceCloseable) -> T): T = try {
|
inline fun <T> SauceCloseable.use(block: (SauceCloseable) -> T): T = try {
|
||||||
block(this)
|
block(this)
|
||||||
} finally {
|
} finally {
|
||||||
close()
|
close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Deprecated("Useless")
|
||||||
suspend fun <T> SauceCloseable.useSafe(block: suspend (SauceCloseable) -> T): T = try {
|
suspend fun <T> SauceCloseable.useSafe(block: suspend (SauceCloseable) -> T): T = try {
|
||||||
supervisorScope {
|
supervisorScope {
|
||||||
block(this@useSafe)
|
block(this@useSafe)
|
||||||
|
@ -1,13 +1,10 @@
|
|||||||
package dev.inmo.saucenaoapi.utils
|
package dev.inmo.saucenaoapi.utils
|
||||||
|
|
||||||
|
import korlibs.time.DateTime
|
||||||
import dev.inmo.saucenaoapi.additional.LONG_TIME_RECALCULATING_MILLIS
|
import dev.inmo.saucenaoapi.additional.LONG_TIME_RECALCULATING_MILLIS
|
||||||
import dev.inmo.saucenaoapi.additional.SHORT_TIME_RECALCULATING_MILLIS
|
import dev.inmo.saucenaoapi.additional.SHORT_TIME_RECALCULATING_MILLIS
|
||||||
import com.soywiz.klock.DateTime
|
import kotlinx.coroutines.*
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlin.coroutines.Continuation
|
|
||||||
import kotlin.coroutines.suspendCoroutine
|
|
||||||
|
|
||||||
private fun MutableList<DateTime>.clearTooOldTimes(relatedTo: DateTime = DateTime.now()) {
|
private fun MutableList<DateTime>.clearTooOldTimes(relatedTo: DateTime = DateTime.now()) {
|
||||||
val limitValue = relatedTo - LONG_TIME_RECALCULATING_MILLIS
|
val limitValue = relatedTo - LONG_TIME_RECALCULATING_MILLIS
|
||||||
@ -38,16 +35,16 @@ private data class TimeManagerTimeAdder(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private data class TimeManagerMostOldestInLongGetter(
|
private data class TimeManagerMostOldestInLongGetter(
|
||||||
private val continuation: Continuation<DateTime?>
|
private val deferred: CompletableDeferred<DateTime?>
|
||||||
) : TimeManagerAction {
|
) : TimeManagerAction {
|
||||||
override suspend fun makeChangeWith(times: MutableList<DateTime>) {
|
override suspend fun makeChangeWith(times: MutableList<DateTime>) {
|
||||||
times.clearTooOldTimes()
|
times.clearTooOldTimes()
|
||||||
continuation.resumeWith(Result.success(times.minOrNull()))
|
deferred.complete(times.minOrNull())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private data class TimeManagerMostOldestInShortGetter(
|
private data class TimeManagerMostOldestInShortGetter(
|
||||||
private val continuation: Continuation<DateTime?>
|
private val deferred: CompletableDeferred<DateTime?>
|
||||||
) : TimeManagerAction {
|
) : TimeManagerAction {
|
||||||
override suspend fun makeChangeWith(times: MutableList<DateTime>) {
|
override suspend fun makeChangeWith(times: MutableList<DateTime>) {
|
||||||
times.clearTooOldTimes()
|
times.clearTooOldTimes()
|
||||||
@ -56,19 +53,17 @@ private data class TimeManagerMostOldestInShortGetter(
|
|||||||
|
|
||||||
val limitTime = now - SHORT_TIME_RECALCULATING_MILLIS
|
val limitTime = now - SHORT_TIME_RECALCULATING_MILLIS
|
||||||
|
|
||||||
continuation.resumeWith(
|
deferred.complete(
|
||||||
Result.success(
|
times.asSequence().filter {
|
||||||
times.asSequence().filter {
|
limitTime < it
|
||||||
limitTime < it
|
}.minOrNull()
|
||||||
}.minOrNull()
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class TimeManager(
|
internal class TimeManager(
|
||||||
scope: CoroutineScope
|
scope: CoroutineScope
|
||||||
) : SauceCloseable {
|
) {
|
||||||
private val actionsChannel = Channel<TimeManagerAction>(Channel.UNLIMITED)
|
private val actionsChannel = Channel<TimeManagerAction>(Channel.UNLIMITED)
|
||||||
|
|
||||||
private val timeUpdateJob = scope.launch {
|
private val timeUpdateJob = scope.launch {
|
||||||
@ -76,6 +71,10 @@ internal class TimeManager(
|
|||||||
for (action in actionsChannel) {
|
for (action in actionsChannel) {
|
||||||
action(times)
|
action(times)
|
||||||
}
|
}
|
||||||
|
}.also {
|
||||||
|
it.invokeOnCompletion {
|
||||||
|
actionsChannel.close(it)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun addTimeAndClear() {
|
suspend fun addTimeAndClear() {
|
||||||
@ -83,21 +82,20 @@ internal class TimeManager(
|
|||||||
}
|
}
|
||||||
|
|
||||||
suspend fun getMostOldestInLongPeriod(): DateTime? {
|
suspend fun getMostOldestInLongPeriod(): DateTime? {
|
||||||
return suspendCoroutine {
|
val deferred = CompletableDeferred<DateTime?>()
|
||||||
actionsChannel.trySend(
|
return if (actionsChannel.trySend(TimeManagerMostOldestInLongGetter(deferred)).isSuccess) {
|
||||||
TimeManagerMostOldestInLongGetter(it)
|
deferred.await()
|
||||||
)
|
} else {
|
||||||
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun getMostOldestInShortPeriod(): DateTime? {
|
suspend fun getMostOldestInShortPeriod(): DateTime? {
|
||||||
return suspendCoroutine {
|
val deferred = CompletableDeferred<DateTime?>()
|
||||||
actionsChannel.trySend(TimeManagerMostOldestInShortGetter(it))
|
return if (actionsChannel.trySend(TimeManagerMostOldestInShortGetter(deferred)).isSuccess) {
|
||||||
|
deferred.await()
|
||||||
|
} else {
|
||||||
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun close() {
|
|
||||||
actionsChannel.close()
|
|
||||||
timeUpdateJob.cancel()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -1,30 +1,27 @@
|
|||||||
import dev.inmo.saucenaoapi.SauceNaoAPI
|
import dev.inmo.saucenaoapi.SauceNaoAPI
|
||||||
import dev.inmo.saucenaoapi.utils.useSafe
|
import io.ktor.client.HttpClient
|
||||||
import io.ktor.http.ContentType
|
|
||||||
import io.ktor.utils.io.streams.asInput
|
|
||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.nio.file.Files
|
|
||||||
|
|
||||||
suspend fun main(vararg args: String) {
|
suspend fun main(vararg args: String) {
|
||||||
val (key, requestSubject) = args
|
val (key, requestSubject) = args
|
||||||
|
|
||||||
val scope = CoroutineScope(Dispatchers.Default)
|
val client = HttpClient()
|
||||||
|
val scope = CoroutineScope(Dispatchers.IO).also {
|
||||||
val api = SauceNaoAPI(key, scope = scope)
|
it.coroutineContext.job.invokeOnCompletion {
|
||||||
api.useSafe { _ ->
|
client.close()
|
||||||
println(
|
}
|
||||||
when {
|
|
||||||
requestSubject.startsWith("/") -> File(requestSubject).let {
|
|
||||||
api.request(
|
|
||||||
it.inputStream().asInput(),
|
|
||||||
ContentType.parse(Files.probeContentType(it.toPath()))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
else -> api.request(requestSubject)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val api = SauceNaoAPI(key, client, scope = scope)
|
||||||
|
println(
|
||||||
|
when {
|
||||||
|
requestSubject.startsWith("/") -> File(requestSubject).let {
|
||||||
|
api.request(it)
|
||||||
|
}
|
||||||
|
else -> api.request(requestSubject)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
scope.cancel()
|
scope.cancel()
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user