Yokan / rebuild
Course 1 8624561

LocalFileService.wasm.kt

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

implementation243 lines
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class)23package eu.friedcutlet.yokan.services.files45import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.domain.ProfileStorageNamespace7import eu.friedcutlet.yokan.database.DatabaseJson8import eu.friedcutlet.yokan.database.DbPageUrl9import io.ktor.http.URLBuilder10import kotlinx.browser.localStorage11import kotlinx.coroutines.NonCancellable12import kotlinx.coroutines.await13import kotlinx.coroutines.withContext14import kotlinx.coroutines.currentCoroutineContext15import kotlinx.coroutines.ensureActive16import kotlinx.serialization.Serializable17import kotlin.io.encoding.Base6418import kotlin.js.JsAny19import kotlin.js.JsString20import kotlin.js.Promise2122internal object WasmSelectedFileStore {23    private var nextId = 0L24    private val files = mutableMapOf<String, ByteArray>()25    fun put(bytes: ByteArray, fileName: String): String {26        val path = "/yokan/selected-file/${nextId++}/${fileName.ifBlank { "selected-file" }}"27        files[path] = bytes28        return path29    }30    fun take(path: String): ByteArray? = files.remove(path)31}3233private object BrowserFileStores {34    private val stores = mutableMapOf<ProfileId, WasmLocalFileService>()35    fun get(id: ProfileId): WasmLocalFileService = stores.getOrPut(id) { WasmLocalFileService(id) { stores.remove(id) } }36}3738actual fun createPlatformLocalFileService(profileId: ProfileId): LocalFileService = BrowserFileStores.get(profileId)39actual fun createPlatformLocalArchiveService(profileId: ProfileId): LocalArchiveService = WasmLocalArchiveService(BrowserFileStores.get(profileId))4041private class WasmLocalArchiveService(private val files: WasmLocalFileService) : LocalArchiveService {42    private val epubChapters = BoundedCache<LocalFileEntry, List<LocalEpubChapter>>(32, 2000) { it.size }43    override fun invalidateIndexCache() = epubChapters.clear()44    override fun listPages(archivePath: String): List<DbPageUrl> = emptyList()45    override suspend fun listPagesAsync(archivePath: String): List<DbPageUrl> {46        files.prepare()47        if (archivePath.substringAfterLast('.').lowercase() in ImageExtensions && files.exists(archivePath)) {48            return listOf(DbPageUrl(files.readableUrl(archivePath), archivePath.substringAfterLast('/')))49        }50        if (archivePath.substringAfterLast('.').lowercase() in setOf("cbz", "zip")) {51            val url = files.readableUrl(archivePath)52            return files.archiveEntries(archivePath).filter { it.name.substringAfterLast('.').lowercase() in ImageExtensions }53                .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }54                .map { entry -> DbPageUrl(url = URLBuilder(url).apply { parameters.append("entry", entry.name) }.buildString(), fileName = entry.name) }55        }56        return files.listFiles(archivePath).filter { it.name.substringAfterLast('.').lowercase() in ImageExtensions }57            .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }58            .map { DbPageUrl(url = files.readableUrl(it.path), fileName = it.name) }59    }60    override fun listEpubChapters(archivePath: String): List<LocalEpubChapter> = emptyList()61    override fun readEpubChapter(archivePath: String, index: Int): String = ""62    override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null63    override suspend fun listEpubChaptersAsync(archivePath: String): List<LocalEpubChapter> {64        files.prepare()65        val fingerprint = files.listFiles(archivePath.substringBeforeLast('/', "")).firstOrNull { it.path == archivePath }66        fingerprint?.let { epubChapters[it] }?.let { return it }67        val chapters = eu.friedcutlet.yokan.services.catchingNonCancellation {68            files.withArchive(archivePath) { session ->69                var remaining = 64L * 1024 * 102470                var reads = 071                readEpubManifestAsync { name ->72                    val maximum = if (reads++ < 2) 1024 * 1024 else 8 * 1024 * 102473                    readArchiveSession(session, name, minOf(maximum.toLong(), remaining).toInt())?.also { remaining -= it.size }74                }75            }76        }.getOrDefault(emptyList())77        if (fingerprint != null && chapters.isNotEmpty()) epubChapters[fingerprint] = chapters78        return chapters79    }80    override suspend fun readEpubChapterAsync(archivePath: String, index: Int): String {81        val chapter = listEpubChaptersAsync(archivePath).getOrNull(index) ?: error("EPUB chapter is unavailable")82        return files.withArchive(archivePath) { session ->83            requireNotNull(readArchiveSession(session, chapter.href, 8 * 1024 * 1024)) { "EPUB chapter is missing" }.decodeToString()84        }85    }86    override suspend fun readEpubResourceAsync(archivePath: String, resourcePath: String): ByteArray? =87        eu.friedcutlet.yokan.services.catchingNonCancellation {88            files.withArchive(archivePath) { session -> readArchiveSession(session, resourcePath, 16 * 1024 * 1024) }89        }.getOrNull()90    override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? = null91    override suspend fun zipDirectoryToCbzAsync(directoryPath: String, deleteSource: Boolean): String? = files.zip(directoryPath, deleteSource)92    private companion object { val ImageExtensions = setOf("jpg", "jpeg", "png", "gif", "webp", "bmp", "avif") }93}9495@Serializable96private data class BrowserStoredFile(val path: String, val name: String, val sizeBytes: Long, val lastModified: Long)9798@Serializable99private data class BrowserArchiveEntry(val name: String, val size: Long)100101@Serializable102private data class BrowserLocalEntry(val path: String, val name: String, val isArchive: Boolean)103104/** OPFS owns downloaded bytes; the synchronous interface is restricted to metadata and legacy backups. */105private class WasmLocalFileService(profileId: ProfileId, private val onClosed: () -> Unit) : LocalFileService {106    private val root = ProfileStorageNamespace(profileId).ownedRoot("/yokan")107    override val downloadRoot = "$root/downloads"108    override val backupRoot = "$root/backups"109    override val cacheRoot = "$root/cache"110    private val store by lazy { browserStore(root) }111    private val storagePrefix = "yokan-backup-file:"112113    override suspend fun prepare() { prepareStore(store).await<JsAny?>() }114    suspend fun archiveEntries(path: String): List<BrowserArchiveEntry> = DatabaseJson.decodeFromString(archiveEntriesStore(store, path).await<JsString>().toString())115    suspend fun <T> withArchive(path: String, block: suspend (JsAny) -> T): T {116        val session = withContext(NonCancellable) { openArchiveStore(store, path).await<JsAny>() }117        return try {118            currentCoroutineContext().ensureActive()119            block(session)120        } finally { withContext(NonCancellable) { closeArchiveSession(session).await<JsAny?>() } }121    }122    suspend fun zip(path: String, deleteSource: Boolean): String? = withContext(NonCancellable) { zipStore(store, path, deleteSource).await<JsString?>()?.toString() }123    override suspend fun awaitPersistence() { flushStore(store).await<JsAny?>() }124    override suspend fun close() { closeStore(store).await<JsAny?>(); onClosed() }125126    override fun writeBytes(path: String, bytes: ByteArray) {127        if (path.startsWith("$backupRoot/")) localStorage.setItem(storagePrefix + path, Base64.encode(bytes))128        else writeStoreDeferred(store, path, Base64.encode(bytes))129    }130    override suspend fun writeBytesAsync(path: String, bytes: ByteArray) {131        if (path.startsWith("$backupRoot/")) writeBytes(path, bytes)132        else writeStore(store, path, Base64.encode(bytes)).await<JsAny?>()133    }134    override fun readBytes(path: String): ByteArray = WasmSelectedFileStore.take(path)135        ?: localStorage.getItem(storagePrefix + path)?.let(Base64::decode)136        ?: cachedStore(store, path)?.let(Base64::decode)137        ?: error("Use asynchronous reads for browser file content")138139    override fun readBytesBounded(path: String, maxBytes: Long): ByteArray {140        val bytes = readBytes(path)141        require(bytes.size.toLong() <= maxBytes) { "File exceeds the read limit" }142        return bytes143    }144    override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray {145        WasmSelectedFileStore.take(path)?.let { require(it.size.toLong() <= maxBytes); return it }146        localStorage.getItem(storagePrefix + path)?.let { require(base64DecodedSize(it) <= maxBytes); return Base64.decode(it) }147        return Base64.decode(readStore(store, path, maxBytes.coerceAtMost(Int.MAX_VALUE.toLong()).toDouble()).await<JsString>().toString())148    }149150    override suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T = chunks(path, false, block)151    override suspend fun <T> appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T = chunks(path, true, block)152    private suspend fun <T> chunks(path: String, append: Boolean, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {153        // Promise cancellation cannot undo a browser writer opened after await was cancelled.154        withContext(NonCancellable) { beginStore(store, path, append).await<JsAny?>() }155        var failure: Throwable? = null156        try {157            currentCoroutineContext().ensureActive()158            return block { bytes -> chunkStore(store, path, Base64.encode(bytes)).await<JsAny?>() }159        }160        catch (error: Throwable) { failure = error; throw error }161        finally {162            // Retain partial bytes for ETag-validated resume. Join disk writes before retirement.163            withContext(NonCancellable) {164                try { endStore(store, path, true).await<JsAny?>() }165                catch (closing: Throwable) { if (failure == null) throw closing else failure.addSuppressed(closing) }166            }167        }168    }169170    override fun canonicalPath(path: String): String? = path.takeIf {171        it.startsWith("$root/") && it.split('/').none { segment -> segment == "." || segment == ".." || '\\' in segment }172    }173    private fun isBackupPath(path: String): Boolean = path == backupRoot || path.startsWith("$backupRoot/")174    override fun exists(path: String): Boolean = if (isBackupPath(path)) storedBackups().any { it == path || it.startsWith("$path/") } else existsStore(store, path)175    override fun deleteRecursively(path: String): Boolean {176        if (!isBackupPath(path)) return false177        storedBackups().filter { it == path || it.startsWith("$path/") }.forEach { localStorage.removeItem(storagePrefix + it) }178        return true179    }180    override suspend fun deleteRecursivelyAsync(path: String): Boolean {181        if (isBackupPath(path)) return deleteRecursively(path)182        removeStore(store, path).await<JsAny?>()183        return true184    }185    override suspend fun promoteAsync(sourcePath: String, targetPath: String): Boolean {186        promoteStore(store, sourcePath, targetPath).await<JsAny?>()187        return true188    }189    override suspend fun readableUrl(path: String): String = urlStore(store, path.removePrefix("file://")).await<JsString>().toString()190    override fun directorySize(path: String): Long = if (isBackupPath(path)) storedBackups().filter { it == path || it.startsWith("$path/") }191        .sumOf { localStorage.getItem(storagePrefix + it)?.let(::base64DecodedSize) ?: 0L } else sizeStore(store, path).toLong()192    override fun openLocation(path: String): Boolean = false193    override fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? =194        DatabaseJson.decodeFromString<List<LocalDirectoryEntry>?>(directoryEntriesStore(store, root))195196    override fun listLocalEntries(root: String): List<LocalEntry>? {197        val encoded = localEntriesStore(store, root, readableLocalFileExtensions.joinToString(","))198        return DatabaseJson.decodeFromString<List<BrowserLocalEntry>?>(encoded)?.map { LocalEntry(it.path, it.name, it.isArchive) }199    }200    override fun listFiles(root: String): List<LocalFileEntry> = if (isBackupPath(root)) storedBackups().filter { it.substringBeforeLast('/') == root }201        .map { LocalFileEntry(it, it.substringAfterLast('/'), directorySize(it), 0) }202        else DatabaseJson.decodeFromString<List<BrowserStoredFile>>(listStore(store, root)).map { LocalFileEntry(it.path, it.name, it.sizeBytes, it.lastModified) }203204    private fun storedBackups(): List<String> = (0 until localStorage.length).mapNotNull { index ->205        localStorage.key(index)?.takeIf { it.startsWith(storagePrefix) }?.removePrefix(storagePrefix)206    }207}208209internal fun base64DecodedSize(encoded: String): Long = encoded.length * 3L / 4 - encoded.takeLast(2).count { it == '=' }210211private fun browserStore(root: String): JsAny = js("globalThis.yokanBrowserFiles.open(root)")212private fun openArchiveStore(store: JsAny, path: String): Promise<JsAny> = js("store.openArchive(path)")213private fun archiveSessionRead(session: JsAny, name: String, maximum: Int): Promise<JsString?> = js("session.read(name, maximum)")214private fun closeArchiveSession(session: JsAny): Promise<JsAny?> = js("session.close().then(() => null)")215private suspend fun readArchiveSession(session: JsAny, name: String, maximum: Int): ByteArray? {216    currentCoroutineContext().ensureActive()217    // Cancelling a Promise await does not stop JS decompression. Join the bounded read218    // before its owner closes the ZIP/session or retires the profile's file storage.219    val encoded = try {220        withContext(NonCancellable) { archiveSessionRead(session, name, maximum).await<JsString?>() }221    } finally { currentCoroutineContext().ensureActive() }222    return encoded?.toString()?.let(Base64::decode)223}224private fun prepareStore(store: JsAny): Promise<JsAny?> = js("store.prepare().then(() => null)")225private fun archiveEntriesStore(store: JsAny, path: String): Promise<JsString> = js("store.archiveEntries(path)")226private fun zipStore(store: JsAny, path: String, deleteSource: Boolean): Promise<JsString?> = js("store.zip(path, deleteSource)")227private fun flushStore(store: JsAny): Promise<JsAny?> = js("store.flush().then(() => null)")228private fun closeStore(store: JsAny): Promise<JsAny?> = js("store.close().then(() => null)")229private fun writeStoreDeferred(store: JsAny, path: String, bytes: String): Unit = js("store.write(path, bytes).catch(() => {})")230private fun writeStore(store: JsAny, path: String, bytes: String): Promise<JsAny?> = js("store.write(path, bytes).then(() => null)")231private fun cachedStore(store: JsAny, path: String): String? = js("store.cached(path)")232private fun readStore(store: JsAny, path: String, maximum: Double): Promise<JsString> = js("store.read(path, maximum)")233private fun beginStore(store: JsAny, path: String, append: Boolean): Promise<JsAny?> = js("store.begin(path, append).then(() => null)")234private fun chunkStore(store: JsAny, path: String, bytes: String): Promise<JsAny?> = js("store.chunk(path, bytes).then(() => null)")235private fun endStore(store: JsAny, path: String, commit: Boolean): Promise<JsAny?> = js("store.end(path, commit).then(() => null)")236private fun removeStore(store: JsAny, path: String): Promise<JsAny?> = js("store.remove(path).then(() => null)")237private fun promoteStore(store: JsAny, source: String, target: String): Promise<JsAny?> = js("store.promote(source, target).then(() => null)")238private fun urlStore(store: JsAny, path: String): Promise<JsString> = js("store.url(path)")239private fun listStore(store: JsAny, path: String): String = js("store.list(path)")240private fun localEntriesStore(store: JsAny, path: String, extensions: String): String = js("store.localEntries(path, extensions)")241private fun directoryEntriesStore(store: JsAny, path: String): String = js("store.directoryEntries(path)")242private fun existsStore(store: JsAny, path: String): Boolean = js("store.exists(path)")243private fun sizeStore(store: JsAny, path: String): Double = js("store.size(path)")244

Search chapters, reference and source filenames.