package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.runJoined import eu.friedcutlet.yokan.util.sha256 import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.util.nowMillis import io.ktor.http.Url import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlin.random.Random /** Profile-owned remote queue. Remote completion never writes a local archive/download mark. */ class ExternalDownloads( private val database: YokanDatabase, private val http: HttpService, private val scope: CoroutineScope, private val resolvePages: suspend (Long, Boolean) -> List, private val clock: () -> Long = ::nowMillis, private val pollMillis: Long = 2000, startPolling: Boolean = true, ) { private val owner = requireNotNull(scope.coroutineContext[Job]) private val gate = Mutex() private val wake = Channel(Channel.CONFLATED) private val _jobs = MutableStateFlow(preferences().jobs) val jobs = _jobs.asStateFlow() private var lastProgressSave = 0L private var jobCursor = 0 private val fileCursors = mutableMapOf() init { if (startPolling) { scope.launch { database.snapshots().map { it.settings.features.externalDownloads.copy(jobs = emptyList()) }.distinctUntilChanged().collect { wake.trySend(Unit) } } scope.launch { _jobs.subscriptionCount.map { it > 0 }.distinctUntilChanged().collect { if (it) wake.trySend(Unit) } } scope.launch { var backoff = pollMillis while (currentCoroutineContext().isActive) { fun hasWork() = preferences().jobs.any { needsPolling(it, _jobs.subscriptionCount.value > 0) } val signalled = if (hasWork()) withTimeoutOrNull(backoff) { wake.receive(); true } ?: false else { wake.receive(); true } if (!signalled && !hasWork()) continue try { gate.withLock { reconcileLocked() } backoff = pollMillis } catch (cancel: CancellationException) { throw cancel } catch (_: Exception) { backoff = (backoff * 2).coerceAtMost(60_000) } } } } } /** Returns false for content that must use managed local storage (novels and HLS playlists). */ suspend fun enqueue(request: DownloadRequest): Boolean = owned { gate.withLock { val prefs = preferences() require(validConfiguration(prefs)) { "Configure the external downloader server and directory first" } if (request.itemType == DbItemType.Novel) return@withLock false val chapter = database.chapter(request.chapterId) ?: error("Chapter no longer exists") val title = chapter.mangaId?.let(database::manga) ?: error("Title no longer exists") require(!title.isLocalArchive) if (prefs.jobs.any { it.chapterId == request.chapterId && it.endpoint == prefs.endpoint && it.accountBinding == accountBinding(prefs) && (!it.terminal || it.complete) }) return@withLock true val pages = withTimeoutOrNull(60_000) { resolvePages(request.chapterId, false) } ?: error("Source resolution timed out") require(pages.isNotEmpty() && pages.size <= 2000) { "No downloadable files resolved" } if (pages.any { it.url.substringBefore('?').substringBefore('#').endsWith(".m3u8", true) }) return@withLock false require(pages.all { publicDownloadUri(it.url) }) { "External downloads require direct HTTP image or video files" } val id = newGid() val remoteDirectory = prefs.directory.trimEnd('/', '\\') + "/Yokan/${request.itemType.name}/${sanitizeDownloadName(request.mangaName).take(50)}/${sanitizeDownloadName(request.chapterName).take(50)}_$id" val job = DbRemoteDownloadJob(id, request.chapterId, request.itemType, request.mangaName, request.chapterName, prefs.endpoint, accountBinding(prefs), remoteDirectory, pages.mapIndexed { index, page -> DbRemoteDownloadFile(newGid(), "${(index + 1).toString().padStart(4, '0')}.${extension(page.url, request.itemType)}", page.url, page.headers.orEmpty(), resourceBinding = resourceBinding(page)) }, createdAt = clock(), mangaId = title.id, sourceId = title.sourceId, mangaLink = title.link, chapterUrl = chapter.url, sourceTitleName = title.name.orEmpty(), sourceChapterName = chapter.name.orEmpty()) // Resolving can suspend while settings/the chapter change. Recheck before durable admission. require(preferences().let { it.endpoint == prefs.endpoint && accountBinding(it) == job.accountBinding }) { "External downloader account changed" } require(database.chapter(request.chapterId)?.mangaId == chapter.mangaId && database.manga(title.id) != null) { "Chapter no longer exists" } val existing = preferences().jobs require(existing.count { !it.terminal } < 100) { "External download queue is full" } val retained = (existing.filterNot { it.terminal }.plus(existing.filter { it.terminal }.takeLast(155)) + job) require(DatabaseJson.encodeToString(DbExternalDownloads.serializer(), prefs.copy(jobs = retained)).encodeToByteArray().size <= 2 * 1024 * 1024) { "External download queue exceeds its storage limit" } save(retained, durable = true) wake.trySend(Unit) true } } suspend fun testConnection(): String = owned { val prefs = preferences() require(Aria2RpcClient.validEndpoint(prefs.endpoint)) { "Invalid external downloader URL" } val version = Aria2RpcClient(http, prefs.endpoint, prefs.secret).version() require(preferences().let { it.endpoint == prefs.endpoint && accountBinding(it) == accountBinding(prefs) }) version } suspend fun setIntent(id: String, intent: RemoteDownloadIntent) = owned { gate.withLock { val current = preferences().jobs require(current.any { it.id == id }) save(current.map { if (it.id == id) it.copy(intent = intent, problem = RemoteDownloadProblem.None) else it }, durable = true) wake.trySend(Unit) } } /** Only confirmed stopped remote files get a new identity; ambiguous work is never duplicated. */ suspend fun retry(id: String) = owned { gate.withLock { val original = preferences().jobs.firstOrNull { it.id == id } ?: error("Remote download no longer exists") requireCurrent(original) requireSourceIdentity(original) val candidates = original.files.filter { it.state in setOf(RemoteDownloadState.Error, RemoteDownloadState.Removed, RemoteDownloadState.Attention, RemoteDownloadState.Submitting) } require(candidates.isNotEmpty()) val prefs = preferences() val client = Aria2RpcClient(http, prefs.endpoint, prefs.secret) val statuses = candidates.chunked(64).flatMap { client.statuses(it.map { file -> file.gid }).entries }.associate { it.key to it.value.getOrThrow() } val pages = withTimeoutOrNull(60_000) { resolvePages(original.chapterId, true) } ?: error("Source resolution timed out") require(pages.size == original.files.size && pages.all { publicDownloadUri(it.url) && !it.url.substringBefore('?').endsWith(".m3u8", true) }) { "Download files changed; enqueue the chapter again" } requireCurrent(original) requireSourceIdentity(original) val files = original.files.mapIndexed { index, file -> val remote = statuses[file.gid] ?: return@mapIndexed file if (remote.status in setOf(Aria2Status.Error, Aria2Status.Removed)) { val gid = newGid() val resource = resourceBinding(pages[index]) val name = if (file.resourceBinding.isNotBlank() && resource == file.resourceBinding) file.name else "${(index + 1).toString().padStart(4, '0')}_r_$gid.${extension(pages[index].url, original.itemType)}" DbRemoteDownloadFile(gid, name, pages[index].url, pages[index].headers.orEmpty(), resourceBinding = resource) } else file.copy(state = RemoteDownloadState.valueOf(remote.status.name), url = "", headers = emptyMap(), totalBytes = remote.totalBytes, completedBytes = remote.completedBytes) } save(preferences().jobs.map { if (it.id == id) original.copy(files = files, intent = RemoteDownloadIntent.Run, problem = RemoteDownloadProblem.None) else it }, durable = true) wake.trySend(Unit) } } /** Removes the local receipt only after every remote task is confirmed stopped/completed. */ suspend fun remove(id: String, forgetUnverified: Boolean = false) = owned { gate.withLock { val current = preferences().jobs val job = current.firstOrNull { it.id == id } ?: return@withLock require(job.terminal || forgetUnverified) { "Cancel the remote download before removing its receipt" } save(current.filterNot { it.id == id }, durable = true) } } /** Also exposed to foreground refresh and deterministic recovery tests. */ suspend fun reconcile(id: String? = null) = owned { gate.withLock { reconcileLocked(id) } } private suspend fun reconcileLocked(id: String? = null) { owner.ensureActive() val prefs = preferences() if (prefs.jobs.isEmpty()) return fileCursors.keys.retainAll(prefs.jobs.mapTo(mutableSetOf()) { it.id }) val binding = accountBinding(prefs) val client = if (validEndpoint(prefs.endpoint)) Aria2RpcClient(http, prefs.endpoint, prefs.secret) else null var work = _jobs.value.associateBy { it.id }.let { live -> prefs.jobs.map { live[it.id] ?: it } } val bound = work.map { job -> if (job.terminal) job else if (client == null || job.endpoint != prefs.endpoint || job.accountBinding != binding) job.copy(problem = RemoteDownloadProblem.ServerChanged) else if (job.problem == RemoteDownloadProblem.ServerChanged) job.copy(problem = RemoteDownloadProblem.None) else job } if (bound != work) { work = bound; save(work, durable = true) } if (client == null) return var failed = false var statusChanged = false // Work is bounded per pass; rotate jobs so a large chapter cannot starve later requests. val candidates = work.filter { !it.terminal && it.endpoint == prefs.endpoint && it.accountBinding == binding }.sortedBy { it.createdAt } val ordered = if (id != null) candidates.filter { it.id == id } else if (candidates.isEmpty()) emptyList() else List(minOf(4, candidates.size)) { candidates[(jobCursor + it) % candidates.size] } jobCursor = if (candidates.isEmpty()) 0 else (jobCursor + ordered.size) % candidates.size for (old in ordered) { var job = old try { job = reconcileJob(client, job) if (job.problem == RemoteDownloadProblem.Connection) failed = true } catch (cancel: CancellationException) { throw cancel } catch (_: AccountChanged) { job = job.copy(problem = RemoteDownloadProblem.ServerChanged) } catch (_: Exception) { failed = true; job = job.copy(problem = RemoteDownloadProblem.Connection) } statusChanged = statusChanged || job.copy(files = job.files.map { it.copy(totalBytes = 0, completedBytes = 0) }) != old.copy(files = old.files.map { it.copy(totalBytes = 0, completedBytes = 0) }) work = work.map { if (it.id == job.id) job else it } // Acknowledgements are durable before another job's remote side effects. if (statusChanged) { save(work, durable = true); statusChanged = false } else _jobs.update { work } if (failed) break } if (clock() - lastProgressSave >= 15_000) { save(work, durable = false); lastProgressSave = clock() } if (failed) error("External download server unavailable") } private suspend fun reconcileJob(client: Aria2RpcClient, original: DbRemoteDownloadJob): DbRemoteDownloadJob { var job = original.copy(problem = RemoteDownloadProblem.None) val files = job.files.toMutableList() val eligible = files.filter { it.state !in setOf(RemoteDownloadState.Pending, RemoteDownloadState.Complete, RemoteDownloadState.Removed) } val cursor = fileCursors[job.id] ?: 0 val query = if (eligible.isEmpty()) emptyList() else List(minOf(64, eligible.size)) { eligible[(cursor + it) % eligible.size] } fileCursors[job.id] = if (eligible.isEmpty()) 0 else (cursor + query.size) % eligible.size for (batch in query.chunked(64)) { requireCurrent(job) val statuses = client.statuses(batch.map { it.gid }) for (file in batch) { val index = files.indexOfFirst { it.gid == file.gid } val result = statuses.getValue(file.gid) val status = result.getOrNull() if (status == null) { // Never re-admit an uncertain/missing GID automatically, even after server restart. files[index] = file.copy(state = RemoteDownloadState.Attention) job = job.copy(problem = RemoteDownloadProblem.MissingOrRejected) continue } files[index] = file.copy(state = RemoteDownloadState.valueOf(status.status.name), totalBytes = status.totalBytes, completedBytes = status.completedBytes, errorCode = status.errorCode, url = "", headers = emptyMap()) when { job.intent == RemoteDownloadIntent.Cancel && status.status == Aria2Status.Error -> files[index] = files[index].copy(state = RemoteDownloadState.Removed) job.intent == RemoteDownloadIntent.Cancel && status.status !in setOf(Aria2Status.Complete, Aria2Status.Removed) -> { requireCurrent(job); client.cancel(file.gid) } job.intent == RemoteDownloadIntent.Pause && status.status in setOf(Aria2Status.Active, Aria2Status.Waiting) -> { requireCurrent(job); client.pause(file.gid) } job.intent == RemoteDownloadIntent.Run && status.status == Aria2Status.Paused -> { requireCurrent(job); client.resume(file.gid) } } } } if (files.any { it.state == RemoteDownloadState.Attention }) return job.copy(files = files.toList(), problem = RemoteDownloadProblem.MissingOrRejected) val pending = files.withIndex().filter { it.value.state == RemoteDownloadState.Pending }.take(4) for ((index, file) in pending) { if (job.intent == RemoteDownloadIntent.Cancel) { files[index] = file.copy(state = RemoteDownloadState.Removed, url = "", headers = emptyMap()); continue } if (job.intent == RemoteDownloadIntent.Pause) continue files[index] = file.copy(state = RemoteDownloadState.Submitting) job = job.copy(files = files.toList()) val all = preferences().jobs.map { if (it.id == job.id) job else it } save(all, durable = true) try { requireCurrent(job) client.addUri(file.gid, file.url, job.directory, file.name, file.headers) files[index] = file.copy(state = RemoteDownloadState.Waiting, url = "", headers = emptyMap()) } catch (cancel: CancellationException) { throw cancel } catch (changed: AccountChanged) { throw changed } catch (_: Exception) { // Persist Submitting: the request may have reached the server even when its reply did not. return job.copy(files = files.toList(), problem = RemoteDownloadProblem.Connection) } } return job.copy(files = files.toList()) } private suspend fun save(jobs: List, durable: Boolean) { owner.ensureActive() if (preferences().jobs != jobs) database.batch { val current = database.settings() database.updateSettings(current.copy(features = current.features.copy(externalDownloads = current.features.externalDownloads.copy(jobs = jobs)))) } _jobs.update { jobs } if (durable) database.awaitPersistence() } private fun preferences() = database.settings().features.externalDownloads private fun requireSourceIdentity(job: DbRemoteDownloadJob) { val chapter = database.chapter(job.chapterId) val title = chapter?.mangaId?.let(database::manga) require(chapter != null && title != null && title.id == job.mangaId && title.sourceId == job.sourceId && title.link == job.mangaLink && chapter.url == job.chapterUrl && title.itemType == job.itemType && !title.isLocalArchive && (!job.mangaLink.isNullOrBlank() || job.chapterUrl.isNotBlank() || (title.name.orEmpty() == job.sourceTitleName && chapter.name.orEmpty() == job.sourceChapterName))) { "Source identity changed; enqueue the chapter again" } } private class AccountChanged : IllegalStateException() private fun requireCurrent(job: DbRemoteDownloadJob) { owner.ensureActive() if (preferences().let { it.endpoint != job.endpoint || accountBinding(it) != job.accountBinding }) throw AccountChanged() } private suspend fun owned(action: suspend () -> T): T = scope.runJoined { action() } companion object { private fun needsPolling(job: DbRemoteDownloadJob, watched: Boolean): Boolean { if (job.problem == RemoteDownloadProblem.ServerChanged) return false val uncertain = job.files.any { it.state == RemoteDownloadState.Attention } return job.files.any { file -> when (file.state) { RemoteDownloadState.Pending -> !uncertain && job.intent != RemoteDownloadIntent.Pause RemoteDownloadState.Submitting -> true RemoteDownloadState.Active, RemoteDownloadState.Waiting -> watched || job.intent != RemoteDownloadIntent.Run RemoteDownloadState.Paused -> watched || job.intent != RemoteDownloadIntent.Pause RemoteDownloadState.Error -> job.intent == RemoteDownloadIntent.Cancel else -> false } } } fun validConfiguration(prefs: DbExternalDownloads): Boolean = validEndpoint(prefs.endpoint) && validDirectory(prefs.directory) fun validEndpoint(value: String): Boolean = Aria2RpcClient.validEndpoint(value) fun validDirectory(value: String): Boolean = value.isNotBlank() && value.none { it.code < 32 } && value.replace('\\', '/').split('/').none { it == ".." } internal fun accountBinding(prefs: DbExternalDownloads): String = sha256((prefs.endpoint + "\u0000" + prefs.secret).encodeToByteArray()).toHexString() private fun resourceBinding(page: DbPageUrl): String = sha256((page.url + "\u0000" + page.headers.orEmpty().entries.sortedBy { it.key.lowercase() }.joinToString("\u0000") { it.key.lowercase() + ":" + it.value }).encodeToByteArray()).toHexString() private fun newGid(): String = Random.nextBytes(8).toHexString().takeUnless { it.all { c -> c == '0' } } ?: newGid() private fun publicDownloadUri(url: String): Boolean = catchingNonCancellation { Url(url).let { it.protocol.name in setOf("http", "https") && it.host.isNotBlank() && it.user.isNullOrEmpty() && it.password.isNullOrEmpty() } }.getOrDefault(false) private fun extension(url: String, type: DbItemType): String = url.substringBefore('?').substringBefore('#').substringAfterLast('/').substringAfterLast('.', "").lowercase().takeIf { it in setOf("jpg", "jpeg", "png", "gif", "webp", "bmp", "avif", "mp4", "mkv", "webm", "mov", "avi", "m4v") } ?: if (type == DbItemType.Anime) "mp4" else "jpg" } }