Yokan / rebuild
Course 1 8624561

KomgaTrackerService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/KomgaTrackerService.kt

implementation102 lines
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 kotlinx.serialization.json.JsonObject9import kotlinx.serialization.json.buildJsonObject10import kotlinx.serialization.json.contentOrNull11import kotlinx.serialization.json.doubleOrNull12import kotlinx.serialization.json.intOrNull13import kotlinx.serialization.json.jsonObject14import kotlinx.serialization.json.jsonPrimitive15import kotlinx.serialization.json.put1617/**18 * Komga (Animetail `KomgaApi`). Item keys are `series/<id>` or `readlists/<id>`; progress is the series'19 * last continuously read book `numberSort` (read lists: book index), via the `read-progress/tachiyomi` API.20 */21class KomgaTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) :22    ServerTrackerService(syncId, database, http) {23    override val name: String = "Komga"24    override val sourceKeywords = listOf("komga")25    override val forManga = true2627    override val loginFields = listOf(28        TrackerLoginField.ServerUrl,29        TrackerLoginField.Username,30        TrackerLoginField.Password,31        TrackerLoginField.ApiKey,32    )3334    /** An API key (`X-API-Key`) when entered, else HTTP Basic with username and password. */35    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {36        val server = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl))37        val apiKey = values.optional(TrackerLoginField.ApiKey)38        val credentials = if (apiKey != null) {39            TrackerCredentials(serverUrl = server, apiKey = apiKey)40        } else {41            TrackerCredentials(42                serverUrl = server,43                apiKey = basicAuth(values.required(TrackerLoginField.Username), values.required(TrackerLoginField.Password)),44            )45        }46        val oauth = apiKey ?: BASIC47        val probe = loginPreference(null, oauth, credentials)48        val me = http.request(HttpRequest("$server/api/v2/users/me", headers = authHeaders(probe))).json(name).jsonObject49        return probe.copy(username = me["email"]?.jsonPrimitive?.contentOrNull)50    }5152    override fun authHeaders(preference: DbTrackPreference): Map<String, String> {53        val secret = preference.credentials().apiKey.orEmpty()54        return if (preference.oauth == BASIC) mapOf("Authorization" to secret) else mapOf("X-API-Key" to secret)55    }5657    override fun itemKey(link: String): String? =58        segmentAfter(link, "readlists")?.let { "readlists/$it" }59            ?: segmentAfter(link, "series")?.let { "series/$it" }60            ?: link.trim().takeIf { id -> id.isNotEmpty() && id.all { it.isLetterOrDigit() } }?.let { "series/$it" }6162    override suspend fun fetch(key: String): DbTrackSearch {63        val url = "${server()}/api/v1/$key"64        val item = getJson(url).jsonObject65        val readList = key.startsWith("readlists/")66        val progress = getJson(progressUrl(key)).jsonObject67        val booksCount = progress.int("booksCount")68        val metadata = item["metadata"] as? JsonObject69        return DbTrackSearch(70            syncId = syncId,71            title = (if (readList) item["name"] else metadata?.get("title"))?.jsonPrimitive?.contentOrNull,72            trackingUrl = url,73            coverUrl = "$url/thumbnail",74            summary = metadata?.get("summary")?.jsonPrimitive?.contentOrNull.orEmpty(),75            publishingStatus = metadata?.get("status")?.jsonPrimitive?.contentOrNull.orEmpty(),76            totalChapter = if (readList) booksCount else progress.double("maxNumberSort").toInt(),77            lastChapterRead = (if (readList) progress.double("lastReadContinuousIndex") else progress.double("lastReadContinuousNumberSort")).toInt(),78            status = remoteStatus(79                unread = booksCount == progress.int("booksUnreadCount"),80                completed = booksCount == progress.int("booksReadCount"),81            ),82        )83    }8485    override suspend fun push(key: String, progress: Int) {86        val body = buildJsonObject {87            if (key.startsWith("readlists/")) put("lastBookRead", progress) else put("lastBookNumberSortRead", progress.toDouble())88        }89        send(progressUrl(key), "PUT", body.toString()).requireSuccess(name)90    }9192    /** Series read progress lives on the v2 API, read lists stay on v1. */93    private fun progressUrl(key: String): String =94        "${server()}/api/${if (key.startsWith("series/")) "v2" else "v1"}/$key/read-progress/tachiyomi"9596    private fun JsonObject.int(field: String): Int = this[field]?.jsonPrimitive?.intOrNull ?: 097    private fun JsonObject.double(field: String): Double = this[field]?.jsonPrimitive?.doubleOrNull ?: 0.09899    private companion object {100        const val BASIC = "basic"101    }102}103

Search chapters, reference and source filenames.