package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbLocalFolder import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.seedDatabaseSnapshot import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.services.files.LocalArchiveService import eu.friedcutlet.yokan.services.files.LocalEntry import eu.friedcutlet.yokan.services.files.LocalEpubChapter import eu.friedcutlet.yokan.services.files.LocalFileEntry import eu.friedcutlet.yokan.services.files.LocalFileService import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.test.runTest import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json class LocalLibraryReconciliationTest { @Test fun unreadableFolderIsUnavailableInsteadOfHealthyEmpty() = runTest { val files = FixtureFiles(roots = setOf("/downloads/local"), entries = emptyMap()) val service = DefaultLocalLibraryService(InMemoryYokanDatabase(), files, EmptyArchives) val result = service.scan() assertEquals(emptyList(), result.healthyFolders) assertEquals(listOf(DbLocalFolder("local", "/downloads/local")), result.unavailableFolders) } @Test fun scansShareOneOperationLock() = runTest { val files = FixtureFiles(roots = emptySet(), entries = emptyMap()) val service = DefaultLocalLibraryService(InMemoryYokanDatabase(), files, EmptyArchives) var active = 0 var maximum = 0 val first = async { service.withOperationLock { active++ maximum = maxOf(maximum, active) delay(10) active-- } } val second = async { service.withOperationLock { active++ maximum = maxOf(maximum, active) delay(10) active-- } } first.await() second.await() assertEquals(1, maximum) } @Test fun reconciliationIsConservativeAndNeverDeletes() { val healthy = DbLocalFolder("USB", "/mounted") val unavailable = DbLocalFolder("Offline", "/offline") val oldTitle = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Old") val oldChapter = localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Old/book.epub#0") val currentTitle = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Current") val duplicateTitle = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Duplicate") val duplicateChapter = localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Duplicate/book.epub#0") val renamedFolder = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "Renamed/Old") val scan = LocalLibraryScanResult( added = 1, updated = 1, total = 1, addedTitleIds = listOf(20), observedTitleIds = listOf(20), addedChapterIds = listOf(21), observedChapterIds = listOf(21), healthyFolders = listOf(healthy), unavailableFolders = listOf(unavailable), observedTitleIdentities = listOf(currentTitle), observedChapterIdentities = listOf( localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Current/book.epub#0"), ), ) val operation = LocalLibraryReconciliationOperation( scan = scan, existingTitles = listOf( LocalLibraryReconciliationEntry(1, oldTitle), LocalLibraryReconciliationEntry(2, duplicateTitle), LocalLibraryReconciliationEntry(3, duplicateTitle), LocalLibraryReconciliationEntry(4, renamedFolder), LocalLibraryReconciliationEntry(5, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "Offline/Kept")), ), existingChapters = listOf( LocalLibraryReconciliationEntry(10, oldChapter), LocalLibraryReconciliationEntry(11, duplicateChapter), LocalLibraryReconciliationEntry(12, duplicateChapter), ), ) val result = reconcileLocalLibrary(operation) assertEquals(listOf(20L), result.addedTitleIds) assertEquals(listOf(20L), result.observedTitleIds) assertEquals("Old/book.epub#0", oldChapter.relativePath) assertEquals(listOf(1L), result.staleTitleCandidates.map { it.id }) assertEquals(listOf(10L), result.staleChapterCandidates.map { it.id }) assertEquals(listOf(2L, 3L), result.duplicateTitleGroups.single().ids) assertEquals(listOf(11L, 12L), result.duplicateChapterGroups.single().ids) assertEquals(listOf(unavailable), result.unavailableFolders) assertTrue(result.staleTitleCandidates.none { it.id == 4L || it.id == 5L }) // The operation/result are transportable and contain no delete command. val roundTrip = Json.decodeFromString(Json.encodeToString(operation)) assertEquals(result, reconcileLocalLibrary(roundTrip)) } @Test fun remountKeepsVirtualIdentityAndSecondScanIsIdempotent() = runTest { val files = FixtureFiles( roots = setOf("/downloads/local", "/old"), entries = mapOf( "/old" to listOf(LocalEntry("/old/Title", "Title", false)), "/old/Title" to listOf(LocalEntry("/old/Title/book.epub", "book", true)), ), ) val database = InMemoryYokanDatabase( seedDatabaseSnapshot().copy( settings = seedDatabaseSnapshot().settings.copy( namedLocalFolders = listOf(DbLocalFolder("USB", "/old")), ), ), ) val service = DefaultLocalLibraryService(database, files, EmptyArchives) val first = service.scan() files.roots = setOf("/downloads/local", "/new") files.entries = mapOf( "/new" to listOf(LocalEntry("/new/Title", "Title", false)), "/new/Title" to listOf(LocalEntry("/new/Title/book.epub", "book", true)), ) database.updateSettings(database.settings().copy(namedLocalFolders = listOf(DbLocalFolder("USB", "/new")))) val second = service.scan() assertEquals(first.observedTitleIds, second.observedTitleIds) assertEquals(1, first.observedChapterIds.size) assertEquals(first.observedChapterIds, second.observedChapterIds) assertEquals("Title/book.epub#0", first.observedChapterIdentities.single().relativePath) assertEquals(first.observedChapterIdentities, second.observedChapterIdentities) assertEquals(emptyList(), second.addedTitleIds) assertEquals("USB/Title", database.mangas().single { it.isLocalArchive }.link) assertTrue(files.deleteCalls == 0) } @Test fun oneScanRefreshesExistingLocalRowsWithoutReplacingTheirIds() = runTest { val folder = DbLocalFolder("USB", "/mounted") val title = eu.friedcutlet.yokan.database.DbManga( id = 90, name = "Old title", link = "USB/Title", source = "local", isLocalArchive = true, favorite = true, lastRead = 4, ) val chapter = eu.friedcutlet.yokan.database.DbChapter( id = 91, mangaId = title.id, name = "Old chapter", url = "USB/Title/book.cbz", archivePath = "USB/Title/book.cbz", ) val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy( settings = seedDatabaseSnapshot().settings.copy(namedLocalFolders = listOf(folder)), mangas = listOf(title), chapters = listOf(chapter), )) val files = FixtureFiles( roots = setOf("/downloads/local", "/mounted"), entries = mapOf( "/mounted" to listOf(LocalEntry("/mounted/Title", "Fresh title", false)), "/mounted/Title" to listOf(LocalEntry("/mounted/Title/book.cbz", "Fresh chapter", true)), ), ) val result = DefaultLocalLibraryService(database, files, EmptyArchives).scan() assertEquals(0, result.added) assertEquals(1, result.updated) assertEquals(listOf(title.id), result.observedTitleIds) assertEquals(listOf(chapter.id), result.observedChapterIds) assertEquals(title.id, database.mangas().single().id) assertEquals("Fresh title", database.mangas().single().name) assertTrue(database.mangas().single().favorite) assertEquals(4, database.mangas().single().lastRead) assertEquals(chapter.id, database.chapters().single().id) assertEquals("Fresh chapter", database.chapters().single().name) } @Test fun colorizerStagingIsIgnoredUntilPublishedAndPublishedCbzIsIdempotent() = runTest { val stagingPath = "/downloads/local/.colorizer-abc123.partial" val files = FixtureFiles( roots = setOf("/downloads/local"), entries = mapOf( "/downloads/local" to listOf( LocalEntry("$stagingPath/cover.jpg", "cover", true), LocalEntry("$stagingPath/chapter.cbz", "chapter", true), ), ), ) val database = InMemoryYokanDatabase() val service = DefaultLocalLibraryService(database, files, EmptyArchives) val stagingScan = service.scan() assertEquals(0, stagingScan.total) assertTrue(database.mangas().isEmpty()) assertTrue(database.chapters().isEmpty()) files.entries = mapOf( "/downloads/local" to listOf(LocalEntry("/downloads/local/Final", "Final", false)), "/downloads/local/Final" to listOf( LocalEntry("/downloads/local/Final/cover.jpg", "cover", true), LocalEntry("/downloads/local/Final/chapter.cbz", "chapter", true), ), ) val publishedScan = service.scan() val repeatedScan = service.scan() assertEquals(1, publishedScan.added) assertEquals(1, publishedScan.total) assertEquals(1, database.mangas().size) assertEquals(1, database.chapters().size) assertEquals("chapter.cbz", database.chapters().single().url.substringAfterLast('/')) assertEquals(emptyList(), repeatedScan.addedTitleIds) assertEquals(publishedScan.observedTitleIds, repeatedScan.observedTitleIds) assertEquals(publishedScan.observedChapterIds, repeatedScan.observedChapterIds) } @Test fun unchangedScanReusesReadsAndFreshScanBypassesFingerprints() = runTest { val root = "/downloads/local" val title = "$root/Title" val metadata = "$title/metadata.json" val cover = "$title/cover.jpg" val files = FixtureFiles(setOf(root), mapOf(root to listOf(LocalEntry(title, "Title", false)), title to listOf(LocalEntry("$title/01.cbz", "01", true)))) files.contents[metadata] = """{"name":"Original"}""".encodeToByteArray() files.contents[cover] = byteArrayOf(1, 2, 3) val database = InMemoryYokanDatabase() val service = DefaultLocalLibraryService(database, files, EmptyArchives) service.scan() val before = database.snapshot() val reads = files.readCalls files.listCalls.clear() service.scan() assertEquals(reads, files.readCalls) assertEquals(1, files.listCalls[title]) kotlin.test.assertSame(before.mangas, database.snapshot().mangas) kotlin.test.assertSame(before.chapters, database.snapshot().chapters) files.contents[metadata] = """{"name":"Modified"}""".encodeToByteArray() files.modified++ service.scan() assertEquals("Modified", database.mangas().single().name) val afterRead = files.readCalls service.scanFresh() assertTrue(files.readCalls > afterRead) } private class FixtureFiles( var roots: Set, var entries: Map>, ) : LocalFileService { var deleteCalls = 0 var readCalls = 0 var modified = 1L val contents = mutableMapOf() val listCalls = mutableMapOf() override val downloadRoot = "/downloads" override val backupRoot = "/backups" override val cacheRoot = "/cache" override fun writeBytes(path: String, bytes: ByteArray) = Unit override fun readBytes(path: String): ByteArray { readCalls++; return contents[path] ?: ByteArray(0) } override fun canonicalPath(path: String): String? = path override fun exists(path: String): Boolean = path in roots || entries.keys.any { path.startsWith("$it/") } override fun deleteRecursively(path: String): Boolean { deleteCalls++ return true } override fun directorySize(path: String): Long = 0 override fun openLocation(path: String): Boolean = false override fun listLocalEntries(root: String): List? { listCalls[root] = (listCalls[root] ?: 0) + 1; return entries[root] } override fun listFiles(root: String): List = contents.filterKeys { it.substringBeforeLast('/') == root } .map { (path, bytes) -> LocalFileEntry(path, path.substringAfterLast('/'), bytes.size.toLong(), modified) } } private object EmptyArchives : LocalArchiveService { override fun listPages(archivePath: String) = emptyList() override fun listEpubChapters(archivePath: String) = listOf(LocalEpubChapter("Chapter", "chapter.xhtml")) override fun readEpubChapter(archivePath: String, index: Int) = "" override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean) = null } }