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 / WhatsAppProtocolParsing.kt

WhatsAppProtocolParsing.kt465 lines · 18.9 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import com.vayunmathur.library.log.Log
4import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol.Node
5import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto
6
7// -- Message parsing: type/body extraction, inbound node parsing, WA formatting --
8
9internal const val SECONDS_PER_MINUTE = 60
10internal const val SECONDS_PER_HOUR = 3600
11internal const val SECONDS_PER_DAY = 86400
12internal const val SECONDS_PER_WEEK = SECONDS_PER_DAY * 7
13internal const val SECONDS_90_DAYS = SECONDS_PER_DAY * 90
14internal const val FENCE_LENGTH = 3
15
16
17fun WhatsAppProtocol.rerouteLIDSender(senderJid: String, participants: Map<String, String>?): String {
18 if (!senderJid.contains("@lid")) return senderJid
19 val phoneJid = participants?.get(senderJid)
20 return phoneJid ?: senderJid
21}
22
23/**
24 * Return the effective PollCreationMessage from a message regardless of version — modern
25 * WhatsApp sends polls as pollCreationMessageV3 (field 64) or V2 (60), older ones as V1 (49).
26 * Returns null if the message isn't a poll creation.
27 */
28fun WhatsAppProtocol.pollCreation(
29 e2eMessage: WhatsAppE2EProto.Message?,
30): WhatsAppE2EProto.PollCreationMessage? = when {
31 e2eMessage == null -> null
32 e2eMessage.hasPollCreationMessageV3() -> e2eMessage.pollCreationMessageV3
33 e2eMessage.hasPollCreationMessageV2() -> e2eMessage.pollCreationMessageV2
34 e2eMessage.hasPollCreationMessage() -> e2eMessage.pollCreationMessage
35 else -> null
36}
37
38/**
39 * If [m] is a view-once container (viewOnceMessage / viewOnceMessageV2 /
40 * viewOnceMessageV2Extension), return the wrapped inner [Message]; otherwise null. Used to
41 * unwrap and flag view-once media on receive. Ref WAWebProtobufsE2E.Message view-once fields.
42 */
43fun WhatsAppProtocol.unwrapViewOnce(
44 m: WhatsAppE2EProto.Message,
45): WhatsAppE2EProto.Message? = when {
46 m.hasViewOnceMessageV2Extension() && m.viewOnceMessageV2Extension.hasMessage() ->
47 m.viewOnceMessageV2Extension.message
48 m.hasViewOnceMessageV2() && m.viewOnceMessageV2.hasMessage() -> m.viewOnceMessageV2.message
49 m.hasViewOnceMessage() && m.viewOnceMessage.hasMessage() -> m.viewOnceMessage.message
50 else -> null
51}
52
53fun WhatsAppProtocol.getMessageType(e2eMessage: WhatsAppE2EProto.Message?): String {
54 val unwrapped = if (e2eMessage != null) unwrapViewOnce(e2eMessage) else null
55 val e2e = unwrapped ?: e2eMessage
56 return when {
57 e2e == null -> "ignore"
58 e2e.hasConversation() || e2e.hasExtendedTextMessage() -> "text"
59 e2e.hasContactMessage() -> "contact"
60 e2e.hasLocationMessage() -> "location"
61 pollCreation(e2e) != null -> "poll"
62 else -> mediaMessageType(e2e) ?: extendedMessageType(e2e)
63 }
64}
65
66/** Media message type, or null when not media. */
67private fun WhatsAppProtocol.mediaMessageType(e2e: WhatsAppE2EProto.Message): String? = when {
68 e2e.hasImageMessage() -> "image ${e2e.imageMessage.mimetype}"
69 e2e.hasStickerMessage() -> "sticker ${e2e.stickerMessage.mimetype}"
70 e2e.hasVideoMessage() -> "video ${e2e.videoMessage.mimetype}"
71 e2e.hasAudioMessage() -> "audio ${e2e.audioMessage.mimetype}"
72 e2e.hasDocumentMessage() -> "document ${e2e.documentMessage.mimetype}"
73 else -> null
74}
75
76/** Type string for reaction/edit/protocol/sender-key messages. */
77private fun WhatsAppProtocol.extendedMessageType(e2e: WhatsAppE2EProto.Message): String {
78 return when {
79 e2e.hasReactionMessage() -> {
80 if (e2e.reactionMessage.text.isNullOrEmpty()) "reaction remove" else "reaction"
81 }
82 e2e.hasEditedMessage() -> {
83 val inner = e2e.editedMessage?.message
84 if (inner != null) getMessageType(inner) else "ignore"
85 }
86 e2e.hasProtocolMessage() -> protocolMessageType(e2e)
87 e2e.hasSenderKeyDistributionMessage() -> "ignore"
88 else -> "unknown"
89 }
90}
91
92/** Type string for protocol messages. */
93private fun WhatsAppProtocol.protocolMessageType(e2e: WhatsAppE2EProto.Message): String {
94 val protocol = e2e.protocolMessage
95 return when (protocol.type) {
96 WhatsAppE2EProto.ProtocolMessage.Type.REVOKE -> {
97 if (protocol.hasKey()) "revoke" else "ignore"
98 }
99 WhatsAppE2EProto.ProtocolMessage.Type.MESSAGE_EDIT -> "edit"
100 WhatsAppE2EProto.ProtocolMessage.Type.EPHEMERAL_SETTING -> "ephemeral setting"
101 WhatsAppE2EProto.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION -> "history_sync"
102 WhatsAppE2EProto.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE -> "app_state_key"
103 WhatsAppE2EProto.ProtocolMessage.Type.INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC,
104 WhatsAppE2EProto.ProtocolMessage.Type.APP_STATE_FATAL_EXCEPTION_NOTIFICATION,
105 WhatsAppE2EProto.ProtocolMessage.Type.SHARE_PHONE_NUMBER,
106 WhatsAppE2EProto.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE,
107 WhatsAppE2EProto.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE -> "ignore"
108 else -> "unknown_protocol_${protocol.type.number}"
109 }
110}
111
112/**
113 * Extract a human-readable body/preview from a decrypted [Message] (used for history-sync
114 * backfill, where each WebMessageInfo wraps a Message). Mirrors the body logic in parseMessage.
115 */
116fun WhatsAppProtocol.extractMessageBody(m: WhatsAppE2EProto.Message): String {
117 var e2e = m
118 if (e2e.hasEditedMessage() && e2e.editedMessage.hasMessage()) e2e = e2e.editedMessage.message
119 unwrapViewOnce(e2e)?.let { e2e = it }
120 return when {
121 e2e.hasConversation() -> e2e.conversation
122 e2e.hasExtendedTextMessage() -> e2e.extendedTextMessage.text
123 e2e.hasImageMessage() -> e2e.imageMessage.caption.ifEmpty { "[Image]" }
124 e2e.hasVideoMessage() -> e2e.videoMessage.caption.ifEmpty { "[Video]" }
125 e2e.hasAudioMessage() -> "[Audio]"
126 e2e.hasDocumentMessage() -> "[Document: ${e2e.documentMessage.title}]"
127 e2e.hasStickerMessage() -> "[Sticker]"
128 e2e.hasContactMessage() -> "[Contact: ${e2e.contactMessage.displayName}]"
129 e2e.hasLocationMessage() -> "[Location]"
130 else -> ""
131 }
132}
133
134/**
135 * Parse an inbound <message> node...
136 * Signal-decrypted (and unpadded) via the callback; otherwise the raw enc data is treated
137 * as already-plaintext padded protobuf (legacy/no-crypto path).
138 *
139 * [decryptEnc] receives (senderJid, encType, encData) and returns the decrypted, still
140 * padded plaintext, or null if decryption failed.
141 */
142fun WhatsAppProtocol.parseMessage(
143 node: Node,
144 decryptEnc: ((senderJid: String, encType: String, data: ByteArray) -> ByteArray?)? = null,
145): WhatsAppMessage? {
146 if (node.tag != "message") return null
147
148 val rawFrom = node.attrs["from"] ?: return null
149 val from = normalizeSender(rawFrom, node.attrs["sender_pn"])
150 val id = node.attrs["id"] ?: return null
151 val type = node.attrs["type"] ?: "text"
152 val timestamp = node.attrs["t"]?.toLongOrNull() ?: System.currentTimeMillis() / 1000
153 val participant = node.attrs["participant"]
154
155 val encNode = node.getChildByTag("enc")
156 if (encNode?.data != null) {
157 return parseEncryptedMessage(node, encNode, from, id, type, timestamp, participant, decryptEnc)
158 }
159
160 // Fallback: plaintext body node
161 val bodyNode = node.getChildByTag("body")
162 val body = bodyNode?.data?.let { String(it, Charsets.UTF_8) } ?: ""
163
164 return WhatsAppMessage(
165 id = id,
166 from = from,
167 to = node.attrs["to"] ?: "",
168 body = body,
169 timestamp = timestamp,
170 type = type,
171 participant = participant,
172 )
173}
174
175/**
176 * Normalize the sender: for 1:1 chats WhatsApp now addresses the sender by LID
177 * (e.g. 13184…@s.whatsapp.net) and carries the phone number in sender_pn.
178 * Normalize to the PN so live messages map to the same conversation as history
179 * (which is keyed by phone JID). Groups/broadcast keep `from`.
180 */
181private fun normalizeSender(rawFrom: String, senderPn: String?): String {
182 if (!senderPn.isNullOrEmpty() && !rawFrom.contains("@g.us") && !rawFrom.contains("broadcast")) {
183 return senderPn.substringBefore(":").let { if (it.contains("@")) it else "[email protected]" }
184 }
185 return rawFrom
186}
187
188/** Decrypt + unwrap + assemble an E2E message node. */
189private fun WhatsAppProtocol.parseEncryptedMessage(
190 node: Node,
191 encNode: Node,
192 from: String,
193 id: String,
194 type: String,
195 timestamp: Long,
196 participant: String?,
197 decryptEnc: ((senderJid: String, encType: String, data: ByteArray) -> ByteArray?)?,
198): WhatsAppMessage? {
199 return try {
200 val plaintext = decryptPayload(encNode, from, participant, decryptEnc)
201 ?: return WhatsAppMessage(
202 id = id, from = from, to = node.attrs["to"] ?: "", body = "",
203 timestamp = timestamp, type = type, participant = participant,
204 )
205 var e2eMessage = WhatsAppE2EProto.Message.parseFrom(plaintext)
206
207 // Messages the user sends from another linked device are echoed to us
208 // either wrapped in a DeviceSentMessage (carrying the real chat in
209 // destinationJid) or, for 1:1, with `from` set to our own JID and the real
210 // chat in the `recipient` attr. Unwrap/redirect so these map to the right
211 // conversation instead of surfacing as a blank message from ourselves.
212 // Ref whatsmeow message.go processProtocolParts / parseMessageSource.
213 val (chatJid, fromMe, unwrapped) = unwrapMessageSource(e2eMessage, from, node)
214 e2eMessage = unwrapped
215
216 // Unwrap FutureProofMessage (Go events.go GetInnerMessage)
217 if (e2eMessage.hasEditedMessage() && e2eMessage.editedMessage.hasMessage()) {
218 e2eMessage = e2eMessage.editedMessage.message
219 }
220
221 // Unwrap view-once container (Go convertMediaMessage viewOnce check) and remember
222 // it so the UI can render "opened once" media.
223 var isViewOnceMsg = false
224 val vo = unwrapViewOnce(e2eMessage)
225 if (vo != null) {
226 isViewOnceMsg = true
227 e2eMessage = vo
228 }
229
230 buildParsedMessage(node, e2eMessage, chatJid, fromMe, isViewOnceMsg, id, type, timestamp, participant)
231 } catch (expected: Exception) {
232 Log.error(TAG, "Failed to parse E2E message", expected)
233 WhatsAppMessage(
234 id = id,
235 from = from,
236 to = node.attrs["to"] ?: "",
237 body = "",
238 timestamp = timestamp,
239 type = type,
240 participant = participant)
241 }
242}
243
244/** Decrypt the enc payload, or null when undecryptable. */
245private fun WhatsAppProtocol.decryptPayload(
246 encNode: Node,
247 from: String,
248 participant: String?,
249 decryptEnc: ((senderJid: String, encType: String, data: ByteArray) -> ByteArray?)?,
250): ByteArray? {
251 val encType = encNode.attrs["type"] ?: "msg"
252 val senderJid = participant ?: from
253 val decryptedPadded: ByteArray = if (decryptEnc != null) {
254 decryptEnc(senderJid, encType, encNode.data ?: return null)
255 ?: return null
256 } else {
257 encNode.data ?: return null
258 }
259 return unpadMessage(decryptedPadded)
260}
261
262/** Unwrap DSM/recipient echo into (chatJid, fromMe, message). */
263private fun WhatsAppProtocol.unwrapMessageSource(
264 e2eMessage: WhatsAppE2EProto.Message,
265 from: String,
266 node: Node,
267): Triple<String, Boolean, WhatsAppE2EProto.Message> {
268 var chatJid = from
269 var fromMe = false
270 var msg = e2eMessage
271 if (msg.hasDeviceSentMessage()) {
272 fromMe = true
273 val dsm = msg.deviceSentMessage
274 if (dsm.destinationJid.isNotEmpty()) chatJid = dsm.destinationJid
275 if (dsm.hasMessage()) msg = dsm.message
276 } else {
277 val recipient = node.attrs["recipient"]
278 if (!recipient.isNullOrEmpty()) {
279 fromMe = true
280 chatJid = recipient
281 }
282 }
283 return Triple(chatJid, fromMe, msg)
284}
285
286/** Assemble the final message, or null for ignorable protocol stanzas. */
287private fun WhatsAppProtocol.buildParsedMessage(
288 node: Node,
289 e2eMessage: WhatsAppE2EProto.Message,
290 chatJid: String,
291 fromMe: Boolean,
292 isViewOnceMsg: Boolean,
293 id: String,
294 type: String,
295 timestamp: Long,
296 participant: String?,
297): WhatsAppMessage? {
298
299 val parsedType = getMessageType(e2eMessage)
300 // A message carrying only a SenderKeyDistributionMessage types as "ignore", but we
301 // MUST still process it — it's what establishes the group sender key so subsequent
302 // skmsg group messages can be decrypted. Let it through here; the caller processes
303 // the key and then stops (see handleIncomingMessage). Other "ignore" / unknown
304 // protocol messages are still dropped.
305 val hasSenderKeyDistribution = e2eMessage.hasSenderKeyDistributionMessage()
306 if ((parsedType == "ignore" && !hasSenderKeyDistribution) ||
307 parsedType.startsWith("unknown_protocol_")
308 ) {
309 return null
310 }
311
312 val body = messageBodyText(e2eMessage, parsedType)
313 val mediaUrl = mediaUrlOf(e2eMessage)
314 val isRevoke = parsedType == "revoke"
315 val revokeTargetId = if (isRevoke) e2eMessage.protocolMessage.key.id else null
316 val isEdit = parsedType == "edit"
317 val editTargetId = if (isEdit) e2eMessage.protocolMessage.key.id else null
318 val contextInfo = extractContextInfo(e2eMessage)
319
320 // View-once: set when the message arrived wrapped in a view-once container
321 // (unwrapped above). HD is not representable in this proto subset — WhatsApp's HD
322 // flag lives in fields we don't model — so it stays false (documented, not faked).
323
324 return WhatsAppMessage(
325 id = id,
326 from = chatJid,
327 to = node.attrs["to"] ?: "",
328 body = body,
329 timestamp = timestamp,
330 type = type,
331 participant = participant,
332 mediaUrl = mediaUrl,
333 isReaction = e2eMessage.hasReactionMessage(),
334 reactionTargetId = if (e2eMessage.hasReactionMessage()) e2eMessage.reactionMessage.key.id else null,
335 isRevoke = isRevoke,
336 revokeTargetId = revokeTargetId,
337 isEdit = isEdit,
338 editTargetId = editTargetId,
339 messageType = parsedType,
340 locationData = locationDataOf(e2eMessage),
341 contactData = contactDataOf(e2eMessage),
342 pollData = pollDataOf(e2eMessage),
343 groupInviteData = null,
344 disappearingTimer = disappearingTimerOf(e2eMessage, parsedType),
345 isForwarded = contextInfo.isForwarded,
346 forwardingScore = contextInfo.forwardingScore,
347 replyToId = contextInfo.replyToId,
348 mentionedJids = contextInfo.mentionedJids,
349 isViewOnce = isViewOnceMsg,
350 isHD = false,
351 isFromMe = fromMe,
352 e2eMessage = e2eMessage,
353 )
354}
355
356/** Location payload, when present. */
357private fun locationDataOf(e2eMessage: WhatsAppE2EProto.Message): LocationData? = when {
358 e2eMessage.hasLocationMessage() -> LocationData(
359 latitude = e2eMessage.locationMessage.degreesLatitude,
360 longitude = e2eMessage.locationMessage.degreesLongitude,
361 name = e2eMessage.locationMessage.name.ifEmpty { null },
362 address = e2eMessage.locationMessage.address.ifEmpty { null },
363 url = e2eMessage.locationMessage.url.ifEmpty { null },
364 )
365 else -> null
366}
367
368/** Contact payload, when present. */
369private fun contactDataOf(e2eMessage: WhatsAppE2EProto.Message): ContactData? = when {
370 e2eMessage.hasContactMessage() -> ContactData(
371 displayName = e2eMessage.contactMessage.displayName,
372 vcard = e2eMessage.contactMessage.vcard,
373 )
374 else -> null
375}
376
377/** Poll payload, when present. */
378private fun WhatsAppProtocol.pollDataOf(e2eMessage: WhatsAppE2EProto.Message): PollData? =
379 pollCreation(e2eMessage)?.let { poll ->
380 PollData(
381 question = poll.name,
382 options = poll.optionsList.map { it.optionName },
383 selectableOptionCount = poll.selectableOptionsCount,
384 )
385 }
386
387/** Disappearing-timer value for ephemeral-setting messages. */
388private fun disappearingTimerOf(e2eMessage: WhatsAppE2EProto.Message, parsedType: String): Long? =
389 if (parsedType == "ephemeral setting") {
390 e2eMessage.protocolMessage.ephemeralExpiration.toLong()
391 } else {
392 null
393 }
394
395/** Display body text for a parsed E2E message. */
396private fun WhatsAppProtocol.messageBodyText(
397 e2eMessage: WhatsAppE2EProto.Message,
398 parsedType: String,
399): String = when {
400 e2eMessage.hasConversation() -> e2eMessage.conversation
401 e2eMessage.hasExtendedTextMessage() -> e2eMessage.extendedTextMessage.text
402 e2eMessage.hasImageMessage() -> e2eMessage.imageMessage.caption.ifEmpty { "[Image]" }
403 e2eMessage.hasVideoMessage() -> e2eMessage.videoMessage.caption.ifEmpty { "[Video]" }
404 e2eMessage.hasAudioMessage() -> "[Audio]"
405 e2eMessage.hasDocumentMessage() -> "[Document: ${e2eMessage.documentMessage.title}]"
406 e2eMessage.hasStickerMessage() -> "[Sticker]"
407 e2eMessage.hasContactMessage() -> {
408 val c = e2eMessage.contactMessage
409 "[Contact: ${c.displayName}]\n${c.vcard}"
410 }
411 e2eMessage.hasLocationMessage() -> locationBodyText(e2eMessage)
412 e2eMessage.hasReactionMessage() -> e2eMessage.reactionMessage.text
413 pollCreation(e2eMessage) != null -> pollBodyText(e2eMessage)
414 e2eMessage.hasProtocolMessage() -> protocolBodyText(e2eMessage, parsedType)
415 else -> ""
416}
417
418/** Location message body with maps link. */
419private fun locationBodyText(e2eMessage: WhatsAppE2EProto.Message): String {
420 val loc = e2eMessage.locationMessage
421 val lat = loc.degreesLatitude
422 val lng = loc.degreesLongitude
423 val name = loc.name.ifEmpty {
424 val latDir = if (lat >= 0) 'N' else 'S'
425 val lngDir = if (lng >= 0) 'E' else 'W'
426 "%.4f\u00b0 %c %.4f\u00b0 %c".format(Math.abs(lat), latDir, Math.abs(lng), lngDir)
427 }
428 val mapsUrl = "https://maps.google.com/?q=%.5f,%.5f".format(lat, lng)
429 return "Location: $name\n${loc.address}\n$mapsUrl"
430}
431
432/** Poll creation body. */
433private fun WhatsAppProtocol.pollBodyText(e2eMessage: WhatsAppE2EProto.Message): String {
434 val poll = pollCreation(e2eMessage)!!
435 return buildString {
436 append("\ud83d\udcca ")
437 append(poll.name)
438 poll.optionsList.forEach { append("\n\u2022 "); append(it.optionName) }
439 }
440}
441
442/** Protocol-message body (revoke/edit/ephemeral). */
443private fun WhatsAppProtocol.protocolBodyText(
444 e2eMessage: WhatsAppE2EProto.Message,
445 parsedType: String,
446): String = when (parsedType) {
447 "revoke" -> "[Message Deleted]"
448 "edit" -> e2eMessage.protocolMessage.editedMessage?.conversation ?: "[Edited]"
449 "ephemeral setting" -> {
450 val timer = e2eMessage.protocolMessage.ephemeralExpiration
451 if (timer == 0) "[Disappearing Messages Disabled]"
452 else "[Disappearing Messages: ${formatDisappearingTimer(timer)}]"
453 }
454 else -> ""
455}
456
457/** Media URL for attachment messages, or null. */
458private fun mediaUrlOf(e2eMessage: WhatsAppE2EProto.Message): String? = when {
459 e2eMessage.hasImageMessage() -> e2eMessage.imageMessage.url
460 e2eMessage.hasVideoMessage() -> e2eMessage.videoMessage.url
461 e2eMessage.hasAudioMessage() -> e2eMessage.audioMessage.url
462 e2eMessage.hasDocumentMessage() -> e2eMessage.documentMessage.url
463 e2eMessage.hasStickerMessage() -> e2eMessage.stickerMessage.url
464 else -> null
465}