EntryEditViewModel.kt

11.8 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.vault.PasswordGenerator9import com.peachpasswords.vault.PasswordHistoryItem10import 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.StateFlow16import kotlinx.coroutines.flow.asStateFlow17import kotlinx.coroutines.flow.update18import kotlinx.coroutines.launch19import javax.inject.Inject2021data class EditForm(22    val type: String = "login",23    val title: String = "",24    val username: String = "",25    val email: String = "",26    val password: String = "",27    val url: String = "",28    val additionalUrls: List<String> = emptyList(),29    val totp: String = "",30    val notes: String = "",31    val cardNumber: String = "",32    val cardholderName: String = "",33    val expiry: String = "",        // "MM/YY"; split into expMonth/expYear on save34    val cvc: String = "",35    val showCvc: Boolean = false,36    val cardNetwork: String = "unknown",37    val tags: List<String> = emptyList(),38    val showPassword: Boolean = false,39    val generatorOpen: Boolean = false,40    val genCopied: Boolean = false,41    val history: List<PasswordHistoryItem> = emptyList(),42    val showHistory: Boolean = false,43    val genLength: Int = 20,44    val genUpper: Boolean = true,45    val genLower: Boolean = true,46    val genNumbers: Boolean = true,47    val genSymbols: Boolean = true,48    val saving: Boolean = false,49    val error: String? = null,50    val showTotp: Boolean = false,51    val showNotes: Boolean = false,52)5354@HiltViewModel55class EntryEditViewModel @Inject constructor(56    private val vault: VaultRepository,57    @ApplicationContext private val appContext: Context,58    savedStateHandle: SavedStateHandle,59) : ViewModel() {60    private val id: String? = savedStateHandle.get<String>("id")?.takeIf { it.isNotBlank() }61    val isNew: Boolean = id == null62    private val existing: VaultEntry? = id?.let { vault.getEntry(it) }6364    private val _form = MutableStateFlow(65        existing?.let {66            EditForm(67                type = it.type ?: "login",68                title = it.title,69                username = it.username.orEmpty(),70                email = it.email.orEmpty(),71                password = it.password.orEmpty(),72                url = it.url.orEmpty(),73                additionalUrls = it.additionalUrls.orEmpty(),74                totp = it.totp.orEmpty(),75                notes = it.notes.orEmpty(),76                cardNumber = CardFieldUtils.formatPan(it.cardNumber.orEmpty()),77                cardholderName = it.cardholderName.orEmpty(),78                expiry = CardFieldUtils.displayExpiry(it.expMonth, it.expYear),79                cvc = it.cvc.orEmpty(),80                cardNetwork = it.cardNetwork ?: CardFieldUtils.detectNetwork(it.cardNumber.orEmpty()),81                tags = it.tags.orEmpty(),82                history = it.passwordHistory.orEmpty(),83                showTotp = !it.totp.isNullOrBlank(),84                showNotes = !it.notes.isNullOrBlank(),85            )86        } ?: EditForm(),87    )88    val form: StateFlow<EditForm> = _form.asStateFlow()8990    /**91     * Up to 4 previously-used identity values, frequency-sorted. Username and92     * email share one field in the Peach model, so both editor fields suggest93     * from "username".94     */95    val usernameSuggestions: StateFlow<List<String>> =96        MutableStateFlow(vault.getDistinctFieldValues("username").take(4)).asStateFlow()9798    fun setType(t: String) = _form.update { it.copy(type = t) }99100    /**101     * Create a blank NOTE entry and hand its id to [onOpen] so the caller can102     * navigate straight into the full-screen notes editor (brief Fix 6 item 7) —103     * a new note never shows the generic edit form.104     */105    fun createNoteAndOpen(onOpen: (String) -> Unit) {106        viewModelScope.launch {107            runCatching {108                vault.addEntry(VaultEntry(id = "", type = "note", title = "", createdAt = 0, modifiedAt = 0))109            }.onSuccess { onOpen(it.id) }110                .onFailure { e -> _form.update { it.copy(error = e.message ?: "could not create note") } }111        }112    }113    fun setTitle(v: String) = _form.update { it.copy(title = v, error = null) }114    fun setUsername(v: String) = _form.update { it.copy(username = v) }115    fun setEmail(v: String) = _form.update { it.copy(email = v) }116    fun setPassword(v: String) = _form.update { it.copy(password = v) }117    fun setUrl(v: String) = _form.update { it.copy(url = v) }118    fun setAdditionalUrl(index: Int, v: String) = _form.update { form ->119        form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it[index] = v })120    }121    fun addAdditionalUrl() = _form.update { form ->122        if (form.additionalUrls.size >= MAX_ADDITIONAL_URLS) form123        else form.copy(additionalUrls = form.additionalUrls + "")124    }125    fun removeAdditionalUrl(index: Int) = _form.update { form ->126        form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it.removeAt(index) })127    }128    fun setTotp(v: String) = _form.update { it.copy(totp = v) }129    fun setNotes(v: String) = _form.update { it.copy(notes = v) }130    fun revealTotp() = _form.update { it.copy(showTotp = true) }131    fun revealNotes() = _form.update { it.copy(showNotes = true) }132    fun setCardNumber(v: String) = _form.update {133        val formatted = CardFieldUtils.formatPan(v)134        it.copy(cardNumber = formatted, cardNetwork = CardFieldUtils.detectNetwork(formatted), error = null)135    }136    fun setCardholderName(v: String) = _form.update { it.copy(cardholderName = v, error = null) }137    fun setExpiry(v: String) = _form.update { it.copy(expiry = CardFieldUtils.formatExpiry(v), error = null) }138    fun setCvc(v: String) = _form.update {139        it.copy(cvc = v.filter { c -> c.isDigit() }.take(CardFieldUtils.cvcMaxDigits(it.cardNetwork)))140    }141    fun toggleShowCvc() = _form.update { it.copy(showCvc = !it.showCvc) }142143    val allTags: List<String> = vault.getDistinctTags()144    fun addTag(raw: String) = _form.update { f ->145        val tag = raw.trim().lowercase().take(32)146        if (tag.isEmpty() || f.tags.size >= 10 || f.tags.any { it == tag }) f147        else f.copy(tags = f.tags + tag)148    }149    fun removeTag(tag: String) = _form.update { it.copy(tags = it.tags - tag) }150151    fun toggleShowPassword() = _form.update { it.copy(showPassword = !it.showPassword) }152    fun toggleGenerator() = _form.update { it.copy(generatorOpen = !it.generatorOpen, showHistory = false) }153    fun toggleHistory() = _form.update { it.copy(showHistory = !it.showHistory, generatorOpen = false) }154155    /** Restore a past password into the editor; the save flow records the swap. */156    fun restorePassword(pw: String) =157        _form.update { it.copy(password = pw, showPassword = true, showHistory = false) }158159    /** Copy the current generated/typed password to the clipboard with a drain latch. */160    fun copyGenerated() {161        val pw = _form.value.password162        if (pw.isEmpty()) return163        PeachClipboard.copy(appContext, "peach", pw)164        viewModelScope.launch {165            _form.update { it.copy(genCopied = true) }166            kotlinx.coroutines.delay(1200)167            _form.update { it.copy(genCopied = false) }168        }169    }170171    fun copyHistoryPassword(pw: String) {172        PeachClipboard.copy(appContext, "peach", pw)173    }174    fun setGenLength(n: Int) = _form.update { it.copy(genLength = n) }175    fun setGenUpper(b: Boolean) = _form.update { it.copy(genUpper = b) }176    fun setGenLower(b: Boolean) = _form.update { it.copy(genLower = b) }177    fun setGenNumbers(b: Boolean) = _form.update { it.copy(genNumbers = b) }178    fun setGenSymbols(b: Boolean) = _form.update { it.copy(genSymbols = b) }179180    fun generate() {181        val f = _form.value182        val pw = PasswordGenerator.generate(183            PasswordGenerator.Options(184                length = f.genLength,185                includeUppercase = f.genUpper,186                includeLowercase = f.genLower,187                includeNumbers = f.genNumbers,188                includeSymbols = f.genSymbols,189            ),190        )191        _form.update { it.copy(password = pw, showPassword = true) }192    }193194    fun save(onDone: () -> Unit) {195        val f = _form.value196        if (f.saving) return197        if (f.title.isBlank()) {198            _form.update { it.copy(error = "title is required") }199            return200        }201        if (f.type == "card" && (f.cardNumber.isBlank() || f.cardholderName.isBlank())) {202            _form.update { it.copy(error = "Cardholder name and card number are required") }203            return204        }205        _form.update { it.copy(saving = true, error = null) }206        viewModelScope.launch {207            runCatching {208                if (isNew) {209                    vault.addEntry(210                        VaultEntry(211                            id = "", type = f.type, title = f.title.trim(),212                            username = f.username.ifBlank { null },213                            email = f.email.ifBlank { null },214                            password = f.password.ifBlank { null },215                            url = f.url.ifBlank { null },216                            additionalUrls = f.additionalUrls217                                .map { it.trim() }.filter { it.isNotBlank() }218                                .ifEmpty { null },219                            totp = f.totp.ifBlank { null },220                            notes = f.notes.ifBlank { null },221                            cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },222                            cardholderName = f.cardholderName.ifBlank { null },223                            expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },224                            expYear = f.expiry.filter { it.isDigit() }.drop(2).take(2).ifBlank { null },225                            cvc = f.cvc.ifBlank { null },226                            cardNetwork = f.cardNetwork.takeIf { it != "unknown" },227                            tags = f.tags.ifEmpty { null },228                            createdAt = 0, modifiedAt = 0,229                        ),230                    )231                } else {232                    vault.updateEntry(233                        existing!!.copy(234                            type = f.type, title = f.title.trim(),235                            username = f.username.ifBlank { null },236                            email = f.email.ifBlank { null },237                            password = f.password.ifBlank { null },238                            url = f.url.ifBlank { null },239                            additionalUrls = f.additionalUrls240                                .map { it.trim() }.filter { it.isNotBlank() }241                                .ifEmpty { null },242                            totp = f.totp.ifBlank { null },243                            notes = f.notes.ifBlank { null },244                            cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },245                            cardholderName = f.cardholderName.ifBlank { null },246                            expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },247                            expYear = f.expiry.filter { it.isDigit() }.drop(2).take(2).ifBlank { null },248                            cvc = f.cvc.ifBlank { null },249                            cardNetwork = f.cardNetwork.takeIf { it != "unknown" },250                            tags = f.tags.ifEmpty { null },251                        ),252                    )253                }254            }.onSuccess { onDone() }255                .onFailure { e -> _form.update { it.copy(saving = false, error = e.message ?: "save failed") } }256        }257    }258}