EntryDetailViewModel.kt

5.1 KB · raw

1package com.peachpasswords.ui.vault23import android.content.ClipData4import android.content.ClipboardManager5import android.content.Context6import androidx.lifecycle.SavedStateHandle7import androidx.lifecycle.ViewModel8import androidx.lifecycle.viewModelScope9import com.peachpasswords.vault.TOTPGenerator10import com.peachpasswords.vault.VaultEntry11import com.peachpasswords.vault.VaultRepository12import dagger.hilt.android.lifecycle.HiltViewModel13import dagger.hilt.android.qualifiers.ApplicationContext14import kotlinx.coroutines.flow.MutableStateFlow15import kotlinx.coroutines.flow.SharingStarted16import kotlinx.coroutines.flow.StateFlow17import kotlinx.coroutines.flow.asStateFlow18import kotlinx.coroutines.flow.map19import kotlinx.coroutines.flow.stateIn20import kotlinx.coroutines.launch21import javax.inject.Inject2223@HiltViewModel24class EntryDetailViewModel @Inject constructor(25    private val vault: VaultRepository,26    @ApplicationContext private val appContext: Context,27    savedStateHandle: SavedStateHandle,28) : ViewModel() {29    private val id: String = savedStateHandle.get<String>("id").orEmpty()3031    val entry: StateFlow<VaultEntry?> =32        vault.entries.map { list -> list.firstOrNull { it.id == id } }33            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), vault.getEntry(id))3435    /** Distinct prior username/email values for the identity-suggest dropdown. */36    val identitySuggestions: StateFlow<List<String>> =37        vault.entries38            .map { vault.getDistinctFieldValues("username").take(4) }39            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())4041    private val _revealed = MutableStateFlow(false)42    val revealed: StateFlow<Boolean> = _revealed.asStateFlow()4344    private val _copiedField = MutableStateFlow<String?>(null)45    val copiedField: StateFlow<String?> = _copiedField.asStateFlow()4647    /** Reveal the password and auto-mask after 10 seconds (matches the browser). */48    fun reveal() {49        _revealed.value = true50        viewModelScope.launch {51            kotlinx.coroutines.delay(10_000)52            _revealed.value = false53        }54    }5556    fun mask() { _revealed.value = false }5758    private val _cvcRevealed = MutableStateFlow(false)59    val cvcRevealed: StateFlow<Boolean> = _cvcRevealed.asStateFlow()6061    /** Reveal the CVC and auto-mask after 10s — same policy as the password reveal. */62    fun revealCvc() {63        _cvcRevealed.value = true64        viewModelScope.launch {65            kotlinx.coroutines.delay(10_000)66            _cvcRevealed.value = false67        }68    }6970    fun maskCvc() { _cvcRevealed.value = false }7172    fun copy(field: String, value: String?) {73        val v = value ?: return74        val cm = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager75        cm.setPrimaryClip(ClipData.newPlainText("peach", v))76        viewModelScope.launch {77            _copiedField.value = field78            kotlinx.coroutines.delay(1200)79            if (_copiedField.value == field) _copiedField.value = null80        }81    }8283    /** Copy the live TOTP code (never the seed). */84    fun copyTotp() {85        val totp = entry.value?.totp ?: return86        copy("totp", TOTPGenerator.generateCode(totp))87    }8889    /**90     * Apply a generated password via updateEntry — VaultRepository captures the91     * prior password into history automatically, so we only pass the new value.92     */93    fun applyGeneratedPassword(newPassword: String, onDone: () -> Unit = {}) {94        val current = entry.value ?: return95        if (newPassword.isEmpty() || newPassword == current.password) { onDone(); return }96        viewModelScope.launch {97            runCatching { vault.updateEntry(current.copy(password = newPassword)) }98            onDone()99        }100    }101102    /**103     * Persist a single field's inline edit via a full-entry updateEntry patch104     * (which handles password-history capture + timestamps). No-op if entry gone.105     */106    fun updateField(field: String, value: String) {107        val current = entry.value ?: return108        val patch = when (field) {109            "username" -> current.copy(username = value.ifBlank { null })110            "email" -> current.copy(email = value.ifBlank { null })111            "password" -> current.copy(password = value.ifBlank { null })112            "notes" -> current.copy(notes = value.ifBlank { null })113            "totp" -> current.copy(totp = value.ifBlank { null })114            else -> return115        }116        viewModelScope.launch {117            runCatching { vault.updateEntry(patch) }118        }119    }120121    /**122     * Restore a past password as the current one. updateEntry captures the123     * now-outgoing password into history, so this is a normal password swap.124     */125    fun restorePassword(entryId: String, oldPassword: String) {126        viewModelScope.launch {127            val current = vault.getEntry(entryId) ?: return@launch128            if (current.password == oldPassword) return@launch129            runCatching { vault.updateEntry(current.copy(password = oldPassword)) }130        }131    }132133    fun delete(onDone: () -> Unit) {134        viewModelScope.launch {135            runCatching { vault.deleteEntry(id) }136            onDone()137        }138    }139}