EntryEditViewModel.kt

11.5 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)5152@HiltViewModel53class EntryEditViewModel @Inject constructor(54    private val vault: VaultRepository,55    @ApplicationContext private val appContext: Context,56    savedStateHandle: SavedStateHandle,57) : ViewModel() {58    private val id: String? = savedStateHandle.get<String>("id")?.takeIf { it.isNotBlank() }59    val isNew: Boolean = id == null60    private val existing: VaultEntry? = id?.let { vault.getEntry(it) }6162    private val _form = MutableStateFlow(63        existing?.let {64            EditForm(65                type = it.type ?: "login",66                title = it.title,67                username = it.username.orEmpty(),68                email = it.email.orEmpty(),69                password = it.password.orEmpty(),70                url = it.url.orEmpty(),71                additionalUrls = it.additionalUrls.orEmpty(),72                totp = it.totp.orEmpty(),73                notes = it.notes.orEmpty(),74                cardNumber = CardFieldUtils.formatPan(it.cardNumber.orEmpty()),75                cardholderName = it.cardholderName.orEmpty(),76                expiry = CardFieldUtils.displayExpiry(it.expMonth, it.expYear),77                cvc = it.cvc.orEmpty(),78                cardNetwork = it.cardNetwork ?: CardFieldUtils.detectNetwork(it.cardNumber.orEmpty()),79                tags = it.tags.orEmpty(),80                history = it.passwordHistory.orEmpty(),81            )82        } ?: EditForm(),83    )84    val form: StateFlow<EditForm> = _form.asStateFlow()8586    /**87     * Up to 4 previously-used identity values, frequency-sorted. Username and88     * email share one field in the Peach model, so both editor fields suggest89     * from "username".90     */91    val usernameSuggestions: StateFlow<List<String>> =92        MutableStateFlow(vault.getDistinctFieldValues("username").take(4)).asStateFlow()9394    fun setType(t: String) = _form.update { it.copy(type = t) }9596    /**97     * Create a blank NOTE entry and hand its id to [onOpen] so the caller can98     * navigate straight into the full-screen notes editor (brief Fix 6 item 7) —99     * a new note never shows the generic edit form.100     */101    fun createNoteAndOpen(onOpen: (String) -> Unit) {102        viewModelScope.launch {103            runCatching {104                vault.addEntry(VaultEntry(id = "", type = "note", title = "", createdAt = 0, modifiedAt = 0))105            }.onSuccess { onOpen(it.id) }106                .onFailure { e -> _form.update { it.copy(error = e.message ?: "could not create note") } }107        }108    }109    fun setTitle(v: String) = _form.update { it.copy(title = v, error = null) }110    fun setUsername(v: String) = _form.update { it.copy(username = v) }111    fun setEmail(v: String) = _form.update { it.copy(email = v) }112    fun setPassword(v: String) = _form.update { it.copy(password = v) }113    fun setUrl(v: String) = _form.update { it.copy(url = v) }114    fun setAdditionalUrl(index: Int, v: String) = _form.update { form ->115        form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it[index] = v })116    }117    fun addAdditionalUrl() = _form.update { form ->118        if (form.additionalUrls.size >= MAX_ADDITIONAL_URLS) form119        else form.copy(additionalUrls = form.additionalUrls + "")120    }121    fun removeAdditionalUrl(index: Int) = _form.update { form ->122        form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it.removeAt(index) })123    }124    fun setTotp(v: String) = _form.update { it.copy(totp = v) }125    fun setNotes(v: String) = _form.update { it.copy(notes = v) }126    fun setCardNumber(v: String) = _form.update {127        val formatted = CardFieldUtils.formatPan(v)128        it.copy(cardNumber = formatted, cardNetwork = CardFieldUtils.detectNetwork(formatted), error = null)129    }130    fun setCardholderName(v: String) = _form.update { it.copy(cardholderName = v, error = null) }131    fun setExpiry(v: String) = _form.update { it.copy(expiry = CardFieldUtils.formatExpiry(v), error = null) }132    fun setCvc(v: String) = _form.update {133        it.copy(cvc = v.filter { c -> c.isDigit() }.take(CardFieldUtils.cvcMaxDigits(it.cardNetwork)))134    }135    fun toggleShowCvc() = _form.update { it.copy(showCvc = !it.showCvc) }136137    val allTags: List<String> = vault.getDistinctTags()138    fun addTag(raw: String) = _form.update { f ->139        val tag = raw.trim().lowercase().take(32)140        if (tag.isEmpty() || f.tags.size >= 10 || f.tags.any { it == tag }) f141        else f.copy(tags = f.tags + tag)142    }143    fun removeTag(tag: String) = _form.update { it.copy(tags = it.tags - tag) }144145    fun toggleShowPassword() = _form.update { it.copy(showPassword = !it.showPassword) }146    fun toggleGenerator() = _form.update { it.copy(generatorOpen = !it.generatorOpen, showHistory = false) }147    fun toggleHistory() = _form.update { it.copy(showHistory = !it.showHistory, generatorOpen = false) }148149    /** Restore a past password into the editor; the save flow records the swap. */150    fun restorePassword(pw: String) =151        _form.update { it.copy(password = pw, showPassword = true, showHistory = false) }152153    /** Copy the current generated/typed password to the clipboard with a drain latch. */154    fun copyGenerated() {155        val pw = _form.value.password156        if (pw.isEmpty()) return157        PeachClipboard.copy(appContext, "peach", pw)158        viewModelScope.launch {159            _form.update { it.copy(genCopied = true) }160            kotlinx.coroutines.delay(1200)161            _form.update { it.copy(genCopied = false) }162        }163    }164165    fun copyHistoryPassword(pw: String) {166        PeachClipboard.copy(appContext, "peach", pw)167    }168    fun setGenLength(n: Int) = _form.update { it.copy(genLength = n) }169    fun setGenUpper(b: Boolean) = _form.update { it.copy(genUpper = b) }170    fun setGenLower(b: Boolean) = _form.update { it.copy(genLower = b) }171    fun setGenNumbers(b: Boolean) = _form.update { it.copy(genNumbers = b) }172    fun setGenSymbols(b: Boolean) = _form.update { it.copy(genSymbols = b) }173174    fun generate() {175        val f = _form.value176        val pw = PasswordGenerator.generate(177            PasswordGenerator.Options(178                length = f.genLength,179                includeUppercase = f.genUpper,180                includeLowercase = f.genLower,181                includeNumbers = f.genNumbers,182                includeSymbols = f.genSymbols,183            ),184        )185        _form.update { it.copy(password = pw, showPassword = true) }186    }187188    fun save(onDone: () -> Unit) {189        val f = _form.value190        if (f.title.isBlank()) {191            _form.update { it.copy(error = "title is required") }192            return193        }194        if (f.type == "card" && (f.cardNumber.isBlank() || f.cardholderName.isBlank())) {195            _form.update { it.copy(error = "Cardholder name and card number are required") }196            return197        }198        _form.update { it.copy(saving = true, error = null) }199        viewModelScope.launch {200            runCatching {201                if (isNew) {202                    vault.addEntry(203                        VaultEntry(204                            id = "", type = f.type, title = f.title.trim(),205                            username = f.username.ifBlank { null },206                            email = f.email.ifBlank { null },207                            password = f.password.ifBlank { null },208                            url = f.url.ifBlank { null },209                            additionalUrls = f.additionalUrls210                                .map { it.trim() }.filter { it.isNotBlank() }211                                .ifEmpty { null },212                            totp = f.totp.ifBlank { null },213                            notes = f.notes.ifBlank { null },214                            cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },215                            cardholderName = f.cardholderName.ifBlank { null },216                            expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },217                            expYear = f.expiry.filter { it.isDigit() }.drop(2).take(2).ifBlank { null },218                            cvc = f.cvc.ifBlank { null },219                            cardNetwork = f.cardNetwork.takeIf { it != "unknown" },220                            tags = f.tags.ifEmpty { null },221                            createdAt = 0, modifiedAt = 0,222                        ),223                    )224                } else {225                    vault.updateEntry(226                        existing!!.copy(227                            type = f.type, title = f.title.trim(),228                            username = f.username.ifBlank { null },229                            email = f.email.ifBlank { null },230                            password = f.password.ifBlank { null },231                            url = f.url.ifBlank { null },232                            additionalUrls = f.additionalUrls233                                .map { it.trim() }.filter { it.isNotBlank() }234                                .ifEmpty { null },235                            totp = f.totp.ifBlank { null },236                            notes = f.notes.ifBlank { null },237                            cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },238                            cardholderName = f.cardholderName.ifBlank { null },239                            expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },240                            expYear = f.expiry.filter { it.isDigit() }.drop(2).take(2).ifBlank { null },241                            cvc = f.cvc.ifBlank { null },242                            cardNetwork = f.cardNetwork.takeIf { it != "unknown" },243                            tags = f.tags.ifEmpty { null },244                        ),245                    )246                }247            }.onSuccess { onDone() }248                .onFailure { e -> _form.update { it.copy(saving = false, error = e.message ?: "save failed") } }249        }250    }251}