1package com.peachpasswords.autofill23import android.annotation.SuppressLint4import android.content.Context5import android.os.Build6import android.service.autofill.Dataset7import android.service.autofill.InlinePresentation8import android.view.autofill.AutofillId9import android.view.autofill.AutofillValue10import android.widget.RemoteViews11import androidx.annotation.RequiresApi12import androidx.autofill.inline.v1.InlineSuggestionUi13import androidx.autofill.inline.UiVersions14import com.peachpasswords.R15import com.peachpasswords.shared.extractDomain16import com.peachpasswords.vault.PasswordGenerator17import com.peachpasswords.vault.TOTPGenerator18import com.peachpasswords.vault.VaultEntry19import com.peachpasswords.vault.isCard20212223242526object AutofillResponseBuilder {2728 29303132 data class MatchResult(val hits: List<VaultEntry>, val rest: List<VaultEntry>) {33 val all: List<VaultEntry> get() = hits + rest34 }3536 fun matchEntries(entries: List<VaultEntry>, origin: String?): MatchResult {37 val originDomain = origin?.let(::extractDomain)38 ?: return MatchResult(emptyList(), emptyList())39 return matchDomains(entries, setOf(originDomain))40 }4142 4344454647 fun matchEntries(entries: List<VaultEntry>, parsed: ParsedStructure): MatchResult {48 val domains = parsed.originDomains.mapNotNull(::extractDomain).toSet()49 val byDomain = matchDomains(entries, domains).hits50 val appTitle = parsed.appTitle?.trim()51 val byTitle = if (appTitle.isNullOrBlank()) {52 emptyList()53 } else {54 entries.filter { it.title.trim().equals(appTitle, ignoreCase = true) }55 }56 return MatchResult((byDomain + byTitle).distinctBy { it.id }, emptyList())57 }5859 private fun matchDomains(entries: List<VaultEntry>, domains: Set<String>): MatchResult =60 MatchResult(61 hits = entries.filter { entry ->62 domains.any { domain -> entry.matchesOriginDomain(domain) }63 },64 rest = emptyList(),65 )6667 68 internal fun otpDigitsFor(boxCount: Int, code: String): List<String> =69 code.filter { !it.isWhitespace() }.take(boxCount).map { it.toString() }7071 private fun VaultEntry.matchesOriginDomain(originDomain: String): Boolean =72 sequenceOf(url)73 .plus(additionalUrls.orEmpty().asSequence())74 .filterNotNull()75 .mapNotNull(::extractDomain)76 .any { it == originDomain }7778 79 data class PreviewLabels(val title: String, val subtitle: String)8081 8283848586 fun previewLabels(privatePreview: Boolean, entry: VaultEntry, originDomain: String?): PreviewLabels =87 if (privatePreview) {88 PreviewLabels("Peach", originDomain ?: "")89 } else {90 PreviewLabels(entry.title, entry.username ?: entry.email ?: entry.url?.let(::extractDomain) ?: "")91 }9293 fun rowFor(context: Context, labels: PreviewLabels): RemoteViews =94 RemoteViews(context.packageName, R.layout.autofill_row).apply {95 setTextViewText(R.id.autofill_row_title, labels.title)96 setTextViewText(R.id.autofill_row_subtitle, labels.subtitle)97 }9899 fun simpleRow(context: Context, title: String, subtitle: String): RemoteViews =100 RemoteViews(context.packageName, R.layout.autofill_row).apply {101 setTextViewText(R.id.autofill_row_title, title)102 setTextViewText(R.id.autofill_row_subtitle, subtitle)103 }104105 106107108109 fun datasetFor(110 context: Context,111 parsed: ParsedStructure,112 entry: VaultEntry,113 inlineSpec: android.widget.inline.InlinePresentationSpec?,114 privatePreview: Boolean,115 ): Dataset? {116 val labels = previewLabels(privatePreview, entry, parsed.origin?.let(::extractDomain))117 val menu = rowFor(context, labels)118 val inline = if (Build.VERSION.SDK_INT >= 30 && inlineSpec != null) {119 buildInline(context, labels, inlineSpec)120 } else {121 null122 }123124 val builder = Dataset.Builder()125 var filledAny = false126 fun put(id: AutofillId?, value: String?) {127 if (id == null || value.isNullOrEmpty()) return128 val av = AutofillValue.forText(value)129 if (inline != null && Build.VERSION.SDK_INT >= 30) {130 builder.setValue(id, av, menu, inline)131 } else {132 builder.setValue(id, av, menu)133 }134 filledAny = true135 }136 put(parsed.identityId, entry.username ?: entry.email)137 put(parsed.passwordId, entry.password)138 val otpCode = entry.totp?.let { TOTPGenerator.generateCode(it) }139 put(parsed.otpId, otpCode)140 141 142 if (parsed.otpId == null && otpCode != null && parsed.otpDigitBoxIds.isNotEmpty()) {143 otpDigitsFor(parsed.otpDigitBoxIds.size, otpCode).forEachIndexed { index, digit ->144 builder.setValue(parsed.otpDigitBoxIds[index], AutofillValue.forText(digit), menu)145 }146 filledAny = true147 }148149 return if (filledAny) builder.build() else null150 }151152 153154155156 fun cardDatasetFor(157 context: Context,158 parsed: ParsedStructure,159 entry: VaultEntry,160 inlineSpec: android.widget.inline.InlinePresentationSpec?,161 privatePreview: Boolean,162 ): Dataset? {163 if (!entry.isCard()) return null164 val labels = previewLabels(privatePreview, entry, parsed.origin?.let(::extractDomain))165 val menu = rowFor(context, labels)166 val inline = if (Build.VERSION.SDK_INT >= 30 && inlineSpec != null) {167 buildInline(context, labels, inlineSpec)168 } else {169 null170 }171172 val builder = Dataset.Builder()173 var filledAny = false174 fun put(id: AutofillId?, value: String?) {175 if (id == null || value.isNullOrEmpty()) return176 val av = AutofillValue.forText(value)177 if (inline != null && Build.VERSION.SDK_INT >= 30) {178 builder.setValue(id, av, menu, inline)179 } else {180 builder.setValue(id, av, menu)181 }182 filledAny = true183 }184185 val digits = entry.cardNumber?.filter { it.isDigit() }186 put(parsed.cardNumberId, digits)187 put(parsed.cardExpMonthId, entry.expMonth)188 put(parsed.cardExpYearId, entry.expYear)189 if (parsed.cardExpDateId != null && !entry.expMonth.isNullOrEmpty() && !entry.expYear.isNullOrEmpty()) {190 val yy = entry.expYear.takeLast(2)191 put(parsed.cardExpDateId, "${entry.expMonth.padStart(2, '0')}/$yy")192 }193 put(parsed.cardCvcId, entry.cvc)194 put(parsed.cardNameId, entry.cardholderName)195196 return if (filledAny) builder.build() else null197 }198199 200201202203204205206207 fun generateDatasetFor(context: Context, parsed: ParsedStructure): Dataset? {208 val passwordId = parsed.passwordId ?: return null209 val policy = parsed.passwordPolicy210 val length = policy?.generationLength() ?: PasswordPolicy.DEFAULT_LENGTH211 val password = PasswordGenerator.generate(PasswordGenerator.Options(length = length))212 val note = policy?.constraintNote(length).orEmpty()213 val menu = simpleRow(context, "Generate strong password", note.ifEmpty { "Peach" })214 return Dataset.Builder()215 .setValue(passwordId, AutofillValue.forText(password), menu)216 .build()217 }218219 220221222223224 fun identityDatasetFor(225 context: Context,226 parsed: ParsedStructure,227 identity: SavedIdentity,228 ): Dataset? {229 val targetId = when (identity.type) {230 IdentityType.EMAIL -> parsed.emailId ?: parsed.usernameId231 IdentityType.USERNAME -> parsed.usernameId ?: parsed.emailId232 } ?: return null233 val subtitle = if (identity.type == IdentityType.EMAIL) "email" else "username"234 val menu = simpleRow(context, identity.value, subtitle)235 return Dataset.Builder()236 .setValue(targetId, AutofillValue.forText(identity.value), menu)237 .build()238 }239240 241 242 @SuppressLint("RestrictedApi")243 @RequiresApi(30)244 private fun buildInline(245 context: Context,246 labels: PreviewLabels,247 spec: android.widget.inline.InlinePresentationSpec,248 ): InlinePresentation? = try {249 val style = spec.style250 if (!UiVersions.getVersions(style).contains(UiVersions.INLINE_UI_VERSION_1)) {251 null252 } else {253 val pending = AutofillIntents.noopChipIntent(context)254 val slice = InlineSuggestionUi.newContentBuilder(pending)255 .setTitle(labels.title)256 .apply { if (labels.subtitle.isNotBlank()) setSubtitle(labels.subtitle) }257 .setStartIcon(android.graphics.drawable.Icon.createWithResource(context, R.drawable.ic_peach_mark))258 .build()259 .slice260 InlinePresentation(slice, spec, false)261 }262 } catch (_: Throwable) {263 264 null265 }266}