LocalEntryManagementServiceTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalEntryManagementServiceTest.kt
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.database.DbActionType4import eu.friedcutlet.yokan.database.DbChangedPart5import eu.friedcutlet.yokan.database.DbChapter6import eu.friedcutlet.yokan.database.DbChapterPageUrls7import eu.friedcutlet.yokan.database.DbDownload8import eu.friedcutlet.yokan.database.DbHistory9import eu.friedcutlet.yokan.database.DbItemType10import eu.friedcutlet.yokan.database.DbManga11import eu.friedcutlet.yokan.database.DbTrack12import eu.friedcutlet.yokan.database.DbTrackStatus13import eu.friedcutlet.yokan.database.DbUpdate14import eu.friedcutlet.yokan.database.InMemoryYokanDatabase15import eu.friedcutlet.yokan.database.YokanDatabase16import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot17import eu.friedcutlet.yokan.database.seedDatabaseSnapshot18import kotlin.test.Test19import kotlin.test.assertEquals20import kotlin.test.assertTrue21import kotlinx.coroutines.test.runTest2223class LocalEntryManagementServiceTest {24 @Test25 fun forgetPreviewIsLogicalAndApplyCleansDependents() = runTest {26 val title = DbManga(id = 10, name = "Old", link = "USB/Old", source = "local", isLocalArchive = true)27 val chapter = DbChapter(id = 11, mangaId = title.id, archivePath = "USB/Old/chapter.cbz")28 val identity = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!)29 val chapterIdentity = localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, chapter.archivePath)30 val evidence = LocalLibraryReconciliationResult(31 staleTitleCandidates = listOf(LocalLibraryStaleCandidate(title.id, identity)),32 staleChapterCandidates = listOf(LocalLibraryStaleCandidate(chapter.id, chapterIdentity)),33 )34 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(35 mangas = listOf(title),36 chapters = listOf(chapter),37 downloads = listOf(DbDownload(id = 1, chapterId = chapter.id, isDownload = true)),38 ))39 val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))40 val preview = service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id)))4142 assertEquals(0, preview.sourceFilesAffected)43 assertEquals(1, preview.titleRowsRemoved)44 assertEquals(1, preview.chapterRowsRemoved)45 assertEquals(1, database.mangas().size)4647 val applied = service.apply(preview.command)48 assertEquals(LocalEntryManagementApplyStatus.Applied, applied.status)49 assertTrue(database.mangas().isEmpty())50 assertTrue(database.chapters().isEmpty())51 assertTrue(database.downloads().isEmpty())52 }5354 @Test55 fun activeDownloadAndChangedStateRejectApply() = runTest {56 val title = DbManga(id = 20, link = "USB/Old", source = "local", isLocalArchive = true)57 val identity = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!)58 val evidence = LocalLibraryReconciliationResult(59 staleTitleCandidates = listOf(LocalLibraryStaleCandidate(title.id, identity)),60 )61 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(title)))62 val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))63 val preview = service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id)))64 database.upsertManga(title.copy(name = "changed"))65 val changed = service.apply(preview.command)66 assertEquals(LocalEntryManagementBlockers.StateChanged, changed.blocker)6768 val activeDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(69 mangas = listOf(title),70 chapters = listOf(DbChapter(id = 21, mangaId = title.id, archivePath = "USB/Old/chapter.cbz")),71 downloads = listOf(DbDownload(id = 2, chapterId = 21, isStartDownload = true)),72 ))73 val activeEvidence = evidence.copy(staleChapterCandidates = listOf(74 LocalLibraryStaleCandidate(21, localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Old/chapter.cbz")),75 ))76 val activeService = DefaultLocalEntryManagementService(activeDatabase, EvidenceLibrary(activeEvidence))77 val activePreview = activeService.preview(LocalEntryManagementOperation.ForgetStale(activeEvidence, titleIds = listOf(title.id)))78 assertEquals(LocalEntryManagementBlockers.ActiveDownload, activeService.apply(activePreview.command).blocker)79 }8081 @Test82 fun atomicReplacementConflictForwardsAsStateChanged() = runTest {83 val title = DbManga(id = 22, link = "USB/Old", source = "local", isLocalArchive = true)84 val evidence = LocalLibraryReconciliationResult(85 staleTitleCandidates = listOf(86 LocalLibraryStaleCandidate(87 title.id,88 localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!),89 ),90 ),91 )92 val backing = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(title)))93 val database = InjectingDatabase(backing) {94 backing.upsertManga(title.copy(name = "Concurrent edit"))95 }96 val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))97 val preview = service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id)))9899 val result = service.apply(preview.command)100101 assertEquals(LocalEntryManagementApplyStatus.Rejected, result.status)102 assertEquals(LocalEntryManagementBlockers.StateChanged, result.blocker)103 assertEquals("Concurrent edit", backing.mangas().single().name)104 }105106 @Test107 fun mergeKeepsCanonicalAndMigratesChapterAndTrackerReferences() = runTest {108 val first = DbManga(id = 30, name = "Canonical", link = "USB/Same", source = "local", isLocalArchive = true, lastRead = 2, dateAdded = 200)109 val second = DbManga(id = 31, name = "Duplicate", link = "USB/Same", source = "local", isLocalArchive = true, favorite = true, lastRead = 8, dateAdded = 100, smartUpdateDays = 4, customCoverImage = byteArrayOf(1, 2), description = "fallback description")110 val groupIdentity = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same")111 val evidence = LocalLibraryReconciliationResult(112 duplicateTitleGroups = listOf(LocalLibraryDuplicateGroup(groupIdentity, listOf(first.id, second.id))),113 )114 val canonicalChapter = DbChapter(id = 32, mangaId = first.id, archivePath = "USB/Same/chapter.cbz", lastPageRead = "2")115 val duplicateChapter = DbChapter(id = 34, mangaId = second.id, archivePath = "USB/Same/chapter.cbz", isRead = true, isBookmarked = true, lastPageRead = "7")116 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(117 mangas = listOf(first, second),118 chapters = listOf(canonicalChapter, duplicateChapter),119 histories = listOf(120 DbHistory(id = 36, mangaId = first.id, chapterId = canonicalChapter.id, itemType = DbItemType.Manga, date = "100", readingTimeSeconds = 10),121 DbHistory(id = 37, mangaId = second.id, chapterId = duplicateChapter.id, itemType = DbItemType.Manga, date = "200", readingTimeSeconds = 25),122 ),123 tracks = listOf(124 DbTrack(id = 33, mangaId = first.id, syncId = 1, mediaId = 99, lastChapterRead = 2, status = DbTrackStatus.Reading),125 DbTrack(id = 35, mangaId = second.id, syncId = 1, mediaId = 99, lastChapterRead = 8, status = DbTrackStatus.Completed),126 ),127 pageCache = listOf(128 DbChapterPageUrls(chapterId = canonicalChapter.id, urls = listOf("page-1")),129 DbChapterPageUrls(chapterId = duplicateChapter.id, urls = listOf("page-2")),130 ),131 changedParts = listOf(132 DbChangedPart(id = 40, actionType = DbActionType.RemoveItem, isarId = first.id, data = "canonical", clientDate = 1),133 DbChangedPart(id = 41, actionType = DbActionType.RemoveItem, isarId = second.id, data = "duplicate", clientDate = 1),134 DbChangedPart(id = 42, actionType = DbActionType.RemoveChapter, isarId = duplicateChapter.id, data = "duplicate chapter", clientDate = 1),135 ),136 ))137 val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))138 val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id)))139 val applied = service.apply(preview.command)140141 assertEquals(LocalEntryManagementApplyStatus.Applied, applied.status)142 assertEquals(listOf(first.id), database.mangas().map { it.id })143 val mergedTitle = database.mangas().single()144 assertTrue(mergedTitle.favorite)145 assertEquals(8, mergedTitle.lastRead)146 assertEquals(100, mergedTitle.dateAdded)147 assertEquals(4, mergedTitle.smartUpdateDays)148 assertTrue(mergedTitle.customCoverImage!!.contentEquals(byteArrayOf(1, 2)))149 assertEquals("fallback description", mergedTitle.description)150 assertEquals(first.id, applied.preview.sourceTitleEffect?.canonicalTitleId)151 assertTrue(applied.preview.sourceTitleEffect?.favoriteAfter == true)152 assertTrue(applied.preview.sourceTitleEffect.metadataFallbackFields.contains("description"))153 assertEquals(listOf(canonicalChapter.id), database.chapters().map { it.id })154 assertEquals(first.id, database.chapters().single().mangaId)155 assertTrue(database.chapters().single().isRead)156 assertTrue(database.chapters().single().isBookmarked)157 assertEquals("7", database.chapters().single().lastPageRead)158 assertEquals(8, database.tracks().single().lastChapterRead)159 assertEquals(DbTrackStatus.Completed, database.tracks().single().status)160 assertEquals(1, database.histories().size)161 assertEquals(35, database.histories().single().readingTimeSeconds)162 assertEquals(canonicalChapter.id, database.histories().single().chapterId)163 assertEquals(listOf("page-1", "page-2"), database.pageCache().single().urls)164 assertTrue(database.changedParts().none { it.actionType == DbActionType.RemoveItem && it.isarId == first.id })165 assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveItem && it.isarId == second.id })166 assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveChapter && it.isarId == duplicateChapter.id })167 assertTrue(database.changedParts().none { it.actionType == DbActionType.RemoveChapter && it.isarId == canonicalChapter.id })168 assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveHistory && it.isarId == 37L })169 assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveTrack && it.isarId == 35L })170 // Removed: title 31, chapter 34, history 37, track 35, tombstone 40, page cache 34.171 // Added: RemoveHistory/RemoveTrack tombstones. Updated: canonical title, chapter, history,172 // track, page cache and settings rows, plus the two added rows.173 assertEquals(6, applied.preview.databaseRowsRemoved)174 assertEquals(2, applied.preview.databaseRowsAdded)175 assertEquals(8, applied.preview.databaseRowsUpdated)176 assertEquals(1, applied.preview.settingsRecordsAffected)177 assertEquals(0, applied.preview.sourceFilesAffected)178 }179180 @Test181 fun mergeRejectsActiveAffectedChapterDownload() = runTest {182 val first = DbManga(id = 40, link = "USB/Same", source = "local", isLocalArchive = true)183 val second = first.copy(id = 41)184 val chapter = DbChapter(id = 42, mangaId = second.id, archivePath = "USB/Same/chapter.cbz")185 val evidence = LocalLibraryReconciliationResult(186 duplicateTitleGroups = listOf(LocalLibraryDuplicateGroup(187 localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same"),188 listOf(first.id, second.id),189 )),190 )191 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(192 mangas = listOf(first, second),193 chapters = listOf(chapter),194 downloads = listOf(DbDownload(id = 43, chapterId = chapter.id, isStartDownload = true)),195 ))196 val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))197 val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id)))198 assertEquals(LocalEntryManagementBlockers.ActiveDownload, service.apply(preview.command).blocker)199 }200201 @Test202 fun forgetRecordsHistoryUpdateAndTrackTombstones() = runTest {203 val title = DbManga(id = 44, link = "USB/Removed", source = "local", isLocalArchive = true)204 val chapter = DbChapter(id = 45, mangaId = title.id, archivePath = "USB/Removed/chapter.cbz")205 val evidence = LocalLibraryReconciliationResult(staleTitleCandidates = listOf(206 LocalLibraryStaleCandidate(207 title.id,208 localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!),209 ),210 ))211 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(212 mangas = listOf(title),213 chapters = listOf(chapter),214 histories = listOf(DbHistory(id = 46, mangaId = title.id, chapterId = chapter.id, itemType = DbItemType.Manga)),215 updates = listOf(DbUpdate(id = 47, mangaId = title.id, chapterId = chapter.id)),216 tracks = listOf(DbTrack(id = 48, mangaId = title.id, status = DbTrackStatus.Reading)),217 ))218 val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))219220 service.apply(service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id))).command)221222 assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveHistory && it.isarId == 46L })223 assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveUpdate && it.isarId == 47L })224 assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveTrack && it.isarId == 48L })225 }226227 @Test228 fun mergeBlocksAmbiguousCompletedDownloadWithoutChangingDownloadIdentity() = runTest {229 val first = DbManga(id = 70, link = "USB/Same", source = "local", isLocalArchive = true)230 val second = first.copy(id = 71)231 val firstChapter = DbChapter(id = 72, mangaId = first.id, archivePath = "USB/Same/chapter.cbz")232 val secondChapter = firstChapter.copy(id = 73, mangaId = second.id)233 val evidence = LocalLibraryReconciliationResult(duplicateTitleGroups = listOf(234 LocalLibraryDuplicateGroup(235 localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same"),236 listOf(first.id, second.id),237 ),238 ))239 val completed = DbDownload(id = 74, chapterId = firstChapter.id, isDownload = true)240 val duplicate = DbDownload(id = 75, chapterId = secondChapter.id, isDownload = true)241 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(242 mangas = listOf(first, second),243 chapters = listOf(firstChapter, secondChapter),244 downloads = listOf(completed, duplicate),245 ))246 val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))247 val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id)))248249 assertEquals(LocalEntryManagementBlockers.CompletedDownloadConflict, preview.blockers.single())250 assertEquals(LocalEntryManagementBlockers.CompletedDownloadConflict, service.apply(preview.command).blocker)251 assertEquals(setOf(74L, 75L), database.downloads().map { it.id }.toSet())252 assertEquals(setOf(firstChapter.id, secondChapter.id), database.downloads().mapNotNull { it.chapterId }.toSet())253 }254255 @Test256 fun mergeBlocksCompletedDownloadOnDuplicateChapterWithoutRemappingIdentity() = runTest {257 val first = DbManga(id = 76, link = "USB/Same", source = "local", isLocalArchive = true)258 val second = first.copy(id = 77)259 val canonicalChapter = DbChapter(id = 78, mangaId = first.id, archivePath = "USB/Same/chapter.cbz")260 val duplicateChapter = canonicalChapter.copy(id = 79, mangaId = second.id)261 val evidence = LocalLibraryReconciliationResult(duplicateTitleGroups = listOf(262 LocalLibraryDuplicateGroup(263 localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same"),264 listOf(first.id, second.id),265 ),266 ))267 val completed = DbDownload(id = 80, chapterId = duplicateChapter.id, isDownload = true)268 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(269 mangas = listOf(first, second),270 chapters = listOf(canonicalChapter, duplicateChapter),271 downloads = listOf(completed),272 ))273 val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))274 val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id)))275276 assertEquals(LocalEntryManagementBlockers.DownloadIdentityConflict, preview.blockers.single())277 assertEquals(LocalEntryManagementBlockers.DownloadIdentityConflict, service.apply(preview.command).blocker)278 assertEquals(listOf(completed), database.downloads())279 }280281 @Test282 fun tombstonesUseTableAwareIdsAndDoNotRedirectRemoveEntries() = runTest {283 val title = DbManga(id = 50, link = "USB/Old", source = "local", isLocalArchive = true)284 val chapter = DbChapter(id = 50, mangaId = title.id, archivePath = "USB/Old/chapter.cbz")285 val evidence = LocalLibraryReconciliationResult(staleTitleCandidates = listOf(286 LocalLibraryStaleCandidate(title.id, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!)),287 ))288 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(289 mangas = listOf(title),290 chapters = listOf(chapter),291 changedParts = listOf(292 DbChangedPart(id = 1, actionType = DbActionType.RemoveExtension, isarId = title.id, data = "source", clientDate = 1),293 DbChangedPart(id = 2, actionType = DbActionType.RemoveItem, isarId = title.id, data = "old", clientDate = 1),294 ),295 ))296 val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))297 val result = service.apply(service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id))).command)298 assertEquals(LocalEntryManagementApplyStatus.Applied, result.status)299 assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveExtension && it.isarId == title.id })300 assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveItem && it.isarId == title.id })301 assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveChapter && it.isarId == chapter.id })302 assertEquals(database.changedParts().map { it.id }.size, database.changedParts().map { it.id }.toSet().size)303 }304305 @Test306 fun applyRequiresFreshReconciliationEvidence() = runTest {307 val title = DbManga(id = 60, link = "USB/Old", source = "local", isLocalArchive = true)308 val oldEvidence = LocalLibraryReconciliationResult(staleTitleCandidates = listOf(309 LocalLibraryStaleCandidate(title.id, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!)),310 ))311 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(title)))312 val freshLibrary = EvidenceLibrary(LocalLibraryReconciliationResult())313 val service = DefaultLocalEntryManagementService(database, freshLibrary)314 val command = service.preview(LocalEntryManagementOperation.ForgetStale(oldEvidence, titleIds = listOf(title.id))).command315 assertEquals(LocalEntryManagementBlockers.FreshReconciliationChanged, service.apply(command).blocker)316 assertEquals(1, freshLibrary.reconcileCalls)317 }318319 private class EvidenceLibrary(320 private val result: LocalLibraryReconciliationResult,321 ) : LocalLibraryService {322 var reconcileCalls = 0323 override suspend fun scan() = LocalLibraryScanResult(0, 0, 0)324 override suspend fun reconcile(): LocalLibraryReconciliationResult {325 reconcileCalls++326 return result327 }328 override suspend fun importTorrent(pathOrMagnet: String, displayName: String?) = null329 }330331 private class InjectingDatabase(332 private val delegate: InMemoryYokanDatabase,333 private val beforeReplacement: () -> Unit,334 ) : YokanDatabase by delegate {335 override suspend fun replaceAllAtomically(336 snapshot: YokanDatabaseSnapshot,337 expectedSnapshot: YokanDatabaseSnapshot?,338 removedSourceIds: Set<Long>,339 ) {340 beforeReplacement()341 delegate.replaceAllAtomically(snapshot, expectedSnapshot, removedSourceIds)342 }343 }344}345