package eu.friedcutlet.yokan.services.metadata import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.util.decodeHtmlEntities import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonObject /** * Cross-catalog recommendations backed by AniList's `Media.recommendations` * graph. Mangayomi sourced this screen from anibrain.ai, but that service shut * down ("AniBrain - Farewell"), so the feature keeps its shape — discover * titles beyond the local library, ranked by similarity — on AniList's data * instead. Results are matched back against the local library so in-library * entries stay clickable. */ class RecommendationService( private val http: HttpService, private val database: YokanDatabase, ) { private val endpoint = "https://graphql.anilist.co" private val json = Json { ignoreUnknownKeys = true; isLenient = true } suspend fun recommendations(title: String, itemType: DbItemType): List { if (title.isBlank()) return emptyList() val primary = fetch(title, itemType) if (primary != null && primary.isNotEmpty()) return primary // Decorated titles ("Main Title ~subtitle~ (TL)") often miss AniList's // fuzzy search; retry once with the decorations stripped. val simplified = simplifyTitle(title) if (simplified != title && simplified.isNotBlank()) { fetch(simplified, itemType)?.let { return it } } return primary ?: emptyList() } private fun simplifyTitle(title: String): String = title .substringBefore('~') .substringBefore('(') .substringBefore('[') .substringBefore(':') .trim() /** Returns null when AniList cannot resolve the title (data.Media == null / HTTP 404). */ private suspend fun fetch(title: String, itemType: DbItemType): List? { val body = buildJsonObject { put( "query", """ query (${'$'}search: String, ${'$'}type: MediaType) { Media(search: ${'$'}search, type: ${'$'}type) { recommendations(sort: RATING_DESC, perPage: 25) { nodes { rating mediaRecommendation { title { romaji english native } description coverImage { large } genres } } } } } """.trimIndent(), ) putJsonObject("variables") { put("search", title) put("type", if (itemType == DbItemType.Anime) "ANIME" else "MANGA") } }.toString() val response = http.request( HttpRequest( url = endpoint, method = "POST", headers = mapOf("Content-Type" to "application/json", "Accept" to "application/json"), body = body, ), ) val root = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull() ?: if (response.statusCode in 200..299) { return emptyList() } else { error("AniList request failed with HTTP ${response.statusCode}") } val media = root.obj("data")?.obj("Media") if (media == null) { // "Not Found." responses carry data.Media == null alongside HTTP 404. if (root.containsKey("data") || response.statusCode == 404) return null error("AniList request failed with HTTP ${response.statusCode}") } val nodes = media.obj("recommendations")?.get("nodes") as? JsonArray ?: return emptyList() val libraryTitles = database.mangas(itemType) val maxRating = nodes.maxOfOrNull { node -> (node as? JsonObject)?.get("rating")?.let { (it as? JsonPrimitive)?.intOrNull } ?: 0 }?.coerceAtLeast(1) ?: 1 return nodes.mapNotNull { node -> val entry = node as? JsonObject ?: return@mapNotNull null val media = entry.obj("mediaRecommendation") ?: return@mapNotNull null val titles = media.obj("title") val english = titles?.string("english") val romaji = titles?.string("romaji") val native = titles?.string("native") val display = english ?: romaji ?: native ?: return@mapNotNull null val genres = (media["genres"] as? JsonArray) ?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull } .orEmpty() val rating = entry["rating"]?.let { (it as? JsonPrimitive)?.intOrNull } ?: 0 val localMatch = libraryTitles.firstOrNull { candidate -> val name = candidate.name.orEmpty() name.equals(display, ignoreCase = true) || (romaji != null && name.equals(romaji, ignoreCase = true)) || (native != null && name.equals(native, ignoreCase = true)) } RecommendationResult( title = display, score = ((rating * 100) / maxRating).coerceIn(0, 100), reason = genres.take(4).joinToString(", ").ifBlank { "AniList recommendation" }, itemType = itemType, mangaId = localMatch?.id, coverUrl = media.obj("coverImage")?.string("large"), description = media.string("description")?.stripAnilistHtml(), genres = genres, ) } } /** AniList descriptions embed light HTML (`
`, ``, entities). */ private fun String.stripAnilistHtml(): String = decodeHtmlEntities( replace(Regex("", RegexOption.IGNORE_CASE), "\n").replace(Regex("<[^>]+>"), ""), ) .replace(Regex("\n{3,}"), "\n\n") .trim() private fun JsonObject.obj(key: String): JsonObject? = get(key) as? JsonObject private fun JsonObject.string(key: String): String? = (get(key) as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() } } data class RecommendationResult( val title: String, val score: Int, val reason: String, val itemType: DbItemType, val mangaId: Long? = null, val coverUrl: String? = null, val description: String? = null, val genres: List = emptyList(), )