@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.media.player import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.files.LocalFileEntry import eu.friedcutlet.yokan.services.files.LocalEntry import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.media.AniSkipService import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.Job import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext class ProfilePlayerServicesTest { @Test fun alreadyCanceledCallerCannotWriteIntoLiveOwner() = runTest { val f = Fixture(this) val configuration = f.reader.configuration(DbSettings()) try { val caller = async(UnconfinedTestDispatcher(testScheduler)) { requireNotNull(currentCoroutineContext()[Job]).cancel() assertFailsWith { f.reader.prepareConfiguration(configuration) } } caller.join() assertTrue(f.files.writes.isEmpty()) assertTrue(f.owner.isActive) } finally { f.close() } } @Test fun configurationUsesCapturedRootAndPreservesExistingUserFiles() = runTest { val f = Fixture(this) try { val configuration = f.reader.configuration(DbSettings(hwdecMode = "custom")) assertEquals("/A/cache/mpv", configuration.mpvConfigDirectory) assertEquals("custom", configuration.hwdecMode) f.files.bytes["/A/cache/mpv/mpv.conf"] = "user config".encodeToByteArray() f.reader.prepareConfiguration(configuration) assertEquals("user config", f.files.bytes.getValue("/A/cache/mpv/mpv.conf").decodeToString()) assertEquals(listOf("/A/cache/mpv/input.conf"), f.files.writes) } finally { f.close() } } @Test fun disabledConfigurationDoesNotTouchFiles() = runTest { val f = Fixture(this) try { f.reader.prepareConfiguration(f.reader.configuration(DbSettings(useMpvConfig = false))) assertTrue(f.files.writes.isEmpty()) assertTrue(f.files.existsReads.isEmpty()) } finally { f.close() } } @Test fun retirementAfterInventoryCannotWriteConfiguration() = runTest { val f = Fixture(this) val configuration = f.reader.configuration(DbSettings()) f.files.onExists = { f.open = false } try { assertFailsWith { f.reader.prepareConfiguration(configuration) } assertTrue(f.files.writes.isEmpty()) assertTrue(f.owner.isActive) } finally { f.close() } } @Test fun readerExpiryBetweenConfigurationFilesStopsFurtherWork() = runTest { val f = Fixture(this) val configuration = f.reader.configuration(DbSettings()) f.files.onWrite = { f.reader.retire() } try { assertFailsWith { f.reader.prepareConfiguration(configuration) } assertEquals(listOf("/A/cache/mpv/mpv.conf"), f.files.writes) assertEquals(listOf("/A/cache/mpv/mpv.conf"), f.files.existsReads) } finally { f.close() } } @Test fun scriptInstallationUsesCapturedFilesAndExistingButtonPolicy() = runTest { val f = Fixture(this) val controller = Controller() try { val button = DbCustomButton(id = 7, title = "Skip", codePress = "aniyomi.seek_by(7)", isFavourite = true, position = 0) assertTrue(f.reader.installCustomButtons(controller, listOf(button), f.reader.configuration(DbSettings()))) assertEquals(listOf( listOf("load-script", "/A/cache/mpv/scripts/yokan_chapter_titles.js"), listOf("load-script", "/A/cache/mpv/scripts/yokan_custom_buttons.js"), ), controller.commands) assertTrue("aniyomi.seek_by(7)" in f.files.bytes.getValue(f.files.writes.last()).decodeToString()) } finally { f.close() } } @Test fun canceledScriptWriteCannotQueueNativeCommand() = runTest { val f = Fixture(this) val controller = Controller() val configuration = f.reader.configuration(DbSettings()) f.files.onWrite = { f.reader.retire() } try { assertFailsWith { f.reader.installCustomButtons(controller, emptyList(), configuration) } assertTrue(controller.commands.isEmpty()) } finally { f.close() } } @Test fun retirementAfterFirstScriptCommandCannotWriteOrDispatchSecondScript() = runTest { val f = Fixture(this) val controller = Controller() val configuration = f.reader.configuration(DbSettings()) controller.onCommand = { f.open = false } try { assertFailsWith { f.reader.installCustomButtons(controller, listOf(DbCustomButton(id = 1, position = 0)), configuration) } assertEquals(1, controller.commands.size) assertEquals(1, f.files.writes.size) } finally { f.close() } } @Test fun screenshotUsesCapturedRootAndSanitizesTitlePath() = runTest { val f = Fixture(this) val controller = Controller() try { val path = requireNotNull(f.reader.requestScreenshot(controller, "../Book/名", "Episode 1")) assertTrue(path.startsWith("/A/cache/screenshots/")) assertTrue('/' !in path.removePrefix("/A/cache/screenshots/")) assertEquals(listOf("sync", "screenshot-to-file", path, "video"), controller.commands.single()) assertTrue(f.files.bytes.containsKey(path)) } finally { f.close() } } @Test fun unsupportedScreenshotRemovesOnlyItsSeededFile() = runTest { val f = Fixture(this) val controller = Controller().apply { accepted = false } try { assertEquals(null, f.reader.requestScreenshot(controller, "Book", "Episode")) assertEquals(f.files.writes, f.files.deletions) assertTrue(f.files.bytes.isEmpty()) } finally { f.close() } } @Test fun screenshotSeedExpiryJoinsCleanupWithoutDispatchingNativeCommand() = runTest { val f = Fixture(this) val controller = Controller() f.files.onWrite = { f.reader.retire() } try { assertFailsWith { f.reader.requestScreenshot(controller, "Book", "Episode") } assertTrue(controller.commands.isEmpty()) assertEquals(f.files.writes, f.files.deletions) assertTrue(f.files.bytes.isEmpty()) } finally { f.close() } } @Test fun longTitleScreenshotsRetainUniqueSuffixAndFailedShotCannotDeletePriorShot() = runTest { val f = Fixture(this) val controller = Controller() try { val title = "Long title ".repeat(30) val first = requireNotNull(f.reader.requestScreenshot(controller, title, "Episode")) controller.accepted = false assertEquals(null, f.reader.requestScreenshot(controller, title, "Episode")) val second = f.files.writes.last() assertTrue(first != second) assertTrue(f.files.bytes.containsKey(first)) assertEquals(listOf(second), f.files.deletions) } finally { f.close() } } @Test fun proxyRetirementDuringRegistrationRejectsLateUrl() = runTest { val f = Fixture(this) f.proxy.onRegister = { f.open = false } try { assertFailsWith { f.reader.streamProxy.proxyUrl("https://stream.test", emptyMap()) } assertEquals(listOf("https://stream.test"), f.proxy.urls) assertFailsWith { f.reader.streamProxy.proxyUrl("https://late.test", emptyMap()) } assertEquals(1, f.proxy.urls.size) } finally { f.close() } } @Test fun markersUseCapturedHttpAndPreserveAniSkipParsing() = runTest { val f = Fixture(this) try { val result = f.reader.markers(42, 12, 1500) assertEquals("op", result.single().type) assertEquals(90.0, result.single().endSeconds) val request = f.http.requests.single() assertTrue("/42/12?" in request.url) assertTrue("episodeLength=1500" in request.url) assertEquals("application/json", request.headers["Accept"]) } finally { f.close() } } @Test fun canceledMarkerCallerJoinsTransportFinalizer() = runTest { val f = Fixture(this) val release = CompletableDeferred() f.http.response = { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } try { val call = async { f.reader.markers(42, 1, 0) } runCurrent(); call.cancel(); runCurrent() assertFalse(call.isCompleted) release.complete(Unit); call.join() assertTrue(call.isCancelled) assertTrue(f.service.isAvailable) } finally { release.complete(Unit); f.close() } } @Test fun retiringMarkersCannotDeliverLateResponseOrFailureFallback() = runTest { val f = Fixture(this) val release = CompletableDeferred() f.http.response = { withContext(NonCancellable) { release.await(); error("late transport failure") } } try { val call = async { f.reader.markers(42, 1, 0) } runCurrent() f.open = false val close = async { f.service.closeAndJoin() } runCurrent() assertFalse(close.isCompleted) release.complete(Unit); close.await() assertFailsWith { call.await() } } finally { release.complete(Unit); f.close() } } @Test fun foreignConfigurationIsRejectedBeforeFilesOrNativeCommands() = runTest { val f = Fixture(this) val foreign = MediaPlayerConfiguration(mpvConfigDirectory = "/B/cache/mpv") val controller = Controller() try { assertFailsWith { f.reader.prepareConfiguration(foreign) } assertFailsWith { f.reader.installCustomButtons(controller, emptyList(), foreign) } assertTrue(f.files.writes.isEmpty()) assertTrue(controller.commands.isEmpty()) } finally { f.close() } } @Test fun retiredReaderRejectsEveryAuxiliaryEntryPoint() = runTest { val f = Fixture(this) val configuration = f.reader.configuration(DbSettings()) val controller = Controller() try { f.reader.closeAndJoin() assertFailsWith { f.reader.configuration(DbSettings()) } assertFailsWith { f.reader.prepareConfiguration(configuration) } assertFailsWith { f.reader.installCustomButtons(controller, emptyList(), configuration) } assertFailsWith { f.reader.markers(42, 1, 0) } assertFailsWith { f.reader.requestScreenshot(controller, "Book", "Episode") } assertFailsWith { f.reader.streamProxy.proxyUrl("https://stream.test", mapOf("Referer" to "A")) } assertTrue(f.files.writes.isEmpty()) assertTrue(f.http.requests.isEmpty()) assertTrue(f.proxy.urls.isEmpty()) assertTrue(f.owner.isActive) } finally { f.close() } } @Test fun stoppingOldProxyHandleCannotStopSiblingOrSharedProxy() = runTest { val f = Fixture(this) try { val current = f.service.reader() f.reader.streamProxy.stop() assertEquals("proxy:https://stream.test", current.streamProxy.proxyUrl("https://stream.test", mapOf("Referer" to "A"))) assertEquals(0, f.proxy.stops) assertFailsWith { f.reader.streamProxy.proxyUrl("https://late.test", emptyMap()) } } finally { f.close() } } @Test fun independentServicesKeepTheirOwnFilesAndProxyAndPreserveParentsOnClose() = runTest { val a = Fixture(this, "A") val b = Fixture(this, "B") try { a.reader.prepareConfiguration(a.reader.configuration(DbSettings())) b.reader.prepareConfiguration(b.reader.configuration(DbSettings())) a.service.closeAndJoin() assertTrue(a.owner.isActive) assertFailsWith { a.reader.configuration(DbSettings()) } assertEquals("/B/cache/mpv", b.reader.configuration(DbSettings()).mpvConfigDirectory) assertEquals("proxy:B", b.reader.streamProxy.proxyUrl("B", emptyMap())) assertTrue(a.files.writes.all { it.startsWith("/A/") }) assertTrue(b.files.writes.all { it.startsWith("/B/") }) } finally { a.close(); b.close() } } internal class Fixture(test: TestScope, label: String = "A", dispatcher: CoroutineDispatcher = StandardTestDispatcher(test.testScheduler), factory: (MediaPlayerConfiguration, MediaStreamProxy) -> MediaPlayerController = ::createMediaPlayerController) { val owner = SupervisorJob() var open = true val files = Files(label) val http = Http() val proxy = Proxy() val service = ProfilePlayerServices(ProfileId.Default, files, AniSkipService(http), proxy, CoroutineScope(owner + StandardTestDispatcher(test.testScheduler)), dispatcher, factory) { open } val reader = service.reader() suspend fun close() { service.closeAndJoin(); owner.cancelAndJoin() } } internal class Files(label: String) : LocalFileService { override val downloadRoot = "/$label/downloads" override val backupRoot = "/$label/backups" override val cacheRoot = "/$label/cache" val bytes = mutableMapOf() val writes = mutableListOf() val deletions = mutableListOf() val existsReads = mutableListOf() var onWrite: (String) -> Unit = { } var onExists: (String) -> Unit = { } override fun writeBytes(path: String, bytes: ByteArray) { writes += path; this.bytes[path] = bytes; onWrite(path) } override fun exists(path: String): Boolean { existsReads += path; onExists(path); return bytes.containsKey(path) } override fun deleteRecursively(path: String): Boolean { deletions += path; return bytes.remove(path) != null } override fun readBytes(path: String) = bytes.getValue(path) override fun canonicalPath(path: String): String = path override fun directorySize(path: String): Long = 0 override fun openLocation(path: String): Boolean = false override fun listLocalEntries(root: String): List = emptyList() override fun listFiles(root: String): List = emptyList() } internal class Http : HttpService { val requests = mutableListOf() var response: suspend () -> HttpResponse = { HttpResponse(statusCode = 200, body = """{"found":true,"results":[{"skipType":"op","interval":{"startTime":0,"endTime":90},"episodeLength":1500}]}""") } override suspend fun request(request: HttpRequest): HttpResponse { requests += request; return response() } } internal class Proxy : MediaStreamProxy { val urls = mutableListOf() var stops = 0 var onRegister: () -> Unit = { } override fun proxyUrl(url: String, headers: Map): String { urls += url; onRegister(); return "proxy:$url" } override fun stop() { stops++ } } internal class Controller : MediaPlayerController { override val isMpvBackend = true val commands = mutableListOf>() var accepted = true var onCommand: () -> Unit = { } var onAwaitedCommand: suspend (List) -> Boolean = { true } override fun load(url: String, headers: Map, initialPositionMs: Long) = Unit override fun play() = Unit override fun pause() = Unit override fun seekTo(positionMs: Long) = Unit override fun setPlaybackSpeed(speed: Float) = Unit override fun executeMpvCommand(vararg arguments: String): Boolean { commands += arguments.toList(); onCommand(); return accepted } override suspend fun executeMpvCommandAndJoin(vararg arguments: String): Boolean = executeMpvCommand(*arguments) && onAwaitedCommand(arguments.toList()) override fun release() = Unit override fun currentPositionMs(): Long = 0 override fun durationMs(): Long = 0 override fun isPlaying(): Boolean = false } }