package eu.friedcutlet.yokan.ui.screens.detail import eu.friedcutlet.yokan.ui.ViewModelTestHost import eu.friedcutlet.yokan.services.notifications.NoNotifications import eu.friedcutlet.yokan.data.DefaultYokanRepository import eu.friedcutlet.yokan.data.LibraryIndexStore import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbChapterReleasePreference import eu.friedcutlet.yokan.database.chapterReleasePreference import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.seedDatabaseSnapshot import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.RecordingHttpService import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.ProfileTestEngine import eu.friedcutlet.yokan.services.together.ProfileTogetherSession import kotlinx.coroutines.awaitCancellation import eu.friedcutlet.yokan.services.download.ChapterDownloads import eu.friedcutlet.yokan.services.download.DownloadProgress import eu.friedcutlet.yokan.services.download.DownloadRequest import eu.friedcutlet.yokan.services.download.DownloadService import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService import eu.friedcutlet.yokan.services.files.NoFiles 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.assertTrue import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import eu.friedcutlet.yokan.services.library.ChapterFilterKind @OptIn(ExperimentalCoroutinesApi::class) class DetailViewModelTest { // No source id: a title without an installed source never triggers the remote refresh. private val database = InMemoryYokanDatabase( seedDatabaseSnapshot().copy( mangas = listOf(DbManga(id = 1, name = "Title", link = "/t", source = "Src", itemType = DbItemType.Manga, favorite = true)), chapters = (1L..3L).map { DbChapter(id = it, mangaId = 1, url = "/c$it", name = "Chapter $it", isRead = it == 2L) }, ), ) private val repository = DefaultYokanRepository(database) private val host = ViewModelTestHost() private val dispatcher = host.dispatcher @AfterTest fun tearDown() = host.close() private fun viewModel( scope: CoroutineScope, downloader: DownloadService = NoDownloads, together: ProfileTogetherSession? = null, http: HttpService? = null, ): DetailViewModel { val settings = SettingsStore(repository, scope, onSchedulingChanged = {}) val downloads = ChapterDownloads(repository, database, downloader, NoNotifications, settings, NoFiles, scope) return host.create { DetailViewModel( mangaId = 1, repository = repository, settings = settings, libraryIndex = LibraryIndexStore(repository, scope), downloads = downloads, metadata = NoMetadata, runtimeFactory = NoRuntimeFactory, database = database, allTrackers = emptyList(), files = NoFiles, workDispatcher = dispatcher, together = together, togetherHttp = http, ) } } @Test fun castOnlyUpdatesReachTheObservedDetailWithoutChangingChapters() = runTest { val vm = viewModel(backgroundScope) vm.state.filterNotNull().first { it.content.loaded } val ids = database.chapters(1).map { it.id } val credit = eu.friedcutlet.yokan.domain.TitleCredit("Actor", "Voice actor", "Hero") database.upsertManga(requireNotNull(database.manga(1)).copy(cast = listOf(credit))) val changed = vm.state.filterNotNull().first { it.content.manga.cast == listOf(credit) } assertEquals(ids.toSet(), changed.content.chapters.map { it.id }.toSet()) database.upsertManga(requireNotNull(database.manga(1)).copy(cast = emptyList())) vm.state.filterNotNull().first { it.content.manga.cast.isEmpty() } } @Test fun seasonSelectionScopesEpisodesContinuationAndActionsAndRecoversAfterRemoval() = runTest { database.upsertManga(requireNotNull(database.manga(1)).copy(itemType = DbItemType.Anime)) database.upsertChapter(DbChapter(id = 1, mangaId = 1, url = "/special", name = "Special", number = 1.0, season = 0)) database.upsertChapter(DbChapter(id = 2, mangaId = 1, url = "/premiere", name = "Premiere", number = 1.0, season = 2)) database.upsertChapter(DbChapter(id = 3, mangaId = 1, url = "/second", name = "S02E02")) database.upsertChapter(DbChapter(id = 4, mangaId = 1, url = "/ova", name = "Unnumbered OVA")) val requests = mutableListOf() val downloader = object : DownloadService by NoDownloads { override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) { requests += request.chapterId } } val vm = viewModel(backgroundScope, downloader) val all = vm.state.filterNotNull().first { it.content.loaded && it.content.chapters.size == 4 } assertEquals(listOf(0, 2), all.content.seasons) assertEquals(null, all.content.selectedSeason) vm.onEvent(DetailEvent.ToggleSelection(1)) vm.onEvent(DetailEvent.SelectSeason(2)) val second = vm.state.filterNotNull().first { it.content.selectedSeason == 2 } assertEquals(setOf(2L, 3L), second.content.chapters.map { it.id }.toSet()) assertTrue(second.selection.ids.isEmpty()) assertTrue(second.content.continueChapter?.id in setOf(2L, 3L)) vm.onEvent(DetailEvent.DownloadAll(repository.chapters(1), DetailDownloadOption.All, null)) assertEquals(setOf(2L, 3L), requests.toSet()) vm.onEvent(DetailEvent.SetRead(setOf(2), true)) assertEquals(false, database.chapter(1)?.isRead) assertEquals(true, database.chapter(2)?.isRead) vm.onEvent(DetailEvent.SelectSeason(99)) assertEquals(2, vm.state.value?.selectedSeason) vm.onEvent(DetailEvent.SelectSeason(0)) val specials = vm.state.filterNotNull().first { it.content.selectedSeason == 0 } assertEquals(listOf(1L), specials.content.chapters.map { it.id }) assertEquals(1L, specials.content.continueChapter?.id) vm.onEvent(DetailEvent.SelectSeason(null)) vm.state.filterNotNull().first { it.content.selectedSeason == null && it.content.chapters.size == 4 } vm.onEvent(DetailEvent.SelectSeason(2)) vm.state.filterNotNull().first { it.content.selectedSeason == 2 } database.batch { database.removeChapter(2); database.removeChapter(3) } val removed = vm.state.filterNotNull().first { it.selectedSeason == null && it.content.chapters.size == 2 } assertEquals(listOf(0), removed.content.seasons) assertEquals(setOf(1L, 4L), removed.content.chapters.map { it.id }.toSet()) } @Test fun seasonsTitleListsItsSeasonRecordsWithTheirOwnProgressAndContinuation() = runTest { database.upsertManga(requireNotNull(database.manga(1)).copy(itemType = DbItemType.Anime, fetchType = eu.friedcutlet.yokan.database.DbFetchType.Seasons)) database.chapters(1).forEach { database.removeChapter(it.id) } database.upsertManga(DbManga(id = 21, name = "Second", link = "/s2", itemType = DbItemType.Anime, parentId = 1, seasonNumber = 2.0)) database.upsertManga(DbManga(id = 20, name = "First", link = "/s1", itemType = DbItemType.Anime, parentId = 1, seasonNumber = 1.0)) database.upsertManga(DbManga(id = 22, name = "Unrelated", link = "/x", itemType = DbItemType.Anime)) database.upsertChapter(DbChapter(id = 30, mangaId = 20, url = "/s1/e1", name = "Episode 1", isRead = true)) database.upsertChapter(DbChapter(id = 31, mangaId = 20, url = "/s1/e2", name = "Episode 2")) database.upsertChapter(DbChapter(id = 32, mangaId = 21, url = "/s2/e1", name = "Episode 1", isRead = true)) val vm = viewModel(backgroundScope) val state = vm.state.filterNotNull().first { it.content.loaded && it.content.seasonTitles.size == 2 } assertEquals(listOf(20L, 21L), state.content.seasonTitles.map { it.title.id }) assertEquals(listOf(2 to 1, 1 to 1), state.content.seasonTitles.map { it.episodeCount to it.watchedCount }) assertEquals(listOf(31L, null), state.content.seasonTitles.map { it.continueChapter?.id }) assertTrue(state.content.chapters.isEmpty()) database.upsertChapter(DbChapter(id = 33, mangaId = 21, url = "/s2/e2", name = "Episode 2")) val updated = vm.state.filterNotNull().first { it.content.seasonTitles.getOrNull(1)?.continueChapter?.id == 33L } assertEquals(2, updated.content.seasonTitles[1].episodeCount) } @Test fun explicitUncategorizedSelectionOverridesDefaultButOrdinaryAddUsesIt() = runTest { val category = repository.createCategory(eu.friedcutlet.yokan.domain.ItemType.Manga, "Default") repository.updateDbSettings { db -> db.copy(features = db.features.copy( library = db.features.library.withDefaultCategory(DbItemType.Manga, category.id), )) } repository.setMangaFavorite(1, false) val vm = viewModel(backgroundScope) vm.state.filterNotNull().first { it.content.loaded && !it.content.manga.favorite } vm.onEvent(DetailEvent.SetFavorite(true)) assertEquals(listOf(category.id), repository.manga(1)?.categories) vm.onEvent(DetailEvent.SetFavorite(false)) vm.onEvent(DetailEvent.SetCategories(emptyList(), favorite = true)) assertEquals(true, repository.manga(1)?.favorite) assertEquals(emptyList(), repository.manga(1)?.categories) vm.state.filterNotNull().first { it.content.manga.favorite && it.content.manga.categories.isEmpty() } } @Test fun togetherEventAndRoomObservationUseTheInjectedControllerAndTransport() = runTest { database.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://captured-hub.test", authToken = "captured-token", deviceId = "captured-device")) val engine = ProfileTestEngine(dispatcher) { awaitCancellation() } val together = ProfileTogetherSession(ProfileId.Default, database, backgroundScope) { engine } val http = RecordingHttpService { HttpResponse(201, "{\"code\":\"ABCDEF\",\"join_url\":\"join\"}") } val vm = viewModel(backgroundScope, together = together, http = http) vm.state.filterNotNull().first { it.content.loaded } vm.onEvent(DetailEvent.Together) assertEquals(DetailEffect.OpenTogetherSettings, vm.effects.first()) assertTrue((vm.effects.first() as DetailEffect.ShowMessage).text.startsWith("Room ABCDEF")) val state = vm.state.filterNotNull().first { it.togetherRoom?.code == "ABCDEF" } assertEquals("ABCDEF", state.togetherRoom?.code) assertEquals("https://captured-hub.test/api/v1/rooms", http.requests.single().url) assertEquals("Bearer captured-token", http.requests.single().headers["Authorization"]) together.leave() vm.state.filterNotNull().first { it.togetherRoom == null } together.closeAndJoin() } @Test fun selectionTogglesSplitByCurrentFlagAndClearTheSelection() = runTest { val vm = viewModel(backgroundScope) vm.state.filterNotNull().first { it.content.loaded } vm.onEvent(DetailEvent.Select(ChapterSelectionOption.All)) vm.onEvent(DetailEvent.ToggleSelectedRead) assertEquals(listOf(true, false, true), (1L..3L).map { database.chapter(it)?.isRead }) assertTrue(checkNotNull(vm.state.value).selection.ids.isEmpty()) vm.state.filterNotNull().first { it.content.chapters.count { chapter -> chapter.isRead } == 2 } vm.onEvent(DetailEvent.ToggleSelection(1)) vm.onEvent(DetailEvent.ToggleSelectedBookmarks) vm.state.filterNotNull().first { it.content.chapters.single { chapter -> chapter.id == 1L }.isBookmarked } vm.onEvent(DetailEvent.ToggleSelection(1)) vm.onEvent(DetailEvent.ToggleSelection(2)) vm.onEvent(DetailEvent.ToggleSelectedBookmarks) assertEquals(listOf(false, true, false), (1L..3L).map { database.chapter(it)?.isBookmarked }) assertTrue(checkNotNull(vm.state.value).selection.ids.isEmpty()) } @Test fun releasePreferencesChooseOneWinnerPreserveFilesAndSupportGroupActionsAndAlternates() = runTest { database.upsertChapter(checkNotNull(database.chapter(1)).copy(scanlator = "Fallback", isRead = true, archivePath = "/kept")) database.upsertChapter(DbChapter(id = 4, mangaId = 1, name = "Chapter 1", url = "/preferred", scanlator = "Preferred")) database.updateSettings(database.settings().copy(chapterReleasePreferences = listOf(DbChapterReleasePreference( scanlatorPriority = listOf("Fallback", "Preferred"), skipDuplicateReleases = true)))) val requests = mutableListOf() val downloader = object : DownloadService by NoDownloads { override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) { requests += request.chapterId } } val vm = viewModel(backgroundScope, downloader) vm.state.filterNotNull().first { it.content.loaded && it.content.chapters.size == 3 } vm.onEvent(DetailEvent.MoveScanlator("Preferred", -1)) val preferred = vm.state.filterNotNull().first { it.content.chapters.any { chapter -> chapter.id == 4L } } assertTrue(preferred.content.chapters.single { it.id == 4L }.isRead) assertEquals("/kept", database.chapter(1)?.archivePath) vm.onEvent(DetailEvent.SetRead(setOf(4), false)) vm.state.filterNotNull().first { !it.content.chapters.single { chapter -> chapter.id == 4L }.isRead } assertEquals(false, database.chapter(1)?.isRead) assertEquals(false, database.chapter(4)?.isRead) vm.onEvent(DetailEvent.SetBookmarked(setOf(4), true)) vm.state.filterNotNull().first { it.content.chapters.single { chapter -> chapter.id == 4L }.isBookmarked } assertTrue(checkNotNull(database.chapter(1)).isBookmarked) assertTrue(checkNotNull(database.chapter(4)).isBookmarked) vm.onEvent(DetailEvent.DownloadAll(checkNotNull(vm.state.value).content.chapters, DetailDownloadOption.All, null)) assertEquals(setOf(2L, 3L, 4L), requests.toSet()) vm.onEvent(DetailEvent.ShowAllReleases(true)) vm.state.filterNotNull().first { it.content.chapters.size == 4 } vm.onEvent(DetailEvent.ShowAllReleases(false)) vm.state.filterNotNull().first { it.content.chapters.size == 3 } vm.onEvent(DetailEvent.ResetReleaseOverride) vm.state.filterNotNull().first { it.content.chapters.any { chapter -> chapter.id == 1L } } assertEquals(listOf("Fallback", "Preferred"), database.settings().chapterReleasePreference(1).scanlatorPriority) assertEquals(4, database.chapters(1).size) assertEquals("/kept", database.chapter(1)?.archivePath) } @Test fun noteSaveCancelAndClearOnlyCommitSavedDrafts() = runTest { val vm = viewModel(backgroundScope) vm.state.filterNotNull().first { it.content.loaded } val note = "日本語 🌙\nSecond line" vm.onEvent(DetailEvent.EditNote) vm.onEvent(DetailEvent.ChangeNote(note)) assertEquals("", repository.manga(1)?.privateNote) vm.onEvent(DetailEvent.SaveNote) assertEquals(note, repository.manga(1)?.privateNote) assertEquals(null, vm.state.value?.noteDraft) vm.onEvent(DetailEvent.EditNote) vm.onEvent(DetailEvent.ChangeNote("discard me")) vm.onEvent(DetailEvent.CancelNote) assertEquals(note, repository.manga(1)?.privateNote) vm.onEvent(DetailEvent.EditNote) vm.onEvent(DetailEvent.ChangeNote("")) vm.onEvent(DetailEvent.CancelNote) assertEquals(note, repository.manga(1)?.privateNote) vm.onEvent(DetailEvent.EditNote) vm.onEvent(DetailEvent.ChangeNote("")) vm.onEvent(DetailEvent.SaveNote) assertEquals("", repository.manga(1)?.privateNote) vm.onEvent(DetailEvent.SetFavorite(false)) vm.state.filterNotNull().first { !it.content.manga.favorite } vm.onEvent(DetailEvent.EditNote) assertEquals(null, vm.state.value?.noteDraft) } @Test fun chapterFilterHidesChaptersAndDropsThemFromTheSelection() = runTest { val vm = viewModel(backgroundScope) val loaded = vm.state.filterNotNull().first { it.content.loaded } assertEquals(listOf(3L, 2L, 1L), loaded.content.chapters.map { it.id }) vm.onEvent(DetailEvent.Select(ChapterSelectionOption.All)) vm.onEvent(DetailEvent.CycleFilter(ChapterFilterKind.Unread)) val filtered = vm.state.filterNotNull().first { it.content.chapters.size == 2 } assertEquals(listOf(3L, 1L), filtered.content.chapters.map { it.id }) assertEquals(setOf(3L, 1L), filtered.selection.ids) } } private object NoDownloads : DownloadService { override suspend fun initialize(poolSize: Int) = Unit override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit override fun cancel(taskId: String) = Unit override fun pause(taskId: String) = Unit override fun resume(taskId: String) = Unit override fun retry(taskId: String): Boolean = false override fun storageLocation(taskId: String): String? = null override fun deleteArtifacts(taskId: String) = Unit override fun activeDownloads(): List = emptyList() } private object NoRuntimeFactory : ExtensionRuntimeFactory { override fun create(source: DbSource): ExtensionRuntimeService = error("No extension runtime in tests") } private object NoMetadata : MetadataService { override suspend fun health(baseUrl: String) = false override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int): List = emptyList() 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 }