Yokan / rebuild
Course 1 8624561

UpdateDeviceConditions.wasm.kt

composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/scheduling/UpdateDeviceConditions.wasm.kt

implementation37 lines
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)23package eu.friedcutlet.yokan.services.scheduling45import eu.friedcutlet.yokan.database.DatabaseJson6import kotlinx.coroutines.await7import kotlin.js.JsString8import kotlin.js.Promise910actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions =11    DatabaseJson.decodeFromString(readBrowserUpdateConditions(needPower).await<JsString>().toString())1213private fun readBrowserUpdateConditions(needPower: Boolean): Promise<JsString> = js("""14    (async () => {15        const n = globalThis.navigator || {};16        const connection = n.connection || n.mozConnection || n.webkitConnection;17        const connected = typeof n.onLine === 'boolean' ? n.onLine : null;18        const type = connection && connection.type;19        const wifi = connected === false ? false : type === 'wifi' ? true :20            ['ethernet', 'cellular', 'bluetooth', 'wimax', 'none'].includes(type) ? false : null;21        // saveData is evidence to defer; its absence/false value is not evidence of free data.22        const unmetered = connected === false || (connection && connection.saveData === true) ? false : null;23        let externalPower = null;24        if (needPower && globalThis.isSecureContext && typeof n.getBattery === 'function') {25            let timer;26            try {27                const battery = await Promise.race([28                    Promise.resolve().then(() => n.getBattery()),29                    new Promise(resolve => { timer = setTimeout(() => resolve(null), 1500); })30                ]);31                if (battery && typeof battery.charging === 'boolean') externalPower = battery.charging;32            } catch (_) { /* Denied/unsupported telemetry stays unknown. */ }33            finally { clearTimeout(timer); }34        }35        return JSON.stringify({ connected, wifi, unmetered, externalPower });36    })()37""")38

Search chapters, reference and source filenames.