package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.services.notifications.RecordingNotifications import eu.friedcutlet.yokan.database.DbDownload import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.seedDatabaseSnapshot import eu.friedcutlet.yokan.services.files.LocalArchiveService import eu.friedcutlet.yokan.services.files.LocalEpubChapter import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.files.MemoryFiles import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.HttpStreamResponse 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 kotlin.random.Random import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.currentTime import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest @OptIn(ExperimentalCoroutinesApi::class) class PersistentDownloadServiceTest { private val location = "/downloads/Manga/Src (EN)/Title/Ch 10" @Test fun pagesResolveWhenEachChapterStartsAndRowsKeepRequestOrder() = runTest { val database = database() val release = CompletableDeferred() val resolved = mutableListOf() val http = ScriptedHttp { request -> if ("c11" in request.url) release.await(); Reply(200) } val service = service(database, http) { chapterId, _ -> resolved += chapterId listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg")) } service.enqueue(request(database, 11)) service.enqueue(request(database, 10)) assertEquals(listOf(11L, 10L), database.downloads().map { it.chapterId }) assertEquals(emptyList(), resolved) runCurrent() // One chapter per source: the second chapter is not resolved until the first one is done. assertEquals(listOf(11L), resolved) release.complete(Unit) advanceUntilIdle() assertEquals(listOf(11L, 10L), resolved) } @Test fun expiredPageUrlIsResolvedAgainOnceAndRetried() = runTest { val database = database() val http = ScriptedHttp { request -> Reply(if ("old" in request.url) 403 else 200) } val refreshes = mutableListOf() val service = service(database, http) { _, forceRefresh -> refreshes += forceRefresh listOf(DbPageUrl(url = if (forceRefresh) "https://img.test/new/1.jpg" else "https://img.test/old/1.jpg")) } service.enqueue(request(database, 10)) advanceUntilIdle() assertEquals(listOf(false, true), refreshes) // A 403 is never retried against the same URL. assertEquals(listOf("https://img.test/old/1.jpg", "https://img.test/new/1.jpg"), http.requested) assertEquals(true, database.downloads().single().isDownload) } @Test fun changedPageCountRestartsTheChapterAndDropsStalePages() = runTest { val database = database() val files = MemoryFiles() val http = ScriptedHttp { request -> Reply(if ("old" in request.url) 410 else 200) } val service = service(database, http, files) { _, forceRefresh -> if (forceRefresh) { listOf(DbPageUrl(url = "https://img.test/new/1.jpg")) } else { listOf(DbPageUrl(url = "https://img.test/old/1.jpg"), DbPageUrl(url = "https://img.test/kept/2.jpg")) } } service.enqueue(request(database, 10)) advanceUntilIdle() assertEquals(true, database.downloads().single().isDownload) assertEquals(1, database.downloads().single().total) assertTrue("$location/0001.jpg" in files.paths) assertFalse(files.paths.any { it.startsWith("$location/0002") }) } @Test fun retryAfterRestartRebuildsTheRequestFromTheChapter() = runTest { val database = database() val files = MemoryFiles() var status = 400 val http = ScriptedHttp { Reply(status) } val pages: suspend (Long, Boolean) -> List = { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) } service(database, http, files, resolve = pages).enqueue(request(database, 10)) advanceUntilIdle() assertEquals(false, database.downloads().single().isStartDownload) status = 200 val restarted = service(database, http, files, resolve = pages) assertTrue(restarted.retry(downloadTaskId(10, 0))) assertFalse(restarted.retry(downloadTaskId(999, 0))) advanceUntilIdle() assertEquals(true, database.downloads().single().isDownload) assertEquals(location, database.chapter(10)?.archivePath) } @Test fun interruptedDownloadResumesOnStartup() = runTest { val database = database() database.upsertDownload(DbDownload(chapterId = 10, succeeded = 1, total = 3, isDownload = false, isStartDownload = true)) val service = service(database, ScriptedHttp { Reply(200) }) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) } service.initialize() advanceUntilIdle() assertEquals(true, database.downloads().single().isDownload) } @Test fun enqueueRetryAndStartupDoNotRecreateRowsForDeletedParents() = runTest { val database = database() val staleRequest = request(database, 10) val service = service(database, ScriptedHttp { Reply(400) }) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) } service.enqueue(staleRequest) advanceUntilIdle() database.upsertDownload(DbDownload(id = 99, chapterId = 10, isStartDownload = true)) database.batch { database.removeChapter(10) database.removeManga(1) database.removeDownload(99) } service.enqueue(staleRequest) assertFalse(service.retry(downloadTaskId(10, 0))) service(database, ScriptedHttp { Reply(200) }) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }.initialize() assertEquals(null, database.download(99)) assertEquals(null, database.chapter(10)) assertEquals(null, database.manga(1)) } @Test fun deletingParentAtFinalizationDoesNotRestoreChapterOrDownloadAndOtherTypeContinues() = runTest { val database = database() val gate = CompletableDeferred() val entered = CompletableDeferred() val http = ScriptedHttp { request -> if ("c10" in request.url) { entered.complete(Unit) gate.await() } Reply(200) } val service = service(database, http) { chapterId, _ -> listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg")) } service.enqueue(request(database, 10)) service.enqueue(request(database, 11)) runCurrent() entered.await() database.batch { database.removeChapter(10) database.removeManga(1) } database.upsertSource(DbSource(id = 8, name = "Other source", lang = "en")) database.upsertManga(DbManga(id = 2, name = "Other", sourceId = 8, itemType = DbItemType.Anime)) database.upsertChapter(DbChapter(id = 20, mangaId = 2, url = "/c20", name = "Other chapter")) service.enqueue(request(database, 20)) gate.complete(Unit) advanceUntilIdle() assertEquals(null, database.chapter(10)) assertEquals(null, database.manga(1)) assertEquals(false, database.downloads().first { it.chapterId == 10L }.isDownload) assertEquals(true, database.downloads().first { it.chapterId == 20L }.isDownload) } @Test fun duplicateEnqueueIsSkippedWhileQueuedOrDownloaded() = runTest { val database = database() val files = MemoryFiles() val http = ScriptedHttp { Reply(200) } val service = service(database, http, files) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) } service.enqueue(request(database, 10)) service.enqueue(request(database, 10)) advanceUntilIdle() service.enqueue(request(database, 10)) advanceUntilIdle() assertEquals(1, http.requested.size) assertEquals(1, database.downloads().size) files.deleteRecursively(location) service.enqueue(request(database, 10)) advanceUntilIdle() assertEquals(2, http.requested.size) assertEquals(location, database.chapter(10)?.archivePath) } @Test fun pagesDownloadInParallelAndEveryPageIsCounted() = runTest { val database = database() val gate = CompletableDeferred() var inFlight = 0 var maxInFlight = 0 val http = ScriptedHttp { inFlight += 1 maxInFlight = maxOf(maxInFlight, inFlight) gate.await() inFlight -= 1 Reply(200) } val service = service(database, http) { _, _ -> (1..7).map { DbPageUrl(url = "https://img.test/$it.jpg") } } service.enqueue(request(database, 10)) runCurrent() assertEquals(PAGE_PARALLELISM, inFlight) gate.complete(Unit) advanceUntilIdle() assertEquals(PAGE_PARALLELISM, maxInFlight) val row = database.downloads().single() assertEquals(7, row.succeeded) assertEquals(7, row.total) assertEquals(true, row.isDownload) } @Test fun clientErrorsFailAtOnceWhileRetryAfterIsHonoured() = runTest { val database = database() val calls = mutableListOf>() var throttled = false val http = ScriptedHttp { request -> calls += request.url to currentTime when { "bad" in request.url -> Reply(400) !throttled -> Reply(429, headers = mapOf("retry-after" to "7")).also { throttled = true } else -> Reply(200) } } val pages = mapOf(10L to "https://img.test/bad.jpg", 11L to "https://img.test/busy.jpg") val service = service(database, http) { chapterId, _ -> listOf(DbPageUrl(url = pages.getValue(chapterId))) } service.enqueue(request(database, 10)) advanceUntilIdle() service.enqueue(request(database, 11)) advanceUntilIdle() assertEquals(1, calls.count { "bad" in it.first }) val busy = calls.filter { "busy" in it.first }.map { it.second } assertEquals(2, busy.size) assertEquals(7_000L, busy[1] - busy[0]) assertEquals(false, database.downloads().first { it.chapterId == 10L }.isDownload) assertEquals(true, database.downloads().first { it.chapterId == 11L }.isDownload) } @Test fun retryDelayUsesRetryAfterElseJitteredExponentialBackoff() { assertEquals(3_000L, downloadRetryDelayMs(1, "3")) assertEquals(60_000L, downloadRetryDelayMs(1, "3600")) repeat(20) { val random = Random(it) assertTrue(downloadRetryDelayMs(1, null, random) in 500L..1_000L) assertTrue(downloadRetryDelayMs(3, "Wed, 21 Oct 2015 07:28:00 GMT", random) in 2_000L..4_000L) } assertTrue(isRetryableDownloadStatus(408) && isRetryableDownloadStatus(429) && isRetryableDownloadStatus(503)) assertFalse(isRetryableDownloadStatus(404) || isRetryableDownloadStatus(400)) } @Test fun completedDownloadMarksItsChapterWithTheArchiveTheReaderOpens() = runTest { val database = database { it.copy(saveAsCBZArchive = true) } val archives = RecordingArchives() val service = service(database, ScriptedHttp { Reply(200, ByteArray(2_000_000)) }, archives = archives) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) } service.enqueue(request(database, 10)) advanceUntilIdle() assertEquals(listOf(location), archives.zipped) val chapter = assertNotNull(database.chapter(10)) assertEquals("$location.cbz", chapter.archivePath) assertEquals("1.9 MB", chapter.downloadSize) } @Test fun pausingWhileTheChapterIsArchivedStillFinishesItOnce() = runTest { val database = database { it.copy(saveAsCBZArchive = true) } lateinit var service: PersistentDownloadService var pauses = 0 val archives = RecordingArchives(onZip = { if (pauses++ == 0) service.pause(downloadTaskId(10, 0)) }) val http = ScriptedHttp { Reply(200) } service = service(database, http, archives = archives) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) } service.enqueue(request(database, 10)) advanceUntilIdle() service.resume(downloadTaskId(10, 0)) advanceUntilIdle() assertEquals("$location.cbz", database.chapter(10)?.archivePath) assertEquals(true, database.downloads().single().isDownload) assertEquals(1, http.requested.size, "a finished chapter is not fetched again") assertEquals(1, archives.zipped.size) } @Test fun pausingARunningChapterFreesItsSourceAndResumeContinuesIt() = runTest { val database = database() val stalledOnce = mutableSetOf() val http = ScriptedHttp { request -> if ("c10" in request.url && stalledOnce.add(request.url)) { awaitCancellation() } Reply(200) } val service = service(database, http) { chapterId, _ -> listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg")) } service.enqueue(request(database, 10)) service.enqueue(request(database, 11)) runCurrent() service.pause(downloadTaskId(10, 0)) advanceUntilIdle() assertEquals(true, database.downloads().first { it.chapterId == 11L }.isDownload) assertEquals(false, database.downloads().first { it.chapterId == 10L }.isDownload) service.resume(downloadTaskId(10, 0)) advanceUntilIdle() assertEquals(true, database.downloads().first { it.chapterId == 10L }.isDownload) } @Test fun contentUriDownloadFoldersAreRejectedBeforeAnythingIsRecorded() = runTest { val database = database() val service = service(database, ScriptedHttp { Reply(200) }) { _, _ -> emptyList() } assertFailsWith { service.enqueue(request(database, 10).copy(destinationRoot = "content://com.android.externalstorage.documents/tree/primary%3AComics")) } assertEquals(emptyList(), database.downloads()) } @Test fun hlsPageFollowsTheBestVariantAndSavesKeyAndSegmentsLocally() = runTest { val database = database() val files = MemoryFiles() val playlists = mapOf( "https://cdn.test/show/master.m3u8?token=a" to """ #EXTM3U #EXT-X-STREAM-INF:BANDWIDTH=800000,CODECS="avc1,mp4a" low/index.m3u8 #EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=9000000,BANDWIDTH=2000000 high/index.m3u8 """.trimIndent(), "https://cdn.test/show/high/index.m3u8" to """ #EXTM3U #EXT-X-KEY:METHOD=AES-128,URI="/keys/k1.bin",IV=0x1 seg0.ts #EXT-X-KEY:METHOD=AES-128,URI="/keys/k1.bin",IV=0x2 https://other.test/seg1.ts """.trimIndent(), ) var segmentFailures = 1 val http = ScriptedHttp( text = { request -> playlists[request.url]?.let { HttpResponse(200, it) } ?: HttpResponse(404, "") }, ) { request -> if ("seg0" in request.url && segmentFailures-- > 0) Reply(503) else Reply(200) } val service = service(database, http, files) { _, _ -> listOf(DbPageUrl(url = "https://cdn.test/show/master.m3u8?token=a")) } service.enqueue(request(database, 10)) advanceUntilIdle() assertEquals(true, database.downloads().single().isDownload) assertEquals( listOf("https://cdn.test/keys/k1.bin", "https://cdn.test/show/high/seg0.ts", "https://cdn.test/show/high/seg0.ts", "https://other.test/seg1.ts").sorted(), http.requested.sorted(), ) assertEquals( """ #EXTM3U #EXT-X-KEY:METHOD=AES-128,URI="0001_key_0.key",IV=0x1 0001_seg_0000.ts #EXT-X-KEY:METHOD=AES-128,URI="0001_key_0.key",IV=0x2 0001_seg_0001.ts """.trimIndent(), files.readBytes("$location/0001.m3u8").decodeToString(), ) assertTrue("$location/0001.m3u8.complete" in files.paths) } @Test fun wifiOnlyKeepsDownloadsQueuedOnAMeteredNetworkUntilWifiReturns() = runTest { val database = database { it.copy(downloadOnlyOnWifi = true) } val network = FakeNetwork(unmetered = false) val notifications = RecordingNotifications() val http = ScriptedHttp { Reply(200) } val service = service(database, http, network = network, notifications = notifications) { chapterId, _ -> listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg")) } service.enqueue(request(database, 10)) service.enqueue(request(database, 11)) service.pause(downloadTaskId(11, 0)) advanceUntilIdle() assertEquals(DownloadQueueStatus(pending = 1, waitingForWifi = true), service.queueStatus.value) assertEquals(emptyList(), http.requested) assertEquals(listOf(true, true), database.downloads().map { it.isStartDownload }) assertEquals(1, notifications.posted.count { it.tag == WAITING_FOR_WIFI_NOTIFICATION_TAG }, "one notification, not one per chapter") network.unmetered.value = true advanceUntilIdle() assertEquals(DownloadQueueStatus(), service.queueStatus.value) assertEquals(true, database.downloads().first { it.chapterId == 10L }.isDownload) assertEquals(false, database.downloads().first { it.chapterId == 11L }.isDownload, "a paused chapter stays paused") assertEquals(listOf(WAITING_FOR_WIFI_NOTIFICATION_TAG), notifications.cancelled.map { it.second }) } @Test fun meteredNetworkPausesARunningChapterAtItsNextPageAndTurningWifiOnlyOffResumesIt() = runTest { val database = database { it.copy(downloadOnlyOnWifi = true) } val network = FakeNetwork(unmetered = true) val http = ScriptedHttp { request -> // The phone leaves Wi-Fi while the first page is downloading. if (request.url.endsWith("/1.jpg")) network.unmetered.value = false Reply(200) } val pages = (1..3).map { DbPageUrl(url = "https://img.test/$it.jpg") } val service = service(database, http, network = network) { _, _ -> pages } service.enqueue(request(database, 10)) advanceUntilIdle() assertEquals(listOf("https://img.test/1.jpg"), http.requested) assertEquals(1, service.activeDownloads().single().succeeded) assertEquals(DownloadQueueStatus(pending = 1, waitingForWifi = true), service.queueStatus.value) database.updateSettings(database.settings().copy(downloadOnlyOnWifi = false)) advanceUntilIdle() assertEquals(pages.map { it.url }, http.requested.sorted(), "the saved page is not fetched again") assertEquals(true, database.downloads().single().isDownload) assertEquals(DownloadQueueStatus(), service.queueStatus.value) } @Test fun restartPreservesPausedQueueAndExactDestination() = runTest { val database = database() val request = request(database, 10).copy(destinationRoot = "/one-off", retries = 1) database.upsertDownload(eu.friedcutlet.yokan.database.DbDownload( id = 50, chapterId = 10, isStartDownload = true, isPaused = true, storageLocation = "/one-off/exact/chapter", requestJson = eu.friedcutlet.yokan.database.DatabaseJson.encodeToString(DownloadRequest.serializer(), request), )) val files = MemoryFiles() val http = ScriptedHttp { Reply(200) } val downloader = service(database, http, files) { _, _ -> listOf(DbPageUrl("https://test/page.jpg")) } assertEquals("/one-off/exact/chapter", downloader.storageLocation(request.taskId)) downloader.initialize() advanceUntilIdle() assertTrue(http.requested.isEmpty()) assertTrue(downloader.activeDownloads().single().isPaused) assertTrue(database.download(50)?.isPaused == true) downloader.resume(request.taskId) advanceUntilIdle() assertEquals(true, database.download(50)?.isDownload) assertEquals(false, database.download(50)?.isPaused) assertTrue(files.paths.any { it.startsWith("/one-off/exact/chapter/") }) } @Test fun hlsSegmentsUseBoundedConcurrencyAndCountSavedBytes() = runTest { val database = database() val playlist = "#EXTM3U\n" + (1..8).joinToString("\n") { "segment$it.ts" } var inFlight = 0 var maximum = 0 val http = ScriptedHttp(text = { HttpResponse(200, playlist) }) { inFlight++ maximum = maxOf(maximum, inFlight) kotlinx.coroutines.delay(10) inFlight-- Reply(200, byteArrayOf(1, 2, 3)) } val files = MemoryFiles() val downloadRequest = request(database, 10) files.writeBytes("$location/0001_seg_0000.ts", byteArrayOf(1, 2, 3)) files.writeBytes("$location/0001_seg_0000.ts.complete", byteArrayOf()) val downloader = service(database, http, files) { _, _ -> listOf(DbPageUrl("https://test/video.m3u8")) } var downloadedBytes = 0L downloader.enqueue(downloadRequest) { downloadedBytes = it.bytesDownloaded } advanceUntilIdle() assertEquals(PAGE_PARALLELISM, maximum) assertEquals(7, http.requested.size) assertEquals(24L + playlist.length, downloadedBytes) assertEquals(true, database.downloads().single().isDownload) } @Test fun automatedDeletionChecksEligibilityAndLeavesIncompleteTransfersUntouched() = runTest { val database = database() val files = MemoryFiles().apply { writeBytes("$location/0001.jpg", byteArrayOf(1)) } val downloader = service(database, ScriptedHttp { Reply(200) }, files) { _, _ -> emptyList() } database.upsertDownload(DbDownload(chapterId = 10, storageLocation = location, isDownload = false)) assertFalse(downloader.deleteCompletedArtifacts("chapter-10")) database.upsertDownload(database.downloads().single().copy(isDownload = true)) assertFalse(downloader.deleteCompletedArtifacts("chapter-10", stillEligible = { false })) assertTrue(files.exists(location)) assertTrue(downloader.deleteCompletedArtifacts("chapter-10")) assertFalse(files.exists(location)) } @Test fun automatedDeletionRefusesMalformedRootAndTitleLocations() = runTest { for (bad in listOf("/", "/downloads", "/downloads/Manga/Src (EN)/Title", "/downloads/Manga/Src (EN)/Title/../other", "")) { val database = database() val files = MemoryFiles().apply { writeBytes("/downloads/important.jpg", byteArrayOf(1)) } val downloader = service(database, ScriptedHttp { Reply(200) }, files) { _, _ -> emptyList() } database.upsertDownload(DbDownload(chapterId = 10, storageLocation = bad, isDownload = true)) // Blank locations fall back to the derived chapter folder, never the root. if (bad.isNotBlank()) assertFalse(downloader.deleteCompletedArtifacts("chapter-10"), bad) assertTrue(files.exists("/downloads/important.jpg")) } } @Test fun automatedDeletionReportsFilesystemFailureAndRejectsRedirectedPaths() = runTest { val database = database() val files = GuardedFiles().apply { writeBytes("$location/0001.jpg", byteArrayOf(1)); rejectDeletion = true } val downloader = service(database, ScriptedHttp { Reply(200) }, files) { _, _ -> emptyList() } database.upsertDownload(DbDownload(chapterId = 10, storageLocation = location, isDownload = true)) assertFalse(downloader.deleteCompletedArtifacts("chapter-10")) assertTrue(files.exists(location)) files.rejectDeletion = false files.redirectedPaths[location] = "/downloads" assertFalse(downloader.deleteCompletedArtifacts("chapter-10")) assertTrue(files.exists(location)) } @Test fun novelDownloadSavesChapterHtmlAndIsReadableWithoutPageListCalls() = runTest { val database = database() database.upsertManga(database.manga(1)!!.copy(itemType = DbItemType.Novel)) val files = MemoryFiles() val downloader = PersistentDownloadService( database, ScriptedHttp { error("No image fetch expected") }, files, RecordingArchives(), this, resolvePages = { _, _ -> error("Novels use htmlContent") }, ioDispatcher = StandardTestDispatcher(testScheduler), resolveNovelText = { "

Offline novel

" }, ) downloader.enqueue(request(database, 10)) advanceUntilIdle() val chapter = database.chapter(10)!! assertTrue(database.downloads().single().isDownload == true) assertEquals("

Offline novel

", files.readBytes("${chapter.archivePath}/0001.html").decodeToString()) assertTrue(files.exists("${chapter.archivePath}/0001.html.complete")) } private fun request(database: InMemoryYokanDatabase, chapterId: Long): DownloadRequest = checkNotNull(chapterDownloadRequest(database, chapterId)) private fun database(settings: (DbSettings) -> DbSettings = { it }): InMemoryYokanDatabase { val seed = seedDatabaseSnapshot() return InMemoryYokanDatabase( seed.copy( settings = settings(seed.settings), sources = listOf(DbSource(id = 7, name = "Src", lang = "en")), mangas = listOf(DbManga(id = 1, name = "Title", sourceId = 7, itemType = DbItemType.Manga)), chapters = listOf( DbChapter(id = 10, mangaId = 1, url = "/c10", name = "Ch 10"), DbChapter(id = 11, mangaId = 1, url = "/c11", name = "Ch 11"), ), ), ) } private fun TestScope.service( database: InMemoryYokanDatabase, http: HttpService, files: LocalFileService = MemoryFiles(), archives: LocalArchiveService = RecordingArchives(), network: NetworkMonitor = UnmeteredNetwork, notifications: NotificationService? = null, resolve: suspend (Long, Boolean) -> List, ) = PersistentDownloadService( database = database, http = http, files = files, archives = archives, // Not backgroundScope: advanceUntilIdle() does not wait for background work. scope = this, resolvePages = resolve, notifications = notifications, network = network, ioDispatcher = StandardTestDispatcher(testScheduler), ) } private class FakeNetwork(unmetered: Boolean) : NetworkMonitor { override val unmetered = MutableStateFlow(unmetered) } private class Reply(val status: Int, val body: ByteArray = byteArrayOf(1), val headers: Map = emptyMap()) /** Streams scripted replies and records every streamed URL; [text] answers playlist requests. */ private class ScriptedHttp( private val text: (HttpRequest) -> HttpResponse = { HttpResponse(statusCode = 404, body = "") }, private val reply: suspend (HttpRequest) -> Reply, ) : HttpService { val requested = mutableListOf() override suspend fun request(request: HttpRequest): HttpResponse = text(request) override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse { requested += request.url val answer = reply(request) onChunk(answer.body) return HttpStreamResponse(statusCode = answer.status, headers = answer.headers) } } private class RecordingArchives(private val onZip: () -> Unit = {}) : LocalArchiveService { val zipped = mutableListOf() override fun listPages(archivePath: String) = emptyList() override fun listEpubChapters(archivePath: String) = emptyList() override fun readEpubChapter(archivePath: String, index: Int) = "" override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String { zipped += directoryPath onZip() return "$directoryPath.cbz" } } /** Lets a test refuse deletion or resolve a path elsewhere, as a hostile filesystem would. */ private class GuardedFiles : MemoryFiles() { var rejectDeletion = false val redirectedPaths = mutableMapOf() override fun canonicalPath(path: String): String? = redirectedPaths[path] ?: path override fun deleteRecursively(path: String): Boolean = !rejectDeletion && super.deleteRecursively(path) }