package eu.friedcutlet.yokan.domain /** * Chapter / episode number recognition and missing chapter gap detection. * * Direct port and enhancement of Mangayomi's `lib/utils/chapter_recognition.dart` * (incorporating commits f1170d47, 4af383cb, and 96f1830a). * * Capabilities: * - Preserves decimal chapter precision (e.g. 12.5). * - Distinguishes unnumbered chapters (null, e.g. "Special", "Prologue") from genuine chapter 0.0. * - Detects missing chapter gaps (e.g. chapters 1, 2, 4, 5 present -> chapter 3 missing). * - Multi-season anime bucket sorting when numbering resets across seasons. */ object ChapterRecognition { fun rawSeasonAndNumber(mangaTitle: String, chapter: Chapter): Pair { val inferred = rawSeasonAndNumber(mangaTitle, chapter.numberingName?.takeIf(String::isNotBlank) ?: chapter.name) return (chapter.season?.takeIf { it >= 0 } ?: inferred.first) to (chapter.number?.takeIf { it.isFinite() && it >= 0 } ?: inferred.second) } fun parseEpisodeNumber(mangaTitle: String, chapter: Chapter): Double = rawSeasonAndNumber(mangaTitle, chapter).second ?: 0.0 private val unwanted = Regex( "\\b(?:v|ver|vol|version|volume|season|staffel|saison|temporada|s)[^a-z]?[0-9]+", ) private val unwantedWhiteSpace = Regex("\\s(?=extra|special|omake)") private val seasonKeyword = Regex( "\\b(?:staffel|season|saison|temporada|s)\\s*([0-9]+)", ) private val episodeKeyword = Regex( "\\b(?:folge|episode|ep\\.?)\\s*([0-9]+(?:\\.[0-9]+)?)", ) fun parseSeasonNumber(name: String): Int? = seasonKeyword.find(name.lowercase())?.groupValues?.get(1)?.toIntOrNull() // Lookbehind for "ch." followed by zero or more spaces. private val chNotation = Regex( "(?<=ch\\.) *([0-9]+)(\\.[0-9]+)?(\\.?[a-z]+)?", ) private val bareNumber = Regex("([0-9]+)(\\.[0-9]+)?(\\.?[a-z]+)?") /** * Sort key for the UI list. Encodes season into the result so * multi-season anime sorts correctly: `season * 100_000 + episode`. */ fun parseChapterNumber(mangaTitle: String, chapterName: String): Double { val (season, ep) = rawSeasonAndNumber(mangaTitle, chapterName) return withSeason(season, ep ?: 0.0) } /** * Episode number within a season — used for tracker updates * (MAL / AniList / Kitsu) and AniSkip lookups. The tracker entry is * already season-specific, so the season prefix is stripped. */ fun parseEpisodeNumber(mangaTitle: String, chapterName: String): Double { val (_, ep) = rawSeasonAndNumber(mangaTitle, chapterName) return ep ?: 0.0 } /** * The key that answers "are these two the same chapter / episode". * * Season is part of the answer. Without it, episode 1 of season 2 is the * same chapter as episode 1 of season 1, and whichever arrives second is * dropped before it reaches the library. A show with two seasons then * displays one of them. * * Null when the name carries no number at all, because "Special" and * "Prologue" are not all the same chapter either. Callers skip the * composite check in that case rather than folding them together. * * [scanlator] is omitted by callers deciding whether read state carries * over, since the same episode from a different group is still that episode. */ fun chapterIdentityKey( mangaTitle: String?, chapterName: String?, scanlator: String? = null, ): String? { val title = mangaTitle.orEmpty() val name = chapterName?.takeIf { it.isNotBlank() } ?: return null val (season, ep) = rawSeasonAndNumber(title, name) if (ep == null || ep <= 0.0) return null return "$season::$ep::${scanlator.orEmpty()}" } /** * Raw (season, episode) pair, unbucketed — season is 0 if none matched. * Episode keeps its fractional part (e.g. 12.5). * Episode is null when the name has no detectable number at all (e.g. "Special", "Prologue") — * distinct from a genuine chapter 0.0. */ fun rawSeasonAndNumber(mangaTitle: String, chapterName: String): Pair { val name = chapterName .lowercase() .replace(mangaTitle.lowercase(), "") .trim() .replace(',', '.') .replace('-', '.') .replace(unwantedWhiteSpace, "") val season = seasonKeyword.find(name)?.groupValues?.getOrNull(1)?.toIntOrNull() ?: 0 episodeKeyword.find(name)?.let { match -> val ep = match.groupValues.getOrNull(1)?.toDoubleOrNull() return season to ep } // Strip season / volume noise, then look for ch.X or a bare number. val stripped = name.replace(unwanted, "") val ep = extractNumber(stripped) return season to ep } /** * Sort/identity keys for chapters. Buckets by season only if numbering actually * repeats across seasons (collisions >= 3). * Returns a map of Chapter ID to sort key. A null key indicates an unnumbered chapter. */ fun chapterSortKeys(mangaTitle: String, chapters: List): Map { val raw = chapters.associate { it.id to rawSeasonAndNumber(mangaTitle, it) } val episodeToSeasons = mutableMapOf>() for (pair in raw.values) { val ep = pair.second ?: continue episodeToSeasons.getOrPut(ep) { mutableSetOf() }.add(pair.first) } val collisions = episodeToSeasons.values.count { it.size > 1 } val resets = collisions >= 3 return raw.mapValues { (_, pair) -> val ep = pair.second ?: return@mapValues null if (resets && pair.first > 0) { pair.first * 100_000.0 + ep } else { ep } } } /** * Count of whole numbers missing from the recognized chapter sequence. * E.g. chapters 1, 2, 4, 5 present means 1 (chapter 3) is missing. * Decimal extras (12.5) are floored into their whole chapter. */ fun missingChapterCount(mangaTitle: String, chapters: List): Int { val numbers = mutableSetOf() for (chapter in chapters) { val (_, ep) = rawSeasonAndNumber(mangaTitle, chapter) if (ep != null) { numbers.add(ep.toInt()) } } if (numbers.size < 2) return 0 val lowest = numbers.minOrNull() ?: return 0 val highest = numbers.maxOrNull() ?: return 0 val expectedCount = highest - lowest + 1 return maxOf(0, expectedCount - numbers.size) } /** * Number of chapters whose name has no detectable chapter/episode number at all * (e.g. "Special", "Prologue", "Extra"). */ fun unrecognizedChapterNumberCount(mangaTitle: String, chapters: List): Int { return chapters.count { chapter -> rawSeasonAndNumber(mangaTitle, chapter).second == null } } private fun withSeason(season: Int, ep: Double): Double = if (season > 0) season * 100_000.0 + ep else ep private fun extractNumber(name: String): Double? { chNotation.find(name)?.let { return fromMatch(it) } bareNumber.find(name)?.let { return fromMatch(it) } return null } private fun fromMatch(match: MatchResult): Double { val groups = match.groupValues val base = groups.getOrNull(1)?.toDoubleOrNull() ?: return 0.0 val decimal = groups.getOrNull(2)?.takeIf { it.isNotEmpty() } val alpha = groups.getOrNull(3)?.takeIf { it.isNotEmpty() } return base + decimalAddition(decimal, alpha) } private fun decimalAddition(decimal: String?, alpha: String?): Double { if (!decimal.isNullOrEmpty()) return decimal.toDoubleOrNull() ?: 0.0 if (!alpha.isNullOrEmpty()) { if ("extra" in alpha) return 0.99 if ("omake" in alpha) return 0.98 if ("special" in alpha) return 0.97 val trimmed = alpha.removePrefix(".") if (trimmed.length == 1) return parseAlphaPostFix(trimmed[0]) } return 0.0 } private fun parseAlphaPostFix(c: Char): Double { val number = c.code - ('a'.code - 1) if (number >= 10) return 0.0 return number / 10.0 } }