Yokan / rebuild
Course 1 8624561

LocalMediaImporterTest.kt

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalMediaImporterTest.kt

test / fixture219 lines
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.data.DefaultYokanRepository4import eu.friedcutlet.yokan.data.SettingsStore5import eu.friedcutlet.yokan.database.*6import eu.friedcutlet.yokan.services.files.*7import kotlinx.coroutines.*8import kotlinx.coroutines.test.runTest9import kotlin.test.*10import eu.friedcutlet.yokan.services.files.effectiveLocalLibraryFolders1112class LocalMediaImporterTest {13    @Test fun copiesAreHiddenUntilCompleteAndPublicationPreservesConcurrentSettings() = runTest {14        val files = ImportFiles()15        val db = InMemoryYokanDatabase(emptySnapshot())16        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}17        val started = CompletableDeferred<Unit>()18        val resume = CompletableDeferred<Unit>()19        val source = Input("Show/Episode 1.mp4", byteArrayOf(1, 2)) {20            started.complete(Unit); resume.await()21        }22        val importer = LocalMediaImporter(files, settings, newId = { "one" })23        val work = async { importer.import(LocalMediaSelection(listOf(source, Input("Show/metadata.json", "{}".encodeToByteArray()))), DbItemType.Anime) }24        started.await()25        assertTrue(settings.db.value.configuredLocalFolders().isEmpty())26        assertTrue(effectiveLocalLibraryFolders(settings.db.value, files).none { "local-imports" in it.path })27        settings.updateDb { it.copy(themeIsDark = true) }28        resume.complete(Unit)29        val folder = work.await()30        assertEquals("Show", folder.name)31        assertEquals("/downloads/local-imports/one/anime", folder.path)32        assertContentEquals(byteArrayOf(1, 2), files.bytes["${folder.path}/Show/Episode 1.mp4"])33        assertTrue(settings.db.value.themeIsDark)34        assertEquals(listOf(folder), settings.db.value.configuredLocalFolders())35        assertTrue(importer.pending().isEmpty())36        assertTrue(files.maxChunk <= LOCAL_IMPORT_CHUNK_BYTES)37    }3839    @Test fun cancellationAndChangedSourcesRemoveOnlyUnpublishedCopies() = runTest {40        val files = ImportFiles().apply { bytes["/source/original.mp4"] = byteArrayOf(7) }41        val db = InMemoryYokanDatabase(emptySnapshot())42        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}43        val importer = LocalMediaImporter(files, settings, newId = { "cancel" })44        val source = Input("clip.mp4", byteArrayOf(1)) { throw CancellationException("Cancelled") }45        assertFailsWith<CancellationException> { importer.import(LocalMediaSelection(listOf(source)), DbItemType.Anime) }46        assertEquals(setOf("/source/original.mp4"), files.bytes.keys)47        val changed = Input("clip.mp4", byteArrayOf(1), announcedSize = 2)48        assertFailsWith<IllegalStateException> { importer.import(LocalMediaSelection(listOf(changed)), DbItemType.Anime) }49        assertEquals(setOf("/source/original.mp4"), files.bytes.keys)50        assertTrue(settings.db.value.configuredLocalFolders().isEmpty())51    }5253    @Test fun readyJournalSurvivesSaveFailureAndRecoveryIsIdempotent() = runTest {54        val files = ImportFiles()55        val db = InMemoryYokanDatabase(emptySnapshot())56        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}57        val importer = LocalMediaImporter(files, settings, persistSettings = { error("Disk save failed") }, newId = { "ready" })58        assertFailsWith<IllegalStateException> { importer.import(LocalMediaSelection(listOf(Input("book.epub", byteArrayOf(8)))), DbItemType.Novel) }59        val journal = importer.pending().single()60        assertEquals(LocalImportPhase.Ready, journal.phase)61        assertFailsWith<IllegalArgumentException> { importer.discardIncomplete(journal.id) }62        val content = settings.db.value.configuredLocalFolders().single().path63        assertContentEquals(byteArrayOf(8), files.bytes["$content/book.epub"])64        // Simulate restart before the settings write reached disk.65        settings.updateDb { it.copy(namedLocalFolders = emptyList()) }66        val reopened = LocalMediaImporter(files, settings)67        val recovered = reopened.recover(journal.id)68        assertEquals(content, recovered.path)69        assertEquals(1, settings.db.value.configuredLocalFolders().size)70        assertTrue(reopened.pending().isEmpty())71    }7273    @Test fun recoveryRejectsMissingFilesAndNeverDeletesCompletedContent() = runTest {74        val files = ImportFiles()75        val db = InMemoryYokanDatabase(emptySnapshot())76        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}77        val importer = LocalMediaImporter(files, settings, persistSettings = { error("Save failed") }, newId = { "changed" })78        assertFails { importer.import(LocalMediaSelection(listOf(Input("chapter.cbz", byteArrayOf(1)))), DbItemType.Manga) }79        files.bytes.remove("/downloads/local-imports/changed/manga/chapter.cbz")80        assertFailsWith<IllegalStateException> { LocalMediaImporter(files, settings).recover("changed") }81        assertEquals(LocalImportPhase.Ready, importer.pending().single().phase)82    }8384    @Test fun incompleteRecoveryCannotDeleteConfiguredRootsOrEscapeItsProfile() = runTest {85        val files = ImportFiles()86        val db = InMemoryYokanDatabase(emptySnapshot())87        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}88        val journal = PendingLocalImport("partial", "Title", DbItemType.Manga)89        files.writeBytes("/downloads/local-imports/partial.json", DatabaseJson.encodeToString(journal).encodeToByteArray())90        files.writeBytes("/downloads/local-imports/partial/manga/title.cbz", byteArrayOf(1))91        // Malformed or mismatched journals never authorize deletion.92        files.writeBytes("/downloads/local-imports/evil.json", DatabaseJson.encodeToString(journal.copy(id = "../outside")).encodeToByteArray())93        val importer = LocalMediaImporter(files, settings)94        assertEquals(listOf(journal), importer.pending())95        settings.updateDb { it.copy(namedLocalFolders = listOf(DbLocalFolder("Owned", "/downloads/local-imports/partial/manga"))) }96        assertFailsWith<IllegalArgumentException> { importer.discardIncomplete("partial") }97        assertTrue(files.exists("/downloads/local-imports/partial/manga/title.cbz"))98        settings.updateDb { it.copy(namedLocalFolders = emptyList()) }99        importer.discardIncomplete("partial")100        assertFalse(files.exists("/downloads/local-imports/partial"))101        assertTrue(files.exists("/downloads/local-imports/evil.json"))102    }103104    @Test fun unsafeOrConflictingNamesAreRejectedBeforeAnySourceRead() = runTest {105        val files = ImportFiles()106        val db = InMemoryYokanDatabase(emptySnapshot())107        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}108        for (names in listOf(listOf("../title.mp4"), listOf("/title.mp4"), listOf("folder\\title.mp4"),109            listOf("Title.mp4", "title.mp4"), listOf("title.mp4", "title.mp4/child.mp4"))) {110            val inputs = names.map { Input(it, byteArrayOf(1)) { error("Must not read") } }111            assertFailsWith<IllegalArgumentException> { LocalMediaImporter(files, settings).import(LocalMediaSelection(inputs), DbItemType.Anime) }112            assertTrue(files.bytes.isEmpty())113        }114    }115116    @Test fun repeatedNamesGetUniqueFoldersAndNoExistingMediaIsOverwritten() = runTest {117        val files = ImportFiles()118        val db = InMemoryYokanDatabase(emptySnapshot())119        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}120        for (id in listOf("first", "second")) LocalMediaImporter(files, settings, newId = { id }).import(121            LocalMediaSelection(listOf(Input("book.epub", byteArrayOf(id.length.toByte())))), DbItemType.Novel)122        val folders = settings.db.value.configuredLocalFolders()123        assertEquals(2, folders.map { it.name }.toSet().size)124        assertEquals(2, folders.map { it.path }.toSet().size)125        assertContentEquals(byteArrayOf(5), files.bytes["${folders[0].path}/book.epub"])126        assertContentEquals(byteArrayOf(6), files.bytes["${folders[1].path}/book.epub"])127    }128129    @Test fun progressCoalescesBurstsButAlwaysReportsTheCompletedByteAndFileCount() = runTest {130        val files = ImportFiles()131        val db = InMemoryYokanDatabase(emptySnapshot())132        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}133        val updates = mutableListOf<LocalImportProgress>()134        val source = object : LocalMediaInput {135            override val relativePath = "clip.mp4"136            override val sizeBytes = 1000L137            override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { repeat(1000) { consume(byteArrayOf(1)) } }138        }139        LocalMediaImporter(files, settings, progressClockMillis = { 0 }).import(LocalMediaSelection(listOf(source)), DbItemType.Anime, updates::add)140        assertEquals(listOf(LocalImportProgress(0, 1, 0), LocalImportProgress(1, 1, 1000)), updates)141    }142143    @Test fun redirectedImportRootsCannotWriteOrDeleteOriginalFiles() = runTest {144        val files = ImportFiles()145        val db = InMemoryYokanDatabase(emptySnapshot())146        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}147        val importer = LocalMediaImporter(files, settings, newId = { "redirected" })148        files.resolveCanonical = { path -> if (path.startsWith("/downloads/local-imports")) path.replace("/downloads/local-imports", "/originals") else path }149        assertFailsWith<IllegalArgumentException> { importer.import(LocalMediaSelection(listOf(Input("chapter.cbz", byteArrayOf(1)))), DbItemType.Manga) }150        assertTrue(files.bytes.isEmpty())151        files.resolveCanonical = { it }152        val journal = PendingLocalImport("redirected", "Title", DbItemType.Manga)153        files.writeBytes("/downloads/local-imports/redirected.json", DatabaseJson.encodeToString(journal).encodeToByteArray())154        files.writeBytes("/downloads/local-imports/redirected/manga/chapter.cbz", byteArrayOf(1))155        files.resolveCanonical = { path -> if (path.startsWith("/downloads/local-imports/redirected/")) path.replace("/downloads/local-imports/redirected", "/originals")156            else if (path == "/downloads/local-imports/redirected") "/originals" else path }157        assertFailsWith<IllegalArgumentException> { importer.discardIncomplete("redirected") }158        assertContentEquals(byteArrayOf(1), files.bytes["/downloads/local-imports/redirected/manga/chapter.cbz"])159    }160161    @Test fun recoveringAnAlreadyPublishedReadyCopyKeepsItsOriginalFolderName() = runTest {162        val files = ImportFiles()163        val db = InMemoryYokanDatabase(emptySnapshot())164        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}165        val importer = LocalMediaImporter(files, settings, persistSettings = { error("Save failed") })166        assertFails { importer.import(LocalMediaSelection(listOf(Input("book.epub", byteArrayOf(1)))), DbItemType.Novel) }167        val before = settings.db.value.configuredLocalFolders().single()168        val pending = importer.pending().single()169        assertEquals(before, LocalMediaImporter(files, settings).recover(pending.id))170        assertEquals(listOf(before), settings.db.value.configuredLocalFolders())171    }172173    @Test fun redirectionDuringCopyStopsNewWritesAndNeverAuthorizesCleanup() = runTest {174        val files = ImportFiles()175        val db = InMemoryYokanDatabase(emptySnapshot())176        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}177        val first = Input("first.mp4", byteArrayOf(1)) {178            files.resolveCanonical = { path -> if (path.startsWith("/downloads/local-imports")) path.replace("/downloads/local-imports", "/originals") else path }179        }180        val second = Input("second.mp4", byteArrayOf(2)) { error("Must not read after redirection") }181        assertFailsWith<IllegalArgumentException> {182            LocalMediaImporter(files, settings, newId = { "moving" }).import(LocalMediaSelection(listOf(first, second)), DbItemType.Anime)183        }184        assertTrue(files.exists("/downloads/local-imports/moving.json"))185        assertTrue(files.exists("/downloads/local-imports/moving/anime/first.mp4"))186        assertFalse(files.exists("/downloads/local-imports/moving/anime/second.mp4"))187        assertTrue(settings.db.value.configuredLocalFolders().isEmpty())188    }189}190191private class Input(192    override val relativePath: String,193    private val bytes: ByteArray,194    override val sizeBytes: Long? = bytes.size.toLong(),195    private val beforeRead: suspend () -> Unit = {},196) : LocalMediaInput {197    constructor(path: String, bytes: ByteArray, announcedSize: Long) : this(path, bytes, announcedSize, {})198    override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { beforeRead(); consume(bytes) }199}200201private class ImportFiles : LocalFileService {202    override val downloadRoot = "/downloads"203    override val backupRoot = "/backups"204    override val cacheRoot = "/cache"205    val bytes = mutableMapOf<String, ByteArray>()206    var resolveCanonical: (String) -> String? = { it }207    var maxChunk = 0208    override fun writeBytes(path: String, bytes: ByteArray) { this.bytes[path] = bytes.copyOf() }209    override fun appendBytes(path: String, bytes: ByteArray) { maxChunk = maxOf(maxChunk, bytes.size); this.bytes[path] = this.bytes[path].orEmptyBytes() + bytes }210    override fun readBytes(path: String): ByteArray = bytes[path] ?: error("Missing file")211    override fun canonicalPath(path: String) = resolveCanonical(path)212    override fun exists(path: String) = bytes.keys.any { it == path || it.startsWith("$path/") }213    override fun deleteRecursively(path: String): Boolean { bytes.keys.filter { it == path || it.startsWith("$path/") }.forEach(bytes::remove); return true }214    override fun directorySize(path: String) = bytes.filterKeys { it == path || it.startsWith("$path/") }.values.sumOf { it.size.toLong() }215    override fun openLocation(path: String) = false216    override fun listLocalEntries(root: String): List<LocalEntry>? = emptyList()217    override fun listFiles(root: String) = bytes.filterKeys { it.substringBeforeLast('/') == root }.map { (path, data) -> LocalFileEntry(path, path.substringAfterLast('/'), data.size.toLong(), 1) }218    private fun ByteArray?.orEmptyBytes() = this ?: ByteArray(0)219}220

Search chapters, reference and source filenames.