package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.database.DatabaseJson import eu.friedcutlet.yokan.database.DbDownload import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.database.configuredLocalFolders import eu.friedcutlet.yokan.services.blockingDispatcher import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.files.LocalArchiveService import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService 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.services.system.NetworkMonitor import eu.friedcutlet.yokan.services.system.UnmeteredNetwork import eu.friedcutlet.yokan.util.PlatformLock import eu.friedcutlet.yokan.util.nowMillis import kotlin.random.Random import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import eu.friedcutlet.yokan.services.files.downloadItemTypeFolder internal const val DOWNLOAD_CONNECTION_TIMEOUT_MS = 30_000L internal const val DOWNLOAD_PREPARATION_TIMEOUT_MS = 45_000L /** Pages of one chapter fetched at once; chapters of one source still download one at a time. */ internal const val PAGE_PARALLELISM = 3 /** Page statuses that mean the URL expired or moved: the chapter's pages are re-resolved once. */ private val ExpiredPageStatuses = setOf(401, 403, 404, 410) /** Tag of the single "waiting for Wi-Fi" notification, however many chapters wait. */ internal const val WAITING_FOR_WIFI_NOTIFICATION_TAG = "downloads-waiting-for-wifi" class PersistentDownloadService( private val database: YokanDatabase, private val http: HttpService, private val files: LocalFileService, private val archives: LocalArchiveService, /** Owner-provided; download workers live and die with it. */ private val scope: CoroutineScope, /** A chapter's pages, resolved when its download starts; `forceRefresh` skips any saved list. */ private val resolvePages: suspend (chapterId: Long, forceRefresh: Boolean) -> List, private val notifications: NotificationService? = null, /** With Wi-Fi-only on, the queue waits while this reports a metered network. */ private val network: NetworkMonitor = UnmeteredNetwork, /** Blocking file work: page writes, promotion, metadata and CBZ zipping. */ private val ioDispatcher: CoroutineDispatcher = blockingDispatcher, private val resolveNovelText: (suspend (chapterId: Long) -> String)? = null, private val onCompleted: (chapterId: Long) -> Unit = {}, private val imageDataSaver: ImageDataSaver? = null, imageHttp: HttpService = http, ) : DownloadService { private val pageTransfer = PageTransfer(database, http, files, imageHttp, imageDataSaver, ioDispatcher, awaitAllowedNetwork = { awaitAllowedNetwork() }) private val _activeDownloadProgress = MutableStateFlow>(emptyList()) override val activeDownloadProgress = _activeDownloadProgress.asStateFlow() private val _queueStatus = MutableStateFlow(DownloadQueueStatus()) override val queueStatus = _queueStatus.asStateFlow() /** True while Wi-Fi-only is on and the network is metered: nothing starts and running chapters wait at their next page. */ private val networkHeld: Flow = combine(network.unmetered, database.snapshots().map { it.settings.downloadOnlyOnWifi }) { unmetered, wifiOnly -> wifiOnly && !unmetered } private data class QueuedDownload( val request: DownloadRequest, val downloadId: Long, val onProgress: (DownloadProgress) -> Unit, val location: String, val sourceKey: String, val transferPermits: Semaphore = Semaphore(PAGE_PARALLELISM), ) /** Page counts of one chapter run; mutated only under [stateLock]. */ private class PageTally(val total: Int) { var succeeded = 0 var failed = 0 var bytes = 0L val inFlightBytes = mutableMapOf() var lastProgressAt = 0L } private val stateLock = PlatformLock() private val queue = ArrayDeque() private val jobs = mutableMapOf() private val active = mutableMapOf() /** Download row per task, indexed once at start so [enqueue] never scans every row. */ private val taskDownloadIds = mutableMapOf() /** Known or derived file locations; a null value caches "no files found". */ // ponytail: files removed outside the app keep their cached location until restart. private val taskStorageLocations = mutableMapOf() /** Running tasks the user cancelled; their row is marked stopped once the worker has ended. */ private val cancelled = mutableSetOf() private val paused = mutableSetOf() /** Running tasks stopped by [pause]; they return to the front of the queue once the worker has ended. */ private val requeueOnStop = mutableSetOf() private val lastRequests = mutableMapOf() private val activeSources = mutableSetOf() private val deleting = mutableSetOf() private val admitting = mutableSetOf() private var running = 0 private var initialized = false private var manualQueueOrder: List = emptyList() override suspend fun initialize(poolSize: Int) = ensureInitialized() /** * Indexes the download rows once and re-queues the ones a previous session left started; rows that * can't be rebuilt (chapter gone) become retryable instead. */ private fun ensureInitialized() { val interrupted = stateLock.withLock { if (initialized) return@withLock emptyList() initialized = true database.downloads().filter { download -> taskDownloadIds[downloadTaskId(download.chapterId, download.id)] = download.id download.isStartDownload == true && download.isDownload != true } } interrupted.forEach { download -> val request = download.requestJson?.let { json -> runCatching { DatabaseJson.decodeFromString(json) }.getOrNull() ?.takeIf { it.chapterId == download.chapterId } } ?: download.chapterId?.let { chapterDownloadRequest(database, it) } val queued = request != null && runCatching { queueTask(request, onProgress = {}, knownLocation = download.storageLocation ?: storageLocation(request.taskId), initiallyPaused = download.isPaused, deferStart = true) } .onFailure { AppLogger.warn("[download] could not resume ${request.taskId}: ${it.message.orEmpty()}") } .getOrDefault(false) if (!queued) database.batch { val chapterId = download.chapterId ?: return@batch val chapter = database.chapter(chapterId) ?: return@batch if (chapter.mangaId?.let(database::manga) == null) return@batch database.download(download.id)?.let { current -> database.upsertDownload(current.copy(isStartDownload = false, isPaused = false)) } } } if (interrupted.isNotEmpty()) processQueue() } override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) { queueTask(request, onProgress, knownLocation = null) } /** * Records and queues [request] before returning, so the queue keeps call order; with Wi-Fi-only on a * metered network it waits in the queue. False when it was skipped: already queued or running, or * already downloaded. */ private fun queueTask( request: DownloadRequest, onProgress: (DownloadProgress) -> Unit, knownLocation: String?, initiallyPaused: Boolean = false, deferStart: Boolean = false, ): Boolean { ensureInitialized() val taskId = request.taskId.ifBlank { downloadTaskId(request.chapterId, 0) } val location = knownLocation ?: resolveStorageLocation(request) // SAF tree grants are read-only here (AndroidSafLocalFileService), so every page would fail. require(!location.startsWith("content://")) { "Downloads can't be saved to a folder picked through the system file picker. Choose another download folder in settings." } val admitted = stateLock.withLock { if (taskId in admitting || taskId in deleting || taskId in jobs || queue.any { it.request.taskId == taskId }) false else { admitting += taskId; true } } if (!admitted) return false try { val validated = database.batch { val chapter = database.chapter(request.chapterId) ?: return@batch null val manga = chapter.mangaId?.let(database::manga) ?: return@batch null val sourceIds = listOfNotNull(manga.sourceId, request.sourceId?.takeIf { it > 0L }).distinct() if (sourceIds.any { database.source(it) == null }) return@batch null val existing = database.downloads().firstOrNull { it.chapterId == chapter.id } existing to Unit } ?: return false if (isAlreadyDownloaded(validated.first, location)) return false val admission = database.batch { val chapter = database.chapter(request.chapterId) ?: return@batch null val manga = chapter.mangaId?.let(database::manga) ?: return@batch null val sourceIds = listOfNotNull(manga.sourceId, request.sourceId?.takeIf { it > 0L }).distinct() if (sourceIds.any { database.source(it) == null }) return@batch null val existing = database.downloads().firstOrNull { it.chapterId == chapter.id } val row = database.upsertDownload( DbDownload( id = existing?.id ?: 0, chapterId = chapter.id, succeeded = 0, failed = 0, total = existing?.total, isDownload = false, isStartDownload = true, isPaused = initiallyPaused, storageLocation = location, requestJson = DatabaseJson.encodeToString(request.copy(taskId = taskId)), ), ) row } ?: return false val normalized = request.copy(taskId = taskId) val download = admission val task = QueuedDownload(normalized, download.id, onProgress, location, resolveDownloadSourceKey(normalized, download.id, database)) val registered = stateLock.withLock { if (taskId in deleting || taskId in jobs || queue.any { it.request.taskId == taskId }) return@withLock false taskDownloadIds[taskId] = download.id taskStorageLocations[taskId] = location lastRequests[taskId] = normalized if (initiallyPaused) { paused += taskId active[taskId] = DownloadProgress(taskId, 0, 0, download.total ?: 0, request.itemType, isPaused = true, storageLocation = location) publishActiveDownloadsLocked() } else paused.remove(taskId) queue += task true } if (!registered) return false if (!deferStart) processQueue() return true } finally { stateLock.withLock { admitting.remove(taskId) } } } /** * True when [existing] finished and its files are still there; its chapter is re-marked in case the mark * was cleared (e.g. by a backup restore). A finished row whose files are gone loses its stale mark. */ private fun isAlreadyDownloaded(existing: DbDownload?, location: String): Boolean { if (existing?.isDownload != true) return false val chapter = existing.chapterId?.let(database::chapter) ?: return false val path = listOf(chapter.archivePath, location, "$location.cbz").firstOrNull { it.isNotBlank() && files.exists(it) } when { path == null -> if (chapter.archivePath.isNotBlank() || chapter.downloadSize != null) setDownloadMark(chapter.id, "", null) chapter.archivePath.isBlank() -> setDownloadMark(chapter.id, path, downloadSizeLabel(files.directorySize(path))) } return path != null } override fun cancel(taskId: String) { val job = stateLock.withLock { queue.removeAll { it.request.taskId == taskId } paused.remove(taskId) requeueOnStop.remove(taskId) active.remove(taskId) publishActiveDownloadsLocked() jobs[taskId]?.also { cancelled += taskId } } if (job != null) job.cancel() else markStopped(taskId) processQueue() } override fun cancelAll() { stateLock.withLock { queue.map { it.request.taskId } + jobs.keys }.forEach(::cancel) } override fun pause(taskId: String) { val job = stateLock.withLock { paused += taskId active[taskId]?.let { active[taskId] = it.copy(isPaused = true) } publishActiveDownloadsLocked() jobs[taskId]?.also { requeueOnStop += taskId } } persistPause(taskId, true) // Saved pages keep their markers, so the run after resume only fetches the rest. job?.cancel() processQueue() } override fun resume(taskId: String) { val resumed = stateLock.withLock { paused.remove(taskId).also { wasPaused -> if (wasPaused) active[taskId]?.let { active[taskId] = it.copy(isPaused = false) } publishActiveDownloadsLocked() } } if (resumed) { persistPause(taskId, false) processQueue() } } private fun persistPause(taskId: String, isPaused: Boolean) { val id = stateLock.withLock { taskDownloadIds[taskId] } ?: return database.batch { database.download(id)?.takeIf { it.isDownload != true }?.let { row -> database.upsertDownload(row.copy(isPaused = isPaused)) } } } override fun retry(taskId: String): Boolean { val request = stateLock.withLock { lastRequests[taskId] } ?: persistedDownload(taskId)?.requestJson?.let { runCatching { DatabaseJson.decodeFromString(it) }.getOrNull() } ?: taskId.chapterIdOrNull()?.let { chapterDownloadRequest(database, it) } ?: return false return queueTask(request, onProgress = {}, knownLocation = storageLocation(taskId)) } private fun persistedDownload(taskId: String): DbDownload? { stateLock.withLock { taskDownloadIds[taskId] }?.let(database::download)?.let { return it } return database.downloads().firstOrNull { row -> downloadTaskId(row.chapterId, row.id) == taskId || row.requestJson?.let { json -> runCatching { DatabaseJson.decodeFromString(json).taskId == taskId }.getOrDefault(false) } == true } } override fun storageLocation(taskId: String): String? { stateLock.withLock { taskStorageLocations.containsKey(taskId) to taskStorageLocations[taskId] } .let { (known, location) -> if (known) return location } val persisted = persistedDownload(taskId)?.storageLocation if (!persisted.isNullOrBlank()) return persisted val found = derivedStorageLocations(taskId).firstOrNull { files.exists(it) || files.exists("$it.cbz") } return stateLock.withLock { if (taskId in taskStorageLocations) taskStorageLocations[taskId] else found.also { taskStorageLocations[taskId] = it } } } override fun deleteArtifacts(taskId: String) { val known = stateLock.withLock { taskStorageLocations.remove(taskId) } val locations = known?.let(::listOf) ?: derivedStorageLocations(taskId) locations.filter { it.isNotBlank() }.forEach { location -> files.deleteRecursively(location) files.deleteRecursively("$location.cbz") files.deleteRecursively("${location}_subtitles") } } override suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit): Boolean { val worker = stateLock.withLock { jobs[taskId] } cancel(taskId) worker?.join() return deleteManagedArtifacts(taskId, completedOnly = false, stillEligible = { true }, onDeleted) } override suspend fun deleteCompletedArtifacts(taskId: String, stillEligible: () -> Boolean, onDeleted: () -> Unit): Boolean = deleteManagedArtifacts(taskId, completedOnly = true, stillEligible, onDeleted) private suspend fun deleteManagedArtifacts(taskId: String, completedOnly: Boolean, stillEligible: () -> Boolean, onDeleted: () -> Unit): Boolean { val accepted = stateLock.withLock { if (taskId in admitting || taskId in deleting || taskId in jobs || queue.any { it.request.taskId == taskId }) false else { deleting += taskId; true } } if (!accepted) return false return try { withContext(ioDispatcher) { files.prepare() val row = persistedDownload(taskId) if (row == null) return@withContext false if ((completedOnly && (row.isDownload != true || row.isPaused || row.isStartDownload == true)) || !stillEligible()) return@withContext false val locations = listOfNotNull(storageLocation(taskId)).ifEmpty { derivedStorageLocations(taskId) }.distinct() val chapter = taskId.chapterIdOrNull()?.let(database::chapter) ?: return@withContext false val title = chapter.mangaId?.let(database::manga) ?: return@withContext false if ((completedOnly && title.isLocalArchive) || locations.isEmpty() || locations.any { !isManagedChapterLocation(it, title.itemType) }) return@withContext false val paths = locations.flatMap { listOf(it, "$it.cbz", "${it}_subtitles") } for (path in paths) { ensureActive() if (!stillEligible()) return@withContext false val parent = files.canonicalPath(path.substringBeforeLast('/')) ?: return@withContext false val canonical = files.canonicalPath(path) ?: return@withContext false if (canonical.replace('\\', '/').trimEnd('/') != "${parent.replace('\\', '/').trimEnd('/')}/${path.substringAfterLast('/')}") return@withContext false if (files.exists(path) && (!files.deleteRecursivelyAsync(path) || files.exists(path))) return@withContext false } stateLock.withLock { taskStorageLocations.remove(taskId) } // Keep the task reservation through the database commit; a retry cannot recreate files // between deletion and clearing the old download row. onDeleted() true } } finally { stateLock.withLock { deleting.remove(taskId) } } } /** Refuse root/title folders and traversal even if an imported manifest has a bad path. */ private fun isManagedChapterLocation(location: String, type: DbItemType): Boolean { val path = location.replace('\\', '/').trimEnd('/') val segments = path.split('/') val marker = segments.indexOfLast { it == downloadItemTypeFolder(type) } return marker >= 0 && segments.size - marker == 4 && segments.none { it == "." || it == ".." } && segments.takeLast(3).none { it.isBlank() } } /** * Where a chapter download from an earlier session lives: the chapter's recorded download path, then the * folder [enqueue] would build from its chapter and title rows under every root a download may target. */ private fun derivedStorageLocations(taskId: String): List { val chapterId = taskId.chapterIdOrNull() ?: return emptyList() val chapter = database.chapter(chapterId) ?: return emptyList() val manga = chapter.mangaId?.let(database::manga) ?: return emptyList() val source = manga.sourceId?.let(database::source) val sourceLabel = downloadSourceLabel(source?.name, source?.lang, manga.source.orEmpty()) val settings = database.settings() // ponytail: a one-off destinationRoot outside these roots is only known in-session (taskStorageLocations). val roots = settings.configuredLocalFolders().map { it.path } + settings.downloadLocation + files.downloadRoot val recorded = chapter.archivePath.takeIf { it.isNotBlank() && !manga.isLocalArchive }?.removeSuffix(".cbz") return listOfNotNull(recorded) + roots.filter { it.isNotBlank() } .map { downloadStorageRoot(it, files) } .distinct() .map { root -> downloadChapterLocation( root, manga.itemType, sourceLabel, manga.name.orEmpty(), chapter.scanlator, chapter.name.orEmpty(), ) } } override fun activeDownloads(): List = stateLock.withLock { active.values.toList() } override fun reorderQueue(order: List) { stateLock.withLock { manualQueueOrder = order reorderQueueInternal(order) } processQueue() } private fun reorderQueueInternal(order: List) { if (order.isEmpty() || queue.size < 2) return val rank = order.withIndex().associate { it.value to it.index } val indexed = queue.withIndex().toList() val sorted = indexed.sortedWith { a, b -> val ra = rank[a.value.downloadId] ?: (order.size + a.index) val rb = rank[b.value.downloadId] ?: (order.size + b.index) ra.compareTo(rb) }.map { it.value } queue.clear() queue.addAll(sorted) } /** * Starts queued chapters up to the concurrency limit, unless the network is held, and publishes * [queueStatus]. Once work waits for Wi-Fi, one notification shows and a watcher resumes the queue. */ private fun processQueue() { val toStart = stateLock.withLock { val settings = database.settings() val effectiveOrder = if (manualQueueOrder.isNotEmpty()) manualQueueOrder else settings.downloadQueueOrder reorderQueueInternal(effectiveOrder) val maxConcurrent = if (settings.allowConcurrentDownloads) { settings.concurrentDownloads.coerceAtLeast(1) } else { 1 } val held = isNetworkHeld() buildList { while (!held && running < maxConcurrent) { val index = queue.indexOfFirst { it.request.taskId !in paused && it.sourceKey !in activeSources } if (index < 0) break val task = queue.removeAt(index) activeSources += task.sourceKey running += 1 add(worker(task).also { jobs[task.request.taskId] = it }) } val pending = running + queue.count { it.request.taskId !in paused } val status = DownloadQueueStatus(pending, waitingForWifi = held && pending > 0) // Under the lock, so the notification always matches the last published status. if (status.waitingForWifi != _queueStatus.value.waitingForWifi) { notifyWaitingForWifi(status.waitingForWifi) if (status.waitingForWifi) add(releaseWatcher()) } _queueStatus.value = status } } toStart.forEach(Job::start) } private fun isNetworkHeld(): Boolean = database.settings().downloadOnlyOnWifi && !network.unmetered.value /** Waits while the network is held, so a running chapter stops at its next page and continues on Wi-Fi. */ private suspend fun awaitAllowedNetwork() { if (!isNetworkHeld()) return processQueue() // Publishes the wait: the screen label, the notification and the release watcher. networkHeld.first { !it } } /** Resumes the queue once Wi-Fi returns or Wi-Fi-only is turned off; ends when nothing waits any more. */ private fun releaseWatcher(): Job = scope.launch(start = CoroutineStart.LAZY) { while (_queueStatus.value.waitingForWifi) { networkHeld.first { !it } processQueue() } } private fun notifyWaitingForWifi(waiting: Boolean) { runCatching { if (waiting) { notifications?.notify( NotificationPayload( channel = NotificationChannel.Downloads, title = "Downloads waiting for Wi-Fi", message = "They continue on Wi-Fi. Turn off Only on Wi-Fi in download settings to use mobile data.", tag = WAITING_FOR_WIFI_NOTIFICATION_TAG, ), ) } else { notifications?.cancel(NotificationChannel.Downloads, WAITING_FOR_WIFI_NOTIFICATION_TAG) } } } /** The task's worker, created lazily so it is registered in [jobs] before it can run or finish. */ private fun worker(task: QueuedDownload): Job { val taskId = task.request.taskId return scope.launch(start = CoroutineStart.LAZY) { try { runDownload(task) } catch (stop: CancellationException) { // A stray timeout from deeper code is a failure; only a stopped worker ends silently. if (!isActive) throw stop AppLogger.error("[download] $taskId failed: ${stop.message.orEmpty()}") finishFailed(task, PageTally(0)) } catch (error: Throwable) { AppLogger.error("[download] $taskId failed: ${error.message.orEmpty()}") finishFailed(task, PageTally(0)) } finally { // A pause that lands while the chapter is being finished must not queue it again. val finished = database.download(task.downloadId)?.isDownload == true val userCancelled = stateLock.withLock { jobs.remove(taskId) running = (running - 1).coerceAtLeast(0) activeSources.remove(task.sourceKey) if (requeueOnStop.remove(taskId) && !finished) { queue.addFirst(task) false } else { active.remove(taskId) publishActiveDownloadsLocked() cancelled.remove(taskId) } } // Written after the worker has stopped so no late progress write can mark the row started again. if (userCancelled) markStopped(taskId) processQueue() } } } private fun markStopped(taskId: String) { val downloadId = stateLock.withLock { taskDownloadIds[taskId] } ?: return database.batch { val download = database.download(downloadId) ?: return@batch val chapterId = download.chapterId ?: return@batch val chapter = database.chapter(chapterId) ?: return@batch if (chapter.mangaId?.let(database::manga) == null) return@batch database.upsertDownload(download.copy(isStartDownload = false, isPaused = false)) } } private suspend fun runDownload(task: QueuedDownload) { files.prepare() val request = task.request val delayMs = downloadStartDelayMs(database.settings().downloadDelaySeconds) if (delayMs > 0L) delay(delayMs) report(task, PageTally(0), persist = false) if (request.itemType == DbItemType.Novel && resolveNovelText != null) { val text = catchingNonCancellation { withTimeoutOrNull(DOWNLOAD_PREPARATION_TIMEOUT_MS) { resolveNovelText.invoke(request.chapterId) } ?.takeIf(String::isNotBlank) ?: error("No novel text resolved") }.getOrElse { return finishFailed(task, PageTally(1), "Failed loading novel text") } val target = "${task.location}/0001.html" withContext(ioDispatcher) { val partial = "$target.part" files.writeBytesAsync(partial, text.encodeToByteArray()) check(pageTransfer.promoteWithMarker(partial, target, "$target.complete")) { "Cannot save novel text" } } val tally = PageTally(1).apply { succeeded = 1; bytes = text.encodeToByteArray().size.toLong() } return finishCompleted(task, tally) } var pages = resolvedPages(request.chapterId, forceRefresh = false) ?: run { AppLogger.warn("[download] ${request.taskId} failed: no pages resolved") return finishFailed(task, PageTally(0), "Failed loading pages for ${request.chapterName.ifBlank { "chapter" }}") } var refreshed = false var tally = PageTally(pages.size) while (true) { report(task, tally, persist = true) val splitHeight = database.settings().features.downloads.takeIf { request.itemType == DbItemType.Manga && it.splitTallImages }?.splitImageHeight val saved = withContext(ioDispatcher) { pageTransfer.savedPages(task.location, pages.size, splitHeight) } val expired = downloadPages(task, tally, pages, pages.indices, saved, countExpired = refreshed) if (expired.isEmpty()) break refreshed = true val fresh = resolvedPages(request.chapterId, forceRefresh = true) when { fresh == null -> expired.forEach { recordPage(task, tally, saved = false) } // The chapter changed: start over. Saved pages are kept by index, extra indices are dropped. // ponytail: a source that inserts a page mid-chapter shifts the kept ones; clear all markers if that shows up. fresh.size != pages.size -> { pages = fresh tally = PageTally(fresh.size) continue } else -> { pages = fresh downloadPages(task, tally, pages, expired, emptyMap(), countExpired = true) } } break } downloadSubtitles(task, tally) if (tally.failed > 0 || tally.succeeded < tally.total) { AppLogger.warn("[download] ${request.taskId} failed: ${tally.succeeded}/${tally.total} pages saved, ${tally.failed} failed") return finishFailed(task, tally) } finishCompleted(task, tally) } /** The chapter's pages, else null (logged) when they can't be resolved or there are none. */ private suspend fun resolvedPages(chapterId: Long, forceRefresh: Boolean): List? = catchingNonCancellation { withTimeoutOrNull(DOWNLOAD_PREPARATION_TIMEOUT_MS) { resolvePages(chapterId, forceRefresh) } ?: error("Timed out loading pages") }.onFailure { AppLogger.warn("[download] resolving pages of chapter $chapterId failed: ${it.message.orEmpty()}") } .getOrNull() ?.takeIf { it.isNotEmpty() } /** * Downloads [indices] of [pages], [PAGE_PARALLELISM] at a time, counting pages found in [saved] without * fetching them. Returns the indices whose URL looked expired, uncounted, unless [countExpired]. */ private suspend fun downloadPages( task: QueuedDownload, tally: PageTally, pages: List, indices: Iterable, saved: Map, countExpired: Boolean, ): List { val permits = Semaphore(PAGE_PARALLELISM) val expired = mutableListOf() coroutineScope { indices.forEach { index -> launch { permits.withPermit { saved[index]?.let { size -> return@withPermit recordPage(task, tally, saved = true, bytes = size) } var bytes = 0L val status = pageTransfer.downloadPage(task.request, task.location, task.transferPermits, pages[index], index, onBytes = { bytes += it }, onTransfer = { current -> stateLock.withLock { tally.inFlightBytes[index] = current val now = nowMillis() if (now - tally.lastProgressAt >= 200) { tally.lastProgressAt = now publishLocked(task, tally) } } }) stateLock.withLock { tally.inFlightBytes.remove(index) } when { status == null -> recordPage(task, tally, saved = true, bytes = bytes) status in ExpiredPageStatuses && !countExpired -> stateLock.withLock { expired += index } else -> recordPage(task, tally, saved = false) } } } } } return expired.sorted() } private suspend fun downloadSubtitles(task: QueuedDownload, tally: PageTally) { task.request.subtitles.forEachIndexed { index, sub -> if (sub.file.isBlank()) return@forEachIndexed val subtitlePath = "${task.location}_subtitles/${index.toString().padStart(2, '0')}_${sub.label.ifBlank { "subtitle" }}.${sub.file.substringAfterLast('.', "srt").lowercase()}" catchingNonCancellation { val response = withTimeoutOrNull(DOWNLOAD_CONNECTION_TIMEOUT_MS) { http.request(HttpRequest(url = sub.file)) } if (response != null && response.statusCode in 200..299 && response.bodyBytes.isNotEmpty()) { withContext(ioDispatcher) { files.writeBytesAsync(subtitlePath, response.bodyBytes) } stateLock.withLock { tally.bytes += response.bodyBytes.size } } } } } /** Not cancellable: once the pages are in, a pause or cancel can't leave a zipped chapter unmarked. */ private suspend fun finishCompleted(task: QueuedDownload, tally: PageTally) = withContext(NonCancellable) { val request = task.request val archive = withContext(ioDispatcher) { writeMetadata(files, request, task.location) writeTitleMetadata(files, http, request, task.location.substringBeforeLast('/', task.location)) if (!shouldArchiveChapter(request)) return@withContext null runCatching { archives.zipDirectoryToCbzAsync(task.location, deleteSource = true) } .onSuccess { path -> path?.let { AppLogger.info("[download] CBZ created for ${request.mangaName} chapter ${request.chapterName}: $it") } } .onFailure { AppLogger.warn("[download] CBZ failed for ${request.taskId}, keeping the folder: ${it.message.orEmpty()}") } .getOrNull() } files.awaitPersistence() // The reader and chapter list read this mark; deleting the download clears it (clearChapterDownloads). // The mark stays on this device: sync and backup restore treat it as device-local (SyncPaths, BackupService). setDownloadMark(request.chapterId, archive ?: task.location, downloadSizeLabel(tally.bytes)) report(task, tally, persist = true, complete = true) AppLogger.info("[download] ${request.taskId} completed: ${tally.succeeded} pages, ${downloadSizeLabel(tally.bytes)}") notify(request, request.mangaName.ifBlank { "Download finished" }, "${request.chapterName.ifBlank { "Chapter" }} • ${tally.succeeded} pages") stateLock.withLock { active.remove(request.taskId) lastRequests.remove(request.taskId) publishActiveDownloadsLocked() } onCompleted(request.chapterId) } private fun finishFailed( task: QueuedDownload, tally: PageTally, message: String = "Failed downloading ${task.request.chapterName.ifBlank { "chapter" }}", ) { val progress = stateLock.withLock { tally.failed = tally.failed.coerceAtLeast(1) publishLocked(task, tally) } database.batch { val chapter = database.chapter(task.request.chapterId) ?: return@batch if (chapter.mangaId?.let(database::manga) == null) return@batch database.download(task.downloadId)?.let { download -> database.upsertDownload( download.copy( succeeded = progress.succeeded, failed = progress.failed, total = progress.total, isDownload = false, isStartDownload = false, ), ) } } runCatching { task.onProgress(progress) } .onFailure { AppLogger.warn("Download progress callback failed: ${it.message.orEmpty()}") } notify(task.request, task.request.mangaName.ifBlank { "Download failed" }, message) stateLock.withLock { active.remove(task.request.taskId) publishActiveDownloadsLocked() } } private fun notify(request: DownloadRequest, title: String, message: String) { runCatching { notifications?.notify( NotificationPayload( channel = NotificationChannel.Downloads, title = title, message = message, tag = request.taskId, ), ) } } private fun setDownloadMark(chapterId: Long, archivePath: String, downloadSize: String?) { database.batch { val chapter = database.chapter(chapterId) ?: return@batch if (chapter.mangaId?.let(database::manga) == null) return@batch database.upsertChapter(chapter.copy(archivePath = archivePath, downloadSize = downloadSize, updatedAt = nowMillis())) } } private fun shouldArchiveChapter(request: DownloadRequest): Boolean = request.itemType == DbItemType.Manga && database.settings().saveAsCBZArchive /** Publishes [tally] as the task's live progress; the caller holds [stateLock]. */ private fun publishLocked(task: QueuedDownload, tally: PageTally, complete: Boolean = false, force: Boolean = true): DownloadProgress { val progress = DownloadProgress( taskId = task.request.taskId, succeeded = tally.succeeded, failed = tally.failed, total = tally.total, itemType = task.request.itemType, isCompleted = complete || (tally.total > 0 && tally.succeeded + tally.failed >= tally.total), isPaused = task.request.taskId in paused, storageLocation = task.location, bytesDownloaded = tally.bytes + tally.inFlightBytes.values.sum(), mangaName = task.request.mangaName, chapterName = task.request.chapterName, ) active[task.request.taskId] = progress val now = nowMillis() if (force || progress.isCompleted || now - tally.lastProgressAt >= 200) { tally.lastProgressAt = now publishActiveDownloadsLocked() } return progress } private fun report(task: QueuedDownload, tally: PageTally, persist: Boolean, complete: Boolean = false) { val progress = stateLock.withLock { publishLocked(task, tally, complete) } if (persist) persistProgress(task, progress, complete) runCatching { task.onProgress(progress) } .onFailure { AppLogger.warn("Download progress callback failed: ${it.message.orEmpty()}") } } /** Counts one page; the row is written on the persist interval and on the chapter's first failure. */ private fun recordPage(task: QueuedDownload, tally: PageTally, saved: Boolean, bytes: Long = 0L) { val progress = stateLock.withLock { if (saved) tally.succeeded += 1 else tally.failed += 1 tally.bytes += bytes publishLocked(task, tally, force = !saved) } val processed = progress.succeeded + progress.failed if (processed % PROGRESS_PERSIST_INTERVAL == 0 || (!saved && progress.failed == 1)) { persistProgress(task, progress, complete = false) } runCatching { task.onProgress(progress) } .onFailure { AppLogger.warn("Download progress callback failed: ${it.message.orEmpty()}") } } private fun persistProgress(task: QueuedDownload, progress: DownloadProgress, complete: Boolean) { database.batch { val chapter = database.chapter(task.request.chapterId) ?: return@batch if (chapter.mangaId?.let(database::manga) == null) return@batch database.download(task.downloadId)?.let { download -> database.upsertDownload( download.copy( succeeded = progress.succeeded, failed = progress.failed, total = progress.total, isDownload = complete, isStartDownload = !progress.isCompleted, isPaused = !complete && download.isPaused, ), ) } } } private fun publishActiveDownloadsLocked() { _activeDownloadProgress.update { active.values.sortedBy(DownloadProgress::taskId) } } private fun resolveStorageLocation(request: DownloadRequest): String { val customRoot = request.destinationRoot ?.takeIf { it.isNotBlank() } ?: database.settings().downloadLocation.takeIf { it.isNotBlank() } ?: files.downloadRoot return downloadChapterLocation( downloadStorageRoot(customRoot, files), request.itemType, request.sourceLabel, request.mangaName, request.scanlator, request.chapterName, ) } private fun String.chapterIdOrNull(): Long? = removePrefix("chapter-").takeIf { it != this }?.toLongOrNull() private companion object { const val PROGRESS_PERSIST_INTERVAL = 5 } } /** Transient statuses worth retrying; any other 4xx fails at once. */ internal fun isRetryableDownloadStatus(status: Int): Boolean = status == 408 || status == 429 || status in 500..599 private const val RETRY_BASE_DELAY_MS = 1_000L private const val MAX_RETRY_AFTER_MS = 60_000L /** * Wait before retry [attempt] (1-based): the server's Retry-After seconds when sent (capped at a minute), * else exponential backoff from one second with equal jitter. */ internal fun downloadRetryDelayMs(attempt: Int, retryAfter: String?, random: Random = Random.Default): Long { // ponytail: an HTTP-date Retry-After falls back to backoff; parse it if a CDN sends one. retryAfter?.trim()?.toLongOrNull()?.let { seconds -> return (seconds * 1_000L).coerceIn(0L, MAX_RETRY_AFTER_MS) } val base = RETRY_BASE_DELAY_MS shl (attempt - 1).coerceIn(0, 6) return base / 2 + random.nextLong(base / 2 + 1) } private const val BYTES_PER_MIB = 1_048_576L /** Size shown next to a downloaded chapter, e.g. `12.3 MB`. */ internal fun downloadSizeLabel(bytes: Long): String { val tenths = (bytes.coerceAtLeast(0L) * 10 + BYTES_PER_MIB / 2) / BYTES_PER_MIB return "${tenths / 10}.${tenths % 10} MB" } internal fun resolveDownloadSourceKey( request: DownloadRequest, downloadId: Long = 0L, database: YokanDatabase? = null, ): String { if (request.sourceId != null && request.sourceId > 0L) { return "source-${request.sourceId}" } if (database != null && request.chapterId > 0L) { val chapter = database.chapter(request.chapterId) val manga = chapter?.mangaId?.let { database.manga(it) } if (manga != null) { val sId = manga.sourceId val source = manga.source if (sId != null && sId > 0L) return "source-$sId" if (!source.isNullOrBlank()) return "source-${source.trim()}|${manga.lang.orEmpty()}" } } if (request.sourceLabel.isNotBlank()) { return "source-${request.sourceLabel.trim()}" } return if (downloadId > 0L) "download-$downloadId" else request.taskId.ifBlank { "download-${request.chapterId}" } } internal fun downloadStartDelayMs( baseSeconds: Int, random: kotlin.random.Random = kotlin.random.Random.Default, ): Long { if (baseSeconds <= 0) return 0L val base = baseSeconds * 1000L val jitter = (base * (0.25 + random.nextDouble() * 0.75)).toLong() return base + jitter }