Yokan / rebuild
Course 1 8624561

BrowserEpubReaderTest.kt

composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/files/BrowserEpubReaderTest.kt

test / fixture176 lines
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class)23package eu.friedcutlet.yokan.services.files45import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.app.profiles.deletePlatformProfileStorage7import eu.friedcutlet.yokan.data.DefaultYokanRepository8import eu.friedcutlet.yokan.data.SettingsStore9import eu.friedcutlet.yokan.database.*10import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver11import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent12import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest13import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService14import eu.friedcutlet.yokan.services.library.LocalMediaImporter15import eu.friedcutlet.yokan.ui.screens.novel.*16import kotlinx.coroutines.await17import kotlinx.coroutines.async18import kotlinx.coroutines.cancelAndJoin19import kotlinx.coroutines.yield20import kotlinx.coroutines.test.runTest21import kotlin.js.JsAny22import kotlin.js.Promise23import kotlin.test.*2425class BrowserEpubReaderTest {26    @Test fun cancellationJoinsAnInFlightJavascriptReadBeforeClosingTheArchive() = runTest {27        val id = ProfileId.random()28        val files = createPlatformLocalFileService(id)29        val selection = browserMediaSelection(epubSelection(0).await<JsAny>())30        try {31            val db = InMemoryYokanDatabase(emptySnapshot())32            val folder = LocalMediaImporter(files, SettingsStore(DefaultYokanRepository(db), backgroundScope) {}).import(selection, DbItemType.Novel)33            holdNextEpubRead()34            val request = async { createPlatformLocalArchiveService(id).readEpubResourceAsync("${folder.path}/Book.epub", "OEBPS/Images/cover art.png") }35            try {36                waitForEpubRead().await<JsAny?>()37                request.cancel()38                yield()39                assertFalse(request.isCompleted)40                assertEquals(0, epubCloses())41            } finally { releaseEpubRead(); request.cancelAndJoin() }42            assertEquals(1, epubOpens())43            assertEquals(1, epubCloses())44        } finally { selection.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) }45    }4647    @Test fun corruptOptionalResourcesFailCrcValidationWithoutChangingTheStoredBook() = runTest {48        val id = ProfileId.random()49        val files = createPlatformLocalFileService(id)50        val selection = browserMediaSelection(epubSelection(2).await<JsAny>())51        try {52            val db = InMemoryYokanDatabase(emptySnapshot())53            val folder = LocalMediaImporter(files, SettingsStore(DefaultYokanRepository(db), backgroundScope) {}).import(selection, DbItemType.Novel)54            val path = "${folder.path}/Book.epub"55            val size = files.directorySize(path)56            val archives = createPlatformLocalArchiveService(id)57            assertEquals(listOf("Second", "First"), archives.listEpubChaptersAsync(path).map { it.title })58            assertNull(archives.readEpubResourceAsync(path, "OEBPS/Images/cover art.png"))59            assertTrue(archives.readEpubChapterAsync(path, 0).contains("Offline second"))60            assertEquals(epubOpens(), epubCloses())61            assertEquals(size, files.directorySize(path))62        } finally { selection.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) }63    }64    @Test fun importedEpubScansAndReadsOfflineWithEmbeddedImagesAndCachedInventory() = runTest {65        val id = ProfileId.random()66        val files = createPlatformLocalFileService(id)67        val archives = createPlatformLocalArchiveService(id)68        val db = InMemoryYokanDatabase(emptySnapshot())69        val repository = DefaultYokanRepository(db)70        val factory = ProfileReaderContentTest.RuntimeFactory(db, "Browser")71        val content = ProfileReaderContent(id, db, factory, ChapterPageResolver(repository, db, factory), files, archives, backgroundScope)72        val selection = browserMediaSelection(epubSelection(0).await<JsAny>())73        try {74            val folder = LocalMediaImporter(files, SettingsStore(repository, backgroundScope) {}).import(selection, DbItemType.Novel)75            val scanner = DefaultLocalLibraryService(db, files, archives)76            assertEquals(1, scanner.scan().added)77            val title = db.mangas().single()78            assertEquals(DbItemType.Novel, title.itemType)79            assertEquals(listOf("Second", "First"), db.chapters(title.id).map { it.name })80            assertEquals(1, epubOpens())81            scanner.scan()82            assertEquals(1, epubOpens())83            val chapter = repository.chapters(title.id).first { it.archivePath.endsWith("#0") }84            val parsed = loadNovelDocument(content, null, title.name.orEmpty(), chapter).parse()85            assertTrue(parsed.plainText.contains("Offline second"))86            val images = parsed.blocks.filterIsInstance<NovelContentBlock.Image>()87            assertEquals(2, images.size)88            assertContentEquals(byteArrayOf(9, 8, 7, 6), assertIs<NovelImageSource.Embedded>(images[0].source).bytes)89            assertSame(assertIs<NovelImageSource.Embedded>(images[0].source).bytes, assertIs<NovelImageSource.Embedded>(images[1].source).bytes)90            assertEquals(0, factory.created)91            assertEquals(3, epubOpens())92            assertEquals(epubOpens(), epubCloses())93            val old = db.chapters(title.id).first { it.archivePath.endsWith("#0") }94            db.upsertChapter(old.copy(isRead = true, lastPageRead = "7", isBookmarked = true))95            scanner.scanFresh()96            val refreshed = assertNotNull(db.chapter(old.id))97            assertTrue(refreshed.isRead && refreshed.isBookmarked)98            assertEquals("7", refreshed.lastPageRead)99            assertEquals(4, epubOpens())100            assertFalse(epubReadPadding())101            assertTrue(files.directorySize("${folder.path}/Book.epub") > 65536)102        } finally {103            selection.close(); content.closeAndJoin(); files.close(); deletePlatformProfileStorage(id, emptyList())104        }105    }106107    @Test fun oversizedChaptersAreRejectedAndArchiveSessionsCloseWithoutLosingTheOriginal() = runTest {108        val id = ProfileId.random()109        val files = createPlatformLocalFileService(id)110        val selection = browserMediaSelection(epubSelection(1).await<JsAny>())111        try {112            val db = InMemoryYokanDatabase(emptySnapshot())113            val folder = LocalMediaImporter(files, SettingsStore(DefaultYokanRepository(db), backgroundScope) {}).import(selection, DbItemType.Novel)114            val path = "${folder.path}/Book.epub"115            val size = files.directorySize(path)116            val archives = createPlatformLocalArchiveService(id)117            assertTrue(archives.listEpubChaptersAsync(path).isEmpty())118            assertFails { archives.readEpubChapterAsync(path, 0) }119            assertEquals(epubOpens(), epubCloses())120            assertEquals(size, files.directorySize(path))121            assertNull(archives.readEpubResourceAsync(path, "../other-profile/secret"))122            assertEquals(epubOpens(), epubCloses())123        } finally { selection.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) }124    }125}126127private fun epubSelection(mode: Int): Promise<JsAny> = js("""(async () => {128    if (!globalThis.yokanBrowserArchives) await new Promise((resolve, reject) => {129        const script = document.createElement('script'); script.src = '/browser-archives.js';130        script.onload = resolve; script.onerror = reject; document.head.append(script);131    });132    const archives = globalThis.yokanBrowserArchives;133    if (!archives.originalOpenRead) archives.originalOpenRead = archives.openRead;134    globalThis.yokanEpubProbe = { opens: 0, closes: 0, paths: [] };135    archives.openRead = async file => {136        const probe = globalThis.yokanEpubProbe;137        const session = await archives.originalOpenRead(file); probe.opens++;138        return { read: async (name, maximum) => {139                probe.paths.push(name);140                if (probe.gate) { const gate = probe.gate; probe.gate = null; probe.enter(); await gate; }141                return session.read(name, maximum);142            },143            close: async () => { probe.closes++; await session.close(); } };144    };145    const entries = [146        ['mimetype', 'application/epub+zip'],147        ['META-INF/container.xml', '<container><rootfiles><rootfile full-path="OEBPS/book.opf"/></rootfiles></container>'],148        ['OEBPS/book.opf', '<package><manifest><item id="one" href="Text/one.xhtml"/><item id="two" href="Text/two%20words.xhtml"/></manifest><spine><itemref idref="two"/><itemref idref="one"/></spine></package>'],149        ['OEBPS/Text/one.xhtml', '<html><head><title>First</title></head><body>Offline first</body></html>'],150        ['OEBPS/Text/two words.xhtml', mode === 1 ? new Uint8Array(8 * 1024 * 1024 + 1) : '<html><head><title>Second</title></head><body><p>Offline second</p><img src="../Images/cover%20art.png"/><img src="../Images/cover%20art.png"/></body></html>'],151        ['OEBPS/Images/cover art.png', new Uint8Array([9,8,7,6])],152        ['unused-padding.bin', new Uint8Array(65536)],153    ];154    const chunks = [];155    await archives.write(entries.map(([name, bytes]) => ({ name, bytes: new Blob([bytes]) })), new WritableStream({ write: bytes => chunks.push(bytes.slice()) }));156    if (mode === 2) {157        const bytes = new Uint8Array(await new Blob(chunks).arrayBuffer());158        let found = false;159        for (let i = 0; i < bytes.length - 3; i++) if (bytes[i] === 9 && bytes[i+1] === 8 && bytes[i+2] === 7 && bytes[i+3] === 6) {160            bytes[i] ^= 1; found = true; break;161        }162        if (!found) throw new Error('CRC fixture payload was not found.');163        return globalThis.yokanBrowserFiles.selectedMedia([new File([bytes], 'Book.epub')]);164    }165    return globalThis.yokanBrowserFiles.selectedMedia([new File(chunks, 'Book.epub')]);166})()""")167private fun epubOpens(): Int = js("globalThis.yokanEpubProbe.opens")168private fun epubCloses(): Int = js("globalThis.yokanEpubProbe.closes")169private fun epubReadPadding(): Boolean = js("globalThis.yokanEpubProbe.paths.includes('unused-padding.bin')")170private fun holdNextEpubRead(): Unit = js("""(() => {171    const probe = globalThis.yokanEpubProbe;172    probe.gate = new Promise(resolve => { probe.release = resolve; });173    probe.entered = new Promise(resolve => { probe.enter = resolve; });174})()""")175private fun waitForEpubRead(): Promise<JsAny?> = js("globalThis.yokanEpubProbe.entered.then(() => null)")176private fun releaseEpubRead(): Unit = js("globalThis.yokanEpubProbe.release()")177

Search chapters, reference and source filenames.