Yokan / rebuild
Course 1 8624561

PersistentDownloadService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadService.kt

implementation935 lines
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.database.DatabaseJson4import eu.friedcutlet.yokan.database.DbDownload5import eu.friedcutlet.yokan.database.DbItemType6import eu.friedcutlet.yokan.database.DbPageUrl7import eu.friedcutlet.yokan.database.YokanDatabase8import eu.friedcutlet.yokan.database.configuredLocalFolders9import eu.friedcutlet.yokan.services.blockingDispatcher10import eu.friedcutlet.yokan.services.catchingNonCancellation11import eu.friedcutlet.yokan.services.files.LocalArchiveService12import eu.friedcutlet.yokan.services.files.LocalFileService13import eu.friedcutlet.yokan.services.http.HttpRequest14import eu.friedcutlet.yokan.services.http.HttpService15import eu.friedcutlet.yokan.services.logging.AppLogger16import eu.friedcutlet.yokan.services.notifications.NotificationChannel17import eu.friedcutlet.yokan.services.notifications.NotificationPayload18import eu.friedcutlet.yokan.services.notifications.NotificationService19import eu.friedcutlet.yokan.services.system.NetworkMonitor20import eu.friedcutlet.yokan.services.system.UnmeteredNetwork21import eu.friedcutlet.yokan.util.PlatformLock22import eu.friedcutlet.yokan.util.nowMillis23import kotlin.random.Random24import kotlinx.coroutines.CancellationException25import kotlinx.coroutines.CoroutineDispatcher26import kotlinx.coroutines.CoroutineScope27import kotlinx.coroutines.CoroutineStart28import kotlinx.coroutines.Job29import kotlinx.coroutines.NonCancellable30import kotlinx.coroutines.coroutineScope31import kotlinx.coroutines.delay32import kotlinx.coroutines.ensureActive33import kotlinx.coroutines.flow.Flow34import kotlinx.coroutines.flow.MutableStateFlow35import kotlinx.coroutines.flow.asStateFlow36import kotlinx.coroutines.flow.combine37import kotlinx.coroutines.flow.first38import kotlinx.coroutines.flow.map39import kotlinx.coroutines.flow.update40import kotlinx.coroutines.isActive41import kotlinx.coroutines.launch42import kotlinx.coroutines.sync.Semaphore43import kotlinx.coroutines.sync.withPermit44import kotlinx.coroutines.withContext45import kotlinx.coroutines.withTimeoutOrNull46import eu.friedcutlet.yokan.services.files.downloadItemTypeFolder4748internal const val DOWNLOAD_CONNECTION_TIMEOUT_MS = 30_000L4950internal const val DOWNLOAD_PREPARATION_TIMEOUT_MS = 45_000L5152/** Pages of one chapter fetched at once; chapters of one source still download one at a time. */53internal const val PAGE_PARALLELISM = 35455/** Page statuses that mean the URL expired or moved: the chapter's pages are re-resolved once. */56private val ExpiredPageStatuses = setOf(401, 403, 404, 410)5758/** Tag of the single "waiting for Wi-Fi" notification, however many chapters wait. */59internal const val WAITING_FOR_WIFI_NOTIFICATION_TAG = "downloads-waiting-for-wifi"6061class PersistentDownloadService(62    private val database: YokanDatabase,63    private val http: HttpService,64    private val files: LocalFileService,65    private val archives: LocalArchiveService,66    /** Owner-provided; download workers live and die with it. */67    private val scope: CoroutineScope,68    /** A chapter's pages, resolved when its download starts; `forceRefresh` skips any saved list. */69    private val resolvePages: suspend (chapterId: Long, forceRefresh: Boolean) -> List<DbPageUrl>,70    private val notifications: NotificationService? = null,71    /** With Wi-Fi-only on, the queue waits while this reports a metered network. */72    private val network: NetworkMonitor = UnmeteredNetwork,73    /** Blocking file work: page writes, promotion, metadata and CBZ zipping. */74    private val ioDispatcher: CoroutineDispatcher = blockingDispatcher,75    private val resolveNovelText: (suspend (chapterId: Long) -> String)? = null,76    private val onCompleted: (chapterId: Long) -> Unit = {},77    private val imageDataSaver: ImageDataSaver? = null,78    imageHttp: HttpService = http,79) : DownloadService {80    private val pageTransfer = PageTransfer(database, http, files, imageHttp, imageDataSaver, ioDispatcher, awaitAllowedNetwork = { awaitAllowedNetwork() })81    private val _activeDownloadProgress = MutableStateFlow<List<DownloadProgress>>(emptyList())82    override val activeDownloadProgress = _activeDownloadProgress.asStateFlow()83    private val _queueStatus = MutableStateFlow(DownloadQueueStatus())84    override val queueStatus = _queueStatus.asStateFlow()8586    /** True while Wi-Fi-only is on and the network is metered: nothing starts and running chapters wait at their next page. */87    private val networkHeld: Flow<Boolean> =88        combine(network.unmetered, database.snapshots().map { it.settings.downloadOnlyOnWifi }) { unmetered, wifiOnly -> wifiOnly && !unmetered }8990    private data class QueuedDownload(91        val request: DownloadRequest,92        val downloadId: Long,93        val onProgress: (DownloadProgress) -> Unit,94        val location: String,95        val sourceKey: String,96        val transferPermits: Semaphore = Semaphore(PAGE_PARALLELISM),97    )9899    /** Page counts of one chapter run; mutated only under [stateLock]. */100    private class PageTally(val total: Int) {101        var succeeded = 0102        var failed = 0103        var bytes = 0L104        val inFlightBytes = mutableMapOf<Int, Long>()105        var lastProgressAt = 0L106    }107108    private val stateLock = PlatformLock()109    private val queue = ArrayDeque<QueuedDownload>()110    private val jobs = mutableMapOf<String, Job>()111    private val active = mutableMapOf<String, DownloadProgress>()112    /** Download row per task, indexed once at start so [enqueue] never scans every row. */113    private val taskDownloadIds = mutableMapOf<String, Long>()114    /** Known or derived file locations; a null value caches "no files found". */115    // ponytail: files removed outside the app keep their cached location until restart.116    private val taskStorageLocations = mutableMapOf<String, String?>()117    /** Running tasks the user cancelled; their row is marked stopped once the worker has ended. */118    private val cancelled = mutableSetOf<String>()119    private val paused = mutableSetOf<String>()120    /** Running tasks stopped by [pause]; they return to the front of the queue once the worker has ended. */121    private val requeueOnStop = mutableSetOf<String>()122    private val lastRequests = mutableMapOf<String, DownloadRequest>()123    private val activeSources = mutableSetOf<String>()124    private val deleting = mutableSetOf<String>()125    private val admitting = mutableSetOf<String>()126    private var running = 0127    private var initialized = false128    private var manualQueueOrder: List<Long> = emptyList()129130    override suspend fun initialize(poolSize: Int) = ensureInitialized()131132    /**133     * Indexes the download rows once and re-queues the ones a previous session left started; rows that134     * can't be rebuilt (chapter gone) become retryable instead.135     */136    private fun ensureInitialized() {137        val interrupted = stateLock.withLock {138            if (initialized) return@withLock emptyList<DbDownload>()139            initialized = true140            database.downloads().filter { download ->141                taskDownloadIds[downloadTaskId(download.chapterId, download.id)] = download.id142                download.isStartDownload == true && download.isDownload != true143            }144        }145        interrupted.forEach { download ->146            val request = download.requestJson?.let { json ->147                runCatching { DatabaseJson.decodeFromString<DownloadRequest>(json) }.getOrNull()148                    ?.takeIf { it.chapterId == download.chapterId }149            } ?: download.chapterId?.let { chapterDownloadRequest(database, it) }150            val queued = request != null && runCatching { queueTask(request, onProgress = {}, knownLocation = download.storageLocation ?: storageLocation(request.taskId), initiallyPaused = download.isPaused, deferStart = true) }151                .onFailure { AppLogger.warn("[download] could not resume ${request.taskId}: ${it.message.orEmpty()}") }152                .getOrDefault(false)153            if (!queued) database.batch {154                val chapterId = download.chapterId ?: return@batch155                val chapter = database.chapter(chapterId) ?: return@batch156                if (chapter.mangaId?.let(database::manga) == null) return@batch157                database.download(download.id)?.let { current ->158                    database.upsertDownload(current.copy(isStartDownload = false, isPaused = false))159                }160            }161        }162        if (interrupted.isNotEmpty()) processQueue()163    }164165    override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) {166        queueTask(request, onProgress, knownLocation = null)167    }168169    /**170     * Records and queues [request] before returning, so the queue keeps call order; with Wi-Fi-only on a171     * metered network it waits in the queue. False when it was skipped: already queued or running, or172     * already downloaded.173     */174    private fun queueTask(175        request: DownloadRequest,176        onProgress: (DownloadProgress) -> Unit,177        knownLocation: String?,178        initiallyPaused: Boolean = false,179        deferStart: Boolean = false,180    ): Boolean {181        ensureInitialized()182        val taskId = request.taskId.ifBlank { downloadTaskId(request.chapterId, 0) }183        val location = knownLocation ?: resolveStorageLocation(request)184        // SAF tree grants are read-only here (AndroidSafLocalFileService), so every page would fail.185        require(!location.startsWith("content://")) {186            "Downloads can't be saved to a folder picked through the system file picker. Choose another download folder in settings."187        }188        val admitted = stateLock.withLock {189            if (taskId in admitting || taskId in deleting || taskId in jobs || queue.any { it.request.taskId == taskId }) false190            else { admitting += taskId; true }191        }192        if (!admitted) return false193        try {194        val validated = database.batch {195            val chapter = database.chapter(request.chapterId) ?: return@batch null196            val manga = chapter.mangaId?.let(database::manga) ?: return@batch null197            val sourceIds = listOfNotNull(manga.sourceId, request.sourceId?.takeIf { it > 0L }).distinct()198            if (sourceIds.any { database.source(it) == null }) return@batch null199            val existing = database.downloads().firstOrNull { it.chapterId == chapter.id }200            existing to Unit201        } ?: return false202        if (isAlreadyDownloaded(validated.first, location)) return false203        val admission = database.batch {204            val chapter = database.chapter(request.chapterId) ?: return@batch null205            val manga = chapter.mangaId?.let(database::manga) ?: return@batch null206            val sourceIds = listOfNotNull(manga.sourceId, request.sourceId?.takeIf { it > 0L }).distinct()207            if (sourceIds.any { database.source(it) == null }) return@batch null208            val existing = database.downloads().firstOrNull { it.chapterId == chapter.id }209            val row = database.upsertDownload(210                DbDownload(211                    id = existing?.id ?: 0,212                    chapterId = chapter.id,213                    succeeded = 0,214                    failed = 0,215                    total = existing?.total,216                    isDownload = false,217                    isStartDownload = true,218                    isPaused = initiallyPaused,219                    storageLocation = location,220                    requestJson = DatabaseJson.encodeToString(request.copy(taskId = taskId)),221                ),222            )223            row224        } ?: return false225        val normalized = request.copy(taskId = taskId)226        val download = admission227        val task = QueuedDownload(normalized, download.id, onProgress, location, resolveDownloadSourceKey(normalized, download.id, database))228        val registered = stateLock.withLock {229            if (taskId in deleting || taskId in jobs || queue.any { it.request.taskId == taskId }) return@withLock false230            taskDownloadIds[taskId] = download.id231            taskStorageLocations[taskId] = location232            lastRequests[taskId] = normalized233            if (initiallyPaused) {234                paused += taskId235                active[taskId] = DownloadProgress(taskId, 0, 0, download.total ?: 0,236                    request.itemType, isPaused = true, storageLocation = location)237                publishActiveDownloadsLocked()238            } else paused.remove(taskId)239            queue += task240            true241        }242        if (!registered) return false243        if (!deferStart) processQueue()244        return true245        } finally { stateLock.withLock { admitting.remove(taskId) } }246    }247248    /**249     * True when [existing] finished and its files are still there; its chapter is re-marked in case the mark250     * was cleared (e.g. by a backup restore). A finished row whose files are gone loses its stale mark.251     */252    private fun isAlreadyDownloaded(existing: DbDownload?, location: String): Boolean {253        if (existing?.isDownload != true) return false254        val chapter = existing.chapterId?.let(database::chapter) ?: return false255        val path = listOf(chapter.archivePath, location, "$location.cbz").firstOrNull { it.isNotBlank() && files.exists(it) }256        when {257            path == null -> if (chapter.archivePath.isNotBlank() || chapter.downloadSize != null) setDownloadMark(chapter.id, "", null)258            chapter.archivePath.isBlank() -> setDownloadMark(chapter.id, path, downloadSizeLabel(files.directorySize(path)))259        }260        return path != null261    }262263    override fun cancel(taskId: String) {264        val job = stateLock.withLock {265            queue.removeAll { it.request.taskId == taskId }266            paused.remove(taskId)267            requeueOnStop.remove(taskId)268            active.remove(taskId)269            publishActiveDownloadsLocked()270            jobs[taskId]?.also { cancelled += taskId }271        }272        if (job != null) job.cancel() else markStopped(taskId)273        processQueue()274    }275276    override fun cancelAll() {277        stateLock.withLock { queue.map { it.request.taskId } + jobs.keys }.forEach(::cancel)278    }279280    override fun pause(taskId: String) {281        val job = stateLock.withLock {282            paused += taskId283            active[taskId]?.let { active[taskId] = it.copy(isPaused = true) }284            publishActiveDownloadsLocked()285            jobs[taskId]?.also { requeueOnStop += taskId }286        }287        persistPause(taskId, true)288        // Saved pages keep their markers, so the run after resume only fetches the rest.289        job?.cancel()290        processQueue()291    }292293    override fun resume(taskId: String) {294        val resumed = stateLock.withLock {295            paused.remove(taskId).also { wasPaused ->296                if (wasPaused) active[taskId]?.let { active[taskId] = it.copy(isPaused = false) }297                publishActiveDownloadsLocked()298            }299        }300        if (resumed) {301            persistPause(taskId, false)302            processQueue()303        }304    }305306    private fun persistPause(taskId: String, isPaused: Boolean) {307        val id = stateLock.withLock { taskDownloadIds[taskId] } ?: return308        database.batch {309            database.download(id)?.takeIf { it.isDownload != true }?.let { row ->310                database.upsertDownload(row.copy(isPaused = isPaused))311            }312        }313    }314315    override fun retry(taskId: String): Boolean {316        val request = stateLock.withLock { lastRequests[taskId] }317            ?: persistedDownload(taskId)?.requestJson?.let {318                runCatching { DatabaseJson.decodeFromString<DownloadRequest>(it) }.getOrNull()319            }320            ?: taskId.chapterIdOrNull()?.let { chapterDownloadRequest(database, it) }321            ?: return false322        return queueTask(request, onProgress = {}, knownLocation = storageLocation(taskId))323    }324325    private fun persistedDownload(taskId: String): DbDownload? {326        stateLock.withLock { taskDownloadIds[taskId] }?.let(database::download)?.let { return it }327        return database.downloads().firstOrNull { row ->328            downloadTaskId(row.chapterId, row.id) == taskId || row.requestJson?.let { json ->329                runCatching { DatabaseJson.decodeFromString<DownloadRequest>(json).taskId == taskId }.getOrDefault(false)330            } == true331        }332    }333334    override fun storageLocation(taskId: String): String? {335        stateLock.withLock { taskStorageLocations.containsKey(taskId) to taskStorageLocations[taskId] }336            .let { (known, location) -> if (known) return location }337        val persisted = persistedDownload(taskId)?.storageLocation338        if (!persisted.isNullOrBlank()) return persisted339        val found = derivedStorageLocations(taskId).firstOrNull { files.exists(it) || files.exists("$it.cbz") }340        return stateLock.withLock {341            if (taskId in taskStorageLocations) taskStorageLocations[taskId] else found.also { taskStorageLocations[taskId] = it }342        }343    }344345    override fun deleteArtifacts(taskId: String) {346        val known = stateLock.withLock { taskStorageLocations.remove(taskId) }347        val locations = known?.let(::listOf) ?: derivedStorageLocations(taskId)348        locations.filter { it.isNotBlank() }.forEach { location ->349            files.deleteRecursively(location)350            files.deleteRecursively("$location.cbz")351            files.deleteRecursively("${location}_subtitles")352        }353    }354355    override suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit): Boolean {356        val worker = stateLock.withLock { jobs[taskId] }357        cancel(taskId)358        worker?.join()359        return deleteManagedArtifacts(taskId, completedOnly = false, stillEligible = { true }, onDeleted)360    }361362    override suspend fun deleteCompletedArtifacts(taskId: String, stillEligible: () -> Boolean, onDeleted: () -> Unit): Boolean =363        deleteManagedArtifacts(taskId, completedOnly = true, stillEligible, onDeleted)364365    private suspend fun deleteManagedArtifacts(taskId: String, completedOnly: Boolean, stillEligible: () -> Boolean, onDeleted: () -> Unit): Boolean {366        val accepted = stateLock.withLock {367            if (taskId in admitting || taskId in deleting || taskId in jobs || queue.any { it.request.taskId == taskId }) false368            else { deleting += taskId; true }369        }370        if (!accepted) return false371        return try { withContext(ioDispatcher) {372            files.prepare()373            val row = persistedDownload(taskId)374            if (row == null) return@withContext false375            if ((completedOnly && (row.isDownload != true || row.isPaused || row.isStartDownload == true)) || !stillEligible()) return@withContext false376            val locations = listOfNotNull(storageLocation(taskId)).ifEmpty { derivedStorageLocations(taskId) }.distinct()377            val chapter = taskId.chapterIdOrNull()?.let(database::chapter) ?: return@withContext false378            val title = chapter.mangaId?.let(database::manga) ?: return@withContext false379            if ((completedOnly && title.isLocalArchive) || locations.isEmpty() || locations.any { !isManagedChapterLocation(it, title.itemType) }) return@withContext false380            val paths = locations.flatMap { listOf(it, "$it.cbz", "${it}_subtitles") }381            for (path in paths) {382                ensureActive()383                if (!stillEligible()) return@withContext false384                val parent = files.canonicalPath(path.substringBeforeLast('/')) ?: return@withContext false385                val canonical = files.canonicalPath(path) ?: return@withContext false386                if (canonical.replace('\\', '/').trimEnd('/') != "${parent.replace('\\', '/').trimEnd('/')}/${path.substringAfterLast('/')}") return@withContext false387                if (files.exists(path) && (!files.deleteRecursivelyAsync(path) || files.exists(path))) return@withContext false388            }389            stateLock.withLock { taskStorageLocations.remove(taskId) }390            // Keep the task reservation through the database commit; a retry cannot recreate files391            // between deletion and clearing the old download row.392            onDeleted()393            true394        } } finally { stateLock.withLock { deleting.remove(taskId) } }395    }396397    /** Refuse root/title folders and traversal even if an imported manifest has a bad path. */398    private fun isManagedChapterLocation(location: String, type: DbItemType): Boolean {399        val path = location.replace('\\', '/').trimEnd('/')400        val segments = path.split('/')401        val marker = segments.indexOfLast { it == downloadItemTypeFolder(type) }402        return marker >= 0 && segments.size - marker == 4 &&403            segments.none { it == "." || it == ".." } && segments.takeLast(3).none { it.isBlank() }404    }405406    /**407     * Where a chapter download from an earlier session lives: the chapter's recorded download path, then the408     * folder [enqueue] would build from its chapter and title rows under every root a download may target.409     */410    private fun derivedStorageLocations(taskId: String): List<String> {411        val chapterId = taskId.chapterIdOrNull() ?: return emptyList()412        val chapter = database.chapter(chapterId) ?: return emptyList()413        val manga = chapter.mangaId?.let(database::manga) ?: return emptyList()414        val source = manga.sourceId?.let(database::source)415        val sourceLabel = downloadSourceLabel(source?.name, source?.lang, manga.source.orEmpty())416        val settings = database.settings()417        // ponytail: a one-off destinationRoot outside these roots is only known in-session (taskStorageLocations).418        val roots = settings.configuredLocalFolders().map { it.path } + settings.downloadLocation + files.downloadRoot419        val recorded = chapter.archivePath.takeIf { it.isNotBlank() && !manga.isLocalArchive }?.removeSuffix(".cbz")420        return listOfNotNull(recorded) + roots.filter { it.isNotBlank() }421            .map { downloadStorageRoot(it, files) }422            .distinct()423            .map { root ->424                downloadChapterLocation(425                    root,426                    manga.itemType,427                    sourceLabel,428                    manga.name.orEmpty(),429                    chapter.scanlator,430                    chapter.name.orEmpty(),431                )432            }433    }434435    override fun activeDownloads(): List<DownloadProgress> = stateLock.withLock { active.values.toList() }436437    override fun reorderQueue(order: List<Long>) {438        stateLock.withLock {439            manualQueueOrder = order440            reorderQueueInternal(order)441        }442        processQueue()443    }444445    private fun reorderQueueInternal(order: List<Long>) {446        if (order.isEmpty() || queue.size < 2) return447        val rank = order.withIndex().associate { it.value to it.index }448        val indexed = queue.withIndex().toList()449        val sorted = indexed.sortedWith { a, b ->450            val ra = rank[a.value.downloadId] ?: (order.size + a.index)451            val rb = rank[b.value.downloadId] ?: (order.size + b.index)452            ra.compareTo(rb)453        }.map { it.value }454        queue.clear()455        queue.addAll(sorted)456    }457458    /**459     * Starts queued chapters up to the concurrency limit, unless the network is held, and publishes460     * [queueStatus]. Once work waits for Wi-Fi, one notification shows and a watcher resumes the queue.461     */462    private fun processQueue() {463        val toStart = stateLock.withLock {464            val settings = database.settings()465            val effectiveOrder = if (manualQueueOrder.isNotEmpty()) manualQueueOrder else settings.downloadQueueOrder466            reorderQueueInternal(effectiveOrder)467            val maxConcurrent = if (settings.allowConcurrentDownloads) {468                settings.concurrentDownloads.coerceAtLeast(1)469            } else {470                1471            }472            val held = isNetworkHeld()473            buildList {474                while (!held && running < maxConcurrent) {475                    val index = queue.indexOfFirst { it.request.taskId !in paused && it.sourceKey !in activeSources }476                    if (index < 0) break477                    val task = queue.removeAt(index)478                    activeSources += task.sourceKey479                    running += 1480                    add(worker(task).also { jobs[task.request.taskId] = it })481                }482                val pending = running + queue.count { it.request.taskId !in paused }483                val status = DownloadQueueStatus(pending, waitingForWifi = held && pending > 0)484                // Under the lock, so the notification always matches the last published status.485                if (status.waitingForWifi != _queueStatus.value.waitingForWifi) {486                    notifyWaitingForWifi(status.waitingForWifi)487                    if (status.waitingForWifi) add(releaseWatcher())488                }489                _queueStatus.value = status490            }491        }492        toStart.forEach(Job::start)493    }494495    private fun isNetworkHeld(): Boolean = database.settings().downloadOnlyOnWifi && !network.unmetered.value496497    /** Waits while the network is held, so a running chapter stops at its next page and continues on Wi-Fi. */498    private suspend fun awaitAllowedNetwork() {499        if (!isNetworkHeld()) return500        processQueue() // Publishes the wait: the screen label, the notification and the release watcher.501        networkHeld.first { !it }502    }503504    /** Resumes the queue once Wi-Fi returns or Wi-Fi-only is turned off; ends when nothing waits any more. */505    private fun releaseWatcher(): Job = scope.launch(start = CoroutineStart.LAZY) {506        while (_queueStatus.value.waitingForWifi) {507            networkHeld.first { !it }508            processQueue()509        }510    }511512    private fun notifyWaitingForWifi(waiting: Boolean) {513        runCatching {514            if (waiting) {515                notifications?.notify(516                    NotificationPayload(517                        channel = NotificationChannel.Downloads,518                        title = "Downloads waiting for Wi-Fi",519                        message = "They continue on Wi-Fi. Turn off Only on Wi-Fi in download settings to use mobile data.",520                        tag = WAITING_FOR_WIFI_NOTIFICATION_TAG,521                    ),522                )523            } else {524                notifications?.cancel(NotificationChannel.Downloads, WAITING_FOR_WIFI_NOTIFICATION_TAG)525            }526        }527    }528529    /** The task's worker, created lazily so it is registered in [jobs] before it can run or finish. */530    private fun worker(task: QueuedDownload): Job {531        val taskId = task.request.taskId532        return scope.launch(start = CoroutineStart.LAZY) {533            try {534                runDownload(task)535            } catch (stop: CancellationException) {536                // A stray timeout from deeper code is a failure; only a stopped worker ends silently.537                if (!isActive) throw stop538                AppLogger.error("[download] $taskId failed: ${stop.message.orEmpty()}")539                finishFailed(task, PageTally(0))540            } catch (error: Throwable) {541                AppLogger.error("[download] $taskId failed: ${error.message.orEmpty()}")542                finishFailed(task, PageTally(0))543            } finally {544                // A pause that lands while the chapter is being finished must not queue it again.545                val finished = database.download(task.downloadId)?.isDownload == true546                val userCancelled = stateLock.withLock {547                    jobs.remove(taskId)548                    running = (running - 1).coerceAtLeast(0)549                    activeSources.remove(task.sourceKey)550                    if (requeueOnStop.remove(taskId) && !finished) {551                        queue.addFirst(task)552                        false553                    } else {554                        active.remove(taskId)555                        publishActiveDownloadsLocked()556                        cancelled.remove(taskId)557                    }558                }559                // Written after the worker has stopped so no late progress write can mark the row started again.560                if (userCancelled) markStopped(taskId)561                processQueue()562            }563        }564    }565566    private fun markStopped(taskId: String) {567        val downloadId = stateLock.withLock { taskDownloadIds[taskId] } ?: return568        database.batch {569            val download = database.download(downloadId) ?: return@batch570            val chapterId = download.chapterId ?: return@batch571            val chapter = database.chapter(chapterId) ?: return@batch572            if (chapter.mangaId?.let(database::manga) == null) return@batch573            database.upsertDownload(download.copy(isStartDownload = false, isPaused = false))574        }575    }576577    private suspend fun runDownload(task: QueuedDownload) {578        files.prepare()579        val request = task.request580        val delayMs = downloadStartDelayMs(database.settings().downloadDelaySeconds)581        if (delayMs > 0L) delay(delayMs)582        report(task, PageTally(0), persist = false)583        if (request.itemType == DbItemType.Novel && resolveNovelText != null) {584            val text = catchingNonCancellation {585                withTimeoutOrNull(DOWNLOAD_PREPARATION_TIMEOUT_MS) { resolveNovelText.invoke(request.chapterId) }586                    ?.takeIf(String::isNotBlank) ?: error("No novel text resolved")587            }.getOrElse { return finishFailed(task, PageTally(1), "Failed loading novel text") }588            val target = "${task.location}/0001.html"589            withContext(ioDispatcher) {590                val partial = "$target.part"591                files.writeBytesAsync(partial, text.encodeToByteArray())592                check(pageTransfer.promoteWithMarker(partial, target, "$target.complete")) { "Cannot save novel text" }593            }594            val tally = PageTally(1).apply { succeeded = 1; bytes = text.encodeToByteArray().size.toLong() }595            return finishCompleted(task, tally)596        }597        var pages = resolvedPages(request.chapterId, forceRefresh = false)598            ?: run {599                AppLogger.warn("[download] ${request.taskId} failed: no pages resolved")600                return finishFailed(task, PageTally(0), "Failed loading pages for ${request.chapterName.ifBlank { "chapter" }}")601            }602        var refreshed = false603        var tally = PageTally(pages.size)604        while (true) {605            report(task, tally, persist = true)606            val splitHeight = database.settings().features.downloads.takeIf { request.itemType == DbItemType.Manga && it.splitTallImages }?.splitImageHeight607            val saved = withContext(ioDispatcher) { pageTransfer.savedPages(task.location, pages.size, splitHeight) }608            val expired = downloadPages(task, tally, pages, pages.indices, saved, countExpired = refreshed)609            if (expired.isEmpty()) break610            refreshed = true611            val fresh = resolvedPages(request.chapterId, forceRefresh = true)612            when {613                fresh == null -> expired.forEach { recordPage(task, tally, saved = false) }614                // The chapter changed: start over. Saved pages are kept by index, extra indices are dropped.615                // ponytail: a source that inserts a page mid-chapter shifts the kept ones; clear all markers if that shows up.616                fresh.size != pages.size -> {617                    pages = fresh618                    tally = PageTally(fresh.size)619                    continue620                }621                else -> {622                    pages = fresh623                    downloadPages(task, tally, pages, expired, emptyMap(), countExpired = true)624                }625            }626            break627        }628        downloadSubtitles(task, tally)629        if (tally.failed > 0 || tally.succeeded < tally.total) {630            AppLogger.warn("[download] ${request.taskId} failed: ${tally.succeeded}/${tally.total} pages saved, ${tally.failed} failed")631            return finishFailed(task, tally)632        }633        finishCompleted(task, tally)634    }635636    /** The chapter's pages, else null (logged) when they can't be resolved or there are none. */637    private suspend fun resolvedPages(chapterId: Long, forceRefresh: Boolean): List<DbPageUrl>? =638        catchingNonCancellation {639            withTimeoutOrNull(DOWNLOAD_PREPARATION_TIMEOUT_MS) { resolvePages(chapterId, forceRefresh) }640                ?: error("Timed out loading pages")641        }.onFailure { AppLogger.warn("[download] resolving pages of chapter $chapterId failed: ${it.message.orEmpty()}") }642            .getOrNull()643            ?.takeIf { it.isNotEmpty() }644645    /**646     * Downloads [indices] of [pages], [PAGE_PARALLELISM] at a time, counting pages found in [saved] without647     * fetching them. Returns the indices whose URL looked expired, uncounted, unless [countExpired].648     */649    private suspend fun downloadPages(650        task: QueuedDownload,651        tally: PageTally,652        pages: List<DbPageUrl>,653        indices: Iterable<Int>,654        saved: Map<Int, Long>,655        countExpired: Boolean,656    ): List<Int> {657        val permits = Semaphore(PAGE_PARALLELISM)658        val expired = mutableListOf<Int>()659        coroutineScope {660            indices.forEach { index ->661                launch {662                    permits.withPermit {663                        saved[index]?.let { size -> return@withPermit recordPage(task, tally, saved = true, bytes = size) }664                        var bytes = 0L665                        val status = pageTransfer.downloadPage(task.request, task.location, task.transferPermits, pages[index], index, onBytes = { bytes += it }, onTransfer = { current ->666                            stateLock.withLock {667                                tally.inFlightBytes[index] = current668                                val now = nowMillis()669                                if (now - tally.lastProgressAt >= 200) {670                                    tally.lastProgressAt = now671                                    publishLocked(task, tally)672                                }673                            }674                        })675                        stateLock.withLock { tally.inFlightBytes.remove(index) }676                        when {677                            status == null -> recordPage(task, tally, saved = true, bytes = bytes)678                            status in ExpiredPageStatuses && !countExpired -> stateLock.withLock { expired += index }679                            else -> recordPage(task, tally, saved = false)680                        }681                    }682                }683            }684        }685        return expired.sorted()686    }687688    private suspend fun downloadSubtitles(task: QueuedDownload, tally: PageTally) {689        task.request.subtitles.forEachIndexed { index, sub ->690            if (sub.file.isBlank()) return@forEachIndexed691            val subtitlePath = "${task.location}_subtitles/${index.toString().padStart(2, '0')}_${sub.label.ifBlank { "subtitle" }}.${sub.file.substringAfterLast('.', "srt").lowercase()}"692            catchingNonCancellation {693                val response = withTimeoutOrNull(DOWNLOAD_CONNECTION_TIMEOUT_MS) { http.request(HttpRequest(url = sub.file)) }694                if (response != null && response.statusCode in 200..299 && response.bodyBytes.isNotEmpty()) {695                    withContext(ioDispatcher) { files.writeBytesAsync(subtitlePath, response.bodyBytes) }696                    stateLock.withLock { tally.bytes += response.bodyBytes.size }697                }698            }699        }700    }701702    /** Not cancellable: once the pages are in, a pause or cancel can't leave a zipped chapter unmarked. */703    private suspend fun finishCompleted(task: QueuedDownload, tally: PageTally) = withContext(NonCancellable) {704        val request = task.request705        val archive = withContext(ioDispatcher) {706            writeMetadata(files, request, task.location)707            writeTitleMetadata(files, http, request, task.location.substringBeforeLast('/', task.location))708            if (!shouldArchiveChapter(request)) return@withContext null709            runCatching { archives.zipDirectoryToCbzAsync(task.location, deleteSource = true) }710                .onSuccess { path -> path?.let { AppLogger.info("[download] CBZ created for ${request.mangaName} chapter ${request.chapterName}: $it") } }711                .onFailure { AppLogger.warn("[download] CBZ failed for ${request.taskId}, keeping the folder: ${it.message.orEmpty()}") }712                .getOrNull()713        }714        files.awaitPersistence()715        // The reader and chapter list read this mark; deleting the download clears it (clearChapterDownloads).716        // The mark stays on this device: sync and backup restore treat it as device-local (SyncPaths, BackupService).717        setDownloadMark(request.chapterId, archive ?: task.location, downloadSizeLabel(tally.bytes))718        report(task, tally, persist = true, complete = true)719        AppLogger.info("[download] ${request.taskId} completed: ${tally.succeeded} pages, ${downloadSizeLabel(tally.bytes)}")720        notify(request, request.mangaName.ifBlank { "Download finished" }, "${request.chapterName.ifBlank { "Chapter" }} • ${tally.succeeded} pages")721        stateLock.withLock {722            active.remove(request.taskId)723            lastRequests.remove(request.taskId)724            publishActiveDownloadsLocked()725        }726        onCompleted(request.chapterId)727    }728729    private fun finishFailed(730        task: QueuedDownload,731        tally: PageTally,732        message: String = "Failed downloading ${task.request.chapterName.ifBlank { "chapter" }}",733    ) {734        val progress = stateLock.withLock {735            tally.failed = tally.failed.coerceAtLeast(1)736            publishLocked(task, tally)737        }738        database.batch {739            val chapter = database.chapter(task.request.chapterId) ?: return@batch740            if (chapter.mangaId?.let(database::manga) == null) return@batch741            database.download(task.downloadId)?.let { download ->742                database.upsertDownload(743                    download.copy(744                        succeeded = progress.succeeded,745                        failed = progress.failed,746                        total = progress.total,747                        isDownload = false,748                        isStartDownload = false,749                    ),750                )751            }752        }753        runCatching { task.onProgress(progress) }754            .onFailure { AppLogger.warn("Download progress callback failed: ${it.message.orEmpty()}") }755        notify(task.request, task.request.mangaName.ifBlank { "Download failed" }, message)756        stateLock.withLock {757            active.remove(task.request.taskId)758            publishActiveDownloadsLocked()759        }760    }761762    private fun notify(request: DownloadRequest, title: String, message: String) {763        runCatching {764            notifications?.notify(765                NotificationPayload(766                    channel = NotificationChannel.Downloads,767                    title = title,768                    message = message,769                    tag = request.taskId,770                ),771            )772        }773    }774775    private fun setDownloadMark(chapterId: Long, archivePath: String, downloadSize: String?) {776        database.batch {777            val chapter = database.chapter(chapterId) ?: return@batch778            if (chapter.mangaId?.let(database::manga) == null) return@batch779            database.upsertChapter(chapter.copy(archivePath = archivePath, downloadSize = downloadSize, updatedAt = nowMillis()))780        }781    }782783    private fun shouldArchiveChapter(request: DownloadRequest): Boolean =784        request.itemType == DbItemType.Manga && database.settings().saveAsCBZArchive785786    /** Publishes [tally] as the task's live progress; the caller holds [stateLock]. */787    private fun publishLocked(task: QueuedDownload, tally: PageTally, complete: Boolean = false, force: Boolean = true): DownloadProgress {788        val progress = DownloadProgress(789            taskId = task.request.taskId,790            succeeded = tally.succeeded,791            failed = tally.failed,792            total = tally.total,793            itemType = task.request.itemType,794            isCompleted = complete || (tally.total > 0 && tally.succeeded + tally.failed >= tally.total),795            isPaused = task.request.taskId in paused,796            storageLocation = task.location,797            bytesDownloaded = tally.bytes + tally.inFlightBytes.values.sum(),798            mangaName = task.request.mangaName,799            chapterName = task.request.chapterName,800        )801        active[task.request.taskId] = progress802        val now = nowMillis()803        if (force || progress.isCompleted || now - tally.lastProgressAt >= 200) {804            tally.lastProgressAt = now805            publishActiveDownloadsLocked()806        }807        return progress808    }809810    private fun report(task: QueuedDownload, tally: PageTally, persist: Boolean, complete: Boolean = false) {811        val progress = stateLock.withLock { publishLocked(task, tally, complete) }812        if (persist) persistProgress(task, progress, complete)813        runCatching { task.onProgress(progress) }814            .onFailure { AppLogger.warn("Download progress callback failed: ${it.message.orEmpty()}") }815    }816817    /** Counts one page; the row is written on the persist interval and on the chapter's first failure. */818    private fun recordPage(task: QueuedDownload, tally: PageTally, saved: Boolean, bytes: Long = 0L) {819        val progress = stateLock.withLock {820            if (saved) tally.succeeded += 1 else tally.failed += 1821            tally.bytes += bytes822            publishLocked(task, tally, force = !saved)823        }824        val processed = progress.succeeded + progress.failed825        if (processed % PROGRESS_PERSIST_INTERVAL == 0 || (!saved && progress.failed == 1)) {826            persistProgress(task, progress, complete = false)827        }828        runCatching { task.onProgress(progress) }829            .onFailure { AppLogger.warn("Download progress callback failed: ${it.message.orEmpty()}") }830    }831832    private fun persistProgress(task: QueuedDownload, progress: DownloadProgress, complete: Boolean) {833        database.batch {834            val chapter = database.chapter(task.request.chapterId) ?: return@batch835            if (chapter.mangaId?.let(database::manga) == null) return@batch836            database.download(task.downloadId)?.let { download ->837                database.upsertDownload(838                    download.copy(839                        succeeded = progress.succeeded,840                        failed = progress.failed,841                        total = progress.total,842                        isDownload = complete,843                        isStartDownload = !progress.isCompleted,844                        isPaused = !complete && download.isPaused,845                    ),846                )847            }848        }849    }850851    private fun publishActiveDownloadsLocked() {852        _activeDownloadProgress.update { active.values.sortedBy(DownloadProgress::taskId) }853    }854855    private fun resolveStorageLocation(request: DownloadRequest): String {856        val customRoot = request.destinationRoot857            ?.takeIf { it.isNotBlank() }858            ?: database.settings().downloadLocation.takeIf { it.isNotBlank() }859            ?: files.downloadRoot860        return downloadChapterLocation(861            downloadStorageRoot(customRoot, files),862            request.itemType,863            request.sourceLabel,864            request.mangaName,865            request.scanlator,866            request.chapterName,867        )868    }869870    private fun String.chapterIdOrNull(): Long? = removePrefix("chapter-").takeIf { it != this }?.toLongOrNull()871872    private companion object {873        const val PROGRESS_PERSIST_INTERVAL = 5874    }875}876877/** Transient statuses worth retrying; any other 4xx fails at once. */878internal fun isRetryableDownloadStatus(status: Int): Boolean = status == 408 || status == 429 || status in 500..599879880private const val RETRY_BASE_DELAY_MS = 1_000L881882private const val MAX_RETRY_AFTER_MS = 60_000L883884/**885 * Wait before retry [attempt] (1-based): the server's Retry-After seconds when sent (capped at a minute),886 * else exponential backoff from one second with equal jitter.887 */888internal fun downloadRetryDelayMs(attempt: Int, retryAfter: String?, random: Random = Random.Default): Long {889    // ponytail: an HTTP-date Retry-After falls back to backoff; parse it if a CDN sends one.890    retryAfter?.trim()?.toLongOrNull()?.let { seconds -> return (seconds * 1_000L).coerceIn(0L, MAX_RETRY_AFTER_MS) }891    val base = RETRY_BASE_DELAY_MS shl (attempt - 1).coerceIn(0, 6)892    return base / 2 + random.nextLong(base / 2 + 1)893}894895private const val BYTES_PER_MIB = 1_048_576L896897/** Size shown next to a downloaded chapter, e.g. `12.3 MB`. */898internal fun downloadSizeLabel(bytes: Long): String {899    val tenths = (bytes.coerceAtLeast(0L) * 10 + BYTES_PER_MIB / 2) / BYTES_PER_MIB900    return "${tenths / 10}.${tenths % 10} MB"901}902903internal fun resolveDownloadSourceKey(904    request: DownloadRequest,905    downloadId: Long = 0L,906    database: YokanDatabase? = null,907): String {908    if (request.sourceId != null && request.sourceId > 0L) {909        return "source-${request.sourceId}"910    }911    if (database != null && request.chapterId > 0L) {912        val chapter = database.chapter(request.chapterId)913        val manga = chapter?.mangaId?.let { database.manga(it) }914        if (manga != null) {915            val sId = manga.sourceId916            val source = manga.source917            if (sId != null && sId > 0L) return "source-$sId"918            if (!source.isNullOrBlank()) return "source-${source.trim()}|${manga.lang.orEmpty()}"919        }920    }921    if (request.sourceLabel.isNotBlank()) {922        return "source-${request.sourceLabel.trim()}"923    }924    return if (downloadId > 0L) "download-$downloadId" else request.taskId.ifBlank { "download-${request.chapterId}" }925}926927internal fun downloadStartDelayMs(928    baseSeconds: Int,929    random: kotlin.random.Random = kotlin.random.Random.Default,930): Long {931    if (baseSeconds <= 0) return 0L932    val base = baseSeconds * 1000L933    val jitter = (base * (0.25 + random.nextDouble() * 0.75)).toLong()934    return base + jitter935}936

Search chapters, reference and source filenames.