DownloadPolicy.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadPolicy.kt
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.data.toDomainChapter4import eu.friedcutlet.yokan.database.*5import eu.friedcutlet.yokan.domain.chapterReadingOrder6import eu.friedcutlet.yokan.domain.chapterReleaseIdentity7import eu.friedcutlet.yokan.domain.selectChapterReleases89enum class DownloadCleanupReason { Consumption, ManualMark }1011internal fun downloadPolicyAllows(title: DbManga, chapter: DbChapter, policy: DbDownloadPolicy): Boolean =12 title.favorite && !title.isLocalArchive && title.sourceId != null &&13 (policy.includeCategoryIds.isEmpty() || title.categories.orEmpty().any(policy.includeCategoryIds::contains)) &&14 title.categories.orEmpty().none(policy.excludeCategoryIds::contains) &&15 (!policy.unreadOnly || !chapter.isRead) && (policy.includeFiller || !chapter.effectiveFiller)1617/** Same release selection and chronological order used by the reader, independent of UI state. */18internal fun downloadReadingSequence(snapshot: YokanDatabaseSnapshot, title: DbManga, raw: List<DbChapter> = snapshot.chapters.filter { it.mangaId == title.id }, selectReleases: Boolean = true): List<DbChapter> {19 val chapters = raw.map(::toDomainChapter)20 val selected = if (selectReleases) selectChapterReleases(title.name.orEmpty(), chapters, snapshot.settings.chapterReleasePreference(title.id).toPolicy()) else chapters21 val byId = raw.associateBy { it.id }22 return chapterReadingOrder(title.name.orEmpty(), selected).mapNotNull { byId[it.id] }23}2425internal fun automaticDownloadCandidates(snapshot: YokanDatabaseSnapshot, chapterIds: Set<Long>): List<Long> {26 val policy = snapshot.settings.features.downloads27 if (!policy.autoDownloadNew) return emptyList()28 val recorded = snapshot.downloads.mapNotNullTo(mutableSetOf()) { it.chapterId }29 val sources = snapshot.sources.filter { it.isActive && it.isAdded }.mapTo(mutableSetOf()) { it.id }30 val byId = snapshot.chapters.associateBy { it.id }31 val byTitle = snapshot.chapters.groupBy { it.mangaId }32 val titles = snapshot.mangas.associateBy { it.id }33 return chapterIds.mapNotNull { byId[it]?.mangaId }.distinct().flatMap { titleId ->34 val title = titles[titleId] ?: return@flatMap emptyList()35 if (title.sourceId !in sources) return@flatMap emptyList()36 downloadReadingSequence(snapshot, title, byTitle[titleId].orEmpty()).filter {37 it.id in chapterIds && it.id !in recorded && downloadPolicyAllows(title, it, policy)38 }.map { it.id }39 }40}4142internal fun downloadAheadCandidates(snapshot: YokanDatabaseSnapshot, currentId: Long): List<Long> {43 if (snapshot.settings.incognitoMode) return emptyList()44 val policy = snapshot.settings.features.downloads45 if (policy.aheadManga <= 0 && policy.aheadAnime <= 0 && policy.aheadNovel <= 0) return emptyList()46 val current = snapshot.chapters.firstOrNull { it.id == currentId } ?: return emptyList()47 val title = snapshot.mangas.firstOrNull { it.id == current.mangaId } ?: return emptyList()48 val count = policy.ahead(title.itemType)49 if (count == 0 || !downloadPolicyAllows(title, current.copy(isRead = false, isFiller = false, fillerOverride = null), policy)) return emptyList()50 if (snapshot.sources.none { it.id == title.sourceId && it.isActive && it.isAdded }) return emptyList()51 val sequence = downloadReadingSequence(snapshot, title)52 val identity = chapterReleaseIdentity(title.name.orEmpty(), current.name.orEmpty(), current.number, current.season, current.numberingName)53 val index = sequence.indexOfFirst { it.id == currentId || (identity != null && chapterReleaseIdentity(title.name.orEmpty(), it.name.orEmpty(), it.number, it.season, it.numberingName) == identity) }54 if (index < 0) return emptyList()55 val recorded = snapshot.downloads.mapNotNullTo(mutableSetOf()) { it.chapterId }56 // Existing queued/downloaded chapters count toward the requested ahead window; cancellation57 // and paused rows are preserved rather than silently replaced by automation.58 return sequence.drop(index + 1).filter { !it.isRead && (policy.includeFiller || !it.effectiveFiller) }59 .take(count).filter { it.id !in recorded }.map { it.id }60}6162internal fun downloadCleanupCandidates(snapshot: YokanDatabaseSnapshot, titleId: Long, reason: DownloadCleanupReason, protectedIds: Set<Long>): List<Long> {63 val policy = snapshot.settings.features.downloads64 val enabled = when (reason) {65 DownloadCleanupReason.Consumption -> policy.cleanupAfterConsumption || snapshot.settings.deleteDownloadAfterReading66 DownloadCleanupReason.ManualMark -> policy.cleanupAfterManualMark67 }68 if (!enabled) return emptyList()69 val title = snapshot.mangas.firstOrNull { it.id == titleId } ?: return emptyList()70 if (title.isLocalArchive || title.categories.orEmpty().any(policy.cleanupExcludedCategoryIds::contains)) return emptyList()71 val completed = snapshot.downloads.filter { it.isDownload == true && it.isStartDownload != true && !it.isPaused }72 .mapNotNullTo(mutableSetOf()) { it.chapterId }73 // An opened alternate release remains eligible even when the preferred reader release differs.74 val consumed = downloadReadingSequence(snapshot, title, selectReleases = false).filter {75 it.isRead && it.id in when (reason) {76 DownloadCleanupReason.Consumption -> policy.consumedChapterIds77 DownloadCleanupReason.ManualMark -> policy.manuallyMarkedChapterIds78 }79 }80 fun identity(chapter: DbChapter): Any = chapterReleaseIdentity(title.name.orEmpty(), chapter.name.orEmpty(), chapter.number, chapter.season, chapter.numberingName) ?: chapter.id81 val keep = consumed.asReversed().map(::identity).distinct().take(policy.keepLastConsumed.coerceIn(0, 1000)).toSet()82 return consumed.filter { it.id in completed && identity(it) !in keep && it.id !in protectedIds && (!policy.protectBookmarks || !it.isBookmarked) }.map { it.id }83}84