package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.cinterop.BetaInteropApi import kotlinx.cinterop.CPointer import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.addressOf import kotlinx.cinterop.usePinned import platform.Foundation.NSDate import platform.Foundation.NSFileManager import platform.Foundation.NSFileModificationDate import platform.Foundation.NSURL import platform.Foundation.timeIntervalSince1970 import platform.posix.FILE import platform.posix.SEEK_CUR import platform.posix.fclose import platform.posix.fopen import platform.posix.fread import platform.posix.fseek import platform.posix.fwrite import platform.posix.remove import platform.posix.rename import kotlin.random.Random actual fun createPlatformLocalArchiveService(profileId: eu.friedcutlet.yokan.domain.ProfileId): LocalArchiveService = IosLocalArchiveService(files = createPlatformLocalFileService(profileId)) actual fun createPlatformLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId): LocalFileService = if (profileId == eu.friedcutlet.yokan.domain.ProfileId.Default) IosLocalFileService else IosProfileLocalFileService(profileId) /** * iOS archive support. Image directories list directly through NSFileManager; CBZ/ZIP pages and * EPUB chapters read through a file-backed [IosZipArchive]; CBT/TAR pages stream entry by entry. Pages * extract into `cacheRoot/archives/` like the JVM implementation, kept least-recently-used within * [extractedPagesBudgetBytes]; zipDirectoryToCbz streams a stored ZIP. * * Memory ceiling: TAR uses one 512 B header and one 64 KiB copy buffer. ZIP reads keep the entry * tables of 8 archives and hold one entry at a time; plus 8 page lists and 8 chapter lists. */ @OptIn(ExperimentalForeignApi::class, BetaInteropApi::class) internal class IosLocalArchiveService( // ponytail: fixed 1 GiB of extracted pages; make it a storage setting if users want a bigger offline cache. private val files: LocalFileService = IosLocalFileService, private val extractedPagesBudgetBytes: Long = 1L shl 30, ) : LocalArchiveService { private val imageExtensions = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif") private val zipArchives = LinkedHashMap() private val epubChapterCache = LinkedHashMap>() private val extractedPages = LinkedHashMap>() private val cacheLock = PlatformLock() private val extractionRoot = "${files.cacheRoot}/archives" private val maxStrictZipPageBytes = 25L * 1024 * 1024 override fun listPages(archivePath: String): List { if (archivePath.isBlank()) return emptyList() cacheLock.withLock { extractedPages[archivePath] }?.takeIf { touchExtraction(it) }?.let { return it } val pages = IosSecurityScopedBookmarks.withAccess(archivePath) { path -> val fm = NSFileManager.defaultManager if (!fm.fileExistsAtPath(path)) return@withAccess emptyList() val lower = path.lowercase() when { fm.directoryExists(path) -> listDirectoryPages(path, archivePath) isImageName(path) -> listOf(DbPageUrl(filePageUrl(path), path.substringAfterLast('/'))) lower.endsWith(".cbz") || lower.endsWith(".zip") -> extractZipPages(path) lower.endsWith(".cbt") || lower.endsWith(".tar") -> extractTarPages(path) else -> emptyList() } }.orEmpty() cacheLock.withLock { extractedPages.putBounded(archivePath, pages) } return pages } override fun listPagesStrict(archivePath: String): List { require(archivePath.isNotBlank()) { "Archive path is blank" } return IosSecurityScopedBookmarks.withAccess(archivePath) { path -> val fm = NSFileManager.defaultManager check(fm.fileExistsAtPath(path)) { "Archive is not readable: $archivePath" } when { fm.directoryExists(path) -> { val names = fm.contentsOfDirectoryAtPath(path, error = null) ?.filterIsInstance() ?: error("Cannot read image directory: $archivePath") names.filter(::isImageName).sortedWith(naturalPageNameComparator).map { name -> val full = "$path/$name" val input = fopen(full, "rb") ?: error("Unreadable image: $name") check(fclose(input) == 0) { "Unreadable image: $name" } DbPageUrl(filePageUrl(full), name) } } path.endsWith(".cbz", true) || path.endsWith(".zip", true) -> extractZipPages(path, strict = true) isImageName(path) -> { val input = fopen(path, "rb") ?: error("Unreadable image") check(fclose(input) == 0) { "Unreadable image" } listOf(DbPageUrl(filePageUrl(path), path.substringAfterLast('/'))) } path.endsWith(".cbt", true) || path.endsWith(".tar", true) -> extractTarPages(path, strict = true) path.endsWith(".cbr", true) || path.endsWith(".rar", true) -> error("Strict RAR inventory is not supported on iOS") else -> error("Unsupported image archive: $archivePath") } } ?: error("Archive is not readable: $archivePath") } private fun listDirectoryPages(path: String, logicalRoot: String): List { val children = NSFileManager.defaultManager.contentsOfDirectoryAtPath(path, error = null) ?.filterIsInstance() ?.filter { name -> isImageName(name) } ?.sortedWith(naturalPageNameComparator) .orEmpty() val root = (if (logicalRoot.startsWith("file:")) NSURL.URLWithString(logicalRoot)?.path else logicalRoot) ?.trimEnd('/') ?: return emptyList() return children.map { name -> DbPageUrl(url = filePageUrl("$root/$name"), fileName = name) } } private fun extractZipPages(path: String, strict: Boolean = false): List { val archive = (if (strict) IosZipArchive.openFile(path, strict = true) else zipArchive(path)) ?: if (strict) error("Unreadable ZIP archive: $path") else return emptyList() val names = archive.entryNames .filter { name -> !name.startsWith(".") && !name.contains("/.") && isImageName(name) } .sortedWith(naturalPageNameComparator) if (names.isEmpty()) return emptyList() val target = if (strict) freshPagesCacheDir(path) else pagesCacheDir(path) val pages = names.mapIndexedNotNull { index, name -> val safeName = indexedPageName(index, name) val output = "$target/$safeName" if (strict || !NSFileManager.defaultManager.fileExistsAtPath(output)) { val data = (if (strict) archive.readImage(name, maxStrictZipPageBytes) else archive.read(name)) ?: if (strict) error("Unreadable ZIP image: $name") else return@mapIndexedNotNull null val partial = "$output.part" try { IosLocalFileService.writeBytes(partial, data) check(rename(partial, output) == 0) { "Cannot promote ZIP image: $name" } } catch (failure: Throwable) { remove(partial) remove(output) throw failure } } DbPageUrl(url = filePageUrl(output), fileName = safeName) } pruneExtractedPages(keep = target) return pages } /** Streams the TAR; a truncated entry ends extraction and keeps the pages read so far. */ private fun extractTarPages(path: String, strict: Boolean = false): List { val input = fopen(path, "rb") ?: return emptyList() val target = if (strict) freshPagesCacheDir(path) else pagesCacheDir(path) val entries = mutableListOf>() try { val header = ByteArray(TAR_BLOCK) val buffer = ByteArray(TAR_COPY_BUFFER) var index = 0 while (true) { val headerRead = input.readBlock(header, header.size) if (headerRead == 0) { if (strict) error("Missing TAR end marker") break } if (headerRead != header.size) { if (strict) error("Truncated TAR header") break } if (header.all { it == 0.toByte() }) { if (strict) { val end = ByteArray(TAR_BLOCK) check(input.readBlock(end, end.size) == end.size && end.all { it == 0.toByte() }) { "Malformed TAR end marker" } } break } val name = header.tarString(0, 100) if (name.isEmpty()) { if (strict) error("Malformed TAR entry name") break } val parsedSize = header.tarString(124, 12).toLongOrNull(8) if (strict) { check(name.isNotBlank()) { "Malformed TAR entry name" } checkTarHeader(header, parsedSize) } val size = parsedSize ?: 0L if (size < 0) { if (strict) error("Malformed TAR entry size: $name") break } val padding = (TAR_BLOCK - size % TAR_BLOCK) % TAR_BLOCK val type = header[156].toInt().toChar() val isPage = (type == '0' || type == 0.toChar()) && !name.startsWith(".") && !name.contains("/.") && isImageName(name) if (!isPage) { val skipped = if (strict) input.skipExactly(size + padding, buffer) else fseek(input, size + padding, SEEK_CUR) == 0 if (!skipped) { if (strict) error("Truncated TAR entry: $name") break } continue } val safeName = indexedPageName(index++, name) val output = "$target/$safeName" val stored = if (!strict && NSFileManager.defaultManager.fileExistsAtPath(output)) { fseek(input, size, SEEK_CUR) == 0 } else { input.copyEntryTo(output, size, buffer) } val paddingSkipped = if (stored && strict) input.skipExactly(padding, buffer) else stored && fseek(input, padding, SEEK_CUR) == 0 if (!stored || !paddingSkipped) { if (strict) error("Truncated TAR image: $name") break } entries += name to DbPageUrl(url = filePageUrl(output), fileName = safeName) } } finally { fclose(input) } pruneExtractedPages(keep = target) return entries.sortedWith { left, right -> naturalPageNameComparator.compare(left.first, right.first) } .map { it.second } } /** Copies [size] bytes to [output] via a temp file so an interrupted copy never looks extracted. */ private fun CPointer.copyEntryTo(output: String, size: Long, buffer: ByteArray): Boolean { val partial = "$output.part" val file = fopen(partial, "wb") ?: return false var remaining = size var closed = false try { while (remaining > 0) { val wanted = minOf(remaining, buffer.size.toLong()).toInt() val read = readBlock(buffer, wanted) if (read <= 0) break val written = buffer.usePinned { pinned -> fwrite(pinned.addressOf(0), 1uL, read.toULong(), file) } if (written != read.toULong()) break remaining -= read } } finally { closed = fclose(file) == 0 } if (remaining == 0L && closed && rename(partial, output) == 0) return true remove(partial) return false } private fun CPointer.readBlock(buffer: ByteArray, count: Int): Int = buffer.usePinned { pinned -> fread(pinned.addressOf(0), 1uL, count.toULong(), this).toInt() } private fun CPointer.skipExactly(size: Long, buffer: ByteArray): Boolean { var remaining = size while (remaining > 0) { val read = readBlock(buffer, minOf(remaining, buffer.size.toLong()).toInt()) if (read <= 0) return false remaining -= read } return true } private fun isImageName(name: String): Boolean = imageExtensions.any { name.lowercase().endsWith(".$it") } private fun indexedPageName(index: Int, entryName: String): String = index.toString().padStart(4, '0') + "_" + entryName.substringAfterLast('/') private fun pagesCacheDir(path: String): String { val fm = NSFileManager.defaultManager val key = ((path.hashCode().toLong() shl 32) xor fm.fileSize(path)).toULong().toString(16) val dir = "$extractionRoot/$key" fm.createDirectoryAtPath(dir, withIntermediateDirectories = true, attributes = null, error = null) markUsed(dir) return dir } private fun freshPagesCacheDir(path: String): String { val dir = "$extractionRoot/strict-${Random.nextLong().toULong()}-${path.hashCode()}" check(NSFileManager.defaultManager.createDirectoryAtPath(dir, withIntermediateDirectories = true, attributes = null, error = null)) { "Cannot create archive extraction directory" } markUsed(dir) return dir } /** Marks the extraction directory behind cached [pages] used; false once it was pruned (re-extract). */ private fun touchExtraction(pages: List): Boolean { val directory = pages.firstOrNull()?.url?.removePrefix("file://")?.substringBeforeLast('/') ?: return true if (directory.substringBeforeLast('/') != extractionRoot) return true // image folders list their own files return markUsed(directory) } /** Deletes the least recently used extraction directories (never [keep]) beyond [extractedPagesBudgetBytes]. */ private fun pruneExtractedPages(keep: String) { val fm = NSFileManager.defaultManager val directories = fm.contentsOfDirectoryAtPath(extractionRoot, error = null).orEmpty() .filterIsInstance() .map { name -> "$extractionRoot/$name" } .map { directory -> Triple(directory, fm.modifiedAt(directory), IosLocalFileService.directorySize(directory)) } .sortedBy { it.second } var bytes = directories.sumOf { it.third } for ((directory, _, size) in directories) { if (bytes <= extractedPagesBudgetBytes) break if (directory == keep) continue fm.removeItemAtPath(directory, error = null) bytes -= size } } override fun invalidateIndexCache() = cacheLock.withLock { epubChapterCache.clear() zipArchives.clear() } override fun listEpubChapters(archivePath: String): List { if (archivePath.isBlank()) return emptyList() return IosSecurityScopedBookmarks.withAccess(archivePath) { path -> val key = archiveFingerprint(path) cacheLock.withLock { epubChapterCache[key] }?.let { return@withAccess it } val chapters = zipArchive(path)?.let { archive -> runCatching { readEpubManifest(archive::read) }.getOrDefault(emptyList()) } ?: return@withAccess emptyList() cacheLock.withLock { epubChapterCache.putBounded(key, chapters) } chapters } ?: emptyList() } override fun readEpubChapter(archivePath: String, index: Int): String { val href = listEpubChapters(archivePath).getOrNull(index)?.href ?: return "" return readEpubResource(archivePath, href)?.decodeToString().orEmpty() } override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = IosSecurityScopedBookmarks.withAccess(archivePath) { path -> zipArchive(path)?.read(resourcePath) } override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? { val source = directoryPath.removePrefix("file://") val fm = NSFileManager.defaultManager if (!fm.directoryExists(source)) return null val names = fm.contentsOfDirectoryAtPath(source, error = null) ?.filterIsInstance() ?.filter { name -> !fm.directoryExists("$source/$name") && !name.startsWith(".") && (isImageName(name) || name == CHAPTER_METADATA_FILE) } ?.sortedWith(naturalPageNameComparator) .orEmpty() if (names.isEmpty()) return null val targetPath = "$source.cbz" val pages = names.asSequence().map { name -> name to files.readBytes("$source/$name") } check(writeStoredZipFile(targetPath, pages)) { "Failed to write file: $targetPath" } if (deleteSource) fm.removeItemAtPath(source, error = null) return targetPath } /** Entry table of the already resolved [path], cached by path and size so a rewritten file reopens. */ private fun archiveFingerprint(path: String): String = "$path:${NSFileManager.defaultManager.fileSize(path)}:${NSFileManager.defaultManager.modifiedAt(path)}" private fun zipArchive(path: String): IosZipArchive? { val key = archiveFingerprint(path) cacheLock.withLock { zipArchives.remove(key)?.also { zipArchives[key] = it } }?.let { return it } val archive = IosZipArchive.openFile(path) ?: return null cacheLock.withLock { zipArchives.putBounded(key, archive) } return archive } private fun LinkedHashMap.putBounded(key: String, value: V) { remove(key) put(key, value) while (size > MAX_METADATA_CACHE_ENTRIES) remove(keys.first()) } private companion object { const val MAX_METADATA_CACHE_ENTRIES = 8 const val TAR_BLOCK = 512 const val TAR_COPY_BUFFER = 64 * 1024 } } /** Encode the actual path bytes once; NSURL.fileURLWithPath treats literal "%20" as an escape. */ private fun filePageUrl(path: String): String = buildString { append("file://") val hex = "0123456789ABCDEF" path.encodeToByteArray().forEach { byte -> val value = byte.toInt() and 255 if (value in 'A'.code..'Z'.code || value in 'a'.code..'z'.code || value in '0'.code..'9'.code || value == '/'.code || value == '-'.code || value == '.'.code || value == '_'.code || value == '~'.code ) append(value.toChar()) else { append('%') append(hex[value ushr 4]) append(hex[value and 15]) } } } /** Bumps [path]'s modification time, the LRU clock for extraction directories; false when it is gone. */ @OptIn(ExperimentalForeignApi::class) private fun markUsed(path: String): Boolean = NSFileManager.defaultManager.setAttributes(mapOf(NSFileModificationDate to NSDate()), ofItemAtPath = path, error = null) @OptIn(ExperimentalForeignApi::class) private fun NSFileManager.modifiedAt(path: String): Double = (attributesOfItemAtPath(path, error = null)?.get(NSFileModificationDate) as? NSDate)?.timeIntervalSince1970 ?: 0.0 private fun ByteArray.tarString(start: Int, length: Int): String { val end = (start + length).coerceAtMost(size) if (start >= end) return "" return sliceArray(start until end).takeWhile { it != 0.toByte() }.toByteArray().decodeToString().trim() } private fun checkTarHeader(header: ByteArray, size: Long?) { check(size != null && size >= 0) { "Malformed TAR entry size" } val storedChecksum = header.tarString(148, 8).toLongOrNull(8) check(storedChecksum != null) { "Malformed TAR checksum" } val checksum = header.indices.sumOf { index -> if (index in 148..155) 32 else header[index].toInt() and 0xff } check(checksum.toLong() == storedChecksum) { "TAR header checksum mismatch" } }