ExternalDownloads.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/ExternalDownloads.kt
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.database.*4import eu.friedcutlet.yokan.services.catchingNonCancellation5import eu.friedcutlet.yokan.services.runJoined6import eu.friedcutlet.yokan.util.sha2567import eu.friedcutlet.yokan.services.http.HttpService8import eu.friedcutlet.yokan.util.nowMillis9import io.ktor.http.Url10import kotlinx.coroutines.*11import kotlinx.coroutines.channels.Channel12import kotlinx.coroutines.flow.*13import kotlinx.coroutines.sync.Mutex14import kotlinx.coroutines.sync.withLock15import kotlin.random.Random1617/** Profile-owned remote queue. Remote completion never writes a local archive/download mark. */18class ExternalDownloads(19 private val database: YokanDatabase,20 private val http: HttpService,21 private val scope: CoroutineScope,22 private val resolvePages: suspend (Long, Boolean) -> List<DbPageUrl>,23 private val clock: () -> Long = ::nowMillis,24 private val pollMillis: Long = 2000,25 startPolling: Boolean = true,26) {27 private val owner = requireNotNull(scope.coroutineContext[Job])28 private val gate = Mutex()29 private val wake = Channel<Unit>(Channel.CONFLATED)30 private val _jobs = MutableStateFlow(preferences().jobs)31 val jobs = _jobs.asStateFlow()32 private var lastProgressSave = 0L33 private var jobCursor = 034 private val fileCursors = mutableMapOf<String, Int>()3536 init {37 if (startPolling) {38 scope.launch {39 database.snapshots().map { it.settings.features.externalDownloads.copy(jobs = emptyList()) }.distinctUntilChanged().collect {40 wake.trySend(Unit)41 }42 }43 scope.launch { _jobs.subscriptionCount.map { it > 0 }.distinctUntilChanged().collect { if (it) wake.trySend(Unit) } }44 scope.launch {45 var backoff = pollMillis46 while (currentCoroutineContext().isActive) {47 fun hasWork() = preferences().jobs.any { needsPolling(it, _jobs.subscriptionCount.value > 0) }48 val signalled = if (hasWork()) withTimeoutOrNull(backoff) { wake.receive(); true } ?: false else { wake.receive(); true }49 if (!signalled && !hasWork()) continue50 try {51 gate.withLock { reconcileLocked() }52 backoff = pollMillis53 } catch (cancel: CancellationException) { throw cancel }54 catch (_: Exception) { backoff = (backoff * 2).coerceAtMost(60_000) }55 }56 }57 }58 }5960 /** Returns false for content that must use managed local storage (novels and HLS playlists). */61 suspend fun enqueue(request: DownloadRequest): Boolean = owned {62 gate.withLock {63 val prefs = preferences()64 require(validConfiguration(prefs)) { "Configure the external downloader server and directory first" }65 if (request.itemType == DbItemType.Novel) return@withLock false66 val chapter = database.chapter(request.chapterId) ?: error("Chapter no longer exists")67 val title = chapter.mangaId?.let(database::manga) ?: error("Title no longer exists")68 require(!title.isLocalArchive)69 if (prefs.jobs.any { it.chapterId == request.chapterId && it.endpoint == prefs.endpoint && it.accountBinding == accountBinding(prefs) && (!it.terminal || it.complete) }) return@withLock true70 val pages = withTimeoutOrNull(60_000) { resolvePages(request.chapterId, false) } ?: error("Source resolution timed out")71 require(pages.isNotEmpty() && pages.size <= 2000) { "No downloadable files resolved" }72 if (pages.any { it.url.substringBefore('?').substringBefore('#').endsWith(".m3u8", true) }) return@withLock false73 require(pages.all { publicDownloadUri(it.url) }) { "External downloads require direct HTTP image or video files" }74 val id = newGid()75 val remoteDirectory = prefs.directory.trimEnd('/', '\\') + "/Yokan/${request.itemType.name}/${sanitizeDownloadName(request.mangaName).take(50)}/${sanitizeDownloadName(request.chapterName).take(50)}_$id"76 val job = DbRemoteDownloadJob(id, request.chapterId, request.itemType, request.mangaName, request.chapterName,77 prefs.endpoint, accountBinding(prefs), remoteDirectory,78 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)) },79 createdAt = clock(), mangaId = title.id, sourceId = title.sourceId, mangaLink = title.link, chapterUrl = chapter.url, sourceTitleName = title.name.orEmpty(), sourceChapterName = chapter.name.orEmpty())80 // Resolving can suspend while settings/the chapter change. Recheck before durable admission.81 require(preferences().let { it.endpoint == prefs.endpoint && accountBinding(it) == job.accountBinding }) { "External downloader account changed" }82 require(database.chapter(request.chapterId)?.mangaId == chapter.mangaId && database.manga(title.id) != null) { "Chapter no longer exists" }83 val existing = preferences().jobs84 require(existing.count { !it.terminal } < 100) { "External download queue is full" }85 val retained = (existing.filterNot { it.terminal }.plus(existing.filter { it.terminal }.takeLast(155)) + job)86 require(DatabaseJson.encodeToString(DbExternalDownloads.serializer(), prefs.copy(jobs = retained)).encodeToByteArray().size <= 2 * 1024 * 1024) { "External download queue exceeds its storage limit" }87 save(retained, durable = true)88 wake.trySend(Unit)89 true90 }91 }9293 suspend fun testConnection(): String = owned {94 val prefs = preferences()95 require(Aria2RpcClient.validEndpoint(prefs.endpoint)) { "Invalid external downloader URL" }96 val version = Aria2RpcClient(http, prefs.endpoint, prefs.secret).version()97 require(preferences().let { it.endpoint == prefs.endpoint && accountBinding(it) == accountBinding(prefs) })98 version99 }100101 suspend fun setIntent(id: String, intent: RemoteDownloadIntent) = owned {102 gate.withLock {103 val current = preferences().jobs104 require(current.any { it.id == id })105 save(current.map { if (it.id == id) it.copy(intent = intent, problem = RemoteDownloadProblem.None) else it }, durable = true)106 wake.trySend(Unit)107 }108 }109110 /** Only confirmed stopped remote files get a new identity; ambiguous work is never duplicated. */111 suspend fun retry(id: String) = owned {112 gate.withLock {113 val original = preferences().jobs.firstOrNull { it.id == id } ?: error("Remote download no longer exists")114 requireCurrent(original)115 requireSourceIdentity(original)116 val candidates = original.files.filter { it.state in setOf(RemoteDownloadState.Error, RemoteDownloadState.Removed, RemoteDownloadState.Attention, RemoteDownloadState.Submitting) }117 require(candidates.isNotEmpty())118 val prefs = preferences()119 val client = Aria2RpcClient(http, prefs.endpoint, prefs.secret)120 val statuses = candidates.chunked(64).flatMap { client.statuses(it.map { file -> file.gid }).entries }.associate { it.key to it.value.getOrThrow() }121 val pages = withTimeoutOrNull(60_000) { resolvePages(original.chapterId, true) } ?: error("Source resolution timed out")122 require(pages.size == original.files.size && pages.all { publicDownloadUri(it.url) && !it.url.substringBefore('?').endsWith(".m3u8", true) }) { "Download files changed; enqueue the chapter again" }123 requireCurrent(original)124 requireSourceIdentity(original)125 val files = original.files.mapIndexed { index, file ->126 val remote = statuses[file.gid] ?: return@mapIndexed file127 if (remote.status in setOf(Aria2Status.Error, Aria2Status.Removed)) {128 val gid = newGid()129 val resource = resourceBinding(pages[index])130 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)}"131 DbRemoteDownloadFile(gid, name, pages[index].url, pages[index].headers.orEmpty(), resourceBinding = resource)132 }133 else file.copy(state = RemoteDownloadState.valueOf(remote.status.name), url = "", headers = emptyMap(), totalBytes = remote.totalBytes, completedBytes = remote.completedBytes)134 }135 save(preferences().jobs.map { if (it.id == id) original.copy(files = files, intent = RemoteDownloadIntent.Run, problem = RemoteDownloadProblem.None) else it }, durable = true)136 wake.trySend(Unit)137 }138 }139140 /** Removes the local receipt only after every remote task is confirmed stopped/completed. */141 suspend fun remove(id: String, forgetUnverified: Boolean = false) = owned {142 gate.withLock {143 val current = preferences().jobs144 val job = current.firstOrNull { it.id == id } ?: return@withLock145 require(job.terminal || forgetUnverified) { "Cancel the remote download before removing its receipt" }146 save(current.filterNot { it.id == id }, durable = true)147 }148 }149150 /** Also exposed to foreground refresh and deterministic recovery tests. */151 suspend fun reconcile(id: String? = null) = owned { gate.withLock { reconcileLocked(id) } }152153 private suspend fun reconcileLocked(id: String? = null) {154 owner.ensureActive()155 val prefs = preferences()156 if (prefs.jobs.isEmpty()) return157 fileCursors.keys.retainAll(prefs.jobs.mapTo(mutableSetOf()) { it.id })158 val binding = accountBinding(prefs)159 val client = if (validEndpoint(prefs.endpoint)) Aria2RpcClient(http, prefs.endpoint, prefs.secret) else null160 var work = _jobs.value.associateBy { it.id }.let { live -> prefs.jobs.map { live[it.id] ?: it } }161 val bound = work.map { job ->162 if (job.terminal) job163 else if (client == null || job.endpoint != prefs.endpoint || job.accountBinding != binding) job.copy(problem = RemoteDownloadProblem.ServerChanged)164 else if (job.problem == RemoteDownloadProblem.ServerChanged) job.copy(problem = RemoteDownloadProblem.None)165 else job166 }167 if (bound != work) { work = bound; save(work, durable = true) }168 if (client == null) return169 var failed = false170 var statusChanged = false171 // Work is bounded per pass; rotate jobs so a large chapter cannot starve later requests.172 val candidates = work.filter { !it.terminal && it.endpoint == prefs.endpoint && it.accountBinding == binding }.sortedBy { it.createdAt }173 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] }174 jobCursor = if (candidates.isEmpty()) 0 else (jobCursor + ordered.size) % candidates.size175 for (old in ordered) {176 var job = old177 try {178 job = reconcileJob(client, job)179 if (job.problem == RemoteDownloadProblem.Connection) failed = true180 } catch (cancel: CancellationException) { throw cancel }181 catch (_: AccountChanged) { job = job.copy(problem = RemoteDownloadProblem.ServerChanged) }182 catch (_: Exception) { failed = true; job = job.copy(problem = RemoteDownloadProblem.Connection) }183 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) })184 work = work.map { if (it.id == job.id) job else it }185 // Acknowledgements are durable before another job's remote side effects.186 if (statusChanged) { save(work, durable = true); statusChanged = false }187 else _jobs.update { work }188 if (failed) break189 }190 if (clock() - lastProgressSave >= 15_000) { save(work, durable = false); lastProgressSave = clock() }191 if (failed) error("External download server unavailable")192 }193194 private suspend fun reconcileJob(client: Aria2RpcClient, original: DbRemoteDownloadJob): DbRemoteDownloadJob {195 var job = original.copy(problem = RemoteDownloadProblem.None)196 val files = job.files.toMutableList()197 val eligible = files.filter { it.state !in setOf(RemoteDownloadState.Pending, RemoteDownloadState.Complete, RemoteDownloadState.Removed) }198 val cursor = fileCursors[job.id] ?: 0199 val query = if (eligible.isEmpty()) emptyList() else List(minOf(64, eligible.size)) { eligible[(cursor + it) % eligible.size] }200 fileCursors[job.id] = if (eligible.isEmpty()) 0 else (cursor + query.size) % eligible.size201 for (batch in query.chunked(64)) {202 requireCurrent(job)203 val statuses = client.statuses(batch.map { it.gid })204 for (file in batch) {205 val index = files.indexOfFirst { it.gid == file.gid }206 val result = statuses.getValue(file.gid)207 val status = result.getOrNull()208 if (status == null) {209 // Never re-admit an uncertain/missing GID automatically, even after server restart.210 files[index] = file.copy(state = RemoteDownloadState.Attention)211 job = job.copy(problem = RemoteDownloadProblem.MissingOrRejected)212 continue213 }214 files[index] = file.copy(state = RemoteDownloadState.valueOf(status.status.name), totalBytes = status.totalBytes,215 completedBytes = status.completedBytes, errorCode = status.errorCode, url = "", headers = emptyMap())216 when {217 job.intent == RemoteDownloadIntent.Cancel && status.status == Aria2Status.Error -> files[index] = files[index].copy(state = RemoteDownloadState.Removed)218 job.intent == RemoteDownloadIntent.Cancel && status.status !in setOf(Aria2Status.Complete, Aria2Status.Removed) -> { requireCurrent(job); client.cancel(file.gid) }219 job.intent == RemoteDownloadIntent.Pause && status.status in setOf(Aria2Status.Active, Aria2Status.Waiting) -> { requireCurrent(job); client.pause(file.gid) }220 job.intent == RemoteDownloadIntent.Run && status.status == Aria2Status.Paused -> { requireCurrent(job); client.resume(file.gid) }221 }222 }223 }224 if (files.any { it.state == RemoteDownloadState.Attention }) return job.copy(files = files.toList(), problem = RemoteDownloadProblem.MissingOrRejected)225 val pending = files.withIndex().filter { it.value.state == RemoteDownloadState.Pending }.take(4)226 for ((index, file) in pending) {227 if (job.intent == RemoteDownloadIntent.Cancel) { files[index] = file.copy(state = RemoteDownloadState.Removed, url = "", headers = emptyMap()); continue }228 if (job.intent == RemoteDownloadIntent.Pause) continue229 files[index] = file.copy(state = RemoteDownloadState.Submitting)230 job = job.copy(files = files.toList())231 val all = preferences().jobs.map { if (it.id == job.id) job else it }232 save(all, durable = true)233 try {234 requireCurrent(job)235 client.addUri(file.gid, file.url, job.directory, file.name, file.headers)236 files[index] = file.copy(state = RemoteDownloadState.Waiting, url = "", headers = emptyMap())237 } catch (cancel: CancellationException) { throw cancel }238 catch (changed: AccountChanged) { throw changed }239 catch (_: Exception) {240 // Persist Submitting: the request may have reached the server even when its reply did not.241 return job.copy(files = files.toList(), problem = RemoteDownloadProblem.Connection)242 }243 }244 return job.copy(files = files.toList())245 }246247 private suspend fun save(jobs: List<DbRemoteDownloadJob>, durable: Boolean) {248 owner.ensureActive()249 if (preferences().jobs != jobs) database.batch {250 val current = database.settings()251 database.updateSettings(current.copy(features = current.features.copy(externalDownloads = current.features.externalDownloads.copy(jobs = jobs))))252 }253 _jobs.update { jobs }254 if (durable) database.awaitPersistence()255 }256257 private fun preferences() = database.settings().features.externalDownloads258 private fun requireSourceIdentity(job: DbRemoteDownloadJob) {259 val chapter = database.chapter(job.chapterId)260 val title = chapter?.mangaId?.let(database::manga)261 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 &&262 (!job.mangaLink.isNullOrBlank() || job.chapterUrl.isNotBlank() || (title.name.orEmpty() == job.sourceTitleName && chapter.name.orEmpty() == job.sourceChapterName))) { "Source identity changed; enqueue the chapter again" }263 }264 private class AccountChanged : IllegalStateException()265 private fun requireCurrent(job: DbRemoteDownloadJob) {266 owner.ensureActive()267 if (preferences().let { it.endpoint != job.endpoint || accountBinding(it) != job.accountBinding }) throw AccountChanged()268 }269 private suspend fun <T> owned(action: suspend () -> T): T = scope.runJoined { action() }270271 companion object {272 private fun needsPolling(job: DbRemoteDownloadJob, watched: Boolean): Boolean {273 if (job.problem == RemoteDownloadProblem.ServerChanged) return false274 val uncertain = job.files.any { it.state == RemoteDownloadState.Attention }275 return job.files.any { file ->276 when (file.state) {277 RemoteDownloadState.Pending -> !uncertain && job.intent != RemoteDownloadIntent.Pause278 RemoteDownloadState.Submitting -> true279 RemoteDownloadState.Active, RemoteDownloadState.Waiting -> watched || job.intent != RemoteDownloadIntent.Run280 RemoteDownloadState.Paused -> watched || job.intent != RemoteDownloadIntent.Pause281 RemoteDownloadState.Error -> job.intent == RemoteDownloadIntent.Cancel282 else -> false283 }284 }285 }286 fun validConfiguration(prefs: DbExternalDownloads): Boolean = validEndpoint(prefs.endpoint) && validDirectory(prefs.directory)287 fun validEndpoint(value: String): Boolean = Aria2RpcClient.validEndpoint(value)288 fun validDirectory(value: String): Boolean = value.isNotBlank() && value.none { it.code < 32 } && value.replace('\\', '/').split('/').none { it == ".." }289 internal fun accountBinding(prefs: DbExternalDownloads): String = sha256((prefs.endpoint + "\u0000" + prefs.secret).encodeToByteArray()).toHexString()290 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()291 private fun newGid(): String = Random.nextBytes(8).toHexString().takeUnless { it.all { c -> c == '0' } } ?: newGid()292 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)293 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"294 }295}296