LibraryAiringService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LibraryAiringService.kt
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.database.*4import eu.friedcutlet.yokan.services.http.HttpRequest5import eu.friedcutlet.yokan.services.http.HttpService6import eu.friedcutlet.yokan.services.runJoined7import eu.friedcutlet.yokan.util.nowMillis8import kotlinx.coroutines.*9import kotlinx.coroutines.sync.Mutex10import kotlinx.coroutines.sync.withLock11import kotlinx.serialization.json.*1213data class LibraryAiringRefreshResult(val updated: Int = 0, val unavailable: Int = 0, val failed: Int = 0)1415/** Explicit, public-ID-only refresh. Profile retirement and caller cancellation both join its work. */16class LibraryAiringService(17 private val database: YokanDatabase,18 private val http: HttpService,19 private val scope: CoroutineScope,20 private val clock: () -> Long = ::nowMillis,21 private val requestIntervalMillis: Long = 2100,22 private val requestTimeoutMillis: Long = 20_000,23) {24 private val gate = Mutex()25 private var lastRequestAt: Long? = null2627 suspend fun refresh(): LibraryAiringRefreshResult = scope.runJoined { gate.withLock { refreshLocked() } }2829 private suspend fun refreshLocked(): LibraryAiringRefreshResult {30 val snapshot = database.snapshot()31 val tracks = snapshot.tracks.groupBy { it.mangaId }32 val metadata = snapshot.settings.titleMetadata.orEmpty().associateBy { it.mangaId }33 val anime = snapshot.mangas.filter { it.favorite && it.itemType == DbItemType.Anime }34 val candidates = anime.mapNotNull { title ->35 binding(tracks[title.id].orEmpty(), metadata[title.id])?.let { Candidate(title, it) }36 }37 var result = LibraryAiringRefreshResult(unavailable = anime.size - candidates.size)38 val batches = candidates.groupBy { it.binding.provider }.values.flatMap { group ->39 // Several source entries can refer to one public anime ID; fetch that ID once.40 group.groupBy { it.binding.id }.values.chunked(50).map { it.flatten() }41 }42 for ((batchIndex, batch) in batches.withIndex()) {43 currentCoroutineContext().ensureActive()44 val rows = try {45 val elapsed = lastRequestAt?.let { (clock() - it).coerceAtLeast(0) } ?: requestIntervalMillis46 if (elapsed < requestIntervalMillis) delay(requestIntervalMillis - elapsed)47 lastRequestAt = clock()48 fetch(batch.first().binding.provider, batch.map { it.binding.id }.distinct())49 } catch (cancel: CancellationException) { throw cancel }50 catch (_: Exception) {51 // Stop on HTTP/rate-limit/protocol failure; keep every previously saved schedule.52 return result.copy(failed = batches.drop(batchIndex).sumOf { it.size })53 }54 currentCoroutineContext().ensureActive()55 database.batch {56 val current = database.snapshot()57 val titles = current.mangas.associateBy { it.id }58 val currentTracks = current.tracks.groupBy { it.mangaId }59 val currentMetadata = current.settings.titleMetadata.orEmpty().associateBy { it.mangaId }60 batch.forEach { candidate ->61 val title = titles[candidate.title.id]62 val schedule = rows[candidate.binding.id]63 if (title == null || !title.favorite || title.itemType != DbItemType.Anime ||64 title.sourceId != candidate.title.sourceId || title.link != candidate.title.link ||65 binding(currentTracks[title.id].orEmpty(), currentMetadata[title.id]) != candidate.binding66 ) return@forEach67 if (schedule == null) { result = result.copy(unavailable = result.unavailable + 1); return@forEach }68 database.upsertManga(title.copy(nextEpisodeAiringAt = schedule.at, nextEpisodeNumber = schedule.episode,69 airingScheduleUpdatedAt = clock()))70 result = if (schedule.at > 0) result.copy(updated = result.updated + 1)71 else result.copy(unavailable = result.unavailable + 1)72 }73 }74 database.awaitPersistence()75 }76 return result77 }7879 private suspend fun fetch(provider: Provider, ids: List<Int>): Map<Int, Schedule> {80 val field = if (provider == Provider.AniList) "id_in" else "idMal_in"81 val query = "query(\$ids:[Int]) { Page(page:1,perPage:50) { media(type:ANIME,$field:\$ids) { id idMal type nextAiringEpisode { airingAt episode } } } }"82 val body = buildJsonObject {83 put("query", query)84 putJsonObject("variables") { putJsonArray("ids") { ids.forEach { add(it) } } }85 }.toString()86 val parts = mutableListOf<ByteArray>()87 var bytes = 088 val response = withTimeoutOrNull(requestTimeoutMillis) {89 http.stream(HttpRequest("https://graphql.anilist.co", method = "POST",90 headers = mapOf("Content-Type" to "application/json", "Accept" to "application/json"), body = body)) { chunk ->91 require(chunk.size <= MaximumResponseBytes - bytes) { "Airing response too large" }92 bytes += chunk.size93 parts += chunk.copyOf()94 }95 } ?: error("Airing request timed out")96 check(response.statusCode in 200..299) { "Airing request failed" }97 val payload = ByteArray(bytes)98 var offset = 099 parts.forEach { it.copyInto(payload, offset); offset += it.size }100 val root = DatabaseJson.parseToJsonElement(payload.decodeToString()).jsonObject101 check((root["errors"] as? JsonArray).isNullOrEmpty()) { "Airing provider rejected the query" }102 val data = (root["data"] as? JsonObject)?.get("Page") as? JsonObject ?: error("Invalid airing response")103 val media = data["media"] as? JsonArray ?: error("Invalid airing response")104 require(media.size <= 50)105 val now = clock()106 val result = mutableMapOf<Int, Schedule>()107 media.forEach { value ->108 val row = value as? JsonObject ?: error("Invalid airing entry")109 check((row["type"] as? JsonPrimitive)?.content == "ANIME") { "Unexpected airing media type" }110 val id = (row[if (provider == Provider.AniList) "id" else "idMal"] as? JsonPrimitive)?.intOrNull111 ?: error("Invalid airing identity")112 if (id !in ids) return@forEach113 check(id !in result) { "Duplicate airing identity" }114 val next = row["nextAiringEpisode"]115 result[id] = when (next) {116 JsonNull -> Schedule(0, null)117 is JsonObject -> {118 val seconds = (next["airingAt"] as? JsonPrimitive)?.longOrNull ?: error("Invalid airing time")119 val episode = (next["episode"] as? JsonPrimitive)?.intOrNull ?: error("Invalid airing episode")120 require(seconds in 1..Int.MAX_VALUE.toLong() && episode > 0)121 val at = seconds * 1000122 if (at > now) Schedule(at, episode) else Schedule(0, null)123 }124 else -> error("Missing airing schedule")125 }126 }127 return result128 }129130 private fun binding(tracks: List<DbTrack>, metadata: DbTitleMetadata?): Binding? {131 tracks.firstOrNull { it.syncId == 2 && it.itemType == DbItemType.Anime && validId(it.mediaId) != null }?.let { return Binding(Provider.AniList, requireNotNull(validId(it.mediaId))) }132 tracks.firstOrNull { it.syncId == 1 && it.itemType == DbItemType.Anime && validId(it.mediaId) != null }?.let { return Binding(Provider.MyAnimeList, requireNotNull(validId(it.mediaId))) }133 val id = validId(metadata?.metadataServerId?.toLongOrNull()) ?: return null134 return when (metadata?.metadataSource?.lowercase()?.replace("-", "")?.replace("_", "")?.replace(" ", "")) {135 "anilist" -> Binding(Provider.AniList, id)136 "myanimelist", "mal" -> Binding(Provider.MyAnimeList, id)137 else -> null138 }139 }140141 private fun validId(id: Long?): Int? = id?.takeIf { it in 1..Int.MAX_VALUE.toLong() }?.toInt()142 private enum class Provider { AniList, MyAnimeList }143 private data class Binding(val provider: Provider, val id: Int)144 private data class Candidate(val title: DbManga, val binding: Binding)145 private data class Schedule(val at: Long, val episode: Int?)146 private companion object { const val MaximumResponseBytes = 256 * 1024 }147}148