KavitaTrackerService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/KavitaTrackerService.kt
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 io.ktor.http.encodeURLParameter9import kotlinx.serialization.json.JsonArray10import kotlinx.serialization.json.JsonObject11import kotlinx.serialization.json.contentOrNull12import kotlinx.serialization.json.intOrNull13import kotlinx.serialization.json.jsonObject14import kotlinx.serialization.json.jsonPrimitive1516/**17 * Kavita (Animetail `KavitaApi`). The API key is exchanged for a JWT via the plugin endpoint and renewed the18 * same way on a 401. Item keys are numeric series ids; progress is the latest read chapter number.19 */20class KavitaTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) :21 ServerTrackerService(syncId, database, http) {22 override val name: String = "Kavita"23 override val sourceKeywords = listOf("kavita")24 override val forManga = true2526 override val loginFields = listOf(TrackerLoginField.ServerUrl, TrackerLoginField.ApiKey)2728 override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {29 // A pasted `…/api` or OPDS URL still names the server.30 val typed = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl))31 val server = typed.substringBefore("://") + "://" + "${typed.substringAfter("://")}/".substringBefore("/api/").trimEnd('/')32 val apiKey = values.required(TrackerLoginField.ApiKey)33 val user = authenticate(server, apiKey)34 return loginPreference(35 username = user["username"]?.jsonPrimitive?.contentOrNull,36 oauth = user.token(),37 credentials = TrackerCredentials(serverUrl = server, apiKey = apiKey),38 )39 }4041 private suspend fun authenticate(server: String, apiKey: String): JsonObject =42 http.request(43 HttpRequest(44 "$server/api/Plugin/authenticate?apiKey=${apiKey.encodeURLParameter()}&pluginName=Yokan",45 method = "POST",46 body = "{}",47 ),48 ).json(name).jsonObject4950 override suspend fun reauthenticate(preference: DbTrackPreference): DbTrackPreference {51 val credentials = preference.credentials()52 val token = authenticate(credentials.serverUrl.orEmpty(), credentials.apiKey.orEmpty()).token()53 return database.upsertTrackPreference(preference.copy(oauth = token))54 }5556 private fun JsonObject.token(): String =57 this["token"]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }58 ?: throw IllegalStateException("Kavita did not return a session token")5960 override fun authHeaders(preference: DbTrackPreference): Map<String, String> =61 mapOf("Authorization" to "Bearer ${preference.oauth}")6263 override fun itemKey(link: String): String? =64 (segmentAfter(link, "series") ?: linkParameter(link, "seriesId") ?: link.trim())65 .takeIf { id -> id.isNotEmpty() && id.all { it.isDigit() } }6667 override suspend fun fetch(key: String): DbTrackSearch {68 val api = "${server()}/api"69 val url = "$api/Series/$key"70 val series = getJson(url).jsonObject71 val pages = series["pages"]?.jsonPrimitive?.intOrNull ?: 072 val pagesRead = series["pagesRead"]?.jsonPrimitive?.intOrNull ?: 073 val volumes = getJson("$api/Series/volumes?seriesId=$key") as? JsonArray ?: JsonArray(emptyList())74 val latest = send("$api/Tachiyomi/latest-chapter?seriesId=$key").requireSuccess(name)75 val lastRead = if (latest.statusCode == 204 || latest.body.isBlank()) 0.076 else trackerJson.parseToJsonElement(latest.body).jsonObject.chapterNumber()77 return DbTrackSearch(78 syncId = syncId,79 mediaId = key.toLong(),80 title = series["name"]?.jsonPrimitive?.contentOrNull,81 trackingUrl = url,82 totalChapter = totalChapters(volumes),83 lastChapterRead = lastRead.toInt(),84 status = remoteStatus(unread = pagesRead == 0, completed = pagesRead == pages),85 )86 }8788 /** Upstream rule: the highest chapter number, or the count of chapterless (single-file) volumes if larger. */89 private fun totalChapters(volumes: JsonArray): Int {90 var volumeCount = 091 var maxChapter = 092 for (volume in volumes) {93 val chapters = (volume.jsonObject["chapters"] as? JsonArray).orEmpty()94 if (chapters.isEmpty()) continue95 val highest = chapters.maxOf { it.jsonObject.chapterNumber() }96 if (highest == 0.0) volumeCount++ else if (highest > maxChapter) maxChapter = highest.toInt()97 }98 return maxOf(maxChapter, volumeCount)99 }100101 /** Kavita chapter `number` is a string (`"12"`, `"12,5"`); negatives mark specials/loose volumes. */102 private fun JsonObject.chapterNumber(): Double =103 (this["number"]?.jsonPrimitive?.contentOrNull?.replace(',', '.')?.toDoubleOrNull() ?: 0.0).coerceAtLeast(0.0)104105 override suspend fun push(key: String, progress: Int) {106 send(107 "${server()}/api/Tachiyomi/mark-chapter-until-as-read?seriesId=$key&chapterNumber=$progress",108 method = "POST",109 body = "{}",110 ).requireSuccess(name)111 }112}113