package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.database.DbPageUrl /** One readable-file definition for native filesystems and browser inventory listings. */ internal val readableLocalFileExtensions: Set = setOf("cbz", "zip", "cbt", "tar", "epub", "cbr", "rar") + setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif") + setOf("mp4", "mkv", "mov", "webm", "avi", "m4v", "ts", "m3u8") + setOf("txt", "html", "xhtml", "md") interface LocalArchiveService { suspend fun listEpubChaptersAsync(archivePath: String): List = listEpubChapters(archivePath) suspend fun readEpubChapterAsync(archivePath: String, index: Int): String = readEpubChapter(archivePath, index) suspend fun readEpubResourceAsync(archivePath: String, resourcePath: String): ByteArray? = readEpubResource(archivePath, resourcePath) suspend fun listPagesAsync(archivePath: String): List = listPages(archivePath) suspend fun zipDirectoryToCbzAsync(directoryPath: String, deleteSource: Boolean = true): String? = zipDirectoryToCbz(directoryPath, deleteSource) fun invalidateIndexCache() = Unit fun listPages(archivePath: String): List /** Fresh, complete inventory for queue cloning; throws if any supported archive image is unreadable. */ fun listPagesStrict(archivePath: String): List = throw UnsupportedOperationException("Strict archive page inventory is unavailable") fun listEpubChapters(archivePath: String): List fun readEpubChapter(archivePath: String, index: Int): String fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? /** Zips the folder's images plus its [CHAPTER_METADATA_FILE] into `.cbz`; null when it is not a folder. */ fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean = true): String? } /** Metadata a downloaded chapter folder keeps next to its pages, and carries into its CBZ. */ internal const val CHAPTER_METADATA_FILE = "metadata.json" data class LocalEpubChapter( val title: String, val href: String, ) data class LocalEntry( val path: String, val name: String, val isArchive: Boolean, ) /** One immediate child; [name] includes the file extension and [path] may be an opaque provider URI. */ @kotlinx.serialization.Serializable data class LocalDirectoryEntry(val path: String, val name: String, val isDirectory: Boolean) interface LocalFileService { val downloadRoot: String val backupRoot: String val cacheRoot: String /** Browser files use asynchronous disk APIs; native implementations are immediately ready. */ suspend fun prepare() = Unit suspend fun awaitPersistence() = Unit suspend fun close() { awaitPersistence() } suspend fun writeBytesAsync(path: String, bytes: ByteArray) = writeBytes(path, bytes) suspend fun readBytesAsync(path: String, maxBytes: Long = Long.MAX_VALUE): ByteArray = if (maxBytes == Long.MAX_VALUE) readBytes(path) else readBytesBounded(path, maxBytes) suspend fun deleteRecursivelyAsync(path: String): Boolean = deleteRecursively(path) suspend fun promoteAsync(sourcePath: String, targetPath: String): Boolean = promote(sourcePath, targetPath) suspend fun readableUrl(path: String): String = if (path.startsWith("file://") || path.startsWith("content://") || path.startsWith("http://") || path.startsWith("https://") || path.startsWith("blob:")) path else "file://$path" fun writeBytes(path: String, bytes: ByteArray) fun appendBytes(path: String, bytes: ByteArray) = writeBytes(path, readBytes(path) + bytes) /** Append without buffering the existing file; native implementations keep one handle open. */ suspend fun appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T = block { bytes -> if (exists(path)) appendBytes(path, bytes) else writeBytes(path, bytes) } /** * Replaces [path] with the chunks [block] writes. Platform implementations keep the file open * for the whole block; nothing may be created if [block] writes no chunk. */ suspend fun writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T { var first = true return block { bytes -> if (first) writeBytes(path, bytes) else appendBytes(path, bytes) first = false } } /** Promote a fully written temporary file to its final name. */ fun promote(sourcePath: String, targetPath: String): Boolean { if (!exists(sourcePath)) return false writeBytes(targetPath, readBytes(sourcePath)) return exists(targetPath) && deleteRecursively(sourcePath) && !exists(sourcePath) } /** Atomically replace an existing file with a staged sibling file; unsupported by default. */ fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean = false /** Publish a complete staged sibling directory only when its destination is absent. */ fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean = false fun readBytes(path: String): ByteArray fun mimeType(path: String): String? = null /** Reads at most [maxBytes], throwing if the source exceeds the limit or cannot be read. */ fun readBytesBounded(path: String, maxBytes: Long): ByteArray { require(maxBytes >= 0) val bytes = readBytes(path) require(bytes.size.toLong() <= maxBytes) { "File exceeds $maxBytes bytes" } return bytes } fun canonicalPath(path: String): String? fun exists(path: String): Boolean fun deleteRecursively(path: String): Boolean fun directorySize(path: String): Long fun openLocation(path: String): Boolean /** Null means the root could not be read; an empty list is a readable empty root. */ fun listLocalEntries(root: String): List? /** Immediate children without recursive flattening. Null means unavailable/unsupported. */ fun listDirectoryEntries(root: String): List? = null fun listFiles(root: String): List } data class LocalFileEntry( val path: String, val name: String, val sizeBytes: Long, val lastModified: Long, ) expect fun createPlatformLocalArchiveService(profileId: eu.friedcutlet.yokan.domain.ProfileId = eu.friedcutlet.yokan.domain.ProfileId.Default): LocalArchiveService expect fun createPlatformLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId = eu.friedcutlet.yokan.domain.ProfileId.Default): LocalFileService