AutofillResponseBuilder.kt

5.1 KB · raw

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.TOTPGenerator17import com.peachpasswords.vault.VaultEntry1819/**20 * Turns parsed form fields + vault entries into autofill [Dataset]s — the menu21 * RemoteViews row, the inline keyboard chip, and the actual field values.22 * TOTP is filled as a freshly-generated code; the seed never leaves the vault.23 */24object AutofillResponseBuilder {2526    /** Entries whose domain/title plausibly match the form origin, best first. */27    fun matchEntries(entries: List<VaultEntry>, origin: String?): List<VaultEntry> {28        if (origin.isNullOrBlank()) return entries29        val core = coreLabel(origin)30        val (hits, rest) = entries.partition { entry ->31            val hay = listOfNotNull(extractDomain(entry.url ?: ""), entry.url, entry.title)32                .joinToString(" ").lowercase()33            core.isNotBlank() && (hay.contains(core) || hay.contains(origin.lowercase()))34        }35        return hits + rest36    }3738    /** The registrable-ish core token of an origin: "login.github.com" → "github". */39    private fun coreLabel(origin: String): String {40        val host = origin.substringAfter("://").substringBefore('/').lowercase()41        val parts = host.removePrefix("www.").split('.')42        return when {43            parts.size >= 2 -> parts[parts.size - 2]44            parts.isNotEmpty() -> parts[0]45            else -> host46        }47    }4849    fun menuRow(context: Context, entry: VaultEntry): RemoteViews {50        val subtitle = entry.username ?: entry.email ?: entry.url?.let(::extractDomain) ?: ""51        return RemoteViews(context.packageName, R.layout.autofill_row).apply {52            setTextViewText(R.id.autofill_row_title, entry.title)53            setTextViewText(R.id.autofill_row_subtitle, subtitle)54        }55    }5657    fun simpleRow(context: Context, title: String, subtitle: String): RemoteViews =58        RemoteViews(context.packageName, R.layout.autofill_row).apply {59            setTextViewText(R.id.autofill_row_title, title)60            setTextViewText(R.id.autofill_row_subtitle, subtitle)61        }6263    /**64     * Build a dataset filling the parsed fields from [entry]. Attaches the inline65     * chip when the IME offered a spec (API 30+); otherwise menu-only.66     */67    fun datasetFor(68        context: Context,69        parsed: ParsedStructure,70        entry: VaultEntry,71        inlineSpec: android.widget.inline.InlinePresentationSpec?,72    ): Dataset? {73        val menu = menuRow(context, entry)74        val inline = if (Build.VERSION.SDK_INT >= 30 && inlineSpec != null) {75            buildInline(context, entry, inlineSpec)76        } else {77            null78        }7980        val builder = Dataset.Builder()81        var filledAny = false82        fun put(id: AutofillId?, value: String?) {83            if (id == null || value.isNullOrEmpty()) return84            val av = AutofillValue.forText(value)85            if (inline != null && Build.VERSION.SDK_INT >= 30) {86                builder.setValue(id, av, menu, inline)87            } else {88                builder.setValue(id, av, menu)89            }90            filledAny = true91        }92        put(parsed.identityId, entry.username ?: entry.email)93        put(parsed.passwordId, entry.password)94        put(parsed.otpId, entry.totp?.let { TOTPGenerator.generateCode(it) })9596        return if (filledAny) builder.build() else null97    }9899    // InlineSuggestionUi.Content.getSlice is @RestrictedApi to androidx, but100    // reading the slice to build an InlinePresentation is the documented usage.101    @SuppressLint("RestrictedApi")102    @RequiresApi(30)103    private fun buildInline(104        context: Context,105        entry: VaultEntry,106        spec: android.widget.inline.InlinePresentationSpec,107    ): InlinePresentation? = try {108        val style = spec.style109        if (!UiVersions.getVersions(style).contains(UiVersions.INLINE_UI_VERSION_1)) {110            null111        } else {112            val subtitle = entry.username ?: entry.email ?: entry.url?.let(::extractDomain) ?: ""113            val pending = AutofillIntents.noopChipIntent(context)114            val slice = InlineSuggestionUi.newContentBuilder(pending)115                .setTitle(entry.title)116                .apply { if (subtitle.isNotBlank()) setSubtitle(subtitle) }117                .setStartIcon(android.graphics.drawable.Icon.createWithResource(context, R.drawable.ic_peach_mark))118                .build()119                .slice120            InlinePresentation(slice, spec, false)121        }122    } catch (_: Throwable) {123        // A non-conforming IME spec must never crash the fill — degrade to menu.124        null125    }126}