package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.data.toDb import eu.friedcutlet.yokan.data.upsertSeasonRecords import eu.friedcutlet.yokan.database.DbFetchType import eu.friedcutlet.yokan.data.toDomain import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbUpdate import eu.friedcutlet.yokan.database.DbUpdateError import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.notifications.NotificationChannel import eu.friedcutlet.yokan.services.notifications.NotificationPayload import eu.friedcutlet.yokan.services.notifications.NotificationService import eu.friedcutlet.yokan.util.nowMillis import kotlin.concurrent.Volatile import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.updateAndGet import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock interface LibraryUpdaterService { suspend fun updateLibrary( itemType: DbItemType, onProgress: (LibraryUpdateProgress) -> Unit = {}, shouldCancel: () -> Boolean = { false }, titleIds: Set? = null, mayStartTitle: suspend () -> Boolean = { true }, ): LibraryUpdateResult suspend fun updateTitle(mangaId: Long): Boolean } data class LibraryUpdateResult( val checked: Int, val updated: Int, val failed: Int, val cancelled: Boolean = false, val errors: List = emptyList(), val deferred: Boolean = false, ) data class LibraryUpdateProgress( val itemType: DbItemType, val checked: Int, val total: Int, val updated: Int, val failed: Int, val currentTitle: String? = null, val isRunning: Boolean = true, ) /** UI projection of [LibraryUpdateProgress], kept visible for a few seconds after a run ends. */ data class LibraryUpdateProgressState( val itemType: ItemType, val checked: Int, val total: Int, val updated: Int, val failed: Int, val currentTitle: String? = null, val running: Boolean = true, val cancelRequested: Boolean = false, val cancelled: Boolean = false, ) fun DbSettings.withoutUpdateError(mangaId: Long): DbSettings = copy(updateErrors = updateErrors.orEmpty().filterNot { it.mangaId == mangaId }) /** * App-scoped front of [LibraryUpdaterService]: one run at a time, observable [progress], a * summary notification, and cooperative [cancel]. */ class LibraryUpdateController( private val updater: LibraryUpdaterService, private val repository: YokanRepository, private val notifications: NotificationService, private val scope: CoroutineScope, ) { private val _progress = MutableStateFlow(null) val progress: StateFlow = _progress.asStateFlow() @Volatile private var cancelRequested = false fun cancel() { cancelRequested = true _progress.update { it?.copy(cancelRequested = true) } } /** Runs in the caller's coroutine; returns an empty result while another run is active. */ suspend fun run(itemType: ItemType, titleIds: Set? = null): LibraryUpdateResult { val capturedIds = titleIds?.toSet() val current = _progress.value val started = LibraryUpdateProgressState( itemType = itemType, checked = 0, total = 0, updated = 0, failed = 0, running = true, ) if (current?.running == true || !_progress.compareAndSet(current, started)) { return LibraryUpdateResult(0, 0, 0) } cancelRequested = false val beforeRecent = repository.updates().map { it.id }.toSet() val result = try { updater.updateLibrary( itemType.toDb(), onProgress = { progress -> _progress.value = progress.toUiState(cancelRequested = cancelRequested, cancelled = false) }, shouldCancel = { cancelRequested }, titleIds = capturedIds, ) } catch (throwable: Throwable) { AppLogger.error("[library-update] $itemType run failed: ${throwable.message?.lineSequence()?.firstOrNull() ?: throwable::class.simpleName}") val failed = _progress.updateAndGet { it?.copy(running = false, currentTitle = throwable.message.orEmpty().ifBlank { "Update failed" }) } failed?.let(::scheduleClear) throw throwable } val finalProgress = (_progress.value ?: LibraryUpdateProgressState( itemType = itemType, checked = result.checked, total = result.checked, updated = result.updated, failed = result.failed, )).copy( running = false, cancelRequested = false, cancelled = result.cancelled, ) _progress.value = finalProgress scheduleClear(finalProgress) if (result.updated > 0) notifySummary(itemType, result, beforeRecent) return result } private fun notifySummary(itemType: ItemType, result: LibraryUpdateResult, beforeRecent: Set) { val newlyUpdatedTitles = repository.updates() .filter { it.id !in beforeRecent && it.itemType == itemType } .sortedByDescending { it.updatedAt } .map { it.title } .distinct() val sample = newlyUpdatedTitles.take(3).joinToString(", ") val extra = if (newlyUpdatedTitles.size > 3) " + ${newlyUpdatedTitles.size - 3} more" else "" val message = buildString { append("${result.updated} of ${result.checked} titles refreshed (${result.failed} failed)") if (sample.isNotBlank()) append("\nNew: $sample$extra") } notifications.notify( NotificationPayload( channel = NotificationChannel.LibraryUpdates, title = "${itemType.label} updates", message = message, tag = "library-${itemType.name}", ), ) } private fun scheduleClear(progress: LibraryUpdateProgressState) { scope.launch { delay(if (progress.cancelled) 6_000L else 4_000L) _progress.compareAndSet(progress, null) } } } private fun LibraryUpdateProgress.toUiState( cancelRequested: Boolean, cancelled: Boolean, ): LibraryUpdateProgressState = LibraryUpdateProgressState( itemType = itemType.toDomain(), checked = checked, total = total, updated = updated, failed = failed, currentTitle = currentTitle, running = isRunning, cancelRequested = cancelRequested, cancelled = cancelled, ) class DefaultLibraryUpdaterService( private val database: YokanDatabase, private val runtimeFactory: ExtensionRuntimeFactory, private val downloadAutomation: eu.friedcutlet.yokan.services.download.DownloadAutomation? = null, private val clock: () -> Long = ::nowMillis, ) : LibraryUpdaterService { private val updateMutex = Mutex() override suspend fun updateLibrary( itemType: DbItemType, onProgress: (LibraryUpdateProgress) -> Unit, shouldCancel: () -> Boolean, titleIds: Set?, mayStartTitle: suspend () -> Boolean, ): LibraryUpdateResult { val capturedIds = titleIds?.toSet() return updateMutex.withLock { updateLibraryLocked(itemType, onProgress, shouldCancel, capturedIds, mayStartTitle) } } private suspend fun updateLibraryLocked(itemType: DbItemType, onProgress: (LibraryUpdateProgress) -> Unit, shouldCancel: () -> Boolean, titleIds: Set?, mayStartTitle: suspend () -> Boolean): LibraryUpdateResult { // Evaluate after waiting for the service lock, before any source work or report mutation. if (!mayStartTitle()) { onProgress(LibraryUpdateProgress(itemType, 0, 0, 0, 0, isRunning = false)) return LibraryUpdateResult(0, 0, 0, deferred = true) } val settings = database.settings() val rules = settings.features.library.updateRules(itemType) val library = database.mangas(itemType) val errorScope = library.asSequence().filter { titleIds == null || it.id in titleIds }.map { it.id }.toSet() val pinnedOnly = settings.onlyIncludePinnedSources val excludedCategoryIds = database.categories(itemType) .filter { it.shouldUpdate == false } .mapNotNull { category -> category.id.takeIf { it > 0 } } .toSet() val chaptersByTitle by lazy { database.chapters().groupBy { it.mangaId } } val candidates = library .filter { it.favorite && (titleIds == null || it.id in titleIds) } .filter { manga -> val needsChapters = rules.onlyCaughtUp || rules.onlyStarted || (rules.respectExpectedReleasePeriod && manga.smartUpdateDays == null) rules.permits(manga, if (needsChapters) chaptersByTitle[manga.id].orEmpty() else emptyList(), clock()) } .filter { manga -> val mangaCategories = manga.categories.orEmpty() excludedCategoryIds.isEmpty() || mangaCategories.isEmpty() || mangaCategories.any { it !in excludedCategoryIds } } val workItems = candidates.mapNotNull { manga -> val source = manga.sourceId?.let(database::source) if (source == null || !source.isActive || (pinnedOnly && !source.isPinned)) { null } else { manga to source } } if (workItems.isEmpty()) { onProgress( LibraryUpdateProgress( itemType = itemType, checked = 0, total = 0, updated = 0, failed = 0, isRunning = false, ), ) writeUpdateErrors(errorScope, emptyList()) return LibraryUpdateResult(0, 0, 0, errors = emptyList()) } var checked = 0 var updated = 0 var failed = 0 val failures = mutableListOf() onProgress( LibraryUpdateProgress( itemType = itemType, checked = checked, total = workItems.size, updated = updated, failed = failed, isRunning = true, ), ) workItems.forEach { (manga, source) -> if (shouldCancel()) { onProgress( LibraryUpdateProgress( itemType = itemType, checked = checked, total = workItems.size, updated = updated, failed = failed, currentTitle = manga.name, isRunning = false, ), ) writeUpdateErrors(errorScope, failures) AppLogger.info("[library-update] $itemType cancelled: $updated of $checked/${workItems.size} updated, $failed failed") return LibraryUpdateResult( checked = checked, updated = updated, failed = failed, cancelled = true, errors = failures, ) } if (!mayStartTitle()) { // Preserve error reports for unchecked titles when constraints change mid-run. writeUpdateErrors(workItems.take(checked).mapTo(mutableSetOf()) { it.first.id }, failures) onProgress(LibraryUpdateProgress(itemType, checked, workItems.size, updated, failed, isRunning = false)) return LibraryUpdateResult(checked, updated, failed, errors = failures, deferred = true) } checked += 1 var errorMsg: String? = null val success = catchingNonCancellation { updateOne(manga, source) }.fold( onSuccess = { ok -> if (!ok) errorMsg = "Update failed (invalid link or source error)" ok }, onFailure = { err -> errorMsg = err.message?.ifBlank { null } ?: err.toString() false }, ) if (success) { updated += 1 } else { failed += 1 failures.add( DbUpdateError( mangaId = manga.id, name = manga.name ?: "Unknown title", error = errorMsg ?: "Unknown error", ), ) } onProgress( LibraryUpdateProgress( itemType = itemType, checked = checked, total = workItems.size, updated = updated, failed = failed, currentTitle = manga.name, isRunning = true, ), ) } writeUpdateErrors(errorScope, failures) val summary = "[library-update] $itemType done: $updated of $checked updated, $failed failed" val firstFailure = failures.firstOrNull() if (firstFailure == null) { AppLogger.info(summary) } else { AppLogger.warn("$summary; first: ${firstFailure.name}: ${firstFailure.error.lineSequence().firstOrNull().orEmpty()}") } onProgress( LibraryUpdateProgress( itemType = itemType, checked = checked, total = workItems.size, updated = updated, failed = failed, isRunning = false, ), ) return LibraryUpdateResult(checked = checked, updated = updated, failed = failed, errors = failures) } override suspend fun updateTitle(mangaId: Long): Boolean = updateMutex.withLock { val manga = database.manga(mangaId) ?: return@withLock false val source = manga.sourceId?.let(database::source) ?: return@withLock false catchingNonCancellation { updateOne(manga, source) } .onFailure { AppLogger.warn("[library-update] title $mangaId failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") } .getOrDefault(false) } private suspend fun updateOne(manga: DbManga, source: DbSource, depth: Int = 0): Boolean { val link = manga.link ?: return false val detail = runtimeFactory.withRuntime(source) { it.detail(link) } val now = clock() detail.seasons?.let { seasons -> val parent = database.batch { val current = database.manga(manga.id) ?: return@batch null if (current.sourceId != manga.sourceId || current.link != link) return@batch null val saved = database.upsertManga(current.copy( description = detail.description.ifBlank { current.description.orEmpty() }, author = detail.author ?: current.author, artist = detail.artist ?: current.artist, imageUrl = detail.thumbnailUrl ?: current.imageUrl, fetchType = DbFetchType.Seasons, lastUpdate = now, updatedAt = now, )) database.upsertSeasonRecords(saved, seasons, now) saved } ?: return false // Each season is its own title: refreshing it records new episodes (or nested seasons) under it. // ponytail: nesting capped at 4 levels and seasons refresh sequentially; parallelize if large franchises stall runs. if (depth >= 4) return true return database.mangas(manga.itemType).filter { it.parentId == parent.id } .fold(true) { ok, season -> updateOne(season, source, depth + 1) && ok } } val seenUrls = mutableSetOf() val seenCompositeKeys = mutableSetOf() val newChapterIds = mutableSetOf() return database.batch { // Re-read after the network request: local edits (and deletion) win. val currentManga = database.manga(manga.id) ?: return@batch false if (currentManga.sourceId != manga.sourceId || currentManga.link != link) return@batch false val currentChapters = database.chapters(manga.id) val mangaTitle = currentManga.name val chaptersByUrl = currentChapters.associateByTo(mutableMapOf(), DbChapter::url) val chaptersByComposite = currentChapters.mapNotNull { c -> eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, c.name, c.scanlator, c.number, c.season, c.numberingName)?.let { it to c } }.toMap() val readByEpisode = currentChapters.filter { it.isRead }.mapNotNull { c -> eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, c.name, number = c.number, season = c.season, numberingName = c.numberingName) }.toSet() val beforeUrls = chaptersByUrl.keys.toSet() database.upsertManga( currentManga.copy( description = detail.description.ifBlank { currentManga.description.orEmpty() }, author = detail.author ?: currentManga.author, artist = detail.artist ?: currentManga.artist, imageUrl = detail.thumbnailUrl ?: currentManga.imageUrl, lastUpdate = now, updatedAt = now, ), ) detail.chapters.forEach { remote -> val compositeKey = eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, remote.title, remote.scanlator) val episodeKey = eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, remote.title) if (!seenUrls.add(remote.url)) return@forEach if (compositeKey != null && !seenCompositeKeys.add(compositeKey)) return@forEach val existing = chaptersByUrl[remote.url] ?: compositeKey?.let { chaptersByComposite[it] } val carryRead = existing?.isRead ?: (episodeKey != null && episodeKey in readByEpisode) val next = (existing ?: DbChapter(mangaId = manga.id)).copy( mangaId = manga.id, name = remote.title, url = remote.url, dateUpload = remote.dateUpload.ifBlank { existing?.dateUpload.orEmpty() }, scanlator = remote.scanlator.ifBlank { existing?.scanlator.orEmpty() }, isBookmarked = existing?.isBookmarked ?: false, isRead = carryRead, lastPageRead = existing?.lastPageRead ?: if (carryRead) "1" else "", fetchedAt = existing?.fetchedAt ?: now, ) // Unchanged chapters are not rewritten: bumping the synced `updatedAt` alone would // cost a write and a hub op per chapter on every library update. val saved = if (existing != null && next == existing) existing else database.upsertChapter(next.copy(updatedAt = now)) chaptersByUrl[remote.url] = saved if (existing == null && remote.url !in beforeUrls) { newChapterIds += saved.id database.upsertUpdate( DbUpdate( mangaId = manga.id, chapterId = saved.id, chapterName = saved.name, date = "Now", updatedAt = now, ), ) } } downloadAutomation?.recordDiscoveredChapters(newChapterIds) true } } private fun writeUpdateErrors(scope: Set, failures: List) { database.batch { val current = database.settings() val next = current.updateErrors.orEmpty().filterNot { it.mangaId in scope } + failures if (next != current.updateErrors.orEmpty()) database.updateSettings(current.copy(updateErrors = next)) } } }