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.JsonObject 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.jsonPrimitive import kotlinx.serialization.json.put /** * Komga (Animetail `KomgaApi`). Item keys are `series/` or `readlists/`; progress is the series' * last continuously read book `numberSort` (read lists: book index), via the `read-progress/tachiyomi` API. */ class KomgaTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) : ServerTrackerService(syncId, database, http) { override val name: String = "Komga" override val sourceKeywords = listOf("komga") override val forManga = true override val loginFields = listOf( TrackerLoginField.ServerUrl, TrackerLoginField.Username, TrackerLoginField.Password, TrackerLoginField.ApiKey, ) /** An API key (`X-API-Key`) when entered, else HTTP Basic with username and password. */ override suspend fun login(values: Map): DbTrackPreference { val server = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl)) val apiKey = values.optional(TrackerLoginField.ApiKey) val credentials = if (apiKey != null) { TrackerCredentials(serverUrl = server, apiKey = apiKey) } else { TrackerCredentials( serverUrl = server, apiKey = basicAuth(values.required(TrackerLoginField.Username), values.required(TrackerLoginField.Password)), ) } val oauth = apiKey ?: BASIC val probe = loginPreference(null, oauth, credentials) val me = http.request(HttpRequest("$server/api/v2/users/me", headers = authHeaders(probe))).json(name).jsonObject return probe.copy(username = me["email"]?.jsonPrimitive?.contentOrNull) } override fun authHeaders(preference: DbTrackPreference): Map { val secret = preference.credentials().apiKey.orEmpty() return if (preference.oauth == BASIC) mapOf("Authorization" to secret) else mapOf("X-API-Key" to secret) } override fun itemKey(link: String): String? = segmentAfter(link, "readlists")?.let { "readlists/$it" } ?: segmentAfter(link, "series")?.let { "series/$it" } ?: link.trim().takeIf { id -> id.isNotEmpty() && id.all { it.isLetterOrDigit() } }?.let { "series/$it" } override suspend fun fetch(key: String): DbTrackSearch { val url = "${server()}/api/v1/$key" val item = getJson(url).jsonObject val readList = key.startsWith("readlists/") val progress = getJson(progressUrl(key)).jsonObject val booksCount = progress.int("booksCount") val metadata = item["metadata"] as? JsonObject return DbTrackSearch( syncId = syncId, title = (if (readList) item["name"] else metadata?.get("title"))?.jsonPrimitive?.contentOrNull, trackingUrl = url, coverUrl = "$url/thumbnail", summary = metadata?.get("summary")?.jsonPrimitive?.contentOrNull.orEmpty(), publishingStatus = metadata?.get("status")?.jsonPrimitive?.contentOrNull.orEmpty(), totalChapter = if (readList) booksCount else progress.double("maxNumberSort").toInt(), lastChapterRead = (if (readList) progress.double("lastReadContinuousIndex") else progress.double("lastReadContinuousNumberSort")).toInt(), status = remoteStatus( unread = booksCount == progress.int("booksUnreadCount"), completed = booksCount == progress.int("booksReadCount"), ), ) } override suspend fun push(key: String, progress: Int) { val body = buildJsonObject { if (key.startsWith("readlists/")) put("lastBookRead", progress) else put("lastBookNumberSortRead", progress.toDouble()) } send(progressUrl(key), "PUT", body.toString()).requireSuccess(name) } /** Series read progress lives on the v2 API, read lists stay on v1. */ private fun progressUrl(key: String): String = "${server()}/api/${if (key.startsWith("series/")) "v2" else "v1"}/$key/read-progress/tachiyomi" private fun JsonObject.int(field: String): Int = this[field]?.jsonPrimitive?.intOrNull ?: 0 private fun JsonObject.double(field: String): Double = this[field]?.jsonPrimitive?.doubleOrNull ?: 0.0 private companion object { const val BASIC = "basic" } }