package eu.friedcutlet.yokan.services.files import kotlinx.cinterop.BetaInteropApi import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.addressOf import kotlinx.cinterop.autoreleasepool import kotlinx.cinterop.usePinned import platform.Foundation.NSDate import platform.Foundation.NSFileModificationDate import platform.Foundation.NSCachesDirectory import platform.Foundation.NSData import platform.Foundation.NSDataReadingMappedIfSafe import platform.Foundation.NSDocumentDirectory import platform.Foundation.NSFileManager import platform.Foundation.NSFileType import platform.Foundation.NSFileTypeDirectory import platform.Foundation.NSFileTypeRegular import platform.Foundation.NSHomeDirectory import platform.Foundation.NSSearchPathForDirectoriesInDomains import platform.Foundation.NSURL import platform.Foundation.NSUserDomainMask import platform.Foundation.create import platform.Foundation.dataWithContentsOfFile import platform.Foundation.timeIntervalSince1970 import platform.Foundation.writeToFile import platform.posix.fclose import platform.posix.fopen import platform.posix.fwrite import platform.posix.rename /** * iOS filesystem service: app Documents/Caches roots plus user folders reached through * [IosSecurityScopedBookmarks]. Paths may carry a `file://` prefix. */ @OptIn(ExperimentalForeignApi::class, BetaInteropApi::class) internal object IosLocalFileService : LocalFileService by IosProfileLocalFileService(eu.friedcutlet.yokan.domain.ProfileId.Default) @OptIn(ExperimentalForeignApi::class, BetaInteropApi::class) internal class IosProfileLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId) : LocalFileService { private val namespace = eu.friedcutlet.yokan.domain.ProfileStorageNamespace(profileId) private val fm get() = NSFileManager.defaultManager private val documentsDir: String = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, true, ).firstOrNull()?.toString() ?: "${NSHomeDirectory()}/Documents" private val cachesDir: String = NSSearchPathForDirectoriesInDomains( NSCachesDirectory, NSUserDomainMask, true, ).firstOrNull()?.toString() ?: "${NSHomeDirectory()}/Library/Caches" override val downloadRoot: String = ensureDirectory(if (namespace.relativeRoot == null) "$documentsDir/Yokan/downloads" else "${namespace.ownedRoot(documentsDir)}/downloads") override val backupRoot: String = ensureDirectory(if (namespace.relativeRoot == null) "$documentsDir/Yokan/backups" else "${namespace.ownedRoot(documentsDir)}/backups") override val cacheRoot: String = ensureDirectory(if (namespace.relativeRoot == null) "$cachesDir/Yokan" else "${namespace.ownedRoot(cachesDir)}/cache") override fun writeBytes(path: String, bytes: ByteArray) { val resolved = path.removePrefix("file://") val parent = resolved.substringBeforeLast('/', missingDelimiterValue = "") if (parent.isNotEmpty()) ensureDirectory(parent) // Borrow the pinned array instead of copying it into NSData; the write finishes before unpinning. val written = autoreleasepool { if (bytes.isEmpty()) { NSData.create(bytes = null, length = 0uL).writeToFile(resolved, atomically = true) } else { bytes.usePinned { pinned -> NSData.create(bytesNoCopy = pinned.addressOf(0), length = bytes.size.toULong(), freeWhenDone = false) .writeToFile(resolved, atomically = true) } } } check(written) { "Failed to write file: $resolved" } } override fun appendBytes(path: String, bytes: ByteArray) { if (bytes.isEmpty()) return val resolved = path.removePrefix("file://") if (!fm.fileExistsAtPath(resolved)) { writeBytes(resolved, bytes) return } val handle = fopen(resolved, "ab") ?: error("Failed to open file for append: $resolved") try { val written = bytes.usePinned { pinned -> fwrite(pinned.addressOf(0), 1uL, bytes.size.toULong(), handle) } check(written == bytes.size.toULong()) { "Short write while appending file: $resolved" } } finally { check(fclose(handle) == 0) { "Failed to close file after append: $resolved" } } } override suspend fun writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T { val resolved = path.removePrefix("file://") val parent = resolved.substringBeforeLast('/', missingDelimiterValue = "") if (parent.isNotEmpty()) ensureDirectory(parent) val handle = fopen(resolved, "wb") ?: error("Failed to open file for writing: $resolved") val result = try { block { bytes -> if (bytes.isNotEmpty()) { val written = bytes.usePinned { pinned -> fwrite(pinned.addressOf(0), 1uL, bytes.size.toULong(), handle) } check(written == bytes.size.toULong()) { "Short write while writing file: $resolved" } } } } catch (error: Throwable) { fclose(handle) throw error } check(fclose(handle) == 0) { "Failed to close file after writing: $resolved" } return result } override suspend fun appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T { val resolved = path.removePrefix("file://") val parent = resolved.substringBeforeLast('/', missingDelimiterValue = "") if (parent.isNotEmpty()) ensureDirectory(parent) val handle = fopen(resolved, "ab") ?: error("Failed to open file for writing: $resolved") val result = try { block { bytes -> if (bytes.isNotEmpty()) { val written = bytes.usePinned { pinned -> fwrite(pinned.addressOf(0), 1uL, bytes.size.toULong(), handle) } check(written == bytes.size.toULong()) { "Short write while writing file: $resolved" } } } } catch (error: Throwable) { fclose(handle) throw error } check(fclose(handle) == 0) { "Failed to close file after writing: $resolved" } return result } override fun promote(sourcePath: String, targetPath: String): Boolean = IosSecurityScopedBookmarks.withAccess(sourcePath) { source -> IosSecurityScopedBookmarks.withAccess(targetPath) { target -> if (!fm.fileExistsAtPath(source)) return@withAccess false val parent = target.substringBeforeLast('/', missingDelimiterValue = "") if (parent.isNotEmpty()) ensureDirectory(parent) if (fm.fileExistsAtPath(target) && !fm.removeItemAtPath(target, error = null)) { return@withAccess false } if (!fm.moveItemAtPath(source, toPath = target, error = null)) return@withAccess false fm.fileExistsAtPath(target) && !fm.fileExistsAtPath(source) } } ?: false override fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean = IosSecurityScopedBookmarks.withAccess(tempPath) { source -> IosSecurityScopedBookmarks.withAccess(finalPath) { target -> if (source.substringBeforeLast('/') != target.substringBeforeLast('/') || !fm.fileExistsAtPath(source) || fm.directoryExists(source) ) return@withAccess false rename(source, target) == 0 } } ?: false override fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean = IosSecurityScopedBookmarks.withAccess(stagedPath) { source -> IosSecurityScopedBookmarks.withAccess(finalPath) { target -> if (source.substringBeforeLast('/') != target.substringBeforeLast('/') || !fm.directoryExists(source) || fm.fileExistsAtPath(target) ) return@withAccess false // ponytail: precheck+rename is not safe against external same-name racers; rely only on // the app-owned namespace with one queue writer and random IDs, or add a native RENAME_EXCL shim. rename(source, target) == 0 } } ?: false override fun readBytes(path: String): ByteArray { return IosSecurityScopedBookmarks.withAccess(path) { raw -> val resolved = raw.fileSystemPath() // Mapped (clean, evictable) pages instead of a second heap copy; the pool unmaps them after the copy out. autoreleasepool { val data = NSData.dataWithContentsOfFile(resolved, NSDataReadingMappedIfSafe, null) ?: return@autoreleasepool ByteArray(0) val length = data.length.toInt() if (length == 0) return@autoreleasepool ByteArray(0) val bytes = ByteArray(length) bytes.usePinned { pinned -> platform.posix.memcpy(pinned.addressOf(0), data.bytes, length.toULong()) } bytes } } ?: ByteArray(0) } override fun readBytesBounded(path: String, maxBytes: Long): ByteArray { require(maxBytes >= 0 && maxBytes < Int.MAX_VALUE) { "Invalid byte limit" } return IosSecurityScopedBookmarks.withAccess(path) { raw -> val resolved = raw.fileSystemPath() val actualSize = fm.fileSize(resolved) check(actualSize <= maxBytes) { "File exceeds $maxBytes bytes" } val file = fopen(resolved, "rb") ?: error("Cannot open file: $path") var bytes = ByteArray(minOf(actualSize, 64L * 1024).toInt()) var total = 0L try { while (total <= maxBytes) { if (total == bytes.size.toLong()) { if (total == maxBytes) { val extra = ByteArray(1) val count = extra.usePinned { pinned -> platform.posix.fread(pinned.addressOf(0), 1uL, 1uL, file).toInt() } if (count > 0) total++ break } val nextSize = minOf(maxBytes + 1, maxOf(16L * 1024, bytes.size.toLong() * 2)) bytes = bytes.copyOf(nextSize.toInt()) } val count = bytes.usePinned { pinned -> platform.posix.fread( pinned.addressOf(total.toInt()), 1uL, minOf(bytes.size.toLong() - total, maxBytes + 1 - total).toULong(), file, ).toInt() } if (count == 0) break total += count } } finally { fclose(file) } check(total == actualSize) { "File changed or was truncated while reading: $path" } check(total <= maxBytes) { "File exceeds $maxBytes bytes" } bytes.copyOf(minOf(total, maxBytes).toInt()) } ?: error("Cannot read file: $path") } override fun canonicalPath(path: String): String? = IosSecurityScopedBookmarks.withAccess(path) { resolved -> NSURL.fileURLWithPath(resolved).URLByResolvingSymlinksInPath?.path } override fun exists(path: String): Boolean = IosSecurityScopedBookmarks.withAccess(path) { resolved -> fm.fileExistsAtPath(resolved) } ?: false override fun deleteRecursively(path: String): Boolean { return IosSecurityScopedBookmarks.withAccess(path) { resolved -> if (!fm.fileExistsAtPath(resolved)) true else fm.removeItemAtPath(resolved, error = null) } ?: false } override fun directorySize(path: String): Long { return IosSecurityScopedBookmarks.withAccess(path) { resolved -> if (!fm.fileExistsAtPath(resolved)) 0L else walkSize(resolved) } ?: 0L } override fun openLocation(path: String): Boolean { return IosSecurityScopedBookmarks.withAccess(path) { resolved -> val url = NSURL.fileURLWithPath(resolved) platform.UIKit.UIApplication.sharedApplication.openURL(url) } ?: false } override fun listLocalEntries(root: String): List? { return IosSecurityScopedBookmarks.withAccess(root) { resolved -> if (!fm.directoryExists(resolved)) return@withAccess null listLocalEntriesRecursive(resolved, root.removePrefix("file://")) } } override fun listDirectoryEntries(root: String): List? = IosSecurityScopedBookmarks.withAccess(root) { resolved -> val names = fm.contentsOfDirectoryAtPath(resolved, error = null) ?: return@withAccess null names.filterIsInstance().mapNotNull { name -> val type = fm.attributesOfItemAtPath("$resolved/$name", error = null)?.get(NSFileType) if (type != NSFileTypeDirectory && type != NSFileTypeRegular) return@mapNotNull null LocalDirectoryEntry("${root.removePrefix("file://").trimEnd('/')}/$name", name, type == NSFileTypeDirectory) }.sortedBy { it.name.lowercase() } } private fun listLocalEntriesRecursive(root: String, logicalRoot: String): List? { val names = fm.contentsOfDirectoryAtPath(root, error = null) ?: return null return names.filterIsInstance() .sortedBy { it.lowercase() } .flatMap { name -> val full = "$root/$name" val logical = "$logicalRoot/$name" when { !fm.directoryExists(full) && hasReadableExtension(name) -> listOf(LocalEntry(path = logical, name = name.substringBeforeLast('.'), isArchive = true)) fm.directoryExists(full) && directoryContainsReadableFiles(full) -> listOf(LocalEntry(path = logical, name = name, isArchive = false)) fm.directoryExists(full) -> listLocalEntriesRecursive(full, logical) ?: return null else -> emptyList() } } } override fun listFiles(root: String): List { return IosSecurityScopedBookmarks.withAccess(root) { resolved -> if (!fm.directoryExists(resolved)) return@withAccess emptyList() fm.contentsOfDirectoryAtPath(resolved, error = null) ?.filterIsInstance() ?.map { name -> val full = "$resolved/$name" LocalFileEntry( path = "${root.removePrefix("file://").trimEnd('/')}/$name", name = name, sizeBytes = fm.fileSize(full), lastModified = ((fm.attributesOfItemAtPath(full, error = null)?.get(NSFileModificationDate) as? NSDate)?.timeIntervalSince1970?.times(1000))?.toLong() ?: 0L, ) } .orEmpty() }.orEmpty() } private fun ensureDirectory(path: String): String { if (!fm.fileExistsAtPath(path)) { fm.createDirectoryAtPath(path, withIntermediateDirectories = true, attributes = null, error = null) } return path } private fun walkSize(path: String): Long { if (!fm.directoryExists(path)) return fm.fileSize(path) val children = fm.contentsOfDirectoryAtPath(path, error = null)?.filterIsInstance().orEmpty() return children.sumOf { walkSize("$path/$it") } } private fun directoryContainsReadableFiles(path: String): Boolean = fm.contentsOfDirectoryAtPath(path, error = null) ?.filterIsInstance() ?.any { name -> val full = "$path/$name" !fm.directoryExists(full) && hasReadableExtension(name) } == true private fun hasReadableExtension(name: String): Boolean { val lower = name.lowercase() return lower.endsWith(".cbz") || lower.endsWith(".zip") || lower.endsWith(".cbt") || lower.endsWith(".tar") || lower.endsWith(".epub") || lower.endsWith(".png") || lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".gif") || lower.endsWith(".webp") || lower.endsWith(".bmp") || lower.endsWith(".avif") || lower.endsWith(".mp4") || lower.endsWith(".mkv") || lower.endsWith(".mov") || lower.endsWith(".webm") || lower.endsWith(".avi") || lower.endsWith(".m4v") || lower.endsWith(".ts") || lower.endsWith(".m3u8") || lower.endsWith(".txt") || lower.endsWith(".html") || lower.endsWith(".xhtml") || lower.endsWith(".md") } } private fun String.fileSystemPath(): String = if (startsWith("file:")) NSURL.URLWithString(this)?.path ?: error("Invalid file URL: $this") else this @OptIn(ExperimentalForeignApi::class) internal fun NSFileManager.directoryExists(path: String): Boolean { return fileExistsAtPath(path) && contentsOfDirectoryAtPath(path, error = null) != null } @OptIn(ExperimentalForeignApi::class) internal fun NSFileManager.fileSize(path: String): Long { val attrs = attributesOfItemAtPath(path, error = null) ?: return 0L val size = attrs["NSFileSize"] as? platform.Foundation.NSNumber ?: return 0L return size.longLongValue }