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 = "", 34 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 val usernameSuggestions: StateFlow<List<String>> =92 MutableStateFlow(identitySuggestionsFor(vault.getActiveEntries(), IdentityField.Username)).asStateFlow()9394 val emailSuggestions: StateFlow<List<String>> =95 MutableStateFlow(identitySuggestionsFor(vault.getActiveEntries(), IdentityField.Email)).asStateFlow()9697 fun setType(t: String) = _form.update { it.copy(type = t) }9899 100101102103104 fun createNoteAndOpen(onOpen: (String) -> Unit) {105 viewModelScope.launch {106 runCatching {107 vault.addEntry(VaultEntry(id = "", type = "note", title = "", createdAt = 0, modifiedAt = 0))108 }.onSuccess { onOpen(it.id) }109 .onFailure { e -> _form.update { it.copy(error = e.message ?: "could not create note") } }110 }111 }112 fun setTitle(v: String) = _form.update { it.copy(title = v, error = null) }113 fun setUsername(v: String) = _form.update { it.copy(username = v) }114 fun setEmail(v: String) = _form.update { it.copy(email = v) }115 fun setPassword(v: String) = _form.update { it.copy(password = v) }116 fun setUrl(v: String) = _form.update { it.copy(url = v) }117 fun setAdditionalUrl(index: Int, v: String) = _form.update { form ->118 form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it[index] = v })119 }120 fun addAdditionalUrl() = _form.update { form ->121 if (form.additionalUrls.size >= MAX_ADDITIONAL_URLS) form122 else form.copy(additionalUrls = form.additionalUrls + "")123 }124 fun removeAdditionalUrl(index: Int) = _form.update { form ->125 form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it.removeAt(index) })126 }127 fun setTotp(v: String) = _form.update { it.copy(totp = v) }128 fun setNotes(v: String) = _form.update { it.copy(notes = v) }129 fun revealTotp() = _form.update { it.copy(showTotp = true) }130 fun revealNotes() = _form.update { it.copy(showNotes = true) }131 fun setCardNumber(v: String) = _form.update {132 val formatted = CardFieldUtils.formatPan(v)133 it.copy(cardNumber = formatted, cardNetwork = CardFieldUtils.detectNetwork(formatted), error = null)134 }135 fun setCardholderName(v: String) = _form.update { it.copy(cardholderName = v, error = null) }136 fun setExpiry(v: String) = _form.update { it.copy(expiry = CardFieldUtils.formatExpiry(v), error = null) }137 fun setCvc(v: String) = _form.update {138 it.copy(cvc = v.filter { c -> c.isDigit() }.take(CardFieldUtils.cvcMaxDigits(it.cardNetwork)))139 }140 fun toggleShowCvc() = _form.update { it.copy(showCvc = !it.showCvc) }141142 val allTags: List<String> = vault.getDistinctTags()143 fun addTag(raw: String) = _form.update { f ->144 val tag = raw.trim().lowercase().take(32)145 if (tag.isEmpty() || f.tags.size >= 10 || f.tags.any { it == tag }) f146 else f.copy(tags = f.tags + tag)147 }148 fun removeTag(tag: String) = _form.update { it.copy(tags = it.tags - tag) }149150 fun toggleShowPassword() = _form.update { it.copy(showPassword = !it.showPassword) }151 fun toggleGenerator() = _form.update { it.copy(generatorOpen = !it.generatorOpen, showHistory = false) }152 fun toggleHistory() = _form.update { it.copy(showHistory = !it.showHistory, generatorOpen = false) }153154 155 fun restorePassword(pw: String) =156 _form.update { it.copy(password = pw, showPassword = true, showHistory = false) }157158 159 fun copyGenerated() {160 val pw = _form.value.password161 if (pw.isEmpty()) return162 PeachClipboard.copy(appContext, "peach", pw)163 viewModelScope.launch {164 _form.update { it.copy(genCopied = true) }165 kotlinx.coroutines.delay(1200)166 _form.update { it.copy(genCopied = false) }167 }168 }169170 fun copyHistoryPassword(pw: String) {171 PeachClipboard.copy(appContext, "peach", pw)172 }173 fun setGenLength(n: Int) = _form.update { it.copy(genLength = n) }174 fun setGenUpper(b: Boolean) = _form.update { it.copy(genUpper = b) }175 fun setGenLower(b: Boolean) = _form.update { it.copy(genLower = b) }176 fun setGenNumbers(b: Boolean) = _form.update { it.copy(genNumbers = b) }177 fun setGenSymbols(b: Boolean) = _form.update { it.copy(genSymbols = b) }178179 fun generate() {180 val f = _form.value181 val pw = PasswordGenerator.generate(182 PasswordGenerator.Options(183 length = f.genLength,184 includeUppercase = f.genUpper,185 includeLowercase = f.genLower,186 includeNumbers = f.genNumbers,187 includeSymbols = f.genSymbols,188 ),189 )190 _form.update { it.copy(password = pw, showPassword = true) }191 }192193 fun save(onDone: () -> Unit) {194 val f = _form.value195 if (f.saving) return196 if (f.title.isBlank()) {197 _form.update { it.copy(error = "title is required") }198 return199 }200 if (f.type == "card" && (f.cardNumber.isBlank() || f.cardholderName.isBlank())) {201 _form.update { it.copy(error = "Cardholder name and card number are required") }202 return203 }204 _form.update { it.copy(saving = true, error = null) }205 viewModelScope.launch {206 runCatching {207 if (isNew) {208 vault.addEntry(209 VaultEntry(210 id = "", type = f.type, title = f.title.trim(),211 username = f.username.ifBlank { null },212 email = f.email.ifBlank { null },213 password = f.password.ifBlank { null },214 url = f.url.ifBlank { null },215 additionalUrls = f.additionalUrls216 .map { it.trim() }.filter { it.isNotBlank() }217 .ifEmpty { null },218 totp = f.totp.ifBlank { null },219 notes = f.notes.ifBlank { null },220 cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },221 cardholderName = f.cardholderName.ifBlank { null },222 expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },223 expYear = f.expiry.filter { it.isDigit() }.drop(2).take(2).ifBlank { null },224 cvc = f.cvc.ifBlank { null },225 cardNetwork = f.cardNetwork.takeIf { it != "unknown" },226 tags = f.tags.ifEmpty { null },227 createdAt = 0, modifiedAt = 0,228 ),229 )230 } else {231 vault.updateEntry(232 existing!!.copy(233 type = f.type, title = f.title.trim(),234 username = f.username.ifBlank { null },235 email = f.email.ifBlank { null },236 password = f.password.ifBlank { null },237 url = f.url.ifBlank { null },238 additionalUrls = f.additionalUrls239 .map { it.trim() }.filter { it.isNotBlank() }240 .ifEmpty { null },241 totp = f.totp.ifBlank { null },242 notes = f.notes.ifBlank { null },243 cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },244 cardholderName = f.cardholderName.ifBlank { null },245 expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },246 expYear = f.expiry.filter { it.isDigit() }.drop(2).take(2).ifBlank { null },247 cvc = f.cvc.ifBlank { null },248 cardNetwork = f.cardNetwork.takeIf { it != "unknown" },249 tags = f.tags.ifEmpty { null },250 ),251 )252 }253 }.onSuccess { onDone() }254 .onFailure { e -> _form.update { it.copy(saving = false, error = e.message ?: "save failed") } }255 }256 }257}258259internal enum class IdentityField { Username, Email }260261internal fun identitySuggestionsFor(entries: List<VaultEntry>, field: IdentityField): List<String> {262 val buckets = linkedMapOf<String, Pair<String, Int>>()263264 fun add(value: String) {265 val trimmed = value.trim()266 if (trimmed.isEmpty()) return267 val key = trimmed.lowercase()268 val current = buckets[key]269 buckets[key] = (current?.first ?: trimmed) to ((current?.second ?: 0) + 1)270 }271272 entries.filter { it.deletedAt == null }.forEach { entry ->273 val username = entry.username?.trim().orEmpty()274 val email = entry.email?.trim().orEmpty()275 when (field) {276 IdentityField.Username -> if (username.isNotEmpty() && !username.contains("@")) add(username)277 IdentityField.Email -> {278 if (username.contains("@")) add(username)279 if (email.isNotEmpty()) add(email)280 }281 }282 }283284 return buckets.values285 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })286 .map { it.first }287 .take(8)288}