package eu.friedcutlet.yokan.services.tracking import eu.friedcutlet.yokan.database.DbTrackPreference import eu.friedcutlet.yokan.database.DbTrackSearch import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put /** * Jellyfin (Animetail `JellyfinApi`). Signs in with username/password for an access token (`X-Emby-Token`). * Item keys are item ids; a series or season counts its leading run of played episodes (season: episode * `IndexNumber`, whole series: position), anything else (movie) is 1 when played. */ class JellyfinTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) : ServerTrackerService(syncId, database, http) { override val name: String = "Jellyfin" override val sourceKeywords = listOf("jellyfin") override val forManga = false override val loginFields = listOf(TrackerLoginField.ServerUrl, TrackerLoginField.Username, TrackerLoginField.Password) override suspend fun login(values: Map): DbTrackPreference { val server = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl)) val body = buildJsonObject { put("Username", values.required(TrackerLoginField.Username)) put("Pw", values[TrackerLoginField.Password].orEmpty()) } val auth = http.request( HttpRequest( "$server/Users/AuthenticateByName", method = "POST", headers = mapOf("X-Emby-Authorization" to CLIENT_AUTHORIZATION), body = body.toString(), ), ).json(name).jsonObject val user = auth["User"]?.jsonObject val token = auth["AccessToken"]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() } val userId = user?.get("Id")?.jsonPrimitive?.contentOrNull if (token == null || userId == null) throw IllegalStateException("Jellyfin did not return a session") return loginPreference( username = user["Name"]?.jsonPrimitive?.contentOrNull, oauth = token, credentials = TrackerCredentials(serverUrl = server, userId = userId), ) } override fun authHeaders(preference: DbTrackPreference): Map = mapOf("X-Emby-Token" to preference.oauth.orEmpty()) override fun itemKey(link: String): String? = (segmentAfter(link, "Items") ?: linkParameter(link, "Id") ?: linkParameter(link, "seriesId") ?: link.trim()) .takeIf { id -> id.isNotEmpty() && id.all { it.isLetterOrDigit() || it == '-' } } private fun userId(): String = preference()?.credentials()?.userId.orEmpty() // Current (10.9+) routes; the `/Users/{userId}/Items|PlayedItems` forms are deprecated upstream. private fun itemUrl(key: String): String = "${server()}/Items/$key?userId=${userId()}" override suspend fun fetch(key: String): DbTrackSearch { val url = "${server()}/Items/$key" val item = getJson(itemUrl(key)).jsonObject val episodes = episodes(item, key) val total: Int val progress: Int if (episodes == null) { total = 1 progress = if (item.played()) 1 else 0 } else { total = episodes.lastOrNull()?.first ?: 0 val firstUnplayed = episodes.indexOfFirst { !it.second.played() } progress = when (firstUnplayed) { -1 -> total 0 -> 0 else -> episodes[firstUnplayed - 1].first } } return DbTrackSearch( syncId = syncId, title = item["Name"]?.jsonPrimitive?.contentOrNull, trackingUrl = url, coverUrl = "${server()}/Items/$key/Images/Primary", summary = item["Overview"]?.jsonPrimitive?.contentOrNull.orEmpty(), totalChapter = total, lastChapterRead = progress, status = remoteStatus(unread = progress == 0, completed = total > 0 && progress >= total), ) } /** Marks every unplayed episode numbered up to [progress] (or the movie) played. */ override suspend fun push(key: String, progress: Int) { val item = getJson(itemUrl(key)).jsonObject val ids = episodes(item, key)?.filter { (number, episode) -> number <= progress && !episode.played() }?.map { it.second.id() } ?: listOf(key).takeIf { progress > 0 && !item.played() }.orEmpty() for (id in ids) send("${server()}/UserPlayedItems/$id?userId=${userId()}", method = "POST").requireSuccess(name) } /** `(episode number, episode)` in order for a series or season; null for a single playable item. */ private suspend fun episodes(item: JsonObject, key: String): List>? { val userId = userId() val url = when (item["Type"]?.jsonPrimitive?.contentOrNull) { "Series" -> "${server()}/Shows/$key/Episodes?userId=$userId" "Season" -> "${server()}/Shows/${item["SeriesId"]?.jsonPrimitive?.contentOrNull}/Episodes?userId=$userId&seasonId=$key" else -> return null } val season = item["Type"]?.jsonPrimitive?.contentOrNull == "Season" val list = (getJson(url).jsonObject["Items"] as? JsonArray).orEmpty().map { it.jsonObject } return list.mapIndexed { i, episode -> ((if (season) episode["IndexNumber"]?.jsonPrimitive?.intOrNull else null) ?: (i + 1)) to episode } } private fun JsonObject.played(): Boolean = (this["UserData"] as? JsonObject)?.get("Played")?.jsonPrimitive?.booleanOrNull == true private fun JsonObject.id(): String = this["Id"]?.jsonPrimitive?.contentOrNull.orEmpty() private companion object { const val CLIENT_AUTHORIZATION = "MediaBrowser Client=\"Yokan\", Device=\"Yokan\", DeviceId=\"yokan\", Version=\"1\"" } }