BrowserLocalLibraryScanTest.kt
composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/files/BrowserLocalLibraryScanTest.kt
1package eu.friedcutlet.yokan.services.files23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.app.profiles.deletePlatformProfileStorage5import eu.friedcutlet.yokan.database.*6import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService7import kotlinx.coroutines.test.runTest8import kotlin.test.*910class BrowserLocalLibraryScanTest {11 @Test fun castSidecarsUseRealOpfsPortraitUrlsAndExplicitClear() = runTest {12 val id = ProfileId.random()13 val files = createPlatformLocalFileService(id)14 val root = "${files.downloadRoot}/anime"15 try {16 files.writeBytesAsync("$root/Show/Episode 1.mp4", byteArrayOf(1))17 files.writeBytesAsync("$root/Show/actor.png", byteArrayOf(2, 3))18 files.writeBytesAsync("$root/Show/details.json", """{"cast":[{"name":"Actor","role":"Voice actor","character":"Hero","image_url":"actor.png"},{"name":"Other","image_url":"../private.png"}]}""".encodeToByteArray())19 val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root)))))20 val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))21 scanner.scan()22 val title = db.mangas().single()23 assertEquals(2, title.cast.size)24 assertEquals("Actor", title.cast[0].name)25 assertEquals("Hero", title.cast[0].character)26 assertTrue(assertNotNull(title.cast[0].imageUrl).contains("__yokan_files__/"))27 assertNull(title.cast[1].imageUrl)28 assertNull(title.customCoverImage)29 val chapter = db.chapters(title.id).single()30 db.upsertChapter(chapter.copy(isRead = true, lastPageRead = "1234"))31 files.writeBytesAsync("$root/Show/details.json", "{}".encodeToByteArray())32 scanner.scanFresh()33 assertEquals(title.cast, db.manga(title.id)?.cast)34 files.writeBytesAsync("$root/Show/details.json", """{"cast":[]}""".encodeToByteArray())35 scanner.scanFresh()36 assertEquals(emptyList(), db.manga(title.id)?.cast)37 assertEquals("1234", db.chapter(chapter.id)?.lastPageRead)38 assertContentEquals(byteArrayOf(2, 3), files.readBytesAsync("$root/Show/actor.png", 2))39 } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }40 }4142 @Test fun nestedAnimeFilesUseSeasonSidecarsWithoutFolderOrPreviewChapters() = runTest {43 val id = ProfileId.random()44 val files = createPlatformLocalFileService(id)45 val root = "${files.downloadRoot}/anime"46 try {47 val show = "$root/Show"48 for (path in listOf("Episode 3.mp4", "Season 0/Episode 1.mkv", "Season 1/Episode 1.mp4", "Season 1/Episode 2.mp4",49 "Season 1/deeper/Episode 99.mp4", ".hidden/Episode 50.mp4", "Season 1/.Episode 51.mp4", "Season 1/art/preview.png")) {50 files.writeBytesAsync("$show/$path", byteArrayOf(1))51 }52 files.writeBytesAsync("$show/episodes.json", """[{"episode_number":3,"name":"Finale"}]""".encodeToByteArray())53 files.writeBytesAsync("$show/Season 0/episodes.json", """[{"episode_number":1,"name":"Special"}]""".encodeToByteArray())54 files.writeBytesAsync("$show/Season 1/episodes.json", """[{"episode_number":1,"name":"Premiere","preview_url":"art/preview.png"}]""".encodeToByteArray())55 assertEquals(setOf("Episode 3.mp4", "Season 0", "Season 1", ".hidden", "episodes.json"),56 assertNotNull(files.listDirectoryEntries(show)).map { it.name }.toSet())57 assertNull(files.listDirectoryEntries("$show/missing"))58 val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root)))))59 val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))60 scanner.scan()61 val title = db.mangas().single()62 val episodes = db.chapters(title.id)63 assertEquals(4, episodes.size)64 assertEquals(setOf("Finale", "Special", "Premiere", "Episode 2"), episodes.map { it.name }.toSet())65 assertEquals(0, episodes.single { it.name == "Special" }.season)66 val premiere = episodes.single { it.name == "Premiere" }67 assertEquals(1, premiere.season)68 assertEquals(1.0, premiere.number)69 assertTrue(assertNotNull(premiere.thumbnailUrl).contains("__yokan_files__/"))70 assertTrue(episodes.all { it.archivePath.endsWith(".mp4") || it.archivePath.endsWith(".mkv") })71 db.upsertChapter(premiere.copy(isRead = true, isBookmarked = true, lastPageRead = "2345"))72 scanner.scanFresh()73 assertEquals(episodes.map { it.id }.toSet(), db.chapters(title.id).map { it.id }.toSet())74 assertEquals("2345", db.chapter(premiere.id)?.lastPageRead)75 assertTrue(db.chapter(premiere.id)?.isRead == true)76 } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }77 }7879 @Test fun episodeMetadataKeepsNumbersSeasonAndProgressInRealOpfsScans() = runTest {80 val id = ProfileId.random()81 val files = createPlatformLocalFileService(id)82 val root = "${files.downloadRoot}/anime"83 val season = "$root/Show/Season 2"84 try {85 files.writeBytesAsync("$season/Episode 12.5.mp4", byteArrayOf(1))86 files.writeBytesAsync("$season/Episode 13.mp4", byteArrayOf(2))87 files.writeBytesAsync("$season/preview.png", byteArrayOf(3, 4))88 files.writeBytesAsync("$season/details.json", """{"title":"Show Season Two"}""".encodeToByteArray())89 files.writeBytesAsync("$season/episodes.json", """[{"episode_number":12.5,"name":"Opening Night","date_upload":"2026-04-12","fillermark":true,"summary":"Local synopsis","preview_url":"preview.png"}]""".encodeToByteArray())90 val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root)))))91 val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))92 scanner.scan()93 // `Show` has no episode files of its own, so it is a Seasons title owning the season record.94 val show = db.mangas().single { it.parentId == null }95 assertEquals(DbFetchType.Seasons, show.fetchType)96 assertTrue(db.chapters(show.id).isEmpty())97 val title = db.mangas().single { it.parentId == show.id }98 assertEquals(2.0, title.seasonNumber)99 assertEquals("Show Season Two", title.name)100 assertEquals(2, db.chapters(title.id).size)101 val episode = db.chapters(title.id).first { it.number == 12.5 }102 assertEquals("Opening Night", episode.name)103 assertEquals("Episode 12.5", episode.numberingName)104 assertEquals(2, episode.season)105 assertTrue(episode.isFiller)106 assertEquals("Local synopsis", episode.description)107 assertEquals("2026-04-12", episode.dateUpload)108 assertTrue(assertNotNull(episode.thumbnailUrl).contains("__yokan_files__/"))109 db.upsertChapter(episode.copy(isRead = true, isBookmarked = true, lastPageRead = "42000"))110 files.writeBytesAsync("$season/episodes.json", """[{"episode_number":12.5,"name":"Another title","fillermark":false,"scanlator":"Group"}]""".encodeToByteArray())111 scanner.scanFresh()112 val updated = assertNotNull(db.chapter(episode.id))113 assertEquals("Another title", updated.name)114 assertEquals(episode.archivePath, updated.archivePath)115 assertEquals(12.5, updated.number)116 assertEquals(2, updated.season)117 assertFalse(updated.isFiller)118 assertEquals("Group", updated.scanlator)119 assertTrue(updated.isRead && updated.isBookmarked)120 assertEquals("42000", updated.lastPageRead)121 assertEquals(2, db.chapters(title.id).size)122 assertEquals(setOf(show.id, title.id), db.mangas().map { it.id }.toSet())123 assertContentEquals(byteArrayOf(1), files.readBytesAsync("$season/Episode 12.5.mp4", 1))124 } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }125 }126 @Test fun animetailDetailsUseTheirOwnStatusMappingAndMergeLegacyArtworkFromOpfs() = runTest {127 val id = ProfileId.random()128 val files = createPlatformLocalFileService(id)129 val root = "${files.downloadRoot}/anime"130 try {131 files.writeBytesAsync("$root/Show/Episode 1.mp4", byteArrayOf(1))132 files.writeBytesAsync("$root/Show/metadata.json", """{"name":"Legacy","status":1,"imageUrl":"https://cover.test/image","language":"ja"}""".encodeToByteArray())133 files.writeBytesAsync("$root/Show/details.json", """{"title":"Animetail title","author":"Writer","genre":["Drama"],"status":1}""".encodeToByteArray())134 val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root)))))135 val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))136 scanner.scan()137 val title = db.mangas().single()138 assertEquals(DbItemType.Anime, title.itemType)139 assertEquals("Animetail title", title.name)140 assertEquals(DbStatus.Ongoing, title.status)141 assertEquals("Writer", title.author)142 assertEquals(listOf("Drama"), title.genre)143 assertEquals("https://cover.test/image", title.imageUrl)144 assertEquals("ja", title.lang)145 assertTrue(db.chapters(title.id).single().archivePath.endsWith("/Episode 1.mp4"))146 scanner.scanFresh()147 assertEquals(1, db.mangas().size)148 assertEquals(1, db.chapters(title.id).size)149 for ((value, status) in listOf(3 to DbStatus.Licensed, 7 to DbStatus.Upcoming)) {150 files.writeBytesAsync("$root/Show/details.json", "{\"title\":\"Animetail title\",\"status\":$value}".encodeToByteArray())151 scanner.scanFresh()152 assertEquals(status, db.manga(title.id)?.status)153 assertEquals(status.name, eu.friedcutlet.yokan.data.DefaultYokanRepository(db).manga(title.id)?.status?.name)154 assertEquals(1, db.chapters(title.id).size)155 }156 } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }157 }158 @Test fun opfsListingsAndSharedScannerReadMetadataAndCoversWithoutSynchronousDiskReads() = runTest {159 val id = ProfileId.random()160 val files = createPlatformLocalFileService(id)161 val root = "${files.downloadRoot}/local"162 try {163 files.writeBytesAsync("$root/Title/metadata.json", "{\"name\":\"Offline title\",\"author\":\"Author\"}".encodeToByteArray())164 files.writeBytesAsync("$root/Title/cover.png", byteArrayOf(1, 2, 3))165 files.writeBytesAsync("$root/Title/Chapter 1/001.jpg", byteArrayOf(4, 5))166 assertEquals(listOf(LocalEntry("$root/Title", "Title", false)), files.listLocalEntries(root))167 assertNull(files.listLocalEntries("$root/missing"))168 val db = InMemoryYokanDatabase(emptySnapshot())169 val service = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))170 assertEquals(1, service.scan().added)171 val title = db.mangas().single()172 assertEquals("Offline title", title.name)173 assertEquals("Author", title.author)174 assertContentEquals(byteArrayOf(1, 2, 3), title.customCoverImage)175 assertTrue(db.chapters(title.id).single().archivePath.endsWith("/Title/Chapter 1"))176 assertEquals(0, service.scan().added)177 assertEquals(1, db.chapters(title.id).size)178 assertFails { files.listLocalEntries("/yokan/profiles/p_00000000000000000000000000000000/downloads/local") }179 } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }180 }181182 @Test fun emptyDirectoriesStayReadableAcrossDeletionAndReload() = runTest {183 val id = ProfileId.random()184 val files = createPlatformLocalFileService(id)185 val root = "${files.downloadRoot}/local"186 val path = "$root/one.cbz"187 files.writeBytesAsync(path, byteArrayOf(1))188 assertEquals(listOf(LocalEntry(path, "one", true)), files.listLocalEntries(root))189 files.deleteRecursivelyAsync(path)190 assertTrue(files.exists(root))191 assertEquals(emptyList(), files.listLocalEntries(root))192 files.close()193 val reopened = createPlatformLocalFileService(id)194 try {195 reopened.prepare()196 assertTrue(reopened.exists(root))197 assertEquals(emptyList(), reopened.listLocalEntries(root))198 } finally { reopened.close(); deletePlatformProfileStorage(id, emptyList()) }199 }200}201