package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.data.toDomain import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbDownload import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.database.configuredLocalFolders import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.files.LocalFileService 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 kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CancellationException import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import eu.friedcutlet.yokan.services.blockingDispatcher import eu.friedcutlet.yokan.services.files.resolveConfiguredLocalArchivePath import eu.friedcutlet.yokan.services.runJoined private val EmptyActiveDownloads = MutableStateFlow>(emptyList()) private val IdleDownloadQueue = MutableStateFlow(DownloadQueueStatus()) interface DownloadService { val activeDownloadProgress: StateFlow> get() = EmptyActiveDownloads val queueStatus: StateFlow get() = IdleDownloadQueue suspend fun initialize(poolSize: Int = 6) /** * Records and queues [request] before returning, so downloads keep the order they were requested in. With * Wi-Fi-only on a metered network it stays queued, waiting for Wi-Fi. */ fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit = {}) fun cancel(taskId: String) /** Cancels every queued and running download. */ fun cancelAll() = Unit fun pause(taskId: String) fun resume(taskId: String) /** Queues a stopped download again; false when it can't be rebuilt (its chapter is gone). */ fun retry(taskId: String): Boolean fun storageLocation(taskId: String): String? /** Deletes the task's files: the chapter folder, its `.cbz` archive and its `_subtitles` folder. */ fun deleteArtifacts(taskId: String) /** Manual removal joins transfer workers and awaits durable filesystem deletion. */ suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit = {}): Boolean { deleteArtifacts(taskId); onDeleted(); return true } /** Automated cleanup must refuse active work and report file deletion failures. */ suspend fun deleteCompletedArtifacts(taskId: String, stillEligible: () -> Boolean = { true }, onDeleted: () -> Unit = {}): Boolean = false fun activeDownloads(): List fun reorderQueue(order: List) = Unit } /** * The queue at a glance: [pending] chapters queued or running, not counting ones the user paused. * [waitingForWifi] is true while Wi-Fi-only holds that work on a metered network. */ data class DownloadQueueStatus( val pending: Int = 0, val waitingForWifi: Boolean = false, ) data class DownloadProgress( val taskId: String, val succeeded: Int, val failed: Int, val total: Int, val itemType: DbItemType, val isCompleted: Boolean = false, val isPaused: Boolean = false, val storageLocation: String? = null, val bytesDownloaded: Long = 0L, val mangaName: String = "", val chapterName: String = "", ) /** Stable download identity used by enqueue, queue controls, recovery, and file cleanup. */ fun downloadTaskId(chapterId: Long?, downloadId: Long): String = chapterId?.let { "chapter-$it" } ?: "download-$downloadId" /** A chapter download; its pages are resolved from [chapterId] when the download starts. */ @kotlinx.serialization.Serializable data class DownloadRequest( val taskId: String, val chapterId: Long, val itemType: DbItemType, val subtitles: List = emptyList(), val mangaName: String = "", val chapterName: String = "", val sourceLabel: String = "", val scanlator: String = "", val destinationRoot: String? = null, val metadata: Map = emptyMap(), val retries: Int = 3, val sourceId: Long? = null, ) @kotlinx.serialization.Serializable data class VideoTrackFile( val file: String, val label: String, ) /** App-scoped chapter download actions: the single enqueue path plus queue and file cleanup. */ class ChapterDownloads( private val repository: YokanRepository, private val database: YokanDatabase, private val downloader: DownloadService, private val notifications: NotificationService, private val settings: SettingsStore, private val localFiles: LocalFileService, private val scope: CoroutineScope, private val externalDownloads: ExternalDownloads? = null, ) { /** * Records and queues [chapter] right away, in call order; its pages are resolved when the download * starts. A null [destinationRoot] means the download folder selected in settings. Failures surface * as a download notification. */ fun enqueue(manga: Manga, chapter: Chapter, destinationRoot: String?) { runCatching { val request = checkNotNull(chapterDownloadRequest(database, chapter.id, destinationRoot)) { "${chapter.name.ifBlank { "The chapter" }} is no longer in the library" } if (destinationRoot == null && externalDownloads != null && request.itemType != DbItemType.Novel && database.settings().features.externalDownloads.preferred == eu.friedcutlet.yokan.database.PreferredDownloader.Aria2) { scope.launch { try { if (!externalDownloads.enqueue(request)) downloader.enqueue(request) } catch (cancel: CancellationException) { throw cancel } catch (_: Exception) { notifyFailure(manga, chapter, "External download failed. Check the server settings and remote queue.") } } } else downloader.enqueue(request) }.onFailure { error -> AppLogger.warn("[download] enqueue chapter ${chapter.id} failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}") notifyFailure(manga, chapter, error.message ?: "Download failed") } } private fun notifyFailure(manga: Manga, chapter: Chapter, message: String) { runCatching { notifications.notify( NotificationPayload( channel = NotificationChannel.Downloads, title = manga.name.ifBlank { "Download failed" }, message = message, tag = "chapter-${chapter.id}", ), ) } } /** Removes the download records and files of [chapterIds]; returns at least their count. */ fun deleteForChapters(chapterIds: Set): Int { if (chapterIds.isEmpty()) return 0 val matching = repository.downloads().filter { it.chapterId != null && it.chapterId in chapterIds } matching.forEach(::removeRecord) return matching.size.coerceAtLeast(chapterIds.size) } suspend fun deleteForChaptersAwait(chapterIds: Set): Int = owned { var removed = 0 repository.downloads().filter { it.chapterId in chapterIds }.forEach { if (removeRecordAwait(it)) removed++ } removed } /** Deletes every download of [mangaIds]; local-archive titles lose their files and library entry. */ fun deleteForManga(mangaIds: Set): Int { scope.launch { deleteForMangaAwait(mangaIds) } return mangaIds.sumOf { repository.chapters(it).size.coerceAtLeast(1) } } /** Returns titles whose files/records were removed; dependent title deletion must await this. */ suspend fun deleteForMangaAwait(mangaIds: Set): Set = owned { val successful = mutableSetOf() mangaIds.forEach { mangaId -> val chapters = repository.chapters(mangaId) val chapterIds = chapters.mapTo(mutableSetOf()) { it.id } val rows = repository.downloads().filter { it.chapterId in chapterIds } var removed = true // Keep every database parent alive until the filesystem work has finished. rows.forEach { if (!removeRecordAwait(it)) removed = false } if (repository.manga(mangaId)?.isLocalArchive == true) { try { val paths = chapters.map { it.archivePath }.filter(String::isNotBlank).map { resolveConfiguredLocalArchivePath(it, localFiles, database.settings()).substringBefore('#') }.distinct() withContext(blockingDispatcher) { localFiles.prepare() paths.forEach { if (!localFiles.deleteRecursivelyAsync(it)) removed = false } } if (removed) repository.removeLibraryEntries(setOf(mangaId)) } catch (cancel: CancellationException) { throw cancel } catch (_: Exception) { removed = false } if (!removed) notifyRemovalFailure("title-$mangaId") } if (removed) successful += mangaId } successful } fun cancel(downloadId: Long) { val download = find(downloadId) ?: return repository.cancelDownload(downloadId) downloader.cancel(downloadTaskId(download.chapterId, download.id)) } fun remove(downloadId: Long) { find(downloadId)?.let(::removeRecord) } fun reorderQueue(newOrder: List) { settings.updateDb { it.copy(downloadQueueOrder = newOrder) } downloader.reorderQueue(newOrder) } fun openLocation(downloadId: Long): Boolean { val download = find(downloadId) ?: return false val location = downloader.storageLocation(downloadTaskId(download.chapterId, download.id)) ?: return false return localFiles.openLocation(location) } private fun find(downloadId: Long): DbDownload? = repository.downloads().firstOrNull { it.id == downloadId } private fun removeRecord(download: DbDownload) { scope.launch { removeRecordAwait(download) } } private suspend fun removeRecordAwait(download: DbDownload): Boolean { val taskId = downloadTaskId(download.chapterId, download.id) return try { var removed = false val deleted = downloader.deleteArtifactsAsync(taskId, onDeleted = { database.batch { val current = database.download(download.id) if (current != null && current.chapterId == download.chapterId && current.isStartDownload != true) { repository.removeDownload(download.id) download.chapterId?.let { repository.clearChapterDownloads(setOf(it)) } removed = true } } }) if (!deleted) notifyRemovalFailure(taskId) deleted && removed } catch (cancel: CancellationException) { throw cancel } catch (_: Exception) { notifyRemovalFailure(taskId); false } } private suspend fun owned(action: suspend () -> T): T = scope.runJoined { action() } private fun notifyRemovalFailure(taskId: String) { AppLogger.warn("[download] File removal failed; download records preserved") runCatching { notifications.notify(NotificationPayload(NotificationChannel.Downloads, "Download removal failed", "Files could not be removed. Retry after checking storage access.", tag = taskId)) } } } /** * The download request for [chapterId], rebuilt from the database so enqueue, retry and restart recovery * all describe a chapter the same way; null when the chapter or its title is gone. A null * [destinationRoot] means the download folder selected in settings. */ internal fun chapterDownloadRequest(database: YokanDatabase, chapterId: Long, destinationRoot: String? = null): DownloadRequest? { val chapter = database.chapter(chapterId) ?: return null val title = chapter.mangaId?.let(database::manga) ?: return null val settings = database.settings() val manga = title.toDomain(settings) val source = manga.sourceId?.let(database::source) return DownloadRequest( taskId = downloadTaskId(chapter.id, 0), chapterId = chapter.id, itemType = title.itemType, mangaName = manga.name, chapterName = chapter.name.orEmpty(), sourceLabel = downloadSourceLabel(source?.name, source?.lang, manga.source), scanlator = chapter.scanlator, destinationRoot = destinationRoot ?: settings.selectedDownloadRoot(), sourceId = source?.id ?: manga.sourceId, metadata = downloadMetadata(manga, source?.name, chapter), ) } /** * The configured download folder picked in settings, else the first one; null means the default root. * SAF (`content://`) folders are read-only local folders, so they are never picked. */ private fun DbSettings.selectedDownloadRoot(): String? { val folders = configuredLocalFolders().filterNot { it.path.startsWith("content://") } return (folders.firstOrNull { it.name == downloadLocalFolderName } ?: folders.firstOrNull())?.path } private fun downloadMetadata(manga: Manga, sourceName: String?, chapter: DbChapter): Map = buildMap { put("name", manga.name) manga.description.takeIf { it.isNotBlank() }?.let { put("description", it) } manga.author?.takeIf { it.isNotBlank() }?.let { put("author", it) } manga.artist?.takeIf { it.isNotBlank() }?.let { put("artist", it) } put("status", manga.status.label) put("itemType", manga.itemType.name) put("source", sourceName ?: manga.source) put("language", manga.lang) manga.imageUrl?.takeIf { it.isNotBlank() }?.let { put("imageUrl", it) } manga.customCoverFromTracker?.takeIf { it.isNotBlank() }?.let { put("customCoverFromTracker", it) } manga.genres.takeIf { it.isNotEmpty() }?.let { put("genre", it.joinToString(", ")) } put("chapterName", chapter.name.orEmpty()) chapter.scanlator.takeIf { it.isNotBlank() }?.let { put("scanlator", it) } chapter.dateUpload.takeIf { it.isNotBlank() }?.let { put("chapterDate", it) } }