PeachAutofillService.kt

4.4 KB · raw

1package com.peachpasswords.autofill23import android.os.Build4import android.os.CancellationSignal5import android.service.autofill.AutofillService6import android.service.autofill.FillCallback7import android.service.autofill.FillRequest8import android.service.autofill.FillResponse9import android.service.autofill.SaveCallback10import android.service.autofill.SaveRequest11import com.peachpasswords.vault.VaultRepository12import dagger.hilt.android.AndroidEntryPoint13import javax.inject.Inject1415/**16 * System autofill provider. Parses the focused form, then either offers17 * matching vault entries (inline chip + drop-down rows) or a single branded18 * "Search Peach…" entry that opens [AutofillEntryPickerActivity].19 *20 * The vault is a process singleton, so when the app has the vault unlocked the21 * service fills directly; when locked it offers only the picker, which routes22 * the user to unlock. The save flow is intentionally a no-op for now — Peach23 * adds entries through its own UI, not the system Save dialog.24 */25@AndroidEntryPoint26class PeachAutofillService : AutofillService() {2728    @Inject lateinit var vault: VaultRepository2930    override fun onFillRequest(31        request: FillRequest,32        cancellationSignal: CancellationSignal,33        callback: FillCallback,34    ) {35        val context = applicationContext36        val structure = latestStructure(request) ?: run { callback.onSuccess(null); return }37        val parsed = AssistStructureParser.parse(structure)38        if (!parsed.hasUsableField) { callback.onSuccess(null); return }3940        val inlineSpecs = inlineSpecs(request)41        val response = FillResponse.Builder()42        var datasetCount = 04344        if (vault.isUnlocked.value) {45            val matches = AutofillResponseBuilder46                .matchEntries(vault.getEntries(), parsed.origin)47                .take(MAX_DATASETS)48            matches.forEachIndexed { index, entry ->49                val spec = inlineSpecs.getOrNull(index)50                AutofillResponseBuilder.datasetFor(context, parsed, entry, spec)?.let {51                    response.addDataset(it)52                    datasetCount++53                }54            }55        }5657        // Always offer the branded picker as the last row (search / unlock).58        runCatching {59            response.addDataset(pickerDataset(context, parsed, inlineSpecs.getOrNull(datasetCount)))60            datasetCount++61        }6263        if (datasetCount == 0) {64            callback.onSuccess(null)65        } else {66            ignoreUnfilledIds(response, parsed)67            callback.onSuccess(response.build())68        }69    }7071    private fun pickerDataset(72        context: android.content.Context,73        parsed: ParsedStructure,74        inlineSpec: android.widget.inline.InlinePresentationSpec?,75    ): android.service.autofill.Dataset {76        val label = if (vault.isUnlocked.value) "Search Peach…" else "Unlock Peach"77        val menu = AutofillResponseBuilder.simpleRow(context, label, parsed.origin ?: "")78        val builder = android.service.autofill.Dataset.Builder(menu)79        // A placeholder value per field keeps the dataset valid; the real values80        // are supplied by the picker via EXTRA_AUTHENTICATION_RESULT.81        listOfNotNull(parsed.identityId, parsed.passwordId, parsed.otpId).forEach { id ->82            builder.setValue(id, null, menu)83        }84        builder.setAuthentication(AutofillIntents.pickerIntentSender(context, parsed))85        return builder.build()86    }8788    /** Mark detected ids the framework should track even when we filled nothing. */89    private fun ignoreUnfilledIds(builder: FillResponse.Builder, parsed: ParsedStructure) {90        val ids = listOfNotNull(parsed.identityId, parsed.passwordId, parsed.otpId)91        if (ids.isNotEmpty()) builder.setIgnoredIds(*ids.toTypedArray())92    }9394    private fun latestStructure(request: FillRequest): android.app.assist.AssistStructure? =95        request.fillContexts.lastOrNull()?.structure9697    private fun inlineSpecs(request: FillRequest): List<android.widget.inline.InlinePresentationSpec> {98        if (Build.VERSION.SDK_INT < 30) return emptyList()99        return request.inlineSuggestionsRequest?.inlinePresentationSpecs ?: emptyList()100    }101102    override fun onSaveRequest(request: SaveRequest, callback: SaveCallback) {103        // Peach captures new logins through its own add-entry flow.104        callback.onSuccess()105    }106107    private companion object {108        const val MAX_DATASETS = 6109    }110}