ChapterDownloadsTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ChapterDownloadsTest.kt
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.data.DefaultYokanRepository4import eu.friedcutlet.yokan.services.notifications.NoNotifications5import eu.friedcutlet.yokan.data.SettingsStore6import eu.friedcutlet.yokan.database.DbChapter7import eu.friedcutlet.yokan.database.DbDownload8import eu.friedcutlet.yokan.database.DbItemType9import eu.friedcutlet.yokan.database.DbLocalFolder10import eu.friedcutlet.yokan.database.DbManga11import eu.friedcutlet.yokan.database.DbSource12import eu.friedcutlet.yokan.database.InMemoryYokanDatabase13import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot14import eu.friedcutlet.yokan.database.seedDatabaseSnapshot15import eu.friedcutlet.yokan.services.files.NoFiles16import kotlin.test.Test17import kotlin.test.assertEquals18import kotlin.test.assertNull19import kotlin.test.assertTrue20import kotlinx.coroutines.test.TestScope21import kotlinx.coroutines.test.runTest22import kotlinx.coroutines.test.advanceUntilIdle2324class ChapterDownloadsTest {25 @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)26 @Test fun preferredRemoteRoutingPreservesExplicitLocalDestinationAndHlsFallback() = runTest {27 val f = fixture(enqueueSnapshot())28 f.database.updateSettings(f.database.settings().let { old -> old.copy(features = old.features.copy(externalDownloads = eu.friedcutlet.yokan.database.DbExternalDownloads(eu.friedcutlet.yokan.database.PreferredDownloader.Aria2, "https://aria.example.org/jsonrpc", "secret", "/remote"))) })29 var url = "https://images.example.org/page.jpg"30 val http = object : eu.friedcutlet.yokan.services.http.HttpService {31 override suspend fun request(request: eu.friedcutlet.yokan.services.http.HttpRequest): eu.friedcutlet.yokan.services.http.HttpResponse = error("Manual routing must persist before any RPC")32 }33 val remote = ExternalDownloads(f.database, http, this, { _, _ -> listOf(eu.friedcutlet.yokan.database.DbPageUrl(url = url)) }, startPolling = false)34 val actions = ChapterDownloads(f.repository, f.database, f.downloader, NoNotifications, SettingsStore(f.repository, backgroundScope) {}, NoFiles, this, remote)35 val title = requireNotNull(f.repository.manga(1)); val chapter = f.repository.chapters(1).single { it.id == 10L }36 actions.enqueue(title, chapter, null)37 advanceUntilIdle()38 assertEquals(1, remote.jobs.value.size)39 assertTrue(f.downloader.requests.isEmpty())40 actions.enqueue(title, chapter, "/explicit-local")41 assertEquals("/explicit-local", f.downloader.requests.single().destinationRoot)42 remote.remove(remote.jobs.value.single().id, forgetUnverified = true)43 url = "https://video.example.org/master.m3u8"44 actions.enqueue(title, chapter, null)45 advanceUntilIdle()46 assertEquals(2, f.downloader.requests.size)47 assertTrue(remote.jobs.value.isEmpty())48 }49 @Test fun awaitingTitleRemovalKeepsDatabaseParentsAvailableAndReportsFailure() = runTest {50 val f = fixture(seedDatabaseSnapshot().copy(51 mangas = listOf(DbManga(id = 1, name = "Title", favorite = true)),52 chapters = listOf(DbChapter(id = 10, mangaId = 1, archivePath = "/saved")),53 downloads = listOf(DbDownload(id = 100, chapterId = 10, isDownload = true)),54 ))55 f.downloader.deletionAllowed = false56 assertEquals(emptySet(), f.downloads.deleteForMangaAwait(setOf(1)))57 assertTrue(f.database.downloads().isNotEmpty())58 assertTrue(f.database.manga(1) != null)59 f.downloader.deletionAllowed = true60 assertEquals(setOf(1L), f.downloads.deleteForMangaAwait(setOf(1)))61 assertTrue(f.database.downloads().isEmpty())62 assertTrue(f.database.manga(1) != null, "The caller removes the title only after deletion finishes")63 f.repository.removeLibraryEntries(setOf(1))64 assertEquals(false, f.database.manga(1)?.favorite)65 }66 @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)67 @Test fun asynchronousRemovalClearsRecordsOnlyAfterSuccessfulFileDeletion() = runTest {68 val snapshot = seedDatabaseSnapshot().copy(69 mangas = listOf(DbManga(id = 1, name = "Title")),70 chapters = listOf(DbChapter(id = 10, mangaId = 1, archivePath = "/saved", downloadSize = "5 MB")),71 downloads = listOf(DbDownload(id = 100, chapterId = 10, isDownload = true)),72 )73 val f = fixture(snapshot)74 f.downloader.deletionAllowed = false75 f.downloads.deleteForChapters(setOf(10))76 advanceUntilIdle()77 assertEquals(true, f.database.download(100)?.isDownload)78 assertEquals("/saved", f.database.chapter(10)?.archivePath)79 f.downloader.deletionAllowed = true80 f.downloads.deleteForChapters(setOf(10))81 assertEquals(true, f.database.download(100)?.isDownload)82 advanceUntilIdle()83 assertNull(f.database.download(100))84 assertEquals("", f.database.chapter(10)?.archivePath)85 assertNull(f.database.chapter(10)?.downloadSize)86 }87 @Test88 fun deleteChaptersRemovesSpecifiedChapters() {89 val manga = DbManga(id = 1, name = "Test Manga", link = "/test", itemType = DbItemType.Manga)90 val chapter1 = DbChapter(id = 10, mangaId = 1, url = "/c1", name = "Ch 1")91 val chapter2 = DbChapter(id = 20, mangaId = 1, url = "/c2", name = "Ch 2")92 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(93 mangas = listOf(manga),94 chapters = listOf(chapter1, chapter2),95 ))96 val repository = DefaultYokanRepository(database)9798 repository.deleteChapters(setOf(10))99100 assertEquals(1, database.chapters().size)101 assertEquals(20, database.chapters().single().id)102 }103104 @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)105 @Test106 fun deleteForChaptersClearsDownloadRecordsAndDownloadSize() = runTest {107 val manga = DbManga(id = 1, name = "Test Manga", link = "/test", itemType = DbItemType.Manga, favorite = true)108 val chapter1 = DbChapter(id = 10, mangaId = 1, url = "/c1", name = "Ch 1", downloadSize = "15 MB")109 val chapter2 = DbChapter(id = 20, mangaId = 1, url = "/c2", name = "Ch 2", downloadSize = "20 MB")110 val download1 = DbDownload(id = 100, chapterId = 10, isDownload = true, succeeded = 10, total = 10)111 val download2 = DbDownload(id = 200, chapterId = 20, isDownload = true, succeeded = 12, total = 12)112 val fixture = fixture(seedDatabaseSnapshot().copy(113 mangas = listOf(manga),114 chapters = listOf(chapter1, chapter2),115 downloads = listOf(download1, download2),116 ))117118 val removed = fixture.downloads.deleteForChapters(setOf(10))119 advanceUntilIdle()120121 assertEquals(1, removed)122 assertNull(fixture.database.chapter(10)?.downloadSize)123 assertEquals("20 MB", fixture.database.chapter(20)?.downloadSize)124 assertEquals(listOf(200L), fixture.database.downloads().map { it.id })125 assertEquals(listOf(downloadTaskId(10, 100)), fixture.downloader.deletedArtifacts)126 }127128 @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)129 @Test130 fun deleteForMangaDeletesAllChaptersOfSeries() = runTest {131 val manga1 = DbManga(id = 1, name = "Manga 1", link = "/m1", itemType = DbItemType.Manga, favorite = true)132 val manga2 = DbManga(id = 2, name = "Manga 2", link = "/m2", itemType = DbItemType.Manga, favorite = true)133 val fixture = fixture(seedDatabaseSnapshot().copy(134 mangas = listOf(manga1, manga2),135 chapters = listOf(136 DbChapter(id = 10, mangaId = 1, url = "/c1", name = "Ch 1", downloadSize = "5 MB"),137 DbChapter(id = 20, mangaId = 1, url = "/c2", name = "Ch 2", downloadSize = "5 MB"),138 DbChapter(id = 30, mangaId = 2, url = "/c3", name = "Ch 3", downloadSize = "10 MB"),139 ),140 downloads = listOf(141 DbDownload(id = 101, chapterId = 10, isDownload = true),142 DbDownload(id = 102, chapterId = 20, isDownload = true),143 DbDownload(id = 103, chapterId = 30, isDownload = true),144 ),145 ))146147 val count = fixture.downloads.deleteForManga(setOf(1))148 advanceUntilIdle()149150 assertTrue(count >= 2)151 assertNull(fixture.database.chapter(10)?.downloadSize)152 assertNull(fixture.database.chapter(20)?.downloadSize)153 assertEquals("10 MB", fixture.database.chapter(30)?.downloadSize)154 assertEquals(listOf(103L), fixture.database.downloads().map { it.id })155 }156157 @Test158 fun enqueueRecordsTheChapterRightAwayWithoutResolvingPages() = runTest {159 val fixture = fixture(enqueueSnapshot())160 val manga = checkNotNull(fixture.repository.manga(1))161 val chapter = fixture.repository.chapters(1).single()162163 fixture.downloads.enqueue(manga, chapter, destinationRoot = "/custom")164165 val request = fixture.downloader.requests.single()166 assertEquals(downloadTaskId(10, 0), request.taskId)167 assertEquals(10L, request.chapterId)168 assertEquals("/custom", request.destinationRoot)169 // The title's installed source labels the download.170 assertEquals("Src (EN)", request.sourceLabel)171 assertEquals(5L, request.sourceId)172 }173174 @Test175 fun enqueueWithoutDestinationUsesTheSelectedDownloadFolder() = runTest {176 val seed = enqueueSnapshot()177 val fixture = fixture(seed.copy(178 settings = seed.settings.copy(179 namedLocalFolders = listOf(DbLocalFolder("a", "/a"), DbLocalFolder("b", "/b")),180 downloadLocalFolderName = "b",181 ),182 ))183 val manga = checkNotNull(fixture.repository.manga(1))184 val chapter = fixture.repository.chapters(1).single()185186 fixture.downloads.enqueue(manga, chapter, destinationRoot = null)187188 assertEquals("/b", fixture.downloader.requests.single().destinationRoot)189 }190191 @Test192 fun enqueueNeverPicksASystemPickerFolderAsTheDownloadRoot() = runTest {193 val seed = enqueueSnapshot()194 val fixture = fixture(seed.copy(195 settings = seed.settings.copy(196 namedLocalFolders = listOf(197 DbLocalFolder("saf", "content://com.android.externalstorage.documents/tree/primary%3AComics"),198 DbLocalFolder("disk", "/disk"),199 ),200 downloadLocalFolderName = "saf",201 ),202 ))203 val manga = checkNotNull(fixture.repository.manga(1))204 val chapter = fixture.repository.chapters(1).single()205206 fixture.downloads.enqueue(manga, chapter, destinationRoot = null)207208 assertEquals("/disk", fixture.downloader.requests.single().destinationRoot)209 }210211 private fun enqueueSnapshot(): YokanDatabaseSnapshot {212 val seed = seedDatabaseSnapshot()213 return seed.copy(214 sources = listOf(DbSource(id = 5, name = "Src", lang = "en", itemType = DbItemType.Manga, isAdded = true)),215 mangas = listOf(216 DbManga(id = 1, name = "Title", link = "/t", source = "Src", sourceId = 5, itemType = DbItemType.Manga, favorite = true),217 ),218 chapters = listOf(DbChapter(id = 10, mangaId = 1, url = "/c1", name = "Ch 1")),219 )220 }221222 private fun TestScope.fixture(snapshot: YokanDatabaseSnapshot): Fixture {223 val database = InMemoryYokanDatabase(snapshot)224 val repository = DefaultYokanRepository(database)225 val downloader = RecordingDownloadService()226 val downloads = ChapterDownloads(227 repository = repository,228 database = database,229 downloader = downloader,230 notifications = NoNotifications,231 settings = SettingsStore(repository, backgroundScope, onSchedulingChanged = {}),232 localFiles = NoFiles,233 scope = this,234 )235 return Fixture(database, repository, downloader, downloads)236 }237238 private class Fixture(239 val database: InMemoryYokanDatabase,240 val repository: DefaultYokanRepository,241 val downloader: RecordingDownloadService,242 val downloads: ChapterDownloads,243 )244}245246private class RecordingDownloadService : DownloadService {247 val requests = mutableListOf<DownloadRequest>()248 val deletedArtifacts = mutableListOf<String>()249 var deletionAllowed = true250251 override suspend fun initialize(poolSize: Int) = Unit252 override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) {253 requests += request254 }255 override fun cancel(taskId: String) = Unit256 override fun pause(taskId: String) = Unit257 override fun resume(taskId: String) = Unit258 override fun retry(taskId: String): Boolean = false259 override fun storageLocation(taskId: String): String? = null260 override fun deleteArtifacts(taskId: String) {261 deletedArtifacts += taskId262 }263 override suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit): Boolean {264 if (!deletionAllowed) return false265 deleteArtifacts(taskId)266 onDeleted()267 return true268 }269 override fun activeDownloads(): List<DownloadProgress> = emptyList()270}271