SettingsViewModel.kt

6.9 KB · raw

1package com.peachpasswords.ui.settings23import android.content.Context4import androidx.biometric.BiometricPrompt5import androidx.fragment.app.FragmentActivity6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import com.peachpasswords.feedback.FeedbackRepository9import com.peachpasswords.feedback.FeedbackState10import com.peachpasswords.license.LicenseRepository11import com.peachpasswords.ui.lock.BiometricKeyStore12import com.peachpasswords.ui.lock.Biometrics13import com.peachpasswords.vault.VaultCrypto14import com.peachpasswords.vault.VaultRepository15import com.peachpasswords.vault.VaultSettings16import dagger.hilt.android.lifecycle.HiltViewModel17import dagger.hilt.android.qualifiers.ApplicationContext18import kotlinx.coroutines.flow.MutableStateFlow19import kotlinx.coroutines.flow.StateFlow20import kotlinx.coroutines.flow.asStateFlow21import kotlinx.coroutines.launch22import javax.inject.Inject2324@HiltViewModel25class SettingsViewModel @Inject constructor(26    private val vault: VaultRepository,27    private val license: LicenseRepository,28    private val feedback: FeedbackRepository,29    @ApplicationContext private val appContext: Context,30) : ViewModel() {3132    private val _feedbackState = MutableStateFlow<FeedbackState>(FeedbackState.Idle)33    val feedbackState: StateFlow<FeedbackState> = _feedbackState.asStateFlow()3435    fun sendFeedback(type: String, message: String) {36        if (_feedbackState.value is FeedbackState.Sending) return37        _feedbackState.value = FeedbackState.Sending38        viewModelScope.launch {39            _feedbackState.value = try {40                feedback.submit(type, message)41                FeedbackState.Sent42            } catch (e: Exception) {43                FeedbackState.Error("Couldn't send feedback — check your connection")44            }45        }46    }4748    /** Reset to Idle when the Feedback card leaves the screen. */49    fun resetFeedback() {50        _feedbackState.value = FeedbackState.Idle51    }52    val entries: StateFlow<List<com.peachpasswords.vault.VaultEntry>> = vault.entries53    val settings: StateFlow<VaultSettings> = vault.settings5455    /** Live Pro entitlement, seeded from the stored (locally Ed25519-validated) license. */56    private val _isPro = MutableStateFlow(license.isProActive())57    val isPro: StateFlow<Boolean> = _isPro.asStateFlow()5859    private val _activating = MutableStateFlow(false)60    val activating: StateFlow<Boolean> = _activating.asStateFlow()6162    private val _activationError = MutableStateFlow<String?>(null)63    val activationError: StateFlow<String?> = _activationError.asStateFlow()6465    /** Set true after a fresh activation so the screen can fire ProCelebration once. */66    private val _showCelebration = MutableStateFlow(false)67    val showCelebration: StateFlow<Boolean> = _showCelebration.asStateFlow()6869    /**70     * Validate a license key locally (offline Ed25519 — there is no activation server)71     * and, on success, persist it and flip Pro on. Surfaces only outcomes that can72     * actually occur offline.73     */74    fun activateLicense(rawKey: String) {75        if (_activating.value) return76        _activating.value = true77        _activationError.value = null78        viewModelScope.launch {79            val key = rawKey.trim()80            if (license.validateLicense(key)) {81                license.storeLicense(key)82                _isPro.value = true83                _showCelebration.value = true84            } else {85                _activationError.value = "Invalid license key"86            }87            _activating.value = false88        }89    }9091    fun clearActivationError() { _activationError.value = null }9293    fun dismissCelebration() {94        license.markProCelebrated()95        _showCelebration.value = false96    }9798    fun deactivate() {99        license.clearLicense()100        _isPro.value = false101    }102103    private fun mutate(block: (VaultSettings) -> VaultSettings) {104        viewModelScope.launch { vault.updateSettings(block(vault.settings.value)) }105    }106107    fun setTheme(theme: String) = mutate { it.copy(theme = theme) }108    fun setAccent(name: String) = mutate { it.copy(accentColor = name) }109    fun setTextSize(size: String) = mutate { it.copy(textSize = size) }110    fun setReduceMotion(on: Boolean) = mutate { it.copy(reduceMotion = on) }111    fun setBreachMonitoring(on: Boolean) = mutate { it.copy(breachMonitoring = on) }112    fun setBiometrics(on: Boolean) = mutate { it.copy(biometricsEnabled = on) }113114    /**115     * Enable biometric unlock: prompt to wrap the live vault key under a hardware116     * KeyStore key and persist the escrow, then flip the setting on. Requires the117     * vault to be unlocked (it is, inside Settings). A failed/cancelled prompt118     * leaves biometrics off.119     */120    fun enableBiometrics(activity: FragmentActivity) {121        val key = vault.currentVaultKey() ?: return122        val cipher = try {123            BiometricKeyStore.encryptCipher()124        } catch (_: Exception) {125            VaultCrypto.zero(key); return126        }127        Biometrics.authenticateCrypto(128            activity = activity,129            title = "Enable biometric unlock",130            subtitle = "Confirm to secure your vault key",131            crypto = BiometricPrompt.CryptoObject(cipher),132            onSuccess = { result ->133                val used = result.cryptoObject?.cipher134                if (used != null) {135                    runCatching { BiometricKeyStore.wrapAndStore(appContext, used, key) }136                        .onSuccess { mutate { it.copy(biometricsEnabled = true) } }137                }138                VaultCrypto.zero(key)139            },140            onFail = { VaultCrypto.zero(key) },141        )142    }143144    /** Disable biometric unlock: drop the escrowed key + KeyStore entry, flip the setting off. */145    fun disableBiometrics() {146        BiometricKeyStore.clear(appContext)147        mutate { it.copy(biometricsEnabled = false) }148    }149    fun setAutoLockMinutes(min: Int?) = mutate { it.copy(autoLockMinutes = min) }150    fun setTrashRetentionDays(days: Int?) = mutate { it.copy(trashRetentionDays = days) }151152    suspend fun changePassword(current: String, next: String): Boolean =153        vault.changePassword(current, next)154155    /** One-line summary shown under each card title; mirrors the browser ledes. */156    fun lede(id: CardId, entriesCount: Int, s: VaultSettings): String = when (id) {157        CardId.Pro -> if (_isPro.value) "active · paid once, yours forever" else "$39 once · yours forever"158        CardId.Protection ->159            "${if (s.breachMonitoring) "breaches watched" else "breach watch off"} · manual lock"160        CardId.Vault ->161            "$entriesCount ${if (entriesCount == 1) "entry" else "entries"} · backups, history, cleanup"162        CardId.Sync -> if (_isPro.value) "pair by chirp, keep in step" else "Pro · encrypted device pairing"163        CardId.Appearance -> "${s.theme} · ${s.accentColor} · ${s.textSize}"164        CardId.Shortcuts -> "bindings · what your fingers know"165        CardId.Feedback -> "tell us what would make it better"166    }167}