Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / ContactPlatformRows.kt
ContactPlatformRows.kt181 lines · 8.7 KiBRaw
| 1 | package com.vayunmathur.communicate.data |
| 2 | |
| 3 | import android.accounts.Account |
| 4 | import android.accounts.AccountManager |
| 5 | import android.content.ContentProviderOperation |
| 6 | import android.content.ContentUris |
| 7 | import android.content.Context |
| 8 | import android.database.Cursor |
| 9 | import android.provider.ContactsContract |
| 10 | import com.vayunmathur.library.log.Log |
| 11 | |
| 12 | /** |
| 13 | * Publishes "reachable on WhatsApp / reachable on Signal" into the system contacts provider. |
| 14 | * |
| 15 | * Deliberately uses the **vendors' own mimetypes** rather than app-specific ones. The contacts app matches |
| 16 | * platform rows by mimetype substring (`%whatsapp%`, `%securesms%`) and opens them with `ACTION_VIEW` on the |
| 17 | * row's content URI, so writing under these mimetypes makes our rows indistinguishable from the real apps' |
| 18 | * to any reader — which is the point: the existing contacts UI gains the actions with no changes, and it |
| 19 | * works the same way whether the vendor app is installed or we are standing in for it. |
| 20 | * |
| 21 | * Rows live under our own account so they never collide with, or get overwritten by, the real vendor's sync. |
| 22 | */ |
| 23 | object ContactPlatformRows { |
| 24 | private const val TAG = "ContactPlatformRows" |
| 25 | |
| 26 | /** The contacts app's own authenticator type, so these rows sit alongside its data. */ |
| 27 | private const val ACCOUNT_TYPE = "com.vayunmathur.contacts" |
| 28 | private const val ACCOUNT_NAME = "Contacts" |
| 29 | |
| 30 | /** Exactly the strings WhatsApp and Signal use, so existing readers match them unchanged. */ |
| 31 | const val MIME_WHATSAPP_MESSAGE = "vnd.android.cursor.item/vnd.com.whatsapp.profile" |
| 32 | const val MIME_WHATSAPP_CALL = "vnd.android.cursor.item/vnd.com.whatsapp.voip.call" |
| 33 | const val MIME_WHATSAPP_VIDEO = "vnd.android.cursor.item/vnd.com.whatsapp.video.call" |
| 34 | const val MIME_SIGNAL_MESSAGE = "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.contact" |
| 35 | const val MIME_SIGNAL_CALL = "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.call" |
| 36 | const val MIME_SIGNAL_VIDEO = "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.video.call" |
| 37 | |
| 38 | private val WHATSAPP_MIMES = listOf(MIME_WHATSAPP_MESSAGE, MIME_WHATSAPP_CALL, MIME_WHATSAPP_VIDEO) |
| 39 | private val SIGNAL_MIMES = listOf(MIME_SIGNAL_MESSAGE, MIME_SIGNAL_CALL, MIME_SIGNAL_VIDEO) |
| 40 | |
| 41 | /** One contact's reachability, as we know it. */ |
| 42 | data class Reachability(val e164: String, val whatsApp: Boolean, val signal: Boolean) |
| 43 | |
| 44 | /** |
| 45 | * Publish [reachable] for the contacts they match, replacing whatever we published before. |
| 46 | * |
| 47 | * Idempotent: our previous rows are removed first, so a contact that has left a network loses the action |
| 48 | * rather than keeping a stale one. |
| 49 | */ |
| 50 | fun publish(context: Context, reachable: List<Reachability>) { |
| 51 | if (context.checkSelfPermission(android.Manifest.permission.WRITE_CONTACTS) != |
| 52 | android.content.pm.PackageManager.PERMISSION_GRANTED |
| 53 | ) { |
| 54 | Log.status(TAG, "no WRITE_CONTACTS; not publishing platform rows") |
| 55 | return |
| 56 | } |
| 57 | if (!ensureAccount(context)) return |
| 58 | |
| 59 | val ops = ArrayList<ContentProviderOperation>() |
| 60 | // Clear ours first; the account filter keeps this from touching the real vendors' rows. |
| 61 | ops.add( |
| 62 | ContentProviderOperation.newDelete(syncUri(ContactsContract.Data.CONTENT_URI)) |
| 63 | .withSelection( |
| 64 | "${ContactsContract.Data.MIMETYPE} IN" + |
| 65 | "(${(WHATSAPP_MIMES + SIGNAL_MIMES).joinToString(",") { "?" }})", |
| 66 | (WHATSAPP_MIMES + SIGNAL_MIMES).toTypedArray(), |
| 67 | ) |
| 68 | .build(), |
| 69 | ) |
| 70 | |
| 71 | var rows = 0 |
| 72 | for (entry in reachable) { |
| 73 | if (!entry.whatsApp && !entry.signal) continue |
| 74 | ourRawContactFor(context, entry.e164)?.let { rawContactId -> |
| 75 | if (entry.whatsApp) { |
| 76 | WHATSAPP_MIMES.forEach { mime -> ops.add(insertRow(rawContactId, mime, entry.e164, "WhatsApp")) } |
| 77 | rows += WHATSAPP_MIMES.size |
| 78 | } |
| 79 | if (entry.signal) { |
| 80 | SIGNAL_MIMES.forEach { mime -> ops.add(insertRow(rawContactId, mime, entry.e164, "Signal")) } |
| 81 | rows += SIGNAL_MIMES.size |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | try { |
| 87 | context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops) |
| 88 | Log.status(TAG, "published $rows platform rows for ${reachable.size} contacts") |
| 89 | } catch (expected: Throwable) { |
| 90 | Log.status(TAG, "could not publish platform rows", expected) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | private fun insertRow( |
| 95 | rawContactId: Long, |
| 96 | mimeType: String, |
| 97 | e164: String, |
| 98 | label: String, |
| 99 | ): ContentProviderOperation = |
| 100 | ContentProviderOperation.newInsert(syncUri(ContactsContract.Data.CONTENT_URI)) |
| 101 | .withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId) |
| 102 | .withValue(ContactsContract.Data.MIMETYPE, mimeType) |
| 103 | // DATA1 is the identifier the row acts on; DATA2/DATA3 are what a contacts UI shows. |
| 104 | .withValue(ContactsContract.Data.DATA1, e164) |
| 105 | .withValue(ContactsContract.Data.DATA2, label) |
| 106 | .withValue(ContactsContract.Data.DATA3, e164) |
| 107 | .build() |
| 108 | |
| 109 | /** |
| 110 | * Our raw contact for [e164], created if absent and linked to the aggregate contact by the phone number. |
| 111 | * |
| 112 | * A separate raw contact under our account is how the provider is meant to be extended: the aggregator |
| 113 | * joins it to the user's existing contact by number, so the rows appear on the right person without us |
| 114 | * editing anybody else's data. |
| 115 | */ |
| 116 | private fun ourRawContactFor(context: Context, e164: String): Long? { |
| 117 | existingRawContact(context, e164)?.let { return it } |
| 118 | return try { |
| 119 | val values = android.content.ContentValues().apply { |
| 120 | put(ContactsContract.RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE) |
| 121 | put(ContactsContract.RawContacts.ACCOUNT_NAME, ACCOUNT_NAME) |
| 122 | put(ContactsContract.RawContacts.SYNC1, e164) |
| 123 | } |
| 124 | val uri = context.contentResolver.insert(syncUri(ContactsContract.RawContacts.CONTENT_URI), values) |
| 125 | ?: return null |
| 126 | val id = ContentUris.parseId(uri) |
| 127 | // A phone row is what lets the aggregator match this to the user's existing contact. |
| 128 | context.contentResolver.insert( |
| 129 | syncUri(ContactsContract.Data.CONTENT_URI), |
| 130 | android.content.ContentValues().apply { |
| 131 | put(ContactsContract.Data.RAW_CONTACT_ID, id) |
| 132 | put( |
| 133 | ContactsContract.Data.MIMETYPE, |
| 134 | ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, |
| 135 | ) |
| 136 | put(ContactsContract.CommonDataKinds.Phone.NUMBER, e164) |
| 137 | }, |
| 138 | ) |
| 139 | id |
| 140 | } catch (expected: Throwable) { |
| 141 | Log.status(TAG, "could not create a raw contact for $e164", expected) |
| 142 | null |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | private fun existingRawContact(context: Context, e164: String): Long? = try { |
| 147 | context.contentResolver.query( |
| 148 | ContactsContract.RawContacts.CONTENT_URI, |
| 149 | arrayOf(ContactsContract.RawContacts._ID), |
| 150 | "${ContactsContract.RawContacts.ACCOUNT_TYPE} = ? AND ${ContactsContract.RawContacts.SYNC1} = ?", |
| 151 | arrayOf(ACCOUNT_TYPE, e164), |
| 152 | null, |
| 153 | )?.use { cursor: Cursor -> if (cursor.moveToFirst()) cursor.getLong(0) else null } |
| 154 | } catch (expected: Throwable) { |
| 155 | Log.status(TAG, "could not look up our raw contact for $e164", expected) |
| 156 | null |
| 157 | } |
| 158 | |
| 159 | /** |
| 160 | * Marks writes as coming from the sync adapter that owns the account. Without this the provider treats a |
| 161 | * delete as a tombstone rather than removing the row. |
| 162 | */ |
| 163 | private fun syncUri(uri: android.net.Uri) = uri.buildUpon() |
| 164 | .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") |
| 165 | .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE) |
| 166 | .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, ACCOUNT_NAME) |
| 167 | .build() |
| 168 | |
| 169 | /** The account must exist before the provider will accept rows attributed to it. */ |
| 170 | private fun ensureAccount(context: Context): Boolean = try { |
| 171 | val manager = AccountManager.get(context) |
| 172 | val account = Account(ACCOUNT_NAME, ACCOUNT_TYPE) |
| 173 | val present = manager.getAccountsByType(ACCOUNT_TYPE).any { it.name == ACCOUNT_NAME } |
| 174 | if (!present) manager.addAccountExplicitly(account, null, null) |
| 175 | true |
| 176 | } catch (expected: Throwable) { |
| 177 | // Adding an account of another app's type needs a matching signature; log rather than fail the sync. |
| 178 | Log.status(TAG, "could not ensure the contacts account exists: ${expected.message}") |
| 179 | false |
| 180 | } |
| 181 | } |