Yokan / rebuild
Course 1 8624561

JellyfinTrackerService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/JellyfinTrackerService.kt

implementation129 lines
1package eu.friedcutlet.yokan.services.tracking23import eu.friedcutlet.yokan.database.DbTrackPreference4import eu.friedcutlet.yokan.database.DbTrackSearch5import eu.friedcutlet.yokan.database.YokanDatabase6import eu.friedcutlet.yokan.services.http.HttpRequest7import eu.friedcutlet.yokan.services.http.HttpService8import kotlinx.serialization.json.JsonArray9import kotlinx.serialization.json.JsonObject10import kotlinx.serialization.json.booleanOrNull11import kotlinx.serialization.json.buildJsonObject12import kotlinx.serialization.json.contentOrNull13import kotlinx.serialization.json.intOrNull14import kotlinx.serialization.json.jsonObject15import kotlinx.serialization.json.jsonPrimitive16import kotlinx.serialization.json.put1718/**19 * Jellyfin (Animetail `JellyfinApi`). Signs in with username/password for an access token (`X-Emby-Token`).20 * Item keys are item ids; a series or season counts its leading run of played episodes (season: episode21 * `IndexNumber`, whole series: position), anything else (movie) is 1 when played.22 */23class JellyfinTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) :24    ServerTrackerService(syncId, database, http) {25    override val name: String = "Jellyfin"26    override val sourceKeywords = listOf("jellyfin")27    override val forManga = false2829    override val loginFields = listOf(TrackerLoginField.ServerUrl, TrackerLoginField.Username, TrackerLoginField.Password)3031    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {32        val server = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl))33        val body = buildJsonObject {34            put("Username", values.required(TrackerLoginField.Username))35            put("Pw", values[TrackerLoginField.Password].orEmpty())36        }37        val auth = http.request(38            HttpRequest(39                "$server/Users/AuthenticateByName",40                method = "POST",41                headers = mapOf("X-Emby-Authorization" to CLIENT_AUTHORIZATION),42                body = body.toString(),43            ),44        ).json(name).jsonObject45        val user = auth["User"]?.jsonObject46        val token = auth["AccessToken"]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }47        val userId = user?.get("Id")?.jsonPrimitive?.contentOrNull48        if (token == null || userId == null) throw IllegalStateException("Jellyfin did not return a session")49        return loginPreference(50            username = user["Name"]?.jsonPrimitive?.contentOrNull,51            oauth = token,52            credentials = TrackerCredentials(serverUrl = server, userId = userId),53        )54    }5556    override fun authHeaders(preference: DbTrackPreference): Map<String, String> =57        mapOf("X-Emby-Token" to preference.oauth.orEmpty())5859    override fun itemKey(link: String): String? =60        (segmentAfter(link, "Items") ?: linkParameter(link, "Id") ?: linkParameter(link, "seriesId") ?: link.trim())61            .takeIf { id -> id.isNotEmpty() && id.all { it.isLetterOrDigit() || it == '-' } }6263    private fun userId(): String = preference()?.credentials()?.userId.orEmpty()6465    // Current (10.9+) routes; the `/Users/{userId}/Items|PlayedItems` forms are deprecated upstream.66    private fun itemUrl(key: String): String = "${server()}/Items/$key?userId=${userId()}"6768    override suspend fun fetch(key: String): DbTrackSearch {69        val url = "${server()}/Items/$key"70        val item = getJson(itemUrl(key)).jsonObject71        val episodes = episodes(item, key)72        val total: Int73        val progress: Int74        if (episodes == null) {75            total = 176            progress = if (item.played()) 1 else 077        } else {78            total = episodes.lastOrNull()?.first ?: 079            val firstUnplayed = episodes.indexOfFirst { !it.second.played() }80            progress = when (firstUnplayed) {81                -1 -> total82                0 -> 083                else -> episodes[firstUnplayed - 1].first84            }85        }86        return DbTrackSearch(87            syncId = syncId,88            title = item["Name"]?.jsonPrimitive?.contentOrNull,89            trackingUrl = url,90            coverUrl = "${server()}/Items/$key/Images/Primary",91            summary = item["Overview"]?.jsonPrimitive?.contentOrNull.orEmpty(),92            totalChapter = total,93            lastChapterRead = progress,94            status = remoteStatus(unread = progress == 0, completed = total > 0 && progress >= total),95        )96    }9798    /** Marks every unplayed episode numbered up to [progress] (or the movie) played. */99    override suspend fun push(key: String, progress: Int) {100        val item = getJson(itemUrl(key)).jsonObject101        val ids = episodes(item, key)?.filter { (number, episode) -> number <= progress && !episode.played() }?.map { it.second.id() }102            ?: listOf(key).takeIf { progress > 0 && !item.played() }.orEmpty()103        for (id in ids) send("${server()}/UserPlayedItems/$id?userId=${userId()}", method = "POST").requireSuccess(name)104    }105106    /** `(episode number, episode)` in order for a series or season; null for a single playable item. */107    private suspend fun episodes(item: JsonObject, key: String): List<Pair<Int, JsonObject>>? {108        val userId = userId()109        val url = when (item["Type"]?.jsonPrimitive?.contentOrNull) {110            "Series" -> "${server()}/Shows/$key/Episodes?userId=$userId"111            "Season" -> "${server()}/Shows/${item["SeriesId"]?.jsonPrimitive?.contentOrNull}/Episodes?userId=$userId&seasonId=$key"112            else -> return null113        }114        val season = item["Type"]?.jsonPrimitive?.contentOrNull == "Season"115        val list = (getJson(url).jsonObject["Items"] as? JsonArray).orEmpty().map { it.jsonObject }116        return list.mapIndexed { i, episode ->117            ((if (season) episode["IndexNumber"]?.jsonPrimitive?.intOrNull else null) ?: (i + 1)) to episode118        }119    }120121    private fun JsonObject.played(): Boolean =122        (this["UserData"] as? JsonObject)?.get("Played")?.jsonPrimitive?.booleanOrNull == true123124    private fun JsonObject.id(): String = this["Id"]?.jsonPrimitive?.contentOrNull.orEmpty()125126    private companion object {127        const val CLIENT_AUTHORIZATION = "MediaBrowser Client=\"Yokan\", Device=\"Yokan\", DeviceId=\"yokan\", Version=\"1\""128    }129}130

Search chapters, reference and source filenames.