Modern Apps git

← Modern-Apps.git

communicate: save-contact actions, vendor deep links, and publish reachability to contacts

Commit
95a868e053e95826d0793d188b28823cefc25b37
Author
vayun-mathur <[email protected]>
When
2026-08-23 01:45 UTC (3 months ago)
Parents
83a8dc3

Diff

communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex 0777338b7b..b225c7ddba 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -62,6 +62,38 @@             android:exported="true"             android:supportsPictureInPicture="true"             android:theme="@style/Theme.General">+            <!-- WhatsApp and Signal contact links, so "message this number" from a browser or another app+                 lands here. autoVerify claims them as App Links where the host allows it. -->+            <intent-filter android:autoVerify="true">+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />+                <data android:scheme="https" android:host="wa.me" />+                <data android:scheme="https" android:host="api.whatsapp.com" />+                <data android:scheme="https" android:host="chat.whatsapp.com" />+                <data android:scheme="https" android:host="signal.me" />+                <data android:scheme="https" android:host="signal.group" />+            </intent-filter>+            <!-- The vendors' own private schemes, which are not verifiable App Links. -->+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />+                <data android:scheme="whatsapp" />+                <data android:scheme="sgnl" />+            </intent-filter>+            <!-- Contact rows we write into the provider. The contacts app opens a platform row with+                 ACTION_VIEW on its content URI, so our own rows must resolve back to us. -->+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="vnd.android.cursor.item/vnd.com.whatsapp.profile" />+                <data android:mimeType="vnd.android.cursor.item/vnd.com.whatsapp.voip.call" />+                <data android:mimeType="vnd.android.cursor.item/vnd.com.whatsapp.video.call" />+                <data android:mimeType="vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.contact" />+                <data android:mimeType="vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.call" />+                <data android:mimeType="vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.video.call" />+            </intent-filter>             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />
communicate/src/main/java/com/vayunmathur/communicate/DeepLinks.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/DeepLinks.kt b/communicate/src/main/java/com/vayunmathur/communicate/DeepLinks.ktnew file mode 100644index 0000000000..76f1f01761--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/DeepLinks.kt@@ -0,0 +1,116 @@+package com.vayunmathur.communicate++import android.content.Intent+import android.net.Uri+import com.vayunmathur.communicate.data.CommunicateLine++/**+ * What an incoming intent asked us to open.+ *+ * The app previously declared `sms:`/`smsto:`/`tel:` filters and then ignored the intent entirely, so every+ * launch landed on the thread list. This turns an intent into a destination.+ */+sealed interface DeepLink {+    /** Open (or start) a conversation with [address] on [line]. */+    data class Conversation(val address: String, val line: CommunicateLine, val body: String? = null) : DeepLink++    /** A group invite we can't join yet, but shouldn't silently swallow either. */+    data class UnsupportedGroupInvite(val line: CommunicateLine) : DeepLink+}++/**+ * Parses share/deep-link intents into a [DeepLink].+ *+ * Vendor links are matched by host so the app can be a target for `wa.me` and `signal.me` links, which is+ * what makes "message this number on WhatsApp/Signal" from a browser or another app land here. The line is+ * taken from the link, since the same phone number can exist on several.+ */+object DeepLinks {+    fun parse(intent: Intent?): DeepLink? {+        val intent = intent ?: return null+        val data = intent.data ?: return null+        return when (intent.action) {+            Intent.ACTION_VIEW, Intent.ACTION_SENDTO, Intent.ACTION_DIAL, Intent.ACTION_CALL ->+                fromUri(data, intent.getStringExtra(Intent.EXTRA_TEXT))+            else -> null+        }+    }++    internal fun fromUri(uri: Uri, body: String? = null): DeepLink? = resolve(+        scheme = uri.scheme,+        host = uri.host,+        path = uri.path,+        fragment = uri.fragment,+        opaque = uri.schemeSpecificPart,+        query = { name -> runCatching { uri.getQueryParameter(name) }.getOrNull() },+        body = body,+    )++    /**+     * The parsing itself, over plain URI components.+     *+     * Split out from [Uri] so it is unit-testable: `android.net.Uri` is a stub on the JVM, and this is exactly+     * the logic worth testing since each vendor hides the number somewhere different.+     */+    internal fun resolve(+        scheme: String?,+        host: String?,+        path: String?,+        fragment: String?,+        opaque: String?,+        query: (String) -> String?,+        body: String? = null,+    ): DeepLink? {+        val scheme = scheme?.lowercase()+        val host = host?.lowercase()+        return when {+            // sms:/smsto:/mms: — the default-SMS-app entry point.+            scheme in SMS_SCHEMES || scheme == "tel" ->+                addressOf(opaque, path)?.let { DeepLink.Conversation(it, CommunicateLine.Sim, body) }++            // WhatsApp: wa.me/<number>, api.whatsapp.com/send?phone=, whatsapp://send?phone=+            host == "wa.me" || host == "api.whatsapp.com" || scheme == "whatsapp" ->+                whatsAppNumber(path, query)?.let {+                    DeepLink.Conversation(it, CommunicateLine.WhatsApp, query("text") ?: body)+                }+            host == "chat.whatsapp.com" -> DeepLink.UnsupportedGroupInvite(CommunicateLine.WhatsApp)++            // Signal: signal.me/#p/<e164>, sgnl://signal.me/#p/<e164>+            host == "signal.me" -> signalNumber(fragment)?.let {+                DeepLink.Conversation(it, CommunicateLine.Signal, body)+            }+            host == "signal.group" -> DeepLink.UnsupportedGroupInvite(CommunicateLine.Signal)+            else -> null+        }+    }++    /** `sms:+1555…?body=hi` keeps the number in the opaque part or the path depending on the sender. */+    private fun addressOf(opaque: String?, path: String?): String? {+        val raw = opaque ?: path+        return raw?.substringBefore('?')?.trim()?.takeIf { it.isNotEmpty() }+    }++    /** `wa.me/15551234567` puts it in the path; `api.whatsapp.com/send?phone=` in a query parameter. */+    private fun whatsAppNumber(path: String?, query: (String) -> String?): String? {+        query("phone")?.trim()?.takeIf { it.isNotEmpty() }?.let { return normalise(it) }+        val fromPath = path?.trim('/')?.takeIf { it.isNotEmpty() && it.any(Char::isDigit) }+        return fromPath?.let { normalise(it) }+    }++    /**+     * `https://signal.me/#p/+15551234567` — the number is in the fragment, not the path, so the path is empty+     * and the fragment has to be read directly.+     */+    private fun signalNumber(fragment: String?): String? {+        val value = fragment?.trim()?.removePrefix("p/")?.trim()+        return value?.takeIf { it.any(Char::isDigit) }?.let { normalise(it) }+    }++    /** Vendor links often omit the leading `+` even though the digits are international. */+    private fun normalise(raw: String): String {+        val digits = raw.filter { it.isDigit() || it == '+' }+        return if (digits.startsWith("+") || digits.isEmpty()) digits else "+$digits"+    }++    private val SMS_SCHEMES = setOf("sms", "smsto", "mms", "mmsto")+}
communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.ktindex 0245dcb401..bef6092fd0 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -2,6 +2,7 @@ package com.vayunmathur.communicate  import android.Manifest import android.app.PictureInPictureParams+import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle@@ -14,7 +15,9 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.res.stringResource import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.IconCall@@ -78,9 +81,13 @@ sealed interface Route : NavKey { }  class MainActivity : ComponentActivity() {+    /** The deep link the app was opened with, or the most recent one delivered to a running instance. */+    private var pendingDeepLink by mutableStateOf<DeepLink?>(null)+     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()+        pendingDeepLink = DeepLinks.parse(intent)          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&             checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED@@ -90,11 +97,21 @@ class MainActivity : ComponentActivity() {          setContent {             DynamicTheme {-                CommunicateApp()+                CommunicateApp(initialDeepLink = pendingDeepLink)             }         }     } +    /**+     * A deep link that arrived while the activity was already running. Held in state so the composition picks+     * it up, rather than being lost — the app declared `sms:`/`tel:` filters for a long time and ignored them.+     */+    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        setIntent(intent)+        pendingDeepLink = DeepLinks.parse(intent)+    }+     /**      * Shrink a video call into picture-in-picture when leaving the app, so the far end stays visible.      *@@ -120,7 +137,7 @@ class MainActivity : ComponentActivity() { }  @Composable-private fun CommunicateApp() {+private fun CommunicateApp(initialDeepLink: DeepLink? = null) {     val context = LocalContext.current     val session = remember { GoogleVoiceSession.get(context) }     val gvSignedIn by session.signedInFlow.collectAsState(initial = false)@@ -174,6 +191,25 @@ private fun CommunicateApp() {      val backStack = rememberNavBackStack<Route>(Route.Main) +    // Deep links open the conversation they name. Keyed on the link so a second link to a running instance+    // navigates again rather than being ignored.+    LaunchedEffect(initialDeepLink) {+        when (val link = initialDeepLink) {+            is DeepLink.Conversation -> backStack.add(+                Route.Conversation(+                    threadId = -1L,+                    address = link.address,+                    line = link.line,+                ),+            )+            is DeepLink.UnsupportedGroupInvite ->+                com.vayunmathur.library.util.AppMessages.show(+                    context.getString(R.string.deep_link_group_unsupported),+                )+            null -> Unit+        }+    }+     MainNavigation(backStack) {         entry<Route.Main> {             CommunicateTabs(backStack)
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.ktindex 12d399f3c8..52e8b502ac 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -422,6 +422,21 @@ object CommunicateRepository {         else -> MessageStatus.Sent // STATUS_PENDING / STATUS_NONE → single tick     } +    /**+     * Whether [number] is a real phone number that no contact claims.+     *+     * Distinct from `findContactName(...) == null`, which is also null when READ_CONTACTS is denied or the+     * address is not a number at all — offering "add to contacts" in those cases would be wrong.+     */+    fun isUnknownContact(context: Context, number: String): Boolean {+        if (number.isBlank()) return false+        // Service ids (ACI/PNI UUIDs, JIDs) are not dialable and cannot be saved as a phone number.+        if (!number.any { it.isDigit() }) return false+        if (number.contains('@') || number.count { it == '-' } >= 4) return false+        if (!context.hasPermission(Manifest.permission.READ_CONTACTS)) return false+        return findContactName(context, number) == null+    }+     fun findContactName(context: Context, number: String): String? {         if (!context.hasPermission(Manifest.permission.READ_CONTACTS) || number.isBlank()) return null         return runCatching {
communicate/src/main/java/com/vayunmathur/communicate/data/ContactPlatformRows.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/ContactPlatformRows.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/ContactPlatformRows.ktnew file mode 100644index 0000000000..fbc5e4a5ac--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/ContactPlatformRows.kt@@ -0,0 +1,179 @@+package com.vayunmathur.communicate.data++import android.accounts.Account+import android.accounts.AccountManager+import android.content.ContentProviderOperation+import android.content.ContentUris+import android.content.Context+import android.database.Cursor+import android.provider.ContactsContract+import android.util.Log++/**+ * Publishes "reachable on WhatsApp / reachable on Signal" into the system contacts provider.+ *+ * Deliberately uses the **vendors' own mimetypes** rather than app-specific ones. The contacts app matches+ * platform rows by mimetype substring (`%whatsapp%`, `%securesms%`) and opens them with `ACTION_VIEW` on the+ * row's content URI, so writing under these mimetypes makes our rows indistinguishable from the real apps'+ * to any reader — which is the point: the existing contacts UI gains the actions with no changes, and it+ * works the same way whether the vendor app is installed or we are standing in for it.+ *+ * Rows live under our own account so they never collide with, or get overwritten by, the real vendor's sync.+ */+object ContactPlatformRows {+    private const val TAG = "ContactPlatformRows"++    /** The contacts app's own authenticator type, so these rows sit alongside its data. */+    private const val ACCOUNT_TYPE = "com.vayunmathur.contacts"+    private const val ACCOUNT_NAME = "Contacts"++    /** Exactly the strings WhatsApp and Signal use, so existing readers match them unchanged. */+    const val MIME_WHATSAPP_MESSAGE = "vnd.android.cursor.item/vnd.com.whatsapp.profile"+    const val MIME_WHATSAPP_CALL = "vnd.android.cursor.item/vnd.com.whatsapp.voip.call"+    const val MIME_WHATSAPP_VIDEO = "vnd.android.cursor.item/vnd.com.whatsapp.video.call"+    const val MIME_SIGNAL_MESSAGE = "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.contact"+    const val MIME_SIGNAL_CALL = "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.call"+    const val MIME_SIGNAL_VIDEO = "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.video.call"++    private val WHATSAPP_MIMES = listOf(MIME_WHATSAPP_MESSAGE, MIME_WHATSAPP_CALL, MIME_WHATSAPP_VIDEO)+    private val SIGNAL_MIMES = listOf(MIME_SIGNAL_MESSAGE, MIME_SIGNAL_CALL, MIME_SIGNAL_VIDEO)++    /** One contact's reachability, as we know it. */+    data class Reachability(val e164: String, val whatsApp: Boolean, val signal: Boolean)++    /**+     * Publish [reachable] for the contacts they match, replacing whatever we published before.+     *+     * Idempotent: our previous rows are removed first, so a contact that has left a network loses the action+     * rather than keeping a stale one.+     */+    fun publish(context: Context, reachable: List<Reachability>) {+        if (context.checkSelfPermission(android.Manifest.permission.WRITE_CONTACTS) !=+            android.content.pm.PackageManager.PERMISSION_GRANTED+        ) {+            Log.i(TAG, "no WRITE_CONTACTS; not publishing platform rows")+            return+        }+        if (!ensureAccount(context)) return++        val ops = ArrayList<ContentProviderOperation>()+        // Clear ours first; the account filter keeps this from touching the real vendors' rows.+        ops.add(+            ContentProviderOperation.newDelete(syncUri(ContactsContract.Data.CONTENT_URI))+                .withSelection(+                    "${ContactsContract.Data.MIMETYPE} IN (${(WHATSAPP_MIMES + SIGNAL_MIMES).joinToString(",") { "?" }})",+                    (WHATSAPP_MIMES + SIGNAL_MIMES).toTypedArray(),+                )+                .build(),+        )++        var rows = 0+        for (entry in reachable) {+            if (!entry.whatsApp && !entry.signal) continue+            val rawContactId = ourRawContactFor(context, entry.e164) ?: continue+            if (entry.whatsApp) {+                WHATSAPP_MIMES.forEach { mime -> ops.add(insertRow(rawContactId, mime, entry.e164, "WhatsApp")) }+                rows += WHATSAPP_MIMES.size+            }+            if (entry.signal) {+                SIGNAL_MIMES.forEach { mime -> ops.add(insertRow(rawContactId, mime, entry.e164, "Signal")) }+                rows += SIGNAL_MIMES.size+            }+        }++        try {+            context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops)+            Log.i(TAG, "published $rows platform rows for ${reachable.size} contacts")+        } catch (t: Throwable) {+            Log.w(TAG, "could not publish platform rows", t)+        }+    }++    private fun insertRow(+        rawContactId: Long,+        mimeType: String,+        e164: String,+        label: String,+    ): ContentProviderOperation =+        ContentProviderOperation.newInsert(syncUri(ContactsContract.Data.CONTENT_URI))+            .withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)+            .withValue(ContactsContract.Data.MIMETYPE, mimeType)+            // DATA1 is the identifier the row acts on; DATA2/DATA3 are what a contacts UI shows.+            .withValue(ContactsContract.Data.DATA1, e164)+            .withValue(ContactsContract.Data.DATA2, label)+            .withValue(ContactsContract.Data.DATA3, e164)+            .build()++    /**+     * Our raw contact for [e164], created if absent and linked to the aggregate contact by the phone number.+     *+     * A separate raw contact under our account is how the provider is meant to be extended: the aggregator+     * joins it to the user's existing contact by number, so the rows appear on the right person without us+     * editing anybody else's data.+     */+    private fun ourRawContactFor(context: Context, e164: String): Long? {+        existingRawContact(context, e164)?.let { return it }+        return try {+            val values = android.content.ContentValues().apply {+                put(ContactsContract.RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE)+                put(ContactsContract.RawContacts.ACCOUNT_NAME, ACCOUNT_NAME)+                put(ContactsContract.RawContacts.SYNC1, e164)+            }+            val uri = context.contentResolver.insert(syncUri(ContactsContract.RawContacts.CONTENT_URI), values)+                ?: return null+            val id = ContentUris.parseId(uri)+            // A phone row is what lets the aggregator match this to the user's existing contact.+            context.contentResolver.insert(+                syncUri(ContactsContract.Data.CONTENT_URI),+                android.content.ContentValues().apply {+                    put(ContactsContract.Data.RAW_CONTACT_ID, id)+                    put(+                        ContactsContract.Data.MIMETYPE,+                        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,+                    )+                    put(ContactsContract.CommonDataKinds.Phone.NUMBER, e164)+                },+            )+            id+        } catch (t: Throwable) {+            Log.w(TAG, "could not create a raw contact for $e164", t)+            null+        }+    }++    private fun existingRawContact(context: Context, e164: String): Long? = try {+        context.contentResolver.query(+            ContactsContract.RawContacts.CONTENT_URI,+            arrayOf(ContactsContract.RawContacts._ID),+            "${ContactsContract.RawContacts.ACCOUNT_TYPE} = ? AND ${ContactsContract.RawContacts.SYNC1} = ?",+            arrayOf(ACCOUNT_TYPE, e164),+            null,+        )?.use { cursor: Cursor -> if (cursor.moveToFirst()) cursor.getLong(0) else null }+    } catch (t: Throwable) {+        Log.w(TAG, "could not look up our raw contact for $e164", t)+        null+    }++    /**+     * Marks writes as coming from the sync adapter that owns the account. Without this the provider treats a+     * delete as a tombstone rather than removing the row.+     */+    private fun syncUri(uri: android.net.Uri) = uri.buildUpon()+        .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true")+        .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE)+        .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, ACCOUNT_NAME)+        .build()++    /** The account must exist before the provider will accept rows attributed to it. */+    private fun ensureAccount(context: Context): Boolean = try {+        val manager = AccountManager.get(context)+        val account = Account(ACCOUNT_NAME, ACCOUNT_TYPE)+        val present = manager.getAccountsByType(ACCOUNT_TYPE).any { it.name == ACCOUNT_NAME }+        if (!present) manager.addAccountExplicitly(account, null, null)+        true+    } catch (t: Throwable) {+        // Adding an account of another app's type needs a matching signature; log rather than fail the sync.+        Log.i(TAG, "could not ensure the contacts account exists: ${t.message}")+        false+    }+}
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.ktindex 064ffecbef..68687034d1 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt@@ -8,6 +8,7 @@ import android.telephony.TelephonyManager import android.util.Base64 as AndroidBase64 import android.util.Log import com.google.i18n.phonenumbers.PhoneNumberUtil+import com.vayunmathur.communicate.data.ContactPlatformRows import com.vayunmathur.communicate.data.signal.transport.SignalCdsi import com.vayunmathur.communicate.data.signal.transport.SignalTrust import com.vayunmathur.library.network.NetworkClient@@ -164,6 +165,18 @@ object SignalContactSync {                 "new=${new.size} registered=$onSignal " +                 "withAci=${result.discovered.count { it.aci != null }}",         )+        // Publish reachability into the contacts provider, so the contacts app can offer "message on Signal"+        // for these numbers using the vendor's own mimetypes.+        try {+            ContactPlatformRows.publish(+                context,+                toUpsert.filter { it.onSignal }.map {+                    ContactPlatformRows.Reachability(e164 = it.phoneE164, whatsApp = false, signal = true)+                },+            )+        } catch (t: Throwable) {+            Log.w(TAG, "could not publish Signal reachability to contacts", t)+        }         return SyncResult(device.size, byE164.size, onSignal)     } }
communicate/src/main/java/com/vayunmathur/communicate/ui/ContactIntents.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ContactIntents.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ContactIntents.ktnew file mode 100644index 0000000000..fa3d485e4c--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ContactIntents.kt@@ -0,0 +1,43 @@+package com.vayunmathur.communicate.ui++import android.content.Context+import android.content.Intent+import android.provider.ContactsContract+import com.vayunmathur.library.ui.ExternalIntents++/**+ * Hand a phone number to the system contacts editor.+ *+ * Both use the platform's standard intents rather than talking to the provider directly, so whichever+ * contacts app the user prefers handles it and the usual account/duplicate handling applies.+ */+object ContactIntents {+    /** Open a new-contact editor pre-filled with [number]. */+    fun createNew(context: Context, number: String) {+        if (number.isBlank()) return+        ExternalIntents.launch(+            context,+            Intent(ContactsContract.Intents.Insert.ACTION).apply {+                type = ContactsContract.RawContacts.CONTENT_TYPE+                putExtra(ContactsContract.Intents.Insert.PHONE, number)+            },+        )+    }++    /**+     * Open the contact picker so [number] can be attached to a contact that already exists.+     *+     * `ACTION_INSERT_OR_EDIT` is the documented way to get the "add to existing contact" chooser; a plain+     * insert would always create a new entry.+     */+    fun addToExisting(context: Context, number: String) {+        if (number.isBlank()) return+        ExternalIntents.launch(+            context,+            Intent(Intent.ACTION_INSERT_OR_EDIT).apply {+                type = ContactsContract.Contacts.CONTENT_ITEM_TYPE+                putExtra(ContactsContract.Intents.Insert.PHONE, number)+            },+        )+    }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.ktindex 4ccaba993a..2ce0c56bdc 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -134,6 +134,10 @@ fun ConversationScreen(                 ?: address.ifBlank { context.getString(R.string.conversation_title) }         }     }+    // Offer "save this number" only for an address that is genuinely an unsaved phone number.+    val isUnknownContact by produceState(initialValue = false, address) {+        value = withContext(Dispatchers.IO) { CommunicateRepository.isUnknownContact(context, address) }+    }     // For groups, resolve a "Alice, Bob +N" subtitle from the participant addresses (contact names     // where available). Cheap: runs once off the main thread.     val groupSubtitle = produceState<String?>(initialValue = null, isGroup, participants) {@@ -327,6 +331,19 @@ fun ConversationScreen(                 }) { IconArchive() }             }             com.vayunmathur.library.ui.OverflowMenu(icon = { com.vayunmathur.library.ui.IconMoreVert() }) {+                // Only worth offering when the address is a bare number we could not resolve to a contact.+                if (!isGroup && isUnknownContact) {+                    Item(+                        text = stringResource(R.string.contact_create_new),+                        leadingIcon = { com.vayunmathur.library.ui.IconPersonAdd() },+                        onClick = { ContactIntents.createNew(context, address) },+                    )+                    Item(+                        text = stringResource(R.string.contact_add_to_existing),+                        leadingIcon = { com.vayunmathur.library.ui.IconPerson() },+                        onClick = { ContactIntents.addToExisting(context, address) },+                    )+                }                 Item(                     text = stringResource(com.vayunmathur.library.ui.R.string.delete),                     leadingIcon = { com.vayunmathur.library.ui.IconDelete() },
communicate/src/main/res/values/strings.xml
diff --git a/communicate/src/main/res/values/strings.xml b/communicate/src/main/res/values/strings.xmlindex 93fc6db79c..d5d3c62f71 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -118,6 +118,9 @@     <string name="call_state_incoming_generic">Incoming call</string>     <string name="call_video">Video</string>     <string name="call_flip_camera">Flip</string>+    <string name="contact_create_new">Create new contact</string>+    <string name="contact_add_to_existing">Add to existing contact</string>+    <string name="deep_link_group_unsupported">Group invite links are not supported yet</string>     <string name="account_whatsapp">WhatsApp</string>     <string name="inapp_ongoing_call">Ongoing call</string>     <string name="inapp_call_channel_name">Calls</string>
communicate/src/test/java/com/vayunmathur/communicate/DeepLinksTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/DeepLinksTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/DeepLinksTest.ktnew file mode 100644index 0000000000..6ba5e5940f--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/DeepLinksTest.kt@@ -0,0 +1,111 @@+package com.vayunmathur.communicate++import com.vayunmathur.communicate.data.CommunicateLine+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Vectors for the vendor link formats. Each vendor puts the number somewhere different — `wa.me` in the path,+ * `api.whatsapp.com` in a query parameter, and `signal.me` in the **fragment**, where a path-based parse finds+ * nothing at all.+ *+ * Drives the component-based parser directly, since `android.net.Uri` is a stub on the JVM.+ */+class DeepLinksTest {+    private fun link(+        scheme: String? = "https",+        host: String? = null,+        path: String? = null,+        fragment: String? = null,+        opaque: String? = null,+        params: Map<String, String> = emptyMap(),+    ) = DeepLinks.resolve(+        scheme = scheme,+        host = host,+        path = path,+        fragment = fragment,+        opaque = opaque,+        query = { params[it] },+    )++    @Test+    fun waMePutsTheNumberInThePath() {+        val result = link(host = "wa.me", path = "/15551234567") as DeepLink.Conversation+        assertEquals("+15551234567", result.address)+        assertEquals(CommunicateLine.WhatsApp, result.line)+    }++    @Test+    fun apiWhatsAppUsesAQueryParameterAndCarriesText() {+        val result = link(+            host = "api.whatsapp.com",+            path = "/send",+            params = mapOf("phone" to "15551234567", "text" to "hello"),+        ) as DeepLink.Conversation+        assertEquals("+15551234567", result.address)+        assertEquals("hello", result.body)+    }++    @Test+    fun whatsAppPrivateSchemeWorks() {+        val result = link(+            scheme = "whatsapp",+            path = "/send",+            params = mapOf("phone" to "15551234567"),+        ) as DeepLink.Conversation+        assertEquals("+15551234567", result.address)+        assertEquals(CommunicateLine.WhatsApp, result.line)+    }++    @Test+    fun signalMeUsesTheFragmentNotThePath() {+        val result = link(host = "signal.me", path = "/", fragment = "p/+15551234567") as DeepLink.Conversation+        assertEquals("+15551234567", result.address)+        assertEquals(CommunicateLine.Signal, result.line)+    }++    @Test+    fun smsSchemeMapsToTheSimLine() {+        val result = link(scheme = "smsto", opaque = "+15551234567") as DeepLink.Conversation+        assertEquals("+15551234567", result.address)+        assertEquals(CommunicateLine.Sim, result.line)+    }++    @Test+    fun smsWithBodyKeepsOnlyTheNumberInTheAddress() {+        val result = link(scheme = "sms", opaque = "+15551234567?body=hi") as DeepLink.Conversation+        assertEquals("+15551234567", result.address)+    }++    @Test+    fun telIsTreatedAsTheSimLine() {+        val result = link(scheme = "tel", opaque = "+15551234567") as DeepLink.Conversation+        assertEquals(CommunicateLine.Sim, result.line)+    }++    @Test+    fun groupInvitesAreReportedRatherThanSwallowed() {+        assertTrue(link(host = "chat.whatsapp.com", path = "/ABC123") is DeepLink.UnsupportedGroupInvite)+        assertTrue(link(host = "signal.group", fragment = "CjQK") is DeepLink.UnsupportedGroupInvite)+    }++    @Test+    fun unrelatedLinksAreIgnored() {+        assertNull(link(host = "example.com", path = "/15551234567"))+        assertNull(link(host = "wa.me", path = "/"))+    }++    @Test+    fun aNumberThatAlreadyHasAPlusIsNotDoubled() {+        val result = link(host = "wa.me", path = "/+15551234567") as DeepLink.Conversation+        assertEquals("+15551234567", result.address)+    }++    @Test+    fun formattingCharactersAreStripped() {+        val result = link(host = "wa.me", path = "/1 (555) 123-4567") as DeepLink.Conversation+        assertEquals("+15551234567", result.address)+    }+}
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 8e93ef5718..eca8f07646 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -4,6 +4,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AcUnit import androidx.compose.material.icons.filled.CallEnd import androidx.compose.material.icons.filled.Dialpad+import androidx.compose.material.icons.filled.PersonAdd import androidx.compose.material.icons.filled.HealthAndSafety import androidx.compose.material.icons.filled.Medication import androidx.compose.material.icons.filled.MonitorHeart@@ -657,6 +658,10 @@ fun IconHourglass(modifier: Modifier = Modifier, tint: Color = LocalContentColor fun IconPerson(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =     AppIcon(Icons.Filled.Person, "Person", modifier, tint) +@Composable+fun IconPersonAdd(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+    AppIcon(Icons.Filled.PersonAdd, "Add contact", modifier, tint)+ @Composable fun IconGroup(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =     AppIcon(Icons.Filled.Group, "Group", modifier, tint)