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 io.ktor.http.encodeURLParameter import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive /** * Kavita (Animetail `KavitaApi`). The API key is exchanged for a JWT via the plugin endpoint and renewed the * same way on a 401. Item keys are numeric series ids; progress is the latest read chapter number. */ class KavitaTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) : ServerTrackerService(syncId, database, http) { override val name: String = "Kavita" override val sourceKeywords = listOf("kavita") override val forManga = true override val loginFields = listOf(TrackerLoginField.ServerUrl, TrackerLoginField.ApiKey) override suspend fun login(values: Map): DbTrackPreference { // A pasted `…/api` or OPDS URL still names the server. val typed = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl)) val server = typed.substringBefore("://") + "://" + "${typed.substringAfter("://")}/".substringBefore("/api/").trimEnd('/') val apiKey = values.required(TrackerLoginField.ApiKey) val user = authenticate(server, apiKey) return loginPreference( username = user["username"]?.jsonPrimitive?.contentOrNull, oauth = user.token(), credentials = TrackerCredentials(serverUrl = server, apiKey = apiKey), ) } private suspend fun authenticate(server: String, apiKey: String): JsonObject = http.request( HttpRequest( "$server/api/Plugin/authenticate?apiKey=${apiKey.encodeURLParameter()}&pluginName=Yokan", method = "POST", body = "{}", ), ).json(name).jsonObject override suspend fun reauthenticate(preference: DbTrackPreference): DbTrackPreference { val credentials = preference.credentials() val token = authenticate(credentials.serverUrl.orEmpty(), credentials.apiKey.orEmpty()).token() return database.upsertTrackPreference(preference.copy(oauth = token)) } private fun JsonObject.token(): String = this["token"]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() } ?: throw IllegalStateException("Kavita did not return a session token") override fun authHeaders(preference: DbTrackPreference): Map = mapOf("Authorization" to "Bearer ${preference.oauth}") override fun itemKey(link: String): String? = (segmentAfter(link, "series") ?: linkParameter(link, "seriesId") ?: link.trim()) .takeIf { id -> id.isNotEmpty() && id.all { it.isDigit() } } override suspend fun fetch(key: String): DbTrackSearch { val api = "${server()}/api" val url = "$api/Series/$key" val series = getJson(url).jsonObject val pages = series["pages"]?.jsonPrimitive?.intOrNull ?: 0 val pagesRead = series["pagesRead"]?.jsonPrimitive?.intOrNull ?: 0 val volumes = getJson("$api/Series/volumes?seriesId=$key") as? JsonArray ?: JsonArray(emptyList()) val latest = send("$api/Tachiyomi/latest-chapter?seriesId=$key").requireSuccess(name) val lastRead = if (latest.statusCode == 204 || latest.body.isBlank()) 0.0 else trackerJson.parseToJsonElement(latest.body).jsonObject.chapterNumber() return DbTrackSearch( syncId = syncId, mediaId = key.toLong(), title = series["name"]?.jsonPrimitive?.contentOrNull, trackingUrl = url, totalChapter = totalChapters(volumes), lastChapterRead = lastRead.toInt(), status = remoteStatus(unread = pagesRead == 0, completed = pagesRead == pages), ) } /** Upstream rule: the highest chapter number, or the count of chapterless (single-file) volumes if larger. */ private fun totalChapters(volumes: JsonArray): Int { var volumeCount = 0 var maxChapter = 0 for (volume in volumes) { val chapters = (volume.jsonObject["chapters"] as? JsonArray).orEmpty() if (chapters.isEmpty()) continue val highest = chapters.maxOf { it.jsonObject.chapterNumber() } if (highest == 0.0) volumeCount++ else if (highest > maxChapter) maxChapter = highest.toInt() } return maxOf(maxChapter, volumeCount) } /** Kavita chapter `number` is a string (`"12"`, `"12,5"`); negatives mark specials/loose volumes. */ private fun JsonObject.chapterNumber(): Double = (this["number"]?.jsonPrimitive?.contentOrNull?.replace(',', '.')?.toDoubleOrNull() ?: 0.0).coerceAtLeast(0.0) override suspend fun push(key: String, progress: Int) { send( "${server()}/api/Tachiyomi/mark-chapter-until-as-read?seriesId=$key&chapterNumber=$progress", method = "POST", body = "{}", ).requireSuccess(name) } }