EntryDetailViewModel.kt

2.6 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    private val _revealed = MutableStateFlow(false)36    val revealed: StateFlow<Boolean> = _revealed.asStateFlow()3738    private val _copiedField = MutableStateFlow<String?>(null)39    val copiedField: StateFlow<String?> = _copiedField.asStateFlow()4041    /** Reveal the password and auto-mask after 10 seconds (matches the browser). */42    fun reveal() {43        _revealed.value = true44        viewModelScope.launch {45            kotlinx.coroutines.delay(10_000)46            _revealed.value = false47        }48    }4950    fun mask() { _revealed.value = false }5152    fun copy(field: String, value: String?) {53        val v = value ?: return54        val cm = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager55        cm.setPrimaryClip(ClipData.newPlainText("peach", v))56        viewModelScope.launch {57            _copiedField.value = field58            kotlinx.coroutines.delay(1200)59            if (_copiedField.value == field) _copiedField.value = null60        }61    }6263    /** Copy the live TOTP code (never the seed). */64    fun copyTotp() {65        val totp = entry.value?.totp ?: return66        copy("totp", TOTPGenerator.generateCode(totp))67    }6869    fun delete(onDone: () -> Unit) {70        viewModelScope.launch {71            runCatching { vault.deleteEntry(id) }72            onDone()73        }74    }75}