TorrServerClient.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerClient.kt
1package eu.friedcutlet.yokan.services.torrent23import eu.friedcutlet.yokan.services.http.HttpRequest4import eu.friedcutlet.yokan.services.http.HttpService5import io.ktor.http.encodeURLParameter6import io.ktor.http.encodeURLPathPart7import kotlinx.serialization.SerialName8import kotlinx.serialization.Serializable9import kotlinx.serialization.json.Json10import kotlinx.serialization.json.JsonObject11import kotlinx.serialization.json.JsonPrimitive12import kotlinx.serialization.json.buildJsonObject13import kotlinx.serialization.json.decodeFromJsonElement14import kotlinx.serialization.json.jsonObject15import kotlinx.serialization.json.put16import kotlin.io.encoding.Base6417import kotlin.random.Random1819@Serializable20data class TorrServerTorrent(21 val title: String = "",22 val hash: String = "",23 @SerialName("stat_string") val state: String = "",24 @SerialName("torrent_size") val size: Long = 0,25 @SerialName("file_stats") val files: List<TorrServerFile> = emptyList(),26)2728/** TorrServer file ids start at 1 and are the `index` of stream URLs. */29@Serializable30data class TorrServerFile(val id: Int, val path: String, val length: Long = 0) {31 val name: String get() = path.substringAfterLast('/')32}3334class TorrServerException(val status: Int, message: String) : IllegalStateException(message)3536/** TorrServer's HTTP API (github.com/YouROK/TorrServer `server/web/api`). */37class TorrServerClient(38 private val http: HttpService,39 baseUrl: String,40 username: String = "",41 password: String = "",42) {43 val baseUrl = baseUrl.trim().trimEnd('/')44 private val auth = if (username.isEmpty()) emptyMap()45 else mapOf("Authorization" to "Basic " + Base64.encode("$username:$password".encodeToByteArray()))4647 /** Health check; TorrServer answers its version. */48 suspend fun echo(): String = call("GET", "/echo").trim()4950 suspend fun add(link: String, title: String): TorrServerTorrent = torrent("add") { put("link", link); put("title", title) }5152 suspend fun get(hash: String): TorrServerTorrent = torrent("get") { put("hash", hash) }5354 suspend fun list(): List<TorrServerTorrent> =55 json.decodeFromString(call("POST", "/torrents", json = buildJsonObject { put("action", "list") }))5657 suspend fun remove(hash: String) {58 call("POST", "/torrents", json = buildJsonObject { put("action", "rem"); put("hash", hash) })59 }6061 /** Adds a local `.torrent` file the server cannot read itself. */62 suspend fun upload(torrent: ByteArray, fileName: String, title: String): TorrServerTorrent {63 val boundary = "yokan" + Random.nextLong().toULong().toString(16)64 fun part(name: String, extra: String = "") = "--$boundary\r\nContent-Disposition: form-data; name=\"$name\"$extra\r\n"65 val body = (part("title") + "\r\n$title\r\n" +66 part("file", "; filename=\"${fileName.replace("\"", "")}\"") + "Content-Type: application/x-bittorrent\r\n\r\n").encodeToByteArray() +67 torrent + "\r\n--$boundary--\r\n".encodeToByteArray()68 return json.decodeFromString(call("POST", "/torrent/upload", body, "multipart/form-data; boundary=$boundary"))69 }7071 /** Full `BTSets`; `set` replaces every field, so callers modify this object rather than build a partial one. */72 suspend fun settings(): JsonObject =73 json.parseToJsonElement(call("POST", "/settings", json = buildJsonObject { put("action", "get") })).jsonObject7475 suspend fun setSettings(sets: JsonObject) {76 call("POST", "/settings", json = JsonObject(mapOf("action" to JsonPrimitive("set"), "sets" to sets)))77 }7879 /** `play` URLs stream with Range support and need no credentials (TorrServer `streamNoAuth`). */80 fun streamUrl(hash: String, file: TorrServerFile): String =81 "$baseUrl/stream/${file.name.encodeURLPathPart()}?link=${hash.encodeURLParameter()}&index=${file.id}&play"8283 private suspend fun torrent(action: String, fields: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit): TorrServerTorrent =84 json.decodeFromJsonElement(json.parseToJsonElement(call("POST", "/torrents", json = buildJsonObject { put("action", action); fields() })))8586 private suspend fun call(method: String, path: String, bytes: ByteArray? = null, contentType: String? = null, json: JsonObject? = null): String {87 val type = contentType ?: if (json != null) "application/json" else null88 val response = http.request(HttpRequest(89 url = baseUrl + path,90 method = method,91 headers = auth + listOfNotNull(type?.let { "Content-Type" to it }),92 body = json?.toString(),93 bodyBytes = bytes,94 ))95 val text = response.bodyBytes.decodeToString()96 if (response.statusCode !in 200..299) {97 val detail = runCatching { Json.parseToJsonElement(text).jsonObject["error"]?.toString()?.trim('"') }.getOrNull() ?: text.take(200)98 throw TorrServerException(response.statusCode, "TorrServer $path failed (HTTP ${response.statusCode})${detail.takeIf(String::isNotBlank)?.let { ": $it" }.orEmpty()}")99 }100 return text101 }102103 private companion object {104 val json = Json { ignoreUnknownKeys = true }105 }106}107