LocalVideoArtworkTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalVideoArtworkTest.kt
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.database.*4import eu.friedcutlet.yokan.domain.Chapter5import eu.friedcutlet.yokan.services.files.*6import eu.friedcutlet.yokan.services.media.VideoFrameExtractor7import kotlinx.coroutines.CompletableDeferred8import kotlinx.coroutines.async9import kotlinx.coroutines.cancelAndJoin10import kotlinx.coroutines.sync.Mutex11import kotlinx.coroutines.sync.withLock12import kotlinx.coroutines.test.runCurrent13import kotlinx.coroutines.test.runTest14import kotlin.test.*1516@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)17class LocalVideoArtworkTest {18 @Test fun framesAreDecodedOnceAndCachedByPathSizeAndModificationTime() = runTest {19 val f = Fixture()20 val title = f.title()21 val first = f.episode(title, "Episode 1.mkv", 1.0)22 val second = f.episode(title, "Episode 2.mp4", 2.0)23 assertTrue(f.artwork().generate())24 assertEquals(listOf("file:///anime/Show/Episode 1.mkv", "file:///anime/Show/Episode 2.mp4"), f.decoded)25 assertEquals(setOf(LocalVideoArtwork.MaxFrameDimension), f.dimensions.toSet())26 assertContentEquals(f.frameFor("file:///anime/Show/Episode 1.mkv"), f.db.manga(title.id)?.customCoverImage)27 val thumbnails = listOf(first, second).map { assertNotNull(f.db.chapter(it.id)?.thumbnailUrl) }28 assertTrue(thumbnails.all { it.startsWith("file:///downloads/.yokan-artwork/") && it.endsWith(".jpg") })29 assertContentEquals(f.frameFor("file:///anime/Show/Episode 2.mp4"), f.files.data.getValue(thumbnails[1].removePrefix("file://")))3031 // A cleared and rescanned library reuses the cache instead of decoding again, even in a new session.32 f.db.upsertManga(f.db.manga(title.id)!!.copy(customCoverImage = null))33 listOf(first, second).forEach { f.db.upsertChapter(f.db.chapter(it.id)!!.copy(thumbnailUrl = null)) }34 f.artwork().generate()35 assertEquals(2, f.decoded.size)36 assertEquals(thumbnails, listOf(first, second).map { f.db.chapter(it.id)?.thumbnailUrl })37 assertNotNull(f.db.manga(title.id)?.customCoverImage)3839 // A replaced file is a different cache entry.40 f.files.modified["/anime/Show/Episode 2.mp4"] = 99L41 f.db.upsertChapter(f.db.chapter(second.id)!!.copy(thumbnailUrl = null))42 f.artwork().generate()43 assertEquals(3, f.decoded.size)44 assertNotEquals(thumbnails[1], f.db.chapter(second.id)?.thumbnailUrl)45 }4647 @Test fun runsAreBoundedAndTheNextRunContinues() = runTest {48 val f = Fixture()49 val title = f.title(imageUrl = "https://cover")50 val episodes = (1..5).map { f.episode(title, "Episode $it.mp4", it.toDouble()) }51 val artwork = f.artwork(maxDecodes = 2)52 artwork.generate()53 assertEquals(2, f.decoded.size)54 artwork.generate()55 artwork.generate()56 assertEquals(5, f.decoded.size)57 assertTrue(episodes.all { f.db.chapter(it.id)?.thumbnailUrl != null })58 assertEquals("https://cover", f.db.manga(title.id)?.imageUrl)59 assertNull(f.db.manga(title.id)?.customCoverImage)60 }6162 @Test fun failedEmptyAndOversizedFramesStoreNothingAndAreNotRetriedThisSession() = runTest {63 val f = Fixture()64 val title = f.title()65 val episodes = listOf("Broken.mp4", "Empty.mp4", "Huge.mp4").mapIndexed { index, name -> f.episode(title, name, index + 1.0) }66 f.extract = { url ->67 when {68 "Broken" in url -> error("decoder failed")69 "Empty" in url -> null70 else -> ByteArray(LocalVideoArtwork.MaxFrameBytes + 1)71 }72 }73 val artwork = f.artwork()74 artwork.generate()75 artwork.generate()76 assertEquals(3, f.decoded.size)77 assertTrue(f.cacheFiles().isEmpty())78 assertTrue(episodes.all { f.db.chapter(it.id)?.thumbnailUrl == null })79 assertNull(f.db.manga(title.id)?.customCoverImage)80 }8182 @Test fun existingCoversPreviewsAndNonLocalTitlesAreNeverTouched() = runTest {83 val f = Fixture()84 val picked = f.title(name = "Picked", cover = byteArrayOf(7))85 val metadata = f.title(name = "Metadata", imageUrl = "file:///anime/Metadata/poster.png")86 val tracker = f.title(name = "Tracker", trackerCover = "https://tracker")87 listOf(picked, metadata, tracker).forEach { f.episode(it, "Episode 1.mp4", 1.0, thumbnail = "file:///sidecar.png") }88 val remote = f.db.upsertManga(DbManga(name = "Remote", itemType = DbItemType.Anime, source = "Some source"))89 f.episode(remote, "Episode 1.mp4", 1.0)90 val manga = f.db.upsertManga(DbManga(name = "Comic", itemType = DbItemType.Manga, isLocalArchive = true, source = "local"))91 f.episode(manga, "Episode 1.mp4", 1.0)92 val missingPreview = f.episode(picked, "Episode 2.mp4", 2.0)93 f.artwork().generate()94 assertEquals(listOf("file:///anime/Picked/Episode 2.mp4"), f.decoded)95 assertNotNull(f.db.chapter(missingPreview.id)?.thumbnailUrl)96 assertContentEquals(byteArrayOf(7), f.db.manga(picked.id)?.customCoverImage)97 assertNull(f.db.manga(metadata.id)?.customCoverImage)98 assertNull(f.db.manga(tracker.id)?.customCoverImage)99 assertNull(f.db.manga(remote.id)?.customCoverImage)100 assertTrue(f.db.chapters().filter { it.id != missingPreview.id && it.mangaId in setOf(picked.id, metadata.id, tracker.id) }101 .all { it.thumbnailUrl == "file:///sidecar.png" })102 assertTrue(f.db.chapters().filter { it.mangaId in setOf(remote.id, manga.id) }.all { it.thumbnailUrl == null })103 }104105 @Test fun editsAndScansDuringDecodingWin() = runTest {106 val f = Fixture()107 val title = f.title()108 val episode = f.episode(title, "Episode 1.mp4", 1.0)109 val entered = CompletableDeferred<Unit>()110 val release = CompletableDeferred<Unit>()111 f.extract = { url -> entered.complete(Unit); release.await(); f.frameFor(url) }112 val artwork = f.artwork()113 val run = async { artwork.generate() }114 entered.await()115 assertFalse(artwork.generate(), "a second run must not start while one is decoding")116 // The user picks a cover; a scan holding the library lock adds a sidecar preview.117 f.db.upsertManga(f.db.manga(title.id)!!.copy(customCoverImage = byteArrayOf(1)))118 f.library.lock.lock()119 release.complete(Unit)120 runCurrent()121 assertNull(f.db.chapter(episode.id)?.thumbnailUrl, "artwork must wait for the running scan")122 f.db.upsertChapter(f.db.chapter(episode.id)!!.copy(thumbnailUrl = "file:///anime/Show/preview.png"))123 f.library.lock.unlock()124 assertTrue(run.await())125 assertContentEquals(byteArrayOf(1), f.db.manga(title.id)?.customCoverImage)126 assertEquals("file:///anime/Show/preview.png", f.db.chapter(episode.id)?.thumbnailUrl)127 }128129 @Test fun cancellationLeavesNoPartialCacheFileAndARetrySucceeds() = runTest {130 val f = Fixture()131 val title = f.title()132 val episode = f.episode(title, "Episode 1.mp4", 1.0)133 val decoding = CompletableDeferred<Unit>()134 f.extract = { decoding.complete(Unit); CompletableDeferred<Unit>().await(); null }135 val duringDecode = async { f.artwork().generate() }136 decoding.await()137 duringDecode.cancelAndJoin()138 assertTrue(f.cacheFiles().isEmpty())139140 val written = CompletableDeferred<Unit>()141 f.extract = { url -> f.frameFor(url) }142 f.files.afterWrite = { path -> if (path.endsWith(".part")) { written.complete(Unit); CompletableDeferred<Unit>().await() } }143 val duringWrite = async { f.artwork().generate() }144 written.await()145 duringWrite.cancelAndJoin()146 assertTrue(f.cacheFiles().isEmpty(), "a partially written frame must be removed: ${f.cacheFiles()}")147 assertNull(f.db.chapter(episode.id)?.thumbnailUrl)148 assertNull(f.db.manga(title.id)?.customCoverImage)149150 f.files.afterWrite = {}151 f.artwork().generate()152 assertEquals(1, f.cacheFiles().size)153 assertNotNull(f.db.chapter(episode.id)?.thumbnailUrl)154 assertNotNull(f.db.manga(title.id)?.customCoverImage)155 }156157 @Test fun seasonsParentUsesItsFirstSeasonFrame() = runTest {158 val f = Fixture()159 val parent = f.title(name = "Show")160 val season = f.db.upsertManga(f.db.manga(f.title(name = "Show/Season 1").id)!!.copy(parentId = parent.id))161 f.episode(season, "Episode 1.mp4", 1.0)162 f.artwork().generate()163 assertEquals(1, f.decoded.size)164 val frame = f.frameFor("file:///anime/Show/Season 1/Episode 1.mp4")165 assertContentEquals(frame, f.db.manga(parent.id)?.customCoverImage)166 assertContentEquals(frame, f.db.manga(season.id)?.customCoverImage)167 }168169 private class Fixture {170 val files = MemoryVideoFiles()171 val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", "/anime")))))172 val library = LockingLibrary()173 val decoded = mutableListOf<String>()174 val dimensions = mutableListOf<Int>()175 var extract: suspend (String) -> ByteArray? = { frameFor(it) }176 fun frameFor(url: String) = "frame:$url".encodeToByteArray()177 fun artwork(maxDecodes: Int = 12) = LocalVideoArtwork(db, files, library, VideoFrameExtractor { url, maxDimension ->178 decoded += url179 dimensions += maxDimension180 extract(url)181 }, maxDecodes)182 fun cacheFiles() = files.data.keys.filter { it.startsWith("/downloads/.yokan-artwork/") }183 fun title(name: String = "Show", cover: ByteArray? = null, imageUrl: String? = null, trackerCover: String? = null) = db.upsertManga(DbManga(184 name = name, link = "Anime/$name", itemType = DbItemType.Anime, isLocalArchive = true, source = "local",185 customCoverImage = cover, imageUrl = imageUrl, customCoverFromTracker = trackerCover,186 ))187 fun episode(title: DbManga, file: String, number: Double, thumbnail: String? = null): DbChapter {188 files.put("/anime/${title.name}/$file")189 return db.upsertChapter(DbChapter(190 mangaId = title.id, name = file, url = "Anime/${title.name}/$file", archivePath = "Anime/${title.name}/$file",191 number = number, thumbnailUrl = thumbnail,192 ))193 }194 }195196 private class LockingLibrary : LocalLibraryService {197 val lock = Mutex()198 override suspend fun <T> withOperationLock(block: suspend () -> T): T = lock.withLock { block() }199 override suspend fun scan(): LocalLibraryScanResult = error("Not scanned here")200 override suspend fun reconcile(): LocalLibraryReconciliationResult = error("Not reconciled here")201 override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? = null202 }203}204205/** A small in-memory filesystem with the immediate-child listing semantics of the native services. */206internal class MemoryVideoFiles : LocalFileService {207 override val downloadRoot = "/downloads"208 override val backupRoot = "/backups"209 override val cacheRoot = "/cache"210 val data = linkedMapOf<String, ByteArray>()211 val modified = mutableMapOf<String, Long>()212 var afterWrite: suspend (String) -> Unit = {}213214 fun put(path: String, bytes: ByteArray = byteArrayOf(1)) { data[path] = bytes }215 private fun children(root: String): List<String> = data.keys.mapNotNull { path ->216 path.removePrefix("$root/").takeIf { path.startsWith("$root/") }?.substringBefore('/')?.let { "$root/$it" }217 }.distinct().sorted()218 private fun isFile(path: String) = path in data219 private fun isReadable(path: String) = path.substringAfterLast('.').lowercase() in readableLocalFileExtensions220221 override fun writeBytes(path: String, bytes: ByteArray) { data[path] = bytes }222 override suspend fun writeBytesAsync(path: String, bytes: ByteArray) { writeBytes(path, bytes); afterWrite(path) }223 override fun readBytes(path: String): ByteArray = data[path] ?: error("Missing $path")224 override fun canonicalPath(path: String) = path225 override fun exists(path: String) = path in data || data.keys.any { it.startsWith("$path/") }226 override fun deleteRecursively(path: String): Boolean { data.keys.removeAll { it == path || it.startsWith("$path/") }; return true }227 override fun directorySize(path: String) = 0L228 override fun openLocation(path: String) = false229 override fun listLocalEntries(root: String): List<LocalEntry>? {230 if (!exists(root)) return null231 return children(root).flatMap { child ->232 when {233 isFile(child) -> if (isReadable(child)) listOf(LocalEntry(child, child.substringAfterLast('/').substringBeforeLast('.'), true)) else emptyList()234 children(child).any { isFile(it) && isReadable(it) } -> listOf(LocalEntry(child, child.substringAfterLast('/'), false))235 else -> listLocalEntries(child).orEmpty()236 }237 }238 }239 override fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? =240 if (!exists(root) || isFile(root)) null else children(root).map { LocalDirectoryEntry(it, it.substringAfterLast('/'), !isFile(it)) }241 override fun listFiles(root: String) = children(root).filter(::isFile)242 .map { LocalFileEntry(it, it.substringAfterLast('/'), data.getValue(it).size.toLong(), modified[it] ?: 1L) }243}244