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

WhatsAppClientSend.kt446 lines · 19.6 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient.State
4import com.vayunmathur.communicate.data.whatsapp.buildConversationMessage
5import com.vayunmathur.communicate.data.whatsapp.buildFanOutMessageNode
6import com.vayunmathur.communicate.data.whatsapp.buildMediaProto
7import com.vayunmathur.communicate.data.whatsapp.buildTextProto
8import com.vayunmathur.communicate.data.whatsapp.deviceSentPlaintext
9import com.vayunmathur.communicate.data.whatsapp.encodeNode
10import com.vayunmathur.communicate.data.whatsapp.encryptMedia
11import com.vayunmathur.communicate.data.whatsapp.generateMessageId
12import com.vayunmathur.communicate.data.whatsapp.padMessage
13import com.vayunmathur.communicate.data.whatsapp.senderKeyDistributionPlaintext
14import android.util.Base64
15import com.vayunmathur.library.log.Log
16import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E
17import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket
18import com.vayunmathur.library.network.NetworkClient
19import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto
20import kotlinx.coroutines.Dispatchers
21import kotlinx.coroutines.withContext
22import org.json.JSONObject
23
24// Recently sent 1:1 messages (id -> padded plaintext + own-device DSM), kept so we can
25// re-encrypt and resend to a specific device when the peer asks for a retry
26// (<receipt type="retry">). Without this, a message the recipient can't decrypt is acked
27// locally (send "succeeds") but is never actually delivered.
28private const val LOG_URL_PREFIX_LENGTH = 40
29
30data class SentDM(
31 val to: String,
32 val type: String,
33 val msgPlaintextPadded: ByteArray,
34 val dsmPlaintextPadded: ByteArray?,
35)
36
37/**
38 * Send a 1:1/group text message. Returns the WhatsApp message id on success (so callers can cache
39 * the outgoing echo under the same id that delivery/read receipts reference), or null on failure.
40 */
41suspend fun WhatsAppClient.sendMessage(conversationId: String, body: String): String? {
42 if (stateMutable.value !is State.Connected) { WhatsAppDiag.log(TAG, "send: not connected"); return null }
43 val ws = webSocket ?: return null
44
45 val to = extractJid(conversationId) ?: run { WhatsAppDiag.log(
46 TAG,
47 "send: bad convId $conversationId"); return null }
48 val id = WhatsAppProtocol.generateMessageId(authData?.wid)
49 WhatsAppDiag.log(TAG, "send: building message to $to")
50
51 val node = buildEncryptedTextNode(
52 to,
53 id,
54 body) ?: run { WhatsAppDiag.log(TAG, "send: build FAILED (no enc)"); return null }
55 pendingMessageIDs.add(id)
56 val sent = ws.send(WhatsAppProtocol.encodeNode(node))
57 if (!sent) pendingMessageIDs.remove(id)
58 WhatsAppDiag.log(TAG, "send: stanza sent=$sent id=$id")
59 return if (sent) id else null
60}
61
62/**
63 * Send a text message with optional rich content: @mentions, a quoted reply, and/or a URL
64 * link-preview. When none are provided this is equivalent to [sendMessage] (a plain
65 * `conversation` proto). Rich content is carried in an ExtendedTextMessage with ContextInfo so
66 * the peer renders mentions/quote/preview. Routed through the normal Signal fan-out (1:1) or
67 * group sender-key path. Ref whatsmeow ExtendedTextMessage / ContextInfo.
68 */
69suspend fun WhatsAppClient.sendMessageAdvanced(
70 conversationId: String,
71 body: String,
72 mentionedJids: List<String> = emptyList(),
73 quoted: WhatsAppProtocol.QuotedContext? = null,
74 linkPreview: WhatsAppProtocol.LinkPreview? = null,
75): String? {
76 if (stateMutable.value !is State.Connected) { WhatsAppDiag.log(TAG, "sendAdv: not connected"); return null }
77 val ws = webSocket ?: return null
78 val to = extractJid(conversationId) ?: return null
79 val id = WhatsAppProtocol.generateMessageId(authData?.wid)
80
81 val proto = WhatsAppProtocol.buildTextProto(body, mentionedJids, quoted, linkPreview)
82 val node = if (to.contains("@g.us")) {
83 buildEncryptedGroupMessageNode(to, id, proto, type = "text")
84 } else {
85 buildEncryptedMessageNode(to, id, proto, "text")
86 } ?: run { WhatsAppDiag.log(TAG, "sendAdv: build FAILED (no enc) for $to"); return null }
87
88 pendingMessageIDs.add(id)
89 val sent = ws.send(WhatsAppProtocol.encodeNode(node))
90 if (!sent) pendingMessageIDs.remove(id)
91 WhatsAppDiag.log(TAG, "sendAdv: sent=$sent id=$id mentions=${mentionedJids.size}" +
92 "quoted=${quoted != null} preview=${linkPreview != null}")
93 return if (sent) id else null
94}
95
96// ---------------------------------------------------------------------------------------------
97// Phase 10a — call signaling spike (media/VoIP engine is native-only, out of scope this pass).
98// ---------------------------------------------------------------------------------------------
99
100/**
101 * Send a WhatsApp call offer over the Noise socket (signaling only). GO/NO-GO: does the server
102 * accept the offer and the target ring? Encrypts a random call key to every peer/own device via
103 * the same Signal fan-out used for messages, then wraps it in a `<call><offer>` stanza.
104 */
105suspend fun WhatsAppClient.sendCallOffer(conversationId: String, video: Boolean = false): Boolean {
106 if (stateMutable.value !is State.Connected) { WhatsAppDiag.log(TAG, "call: not connected"); return false }
107 val ws = webSocket ?: return false
108 val auth = authData ?: return false
109 val crypto = ensureE2E(auth) ?: return false
110 val to = extractJid(conversationId) ?: return false
111 return sendCallOfferTo(ws, auth, crypto, to, video)
112}
113
114/** Encrypt a call key for the peer's (and our) devices and send the offer stanza. */
115private suspend fun WhatsAppClient.sendCallOfferTo(
116 ws: WhatsAppSocket,
117 auth: WhatsAppAuthData,
118 crypto: WhatsAppE2E,
119 to: String,
120 video: Boolean,
121): Boolean {
122 val ownUser = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".")
123 val callId = WhatsAppProtocol.generateMessageId(auth.wid)
124 val stanzaId = WhatsAppProtocol.generateMessageId(auth.wid)
125 val callKey = ByteArray(32).also { random.nextBytes(it) }
126 val padded = WhatsAppProtocol.padMessage(callKey)
127 val devices = (getUserDevices(listOf(to)).ifEmpty { listOf(to) } +
128 getUserDevices(listOf("[email protected]"))).distinct()
129 val (encs, _) = encryptForDevices(crypto, devices, ownUser, auth.wid, padded, null)
130 if (encs.isEmpty()) { WhatsAppDiag.log(TAG, "call: no devices to encrypt to"); return false }
131 val node = com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallSignaling.buildOffer(
132 to,
133 callId,
134 auth.wid,
135 video,
136 encs,
137 stanzaId)
138 val sent = ws.send(WhatsAppProtocol.encodeNode(node))
139 WhatsAppDiag.log(TAG, "call: offer sent=$sent callId=$callId to=$to devices=${encs.size}")
140 return sent
141}
142
143/** Reject an inbound call. */
144suspend fun WhatsAppClient.rejectCall(from: String, callId: String, callCreator: String): Boolean {
145 val ws = webSocket ?: return false
146 return ws.send(
147 WhatsAppProtocol.encodeNode(
148 com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallSignaling.buildReject(
149 from,
150 callId,
151 callCreator,
152 generateMessageId()),
153 ),
154 )
155}
156
157/** Place a WhatsApp call (audio or video) via the call manager. */
158fun WhatsAppClient.placeCall(conversationId: String, video: Boolean = false) {
159 val to = extractJid(conversationId) ?: return
160 com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager.placeCall(to, video)
161}
162
163/**
164 * Build a Signal-encrypted text message node for a recipient, fanning out to all of the
165 * recipient's devices and our own other devices (via usync), establishing sessions as needed.
166 * Group recipients (@g.us) use the sender-key (skmsg) path. Returns null on failure.
167 */
168internal suspend fun WhatsAppClient.buildEncryptedTextNode(
169 to: String,
170 id: String,
171 body: String): WhatsAppProtocol.Node? {
172 if (to.contains("@g.us")) {
173 return buildEncryptedGroupTextNode(to, id, body)
174 }
175 return buildEncryptedMessageNode(to, id, WhatsAppProtocol.buildConversationMessage(body), "text")
176}
177
178/** Encrypt+fan-out an arbitrary Message proto to a 1:1 recipient (and our own devices). */
179internal suspend fun WhatsAppClient.buildEncryptedMessageNode(
180 to: String,
181 id: String,
182 msg: WhatsAppE2EProto.Message,
183 type: String,
184 extraEncAttrs: Map<String, String> = emptyMap(),
185 messageAttrs: Map<String, String> = emptyMap(),
186): WhatsAppProtocol.Node? {
187 val auth = authData ?: return null
188 val crypto = ensureE2E(auth) ?: return null
189 val msgPlaintext = WhatsAppProtocol.padMessage(msg.toByteArray())
190 val dsmPlaintext = WhatsAppProtocol.padMessage(WhatsAppProtocol.deviceSentPlaintext(to, msg))
191 val ownUser = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".")
192 // Cache so we can re-encrypt+resend to a single device on a retry receipt.
193 recentSentDMs[id] = SentDM(to, type, msgPlaintext, dsmPlaintext)
194
195 val recipientDevices = getUserDevices(listOf(to)).ifEmpty { listOf(to) }
196 val ownDevices = getUserDevices(listOf("[email protected]"))
197 val allDevices = (recipientDevices + ownDevices).distinct()
198 // Log the actual device JIDs so device tests reveal whether the recipient is addressed by
199 // phone (…@s.whatsapp.net) or LID (…@lid). A phone-addressed <message to=..> carrying LID
200 // participant <to jid=…@lid> without addressing_mode="lid" can be dropped by the server.
201 WhatsAppDiag.log(TAG, "send: fanout to ${allDevices.size} device(s) [${allDevices.joinToString()}] (msg to=$to)")
202
203 val (encs, includeIdentity) = encryptForDevices(
204 crypto, allDevices, ownUser, auth.wid, msgPlaintext, dsmPlaintext,
205 )
206 WhatsAppDiag.log(TAG, "send: encrypted for ${encs.size} device(s) includeIdentity=$includeIdentity")
207 if (encs.isEmpty()) {
208 Log.error(TAG, "No devices could be encrypted for $to")
209 return null
210 }
211 val deviceIdentity = if (includeIdentity) accountDeviceIdentity() else null
212 return WhatsAppProtocol.buildFanOutMessageNode(
213 to = to,
214 id = id,
215 type = type,
216 participantEncs = encs,
217 includeDeviceIdentity = includeIdentity,
218 deviceIdentity = deviceIdentity,
219 extraEncAttrs = extraEncAttrs,
220 messageAttrs = messageAttrs,
221 )
222}
223
224/**
225 * Build a group text message. Delegates to [buildEncryptedGroupMessageNode] with a plain
226 * conversation proto.
227 */
228internal suspend fun WhatsAppClient.buildEncryptedGroupTextNode(
229 groupJid: String,
230 id: String,
231 body: String): WhatsAppProtocol.Node? =
232 buildEncryptedGroupMessageNode(groupJid, id, WhatsAppProtocol.buildConversationMessage(body))
233
234/**
235 * Build an arbitrary group message: sender-key encrypt the content (skmsg) and 1:1 fan out the
236 * SenderKeyDistributionMessage to every member device. Mirrors whatsmeow send.go sendGroup.
237 *
238 * The skmsg wire is produced by the Rust `communicate_signal` sender-key implementation
239 * ([RustWhatsAppCrypto.encryptGroup]/`createSenderKey`), NOT libsignal-client. Its SKDM +
240 * skmsg round-trip is self-loopback-verified on-device via
241 * [WhatsAppDiag.verifyGroupSenderKeyRoundTrip] (encrypt→decrypt through the same Rust path).
242 * Live peer interop still cannot be validated because the test number is banned.
243 */
244internal suspend fun WhatsAppClient.buildEncryptedGroupMessageNode(
245 groupJid: String,
246 id: String,
247 msg: WhatsAppE2EProto.Message,
248 type: String = "text",
249 extraEncAttrs: Map<String, String> = emptyMap(),
250 messageAttrs: Map<String, String> = emptyMap(),
251): WhatsAppProtocol.Node? {
252 val auth = authData ?: return null
253 val crypto = ensureE2E(auth) ?: return null
254 val contentPadded = WhatsAppProtocol.padMessage(msg.toByteArray())
255
256 val skmsgCiphertext = try {
257 crypto.encryptGroup(groupJid, contentPadded)
258 } catch (expected: Exception) {
259 Log.error(TAG, "Group sender-key encrypt failed for $groupJid", expected)
260 return null
261 }
262 val skdmBytes = crypto.createSenderKeyDistribution(groupJid)
263 val skdmPlaintext = WhatsAppProtocol.padMessage(
264 WhatsAppProtocol.senderKeyDistributionPlaintext(groupJid, skdmBytes)
265 )
266
267 // Meta AI / bots participate in a group via a special "hosted"/"bot" server and are NOT
268 // part of the group's end-to-end sender-key encryption — you literally cannot send them
269 // the group sender key, and including them aborts the whole send. The reference
270 // (whatsmeow prepareMessageNode) deletes hosted/hosted.lid devices for group sends for
271 // exactly this reason; the bot instead receives @mentions over its own message-secret
272 // channel. Keep every real user (phone + LID); drop only bot/hosted servers.
273 val participants = queryGroupParticipants(groupJid).filter { jid ->
274 val server = jid.substringAfter("@", "")
275 server != "bot" && server != "hosted" && server != "hosted.lid"
276 }
277 if (participants.isEmpty()) {
278 Log.status(TAG, "No user participants resolved for group $groupJid; cannot fan out SKDM")
279 return null
280 }
281 val devices = getUserDevices(participants).ifEmpty { participants }
282 val ownUser = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".")
283 val (encs, includeIdentity) = encryptForDevices(
284 crypto, devices, ownUser, auth.wid, skdmPlaintext, null,
285 )
286 if (encs.isEmpty()) {
287 Log.error(TAG, "No group devices could be encrypted for $groupJid")
288 return null
289 }
290 val skMsg = WhatsAppProtocol.Node(
291 tag = "enc",
292 attrs = mapOf("v" to "2", "type" to "skmsg"),
293 data = skmsgCiphertext,
294 )
295 val deviceIdentity = if (includeIdentity) accountDeviceIdentity() else null
296 return WhatsAppProtocol.buildFanOutMessageNode(
297 to = groupJid,
298 id = id,
299 type = type,
300 participantEncs = encs,
301 includeDeviceIdentity = includeIdentity,
302 deviceIdentity = deviceIdentity,
303 extraEnc = skMsg,
304 extraEncAttrs = extraEncAttrs,
305 messageAttrs = messageAttrs,
306 )
307}
308
309// The self-signed ADV device identity sent in the device-identity node for pkmsg sends.
310// UNVERIFIED: stored at pair time; null until paired with the new pairing flow.
311internal fun WhatsAppClient.accountDeviceIdentity(): ByteArray? {
312 val b64 = authData?.accountSignedDeviceIdentity?.takeIf { it.isNotEmpty() } ?: return null
313 return try { Base64.decode(b64, Base64.NO_WRAP) } catch (ignored: Exception) { null }
314}
315
316internal data class MediaUploadResult(
317 val url: String,
318 val directPath: String,
319)
320
321internal suspend fun WhatsAppClient.uploadMedia(
322 encryptedData: ByteArray,
323 mediaType: String,
324 token: String,
325): MediaUploadResult = withContext(Dispatchers.IO) {
326 val conn = mediaConn() ?: throw IllegalStateException("media_conn unavailable (no upload host/auth)")
327 val (host, auth) = conn
328 // whatsmeow upload.go: mmsType "image"/"video"/"audio"/"document"; stickers use the image bucket.
329 val mmsType = if (mediaType == "sticker") "image" else mediaType
330 val encAuth = java.net.URLEncoder.encode(auth, "UTF-8")
331 val encToken = java.net.URLEncoder.encode(token, "UTF-8")
332 val uploadUrl = "https://$host/mms/$mmsType/$token?auth=$encAuth&token=$encToken"
333 // WhatsApp's rupload endpoint expects POST (whatsmeow upload.go rawUpload). A PUT here
334 // returns 404, which is why media send was failing. No Content-Type is sent, matching
335 // the previous okhttp `toRequestBody(null)`.
336 val response = NetworkClient.execute(
337 uploadUrl,
338 "POST",
339 mapOf(
340 "Origin" to "https://web.whatsapp.com",
341 "Referer" to "https://web.whatsapp.com/",
342 "User-Agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
343 "(KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
344 ),
345 encryptedData,
346 connectTimeoutMs = MEDIA_CONNECT_TIMEOUT_MS,
347 readTimeoutMs = MEDIA_READ_TIMEOUT_MS,
348 )
349 if (!response.isSuccess) {
350 throw IllegalStateException("Media upload failed: HTTP ${response.status}")
351 }
352 if (response.bytes.isEmpty()) throw IllegalStateException("Empty upload response")
353 val json = JSONObject(response.text)
354 MediaUploadResult(
355 url = json.getString("url"),
356 directPath = json.getString("direct_path"),
357 )
358}
359
360suspend fun WhatsAppClient.sendMedia(
361 conversationId: String,
362 bytes: ByteArray,
363 mimeType: String,
364 fileName: String?
365): Boolean {
366 if (stateMutable.value !is State.Connected) return false
367 val ws = webSocket ?: return false
368 val to = extractJid(conversationId) ?: return false
369 val id = WhatsAppProtocol.generateMessageId(authData?.wid)
370
371 val mediaType = mediaTypeFor(mimeType)
372 val mediaKeyStr = mediaKeyFor(mediaType)
373
374 pendingMessageIDs.add(id)
375 if (bytes.size > MAX_FILE_SIZE) {
376 Log.error(TAG, "File too large: ${bytes.size} bytes (max $MAX_FILE_SIZE)")
377 pendingMessageIDs.remove(id)
378 return false
379 }
380 return try {
381 sendMediaPayload(ws, to, id, bytes, mimeType, fileName, mediaType, mediaKeyStr)
382 } catch (expected: Exception) {
383 WhatsAppDiag.log(TAG, "media: FAILED ${expected.message}")
384 Log.error(TAG, "Failed to send media", expected)
385 pendingMessageIDs.remove(id)
386 false
387 }
388}
389
390/** Media type string for a MIME type. */
391private fun mediaTypeFor(mimeType: String): String = when {
392 mimeType == "image/webp" -> "sticker"
393 mimeType.startsWith("image/") -> "image"
394 mimeType.startsWith("video/") -> "video"
395 mimeType.startsWith("audio/") -> "audio"
396 else -> "document"
397}
398
399/** Media key string for a media type. */
400private fun mediaKeyFor(mediaType: String): String = when (mediaType) {
401 "sticker" -> WhatsAppProtocol.MEDIA_KEY_STICKER
402 "image" -> WhatsAppProtocol.MEDIA_KEY_IMAGE
403 "video" -> WhatsAppProtocol.MEDIA_KEY_VIDEO
404 "audio" -> WhatsAppProtocol.MEDIA_KEY_AUDIO
405 else -> WhatsAppProtocol.MEDIA_KEY_DOCUMENT
406}
407
408/** Encrypt, upload, build, and send the media stanza. */
409private suspend fun WhatsAppClient.sendMediaPayload(
410 ws: com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket,
411 to: String,
412 id: String,
413 bytes: ByteArray,
414 mimeType: String,
415 fileName: String?,
416 mediaType: String,
417 mediaKeyStr: String,
418): Boolean {
419 WhatsAppDiag.log(TAG, "media: start type=$mediaType size=${bytes.size} to=$to")
420 val enc = WhatsAppProtocol.encryptMedia(bytes, mediaKeyStr)
421 val token = Base64.encodeToString(enc.fileEncSha256, Base64.URL_SAFE or Base64.NO_WRAP)
422 WhatsAppDiag.log(TAG, "media: encrypted, uploading…")
423 val upload = uploadMedia(enc.encryptedData, mediaType, token)
424 WhatsAppDiag.log(TAG, "media: uploaded url=${upload.url.take(LOG_URL_PREFIX_LENGTH)}")
425 val proto = WhatsAppProtocol.buildMediaProto(
426 upload.url, upload.directPath,
427 enc.mediaKey, enc.fileSha256, enc.fileEncSha256, enc.fileLength,
428 mimeType, fileName, mediaType
429 )
430 // Media must be Signal-encrypted + fanned out like any other message (an
431 // unencrypted node is dropped) and carry stanza type "media" + a "mediatype"
432 // enc attr. Ref whatsmeow send.go getTypeFromMessage / prepareMessageNode.
433 val encAttrs = mapOf("mediatype" to mediaType)
434 val node = if (to.contains("@g.us")) {
435 buildEncryptedGroupMessageNode(to, id, proto, type = "media", extraEncAttrs = encAttrs)
436 } else {
437 buildEncryptedMessageNode(to, id, proto, "media", extraEncAttrs = encAttrs)
438 } ?: run {
439 WhatsAppDiag.log(TAG, "media: build node FAILED (encryption produced no recipients)")
440 pendingMessageIDs.remove(id); return false
441 }
442 val sent = ws.send(WhatsAppProtocol.encodeNode(node))
443 WhatsAppDiag.log(TAG, "media: stanza sent=$sent id=$id")
444 if (!sent) pendingMessageIDs.remove(id)
445 return sent
446}