Yokan / rebuild
Course 1 8624561

LibraryUpdaterService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LibraryUpdaterService.kt

implementation484 lines
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.data.YokanRepository4import eu.friedcutlet.yokan.data.toDb5import eu.friedcutlet.yokan.data.upsertSeasonRecords6import eu.friedcutlet.yokan.database.DbFetchType7import eu.friedcutlet.yokan.data.toDomain8import eu.friedcutlet.yokan.services.catchingNonCancellation9import eu.friedcutlet.yokan.database.DbChapter10import eu.friedcutlet.yokan.database.DbItemType11import eu.friedcutlet.yokan.database.DbManga12import eu.friedcutlet.yokan.database.DbSettings13import eu.friedcutlet.yokan.database.DbSource14import eu.friedcutlet.yokan.database.DbUpdate15import eu.friedcutlet.yokan.database.DbUpdateError16import eu.friedcutlet.yokan.database.YokanDatabase17import eu.friedcutlet.yokan.domain.ItemType18import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory19import eu.friedcutlet.yokan.services.logging.AppLogger20import eu.friedcutlet.yokan.services.notifications.NotificationChannel21import eu.friedcutlet.yokan.services.notifications.NotificationPayload22import eu.friedcutlet.yokan.services.notifications.NotificationService23import eu.friedcutlet.yokan.util.nowMillis24import kotlin.concurrent.Volatile25import kotlinx.coroutines.CoroutineScope26import kotlinx.coroutines.delay27import kotlinx.coroutines.flow.MutableStateFlow28import kotlinx.coroutines.flow.StateFlow29import kotlinx.coroutines.flow.asStateFlow30import kotlinx.coroutines.flow.update31import kotlinx.coroutines.flow.updateAndGet32import kotlinx.coroutines.launch33import kotlinx.coroutines.sync.Mutex34import kotlinx.coroutines.sync.withLock3536interface LibraryUpdaterService {37    suspend fun updateLibrary(38        itemType: DbItemType,39        onProgress: (LibraryUpdateProgress) -> Unit = {},40        shouldCancel: () -> Boolean = { false },41        titleIds: Set<Long>? = null,42        mayStartTitle: suspend () -> Boolean = { true },43    ): LibraryUpdateResult4445    suspend fun updateTitle(mangaId: Long): Boolean46}4748data class LibraryUpdateResult(49    val checked: Int,50    val updated: Int,51    val failed: Int,52    val cancelled: Boolean = false,53    val errors: List<DbUpdateError> = emptyList(),54    val deferred: Boolean = false,55)5657data class LibraryUpdateProgress(58    val itemType: DbItemType,59    val checked: Int,60    val total: Int,61    val updated: Int,62    val failed: Int,63    val currentTitle: String? = null,64    val isRunning: Boolean = true,65)6667/** UI projection of [LibraryUpdateProgress], kept visible for a few seconds after a run ends. */68data class LibraryUpdateProgressState(69    val itemType: ItemType,70    val checked: Int,71    val total: Int,72    val updated: Int,73    val failed: Int,74    val currentTitle: String? = null,75    val running: Boolean = true,76    val cancelRequested: Boolean = false,77    val cancelled: Boolean = false,78)7980fun DbSettings.withoutUpdateError(mangaId: Long): DbSettings =81    copy(updateErrors = updateErrors.orEmpty().filterNot { it.mangaId == mangaId })8283/**84 * App-scoped front of [LibraryUpdaterService]: one run at a time, observable [progress], a85 * summary notification, and cooperative [cancel].86 */87class LibraryUpdateController(88    private val updater: LibraryUpdaterService,89    private val repository: YokanRepository,90    private val notifications: NotificationService,91    private val scope: CoroutineScope,92) {93    private val _progress = MutableStateFlow<LibraryUpdateProgressState?>(null)94    val progress: StateFlow<LibraryUpdateProgressState?> = _progress.asStateFlow()9596    @Volatile97    private var cancelRequested = false9899    fun cancel() {100        cancelRequested = true101        _progress.update { it?.copy(cancelRequested = true) }102    }103104    /** Runs in the caller's coroutine; returns an empty result while another run is active. */105    suspend fun run(itemType: ItemType, titleIds: Set<Long>? = null): LibraryUpdateResult {106        val capturedIds = titleIds?.toSet()107        val current = _progress.value108        val started = LibraryUpdateProgressState(109            itemType = itemType,110            checked = 0,111            total = 0,112            updated = 0,113            failed = 0,114            running = true,115        )116        if (current?.running == true || !_progress.compareAndSet(current, started)) {117            return LibraryUpdateResult(0, 0, 0)118        }119        cancelRequested = false120        val beforeRecent = repository.updates().map { it.id }.toSet()121        val result = try {122            updater.updateLibrary(123                itemType.toDb(),124                onProgress = { progress ->125                    _progress.value = progress.toUiState(cancelRequested = cancelRequested, cancelled = false)126                },127                shouldCancel = { cancelRequested },128                titleIds = capturedIds,129            )130        } catch (throwable: Throwable) {131            AppLogger.error("[library-update] $itemType run failed: ${throwable.message?.lineSequence()?.firstOrNull() ?: throwable::class.simpleName}")132            val failed = _progress.updateAndGet {133                it?.copy(running = false, currentTitle = throwable.message.orEmpty().ifBlank { "Update failed" })134            }135            failed?.let(::scheduleClear)136            throw throwable137        }138        val finalProgress = (_progress.value ?: LibraryUpdateProgressState(139            itemType = itemType,140            checked = result.checked,141            total = result.checked,142            updated = result.updated,143            failed = result.failed,144        )).copy(145            running = false,146            cancelRequested = false,147            cancelled = result.cancelled,148        )149        _progress.value = finalProgress150        scheduleClear(finalProgress)151        if (result.updated > 0) notifySummary(itemType, result, beforeRecent)152        return result153    }154155    private fun notifySummary(itemType: ItemType, result: LibraryUpdateResult, beforeRecent: Set<Long>) {156        val newlyUpdatedTitles = repository.updates()157            .filter { it.id !in beforeRecent && it.itemType == itemType }158            .sortedByDescending { it.updatedAt }159            .map { it.title }160            .distinct()161        val sample = newlyUpdatedTitles.take(3).joinToString(", ")162        val extra = if (newlyUpdatedTitles.size > 3) " + ${newlyUpdatedTitles.size - 3} more" else ""163        val message = buildString {164            append("${result.updated} of ${result.checked} titles refreshed (${result.failed} failed)")165            if (sample.isNotBlank()) append("\nNew: $sample$extra")166        }167        notifications.notify(168            NotificationPayload(169                channel = NotificationChannel.LibraryUpdates,170                title = "${itemType.label} updates",171                message = message,172                tag = "library-${itemType.name}",173            ),174        )175    }176177    private fun scheduleClear(progress: LibraryUpdateProgressState) {178        scope.launch {179            delay(if (progress.cancelled) 6_000L else 4_000L)180            _progress.compareAndSet(progress, null)181        }182    }183}184185private fun LibraryUpdateProgress.toUiState(186    cancelRequested: Boolean,187    cancelled: Boolean,188): LibraryUpdateProgressState = LibraryUpdateProgressState(189    itemType = itemType.toDomain(),190    checked = checked,191    total = total,192    updated = updated,193    failed = failed,194    currentTitle = currentTitle,195    running = isRunning,196    cancelRequested = cancelRequested,197    cancelled = cancelled,198)199200class DefaultLibraryUpdaterService(201    private val database: YokanDatabase,202    private val runtimeFactory: ExtensionRuntimeFactory,203    private val downloadAutomation: eu.friedcutlet.yokan.services.download.DownloadAutomation? = null,204    private val clock: () -> Long = ::nowMillis,205) : LibraryUpdaterService {206    private val updateMutex = Mutex()207208    override suspend fun updateLibrary(209        itemType: DbItemType,210        onProgress: (LibraryUpdateProgress) -> Unit,211        shouldCancel: () -> Boolean,212        titleIds: Set<Long>?,213        mayStartTitle: suspend () -> Boolean,214    ): LibraryUpdateResult {215        val capturedIds = titleIds?.toSet()216        return updateMutex.withLock { updateLibraryLocked(itemType, onProgress, shouldCancel, capturedIds, mayStartTitle) }217    }218219    private suspend fun updateLibraryLocked(itemType: DbItemType, onProgress: (LibraryUpdateProgress) -> Unit,220        shouldCancel: () -> Boolean, titleIds: Set<Long>?, mayStartTitle: suspend () -> Boolean): LibraryUpdateResult {221        // Evaluate after waiting for the service lock, before any source work or report mutation.222        if (!mayStartTitle()) {223            onProgress(LibraryUpdateProgress(itemType, 0, 0, 0, 0, isRunning = false))224            return LibraryUpdateResult(0, 0, 0, deferred = true)225        }226        val settings = database.settings()227        val rules = settings.features.library.updateRules(itemType)228        val library = database.mangas(itemType)229        val errorScope = library.asSequence().filter { titleIds == null || it.id in titleIds }.map { it.id }.toSet()230        val pinnedOnly = settings.onlyIncludePinnedSources231        val excludedCategoryIds = database.categories(itemType)232            .filter { it.shouldUpdate == false }233            .mapNotNull { category -> category.id.takeIf { it > 0 } }234            .toSet()235        val chaptersByTitle by lazy { database.chapters().groupBy { it.mangaId } }236        val candidates = library237            .filter { it.favorite && (titleIds == null || it.id in titleIds) }238            .filter { manga ->239                val needsChapters = rules.onlyCaughtUp || rules.onlyStarted ||240                    (rules.respectExpectedReleasePeriod && manga.smartUpdateDays == null)241                rules.permits(manga, if (needsChapters) chaptersByTitle[manga.id].orEmpty() else emptyList(), clock())242            }243            .filter { manga ->244                val mangaCategories = manga.categories.orEmpty()245                excludedCategoryIds.isEmpty() ||246                    mangaCategories.isEmpty() ||247                    mangaCategories.any { it !in excludedCategoryIds }248            }249        val workItems = candidates.mapNotNull { manga ->250            val source = manga.sourceId?.let(database::source)251            if (source == null || !source.isActive || (pinnedOnly && !source.isPinned)) {252                null253            } else {254                manga to source255            }256        }257        if (workItems.isEmpty()) {258            onProgress(259                LibraryUpdateProgress(260                    itemType = itemType,261                    checked = 0,262                    total = 0,263                    updated = 0,264                    failed = 0,265                    isRunning = false,266                ),267            )268            writeUpdateErrors(errorScope, emptyList())269            return LibraryUpdateResult(0, 0, 0, errors = emptyList())270        }271        var checked = 0272        var updated = 0273        var failed = 0274        val failures = mutableListOf<DbUpdateError>()275        onProgress(276            LibraryUpdateProgress(277                itemType = itemType,278                checked = checked,279                total = workItems.size,280                updated = updated,281                failed = failed,282                isRunning = true,283            ),284        )285        workItems.forEach { (manga, source) ->286            if (shouldCancel()) {287                onProgress(288                    LibraryUpdateProgress(289                        itemType = itemType,290                        checked = checked,291                        total = workItems.size,292                        updated = updated,293                        failed = failed,294                        currentTitle = manga.name,295                        isRunning = false,296                    ),297                )298                writeUpdateErrors(errorScope, failures)299                AppLogger.info("[library-update] $itemType cancelled: $updated of $checked/${workItems.size} updated, $failed failed")300                return LibraryUpdateResult(301                    checked = checked,302                    updated = updated,303                    failed = failed,304                    cancelled = true,305                    errors = failures,306                )307            }308            if (!mayStartTitle()) {309                // Preserve error reports for unchecked titles when constraints change mid-run.310                writeUpdateErrors(workItems.take(checked).mapTo(mutableSetOf()) { it.first.id }, failures)311                onProgress(LibraryUpdateProgress(itemType, checked, workItems.size, updated, failed, isRunning = false))312                return LibraryUpdateResult(checked, updated, failed, errors = failures, deferred = true)313            }314            checked += 1315            var errorMsg: String? = null316            val success = catchingNonCancellation {317                updateOne(manga, source)318            }.fold(319                onSuccess = { ok ->320                    if (!ok) errorMsg = "Update failed (invalid link or source error)"321                    ok322                },323                onFailure = { err ->324                    errorMsg = err.message?.ifBlank { null } ?: err.toString()325                    false326                },327            )328            if (success) {329                updated += 1330            } else {331                failed += 1332                failures.add(333                    DbUpdateError(334                        mangaId = manga.id,335                        name = manga.name ?: "Unknown title",336                        error = errorMsg ?: "Unknown error",337                    ),338                )339            }340            onProgress(341                LibraryUpdateProgress(342                    itemType = itemType,343                    checked = checked,344                    total = workItems.size,345                    updated = updated,346                    failed = failed,347                    currentTitle = manga.name,348                    isRunning = true,349                ),350            )351        }352        writeUpdateErrors(errorScope, failures)353        val summary = "[library-update] $itemType done: $updated of $checked updated, $failed failed"354        val firstFailure = failures.firstOrNull()355        if (firstFailure == null) {356            AppLogger.info(summary)357        } else {358            AppLogger.warn("$summary; first: ${firstFailure.name}: ${firstFailure.error.lineSequence().firstOrNull().orEmpty()}")359        }360        onProgress(361            LibraryUpdateProgress(362                itemType = itemType,363                checked = checked,364                total = workItems.size,365                updated = updated,366                failed = failed,367                isRunning = false,368            ),369        )370        return LibraryUpdateResult(checked = checked, updated = updated, failed = failed, errors = failures)371    }372373    override suspend fun updateTitle(mangaId: Long): Boolean = updateMutex.withLock {374        val manga = database.manga(mangaId) ?: return@withLock false375        val source = manga.sourceId?.let(database::source) ?: return@withLock false376        catchingNonCancellation { updateOne(manga, source) }377            .onFailure { AppLogger.warn("[library-update] title $mangaId failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }378            .getOrDefault(false)379    }380381    private suspend fun updateOne(manga: DbManga, source: DbSource, depth: Int = 0): Boolean {382        val link = manga.link ?: return false383        val detail = runtimeFactory.withRuntime(source) { it.detail(link) }384        val now = clock()385        detail.seasons?.let { seasons ->386            val parent = database.batch {387                val current = database.manga(manga.id) ?: return@batch null388                if (current.sourceId != manga.sourceId || current.link != link) return@batch null389                val saved = database.upsertManga(current.copy(390                    description = detail.description.ifBlank { current.description.orEmpty() },391                    author = detail.author ?: current.author,392                    artist = detail.artist ?: current.artist,393                    imageUrl = detail.thumbnailUrl ?: current.imageUrl,394                    fetchType = DbFetchType.Seasons,395                    lastUpdate = now,396                    updatedAt = now,397                ))398                database.upsertSeasonRecords(saved, seasons, now)399                saved400            } ?: return false401            // Each season is its own title: refreshing it records new episodes (or nested seasons) under it.402            // ponytail: nesting capped at 4 levels and seasons refresh sequentially; parallelize if large franchises stall runs.403            if (depth >= 4) return true404            return database.mangas(manga.itemType).filter { it.parentId == parent.id }405                .fold(true) { ok, season -> updateOne(season, source, depth + 1) && ok }406        }407        val seenUrls = mutableSetOf<String>()408        val seenCompositeKeys = mutableSetOf<String>()409        val newChapterIds = mutableSetOf<Long>()410        return database.batch {411            // Re-read after the network request: local edits (and deletion) win.412            val currentManga = database.manga(manga.id) ?: return@batch false413            if (currentManga.sourceId != manga.sourceId || currentManga.link != link) return@batch false414            val currentChapters = database.chapters(manga.id)415            val mangaTitle = currentManga.name416            val chaptersByUrl = currentChapters.associateByTo(mutableMapOf(), DbChapter::url)417            val chaptersByComposite = currentChapters.mapNotNull { c ->418                eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, c.name, c.scanlator, c.number, c.season, c.numberingName)?.let { it to c }419            }.toMap()420            val readByEpisode = currentChapters.filter { it.isRead }.mapNotNull { c ->421                eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, c.name, number = c.number, season = c.season, numberingName = c.numberingName)422            }.toSet()423            val beforeUrls = chaptersByUrl.keys.toSet()424            database.upsertManga(425                currentManga.copy(426                    description = detail.description.ifBlank { currentManga.description.orEmpty() },427                    author = detail.author ?: currentManga.author,428                    artist = detail.artist ?: currentManga.artist,429                    imageUrl = detail.thumbnailUrl ?: currentManga.imageUrl,430                    lastUpdate = now,431                    updatedAt = now,432                ),433            )434            detail.chapters.forEach { remote ->435                val compositeKey = eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, remote.title, remote.scanlator)436                val episodeKey = eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, remote.title)437438                if (!seenUrls.add(remote.url)) return@forEach439                if (compositeKey != null && !seenCompositeKeys.add(compositeKey)) return@forEach440441                val existing = chaptersByUrl[remote.url] ?: compositeKey?.let { chaptersByComposite[it] }442                val carryRead = existing?.isRead ?: (episodeKey != null && episodeKey in readByEpisode)443444                val next = (existing ?: DbChapter(mangaId = manga.id)).copy(445                    mangaId = manga.id,446                    name = remote.title,447                    url = remote.url,448                    dateUpload = remote.dateUpload.ifBlank { existing?.dateUpload.orEmpty() },449                    scanlator = remote.scanlator.ifBlank { existing?.scanlator.orEmpty() },450                    isBookmarked = existing?.isBookmarked ?: false,451                    isRead = carryRead,452                    lastPageRead = existing?.lastPageRead ?: if (carryRead) "1" else "",453                    fetchedAt = existing?.fetchedAt ?: now,454                )455                // Unchanged chapters are not rewritten: bumping the synced `updatedAt` alone would456                // cost a write and a hub op per chapter on every library update.457                val saved = if (existing != null && next == existing) existing else database.upsertChapter(next.copy(updatedAt = now))458                chaptersByUrl[remote.url] = saved459                if (existing == null && remote.url !in beforeUrls) {460                    newChapterIds += saved.id461                    database.upsertUpdate(462                        DbUpdate(463                            mangaId = manga.id,464                            chapterId = saved.id,465                            chapterName = saved.name,466                            date = "Now",467                            updatedAt = now,468                        ),469                    )470                }471            }472            downloadAutomation?.recordDiscoveredChapters(newChapterIds)473            true474        }475    }476477    private fun writeUpdateErrors(scope: Set<Long>, failures: List<DbUpdateError>) {478        database.batch {479            val current = database.settings()480            val next = current.updateErrors.orEmpty().filterNot { it.mangaId in scope } + failures481            if (next != current.updateErrors.orEmpty()) database.updateSettings(current.copy(updateErrors = next))482        }483    }484}485

Search chapters, reference and source filenames.