@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class) package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.database.DatabaseJson import kotlin.io.encoding.Base64 import kotlin.js.JsAny import kotlin.js.JsString import kotlin.js.Promise import kotlinx.coroutines.await import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.serialization.Serializable @Serializable private data class BrowserSelectedMedia(val path: String, val size: Long) actual suspend fun pickLocalMedia(directory: Boolean): LocalMediaSelection? { // Invoked synchronously from the click handler before the first suspension (browser activation). val picker = createMediaPicker(directory) try { val selection = mediaPickerResult(picker).await() ?: return null return browserMediaSelection(selection) } catch (error: Throwable) { cancelMediaPicker(picker) throw error } } internal fun browserMediaSelection(selection: JsAny): LocalMediaSelection { val metadata = try { DatabaseJson.decodeFromString>(mediaMetadata(selection)) } catch (error: Throwable) { closeMediaSelection(selection); throw error } return LocalMediaSelection(metadata.mapIndexed { index, file -> object : LocalMediaInput { override val relativePath = file.path override val sizeBytes = file.size override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { var offset = 0L while (offset < sizeBytes) { currentCoroutineContext().ensureActive() val encoded = mediaChunk(selection, index, offset.toDouble()).await().toString() val bytes = Base64.decode(encoded) check(bytes.isNotEmpty() && bytes.size <= LOCAL_IMPORT_CHUNK_BYTES) { "Invalid selected-file chunk" } consume(bytes) offset += bytes.size } } } }) { closeMediaSelection(selection) } } private fun createMediaPicker(directory: Boolean): JsAny = js("globalThis.yokanBrowserFiles.pickMedia(directory)") private fun mediaPickerResult(picker: JsAny): Promise = js("picker.result") private fun cancelMediaPicker(picker: JsAny): Unit = js("picker.cancel()") private fun mediaMetadata(selection: JsAny): String = js("selection.metadata()") private fun mediaChunk(selection: JsAny, index: Int, offset: Double): Promise = js("selection.chunk(index, offset)") private fun closeMediaSelection(selection: JsAny): Unit = js("selection.close()")