SuwayomiTrackerService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/SuwayomiTrackerService.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 kotlinx.serialization.json.JsonObject9import kotlinx.serialization.json.contentOrNull10import kotlinx.serialization.json.doubleOrNull11import kotlinx.serialization.json.intOrNull12import kotlinx.serialization.json.jsonArray13import kotlinx.serialization.json.jsonObject14import kotlinx.serialization.json.jsonPrimitive15import kotlinx.serialization.json.longOrNull16import kotlin.math.abs1718/**19 * Suwayomi-Server (Animetail `SuwayomiApi`, REST `/api/v1`; deprecated upstream in favour of GraphQL but still20 * served). Optional HTTP Basic auth. Item keys are numeric manga ids; progress is the last read chapter number.21 */22class SuwayomiTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) :23 ServerTrackerService(syncId, database, http) {24 override val name: String = "Suwayomi"25 override val sourceKeywords = listOf("suwayomi", "tachidesk")26 override val forManga = true2728 override val loginFields = listOf(TrackerLoginField.ServerUrl, TrackerLoginField.Username, TrackerLoginField.Password)2930 override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {31 val server = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl))32 val username = values.optional(TrackerLoginField.Username)33 val basic = username?.let { basicAuth(it, values.required(TrackerLoginField.Password)) }34 val preference = loginPreference(username, basic?.let { BASIC } ?: ANONYMOUS, TrackerCredentials(serverUrl = server, apiKey = basic))35 val about = http.request(HttpRequest("$server/api/v1/settings/about", headers = authHeaders(preference))).json(name).jsonObject36 return preference.copy(accountName = about["name"]?.jsonPrimitive?.contentOrNull)37 }3839 override fun authHeaders(preference: DbTrackPreference): Map<String, String> =40 preference.credentials().apiKey?.takeIf { preference.oauth == BASIC }?.let { mapOf("Authorization" to it) }.orEmpty()4142 override fun itemKey(link: String): String? =43 (segmentAfter(link, "manga") ?: link.trim()).takeIf { id -> id.isNotEmpty() && id.all { it.isDigit() } }4445 override suspend fun fetch(key: String): DbTrackSearch {46 val url = "${server()}/api/v1/manga/$key"47 val manga = getJson("$url/full").jsonObject48 val chapterCount = manga.long("chapterCount")49 val unread = manga.long("unreadCount")50 return DbTrackSearch(51 syncId = syncId,52 mediaId = key.toLong(),53 title = manga["title"]?.jsonPrimitive?.contentOrNull,54 trackingUrl = url,55 coverUrl = "$url/thumbnail",56 summary = manga["description"]?.jsonPrimitive?.contentOrNull.orEmpty(),57 publishingStatus = manga["status"]?.jsonPrimitive?.contentOrNull.orEmpty(),58 totalChapter = chapterCount.toInt(),59 lastChapterRead = ((manga["lastChapterRead"] as? JsonObject)?.chapterNumber() ?: 0.0).toInt(),60 status = remoteStatus(unread = unread == chapterCount, completed = unread == 0L),61 )62 }6364 /** Marks the chapter numbered [progress] and every earlier one read (`markPrevRead`). */65 override suspend fun push(key: String, progress: Int) {66 if (progress <= 0) return67 val url = "${server()}/api/v1/manga/$key"68 val chapter = getJson("$url/chapters").jsonArray69 .map { it.jsonObject }70 .firstOrNull { abs(it.chapterNumber() - progress) <= 0.001 }71 ?: throw IllegalArgumentException("Suwayomi has no chapter $progress")72 val index = chapter["index"]?.jsonPrimitive?.intOrNull ?: throw IllegalStateException("Suwayomi chapter has no index")73 send(74 "$url/chapter/$index",75 method = "PUT",76 body = formBody("markPrevRead" to "true", "read" to "true"),77 headers = mapOf("Content-Type" to "application/x-www-form-urlencoded"),78 ).requireSuccess(name)79 }8081 private fun JsonObject.chapterNumber(): Double = this["chapterNumber"]?.jsonPrimitive?.doubleOrNull ?: 0.082 private fun JsonObject.long(field: String): Long = this[field]?.jsonPrimitive?.longOrNull ?: 0L8384 private companion object {85 const val BASIC = "basic"86 const val ANONYMOUS = "anonymous"87 }88}89