IosLocalFileService.ios.kt
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/IosLocalFileService.ios.kt
1package eu.friedcutlet.yokan.services.files23import kotlinx.cinterop.BetaInteropApi4import kotlinx.cinterop.ExperimentalForeignApi5import kotlinx.cinterop.addressOf6import kotlinx.cinterop.autoreleasepool7import kotlinx.cinterop.usePinned8import platform.Foundation.NSDate9import platform.Foundation.NSFileModificationDate10import platform.Foundation.NSCachesDirectory11import platform.Foundation.NSData12import platform.Foundation.NSDataReadingMappedIfSafe13import platform.Foundation.NSDocumentDirectory14import platform.Foundation.NSFileManager15import platform.Foundation.NSFileType16import platform.Foundation.NSFileTypeDirectory17import platform.Foundation.NSFileTypeRegular18import platform.Foundation.NSHomeDirectory19import platform.Foundation.NSSearchPathForDirectoriesInDomains20import platform.Foundation.NSURL21import platform.Foundation.NSUserDomainMask22import platform.Foundation.create23import platform.Foundation.dataWithContentsOfFile24import platform.Foundation.timeIntervalSince197025import platform.Foundation.writeToFile26import platform.posix.fclose27import platform.posix.fopen28import platform.posix.fwrite29import platform.posix.rename3031/**32 * iOS filesystem service: app Documents/Caches roots plus user folders reached through33 * [IosSecurityScopedBookmarks]. Paths may carry a `file://` prefix.34 */35@OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)36internal object IosLocalFileService : LocalFileService by IosProfileLocalFileService(eu.friedcutlet.yokan.domain.ProfileId.Default)3738@OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)39internal class IosProfileLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId) : LocalFileService {40 private val namespace = eu.friedcutlet.yokan.domain.ProfileStorageNamespace(profileId)41 private val fm get() = NSFileManager.defaultManager42 private val documentsDir: String = NSSearchPathForDirectoriesInDomains(43 NSDocumentDirectory,44 NSUserDomainMask,45 true,46 ).firstOrNull()?.toString() ?: "${NSHomeDirectory()}/Documents"47 private val cachesDir: String = NSSearchPathForDirectoriesInDomains(48 NSCachesDirectory,49 NSUserDomainMask,50 true,51 ).firstOrNull()?.toString() ?: "${NSHomeDirectory()}/Library/Caches"5253 override val downloadRoot: String = ensureDirectory(if (namespace.relativeRoot == null) "$documentsDir/Yokan/downloads" else "${namespace.ownedRoot(documentsDir)}/downloads")54 override val backupRoot: String = ensureDirectory(if (namespace.relativeRoot == null) "$documentsDir/Yokan/backups" else "${namespace.ownedRoot(documentsDir)}/backups")55 override val cacheRoot: String = ensureDirectory(if (namespace.relativeRoot == null) "$cachesDir/Yokan" else "${namespace.ownedRoot(cachesDir)}/cache")5657 override fun writeBytes(path: String, bytes: ByteArray) {58 val resolved = path.removePrefix("file://")59 val parent = resolved.substringBeforeLast('/', missingDelimiterValue = "")60 if (parent.isNotEmpty()) ensureDirectory(parent)61 // Borrow the pinned array instead of copying it into NSData; the write finishes before unpinning.62 val written = autoreleasepool {63 if (bytes.isEmpty()) {64 NSData.create(bytes = null, length = 0uL).writeToFile(resolved, atomically = true)65 } else {66 bytes.usePinned { pinned ->67 NSData.create(bytesNoCopy = pinned.addressOf(0), length = bytes.size.toULong(), freeWhenDone = false)68 .writeToFile(resolved, atomically = true)69 }70 }71 }72 check(written) {73 "Failed to write file: $resolved"74 }75 }7677 override fun appendBytes(path: String, bytes: ByteArray) {78 if (bytes.isEmpty()) return79 val resolved = path.removePrefix("file://")80 if (!fm.fileExistsAtPath(resolved)) {81 writeBytes(resolved, bytes)82 return83 }84 val handle = fopen(resolved, "ab") ?: error("Failed to open file for append: $resolved")85 try {86 val written = bytes.usePinned { pinned ->87 fwrite(pinned.addressOf(0), 1uL, bytes.size.toULong(), handle)88 }89 check(written == bytes.size.toULong()) {90 "Short write while appending file: $resolved"91 }92 } finally {93 check(fclose(handle) == 0) { "Failed to close file after append: $resolved" }94 }95 }9697 override suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {98 val resolved = path.removePrefix("file://")99 val parent = resolved.substringBeforeLast('/', missingDelimiterValue = "")100 if (parent.isNotEmpty()) ensureDirectory(parent)101 val handle = fopen(resolved, "wb") ?: error("Failed to open file for writing: $resolved")102 val result = try {103 block { bytes ->104 if (bytes.isNotEmpty()) {105 val written = bytes.usePinned { pinned ->106 fwrite(pinned.addressOf(0), 1uL, bytes.size.toULong(), handle)107 }108 check(written == bytes.size.toULong()) { "Short write while writing file: $resolved" }109 }110 }111 } catch (error: Throwable) {112 fclose(handle)113 throw error114 }115 check(fclose(handle) == 0) { "Failed to close file after writing: $resolved" }116 return result117 }118119 override suspend fun <T> appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {120 val resolved = path.removePrefix("file://")121 val parent = resolved.substringBeforeLast('/', missingDelimiterValue = "")122 if (parent.isNotEmpty()) ensureDirectory(parent)123 val handle = fopen(resolved, "ab") ?: error("Failed to open file for writing: $resolved")124 val result = try {125 block { bytes ->126 if (bytes.isNotEmpty()) {127 val written = bytes.usePinned { pinned ->128 fwrite(pinned.addressOf(0), 1uL, bytes.size.toULong(), handle)129 }130 check(written == bytes.size.toULong()) { "Short write while writing file: $resolved" }131 }132 }133 } catch (error: Throwable) {134 fclose(handle)135 throw error136 }137 check(fclose(handle) == 0) { "Failed to close file after writing: $resolved" }138 return result139 }140141 override fun promote(sourcePath: String, targetPath: String): Boolean =142 IosSecurityScopedBookmarks.withAccess(sourcePath) { source ->143 IosSecurityScopedBookmarks.withAccess(targetPath) { target ->144 if (!fm.fileExistsAtPath(source)) return@withAccess false145 val parent = target.substringBeforeLast('/', missingDelimiterValue = "")146 if (parent.isNotEmpty()) ensureDirectory(parent)147 if (fm.fileExistsAtPath(target) && !fm.removeItemAtPath(target, error = null)) {148 return@withAccess false149 }150 if (!fm.moveItemAtPath(source, toPath = target, error = null)) return@withAccess false151 fm.fileExistsAtPath(target) && !fm.fileExistsAtPath(source)152 }153 } ?: false154155 override fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean =156 IosSecurityScopedBookmarks.withAccess(tempPath) { source ->157 IosSecurityScopedBookmarks.withAccess(finalPath) { target ->158 if (source.substringBeforeLast('/') != target.substringBeforeLast('/') ||159 !fm.fileExistsAtPath(source) || fm.directoryExists(source)160 ) return@withAccess false161 rename(source, target) == 0162 }163 } ?: false164165 override fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean =166 IosSecurityScopedBookmarks.withAccess(stagedPath) { source ->167 IosSecurityScopedBookmarks.withAccess(finalPath) { target ->168 if (source.substringBeforeLast('/') != target.substringBeforeLast('/') ||169 !fm.directoryExists(source) || fm.fileExistsAtPath(target)170 ) return@withAccess false171 // ponytail: precheck+rename is not safe against external same-name racers; rely only on172 // the app-owned namespace with one queue writer and random IDs, or add a native RENAME_EXCL shim.173 rename(source, target) == 0174 }175 } ?: false176177 override fun readBytes(path: String): ByteArray {178 return IosSecurityScopedBookmarks.withAccess(path) { raw ->179 val resolved = raw.fileSystemPath()180 // Mapped (clean, evictable) pages instead of a second heap copy; the pool unmaps them after the copy out.181 autoreleasepool {182 val data = NSData.dataWithContentsOfFile(resolved, NSDataReadingMappedIfSafe, null)183 ?: return@autoreleasepool ByteArray(0)184 val length = data.length.toInt()185 if (length == 0) return@autoreleasepool ByteArray(0)186 val bytes = ByteArray(length)187 bytes.usePinned { pinned ->188 platform.posix.memcpy(pinned.addressOf(0), data.bytes, length.toULong())189 }190 bytes191 }192 } ?: ByteArray(0)193 }194195 override fun readBytesBounded(path: String, maxBytes: Long): ByteArray {196 require(maxBytes >= 0 && maxBytes < Int.MAX_VALUE) { "Invalid byte limit" }197 return IosSecurityScopedBookmarks.withAccess(path) { raw ->198 val resolved = raw.fileSystemPath()199 val actualSize = fm.fileSize(resolved)200 check(actualSize <= maxBytes) { "File exceeds $maxBytes bytes" }201 val file = fopen(resolved, "rb") ?: error("Cannot open file: $path")202 var bytes = ByteArray(minOf(actualSize, 64L * 1024).toInt())203 var total = 0L204 try {205 while (total <= maxBytes) {206 if (total == bytes.size.toLong()) {207 if (total == maxBytes) {208 val extra = ByteArray(1)209 val count = extra.usePinned { pinned ->210 platform.posix.fread(pinned.addressOf(0), 1uL, 1uL, file).toInt()211 }212 if (count > 0) total++213 break214 }215 val nextSize = minOf(maxBytes + 1, maxOf(16L * 1024, bytes.size.toLong() * 2))216 bytes = bytes.copyOf(nextSize.toInt())217 }218 val count = bytes.usePinned { pinned ->219 platform.posix.fread(220 pinned.addressOf(total.toInt()),221 1uL,222 minOf(bytes.size.toLong() - total, maxBytes + 1 - total).toULong(),223 file,224 ).toInt()225 }226 if (count == 0) break227 total += count228 }229 } finally {230 fclose(file)231 }232 check(total == actualSize) { "File changed or was truncated while reading: $path" }233 check(total <= maxBytes) { "File exceeds $maxBytes bytes" }234 bytes.copyOf(minOf(total, maxBytes).toInt())235 } ?: error("Cannot read file: $path")236 }237238 override fun canonicalPath(path: String): String? =239 IosSecurityScopedBookmarks.withAccess(path) { resolved ->240 NSURL.fileURLWithPath(resolved).URLByResolvingSymlinksInPath?.path241 }242243 override fun exists(path: String): Boolean =244 IosSecurityScopedBookmarks.withAccess(path) { resolved -> fm.fileExistsAtPath(resolved) } ?: false245246 override fun deleteRecursively(path: String): Boolean {247 return IosSecurityScopedBookmarks.withAccess(path) { resolved ->248 if (!fm.fileExistsAtPath(resolved)) true else fm.removeItemAtPath(resolved, error = null)249 } ?: false250 }251252 override fun directorySize(path: String): Long {253 return IosSecurityScopedBookmarks.withAccess(path) { resolved ->254 if (!fm.fileExistsAtPath(resolved)) 0L else walkSize(resolved)255 } ?: 0L256 }257258 override fun openLocation(path: String): Boolean {259 return IosSecurityScopedBookmarks.withAccess(path) { resolved ->260 val url = NSURL.fileURLWithPath(resolved)261 platform.UIKit.UIApplication.sharedApplication.openURL(url)262 } ?: false263 }264265 override fun listLocalEntries(root: String): List<LocalEntry>? {266 return IosSecurityScopedBookmarks.withAccess(root) { resolved ->267 if (!fm.directoryExists(resolved)) return@withAccess null268 listLocalEntriesRecursive(resolved, root.removePrefix("file://"))269 }270 }271272 override fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? =273 IosSecurityScopedBookmarks.withAccess(root) { resolved ->274 val names = fm.contentsOfDirectoryAtPath(resolved, error = null) ?: return@withAccess null275 names.filterIsInstance<String>().mapNotNull { name ->276 val type = fm.attributesOfItemAtPath("$resolved/$name", error = null)?.get(NSFileType)277 if (type != NSFileTypeDirectory && type != NSFileTypeRegular) return@mapNotNull null278 LocalDirectoryEntry("${root.removePrefix("file://").trimEnd('/')}/$name", name, type == NSFileTypeDirectory)279 }.sortedBy { it.name.lowercase() }280 }281282 private fun listLocalEntriesRecursive(root: String, logicalRoot: String): List<LocalEntry>? {283 val names = fm.contentsOfDirectoryAtPath(root, error = null) ?: return null284 return names.filterIsInstance<String>()285 .sortedBy { it.lowercase() }286 .flatMap { name ->287 val full = "$root/$name"288 val logical = "$logicalRoot/$name"289 when {290 !fm.directoryExists(full) && hasReadableExtension(name) ->291 listOf(LocalEntry(path = logical, name = name.substringBeforeLast('.'), isArchive = true))292 fm.directoryExists(full) && directoryContainsReadableFiles(full) ->293 listOf(LocalEntry(path = logical, name = name, isArchive = false))294 fm.directoryExists(full) -> listLocalEntriesRecursive(full, logical) ?: return null295 else -> emptyList()296 }297 }298 }299300 override fun listFiles(root: String): List<LocalFileEntry> {301 return IosSecurityScopedBookmarks.withAccess(root) { resolved ->302 if (!fm.directoryExists(resolved)) return@withAccess emptyList()303 fm.contentsOfDirectoryAtPath(resolved, error = null)304 ?.filterIsInstance<String>()305 ?.map { name ->306 val full = "$resolved/$name"307 LocalFileEntry(308 path = "${root.removePrefix("file://").trimEnd('/')}/$name",309 name = name,310 sizeBytes = fm.fileSize(full),311 lastModified = ((fm.attributesOfItemAtPath(full, error = null)?.get(NSFileModificationDate) as? NSDate)?.timeIntervalSince1970?.times(1000))?.toLong() ?: 0L,312 )313 }314 .orEmpty()315 }.orEmpty()316 }317318 private fun ensureDirectory(path: String): String {319 if (!fm.fileExistsAtPath(path)) {320 fm.createDirectoryAtPath(path, withIntermediateDirectories = true, attributes = null, error = null)321 }322 return path323 }324325 private fun walkSize(path: String): Long {326 if (!fm.directoryExists(path)) return fm.fileSize(path)327 val children = fm.contentsOfDirectoryAtPath(path, error = null)?.filterIsInstance<String>().orEmpty()328 return children.sumOf { walkSize("$path/$it") }329 }330331 private fun directoryContainsReadableFiles(path: String): Boolean =332 fm.contentsOfDirectoryAtPath(path, error = null)333 ?.filterIsInstance<String>()334 ?.any { name ->335 val full = "$path/$name"336 !fm.directoryExists(full) && hasReadableExtension(name)337 } == true338339 private fun hasReadableExtension(name: String): Boolean {340 val lower = name.lowercase()341 return lower.endsWith(".cbz") || lower.endsWith(".zip") ||342 lower.endsWith(".cbt") || lower.endsWith(".tar") ||343 lower.endsWith(".epub") || lower.endsWith(".png") ||344 lower.endsWith(".jpg") || lower.endsWith(".jpeg") ||345 lower.endsWith(".gif") || lower.endsWith(".webp") ||346 lower.endsWith(".bmp") || lower.endsWith(".avif") ||347 lower.endsWith(".mp4") || lower.endsWith(".mkv") ||348 lower.endsWith(".mov") || lower.endsWith(".webm") ||349 lower.endsWith(".avi") || lower.endsWith(".m4v") ||350 lower.endsWith(".ts") || lower.endsWith(".m3u8") ||351 lower.endsWith(".txt") || lower.endsWith(".html") ||352 lower.endsWith(".xhtml") || lower.endsWith(".md")353 }354}355356private fun String.fileSystemPath(): String =357 if (startsWith("file:")) NSURL.URLWithString(this)?.path ?: error("Invalid file URL: $this") else this358359@OptIn(ExperimentalForeignApi::class)360internal fun NSFileManager.directoryExists(path: String): Boolean {361 return fileExistsAtPath(path) && contentsOfDirectoryAtPath(path, error = null) != null362}363364@OptIn(ExperimentalForeignApi::class)365internal fun NSFileManager.fileSize(path: String): Long {366 val attrs = attributesOfItemAtPath(path, error = null) ?: return 0L367 val size = attrs["NSFileSize"] as? platform.Foundation.NSNumber ?: return 0L368 return size.longLongValue369}370