@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.services.blockingDispatcher import kotlinx.cinterop.addressOf import kotlinx.cinterop.usePinned import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import kotlinx.coroutines.yield import platform.Foundation.NSFileManager import platform.Foundation.NSFileSize import platform.Foundation.NSFileType import platform.Foundation.NSFileTypeDirectory import platform.Foundation.NSFileTypeRegular import platform.Foundation.NSNumber import platform.posix.fclose import platform.posix.ferror import platform.posix.fopen import platform.posix.fread actual suspend fun pickLocalMedia(directory: Boolean): LocalMediaSelection? { val chosen = if (directory) pickFolder() else pickScopedMediaFile() if (chosen == null) return null return withContext(blockingDispatcher) { IosSecurityScopedBookmarks.withCoordinatedRead(chosen) { root -> val fm = NSFileManager.defaultManager val inputs = mutableListOf() val pending = ArrayDeque>().apply { add(root to root.substringAfterLast('/')) } var visited = 0 while (pending.isNotEmpty()) { currentCoroutineContext().ensureActive() check(++visited <= 50_000) { "Selected folder is too large" } val (path, relative) = pending.removeFirst() check(relative.count { it == '/' } < 64) { "Selected folder is too deep" } val attrs = fm.attributesOfItemAtPath(path, error = null) ?: error("Selected file is unavailable") when (attrs[NSFileType]) { NSFileTypeDirectory -> { check(directory) { "Select a media file" } val names = fm.contentsOfDirectoryAtPath(path, error = null)?.filterIsInstance() ?: error("Selected folder is unreadable") for (name in names) if (!name.startsWith('.')) pending.add("$path/$name" to "$relative/$name") } NSFileTypeRegular -> { if (relative.substringAfterLast('.', "").lowercase() !in localImportExtensions) continue check(inputs.size < LOCAL_IMPORT_MAX_FILES) { "Too many selected files" } val logical = if (directory) "$chosen/${path.removePrefix("$root/")}" else chosen inputs += IosLocalMediaInput(relative, (attrs[NSFileSize] as? NSNumber)?.longLongValue, logical) } // Symlinks and special files are never followed out of the selected tree. else -> Unit } } LocalMediaSelection(inputs) } } } internal class IosLocalMediaInput( override val relativePath: String, override val sizeBytes: Long?, private val path: String, ) : LocalMediaInput { override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) = withContext(blockingDispatcher) { IosSecurityScopedBookmarks.withCoordinatedRead(path) { physical -> val input = fopen(physical, "rb") ?: error("Selected file is no longer readable") try { val buffer = ByteArray(LOCAL_IMPORT_CHUNK_BYTES) while (true) { currentCoroutineContext().ensureActive() val count = buffer.usePinned { fread(it.addressOf(0), 1uL, buffer.size.toULong(), input).toInt() } if (count == 0) { check(ferror(input) == 0) { "Could not read selected file" }; break } consume(buffer.copyOf(count)) yield() } } finally { fclose(input) } } } }