ProfileReaderContentTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/ProfileReaderContentTest.kt
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.data.DefaultYokanRepository5import eu.friedcutlet.yokan.database.DbChapter6import eu.friedcutlet.yokan.database.DbManga7import eu.friedcutlet.yokan.database.DbPageUrl8import eu.friedcutlet.yokan.database.DbSource9import eu.friedcutlet.yokan.database.DbVideo10import eu.friedcutlet.yokan.database.InMemoryYokanDatabase11import eu.friedcutlet.yokan.database.YokanDatabase12import eu.friedcutlet.yokan.database.seedDatabaseSnapshot13import eu.friedcutlet.yokan.domain.Chapter14import eu.friedcutlet.yokan.services.files.LocalArchiveService15import eu.friedcutlet.yokan.services.files.LocalEpubChapter16import eu.friedcutlet.yokan.services.files.LocalEntry17import eu.friedcutlet.yokan.services.files.LocalFileEntry18import eu.friedcutlet.yokan.services.files.LocalFileService19import androidx.compose.ui.text.LinkAnnotation20import eu.friedcutlet.yokan.ui.screens.novel.NovelContentBlock21import eu.friedcutlet.yokan.ui.screens.novel.NovelImageSource22import eu.friedcutlet.yokan.ui.screens.novel.loadNovelDocument23import kotlin.test.assertContentEquals24import kotlin.test.assertIs25import kotlin.test.assertNotNull26import kotlin.test.Test27import kotlin.test.assertEquals28import kotlin.test.assertFailsWith29import kotlin.test.assertFalse30import kotlin.test.assertTrue31import kotlinx.coroutines.CancellationException32import kotlinx.coroutines.CompletableDeferred33import kotlinx.coroutines.CoroutineDispatcher34import kotlinx.coroutines.CoroutineScope35import kotlinx.coroutines.ExperimentalCoroutinesApi36import kotlinx.coroutines.NonCancellable37import kotlinx.coroutines.SupervisorJob38import kotlinx.coroutines.async39import kotlinx.coroutines.awaitCancellation40import kotlinx.coroutines.cancelAndJoin41import kotlinx.coroutines.withContext42import kotlinx.coroutines.test.StandardTestDispatcher43import kotlinx.coroutines.test.TestScope44import kotlinx.coroutines.test.runCurrent45import kotlinx.coroutines.test.runTest4647@OptIn(ExperimentalCoroutinesApi::class)48class ProfileReaderContentTest {49 @Test fun downloadedEpisodeUsesLocalMediaBeforeAnySourceExtraction() = runTest {50 val f = Fixture(this)51 try {52 f.localFiles = listOf(LocalFileEntry("/A/episode/0001.mp4", "0001.mp4", 500, 0))53 val video = f.content.videos(f.source, chapter.copy(archivePath = "/A/episode")).single()54 assertEquals("file:///A/episode/0001.mp4", video.url)55 assertEquals("Downloaded", video.quality)56 assertEquals(0, f.factory.created)57 f.fileExists = true58 assertEquals("file:///A/movie.mp4", f.content.videos(null, chapter.copy(url = "/A/movie.mp4")).single().url)59 } finally { f.close() }60 }6162 @Test fun downloadedNovelHtmlIsReadOfflineWithoutSourceRuntime() = runTest {63 val f = Fixture(this)64 try {65 f.localFiles = listOf(LocalFileEntry("/A/novel/0001.html", "0001.html", 100, 0))66 f.localBytes = "<p>Offline novel chapter</p>".encodeToByteArray()67 val parsed = loadNovelDocument(f.content, f.source, "Novel", chapter.copy(archivePath = "/A/novel")).parse()68 assertEquals("Offline novel chapter", parsed.plainText)69 assertEquals(0, f.factory.created)70 } finally { f.close() }71 }7273 @Test fun remotePagesMergeHeadersAndCacheOnlyInCapturedDatabase() = runTest {74 val a = Fixture(this, "A")75 val b = Fixture(this, "B")76 try {77 val pages = a.content.pages(a.source, chapter, false)78 assertEquals(mapOf("User-Agent" to "A", "referer" to "page"), pages.single().headers)79 assertEquals(listOf("A/page"), a.db.pageCache(10).single().urls)80 assertTrue(b.db.pageCache(10).isEmpty())81 assertEquals(pages, a.content.pages(a.source, chapter, false))82 assertEquals(1, a.factory.created)83 assertEquals(1, a.factory.disposed)84 a.content.pages(a.source, chapter, true)85 assertEquals(2, a.factory.created)86 } finally { a.close(); b.close() }87 }8889 @Test fun localArchiveUsesCapturedFilesWithoutAllocatingRuntime() = runTest {90 val f = Fixture(this, "A")91 try {92 f.archivePages = listOf(DbPageUrl("file://A/local/1.jpg"))93 val local = chapter.copy(archivePath = "/A/local/book.cbz#chapter")94 assertEquals(f.archivePages, f.content.pages(f.source, local, false))95 assertEquals(listOf("/A/local/book.cbz"), f.archivePaths)96 assertEquals(0, f.factory.created)97 assertTrue(f.db.pageCache(10).isEmpty())98 } finally { f.close() }99 }100101 @Test fun localImageAndContentUriKeepTheirOriginalAddress() = runTest {102 val f = Fixture(this)103 try {104 f.fileExists = true105 for ((path, expected) in listOf("/local/page.png" to "file:///local/page.png",106 "content://books/page.png" to "content://books/page.png")) {107 val pages = f.content.pages(null, chapter.copy(url = path), false)108 assertEquals(expected, pages.single().url)109 assertEquals("page.png", pages.single().fileName)110 }111 assertEquals(0, f.factory.created)112 } finally { f.close() }113 }114115 @Test fun headerFailurePreservesOfflineFallback() = runTest {116 val f = Fixture(this)117 try {118 f.factory.headerAction = { error("Runtime unavailable") }119 assertEquals(mapOf("User-Agent" to f.db.settings().userAgent), f.content.headers(f.source))120 assertEquals(1, f.factory.disposed)121 } finally { f.close() }122 }123124 @Test fun episodeFailureDoesNotFabricateAStreamFromTheChapterUrl() = runTest {125 val f = Fixture(this)126 try {127 f.factory.videoAction = { error("Extraction failed") }128 assertFailsWith<IllegalStateException> { f.content.videos(f.source, chapter) }129 assertEquals(1, f.factory.disposed)130 assertEquals("https://cdn.test/movie", f.content.videos(null, chapter.copy(url = "//cdn.test/movie")).single().url)131 assertTrue(f.content.videos(null, chapter.copy(url = "/episode.html")).isEmpty())132 } finally { f.close() }133 }134135 @Test fun novelExtractionRetainsCleanedMarkupAndUsesCapturedRuntime() = runTest {136 val f = Fixture(this, "A")137 try {138 assertEquals("<p>A novel</p>", f.content.novelText(f.source, "Novel", chapter.url))139 assertEquals(1, f.factory.cleaned)140 assertEquals(1, f.factory.disposed)141 assertEquals("inline text", f.content.novelText(null, "Novel", "inline text"))142 assertEquals(1, f.factory.created)143 } finally { f.close() }144 }145146 @Test fun ownerCancellationDiscardsNonCancellablePageResultAndCache() = runTest {147 val f = Fixture(this)148 val entered = CompletableDeferred<Unit>()149 val release = CompletableDeferred<Unit>()150 f.factory.pageAction = {151 withContext(NonCancellable) { entered.complete(Unit); release.await() }152 listOf(DbPageUrl("late"))153 }154 val request = async { f.content.pages(f.source, chapter, true) }155 entered.await()156 f.owner.cancel()157 assertFalse(request.isCompleted)158 release.complete(Unit)159 assertFailsWith<CancellationException> { request.await() }160 f.close()161 assertTrue(f.db.pageCache(10).isEmpty())162 assertEquals(1, f.factory.disposed)163 }164165 @Test fun retirementAdmissionDiscardsLatePagesEvenBeforeOwnerJobCancellation() = runTest {166 val f = Fixture(this)167 f.factory.pageAction = { f.open = false; listOf(DbPageUrl("late")) }168 try {169 assertFailsWith<CancellationException> { f.content.pages(f.source, chapter, true) }170 assertTrue(f.db.pageCache(10).isEmpty())171 assertTrue(f.owner.isActive)172 } finally { f.close() }173 }174175 @Test fun retirementDuringRuntimeFinalizationPreventsPageCacheWrite() = runTest {176 val f = Fixture(this)177 f.factory.finalizer = { f.open = false }178 try {179 assertFailsWith<CancellationException> { f.content.pages(f.source, chapter, true) }180 assertTrue(f.db.pageCache(10).isEmpty())181 assertEquals(1, f.factory.disposed)182 } finally { f.close() }183 }184185 @Test fun lateHeadersCannotStartAnotherExtractionAfterCancellation() = runTest {186 val f = Fixture(this)187 val entered = CompletableDeferred<Unit>()188 val release = CompletableDeferred<Unit>()189 var pageCalls = 0190 f.factory.headerAction = {191 withContext(NonCancellable) { entered.complete(Unit); release.await() }192 emptyMap()193 }194 f.factory.pageAction = { pageCalls++; listOf(DbPageUrl("late")) }195 val request = async { f.content.pages(f.source, chapter, true) }196 entered.await(); f.owner.cancel(); release.complete(Unit)197 assertFailsWith<CancellationException> { request.await() }198 f.close()199 assertEquals(0, pageCalls)200 assertTrue(f.db.pageCache(10).isEmpty())201 assertEquals(1, f.factory.disposed)202 }203204 @Test fun lateNovelHtmlCannotStartCleanupAfterCallerCancellation() = runTest {205 val f = Fixture(this)206 val entered = CompletableDeferred<Unit>()207 val release = CompletableDeferred<Unit>()208 f.factory.htmlAction = {209 withContext(NonCancellable) { entered.complete(Unit); release.await() }210 "late"211 }212 val request = async { f.content.novelText(f.source, "Novel", chapter.url) }213 entered.await(); request.cancel()214 runCurrent()215 assertFalse(request.isCompleted, "caller waits for its owned extraction")216 release.complete(Unit)217 request.join()218 assertEquals(0, f.factory.cleaned)219 assertEquals(1, f.factory.disposed)220 assertTrue(f.owner.isActive)221 f.close()222 }223224 @Test fun callerCancellationJoinsRuntimeFinalizerAndLeavesOtherRequestsUsable() = runTest {225 val f = Fixture(this)226 val entered = CompletableDeferred<Unit>()227 val finalizing = CompletableDeferred<Unit>()228 val release = CompletableDeferred<Unit>()229 f.factory.videoAction = { entered.complete(Unit); awaitCancellation() }230 f.factory.finalizer = { finalizing.complete(Unit); release.await() }231 val request = async { f.content.videos(f.source, chapter) }232 entered.await(); request.cancel(); finalizing.await()233 assertFalse(request.isCompleted)234 release.complete(Unit); request.join()235 assertEquals(1, f.factory.disposed)236 f.factory.finalizer = {}237 assertEquals(mapOf("User-Agent" to "A", "Referer" to "source"), f.content.headers(f.source))238 assertTrue(f.owner.isActive)239 f.close()240 }241242 @Test fun closeJoinsRuntimeCleanupRejectsRetainedRequestsAndPreservesParent() = runTest {243 val f = Fixture(this)244 val entered = CompletableDeferred<Unit>()245 val finalizing = CompletableDeferred<Unit>()246 val release = CompletableDeferred<Unit>()247 f.factory.videoAction = { entered.complete(Unit); awaitCancellation() }248 f.factory.finalizer = { finalizing.complete(Unit); release.await() }249 val request = async { f.content.videos(f.source, chapter) }250 entered.await()251 val closing = async { f.content.closeAndJoin() }252 finalizing.await()253 assertFalse(closing.isCompleted)254 release.complete(Unit); closing.await()255 assertFailsWith<CancellationException> { request.await() }256 assertTrue(f.owner.isActive)257 assertFailsWith<CancellationException> { f.content.pages(null, chapter, false) }258 assertFailsWith<CancellationException> { f.content.headers(f.source) }259 assertFailsWith<CancellationException> { f.content.videos(null, chapter) }260 assertFailsWith<CancellationException> { f.content.novelText(null, "Novel", "inline") }261 assertEquals(1, f.factory.created)262 assertTrue(f.archivePaths.isEmpty())263 f.close()264 }265266 @Test fun localNovelParsesCapturedChapterAndEmbeddedImagesWithoutExtension() = runTest {267 val f = Fixture(this)268 val other = Fixture(this, "B")269 try {270 f.epubChapters = listOf(LocalEpubChapter("First", "OEBPS/first.xhtml"), LocalEpubChapter("Second", "OEBPS/Text/second.xhtml"))271 f.epubHtml = "<h2>Second</h2><p><a href='https://book.test/next'>Next</a></p><img src='../Images/cover%20art.png?size=2#x'>"272 f.epubResources["OEBPS/Images/cover art.png"] = byteArrayOf(1, 2, 3)273 val opened = mutableListOf<String>()274 val parsed = loadNovelDocument(f.content, f.source, "Book", localNovel).parse(opened::add)275 assertEquals("Second", assertIs<NovelContentBlock.Text>(parsed.blocks[0]).text.text)276 val paragraph = assertIs<NovelContentBlock.Text>(parsed.blocks[1]).text277 val link = assertIs<LinkAnnotation.Url>(paragraph.getLinkAnnotations(0, paragraph.length).single().item)278 link.linkInteractionListener?.onClick(link)279 assertEquals(listOf("https://book.test/next"), opened)280 assertContentEquals(byteArrayOf(1, 2, 3), assertIs<NovelImageSource.Embedded>(assertIs<NovelContentBlock.Image>(parsed.blocks[2]).source).bytes)281 assertEquals(listOf("/A/book.epub" to 1), f.epubChapterReads)282 assertEquals(listOf("/A/book.epub" to "OEBPS/Images/cover art.png"), f.epubResourceReads)283 assertEquals(0, f.factory.created)284 assertTrue(other.epubChapterReads.isEmpty())285 assertTrue(other.epubResourceReads.isEmpty())286 } finally { f.close(); other.close() }287 }288289 @Test fun blankLocalChapterFallsBackToRemoteMarkupWithItsLocalResources() = runTest {290 val f = Fixture(this)291 try {292 f.epubHtml = " "293 f.factory.htmlAction = { "<p>Remote</p><img src='../Images/cover.png'>" }294 f.epubResources["OEBPS/Images/cover.png"] = byteArrayOf(4)295 val parsed = loadNovelDocument(f.content, f.source, "Book", localNovel).parse()296 assertEquals("Remote", assertIs<NovelContentBlock.Text>(parsed.blocks[0]).text.text)297 assertContentEquals(byteArrayOf(4), assertIs<NovelImageSource.Embedded>(assertIs<NovelContentBlock.Image>(parsed.blocks[1]).source).bytes)298 assertEquals(1, f.factory.created)299 assertEquals(1, f.factory.disposed)300 } finally { f.close() }301 }302303 @Test fun malformedEpubIndexDefaultsToZeroAndMissingHrefDoesNotReadImages() = runTest {304 val f = Fixture(this)305 try {306 f.epubChapters = emptyList()307 f.epubHtml = "<p>Local</p><img src='https://img.test/cover.png'>"308 val parsed = loadNovelDocument(f.content, f.source, "Book", localNovel.copy(archivePath = "/A/book.EPUB#bad")).parse()309 assertEquals(listOf("/A/book.EPUB" to 0), f.epubChapterReads)310 assertIs<NovelImageSource.Remote>(assertIs<NovelContentBlock.Image>(parsed.blocks[1]).source)311 assertTrue(f.epubResourceReads.isEmpty())312 } finally { f.close() }313 }314315 @Test fun embeddedResourceCapabilityExpiresAfterParsingEvenWithALiveOwner() = runTest {316 val f = Fixture(this)317 try {318 var retained: ProfileNovelContent? = null319 f.content.novelContent(f.source, "Book", localNovel) { retained = it }320 assertFailsWith<CancellationException> { assertNotNull(retained).readEmbeddedResource("cover.png") }321 assertTrue(f.epubResourceReads.isEmpty())322 assertTrue(f.owner.isActive)323 } finally { f.close() }324 }325326 @Test fun cancellationDuringEpubInventoryPreventsChapterReadAndParsing() = runTest {327 val f = Fixture(this)328 var parsed = false329 f.beforeEpubInventory = { f.owner.cancel() }330 try {331 assertFailsWith<CancellationException> {332 f.content.novelContent(f.source, "Book", localNovel) { parsed = true }333 }334 assertTrue(f.epubChapterReads.isEmpty())335 assertEquals(0, f.factory.created)336 assertFalse(parsed)337 } finally { f.close() }338 }339340 @Test fun retirementDuringEpubReadPreventsFallbackAndParsing() = runTest {341 val f = Fixture(this)342 var parsed = false343 f.epubHtml = ""344 f.beforeEpubChapterRead = { f.open = false }345 try {346 assertFailsWith<CancellationException> {347 f.content.novelContent(f.source, "Book", localNovel) { parsed = true }348 }349 assertEquals(0, f.factory.created)350 assertFalse(parsed)351 } finally { f.close() }352 }353354 @Test fun archiveFailureAfterRetirementIsCancellationAndCannotStartUiFallback() = runTest {355 val f = Fixture(this)356 f.beforeEpubChapterRead = { f.open = false; error("Archive failed after retirement") }357 var fallback = false358 try {359 assertFailsWith<CancellationException> {360 eu.friedcutlet.yokan.services.catchingNonCancellation {361 loadNovelDocument(f.content, f.source, "Book", localNovel)362 }.getOrElse { fallback = true; throw it }363 }364 assertFalse(fallback)365 assertEquals(0, f.factory.created)366 assertTrue(f.owner.isActive)367 } finally { f.close() }368 }369370 @Test fun retirementDuringEmbeddedImageReadRejectsTheEntireParsedResult() = runTest {371 val f = Fixture(this)372 f.epubHtml = "<img src='../Images/first.png'><img src='../Images/second.png'>"373 f.beforeEpubResourceRead = { f.open = false }374 try {375 assertFailsWith<CancellationException> { loadNovelDocument(f.content, f.source, "Book", localNovel) }376 assertEquals(1, f.epubResourceReads.size)377 assertTrue(f.owner.isActive)378 } finally { f.close() }379 }380381 @Test fun parserFailurePreservesTheContentServiceAndParent() = runTest {382 val f = Fixture(this)383 try {384 assertFailsWith<IllegalArgumentException> {385 f.content.novelContent(f.source, "Book", localNovel) { throw IllegalArgumentException("Malformed content") }386 }387 assertEquals("A epub", loadNovelDocument(f.content, f.source, "Book", localNovel).parse().plainText)388 assertTrue(f.owner.isActive)389 } finally { f.close() }390 }391392 @Test fun retiredContentCannotReadAnEpubOrStartParsing() = runTest {393 val f = Fixture(this)394 try {395 f.content.closeAndJoin()396 assertFailsWith<CancellationException> {397 f.content.novelContent(f.source, "Book", localNovel) { error("Retired parser") }398 }399 assertTrue(f.epubInventoryPaths.isEmpty())400 assertTrue(f.epubChapterReads.isEmpty())401 assertTrue(f.epubResourceReads.isEmpty())402 } finally { f.close() }403 }404405 internal class Fixture(406 test: TestScope,407 label: String = "A",408 fileDispatcher: CoroutineDispatcher = StandardTestDispatcher(test.testScheduler),409 ) {410 val owner = SupervisorJob()411 val scope = CoroutineScope(owner + StandardTestDispatcher(test.testScheduler))412 val db = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(413 sources = listOf(DbSource(id = 7, name = label, version = "1", isAdded = true)),414 mangas = listOf(DbManga(id = 1, sourceId = 7)),415 chapters = listOf(DbChapter(id = 10, mangaId = 1, url = "/chapter")),416 pageCache = emptyList(),417 ))418 val repository = DefaultYokanRepository(db)419 val source = requireNotNull(repository.source(7))420 val factory = RuntimeFactory(db, label)421 var open = true422 var archivePages = emptyList<DbPageUrl>()423 val archivePaths = mutableListOf<String>()424 var fileExists = false425 var localFiles = emptyList<LocalFileEntry>()426 var localBytes = byteArrayOf()427 var epubChapters = listOf(LocalEpubChapter("Chapter", "OEBPS/Text/chapter.xhtml"), LocalEpubChapter("Next", "OEBPS/Text/next.xhtml"))428 var epubHtml = "<p>$label epub</p>"429 val epubResources = mutableMapOf<String, ByteArray>()430 val epubInventoryPaths = mutableListOf<String>()431 val epubChapterReads = mutableListOf<Pair<String, Int>>()432 val epubResourceReads = mutableListOf<Pair<String, String>>()433 var beforeEpubInventory: () -> Unit = {}434 var beforeEpubChapterRead: () -> Unit = {}435 var beforeEpubResourceRead: () -> Unit = {}436 val files = object : LocalFileService {437 override val downloadRoot = "/$label/downloads"438 override val backupRoot = "/$label/backups"439 override val cacheRoot = "/$label/cache"440 override fun writeBytes(path: String, bytes: ByteArray) = error("Unexpected write")441 override fun readBytes(path: String): ByteArray = error("Unexpected read")442 override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray = localBytes443 override fun canonicalPath(path: String) = path444 override fun exists(path: String) = fileExists445 override fun deleteRecursively(path: String) = error("Unexpected delete")446 override fun directorySize(path: String) = 0L447 override fun openLocation(path: String) = false448 override fun listLocalEntries(root: String) = emptyList<LocalEntry>()449 override fun listFiles(root: String) = localFiles450 }451 val archives = object : LocalArchiveService {452 override fun listPages(archivePath: String): List<DbPageUrl> {453 archivePaths += archivePath454 return archivePages455 }456 override fun listEpubChapters(archivePath: String): List<LocalEpubChapter> {457 epubInventoryPaths += archivePath458 beforeEpubInventory()459 return epubChapters460 }461 override fun readEpubChapter(archivePath: String, index: Int): String {462 epubChapterReads += archivePath to index463 beforeEpubChapterRead()464 return epubHtml465 }466 override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? {467 epubResourceReads += archivePath to resourcePath468 beforeEpubResourceRead()469 return epubResources[resourcePath]470 }471 override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? = null472 }473 val content = ProfileReaderContent(474 ProfileId.Default, db, factory, ChapterPageResolver(repository, db, factory),475 files, archives, scope, fileDispatcher, { open },476 )477 suspend fun close() { content.closeAndJoin(); owner.cancelAndJoin() }478 }479480 internal class RuntimeFactory(val db: YokanDatabase, label: String) : ExtensionRuntimeFactory {481 var created = 0482 var disposed = 0483 var cleaned = 0484 var headerAction: suspend () -> Map<String, String> = { mapOf("User-Agent" to label, "Referer" to "source") }485 var pageAction: suspend () -> List<DbPageUrl> = { listOf(DbPageUrl("$label/page", headers = mapOf("referer" to "page"))) }486 var videoAction: suspend () -> List<DbVideo> = { listOf(DbVideo(url = "$label/video", quality = "Auto", originalUrl = "$label/video")) }487 var htmlAction: suspend () -> String = { "<p>$label novel</p>" }488 var finalizer: suspend () -> Unit = {}489 override fun create(source: DbSource): ExtensionRuntimeService {490 created++491 return object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, db) {492 override fun dispose() { disposed++ }493 override suspend fun headers() = headerAction()494 override suspend fun pageList(url: String) = pageAction()495 override suspend fun videoList(url: String) = videoAction()496 override suspend fun htmlContent(name: String, url: String) = htmlAction()497 override suspend fun cleanHtmlContent(html: String): String { cleaned++; return html }498 }499 }500 override suspend fun <T> withRuntime(source: DbSource, block: suspend (ExtensionRuntimeService) -> T): T {501 val runtime = create(source)502 try { return block(runtime) }503 finally { withContext(NonCancellable) { try { finalizer() } finally { runtime.dispose() } } }504 }505 }506507 private companion object {508 val chapter = Chapter(id = 10, mangaId = 1, name = "Chapter", url = "/chapter")509 val localNovel = chapter.copy(archivePath = "/A/book.epub#1")510 }511}512