communicate: various fixes
- Commit
b5014c6a5f8f5bb7be29e2f15efa81300aac8486- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-14 00:11 UTC (3 months ago)
- Parents
7ae41eb
Diff
communicate/src/main/assets/whatsapp/mex_persist_ids.json
diff --git a/communicate/src/main/assets/whatsapp/mex_persist_ids.json b/communicate/src/main/assets/whatsapp/mex_persist_ids.jsonnew file mode 100644index 0000000000..1ee3a466c4--- /dev/null+++ b/communicate/src/main/assets/whatsapp/mex_persist_ids.json@@ -0,0 +1,12 @@+{+ "version": 1,+ "data": {+ "QueryGroupInfo": "27462649126753603",+ "ContactUserInfoQuery": "27056625294008854",+ "UsernameSetMutation": "7225825540870559",+ "GetTextStatus": "6681894428597832",+ "NotificationNewsletterJoin": "24434120059586833",+ "AccountSyncUsernameNotification": "25290488857205803",+ "TextStatusUpdateNotification": "6601560246628795"+ }+}
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 fe63832241..b271ef4070 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -848,6 +848,82 @@ object CommunicateRepository { /** True only when the WhatsApp primary client is logged in (needed for send/group ops). */ fun isWhatsAppConnected(): Boolean = WhatsAppClient.isConnected() + // -- WhatsApp MEX / GraphQL (dev-only scaffolding, gated on WhatsAppFeature.enabled) --+ //+ // Thin pass-throughs to the xwa2_* operation catalog so the new MEX capabilities are+ // callable/integrable without new UI. Every entry is gated behind WhatsAppFeature.enabled+ // (stripped from release by R8) and runs on Dispatchers.IO. Each returns a MexResult; when the+ // feature is off or an op's persisted doc_id isn't captured yet, callers get a typed transport+ // failure rather than a crash.++ private val mexDisabled: com.vayunmathur.communicate.data.whatsapp.mex.MexResult+ get() = com.vayunmathur.communicate.data.whatsapp.mex.MexResult.transport("disabled")++ /** MEX group metadata read (`xwa2_group_query_by_id`). */+ suspend fun whatsAppGroupInfo(+ context: Context,+ groupJid: String,+ ): com.vayunmathur.communicate.data.whatsapp.mex.MexResult = withContext(Dispatchers.IO) {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return@withContext mexDisabled+ com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.groupQueryById(context, groupJid)+ }++ /** MEX contact discovery (`xwa2_contact_discovery`) for raw phone numbers. */+ suspend fun whatsAppContactDiscovery(+ context: Context,+ rawPhoneNumbers: List<String>,+ discoveryContext: String = "SEARCH",+ ): com.vayunmathur.communicate.data.whatsapp.mex.MexResult = withContext(Dispatchers.IO) {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return@withContext mexDisabled+ com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.contactDiscovery(context, rawPhoneNumbers, discoveryContext)+ }++ /** MEX username read (`xwa2_username_get`). */+ suspend fun whatsAppUsernameGet(+ context: Context,+ ): com.vayunmathur.communicate.data.whatsapp.mex.MexResult = withContext(Dispatchers.IO) {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return@withContext mexDisabled+ com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.usernameGet(context)+ }++ /** MEX username claim (`xwa2_username_set`). */+ suspend fun whatsAppUsernameSet(+ context: Context,+ username: String,+ pin: String? = null,+ sessionId: String? = null,+ ): com.vayunmathur.communicate.data.whatsapp.mex.MexResult = withContext(Dispatchers.IO) {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return@withContext mexDisabled+ com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.usernameSet(context, username, pin, sessionId = sessionId)+ }++ /** MEX blocklist read (`xwa2_blocklist_get`). */+ suspend fun whatsAppBlocklistGet(+ context: Context,+ dhash: String? = null,+ ): com.vayunmathur.communicate.data.whatsapp.mex.MexResult = withContext(Dispatchers.IO) {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return@withContext mexDisabled+ com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.blocklistGet(context, dhash)+ }++ /** MEX presence read (`xwa2_presence_data_platform_get_online_or_last_status`). */+ suspend fun whatsAppPresence(+ context: Context,+ lidJids: List<String>,+ lastActiveFilter: String? = null,+ ): com.vayunmathur.communicate.data.whatsapp.mex.MexResult = withContext(Dispatchers.IO) {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return@withContext mexDisabled+ com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.getOnlineOrLastStatus(context, lidJids, lastActiveFilter)+ }++ /** MEX Signal-prekey publish (`xwa2_set_messaging_keys`); mints + persists one-time prekeys. */+ suspend fun whatsAppSetMessagingKeys(+ context: Context,+ ): com.vayunmathur.communicate.data.whatsapp.mex.MexResult = withContext(Dispatchers.IO) {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return@withContext mexDisabled+ com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.setMessagingKeys(context)+ }+ /** * Create a WhatsApp group with [subject] and the given [contacts] (phone numbers / addresses). * Each contact is normalized to a full WhatsApp user JID before the create IQ is sent. Returns
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.ktindex 814d39d90c..5bd13e2cbb 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt@@ -360,6 +360,46 @@ object WhatsAppClient { } } + /**+ * Perform a MEX (`w:mex`) GraphQL call over the existing Noise/XMPP socket (w2.md §5.2). Resolves+ * the persisted-query [operationName] → doc_id via [MexPersistedQueryProvider]; when the id isn't+ * in the bundled JSON returns a typed `no_persisted_id:<op>` transport failure (never crashes,+ * unlike the official debug client). Builds the `{"queryId":…,"variables":…}` envelope, sends the+ * `<iq xmlns="w:mex">`, waits (32s per §1.5), then extracts the `<result>` node's+ * `{"data":…,"errors":…}` envelope into a [MexResult].+ *+ * Dev-only: guarded by [WhatsAppFeature.enabled] at the repository layer; requires an active+ * connection (use [com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMex] to fall back to WWW+ * HTTP when disconnected).+ */+ suspend fun mexCall(+ operationName: String,+ variablesJson: String,+ type: String = "get",+ ): com.vayunmathur.communicate.data.whatsapp.mex.MexResult {+ val docId = com.vayunmathur.communicate.data.whatsapp.mex.MexPersistedQueryProvider+ .docIdFor(appContext, operationName)+ ?: run {+ WhatsAppDiag.log(TAG, "mex[$operationName]: no persisted doc_id (add it to mex_persist_ids.json)")+ return com.vayunmathur.communicate.data.whatsapp.mex.MexResult.transport("no_persisted_id:$operationName")+ }+ val id = generateMessageId()+ val queryJson = com.vayunmathur.communicate.data.whatsapp.mex.MexEnvelope.buildQueryJson(docId, variablesJson)+ val node = WhatsAppProtocol.buildMexQuery(docId, queryJson, id, type)+ val resp = sendIqAndWait(node, timeoutMs = 32_000)+ ?: return com.vayunmathur.communicate.data.whatsapp.mex.MexResult.transport("timeout")+ if (resp.attrs["type"] == "error") {+ val code = resp.getChildByTag("error")?.attrs?.get("code")+ WhatsAppDiag.log(TAG, "mex[$operationName]: iq error code=${code ?: "unknown"}")+ return com.vayunmathur.communicate.data.whatsapp.mex.MexResult.transport("iq_error:${code ?: "unknown"}")+ }+ val envelope = resp.getChildByTag("result")?.data?.toString(Charsets.UTF_8)+ ?: return com.vayunmathur.communicate.data.whatsapp.mex.MexResult.transport("no_result")+ val out = com.vayunmathur.communicate.data.whatsapp.mex.MexResult.fromEnvelope(envelope)+ WhatsAppDiag.log(TAG, "mex[$operationName]: success=${out.isSuccess} errors=${out.errors.size}")+ return out+ }+ /** * Upload one-time + signed prekeys to the server. * Ref whatsmeow prekeys.go uploadPreKeys. [initialUpload] uploads a large batch after pair.@@ -2013,6 +2053,39 @@ object WhatsAppClient { return if (sent) id else null } + /**+ * Send a text message with optional rich content: @mentions, a quoted reply, and/or a URL+ * link-preview. When none are provided this is equivalent to [sendMessage] (a plain+ * `conversation` proto). Rich content is carried in an ExtendedTextMessage with ContextInfo so+ * the peer renders mentions/quote/preview. Routed through the normal Signal fan-out (1:1) or+ * group sender-key path. Ref whatsmeow ExtendedTextMessage / ContextInfo.+ */+ suspend fun sendMessageAdvanced(+ conversationId: String,+ body: String,+ mentionedJids: List<String> = emptyList(),+ quoted: WhatsAppProtocol.QuotedContext? = null,+ linkPreview: WhatsAppProtocol.LinkPreview? = null,+ ): String? {+ if (_state.value !is State.Connected) { WhatsAppDiag.log(TAG, "sendAdv: not connected"); return null }+ val ws = webSocket ?: return null+ val to = extractJid(conversationId) ?: return null+ val id = WhatsAppProtocol.generateMessageId(authData?.wid)++ val proto = WhatsAppProtocol.buildTextProto(body, mentionedJids, quoted, linkPreview)+ val node = if (to.contains("@g.us")) {+ buildEncryptedGroupMessageNode(to, id, proto, type = "text")+ } else {+ buildEncryptedMessageNode(to, id, proto, "text")+ } ?: run { WhatsAppDiag.log(TAG, "sendAdv: build FAILED (no enc) for $to"); return null }++ pendingMessageIDs.add(id)+ val sent = ws.send(WhatsAppProtocol.encodeNode(node))+ if (!sent) pendingMessageIDs.remove(id)+ WhatsAppDiag.log(TAG, "sendAdv: sent=$sent id=$id mentions=${mentionedJids.size} quoted=${quoted != null} preview=${linkPreview != null}")+ return if (sent) id else null+ }+ // --------------------------------------------------------------------------------------------- // Phase 10a — call signaling spike (media/VoIP engine is native-only, out of scope this pass). // ---------------------------------------------------------------------------------------------@@ -2072,6 +2145,7 @@ object WhatsAppClient { msg: WhatsAppE2EProto.Message, type: String, extraEncAttrs: Map<String, String> = emptyMap(),+ messageAttrs: Map<String, String> = emptyMap(), ): WhatsAppProtocol.Node? { val auth = authData ?: return null val crypto = ensureE2E(auth) ?: return null@@ -2106,6 +2180,7 @@ object WhatsAppClient { includeDeviceIdentity = includeIdentity, deviceIdentity = deviceIdentity, extraEncAttrs = extraEncAttrs,+ messageAttrs = messageAttrs, ) } @@ -2119,9 +2194,12 @@ object WhatsAppClient { /** * Build an arbitrary group message: sender-key encrypt the content (skmsg) and 1:1 fan out the * SenderKeyDistributionMessage to every member device. Mirrors whatsmeow send.go sendGroup.- * UNVERIFIED: libsignal-client's sender-key wire format (distribution UUID + versioned- * SenderKeyMessage) differs from WhatsApp's legacy libsignal sender-key format, so group- * skmsg crypto interop is not runtime-verified.+ *+ * The skmsg wire is produced by the Rust `communicate_signal` sender-key implementation+ * ([RustWhatsAppCrypto.encryptGroup]/`createSenderKey`), NOT libsignal-client. Its SKDM ++ * skmsg round-trip is self-loopback-verified on-device via+ * [WhatsAppDiag.verifyGroupSenderKeyRoundTrip] (encrypt→decrypt through the same Rust path).+ * Live peer interop still cannot be validated because the test number is banned. */ private suspend fun buildEncryptedGroupMessageNode( groupJid: String,@@ -2129,6 +2207,7 @@ object WhatsAppClient { msg: WhatsAppE2EProto.Message, type: String = "text", extraEncAttrs: Map<String, String> = emptyMap(),+ messageAttrs: Map<String, String> = emptyMap(), ): WhatsAppProtocol.Node? { val auth = authData ?: return null val crypto = ensureE2E(auth) ?: return null@@ -2183,6 +2262,7 @@ object WhatsAppClient { deviceIdentity = deviceIdentity, extraEnc = skMsg, extraEncAttrs = extraEncAttrs,+ messageAttrs = messageAttrs, ) } @@ -2546,33 +2626,64 @@ object WhatsAppClient { } /**- * Edit a previously sent message.- * From whatsmeow HandleMatrixEdit / BuildEdit+ * Edit a previously sent message. Builds a MESSAGE_EDIT ProtocolMessage proto and routes it+ * through the normal Signal encryption + multi-device fan-out (1:1 or group sender-key) with a+ * message-level `edit="1"` attribute. Previously this sent a plaintext `<enc>` that bypassed+ * Signal fan-out and was undeliverable. */ suspend fun sendEdit(conversationId: String, targetMessageId: String, newBody: String): Boolean { if (_state.value !is State.Connected) return false val ws = webSocket ?: return false val chatJid = extractJid(conversationId) ?: return false val id = WhatsAppProtocol.generateMessageId(authData?.wid)- val ownJid = authData?.wid ?: ""+ val rawTargetId = extractMessageId(targetMessageId) - val node = WhatsAppProtocol.buildEditMessage(chatJid, targetMessageId, newBody, ownJid, id)- return ws.send(WhatsAppProtocol.encodeNode(node))+ val proto = WhatsAppProtocol.buildEditProto(chatJid, rawTargetId, newBody)+ val editAttrs = mapOf("edit" to "1")+ val node = if (chatJid.contains("@g.us")) {+ buildEncryptedGroupMessageNode(chatJid, id, proto, type = "text", messageAttrs = editAttrs)+ } else {+ buildEncryptedMessageNode(chatJid, id, proto, "text", messageAttrs = editAttrs)+ } ?: run { WhatsAppDiag.log(TAG, "edit: build FAILED (no enc) for $chatJid"); return false }++ pendingMessageIDs.add(id)+ val sent = ws.send(WhatsAppProtocol.encodeNode(node))+ if (!sent) pendingMessageIDs.remove(id)+ WhatsAppDiag.log(TAG, "edit to=$chatJid target=$rawTargetId sent=$sent")+ return sent } /** * Revoke (delete) a previously sent message. * From whatsmeow HandleMatrixMessageRemove / BuildRevoke */+ /**+ * Revoke (delete-for-everyone) a previously sent message. Builds a REVOKE ProtocolMessage+ * proto and routes it through the normal Signal fan-out (1:1 or group sender-key) with the+ * message-level `edit` attribute ("7" own / "8" other). Previously sent a plaintext `<enc>`.+ */ suspend fun sendRevoke(conversationId: String, targetMessageId: String, senderJid: String = ""): Boolean { if (_state.value !is State.Connected) return false val ws = webSocket ?: return false val chatJid = extractJid(conversationId) ?: return false val id = WhatsAppProtocol.generateMessageId(authData?.wid) val ownJid = authData?.wid ?: ""+ val rawTargetId = extractMessageId(targetMessageId) - val node = WhatsAppProtocol.buildRevokeMessage(chatJid, senderJid, targetMessageId, ownJid, id)- return ws.send(WhatsAppProtocol.encodeNode(node))+ val proto = WhatsAppProtocol.buildRevokeProto(chatJid, senderJid, rawTargetId, ownJid)+ val isFromMe = WhatsAppProtocol.isRevokeFromMe(senderJid, ownJid)+ val revokeAttrs = mapOf("edit" to if (isFromMe) "7" else "8")+ val node = if (chatJid.contains("@g.us")) {+ buildEncryptedGroupMessageNode(chatJid, id, proto, type = "text", messageAttrs = revokeAttrs)+ } else {+ buildEncryptedMessageNode(chatJid, id, proto, "text", messageAttrs = revokeAttrs)+ } ?: run { WhatsAppDiag.log(TAG, "revoke: build FAILED (no enc) for $chatJid"); return false }++ pendingMessageIDs.add(id)+ val sent = ws.send(WhatsAppProtocol.encodeNode(node))+ if (!sent) pendingMessageIDs.remove(id)+ WhatsAppDiag.log(TAG, "revoke to=$chatJid target=$rawTargetId sent=$sent")+ return sent } /**@@ -2735,7 +2846,8 @@ object WhatsAppClient { } /**- * Send a contact/vCard message.+ * Send a contact/vCard message. Routed through the normal Signal encryption + multi-device+ * fan-out (1:1 or group sender-key) — previously emitted a plaintext `<enc>` that was dropped. * From Go wa-contact.go convertContactMessage. */ suspend fun sendContact(@@ -2748,14 +2860,28 @@ object WhatsAppClient { val chatJid = extractJid(conversationId) ?: return false val id = WhatsAppProtocol.generateMessageId(authData?.wid) - val node = WhatsAppProtocol.buildContactMessage(chatJid, displayName, vcard, id)- return ws.send(WhatsAppProtocol.encodeNode(node))+ val proto = WhatsAppProtocol.buildContactProto(displayName, vcard)+ val node = if (chatJid.contains("@g.us")) {+ buildEncryptedGroupMessageNode(chatJid, id, proto, type = "text")+ } else {+ buildEncryptedMessageNode(chatJid, id, proto, "text")+ } ?: run { WhatsAppDiag.log(TAG, "contact: build FAILED (no enc) for $chatJid"); return false }++ pendingMessageIDs.add(id)+ val sent = ws.send(WhatsAppProtocol.encodeNode(node))+ if (!sent) pendingMessageIDs.remove(id)+ WhatsAppDiag.log(TAG, "contact to=$chatJid sent=$sent")+ return sent } /** * Set disappearing messages timer. * From Go HandleMatrixDisappearingTimer. * Allowed values: 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d).+ *+ * 1:1 chats carry the setting as an EPHEMERAL_SETTING ProtocolMessage over the normal Signal+ * fan-out. Groups instead use a `w:g2` IQ (`<ephemeral expiration=..>` / `<not_ephemeral/>`)+ * so the whole group is updated server-side, matching whatsmeow SetDisappearingTimer. */ suspend fun setDisappearingTimer(conversationId: String, timerSeconds: Long): Boolean { if (_state.value !is State.Connected) return false@@ -2769,8 +2895,31 @@ object WhatsAppClient { } val id = WhatsAppProtocol.generateMessageId(authData?.wid)- val node = WhatsAppProtocol.buildDisappearingTimerMessage(chatJid, timerSeconds, id)- return ws.send(WhatsAppProtocol.encodeNode(node))+ if (chatJid.contains("@g.us")) {+ val child = if (timerSeconds == 0L) {+ WhatsAppProtocol.Node(tag = "not_ephemeral")+ } else {+ WhatsAppProtocol.Node(tag = "ephemeral", attrs = mapOf("expiration" to timerSeconds.toString()))+ }+ val iq = WhatsAppProtocol.Node(+ tag = "iq",+ attrs = mapOf("id" to id, "type" to "set", "xmlns" to "w:g2", "to" to chatJid),+ content = listOf(child),+ )+ val resp = sendIqAndWait(iq, timeoutMs = 10_000)+ val ok = resp != null && resp.attrs["type"] != "error"+ WhatsAppDiag.log(TAG, "disappearing(group) to=$chatJid secs=$timerSeconds ok=$ok")+ return ok+ }++ val proto = WhatsAppProtocol.buildDisappearingTimerProto(timerSeconds)+ val node = buildEncryptedMessageNode(chatJid, id, proto, "text")+ ?: run { WhatsAppDiag.log(TAG, "disappearing: build FAILED (no enc) for $chatJid"); return false }+ pendingMessageIDs.add(id)+ val sent = ws.send(WhatsAppProtocol.encodeNode(node))+ if (!sent) pendingMessageIDs.remove(id)+ WhatsAppDiag.log(TAG, "disappearing to=$chatJid secs=$timerSeconds sent=$sent")+ return sent } /**
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDiag.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDiag.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDiag.ktindex 2f4e5cce38..25d81f629e 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDiag.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDiag.kt@@ -48,4 +48,36 @@ object WhatsAppDiag { } return "${data.size}B[${hex}${if (data.size > max) "…" else ""}]" }++ /**+ * Group sender-key (`skmsg`) self-loopback diagnostic (Phase A 1d). Exercises the exact Rust+ * sender-key wire that [WhatsAppE2E.encryptGroup]/[buildEncryptedGroupMessageNode] produce:+ *+ * 1. sender: create sender key → (state, SKDM)+ * 2. receiver: processSenderKey(SKDM) → receiver state+ * 3. sender: encryptGroup(state, padded) → skmsg ciphertext+ * 4. receiver: decryptGroup(receiverState, ciphertext) → plaintext+ * 5. assert plaintext == padded+ *+ * This validates the SKDM + skmsg round-trips through [RustWhatsAppCrypto] end-to-end on-device+ * (it requires the native `libcommunicate_signal` .so, so it is a dev diagnostic, NOT a JVM+ * unit test). Live peer interop still can't be validated because the test number is banned.+ * Returns true on a successful round-trip.+ */+ fun verifyGroupSenderKeyRoundTrip(): Boolean {+ return try {+ val plaintext = WhatsAppProtocol.padMessage("skmsg loopback probe".toByteArray(Charsets.UTF_8))+ val created = com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto.createSenderKeySplit()+ val receiverState = com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto.processSenderKey(created.skdm)+ ?: throw RuntimeException("processSenderKey returned null")+ val enc = com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto.encryptGroupSplit(created.state, plaintext)+ val dec = com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto.decryptGroupSplit(receiverState, enc.data)+ val ok = dec.data.contentEquals(plaintext)+ log("WA-SKMSG", "sender-key loopback ${if (ok) "PASS" else "FAIL"} skdm=${preview(created.skdm)} ct=${preview(enc.data)}")+ ok+ } catch (e: Exception) {+ log("WA-SKMSG", "sender-key loopback ERROR ${e.message}")+ false+ }+ } }
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppProtocol.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppProtocol.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppProtocol.ktindex cc48522302..610ab6b4b7 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppProtocol.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppProtocol.kt@@ -1152,6 +1152,38 @@ object WhatsAppProtocol { content = listOf(Node(tag = "media_conn")), ) }++ /**+ * Build a MEX (`w:mex`) query IQ carrying a persisted-query GraphQL envelope. Ref w2.md §5.2+ * (SMAX `QueryRequest.kt`): `<iq xmlns="w:mex" to="s.whatsapp.net" type=<type> id=…>` with a+ * single `<query query_id="<docId>"[ argo_mode=…]>` child whose text/data node is the JSON+ * envelope `{"queryId":"<docId>","variables":{…}}` (built JVM-pure by+ * [com.vayunmathur.communicate.data.whatsapp.mex.MexEnvelope.buildQueryJson]).+ *+ * The envelope is attached as the `<query>` node's UTF-8 [Node.data] (like+ * [buildGroupInfoChange]); `data` and `content` are mutually exclusive. [argoMode] is omitted+ * when null (we send the plaintext JSON `<result>` envelope rather than Argo binary).+ *+ * @param docId the resolved 17-digit persisted-query id (also embedded inside [queryJson]).+ * @param queryJson the full `{"queryId":…,"variables":…}` envelope string.+ */+ fun buildMexQuery(+ docId: String,+ queryJson: String,+ id: String,+ type: String = "get",+ argoMode: Long? = null,+ ): Node {+ val queryAttrs = mutableMapOf("query_id" to docId)+ if (argoMode != null) queryAttrs["argo_mode"] = argoMode.toString()+ return Node(+ tag = "iq",+ attrs = mapOf("id" to id, "type" to type, "xmlns" to "w:mex", "to" to "s.whatsapp.net"),+ content = listOf(+ Node(tag = "query", attrs = queryAttrs, data = queryJson.toByteArray(Charsets.UTF_8)),+ ),+ )+ } /** * Build a reaction as an E2E [Message] proto (ReactionMessage). Returned as a proto — NOT a * wire node — so the caller sends it through the normal Signal encryption + multi-device@@ -1336,18 +1368,88 @@ object WhatsAppProtocol { return Node(tag = "receipt", attrs = attrs, content = children) } + // -- Rich send content (mentions / quoted reply / link preview) --------------------------------++ /** A quoted-reply context: the stanza id of the message being replied to, the sender of that+ * message (participant), and (best-effort) the quoted message's proto for the preview. */+ data class QuotedContext(+ val stanzaId: String,+ val participant: String,+ val quotedMessage: com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message? = null,+ )++ /** A URL link-preview attached to an ExtendedTextMessage. */+ data class LinkPreview(+ val matchedText: String,+ val canonicalUrl: String,+ val title: String? = null,+ val description: String? = null,+ val jpegThumbnail: ByteArray? = null,+ )++ /**+ * Build a [ContextInfo] from optional mentions + quoted-reply. Returns null when neither is+ * present so callers can send a bare `conversation` message. Ref whatsmeow ContextInfo usage.+ */+ fun buildContextInfo(+ mentionedJids: List<String> = emptyList(),+ quoted: QuotedContext? = null,+ ): com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ContextInfo? {+ if (mentionedJids.isEmpty() && quoted == null) return null+ val ctx = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ContextInfo.newBuilder()+ for (jid in mentionedJids) ctx.addMentionedJid(jid)+ if (quoted != null) {+ ctx.stanzaId = quoted.stanzaId+ if (quoted.participant.isNotEmpty()) ctx.participant = quoted.participant+ quoted.quotedMessage?.let { ctx.quotedMessage = it }+ }+ return ctx.build()+ }+ /**- * Build an edit message node.- * From whatsmeow/send.go BuildEdit()- * Go wraps in EditedMessage -> FutureProofMessage -> Message -> ProtocolMessage+ * Build a text message proto with optional rich content. When there are no mentions, no quoted+ * reply and no link preview, a plain `conversation` message is produced (matching+ * [buildConversationMessage]); otherwise the text is carried in an [ExtendedTextMessage] with+ * the accompanying [ContextInfo] and link-preview fields so the peer renders them. Ref+ * whatsmeow send.go ExtendedTextMessage. */- fun buildEditMessage(+ fun buildTextProto(+ text: String,+ mentionedJids: List<String> = emptyList(),+ quoted: QuotedContext? = null,+ linkPreview: LinkPreview? = null,+ ): com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message {+ val ctx = buildContextInfo(mentionedJids, quoted)+ if (ctx == null && linkPreview == null) {+ return buildConversationMessage(text)+ }+ val ext = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ExtendedTextMessage.newBuilder()+ .setText(text)+ if (ctx != null) ext.contextInfo = ctx+ if (linkPreview != null) {+ ext.matchedText = linkPreview.matchedText+ ext.canonicalUrl = linkPreview.canonicalUrl+ linkPreview.title?.let { ext.title = it }+ linkPreview.description?.let { ext.description = it }+ linkPreview.jpegThumbnail?.let { ext.jpegThumbnail = com.google.protobuf.ByteString.copyFrom(it) }+ }+ return com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder()+ .setExtendedTextMessage(ext.build())+ .build()+ }++ /**+ * Build an edit as an E2E [Message] proto (ProtocolMessage type MESSAGE_EDIT). Returned as a+ * proto — NOT a wire node — so the caller sends it through the normal Signal encryption ++ * multi-device fan-out (buildEncryptedMessageNode / buildEncryptedGroupMessageNode) with a+ * message-level `edit="1"` attribute. Previously this emitted a plaintext `<enc>` node that+ * bypassed Signal and was therefore undeliverable. Ref whatsmeow send.go BuildEdit.+ */+ fun buildEditProto( chatJid: String, targetMessageId: String, newText: String,- ownJid: String,- id: String,- ): Node {+ ): com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message { val messageKey = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.MessageKey.newBuilder() .setFromMe(true) .setId(targetMessageId)@@ -1365,50 +1467,28 @@ object WhatsAppProtocol { .setTimestampMs(System.currentTimeMillis()) .build() - val innerMessage = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder()+ return com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder() .setProtocolMessage(protocolMessage) .build()-- val futureProof = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.FutureProofMessage.newBuilder()- .setMessage(innerMessage)- .build()-- val e2eMessage = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder()- .setEditedMessage(futureProof)- .build()- val plaintext = e2eMessage.toByteArray()-- return Node(- tag = "message",- attrs = mapOf(- "to" to chatJid,- "id" to id,- "type" to "text",- "edit" to "1"- ),- content = listOf(- Node(- tag = "enc",- attrs = mapOf("v" to "2", "type" to "msg", "decrypt-fail" to "hide"),- data = padMessage(plaintext)- )- )- ) } + /** Whether a revoke targets a message that the local user sent (empty/own sender = self). */+ fun isRevokeFromMe(senderJid: String, ownJid: String): Boolean =+ senderJid.isEmpty() || senderJid == ownJid ||+ senderJid.substringBefore("@") == ownJid.substringBefore("@")+ /**- * Build a revoke (delete) message node.- * From whatsmeow/send.go BuildRevoke()+ * Build a revoke (delete-for-everyone) as an E2E [Message] proto (ProtocolMessage type REVOKE).+ * Returned as a proto for the normal fan-out path; the caller sets the message-level `edit`+ * attribute ("7" for own messages, "8" for others'). Ref whatsmeow send.go BuildRevoke. */- fun buildRevokeMessage(+ fun buildRevokeProto( chatJid: String, senderJid: String, targetMessageId: String, ownJid: String,- id: String,- ): Node {- val isFromMe = senderJid.isEmpty() || senderJid == ownJid ||- senderJid.substringBefore("@") == ownJid.substringBefore("@")+ ): com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message {+ val isFromMe = isRevokeFromMe(senderJid, ownJid) val messageKey = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.MessageKey.newBuilder() .setFromMe(isFromMe) .setId(targetMessageId)@@ -1422,27 +1502,9 @@ object WhatsAppProtocol { .setKey(messageKey.build()) .build() - val e2eMessage = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder()+ return com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder() .setProtocolMessage(protocolMessage) .build()- val plaintext = e2eMessage.toByteArray()-- return Node(- tag = "message",- attrs = mapOf(- "to" to chatJid,- "id" to id,- "type" to "text",- "edit" to if (isFromMe) "7" else "8"- ),- content = listOf(- Node(- tag = "enc",- attrs = mapOf("v" to "2", "type" to "msg", "decrypt-fail" to "hide"),- data = padMessage(plaintext)- )- )- ) } /**@@ -1638,61 +1700,40 @@ object WhatsAppProtocol { } /**- * Build a contact/vCard message.- * From whatsmeow wa-contact.go+ * Build a contact/vCard message as an E2E [Message] proto. Returned as a proto for the normal+ * Signal fan-out path (previously emitted a plaintext `<enc>` node that was undeliverable).+ * Ref whatsmeow wa-contact.go. */- fun buildContactMessage(- chatJid: String,+ fun buildContactProto( displayName: String, vcard: String,- id: String,- ): Node {+ ): com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message { val contactMsg = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ContactMessage.newBuilder() .setDisplayName(displayName) .setVcard(vcard) .build() - val e2eMessage = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder()+ return com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder() .setContactMessage(contactMsg) .build()-- val plaintext = e2eMessage.toByteArray()- return Node(- tag = "message",- attrs = mapOf("to" to chatJid, "id" to id, "type" to "text"),- content = listOf(- Node(tag = "enc", attrs = mapOf("v" to "2", "type" to "msg"), data = padMessage(plaintext))- )- ) } /**- * Build a disappearing timer change message.- * From whatsmeow handlematrix.go HandleMatrixDisappearingTimer()- * Allowed values: 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d)+ * Build a disappearing-timer change as an E2E [Message] proto (ProtocolMessage type+ * EPHEMERAL_SETTING). Returned as a proto for the normal Signal fan-out path. Allowed values:+ * 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d). Ref whatsmeow HandleMatrixDisappearingTimer. */- fun buildDisappearingTimerMessage(- chatJid: String,+ fun buildDisappearingTimerProto( timerSeconds: Long,- id: String,- ): Node {+ ): com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message { val protocolMsg = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ProtocolMessage.newBuilder() .setType(com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ProtocolMessage.Type.EPHEMERAL_SETTING) .setEphemeralExpiration(timerSeconds.toInt()) .build() - val e2eMessage = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder()+ return com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder() .setProtocolMessage(protocolMsg) .build()-- val plaintext = e2eMessage.toByteArray()- return Node(- tag = "message",- attrs = mapOf("to" to chatJid, "id" to id, "type" to "text"),- content = listOf(- Node(tag = "enc", attrs = mapOf("v" to "2", "type" to "msg"), data = padMessage(plaintext))- )- ) } /**@@ -2104,29 +2145,46 @@ object WhatsAppProtocol { else -> null } + /**+ * If [m] is a view-once container (viewOnceMessage / viewOnceMessageV2 /+ * viewOnceMessageV2Extension), return the wrapped inner [Message]; otherwise null. Used to+ * unwrap and flag view-once media on receive. Ref WAWebProtobufsE2E.Message view-once fields.+ */+ fun unwrapViewOnce(+ m: com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message,+ ): com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message? = when {+ m.hasViewOnceMessageV2Extension() && m.viewOnceMessageV2Extension.hasMessage() ->+ m.viewOnceMessageV2Extension.message+ m.hasViewOnceMessageV2() && m.viewOnceMessageV2.hasMessage() -> m.viewOnceMessageV2.message+ m.hasViewOnceMessage() && m.viewOnceMessage.hasMessage() -> m.viewOnceMessage.message+ else -> null+ }+ fun getMessageType(e2eMessage: com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message?): String {+ val unwrapped = if (e2eMessage != null) unwrapViewOnce(e2eMessage) else null+ val e2e = unwrapped ?: e2eMessage return when {- e2eMessage == null -> "ignore"- e2eMessage.hasConversation() || e2eMessage.hasExtendedTextMessage() -> "text"- e2eMessage.hasImageMessage() -> "image ${e2eMessage.imageMessage.mimetype}"- e2eMessage.hasStickerMessage() -> "sticker ${e2eMessage.stickerMessage.mimetype}"- e2eMessage.hasVideoMessage() -> "video ${e2eMessage.videoMessage.mimetype}"- e2eMessage.hasAudioMessage() -> "audio ${e2eMessage.audioMessage.mimetype}"- e2eMessage.hasDocumentMessage() -> "document ${e2eMessage.documentMessage.mimetype}"- e2eMessage.hasContactMessage() -> "contact"- e2eMessage.hasLocationMessage() -> "location"- pollCreation(e2eMessage) != null -> "poll"- e2eMessage.hasReactionMessage() -> {- if (e2eMessage.reactionMessage.text.isNullOrEmpty()) "reaction remove" else "reaction"+ e2e == null -> "ignore"+ e2e.hasConversation() || e2e.hasExtendedTextMessage() -> "text"+ e2e.hasImageMessage() -> "image ${e2e.imageMessage.mimetype}"+ e2e.hasStickerMessage() -> "sticker ${e2e.stickerMessage.mimetype}"+ e2e.hasVideoMessage() -> "video ${e2e.videoMessage.mimetype}"+ e2e.hasAudioMessage() -> "audio ${e2e.audioMessage.mimetype}"+ e2e.hasDocumentMessage() -> "document ${e2e.documentMessage.mimetype}"+ e2e.hasContactMessage() -> "contact"+ e2e.hasLocationMessage() -> "location"+ pollCreation(e2e) != null -> "poll"+ e2e.hasReactionMessage() -> {+ if (e2e.reactionMessage.text.isNullOrEmpty()) "reaction remove" else "reaction" }- e2eMessage.hasEditedMessage() -> {- val inner = e2eMessage.editedMessage?.message+ e2e.hasEditedMessage() -> {+ val inner = e2e.editedMessage?.message if (inner != null) getMessageType(inner) else "ignore" }- e2eMessage.hasProtocolMessage() -> {- when (e2eMessage.protocolMessage.type) {+ e2e.hasProtocolMessage() -> {+ when (e2e.protocolMessage.type) { com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ProtocolMessage.Type.REVOKE -> {- if (e2eMessage.protocolMessage.hasKey()) "revoke" else "ignore"+ if (e2e.protocolMessage.hasKey()) "revoke" else "ignore" } com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ProtocolMessage.Type.MESSAGE_EDIT -> "edit" com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ProtocolMessage.Type.EPHEMERAL_SETTING -> "ephemeral setting"@@ -2137,10 +2195,10 @@ object WhatsAppProtocol { com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ProtocolMessage.Type.SHARE_PHONE_NUMBER, com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE, com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE -> "ignore"- else -> "unknown_protocol_${e2eMessage.protocolMessage.type.number}"+ else -> "unknown_protocol_${e2e.protocolMessage.type.number}" } }- e2eMessage.hasSenderKeyDistributionMessage() -> "ignore"+ e2e.hasSenderKeyDistributionMessage() -> "ignore" else -> "unknown" } }@@ -2152,6 +2210,7 @@ object WhatsAppProtocol { fun extractMessageBody(m: com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message): String { var e2e = m if (e2e.hasEditedMessage() && e2e.editedMessage.hasMessage()) e2e = e2e.editedMessage.message+ unwrapViewOnce(e2e)?.let { e2e = it } return when { e2e.hasConversation() -> e2e.conversation e2e.hasExtendedTextMessage() -> e2e.extendedTextMessage.text@@ -2238,6 +2297,14 @@ object WhatsAppProtocol { e2eMessage = e2eMessage.editedMessage.message } + // Unwrap view-once container (Go convertMediaMessage viewOnce check) and remember+ // it so the UI can render "opened once" media.+ var isViewOnceMsg = false+ val vo = unwrapViewOnce(e2eMessage)+ if (vo != null) {+ isViewOnceMsg = true+ e2eMessage = vo+ } val parsedType = getMessageType(e2eMessage) // A message carrying only a SenderKeyDistributionMessage types as "ignore", but we@@ -2347,8 +2414,10 @@ object WhatsAppProtocol { val contextInfo = extractContextInfo(e2eMessage) - // View-once detection (Go convertMediaMessage viewOnce check)- val isViewOnce = false+ // View-once: set when the message arrived wrapped in a view-once container+ // (unwrapped above). HD is not representable in this proto subset — WhatsApp's HD+ // flag lives in fields we don't model — so it stays false (documented, not faked).+ val isViewOnce = isViewOnceMsg val isHD = false
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexEnvelope.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexEnvelope.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexEnvelope.ktnew file mode 100644index 0000000000..b2621b40ba--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexEnvelope.kt@@ -0,0 +1,66 @@+package com.vayunmathur.communicate.data.whatsapp.mex++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put++/**+ * Pure (JVM-only, kotlinx.serialization) builders for the two MEX/GraphQL wire envelopes. Kept free+ * of any Android dependency so the exact wire shapes can be asserted in JVM unit tests.+ *+ * - [buildQueryJson] — the `<query>` text node payload for MEX-over-XMPP (w2.md §5.2):+ * `{"queryId":"<docId>","variables":{…}}` (queryId is a STRING).+ * - [buildWwwBody] — the WWW GraphQL HTTP body (w2.md §4.1 / §5.3):+ * `{"access_token":…,"doc_id":<int64>,"lang":…,"Content-Type":"application/json","variables":{…}}`+ * (doc_id is a NUMBER; `Content-Type` is intentionally replicated as a JSON key, not only a+ * header).+ *+ * [variablesJson] is a raw JSON object string (e.g. `{"input":{…}}`). Blank/empty is normalized to+ * `{}` so an argument-less operation still sends `variables:{}`.+ */+object MexEnvelope {++ private val json = Json { encodeDefaults = true }++ private fun parseVariables(variablesJson: String): JsonElement {+ val trimmed = variablesJson.trim()+ if (trimmed.isEmpty()) return JsonObject(emptyMap())+ return try {+ json.parseToJsonElement(trimmed)+ } catch (t: Throwable) {+ JsonObject(emptyMap())+ }+ }++ /** MEX-over-XMPP `<query>` payload: `{"queryId":"<docId>","variables":{…}}`. */+ fun buildQueryJson(docId: String, variablesJson: String): String {+ val obj = buildJsonObject {+ put("queryId", docId)+ put("variables", parseVariables(variablesJson))+ }+ return json.encodeToString(JsonObject.serializer(), obj)+ }++ /**+ * WWW GraphQL HTTP body. [docId] is emitted as a JSON number (int64) when it parses as a Long,+ * else as a string (defensive — the server expects a number).+ */+ fun buildWwwBody(+ accessToken: String,+ docId: String,+ variablesJson: String,+ lang: String = "en_US",+ ): String {+ val obj = buildJsonObject {+ put("access_token", accessToken)+ val asLong = docId.toLongOrNull()+ if (asLong != null) put("doc_id", asLong) else put("doc_id", docId)+ put("lang", lang)+ put("Content-Type", "application/json")+ put("variables", parseVariables(variablesJson))+ }+ return json.encodeToString(JsonObject.serializer(), obj)+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexModels.ktnew file mode 100644index 0000000000..c1330da36a--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexModels.kt@@ -0,0 +1,63 @@+package com.vayunmathur.communicate.data.whatsapp.mex++import org.json.JSONObject++/**+ * A single GraphQL error entry from a MEX/WWW response `{"errors":[{message, code, …}]}`.+ */+data class MexError(+ val message: String?,+ val code: Int?,+)++/**+ * Result of a MEX (`w:mex` XMPP IQ) or WWW GraphQL call.+ *+ * - [data]: the `data` object of the GraphQL envelope `{"data":…,"errors":…}` (null on failure).+ * - [errors]: GraphQL-level errors returned by the server (may be non-empty even with partial data).+ * - [transportError]: a client/transport-side failure that never reached the GraphQL layer, e.g.+ * `no_persisted_id:<op>` (the operation's doc_id isn't in the bundled JSON), `timeout`, `iq_error`,+ * or `http:<status>`. Null when the request completed at the GraphQL layer.+ *+ * [isSuccess] is true only when there was no transport error and no GraphQL errors.+ */+data class MexResult(+ val data: JSONObject?,+ val errors: List<MexError> = emptyList(),+ val transportError: String? = null,+) {+ val isSuccess: Boolean get() = transportError == null && errors.isEmpty()++ companion object {+ /** Build a transport-level failure result (no GraphQL round-trip completed). */+ fun transport(reason: String): MexResult = MexResult(null, emptyList(), reason)++ /**+ * Parse a GraphQL envelope string `{"data":…,"errors":[…]}` into a [MexResult].+ * Runtime-only (Android `org.json`); envelope *building* is done JVM-pure in [MexEnvelope].+ */+ fun fromEnvelope(envelopeJson: String): MexResult {+ return try {+ val root = JSONObject(envelopeJson)+ val data = root.optJSONObject("data")+ val errorsArr = root.optJSONArray("errors")+ val errors = buildList {+ if (errorsArr != null) {+ for (i in 0 until errorsArr.length()) {+ val e = errorsArr.optJSONObject(i) ?: continue+ add(+ MexError(+ message = e.optString("message").ifEmpty { null },+ code = if (e.has("code") && !e.isNull("code")) e.optInt("code") else null,+ ),+ )+ }+ }+ }+ MexResult(data = data, errors = errors, transportError = null)+ } catch (t: Throwable) {+ transport("parse_error:${t.message}")+ }+ }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexPersistedQueryProvider.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexPersistedQueryProvider.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexPersistedQueryProvider.ktnew file mode 100644index 0000000000..3aca72b8c3--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexPersistedQueryProvider.kt@@ -0,0 +1,71 @@+package com.vayunmathur.communicate.data.whatsapp.mex++import android.content.Context+import com.vayunmathur.communicate.data.whatsapp.WhatsAppDiag+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import java.util.concurrent.ConcurrentHashMap++/**+ * Resolves a MEX/GraphQL **persisted-query `doc_id`** from a GraphQL **operation name**.+ *+ * MEX never sends raw GraphQL text — the wire `query_id`/`doc_id` is a server-assigned 17-digit id+ * keyed by GraphQL operation name (see w2.md §5.5). The official client resolves+ * `operationName → doc_id` from a bundled assets JSON of the shape+ * `{"version":1,"data":{OperationName: docId, …}}`. This class replicates that, backed by+ * `assets/whatsapp/mex_persist_ids.json`, seeded with the 7 real committed ids from §5.5.+ *+ * Operations whose id is not present return `null` (callers surface a typed+ * `no_persisted_id:<op>` failure). This deliberately does NOT crash like the official debug+ * client's `MexPersistedIdNotFoundFailure` — a dev can drop a captured `operationName:doc_id` pair+ * into the JSON to enable an operation without touching code.+ */+object MexPersistedQueryProvider {++ private const val TAG = "WAMex"+ private const val ASSET_PATH = "whatsapp/mex_persist_ids.json"++ private val json = Json { ignoreUnknownKeys = true; isLenient = true }++ /** Cached `operationName → doc_id` map; loaded lazily from the asset on first use. */+ @Volatile+ private var cache: Map<String, String>? = null++ /**+ * The doc_id for [operationName], or null when it isn't in the bundled JSON (uncaptured op).+ */+ fun docIdFor(context: Context, operationName: String): String? {+ val map = cache ?: loadFromAsset(context).also { cache = it }+ return map[operationName]+ }++ /** Test/refresh hook: drop the cached map so the next [docIdFor] re-reads the asset. */+ fun invalidate() {+ cache = null+ }++ private fun loadFromAsset(context: Context): Map<String, String> {+ return try {+ val text = context.assets.open(ASSET_PATH).use { it.readBytes().toString(Charsets.UTF_8) }+ parsePersistIds(text)+ } catch (t: Throwable) {+ WhatsAppDiag.log(TAG, "persist-ids: failed to load $ASSET_PATH: ${t.message}")+ emptyMap()+ }+ }++ /**+ * Pure parser for the `{"version":1,"data":{name:docId}}` shape. Kept JVM-pure (kotlinx only)+ * so it is unit-testable without Android. Returns an empty map on malformed input.+ */+ fun parsePersistIds(jsonText: String): Map<String, String> {+ return try {+ val root = json.parseToJsonElement(jsonText).jsonObject+ val data = root["data"]?.jsonObject ?: return emptyMap()+ data.mapValues { (_, v) -> v.jsonPrimitive.content }+ } catch (t: Throwable) {+ emptyMap()+ }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMex.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMex.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMex.ktnew file mode 100644index 0000000000..7aa934b651--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMex.kt@@ -0,0 +1,37 @@+package com.vayunmathur.communicate.data.whatsapp.mex++import android.content.Context+import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient++/**+ * MEX transport router (w2.md §5.1). Prefers the `w:mex` XMPP path over the live Noise socket and+ * falls back to the WWW GraphQL HTTP client when disconnected — the same MEX-preferred / WWW-fallback+ * split the official client uses (minus the Pando C++ path, which is out of scope).+ *+ * All calls resolve the same persisted-query [operationName] → doc_id; an uncaptured operation+ * returns a typed `no_persisted_id:<op>` [MexResult] on either path (never crashes).+ *+ * Dev-only: callers go through `CommunicateRepository`, which gates every entry point on+ * `WhatsAppFeature.enabled`.+ */+object WhatsAppMex {++ /**+ * Execute [operationName] with the given `variables` JSON. Uses XMPP when+ * [WhatsAppClient.isConnected]; otherwise resolves the doc_id and posts to WWW GraphQL.+ */+ suspend fun call(+ context: Context,+ operationName: String,+ variablesJson: String,+ type: String = "get",+ ): MexResult {+ return if (WhatsAppClient.isConnected()) {+ WhatsAppClient.mexCall(operationName, variablesJson, type)+ } else {+ val docId = MexPersistedQueryProvider.docIdFor(context, operationName)+ ?: return MexResult.transport("no_persisted_id:$operationName")+ WhatsAppWwwGraphQlClient.post(context, docId, variablesJson)+ }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexOps.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexOps.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexOps.ktnew file mode 100644index 0000000000..1bffe2f49f--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexOps.kt@@ -0,0 +1,451 @@+package com.vayunmathur.communicate.data.whatsapp.mex++import android.content.Context+import android.util.Base64 as AndroidBase64+import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData+import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase+import com.vayunmathur.communicate.data.whatsapp.WhatsAppDiag+import com.vayunmathur.communicate.data.whatsapp.WhatsAppE2EPreKey+import com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.add+import kotlinx.serialization.json.addJsonObject+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put+import kotlinx.serialization.json.putJsonArray+import kotlinx.serialization.json.putJsonObject+import java.util.Base64 as JavaBase64++/**+ * Typed, bounded catalog of `xwa2_*` MEX operations (w2.md §8). Each entry pairs a **GraphQL+ * operation name** (the persist-ids JSON key — documented in KDoc so a dev knows what to capture)+ * with a JVM-pure `variables` builder, then delegates to the [WhatsAppMex] router.+ *+ * `variables` shapes follow the SDL argument names from w2.md §8.0 ("single `variables` map keyed by+ * arg name"). JIDs and `XWA2Binary` are transmitted as Base64 (Argo BYTES over the JSON shim).+ *+ * Only the operations with a real committed doc_id (see `mex_persist_ids.json`, §5.5) will actually+ * round-trip today — `QueryGroupInfo`, `ContactUserInfoQuery`, `UsernameSetMutation`; the rest are+ * callable and return a typed `no_persisted_id:<op>` until a captured id is dropped into the JSON.+ *+ * Dev-only: reached via `CommunicateRepository`, gated on `WhatsAppFeature.enabled`.+ */+object WhatsAppMexOps {++ private const val TAG = "WAMex"++ // -- GraphQL operation names (persist-ids JSON keys) ---------------------------------------++ /** Seeded id 27462649126753603. `query QueryGroupInfo($group_input:XWA2GroupQueryInput!){xwa2_group_query_by_id…}`. */+ const val OP_GROUP_QUERY = "QueryGroupInfo"+ /** Uncaptured. `xwa2_group_query_participating_groups`. */+ const val OP_GROUP_PARTICIPATING = "QueryParticipatingGroups"+ /** Uncaptured. `xwa2_group_batch_query_by_id`. */+ const val OP_GROUP_BATCH = "QueryGroupInfoBatch"+ /** Seeded id 27056625294008854 (nearest known contact op). `xwa2_contact_discovery`. */+ const val OP_CONTACT_DISCOVERY = "ContactUserInfoQuery"+ /** Uncaptured. `xwa2_primary_contacts_full_sync`. */+ const val OP_PRIMARY_CONTACTS_FULL_SYNC = "PrimaryContactsFullSync"+ /** Uncaptured. `xwa2_username_get`. */+ const val OP_USERNAME_GET = "UsernameGet"+ /** Uncaptured. `xwa2_username_check`. */+ const val OP_USERNAME_CHECK = "UsernameCheck"+ /** Seeded id 7225825540870559. `xwa2_username_set`. */+ const val OP_USERNAME_SET = "UsernameSetMutation"+ /** Uncaptured. `xwa2_blocklist_get`. */+ const val OP_BLOCKLIST_GET = "BlocklistGet"+ /** Uncaptured. `xwa2_update_blocklist_lid`. */+ const val OP_BLOCKLIST_UPDATE_LID = "UpdateBlocklistLid"+ /** Uncaptured. `xwa2_presence_data_platform_get_online_or_last_status`. */+ const val OP_PRESENCE_ONLINE_OR_LAST = "GetOnlineOrLastStatus"+ /** Uncaptured. `xwa2_newsletter`. */+ const val OP_NEWSLETTER = "NewsletterQuery"+ /** Uncaptured. `xwa2_newsletter_join_v2`. */+ const val OP_NEWSLETTER_JOIN_V2 = "NewsletterJoinV2"+ /** Uncaptured. `xwa2_newsletter_leave_v2`. */+ const val OP_NEWSLETTER_LEAVE_V2 = "NewsletterLeaveV2"+ /** Uncaptured. `xwa2_get_messaging_keys`. */+ const val OP_GET_MESSAGING_KEYS = "GetMessagingKeys"+ /** Uncaptured. `xwa2_set_messaging_keys`. */+ const val OP_SET_MESSAGING_KEYS = "SetMessagingKeys"++ private val json = Json { encodeDefaults = true }++ // ============================================================ Groups (§8.1)++ /** `xwa2_group_query_by_id` — read a group's metadata/participants over MEX. */+ suspend fun groupQueryById(context: Context, groupJid: String, queryContext: String = "INTERACTIVE"): MexResult =+ WhatsAppMex.call(context, OP_GROUP_QUERY, buildGroupQueryByIdVariables(groupJid, queryContext), "get")++ /** `xwa2_group_query_participating_groups` — groups the (optional) user participates in. */+ suspend fun groupParticipatingGroups(context: Context, userJid: String? = null): MexResult =+ WhatsAppMex.call(context, OP_GROUP_PARTICIPATING, buildParticipatingGroupsVariables(userJid), "get")++ /** `xwa2_group_batch_query_by_id` — batch group metadata read. */+ suspend fun groupBatchQueryById(context: Context, groupJids: List<String>, queryContext: String = "INTERACTIVE"): MexResult =+ WhatsAppMex.call(context, OP_GROUP_BATCH, buildGroupBatchQueryVariables(groupJids, queryContext), "get")++ fun buildGroupQueryByIdVariables(groupJid: String, queryContext: String): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("group_input") {+ put("group_jid", groupJid)+ put("query_context", queryContext)+ }+ },+ )++ fun buildParticipatingGroupsVariables(userJid: String?): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("participating_groups_input") {+ if (userJid != null) put("id", userJid)+ }+ },+ )++ fun buildGroupBatchQueryVariables(groupJids: List<String>, queryContext: String): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("batch_query_input") {+ putJsonArray("groups") {+ groupJids.forEach { jid ->+ addJsonObject {+ put("group_jid", jid)+ put("query_context", queryContext)+ }+ }+ }+ }+ },+ )++ // ============================================================ Contacts (§8.3)++ /** `xwa2_contact_discovery` — resolve raw phone numbers to LIDs. [context] = SEARCH|QR_SCAN. */+ suspend fun contactDiscovery(context: Context, rawPhoneNumbers: List<String>, discoveryContext: String = "SEARCH"): MexResult =+ WhatsAppMex.call(context, OP_CONTACT_DISCOVERY, buildContactDiscoveryVariables(rawPhoneNumbers, discoveryContext), "get")++ /** `xwa2_primary_contacts_full_sync` — single/multi-page primary-contact sync. */+ suspend fun primaryContactsFullSync(+ context: Context,+ rawPhoneNumbers: List<String>,+ sessionId: String,+ pageIndex: Int,+ last: Boolean,+ syncContext: String = "REGISTRATION",+ ): MexResult = WhatsAppMex.call(+ context,+ OP_PRIMARY_CONTACTS_FULL_SYNC,+ buildPrimaryContactsFullSyncVariables(rawPhoneNumbers, sessionId, pageIndex, last, syncContext),+ "set",+ )++ fun buildContactDiscoveryVariables(rawPhoneNumbers: List<String>, discoveryContext: String): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("input") {+ putJsonArray("contacts") {+ rawPhoneNumbers.forEach { pn ->+ addJsonObject { putJsonObject("phone") { put("raw_pn", pn) } }+ }+ }+ put("context", discoveryContext)+ }+ },+ )++ fun buildPrimaryContactsFullSyncVariables(+ rawPhoneNumbers: List<String>,+ sessionId: String,+ pageIndex: Int,+ last: Boolean,+ syncContext: String,+ ): String = json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("input") {+ putJsonArray("primary_contacts") {+ rawPhoneNumbers.forEach { pn ->+ addJsonObject { putJsonObject("phone") { put("raw_pn", pn) } }+ }+ }+ putJsonObject("cursor") {+ put("session_id", sessionId)+ put("page_index", pageIndex)+ put("last", last)+ }+ put("context", syncContext)+ }+ },+ )++ // ============================================================ Username (§8.11)++ /** `xwa2_username_get` — the account's current username (no args). */+ suspend fun usernameGet(context: Context): MexResult =+ WhatsAppMex.call(context, OP_USERNAME_GET, "{}", "get")++ /** `xwa2_username_check` — availability check with optional suggestions. */+ suspend fun usernameCheck(+ context: Context,+ username: String,+ includeSuggestions: Boolean = true,+ source: String = "USER_INPUT",+ sessionId: String? = null,+ ): MexResult = WhatsAppMex.call(+ context,+ OP_USERNAME_CHECK,+ buildUsernameCheckVariables(username, includeSuggestions, source, sessionId),+ "get",+ )++ /** `xwa2_username_set` — claim a username. [pin] is 6 uppercase alphanum (teen accounts require it). */+ suspend fun usernameSet(+ context: Context,+ username: String,+ pin: String? = null,+ source: String = "USER_INPUT",+ sessionId: String? = null,+ ): MexResult = WhatsAppMex.call(+ context,+ OP_USERNAME_SET,+ buildUsernameSetVariables(username, pin, source, sessionId),+ "set",+ )++ fun buildUsernameCheckVariables(username: String, includeSuggestions: Boolean, source: String, sessionId: String?): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ put("username", username)+ put("include_suggestions", includeSuggestions)+ put("source", source)+ if (sessionId != null) put("session_id", sessionId)+ },+ )++ fun buildUsernameSetVariables(username: String, pin: String?, source: String, sessionId: String?): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ put("username", username)+ put("source", source)+ if (pin != null) put("pin", pin)+ if (sessionId != null) put("session_id", sessionId)+ },+ )++ // ============================================================ Blocklist (§8.8)++ /** `xwa2_blocklist_get` — the account blocklist; [dhash] is the previously-returned delta hash. */+ suspend fun blocklistGet(context: Context, dhash: String? = null): MexResult =+ WhatsAppMex.call(context, OP_BLOCKLIST_GET, buildBlocklistGetVariables(dhash), "get")++ /**+ * `xwa2_update_blocklist_lid` — block/unblock a LID user. [identifierKey] is exactly one of+ * `pn_jid|username|display_name|guest_name` (per XWA2BlockedUserIdentifierLidInput). [action] =+ * BLOCK|UNBLOCK.+ */+ suspend fun updateBlocklistLid(+ context: Context,+ userLid: String,+ identifierKey: String,+ identifierValue: String,+ action: String,+ dhash: String? = null,+ ): MexResult = WhatsAppMex.call(+ context,+ OP_BLOCKLIST_UPDATE_LID,+ buildUpdateBlocklistLidVariables(userLid, identifierKey, identifierValue, action, dhash),+ "set",+ )++ fun buildBlocklistGetVariables(dhash: String?): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject { if (dhash != null) put("dhash", dhash) },+ )++ fun buildUpdateBlocklistLidVariables(+ userLid: String,+ identifierKey: String,+ identifierValue: String,+ action: String,+ dhash: String?,+ ): String = json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("block_input") {+ put("user", userLid)+ putJsonObject("identifier") { put(identifierKey, identifierValue) }+ put("action", action)+ if (dhash != null) put("dhash", dhash)+ }+ },+ )++ // ============================================================ Presence (§8.6)++ /**+ * `xwa2_presence_data_platform_get_online_or_last_status` — online/last-seen for LID users.+ * [lastActiveFilter] = LAST_MINUTE|LAST_HOUR|LAST_DAY (optional).+ */+ suspend fun getOnlineOrLastStatus(context: Context, lidJids: List<String>, lastActiveFilter: String? = null): MexResult =+ WhatsAppMex.call(context, OP_PRESENCE_ONLINE_OR_LAST, buildOnlineOrLastStatusVariables(lidJids, lastActiveFilter), "get")++ fun buildOnlineOrLastStatusVariables(lidJids: List<String>, lastActiveFilter: String?): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("get_online_or_last_status_input") {+ putJsonArray("online_or_last_status_input") {+ lidJids.forEach { jid -> addJsonObject { put("jid", jid) } }+ }+ if (lastActiveFilter != null) put("last_active_filter", lastActiveFilter)+ }+ },+ )++ // ============================================================ Newsletters (§8.4)++ /** `xwa2_newsletter` — read a channel. [keyType] = JID|INVITE; [viewRole] = SUBSCRIBER|GUEST|ADMIN. */+ suspend fun newsletter(context: Context, key: String, keyType: String = "JID", viewRole: String? = null): MexResult =+ WhatsAppMex.call(context, OP_NEWSLETTER, buildNewsletterVariables(key, keyType, viewRole), "get")++ /** `xwa2_newsletter_join_v2`. */+ suspend fun newsletterJoinV2(context: Context, newsletterId: String): MexResult =+ WhatsAppMex.call(context, OP_NEWSLETTER_JOIN_V2, buildNewsletterIdVariables(newsletterId), "set")++ /** `xwa2_newsletter_leave_v2`. */+ suspend fun newsletterLeaveV2(context: Context, newsletterId: String): MexResult =+ WhatsAppMex.call(context, OP_NEWSLETTER_LEAVE_V2, buildNewsletterIdVariables(newsletterId), "set")++ fun buildNewsletterVariables(key: String, keyType: String, viewRole: String?): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("input") {+ put("key", key)+ put("type", keyType)+ if (viewRole != null) put("view_role", viewRole)+ }+ },+ )++ fun buildNewsletterIdVariables(newsletterId: String): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject { put("newsletter_id", newsletterId) },+ )++ // ============================================================ Messaging keys (§8.2)++ /** `xwa2_get_messaging_keys` — fetch Signal prekey bundles for the given interop user JIDs. */+ suspend fun getMessagingKeys(context: Context, userJids: List<String>): MexResult =+ WhatsAppMex.call(context, OP_GET_MESSAGING_KEYS, buildGetMessagingKeysVariables(userJids), "get")++ fun buildGetMessagingKeysVariables(userJids: List<String>): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("input") {+ putJsonArray("users") { userJids.forEach { add(it) } }+ }+ },+ )++ /**+ * `xwa2_set_messaging_keys` — publish our identity + signed prekey + a batch of freshly-minted+ * one-time prekeys (§8.2). The one-time prekeys are minted via+ * [RustWhatsAppCrypto.generateKeyPairSplit] and persisted into the `whatsapp_e2e_pre_keys` Room+ * table (private||public, unuploaded) so what we upload matches our local store. All binary is+ * standard Base64 (Argo BYTES over the JSON shim).+ *+ * Requires persisted [WhatsAppAuthData]; returns a `no_auth` transport failure otherwise.+ */+ suspend fun setMessagingKeys(context: Context, oneTimePreKeyCount: Int = 10): MexResult {+ val auth = WhatsAppAuthData.load(context)+ ?: return MexResult.transport("no_auth")+ val db = WhatsAppDatabase.getDatabase(context)++ val identity = decodeStd(auth.identityPublicKey)+ val skeyValue = decodeStd(auth.signedPreKeyPublic)+ val skeySignature = decodeStd(auth.signedPreKeySignature)++ // Mint one-time prekeys, continuing ids after the current max, and persist them.+ val maxId = db.e2ePreKeyDao().getMaxId()+ val minted = ArrayList<Pair<Int, ByteArray>>(oneTimePreKeyCount)+ val entities = ArrayList<WhatsAppE2EPreKey>(oneTimePreKeyCount)+ for (i in 1..oneTimePreKeyCount) {+ val id = maxId + i+ val kp = RustWhatsAppCrypto.generateKeyPairSplit()+ entities.add(WhatsAppE2EPreKey(id, kp.privateKey + kp.publicKey, uploaded = false))+ minted.add(id to kp.publicKey)+ }+ db.e2ePreKeyDao().insertAll(entities)+ WhatsAppDiag.log(TAG, "setMessagingKeys: minted ${minted.size} one-time prekeys (ids ${maxId + 1}..${maxId + minted.size})")++ val variables = buildSetMessagingKeysVariables(+ identity = identity,+ skeyId = auth.signedPreKeyId,+ skeyValue = skeyValue,+ skeySignature = skeySignature,+ prekeys = minted,+ )+ return WhatsAppMex.call(context, OP_SET_MESSAGING_KEYS, variables, "set")+ }++ /**+ * Pure builder for the `xwa2_set_messaging_keys` `variables` (§8.2). Binary fields are standard+ * Base64; ids are 3-byte big-endian (skey/prekey id space), `type` is Base64 of `0x05`.+ */+ fun buildSetMessagingKeysVariables(+ identity: ByteArray,+ skeyId: Int,+ skeyValue: ByteArray,+ skeySignature: ByteArray,+ prekeys: List<Pair<Int, ByteArray>>,+ ): String = json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("input") {+ put("type", b64(byteArrayOf(0x05)))+ put("identity", b64(identity))+ putJsonObject("skey") {+ put("id", b64(int3BE(skeyId)))+ put("value", b64(skeyValue))+ put("signature", b64(skeySignature))+ }+ putJsonArray("prekeys") {+ prekeys.forEach { (id, value) ->+ addJsonObject {+ put("id", b64(int3BE(id)))+ put("value", b64(value))+ }+ }+ }+ }+ },+ )++ // -- encoding helpers ------------------------------------------------------------------------++ /** Standard Base64 (with padding), JVM-pure so the builders are unit-testable off-device. */+ private fun b64(bytes: ByteArray): String = JavaBase64.getEncoder().encodeToString(bytes)++ /** Decode a STANDARD-base64 field stored in [WhatsAppAuthData] (android.util.Base64.NO_WRAP). */+ private fun decodeStd(s: String): ByteArray = AndroidBase64.decode(s, AndroidBase64.NO_WRAP)++ /** 3-byte big-endian encoding of a prekey/skey id (matches the classic wire encoding). */+ private fun int3BE(id: Int): ByteArray = byteArrayOf(+ (id ushr 16).toByte(),+ (id ushr 8).toByte(),+ id.toByte(),+ )+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppWwwGraphQlClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppWwwGraphQlClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppWwwGraphQlClient.ktnew file mode 100644index 0000000000..14829c7c6a--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppWwwGraphQlClient.kt@@ -0,0 +1,64 @@+package com.vayunmathur.communicate.data.whatsapp.mex++import android.content.Context+import android.os.Build+import com.vayunmathur.communicate.data.whatsapp.WhatsAppDiag+import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol+import com.vayunmathur.library.network.NetworkClient++/**+ * WWW GraphQL HTTP transport — the fallback used when the XMPP/`w:mex` socket is not connected+ * (w2.md §4.1 / §5.3). Posts the persisted-query envelope to `graph.whatsapp.com/graphql` over the+ * repo's own HTTP stack ([NetworkClient], no OkHttp).+ *+ * The body is built JVM-pure by [MexEnvelope.buildWwwBody]:+ * `{"access_token":…,"doc_id":<int64>,"lang":"en_US","Content-Type":"application/json","variables":{…}}`.+ * Unauthenticated calls use the consumer client token from §4.1; there is no `Authorization` header+ * (auth lives in the body).+ *+ * Dev-only, reached via [WhatsAppMex]; gated at the repository layer by `WhatsAppFeature.enabled`.+ */+object WhatsAppWwwGraphQlClient {++ private const val TAG = "WAMex"+ private const val URL = "https://graph.whatsapp.com/graphql"++ /** Consumer/wearos/orbit/vr client token (w2.md §4.1 `GraphqlRequestBase.kt:618-636`). */+ private const val CLIENT_TOKEN = "WA|1015890928915437|3201f239340c1c8ec6262a6dad04200e"++ /**+ * POST the given [docId] + [variablesJson] to the WWW GraphQL endpoint and parse the+ * `{"data":…,"errors":…}` envelope into a [MexResult]. Transport failures (network, non-2xx)+ * surface as [MexResult.transport].+ */+ suspend fun post(context: Context, docId: String, variablesJson: String): MexResult {+ val body = MexEnvelope.buildWwwBody(CLIENT_TOKEN, docId, variablesJson)+ val headers = mapOf(+ "Content-Type" to "application/json",+ "User-Agent" to userAgent(),+ )+ return try {+ val resp = NetworkClient.performRequest(+ url = URL,+ method = "POST",+ headers = headers,+ body = body,+ useSystemTrust = true,+ )+ if (!resp.isSuccess) {+ WhatsAppDiag.log(TAG, "www[$docId]: HTTP ${resp.status}: ${resp.body.take(200)}")+ return MexResult.transport("http:${resp.status}")+ }+ MexResult.fromEnvelope(resp.body)+ } catch (t: Throwable) {+ WhatsAppDiag.log(TAG, "www[$docId]: request failed: ${t.message}")+ MexResult.transport("network:${t.message}")+ }+ }++ /** WhatsApp/<ver> Android/<osrel> Device/<manufacturer>-<model> — same shape as registration. */+ private fun userAgent(): String {+ val device = "${Build.MANUFACTURER}-${Build.MODEL}".replace(' ', '_')+ return "WhatsApp/${WhatsAppProtocol.WA_VERSION_NAME} Android/${Build.VERSION.RELEASE} Device/$device"+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.ktindex 1c10e9e4b8..8bed1f3f66 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt@@ -47,6 +47,36 @@ class RegistrationHttpClient( data class ExistResult(val status: String, val reason: String?, val raw: String) + /** `/v2/consent` — over-18 self-declare / DOB / parent-verification consent (§3.12). */+ data class ConsentResult(+ val status: String, val reason: String?, val pending: String?, val url: String?, val raw: String,+ ) { val ok: Boolean get() = status == "ok" }++ /** `/v2/autoconf` — request the autoconf verifier / attribute list (§3.8). */+ data class AutoconfResult(+ val status: String, val reason: String?, val registerStartMessage: String?, val raw: String,+ ) { val ok: Boolean get() = status == "ok" || status == "sent" }++ /** `/v2/autoconf_verifier` — submit the encrypted verifier data (§3.9). */+ data class AutoconfVerifierResult(val status: String, val reason: String?, val raw: String) {+ val ok: Boolean get() = status == "ok"+ }++ /** `/v2/captcha_verify` — fraud-checkpoint code verification (§3.10). */+ data class CaptchaVerifyResult(+ val status: String, val reason: String?, val violationType: String?, val appealToken: String?, val raw: String,+ ) { val ok: Boolean get() = status == "verified" }++ /** `/v2/challenge` — email/oauth challenge step (§3.14). */+ data class ChallengeResult(val status: String, val reason: String?, val raw: String) {+ val ok: Boolean get() = status == "ok"+ }++ /** `/v2/client_log` — fire-and-forget onboarding funnel log (§3.6). */+ data class ClientLogResult(val status: String, val raw: String) {+ val ok: Boolean get() = status == "ok"+ }+ // ------------------------------------------------------------------ endpoints /** POST `/v2/code` — request an OTP. Generates + persists fresh key material first. */@@ -131,6 +161,177 @@ class RegistrationHttpClient( return ExistResult(j.optString("status", "error"), j.optStringOrNull("reason"), body) } + /**+ * POST `/v2/consent` (§3.12). Records the age/consent decision. Needs the E2E encryption bundle+ * (`/v2/consent` is in the proto-2.0 encryption list, §2.1). [consentContext] is one of+ * `app_store_age|dob|parent_verification|consent`.+ */+ suspend fun consent(+ cc: String,+ number: String,+ consentContext: String,+ dob: String? = null,+ ageLowerBound: Int? = null,+ consentDecision: String? = null,+ consentId: String? = null,+ consentVersion: String? = null,+ securityCode: String? = null,+ ): ConsentResult {+ val auth = WhatsAppAuthData.load(context)+ val p = RegParams()+ p.a01("cc", cc)+ p.a01("in", number)+ p.addCommon()+ p.addDevice()+ if (auth != null) p.bundle(RegistrationKeys.bundleFields(auth))+ p.a01("context", consentContext)+ p.a02("dob", dob)+ if (ageLowerBound != null) p.a01("age_lower_bound", ageLowerBound.toString())+ p.a02("consent_decision", consentDecision)+ p.a02("consent_id", consentId)+ p.a02("consent_version", consentVersion)+ p.a02("security_code", securityCode)+ val body = send("consent", p)+ val j = parse(body)+ return ConsentResult(+ status = j.optString("status", "error"),+ reason = j.optStringOrNull("reason"),+ pending = j.optStringOrNull("pending"),+ url = j.optStringOrNull("url"),+ raw = body,+ )+ }++ /**+ * POST `/v2/autoconf` (§3.8). Requests the autoconf verifier / attribute list. No E2E bundle+ * (autoconf is not in the §2.1 encryption list). [consent] is `1` or `2`.+ */+ suspend fun autoconf(+ cc: String,+ number: String,+ consent: Int,+ clientCapabilities: String? = null,+ consentShown: Boolean,+ createVerifier: Boolean,+ ): AutoconfResult {+ val p = RegParams()+ p.a01("cc", cc)+ p.a01("in", number)+ p.addCommon()+ p.addDevice()+ p.a01("consent", consent.toString())+ p.a02("client_capabilities", clientCapabilities)+ p.a00("consent_shown", consentShown)+ p.a00("create_verifier", createVerifier)+ val body = send("autoconf", p)+ val j = parse(body)+ return AutoconfResult(+ status = j.optString("status", "error"),+ reason = j.optStringOrNull("reason"),+ registerStartMessage = j.optStringOrNull("register_start_message"),+ raw = body,+ )+ }++ /**+ * POST `/v2/autoconf_verifier` (§3.9). Submits the encrypted verifier data.+ * [registrationMethod]: 0 token, 2 wa_old, 3 email, 4 flash, 5 sms.+ */+ suspend fun autoconfVerifier(+ cc: String,+ number: String,+ code: String,+ encryptedVerifierData: String,+ registrationMethod: Int,+ ): AutoconfVerifierResult {+ val p = RegParams()+ p.a01("cc", cc)+ p.a01("in", number)+ p.addCommon()+ p.addDevice()+ p.a01("code", code.filter { it.isDigit() })+ p.a01("encrypted_verifier_data", encryptedVerifierData)+ p.a01("registration_method", registrationMethod.toString())+ val body = send("autoconf_verifier", p)+ val j = parse(body)+ return AutoconfVerifierResult(j.optString("status", "error"), j.optStringOrNull("reason"), body)+ }++ /**+ * POST `/v2/captcha_verify` (§3.10). Verifies a fraud-checkpoint code. Needs only `authkey` from+ * the E2E bundle (per §3.10), not the full `e_*` set.+ */+ suspend fun captchaVerify(cc: String, number: String, fraudCheckpointCode: String): CaptchaVerifyResult {+ val auth = WhatsAppAuthData.load(context)+ val p = RegParams()+ p.a01("cc", cc)+ p.a01("in", number)+ p.addCommon()+ p.addDevice()+ if (auth != null) {+ RegistrationKeys.bundleFields(auth)["authkey"]?.let { p.bundle(mapOf("authkey" to it)) }+ }+ p.a01("fraud_checkpoint_code", fraudCheckpointCode)+ val body = send("captcha_verify", p)+ val j = parse(body)+ return CaptchaVerifyResult(+ status = j.optString("status", "error"),+ reason = j.optStringOrNull("reason"),+ violationType = j.optStringOrNull("violation_type"),+ appealToken = j.optStringOrNull("appeal_token"),+ raw = body,+ )+ }++ /**+ * POST `/v2/challenge` (§3.14). Email/OAuth challenge step. No E2E bundle.+ * [challengeType]: `email_enter|email_verify`.+ */+ suspend fun challenge(+ cc: String,+ number: String,+ challengeType: String,+ email: String? = null,+ oauthToken: String? = null,+ code: String? = null,+ ): ChallengeResult {+ val p = RegParams()+ p.a01("cc", cc)+ p.a01("in", number)+ p.addCommon()+ p.addDevice()+ p.a01("challenge_type", challengeType)+ p.a02("email", email)+ p.a02("oauth_token", oauthToken)+ p.a02("code", code)+ val body = send("challenge", p)+ val j = parse(body)+ return ChallengeResult(j.optString("status", "error"), j.optStringOrNull("reason"), body)+ }++ /**+ * POST `/v2/client_log` (§3.6). Fire-and-forget onboarding funnel log; no encryption/integrity,+ * only `lg,lc,rc` + `cc?/in?` + the error context/type. Always returns `ok` server-side.+ */+ suspend fun clientLog(+ errorContext: String,+ errorType: String,+ cc: String? = null,+ number: String? = null,+ ): ClientLogResult {+ val p = RegParams()+ p.a02("cc", cc)+ p.a02("in", number)+ p.a01("lg", context.resources.configuration.locales[0].language.ifEmpty { "en" })+ p.a01("lc", context.resources.configuration.locales[0].country.ifEmpty { "US" })+ p.a01("rc", "0")+ p.a01("client_error_context", errorContext)+ p.a01("client_error_type", errorType)+ val body = send("client_log", p)+ val j = parse(body)+ return ClientLogResult(j.optString("status", "error"), body)+ }+ // ------------------------------------------------------------------ internals private fun finalizeRegister(body: String, auth: WhatsAppAuthData): RegisterResult {
communicate/src/main/proto/whatsapp_e2e.proto
diff --git a/communicate/src/main/proto/whatsapp_e2e.proto b/communicate/src/main/proto/whatsapp_e2e.protoindex adc5d755e8..161a33e534 100644--- a/communicate/src/main/proto/whatsapp_e2e.proto+++ b/communicate/src/main/proto/whatsapp_e2e.proto@@ -49,6 +49,11 @@ message Message { optional DeviceSentMessage deviceSentMessage = 31; optional MessageContextInfo messageContextInfo = 35; optional FutureProofMessage editedMessage = 58;+ // View-once wrappers (media that can be opened once). Ref WAWebProtobufsE2E.Message+ // viewOnceMessage / viewOnceMessageV2 / viewOnceMessageV2Extension.+ optional FutureProofMessage viewOnceMessage = 28;+ optional FutureProofMessage viewOnceMessageV2 = 78;+ optional FutureProofMessage viewOnceMessageV2Extension = 79; } message ExtendedTextMessage {
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/MexEnvelopeTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/MexEnvelopeTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/MexEnvelopeTest.ktnew file mode 100644index 0000000000..0c56f31fb9--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/MexEnvelopeTest.kt@@ -0,0 +1,33 @@+package com.vayunmathur.communicate.whatsapp++import com.vayunmathur.communicate.data.whatsapp.mex.MexEnvelope+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Asserts the MEX-over-XMPP `<query>` envelope shape (w2.md §5.2):+ * `{"queryId":"<docId>","variables":{…}}`. Pure kotlinx — no Android/org.json.+ */+class MexEnvelopeTest {++ @Test+ fun buildQueryJson_wrapsVariablesWithStringQueryId() {+ val out = MexEnvelope.buildQueryJson("27462649126753603", """{"group_input":{"group_jid":"[email protected]"}}""")+ assertEquals(+ """{"queryId":"27462649126753603","variables":{"group_input":{"group_jid":"[email protected]"}}}""",+ out,+ )+ }++ @Test+ fun buildQueryJson_blankVariablesBecomesEmptyObject() {+ val out = MexEnvelope.buildQueryJson("123", "")+ assertEquals("""{"queryId":"123","variables":{}}""", out)+ }++ @Test+ fun buildQueryJson_malformedVariablesFallsBackToEmptyObject() {+ val out = MexEnvelope.buildQueryJson("123", "not json")+ assertEquals("""{"queryId":"123","variables":{}}""", out)+ }+}
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/MexPersistedQueryProviderTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/MexPersistedQueryProviderTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/MexPersistedQueryProviderTest.ktnew file mode 100644index 0000000000..8d08db2fd0--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/MexPersistedQueryProviderTest.kt@@ -0,0 +1,33 @@+package com.vayunmathur.communicate.whatsapp++import com.vayunmathur.communicate.data.whatsapp.mex.MexPersistedQueryProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * Asserts the persist-ids JSON parser (w2.md §5.5 shape `{"version":1,"data":{name:docId}}`).+ * Pure kotlinx — no Android assets needed.+ */+class MexPersistedQueryProviderTest {++ @Test+ fun parsePersistIds_readsOperationNameToDocId() {+ val map = MexPersistedQueryProvider.parsePersistIds(+ """{"version":1,"data":{"QueryGroupInfo":"27462649126753603","UsernameSetMutation":"7225825540870559"}}""",+ )+ assertEquals("27462649126753603", map["QueryGroupInfo"])+ assertEquals("7225825540870559", map["UsernameSetMutation"])+ assertNull(map["NotAnOp"])+ }++ @Test+ fun parsePersistIds_emptyDataYieldsEmptyMap() {+ assertEquals(emptyMap(), MexPersistedQueryProvider.parsePersistIds("""{"version":1,"data":{}}"""))+ }++ @Test+ fun parsePersistIds_malformedYieldsEmptyMap() {+ assertEquals(emptyMap(), MexPersistedQueryProvider.parsePersistIds("not json at all"))+ }+}
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppMexOpsVariablesTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppMexOpsVariablesTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppMexOpsVariablesTest.ktnew file mode 100644index 0000000000..ec9fc627b3--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppMexOpsVariablesTest.kt@@ -0,0 +1,69 @@+package com.vayunmathur.communicate.whatsapp++import com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps+import java.util.Base64+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Asserts a representative set of `xwa2_*` `variables` builders match the w2.md §8 JSON shapes.+ * Pure — the builders use java.util.Base64, so no Android runtime is required.+ */+class WhatsAppMexOpsVariablesTest {++ @Test+ fun groupQueryByIdVariables_usesGroupInputArg() {+ assertEquals(+ """{"group_input":{"group_jid":"[email protected]","query_context":"INTERACTIVE"}}""",+ WhatsAppMexOps.buildGroupQueryByIdVariables("[email protected]", "INTERACTIVE"),+ )+ }++ @Test+ fun usernameSetVariables_omitsNullPinAndSession() {+ assertEquals(+ """{"username":"johndoe","source":"USER_INPUT","pin":"ABC123"}""",+ WhatsAppMexOps.buildUsernameSetVariables("johndoe", "ABC123", "USER_INPUT", null),+ )+ }++ @Test+ fun contactDiscoveryVariables_matchesSection83Shape() {+ assertEquals(+ """{"input":{"contacts":[{"phone":{"raw_pn":"+15551234567"}}],"context":"SEARCH"}}""",+ WhatsAppMexOps.buildContactDiscoveryVariables(listOf("+15551234567"), "SEARCH"),+ )+ }++ @Test+ fun setMessagingKeysVariables_matchesSection82Shape() {+ val identity = ByteArray(32) { 1 }+ val skeyValue = ByteArray(32) { 2 }+ val skeySignature = ByteArray(64) { 3 }+ val prekeyValue = ByteArray(32) { 4 }++ val enc = Base64.getEncoder()+ val expectedType = enc.encodeToString(byteArrayOf(0x05))+ val expectedIdentity = enc.encodeToString(identity)+ val expectedSkeyId = enc.encodeToString(byteArrayOf(0, 0, 1))+ val expectedSkeyValue = enc.encodeToString(skeyValue)+ val expectedSkeySig = enc.encodeToString(skeySignature)+ val expectedPrekeyId = enc.encodeToString(byteArrayOf(0, 0, 7))+ val expectedPrekeyValue = enc.encodeToString(prekeyValue)++ val out = WhatsAppMexOps.buildSetMessagingKeysVariables(+ identity = identity,+ skeyId = 1,+ skeyValue = skeyValue,+ skeySignature = skeySignature,+ prekeys = listOf(7 to prekeyValue),+ )++ assertEquals(+ """{"input":{"type":"$expectedType","identity":"$expectedIdentity",""" ++ """"skey":{"id":"$expectedSkeyId","value":"$expectedSkeyValue","signature":"$expectedSkeySig"},""" ++ """"prekeys":[{"id":"$expectedPrekeyId","value":"$expectedPrekeyValue"}]}}""",+ out,+ )+ }+}
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppSendProtoTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppSendProtoTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppSendProtoTest.ktnew file mode 100644index 0000000000..d81b4ecde9--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppSendProtoTest.kt@@ -0,0 +1,156 @@+package com.vayunmathur.communicate.whatsapp++import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol+import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Wire-shape assertions for the messaging-hardening send builders (Phase A 1a-1c). These are the+ * proto builders that were previously emitting plaintext `<enc>` nodes; they now return E2E+ * [WhatsAppE2EProto.Message] protos so the caller routes them through the Signal fan-out. Pure+ * (protobuf-java only), so no Android runtime is required.+ */+class WhatsAppSendProtoTest {++ @Test+ fun editProto_setsMessageEditProtocolMessage() {+ val msg = WhatsAppProtocol.buildEditProto("[email protected]", "TARGET1", "new text")+ assertTrue(msg.hasProtocolMessage())+ val pm = msg.protocolMessage+ assertEquals(WhatsAppE2EProto.ProtocolMessage.Type.MESSAGE_EDIT, pm.type)+ assertEquals("TARGET1", pm.key.id)+ assertTrue(pm.key.fromMe)+ assertEquals("[email protected]", pm.key.remoteJid)+ assertEquals("new text", pm.editedMessage.conversation)+ assertTrue(pm.timestampMs > 0)+ }++ @Test+ fun revokeProto_ownMessage_fromMeNoParticipant() {+ val msg = WhatsAppProtocol.buildRevokeProto(+ chatJid = "[email protected]",+ senderJid = "[email protected]",+ targetMessageId = "T1",+ ownJid = "[email protected]",+ )+ val pm = msg.protocolMessage+ assertEquals(WhatsAppE2EProto.ProtocolMessage.Type.REVOKE, pm.type)+ assertTrue(pm.key.fromMe)+ assertFalse(pm.key.hasParticipant())+ assertTrue(WhatsAppProtocol.isRevokeFromMe("[email protected]", "[email protected]"))+ assertTrue(WhatsAppProtocol.isRevokeFromMe("", "[email protected]"))+ }++ @Test+ fun revokeProto_groupOtherSender_setsParticipant() {+ val msg = WhatsAppProtocol.buildRevokeProto(+ chatJid = "[email protected]",+ senderJid = "[email protected]",+ targetMessageId = "T2",+ ownJid = "[email protected]",+ )+ val pm = msg.protocolMessage+ assertFalse(pm.key.fromMe)+ assertEquals("[email protected]", pm.key.participant)+ assertFalse(WhatsAppProtocol.isRevokeFromMe("[email protected]", "[email protected]"))+ }++ @Test+ fun contactProto_setsDisplayNameAndVcard() {+ val msg = WhatsAppProtocol.buildContactProto("Alice", "BEGIN:VCARD\nEND:VCARD")+ assertTrue(msg.hasContactMessage())+ assertEquals("Alice", msg.contactMessage.displayName)+ assertEquals("BEGIN:VCARD\nEND:VCARD", msg.contactMessage.vcard)+ }++ @Test+ fun disappearingTimerProto_setsEphemeralSetting() {+ val msg = WhatsAppProtocol.buildDisappearingTimerProto(604800L)+ val pm = msg.protocolMessage+ assertEquals(WhatsAppE2EProto.ProtocolMessage.Type.EPHEMERAL_SETTING, pm.type)+ assertEquals(604800, pm.ephemeralExpiration)+ }++ @Test+ fun textProto_plain_isConversation() {+ val msg = WhatsAppProtocol.buildTextProto("hello")+ assertTrue(msg.hasConversation())+ assertEquals("hello", msg.conversation)+ assertFalse(msg.hasExtendedTextMessage())+ }++ @Test+ fun textProto_withMentions_usesExtendedTextWithContextInfo() {+ val msg = WhatsAppProtocol.buildTextProto(+ "hi @alice",+ mentionedJids = listOf("[email protected]"),+ )+ assertTrue(msg.hasExtendedTextMessage())+ val ext = msg.extendedTextMessage+ assertEquals("hi @alice", ext.text)+ assertEquals(listOf("[email protected]"), ext.contextInfo.mentionedJidList)+ }++ @Test+ fun textProto_withQuotedReply_setsStanzaIdAndParticipant() {+ val quoted = WhatsAppProtocol.QuotedContext(+ stanzaId = "QID",+ participant = "[email protected]",+ quotedMessage = WhatsAppProtocol.buildConversationMessage("original"),+ )+ val msg = WhatsAppProtocol.buildTextProto("reply", quoted = quoted)+ val ctx = msg.extendedTextMessage.contextInfo+ assertEquals("QID", ctx.stanzaId)+ assertEquals("[email protected]", ctx.participant)+ assertEquals("original", ctx.quotedMessage.conversation)+ }++ @Test+ fun textProto_withLinkPreview_setsPreviewFields() {+ val preview = WhatsAppProtocol.LinkPreview(+ matchedText = "https://example.com",+ canonicalUrl = "https://example.com/",+ title = "Example",+ description = "An example",+ )+ val msg = WhatsAppProtocol.buildTextProto("see https://example.com", linkPreview = preview)+ val ext = msg.extendedTextMessage+ assertEquals("https://example.com", ext.matchedText)+ assertEquals("https://example.com/", ext.canonicalUrl)+ assertEquals("Example", ext.title)+ assertEquals("An example", ext.description)+ }++ @Test+ fun buildContextInfo_returnsNullWhenEmpty() {+ assertNull(WhatsAppProtocol.buildContextInfo())+ }++ @Test+ fun unwrapViewOnce_v2_returnsInnerAndTypesAsImage() {+ val image = WhatsAppE2EProto.Message.newBuilder()+ .setImageMessage(+ WhatsAppE2EProto.ImageMessage.newBuilder().setMimetype("image/jpeg"),+ )+ .build()+ val wrapped = WhatsAppE2EProto.Message.newBuilder()+ .setViewOnceMessageV2(+ WhatsAppE2EProto.FutureProofMessage.newBuilder().setMessage(image),+ )+ .build()++ val inner = WhatsAppProtocol.unwrapViewOnce(wrapped)+ assertTrue(inner != null && inner.hasImageMessage())+ assertEquals("image image/jpeg", WhatsAppProtocol.getMessageType(wrapped))+ }++ @Test+ fun unwrapViewOnce_nonWrapper_returnsNull() {+ val plain = WhatsAppProtocol.buildConversationMessage("hi")+ assertNull(WhatsAppProtocol.unwrapViewOnce(plain))+ }+}
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WwwGraphQlBodyTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WwwGraphQlBodyTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WwwGraphQlBodyTest.ktnew file mode 100644index 0000000000..1fe9d89c7d--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WwwGraphQlBodyTest.kt@@ -0,0 +1,36 @@+package com.vayunmathur.communicate.whatsapp++import com.vayunmathur.communicate.data.whatsapp.mex.MexEnvelope+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Asserts the WWW GraphQL HTTP body shape (w2.md §4.1 / §5.3): `access_token` string, `doc_id` as a+ * JSON **number**, `lang`, the literal `Content-Type` JSON key, and raw `variables`.+ */+class WwwGraphQlBodyTest {++ @Test+ fun buildWwwBody_matchesDocumentedEnvelope() {+ val out = MexEnvelope.buildWwwBody(TOKEN, "27056625294008854", """{"input":{"key":"1@newsletter"}}""")+ assertEquals(+ """{"access_token":"$TOKEN","doc_id":27056625294008854,"lang":"en_US",""" ++ """"Content-Type":"application/json","variables":{"input":{"key":"1@newsletter"}}}""",+ out,+ )+ }++ @Test+ fun buildWwwBody_nonNumericDocIdStaysString() {+ val out = MexEnvelope.buildWwwBody(TOKEN, "abc", "{}")+ assertEquals(+ """{"access_token":"$TOKEN","doc_id":"abc","lang":"en_US",""" ++ """"Content-Type":"application/json","variables":{}}""",+ out,+ )+ }++ private companion object {+ const val TOKEN = "WA|1015890928915437|3201f239340c1c8ec6262a6dad04200e"+ }+}