LockViewModel.kt

2.8 KB · raw

1package com.peachpasswords.ui.lock23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import com.peachpasswords.vault.CreateVaultResult6import com.peachpasswords.vault.UnlockResult7import com.peachpasswords.vault.VaultRepository8import dagger.hilt.android.lifecycle.HiltViewModel9import kotlinx.coroutines.flow.MutableStateFlow10import kotlinx.coroutines.flow.StateFlow11import kotlinx.coroutines.flow.asStateFlow12import kotlinx.coroutines.flow.update13import kotlinx.coroutines.launch14import javax.inject.Inject1516data class LockUiState(17    val hasVault: Boolean = false,18    val loading: Boolean = false,19    val error: String? = null,20    val unlocked: Boolean = false,21    /** Increments on each failed unlock so the screen can fire its shake animation. */22    val shakeNonce: Int = 0,23)2425const val MIN_PASSWORD_LENGTH = 82627@HiltViewModel28class LockViewModel @Inject constructor(29    private val vault: VaultRepository,30) : ViewModel() {31    private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))32    val state: StateFlow<LockUiState> = _state.asStateFlow()3334    fun unlock(password: String) {35        if (password.isBlank() || _state.value.loading) return36        _state.update { it.copy(loading = true, error = null) }37        viewModelScope.launch {38            when (val r = vault.unlock(password)) {39                is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }40                is UnlockResult.WrongPassword -> _state.update {41                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)42                }43                is UnlockResult.Error -> _state.update {44                    it.copy(loading = false, error = r.reason, shakeNonce = it.shakeNonce + 1)45                }46            }47        }48    }4950    fun create(password: String, confirm: String) {51        if (_state.value.loading) return52        when {53            password.length < MIN_PASSWORD_LENGTH ->54                return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") }55            password != confirm ->56                return _state.update { it.copy(error = "passwords do not match") }57        }58        _state.update { it.copy(loading = true, error = null) }59        viewModelScope.launch {60            when (val r = vault.createVault(password)) {61                is CreateVaultResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }62                is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }63            }64        }65    }6667    fun clearError() = _state.update { it.copy(error = null) }6869    /** Dormant until biometric enrollment lands with Protection settings. */70    fun canTryBiometric(): Boolean = false71}