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

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

WhatsAppProtocolBuilders.kt509 lines · 18.4 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol.Node
4import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol.ParticipantEnc
5import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto
6
7// -- Message node builders (from whatsmeow/send.go) --
8
9private const val PEER_DATA_HISTORY_SYNC_ON_DEMAND = 3
10private const val SHIFT_BYTE3 = 24
11private const val SHIFT_BYTE2 = 16
12private const val SHIFT_BYTE1 = 8
13private const val MS_PER_SECOND = 1000L
14
15/**
16 * Build a text message node with E2E encrypted protobuf payload.
17 * The enc node contains the Signal-encrypted E2E.Message protobuf.
18 */
19/**
20 * Build the E2E protobuf plaintext for a conversation (text) message.
21 * The returned bytes are the unencrypted, unpadded waE2E.Message; the caller pads and
22 * Signal-encrypts them before placing into an <enc> node.
23 */
24fun WhatsAppProtocol.buildConversationPlaintext(text: String): ByteArray {
25 return buildConversationMessage(text).toByteArray()
26}
27
28/** Build the waE2E.Message proto object for a conversation (text) message. */
29fun WhatsAppProtocol.buildConversationMessage(text: String): WhatsAppE2EProto.Message {
30 return WhatsAppE2EProto.Message.newBuilder()
31 .setConversation(text)
32 .build()
33}
34
35/**
36 * Build a HISTORY_SYNC_ON_DEMAND peer-data-operation request. Sent E2E to our own account to
37 * ask the primary to stream older messages for a chat. Ref whatsmeow BuildHistorySyncRequest.
38 * Note: oldestMsgTimestampMs is actually seconds despite the field name.
39 */
40fun WhatsAppProtocol.buildHistoryOnDemandRequest(
41 chatJid: String,
42 oldestMsgId: String,
43 oldestMsgFromMe: Boolean,
44 oldestMsgTimestampSec: Long,
45 count: Int,
46): WhatsAppE2EProto.Message {
47 val req = WhatsAppE2EProto.HistorySyncOnDemandRequest.newBuilder()
48 .setChatJid(chatJid)
49 .setOldestMsgId(oldestMsgId)
50 .setOldestMsgFromMe(oldestMsgFromMe)
51 .setOnDemandMsgCount(count)
52 .setOldestMsgTimestampMs(oldestMsgTimestampSec)
53 val pdo =
54 WhatsAppE2EProto.PeerDataOperationRequestMessage.newBuilder()
55 .setPeerDataOperationRequestType(PEER_DATA_HISTORY_SYNC_ON_DEMAND) // HISTORY_SYNC_ON_DEMAND
56 .setHistorySyncOnDemandRequest(req)
57 val proto = WhatsAppE2EProto.ProtocolMessage.newBuilder()
58 .setType(WhatsAppE2EProto.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE)
59 .setPeerDataOperationRequestMessage(pdo)
60 return WhatsAppE2EProto.Message.newBuilder()
61 .setProtocolMessage(proto)
62 .build()
63}
64
65/**
66 * Wrap a message in a DeviceSentMessage for fan-out to the sender's own other devices.
67 * Ref whatsmeow send.go marshalMessage() dsmPlaintext.
68 */
69fun WhatsAppProtocol.deviceSentPlaintext(
70 destinationJid: String,
71 message: WhatsAppE2EProto.Message,
72): ByteArray {
73 return WhatsAppE2EProto.Message.newBuilder()
74 .setDeviceSentMessage(
75 WhatsAppE2EProto.DeviceSentMessage.newBuilder()
76 .setDestinationJid(destinationJid)
77 .setMessage(message)
78 )
79 .build()
80 .toByteArray()
81}
82
83/**
84 * Build the SKDM-bearing plaintext that is 1:1 fanned out to every group device so they
85 * can decrypt the group skmsg. Ref whatsmeow send.go sendGroup() skdMessage.
86 */
87fun WhatsAppProtocol.senderKeyDistributionPlaintext(groupJid: String, axolotlSkdm: ByteArray): ByteArray {
88 return WhatsAppE2EProto.Message.newBuilder()
89 .setSenderKeyDistributionMessage(
90 WhatsAppE2EProto.SenderKeyDistributionMessage.newBuilder()
91 .setGroupId(groupJid)
92 .setAxolotlSenderKeyDistributionMessage(com.google.protobuf.ByteString.copyFrom(axolotlSkdm))
93 )
94 .build()
95 .toByteArray()
96}
97
98/**
99 * Build an outgoing message node with a <participants> fan-out: one <to jid><enc> per
100 * recipient/own device, plus an optional message-level extra <enc> (the group skmsg) and a
101 * <device-identity> node when any per-device enc is a pkmsg. Mirrors whatsmeow
102 * send.go prepareMessageNode/sendGroup.
103 *
104 * [participantEncs] is (wireDeviceJid, encType, ciphertext) per device.
105 */
106fun WhatsAppProtocol.buildFanOutMessageNode(
107 to: String,
108 id: String,
109 type: String,
110 participantEncs: List<ParticipantEnc>,
111 includeDeviceIdentity: Boolean,
112 deviceIdentity: ByteArray?,
113 extraEnc: Node? = null,
114 extraEncAttrs: Map<String, String> = emptyMap(),
115 messageAttrs: Map<String, String> = emptyMap(),
116): Node {
117 val toNodes = participantEncs.map { pe ->
118 val encAttrs = mutableMapOf("v" to "2", "type" to pe.encType)
119 encAttrs.putAll(extraEncAttrs)
120 Node(
121 tag = "to",
122 attrs = mapOf("jid" to pe.deviceJid),
123 content = listOf(Node(tag = "enc", attrs = encAttrs, data = pe.ciphertext)),
124 )
125 }
126 val participants = Node(tag = "participants", content = toNodes)
127 val content = mutableListOf(participants)
128 if (extraEnc != null) content.add(extraEnc)
129 if (includeDeviceIdentity && deviceIdentity != null) {
130 content.add(Node(tag = "device-identity", data = deviceIdentity))
131 }
132 val attrs = mutableMapOf("to" to to, "id" to id, "type" to type)
133 attrs.putAll(messageAttrs)
134 return Node(tag = "message", attrs = attrs, content = content)
135}
136
137/**
138 * Build a retry receipt sent when an inbound message fails to decrypt, asking the sender to
139 * re-encrypt. Ref whatsmeow retry.go sendRetryReceipt. [keysNode] (identity + fresh prekeys +
140 * device-identity) should be included on the 2nd+ retry or when forced.
141 */
142fun WhatsAppProtocol.buildRetryReceipt(
143 originalNode: Node,
144 registrationId: Int,
145 retryCount: Int,
146 keysNode: Node?,
147): Node {
148 val msgId = originalNode.attrs["id"] ?: ""
149 val attrs = mutableMapOf(
150 "id" to msgId,
151 "to" to (originalNode.attrs["from"] ?: ""),
152 "type" to "retry",
153 )
154 originalNode.attrs["recipient"]?.let { attrs["recipient"] = it }
155 originalNode.attrs["participant"]?.let { attrs["participant"] = it }
156 val regBytes = byteArrayOf(
157 (registrationId ushr SHIFT_BYTE3).toByte(),
158 (registrationId ushr SHIFT_BYTE2).toByte(),
159 (registrationId ushr SHIFT_BYTE1).toByte(),
160 registrationId.toByte(),
161 )
162 val retryNode = Node(
163 tag = "retry",
164 attrs = mapOf(
165 "count" to retryCount.toString(),
166 "id" to msgId,
167 "t" to (originalNode.attrs["t"] ?: ""),
168 "v" to "1",
169 ),
170 )
171 val content = mutableListOf(retryNode, Node(tag = "registration", data = regBytes))
172 if (keysNode != null) content.add(keysNode)
173 return Node(tag = "receipt", attrs = attrs, content = content)
174}
175
176/**
177 * Build a group-info (participants) interactive query IQ.
178 * Ref whatsmeow group.go getGroupInfo: <iq to=group xmlns=w:g2 type=get><query request=interactive/>.
179 */
180fun WhatsAppProtocol.buildGroupParticipantsQuery(groupJid: String, id: String): Node {
181 return Node(
182 tag = "iq",
183 attrs = mapOf("id" to id, "type" to "get", "xmlns" to "w:g2", "to" to groupJid),
184 content = listOf(Node(tag = "query", attrs = mapOf("request" to "interactive"))),
185 )
186}
187
188/**
189 * Build a usync device-list query for the given users.
190 * Ref whatsmeow user.go GetUserDevices/usync: <iq xmlns=usync><usync mode=query context=message>
191 * <query><devices version=2/></query><list><user jid=.../></list></usync>.
192 */
193fun WhatsAppProtocol.buildUsyncDevicesQuery(userJids: List<String>, id: String, sid: String): Node {
194 val userNodes = userJids.map { Node(tag = "user", attrs = mapOf("jid" to it)) }
195 return Node(
196 tag = "iq",
197 attrs = mapOf("id" to id, "type" to "get", "xmlns" to "usync", "to" to "s.whatsapp.net"),
198 content = listOf(
199 Node(
200 tag = "usync",
201 attrs = mapOf(
202 "sid" to sid,
203 "mode" to "query",
204 "last" to "true",
205 "index" to "0",
206 "context" to "message",
207 ),
208 content = listOf(
209 Node(
210 tag = "query",
211 content = listOf(Node(tag = "devices", attrs = mapOf("version" to "2"))),
212 ),
213 Node(tag = "list", content = userNodes),
214 ),
215 )
216 ),
217 )
218}
219
220/**
221 * Build a media_conn query IQ to obtain the upload auth token + hosts.
222 * Ref whatsmeow mediaconn.go queryMediaConn: <iq xmlns=w:m type=set><media_conn/>.
223 */
224fun WhatsAppProtocol.buildMediaConnQuery(id: String): Node {
225 return Node(
226 tag = "iq",
227 attrs = mapOf("id" to id, "type" to "set", "xmlns" to "w:m", "to" to "s.whatsapp.net"),
228 content = listOf(Node(tag = "media_conn")),
229 )
230}
231
232/**
233 * Build a MEX (`w:mex`) query IQ carrying a persisted-query GraphQL envelope. Ref w2.md §5.2
234 * (SMAX `QueryRequest.kt`): `<iq xmlns="w:mex" to="s.whatsapp.net" type=<type> id=…>` with a
235 * single `<query query_id="<docId>"[ argo_mode=…]>` child whose text/data node is the JSON
236 * envelope `{"queryId":"<docId>","variables":{…}}` (built JVM-pure by
237 * [com.vayunmathur.communicate.data.whatsapp.mex.MexEnvelope.buildQueryJson]).
238 *
239 * The envelope is attached as the `<query>` node's UTF-8 [Node.data] (like
240 * [buildGroupInfoChange]); `data` and `content` are mutually exclusive. [argoMode] is omitted
241 * when null (we send the plaintext JSON `<result>` envelope rather than Argo binary).
242 *
243 * @param docId the resolved 17-digit persisted-query id (also embedded inside [queryJson]).
244 * @param queryJson the full `{"queryId":…,"variables":…}` envelope string.
245 */
246fun WhatsAppProtocol.buildMexQuery(
247 docId: String,
248 queryJson: String,
249 id: String,
250 type: String = "get",
251 argoMode: Long? = null,
252): Node {
253 val queryAttrs = mutableMapOf("query_id" to docId)
254 if (argoMode != null) queryAttrs["argo_mode"] = argoMode.toString()
255 return Node(
256 tag = "iq",
257 attrs = mapOf("id" to id, "type" to type, "xmlns" to "w:mex", "to" to "s.whatsapp.net"),
258 content = listOf(
259 Node(tag = "query", attrs = queryAttrs, data = queryJson.toByteArray(Charsets.UTF_8)),
260 ),
261 )
262}
263/**
264 * Build a reaction as an E2E [Message] proto (ReactionMessage). Returned as a proto — NOT a
265 * wire node — so the caller sends it through the normal Signal encryption + multi-device
266 * fan-out path (buildEncryptedMessageNode / buildEncryptedGroupMessageNode) like any other
267 * message. The reaction key must point at the TARGET message: [targetFromMe] reflects whether
268 * the target was sent by us, and for group targets from someone else [targetSenderJid] is that
269 * sender's JID (participant). Ref whatsmeow send.go BuildReaction + BuildMessageKey.
270 * An empty [emoji] removes the reaction.
271 */
272fun WhatsAppProtocol.buildReactionProto(
273 chatJid: String,
274 targetMessageId: String,
275 emoji: String,
276 targetFromMe: Boolean,
277 targetSenderJid: String?,
278): WhatsAppE2EProto.Message {
279 val messageKey = WhatsAppE2EProto.MessageKey.newBuilder()
280 .setFromMe(targetFromMe)
281 .setId(targetMessageId)
282 .setRemoteJid(chatJid)
283 if (!targetFromMe && chatJid.contains("@g.us") && !targetSenderJid.isNullOrEmpty()) {
284 messageKey.setParticipant(targetSenderJid)
285 }
286
287 val reactionMessage = WhatsAppE2EProto.ReactionMessage.newBuilder()
288 .setKey(messageKey.build())
289 .setText(emoji)
290 .setSenderTimestampMs(System.currentTimeMillis())
291 .build()
292
293 return WhatsAppE2EProto.Message.newBuilder()
294 .setReactionMessage(reactionMessage)
295 .build()
296}
297
298/**
299 * Build a receipt node with configurable type.
300 * Supports: "read", "read-self", "played", "" (delivery), "inactive"
301 * From whatsmeow/receipt.go
302 */
303fun WhatsAppProtocol.buildReceipt(
304 chatJid: String,
305 messageIds: List<String>,
306 receiptType: String,
307 senderJid: String? = null,
308): Node {
309 if (messageIds.isEmpty()) throw IllegalArgumentException("No message IDs")
310
311 val attrs = mutableMapOf(
312 "id" to messageIds.first(),
313 "to" to chatJid
314 )
315 if (receiptType.isNotEmpty()) {
316 attrs["type"] = receiptType
317 }
318 if (senderJid != null && chatJid.contains("@g.us")) {
319 attrs["participant"] = senderJid
320 }
321
322 val children = mutableListOf<Node>()
323 if (messageIds.size > 1) {
324 val items = messageIds.drop(1).map { id ->
325 Node(tag = "item", attrs = mapOf("id" to id))
326 }
327 children.add(Node(tag = "list", content = items))
328 }
329
330 return Node(tag = "receipt", attrs = attrs, content = children)
331}
332
333/**
334 * Build a media message node.
335 * From whatsmeow/send.go + upload.go
336 */
337fun WhatsAppProtocol.buildMediaProto(
338 url: String,
339 directPath: String,
340 mediaKey: ByteArray,
341 fileSha256: ByteArray,
342 fileEncSha256: ByteArray,
343 fileLength: Long,
344 mimeType: String,
345 caption: String?,
346 mediaType: String, // "image", "video", "audio", "document", "sticker"
347): WhatsAppE2EProto.Message {
348 val e2eBuilder = WhatsAppE2EProto.Message.newBuilder()
349
350 when (mediaType) {
351 "image" -> e2eBuilder.setImageMessage(
352 buildImageMedia(url, directPath, mediaKey, fileSha256, fileEncSha256, fileLength, mimeType, caption))
353 "video" -> e2eBuilder.setVideoMessage(
354 buildVideoMedia(url, directPath, mediaKey, fileSha256, fileEncSha256, fileLength, mimeType, caption))
355 "audio" -> e2eBuilder.setAudioMessage(
356 buildAudioMedia(url, directPath, mediaKey, fileSha256, fileEncSha256, fileLength, mimeType))
357 "document" -> e2eBuilder.setDocumentMessage(
358 buildDocumentMedia(url, directPath, mediaKey, fileSha256, fileEncSha256, fileLength, mimeType))
359 "sticker" -> e2eBuilder.setStickerMessage(
360 buildStickerMedia(url, directPath, mediaKey, fileSha256, fileEncSha256, fileLength, mimeType))
361 }
362
363 val plaintext = e2eBuilder.build()
364 return plaintext
365}
366
367/** Image media message. */
368private fun buildImageMedia(
369 url: String,
370 directPath: String,
371 mediaKey: ByteArray,
372 fileSha256: ByteArray,
373 fileEncSha256: ByteArray,
374 fileLength: Long,
375 mimeType: String,
376 caption: String?,
377): WhatsAppE2EProto.ImageMessage {
378 val imgBuilder = WhatsAppE2EProto.ImageMessage.newBuilder()
379 .setUrl(url)
380 .setDirectPath(directPath)
381 .setMediaKey(com.google.protobuf.ByteString.copyFrom(mediaKey))
382 .setFileSha256(com.google.protobuf.ByteString.copyFrom(fileSha256))
383 .setFileEncSha256(com.google.protobuf.ByteString.copyFrom(fileEncSha256))
384 .setFileLength(fileLength.toULong().toLong())
385 .setMimetype(mimeType)
386 if (caption != null) imgBuilder.setCaption(caption)
387 return imgBuilder.build()
388}
389
390/** Video media message. */
391private fun buildVideoMedia(
392 url: String,
393 directPath: String,
394 mediaKey: ByteArray,
395 fileSha256: ByteArray,
396 fileEncSha256: ByteArray,
397 fileLength: Long,
398 mimeType: String,
399 caption: String?,
400): WhatsAppE2EProto.VideoMessage {
401 val vidBuilder = WhatsAppE2EProto.VideoMessage.newBuilder()
402 .setUrl(url)
403 .setDirectPath(directPath)
404 .setMediaKey(com.google.protobuf.ByteString.copyFrom(mediaKey))
405 .setFileSha256(com.google.protobuf.ByteString.copyFrom(fileSha256))
406 .setFileEncSha256(com.google.protobuf.ByteString.copyFrom(fileEncSha256))
407 .setFileLength(fileLength.toULong().toLong())
408 .setMimetype(mimeType)
409 if (caption != null) vidBuilder.setCaption(caption)
410 return vidBuilder.build()
411}
412
413/** Audio media message. */
414private fun buildAudioMedia(
415 url: String,
416 directPath: String,
417 mediaKey: ByteArray,
418 fileSha256: ByteArray,
419 fileEncSha256: ByteArray,
420 fileLength: Long,
421 mimeType: String,
422): WhatsAppE2EProto.AudioMessage {
423 val audBuilder = WhatsAppE2EProto.AudioMessage.newBuilder()
424 .setUrl(url)
425 .setDirectPath(directPath)
426 .setMediaKey(com.google.protobuf.ByteString.copyFrom(mediaKey))
427 .setFileSha256(com.google.protobuf.ByteString.copyFrom(fileSha256))
428 .setFileEncSha256(com.google.protobuf.ByteString.copyFrom(fileEncSha256))
429 .setFileLength(fileLength.toULong().toLong())
430 .setMimetype(mimeType)
431 return audBuilder.build()
432}
433
434/** Document media message. */
435private fun buildDocumentMedia(
436 url: String,
437 directPath: String,
438 mediaKey: ByteArray,
439 fileSha256: ByteArray,
440 fileEncSha256: ByteArray,
441 fileLength: Long,
442 mimeType: String,
443): WhatsAppE2EProto.DocumentMessage {
444 val docBuilder =
445 WhatsAppE2EProto.DocumentMessage.newBuilder()
446 .setUrl(url)
447 .setDirectPath(directPath)
448 .setMediaKey(com.google.protobuf.ByteString.copyFrom(mediaKey))
449 .setFileSha256(com.google.protobuf.ByteString.copyFrom(fileSha256))
450 .setFileEncSha256(com.google.protobuf.ByteString.copyFrom(fileEncSha256))
451 .setFileLength(fileLength.toULong().toLong())
452 .setMimetype(mimeType)
453 return docBuilder.build()
454}
455
456/** Sticker media message. */
457private fun buildStickerMedia(
458 url: String,
459 directPath: String,
460 mediaKey: ByteArray,
461 fileSha256: ByteArray,
462 fileEncSha256: ByteArray,
463 fileLength: Long,
464 mimeType: String,
465): WhatsAppE2EProto.StickerMessage {
466 val stickerBuilder =
467 WhatsAppE2EProto.StickerMessage.newBuilder()
468 .setUrl(url)
469 .setDirectPath(directPath)
470 .setMediaKey(com.google.protobuf.ByteString.copyFrom(mediaKey))
471 .setFileSha256(com.google.protobuf.ByteString.copyFrom(fileSha256))
472 .setFileEncSha256(com.google.protobuf.ByteString.copyFrom(fileEncSha256))
473 .setFileLength(fileLength.toULong().toLong())
474 .setMimetype(mimeType)
475 return stickerBuilder.build()
476}
477
478/**
479 * Build a read receipt node.
480 * From whatsmeow/receipt.go MarkRead()
481 */
482fun WhatsAppProtocol.buildReadReceipt(
483 chatJid: String,
484 messageIds: List<String>,
485 senderJid: String? = null,
486 timestamp: Long = System.currentTimeMillis() / MS_PER_SECOND,
487): Node {
488 if (messageIds.isEmpty()) throw IllegalArgumentException("No message IDs")
489
490 val attrs = mutableMapOf(
491 "id" to messageIds.first(),
492 "type" to "read",
493 "to" to chatJid,
494 "t" to timestamp.toString()
495 )
496 if (senderJid != null && chatJid.contains("@g.us")) {
497 attrs["participant"] = senderJid
498 }
499
500 val children = mutableListOf<Node>()
501 if (messageIds.size > 1) {
502 val items = messageIds.drop(1).map { id ->
503 Node(tag = "item", attrs = mapOf("id" to id))
504 }
505 children.add(Node(tag = "list", content = items))
506 }
507
508 return Node(tag = "receipt", attrs = attrs, content = children)
509}