IosSecurityScopedBookmarks.ios.kt
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/IosSecurityScopedBookmarks.ios.kt
1@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)23package eu.friedcutlet.yokan.services.files45import kotlinx.cinterop.BooleanVarOf6import kotlinx.cinterop.ExperimentalForeignApi7import kotlinx.cinterop.alloc8import kotlinx.cinterop.ObjCObjectVar9import kotlinx.cinterop.memScoped10import kotlinx.cinterop.ptr11import kotlinx.cinterop.value12import platform.Foundation.NSData13import platform.Foundation.NSURL14import platform.Foundation.NSURLBookmarkCreationMinimalBookmark15import platform.Foundation.NSURLBookmarkResolutionWithoutImplicitStartAccessing16import platform.Foundation.NSFileCoordinator17import platform.Foundation.NSFileCoordinatorReadingWithoutChanges18import platform.Foundation.NSError19import platform.Foundation.NSUserDefaults20import eu.friedcutlet.yokan.services.blockingDispatcher21import kotlin.coroutines.ContinuationInterceptor22import kotlinx.coroutines.coroutineScope23import kotlinx.coroutines.currentCoroutineContext24import kotlinx.coroutines.launch25import kotlinx.coroutines.runBlocking26import kotlinx.coroutines.suspendCancellableCoroutine27import kotlinx.coroutines.withContext2829/**30 * Keeps security-scoped bookmark data outside the common settings model. The31 * configured path remains the opaque path returned by the picker; this class32 * resolves it only at the point where a filesystem operation is performed.33 */34@OptIn(ExperimentalForeignApi::class)35internal object IosSecurityScopedBookmarks {36 private const val rootsKey = "eu.friedcutlet.yokan.securityScopedBookmarkRoots"37 private const val bookmarkKeyPrefix = "eu.friedcutlet.yokan.securityScopedBookmark."3839 private val defaults: NSUserDefaults40 get() = NSUserDefaults.standardUserDefaults4142 fun persist(url: NSURL): String? {43 val path = url.path?.takeIf(String::isNotBlank) ?: return null44 val started = url.startAccessingSecurityScopedResource()45 return try {46 val bookmark = url.bookmarkDataWithOptions(47 options = NSURLBookmarkCreationMinimalBookmark,48 includingResourceValuesForKeys = null,49 relativeToURL = null,50 error = null,51 ) ?: return null52 defaults.setObject(bookmark, forKey = bookmarkKey(path))53 val roots = storedRoots()54 if (path !in roots) defaults.setObject(roots + path, forKey = rootsKey)55 path56 } finally {57 if (started) url.stopAccessingSecurityScopedResource()58 }59 }6061 /**62 * Resolves the bookmark for [path], refreshes stale data, and holds the63 * security scope for exactly the duration of [block]. A path without a64 * bookmark is treated as an app-local path and is used directly.65 */66 fun <T> withAccess(path: String, block: (String) -> T): T? {67 val logicalPath = if (path.startsWith("file:")) {68 NSURL.URLWithString(path)?.path ?: return null69 } else path70 val root = matchingRoot(logicalPath)71 if (root == null) return runCatching { block(logicalPath) }.getOrNull()7273 val bookmark = defaults.objectForKey(bookmarkKey(root)) as? NSData ?: return null74 return memScoped {75 val stale = alloc<BooleanVarOf<Boolean>>()76 val resolved = NSURL.URLByResolvingBookmarkData(77 bookmarkData = bookmark,78 options = NSURLBookmarkResolutionWithoutImplicitStartAccessing,79 relativeToURL = null,80 bookmarkDataIsStale = stale.ptr,81 error = null,82 ) ?: return@memScoped null83 val physicalRoot = resolved.path?.takeIf(String::isNotBlank) ?: return@memScoped null84 val started = resolved.startAccessingSecurityScopedResource()85 try {86 if (stale.value) refresh(root, resolved)87 val relative = logicalPath.removePrefix(root).trimStart('/')88 if (relative.split('/').any { it == ".." }) return@memScoped null89 val physicalPath = if (relative.isEmpty()) physicalRoot else "$physicalRoot/$relative"90 runCatching { block(physicalPath) }.getOrNull()91 } finally {92 if (started) resolved.stopAccessingSecurityScopedResource()93 }94 }95 }9697 /** Holds a balanced security scope across suspended, bounded file reads. Errors propagate. */98 suspend fun <T> withAccessAsync(path: String, block: suspend (String) -> T): T {99 val logicalPath = if (path.startsWith("file:")) {100 requireNotNull(NSURL.URLWithString(path)?.path)101 } else path102 val root = matchingRoot(logicalPath) ?: return block(logicalPath)103 val bookmark = defaults.objectForKey(bookmarkKey(root)) as? NSData ?: error("Folder permission is unavailable")104 var staleBookmark = false105 val resolved = memScoped {106 val stale = alloc<BooleanVarOf<Boolean>>()107 val url = NSURL.URLByResolvingBookmarkData(bookmark, NSURLBookmarkResolutionWithoutImplicitStartAccessing, null, stale.ptr, null)108 ?: error("Folder permission could not be resolved")109 staleBookmark = stale.value110 url111 }112 val physicalRoot = requireNotNull(resolved.path)113 val started = resolved.startAccessingSecurityScopedResource()114 try {115 if (staleBookmark) refresh(root, resolved)116 val relative = logicalPath.removePrefix(root).trimStart('/')117 require(relative.split('/').none { it == ".." })118 return block(if (relative.isEmpty()) physicalRoot else "$physicalRoot/$relative")119 } finally { if (started) resolved.stopAccessingSecurityScopedResource() }120 }121122 /** Keeps provider materialization and all reads inside its synchronous coordination accessor. */123 @OptIn(kotlinx.cinterop.BetaInteropApi::class)124 suspend fun <T> withCoordinatedRead(path: String, block: suspend (String) -> T): T = withContext(blockingDispatcher) {125 withAccessAsync(path) { physical ->126 coroutineScope {127 val coordinator = NSFileCoordinator(filePresenter = null)128 suspendCancellableCoroutine { continuation ->129 continuation.invokeOnCancellation { coordinator.cancel() }130 launch(blockingDispatcher) {131 val outcome = runCatching {132 val readerContext = currentCoroutineContext().minusKey(ContinuationInterceptor)133 memScoped {134 val failure = alloc<ObjCObjectVar<NSError?>>()135 failure.value = null136 var result: Result<T>? = null137 coordinator.coordinateReadingItemAtURL(138 NSURL.fileURLWithPath(physical),139 options = NSFileCoordinatorReadingWithoutChanges,140 error = failure.ptr,141 ) { coordinated ->142 // This bridge stays on the background thread and inherits cancellation.143 // The native destination writer is synchronous; no UI thread is blocked.144 result = runCatching { runBlocking(readerContext) { block(requireNotNull(requireNotNull(coordinated).path)) } }145 }146 val completed = result ?: error(failure.value?.localizedDescription ?: "Document provider could not open the file")147 completed.getOrThrow()148 }149 }150 if (continuation.isActive) continuation.resumeWith(outcome)151 }152 }153 }154 }155 }156157 private fun refresh(root: String, url: NSURL) {158 runCatching {159 url.bookmarkDataWithOptions(160 options = NSURLBookmarkCreationMinimalBookmark,161 includingResourceValuesForKeys = null,162 relativeToURL = null,163 error = null,164 )?.let { defaults.setObject(it, forKey = bookmarkKey(root)) }165 }166 }167168 private fun matchingRoot(path: String): String? = storedRoots()169 .filter { root ->170 val normalizedRoot = root.trimEnd('/').ifEmpty { "/" }171 path == normalizedRoot ||172 (normalizedRoot == "/" && path.startsWith('/')) ||173 path.startsWith("$normalizedRoot/")174 }175 .maxByOrNull(String::length)176177 private fun storedRoots(): List<String> =178 defaults.arrayForKey(rootsKey)?.filterIsInstance<String>().orEmpty()179180 private fun bookmarkKey(root: String): String = bookmarkKeyPrefix + root181}182