package eu.friedcutlet.yokan.services.tracking import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackPreference import eu.friedcutlet.yokan.database.DbTrackSearch import eu.friedcutlet.yokan.database.DbTrackStatus import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import io.ktor.http.encodeURLParameter import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.doubleOrNull import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.longOrNull import kotlinx.serialization.json.put import kotlin.math.roundToInt /** * TMDB v3 (movies + TV) with the user's own API key and a session from the request-token approval flow. * TMDB has no episode progress: progress stays local; the watchlist mirrors PlanToWatch and ratings the score. */ class TmdbTrackerService( override val syncId: Int, private val database: YokanDatabase, private val http: HttpService, ) : TrackerService { override val name: String = "TMDB" /** Request token from [authorizeUrl], keyed by the API key that created it. */ private var pendingToken: Pair? = null override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? = database.tracks(track.mangaId).firstOrNull { it.syncId == syncId } override fun supports(isManga: Boolean): Boolean = !isManga override fun statusList(isManga: Boolean): List = DbTrack(status = DbTrackStatus.Watching).readableStatusList(false) override fun scoreValue(): Pair = 0 to 10 override fun displayScore(score: Int): String = if (score == 0) "-" else "$score/10" override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List = emptyList() override suspend fun fetchUserData(isManga: Boolean): List = emptyList() override val loginFields: List = listOf(TrackerLoginField.ApiKey) override val browserSignIn: Boolean = true override suspend fun authorizeUrl(values: Map): String { val apiKey = values.required(TrackerLoginField.ApiKey) val token = http.request(HttpRequest("$Api/authentication/token/new?api_key=${apiKey.encodeURLParameter()}")) .json(name).jsonObject.string("request_token") ?: throw IllegalStateException("TMDB returned no request token") pendingToken = apiKey to token return "https://www.themoviedb.org/authenticate/$token?redirect_to=${TrackerOAuth.redirectUri(syncId).encodeURLParameter()}" } override suspend fun login(values: Map): DbTrackPreference { val apiKey = values.required(TrackerLoginField.ApiKey) val token = pendingToken?.takeIf { it.first == apiKey }?.second ?: throw IllegalStateException("Sign in first: open the TMDB approval page, approve, then connect") val key = apiKey.encodeURLParameter() val sessionBody = buildJsonObject { put("request_token", token) }.toString() val session = http.request(HttpRequest("$Api/authentication/session/new?api_key=$key", "POST", body = sessionBody)) .json(name).jsonObject.string("session_id") ?: throw IllegalStateException("TMDB returned no session") pendingToken = null val account = http.request(HttpRequest("$Api/account?api_key=$key&session_id=${session.encodeURLParameter()}")) .json(name).jsonObject return DbTrackPreference( syncId = syncId.toLong(), username = account.string("username"), accountName = account.string("name")?.takeIf { it.isNotBlank() } ?: account.string("username"), oauth = session, prefs = TrackerCredentials(apiKey = apiKey, userId = account.long("id")?.toString()).encode(), refreshing = false, ) } override suspend fun accountProfile(): TrackerAccountProfile? { val account = request("/account").json(name).jsonObject return TrackerAccountProfile(name = account.string("username")) } override suspend fun search(query: String, isManga: Boolean): List { trackerSearchId(query)?.let { raw -> val type = raw.substringBefore('/', "").lowercase().takeIf { it == "movie" || it == "tv" } val id = raw.substringAfter('/').toLongOrNull() ?: return emptyList() for (kind in type?.let { listOf(it) } ?: listOf("tv", "movie")) { val response = request("/$kind/$id") if (response.statusCode == 404) continue return listOf(response.json(name).jsonObject.toSearch(kind)) } return emptyList() } if (query.isBlank()) return emptyList() val results = request("/search/multi", "query=${query.trim().encodeURLParameter()}").json(name).jsonObject["results"] as? JsonArray return results.orEmpty().mapNotNull { item -> val obj = item as? JsonObject ?: return@mapNotNull null obj.string("media_type")?.takeIf { it == "movie" || it == "tv" }?.let { obj.toSearch(it) } } } override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack { val states = accountStates(track) return if (states.watchlist() || states.rating() != null) track.withStates(states) else update(track, isManga) } override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack = track.withStates(accountStates(track)) override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack { val (kind, id) = media(track) setWatchlist(kind, id, track.status == DbTrackStatus.PlanToWatch) val score = (track.score ?: 0).coerceIn(0, 10) if (score > 0) { request("/$kind/$id/rating", method = "POST", body = buildJsonObject { put("value", score.toDouble()) }.toString()) .requireSuccess(name) } else { deleteRating(kind, id) } return track.copy(score = score) } override suspend fun unbind(track: DbTrack, isManga: Boolean) { val (kind, id) = media(track) setWatchlist(kind, id, false) deleteRating(kind, id) } private suspend fun accountStates(track: DbTrack): JsonObject { val (kind, id) = media(track) return request("/$kind/$id/account_states").json(name).jsonObject } private fun DbTrack.withStates(states: JsonObject): DbTrack { val rating = states.rating() return copy( status = if (states.watchlist()) DbTrackStatus.PlanToWatch else if (status == DbTrackStatus.PlanToWatch) DbTrackStatus.Watching else status, score = rating?.let { it.roundToInt().coerceIn(1, 10) } ?: 0, ) } private suspend fun setWatchlist(kind: String, id: Long, watchlist: Boolean) { val accountId = database.trackPreference(syncId)?.credentials()?.userId ?: throw IllegalStateException("Not logged in to $name") val body = buildJsonObject { put("media_type", kind) put("media_id", id) put("watchlist", watchlist) }.toString() request("/account/$accountId/watchlist", method = "POST", body = body).requireSuccess(name) } /** Deleting a rating that was never set answers 404; nothing to remove then. */ private suspend fun deleteRating(kind: String, id: Long) { val response = request("/$kind/$id/rating", method = "DELETE") if (response.statusCode != 404) response.requireSuccess(name) } private fun media(track: DbTrack): Pair = tmdbMediaOf(track) ?: throw IllegalStateException("TMDB entry has no id") private fun JsonObject.toSearch(kind: String): DbTrackSearch { val id = long("id") ?: 0L return DbTrackSearch( syncId = syncId, mediaId = id, title = string(if (kind == "movie") "title" else "name") ?: string("original_title") ?: string("original_name"), trackingUrl = "https://www.themoviedb.org/$kind/$id", totalChapter = if (kind == "movie") 1 else int("number_of_episodes"), coverUrl = string("poster_path")?.let { "https://image.tmdb.org/t/p/w500$it" }.orEmpty(), summary = string("overview").orEmpty(), publishingStatus = string("status").orEmpty(), publishingType = kind, startDate = (string("release_date") ?: string("first_air_date")).orEmpty(), score = (this["vote_average"] as? JsonPrimitive)?.doubleOrNull, status = "", ) } /** `api_key` + `session_id` query auth; 401 means the key or session was revoked (sign in again). */ private suspend fun request(path: String, query: String? = null, method: String = "GET", body: String? = null): HttpResponse { val preference = database.trackPreference(syncId) val session = preference?.oauth?.takeIf { it.isNotBlank() } ?: throw IllegalStateException("Not logged in to $name") val apiKey = preference.credentials().apiKey ?: throw IllegalStateException("Not logged in to $name") val url = "$Api$path?api_key=${apiKey.encodeURLParameter()}&session_id=${session.encodeURLParameter()}" + query?.let { "&$it" }.orEmpty() val response = http.request(HttpRequest(url, method, body = body)) if (response.statusCode == 401) throw TrackerHttpException(name, 401, response.body) return response } private companion object { const val Api = "https://api.themoviedb.org/3" fun JsonObject.watchlist(): Boolean = (this["watchlist"] as? JsonPrimitive)?.booleanOrNull == true /** `rated` is `false` or `{"value": 8.5}`. */ fun JsonObject.rating(): Double? = ((this["rated"] as? JsonObject)?.get("value") as? JsonPrimitive)?.doubleOrNull fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull fun JsonObject.long(key: String): Long? = (this[key] as? JsonPrimitive)?.longOrNull } } /** `movie`/`tv` and the TMDB id from the stored tracking URL (falls back to tv + [DbTrack.mediaId]). */ fun tmdbMediaOf(track: DbTrack): Pair? { val path = track.trackingUrl.orEmpty().substringAfter("themoviedb.org/", "").split('/') val kind = path.getOrNull(0)?.takeIf { it == "movie" || it == "tv" } ?: "tv" val id = path.getOrNull(1)?.substringBefore('-')?.toLongOrNull() ?: track.mediaId ?: return null return kind to id }