Yokan / rebuild
Course 1 8624561

Aria2RpcClient.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/Aria2RpcClient.kt

implementation141 lines
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.services.http.HttpRequest4import eu.friedcutlet.yokan.services.http.HttpService5import eu.friedcutlet.yokan.util.PlatformLock6import io.ktor.http.Url7import kotlinx.coroutines.CancellationException8import kotlinx.coroutines.withTimeoutOrNull9import kotlinx.serialization.json.*1011internal class Aria2RpcException(val code: Int? = null) : IllegalStateException(12    if (code == null) "Invalid external downloader response" else "External downloader RPC error ($code)",13)1415internal enum class Aria2Status { Active, Waiting, Paused, Error, Complete, Removed }1617internal data class Aria2Progress(18    val gid: String,19    val status: Aria2Status,20    val totalBytes: Long,21    val completedBytes: Long,22    val bytesPerSecond: Long,23    val errorCode: Int?,24)2526/** Bounded JSON-RPC transport; callers persist owned GIDs before creating remote work. */27internal class Aria2RpcClient(private val http: HttpService, private val endpoint: String, private val secret: String) {28    private val idsLock = PlatformLock()29    private var nextId = 0L30    init { require(validEndpoint(endpoint)) { "Invalid external downloader URL" } }3132    suspend fun version(): String {33        val response = call("aria2.getVersion", emptyList()) as? JsonObject ?: throw Aria2RpcException()34        return (response["version"] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() && it.length <= 128 } ?: throw Aria2RpcException()35    }3637    suspend fun addUri(gid: String, url: String, directory: String, fileName: String, headers: Map<String, String>, paused: Boolean = false) {38        require(validGid(gid))39        require(fileName.isNotBlank() && fileName !in setOf(".", "..") && fileName.none { it == '/' || it == '\\' || it.code < 32 })40        require(directory.isNotBlank() && directory.none { it.code < 32 })41        require(directory.replace('\\', '/').split('/').none { it == ".." })42        val parsed = Url(url)43        require(parsed.protocol.name in setOf("http", "https") && parsed.host.isNotBlank() && parsed.user.isNullOrEmpty() && parsed.password.isNullOrEmpty())44        val options = buildJsonObject {45            put("gid", gid)46            put("dir", directory)47            put("out", fileName)48            put("allow-overwrite", "false")49            put("auto-file-renaming", "false")50            put("continue", "true")51            put("pause", paused.toString())52            if (headers.isNotEmpty()) put("header", JsonArray(headers.map { (name, value) ->53                require(name.matches(Regex("[!#$%&'*+.^_`|~0-9a-zA-Z-]+")) && value.none { it == '\r' || it == '\n' || it == '\u0000' })54                JsonPrimitive("$name: $value")55            }))56        }57        val actual = (call("aria2.addUri", listOf(JsonArray(listOf(JsonPrimitive(url))), options)) as? JsonPrimitive)?.contentOrNull58        if (!gid.equals(actual, true)) throw Aria2RpcException()59    }6061    suspend fun statuses(gids: List<String>): Map<String, Result<Aria2Progress>> {62        require(gids.size in 1..64 && gids.distinct().size == gids.size && gids.all(::validGid))63        val keys = JsonArray(listOf("gid", "status", "totalLength", "completedLength", "downloadSpeed", "errorCode").map(::JsonPrimitive))64        val results = batch(gids.map { "aria2.tellStatus" to listOf(JsonPrimitive(it), keys) })65        return gids.mapIndexed { index, gid -> gid to results[index].mapCatching { result ->66            val value = result as? JsonObject ?: throw Aria2RpcException()67            if ((value["gid"] as? JsonPrimitive)?.contentOrNull?.equals(gid, true) != true) throw Aria2RpcException()68            val status = Aria2Status.entries.firstOrNull { it.name.equals((value["status"] as? JsonPrimitive)?.contentOrNull, true) } ?: throw Aria2RpcException()69            fun length(name: String): Long = (value[name] as? JsonPrimitive)?.longOrNull?.takeIf { it >= 0 } ?: throw Aria2RpcException()70            Aria2Progress(gid, status, length("totalLength"), length("completedLength"), length("downloadSpeed"), (value["errorCode"] as? JsonPrimitive)?.intOrNull)71        } }.toMap()72    }7374    suspend fun pause(gid: String) = control("aria2.forcePause", gid, expected = gid)75    suspend fun resume(gid: String) = control("aria2.unpause", gid, expected = gid)76    suspend fun cancel(gid: String) = control("aria2.forceRemove", gid, expected = gid)77    suspend fun forgetResult(gid: String) = control("aria2.removeDownloadResult", gid, expected = "OK")7879    private suspend fun control(method: String, gid: String, expected: String) {80        require(validGid(gid))81        if ((call(method, listOf(JsonPrimitive(gid))) as? JsonPrimitive)?.content?.equals(expected, true) != true) throw Aria2RpcException()82    }8384    private suspend fun call(method: String, params: List<JsonElement>): JsonElement {85        val request = request(method, params)86        return result(exchange(request) as? JsonObject ?: throw Aria2RpcException(), request["id"].toString()).getOrThrow()87    }8889    private suspend fun batch(calls: List<Pair<String, List<JsonElement>>>): List<Result<JsonElement>> {90        val requests = calls.map { (method, params) -> request(method, params) }91        val response = exchange(JsonArray(requests)) as? JsonArray ?: throw Aria2RpcException()92        if (response.size != requests.size) throw Aria2RpcException()93        val byId = response.map { it as? JsonObject ?: throw Aria2RpcException() }.associateBy { it["id"].toString() }94        if (byId.size != response.size) throw Aria2RpcException()95        return requests.map { request ->96            val id = request["id"].toString()97            byId[id]?.let { result(it, id) } ?: Result.failure(Aria2RpcException())98        }99    }100101    private fun request(method: String, params: List<JsonElement>) = buildJsonObject {102        put("jsonrpc", "2.0")103        put("id", idsLock.withLock { "yokan-${++nextId}" })104        put("method", method)105        put("params", JsonArray((if (secret.isNotBlank()) listOf(JsonPrimitive("token:$secret")) else emptyList()) + params))106    }107108    private fun result(response: JsonObject, id: String): Result<JsonElement> {109        if ((response["jsonrpc"] as? JsonPrimitive)?.contentOrNull != "2.0" || response["id"].toString() != id) return Result.failure(Aria2RpcException())110        response["error"]?.let { error ->111            return Result.failure(Aria2RpcException(((error as? JsonObject)?.get("code") as? JsonPrimitive)?.intOrNull))112        }113        return response["result"]?.let(Result.Companion::success) ?: Result.failure(Aria2RpcException())114    }115116    private suspend fun exchange(body: JsonElement): JsonElement = withTimeoutOrNull(15_000) {117        val chunks = mutableListOf<ByteArray>()118        var size = 0119        val response = http.stream(HttpRequest(endpoint, method = "POST", headers = mapOf("Content-Type" to "application/json"), body = body.toString())) { chunk ->120            size += chunk.size121            if (size > 1024 * 1024) throw Aria2RpcException()122            chunks += chunk123        }124        if (response.statusCode !in 200..299) throw Aria2RpcException(response.statusCode)125        val bytes = ByteArray(size)126        var offset = 0127        chunks.forEach { chunk -> chunk.copyInto(bytes, offset); offset += chunk.size }128        try { Json.parseToJsonElement(bytes.decodeToString()) }129        catch (cancel: CancellationException) { throw cancel }130        catch (_: Exception) { throw Aria2RpcException() }131    } ?: throw Aria2RpcException()132133    companion object {134        fun validGid(gid: String) = gid.matches(Regex("[0-9a-fA-F]{16}")) && gid.any { it != '0' }135        fun validEndpoint(raw: String): Boolean = try {136            val url = Url(raw)137            url.protocol.name in setOf("http", "https") && url.host.isNotBlank() && url.user.isNullOrEmpty() && url.password.isNullOrEmpty() &&138                url.fragment.isEmpty() && url.parameters.entries().isEmpty()139        } catch (_: Exception) { false }140    }141}142

Search chapters, reference and source filenames.