package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.services.files.* import eu.friedcutlet.yokan.services.media.VideoFrameExtractor import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlin.test.* @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) class LocalVideoArtworkTest { @Test fun framesAreDecodedOnceAndCachedByPathSizeAndModificationTime() = runTest { val f = Fixture() val title = f.title() val first = f.episode(title, "Episode 1.mkv", 1.0) val second = f.episode(title, "Episode 2.mp4", 2.0) assertTrue(f.artwork().generate()) assertEquals(listOf("file:///anime/Show/Episode 1.mkv", "file:///anime/Show/Episode 2.mp4"), f.decoded) assertEquals(setOf(LocalVideoArtwork.MaxFrameDimension), f.dimensions.toSet()) assertContentEquals(f.frameFor("file:///anime/Show/Episode 1.mkv"), f.db.manga(title.id)?.customCoverImage) val thumbnails = listOf(first, second).map { assertNotNull(f.db.chapter(it.id)?.thumbnailUrl) } assertTrue(thumbnails.all { it.startsWith("file:///downloads/.yokan-artwork/") && it.endsWith(".jpg") }) assertContentEquals(f.frameFor("file:///anime/Show/Episode 2.mp4"), f.files.data.getValue(thumbnails[1].removePrefix("file://"))) // A cleared and rescanned library reuses the cache instead of decoding again, even in a new session. f.db.upsertManga(f.db.manga(title.id)!!.copy(customCoverImage = null)) listOf(first, second).forEach { f.db.upsertChapter(f.db.chapter(it.id)!!.copy(thumbnailUrl = null)) } f.artwork().generate() assertEquals(2, f.decoded.size) assertEquals(thumbnails, listOf(first, second).map { f.db.chapter(it.id)?.thumbnailUrl }) assertNotNull(f.db.manga(title.id)?.customCoverImage) // A replaced file is a different cache entry. f.files.modified["/anime/Show/Episode 2.mp4"] = 99L f.db.upsertChapter(f.db.chapter(second.id)!!.copy(thumbnailUrl = null)) f.artwork().generate() assertEquals(3, f.decoded.size) assertNotEquals(thumbnails[1], f.db.chapter(second.id)?.thumbnailUrl) } @Test fun runsAreBoundedAndTheNextRunContinues() = runTest { val f = Fixture() val title = f.title(imageUrl = "https://cover") val episodes = (1..5).map { f.episode(title, "Episode $it.mp4", it.toDouble()) } val artwork = f.artwork(maxDecodes = 2) artwork.generate() assertEquals(2, f.decoded.size) artwork.generate() artwork.generate() assertEquals(5, f.decoded.size) assertTrue(episodes.all { f.db.chapter(it.id)?.thumbnailUrl != null }) assertEquals("https://cover", f.db.manga(title.id)?.imageUrl) assertNull(f.db.manga(title.id)?.customCoverImage) } @Test fun failedEmptyAndOversizedFramesStoreNothingAndAreNotRetriedThisSession() = runTest { val f = Fixture() val title = f.title() val episodes = listOf("Broken.mp4", "Empty.mp4", "Huge.mp4").mapIndexed { index, name -> f.episode(title, name, index + 1.0) } f.extract = { url -> when { "Broken" in url -> error("decoder failed") "Empty" in url -> null else -> ByteArray(LocalVideoArtwork.MaxFrameBytes + 1) } } val artwork = f.artwork() artwork.generate() artwork.generate() assertEquals(3, f.decoded.size) assertTrue(f.cacheFiles().isEmpty()) assertTrue(episodes.all { f.db.chapter(it.id)?.thumbnailUrl == null }) assertNull(f.db.manga(title.id)?.customCoverImage) } @Test fun existingCoversPreviewsAndNonLocalTitlesAreNeverTouched() = runTest { val f = Fixture() val picked = f.title(name = "Picked", cover = byteArrayOf(7)) val metadata = f.title(name = "Metadata", imageUrl = "file:///anime/Metadata/poster.png") val tracker = f.title(name = "Tracker", trackerCover = "https://tracker") listOf(picked, metadata, tracker).forEach { f.episode(it, "Episode 1.mp4", 1.0, thumbnail = "file:///sidecar.png") } val remote = f.db.upsertManga(DbManga(name = "Remote", itemType = DbItemType.Anime, source = "Some source")) f.episode(remote, "Episode 1.mp4", 1.0) val manga = f.db.upsertManga(DbManga(name = "Comic", itemType = DbItemType.Manga, isLocalArchive = true, source = "local")) f.episode(manga, "Episode 1.mp4", 1.0) val missingPreview = f.episode(picked, "Episode 2.mp4", 2.0) f.artwork().generate() assertEquals(listOf("file:///anime/Picked/Episode 2.mp4"), f.decoded) assertNotNull(f.db.chapter(missingPreview.id)?.thumbnailUrl) assertContentEquals(byteArrayOf(7), f.db.manga(picked.id)?.customCoverImage) assertNull(f.db.manga(metadata.id)?.customCoverImage) assertNull(f.db.manga(tracker.id)?.customCoverImage) assertNull(f.db.manga(remote.id)?.customCoverImage) assertTrue(f.db.chapters().filter { it.id != missingPreview.id && it.mangaId in setOf(picked.id, metadata.id, tracker.id) } .all { it.thumbnailUrl == "file:///sidecar.png" }) assertTrue(f.db.chapters().filter { it.mangaId in setOf(remote.id, manga.id) }.all { it.thumbnailUrl == null }) } @Test fun editsAndScansDuringDecodingWin() = runTest { val f = Fixture() val title = f.title() val episode = f.episode(title, "Episode 1.mp4", 1.0) val entered = CompletableDeferred() val release = CompletableDeferred() f.extract = { url -> entered.complete(Unit); release.await(); f.frameFor(url) } val artwork = f.artwork() val run = async { artwork.generate() } entered.await() assertFalse(artwork.generate(), "a second run must not start while one is decoding") // The user picks a cover; a scan holding the library lock adds a sidecar preview. f.db.upsertManga(f.db.manga(title.id)!!.copy(customCoverImage = byteArrayOf(1))) f.library.lock.lock() release.complete(Unit) runCurrent() assertNull(f.db.chapter(episode.id)?.thumbnailUrl, "artwork must wait for the running scan") f.db.upsertChapter(f.db.chapter(episode.id)!!.copy(thumbnailUrl = "file:///anime/Show/preview.png")) f.library.lock.unlock() assertTrue(run.await()) assertContentEquals(byteArrayOf(1), f.db.manga(title.id)?.customCoverImage) assertEquals("file:///anime/Show/preview.png", f.db.chapter(episode.id)?.thumbnailUrl) } @Test fun cancellationLeavesNoPartialCacheFileAndARetrySucceeds() = runTest { val f = Fixture() val title = f.title() val episode = f.episode(title, "Episode 1.mp4", 1.0) val decoding = CompletableDeferred() f.extract = { decoding.complete(Unit); CompletableDeferred().await(); null } val duringDecode = async { f.artwork().generate() } decoding.await() duringDecode.cancelAndJoin() assertTrue(f.cacheFiles().isEmpty()) val written = CompletableDeferred() f.extract = { url -> f.frameFor(url) } f.files.afterWrite = { path -> if (path.endsWith(".part")) { written.complete(Unit); CompletableDeferred().await() } } val duringWrite = async { f.artwork().generate() } written.await() duringWrite.cancelAndJoin() assertTrue(f.cacheFiles().isEmpty(), "a partially written frame must be removed: ${f.cacheFiles()}") assertNull(f.db.chapter(episode.id)?.thumbnailUrl) assertNull(f.db.manga(title.id)?.customCoverImage) f.files.afterWrite = {} f.artwork().generate() assertEquals(1, f.cacheFiles().size) assertNotNull(f.db.chapter(episode.id)?.thumbnailUrl) assertNotNull(f.db.manga(title.id)?.customCoverImage) } @Test fun seasonsParentUsesItsFirstSeasonFrame() = runTest { val f = Fixture() val parent = f.title(name = "Show") val season = f.db.upsertManga(f.db.manga(f.title(name = "Show/Season 1").id)!!.copy(parentId = parent.id)) f.episode(season, "Episode 1.mp4", 1.0) f.artwork().generate() assertEquals(1, f.decoded.size) val frame = f.frameFor("file:///anime/Show/Season 1/Episode 1.mp4") assertContentEquals(frame, f.db.manga(parent.id)?.customCoverImage) assertContentEquals(frame, f.db.manga(season.id)?.customCoverImage) } private class Fixture { val files = MemoryVideoFiles() val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", "/anime"))))) val library = LockingLibrary() val decoded = mutableListOf() val dimensions = mutableListOf() var extract: suspend (String) -> ByteArray? = { frameFor(it) } fun frameFor(url: String) = "frame:$url".encodeToByteArray() fun artwork(maxDecodes: Int = 12) = LocalVideoArtwork(db, files, library, VideoFrameExtractor { url, maxDimension -> decoded += url dimensions += maxDimension extract(url) }, maxDecodes) fun cacheFiles() = files.data.keys.filter { it.startsWith("/downloads/.yokan-artwork/") } fun title(name: String = "Show", cover: ByteArray? = null, imageUrl: String? = null, trackerCover: String? = null) = db.upsertManga(DbManga( name = name, link = "Anime/$name", itemType = DbItemType.Anime, isLocalArchive = true, source = "local", customCoverImage = cover, imageUrl = imageUrl, customCoverFromTracker = trackerCover, )) fun episode(title: DbManga, file: String, number: Double, thumbnail: String? = null): DbChapter { files.put("/anime/${title.name}/$file") return db.upsertChapter(DbChapter( mangaId = title.id, name = file, url = "Anime/${title.name}/$file", archivePath = "Anime/${title.name}/$file", number = number, thumbnailUrl = thumbnail, )) } } private class LockingLibrary : LocalLibraryService { val lock = Mutex() override suspend fun withOperationLock(block: suspend () -> T): T = lock.withLock { block() } override suspend fun scan(): LocalLibraryScanResult = error("Not scanned here") override suspend fun reconcile(): LocalLibraryReconciliationResult = error("Not reconciled here") override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? = null } } /** A small in-memory filesystem with the immediate-child listing semantics of the native services. */ internal class MemoryVideoFiles : LocalFileService { override val downloadRoot = "/downloads" override val backupRoot = "/backups" override val cacheRoot = "/cache" val data = linkedMapOf() val modified = mutableMapOf() var afterWrite: suspend (String) -> Unit = {} fun put(path: String, bytes: ByteArray = byteArrayOf(1)) { data[path] = bytes } private fun children(root: String): List = data.keys.mapNotNull { path -> path.removePrefix("$root/").takeIf { path.startsWith("$root/") }?.substringBefore('/')?.let { "$root/$it" } }.distinct().sorted() private fun isFile(path: String) = path in data private fun isReadable(path: String) = path.substringAfterLast('.').lowercase() in readableLocalFileExtensions override fun writeBytes(path: String, bytes: ByteArray) { data[path] = bytes } override suspend fun writeBytesAsync(path: String, bytes: ByteArray) { writeBytes(path, bytes); afterWrite(path) } override fun readBytes(path: String): ByteArray = data[path] ?: error("Missing $path") override fun canonicalPath(path: String) = path override fun exists(path: String) = path in data || data.keys.any { it.startsWith("$path/") } override fun deleteRecursively(path: String): Boolean { data.keys.removeAll { it == path || it.startsWith("$path/") }; return true } override fun directorySize(path: String) = 0L override fun openLocation(path: String) = false override fun listLocalEntries(root: String): List? { if (!exists(root)) return null return children(root).flatMap { child -> when { isFile(child) -> if (isReadable(child)) listOf(LocalEntry(child, child.substringAfterLast('/').substringBeforeLast('.'), true)) else emptyList() children(child).any { isFile(it) && isReadable(it) } -> listOf(LocalEntry(child, child.substringAfterLast('/'), false)) else -> listLocalEntries(child).orEmpty() } } } override fun listDirectoryEntries(root: String): List? = if (!exists(root) || isFile(root)) null else children(root).map { LocalDirectoryEntry(it, it.substringAfterLast('/'), !isFile(it)) } override fun listFiles(root: String) = children(root).filter(::isFile) .map { LocalFileEntry(it, it.substringAfterLast('/'), data.getValue(it).size.toLong(), modified[it] ?: 1L) } }