package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.data.DefaultYokanRepository import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.services.files.* import kotlinx.coroutines.* import kotlinx.coroutines.test.runTest import kotlin.test.* import eu.friedcutlet.yokan.services.files.effectiveLocalLibraryFolders class LocalMediaImporterTest { @Test fun copiesAreHiddenUntilCompleteAndPublicationPreservesConcurrentSettings() = runTest { val files = ImportFiles() val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} val started = CompletableDeferred() val resume = CompletableDeferred() val source = Input("Show/Episode 1.mp4", byteArrayOf(1, 2)) { started.complete(Unit); resume.await() } val importer = LocalMediaImporter(files, settings, newId = { "one" }) val work = async { importer.import(LocalMediaSelection(listOf(source, Input("Show/metadata.json", "{}".encodeToByteArray()))), DbItemType.Anime) } started.await() assertTrue(settings.db.value.configuredLocalFolders().isEmpty()) assertTrue(effectiveLocalLibraryFolders(settings.db.value, files).none { "local-imports" in it.path }) settings.updateDb { it.copy(themeIsDark = true) } resume.complete(Unit) val folder = work.await() assertEquals("Show", folder.name) assertEquals("/downloads/local-imports/one/anime", folder.path) assertContentEquals(byteArrayOf(1, 2), files.bytes["${folder.path}/Show/Episode 1.mp4"]) assertTrue(settings.db.value.themeIsDark) assertEquals(listOf(folder), settings.db.value.configuredLocalFolders()) assertTrue(importer.pending().isEmpty()) assertTrue(files.maxChunk <= LOCAL_IMPORT_CHUNK_BYTES) } @Test fun cancellationAndChangedSourcesRemoveOnlyUnpublishedCopies() = runTest { val files = ImportFiles().apply { bytes["/source/original.mp4"] = byteArrayOf(7) } val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} val importer = LocalMediaImporter(files, settings, newId = { "cancel" }) val source = Input("clip.mp4", byteArrayOf(1)) { throw CancellationException("Cancelled") } assertFailsWith { importer.import(LocalMediaSelection(listOf(source)), DbItemType.Anime) } assertEquals(setOf("/source/original.mp4"), files.bytes.keys) val changed = Input("clip.mp4", byteArrayOf(1), announcedSize = 2) assertFailsWith { importer.import(LocalMediaSelection(listOf(changed)), DbItemType.Anime) } assertEquals(setOf("/source/original.mp4"), files.bytes.keys) assertTrue(settings.db.value.configuredLocalFolders().isEmpty()) } @Test fun readyJournalSurvivesSaveFailureAndRecoveryIsIdempotent() = runTest { val files = ImportFiles() val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} val importer = LocalMediaImporter(files, settings, persistSettings = { error("Disk save failed") }, newId = { "ready" }) assertFailsWith { importer.import(LocalMediaSelection(listOf(Input("book.epub", byteArrayOf(8)))), DbItemType.Novel) } val journal = importer.pending().single() assertEquals(LocalImportPhase.Ready, journal.phase) assertFailsWith { importer.discardIncomplete(journal.id) } val content = settings.db.value.configuredLocalFolders().single().path assertContentEquals(byteArrayOf(8), files.bytes["$content/book.epub"]) // Simulate restart before the settings write reached disk. settings.updateDb { it.copy(namedLocalFolders = emptyList()) } val reopened = LocalMediaImporter(files, settings) val recovered = reopened.recover(journal.id) assertEquals(content, recovered.path) assertEquals(1, settings.db.value.configuredLocalFolders().size) assertTrue(reopened.pending().isEmpty()) } @Test fun recoveryRejectsMissingFilesAndNeverDeletesCompletedContent() = runTest { val files = ImportFiles() val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} val importer = LocalMediaImporter(files, settings, persistSettings = { error("Save failed") }, newId = { "changed" }) assertFails { importer.import(LocalMediaSelection(listOf(Input("chapter.cbz", byteArrayOf(1)))), DbItemType.Manga) } files.bytes.remove("/downloads/local-imports/changed/manga/chapter.cbz") assertFailsWith { LocalMediaImporter(files, settings).recover("changed") } assertEquals(LocalImportPhase.Ready, importer.pending().single().phase) } @Test fun incompleteRecoveryCannotDeleteConfiguredRootsOrEscapeItsProfile() = runTest { val files = ImportFiles() val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} val journal = PendingLocalImport("partial", "Title", DbItemType.Manga) files.writeBytes("/downloads/local-imports/partial.json", DatabaseJson.encodeToString(journal).encodeToByteArray()) files.writeBytes("/downloads/local-imports/partial/manga/title.cbz", byteArrayOf(1)) // Malformed or mismatched journals never authorize deletion. files.writeBytes("/downloads/local-imports/evil.json", DatabaseJson.encodeToString(journal.copy(id = "../outside")).encodeToByteArray()) val importer = LocalMediaImporter(files, settings) assertEquals(listOf(journal), importer.pending()) settings.updateDb { it.copy(namedLocalFolders = listOf(DbLocalFolder("Owned", "/downloads/local-imports/partial/manga"))) } assertFailsWith { importer.discardIncomplete("partial") } assertTrue(files.exists("/downloads/local-imports/partial/manga/title.cbz")) settings.updateDb { it.copy(namedLocalFolders = emptyList()) } importer.discardIncomplete("partial") assertFalse(files.exists("/downloads/local-imports/partial")) assertTrue(files.exists("/downloads/local-imports/evil.json")) } @Test fun unsafeOrConflictingNamesAreRejectedBeforeAnySourceRead() = runTest { val files = ImportFiles() val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} for (names in listOf(listOf("../title.mp4"), listOf("/title.mp4"), listOf("folder\\title.mp4"), listOf("Title.mp4", "title.mp4"), listOf("title.mp4", "title.mp4/child.mp4"))) { val inputs = names.map { Input(it, byteArrayOf(1)) { error("Must not read") } } assertFailsWith { LocalMediaImporter(files, settings).import(LocalMediaSelection(inputs), DbItemType.Anime) } assertTrue(files.bytes.isEmpty()) } } @Test fun repeatedNamesGetUniqueFoldersAndNoExistingMediaIsOverwritten() = runTest { val files = ImportFiles() val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} for (id in listOf("first", "second")) LocalMediaImporter(files, settings, newId = { id }).import( LocalMediaSelection(listOf(Input("book.epub", byteArrayOf(id.length.toByte())))), DbItemType.Novel) val folders = settings.db.value.configuredLocalFolders() assertEquals(2, folders.map { it.name }.toSet().size) assertEquals(2, folders.map { it.path }.toSet().size) assertContentEquals(byteArrayOf(5), files.bytes["${folders[0].path}/book.epub"]) assertContentEquals(byteArrayOf(6), files.bytes["${folders[1].path}/book.epub"]) } @Test fun progressCoalescesBurstsButAlwaysReportsTheCompletedByteAndFileCount() = runTest { val files = ImportFiles() val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} val updates = mutableListOf() val source = object : LocalMediaInput { override val relativePath = "clip.mp4" override val sizeBytes = 1000L override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { repeat(1000) { consume(byteArrayOf(1)) } } } LocalMediaImporter(files, settings, progressClockMillis = { 0 }).import(LocalMediaSelection(listOf(source)), DbItemType.Anime, updates::add) assertEquals(listOf(LocalImportProgress(0, 1, 0), LocalImportProgress(1, 1, 1000)), updates) } @Test fun redirectedImportRootsCannotWriteOrDeleteOriginalFiles() = runTest { val files = ImportFiles() val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} val importer = LocalMediaImporter(files, settings, newId = { "redirected" }) files.resolveCanonical = { path -> if (path.startsWith("/downloads/local-imports")) path.replace("/downloads/local-imports", "/originals") else path } assertFailsWith { importer.import(LocalMediaSelection(listOf(Input("chapter.cbz", byteArrayOf(1)))), DbItemType.Manga) } assertTrue(files.bytes.isEmpty()) files.resolveCanonical = { it } val journal = PendingLocalImport("redirected", "Title", DbItemType.Manga) files.writeBytes("/downloads/local-imports/redirected.json", DatabaseJson.encodeToString(journal).encodeToByteArray()) files.writeBytes("/downloads/local-imports/redirected/manga/chapter.cbz", byteArrayOf(1)) files.resolveCanonical = { path -> if (path.startsWith("/downloads/local-imports/redirected/")) path.replace("/downloads/local-imports/redirected", "/originals") else if (path == "/downloads/local-imports/redirected") "/originals" else path } assertFailsWith { importer.discardIncomplete("redirected") } assertContentEquals(byteArrayOf(1), files.bytes["/downloads/local-imports/redirected/manga/chapter.cbz"]) } @Test fun recoveringAnAlreadyPublishedReadyCopyKeepsItsOriginalFolderName() = runTest { val files = ImportFiles() val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} val importer = LocalMediaImporter(files, settings, persistSettings = { error("Save failed") }) assertFails { importer.import(LocalMediaSelection(listOf(Input("book.epub", byteArrayOf(1)))), DbItemType.Novel) } val before = settings.db.value.configuredLocalFolders().single() val pending = importer.pending().single() assertEquals(before, LocalMediaImporter(files, settings).recover(pending.id)) assertEquals(listOf(before), settings.db.value.configuredLocalFolders()) } @Test fun redirectionDuringCopyStopsNewWritesAndNeverAuthorizesCleanup() = runTest { val files = ImportFiles() val db = InMemoryYokanDatabase(emptySnapshot()) val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {} val first = Input("first.mp4", byteArrayOf(1)) { files.resolveCanonical = { path -> if (path.startsWith("/downloads/local-imports")) path.replace("/downloads/local-imports", "/originals") else path } } val second = Input("second.mp4", byteArrayOf(2)) { error("Must not read after redirection") } assertFailsWith { LocalMediaImporter(files, settings, newId = { "moving" }).import(LocalMediaSelection(listOf(first, second)), DbItemType.Anime) } assertTrue(files.exists("/downloads/local-imports/moving.json")) assertTrue(files.exists("/downloads/local-imports/moving/anime/first.mp4")) assertFalse(files.exists("/downloads/local-imports/moving/anime/second.mp4")) assertTrue(settings.db.value.configuredLocalFolders().isEmpty()) } } private class Input( override val relativePath: String, private val bytes: ByteArray, override val sizeBytes: Long? = bytes.size.toLong(), private val beforeRead: suspend () -> Unit = {}, ) : LocalMediaInput { constructor(path: String, bytes: ByteArray, announcedSize: Long) : this(path, bytes, announcedSize, {}) override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { beforeRead(); consume(bytes) } } private class ImportFiles : LocalFileService { override val downloadRoot = "/downloads" override val backupRoot = "/backups" override val cacheRoot = "/cache" val bytes = mutableMapOf() var resolveCanonical: (String) -> String? = { it } var maxChunk = 0 override fun writeBytes(path: String, bytes: ByteArray) { this.bytes[path] = bytes.copyOf() } override fun appendBytes(path: String, bytes: ByteArray) { maxChunk = maxOf(maxChunk, bytes.size); this.bytes[path] = this.bytes[path].orEmptyBytes() + bytes } override fun readBytes(path: String): ByteArray = bytes[path] ?: error("Missing file") override fun canonicalPath(path: String) = resolveCanonical(path) override fun exists(path: String) = bytes.keys.any { it == path || it.startsWith("$path/") } override fun deleteRecursively(path: String): Boolean { bytes.keys.filter { it == path || it.startsWith("$path/") }.forEach(bytes::remove); return true } override fun directorySize(path: String) = bytes.filterKeys { it == path || it.startsWith("$path/") }.values.sumOf { it.size.toLong() } override fun openLocation(path: String) = false override fun listLocalEntries(root: String): List? = emptyList() override fun listFiles(root: String) = bytes.filterKeys { it.substringBeforeLast('/') == root }.map { (path, data) -> LocalFileEntry(path, path.substringAfterLast('/'), data.size.toLong(), 1) } private fun ByteArray?.orEmptyBytes() = this ?: ByteArray(0) }