Yokan / rebuild
Course 1 8624561

LocalFileService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.kt

implementation121 lines
1package eu.friedcutlet.yokan.services.files23import eu.friedcutlet.yokan.database.DbPageUrl45/** One readable-file definition for native filesystems and browser inventory listings. */6internal val readableLocalFileExtensions: Set<String> =7    setOf("cbz", "zip", "cbt", "tar", "epub", "cbr", "rar") +8        setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif") +9        setOf("mp4", "mkv", "mov", "webm", "avi", "m4v", "ts", "m3u8") +10        setOf("txt", "html", "xhtml", "md")1112interface LocalArchiveService {13    suspend fun listEpubChaptersAsync(archivePath: String): List<LocalEpubChapter> = listEpubChapters(archivePath)14    suspend fun readEpubChapterAsync(archivePath: String, index: Int): String = readEpubChapter(archivePath, index)15    suspend fun readEpubResourceAsync(archivePath: String, resourcePath: String): ByteArray? = readEpubResource(archivePath, resourcePath)16    suspend fun listPagesAsync(archivePath: String): List<DbPageUrl> = listPages(archivePath)17    suspend fun zipDirectoryToCbzAsync(directoryPath: String, deleteSource: Boolean = true): String? = zipDirectoryToCbz(directoryPath, deleteSource)18    fun invalidateIndexCache() = Unit19    fun listPages(archivePath: String): List<DbPageUrl>20    /** Fresh, complete inventory for queue cloning; throws if any supported archive image is unreadable. */21    fun listPagesStrict(archivePath: String): List<DbPageUrl> =22        throw UnsupportedOperationException("Strict archive page inventory is unavailable")23    fun listEpubChapters(archivePath: String): List<LocalEpubChapter>24    fun readEpubChapter(archivePath: String, index: Int): String25    fun readEpubResource(archivePath: String, resourcePath: String): ByteArray?26    /** Zips the folder's images plus its [CHAPTER_METADATA_FILE] into `<folder>.cbz`; null when it is not a folder. */27    fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean = true): String?28}2930/** Metadata a downloaded chapter folder keeps next to its pages, and carries into its CBZ. */31internal const val CHAPTER_METADATA_FILE = "metadata.json"3233data class LocalEpubChapter(34    val title: String,35    val href: String,36)3738data class LocalEntry(39    val path: String,40    val name: String,41    val isArchive: Boolean,42)4344/** One immediate child; [name] includes the file extension and [path] may be an opaque provider URI. */45@kotlinx.serialization.Serializable46data class LocalDirectoryEntry(val path: String, val name: String, val isDirectory: Boolean)4748interface LocalFileService {49    val downloadRoot: String50    val backupRoot: String51    val cacheRoot: String5253    /** Browser files use asynchronous disk APIs; native implementations are immediately ready. */54    suspend fun prepare() = Unit55    suspend fun awaitPersistence() = Unit56    suspend fun close() { awaitPersistence() }57    suspend fun writeBytesAsync(path: String, bytes: ByteArray) = writeBytes(path, bytes)58    suspend fun readBytesAsync(path: String, maxBytes: Long = Long.MAX_VALUE): ByteArray =59        if (maxBytes == Long.MAX_VALUE) readBytes(path) else readBytesBounded(path, maxBytes)60    suspend fun deleteRecursivelyAsync(path: String): Boolean = deleteRecursively(path)61    suspend fun promoteAsync(sourcePath: String, targetPath: String): Boolean = promote(sourcePath, targetPath)62    suspend fun readableUrl(path: String): String =63        if (path.startsWith("file://") || path.startsWith("content://") || path.startsWith("http://") || path.startsWith("https://") || path.startsWith("blob:")) path else "file://$path"6465    fun writeBytes(path: String, bytes: ByteArray)66    fun appendBytes(path: String, bytes: ByteArray) = writeBytes(path, readBytes(path) + bytes)67    /** Append without buffering the existing file; native implementations keep one handle open. */68    suspend fun <T> appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T =69        block { bytes -> if (exists(path)) appendBytes(path, bytes) else writeBytes(path, bytes) }70    /**71     * Replaces [path] with the chunks [block] writes. Platform implementations keep the file open72     * for the whole block; nothing may be created if [block] writes no chunk.73     */74    suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {75        var first = true76        return block { bytes ->77            if (first) writeBytes(path, bytes) else appendBytes(path, bytes)78            first = false79        }80    }81    /** Promote a fully written temporary file to its final name. */82    fun promote(sourcePath: String, targetPath: String): Boolean {83        if (!exists(sourcePath)) return false84        writeBytes(targetPath, readBytes(sourcePath))85        return exists(targetPath) && deleteRecursively(sourcePath) && !exists(sourcePath)86    }87    /** Atomically replace an existing file with a staged sibling file; unsupported by default. */88    fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean = false89    /** Publish a complete staged sibling directory only when its destination is absent. */90    fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean = false91    fun readBytes(path: String): ByteArray92    fun mimeType(path: String): String? = null93    /** Reads at most [maxBytes], throwing if the source exceeds the limit or cannot be read. */94    fun readBytesBounded(path: String, maxBytes: Long): ByteArray {95        require(maxBytes >= 0)96        val bytes = readBytes(path)97        require(bytes.size.toLong() <= maxBytes) { "File exceeds $maxBytes bytes" }98        return bytes99    }100    fun canonicalPath(path: String): String?101    fun exists(path: String): Boolean102    fun deleteRecursively(path: String): Boolean103    fun directorySize(path: String): Long104    fun openLocation(path: String): Boolean105    /** Null means the root could not be read; an empty list is a readable empty root. */106    fun listLocalEntries(root: String): List<LocalEntry>?107    /** Immediate children without recursive flattening. Null means unavailable/unsupported. */108    fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? = null109    fun listFiles(root: String): List<LocalFileEntry>110}111112data class LocalFileEntry(113    val path: String,114    val name: String,115    val sizeBytes: Long,116    val lastModified: Long,117)118119expect fun createPlatformLocalArchiveService(profileId: eu.friedcutlet.yokan.domain.ProfileId = eu.friedcutlet.yokan.domain.ProfileId.Default): LocalArchiveService120121expect fun createPlatformLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId = eu.friedcutlet.yokan.domain.ProfileId.Default): LocalFileService122

Search chapters, reference and source filenames.