EntryDetailViewModel.kt

6.6 KB · raw

1package com.peachpasswords.ui.vault23import android.content.Context4import com.peachpasswords.shared.PeachClipboard5import androidx.lifecycle.SavedStateHandle6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import com.peachpasswords.ui.PeachNav9import com.peachpasswords.ui.vault.entryTapDestination10import com.peachpasswords.vault.LastViewedEntryStore11import com.peachpasswords.vault.TOTPGenerator12import com.peachpasswords.vault.VaultEntry13import com.peachpasswords.vault.VaultRepository14import dagger.hilt.android.lifecycle.HiltViewModel15import dagger.hilt.android.qualifiers.ApplicationContext16import kotlinx.coroutines.flow.MutableStateFlow17import kotlinx.coroutines.flow.SharingStarted18import kotlinx.coroutines.flow.StateFlow19import kotlinx.coroutines.flow.asStateFlow20import kotlinx.coroutines.flow.map21import kotlinx.coroutines.flow.stateIn22import kotlinx.coroutines.launch23import javax.inject.Inject2425@HiltViewModel26class EntryDetailViewModel @Inject constructor(27    private val vault: VaultRepository,28    @ApplicationContext private val appContext: Context,29    private val lastViewed: LastViewedEntryStore,30    savedStateHandle: SavedStateHandle,31) : ViewModel() {32    private val id: String = savedStateHandle.get<String>("id").orEmpty()3334    init {35        // Remember this as the entry to reopen on the next unlock (brief Fix 3).36        // Only record a real, live entry so a bad deep-link id never becomes the target.37        if (id.isNotBlank() && vault.getEntry(id) != null) lastViewed.set(id)38    }3940    val entry: StateFlow<VaultEntry?> =41        vault.entries.map { list -> list.firstOrNull { it.id == id } }42            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), vault.getEntry(id))4344    val activeEntries: StateFlow<List<VaultEntry>> =45        vault.entries.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), vault.getActiveEntries())4647    /** Distinct prior username/email values for the identity-suggest dropdown. */48    val identitySuggestions: StateFlow<List<String>> =49        vault.entries50            .map { vault.getDistinctFieldValues("username").take(4) }51            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())5253    private val _revealed = MutableStateFlow(false)54    val revealed: StateFlow<Boolean> = _revealed.asStateFlow()5556    private val _copiedField = MutableStateFlow<String?>(null)57    val copiedField: StateFlow<String?> = _copiedField.asStateFlow()5859    /** Reveal the password and auto-mask after 10 seconds (matches the browser). */60    fun reveal() {61        _revealed.value = true62        viewModelScope.launch {63            kotlinx.coroutines.delay(10_000)64            _revealed.value = false65        }66    }6768    fun mask() { _revealed.value = false }6970    private val _cvcRevealed = MutableStateFlow(false)71    val cvcRevealed: StateFlow<Boolean> = _cvcRevealed.asStateFlow()7273    /** Reveal the CVC and auto-mask after 10s — same policy as the password reveal. */74    fun revealCvc() {75        _cvcRevealed.value = true76        viewModelScope.launch {77            kotlinx.coroutines.delay(10_000)78            _cvcRevealed.value = false79        }80    }8182    fun maskCvc() { _cvcRevealed.value = false }8384    fun copy(field: String, value: String?) {85        val v = value ?: return86        PeachClipboard.copy(appContext, "peach", v)87        viewModelScope.launch {88            _copiedField.value = field89            kotlinx.coroutines.delay(1200)90            if (_copiedField.value == field) _copiedField.value = null91        }92    }9394    /** Copy the live TOTP code (never the seed). */95    fun copyTotp() {96        val totp = entry.value?.totp ?: return97        copy("totp", TOTPGenerator.generateCode(totp))98    }99100    fun adjacentDestination(offset: Int): PeachNav? {101        val list = activeEntries.value102        if (list.isEmpty()) return null103        val currentIndex = list.indexOfFirst { it.id == id }104        if (currentIndex < 0) return null105        val nextIndex = (currentIndex + offset + list.size) % list.size106        return entryTapDestination(list[nextIndex])107    }108109    /**110     * Apply a generated password via updateEntry — VaultRepository captures the111     * prior password into history automatically, so we only pass the new value.112     */113    fun applyGeneratedPassword(newPassword: String, onDone: () -> Unit = {}) {114        val current = entry.value ?: return115        if (newPassword.isEmpty() || newPassword == current.password) { onDone(); return }116        viewModelScope.launch {117            runCatching { vault.updateEntry(current.copy(password = newPassword)) }118            onDone()119        }120    }121122    /**123     * Persist a single field's inline edit via a full-entry updateEntry patch124     * (which handles password-history capture + timestamps). No-op if entry gone.125     */126    fun updateField(field: String, value: String) {127        val current = entry.value ?: return128        val patch = when (field) {129            "title" -> current.copy(title = value.trim().ifBlank { current.title })130            "url" -> current.copy(url = value.ifBlank { null })131            "username" -> current.copy(username = value.ifBlank { null })132            "email" -> current.copy(email = value.ifBlank { null })133            "password" -> current.copy(password = value.ifBlank { null })134            "notes" -> current.copy(notes = value.ifBlank { null })135            "totp" -> current.copy(totp = value.ifBlank { null })136            else -> return137        }138        viewModelScope.launch {139            runCatching { vault.updateEntry(patch) }140        }141    }142143    fun updateAdditionalUrl(index: Int, value: String) {144        val current = entry.value ?: return145        val urls = current.additionalUrls.orEmpty().toMutableList()146        if (index !in urls.indices) return147        urls[index] = value148        val patch = current.copy(149            additionalUrls = urls.map { it.trim() }.filter { it.isNotBlank() }.ifEmpty { null },150        )151        viewModelScope.launch {152            runCatching { vault.updateEntry(patch) }153        }154    }155156    /**157     * Restore a past password as the current one. updateEntry captures the158     * now-outgoing password into history, so this is a normal password swap.159     */160    fun restorePassword(entryId: String, oldPassword: String) {161        viewModelScope.launch {162            val current = vault.getEntry(entryId) ?: return@launch163            if (current.password == oldPassword) return@launch164            runCatching { vault.updateEntry(current.copy(password = oldPassword)) }165        }166    }167168    fun delete(onDone: () -> Unit) {169        viewModelScope.launch {170            runCatching { vault.deleteEntry(id) }171            onDone()172        }173    }174}