EntryEditViewModel.kt

10.9 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) }95    fun setTitle(v: String) = _form.update { it.copy(title = v, error = null) }96    fun setUsername(v: String) = _form.update { it.copy(username = v) }97    fun setEmail(v: String) = _form.update { it.copy(email = v) }98    fun setPassword(v: String) = _form.update { it.copy(password = v) }99    fun setUrl(v: String) = _form.update { it.copy(url = v) }100    fun setAdditionalUrl(index: Int, v: String) = _form.update { form ->101        form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it[index] = v })102    }103    fun addAdditionalUrl() = _form.update { form ->104        if (form.additionalUrls.size >= MAX_ADDITIONAL_URLS) form105        else form.copy(additionalUrls = form.additionalUrls + "")106    }107    fun removeAdditionalUrl(index: Int) = _form.update { form ->108        form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it.removeAt(index) })109    }110    fun setTotp(v: String) = _form.update { it.copy(totp = v) }111    fun setNotes(v: String) = _form.update { it.copy(notes = v) }112    fun setCardNumber(v: String) = _form.update {113        val formatted = CardFieldUtils.formatPan(v)114        it.copy(cardNumber = formatted, cardNetwork = CardFieldUtils.detectNetwork(formatted), error = null)115    }116    fun setCardholderName(v: String) = _form.update { it.copy(cardholderName = v, error = null) }117    fun setExpiry(v: String) = _form.update { it.copy(expiry = CardFieldUtils.formatExpiry(v), error = null) }118    fun setCvc(v: String) = _form.update {119        it.copy(cvc = v.filter { c -> c.isDigit() }.take(CardFieldUtils.cvcMaxDigits(it.cardNetwork)))120    }121    fun toggleShowCvc() = _form.update { it.copy(showCvc = !it.showCvc) }122123    val allTags: List<String> = vault.getDistinctTags()124    fun addTag(raw: String) = _form.update { f ->125        val tag = raw.trim().lowercase().take(32)126        if (tag.isEmpty() || f.tags.size >= 10 || f.tags.any { it == tag }) f127        else f.copy(tags = f.tags + tag)128    }129    fun removeTag(tag: String) = _form.update { it.copy(tags = it.tags - tag) }130131    fun toggleShowPassword() = _form.update { it.copy(showPassword = !it.showPassword) }132    fun toggleGenerator() = _form.update { it.copy(generatorOpen = !it.generatorOpen, showHistory = false) }133    fun toggleHistory() = _form.update { it.copy(showHistory = !it.showHistory, generatorOpen = false) }134135    /** Restore a past password into the editor; the save flow records the swap. */136    fun restorePassword(pw: String) =137        _form.update { it.copy(password = pw, showPassword = true, showHistory = false) }138139    /** Copy the current generated/typed password to the clipboard with a drain latch. */140    fun copyGenerated() {141        val pw = _form.value.password142        if (pw.isEmpty()) return143        PeachClipboard.copy(appContext, "peach", pw)144        viewModelScope.launch {145            _form.update { it.copy(genCopied = true) }146            kotlinx.coroutines.delay(1200)147            _form.update { it.copy(genCopied = false) }148        }149    }150151    fun copyHistoryPassword(pw: String) {152        PeachClipboard.copy(appContext, "peach", pw)153    }154    fun setGenLength(n: Int) = _form.update { it.copy(genLength = n) }155    fun setGenUpper(b: Boolean) = _form.update { it.copy(genUpper = b) }156    fun setGenLower(b: Boolean) = _form.update { it.copy(genLower = b) }157    fun setGenNumbers(b: Boolean) = _form.update { it.copy(genNumbers = b) }158    fun setGenSymbols(b: Boolean) = _form.update { it.copy(genSymbols = b) }159160    fun generate() {161        val f = _form.value162        val pw = PasswordGenerator.generate(163            PasswordGenerator.Options(164                length = f.genLength,165                includeUppercase = f.genUpper,166                includeLowercase = f.genLower,167                includeNumbers = f.genNumbers,168                includeSymbols = f.genSymbols,169            ),170        )171        _form.update { it.copy(password = pw, showPassword = true) }172    }173174    fun save(onDone: () -> Unit) {175        val f = _form.value176        if (f.title.isBlank()) {177            _form.update { it.copy(error = "title is required") }178            return179        }180        if (f.type == "card" && (f.cardNumber.isBlank() || f.cardholderName.isBlank())) {181            _form.update { it.copy(error = "Cardholder name and card number are required") }182            return183        }184        _form.update { it.copy(saving = true, error = null) }185        viewModelScope.launch {186            runCatching {187                if (isNew) {188                    vault.addEntry(189                        VaultEntry(190                            id = "", type = f.type, title = f.title.trim(),191                            username = f.username.ifBlank { null },192                            email = f.email.ifBlank { null },193                            password = f.password.ifBlank { null },194                            url = f.url.ifBlank { null },195                            additionalUrls = f.additionalUrls196                                .map { it.trim() }.filter { it.isNotBlank() }197                                .ifEmpty { null },198                            totp = f.totp.ifBlank { null },199                            notes = f.notes.ifBlank { null },200                            cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },201                            cardholderName = f.cardholderName.ifBlank { null },202                            expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },203                            expYear = f.expiry.filter { it.isDigit() }.drop(2).take(2).ifBlank { null },204                            cvc = f.cvc.ifBlank { null },205                            cardNetwork = f.cardNetwork.takeIf { it != "unknown" },206                            tags = f.tags.ifEmpty { null },207                            createdAt = 0, modifiedAt = 0,208                        ),209                    )210                } else {211                    vault.updateEntry(212                        existing!!.copy(213                            type = f.type, title = f.title.trim(),214                            username = f.username.ifBlank { null },215                            email = f.email.ifBlank { null },216                            password = f.password.ifBlank { null },217                            url = f.url.ifBlank { null },218                            additionalUrls = f.additionalUrls219                                .map { it.trim() }.filter { it.isNotBlank() }220                                .ifEmpty { null },221                            totp = f.totp.ifBlank { null },222                            notes = f.notes.ifBlank { null },223                            cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },224                            cardholderName = f.cardholderName.ifBlank { null },225                            expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },226                            expYear = f.expiry.filter { it.isDigit() }.drop(2).take(2).ifBlank { null },227                            cvc = f.cvc.ifBlank { null },228                            cardNetwork = f.cardNetwork.takeIf { it != "unknown" },229                            tags = f.tags.ifEmpty { null },230                        ),231                    )232                }233            }.onSuccess { onDone() }234                .onFailure { e -> _form.update { it.copy(saving = false, error = e.message ?: "save failed") } }235        }236    }237}