Yokan / rebuild
Course 1 8624561

DownloadService.kt

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

implementation314 lines
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.data.SettingsStore4import eu.friedcutlet.yokan.data.YokanRepository5import eu.friedcutlet.yokan.data.toDomain6import eu.friedcutlet.yokan.database.DbChapter7import eu.friedcutlet.yokan.database.DbDownload8import eu.friedcutlet.yokan.database.DbItemType9import eu.friedcutlet.yokan.database.DbSettings10import eu.friedcutlet.yokan.database.YokanDatabase11import eu.friedcutlet.yokan.database.configuredLocalFolders12import eu.friedcutlet.yokan.domain.Chapter13import eu.friedcutlet.yokan.domain.Manga14import eu.friedcutlet.yokan.services.files.LocalFileService15import eu.friedcutlet.yokan.services.logging.AppLogger16import eu.friedcutlet.yokan.services.notifications.NotificationChannel17import eu.friedcutlet.yokan.services.notifications.NotificationPayload18import eu.friedcutlet.yokan.services.notifications.NotificationService19import kotlinx.coroutines.flow.MutableStateFlow20import kotlinx.coroutines.flow.StateFlow21import kotlinx.coroutines.CoroutineScope22import kotlinx.coroutines.CancellationException23import kotlinx.coroutines.launch24import kotlinx.coroutines.withContext25import eu.friedcutlet.yokan.services.blockingDispatcher26import eu.friedcutlet.yokan.services.files.resolveConfiguredLocalArchivePath27import eu.friedcutlet.yokan.services.runJoined2829private val EmptyActiveDownloads = MutableStateFlow<List<DownloadProgress>>(emptyList())3031private val IdleDownloadQueue = MutableStateFlow(DownloadQueueStatus())3233interface DownloadService {34    val activeDownloadProgress: StateFlow<List<DownloadProgress>>35        get() = EmptyActiveDownloads36    val queueStatus: StateFlow<DownloadQueueStatus>37        get() = IdleDownloadQueue38    suspend fun initialize(poolSize: Int = 6)39    /**40     * Records and queues [request] before returning, so downloads keep the order they were requested in. With41     * Wi-Fi-only on a metered network it stays queued, waiting for Wi-Fi.42     */43    fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit = {})44    fun cancel(taskId: String)45    /** Cancels every queued and running download. */46    fun cancelAll() = Unit47    fun pause(taskId: String)48    fun resume(taskId: String)49    /** Queues a stopped download again; false when it can't be rebuilt (its chapter is gone). */50    fun retry(taskId: String): Boolean51    fun storageLocation(taskId: String): String?52    /** Deletes the task's files: the chapter folder, its `.cbz` archive and its `_subtitles` folder. */53    fun deleteArtifacts(taskId: String)54    /** Manual removal joins transfer workers and awaits durable filesystem deletion. */55    suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit = {}): Boolean { deleteArtifacts(taskId); onDeleted(); return true }56    /** Automated cleanup must refuse active work and report file deletion failures. */57    suspend fun deleteCompletedArtifacts(taskId: String, stillEligible: () -> Boolean = { true }, onDeleted: () -> Unit = {}): Boolean = false58    fun activeDownloads(): List<DownloadProgress>59    fun reorderQueue(order: List<Long>) = Unit60}6162/**63 * The queue at a glance: [pending] chapters queued or running, not counting ones the user paused.64 * [waitingForWifi] is true while Wi-Fi-only holds that work on a metered network.65 */66data class DownloadQueueStatus(67    val pending: Int = 0,68    val waitingForWifi: Boolean = false,69)7071data class DownloadProgress(72    val taskId: String,73    val succeeded: Int,74    val failed: Int,75    val total: Int,76    val itemType: DbItemType,77    val isCompleted: Boolean = false,78    val isPaused: Boolean = false,79    val storageLocation: String? = null,80    val bytesDownloaded: Long = 0L,81    val mangaName: String = "",82    val chapterName: String = "",83)8485/** Stable download identity used by enqueue, queue controls, recovery, and file cleanup. */86fun downloadTaskId(chapterId: Long?, downloadId: Long): String =87    chapterId?.let { "chapter-$it" } ?: "download-$downloadId"8889/** A chapter download; its pages are resolved from [chapterId] when the download starts. */90@kotlinx.serialization.Serializable91data class DownloadRequest(92    val taskId: String,93    val chapterId: Long,94    val itemType: DbItemType,95    val subtitles: List<VideoTrackFile> = emptyList(),96    val mangaName: String = "",97    val chapterName: String = "",98    val sourceLabel: String = "",99    val scanlator: String = "",100    val destinationRoot: String? = null,101    val metadata: Map<String, String> = emptyMap(),102    val retries: Int = 3,103    val sourceId: Long? = null,104)105106@kotlinx.serialization.Serializable107data class VideoTrackFile(108    val file: String,109    val label: String,110)111112/** App-scoped chapter download actions: the single enqueue path plus queue and file cleanup. */113class ChapterDownloads(114    private val repository: YokanRepository,115    private val database: YokanDatabase,116    private val downloader: DownloadService,117    private val notifications: NotificationService,118    private val settings: SettingsStore,119    private val localFiles: LocalFileService,120    private val scope: CoroutineScope,121    private val externalDownloads: ExternalDownloads? = null,122) {123    /**124     * Records and queues [chapter] right away, in call order; its pages are resolved when the download125     * starts. A null [destinationRoot] means the download folder selected in settings. Failures surface126     * as a download notification.127     */128    fun enqueue(manga: Manga, chapter: Chapter, destinationRoot: String?) {129        runCatching {130            val request = checkNotNull(chapterDownloadRequest(database, chapter.id, destinationRoot)) {131                "${chapter.name.ifBlank { "The chapter" }} is no longer in the library"132            }133            if (destinationRoot == null && externalDownloads != null && request.itemType != DbItemType.Novel && database.settings().features.externalDownloads.preferred == eu.friedcutlet.yokan.database.PreferredDownloader.Aria2) {134                scope.launch {135                    try {136                        if (!externalDownloads.enqueue(request)) downloader.enqueue(request)137                    } catch (cancel: CancellationException) { throw cancel }138                    catch (_: Exception) { notifyFailure(manga, chapter, "External download failed. Check the server settings and remote queue.") }139                }140            } else downloader.enqueue(request)141        }.onFailure { error ->142            AppLogger.warn("[download] enqueue chapter ${chapter.id} failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")143            notifyFailure(manga, chapter, error.message ?: "Download failed")144        }145    }146147    private fun notifyFailure(manga: Manga, chapter: Chapter, message: String) {148        runCatching {149            notifications.notify(150                NotificationPayload(151                    channel = NotificationChannel.Downloads,152                    title = manga.name.ifBlank { "Download failed" },153                    message = message,154                    tag = "chapter-${chapter.id}",155                ),156            )157        }158    }159160    /** Removes the download records and files of [chapterIds]; returns at least their count. */161    fun deleteForChapters(chapterIds: Set<Long>): Int {162        if (chapterIds.isEmpty()) return 0163        val matching = repository.downloads().filter { it.chapterId != null && it.chapterId in chapterIds }164        matching.forEach(::removeRecord)165        return matching.size.coerceAtLeast(chapterIds.size)166    }167168    suspend fun deleteForChaptersAwait(chapterIds: Set<Long>): Int = owned {169        var removed = 0170        repository.downloads().filter { it.chapterId in chapterIds }.forEach {171            if (removeRecordAwait(it)) removed++172        }173        removed174    }175176    /** Deletes every download of [mangaIds]; local-archive titles lose their files and library entry. */177    fun deleteForManga(mangaIds: Set<Long>): Int {178        scope.launch { deleteForMangaAwait(mangaIds) }179        return mangaIds.sumOf { repository.chapters(it).size.coerceAtLeast(1) }180    }181182    /** Returns titles whose files/records were removed; dependent title deletion must await this. */183    suspend fun deleteForMangaAwait(mangaIds: Set<Long>): Set<Long> = owned {184        val successful = mutableSetOf<Long>()185        mangaIds.forEach { mangaId ->186            val chapters = repository.chapters(mangaId)187            val chapterIds = chapters.mapTo(mutableSetOf()) { it.id }188            val rows = repository.downloads().filter { it.chapterId in chapterIds }189            var removed = true190            // Keep every database parent alive until the filesystem work has finished.191            rows.forEach { if (!removeRecordAwait(it)) removed = false }192            if (repository.manga(mangaId)?.isLocalArchive == true) {193                try {194                    val paths = chapters.map { it.archivePath }.filter(String::isNotBlank).map {195                        resolveConfiguredLocalArchivePath(it, localFiles, database.settings()).substringBefore('#')196                    }.distinct()197                    withContext(blockingDispatcher) {198                        localFiles.prepare()199                        paths.forEach { if (!localFiles.deleteRecursivelyAsync(it)) removed = false }200                    }201                    if (removed) repository.removeLibraryEntries(setOf(mangaId))202                } catch (cancel: CancellationException) { throw cancel }203                catch (_: Exception) { removed = false }204                if (!removed) notifyRemovalFailure("title-$mangaId")205            }206            if (removed) successful += mangaId207        }208        successful209    }210211    fun cancel(downloadId: Long) {212        val download = find(downloadId) ?: return213        repository.cancelDownload(downloadId)214        downloader.cancel(downloadTaskId(download.chapterId, download.id))215    }216217    fun remove(downloadId: Long) {218        find(downloadId)?.let(::removeRecord)219    }220221    fun reorderQueue(newOrder: List<Long>) {222        settings.updateDb { it.copy(downloadQueueOrder = newOrder) }223        downloader.reorderQueue(newOrder)224    }225226    fun openLocation(downloadId: Long): Boolean {227        val download = find(downloadId) ?: return false228        val location = downloader.storageLocation(downloadTaskId(download.chapterId, download.id)) ?: return false229        return localFiles.openLocation(location)230    }231232    private fun find(downloadId: Long): DbDownload? = repository.downloads().firstOrNull { it.id == downloadId }233234    private fun removeRecord(download: DbDownload) {235        scope.launch { removeRecordAwait(download) }236    }237238    private suspend fun removeRecordAwait(download: DbDownload): Boolean {239        val taskId = downloadTaskId(download.chapterId, download.id)240        return try {241            var removed = false242            val deleted = downloader.deleteArtifactsAsync(taskId, onDeleted = { database.batch {243                val current = database.download(download.id)244                if (current != null && current.chapterId == download.chapterId && current.isStartDownload != true) {245                    repository.removeDownload(download.id)246                    download.chapterId?.let { repository.clearChapterDownloads(setOf(it)) }247                    removed = true248                }249            } })250            if (!deleted) notifyRemovalFailure(taskId)251            deleted && removed252        } catch (cancel: CancellationException) { throw cancel }253        catch (_: Exception) { notifyRemovalFailure(taskId); false }254    }255256    private suspend fun <T> owned(action: suspend () -> T): T = scope.runJoined { action() }257258    private fun notifyRemovalFailure(taskId: String) {259        AppLogger.warn("[download] File removal failed; download records preserved")260        runCatching { notifications.notify(NotificationPayload(NotificationChannel.Downloads, "Download removal failed", "Files could not be removed. Retry after checking storage access.", tag = taskId)) }261    }262}263264/**265 * The download request for [chapterId], rebuilt from the database so enqueue, retry and restart recovery266 * all describe a chapter the same way; null when the chapter or its title is gone. A null267 * [destinationRoot] means the download folder selected in settings.268 */269internal fun chapterDownloadRequest(database: YokanDatabase, chapterId: Long, destinationRoot: String? = null): DownloadRequest? {270    val chapter = database.chapter(chapterId) ?: return null271    val title = chapter.mangaId?.let(database::manga) ?: return null272    val settings = database.settings()273    val manga = title.toDomain(settings)274    val source = manga.sourceId?.let(database::source)275    return DownloadRequest(276        taskId = downloadTaskId(chapter.id, 0),277        chapterId = chapter.id,278        itemType = title.itemType,279        mangaName = manga.name,280        chapterName = chapter.name.orEmpty(),281        sourceLabel = downloadSourceLabel(source?.name, source?.lang, manga.source),282        scanlator = chapter.scanlator,283        destinationRoot = destinationRoot ?: settings.selectedDownloadRoot(),284        sourceId = source?.id ?: manga.sourceId,285        metadata = downloadMetadata(manga, source?.name, chapter),286    )287}288289/**290 * The configured download folder picked in settings, else the first one; null means the default root.291 * SAF (`content://`) folders are read-only local folders, so they are never picked.292 */293private fun DbSettings.selectedDownloadRoot(): String? {294    val folders = configuredLocalFolders().filterNot { it.path.startsWith("content://") }295    return (folders.firstOrNull { it.name == downloadLocalFolderName } ?: folders.firstOrNull())?.path296}297298private fun downloadMetadata(manga: Manga, sourceName: String?, chapter: DbChapter): Map<String, String> =299    buildMap {300        put("name", manga.name)301        manga.description.takeIf { it.isNotBlank() }?.let { put("description", it) }302        manga.author?.takeIf { it.isNotBlank() }?.let { put("author", it) }303        manga.artist?.takeIf { it.isNotBlank() }?.let { put("artist", it) }304        put("status", manga.status.label)305        put("itemType", manga.itemType.name)306        put("source", sourceName ?: manga.source)307        put("language", manga.lang)308        manga.imageUrl?.takeIf { it.isNotBlank() }?.let { put("imageUrl", it) }309        manga.customCoverFromTracker?.takeIf { it.isNotBlank() }?.let { put("customCoverFromTracker", it) }310        manga.genres.takeIf { it.isNotEmpty() }?.let { put("genre", it.joinToString(", ")) }311        put("chapterName", chapter.name.orEmpty())312        chapter.scanlator.takeIf { it.isNotBlank() }?.let { put("scanlator", it) }313        chapter.dateUpload.takeIf { it.isNotBlank() }?.let { put("chapterDate", it) }314    }315

Search chapters, reference and source filenames.