BangumiTrackerService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/BangumiTrackerService.kt
1package eu.friedcutlet.yokan.services.tracking23import eu.friedcutlet.yokan.database.DbTrack4import eu.friedcutlet.yokan.database.DbTrackPreference5import eu.friedcutlet.yokan.database.DbTrackSearch6import eu.friedcutlet.yokan.database.DbTrackStatus7import eu.friedcutlet.yokan.database.YokanDatabase8import eu.friedcutlet.yokan.services.http.HttpResponse9import eu.friedcutlet.yokan.services.http.HttpService10import io.ktor.http.encodeURLParameter11import io.ktor.http.encodeURLPathPart12import kotlinx.serialization.json.JsonArray13import kotlinx.serialization.json.JsonObject14import kotlinx.serialization.json.JsonPrimitive15import kotlinx.serialization.json.add16import kotlinx.serialization.json.buildJsonObject17import kotlinx.serialization.json.contentOrNull18import kotlinx.serialization.json.doubleOrNull19import kotlinx.serialization.json.intOrNull20import kotlinx.serialization.json.longOrNull21import kotlinx.serialization.json.put22import kotlinx.serialization.json.putJsonArray23import kotlinx.serialization.json.putJsonObject2425/**26 * Bangumi v0 API (https://bangumi.github.io/api/). Signs in with a personal access token, or with the27 * user's own OAuth application (bgm.tv's token endpoint sends no CORS headers, so the web build needs the token).28 */29class BangumiTrackerService(30 override val syncId: Int,31 private val database: YokanDatabase,32 private val http: HttpService,33) : TrackerService {34 override val name: String = "Bangumi"3536 private val oauth = TrackerOAuthClient(37 tracker = name,38 syncId = syncId,39 tokenUrl = "https://bgm.tv/oauth/access_token",40 database = database,41 http = http,42 refreshFields = listOf("redirect_uri" to TrackerOAuth.redirectUri(syncId)),43 )4445 override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true4647 override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =48 database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }4950 // Bangumi has no re-reading collection type.51 override fun statusList(isManga: Boolean): List<DbTrackStatus> =52 DbTrack(status = DbTrackStatus.Reading).readableStatusList(isManga)53 .filter { it != DbTrackStatus.ReReading && it != DbTrackStatus.ReWatching }5455 override fun scoreValue(): Pair<Int, Int> = 0 to 105657 override fun displayScore(score: Int): String = if (score == 0) "-" else "$score/10"5859 override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> = emptyList()6061 override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> = emptyList()6263 override val loginFields: List<TrackerLoginField> = listOf(64 TrackerLoginField.ApiKey,65 TrackerLoginField.ClientId,66 TrackerLoginField.ClientSecret,67 TrackerLoginField.AuthorizationCode,68 )6970 /** OAuth page for an entered client id; otherwise the personal access token page. */71 override suspend fun authorizeUrl(values: Map<TrackerLoginField, String>): String {72 val clientId = values.optional(TrackerLoginField.ClientId) ?: return TokenPage73 return "https://bgm.tv/oauth/authorize?client_id=${clientId.encodeURLParameter()}&response_type=code" +74 "&redirect_uri=${TrackerOAuth.redirectUri(syncId).encodeURLParameter()}"75 }7677 override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {78 val apiKey = values.optional(TrackerLoginField.ApiKey)79 val token: String80 val credentials: TrackerCredentials81 if (apiKey != null) {82 token = apiKey83 credentials = TrackerCredentials()84 } else {85 val clientId = values.required(TrackerLoginField.ClientId)86 val clientSecret = values.required(TrackerLoginField.ClientSecret)87 val response = oauth.tokenRequest(88 "grant_type" to "authorization_code",89 "client_id" to clientId,90 "client_secret" to clientSecret,91 "code" to callbackParameter(values.required(TrackerLoginField.AuthorizationCode), "code"),92 "redirect_uri" to TrackerOAuth.redirectUri(syncId),93 )94 token = response.str("access_token") ?: throw TrackerHttpException(name, 401, "No access token")95 credentials = TrackerCredentials(96 clientId = clientId,97 clientSecret = clientSecret,98 refreshToken = response.str("refresh_token"),99 expiresAt = response.oauthExpiresAt(),100 userId = response.str("user_id"),101 )102 }103 val me = oauth.send("GET", "$ApiUrl/v0/me", token).json(name) as JsonObject104 // `username` is the stringified user id until the user sets one; collection URLs accept both.105 val username = me.str("username") ?: me.str("id")106 return DbTrackPreference(107 syncId = syncId.toLong(),108 username = username,109 accountName = me.str("nickname")?.takeIf { it.isNotBlank() } ?: username,110 accountAvatarUrl = (me["avatar"] as? JsonObject)?.str("large"),111 oauth = token,112 prefs = credentials.copy(userId = me.str("id") ?: credentials.userId).encode(),113 refreshing = false,114 )115 }116117 override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {118 trackerSearchId(query)?.let { id ->119 val response = oauth.api("GET", "$ApiUrl/v0/subjects/${id.encodeURLPathPart()}")120 if (response.statusCode == 404) return emptyList()121 return listOfNotNull((response.json(name) as? JsonObject)?.toSearch(isManga))122 }123 if (query.isBlank()) return emptyList()124 val body = buildJsonObject {125 put("keyword", query.trim())126 put("sort", "match")127 putJsonObject("filter") { putJsonArray("type") { add(if (isManga) 1 else 2) } }128 }.toString()129 val result = oauth.api("POST", "$ApiUrl/v0/search/subjects?limit=20", body).json(name) as? JsonObject130 return (result?.get("data") as? JsonArray).orEmpty().mapNotNull { (it as? JsonObject)?.toSearch(isManga) }131 }132133 override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack {134 collection(track)?.let { return track.withCollection(it, isManga) }135 write("POST", track)136 return track137 }138139 override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack =140 collection(track)?.let { track.withCollection(it, isManga) } ?: track141142 /** PATCH needs an existing collection (404 otherwise), so a missing one is created with POST. */143 override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack {144 val adjusted = track.autoStatus(isManga)145 val response = write("PATCH", adjusted, requireSuccess = false)146 if (response.statusCode == 404) write("POST", adjusted) else response.requireSuccess(name)147 return adjusted148 }149150 // ponytail: the v0 API has no collection delete endpoint; unbinding only removes the local track.151 override suspend fun unbind(track: DbTrack, isManga: Boolean) {}152153 private suspend fun collection(track: DbTrack): JsonObject? {154 val username = database.trackPreference(syncId)?.username?.takeIf { it.isNotBlank() }155 ?: throw IllegalStateException("Not logged in to $name")156 val response = oauth.api("GET", "$ApiUrl/v0/users/${username.encodeURLPathPart()}/collections/${mediaId(track)}")157 if (response.statusCode == 404) return null158 return response.json(name) as? JsonObject159 }160161 // Upstream sends chapter progress as `ep_status` for books too.162 private suspend fun write(method: String, track: DbTrack, requireSuccess: Boolean = true): HttpResponse {163 val body = buildJsonObject {164 put("type", track.status.toBangumi())165 put("rate", (track.score ?: 0).coerceIn(0, 10))166 put("ep_status", track.lastChapterRead ?: 0)167 }.toString()168 val response = oauth.api(method, "$ApiUrl/v0/users/-/collections/${mediaId(track)}", body)169 return if (requireSuccess) response.requireSuccess(name) else response170 }171172 private fun mediaId(track: DbTrack): Long = track.mediaId ?: error("Bangumi track has no media id")173174 private fun DbTrack.withCollection(collection: JsonObject, isManga: Boolean): DbTrack = copy(175 status = collection.int("type")?.let { fromBangumi(it, isManga) } ?: status,176 score = collection.int("rate") ?: score,177 lastChapterRead = collection.int("ep_status") ?: lastChapterRead,178 totalChapter = (collection["subject"] as? JsonObject)?.int("eps")?.takeIf { it > 0 } ?: totalChapter,179 trackingUrl = trackingUrl ?: mediaId?.let { "$WebUrl/subject/$it" },180 )181182 private fun JsonObject.toSearch(isManga: Boolean): DbTrackSearch? {183 val id = (this["id"] as? JsonPrimitive)?.longOrNull ?: return null184 val name = str("name").orEmpty()185 val nameCn = str("name_cn").orEmpty()186 val summary = str("summary")?.trim().orEmpty()187 return DbTrackSearch(188 syncId = syncId,189 mediaId = id,190 title = nameCn.ifBlank { name },191 trackingUrl = "$WebUrl/subject/$id",192 totalChapter = int("eps")?.takeIf { it > 0 },193 coverUrl = (this["images"] as? JsonObject)?.str("common").orEmpty(),194 summary = if (nameCn.isNotBlank() && name.isNotBlank()) "$name\n$summary".trim() else summary,195 publishingStatus = "",196 publishingType = str("platform").orEmpty(),197 startDate = str("date").orEmpty(),198 score = ((this["rating"] as? JsonObject)?.get("score") as? JsonPrimitive)?.doubleOrNull,199 status = "",200 )201 }202203 private companion object {204 const val ApiUrl = "https://api.bgm.tv"205 const val WebUrl = "https://bgm.tv"206 const val TokenPage = "https://next.bgm.tv/demo/access-token"207208 fun DbTrackStatus.toBangumi(): Int = when (this) {209 DbTrackStatus.PlanToRead, DbTrackStatus.PlanToWatch -> 1210 DbTrackStatus.Completed -> 2211 DbTrackStatus.Reading, DbTrackStatus.Watching, DbTrackStatus.ReReading, DbTrackStatus.ReWatching -> 3212 DbTrackStatus.OnHold -> 4213 DbTrackStatus.Dropped -> 5214 }215216 fun fromBangumi(type: Int, isManga: Boolean): DbTrackStatus? = when (type) {217 1 -> if (isManga) DbTrackStatus.PlanToRead else DbTrackStatus.PlanToWatch218 2 -> DbTrackStatus.Completed219 3 -> if (isManga) DbTrackStatus.Reading else DbTrackStatus.Watching220 4 -> DbTrackStatus.OnHold221 5 -> DbTrackStatus.Dropped222 else -> null223 }224 }225}226227private fun DbTrack.autoStatus(isManga: Boolean): DbTrack {228 val progress = lastChapterRead ?: 0229 val total = totalChapter ?: 0230 return when {231 status == DbTrackStatus.Completed -> this232 total > 0 && progress >= total -> copy(status = DbTrackStatus.Completed)233 progress > 0 && (status == DbTrackStatus.PlanToRead || status == DbTrackStatus.PlanToWatch) ->234 copy(status = if (isManga) DbTrackStatus.Reading else DbTrackStatus.Watching)235 else -> this236 }237}238239private fun JsonObject.str(key: String): String? = (this[key] as? JsonPrimitive)?.contentOrNull240241private fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull242