package eu.friedcutlet.yokan.ui.screens.player 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.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbVideo import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.seedDatabaseSnapshot import eu.friedcutlet.yokan.database.withPlayer import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.domain.testManga import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.media.cast.CastController import eu.friedcutlet.yokan.services.media.cast.CastDevice import eu.friedcutlet.yokan.services.media.cast.CastMedia import eu.friedcutlet.yokan.services.media.cast.CastStatus import eu.friedcutlet.yokan.services.media.cast.CastTextStyle import eu.friedcutlet.yokan.ui.ViewModelTestHost import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertTrue import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest class PlayerViewModelTest { private val database = InMemoryYokanDatabase( seedDatabaseSnapshot().copy( mangas = listOf(DbManga(id = 1, name = "Show", link = "/s", source = "Src", itemType = DbItemType.Anime, favorite = true)), chapters = (1L..5L).map { DbChapter(id = it, mangaId = 1, url = "/e$it", name = "Episode $it") }, ), ) private val repository = DefaultYokanRepository(database) private val host = ViewModelTestHost() private val manga = testManga(1, name = "Show", itemType = ItemType.Anime) private val noHttp = HttpService { error("no seek previews in these tests") } private val cast = RecordingCast() private val sd = DbVideo(url = "https://cdn.example/sd.m3u8", quality = "480p", originalUrl = "") private val hd = DbVideo(url = "https://cdn.example/hd.m3u8", quality = "1080p", originalUrl = "") @AfterTest fun tearDown() = host.close() private fun episode(id: Long, lastPageRead: String = "") = Chapter(id = id, mangaId = 1, name = "Episode $id", url = "/e$id", lastPageRead = lastPageRead) private fun viewModel( scope: CoroutineScope, chapter: Chapter = episode(3), settings: SettingsStore = SettingsStore(repository, scope, onSchedulingChanged = {}), loadVideos: suspend (Source?, Chapter) -> List, ): PlayerViewModel = host.create { PlayerViewModel( manga = manga, chapter = chapter, repository = repository, settings = settings, libraryIndex = LibraryIndexStore(repository, scope), http = noHttp, loadVideos = loadVideos, aniSkipMarkers = { _, _ -> emptyList() }, openExternalPlayer = { _, _ -> false }, cast = cast, workDispatcher = host.dispatcher, ) } private fun CoroutineScope.effectsOf(vm: PlayerViewModel): List = mutableListOf().also { effects -> launch(host.dispatcher) { vm.effects.collect { effects += it } } } @Test fun loadingSelectsTheFirstStreamAtTheSavedPosition() = runTest { val requested = mutableListOf() val vm = viewModel(backgroundScope, chapter = episode(3, lastPageRead = "65000")) { _, chapter -> requested += chapter.id listOf(sd, hd) } val loaded = vm.state.first { !it.loading } assertEquals(listOf(3L), requested) assertEquals(listOf(sd, hd), loaded.videos) assertEquals(sd, loaded.selectedVideo) assertEquals(65_000L, loaded.startPositionMs) assertTrue(loaded.autoplay) assertNull(loaded.error) } @Test fun failedOrEmptyLoadsReportAnErrorWithoutAStream() = runTest { val failed = viewModel(backgroundScope) { _, _ -> error("extension crashed") }.state.first { !it.loading } val empty = viewModel(backgroundScope) { _, _ -> emptyList() }.state.first { !it.loading } assertEquals("extension crashed", failed.error) assertNull(failed.selectedVideo) assertEquals("No streams were returned by this source.", empty.error) assertNull(empty.selectedVideo) } @Test fun playbackFailureSwitchesToEachRemainingStreamOnceThenReports() = runTest { val settings = SettingsStore(repository, backgroundScope, onSchedulingChanged = {}) settings.updateDb { db -> db.withPlayer { it.copy(switchStreamOnFailure = true) } } val vm = viewModel(backgroundScope, settings = settings) { _, _ -> listOf(sd, hd) } val effects = backgroundScope.effectsOf(vm) vm.state.first { !it.loading } vm.onEvent(PlayerEvent.PlaybackFailed("decoder", positionMs = 42_000)) val switched = vm.state.value vm.onEvent(PlayerEvent.PlaybackFailed("decoder", positionMs = 50_000)) assertEquals(hd, switched.selectedVideo) assertEquals(42_000L, switched.startPositionMs) assertEquals(hd, vm.state.value.selectedVideo) assertEquals( listOf( PlayerEffect.ShowNotice("Stream failed; switching to 1080p"), PlayerEffect.ShowNotice("Playback failed: decoder"), ), effects, ) } @Test fun playbackFailureWithoutFailoverOnlyReports() = runTest { val vm = viewModel(backgroundScope) { _, _ -> listOf(sd, hd) } val effects = backgroundScope.effectsOf(vm) vm.state.first { !it.loading } vm.onEvent(PlayerEvent.PlaybackFailed("decoder", positionMs = 42_000)) assertEquals(sd, vm.state.value.selectedVideo) assertEquals(listOf(PlayerEffect.ShowNotice("Playback failed: decoder")), effects) } @Test fun castingQueuesThisEpisodeThenTheNextTwoInTitleOrder() = runTest { val vm = viewModel(backgroundScope) { _, chapter -> listOf(DbVideo(url = "https://cdn.example/${chapter.id}.mp4", quality = "720p", originalUrl = "")) } val episodes = vm.state.first { !it.loading && it.episodes.size == 5 }.episodes.map { it.id } val following = episodes.dropWhile { it != 3L }.drop(1).take(2) vm.onEvent(PlayerEvent.StartCasting(device = null, startPositionMs = 12_000, subtitleFile = null)) assertEquals(2, following.size) assertEquals(listOf("connect"), cast.calls) assertEquals(listOf("3"), cast.loaded.map { it.itemKey }) assertEquals(12_000L, cast.loadedAtMs) assertEquals(following.map { it.toString() }, cast.appended.map { it.itemKey }) } @Test fun castingStreamsThatNeedHeadersIsRefused() = runTest { val vm = viewModel(backgroundScope) { _, _ -> listOf(sd.copy(headers = mapOf("Referer" to "x"))) } val effects = backgroundScope.effectsOf(vm) vm.state.first { !it.loading } vm.onEvent(PlayerEvent.StartCasting(device = null, startPositionMs = 0, subtitleFile = null)) assertTrue(cast.calls.isEmpty()) assertEquals( listOf(PlayerEffect.ShowNotice("This episode's streams need request headers or are local, so they cannot be cast")), effects, ) } private class RecordingCast : CastController { val calls = mutableListOf() val loaded = mutableListOf() val appended = mutableListOf() var loadedAtMs = -1L override val isSupported = MutableStateFlow(true) override val usesSystemPicker = false override val devices = MutableStateFlow(emptyList()) override val status = MutableStateFlow(null) override fun startDiscovery() { calls += "discover" } override fun stopDiscovery() { calls += "stop-discovery" } override suspend fun connect(device: CastDevice?) { calls += "connect" } override suspend fun loadQueue( items: List, startIndex: Int, startPositionMs: Long, style: CastTextStyle, activeSubtitleIndex: Int?, ) { loaded += items loadedAtMs = startPositionMs } override suspend fun append(items: List) { appended += items } override fun play() = Unit override fun pause() = Unit override fun seekTo(positionMs: Long) = Unit override fun next() = Unit override fun previous() = Unit override fun jumpTo(index: Int) = Unit override suspend fun disconnect() { calls += "disconnect" } override fun close() = Unit } }