Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / WhatsAppContactSync.kt
WhatsAppContactSync.kt181 lines · 8.4 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp |
| 2 | |
| 3 | import android.Manifest |
| 4 | import android.content.Context |
| 5 | import android.content.pm.PackageManager |
| 6 | import android.provider.ContactsContract |
| 7 | import android.telephony.TelephonyManager |
| 8 | import com.vayunmathur.library.log.Log |
| 9 | import com.google.i18n.phonenumbers.PhoneNumberUtil |
| 10 | import com.vayunmathur.communicate.data.whatsapp.mex.MexResult |
| 11 | import com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps |
| 12 | import java.util.UUID |
| 13 | import org.json.JSONObject |
| 14 | |
| 15 | /** |
| 16 | * Device address-book → WhatsApp contact sync (w2.md §8.3, Phase C 2f). |
| 17 | * |
| 18 | * Reads the device contacts (behind a `READ_CONTACTS` check — the permission is already declared in |
| 19 | * the module manifest), normalizes numbers to E.164 via libphonenumber, de-dups, chunks, and drives |
| 20 | * [WhatsAppMexOps.primaryContactsFullSync] (paged: one `session_id` UUID across pages, `last=true` |
| 21 | * on the final page) followed by [WhatsAppMexOps.contactDiscovery]. Returned LID/phone mappings are |
| 22 | * persisted to the [WhatsAppContact] Room table so 1:1 threads can be enriched. |
| 23 | * |
| 24 | * Dev-only scaffolding: the MEX contact ops resolve their `doc_id` from the bundled persist-id map, |
| 25 | * which is currently empty, so the sync gracefully no-ops (persisting the local numbers with |
| 26 | * `onWhatsApp=false`) until real ids are captured. Live validation is impossible (test number is |
| 27 | * banned). |
| 28 | */ |
| 29 | object WhatsAppContactSync { |
| 30 | |
| 31 | private const val TAG = "WAContactSync" |
| 32 | private const val PAGE_SIZE = 500 |
| 33 | |
| 34 | /** One device address-book contact to check against WhatsApp. */ |
| 35 | data class DeviceContact(val e164: String, val name: String) |
| 36 | |
| 37 | /** The outcome of a contact sync: how many numbers were checked and how many are on WhatsApp. */ |
| 38 | data class SyncResult( |
| 39 | val deviceCount: Int, |
| 40 | val e164Count: Int, |
| 41 | val onWhatsAppCount: Int, |
| 42 | val transportError: String? = null, |
| 43 | ) |
| 44 | |
| 45 | /** |
| 46 | * Normalize a raw phone string to E.164 using [region] (ISO-3166 alpha-2). Pure/JVM-testable |
| 47 | * (libphonenumber only). Returns null when the number can't be parsed. |
| 48 | */ |
| 49 | fun normalizeE164(raw: String, region: String): String? = runCatching { |
| 50 | val util = PhoneNumberUtil.getInstance() |
| 51 | val parsed = util.parse(raw, region) |
| 52 | if (!util.isValidNumber(parsed)) return null |
| 53 | util.format(parsed, PhoneNumberUtil.PhoneNumberFormat.E164) |
| 54 | }.getOrNull() |
| 55 | |
| 56 | /** The device's default region (SIM/network country, falling back to the locale). */ |
| 57 | fun defaultRegion(context: Context): String = runCatching { |
| 58 | val tm = context.getSystemService(TelephonyManager::class.java) |
| 59 | (tm?.simCountryIso?.takeIf { it.isNotBlank() } ?: tm?.networkCountryIso)?.uppercase() |
| 60 | }.getOrNull()?.takeIf { it.isNotBlank() } |
| 61 | ?: context.resources.configuration.locales[0].country.ifEmpty { "US" } |
| 62 | |
| 63 | /** Read (name, number) pairs from the device address book. Empty when permission is missing. */ |
| 64 | fun readDeviceContacts(context: Context): List<Pair<String, String>> { |
| 65 | if (context.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { |
| 66 | return emptyList() |
| 67 | } |
| 68 | val projection = arrayOf( |
| 69 | ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY, |
| 70 | ContactsContract.CommonDataKinds.Phone.NUMBER, |
| 71 | ) |
| 72 | return runCatching { |
| 73 | context.contentResolver.query( |
| 74 | ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null, |
| 75 | )?.use { cursor -> |
| 76 | buildList { |
| 77 | val nameIdx = |
| 78 | cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY) |
| 79 | val numIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER) |
| 80 | while (cursor.moveToNext()) { |
| 81 | val number = cursor.getString(numIdx).orEmpty().trim() |
| 82 | if (number.isEmpty()) continue |
| 83 | add(cursor.getString(nameIdx).orEmpty() to number) |
| 84 | } |
| 85 | } |
| 86 | }.orEmpty() |
| 87 | }.getOrDefault(emptyList()) |
| 88 | } |
| 89 | |
| 90 | /** |
| 91 | * Run a full contact sync: read → normalize → dedup → paged full-sync → discovery → persist. |
| 92 | * Best-effort; never throws (returns a [SyncResult] with a transportError on MEX failure). |
| 93 | */ |
| 94 | suspend fun sync(context: Context, syncContext: String = "PERIODIC_SYNC"): SyncResult { |
| 95 | if (!WhatsAppFeature.enabled) return SyncResult(0, 0, 0, "disabled") |
| 96 | val region = defaultRegion(context) |
| 97 | val device = readDeviceContacts(context) |
| 98 | |
| 99 | // Normalize + de-dup by E.164, keeping the first display name seen. |
| 100 | val byE164 = LinkedHashMap<String, String>() |
| 101 | for ((name, number) in device) { |
| 102 | val e164 = normalizeE164(number, region) ?: continue |
| 103 | byE164.putIfAbsent(e164, name) |
| 104 | } |
| 105 | val e164s = byE164.keys.toList() |
| 106 | if (e164s.isEmpty()) { |
| 107 | return SyncResult(deviceCount = device.size, e164Count = 0, onWhatsAppCount = 0) |
| 108 | } |
| 109 | |
| 110 | // Persist the local numbers first (onWhatsApp defaults false) so the mapping table is |
| 111 | // populated even when the MEX ops can't resolve a doc_id. |
| 112 | val now = System.currentTimeMillis() |
| 113 | val db = WhatsAppDatabase.getDatabase(context) |
| 114 | db.contactDao().upsertAll( |
| 115 | byE164.map { (e164, name) -> WhatsAppContact(phoneE164 = e164, displayName = name, updatedAt = now) }, |
| 116 | ) |
| 117 | |
| 118 | // Paged primary-contacts full sync: one session id, last=true on the final page. |
| 119 | val sessionId = UUID.randomUUID().toString() |
| 120 | val pages = e164s.chunked(PAGE_SIZE) |
| 121 | var transportError: String? = null |
| 122 | pages.forEachIndexed { index, page -> |
| 123 | val res = WhatsAppMexOps.primaryContactsFullSync( |
| 124 | context = context, |
| 125 | rawPhoneNumbers = page, |
| 126 | sessionId = sessionId, |
| 127 | pageIndex = index, |
| 128 | last = index == pages.lastIndex, |
| 129 | syncContext = syncContext, |
| 130 | ) |
| 131 | if (res.transportError != null) transportError = res.transportError |
| 132 | } |
| 133 | |
| 134 | // Discovery resolves per-number LID + on-WhatsApp status; parse and persist mappings. |
| 135 | val discovery = WhatsAppMexOps.contactDiscovery(context, e164s, "SEARCH") |
| 136 | val mappings = parseDiscovery(discovery) |
| 137 | if (mappings.isNotEmpty()) { |
| 138 | db.contactDao().upsertAll( |
| 139 | mappings.map { (e164, m) -> |
| 140 | WhatsAppContact( |
| 141 | phoneE164 = e164, |
| 142 | lid = m.lid, |
| 143 | displayName = byE164[e164] ?: "", |
| 144 | onWhatsApp = m.onWhatsApp, |
| 145 | updatedAt = now, |
| 146 | ) |
| 147 | }, |
| 148 | ) |
| 149 | } |
| 150 | if (discovery.transportError != null) transportError = discovery.transportError |
| 151 | |
| 152 | val onWa = mappings.count { it.value.onWhatsApp } |
| 153 | Log.status(TAG, "sync: device=${device.size} e164=${e164s.size} onWA=$onWa err=$transportError") |
| 154 | return SyncResult(device.size, e164s.size, onWa, transportError) |
| 155 | } |
| 156 | |
| 157 | private data class Mapping(val lid: String, val onWhatsApp: Boolean) |
| 158 | |
| 159 | /** |
| 160 | * Parse `xwa2_contact_discovery` results into E.164 → (lid, onWhatsApp). Tolerant of missing |
| 161 | * fields (the exact wire shape depends on captured doc_ids). Ref w2.md §8.3 |
| 162 | * XWA2ContactDiscoveryResult / XWA2PhoneDiscoveryOutput (status IN|OUT|INVALID). |
| 163 | */ |
| 164 | private fun parseDiscovery(result: MexResult): Map<String, Mapping> { |
| 165 | val data = result.data ?: return emptyMap() |
| 166 | val payload = data.optJSONObject("xwa2_contact_discovery") ?: return emptyMap() |
| 167 | val results = payload.optJSONArray("results") ?: return emptyMap() |
| 168 | val out = LinkedHashMap<String, Mapping>() |
| 169 | for (i in 0 until results.length()) { |
| 170 | val r = results.optJSONObject(i) ?: continue |
| 171 | val lid = r.optString("lid", "") |
| 172 | val detail: JSONObject? = r.optJSONObject("detail") |
| 173 | val rawPn = detail?.optString("normalized_phone").orEmpty() |
| 174 | .ifEmpty { detail?.optString("raw_pn").orEmpty() } |
| 175 | val status = detail?.optString("status").orEmpty() |
| 176 | val onWa = status.equals("IN", ignoreCase = true) || (lid.isNotEmpty() && !r.optBoolean("failed", false)) |
| 177 | if (rawPn.isNotEmpty()) out[rawPn] = Mapping(lid, onWa) |
| 178 | } |
| 179 | return out |
| 180 | } |
| 181 | } |