Yokan / rebuild
Course 1 8624561

LocalMediaImporter.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalMediaImporter.kt

implementation214 lines
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.data.SettingsStore4import eu.friedcutlet.yokan.database.DatabaseJson5import eu.friedcutlet.yokan.database.DbItemType6import eu.friedcutlet.yokan.database.DbLocalFolder7import eu.friedcutlet.yokan.database.configuredLocalFolders8import eu.friedcutlet.yokan.database.normalizeLocalFolders9import eu.friedcutlet.yokan.database.sync.SyncIds10import eu.friedcutlet.yokan.services.files.*11import eu.friedcutlet.yokan.util.nowMillis12import kotlinx.coroutines.NonCancellable13import kotlinx.coroutines.currentCoroutineContext14import kotlinx.coroutines.ensureActive15import kotlinx.coroutines.sync.Mutex16import kotlinx.coroutines.sync.withLock17import kotlinx.coroutines.withContext18import kotlinx.serialization.Serializable1920data class LocalImportProgress(val filesDone: Int, val filesTotal: Int, val bytesDone: Long)2122@Serializable23enum class LocalImportPhase { Copying, Ready }2425@Serializable26data class LocalImportFile(val path: String, val size: Long)2728/** Journal stays outside scanned roots. A ready import survives a failed settings write/restart. */29@Serializable30data class PendingLocalImport(31    val id: String,32    val name: String,33    val type: DbItemType,34    val phase: LocalImportPhase = LocalImportPhase.Copying,35    val files: List<LocalImportFile> = emptyList(),36)3738/** Profile-owned import. Settings membership is the publication boundary on every filesystem. */39class LocalMediaImporter(40    private val files: LocalFileService,41    private val settings: SettingsStore,42    private val persistSettings: suspend () -> Unit = {},43    private val newId: () -> String = { SyncIds.random().toString() },44    private val progressClockMillis: () -> Long = ::nowMillis,45) {46    private val mutex = Mutex()47    private val root = "${files.downloadRoot.trimEnd('/')}/local-imports"4849    suspend fun import(50        selection: LocalMediaSelection,51        type: DbItemType,52        progress: (LocalImportProgress) -> Unit = {},53    ): DbLocalFolder = mutex.withLock {54        files.prepare()55        val selected = selection.files.filter { it.relativePath.substringAfterLast('.', "").lowercase() in localImportExtensions }56        require(selected.size in 1..LOCAL_IMPORT_MAX_FILES) { "Select between 1 and $LOCAL_IMPORT_MAX_FILES supported files" }57        require(selected.any { it.relativePath.substringAfterLast('.', "").lowercase() in readableLocalFileExtensions }) { "No supported media files selected" }58        validatePaths(selected.map { it.relativePath })59        require(selected.all { it.sizeBytes == null || requireNotNull(it.sizeBytes) >= 0 }) { "Invalid file size" }60        val id = newId().also(::validateId)61        checkOwnedRoot(id)62        check(!files.exists("$root/$id") && !files.exists(journalPath(id))) { "Import identity already exists" }63        var journal = PendingLocalImport(id, selectionName(selected.first().relativePath), type)64        val content = contentPath(journal)65        // Written before any content: interrupted copies cannot accidentally become scanned originals.66        writeJournal(journal)67        var ready = false68        try {69            var bytesDone = 0L70            val copied = mutableListOf<LocalImportFile>()71            var lastProgress = progressClockMillis()72            fun report(done: Int, force: Boolean = false) {73                val now = progressClockMillis()74                if (force || now < lastProgress || now - lastProgress >= 200) {75                    progress(LocalImportProgress(done, selected.size, bytesDone))76                    lastProgress = now77                }78            }79            report(0, force = true)80            selected.forEachIndexed { index, input ->81                currentCoroutineContext().ensureActive()82                checkOwnedRoot(id)83                var count = 0L84                check(!files.exists("$content/${input.relativePath}")) { "Conflicting import filenames" }85                files.writeChunks("$content/${input.relativePath}") { write ->86                    // Also creates zero-byte sidecars on implementations whose default writer is lazy.87                    write(ByteArray(0))88                    input.readChunks { chunk ->89                        currentCoroutineContext().ensureActive()90                        require(chunk.size <= LOCAL_IMPORT_CHUNK_BYTES) { "Import reader exceeded its memory bound" }91                        check(count <= Long.MAX_VALUE - chunk.size && bytesDone <= Long.MAX_VALUE - chunk.size) { "Import size overflow" }92                        count += chunk.size93                        input.sizeBytes?.let { check(count <= it) { "Selected file changed while importing" } }94                        write(chunk)95                        bytesDone += chunk.size96                        report(index)97                    }98                }99                input.sizeBytes?.let { check(count == it) { "Selected file changed while importing" } }100                copied += LocalImportFile(input.relativePath, count)101                report(index + 1, force = index == selected.lastIndex)102            }103            currentCoroutineContext().ensureActive()104            journal = journal.copy(phase = LocalImportPhase.Ready, files = copied)105            // Cancellation of a Promise does not cancel its disk write. Join before changing phase.106            withContext(NonCancellable) { writeJournal(journal); ready = true }107            currentCoroutineContext().ensureActive()108            publish(journal)109        } catch (failure: Throwable) {110            // A READY import might already be published. Never delete its content, even on a save error.111            if (!ready) withContext(NonCancellable) {112                try {113                    checkOwnedRoot(id)114                    check(files.deleteRecursivelyAsync("$root/$id")) { "Could not remove partial import" }115                    check(files.deleteRecursivelyAsync(journalPath(id))) { "Could not remove import journal" }116                } catch (cleanup: Throwable) { failure.addSuppressed(cleanup) }117            }118            throw failure119        }120    }121122    suspend fun pending(): List<PendingLocalImport> = mutex.withLock { pendingUnlocked() }123124    /** Explicitly finish a complete copy after restart/save failure; validates every committed file. */125    suspend fun recover(id: String): DbLocalFolder = mutex.withLock {126        val journal = pendingUnlocked().single { it.id == id }127        require(journal.phase == LocalImportPhase.Ready) { "Incomplete copies must be selected again" }128        publish(journal)129    }130131    /** Only COPY journals can be discarded. READY content may already have been a user's original. */132    suspend fun discardIncomplete(id: String) = mutex.withLock {133        val journal = pendingUnlocked().single { it.id == id }134        require(journal.phase == LocalImportPhase.Copying) { "Completed imports cannot be discarded here" }135        checkOwnedRoot(id)136        require(settings.db.value.configuredLocalFolders().none { pathsOverlap(it.path, "$root/$id") }) { "Import is already in use" }137        check(files.deleteRecursivelyAsync("$root/$id")) { "Could not remove partial import" }138        check(files.deleteRecursivelyAsync(journalPath(id))) { "Could not remove import journal" }139    }140141    private suspend fun publish(journal: PendingLocalImport): DbLocalFolder {142        checkOwnedRoot(journal.id)143        validatePaths(journal.files.map { it.path })144        require(journal.files.isNotEmpty() && journal.files.size <= LOCAL_IMPORT_MAX_FILES)145        val content = contentPath(journal)146        journal.files.forEach {147            check(it.size >= 0 && files.exists("$content/${it.path}") && files.directorySize("$content/${it.path}") == it.size) { "Imported file is missing or changed: ${it.path}" }148        }149        currentCoroutineContext().ensureActive()150        var published: DbLocalFolder? = null151        settings.updateDb { db ->152            val configured = db.configuredLocalFolders()153            val existing = configured.firstOrNull { it.path == content }154            val next = if (existing == null) normalizeLocalFolders(configured + DbLocalFolder(journal.name, content)) else configured155            published = existing ?: next.last()156            db.copy(namedLocalFolders = next)157        }158        // Retain READY journal until both settings and disk are durable. Recovery is idempotent.159        withContext(NonCancellable) {160            persistSettings()161            check(files.deleteRecursivelyAsync(journalPath(journal.id))) { "Could not retire import journal" }162        }163        return checkNotNull(published)164    }165166    private suspend fun pendingUnlocked(): List<PendingLocalImport> {167        files.prepare()168        checkOwnedRoot()169        return files.listFiles(root).filter { it.name.endsWith(".json") }.mapNotNull { entry ->170            try {171                val journal = DatabaseJson.decodeFromString<PendingLocalImport>(files.readBytesAsync(entry.path, 2L * 1024 * 1024).decodeToString())172                validateId(journal.id)173                require(entry.path == journalPath(journal.id))174                journal175            } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled }176            catch (_: Throwable) { null } // Corrupt journals never authorize deleting content.177        }178    }179180    private suspend fun writeJournal(journal: PendingLocalImport) {181        files.writeBytesAsync(journalPath(journal.id), DatabaseJson.encodeToString(journal).encodeToByteArray())182        files.awaitPersistence()183    }184185    private fun journalPath(id: String) = "$root/$id.json"186    private fun contentPath(journal: PendingLocalImport) = "$root/${journal.id}/${journal.type.name.lowercase()}"187    private fun validateId(id: String) = require(id.matches(Regex("[a-zA-Z0-9_-]{1,80}"))) { "Invalid import identity" }188    private fun checkOwnedRoot(id: String? = null) {189        fun canonical(path: String) = files.canonicalPath(path)?.replace('\\', '/')?.trimEnd('/')190        val owned = requireNotNull(canonical(files.downloadRoot)) { "Import storage is unavailable" }191        require(canonical(root) == "$owned/local-imports") { "Import storage points outside its owned directory" }192        if (id != null) {193            validateId(id)194            require(canonical("$root/$id") == "$owned/local-imports/$id") { "Import directory was redirected" }195        }196    }197    private fun selectionName(path: String) = path.substringBefore('/').substringBeforeLast('.', path.substringBefore('/')).take(120)198    private fun pathsOverlap(a: String, b: String): Boolean = a == b || a.startsWith("$b/") || b.startsWith("${a.trimEnd('/')}/")199200    private fun validatePaths(paths: List<String>) {201        require(paths.size <= LOCAL_IMPORT_MAX_FILES)202        require(paths.sumOf { it.length.toLong() } <= 256L * 1024) { "Import filenames exceed the journal limit" }203        val normalized = paths.map { path ->204            require(path.length in 1..1024 && path.split('/').all { part ->205                part.isNotBlank() && part != "." && part != ".." && part.length <= 240 &&206                    part.none { it.code < 32 || it in "\\:*?\"<>|" } && !part.endsWith('.') && !part.endsWith(' ')207            }) { "Unsupported import filename: $path" }208            path.lowercase()209        }.sorted()210        normalized.zipWithNext().forEach { (a, b) ->211            require(a != b && !b.startsWith("$a/")) { "Conflicting import filenames" }212        }213    }214}215

Search chapters, reference and source filenames.