package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.runJoined import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.serialization.json.* data class LibraryAiringRefreshResult(val updated: Int = 0, val unavailable: Int = 0, val failed: Int = 0) /** Explicit, public-ID-only refresh. Profile retirement and caller cancellation both join its work. */ class LibraryAiringService( private val database: YokanDatabase, private val http: HttpService, private val scope: CoroutineScope, private val clock: () -> Long = ::nowMillis, private val requestIntervalMillis: Long = 2100, private val requestTimeoutMillis: Long = 20_000, ) { private val gate = Mutex() private var lastRequestAt: Long? = null suspend fun refresh(): LibraryAiringRefreshResult = scope.runJoined { gate.withLock { refreshLocked() } } private suspend fun refreshLocked(): LibraryAiringRefreshResult { val snapshot = database.snapshot() val tracks = snapshot.tracks.groupBy { it.mangaId } val metadata = snapshot.settings.titleMetadata.orEmpty().associateBy { it.mangaId } val anime = snapshot.mangas.filter { it.favorite && it.itemType == DbItemType.Anime } val candidates = anime.mapNotNull { title -> binding(tracks[title.id].orEmpty(), metadata[title.id])?.let { Candidate(title, it) } } var result = LibraryAiringRefreshResult(unavailable = anime.size - candidates.size) val batches = candidates.groupBy { it.binding.provider }.values.flatMap { group -> // Several source entries can refer to one public anime ID; fetch that ID once. group.groupBy { it.binding.id }.values.chunked(50).map { it.flatten() } } for ((batchIndex, batch) in batches.withIndex()) { currentCoroutineContext().ensureActive() val rows = try { val elapsed = lastRequestAt?.let { (clock() - it).coerceAtLeast(0) } ?: requestIntervalMillis if (elapsed < requestIntervalMillis) delay(requestIntervalMillis - elapsed) lastRequestAt = clock() fetch(batch.first().binding.provider, batch.map { it.binding.id }.distinct()) } catch (cancel: CancellationException) { throw cancel } catch (_: Exception) { // Stop on HTTP/rate-limit/protocol failure; keep every previously saved schedule. return result.copy(failed = batches.drop(batchIndex).sumOf { it.size }) } currentCoroutineContext().ensureActive() database.batch { val current = database.snapshot() val titles = current.mangas.associateBy { it.id } val currentTracks = current.tracks.groupBy { it.mangaId } val currentMetadata = current.settings.titleMetadata.orEmpty().associateBy { it.mangaId } batch.forEach { candidate -> val title = titles[candidate.title.id] val schedule = rows[candidate.binding.id] if (title == null || !title.favorite || title.itemType != DbItemType.Anime || title.sourceId != candidate.title.sourceId || title.link != candidate.title.link || binding(currentTracks[title.id].orEmpty(), currentMetadata[title.id]) != candidate.binding ) return@forEach if (schedule == null) { result = result.copy(unavailable = result.unavailable + 1); return@forEach } database.upsertManga(title.copy(nextEpisodeAiringAt = schedule.at, nextEpisodeNumber = schedule.episode, airingScheduleUpdatedAt = clock())) result = if (schedule.at > 0) result.copy(updated = result.updated + 1) else result.copy(unavailable = result.unavailable + 1) } } database.awaitPersistence() } return result } private suspend fun fetch(provider: Provider, ids: List): Map { val field = if (provider == Provider.AniList) "id_in" else "idMal_in" val query = "query(\$ids:[Int]) { Page(page:1,perPage:50) { media(type:ANIME,$field:\$ids) { id idMal type nextAiringEpisode { airingAt episode } } } }" val body = buildJsonObject { put("query", query) putJsonObject("variables") { putJsonArray("ids") { ids.forEach { add(it) } } } }.toString() val parts = mutableListOf() var bytes = 0 val response = withTimeoutOrNull(requestTimeoutMillis) { http.stream(HttpRequest("https://graphql.anilist.co", method = "POST", headers = mapOf("Content-Type" to "application/json", "Accept" to "application/json"), body = body)) { chunk -> require(chunk.size <= MaximumResponseBytes - bytes) { "Airing response too large" } bytes += chunk.size parts += chunk.copyOf() } } ?: error("Airing request timed out") check(response.statusCode in 200..299) { "Airing request failed" } val payload = ByteArray(bytes) var offset = 0 parts.forEach { it.copyInto(payload, offset); offset += it.size } val root = DatabaseJson.parseToJsonElement(payload.decodeToString()).jsonObject check((root["errors"] as? JsonArray).isNullOrEmpty()) { "Airing provider rejected the query" } val data = (root["data"] as? JsonObject)?.get("Page") as? JsonObject ?: error("Invalid airing response") val media = data["media"] as? JsonArray ?: error("Invalid airing response") require(media.size <= 50) val now = clock() val result = mutableMapOf() media.forEach { value -> val row = value as? JsonObject ?: error("Invalid airing entry") check((row["type"] as? JsonPrimitive)?.content == "ANIME") { "Unexpected airing media type" } val id = (row[if (provider == Provider.AniList) "id" else "idMal"] as? JsonPrimitive)?.intOrNull ?: error("Invalid airing identity") if (id !in ids) return@forEach check(id !in result) { "Duplicate airing identity" } val next = row["nextAiringEpisode"] result[id] = when (next) { JsonNull -> Schedule(0, null) is JsonObject -> { val seconds = (next["airingAt"] as? JsonPrimitive)?.longOrNull ?: error("Invalid airing time") val episode = (next["episode"] as? JsonPrimitive)?.intOrNull ?: error("Invalid airing episode") require(seconds in 1..Int.MAX_VALUE.toLong() && episode > 0) val at = seconds * 1000 if (at > now) Schedule(at, episode) else Schedule(0, null) } else -> error("Missing airing schedule") } } return result } private fun binding(tracks: List, metadata: DbTitleMetadata?): Binding? { tracks.firstOrNull { it.syncId == 2 && it.itemType == DbItemType.Anime && validId(it.mediaId) != null }?.let { return Binding(Provider.AniList, requireNotNull(validId(it.mediaId))) } tracks.firstOrNull { it.syncId == 1 && it.itemType == DbItemType.Anime && validId(it.mediaId) != null }?.let { return Binding(Provider.MyAnimeList, requireNotNull(validId(it.mediaId))) } val id = validId(metadata?.metadataServerId?.toLongOrNull()) ?: return null return when (metadata?.metadataSource?.lowercase()?.replace("-", "")?.replace("_", "")?.replace(" ", "")) { "anilist" -> Binding(Provider.AniList, id) "myanimelist", "mal" -> Binding(Provider.MyAnimeList, id) else -> null } } private fun validId(id: Long?): Int? = id?.takeIf { it in 1..Int.MAX_VALUE.toLong() }?.toInt() private enum class Provider { AniList, MyAnimeList } private data class Binding(val provider: Provider, val id: Int) private data class Candidate(val title: DbManga, val binding: Binding) private data class Schedule(val at: Long, val episode: Int?) private companion object { const val MaximumResponseBytes = 256 * 1024 } }