LocalMediaSelection.wasm.kt
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.wasm.kt
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class)23package eu.friedcutlet.yokan.services.files45import eu.friedcutlet.yokan.database.DatabaseJson6import kotlin.io.encoding.Base647import kotlin.js.JsAny8import kotlin.js.JsString9import kotlin.js.Promise10import kotlinx.coroutines.await11import kotlinx.coroutines.currentCoroutineContext12import kotlinx.coroutines.ensureActive13import kotlinx.serialization.Serializable1415@Serializable16private data class BrowserSelectedMedia(val path: String, val size: Long)1718actual suspend fun pickLocalMedia(directory: Boolean): LocalMediaSelection? {19 // Invoked synchronously from the click handler before the first suspension (browser activation).20 val picker = createMediaPicker(directory)21 try {22 val selection = mediaPickerResult(picker).await<JsAny?>() ?: return null23 return browserMediaSelection(selection)24 } catch (error: Throwable) {25 cancelMediaPicker(picker)26 throw error27 }28}2930internal fun browserMediaSelection(selection: JsAny): LocalMediaSelection {31 val metadata = try { DatabaseJson.decodeFromString<List<BrowserSelectedMedia>>(mediaMetadata(selection)) }32 catch (error: Throwable) { closeMediaSelection(selection); throw error }33 return LocalMediaSelection(metadata.mapIndexed { index, file ->34 object : LocalMediaInput {35 override val relativePath = file.path36 override val sizeBytes = file.size37 override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) {38 var offset = 0L39 while (offset < sizeBytes) {40 currentCoroutineContext().ensureActive()41 val encoded = mediaChunk(selection, index, offset.toDouble()).await<JsString>().toString()42 val bytes = Base64.decode(encoded)43 check(bytes.isNotEmpty() && bytes.size <= LOCAL_IMPORT_CHUNK_BYTES) { "Invalid selected-file chunk" }44 consume(bytes)45 offset += bytes.size46 }47 }48 }49 }) { closeMediaSelection(selection) }50}5152private fun createMediaPicker(directory: Boolean): JsAny = js("globalThis.yokanBrowserFiles.pickMedia(directory)")53private fun mediaPickerResult(picker: JsAny): Promise<JsAny?> = js("picker.result")54private fun cancelMediaPicker(picker: JsAny): Unit = js("picker.cancel()")55private fun mediaMetadata(selection: JsAny): String = js("selection.metadata()")56private fun mediaChunk(selection: JsAny, index: Int, offset: Double): Promise<JsString> = js("selection.chunk(index, offset)")57private fun closeMediaSelection(selection: JsAny): Unit = js("selection.close()")58