Yokan / rebuild
Course 1 8624561

PersistentDownloadServiceTest.kt

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadServiceTest.kt

test / fixture671 lines
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.database.DbChapter4import eu.friedcutlet.yokan.services.notifications.RecordingNotifications5import eu.friedcutlet.yokan.database.DbDownload6import eu.friedcutlet.yokan.database.DbItemType7import eu.friedcutlet.yokan.database.DbManga8import eu.friedcutlet.yokan.database.DbPageUrl9import eu.friedcutlet.yokan.database.DbSettings10import eu.friedcutlet.yokan.database.DbSource11import eu.friedcutlet.yokan.database.InMemoryYokanDatabase12import eu.friedcutlet.yokan.database.seedDatabaseSnapshot13import eu.friedcutlet.yokan.services.files.LocalArchiveService14import eu.friedcutlet.yokan.services.files.LocalEpubChapter15import eu.friedcutlet.yokan.services.files.LocalFileService16import eu.friedcutlet.yokan.services.files.MemoryFiles17import eu.friedcutlet.yokan.services.http.HttpRequest18import eu.friedcutlet.yokan.services.http.HttpResponse19import eu.friedcutlet.yokan.services.http.HttpService20import eu.friedcutlet.yokan.services.http.HttpStreamResponse21import eu.friedcutlet.yokan.services.notifications.NotificationChannel22import eu.friedcutlet.yokan.services.notifications.NotificationPayload23import eu.friedcutlet.yokan.services.notifications.NotificationService24import eu.friedcutlet.yokan.services.system.NetworkMonitor25import eu.friedcutlet.yokan.services.system.UnmeteredNetwork26import kotlin.random.Random27import kotlin.test.Test28import kotlin.test.assertEquals29import kotlin.test.assertFailsWith30import kotlin.test.assertFalse31import kotlin.test.assertNotNull32import kotlin.test.assertTrue33import kotlinx.coroutines.CompletableDeferred34import kotlinx.coroutines.ExperimentalCoroutinesApi35import kotlinx.coroutines.awaitCancellation36import kotlinx.coroutines.flow.MutableStateFlow37import kotlinx.coroutines.test.StandardTestDispatcher38import kotlinx.coroutines.test.TestScope39import kotlinx.coroutines.test.advanceUntilIdle40import kotlinx.coroutines.test.currentTime41import kotlinx.coroutines.test.runCurrent42import kotlinx.coroutines.test.runTest4344@OptIn(ExperimentalCoroutinesApi::class)45class PersistentDownloadServiceTest {46    private val location = "/downloads/Manga/Src (EN)/Title/Ch 10"4748    @Test49    fun pagesResolveWhenEachChapterStartsAndRowsKeepRequestOrder() = runTest {50        val database = database()51        val release = CompletableDeferred<Unit>()52        val resolved = mutableListOf<Long>()53        val http = ScriptedHttp { request -> if ("c11" in request.url) release.await(); Reply(200) }54        val service = service(database, http) { chapterId, _ ->55            resolved += chapterId56            listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg"))57        }5859        service.enqueue(request(database, 11))60        service.enqueue(request(database, 10))6162        assertEquals(listOf(11L, 10L), database.downloads().map { it.chapterId })63        assertEquals(emptyList(), resolved)64        runCurrent()65        // One chapter per source: the second chapter is not resolved until the first one is done.66        assertEquals(listOf(11L), resolved)67        release.complete(Unit)68        advanceUntilIdle()69        assertEquals(listOf(11L, 10L), resolved)70    }7172    @Test73    fun expiredPageUrlIsResolvedAgainOnceAndRetried() = runTest {74        val database = database()75        val http = ScriptedHttp { request -> Reply(if ("old" in request.url) 403 else 200) }76        val refreshes = mutableListOf<Boolean>()77        val service = service(database, http) { _, forceRefresh ->78            refreshes += forceRefresh79            listOf(DbPageUrl(url = if (forceRefresh) "https://img.test/new/1.jpg" else "https://img.test/old/1.jpg"))80        }8182        service.enqueue(request(database, 10))83        advanceUntilIdle()8485        assertEquals(listOf(false, true), refreshes)86        // A 403 is never retried against the same URL.87        assertEquals(listOf("https://img.test/old/1.jpg", "https://img.test/new/1.jpg"), http.requested)88        assertEquals(true, database.downloads().single().isDownload)89    }9091    @Test92    fun changedPageCountRestartsTheChapterAndDropsStalePages() = runTest {93        val database = database()94        val files = MemoryFiles()95        val http = ScriptedHttp { request -> Reply(if ("old" in request.url) 410 else 200) }96        val service = service(database, http, files) { _, forceRefresh ->97            if (forceRefresh) {98                listOf(DbPageUrl(url = "https://img.test/new/1.jpg"))99            } else {100                listOf(DbPageUrl(url = "https://img.test/old/1.jpg"), DbPageUrl(url = "https://img.test/kept/2.jpg"))101            }102        }103104        service.enqueue(request(database, 10))105        advanceUntilIdle()106107        assertEquals(true, database.downloads().single().isDownload)108        assertEquals(1, database.downloads().single().total)109        assertTrue("$location/0001.jpg" in files.paths)110        assertFalse(files.paths.any { it.startsWith("$location/0002") })111    }112113    @Test114    fun retryAfterRestartRebuildsTheRequestFromTheChapter() = runTest {115        val database = database()116        val files = MemoryFiles()117        var status = 400118        val http = ScriptedHttp { Reply(status) }119        val pages: suspend (Long, Boolean) -> List<DbPageUrl> = { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }120        service(database, http, files, resolve = pages).enqueue(request(database, 10))121        advanceUntilIdle()122        assertEquals(false, database.downloads().single().isStartDownload)123124        status = 200125        val restarted = service(database, http, files, resolve = pages)126127        assertTrue(restarted.retry(downloadTaskId(10, 0)))128        assertFalse(restarted.retry(downloadTaskId(999, 0)))129        advanceUntilIdle()130        assertEquals(true, database.downloads().single().isDownload)131        assertEquals(location, database.chapter(10)?.archivePath)132    }133134    @Test135    fun interruptedDownloadResumesOnStartup() = runTest {136        val database = database()137        database.upsertDownload(DbDownload(chapterId = 10, succeeded = 1, total = 3, isDownload = false, isStartDownload = true))138        val service = service(database, ScriptedHttp { Reply(200) }) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }139140        service.initialize()141        advanceUntilIdle()142143        assertEquals(true, database.downloads().single().isDownload)144    }145146    @Test147    fun enqueueRetryAndStartupDoNotRecreateRowsForDeletedParents() = runTest {148        val database = database()149        val staleRequest = request(database, 10)150        val service = service(database, ScriptedHttp { Reply(400) }) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }151152        service.enqueue(staleRequest)153        advanceUntilIdle()154        database.upsertDownload(DbDownload(id = 99, chapterId = 10, isStartDownload = true))155        database.batch {156            database.removeChapter(10)157            database.removeManga(1)158            database.removeDownload(99)159        }160        service.enqueue(staleRequest)161        assertFalse(service.retry(downloadTaskId(10, 0)))162163        service(database, ScriptedHttp { Reply(200) }) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }.initialize()164165        assertEquals(null, database.download(99))166        assertEquals(null, database.chapter(10))167        assertEquals(null, database.manga(1))168    }169170    @Test171    fun deletingParentAtFinalizationDoesNotRestoreChapterOrDownloadAndOtherTypeContinues() = runTest {172        val database = database()173        val gate = CompletableDeferred<Unit>()174        val entered = CompletableDeferred<Unit>()175        val http = ScriptedHttp { request ->176            if ("c10" in request.url) {177                entered.complete(Unit)178                gate.await()179            }180            Reply(200)181        }182        val service = service(database, http) { chapterId, _ -> listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg")) }183        service.enqueue(request(database, 10))184        service.enqueue(request(database, 11))185        runCurrent()186        entered.await()187        database.batch {188            database.removeChapter(10)189            database.removeManga(1)190        }191        database.upsertSource(DbSource(id = 8, name = "Other source", lang = "en"))192        database.upsertManga(DbManga(id = 2, name = "Other", sourceId = 8, itemType = DbItemType.Anime))193        database.upsertChapter(DbChapter(id = 20, mangaId = 2, url = "/c20", name = "Other chapter"))194        service.enqueue(request(database, 20))195        gate.complete(Unit)196        advanceUntilIdle()197198        assertEquals(null, database.chapter(10))199        assertEquals(null, database.manga(1))200        assertEquals(false, database.downloads().first { it.chapterId == 10L }.isDownload)201        assertEquals(true, database.downloads().first { it.chapterId == 20L }.isDownload)202    }203204    @Test205    fun duplicateEnqueueIsSkippedWhileQueuedOrDownloaded() = runTest {206        val database = database()207        val files = MemoryFiles()208        val http = ScriptedHttp { Reply(200) }209        val service = service(database, http, files) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }210211        service.enqueue(request(database, 10))212        service.enqueue(request(database, 10))213        advanceUntilIdle()214        service.enqueue(request(database, 10))215        advanceUntilIdle()216217        assertEquals(1, http.requested.size)218        assertEquals(1, database.downloads().size)219        files.deleteRecursively(location)220        service.enqueue(request(database, 10))221        advanceUntilIdle()222        assertEquals(2, http.requested.size)223        assertEquals(location, database.chapter(10)?.archivePath)224    }225226    @Test227    fun pagesDownloadInParallelAndEveryPageIsCounted() = runTest {228        val database = database()229        val gate = CompletableDeferred<Unit>()230        var inFlight = 0231        var maxInFlight = 0232        val http = ScriptedHttp {233            inFlight += 1234            maxInFlight = maxOf(maxInFlight, inFlight)235            gate.await()236            inFlight -= 1237            Reply(200)238        }239        val service = service(database, http) { _, _ -> (1..7).map { DbPageUrl(url = "https://img.test/$it.jpg") } }240241        service.enqueue(request(database, 10))242        runCurrent()243        assertEquals(PAGE_PARALLELISM, inFlight)244        gate.complete(Unit)245        advanceUntilIdle()246247        assertEquals(PAGE_PARALLELISM, maxInFlight)248        val row = database.downloads().single()249        assertEquals(7, row.succeeded)250        assertEquals(7, row.total)251        assertEquals(true, row.isDownload)252    }253254    @Test255    fun clientErrorsFailAtOnceWhileRetryAfterIsHonoured() = runTest {256        val database = database()257        val calls = mutableListOf<Pair<String, Long>>()258        var throttled = false259        val http = ScriptedHttp { request ->260            calls += request.url to currentTime261            when {262                "bad" in request.url -> Reply(400)263                !throttled -> Reply(429, headers = mapOf("retry-after" to "7")).also { throttled = true }264                else -> Reply(200)265            }266        }267        val pages = mapOf(10L to "https://img.test/bad.jpg", 11L to "https://img.test/busy.jpg")268        val service = service(database, http) { chapterId, _ -> listOf(DbPageUrl(url = pages.getValue(chapterId))) }269270        service.enqueue(request(database, 10))271        advanceUntilIdle()272        service.enqueue(request(database, 11))273        advanceUntilIdle()274275        assertEquals(1, calls.count { "bad" in it.first })276        val busy = calls.filter { "busy" in it.first }.map { it.second }277        assertEquals(2, busy.size)278        assertEquals(7_000L, busy[1] - busy[0])279        assertEquals(false, database.downloads().first { it.chapterId == 10L }.isDownload)280        assertEquals(true, database.downloads().first { it.chapterId == 11L }.isDownload)281    }282283    @Test284    fun retryDelayUsesRetryAfterElseJitteredExponentialBackoff() {285        assertEquals(3_000L, downloadRetryDelayMs(1, "3"))286        assertEquals(60_000L, downloadRetryDelayMs(1, "3600"))287        repeat(20) {288            val random = Random(it)289            assertTrue(downloadRetryDelayMs(1, null, random) in 500L..1_000L)290            assertTrue(downloadRetryDelayMs(3, "Wed, 21 Oct 2015 07:28:00 GMT", random) in 2_000L..4_000L)291        }292        assertTrue(isRetryableDownloadStatus(408) && isRetryableDownloadStatus(429) && isRetryableDownloadStatus(503))293        assertFalse(isRetryableDownloadStatus(404) || isRetryableDownloadStatus(400))294    }295296    @Test297    fun completedDownloadMarksItsChapterWithTheArchiveTheReaderOpens() = runTest {298        val database = database { it.copy(saveAsCBZArchive = true) }299        val archives = RecordingArchives()300        val service = service(database, ScriptedHttp { Reply(200, ByteArray(2_000_000)) }, archives = archives) { _, _ ->301            listOf(DbPageUrl(url = "https://img.test/1.jpg"))302        }303304        service.enqueue(request(database, 10))305        advanceUntilIdle()306307        assertEquals(listOf(location), archives.zipped)308        val chapter = assertNotNull(database.chapter(10))309        assertEquals("$location.cbz", chapter.archivePath)310        assertEquals("1.9 MB", chapter.downloadSize)311    }312313    @Test314    fun pausingWhileTheChapterIsArchivedStillFinishesItOnce() = runTest {315        val database = database { it.copy(saveAsCBZArchive = true) }316        lateinit var service: PersistentDownloadService317        var pauses = 0318        val archives = RecordingArchives(onZip = { if (pauses++ == 0) service.pause(downloadTaskId(10, 0)) })319        val http = ScriptedHttp { Reply(200) }320        service = service(database, http, archives = archives) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }321322        service.enqueue(request(database, 10))323        advanceUntilIdle()324        service.resume(downloadTaskId(10, 0))325        advanceUntilIdle()326327        assertEquals("$location.cbz", database.chapter(10)?.archivePath)328        assertEquals(true, database.downloads().single().isDownload)329        assertEquals(1, http.requested.size, "a finished chapter is not fetched again")330        assertEquals(1, archives.zipped.size)331    }332333    @Test334    fun pausingARunningChapterFreesItsSourceAndResumeContinuesIt() = runTest {335        val database = database()336        val stalledOnce = mutableSetOf<String>()337        val http = ScriptedHttp { request ->338            if ("c10" in request.url && stalledOnce.add(request.url)) {339                awaitCancellation()340            }341            Reply(200)342        }343        val service = service(database, http) { chapterId, _ -> listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg")) }344        service.enqueue(request(database, 10))345        service.enqueue(request(database, 11))346        runCurrent()347348        service.pause(downloadTaskId(10, 0))349        advanceUntilIdle()350351        assertEquals(true, database.downloads().first { it.chapterId == 11L }.isDownload)352        assertEquals(false, database.downloads().first { it.chapterId == 10L }.isDownload)353        service.resume(downloadTaskId(10, 0))354        advanceUntilIdle()355        assertEquals(true, database.downloads().first { it.chapterId == 10L }.isDownload)356    }357358    @Test359    fun contentUriDownloadFoldersAreRejectedBeforeAnythingIsRecorded() = runTest {360        val database = database()361        val service = service(database, ScriptedHttp { Reply(200) }) { _, _ -> emptyList() }362363        assertFailsWith<IllegalArgumentException> {364            service.enqueue(request(database, 10).copy(destinationRoot = "content://com.android.externalstorage.documents/tree/primary%3AComics"))365        }366367        assertEquals(emptyList(), database.downloads())368    }369370    @Test371    fun hlsPageFollowsTheBestVariantAndSavesKeyAndSegmentsLocally() = runTest {372        val database = database()373        val files = MemoryFiles()374        val playlists = mapOf(375            "https://cdn.test/show/master.m3u8?token=a" to """376                #EXTM3U377                #EXT-X-STREAM-INF:BANDWIDTH=800000,CODECS="avc1,mp4a"378                low/index.m3u8379                #EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=9000000,BANDWIDTH=2000000380                high/index.m3u8381            """.trimIndent(),382            "https://cdn.test/show/high/index.m3u8" to """383                #EXTM3U384                #EXT-X-KEY:METHOD=AES-128,URI="/keys/k1.bin",IV=0x1385                seg0.ts386                #EXT-X-KEY:METHOD=AES-128,URI="/keys/k1.bin",IV=0x2387                https://other.test/seg1.ts388            """.trimIndent(),389        )390        var segmentFailures = 1391        val http = ScriptedHttp(392            text = { request -> playlists[request.url]?.let { HttpResponse(200, it) } ?: HttpResponse(404, "") },393        ) { request ->394            if ("seg0" in request.url && segmentFailures-- > 0) Reply(503) else Reply(200)395        }396        val service = service(database, http, files) { _, _ -> listOf(DbPageUrl(url = "https://cdn.test/show/master.m3u8?token=a")) }397398        service.enqueue(request(database, 10))399        advanceUntilIdle()400401        assertEquals(true, database.downloads().single().isDownload)402        assertEquals(403            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(),404            http.requested.sorted(),405        )406        assertEquals(407            """408                #EXTM3U409                #EXT-X-KEY:METHOD=AES-128,URI="0001_key_0.key",IV=0x1410                0001_seg_0000.ts411                #EXT-X-KEY:METHOD=AES-128,URI="0001_key_0.key",IV=0x2412                0001_seg_0001.ts413            """.trimIndent(),414            files.readBytes("$location/0001.m3u8").decodeToString(),415        )416        assertTrue("$location/0001.m3u8.complete" in files.paths)417    }418419    @Test420    fun wifiOnlyKeepsDownloadsQueuedOnAMeteredNetworkUntilWifiReturns() = runTest {421        val database = database { it.copy(downloadOnlyOnWifi = true) }422        val network = FakeNetwork(unmetered = false)423        val notifications = RecordingNotifications()424        val http = ScriptedHttp { Reply(200) }425        val service = service(database, http, network = network, notifications = notifications) { chapterId, _ ->426            listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg"))427        }428429        service.enqueue(request(database, 10))430        service.enqueue(request(database, 11))431        service.pause(downloadTaskId(11, 0))432        advanceUntilIdle()433434        assertEquals(DownloadQueueStatus(pending = 1, waitingForWifi = true), service.queueStatus.value)435        assertEquals(emptyList(), http.requested)436        assertEquals(listOf(true, true), database.downloads().map { it.isStartDownload })437        assertEquals(1, notifications.posted.count { it.tag == WAITING_FOR_WIFI_NOTIFICATION_TAG }, "one notification, not one per chapter")438439        network.unmetered.value = true440        advanceUntilIdle()441442        assertEquals(DownloadQueueStatus(), service.queueStatus.value)443        assertEquals(true, database.downloads().first { it.chapterId == 10L }.isDownload)444        assertEquals(false, database.downloads().first { it.chapterId == 11L }.isDownload, "a paused chapter stays paused")445        assertEquals(listOf<String?>(WAITING_FOR_WIFI_NOTIFICATION_TAG), notifications.cancelled.map { it.second })446    }447448    @Test449    fun meteredNetworkPausesARunningChapterAtItsNextPageAndTurningWifiOnlyOffResumesIt() = runTest {450        val database = database { it.copy(downloadOnlyOnWifi = true) }451        val network = FakeNetwork(unmetered = true)452        val http = ScriptedHttp { request ->453            // The phone leaves Wi-Fi while the first page is downloading.454            if (request.url.endsWith("/1.jpg")) network.unmetered.value = false455            Reply(200)456        }457        val pages = (1..3).map { DbPageUrl(url = "https://img.test/$it.jpg") }458        val service = service(database, http, network = network) { _, _ -> pages }459460        service.enqueue(request(database, 10))461        advanceUntilIdle()462463        assertEquals(listOf("https://img.test/1.jpg"), http.requested)464        assertEquals(1, service.activeDownloads().single().succeeded)465        assertEquals(DownloadQueueStatus(pending = 1, waitingForWifi = true), service.queueStatus.value)466467        database.updateSettings(database.settings().copy(downloadOnlyOnWifi = false))468        advanceUntilIdle()469470        assertEquals(pages.map { it.url }, http.requested.sorted(), "the saved page is not fetched again")471        assertEquals(true, database.downloads().single().isDownload)472        assertEquals(DownloadQueueStatus(), service.queueStatus.value)473    }474475    @Test476    fun restartPreservesPausedQueueAndExactDestination() = runTest {477        val database = database()478        val request = request(database, 10).copy(destinationRoot = "/one-off", retries = 1)479        database.upsertDownload(eu.friedcutlet.yokan.database.DbDownload(480            id = 50, chapterId = 10, isStartDownload = true, isPaused = true,481            storageLocation = "/one-off/exact/chapter",482            requestJson = eu.friedcutlet.yokan.database.DatabaseJson.encodeToString(DownloadRequest.serializer(), request),483        ))484        val files = MemoryFiles()485        val http = ScriptedHttp { Reply(200) }486        val downloader = service(database, http, files) { _, _ -> listOf(DbPageUrl("https://test/page.jpg")) }487        assertEquals("/one-off/exact/chapter", downloader.storageLocation(request.taskId))488        downloader.initialize()489        advanceUntilIdle()490        assertTrue(http.requested.isEmpty())491        assertTrue(downloader.activeDownloads().single().isPaused)492        assertTrue(database.download(50)?.isPaused == true)493494        downloader.resume(request.taskId)495        advanceUntilIdle()496        assertEquals(true, database.download(50)?.isDownload)497        assertEquals(false, database.download(50)?.isPaused)498        assertTrue(files.paths.any { it.startsWith("/one-off/exact/chapter/") })499    }500501    @Test502    fun hlsSegmentsUseBoundedConcurrencyAndCountSavedBytes() = runTest {503        val database = database()504        val playlist = "#EXTM3U\n" + (1..8).joinToString("\n") { "segment$it.ts" }505        var inFlight = 0506        var maximum = 0507        val http = ScriptedHttp(text = { HttpResponse(200, playlist) }) {508            inFlight++509            maximum = maxOf(maximum, inFlight)510            kotlinx.coroutines.delay(10)511            inFlight--512            Reply(200, byteArrayOf(1, 2, 3))513        }514        val files = MemoryFiles()515        val downloadRequest = request(database, 10)516        files.writeBytes("$location/0001_seg_0000.ts", byteArrayOf(1, 2, 3))517        files.writeBytes("$location/0001_seg_0000.ts.complete", byteArrayOf())518        val downloader = service(database, http, files) { _, _ -> listOf(DbPageUrl("https://test/video.m3u8")) }519        var downloadedBytes = 0L520        downloader.enqueue(downloadRequest) { downloadedBytes = it.bytesDownloaded }521        advanceUntilIdle()522        assertEquals(PAGE_PARALLELISM, maximum)523        assertEquals(7, http.requested.size)524        assertEquals(24L + playlist.length, downloadedBytes)525        assertEquals(true, database.downloads().single().isDownload)526    }527528    @Test529    fun automatedDeletionChecksEligibilityAndLeavesIncompleteTransfersUntouched() = runTest {530        val database = database()531        val files = MemoryFiles().apply { writeBytes("$location/0001.jpg", byteArrayOf(1)) }532        val downloader = service(database, ScriptedHttp { Reply(200) }, files) { _, _ -> emptyList() }533        database.upsertDownload(DbDownload(chapterId = 10, storageLocation = location, isDownload = false))534        assertFalse(downloader.deleteCompletedArtifacts("chapter-10"))535        database.upsertDownload(database.downloads().single().copy(isDownload = true))536        assertFalse(downloader.deleteCompletedArtifacts("chapter-10", stillEligible = { false }))537        assertTrue(files.exists(location))538        assertTrue(downloader.deleteCompletedArtifacts("chapter-10"))539        assertFalse(files.exists(location))540    }541542    @Test543    fun automatedDeletionRefusesMalformedRootAndTitleLocations() = runTest {544        for (bad in listOf("/", "/downloads", "/downloads/Manga/Src (EN)/Title", "/downloads/Manga/Src (EN)/Title/../other", "")) {545            val database = database()546            val files = MemoryFiles().apply { writeBytes("/downloads/important.jpg", byteArrayOf(1)) }547            val downloader = service(database, ScriptedHttp { Reply(200) }, files) { _, _ -> emptyList() }548            database.upsertDownload(DbDownload(chapterId = 10, storageLocation = bad, isDownload = true))549            // Blank locations fall back to the derived chapter folder, never the root.550            if (bad.isNotBlank()) assertFalse(downloader.deleteCompletedArtifacts("chapter-10"), bad)551            assertTrue(files.exists("/downloads/important.jpg"))552        }553    }554555    @Test556    fun automatedDeletionReportsFilesystemFailureAndRejectsRedirectedPaths() = runTest {557        val database = database()558        val files = GuardedFiles().apply { writeBytes("$location/0001.jpg", byteArrayOf(1)); rejectDeletion = true }559        val downloader = service(database, ScriptedHttp { Reply(200) }, files) { _, _ -> emptyList() }560        database.upsertDownload(DbDownload(chapterId = 10, storageLocation = location, isDownload = true))561        assertFalse(downloader.deleteCompletedArtifacts("chapter-10"))562        assertTrue(files.exists(location))563        files.rejectDeletion = false564        files.redirectedPaths[location] = "/downloads"565        assertFalse(downloader.deleteCompletedArtifacts("chapter-10"))566        assertTrue(files.exists(location))567    }568569    @Test570    fun novelDownloadSavesChapterHtmlAndIsReadableWithoutPageListCalls() = runTest {571        val database = database()572        database.upsertManga(database.manga(1)!!.copy(itemType = DbItemType.Novel))573        val files = MemoryFiles()574        val downloader = PersistentDownloadService(575            database, ScriptedHttp { error("No image fetch expected") }, files, RecordingArchives(), this,576            resolvePages = { _, _ -> error("Novels use htmlContent") },577            ioDispatcher = StandardTestDispatcher(testScheduler),578            resolveNovelText = { "<p>Offline novel</p>" },579        )580        downloader.enqueue(request(database, 10))581        advanceUntilIdle()582        val chapter = database.chapter(10)!!583        assertTrue(database.downloads().single().isDownload == true)584        assertEquals("<p>Offline novel</p>", files.readBytes("${chapter.archivePath}/0001.html").decodeToString())585        assertTrue(files.exists("${chapter.archivePath}/0001.html.complete"))586    }587588    private fun request(database: InMemoryYokanDatabase, chapterId: Long): DownloadRequest =589        checkNotNull(chapterDownloadRequest(database, chapterId))590591    private fun database(settings: (DbSettings) -> DbSettings = { it }): InMemoryYokanDatabase {592        val seed = seedDatabaseSnapshot()593        return InMemoryYokanDatabase(594            seed.copy(595                settings = settings(seed.settings),596                sources = listOf(DbSource(id = 7, name = "Src", lang = "en")),597                mangas = listOf(DbManga(id = 1, name = "Title", sourceId = 7, itemType = DbItemType.Manga)),598                chapters = listOf(599                    DbChapter(id = 10, mangaId = 1, url = "/c10", name = "Ch 10"),600                    DbChapter(id = 11, mangaId = 1, url = "/c11", name = "Ch 11"),601                ),602            ),603        )604    }605606    private fun TestScope.service(607        database: InMemoryYokanDatabase,608        http: HttpService,609        files: LocalFileService = MemoryFiles(),610        archives: LocalArchiveService = RecordingArchives(),611        network: NetworkMonitor = UnmeteredNetwork,612        notifications: NotificationService? = null,613        resolve: suspend (Long, Boolean) -> List<DbPageUrl>,614    ) = PersistentDownloadService(615        database = database,616        http = http,617        files = files,618        archives = archives,619        // Not backgroundScope: advanceUntilIdle() does not wait for background work.620        scope = this,621        resolvePages = resolve,622        notifications = notifications,623        network = network,624        ioDispatcher = StandardTestDispatcher(testScheduler),625    )626}627628private class FakeNetwork(unmetered: Boolean) : NetworkMonitor {629    override val unmetered = MutableStateFlow(unmetered)630}631632private class Reply(val status: Int, val body: ByteArray = byteArrayOf(1), val headers: Map<String, String> = emptyMap())633634/** Streams scripted replies and records every streamed URL; [text] answers playlist requests. */635private class ScriptedHttp(636    private val text: (HttpRequest) -> HttpResponse = { HttpResponse(statusCode = 404, body = "") },637    private val reply: suspend (HttpRequest) -> Reply,638) : HttpService {639    val requested = mutableListOf<String>()640641    override suspend fun request(request: HttpRequest): HttpResponse = text(request)642643    override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {644        requested += request.url645        val answer = reply(request)646        onChunk(answer.body)647        return HttpStreamResponse(statusCode = answer.status, headers = answer.headers)648    }649}650651private class RecordingArchives(private val onZip: () -> Unit = {}) : LocalArchiveService {652    val zipped = mutableListOf<String>()653    override fun listPages(archivePath: String) = emptyList<DbPageUrl>()654    override fun listEpubChapters(archivePath: String) = emptyList<LocalEpubChapter>()655    override fun readEpubChapter(archivePath: String, index: Int) = ""656    override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null657    override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String {658        zipped += directoryPath659        onZip()660        return "$directoryPath.cbz"661    }662}663664/** Lets a test refuse deletion or resolve a path elsewhere, as a hostile filesystem would. */665private class GuardedFiles : MemoryFiles() {666    var rejectDeletion = false667    val redirectedPaths = mutableMapOf<String, String>()668669    override fun canonicalPath(path: String): String? = redirectedPaths[path] ?: path670    override fun deleteRecursively(path: String): Boolean = !rejectDeletion && super.deleteRecursively(path)671}672

Search chapters, reference and source filenames.