package eu.friedcutlet.yokan.ui.screens.local import eu.friedcutlet.yokan.ui.ViewModelTestHost import eu.friedcutlet.yokan.data.DefaultYokanRepository import eu.friedcutlet.yokan.data.LibraryIndexStore import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbTitleMetadata import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.seedDatabaseSnapshot import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.services.files.NoFiles import eu.friedcutlet.yokan.services.files.LocalMediaInput import eu.friedcutlet.yokan.services.files.LocalMediaSelection import eu.friedcutlet.yokan.services.files.pickLocalMedia import eu.friedcutlet.yokan.services.library.DefaultLocalEntryManagementService import eu.friedcutlet.yokan.services.library.LocalLibraryController import eu.friedcutlet.yokan.services.library.LocalLibraryReconciliationResult import eu.friedcutlet.yokan.services.library.LocalLibraryScanResult import eu.friedcutlet.yokan.services.library.LocalLibraryService import eu.friedcutlet.yokan.services.metadata.LocalMetadataField import eu.friedcutlet.yokan.services.metadata.MetadataLibraryEntry import eu.friedcutlet.yokan.services.metadata.MetadataMedia import eu.friedcutlet.yokan.services.metadata.MetadataService import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertSame import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest @OptIn(ExperimentalCoroutinesApi::class) class LocalLibraryViewModelTest { private val database = InMemoryYokanDatabase( seedDatabaseSnapshot().copy( mangas = listOf( DbManga(id = 1, name = "Local", link = "/local/a", source = "local", itemType = DbItemType.Manga, isLocalArchive = true), DbManga(id = 2, name = "Torrent", link = "magnet:x", source = "torrent", itemType = DbItemType.Manga, isLocalArchive = true), DbManga(id = 3, name = "Remote", link = "/remote", source = "Remote", itemType = DbItemType.Manga), ), ), ) private val repository = DefaultYokanRepository(database) private val candidate = MetadataMedia( id = "m1", source = "Metadata server", mediaType = DbItemType.Manga, title = "Better title", description = "Found description", ) private val host = ViewModelTestHost() private val dispatcher = host.dispatcher private var browseModel: LocalLibraryBrowseViewModel? = null @AfterTest fun tearDown() = host.close() private fun viewModel( scope: CoroutineScope, includeBrowse: Boolean = false, mediaPicker: suspend (Boolean) -> LocalMediaSelection? = ::pickLocalMedia, importScope: CoroutineScope = scope, ): LocalLibraryViewModel { val settings = SettingsStore(repository, scope, onSchedulingChanged = {}) val controller = LocalLibraryController( localLibrary = NoScanLibrary, entryManagement = DefaultLocalEntryManagementService(database, NoScanLibrary), repository = repository, metadata = SingleCandidateMetadata(candidate), trackers = emptyList(), files = NoFiles, settings = settings, importScope = importScope, ) val index = LibraryIndexStore(repository, scope) if (includeBrowse) browseModel = host.create { LocalLibraryBrowseViewModel(controller, dispatcher) } return host.create { LocalLibraryViewModel(controller, settings, index, workDispatcher = dispatcher, mediaPicker = mediaPicker) } } @Test fun cancellingImportReleasesItsSelectionAndClearsBusyStateWithoutReportingFailure() = runTest { val started = CompletableDeferred() val closed = CompletableDeferred() val source = object : LocalMediaInput { override val relativePath = "clip.mp4" override val sizeBytes = 1L override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { started.complete(Unit); awaitCancellation() } } val vm = viewModel(backgroundScope, mediaPicker = { LocalMediaSelection(listOf(source)) { closed.complete(Unit) } }) vm.onEvent(LocalLibraryEvent.ImportMedia(ItemType.Anime, directory = false)) started.await() vm.onEvent(LocalLibraryEvent.CancelImport) closed.await() val state = vm.state.first { !it.importBusy } kotlin.test.assertFalse(state.importFailed) kotlin.test.assertFalse(state.importCompleted) assertNull(state.importProgress) } @Test fun profileRetirementCancelsImportAndReleasesThePickerSelection() = runTest { val owner = CoroutineScope(SupervisorJob() + dispatcher) val started = CompletableDeferred() val closed = CompletableDeferred() val source = object : LocalMediaInput { override val relativePath = "clip.mp4" override val sizeBytes = 1L override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { started.complete(Unit); awaitCancellation() } } val vm = viewModel(backgroundScope, mediaPicker = { LocalMediaSelection(listOf(source)) { closed.complete(Unit) } }, importScope = owner) try { vm.onEvent(LocalLibraryEvent.ImportMedia(ItemType.Anime, directory = false)) started.await() owner.cancel() closed.await() kotlin.test.assertFalse(vm.state.first { !it.importBusy }.importFailed) } finally { owner.cancel() } } @Test fun bridgeFailuresAreShownAndDoNotLeaveImportBusy() = runTest { // JavaScript bridge failures need not derive from kotlin.Exception. val vm = viewModel(backgroundScope, mediaPicker = { throw Throwable("Storage provider failed") }) vm.onEvent(LocalLibraryEvent.ImportMedia(ItemType.Anime, directory = false)) val state = vm.state.first { it.importFailed && !it.importBusy } assertEquals("Storage provider failed", state.importError) assertNull(state.importProgress) } @Test fun metadataOnlyEditsRefreshBothScreensAndScanStatusReusesTitles() = runTest { database.upsertManga(checkNotNull(database.manga(1)).copy(description = "Description")) val vm = viewModel(backgroundScope, includeBrowse = true) val browse = checkNotNull(browseModel) val initial = vm.state.first { it.titlesByType.isNotEmpty() } browse.state.first { it.titlesByType.isNotEmpty() } val mangas = database.snapshots().value.mangas database.updateSettings(database.settings().copy(titleMetadata = listOf(DbTitleMetadata(1, metadataServerId = "linked")))) val updated = vm.state.first { it.reviewQueue.isEmpty() } val browsed = browse.state.first { it.titlesByType[ItemType.Manga]?.first()?.metadataServerId == "linked" } assertSame(mangas, database.snapshots().value.mangas) assertEquals(listOf(1L), initial.reviewQueue.map { it.id }) assertEquals("linked", updated.titlesByType.getValue(ItemType.Manga).single().metadataServerId) assertSame(updated.titlesByType.getValue(ItemType.Manga).single(), browsed.titlesByType.getValue(ItemType.Manga).first()) database.updateSettings(database.settings().copy(themeIsDark = !database.settings().themeIsDark)) vm.onEvent(LocalLibraryEvent.Rescan) val scanned = vm.state.first { it.overview.lastScan != null && !it.overview.scanRunning } assertSame(updated.titlesByType, scanned.titlesByType) assertSame(browsed.titlesByType, browse.state.value.titlesByType) } @Test fun overviewListsLocalTitlesWithoutTorrentsAndFollowsDatabaseChanges() = runTest { val vm = viewModel(backgroundScope) val initial = vm.state.first { it.titlesByType.isNotEmpty() } assertEquals(listOf(1L), initial.titlesByType.getValue(ItemType.Manga).map { it.id }) assertEquals(1, initial.overview.manga) assertEquals(listOf(1L), initial.reviewQueue.map { it.id }) database.upsertManga(DbManga(id = 4, name = "Clip", link = "/local/b", source = "local", itemType = DbItemType.Anime, isLocalArchive = true)) val updated = vm.state.first { it.overview.anime == 1 } assertEquals(listOf(4L), updated.titlesByType.getValue(ItemType.Anime).map { it.id }) assertEquals(setOf(1L, 4L), updated.reviewQueue.map { it.id }.toSet()) } @Test fun reopeningReviewStartsWithNoPreviousSearchOrSelection() = runTest { val vm = viewModel(backgroundScope) val manga = checkNotNull(repository.manga(1)) vm.onEvent(LocalLibraryEvent.OpenMetadataReview(manga)) vm.onEvent(LocalLibraryEvent.SearchMetadataCandidates) vm.state.first { it.metadataReview?.candidates == listOf(candidate) } vm.onEvent(LocalLibraryEvent.SelectCandidate(candidate)) vm.onEvent(LocalLibraryEvent.SetFieldSelected(LocalMetadataField.Description, true)) vm.onEvent(LocalLibraryEvent.DismissMetadataReview) vm.onEvent(LocalLibraryEvent.OpenMetadataReview(manga)) assertEquals(LocalMetadataReviewState(manga), vm.state.value.metadataReview) } @Test fun applyingMetadataWritesOnlySelectedFieldsAndClosesTheReview() = runTest { val vm = viewModel(backgroundScope) vm.onEvent(LocalLibraryEvent.OpenMetadataReview(checkNotNull(repository.manga(1)))) vm.onEvent(LocalLibraryEvent.SearchMetadataCandidates) vm.state.first { it.metadataReview?.candidates?.isNotEmpty() == true } vm.onEvent(LocalLibraryEvent.SelectCandidate(candidate)) vm.onEvent(LocalLibraryEvent.SetFieldSelected(LocalMetadataField.Title, true)) vm.onEvent(LocalLibraryEvent.SetFieldSelected(LocalMetadataField.Description, true)) vm.onEvent(LocalLibraryEvent.SetFieldSelected(LocalMetadataField.Title, false)) vm.onEvent(LocalLibraryEvent.ApplyMetadata) val saved = checkNotNull(repository.manga(1)) assertEquals("Local", saved.name) assertEquals("Found description", saved.description) assertNull(vm.state.value.metadataReview) } } private object NoScanLibrary : LocalLibraryService { override suspend fun scan() = LocalLibraryScanResult(0, 0, 0) override suspend fun reconcile() = LocalLibraryReconciliationResult() override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? = null } private class SingleCandidateMetadata(private val candidate: MetadataMedia) : MetadataService { override suspend fun health(baseUrl: String) = true override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int) = listOf(candidate) override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List> = emptyList() override suspend fun upsertLibraryEntry( baseUrl: String, token: String, mediaId: String, status: String, progress: Int, score: Int?, isFavorite: Boolean, ) = false }