Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / mex / WhatsAppMexOps.kt

WhatsAppMexOps.kt274 lines · 12.6 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp.mex
2
3import android.content.Context
4import android.util.Base64 as AndroidBase64
5import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData
6import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase
7import com.vayunmathur.communicate.data.whatsapp.WhatsAppDiag
8import com.vayunmathur.communicate.data.whatsapp.WhatsAppE2EPreKey
9import com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto
10import kotlinx.serialization.json.Json
11import kotlinx.serialization.json.JsonObject
12import kotlinx.serialization.json.add
13import kotlinx.serialization.json.addJsonObject
14import kotlinx.serialization.json.buildJsonObject
15import kotlinx.serialization.json.put
16import kotlinx.serialization.json.putJsonArray
17import kotlinx.serialization.json.putJsonObject
18
19/**
20 * Typed, bounded catalog of `xwa2_*` MEX operations (w2.md §8). Each entry pairs a **GraphQL
21 * operation name** (the persist-ids JSON key — documented in KDoc so a dev knows what to capture)
22 * with a JVM-pure `variables` builder, then delegates to the [WhatsAppMex] router.
23 *
24 * `variables` shapes follow the SDL argument names from w2.md §8.0 ("single `variables` map keyed by
25 * arg name"). JIDs and `XWA2Binary` are transmitted as Base64 (Argo BYTES over the JSON shim).
26 *
27 * Only the operations with a real committed doc_id (see `mex_persist_ids.json`, §5.5) will actually
28 * round-trip today — `QueryGroupInfo`, `ContactUserInfoQuery`, `UsernameSetMutation`; the rest are
29 * callable and return a typed `no_persisted_id:<op>` until a captured id is dropped into the JSON.
30 *
31 * Dev-only: reached via `CommunicateRepository`, gated on `WhatsAppFeature.enabled`.
32 */
33object WhatsAppMexOps {
34
35 private const val TAG = "WAMex"
36
37 // -- GraphQL operation names (persist-ids JSON keys) ---------------------------------------
38
39 // Seeded id 27462649126753603. `query
40 // QueryGroupInfo($group_input:XWA2GroupQueryInput!){xwa2_group_query_by_id…}`.
41 const val OP_GROUP_QUERY = "QueryGroupInfo"
42 /** Uncaptured. `xwa2_group_query_participating_groups`. */
43 const val OP_GROUP_PARTICIPATING = "QueryParticipatingGroups"
44 /** Uncaptured. `xwa2_group_batch_query_by_id`. */
45 const val OP_GROUP_BATCH = "QueryGroupInfoBatch"
46 /** Seeded id 27056625294008854 (nearest known contact op). `xwa2_contact_discovery`. */
47 const val OP_CONTACT_DISCOVERY = "ContactUserInfoQuery"
48 /** Uncaptured. `xwa2_primary_contacts_full_sync`. */
49 const val OP_PRIMARY_CONTACTS_FULL_SYNC = "PrimaryContactsFullSync"
50 /** Uncaptured. `xwa2_username_get`. */
51 const val OP_USERNAME_GET = "UsernameGet"
52 /** Uncaptured. `xwa2_username_check`. */
53 const val OP_USERNAME_CHECK = "UsernameCheck"
54 /** Seeded id 7225825540870559. `xwa2_username_set`. */
55 const val OP_USERNAME_SET = "UsernameSetMutation"
56 /** Uncaptured. `xwa2_blocklist_get`. */
57 const val OP_BLOCKLIST_GET = "BlocklistGet"
58 /** Uncaptured. `xwa2_update_blocklist_lid`. */
59 const val OP_BLOCKLIST_UPDATE_LID = "UpdateBlocklistLid"
60 /** Uncaptured. `xwa2_presence_data_platform_get_online_or_last_status`. */
61 const val OP_PRESENCE_ONLINE_OR_LAST = "GetOnlineOrLastStatus"
62 /** Uncaptured. `xwa2_newsletter`. */
63 const val OP_NEWSLETTER = "NewsletterQuery"
64 /** Uncaptured. `xwa2_newsletter_join_v2`. */
65 const val OP_NEWSLETTER_JOIN_V2 = "NewsletterJoinV2"
66 /** Uncaptured. `xwa2_newsletter_leave_v2`. */
67 const val OP_NEWSLETTER_LEAVE_V2 = "NewsletterLeaveV2"
68 /** Uncaptured. `xwa2_get_messaging_keys`. */
69 const val OP_GET_MESSAGING_KEYS = "GetMessagingKeys"
70 /** Uncaptured. `xwa2_set_messaging_keys`. */
71 const val OP_SET_MESSAGING_KEYS = "SetMessagingKeys"
72
73 private val json = Json { encodeDefaults = true }
74
75 // ============================================================ Groups (§8.1)
76
77 /** `xwa2_group_query_by_id` — read a group's metadata/participants over MEX. */
78 suspend fun groupQueryById(context: Context, groupJid: String, queryContext: String = "INTERACTIVE"): MexResult =
79 WhatsAppMex.call(
80 context, OP_GROUP_QUERY, WhatsAppMexVariables.buildGroupQueryByIdVariables(groupJid, queryContext), "get")
81
82 /** `xwa2_group_query_participating_groups` — groups the (optional) user participates in. */
83 suspend fun groupParticipatingGroups(context: Context, userJid: String? = null): MexResult =
84 WhatsAppMex.call(
85 context, OP_GROUP_PARTICIPATING, WhatsAppMexVariables.buildParticipatingGroupsVariables(userJid), "get")
86
87 /** `xwa2_group_batch_query_by_id` — batch group metadata read. */
88 suspend fun groupBatchQueryById(
89 context: Context,
90 groupJids: List<String>,
91 queryContext: String = "INTERACTIVE"): MexResult =
92 WhatsAppMex.call(
93 context, OP_GROUP_BATCH, WhatsAppMexVariables.buildGroupBatchQueryVariables(groupJids, queryContext), "get")
94
95 // ============================================================ Contacts (§8.3)
96
97 /** `xwa2_contact_discovery` — resolve raw phone numbers to LIDs. [context] = SEARCH|QR_SCAN. */
98 suspend fun contactDiscovery(
99 context: Context,
100 rawPhoneNumbers: List<String>,
101 discoveryContext: String = "SEARCH"): MexResult =
102 WhatsAppMex.call(
103 context,
104 OP_CONTACT_DISCOVERY,
105 WhatsAppMexVariables.buildContactDiscoveryVariables(rawPhoneNumbers, discoveryContext),
106 "get")
107
108 /** `xwa2_primary_contacts_full_sync` — single/multi-page primary-contact sync. */
109 suspend fun primaryContactsFullSync(
110 context: Context,
111 rawPhoneNumbers: List<String>,
112 sessionId: String,
113 pageIndex: Int,
114 last: Boolean,
115 syncContext: String = "REGISTRATION",
116 ): MexResult = WhatsAppMex.call(
117 context,
118 OP_PRIMARY_CONTACTS_FULL_SYNC,
119 WhatsAppMexVariables.buildPrimaryContactsFullSyncVariables(
120 rawPhoneNumbers, sessionId, pageIndex, last, syncContext),
121 "set",
122 )
123
124 // ============================================================ Username (§8.11)
125
126 /** `xwa2_username_get` — the account's current username (no args). */
127 suspend fun usernameGet(context: Context): MexResult =
128 WhatsAppMex.call(context, OP_USERNAME_GET, "{}", "get")
129
130 /** `xwa2_username_check` — availability check with optional suggestions. */
131 suspend fun usernameCheck(
132 context: Context,
133 username: String,
134 includeSuggestions: Boolean = true,
135 source: String = "USER_INPUT",
136 sessionId: String? = null,
137 ): MexResult = WhatsAppMex.call(
138 context,
139 OP_USERNAME_CHECK,
140 WhatsAppMexVariables.buildUsernameCheckVariables(username, includeSuggestions, source, sessionId),
141 "get",
142 )
143
144 /** `xwa2_username_set` — claim a username. [pin] is 6 uppercase alphanum (teen accounts require it). */
145 suspend fun usernameSet(
146 context: Context,
147 username: String,
148 pin: String? = null,
149 source: String = "USER_INPUT",
150 sessionId: String? = null,
151 ): MexResult = WhatsAppMex.call(
152 context,
153 OP_USERNAME_SET,
154 WhatsAppMexVariables.buildUsernameSetVariables(username, pin, source, sessionId),
155 "set",
156 )
157
158 // ============================================================ Blocklist (§8.8)
159
160 /** `xwa2_blocklist_get` — the account blocklist; [dhash] is the previously-returned delta hash. */
161 suspend fun blocklistGet(context: Context, dhash: String? = null): MexResult =
162 WhatsAppMex.call(context, OP_BLOCKLIST_GET, WhatsAppMexVariables.buildBlocklistGetVariables(dhash), "get")
163
164 /**
165 * `xwa2_update_blocklist_lid` — block/unblock a LID user. [identifierKey] is exactly one of
166 * `pn_jid|username|display_name|guest_name` (per XWA2BlockedUserIdentifierLidInput). [action] =
167 * BLOCK|UNBLOCK.
168 */
169 suspend fun updateBlocklistLid(
170 context: Context,
171 userLid: String,
172 identifierKey: String,
173 identifierValue: String,
174 action: String,
175 dhash: String? = null,
176 ): MexResult = WhatsAppMex.call(
177 context,
178 OP_BLOCKLIST_UPDATE_LID,
179 WhatsAppMexVariables.buildUpdateBlocklistLidVariables(userLid, identifierKey, identifierValue, action, dhash),
180 "set",
181 )
182
183 // ============================================================ Presence (§8.6)
184
185 /**
186 * `xwa2_presence_data_platform_get_online_or_last_status` — online/last-seen for LID users.
187 * [lastActiveFilter] = LAST_MINUTE|LAST_HOUR|LAST_DAY (optional).
188 */
189 suspend fun getOnlineOrLastStatus(
190 context: Context,
191 lidJids: List<String>,
192 lastActiveFilter: String? = null): MexResult =
193 WhatsAppMex.call(
194 context,
195 OP_PRESENCE_ONLINE_OR_LAST,
196 WhatsAppMexVariables.buildOnlineOrLastStatusVariables(lidJids, lastActiveFilter),
197 "get")
198
199 // ============================================================ Newsletters (§8.4)
200
201 /** `xwa2_newsletter` — read a channel. [keyType] = JID|INVITE; [viewRole] = SUBSCRIBER|GUEST|ADMIN. */
202 suspend fun newsletter(
203 context: Context,
204 key: String,
205 keyType: String = "JID",
206 viewRole: String? = null): MexResult =
207 WhatsAppMex.call(
208 context, OP_NEWSLETTER, WhatsAppMexVariables.buildNewsletterVariables(key, keyType, viewRole), "get")
209
210 /** `xwa2_newsletter_join_v2`. */
211 suspend fun newsletterJoinV2(context: Context, newsletterId: String): MexResult =
212 WhatsAppMex.call(
213 context, OP_NEWSLETTER_JOIN_V2, WhatsAppMexVariables.buildNewsletterIdVariables(newsletterId), "set")
214
215 /** `xwa2_newsletter_leave_v2`. */
216 suspend fun newsletterLeaveV2(context: Context, newsletterId: String): MexResult =
217 WhatsAppMex.call(
218 context, OP_NEWSLETTER_LEAVE_V2, WhatsAppMexVariables.buildNewsletterIdVariables(newsletterId), "set")
219
220 // ============================================================ Messaging keys (§8.2)
221
222 /** `xwa2_get_messaging_keys` — fetch Signal prekey bundles for the given interop user JIDs. */
223 suspend fun getMessagingKeys(context: Context, userJids: List<String>): MexResult =
224 WhatsAppMex.call(
225 context, OP_GET_MESSAGING_KEYS, WhatsAppMexVariables.buildGetMessagingKeysVariables(userJids), "get")
226
227 /**
228 * `xwa2_set_messaging_keys` — publish our identity + signed prekey + a batch of freshly-minted
229 * one-time prekeys (§8.2). The one-time prekeys are minted via
230 * [RustWhatsAppCrypto.generateKeyPairSplit] and persisted into the `whatsapp_e2e_pre_keys` Room
231 * table (private||public, unuploaded) so what we upload matches our local store. All binary is
232 * standard Base64 (Argo BYTES over the JSON shim).
233 *
234 * Requires persisted [WhatsAppAuthData]; returns a `no_auth` transport failure otherwise.
235 */
236 suspend fun setMessagingKeys(context: Context, oneTimePreKeyCount: Int = 10): MexResult {
237 val auth = WhatsAppAuthData.load(context)
238 ?: return MexResult.transport("no_auth")
239 val db = WhatsAppDatabase.getDatabase(context)
240
241 val identity = decodeStd(auth.identityPublicKey)
242 val skeyValue = decodeStd(auth.signedPreKeyPublic)
243 val skeySignature = decodeStd(auth.signedPreKeySignature)
244
245 // Mint one-time prekeys, continuing ids after the current max, and persist them.
246 val maxId = db.e2ePreKeyDao().getMaxId()
247 val minted = ArrayList<Pair<Int, ByteArray>>(oneTimePreKeyCount)
248 val entities = ArrayList<WhatsAppE2EPreKey>(oneTimePreKeyCount)
249 for (i in 1..oneTimePreKeyCount) {
250 val id = maxId + i
251 val kp = RustWhatsAppCrypto.generateKeyPairSplit()
252 entities.add(WhatsAppE2EPreKey(id, kp.privateKey + kp.publicKey, uploaded = false))
253 minted.add(id to kp.publicKey)
254 }
255 db.e2ePreKeyDao().insertAll(entities)
256 WhatsAppDiag.log(
257 TAG,
258 "setMessagingKeys: minted ${minted.size} one-time prekeys (ids ${maxId + 1}..${maxId + minted.size})")
259
260 val variables = WhatsAppMexVariables.buildSetMessagingKeysVariables(
261 identity = identity,
262 skeyId = auth.signedPreKeyId,
263 skeyValue = skeyValue,
264 skeySignature = skeySignature,
265 prekeys = minted,
266 )
267 return WhatsAppMex.call(context, OP_SET_MESSAGING_KEYS, variables, "set")
268 }
269
270 // -- encoding helpers ------------------------------------------------------------------------
271
272 /** Decode a STANDARD-base64 field stored in [WhatsAppAuthData] (android.util.Base64.NO_WRAP). */
273 private fun decodeStd(s: String): ByteArray = AndroidBase64.decode(s, AndroidBase64.NO_WRAP)
274}