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 22 val created: Boolean = false,23 24 val shakeNonce: Int = 0,25)2627const val MIN_PASSWORD_LENGTH = 122829@HiltViewModel30class LockViewModel @Inject constructor(31 private val vault: VaultRepository,32) : ViewModel() {33 private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))34 val state: StateFlow<LockUiState> = _state.asStateFlow()3536 fun unlock(password: String) {37 if (password.isBlank() || _state.value.loading) return38 _state.update { it.copy(loading = true, error = null) }39 viewModelScope.launch {40 when (val r = vault.unlock(password)) {41 is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }42 is UnlockResult.WrongPassword -> _state.update {43 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)44 }45 is UnlockResult.Error -> _state.update {46 it.copy(loading = false, error = r.reason, shakeNonce = it.shakeNonce + 1)47 }48 }49 }50 }5152 fun create(password: String, confirm: String) {53 if (_state.value.loading) return54 when {55 password.length < MIN_PASSWORD_LENGTH ->56 return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") }57 password != confirm ->58 return _state.update { it.copy(error = "passwords do not match") }59 }60 _state.update { it.copy(loading = true, error = null) }61 viewModelScope.launch {62 when (val r = vault.createVault(password)) {63 is CreateVaultResult.Success -> _state.update { it.copy(loading = false, unlocked = true, created = true) }64 is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }65 }66 }67 }6869 fun clearError() = _state.update { it.copy(error = null) }7071 72 fun canTryBiometric(): Boolean = false73}