ProfilePlayerServicesTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServicesTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)23package eu.friedcutlet.yokan.services.media.player45import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.database.DbCustomButton7import eu.friedcutlet.yokan.database.DbSettings8import eu.friedcutlet.yokan.services.files.LocalFileService9import eu.friedcutlet.yokan.services.files.LocalFileEntry10import eu.friedcutlet.yokan.services.files.LocalEntry11import eu.friedcutlet.yokan.services.http.HttpService12import eu.friedcutlet.yokan.services.http.HttpRequest13import eu.friedcutlet.yokan.services.http.HttpResponse14import eu.friedcutlet.yokan.services.media.AniSkipService15import kotlin.test.Test16import kotlin.test.assertEquals17import kotlin.test.assertFailsWith18import kotlin.test.assertFalse19import kotlin.test.assertTrue20import kotlinx.coroutines.CancellationException21import kotlinx.coroutines.CompletableDeferred22import kotlinx.coroutines.CoroutineDispatcher23import kotlinx.coroutines.CoroutineScope24import kotlinx.coroutines.NonCancellable25import kotlinx.coroutines.Job26import kotlinx.coroutines.currentCoroutineContext27import kotlinx.coroutines.test.UnconfinedTestDispatcher28import kotlinx.coroutines.SupervisorJob29import kotlinx.coroutines.async30import kotlinx.coroutines.awaitCancellation31import kotlinx.coroutines.cancelAndJoin32import kotlinx.coroutines.test.StandardTestDispatcher33import kotlinx.coroutines.test.TestScope34import kotlinx.coroutines.test.runCurrent35import kotlinx.coroutines.test.runTest36import kotlinx.coroutines.withContext3738class ProfilePlayerServicesTest {39 @Test fun alreadyCanceledCallerCannotWriteIntoLiveOwner() = runTest {40 val f = Fixture(this)41 val configuration = f.reader.configuration(DbSettings())42 try {43 val caller = async(UnconfinedTestDispatcher(testScheduler)) {44 requireNotNull(currentCoroutineContext()[Job]).cancel()45 assertFailsWith<CancellationException> { f.reader.prepareConfiguration(configuration) }46 }47 caller.join()48 assertTrue(f.files.writes.isEmpty())49 assertTrue(f.owner.isActive)50 } finally { f.close() }51 }5253 @Test fun configurationUsesCapturedRootAndPreservesExistingUserFiles() = runTest {54 val f = Fixture(this)55 try {56 val configuration = f.reader.configuration(DbSettings(hwdecMode = "custom"))57 assertEquals("/A/cache/mpv", configuration.mpvConfigDirectory)58 assertEquals("custom", configuration.hwdecMode)59 f.files.bytes["/A/cache/mpv/mpv.conf"] = "user config".encodeToByteArray()60 f.reader.prepareConfiguration(configuration)61 assertEquals("user config", f.files.bytes.getValue("/A/cache/mpv/mpv.conf").decodeToString())62 assertEquals(listOf("/A/cache/mpv/input.conf"), f.files.writes)63 } finally { f.close() }64 }6566 @Test fun disabledConfigurationDoesNotTouchFiles() = runTest {67 val f = Fixture(this)68 try {69 f.reader.prepareConfiguration(f.reader.configuration(DbSettings(useMpvConfig = false)))70 assertTrue(f.files.writes.isEmpty())71 assertTrue(f.files.existsReads.isEmpty())72 } finally { f.close() }73 }7475 @Test fun retirementAfterInventoryCannotWriteConfiguration() = runTest {76 val f = Fixture(this)77 val configuration = f.reader.configuration(DbSettings())78 f.files.onExists = { f.open = false }79 try {80 assertFailsWith<CancellationException> { f.reader.prepareConfiguration(configuration) }81 assertTrue(f.files.writes.isEmpty())82 assertTrue(f.owner.isActive)83 } finally { f.close() }84 }8586 @Test fun readerExpiryBetweenConfigurationFilesStopsFurtherWork() = runTest {87 val f = Fixture(this)88 val configuration = f.reader.configuration(DbSettings())89 f.files.onWrite = { f.reader.retire() }90 try {91 assertFailsWith<CancellationException> { f.reader.prepareConfiguration(configuration) }92 assertEquals(listOf("/A/cache/mpv/mpv.conf"), f.files.writes)93 assertEquals(listOf("/A/cache/mpv/mpv.conf"), f.files.existsReads)94 } finally { f.close() }95 }9697 @Test fun scriptInstallationUsesCapturedFilesAndExistingButtonPolicy() = runTest {98 val f = Fixture(this)99 val controller = Controller()100 try {101 val button = DbCustomButton(id = 7, title = "Skip", codePress = "aniyomi.seek_by(7)", isFavourite = true, position = 0)102 assertTrue(f.reader.installCustomButtons(controller, listOf(button), f.reader.configuration(DbSettings())))103 assertEquals(listOf(104 listOf("load-script", "/A/cache/mpv/scripts/yokan_chapter_titles.js"),105 listOf("load-script", "/A/cache/mpv/scripts/yokan_custom_buttons.js"),106 ), controller.commands)107 assertTrue("aniyomi.seek_by(7)" in f.files.bytes.getValue(f.files.writes.last()).decodeToString())108 } finally { f.close() }109 }110111 @Test fun canceledScriptWriteCannotQueueNativeCommand() = runTest {112 val f = Fixture(this)113 val controller = Controller()114 val configuration = f.reader.configuration(DbSettings())115 f.files.onWrite = { f.reader.retire() }116 try {117 assertFailsWith<CancellationException> { f.reader.installCustomButtons(controller, emptyList(), configuration) }118 assertTrue(controller.commands.isEmpty())119 } finally { f.close() }120 }121122 @Test fun retirementAfterFirstScriptCommandCannotWriteOrDispatchSecondScript() = runTest {123 val f = Fixture(this)124 val controller = Controller()125 val configuration = f.reader.configuration(DbSettings())126 controller.onCommand = { f.open = false }127 try {128 assertFailsWith<CancellationException> {129 f.reader.installCustomButtons(controller, listOf(DbCustomButton(id = 1, position = 0)), configuration)130 }131 assertEquals(1, controller.commands.size)132 assertEquals(1, f.files.writes.size)133 } finally { f.close() }134 }135136 @Test fun screenshotUsesCapturedRootAndSanitizesTitlePath() = runTest {137 val f = Fixture(this)138 val controller = Controller()139 try {140 val path = requireNotNull(f.reader.requestScreenshot(controller, "../Book/名", "Episode 1"))141 assertTrue(path.startsWith("/A/cache/screenshots/"))142 assertTrue('/' !in path.removePrefix("/A/cache/screenshots/"))143 assertEquals(listOf("sync", "screenshot-to-file", path, "video"), controller.commands.single())144 assertTrue(f.files.bytes.containsKey(path))145 } finally { f.close() }146 }147148 @Test fun unsupportedScreenshotRemovesOnlyItsSeededFile() = runTest {149 val f = Fixture(this)150 val controller = Controller().apply { accepted = false }151 try {152 assertEquals(null, f.reader.requestScreenshot(controller, "Book", "Episode"))153 assertEquals(f.files.writes, f.files.deletions)154 assertTrue(f.files.bytes.isEmpty())155 } finally { f.close() }156 }157158 @Test fun screenshotSeedExpiryJoinsCleanupWithoutDispatchingNativeCommand() = runTest {159 val f = Fixture(this)160 val controller = Controller()161 f.files.onWrite = { f.reader.retire() }162 try {163 assertFailsWith<CancellationException> { f.reader.requestScreenshot(controller, "Book", "Episode") }164 assertTrue(controller.commands.isEmpty())165 assertEquals(f.files.writes, f.files.deletions)166 assertTrue(f.files.bytes.isEmpty())167 } finally { f.close() }168 }169170 @Test fun longTitleScreenshotsRetainUniqueSuffixAndFailedShotCannotDeletePriorShot() = runTest {171 val f = Fixture(this)172 val controller = Controller()173 try {174 val title = "Long title ".repeat(30)175 val first = requireNotNull(f.reader.requestScreenshot(controller, title, "Episode"))176 controller.accepted = false177 assertEquals(null, f.reader.requestScreenshot(controller, title, "Episode"))178 val second = f.files.writes.last()179 assertTrue(first != second)180 assertTrue(f.files.bytes.containsKey(first))181 assertEquals(listOf(second), f.files.deletions)182 } finally { f.close() }183 }184185 @Test fun proxyRetirementDuringRegistrationRejectsLateUrl() = runTest {186 val f = Fixture(this)187 f.proxy.onRegister = { f.open = false }188 try {189 assertFailsWith<CancellationException> { f.reader.streamProxy.proxyUrl("https://stream.test", emptyMap()) }190 assertEquals(listOf("https://stream.test"), f.proxy.urls)191 assertFailsWith<CancellationException> { f.reader.streamProxy.proxyUrl("https://late.test", emptyMap()) }192 assertEquals(1, f.proxy.urls.size)193 } finally { f.close() }194 }195196 @Test fun markersUseCapturedHttpAndPreserveAniSkipParsing() = runTest {197 val f = Fixture(this)198 try {199 val result = f.reader.markers(42, 12, 1500)200 assertEquals("op", result.single().type)201 assertEquals(90.0, result.single().endSeconds)202 val request = f.http.requests.single()203 assertTrue("/42/12?" in request.url)204 assertTrue("episodeLength=1500" in request.url)205 assertEquals("application/json", request.headers["Accept"])206 } finally { f.close() }207 }208209 @Test fun canceledMarkerCallerJoinsTransportFinalizer() = runTest {210 val f = Fixture(this)211 val release = CompletableDeferred<Unit>()212 f.http.response = {213 try { awaitCancellation() }214 finally { withContext(NonCancellable) { release.await() } }215 }216 try {217 val call = async { f.reader.markers(42, 1, 0) }218 runCurrent(); call.cancel(); runCurrent()219 assertFalse(call.isCompleted)220 release.complete(Unit); call.join()221 assertTrue(call.isCancelled)222 assertTrue(f.service.isAvailable)223 } finally { release.complete(Unit); f.close() }224 }225226 @Test fun retiringMarkersCannotDeliverLateResponseOrFailureFallback() = runTest {227 val f = Fixture(this)228 val release = CompletableDeferred<Unit>()229 f.http.response = { withContext(NonCancellable) { release.await(); error("late transport failure") } }230 try {231 val call = async { f.reader.markers(42, 1, 0) }232 runCurrent()233 f.open = false234 val close = async { f.service.closeAndJoin() }235 runCurrent()236 assertFalse(close.isCompleted)237 release.complete(Unit); close.await()238 assertFailsWith<CancellationException> { call.await() }239 } finally { release.complete(Unit); f.close() }240 }241242 @Test fun foreignConfigurationIsRejectedBeforeFilesOrNativeCommands() = runTest {243 val f = Fixture(this)244 val foreign = MediaPlayerConfiguration(mpvConfigDirectory = "/B/cache/mpv")245 val controller = Controller()246 try {247 assertFailsWith<IllegalArgumentException> { f.reader.prepareConfiguration(foreign) }248 assertFailsWith<IllegalArgumentException> { f.reader.installCustomButtons(controller, emptyList(), foreign) }249 assertTrue(f.files.writes.isEmpty())250 assertTrue(controller.commands.isEmpty())251 } finally { f.close() }252 }253254 @Test fun retiredReaderRejectsEveryAuxiliaryEntryPoint() = runTest {255 val f = Fixture(this)256 val configuration = f.reader.configuration(DbSettings())257 val controller = Controller()258 try {259 f.reader.closeAndJoin()260 assertFailsWith<CancellationException> { f.reader.configuration(DbSettings()) }261 assertFailsWith<CancellationException> { f.reader.prepareConfiguration(configuration) }262 assertFailsWith<CancellationException> { f.reader.installCustomButtons(controller, emptyList(), configuration) }263 assertFailsWith<CancellationException> { f.reader.markers(42, 1, 0) }264 assertFailsWith<CancellationException> { f.reader.requestScreenshot(controller, "Book", "Episode") }265 assertFailsWith<CancellationException> { f.reader.streamProxy.proxyUrl("https://stream.test", mapOf("Referer" to "A")) }266 assertTrue(f.files.writes.isEmpty())267 assertTrue(f.http.requests.isEmpty())268 assertTrue(f.proxy.urls.isEmpty())269 assertTrue(f.owner.isActive)270 } finally { f.close() }271 }272273 @Test fun stoppingOldProxyHandleCannotStopSiblingOrSharedProxy() = runTest {274 val f = Fixture(this)275 try {276 val current = f.service.reader()277 f.reader.streamProxy.stop()278 assertEquals("proxy:https://stream.test", current.streamProxy.proxyUrl("https://stream.test", mapOf("Referer" to "A")))279 assertEquals(0, f.proxy.stops)280 assertFailsWith<CancellationException> { f.reader.streamProxy.proxyUrl("https://late.test", emptyMap()) }281 } finally { f.close() }282 }283284 @Test fun independentServicesKeepTheirOwnFilesAndProxyAndPreserveParentsOnClose() = runTest {285 val a = Fixture(this, "A")286 val b = Fixture(this, "B")287 try {288 a.reader.prepareConfiguration(a.reader.configuration(DbSettings()))289 b.reader.prepareConfiguration(b.reader.configuration(DbSettings()))290 a.service.closeAndJoin()291 assertTrue(a.owner.isActive)292 assertFailsWith<CancellationException> { a.reader.configuration(DbSettings()) }293 assertEquals("/B/cache/mpv", b.reader.configuration(DbSettings()).mpvConfigDirectory)294 assertEquals("proxy:B", b.reader.streamProxy.proxyUrl("B", emptyMap()))295 assertTrue(a.files.writes.all { it.startsWith("/A/") })296 assertTrue(b.files.writes.all { it.startsWith("/B/") })297 } finally { a.close(); b.close() }298 }299300 internal class Fixture(test: TestScope, label: String = "A", dispatcher: CoroutineDispatcher = StandardTestDispatcher(test.testScheduler),301 factory: (MediaPlayerConfiguration, MediaStreamProxy) -> MediaPlayerController = ::createMediaPlayerController) {302 val owner = SupervisorJob()303 var open = true304 val files = Files(label)305 val http = Http()306 val proxy = Proxy()307 val service = ProfilePlayerServices(ProfileId.Default, files, AniSkipService(http), proxy,308 CoroutineScope(owner + StandardTestDispatcher(test.testScheduler)), dispatcher, factory) { open }309 val reader = service.reader()310 suspend fun close() { service.closeAndJoin(); owner.cancelAndJoin() }311 }312 internal class Files(label: String) : LocalFileService {313 override val downloadRoot = "/$label/downloads"314 override val backupRoot = "/$label/backups"315 override val cacheRoot = "/$label/cache"316 val bytes = mutableMapOf<String, ByteArray>()317 val writes = mutableListOf<String>()318 val deletions = mutableListOf<String>()319 val existsReads = mutableListOf<String>()320 var onWrite: (String) -> Unit = { }321 var onExists: (String) -> Unit = { }322 override fun writeBytes(path: String, bytes: ByteArray) { writes += path; this.bytes[path] = bytes; onWrite(path) }323 override fun exists(path: String): Boolean { existsReads += path; onExists(path); return bytes.containsKey(path) }324 override fun deleteRecursively(path: String): Boolean { deletions += path; return bytes.remove(path) != null }325 override fun readBytes(path: String) = bytes.getValue(path)326 override fun canonicalPath(path: String): String = path327 override fun directorySize(path: String): Long = 0328 override fun openLocation(path: String): Boolean = false329 override fun listLocalEntries(root: String): List<LocalEntry> = emptyList()330 override fun listFiles(root: String): List<LocalFileEntry> = emptyList()331 }332 internal class Http : HttpService {333 val requests = mutableListOf<HttpRequest>()334 var response: suspend () -> HttpResponse = {335 HttpResponse(statusCode = 200, body = """{"found":true,"results":[{"skipType":"op","interval":{"startTime":0,"endTime":90},"episodeLength":1500}]}""")336 }337 override suspend fun request(request: HttpRequest): HttpResponse { requests += request; return response() }338 }339 internal class Proxy : MediaStreamProxy {340 val urls = mutableListOf<String>()341 var stops = 0342 var onRegister: () -> Unit = { }343 override fun proxyUrl(url: String, headers: Map<String, String>): String { urls += url; onRegister(); return "proxy:$url" }344 override fun stop() { stops++ }345 }346 internal class Controller : MediaPlayerController {347 override val isMpvBackend = true348 val commands = mutableListOf<List<String>>()349 var accepted = true350 var onCommand: () -> Unit = { }351 var onAwaitedCommand: suspend (List<String>) -> Boolean = { true }352 override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) = Unit353 override fun play() = Unit354 override fun pause() = Unit355 override fun seekTo(positionMs: Long) = Unit356 override fun setPlaybackSpeed(speed: Float) = Unit357 override fun executeMpvCommand(vararg arguments: String): Boolean { commands += arguments.toList(); onCommand(); return accepted }358 override suspend fun executeMpvCommandAndJoin(vararg arguments: String): Boolean =359 executeMpvCommand(*arguments) && onAwaitedCommand(arguments.toList())360 override fun release() = Unit361 override fun currentPositionMs(): Long = 0362 override fun durationMs(): Long = 0363 override fun isPlaying(): Boolean = false364 }365}366