LocalMediaSelection.ios.kt
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.ios.kt
1@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)23package eu.friedcutlet.yokan.services.files45import eu.friedcutlet.yokan.services.blockingDispatcher6import kotlinx.cinterop.addressOf7import kotlinx.cinterop.usePinned8import kotlinx.coroutines.currentCoroutineContext9import kotlinx.coroutines.ensureActive10import kotlinx.coroutines.withContext11import kotlinx.coroutines.yield12import platform.Foundation.NSFileManager13import platform.Foundation.NSFileSize14import platform.Foundation.NSFileType15import platform.Foundation.NSFileTypeDirectory16import platform.Foundation.NSFileTypeRegular17import platform.Foundation.NSNumber18import platform.posix.fclose19import platform.posix.ferror20import platform.posix.fopen21import platform.posix.fread2223actual suspend fun pickLocalMedia(directory: Boolean): LocalMediaSelection? {24 val chosen = if (directory) pickFolder() else pickScopedMediaFile()25 if (chosen == null) return null26 return withContext(blockingDispatcher) {27 IosSecurityScopedBookmarks.withCoordinatedRead(chosen) { root ->28 val fm = NSFileManager.defaultManager29 val inputs = mutableListOf<LocalMediaInput>()30 val pending = ArrayDeque<Pair<String, String>>().apply { add(root to root.substringAfterLast('/')) }31 var visited = 032 while (pending.isNotEmpty()) {33 currentCoroutineContext().ensureActive()34 check(++visited <= 50_000) { "Selected folder is too large" }35 val (path, relative) = pending.removeFirst()36 check(relative.count { it == '/' } < 64) { "Selected folder is too deep" }37 val attrs = fm.attributesOfItemAtPath(path, error = null) ?: error("Selected file is unavailable")38 when (attrs[NSFileType]) {39 NSFileTypeDirectory -> {40 check(directory) { "Select a media file" }41 val names = fm.contentsOfDirectoryAtPath(path, error = null)?.filterIsInstance<String>()42 ?: error("Selected folder is unreadable")43 for (name in names) if (!name.startsWith('.')) pending.add("$path/$name" to "$relative/$name")44 }45 NSFileTypeRegular -> {46 if (relative.substringAfterLast('.', "").lowercase() !in localImportExtensions) continue47 check(inputs.size < LOCAL_IMPORT_MAX_FILES) { "Too many selected files" }48 val logical = if (directory) "$chosen/${path.removePrefix("$root/")}" else chosen49 inputs += IosLocalMediaInput(relative, (attrs[NSFileSize] as? NSNumber)?.longLongValue, logical)50 }51 // Symlinks and special files are never followed out of the selected tree.52 else -> Unit53 }54 }55 LocalMediaSelection(inputs)56 }57 }58}5960internal class IosLocalMediaInput(61 override val relativePath: String,62 override val sizeBytes: Long?,63 private val path: String,64) : LocalMediaInput {65 override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) = withContext(blockingDispatcher) {66 IosSecurityScopedBookmarks.withCoordinatedRead(path) { physical ->67 val input = fopen(physical, "rb") ?: error("Selected file is no longer readable")68 try {69 val buffer = ByteArray(LOCAL_IMPORT_CHUNK_BYTES)70 while (true) {71 currentCoroutineContext().ensureActive()72 val count = buffer.usePinned { fread(it.addressOf(0), 1uL, buffer.size.toULong(), input).toInt() }73 if (count == 0) { check(ferror(input) == 0) { "Could not read selected file" }; break }74 consume(buffer.copyOf(count))75 yield()76 }77 } finally { fclose(input) }78 }79 }80}81