package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.database.DatabaseJson import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbLocalFolder import eu.friedcutlet.yokan.database.configuredLocalFolders import eu.friedcutlet.yokan.database.normalizeLocalFolders import eu.friedcutlet.yokan.database.sync.SyncIds import eu.friedcutlet.yokan.services.files.* import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable data class LocalImportProgress(val filesDone: Int, val filesTotal: Int, val bytesDone: Long) @Serializable enum class LocalImportPhase { Copying, Ready } @Serializable data class LocalImportFile(val path: String, val size: Long) /** Journal stays outside scanned roots. A ready import survives a failed settings write/restart. */ @Serializable data class PendingLocalImport( val id: String, val name: String, val type: DbItemType, val phase: LocalImportPhase = LocalImportPhase.Copying, val files: List = emptyList(), ) /** Profile-owned import. Settings membership is the publication boundary on every filesystem. */ class LocalMediaImporter( private val files: LocalFileService, private val settings: SettingsStore, private val persistSettings: suspend () -> Unit = {}, private val newId: () -> String = { SyncIds.random().toString() }, private val progressClockMillis: () -> Long = ::nowMillis, ) { private val mutex = Mutex() private val root = "${files.downloadRoot.trimEnd('/')}/local-imports" suspend fun import( selection: LocalMediaSelection, type: DbItemType, progress: (LocalImportProgress) -> Unit = {}, ): DbLocalFolder = mutex.withLock { files.prepare() val selected = selection.files.filter { it.relativePath.substringAfterLast('.', "").lowercase() in localImportExtensions } require(selected.size in 1..LOCAL_IMPORT_MAX_FILES) { "Select between 1 and $LOCAL_IMPORT_MAX_FILES supported files" } require(selected.any { it.relativePath.substringAfterLast('.', "").lowercase() in readableLocalFileExtensions }) { "No supported media files selected" } validatePaths(selected.map { it.relativePath }) require(selected.all { it.sizeBytes == null || requireNotNull(it.sizeBytes) >= 0 }) { "Invalid file size" } val id = newId().also(::validateId) checkOwnedRoot(id) check(!files.exists("$root/$id") && !files.exists(journalPath(id))) { "Import identity already exists" } var journal = PendingLocalImport(id, selectionName(selected.first().relativePath), type) val content = contentPath(journal) // Written before any content: interrupted copies cannot accidentally become scanned originals. writeJournal(journal) var ready = false try { var bytesDone = 0L val copied = mutableListOf() var lastProgress = progressClockMillis() fun report(done: Int, force: Boolean = false) { val now = progressClockMillis() if (force || now < lastProgress || now - lastProgress >= 200) { progress(LocalImportProgress(done, selected.size, bytesDone)) lastProgress = now } } report(0, force = true) selected.forEachIndexed { index, input -> currentCoroutineContext().ensureActive() checkOwnedRoot(id) var count = 0L check(!files.exists("$content/${input.relativePath}")) { "Conflicting import filenames" } files.writeChunks("$content/${input.relativePath}") { write -> // Also creates zero-byte sidecars on implementations whose default writer is lazy. write(ByteArray(0)) input.readChunks { chunk -> currentCoroutineContext().ensureActive() require(chunk.size <= LOCAL_IMPORT_CHUNK_BYTES) { "Import reader exceeded its memory bound" } check(count <= Long.MAX_VALUE - chunk.size && bytesDone <= Long.MAX_VALUE - chunk.size) { "Import size overflow" } count += chunk.size input.sizeBytes?.let { check(count <= it) { "Selected file changed while importing" } } write(chunk) bytesDone += chunk.size report(index) } } input.sizeBytes?.let { check(count == it) { "Selected file changed while importing" } } copied += LocalImportFile(input.relativePath, count) report(index + 1, force = index == selected.lastIndex) } currentCoroutineContext().ensureActive() journal = journal.copy(phase = LocalImportPhase.Ready, files = copied) // Cancellation of a Promise does not cancel its disk write. Join before changing phase. withContext(NonCancellable) { writeJournal(journal); ready = true } currentCoroutineContext().ensureActive() publish(journal) } catch (failure: Throwable) { // A READY import might already be published. Never delete its content, even on a save error. if (!ready) withContext(NonCancellable) { try { checkOwnedRoot(id) check(files.deleteRecursivelyAsync("$root/$id")) { "Could not remove partial import" } check(files.deleteRecursivelyAsync(journalPath(id))) { "Could not remove import journal" } } catch (cleanup: Throwable) { failure.addSuppressed(cleanup) } } throw failure } } suspend fun pending(): List = mutex.withLock { pendingUnlocked() } /** Explicitly finish a complete copy after restart/save failure; validates every committed file. */ suspend fun recover(id: String): DbLocalFolder = mutex.withLock { val journal = pendingUnlocked().single { it.id == id } require(journal.phase == LocalImportPhase.Ready) { "Incomplete copies must be selected again" } publish(journal) } /** Only COPY journals can be discarded. READY content may already have been a user's original. */ suspend fun discardIncomplete(id: String) = mutex.withLock { val journal = pendingUnlocked().single { it.id == id } require(journal.phase == LocalImportPhase.Copying) { "Completed imports cannot be discarded here" } checkOwnedRoot(id) require(settings.db.value.configuredLocalFolders().none { pathsOverlap(it.path, "$root/$id") }) { "Import is already in use" } check(files.deleteRecursivelyAsync("$root/$id")) { "Could not remove partial import" } check(files.deleteRecursivelyAsync(journalPath(id))) { "Could not remove import journal" } } private suspend fun publish(journal: PendingLocalImport): DbLocalFolder { checkOwnedRoot(journal.id) validatePaths(journal.files.map { it.path }) require(journal.files.isNotEmpty() && journal.files.size <= LOCAL_IMPORT_MAX_FILES) val content = contentPath(journal) journal.files.forEach { check(it.size >= 0 && files.exists("$content/${it.path}") && files.directorySize("$content/${it.path}") == it.size) { "Imported file is missing or changed: ${it.path}" } } currentCoroutineContext().ensureActive() var published: DbLocalFolder? = null settings.updateDb { db -> val configured = db.configuredLocalFolders() val existing = configured.firstOrNull { it.path == content } val next = if (existing == null) normalizeLocalFolders(configured + DbLocalFolder(journal.name, content)) else configured published = existing ?: next.last() db.copy(namedLocalFolders = next) } // Retain READY journal until both settings and disk are durable. Recovery is idempotent. withContext(NonCancellable) { persistSettings() check(files.deleteRecursivelyAsync(journalPath(journal.id))) { "Could not retire import journal" } } return checkNotNull(published) } private suspend fun pendingUnlocked(): List { files.prepare() checkOwnedRoot() return files.listFiles(root).filter { it.name.endsWith(".json") }.mapNotNull { entry -> try { val journal = DatabaseJson.decodeFromString(files.readBytesAsync(entry.path, 2L * 1024 * 1024).decodeToString()) validateId(journal.id) require(entry.path == journalPath(journal.id)) journal } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled } catch (_: Throwable) { null } // Corrupt journals never authorize deleting content. } } private suspend fun writeJournal(journal: PendingLocalImport) { files.writeBytesAsync(journalPath(journal.id), DatabaseJson.encodeToString(journal).encodeToByteArray()) files.awaitPersistence() } private fun journalPath(id: String) = "$root/$id.json" private fun contentPath(journal: PendingLocalImport) = "$root/${journal.id}/${journal.type.name.lowercase()}" private fun validateId(id: String) = require(id.matches(Regex("[a-zA-Z0-9_-]{1,80}"))) { "Invalid import identity" } private fun checkOwnedRoot(id: String? = null) { fun canonical(path: String) = files.canonicalPath(path)?.replace('\\', '/')?.trimEnd('/') val owned = requireNotNull(canonical(files.downloadRoot)) { "Import storage is unavailable" } require(canonical(root) == "$owned/local-imports") { "Import storage points outside its owned directory" } if (id != null) { validateId(id) require(canonical("$root/$id") == "$owned/local-imports/$id") { "Import directory was redirected" } } } private fun selectionName(path: String) = path.substringBefore('/').substringBeforeLast('.', path.substringBefore('/')).take(120) private fun pathsOverlap(a: String, b: String): Boolean = a == b || a.startsWith("$b/") || b.startsWith("${a.trimEnd('/')}/") private fun validatePaths(paths: List) { require(paths.size <= LOCAL_IMPORT_MAX_FILES) require(paths.sumOf { it.length.toLong() } <= 256L * 1024) { "Import filenames exceed the journal limit" } val normalized = paths.map { path -> require(path.length in 1..1024 && path.split('/').all { part -> part.isNotBlank() && part != "." && part != ".." && part.length <= 240 && part.none { it.code < 32 || it in "\\:*?\"<>|" } && !part.endsWith('.') && !part.endsWith(' ') }) { "Unsupported import filename: $path" } path.lowercase() }.sorted() normalized.zipWithNext().forEach { (a, b) -> require(a != b && !b.startsWith("$a/")) { "Conflicting import filenames" } } } }