LocalLibraryReconciliationTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryReconciliationTest.kt
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.DbLocalFolder5import eu.friedcutlet.yokan.database.InMemoryYokanDatabase6import eu.friedcutlet.yokan.database.seedDatabaseSnapshot7import eu.friedcutlet.yokan.domain.Chapter8import eu.friedcutlet.yokan.services.files.LocalArchiveService9import eu.friedcutlet.yokan.services.files.LocalEntry10import eu.friedcutlet.yokan.services.files.LocalEpubChapter11import eu.friedcutlet.yokan.services.files.LocalFileEntry12import eu.friedcutlet.yokan.services.files.LocalFileService13import kotlin.test.Test14import kotlin.test.assertEquals15import kotlin.test.assertTrue16import kotlinx.coroutines.async17import kotlinx.coroutines.delay18import kotlinx.coroutines.test.runTest19import kotlinx.serialization.encodeToString20import kotlinx.serialization.json.Json2122class LocalLibraryReconciliationTest {23 @Test24 fun unreadableFolderIsUnavailableInsteadOfHealthyEmpty() = runTest {25 val files = FixtureFiles(roots = setOf("/downloads/local"), entries = emptyMap())26 val service = DefaultLocalLibraryService(InMemoryYokanDatabase(), files, EmptyArchives)2728 val result = service.scan()2930 assertEquals(emptyList(), result.healthyFolders)31 assertEquals(listOf(DbLocalFolder("local", "/downloads/local")), result.unavailableFolders)32 }3334 @Test35 fun scansShareOneOperationLock() = runTest {36 val files = FixtureFiles(roots = emptySet(), entries = emptyMap())37 val service = DefaultLocalLibraryService(InMemoryYokanDatabase(), files, EmptyArchives)38 var active = 039 var maximum = 040 val first = async {41 service.withOperationLock {42 active++43 maximum = maxOf(maximum, active)44 delay(10)45 active--46 }47 }48 val second = async {49 service.withOperationLock {50 active++51 maximum = maxOf(maximum, active)52 delay(10)53 active--54 }55 }56 first.await()57 second.await()58 assertEquals(1, maximum)59 }6061 @Test62 fun reconciliationIsConservativeAndNeverDeletes() {63 val healthy = DbLocalFolder("USB", "/mounted")64 val unavailable = DbLocalFolder("Offline", "/offline")65 val oldTitle = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Old")66 val oldChapter = localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Old/book.epub#0")67 val currentTitle = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Current")68 val duplicateTitle = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Duplicate")69 val duplicateChapter = localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Duplicate/book.epub#0")70 val renamedFolder = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "Renamed/Old")71 val scan = LocalLibraryScanResult(72 added = 1,73 updated = 1,74 total = 1,75 addedTitleIds = listOf(20),76 observedTitleIds = listOf(20),77 addedChapterIds = listOf(21),78 observedChapterIds = listOf(21),79 healthyFolders = listOf(healthy),80 unavailableFolders = listOf(unavailable),81 observedTitleIdentities = listOf(currentTitle),82 observedChapterIdentities = listOf(83 localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Current/book.epub#0"),84 ),85 )86 val operation = LocalLibraryReconciliationOperation(87 scan = scan,88 existingTitles = listOf(89 LocalLibraryReconciliationEntry(1, oldTitle),90 LocalLibraryReconciliationEntry(2, duplicateTitle),91 LocalLibraryReconciliationEntry(3, duplicateTitle),92 LocalLibraryReconciliationEntry(4, renamedFolder),93 LocalLibraryReconciliationEntry(5, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "Offline/Kept")),94 ),95 existingChapters = listOf(96 LocalLibraryReconciliationEntry(10, oldChapter),97 LocalLibraryReconciliationEntry(11, duplicateChapter),98 LocalLibraryReconciliationEntry(12, duplicateChapter),99 ),100 )101102 val result = reconcileLocalLibrary(operation)103104 assertEquals(listOf(20L), result.addedTitleIds)105 assertEquals(listOf(20L), result.observedTitleIds)106 assertEquals("Old/book.epub#0", oldChapter.relativePath)107 assertEquals(listOf(1L), result.staleTitleCandidates.map { it.id })108 assertEquals(listOf(10L), result.staleChapterCandidates.map { it.id })109 assertEquals(listOf(2L, 3L), result.duplicateTitleGroups.single().ids)110 assertEquals(listOf(11L, 12L), result.duplicateChapterGroups.single().ids)111 assertEquals(listOf(unavailable), result.unavailableFolders)112 assertTrue(result.staleTitleCandidates.none { it.id == 4L || it.id == 5L })113114 // The operation/result are transportable and contain no delete command.115 val roundTrip = Json.decodeFromString<LocalLibraryReconciliationOperation>(Json.encodeToString(operation))116 assertEquals(result, reconcileLocalLibrary(roundTrip))117 }118119 @Test120 fun remountKeepsVirtualIdentityAndSecondScanIsIdempotent() = runTest {121 val files = FixtureFiles(122 roots = setOf("/downloads/local", "/old"),123 entries = mapOf(124 "/old" to listOf(LocalEntry("/old/Title", "Title", false)),125 "/old/Title" to listOf(LocalEntry("/old/Title/book.epub", "book", true)),126 ),127 )128 val database = InMemoryYokanDatabase(129 seedDatabaseSnapshot().copy(130 settings = seedDatabaseSnapshot().settings.copy(131 namedLocalFolders = listOf(DbLocalFolder("USB", "/old")),132 ),133 ),134 )135 val service = DefaultLocalLibraryService(database, files, EmptyArchives)136137 val first = service.scan()138 files.roots = setOf("/downloads/local", "/new")139 files.entries = mapOf(140 "/new" to listOf(LocalEntry("/new/Title", "Title", false)),141 "/new/Title" to listOf(LocalEntry("/new/Title/book.epub", "book", true)),142 )143 database.updateSettings(database.settings().copy(namedLocalFolders = listOf(DbLocalFolder("USB", "/new"))))144 val second = service.scan()145146 assertEquals(first.observedTitleIds, second.observedTitleIds)147 assertEquals(1, first.observedChapterIds.size)148 assertEquals(first.observedChapterIds, second.observedChapterIds)149 assertEquals("Title/book.epub#0", first.observedChapterIdentities.single().relativePath)150 assertEquals(first.observedChapterIdentities, second.observedChapterIdentities)151 assertEquals(emptyList(), second.addedTitleIds)152 assertEquals("USB/Title", database.mangas().single { it.isLocalArchive }.link)153 assertTrue(files.deleteCalls == 0)154 }155156 @Test157 fun oneScanRefreshesExistingLocalRowsWithoutReplacingTheirIds() = runTest {158 val folder = DbLocalFolder("USB", "/mounted")159 val title = eu.friedcutlet.yokan.database.DbManga(160 id = 90,161 name = "Old title",162 link = "USB/Title",163 source = "local",164 isLocalArchive = true,165 favorite = true,166 lastRead = 4,167 )168 val chapter = eu.friedcutlet.yokan.database.DbChapter(169 id = 91,170 mangaId = title.id,171 name = "Old chapter",172 url = "USB/Title/book.cbz",173 archivePath = "USB/Title/book.cbz",174 )175 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(176 settings = seedDatabaseSnapshot().settings.copy(namedLocalFolders = listOf(folder)),177 mangas = listOf(title),178 chapters = listOf(chapter),179 ))180 val files = FixtureFiles(181 roots = setOf("/downloads/local", "/mounted"),182 entries = mapOf(183 "/mounted" to listOf(LocalEntry("/mounted/Title", "Fresh title", false)),184 "/mounted/Title" to listOf(LocalEntry("/mounted/Title/book.cbz", "Fresh chapter", true)),185 ),186 )187188 val result = DefaultLocalLibraryService(database, files, EmptyArchives).scan()189190 assertEquals(0, result.added)191 assertEquals(1, result.updated)192 assertEquals(listOf(title.id), result.observedTitleIds)193 assertEquals(listOf(chapter.id), result.observedChapterIds)194 assertEquals(title.id, database.mangas().single().id)195 assertEquals("Fresh title", database.mangas().single().name)196 assertTrue(database.mangas().single().favorite)197 assertEquals(4, database.mangas().single().lastRead)198 assertEquals(chapter.id, database.chapters().single().id)199 assertEquals("Fresh chapter", database.chapters().single().name)200 }201202 @Test203 fun colorizerStagingIsIgnoredUntilPublishedAndPublishedCbzIsIdempotent() = runTest {204 val stagingPath = "/downloads/local/.colorizer-abc123.partial"205 val files = FixtureFiles(206 roots = setOf("/downloads/local"),207 entries = mapOf(208 "/downloads/local" to listOf(209 LocalEntry("$stagingPath/cover.jpg", "cover", true),210 LocalEntry("$stagingPath/chapter.cbz", "chapter", true),211 ),212 ),213 )214 val database = InMemoryYokanDatabase()215 val service = DefaultLocalLibraryService(database, files, EmptyArchives)216217 val stagingScan = service.scan()218219 assertEquals(0, stagingScan.total)220 assertTrue(database.mangas().isEmpty())221 assertTrue(database.chapters().isEmpty())222223 files.entries = mapOf(224 "/downloads/local" to listOf(LocalEntry("/downloads/local/Final", "Final", false)),225 "/downloads/local/Final" to listOf(226 LocalEntry("/downloads/local/Final/cover.jpg", "cover", true),227 LocalEntry("/downloads/local/Final/chapter.cbz", "chapter", true),228 ),229 )230 val publishedScan = service.scan()231 val repeatedScan = service.scan()232233 assertEquals(1, publishedScan.added)234 assertEquals(1, publishedScan.total)235 assertEquals(1, database.mangas().size)236 assertEquals(1, database.chapters().size)237 assertEquals("chapter.cbz", database.chapters().single().url.substringAfterLast('/'))238 assertEquals(emptyList(), repeatedScan.addedTitleIds)239 assertEquals(publishedScan.observedTitleIds, repeatedScan.observedTitleIds)240 assertEquals(publishedScan.observedChapterIds, repeatedScan.observedChapterIds)241 }242243 @Test244 fun unchangedScanReusesReadsAndFreshScanBypassesFingerprints() = runTest {245 val root = "/downloads/local"246 val title = "$root/Title"247 val metadata = "$title/metadata.json"248 val cover = "$title/cover.jpg"249 val files = FixtureFiles(setOf(root), mapOf(root to listOf(LocalEntry(title, "Title", false)),250 title to listOf(LocalEntry("$title/01.cbz", "01", true))))251 files.contents[metadata] = """{"name":"Original"}""".encodeToByteArray()252 files.contents[cover] = byteArrayOf(1, 2, 3)253 val database = InMemoryYokanDatabase()254 val service = DefaultLocalLibraryService(database, files, EmptyArchives)255 service.scan()256 val before = database.snapshot()257 val reads = files.readCalls258 files.listCalls.clear()259 service.scan()260 assertEquals(reads, files.readCalls)261 assertEquals(1, files.listCalls[title])262 kotlin.test.assertSame(before.mangas, database.snapshot().mangas)263 kotlin.test.assertSame(before.chapters, database.snapshot().chapters)264265 files.contents[metadata] = """{"name":"Modified"}""".encodeToByteArray()266 files.modified++267 service.scan()268 assertEquals("Modified", database.mangas().single().name)269 val afterRead = files.readCalls270 service.scanFresh()271 assertTrue(files.readCalls > afterRead)272 }273274 private class FixtureFiles(275 var roots: Set<String>,276 var entries: Map<String, List<LocalEntry>>,277 ) : LocalFileService {278 var deleteCalls = 0279 var readCalls = 0280 var modified = 1L281 val contents = mutableMapOf<String, ByteArray>()282 val listCalls = mutableMapOf<String, Int>()283 override val downloadRoot = "/downloads"284 override val backupRoot = "/backups"285 override val cacheRoot = "/cache"286 override fun writeBytes(path: String, bytes: ByteArray) = Unit287 override fun readBytes(path: String): ByteArray { readCalls++; return contents[path] ?: ByteArray(0) }288 override fun canonicalPath(path: String): String? = path289 override fun exists(path: String): Boolean = path in roots || entries.keys.any { path.startsWith("$it/") }290 override fun deleteRecursively(path: String): Boolean {291 deleteCalls++292 return true293 }294 override fun directorySize(path: String): Long = 0295 override fun openLocation(path: String): Boolean = false296 override fun listLocalEntries(root: String): List<LocalEntry>? { listCalls[root] = (listCalls[root] ?: 0) + 1; return entries[root] }297 override fun listFiles(root: String): List<LocalFileEntry> = contents.filterKeys { it.substringBeforeLast('/') == root }298 .map { (path, bytes) -> LocalFileEntry(path, path.substringAfterLast('/'), bytes.size.toLong(), modified) }299 }300301 private object EmptyArchives : LocalArchiveService {302 override fun listPages(archivePath: String) = emptyList<eu.friedcutlet.yokan.database.DbPageUrl>()303 override fun listEpubChapters(archivePath: String) = listOf(LocalEpubChapter("Chapter", "chapter.xhtml"))304 override fun readEpubChapter(archivePath: String, index: Int) = ""305 override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null306 override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean) = null307 }308}309