ChapterReleasePolicy.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/ChapterReleasePolicy.kt
1package eu.friedcutlet.yokan.domain23data class ChapterReleasePreferences(4 val scanlatorPriority: List<String> = emptyList(),5 val skipDuplicates: Boolean = false,6)78/** Only explicit chapter/episode numbers or leading numeric chapter labels establish equivalence. */9data class ChapterReleaseIdentity(10 val number: Double,11 val season: Int?,12 val volume: Int?,13 val part: String,14 val language: String,15 val edition: String,16)1718private val explicitNumber = Regex("\\b(?:chapter|chap|ch|episode|ep|folge)\\.?\\s*#?\\s*(\\d+(?:[.,]\\d+)?)([a-z]?)(?=\\s|[:.\\-]|$)")19private val leadingNumber = Regex("^#?(\\d+(?:[.,]\\d+)?)([a-z]?)(?=\\s|[:.\\-]|$)")20private val seasonLabel = Regex("\\b(?:season|staffel|saison|temporada|s)\\.?\\s*(\\d+)\\b")21private val volumeLabel = Regex("\\b(?:volume|vol|v)\\.?\\s*(\\d+)\\b")22private val editionLabel = Regex("\\b(?:special|extra|omake|oneshot|one-shot|colored|coloured|color|colour|remaster(?:ed)?|uncensored|censored|revised|bonus|part\\s*\\d+)\\b")23private val languageLabel = Regex("\\[(?:lang[:=]\\s*)?([a-z]{2}(?:-[a-z]{2})?)\\]")24private val whitespace = Regex("\\s+")25private val numberRange = Regex("^\\s*(?:[-–/&]|and|\\.)\\s*\\d")26private val namedLanguage = Regex("\\b(?:english|spanish|french|german|russian|portuguese|japanese|chinese|korean|italian|turkish)\\b")2728/** Case/whitespace normalization only: punctuation and combined group names keep their meaning. */29fun normalizeScanlator(name: String): String = name.trim().replace(whitespace, " ").lowercase()3031fun chapterReleaseIdentity(32 mangaTitle: String,33 chapterName: String,34 number: Double? = null,35 season: Int? = null,36 numberingName: String? = null,37): ChapterReleaseIdentity? {38 val named = namedChapterReleaseIdentity(mangaTitle, numberingName?.takeIf(String::isNotBlank) ?: chapterName)39 val validSeason = season?.takeIf { it >= 0 }40 val explicit = number?.takeIf { it.isFinite() && it >= 0 }41 return if (explicit != null) {42 named?.copy(number = explicit, season = validSeason ?: named.season)43 ?: ChapterReleaseIdentity(explicit, validSeason, null, "", "", "")44 } else named?.let { if (validSeason == null) it else it.copy(season = validSeason) }45}4647private fun namedChapterReleaseIdentity(mangaTitle: String, chapterName: String): ChapterReleaseIdentity? {48 var name = chapterName.lowercase().trim()49 if (mangaTitle.isNotBlank()) name = name.replace(mangaTitle.lowercase(), "").trim()50 val matches = explicitNumber.findAll(name).toList()51 if (matches.size > 1) return null // Ranges/combined chapters are uncertain.52 val number = matches.singleOrNull() ?: leadingNumber.find(name) ?: return null53 val value = number.groupValues[1].replace(',', '.').toDoubleOrNull()?.takeIf { it.isFinite() } ?: return null54 // A second number after a range separator is not a decimal or a separate release.55 if (numberRange.containsMatchIn(name.substring(number.range.last + 1))) return null56 fun label(regex: Regex): Int? = regex.find(name)?.groupValues?.get(1)?.toIntOrNull()57 return ChapterReleaseIdentity(value, label(seasonLabel), label(volumeLabel), number.groupValues[2],58 (languageLabel.findAll(name).map { it.groupValues[1] } + namedLanguage.findAll(name).map { it.value })59 .distinct().sorted().joinToString("/"),60 editionLabel.findAll(name).map { it.value.replace(whitespace, " ") }.distinct().sorted().joinToString("/"))61}6263/** Transient ingestion/read-state key; uncertain names retain their independent URL identity. */64fun chapterReleaseKey(65 mangaTitle: String?, chapterName: String?, scanlator: String? = null,66 number: Double? = null, season: Int? = null, numberingName: String? = null,67): String? = chapterReleaseIdentity(mangaTitle.orEmpty(), chapterName.orEmpty(), number, season, numberingName)68 ?.let { "$it::${normalizeScanlator(scanlator.orEmpty())}" }6970private fun Chapter.releaseIdentity(title: String): ChapterReleaseIdentity? =71 chapterReleaseIdentity(title, name, number, season, numberingName)7273/**74 * Select without deleting releases. Read/bookmark state belongs to an equivalence group while75 * file locations and page positions always belong to the actual winning release.76 */77fun selectChapterReleases(78 mangaTitle: String,79 chapters: List<Chapter>,80 preferences: ChapterReleasePreferences = ChapterReleasePreferences(),81 excludedScanlators: Set<String> = emptySet(),82 downloadedIds: Set<Long> = emptySet(),83 offlineOnly: Boolean = false,84 showAllReleases: Boolean = false,85): List<Chapter> {86 val hidden = excludedScanlators.map(::normalizeScanlator).toSet()87 fun downloaded(chapter: Chapter) = chapter.id in downloadedIds || chapter.downloadSize != null || chapter.archivePath.isNotBlank()88 val eligible = chapters.filter { normalizeScanlator(it.scanlator) !in hidden && (!offlineOnly || downloaded(it)) }89 if (!preferences.skipDuplicates || showAllReleases) return eligible90 val identities = chapters.associate { it.id to it.releaseIdentity(mangaTitle) }91 val groups = chapters.groupBy { identities[it.id] ?: it.id }92 val ranks = preferences.scanlatorPriority.map(::normalizeScanlator).distinct().withIndex().associate { it.value to it.index }93 val comparator = compareBy<Chapter> { ranks[normalizeScanlator(it.scanlator)] ?: Int.MAX_VALUE }94 .thenBy { !downloaded(it) }.thenBy { normalizeScanlator(it.scanlator) }95 .thenBy { it.url }.thenBy { it.id }96 return eligible.groupBy { identities[it.id] ?: it.id }.map { (key, releases) ->97 val winner = releases.minWith(comparator)98 val equivalents = groups.getValue(key)99 winner.copy(isRead = equivalents.any { it.isRead }, isBookmarked = equivalents.any { it.isBookmarked })100 }101}102103/** Explicit group actions can clear aggregated state as well as set it. Uncertain rows stay local. */104fun equivalentReleaseIds(mangaTitle: String, chapters: List<Chapter>, selectedIds: Set<Long>): Set<Long> {105 val identities = chapters.associate { it.id to it.releaseIdentity(mangaTitle) }106 val selectedKeys = selectedIds.mapNotNull { identities[it] }.toSet()107 return chapters.filter { it.id in selectedIds || identities[it.id]?.let(selectedKeys::contains) == true }.mapTo(HashSet()) { it.id }108}109110fun chapterReadingOrder(mangaTitle: String, chapters: List<Chapter>): List<Chapter> {111 val identities = chapters.associate { it.id to it.releaseIdentity(mangaTitle) }112 return chapters.sortedWith(compareBy<Chapter> { identities[it.id]?.season ?: 0 }113 .thenBy { identities[it.id]?.volume ?: 0 }.thenBy { identities[it.id]?.number ?: 0.0 }114 .thenBy { identities[it.id]?.part.orEmpty() }.thenBy { it.id })115}116