@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class) package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.app.profiles.deletePlatformProfileStorage import eu.friedcutlet.yokan.data.DefaultYokanRepository import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService import eu.friedcutlet.yokan.services.library.LocalMediaImporter import eu.friedcutlet.yokan.ui.screens.novel.* import kotlinx.coroutines.await import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.yield import kotlinx.coroutines.test.runTest import kotlin.js.JsAny import kotlin.js.Promise import kotlin.test.* class BrowserEpubReaderTest { @Test fun cancellationJoinsAnInFlightJavascriptReadBeforeClosingTheArchive() = runTest { val id = ProfileId.random() val files = createPlatformLocalFileService(id) val selection = browserMediaSelection(epubSelection(0).await()) try { val db = InMemoryYokanDatabase(emptySnapshot()) val folder = LocalMediaImporter(files, SettingsStore(DefaultYokanRepository(db), backgroundScope) {}).import(selection, DbItemType.Novel) holdNextEpubRead() val request = async { createPlatformLocalArchiveService(id).readEpubResourceAsync("${folder.path}/Book.epub", "OEBPS/Images/cover art.png") } try { waitForEpubRead().await() request.cancel() yield() assertFalse(request.isCompleted) assertEquals(0, epubCloses()) } finally { releaseEpubRead(); request.cancelAndJoin() } assertEquals(1, epubOpens()) assertEquals(1, epubCloses()) } finally { selection.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) } } @Test fun corruptOptionalResourcesFailCrcValidationWithoutChangingTheStoredBook() = runTest { val id = ProfileId.random() val files = createPlatformLocalFileService(id) val selection = browserMediaSelection(epubSelection(2).await()) try { val db = InMemoryYokanDatabase(emptySnapshot()) val folder = LocalMediaImporter(files, SettingsStore(DefaultYokanRepository(db), backgroundScope) {}).import(selection, DbItemType.Novel) val path = "${folder.path}/Book.epub" val size = files.directorySize(path) val archives = createPlatformLocalArchiveService(id) assertEquals(listOf("Second", "First"), archives.listEpubChaptersAsync(path).map { it.title }) assertNull(archives.readEpubResourceAsync(path, "OEBPS/Images/cover art.png")) assertTrue(archives.readEpubChapterAsync(path, 0).contains("Offline second")) assertEquals(epubOpens(), epubCloses()) assertEquals(size, files.directorySize(path)) } finally { selection.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) } } @Test fun importedEpubScansAndReadsOfflineWithEmbeddedImagesAndCachedInventory() = runTest { val id = ProfileId.random() val files = createPlatformLocalFileService(id) val archives = createPlatformLocalArchiveService(id) val db = InMemoryYokanDatabase(emptySnapshot()) val repository = DefaultYokanRepository(db) val factory = ProfileReaderContentTest.RuntimeFactory(db, "Browser") val content = ProfileReaderContent(id, db, factory, ChapterPageResolver(repository, db, factory), files, archives, backgroundScope) val selection = browserMediaSelection(epubSelection(0).await()) try { val folder = LocalMediaImporter(files, SettingsStore(repository, backgroundScope) {}).import(selection, DbItemType.Novel) val scanner = DefaultLocalLibraryService(db, files, archives) assertEquals(1, scanner.scan().added) val title = db.mangas().single() assertEquals(DbItemType.Novel, title.itemType) assertEquals(listOf("Second", "First"), db.chapters(title.id).map { it.name }) assertEquals(1, epubOpens()) scanner.scan() assertEquals(1, epubOpens()) val chapter = repository.chapters(title.id).first { it.archivePath.endsWith("#0") } val parsed = loadNovelDocument(content, null, title.name.orEmpty(), chapter).parse() assertTrue(parsed.plainText.contains("Offline second")) val images = parsed.blocks.filterIsInstance() assertEquals(2, images.size) assertContentEquals(byteArrayOf(9, 8, 7, 6), assertIs(images[0].source).bytes) assertSame(assertIs(images[0].source).bytes, assertIs(images[1].source).bytes) assertEquals(0, factory.created) assertEquals(3, epubOpens()) assertEquals(epubOpens(), epubCloses()) val old = db.chapters(title.id).first { it.archivePath.endsWith("#0") } db.upsertChapter(old.copy(isRead = true, lastPageRead = "7", isBookmarked = true)) scanner.scanFresh() val refreshed = assertNotNull(db.chapter(old.id)) assertTrue(refreshed.isRead && refreshed.isBookmarked) assertEquals("7", refreshed.lastPageRead) assertEquals(4, epubOpens()) assertFalse(epubReadPadding()) assertTrue(files.directorySize("${folder.path}/Book.epub") > 65536) } finally { selection.close(); content.closeAndJoin(); files.close(); deletePlatformProfileStorage(id, emptyList()) } } @Test fun oversizedChaptersAreRejectedAndArchiveSessionsCloseWithoutLosingTheOriginal() = runTest { val id = ProfileId.random() val files = createPlatformLocalFileService(id) val selection = browserMediaSelection(epubSelection(1).await()) try { val db = InMemoryYokanDatabase(emptySnapshot()) val folder = LocalMediaImporter(files, SettingsStore(DefaultYokanRepository(db), backgroundScope) {}).import(selection, DbItemType.Novel) val path = "${folder.path}/Book.epub" val size = files.directorySize(path) val archives = createPlatformLocalArchiveService(id) assertTrue(archives.listEpubChaptersAsync(path).isEmpty()) assertFails { archives.readEpubChapterAsync(path, 0) } assertEquals(epubOpens(), epubCloses()) assertEquals(size, files.directorySize(path)) assertNull(archives.readEpubResourceAsync(path, "../other-profile/secret")) assertEquals(epubOpens(), epubCloses()) } finally { selection.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) } } } private fun epubSelection(mode: Int): Promise = js("""(async () => { if (!globalThis.yokanBrowserArchives) await new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = '/browser-archives.js'; script.onload = resolve; script.onerror = reject; document.head.append(script); }); const archives = globalThis.yokanBrowserArchives; if (!archives.originalOpenRead) archives.originalOpenRead = archives.openRead; globalThis.yokanEpubProbe = { opens: 0, closes: 0, paths: [] }; archives.openRead = async file => { const probe = globalThis.yokanEpubProbe; const session = await archives.originalOpenRead(file); probe.opens++; return { read: async (name, maximum) => { probe.paths.push(name); if (probe.gate) { const gate = probe.gate; probe.gate = null; probe.enter(); await gate; } return session.read(name, maximum); }, close: async () => { probe.closes++; await session.close(); } }; }; const entries = [ ['mimetype', 'application/epub+zip'], ['META-INF/container.xml', ''], ['OEBPS/book.opf', ''], ['OEBPS/Text/one.xhtml', 'FirstOffline first'], ['OEBPS/Text/two words.xhtml', mode === 1 ? new Uint8Array(8 * 1024 * 1024 + 1) : 'Second

Offline second

'], ['OEBPS/Images/cover art.png', new Uint8Array([9,8,7,6])], ['unused-padding.bin', new Uint8Array(65536)], ]; const chunks = []; await archives.write(entries.map(([name, bytes]) => ({ name, bytes: new Blob([bytes]) })), new WritableStream({ write: bytes => chunks.push(bytes.slice()) })); if (mode === 2) { const bytes = new Uint8Array(await new Blob(chunks).arrayBuffer()); let found = false; 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) { bytes[i] ^= 1; found = true; break; } if (!found) throw new Error('CRC fixture payload was not found.'); return globalThis.yokanBrowserFiles.selectedMedia([new File([bytes], 'Book.epub')]); } return globalThis.yokanBrowserFiles.selectedMedia([new File(chunks, 'Book.epub')]); })()""") private fun epubOpens(): Int = js("globalThis.yokanEpubProbe.opens") private fun epubCloses(): Int = js("globalThis.yokanEpubProbe.closes") private fun epubReadPadding(): Boolean = js("globalThis.yokanEpubProbe.paths.includes('unused-padding.bin')") private fun holdNextEpubRead(): Unit = js("""(() => { const probe = globalThis.yokanEpubProbe; probe.gate = new Promise(resolve => { probe.release = resolve; }); probe.entered = new Promise(resolve => { probe.enter = resolve; }); })()""") private fun waitForEpubRead(): Promise = js("globalThis.yokanEpubProbe.entered.then(() => null)") private fun releaseEpubRead(): Unit = js("globalThis.yokanEpubProbe.release()")