Yokan / rebuild
Course 1 8624561

LocalFileService.ios.kt

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

implementation417 lines
1package eu.friedcutlet.yokan.services.files23import eu.friedcutlet.yokan.database.DbPageUrl4import eu.friedcutlet.yokan.util.PlatformLock5import kotlinx.cinterop.BetaInteropApi6import kotlinx.cinterop.CPointer7import kotlinx.cinterop.ExperimentalForeignApi8import kotlinx.cinterop.addressOf9import kotlinx.cinterop.usePinned10import platform.Foundation.NSDate11import platform.Foundation.NSFileManager12import platform.Foundation.NSFileModificationDate13import platform.Foundation.NSURL14import platform.Foundation.timeIntervalSince197015import platform.posix.FILE16import platform.posix.SEEK_CUR17import platform.posix.fclose18import platform.posix.fopen19import platform.posix.fread20import platform.posix.fseek21import platform.posix.fwrite22import platform.posix.remove23import platform.posix.rename24import kotlin.random.Random2526actual fun createPlatformLocalArchiveService(profileId: eu.friedcutlet.yokan.domain.ProfileId): LocalArchiveService = IosLocalArchiveService(files = createPlatformLocalFileService(profileId))2728actual fun createPlatformLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId): LocalFileService = if (profileId == eu.friedcutlet.yokan.domain.ProfileId.Default) IosLocalFileService else IosProfileLocalFileService(profileId)2930/**31 * iOS archive support. Image directories list directly through NSFileManager; CBZ/ZIP pages and32 * EPUB chapters read through a file-backed [IosZipArchive]; CBT/TAR pages stream entry by entry. Pages33 * extract into `cacheRoot/archives/<key>` like the JVM implementation, kept least-recently-used within34 * [extractedPagesBudgetBytes]; zipDirectoryToCbz streams a stored ZIP.35 *36 * Memory ceiling: TAR uses one 512 B header and one 64 KiB copy buffer. ZIP reads keep the entry37 * tables of 8 archives and hold one entry at a time; plus 8 page lists and 8 chapter lists.38 */39@OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)40internal class IosLocalArchiveService(41    // ponytail: fixed 1 GiB of extracted pages; make it a storage setting if users want a bigger offline cache.42    private val files: LocalFileService = IosLocalFileService,43    private val extractedPagesBudgetBytes: Long = 1L shl 30,44) : LocalArchiveService {45    private val imageExtensions = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif")46    private val zipArchives = LinkedHashMap<String, IosZipArchive>()47    private val epubChapterCache = LinkedHashMap<String, List<LocalEpubChapter>>()48    private val extractedPages = LinkedHashMap<String, List<DbPageUrl>>()49    private val cacheLock = PlatformLock()50    private val extractionRoot = "${files.cacheRoot}/archives"51    private val maxStrictZipPageBytes = 25L * 1024 * 10245253    override fun listPages(archivePath: String): List<DbPageUrl> {54        if (archivePath.isBlank()) return emptyList()55        cacheLock.withLock { extractedPages[archivePath] }?.takeIf { touchExtraction(it) }?.let { return it }56        val pages = IosSecurityScopedBookmarks.withAccess(archivePath) { path ->57            val fm = NSFileManager.defaultManager58            if (!fm.fileExistsAtPath(path)) return@withAccess emptyList()59            val lower = path.lowercase()60            when {61                fm.directoryExists(path) -> listDirectoryPages(path, archivePath)62                isImageName(path) -> listOf(DbPageUrl(filePageUrl(path), path.substringAfterLast('/')))63                lower.endsWith(".cbz") || lower.endsWith(".zip") -> extractZipPages(path)64                lower.endsWith(".cbt") || lower.endsWith(".tar") -> extractTarPages(path)65                else -> emptyList()66            }67        }.orEmpty()68        cacheLock.withLock { extractedPages.putBounded(archivePath, pages) }69        return pages70    }7172    override fun listPagesStrict(archivePath: String): List<DbPageUrl> {73        require(archivePath.isNotBlank()) { "Archive path is blank" }74        return IosSecurityScopedBookmarks.withAccess(archivePath) { path ->75            val fm = NSFileManager.defaultManager76            check(fm.fileExistsAtPath(path)) { "Archive is not readable: $archivePath" }77            when {78                fm.directoryExists(path) -> {79                    val names = fm.contentsOfDirectoryAtPath(path, error = null)80                        ?.filterIsInstance<String>() ?: error("Cannot read image directory: $archivePath")81                    names.filter(::isImageName).sortedWith(naturalPageNameComparator).map { name ->82                        val full = "$path/$name"83                        val input = fopen(full, "rb") ?: error("Unreadable image: $name")84                        check(fclose(input) == 0) { "Unreadable image: $name" }85                        DbPageUrl(filePageUrl(full), name)86                    }87                }88                path.endsWith(".cbz", true) || path.endsWith(".zip", true) -> extractZipPages(path, strict = true)89                isImageName(path) -> {90                    val input = fopen(path, "rb") ?: error("Unreadable image")91                    check(fclose(input) == 0) { "Unreadable image" }92                    listOf(DbPageUrl(filePageUrl(path), path.substringAfterLast('/')))93                }94                path.endsWith(".cbt", true) || path.endsWith(".tar", true) -> extractTarPages(path, strict = true)95                path.endsWith(".cbr", true) || path.endsWith(".rar", true) -> error("Strict RAR inventory is not supported on iOS")96                else -> error("Unsupported image archive: $archivePath")97            }98        } ?: error("Archive is not readable: $archivePath")99    }100101    private fun listDirectoryPages(path: String, logicalRoot: String): List<DbPageUrl> {102        val children = NSFileManager.defaultManager.contentsOfDirectoryAtPath(path, error = null)103            ?.filterIsInstance<String>()104            ?.filter { name -> isImageName(name) }105            ?.sortedWith(naturalPageNameComparator)106            .orEmpty()107        val root = (if (logicalRoot.startsWith("file:")) NSURL.URLWithString(logicalRoot)?.path else logicalRoot)108            ?.trimEnd('/') ?: return emptyList()109        return children.map { name ->110            DbPageUrl(url = filePageUrl("$root/$name"), fileName = name)111        }112    }113114    private fun extractZipPages(path: String, strict: Boolean = false): List<DbPageUrl> {115        val archive = (if (strict) IosZipArchive.openFile(path, strict = true) else zipArchive(path))116            ?: if (strict) error("Unreadable ZIP archive: $path") else return emptyList()117        val names = archive.entryNames118            .filter { name -> !name.startsWith(".") && !name.contains("/.") && isImageName(name) }119            .sortedWith(naturalPageNameComparator)120        if (names.isEmpty()) return emptyList()121        val target = if (strict) freshPagesCacheDir(path) else pagesCacheDir(path)122        val pages = names.mapIndexedNotNull { index, name ->123            val safeName = indexedPageName(index, name)124            val output = "$target/$safeName"125            if (strict || !NSFileManager.defaultManager.fileExistsAtPath(output)) {126                val data = (if (strict) archive.readImage(name, maxStrictZipPageBytes) else archive.read(name))127                    ?: if (strict) error("Unreadable ZIP image: $name") else return@mapIndexedNotNull null128                val partial = "$output.part"129                try {130                    IosLocalFileService.writeBytes(partial, data)131                    check(rename(partial, output) == 0) { "Cannot promote ZIP image: $name" }132                } catch (failure: Throwable) {133                    remove(partial)134                    remove(output)135                    throw failure136                }137            }138            DbPageUrl(url = filePageUrl(output), fileName = safeName)139        }140        pruneExtractedPages(keep = target)141        return pages142    }143144    /** Streams the TAR; a truncated entry ends extraction and keeps the pages read so far. */145    private fun extractTarPages(path: String, strict: Boolean = false): List<DbPageUrl> {146        val input = fopen(path, "rb") ?: return emptyList()147        val target = if (strict) freshPagesCacheDir(path) else pagesCacheDir(path)148        val entries = mutableListOf<Pair<String, DbPageUrl>>()149        try {150            val header = ByteArray(TAR_BLOCK)151            val buffer = ByteArray(TAR_COPY_BUFFER)152            var index = 0153            while (true) {154                val headerRead = input.readBlock(header, header.size)155                if (headerRead == 0) {156                    if (strict) error("Missing TAR end marker")157                    break158                }159                if (headerRead != header.size) {160                    if (strict) error("Truncated TAR header")161                    break162                }163                if (header.all { it == 0.toByte() }) {164                    if (strict) {165                        val end = ByteArray(TAR_BLOCK)166                        check(input.readBlock(end, end.size) == end.size && end.all { it == 0.toByte() }) {167                            "Malformed TAR end marker"168                        }169                    }170                    break171                }172                val name = header.tarString(0, 100)173                if (name.isEmpty()) {174                    if (strict) error("Malformed TAR entry name")175                    break176                }177                val parsedSize = header.tarString(124, 12).toLongOrNull(8)178                if (strict) {179                    check(name.isNotBlank()) { "Malformed TAR entry name" }180                    checkTarHeader(header, parsedSize)181                }182                val size = parsedSize ?: 0L183                if (size < 0) {184                    if (strict) error("Malformed TAR entry size: $name")185                    break186                }187                val padding = (TAR_BLOCK - size % TAR_BLOCK) % TAR_BLOCK188                val type = header[156].toInt().toChar()189                val isPage = (type == '0' || type == 0.toChar()) &&190                    !name.startsWith(".") && !name.contains("/.") && isImageName(name)191                if (!isPage) {192                    val skipped = if (strict) input.skipExactly(size + padding, buffer) else fseek(input, size + padding, SEEK_CUR) == 0193                    if (!skipped) {194                        if (strict) error("Truncated TAR entry: $name")195                        break196                    }197                    continue198                }199                val safeName = indexedPageName(index++, name)200                val output = "$target/$safeName"201                val stored = if (!strict && NSFileManager.defaultManager.fileExistsAtPath(output)) {202                    fseek(input, size, SEEK_CUR) == 0203                } else {204                    input.copyEntryTo(output, size, buffer)205                }206                val paddingSkipped = if (stored && strict) input.skipExactly(padding, buffer) else stored && fseek(input, padding, SEEK_CUR) == 0207                if (!stored || !paddingSkipped) {208                    if (strict) error("Truncated TAR image: $name")209                    break210                }211                entries += name to DbPageUrl(url = filePageUrl(output), fileName = safeName)212            }213        } finally {214            fclose(input)215        }216        pruneExtractedPages(keep = target)217        return entries.sortedWith { left, right -> naturalPageNameComparator.compare(left.first, right.first) }218            .map { it.second }219    }220221    /** Copies [size] bytes to [output] via a temp file so an interrupted copy never looks extracted. */222    private fun CPointer<FILE>.copyEntryTo(output: String, size: Long, buffer: ByteArray): Boolean {223        val partial = "$output.part"224        val file = fopen(partial, "wb") ?: return false225        var remaining = size226        var closed = false227        try {228            while (remaining > 0) {229                val wanted = minOf(remaining, buffer.size.toLong()).toInt()230                val read = readBlock(buffer, wanted)231                if (read <= 0) break232                val written = buffer.usePinned { pinned ->233                    fwrite(pinned.addressOf(0), 1uL, read.toULong(), file)234                }235                if (written != read.toULong()) break236                remaining -= read237            }238        } finally {239            closed = fclose(file) == 0240        }241        if (remaining == 0L && closed && rename(partial, output) == 0) return true242        remove(partial)243        return false244    }245246    private fun CPointer<FILE>.readBlock(buffer: ByteArray, count: Int): Int =247        buffer.usePinned { pinned -> fread(pinned.addressOf(0), 1uL, count.toULong(), this).toInt() }248249    private fun CPointer<FILE>.skipExactly(size: Long, buffer: ByteArray): Boolean {250        var remaining = size251        while (remaining > 0) {252            val read = readBlock(buffer, minOf(remaining, buffer.size.toLong()).toInt())253            if (read <= 0) return false254            remaining -= read255        }256        return true257    }258259    private fun isImageName(name: String): Boolean =260        imageExtensions.any { name.lowercase().endsWith(".$it") }261262    private fun indexedPageName(index: Int, entryName: String): String =263        index.toString().padStart(4, '0') + "_" + entryName.substringAfterLast('/')264265    private fun pagesCacheDir(path: String): String {266        val fm = NSFileManager.defaultManager267        val key = ((path.hashCode().toLong() shl 32) xor fm.fileSize(path)).toULong().toString(16)268        val dir = "$extractionRoot/$key"269        fm.createDirectoryAtPath(dir, withIntermediateDirectories = true, attributes = null, error = null)270        markUsed(dir)271        return dir272    }273274    private fun freshPagesCacheDir(path: String): String {275        val dir = "$extractionRoot/strict-${Random.nextLong().toULong()}-${path.hashCode()}"276        check(NSFileManager.defaultManager.createDirectoryAtPath(dir, withIntermediateDirectories = true, attributes = null, error = null)) {277            "Cannot create archive extraction directory"278        }279        markUsed(dir)280        return dir281    }282283    /** Marks the extraction directory behind cached [pages] used; false once it was pruned (re-extract). */284    private fun touchExtraction(pages: List<DbPageUrl>): Boolean {285        val directory = pages.firstOrNull()?.url?.removePrefix("file://")?.substringBeforeLast('/') ?: return true286        if (directory.substringBeforeLast('/') != extractionRoot) return true // image folders list their own files287        return markUsed(directory)288    }289290    /** Deletes the least recently used extraction directories (never [keep]) beyond [extractedPagesBudgetBytes]. */291    private fun pruneExtractedPages(keep: String) {292        val fm = NSFileManager.defaultManager293        val directories = fm.contentsOfDirectoryAtPath(extractionRoot, error = null).orEmpty()294            .filterIsInstance<String>()295            .map { name -> "$extractionRoot/$name" }296            .map { directory -> Triple(directory, fm.modifiedAt(directory), IosLocalFileService.directorySize(directory)) }297            .sortedBy { it.second }298        var bytes = directories.sumOf { it.third }299        for ((directory, _, size) in directories) {300            if (bytes <= extractedPagesBudgetBytes) break301            if (directory == keep) continue302            fm.removeItemAtPath(directory, error = null)303            bytes -= size304        }305    }306307    override fun invalidateIndexCache() = cacheLock.withLock {308        epubChapterCache.clear()309        zipArchives.clear()310    }311312    override fun listEpubChapters(archivePath: String): List<LocalEpubChapter> {313        if (archivePath.isBlank()) return emptyList()314        return IosSecurityScopedBookmarks.withAccess(archivePath) { path ->315            val key = archiveFingerprint(path)316            cacheLock.withLock { epubChapterCache[key] }?.let { return@withAccess it }317            val chapters = zipArchive(path)?.let { archive ->318                runCatching { readEpubManifest(archive::read) }.getOrDefault(emptyList())319            } ?: return@withAccess emptyList()320            cacheLock.withLock { epubChapterCache.putBounded(key, chapters) }321            chapters322        } ?: emptyList()323    }324325    override fun readEpubChapter(archivePath: String, index: Int): String {326        val href = listEpubChapters(archivePath).getOrNull(index)?.href ?: return ""327        return readEpubResource(archivePath, href)?.decodeToString().orEmpty()328    }329330    override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? =331        IosSecurityScopedBookmarks.withAccess(archivePath) { path -> zipArchive(path)?.read(resourcePath) }332333    override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? {334        val source = directoryPath.removePrefix("file://")335        val fm = NSFileManager.defaultManager336        if (!fm.directoryExists(source)) return null337        val names = fm.contentsOfDirectoryAtPath(source, error = null)338            ?.filterIsInstance<String>()339            ?.filter { name ->340                !fm.directoryExists("$source/$name") && !name.startsWith(".") && (isImageName(name) || name == CHAPTER_METADATA_FILE)341            }342            ?.sortedWith(naturalPageNameComparator)343            .orEmpty()344        if (names.isEmpty()) return null345        val targetPath = "$source.cbz"346        val pages = names.asSequence().map { name -> name to files.readBytes("$source/$name") }347        check(writeStoredZipFile(targetPath, pages)) { "Failed to write file: $targetPath" }348        if (deleteSource) fm.removeItemAtPath(source, error = null)349        return targetPath350    }351352    /** Entry table of the already resolved [path], cached by path and size so a rewritten file reopens. */353    private fun archiveFingerprint(path: String): String =354        "$path:${NSFileManager.defaultManager.fileSize(path)}:${NSFileManager.defaultManager.modifiedAt(path)}"355356    private fun zipArchive(path: String): IosZipArchive? {357        val key = archiveFingerprint(path)358        cacheLock.withLock { zipArchives.remove(key)?.also { zipArchives[key] = it } }?.let { return it }359        val archive = IosZipArchive.openFile(path) ?: return null360        cacheLock.withLock { zipArchives.putBounded(key, archive) }361        return archive362    }363364    private fun <V> LinkedHashMap<String, V>.putBounded(key: String, value: V) {365        remove(key)366        put(key, value)367        while (size > MAX_METADATA_CACHE_ENTRIES) remove(keys.first())368    }369370    private companion object {371        const val MAX_METADATA_CACHE_ENTRIES = 8372        const val TAR_BLOCK = 512373        const val TAR_COPY_BUFFER = 64 * 1024374    }375}376377/** Encode the actual path bytes once; NSURL.fileURLWithPath treats literal "%20" as an escape. */378private fun filePageUrl(path: String): String = buildString {379    append("file://")380    val hex = "0123456789ABCDEF"381    path.encodeToByteArray().forEach { byte ->382        val value = byte.toInt() and 255383        if (value in 'A'.code..'Z'.code || value in 'a'.code..'z'.code ||384            value in '0'.code..'9'.code || value == '/'.code || value == '-'.code ||385            value == '.'.code || value == '_'.code || value == '~'.code386        ) append(value.toChar()) else {387            append('%')388            append(hex[value ushr 4])389            append(hex[value and 15])390        }391    }392}393394/** Bumps [path]'s modification time, the LRU clock for extraction directories; false when it is gone. */395@OptIn(ExperimentalForeignApi::class)396private fun markUsed(path: String): Boolean =397    NSFileManager.defaultManager.setAttributes(mapOf<Any?, Any?>(NSFileModificationDate to NSDate()), ofItemAtPath = path, error = null)398399@OptIn(ExperimentalForeignApi::class)400private fun NSFileManager.modifiedAt(path: String): Double =401    (attributesOfItemAtPath(path, error = null)?.get(NSFileModificationDate) as? NSDate)?.timeIntervalSince1970 ?: 0.0402403private fun ByteArray.tarString(start: Int, length: Int): String {404    val end = (start + length).coerceAtMost(size)405    if (start >= end) return ""406    return sliceArray(start until end).takeWhile { it != 0.toByte() }.toByteArray().decodeToString().trim()407}408409private fun checkTarHeader(header: ByteArray, size: Long?) {410    check(size != null && size >= 0) { "Malformed TAR entry size" }411    val storedChecksum = header.tarString(148, 8).toLongOrNull(8)412    check(storedChecksum != null) { "Malformed TAR checksum" }413    val checksum = header.indices.sumOf { index ->414        if (index in 148..155) 32 else header[index].toInt() and 0xff415    }416    check(checksum.toLong() == storedChecksum) { "TAR header checksum mismatch" }417}418

Search chapters, reference and source filenames.