Yokan / rebuild
Course 1 8624561

WatchOrderService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/WatchOrderService.kt

implementation505 lines
1package eu.friedcutlet.yokan.services.metadata23import eu.friedcutlet.yokan.services.catchingNonCancellation4import eu.friedcutlet.yokan.services.http.HttpRequest5import eu.friedcutlet.yokan.services.http.HttpService6import io.ktor.http.encodeURLParameter7import kotlinx.serialization.json.Json8import kotlinx.serialization.json.JsonArray9import kotlinx.serialization.json.JsonObject10import kotlinx.serialization.json.JsonPrimitive11import kotlinx.serialization.json.buildJsonObject12import kotlinx.serialization.json.contentOrNull13import kotlinx.serialization.json.intOrNull14import kotlinx.serialization.json.jsonObject15import kotlinx.serialization.json.put16import kotlinx.serialization.json.putJsonObject1718/**19 * AniList franchise relations and watch-order service, mirroring Mangayomi's20 * rebuilt `lib/services/fetch_watch_order.dart` (`2b8a99f3`, `912b5337`).21 *22 * Traverses the AniList relation graph (prequel/sequel/parent chain + side stories,23 * anime-only, up to 20 lookups), orders entries chronologically by air date, and24 * labels them relative to the queried anchor (Previous, Currently watching, Up next).25 * The tracker-based sequel locator flow (`sequels`) remains backed by chiaki.site.26 */27class WatchOrderService(28    private val http: HttpService,29) {30    private val json = Json { ignoreUnknownKeys = true; isLenient = true }3132    /**33     * Searches AniList for anime to build a watch order from.34     */35    suspend fun search(name: String): List<WatchOrderSearchResult> = searchAniList(name)3637    /**38     * Resolves an anime title to its AniList franchise and builds its chronological watch order39     * directly with no manual pick step. The resolved title becomes the "Current" anchor.40     */41    suspend fun watchOrderByName(name: String): List<WatchOrderEntry> {42        if (name.isBlank()) return emptyList()43        val hits = searchAniList(name)44        val rootId = hits.firstOrNull()?.id ?: return emptyList()45        return watchOrder(rootId)46    }4748    /**49     * Searches AniList for anime using the lightweight search GraphQL selection.50     */51    suspend fun searchAniList(name: String): List<WatchOrderSearchResult> {52        if (name.isBlank()) return emptyList()53        val query = """54            query (${'$'}search: String) {55              Page(page: 1, perPage: 15) {56                media(type: ANIME, sort: [SEARCH_MATCH], search: ${'$'}search) {57                  id58                  idMal59                  title { romaji english native }60                  coverImage { large color }61                  format62                  episodes63                  seasonYear64                  startDate { year month }65                }66              }67            }68        """.trimIndent()69        val body = buildJsonObject {70            put("query", query)71            putJsonObject("variables") {72                put("search", name)73            }74        }.toString()75        val response = http.request(76            HttpRequest(77                url = ANILIST_ENDPOINT,78                method = "POST",79                headers = anilistHeaders,80                body = body,81            ),82        )83        if (response.statusCode !in 200..299) return emptyList()84        val root = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()85            ?: return emptyList()86        val mediaArray = root["data"]?.jsonObject?.get("Page")?.jsonObject?.get("media") as? JsonArray87            ?: return emptyList()88        return mediaArray.mapNotNull { element ->89            val media = element as? JsonObject ?: return@mapNotNull null90            val id = (media["id"] as? JsonPrimitive)?.intOrNull ?: return@mapNotNull null91            val titleObj = media["title"] as? JsonObject92            val title = titleObj?.primitive("english")93                ?: titleObj?.primitive("romaji")94                ?: titleObj?.primitive("native")95                ?: return@mapNotNull null96            val coverImage = (media["coverImage"] as? JsonObject)?.primitive("large").orEmpty()97            val format = media.primitive("format").orEmpty()98            val seasonYear = (media["seasonYear"] as? JsonPrimitive)?.intOrNull99                ?: ((media["startDate"] as? JsonObject)?.get("year") as? JsonPrimitive)?.intOrNull100            WatchOrderSearchResult(101                id = id.toString(),102                name = title,103                imageUrl = coverImage,104                type = format,105                year = seasonYear,106            )107        }108    }109110    /**111     * Legacy chiaki.site autocomplete series search retained for backwards compatibility.112     */113    suspend fun searchChiaki(name: String): List<WatchOrderSearchResult> {114        if (name.isBlank()) return emptyList()115        val response = http.request(116            HttpRequest(117                url = "https://chiaki.site/?/tools/autocomplete_series&term=${name.encodeURLParameter()}",118                headers = chiakiHeaders,119            ),120        )121        if (response.statusCode !in 200..299) return emptyList()122        val entries = runCatching { json.parseToJsonElement(response.body) }.getOrNull() as? JsonArray123            ?: return emptyList()124        return entries.mapNotNull { element ->125            val entry = element as? JsonObject ?: return@mapNotNull null126            WatchOrderSearchResult(127                id = entry.primitive("id") ?: return@mapNotNull null,128                name = entry.primitive("value") ?: return@mapNotNull null,129                imageUrl = entry.primitive("image")?.let { "https://chiaki.site/$it" }.orEmpty(),130                type = entry.primitive("type").orEmpty(),131                year = (entry["year"] as? JsonPrimitive)?.intOrNull,132            )133        }134    }135136    /**137     * Builds a watch order from an AniList media ID by walking its franchise relation graph.138     * Capped at 20 lookups; strictly anime-only; ordered chronologically by release date.139     */140    suspend fun watchOrder(seriesId: String): List<WatchOrderEntry> {141        if (seriesId.isBlank()) return emptyList()142        val rootId = seriesId.toIntOrNull()143        if (rootId == null) {144            val response = http.request(145                HttpRequest(146                    url = "https://chiaki.site/?/tools/watch_order/id/$seriesId",147                    headers = chiakiHeaders,148                ),149            )150            if (response.statusCode !in 200..299) return emptyList()151            return parseWatchOrderRows(response.body)152        }153154        val chain = setOf("PREQUEL", "SEQUEL", "PARENT")155        val extra = setOf("SIDE_STORY", "SPIN_OFF", "ALTERNATIVE", "SUMMARY", "COMPILATION")156        val collected = mutableMapOf<Int, AniListMedia>()157        val queue = ArrayDeque<Int>()158        val visited = mutableSetOf<Int>()159        var queries = 0160161        queue.add(rootId)162        while (queue.isNotEmpty() && queries < 20) {163            val current = queue.removeFirst()164            if (!visited.add(current)) continue165            queries++166            val (self, relations) = fetchMediaWithRelations(current)167            if (self != null && self.isAnime) {168                collected[self.id] = self169            }170            for (r in relations) {171                if (!r.media.isAnime) continue172                if (r.relationType in chain) {173                    collected[r.media.id] = r.media174                    if (r.media.id !in visited) queue.add(r.media.id)175                } else if (r.relationType in extra) {176                    collected[r.media.id] = r.media177                }178            }179        }180181        if (collected.isEmpty()) {182            val response = catchingNonCancellation {183                http.request(184                    HttpRequest(185                        url = "https://chiaki.site/?/tools/watch_order/id/$seriesId",186                        headers = chiakiHeaders,187                    ),188                )189            }.getOrNull()190            if (response != null && response.statusCode in 200..299) {191                val legacyRows = parseWatchOrderRows(response.body)192                if (legacyRows.isNotEmpty()) return legacyRows193            }194            return emptyList()195        }196197        val sorted = collected.values.sortedWith(198            compareBy<AniListMedia> { it.startSortKey }.thenBy { it.id },199        )200        val currentIndex = sorted.indexOfFirst { it.id == rootId }201202        return sorted.mapIndexed { index, m ->203            val role = when {204                currentIndex < 0 -> WatchOrderRole.Next205                index < currentIndex -> WatchOrderRole.Previous206                index == currentIndex -> WatchOrderRole.Current207                else -> WatchOrderRole.Next208            }209            val meta = listOfNotNull(210                m.format,211                m.episodes?.let { "$it eps" },212                m.startYear?.toString(),213            ).joinToString(" | ")214            WatchOrderEntry(215                id = m.id.toString(),216                anilistId = m.id.toString(),217                title = m.romaji ?: m.title,218                titleEnglish = m.english,219                info = meta,220                imageUrl = m.coverImage.orEmpty(),221                role = role,222            )223        }224    }225226    private suspend fun fetchMediaWithRelations(mediaId: Int): Pair<AniListMedia?, List<AniListRelation>> {227        val query = """228            query (${'$'}id: Int) {229              Media(id: ${'$'}id) {230                id231                idMal232                title { romaji english native }233                coverImage { large color }234                format235                status236                type237                episodes238                seasonYear239                startDate { year month }240                relations {241                  edges {242                    relationType243                    node {244                      id245                      idMal246                      title { romaji english native }247                      coverImage { large color }248                      format249                      status250                      type251                      episodes252                      seasonYear253                      startDate { year month }254                    }255                  }256                }257              }258            }259        """.trimIndent()260        val body = buildJsonObject {261            put("query", query)262            putJsonObject("variables") {263                put("id", mediaId)264            }265        }.toString()266        val response = http.request(267            HttpRequest(268                url = ANILIST_ENDPOINT,269                method = "POST",270                headers = anilistHeaders,271                body = body,272            ),273        )274        if (response.statusCode !in 200..299) return null to emptyList()275        val root = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()276            ?: return null to emptyList()277        val mediaObj = root["data"]?.jsonObject?.get("Media") as? JsonObject ?: return null to emptyList()278        val self = parseAniListMedia(mediaObj)279        val edges = (mediaObj["relations"] as? JsonObject)?.get("edges") as? JsonArray280        val relations = edges.orEmpty().mapNotNull { edgeElem ->281            val edge = edgeElem as? JsonObject ?: return@mapNotNull null282            val relType = edge.primitive("relationType") ?: return@mapNotNull null283            val nodeObj = edge["node"] as? JsonObject ?: return@mapNotNull null284            val nodeMedia = parseAniListMedia(nodeObj) ?: return@mapNotNull null285            AniListRelation(relationType = relType, media = nodeMedia)286        }287        return self to relations288    }289290    private fun parseAniListMedia(obj: JsonObject): AniListMedia? {291        val id = (obj["id"] as? JsonPrimitive)?.intOrNull ?: return null292        val titleObj = obj["title"] as? JsonObject293        val coverObj = obj["coverImage"] as? JsonObject294        val dateObj = obj["startDate"] as? JsonObject295        return AniListMedia(296            id = id,297            idMal = (obj["idMal"] as? JsonPrimitive)?.intOrNull,298            romaji = titleObj?.primitive("romaji"),299            english = titleObj?.primitive("english"),300            native = titleObj?.primitive("native"),301            coverImage = coverObj?.primitive("large"),302            format = obj.primitive("format"),303            status = obj.primitive("status"),304            type = obj.primitive("type") ?: "ANIME",305            episodes = (obj["episodes"] as? JsonPrimitive)?.intOrNull,306            startYear = (dateObj?.get("year") as? JsonPrimitive)?.intOrNull307                ?: (obj["seasonYear"] as? JsonPrimitive)?.intOrNull,308            startMonth = (dateObj?.get("month") as? JsonPrimitive)?.intOrNull,309        )310    }311312    suspend fun sequels(malUsername: String?, anilistUsername: String?): List<SequelEntry> {313        val user = malUsername?.takeIf(String::isNotBlank)314            ?: anilistUsername?.takeIf(String::isNotBlank)315            ?: return emptyList()316        val source = if (malUsername?.isNotBlank() == true) "mal" else "anilist"317        val response = http.request(318            HttpRequest(319                url = "https://chiaki.site/?/tools/sequel_locator_fetch",320                method = "POST",321                headers = chiakiHeaders + ("Content-Type" to "application/x-www-form-urlencoded"),322                body = "user=${user.encodeURLParameter()}&list_source=$source$SEQUEL_FILTERS",323            ),324        )325        if (response.statusCode !in 200..299) return emptyList()326        val root = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()327            ?: return emptyList()328        // Live chiaki wraps the list: {"data":{"result":[…],"entry_count":N}}.329        // Mangayomi's parser predates that and expected a bare array — accept both.330        val data = when (val payload = root["data"]) {331            is JsonArray -> payload332            is JsonObject -> payload["result"] as? JsonArray ?: return emptyList()333            else -> return emptyList()334        }335        return data.mapNotNull { element ->336            val entry = element as? JsonObject ?: return@mapNotNull null337            SequelEntry(338                id = entry.primitive("id") ?: return@mapNotNull null,339                anilistId = entry.primitive("anilist_id"),340                title = entry.primitive("title") ?: return@mapNotNull null,341                imageUrl = entry.primitive("image_url")?.let { "https://chiaki.site/$it" }.orEmpty(),342                episodes = entry.primitive("episodes").orEmpty(),343                period = entry.primitive("period").orEmpty(),344                score = entry.primitive("score")?.formatChiakiScore().orEmpty(),345                type = entry.primitive("type").orEmpty(),346                reasons = (entry["reason"] as? JsonArray).orEmpty().mapNotNull { reason ->347                    val obj = reason as? JsonObject ?: return@mapNotNull null348                    SequelReasonRef(349                        id = obj.primitive("id") ?: return@mapNotNull null,350                        title = obj.primitive("title").orEmpty(),351                        imageUrl = obj.primitive("image_url")?.let { "https://chiaki.site/$it" }.orEmpty(),352                    )353                },354            )355        }356    }357358    private fun JsonObject.primitive(key: String): String? =359        (get(key) as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() }360361    /** chiaki scores arrive as hundredths ("811" == 8.11); older payloads were already formatted. */362    private fun String.formatChiakiScore(): String {363        val hundredths = toIntOrNull() ?: return this364        return "${hundredths / 100}.${(hundredths % 100).toString().padStart(2, '0')}"365    }366367    private fun JsonArray?.orEmpty(): List<kotlinx.serialization.json.JsonElement> = this ?: emptyList()368369    private companion object {370        const val ANILIST_ENDPOINT = "https://graphql.anilist.co"371372        val anilistHeaders = mapOf(373            "Content-Type" to "application/json",374            "Accept" to "application/json",375            "User-Agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",376        )377378        val chiakiHeaders = mapOf(379            "priority" to "u=1, i",380            "Referer" to "https://chiaki.site/?/tools/watch_order",381            "User-Agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",382        )383384        /** Fixed filter payload copied from Mangayomi's `_sequelData`. */385        const val SEQUEL_FILTERS =386            "&types%5B%5D=1&types%5B%5D=3&types%5B%5D=2&types%5B%5D=4&types%5B%5D=9&score=0&date_from=false&date_to=false" +387                "&include_ptw=1&exclude_h=1&exclude_planned=1&exclude_dropped=0&exclude_not_aired=0&exclude_short=1&exclude_short_value=3"388    }389}390391data class AniListMedia(392    val id: Int,393    val idMal: Int? = null,394    val romaji: String? = null,395    val english: String? = null,396    val native: String? = null,397    val coverImage: String? = null,398    val format: String? = null,399    val status: String? = null,400    val type: String? = null,401    val episodes: Int? = null,402    val startYear: Int? = null,403    val startMonth: Int? = null,404) {405    val title: String get() = english ?: romaji ?: native ?: "Unknown"406    val isAnime: Boolean get() = type == null || type.equals("ANIME", ignoreCase = true)407    val startSortKey: Int get() = if (startYear == null) (1 shl 30) else (startYear * 12 + (startMonth ?: 0))408}409410data class AniListRelation(411    val relationType: String,412    val media: AniListMedia,413)414415/** Where an entry sits relative to the title opened by the user. */416enum class WatchOrderRole {417    Previous,418    Current,419    Next,420}421422/**423 * Parses chiaki's rendered watch-order table without a DOM: one `<tr>` per424 * entry carrying `data-id`/`data-anilist-id`, a `wo_title` span, an optional425 * plain `uk-text-small` English title, a muted info span, and a CSS426 * `background-image:url('…')` avatar.427 */428internal fun parseWatchOrderRows(html: String): List<WatchOrderEntry> {429    val rowRegex = Regex(430        "(?s)<tr[^>]*data-id=\"(?<id>\\d+)\"[^>]*>(?<body>.*?)</tr>",431    )432    val anilistRegex = Regex("data-anilist-id=\"(?<v>\\d+)\"")433    val titleRegex = Regex("class=\"[^\"]*wo_title[^\"]*\"[^>]*>(?<v>[^<]+)<")434    val mutedRegex = Regex("class=\"[^\"]*uk-text-muted[^\"]*\"[^>]*>(?<v>[^<]+)<")435    val metaRegex = Regex(436        "(?s)class=\"[^\"]*wo_meta[^\"]*\"[^>]*>(?<v>.*?)(?:<div class=\"list_status|</td>)",437    )438    val englishRegex = Regex("class=\"uk-text-small\"[^>]*>(?<v>[^<]+)<")439    val imageRegex = Regex("url\\('(?<v>[^']+)'\\)")440    return rowRegex.findAll(html).mapNotNull { row ->441        val body = row.groups["body"]?.value ?: return@mapNotNull null442        val title = titleRegex.find(body)?.groups?.get("v")?.value?.trim()443            ?.takeIf(String::isNotBlank) ?: return@mapNotNull null444        WatchOrderEntry(445            id = row.groups["id"]?.value ?: return@mapNotNull null,446            anilistId = anilistRegex.find(row.value)?.groups?.get("v")?.value,447            title = title,448            titleEnglish = englishRegex.find(body)?.groups?.get("v")?.value?.trim()449                ?.takeIf(String::isNotBlank),450            info = metaRegex.find(body)?.groups?.get("v")?.value?.cleanWatchOrderMeta()451                ?: mutedRegex.find(body)?.groups?.get("v")?.value?.trim().orEmpty(),452            imageUrl = imageRegex.find(body)?.groups?.get("v")?.value453                ?.let { "https://chiaki.site/$it" }.orEmpty(),454        )455    }.toList()456}457458/** Flattens chiaki's `wo_meta` markup into a single "date | type | eps | ★score" line. */459private fun String.cleanWatchOrderMeta(): String = this460    .replace(Regex("(?s)<a\\b.*?</a>"), "")461    .replace(Regex("<[^>]+>"), " ")462    .replace(Regex("\\s+"), " ")463    .trim()464    .trim('|')465    .trim()466467/** chiaki.site `autocomplete_series` hit or AniList search hit. */468data class WatchOrderSearchResult(469    val id: String,470    val name: String,471    val imageUrl: String,472    val type: String,473    val year: Int?,474)475476/** One row of a watch-order table. */477data class WatchOrderEntry(478    val id: String,479    val anilistId: String?,480    val title: String,481    val titleEnglish: String?,482    val info: String,483    val imageUrl: String,484    val role: WatchOrderRole = WatchOrderRole.Next,485)486487/** Series that caused a sequel-locator hit. */488data class SequelReasonRef(489    val id: String,490    val title: String,491    val imageUrl: String,492)493494/** chiaki.site `sequel_locator_fetch` result. */495data class SequelEntry(496    val id: String,497    val anilistId: String?,498    val title: String,499    val imageUrl: String,500    val episodes: String,501    val period: String,502    val score: String,503    val type: String,504    val reasons: List<SequelReasonRef>,505)506

Search chapters, reference and source filenames.