package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.util.PlatformLock import io.ktor.http.Url import kotlinx.coroutines.CancellationException import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.json.* internal class Aria2RpcException(val code: Int? = null) : IllegalStateException( if (code == null) "Invalid external downloader response" else "External downloader RPC error ($code)", ) internal enum class Aria2Status { Active, Waiting, Paused, Error, Complete, Removed } internal data class Aria2Progress( val gid: String, val status: Aria2Status, val totalBytes: Long, val completedBytes: Long, val bytesPerSecond: Long, val errorCode: Int?, ) /** Bounded JSON-RPC transport; callers persist owned GIDs before creating remote work. */ internal class Aria2RpcClient(private val http: HttpService, private val endpoint: String, private val secret: String) { private val idsLock = PlatformLock() private var nextId = 0L init { require(validEndpoint(endpoint)) { "Invalid external downloader URL" } } suspend fun version(): String { val response = call("aria2.getVersion", emptyList()) as? JsonObject ?: throw Aria2RpcException() return (response["version"] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() && it.length <= 128 } ?: throw Aria2RpcException() } suspend fun addUri(gid: String, url: String, directory: String, fileName: String, headers: Map, paused: Boolean = false) { require(validGid(gid)) require(fileName.isNotBlank() && fileName !in setOf(".", "..") && fileName.none { it == '/' || it == '\\' || it.code < 32 }) require(directory.isNotBlank() && directory.none { it.code < 32 }) require(directory.replace('\\', '/').split('/').none { it == ".." }) val parsed = Url(url) require(parsed.protocol.name in setOf("http", "https") && parsed.host.isNotBlank() && parsed.user.isNullOrEmpty() && parsed.password.isNullOrEmpty()) val options = buildJsonObject { put("gid", gid) put("dir", directory) put("out", fileName) put("allow-overwrite", "false") put("auto-file-renaming", "false") put("continue", "true") put("pause", paused.toString()) if (headers.isNotEmpty()) put("header", JsonArray(headers.map { (name, value) -> require(name.matches(Regex("[!#$%&'*+.^_`|~0-9a-zA-Z-]+")) && value.none { it == '\r' || it == '\n' || it == '\u0000' }) JsonPrimitive("$name: $value") })) } val actual = (call("aria2.addUri", listOf(JsonArray(listOf(JsonPrimitive(url))), options)) as? JsonPrimitive)?.contentOrNull if (!gid.equals(actual, true)) throw Aria2RpcException() } suspend fun statuses(gids: List): Map> { require(gids.size in 1..64 && gids.distinct().size == gids.size && gids.all(::validGid)) val keys = JsonArray(listOf("gid", "status", "totalLength", "completedLength", "downloadSpeed", "errorCode").map(::JsonPrimitive)) val results = batch(gids.map { "aria2.tellStatus" to listOf(JsonPrimitive(it), keys) }) return gids.mapIndexed { index, gid -> gid to results[index].mapCatching { result -> val value = result as? JsonObject ?: throw Aria2RpcException() if ((value["gid"] as? JsonPrimitive)?.contentOrNull?.equals(gid, true) != true) throw Aria2RpcException() val status = Aria2Status.entries.firstOrNull { it.name.equals((value["status"] as? JsonPrimitive)?.contentOrNull, true) } ?: throw Aria2RpcException() fun length(name: String): Long = (value[name] as? JsonPrimitive)?.longOrNull?.takeIf { it >= 0 } ?: throw Aria2RpcException() Aria2Progress(gid, status, length("totalLength"), length("completedLength"), length("downloadSpeed"), (value["errorCode"] as? JsonPrimitive)?.intOrNull) } }.toMap() } suspend fun pause(gid: String) = control("aria2.forcePause", gid, expected = gid) suspend fun resume(gid: String) = control("aria2.unpause", gid, expected = gid) suspend fun cancel(gid: String) = control("aria2.forceRemove", gid, expected = gid) suspend fun forgetResult(gid: String) = control("aria2.removeDownloadResult", gid, expected = "OK") private suspend fun control(method: String, gid: String, expected: String) { require(validGid(gid)) if ((call(method, listOf(JsonPrimitive(gid))) as? JsonPrimitive)?.content?.equals(expected, true) != true) throw Aria2RpcException() } private suspend fun call(method: String, params: List): JsonElement { val request = request(method, params) return result(exchange(request) as? JsonObject ?: throw Aria2RpcException(), request["id"].toString()).getOrThrow() } private suspend fun batch(calls: List>>): List> { val requests = calls.map { (method, params) -> request(method, params) } val response = exchange(JsonArray(requests)) as? JsonArray ?: throw Aria2RpcException() if (response.size != requests.size) throw Aria2RpcException() val byId = response.map { it as? JsonObject ?: throw Aria2RpcException() }.associateBy { it["id"].toString() } if (byId.size != response.size) throw Aria2RpcException() return requests.map { request -> val id = request["id"].toString() byId[id]?.let { result(it, id) } ?: Result.failure(Aria2RpcException()) } } private fun request(method: String, params: List) = buildJsonObject { put("jsonrpc", "2.0") put("id", idsLock.withLock { "yokan-${++nextId}" }) put("method", method) put("params", JsonArray((if (secret.isNotBlank()) listOf(JsonPrimitive("token:$secret")) else emptyList()) + params)) } private fun result(response: JsonObject, id: String): Result { if ((response["jsonrpc"] as? JsonPrimitive)?.contentOrNull != "2.0" || response["id"].toString() != id) return Result.failure(Aria2RpcException()) response["error"]?.let { error -> return Result.failure(Aria2RpcException(((error as? JsonObject)?.get("code") as? JsonPrimitive)?.intOrNull)) } return response["result"]?.let(Result.Companion::success) ?: Result.failure(Aria2RpcException()) } private suspend fun exchange(body: JsonElement): JsonElement = withTimeoutOrNull(15_000) { val chunks = mutableListOf() var size = 0 val response = http.stream(HttpRequest(endpoint, method = "POST", headers = mapOf("Content-Type" to "application/json"), body = body.toString())) { chunk -> size += chunk.size if (size > 1024 * 1024) throw Aria2RpcException() chunks += chunk } if (response.statusCode !in 200..299) throw Aria2RpcException(response.statusCode) val bytes = ByteArray(size) var offset = 0 chunks.forEach { chunk -> chunk.copyInto(bytes, offset); offset += chunk.size } try { Json.parseToJsonElement(bytes.decodeToString()) } catch (cancel: CancellationException) { throw cancel } catch (_: Exception) { throw Aria2RpcException() } } ?: throw Aria2RpcException() companion object { fun validGid(gid: String) = gid.matches(Regex("[0-9a-fA-F]{16}")) && gid.any { it != '0' } fun validEndpoint(raw: String): Boolean = try { val url = Url(raw) url.protocol.name in setOf("http", "https") && url.host.isNotBlank() && url.user.isNullOrEmpty() && url.password.isNullOrEmpty() && url.fragment.isEmpty() && url.parameters.entries().isEmpty() } catch (_: Exception) { false } } }