EntryEditViewModel.kt

6.2 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.PasswordGenerator10import com.peachpasswords.vault.PasswordHistoryItem11import com.peachpasswords.vault.VaultEntry12import com.peachpasswords.vault.VaultRepository13import dagger.hilt.android.lifecycle.HiltViewModel14import dagger.hilt.android.qualifiers.ApplicationContext15import kotlinx.coroutines.flow.MutableStateFlow16import kotlinx.coroutines.flow.StateFlow17import kotlinx.coroutines.flow.asStateFlow18import kotlinx.coroutines.flow.update19import kotlinx.coroutines.launch20import javax.inject.Inject2122data class EditForm(23    val type: String = "login",24    val title: String = "",25    val username: String = "",26    val email: String = "",27    val password: String = "",28    val url: String = "",29    val totp: String = "",30    val notes: String = "",31    val showPassword: Boolean = false,32    val generatorOpen: Boolean = false,33    val history: List<PasswordHistoryItem> = emptyList(),34    val showHistory: Boolean = false,35    val genLength: Int = 20,36    val genUpper: Boolean = true,37    val genLower: Boolean = true,38    val genNumbers: Boolean = true,39    val genSymbols: Boolean = true,40    val saving: Boolean = false,41    val error: String? = null,42)4344@HiltViewModel45class EntryEditViewModel @Inject constructor(46    private val vault: VaultRepository,47    @ApplicationContext private val appContext: Context,48    savedStateHandle: SavedStateHandle,49) : ViewModel() {50    private val id: String? = savedStateHandle.get<String>("id")?.takeIf { it.isNotBlank() }51    val isNew: Boolean = id == null52    private val existing: VaultEntry? = id?.let { vault.getEntry(it) }5354    private val _form = MutableStateFlow(55        existing?.let {56            EditForm(57                type = it.type ?: "login",58                title = it.title,59                username = it.username.orEmpty(),60                email = it.email.orEmpty(),61                password = it.password.orEmpty(),62                url = it.url.orEmpty(),63                totp = it.totp.orEmpty(),64                notes = it.notes.orEmpty(),65                history = it.passwordHistory.orEmpty(),66            )67        } ?: EditForm(),68    )69    val form: StateFlow<EditForm> = _form.asStateFlow()7071    fun setType(t: String) = _form.update { it.copy(type = t) }72    fun setTitle(v: String) = _form.update { it.copy(title = v, error = null) }73    fun setUsername(v: String) = _form.update { it.copy(username = v) }74    fun setEmail(v: String) = _form.update { it.copy(email = v) }75    fun setPassword(v: String) = _form.update { it.copy(password = v) }76    fun setUrl(v: String) = _form.update { it.copy(url = v) }77    fun setTotp(v: String) = _form.update { it.copy(totp = v) }78    fun setNotes(v: String) = _form.update { it.copy(notes = v) }79    fun toggleShowPassword() = _form.update { it.copy(showPassword = !it.showPassword) }80    fun toggleGenerator() = _form.update { it.copy(generatorOpen = !it.generatorOpen, showHistory = false) }81    fun toggleHistory() = _form.update { it.copy(showHistory = !it.showHistory, generatorOpen = false) }8283    /** Restore a past password into the editor; the save flow records the swap. */84    fun restorePassword(pw: String) =85        _form.update { it.copy(password = pw, showPassword = true, showHistory = false) }8687    fun copyHistoryPassword(pw: String) {88        val cm = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager89        cm.setPrimaryClip(ClipData.newPlainText("peach", pw))90    }91    fun setGenLength(n: Int) = _form.update { it.copy(genLength = n) }92    fun setGenUpper(b: Boolean) = _form.update { it.copy(genUpper = b) }93    fun setGenLower(b: Boolean) = _form.update { it.copy(genLower = b) }94    fun setGenNumbers(b: Boolean) = _form.update { it.copy(genNumbers = b) }95    fun setGenSymbols(b: Boolean) = _form.update { it.copy(genSymbols = b) }9697    fun generate() {98        val f = _form.value99        val pw = PasswordGenerator.generate(100            PasswordGenerator.Options(101                length = f.genLength,102                includeUppercase = f.genUpper,103                includeLowercase = f.genLower,104                includeNumbers = f.genNumbers,105                includeSymbols = f.genSymbols,106            ),107        )108        _form.update { it.copy(password = pw, showPassword = true) }109    }110111    fun save(onDone: () -> Unit) {112        val f = _form.value113        if (f.title.isBlank()) {114            _form.update { it.copy(error = "title is required") }115            return116        }117        _form.update { it.copy(saving = true, error = null) }118        viewModelScope.launch {119            runCatching {120                if (isNew) {121                    vault.addEntry(122                        VaultEntry(123                            id = "", type = f.type, title = f.title.trim(),124                            username = f.username.ifBlank { null },125                            email = f.email.ifBlank { null },126                            password = f.password.ifBlank { null },127                            url = f.url.ifBlank { null },128                            totp = f.totp.ifBlank { null },129                            notes = f.notes.ifBlank { null },130                            createdAt = 0, modifiedAt = 0,131                        ),132                    )133                } else {134                    vault.updateEntry(135                        existing!!.copy(136                            type = f.type, title = f.title.trim(),137                            username = f.username.ifBlank { null },138                            email = f.email.ifBlank { null },139                            password = f.password.ifBlank { null },140                            url = f.url.ifBlank { null },141                            totp = f.totp.ifBlank { null },142                            notes = f.notes.ifBlank { null },143                        ),144                    )145                }146            }.onSuccess { onDone() }147                .onFailure { e -> _form.update { it.copy(saving = false, error = e.message ?: "save failed") } }148        }149    }150}