package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.database.DbActionType import eu.friedcutlet.yokan.database.DbChangedPart import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbChapterPageUrls import eu.friedcutlet.yokan.database.DbDownload import eu.friedcutlet.yokan.database.DbHistory import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackStatus import eu.friedcutlet.yokan.database.DbUpdate import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot import eu.friedcutlet.yokan.database.seedDatabaseSnapshot import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlinx.coroutines.test.runTest class LocalEntryManagementServiceTest { @Test fun forgetPreviewIsLogicalAndApplyCleansDependents() = runTest { val title = DbManga(id = 10, name = "Old", link = "USB/Old", source = "local", isLocalArchive = true) val chapter = DbChapter(id = 11, mangaId = title.id, archivePath = "USB/Old/chapter.cbz") val identity = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!) val chapterIdentity = localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, chapter.archivePath) val evidence = LocalLibraryReconciliationResult( staleTitleCandidates = listOf(LocalLibraryStaleCandidate(title.id, identity)), staleChapterCandidates = listOf(LocalLibraryStaleCandidate(chapter.id, chapterIdentity)), ) val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy( mangas = listOf(title), chapters = listOf(chapter), downloads = listOf(DbDownload(id = 1, chapterId = chapter.id, isDownload = true)), )) val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence)) val preview = service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id))) assertEquals(0, preview.sourceFilesAffected) assertEquals(1, preview.titleRowsRemoved) assertEquals(1, preview.chapterRowsRemoved) assertEquals(1, database.mangas().size) val applied = service.apply(preview.command) assertEquals(LocalEntryManagementApplyStatus.Applied, applied.status) assertTrue(database.mangas().isEmpty()) assertTrue(database.chapters().isEmpty()) assertTrue(database.downloads().isEmpty()) } @Test fun activeDownloadAndChangedStateRejectApply() = runTest { val title = DbManga(id = 20, link = "USB/Old", source = "local", isLocalArchive = true) val identity = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!) val evidence = LocalLibraryReconciliationResult( staleTitleCandidates = listOf(LocalLibraryStaleCandidate(title.id, identity)), ) val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(title))) val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence)) val preview = service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id))) database.upsertManga(title.copy(name = "changed")) val changed = service.apply(preview.command) assertEquals(LocalEntryManagementBlockers.StateChanged, changed.blocker) val activeDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot().copy( mangas = listOf(title), chapters = listOf(DbChapter(id = 21, mangaId = title.id, archivePath = "USB/Old/chapter.cbz")), downloads = listOf(DbDownload(id = 2, chapterId = 21, isStartDownload = true)), )) val activeEvidence = evidence.copy(staleChapterCandidates = listOf( LocalLibraryStaleCandidate(21, localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Old/chapter.cbz")), )) val activeService = DefaultLocalEntryManagementService(activeDatabase, EvidenceLibrary(activeEvidence)) val activePreview = activeService.preview(LocalEntryManagementOperation.ForgetStale(activeEvidence, titleIds = listOf(title.id))) assertEquals(LocalEntryManagementBlockers.ActiveDownload, activeService.apply(activePreview.command).blocker) } @Test fun atomicReplacementConflictForwardsAsStateChanged() = runTest { val title = DbManga(id = 22, link = "USB/Old", source = "local", isLocalArchive = true) val evidence = LocalLibraryReconciliationResult( staleTitleCandidates = listOf( LocalLibraryStaleCandidate( title.id, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!), ), ), ) val backing = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(title))) val database = InjectingDatabase(backing) { backing.upsertManga(title.copy(name = "Concurrent edit")) } val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence)) val preview = service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id))) val result = service.apply(preview.command) assertEquals(LocalEntryManagementApplyStatus.Rejected, result.status) assertEquals(LocalEntryManagementBlockers.StateChanged, result.blocker) assertEquals("Concurrent edit", backing.mangas().single().name) } @Test fun mergeKeepsCanonicalAndMigratesChapterAndTrackerReferences() = runTest { val first = DbManga(id = 30, name = "Canonical", link = "USB/Same", source = "local", isLocalArchive = true, lastRead = 2, dateAdded = 200) 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") val groupIdentity = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same") val evidence = LocalLibraryReconciliationResult( duplicateTitleGroups = listOf(LocalLibraryDuplicateGroup(groupIdentity, listOf(first.id, second.id))), ) val canonicalChapter = DbChapter(id = 32, mangaId = first.id, archivePath = "USB/Same/chapter.cbz", lastPageRead = "2") val duplicateChapter = DbChapter(id = 34, mangaId = second.id, archivePath = "USB/Same/chapter.cbz", isRead = true, isBookmarked = true, lastPageRead = "7") val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy( mangas = listOf(first, second), chapters = listOf(canonicalChapter, duplicateChapter), histories = listOf( DbHistory(id = 36, mangaId = first.id, chapterId = canonicalChapter.id, itemType = DbItemType.Manga, date = "100", readingTimeSeconds = 10), DbHistory(id = 37, mangaId = second.id, chapterId = duplicateChapter.id, itemType = DbItemType.Manga, date = "200", readingTimeSeconds = 25), ), tracks = listOf( DbTrack(id = 33, mangaId = first.id, syncId = 1, mediaId = 99, lastChapterRead = 2, status = DbTrackStatus.Reading), DbTrack(id = 35, mangaId = second.id, syncId = 1, mediaId = 99, lastChapterRead = 8, status = DbTrackStatus.Completed), ), pageCache = listOf( DbChapterPageUrls(chapterId = canonicalChapter.id, urls = listOf("page-1")), DbChapterPageUrls(chapterId = duplicateChapter.id, urls = listOf("page-2")), ), changedParts = listOf( DbChangedPart(id = 40, actionType = DbActionType.RemoveItem, isarId = first.id, data = "canonical", clientDate = 1), DbChangedPart(id = 41, actionType = DbActionType.RemoveItem, isarId = second.id, data = "duplicate", clientDate = 1), DbChangedPart(id = 42, actionType = DbActionType.RemoveChapter, isarId = duplicateChapter.id, data = "duplicate chapter", clientDate = 1), ), )) val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence)) val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id))) val applied = service.apply(preview.command) assertEquals(LocalEntryManagementApplyStatus.Applied, applied.status) assertEquals(listOf(first.id), database.mangas().map { it.id }) val mergedTitle = database.mangas().single() assertTrue(mergedTitle.favorite) assertEquals(8, mergedTitle.lastRead) assertEquals(100, mergedTitle.dateAdded) assertEquals(4, mergedTitle.smartUpdateDays) assertTrue(mergedTitle.customCoverImage!!.contentEquals(byteArrayOf(1, 2))) assertEquals("fallback description", mergedTitle.description) assertEquals(first.id, applied.preview.sourceTitleEffect?.canonicalTitleId) assertTrue(applied.preview.sourceTitleEffect?.favoriteAfter == true) assertTrue(applied.preview.sourceTitleEffect.metadataFallbackFields.contains("description")) assertEquals(listOf(canonicalChapter.id), database.chapters().map { it.id }) assertEquals(first.id, database.chapters().single().mangaId) assertTrue(database.chapters().single().isRead) assertTrue(database.chapters().single().isBookmarked) assertEquals("7", database.chapters().single().lastPageRead) assertEquals(8, database.tracks().single().lastChapterRead) assertEquals(DbTrackStatus.Completed, database.tracks().single().status) assertEquals(1, database.histories().size) assertEquals(35, database.histories().single().readingTimeSeconds) assertEquals(canonicalChapter.id, database.histories().single().chapterId) assertEquals(listOf("page-1", "page-2"), database.pageCache().single().urls) assertTrue(database.changedParts().none { it.actionType == DbActionType.RemoveItem && it.isarId == first.id }) assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveItem && it.isarId == second.id }) assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveChapter && it.isarId == duplicateChapter.id }) assertTrue(database.changedParts().none { it.actionType == DbActionType.RemoveChapter && it.isarId == canonicalChapter.id }) assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveHistory && it.isarId == 37L }) assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveTrack && it.isarId == 35L }) // Removed: title 31, chapter 34, history 37, track 35, tombstone 40, page cache 34. // Added: RemoveHistory/RemoveTrack tombstones. Updated: canonical title, chapter, history, // track, page cache and settings rows, plus the two added rows. assertEquals(6, applied.preview.databaseRowsRemoved) assertEquals(2, applied.preview.databaseRowsAdded) assertEquals(8, applied.preview.databaseRowsUpdated) assertEquals(1, applied.preview.settingsRecordsAffected) assertEquals(0, applied.preview.sourceFilesAffected) } @Test fun mergeRejectsActiveAffectedChapterDownload() = runTest { val first = DbManga(id = 40, link = "USB/Same", source = "local", isLocalArchive = true) val second = first.copy(id = 41) val chapter = DbChapter(id = 42, mangaId = second.id, archivePath = "USB/Same/chapter.cbz") val evidence = LocalLibraryReconciliationResult( duplicateTitleGroups = listOf(LocalLibraryDuplicateGroup( localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same"), listOf(first.id, second.id), )), ) val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy( mangas = listOf(first, second), chapters = listOf(chapter), downloads = listOf(DbDownload(id = 43, chapterId = chapter.id, isStartDownload = true)), )) val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence)) val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id))) assertEquals(LocalEntryManagementBlockers.ActiveDownload, service.apply(preview.command).blocker) } @Test fun forgetRecordsHistoryUpdateAndTrackTombstones() = runTest { val title = DbManga(id = 44, link = "USB/Removed", source = "local", isLocalArchive = true) val chapter = DbChapter(id = 45, mangaId = title.id, archivePath = "USB/Removed/chapter.cbz") val evidence = LocalLibraryReconciliationResult(staleTitleCandidates = listOf( LocalLibraryStaleCandidate( title.id, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!), ), )) val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy( mangas = listOf(title), chapters = listOf(chapter), histories = listOf(DbHistory(id = 46, mangaId = title.id, chapterId = chapter.id, itemType = DbItemType.Manga)), updates = listOf(DbUpdate(id = 47, mangaId = title.id, chapterId = chapter.id)), tracks = listOf(DbTrack(id = 48, mangaId = title.id, status = DbTrackStatus.Reading)), )) val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence)) service.apply(service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id))).command) assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveHistory && it.isarId == 46L }) assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveUpdate && it.isarId == 47L }) assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveTrack && it.isarId == 48L }) } @Test fun mergeBlocksAmbiguousCompletedDownloadWithoutChangingDownloadIdentity() = runTest { val first = DbManga(id = 70, link = "USB/Same", source = "local", isLocalArchive = true) val second = first.copy(id = 71) val firstChapter = DbChapter(id = 72, mangaId = first.id, archivePath = "USB/Same/chapter.cbz") val secondChapter = firstChapter.copy(id = 73, mangaId = second.id) val evidence = LocalLibraryReconciliationResult(duplicateTitleGroups = listOf( LocalLibraryDuplicateGroup( localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same"), listOf(first.id, second.id), ), )) val completed = DbDownload(id = 74, chapterId = firstChapter.id, isDownload = true) val duplicate = DbDownload(id = 75, chapterId = secondChapter.id, isDownload = true) val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy( mangas = listOf(first, second), chapters = listOf(firstChapter, secondChapter), downloads = listOf(completed, duplicate), )) val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence)) val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id))) assertEquals(LocalEntryManagementBlockers.CompletedDownloadConflict, preview.blockers.single()) assertEquals(LocalEntryManagementBlockers.CompletedDownloadConflict, service.apply(preview.command).blocker) assertEquals(setOf(74L, 75L), database.downloads().map { it.id }.toSet()) assertEquals(setOf(firstChapter.id, secondChapter.id), database.downloads().mapNotNull { it.chapterId }.toSet()) } @Test fun mergeBlocksCompletedDownloadOnDuplicateChapterWithoutRemappingIdentity() = runTest { val first = DbManga(id = 76, link = "USB/Same", source = "local", isLocalArchive = true) val second = first.copy(id = 77) val canonicalChapter = DbChapter(id = 78, mangaId = first.id, archivePath = "USB/Same/chapter.cbz") val duplicateChapter = canonicalChapter.copy(id = 79, mangaId = second.id) val evidence = LocalLibraryReconciliationResult(duplicateTitleGroups = listOf( LocalLibraryDuplicateGroup( localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same"), listOf(first.id, second.id), ), )) val completed = DbDownload(id = 80, chapterId = duplicateChapter.id, isDownload = true) val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy( mangas = listOf(first, second), chapters = listOf(canonicalChapter, duplicateChapter), downloads = listOf(completed), )) val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence)) val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id))) assertEquals(LocalEntryManagementBlockers.DownloadIdentityConflict, preview.blockers.single()) assertEquals(LocalEntryManagementBlockers.DownloadIdentityConflict, service.apply(preview.command).blocker) assertEquals(listOf(completed), database.downloads()) } @Test fun tombstonesUseTableAwareIdsAndDoNotRedirectRemoveEntries() = runTest { val title = DbManga(id = 50, link = "USB/Old", source = "local", isLocalArchive = true) val chapter = DbChapter(id = 50, mangaId = title.id, archivePath = "USB/Old/chapter.cbz") val evidence = LocalLibraryReconciliationResult(staleTitleCandidates = listOf( LocalLibraryStaleCandidate(title.id, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!)), )) val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy( mangas = listOf(title), chapters = listOf(chapter), changedParts = listOf( DbChangedPart(id = 1, actionType = DbActionType.RemoveExtension, isarId = title.id, data = "source", clientDate = 1), DbChangedPart(id = 2, actionType = DbActionType.RemoveItem, isarId = title.id, data = "old", clientDate = 1), ), )) val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence)) val result = service.apply(service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id))).command) assertEquals(LocalEntryManagementApplyStatus.Applied, result.status) assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveExtension && it.isarId == title.id }) assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveItem && it.isarId == title.id }) assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveChapter && it.isarId == chapter.id }) assertEquals(database.changedParts().map { it.id }.size, database.changedParts().map { it.id }.toSet().size) } @Test fun applyRequiresFreshReconciliationEvidence() = runTest { val title = DbManga(id = 60, link = "USB/Old", source = "local", isLocalArchive = true) val oldEvidence = LocalLibraryReconciliationResult(staleTitleCandidates = listOf( LocalLibraryStaleCandidate(title.id, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!)), )) val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(title))) val freshLibrary = EvidenceLibrary(LocalLibraryReconciliationResult()) val service = DefaultLocalEntryManagementService(database, freshLibrary) val command = service.preview(LocalEntryManagementOperation.ForgetStale(oldEvidence, titleIds = listOf(title.id))).command assertEquals(LocalEntryManagementBlockers.FreshReconciliationChanged, service.apply(command).blocker) assertEquals(1, freshLibrary.reconcileCalls) } private class EvidenceLibrary( private val result: LocalLibraryReconciliationResult, ) : LocalLibraryService { var reconcileCalls = 0 override suspend fun scan() = LocalLibraryScanResult(0, 0, 0) override suspend fun reconcile(): LocalLibraryReconciliationResult { reconcileCalls++ return result } override suspend fun importTorrent(pathOrMagnet: String, displayName: String?) = null } private class InjectingDatabase( private val delegate: InMemoryYokanDatabase, private val beforeReplacement: () -> Unit, ) : YokanDatabase by delegate { override suspend fun replaceAllAtomically( snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?, removedSourceIds: Set, ) { beforeReplacement() delegate.replaceAllAtomically(snapshot, expectedSnapshot, removedSourceIds) } } }