package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.app.profiles.deletePlatformProfileStorage import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService import kotlinx.coroutines.test.runTest import kotlin.test.* class BrowserLocalLibraryScanTest { @Test fun castSidecarsUseRealOpfsPortraitUrlsAndExplicitClear() = runTest { val id = ProfileId.random() val files = createPlatformLocalFileService(id) val root = "${files.downloadRoot}/anime" try { files.writeBytesAsync("$root/Show/Episode 1.mp4", byteArrayOf(1)) files.writeBytesAsync("$root/Show/actor.png", byteArrayOf(2, 3)) 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()) val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root))))) val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id)) scanner.scan() val title = db.mangas().single() assertEquals(2, title.cast.size) assertEquals("Actor", title.cast[0].name) assertEquals("Hero", title.cast[0].character) assertTrue(assertNotNull(title.cast[0].imageUrl).contains("__yokan_files__/")) assertNull(title.cast[1].imageUrl) assertNull(title.customCoverImage) val chapter = db.chapters(title.id).single() db.upsertChapter(chapter.copy(isRead = true, lastPageRead = "1234")) files.writeBytesAsync("$root/Show/details.json", "{}".encodeToByteArray()) scanner.scanFresh() assertEquals(title.cast, db.manga(title.id)?.cast) files.writeBytesAsync("$root/Show/details.json", """{"cast":[]}""".encodeToByteArray()) scanner.scanFresh() assertEquals(emptyList(), db.manga(title.id)?.cast) assertEquals("1234", db.chapter(chapter.id)?.lastPageRead) assertContentEquals(byteArrayOf(2, 3), files.readBytesAsync("$root/Show/actor.png", 2)) } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) } } @Test fun nestedAnimeFilesUseSeasonSidecarsWithoutFolderOrPreviewChapters() = runTest { val id = ProfileId.random() val files = createPlatformLocalFileService(id) val root = "${files.downloadRoot}/anime" try { val show = "$root/Show" for (path in listOf("Episode 3.mp4", "Season 0/Episode 1.mkv", "Season 1/Episode 1.mp4", "Season 1/Episode 2.mp4", "Season 1/deeper/Episode 99.mp4", ".hidden/Episode 50.mp4", "Season 1/.Episode 51.mp4", "Season 1/art/preview.png")) { files.writeBytesAsync("$show/$path", byteArrayOf(1)) } files.writeBytesAsync("$show/episodes.json", """[{"episode_number":3,"name":"Finale"}]""".encodeToByteArray()) files.writeBytesAsync("$show/Season 0/episodes.json", """[{"episode_number":1,"name":"Special"}]""".encodeToByteArray()) files.writeBytesAsync("$show/Season 1/episodes.json", """[{"episode_number":1,"name":"Premiere","preview_url":"art/preview.png"}]""".encodeToByteArray()) assertEquals(setOf("Episode 3.mp4", "Season 0", "Season 1", ".hidden", "episodes.json"), assertNotNull(files.listDirectoryEntries(show)).map { it.name }.toSet()) assertNull(files.listDirectoryEntries("$show/missing")) val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root))))) val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id)) scanner.scan() val title = db.mangas().single() val episodes = db.chapters(title.id) assertEquals(4, episodes.size) assertEquals(setOf("Finale", "Special", "Premiere", "Episode 2"), episodes.map { it.name }.toSet()) assertEquals(0, episodes.single { it.name == "Special" }.season) val premiere = episodes.single { it.name == "Premiere" } assertEquals(1, premiere.season) assertEquals(1.0, premiere.number) assertTrue(assertNotNull(premiere.thumbnailUrl).contains("__yokan_files__/")) assertTrue(episodes.all { it.archivePath.endsWith(".mp4") || it.archivePath.endsWith(".mkv") }) db.upsertChapter(premiere.copy(isRead = true, isBookmarked = true, lastPageRead = "2345")) scanner.scanFresh() assertEquals(episodes.map { it.id }.toSet(), db.chapters(title.id).map { it.id }.toSet()) assertEquals("2345", db.chapter(premiere.id)?.lastPageRead) assertTrue(db.chapter(premiere.id)?.isRead == true) } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) } } @Test fun episodeMetadataKeepsNumbersSeasonAndProgressInRealOpfsScans() = runTest { val id = ProfileId.random() val files = createPlatformLocalFileService(id) val root = "${files.downloadRoot}/anime" val season = "$root/Show/Season 2" try { files.writeBytesAsync("$season/Episode 12.5.mp4", byteArrayOf(1)) files.writeBytesAsync("$season/Episode 13.mp4", byteArrayOf(2)) files.writeBytesAsync("$season/preview.png", byteArrayOf(3, 4)) files.writeBytesAsync("$season/details.json", """{"title":"Show Season Two"}""".encodeToByteArray()) 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()) val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root))))) val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id)) scanner.scan() // `Show` has no episode files of its own, so it is a Seasons title owning the season record. val show = db.mangas().single { it.parentId == null } assertEquals(DbFetchType.Seasons, show.fetchType) assertTrue(db.chapters(show.id).isEmpty()) val title = db.mangas().single { it.parentId == show.id } assertEquals(2.0, title.seasonNumber) assertEquals("Show Season Two", title.name) assertEquals(2, db.chapters(title.id).size) val episode = db.chapters(title.id).first { it.number == 12.5 } assertEquals("Opening Night", episode.name) assertEquals("Episode 12.5", episode.numberingName) assertEquals(2, episode.season) assertTrue(episode.isFiller) assertEquals("Local synopsis", episode.description) assertEquals("2026-04-12", episode.dateUpload) assertTrue(assertNotNull(episode.thumbnailUrl).contains("__yokan_files__/")) db.upsertChapter(episode.copy(isRead = true, isBookmarked = true, lastPageRead = "42000")) files.writeBytesAsync("$season/episodes.json", """[{"episode_number":12.5,"name":"Another title","fillermark":false,"scanlator":"Group"}]""".encodeToByteArray()) scanner.scanFresh() val updated = assertNotNull(db.chapter(episode.id)) assertEquals("Another title", updated.name) assertEquals(episode.archivePath, updated.archivePath) assertEquals(12.5, updated.number) assertEquals(2, updated.season) assertFalse(updated.isFiller) assertEquals("Group", updated.scanlator) assertTrue(updated.isRead && updated.isBookmarked) assertEquals("42000", updated.lastPageRead) assertEquals(2, db.chapters(title.id).size) assertEquals(setOf(show.id, title.id), db.mangas().map { it.id }.toSet()) assertContentEquals(byteArrayOf(1), files.readBytesAsync("$season/Episode 12.5.mp4", 1)) } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) } } @Test fun animetailDetailsUseTheirOwnStatusMappingAndMergeLegacyArtworkFromOpfs() = runTest { val id = ProfileId.random() val files = createPlatformLocalFileService(id) val root = "${files.downloadRoot}/anime" try { files.writeBytesAsync("$root/Show/Episode 1.mp4", byteArrayOf(1)) files.writeBytesAsync("$root/Show/metadata.json", """{"name":"Legacy","status":1,"imageUrl":"https://cover.test/image","language":"ja"}""".encodeToByteArray()) files.writeBytesAsync("$root/Show/details.json", """{"title":"Animetail title","author":"Writer","genre":["Drama"],"status":1}""".encodeToByteArray()) val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root))))) val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id)) scanner.scan() val title = db.mangas().single() assertEquals(DbItemType.Anime, title.itemType) assertEquals("Animetail title", title.name) assertEquals(DbStatus.Ongoing, title.status) assertEquals("Writer", title.author) assertEquals(listOf("Drama"), title.genre) assertEquals("https://cover.test/image", title.imageUrl) assertEquals("ja", title.lang) assertTrue(db.chapters(title.id).single().archivePath.endsWith("/Episode 1.mp4")) scanner.scanFresh() assertEquals(1, db.mangas().size) assertEquals(1, db.chapters(title.id).size) for ((value, status) in listOf(3 to DbStatus.Licensed, 7 to DbStatus.Upcoming)) { files.writeBytesAsync("$root/Show/details.json", "{\"title\":\"Animetail title\",\"status\":$value}".encodeToByteArray()) scanner.scanFresh() assertEquals(status, db.manga(title.id)?.status) assertEquals(status.name, eu.friedcutlet.yokan.data.DefaultYokanRepository(db).manga(title.id)?.status?.name) assertEquals(1, db.chapters(title.id).size) } } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) } } @Test fun opfsListingsAndSharedScannerReadMetadataAndCoversWithoutSynchronousDiskReads() = runTest { val id = ProfileId.random() val files = createPlatformLocalFileService(id) val root = "${files.downloadRoot}/local" try { files.writeBytesAsync("$root/Title/metadata.json", "{\"name\":\"Offline title\",\"author\":\"Author\"}".encodeToByteArray()) files.writeBytesAsync("$root/Title/cover.png", byteArrayOf(1, 2, 3)) files.writeBytesAsync("$root/Title/Chapter 1/001.jpg", byteArrayOf(4, 5)) assertEquals(listOf(LocalEntry("$root/Title", "Title", false)), files.listLocalEntries(root)) assertNull(files.listLocalEntries("$root/missing")) val db = InMemoryYokanDatabase(emptySnapshot()) val service = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id)) assertEquals(1, service.scan().added) val title = db.mangas().single() assertEquals("Offline title", title.name) assertEquals("Author", title.author) assertContentEquals(byteArrayOf(1, 2, 3), title.customCoverImage) assertTrue(db.chapters(title.id).single().archivePath.endsWith("/Title/Chapter 1")) assertEquals(0, service.scan().added) assertEquals(1, db.chapters(title.id).size) assertFails { files.listLocalEntries("/yokan/profiles/p_00000000000000000000000000000000/downloads/local") } } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) } } @Test fun emptyDirectoriesStayReadableAcrossDeletionAndReload() = runTest { val id = ProfileId.random() val files = createPlatformLocalFileService(id) val root = "${files.downloadRoot}/local" val path = "$root/one.cbz" files.writeBytesAsync(path, byteArrayOf(1)) assertEquals(listOf(LocalEntry(path, "one", true)), files.listLocalEntries(root)) files.deleteRecursivelyAsync(path) assertTrue(files.exists(root)) assertEquals(emptyList(), files.listLocalEntries(root)) files.close() val reopened = createPlatformLocalFileService(id) try { reopened.prepare() assertTrue(reopened.exists(root)) assertEquals(emptyList(), reopened.listLocalEntries(root)) } finally { reopened.close(); deletePlatformProfileStorage(id, emptyList()) } } }