tawasuyu

sergio/humanoid

HTML 37Markdown 1TOML 10 Definitions

⎇ 8ed22f8ad9c8dd0eafa48327dcaf4e12babcf7ae consola/src/main/java/com/rizoma/consola/data/Settings.kt 47 lines · 1.6 KB History raw

Consola: nuevo módulo Android :consola — cliente del daemon shuma 8ed22f8ad · sergio ·

1package com.rizoma.consola.data
2
3import android.content.Context
4import androidx.datastore.core.DataStore
5import androidx.datastore.preferences.core.Preferences
6import androidx.datastore.preferences.core.edit
7import androidx.datastore.preferences.core.stringPreferencesKey
8import androidx.datastore.preferences.preferencesDataStore
9import kotlinx.coroutines.flow.Flow
10import kotlinx.coroutines.flow.map
11
12private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "consola")
13
14/** Configuración de conexión al shuma-gateway, persistida en DataStore. */
15data class GatewayConfig(
16    val baseUrl: String = DEFAULT_URL,
17    val token: String = "",
18) {
19    companion object {
20        // 10.0.2.2 = loopback del host desde el emulador de Android. En un
21        // dispositivo real se cambia por la IP/host del gateway (o el túnel).
22        const val DEFAULT_URL = "http://10.0.2.2:7378"
23    }
24}
25
26class Settings(context: Context) {
27    private val store = context.applicationContext.dataStore
28
29    val config: Flow<GatewayConfig> = store.data.map { p ->
30        GatewayConfig(
31            baseUrl = p[KEY_URL]?.ifBlank { GatewayConfig.DEFAULT_URL } ?: GatewayConfig.DEFAULT_URL,
32            token = p[KEY_TOKEN].orEmpty(),
33        )
34    }
35
36    suspend fun setConfig(baseUrl: String, token: String) {
37        store.edit { p ->
38            p[KEY_URL] = baseUrl.trim().ifBlank { GatewayConfig.DEFAULT_URL }
39            p[KEY_TOKEN] = token.trim()
40        }
41    }
42
43    private companion object {
44        val KEY_URL = stringPreferencesKey("base_url")
45        val KEY_TOKEN = stringPreferencesKey("token")
46    }
47}