Yokan / rebuild
Course 1 8624561

RecommendationService.kt

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

implementation160 lines
1package eu.friedcutlet.yokan.services.metadata23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.YokanDatabase5import eu.friedcutlet.yokan.services.http.HttpRequest6import eu.friedcutlet.yokan.services.http.HttpService7import eu.friedcutlet.yokan.util.decodeHtmlEntities8import kotlinx.serialization.json.Json9import kotlinx.serialization.json.JsonArray10import kotlinx.serialization.json.JsonObject11import kotlinx.serialization.json.JsonPrimitive12import kotlinx.serialization.json.buildJsonObject13import kotlinx.serialization.json.contentOrNull14import kotlinx.serialization.json.intOrNull15import kotlinx.serialization.json.jsonObject16import kotlinx.serialization.json.put17import kotlinx.serialization.json.putJsonObject1819/**20 * Cross-catalog recommendations backed by AniList's `Media.recommendations`21 * graph. Mangayomi sourced this screen from anibrain.ai, but that service shut22 * down ("AniBrain - Farewell"), so the feature keeps its shape — discover23 * titles beyond the local library, ranked by similarity — on AniList's data24 * instead. Results are matched back against the local library so in-library25 * entries stay clickable.26 */27class RecommendationService(28    private val http: HttpService,29    private val database: YokanDatabase,30) {31    private val endpoint = "https://graphql.anilist.co"32    private val json = Json { ignoreUnknownKeys = true; isLenient = true }3334    suspend fun recommendations(title: String, itemType: DbItemType): List<RecommendationResult> {35        if (title.isBlank()) return emptyList()36        val primary = fetch(title, itemType)37        if (primary != null && primary.isNotEmpty()) return primary38        // Decorated titles ("Main Title ~subtitle~ (TL)") often miss AniList's39        // fuzzy search; retry once with the decorations stripped.40        val simplified = simplifyTitle(title)41        if (simplified != title && simplified.isNotBlank()) {42            fetch(simplified, itemType)?.let { return it }43        }44        return primary ?: emptyList()45    }4647    private fun simplifyTitle(title: String): String = title48        .substringBefore('~')49        .substringBefore('(')50        .substringBefore('[')51        .substringBefore(':')52        .trim()5354    /** Returns null when AniList cannot resolve the title (data.Media == null / HTTP 404). */55    private suspend fun fetch(title: String, itemType: DbItemType): List<RecommendationResult>? {56        val body = buildJsonObject {57            put(58                "query",59                """60                query (${'$'}search: String, ${'$'}type: MediaType) {61                  Media(search: ${'$'}search, type: ${'$'}type) {62                    recommendations(sort: RATING_DESC, perPage: 25) {63                      nodes {64                        rating65                        mediaRecommendation {66                          title { romaji english native }67                          description68                          coverImage { large }69                          genres70                        }71                      }72                    }73                  }74                }75                """.trimIndent(),76            )77            putJsonObject("variables") {78                put("search", title)79                put("type", if (itemType == DbItemType.Anime) "ANIME" else "MANGA")80            }81        }.toString()82        val response = http.request(83            HttpRequest(84                url = endpoint,85                method = "POST",86                headers = mapOf("Content-Type" to "application/json", "Accept" to "application/json"),87                body = body,88            ),89        )90        val root = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()91            ?: if (response.statusCode in 200..299) {92                return emptyList()93            } else {94                error("AniList request failed with HTTP ${response.statusCode}")95            }96        val media = root.obj("data")?.obj("Media")97        if (media == null) {98            // "Not Found." responses carry data.Media == null alongside HTTP 404.99            if (root.containsKey("data") || response.statusCode == 404) return null100            error("AniList request failed with HTTP ${response.statusCode}")101        }102        val nodes = media.obj("recommendations")?.get("nodes") as? JsonArray ?: return emptyList()103        val libraryTitles = database.mangas(itemType)104        val maxRating = nodes.maxOfOrNull { node ->105            (node as? JsonObject)?.get("rating")?.let { (it as? JsonPrimitive)?.intOrNull } ?: 0106        }?.coerceAtLeast(1) ?: 1107        return nodes.mapNotNull { node ->108            val entry = node as? JsonObject ?: return@mapNotNull null109            val media = entry.obj("mediaRecommendation") ?: return@mapNotNull null110            val titles = media.obj("title")111            val english = titles?.string("english")112            val romaji = titles?.string("romaji")113            val native = titles?.string("native")114            val display = english ?: romaji ?: native ?: return@mapNotNull null115            val genres = (media["genres"] as? JsonArray)116                ?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }117                .orEmpty()118            val rating = entry["rating"]?.let { (it as? JsonPrimitive)?.intOrNull } ?: 0119            val localMatch = libraryTitles.firstOrNull { candidate ->120                val name = candidate.name.orEmpty()121                name.equals(display, ignoreCase = true) ||122                    (romaji != null && name.equals(romaji, ignoreCase = true)) ||123                    (native != null && name.equals(native, ignoreCase = true))124            }125            RecommendationResult(126                title = display,127                score = ((rating * 100) / maxRating).coerceIn(0, 100),128                reason = genres.take(4).joinToString(", ").ifBlank { "AniList recommendation" },129                itemType = itemType,130                mangaId = localMatch?.id,131                coverUrl = media.obj("coverImage")?.string("large"),132                description = media.string("description")?.stripAnilistHtml(),133                genres = genres,134            )135        }136    }137138    /** AniList descriptions embed light HTML (`<br>`, `<i>`, entities). */139    private fun String.stripAnilistHtml(): String = decodeHtmlEntities(140        replace(Regex("<br\\s*/?>", RegexOption.IGNORE_CASE), "\n").replace(Regex("<[^>]+>"), ""),141    )142        .replace(Regex("\n{3,}"), "\n\n")143        .trim()144145    private fun JsonObject.obj(key: String): JsonObject? = get(key) as? JsonObject146147    private fun JsonObject.string(key: String): String? =148        (get(key) as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() }149}150151data class RecommendationResult(152    val title: String,153    val score: Int,154    val reason: String,155    val itemType: DbItemType,156    val mangaId: Long? = null,157    val coverUrl: String? = null,158    val description: String? = null,159    val genres: List<String> = emptyList(),160)161

Search chapters, reference and source filenames.