@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class) package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.domain.ProfileStorageNamespace import eu.friedcutlet.yokan.database.DatabaseJson import eu.friedcutlet.yokan.database.DbPageUrl import io.ktor.http.URLBuilder import kotlinx.browser.localStorage import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.await import kotlinx.coroutines.withContext import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.serialization.Serializable import kotlin.io.encoding.Base64 import kotlin.js.JsAny import kotlin.js.JsString import kotlin.js.Promise internal object WasmSelectedFileStore { private var nextId = 0L private val files = mutableMapOf() fun put(bytes: ByteArray, fileName: String): String { val path = "/yokan/selected-file/${nextId++}/${fileName.ifBlank { "selected-file" }}" files[path] = bytes return path } fun take(path: String): ByteArray? = files.remove(path) } private object BrowserFileStores { private val stores = mutableMapOf() fun get(id: ProfileId): WasmLocalFileService = stores.getOrPut(id) { WasmLocalFileService(id) { stores.remove(id) } } } actual fun createPlatformLocalFileService(profileId: ProfileId): LocalFileService = BrowserFileStores.get(profileId) actual fun createPlatformLocalArchiveService(profileId: ProfileId): LocalArchiveService = WasmLocalArchiveService(BrowserFileStores.get(profileId)) private class WasmLocalArchiveService(private val files: WasmLocalFileService) : LocalArchiveService { private val epubChapters = BoundedCache>(32, 2000) { it.size } override fun invalidateIndexCache() = epubChapters.clear() override fun listPages(archivePath: String): List = emptyList() override suspend fun listPagesAsync(archivePath: String): List { files.prepare() if (archivePath.substringAfterLast('.').lowercase() in ImageExtensions && files.exists(archivePath)) { return listOf(DbPageUrl(files.readableUrl(archivePath), archivePath.substringAfterLast('/'))) } if (archivePath.substringAfterLast('.').lowercase() in setOf("cbz", "zip")) { val url = files.readableUrl(archivePath) return files.archiveEntries(archivePath).filter { it.name.substringAfterLast('.').lowercase() in ImageExtensions } .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) } .map { entry -> DbPageUrl(url = URLBuilder(url).apply { parameters.append("entry", entry.name) }.buildString(), fileName = entry.name) } } return files.listFiles(archivePath).filter { it.name.substringAfterLast('.').lowercase() in ImageExtensions } .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) } .map { DbPageUrl(url = files.readableUrl(it.path), fileName = it.name) } } override fun listEpubChapters(archivePath: String): List = emptyList() override fun readEpubChapter(archivePath: String, index: Int): String = "" override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null override suspend fun listEpubChaptersAsync(archivePath: String): List { files.prepare() val fingerprint = files.listFiles(archivePath.substringBeforeLast('/', "")).firstOrNull { it.path == archivePath } fingerprint?.let { epubChapters[it] }?.let { return it } val chapters = eu.friedcutlet.yokan.services.catchingNonCancellation { files.withArchive(archivePath) { session -> var remaining = 64L * 1024 * 1024 var reads = 0 readEpubManifestAsync { name -> val maximum = if (reads++ < 2) 1024 * 1024 else 8 * 1024 * 1024 readArchiveSession(session, name, minOf(maximum.toLong(), remaining).toInt())?.also { remaining -= it.size } } } }.getOrDefault(emptyList()) if (fingerprint != null && chapters.isNotEmpty()) epubChapters[fingerprint] = chapters return chapters } override suspend fun readEpubChapterAsync(archivePath: String, index: Int): String { val chapter = listEpubChaptersAsync(archivePath).getOrNull(index) ?: error("EPUB chapter is unavailable") return files.withArchive(archivePath) { session -> requireNotNull(readArchiveSession(session, chapter.href, 8 * 1024 * 1024)) { "EPUB chapter is missing" }.decodeToString() } } override suspend fun readEpubResourceAsync(archivePath: String, resourcePath: String): ByteArray? = eu.friedcutlet.yokan.services.catchingNonCancellation { files.withArchive(archivePath) { session -> readArchiveSession(session, resourcePath, 16 * 1024 * 1024) } }.getOrNull() override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? = null override suspend fun zipDirectoryToCbzAsync(directoryPath: String, deleteSource: Boolean): String? = files.zip(directoryPath, deleteSource) private companion object { val ImageExtensions = setOf("jpg", "jpeg", "png", "gif", "webp", "bmp", "avif") } } @Serializable private data class BrowserStoredFile(val path: String, val name: String, val sizeBytes: Long, val lastModified: Long) @Serializable private data class BrowserArchiveEntry(val name: String, val size: Long) @Serializable private data class BrowserLocalEntry(val path: String, val name: String, val isArchive: Boolean) /** OPFS owns downloaded bytes; the synchronous interface is restricted to metadata and legacy backups. */ private class WasmLocalFileService(profileId: ProfileId, private val onClosed: () -> Unit) : LocalFileService { private val root = ProfileStorageNamespace(profileId).ownedRoot("/yokan") override val downloadRoot = "$root/downloads" override val backupRoot = "$root/backups" override val cacheRoot = "$root/cache" private val store by lazy { browserStore(root) } private val storagePrefix = "yokan-backup-file:" override suspend fun prepare() { prepareStore(store).await() } suspend fun archiveEntries(path: String): List = DatabaseJson.decodeFromString(archiveEntriesStore(store, path).await().toString()) suspend fun withArchive(path: String, block: suspend (JsAny) -> T): T { val session = withContext(NonCancellable) { openArchiveStore(store, path).await() } return try { currentCoroutineContext().ensureActive() block(session) } finally { withContext(NonCancellable) { closeArchiveSession(session).await() } } } suspend fun zip(path: String, deleteSource: Boolean): String? = withContext(NonCancellable) { zipStore(store, path, deleteSource).await()?.toString() } override suspend fun awaitPersistence() { flushStore(store).await() } override suspend fun close() { closeStore(store).await(); onClosed() } override fun writeBytes(path: String, bytes: ByteArray) { if (path.startsWith("$backupRoot/")) localStorage.setItem(storagePrefix + path, Base64.encode(bytes)) else writeStoreDeferred(store, path, Base64.encode(bytes)) } override suspend fun writeBytesAsync(path: String, bytes: ByteArray) { if (path.startsWith("$backupRoot/")) writeBytes(path, bytes) else writeStore(store, path, Base64.encode(bytes)).await() } override fun readBytes(path: String): ByteArray = WasmSelectedFileStore.take(path) ?: localStorage.getItem(storagePrefix + path)?.let(Base64::decode) ?: cachedStore(store, path)?.let(Base64::decode) ?: error("Use asynchronous reads for browser file content") override fun readBytesBounded(path: String, maxBytes: Long): ByteArray { val bytes = readBytes(path) require(bytes.size.toLong() <= maxBytes) { "File exceeds the read limit" } return bytes } override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray { WasmSelectedFileStore.take(path)?.let { require(it.size.toLong() <= maxBytes); return it } localStorage.getItem(storagePrefix + path)?.let { require(base64DecodedSize(it) <= maxBytes); return Base64.decode(it) } return Base64.decode(readStore(store, path, maxBytes.coerceAtMost(Int.MAX_VALUE.toLong()).toDouble()).await().toString()) } override suspend fun writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T = chunks(path, false, block) override suspend fun appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T = chunks(path, true, block) private suspend fun chunks(path: String, append: Boolean, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T { // Promise cancellation cannot undo a browser writer opened after await was cancelled. withContext(NonCancellable) { beginStore(store, path, append).await() } var failure: Throwable? = null try { currentCoroutineContext().ensureActive() return block { bytes -> chunkStore(store, path, Base64.encode(bytes)).await() } } catch (error: Throwable) { failure = error; throw error } finally { // Retain partial bytes for ETag-validated resume. Join disk writes before retirement. withContext(NonCancellable) { try { endStore(store, path, true).await() } catch (closing: Throwable) { if (failure == null) throw closing else failure.addSuppressed(closing) } } } } override fun canonicalPath(path: String): String? = path.takeIf { it.startsWith("$root/") && it.split('/').none { segment -> segment == "." || segment == ".." || '\\' in segment } } private fun isBackupPath(path: String): Boolean = path == backupRoot || path.startsWith("$backupRoot/") override fun exists(path: String): Boolean = if (isBackupPath(path)) storedBackups().any { it == path || it.startsWith("$path/") } else existsStore(store, path) override fun deleteRecursively(path: String): Boolean { if (!isBackupPath(path)) return false storedBackups().filter { it == path || it.startsWith("$path/") }.forEach { localStorage.removeItem(storagePrefix + it) } return true } override suspend fun deleteRecursivelyAsync(path: String): Boolean { if (isBackupPath(path)) return deleteRecursively(path) removeStore(store, path).await() return true } override suspend fun promoteAsync(sourcePath: String, targetPath: String): Boolean { promoteStore(store, sourcePath, targetPath).await() return true } override suspend fun readableUrl(path: String): String = urlStore(store, path.removePrefix("file://")).await().toString() override fun directorySize(path: String): Long = if (isBackupPath(path)) storedBackups().filter { it == path || it.startsWith("$path/") } .sumOf { localStorage.getItem(storagePrefix + it)?.let(::base64DecodedSize) ?: 0L } else sizeStore(store, path).toLong() override fun openLocation(path: String): Boolean = false override fun listDirectoryEntries(root: String): List? = DatabaseJson.decodeFromString?>(directoryEntriesStore(store, root)) override fun listLocalEntries(root: String): List? { val encoded = localEntriesStore(store, root, readableLocalFileExtensions.joinToString(",")) return DatabaseJson.decodeFromString?>(encoded)?.map { LocalEntry(it.path, it.name, it.isArchive) } } override fun listFiles(root: String): List = if (isBackupPath(root)) storedBackups().filter { it.substringBeforeLast('/') == root } .map { LocalFileEntry(it, it.substringAfterLast('/'), directorySize(it), 0) } else DatabaseJson.decodeFromString>(listStore(store, root)).map { LocalFileEntry(it.path, it.name, it.sizeBytes, it.lastModified) } private fun storedBackups(): List = (0 until localStorage.length).mapNotNull { index -> localStorage.key(index)?.takeIf { it.startsWith(storagePrefix) }?.removePrefix(storagePrefix) } } internal fun base64DecodedSize(encoded: String): Long = encoded.length * 3L / 4 - encoded.takeLast(2).count { it == '=' } private fun browserStore(root: String): JsAny = js("globalThis.yokanBrowserFiles.open(root)") private fun openArchiveStore(store: JsAny, path: String): Promise = js("store.openArchive(path)") private fun archiveSessionRead(session: JsAny, name: String, maximum: Int): Promise = js("session.read(name, maximum)") private fun closeArchiveSession(session: JsAny): Promise = js("session.close().then(() => null)") private suspend fun readArchiveSession(session: JsAny, name: String, maximum: Int): ByteArray? { currentCoroutineContext().ensureActive() // Cancelling a Promise await does not stop JS decompression. Join the bounded read // before its owner closes the ZIP/session or retires the profile's file storage. val encoded = try { withContext(NonCancellable) { archiveSessionRead(session, name, maximum).await() } } finally { currentCoroutineContext().ensureActive() } return encoded?.toString()?.let(Base64::decode) } private fun prepareStore(store: JsAny): Promise = js("store.prepare().then(() => null)") private fun archiveEntriesStore(store: JsAny, path: String): Promise = js("store.archiveEntries(path)") private fun zipStore(store: JsAny, path: String, deleteSource: Boolean): Promise = js("store.zip(path, deleteSource)") private fun flushStore(store: JsAny): Promise = js("store.flush().then(() => null)") private fun closeStore(store: JsAny): Promise = js("store.close().then(() => null)") private fun writeStoreDeferred(store: JsAny, path: String, bytes: String): Unit = js("store.write(path, bytes).catch(() => {})") private fun writeStore(store: JsAny, path: String, bytes: String): Promise = js("store.write(path, bytes).then(() => null)") private fun cachedStore(store: JsAny, path: String): String? = js("store.cached(path)") private fun readStore(store: JsAny, path: String, maximum: Double): Promise = js("store.read(path, maximum)") private fun beginStore(store: JsAny, path: String, append: Boolean): Promise = js("store.begin(path, append).then(() => null)") private fun chunkStore(store: JsAny, path: String, bytes: String): Promise = js("store.chunk(path, bytes).then(() => null)") private fun endStore(store: JsAny, path: String, commit: Boolean): Promise = js("store.end(path, commit).then(() => null)") private fun removeStore(store: JsAny, path: String): Promise = js("store.remove(path).then(() => null)") private fun promoteStore(store: JsAny, source: String, target: String): Promise = js("store.promote(source, target).then(() => null)") private fun urlStore(store: JsAny, path: String): Promise = js("store.url(path)") private fun listStore(store: JsAny, path: String): String = js("store.list(path)") private fun localEntriesStore(store: JsAny, path: String, extensions: String): String = js("store.localEntries(path, extensions)") private fun directoryEntriesStore(store: JsAny, path: String): String = js("store.directoryEntries(path)") private fun existsStore(store: JsAny, path: String): Boolean = js("store.exists(path)") private fun sizeStore(store: JsAny, path: String): Double = js("store.size(path)")