MetadataServerSettingsViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/metadata/MetadataServerSettingsViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.metadata23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.services.catchingNonCancellation6import eu.friedcutlet.yokan.services.metadata.MetadataService7import eu.friedcutlet.yokan.services.notifications.NotificationService8import kotlinx.coroutines.flow.MutableStateFlow9import kotlinx.coroutines.flow.StateFlow10import kotlinx.coroutines.flow.asStateFlow11import kotlinx.coroutines.flow.update12import kotlinx.coroutines.launch1314internal data class MetadataServerSettingsState(val status: String? = null, val checking: Boolean = false)1516internal class MetadataServerSettingsViewModel(17 private val metadata: MetadataService,18 private val notifications: NotificationService,19) : ViewModel() {20 private val _state = MutableStateFlow(MetadataServerSettingsState())21 val state: StateFlow<MetadataServerSettingsState> = _state.asStateFlow()2223 fun requestNotificationPermission() = notifications.requestPermission()2425 fun markSaved() {26 _state.update { it.copy(status = "Metadata server settings saved.") }27 }2829 fun check(serverUrl: String) {30 viewModelScope.launch {31 _state.update { it.copy(checking = true) }32 val checkUrl = serverUrl.trim().trimEnd('/')33 val ok = catchingNonCancellation { metadata.health(checkUrl) }.getOrDefault(false)34 val status = if (ok) {35 "Metadata server is reachable at $checkUrl."36 } else {37 "Metadata server check failed at $checkUrl."38 }39 _state.update { it.copy(status = status, checking = false) }40 }41 }42}43