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

WhatsAppClientUtils.kt456 lines · 18.7 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient.State
4import com.vayunmathur.communicate.data.whatsapp.buildUsyncDevicesQuery
5import com.vayunmathur.communicate.data.whatsapp.decryptMedia
6import com.vayunmathur.communicate.data.whatsapp.encodeNode
7import com.vayunmathur.communicate.data.whatsapp.generateMessageId
8import android.util.Base64
9import com.vayunmathur.library.log.Log
10import com.vayunmathur.library.network.NetworkClient
11import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto
12import kotlinx.coroutines.Dispatchers
13import kotlinx.coroutines.launch
14import kotlinx.coroutines.withContext
15
16/**
17 * Resolve the device list for the given (bare) user JIDs via a usync query.
18 * Ref whatsmeow user.go GetUserDevices. Returns wire device JIDs ("user@server" for device 0,
19 * "user:N@server" otherwise). Returns empty on failure (callers fall back to the bare JID).
20 */
21internal suspend fun WhatsAppClient.getUserDevices(userJids: List<String>): List<String> {
22 if (userJids.isEmpty()) return emptyList()
23 val bareUsers =
24 userJids.map { it.substringBefore(":").let { u -> if (u.contains("@")) u else "[email protected]" } }
25 val iq = WhatsAppProtocol.buildUsyncDevicesQuery(bareUsers, generateMessageId(), generateMessageId())
26 val resp = sendIqAndWait(iq, timeoutMs = 10_000) ?: run {
27 WhatsAppDiag.log(TAG, "usync: no response for $bareUsers (timeout)")
28 return emptyList()
29 }
30 val list = resp.getChildByTag("usync")?.getChildByTag("list") ?: run {
31 WhatsAppDiag.log(TAG, "usync: malformed response (no list) for $bareUsers")
32 return emptyList()
33 }
34 val devices = collectUserDevices(list)
35 WhatsAppDiag.log(TAG, "usync: $bareUsers -> ${devices.size} device(s)")
36 return devices
37}
38
39/** Collect device JIDs from a usync user list. */
40private fun collectUserDevices(list: WhatsAppProtocol.Node): List<String> {
41 val devices = mutableListOf<String>()
42 list.getChildren().filter { it.tag == "user" }.forEach { user ->
43 val userJid = user.attrs["jid"] ?: return@forEach
44 val bareUser = userJid.substringBefore("@").substringBefore(":")
45 val server = userJid.substringAfter("@", "s.whatsapp.net")
46 val deviceList = user.getChildByTag("devices")?.getChildByTag("device-list") ?: return@forEach
47 deviceList.getChildren().filter { it.tag == "device" }.forEach { d ->
48 if (d.attrs["is_hosted"] == "true") return@forEach
49 val devId = d.attrs["id"]?.toIntOrNull() ?: return@forEach
50 devices.add(if (devId == 0) "$bareUser@$server" else "$bareUser:$devId@$server")
51 }
52 }
53 return devices
54}
55
56/**
57 * Track undecryptable messages.
58 * From Go handleWAUndecryptableMessage / trackUndecryptable.
59 */
60internal fun WhatsAppClient.trackUndecryptable(node: WhatsAppProtocol.Node) {
61 val from = node.attrs["from"] ?: return
62 val count = undecryptableTracker.merge(from, 1) { old, new -> old + new } ?: 1
63 Log.status(TAG, "Undecryptable message from $from (count: $count)")
64}
65
66/**
67 * Resolve JID: convert LID JIDs to phone number JIDs.
68 * Handles DM sender LID, own message LID, broadcast, and bot cases.
69 * From Go resolveJID / rerouteWAMessage — 5 distinct rerouting cases.
70 */
71internal fun WhatsAppClient.resolveJID(jid: String): String {
72 // Case 1: Not a LID — no rerouting needed
73 if (!jid.contains("@lid")) return jid
74
75 // Case 2: Direct LID→phone mapping from cache
76 lidToPhoneMap[jid]?.let { return it }
77
78 // Case 3: Own LID matches
79 val ownLid = authData?.lid
80 if (ownLid != null && ownLid.isNotEmpty() && jid == ownLid) {
81 return authData?.wid ?: jid
82 }
83
84 // Case 4: Bot server JIDs (Go rerouteWAMessage bot server case)
85 if (jid.contains("@bot")) {
86 return jid // Bot JIDs are valid as-is
87 }
88
89 // Case 5: Extract user part and check LID map without server suffix
90 val userPart = jid.substringBefore("@")
91 lidToPhoneMap.entries.find { it.key.startsWith("$userPart@") }?.let { return it.value }
92
93 return jid
94}
95
96/** Look up a device contact display name for an E.164 number (null if none / no permission). */
97internal fun WhatsAppClient.resolveDeviceContactName(phoneE164: String?): String? {
98 if (phoneE164.isNullOrEmpty()) return null
99 return try {
100 val uri = android.net.Uri.withAppendedPath(
101 android.provider.ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
102 android.net.Uri.encode(phoneE164),
103 )
104 appContext.contentResolver.query(
105 uri,
106 arrayOf(android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME),
107 null, null, null,
108 )?.use { c -> if (c.moveToFirst()) c.getString(0)?.takeIf { it.isNotBlank() } else null }
109 } catch (ignored: Exception) {
110 null
111 }
112}
113
114/** Inflate a zlib (RFC 1950) compressed buffer. WhatsApp history blobs are zlib-compressed. */
115internal fun WhatsAppClient.inflateZlib(data: ByteArray): ByteArray {
116 val inflater = java.util.zip.Inflater()
117 inflater.setInput(data)
118 val out = java.io.ByteArrayOutputStream(maxOf(64, data.size * 4))
119 val buf = ByteArray(16384)
120 try {
121 while (!inflater.finished()) {
122 val n = inflater.inflate(buf)
123 if (n == 0 && isInflateDone(inflater)) break
124 out.write(buf, 0, n)
125 }
126 } finally {
127 inflater.end()
128 }
129 return out.toByteArray()
130}
131
132/** True when the inflater is exhausted (finished, missing dictionary, or needs input). */
133private fun isInflateDone(inflater: java.util.zip.Inflater): Boolean =
134 inflater.finished() || inflater.needsDictionary() || inflater.needsInput()
135
136/**
137 * Download and decrypt media from a WhatsApp media message.
138 * Integrates WhatsAppProtocol.decryptMedia() for incoming media.
139 * From Go whatsmeow.Download.
140 */
141suspend fun WhatsAppClient.downloadMedia(
142 url: String,
143 mediaKey: ByteArray,
144 mediaType: String,
145): ByteArray? = withContext(Dispatchers.IO) {
146 try {
147 val response = NetworkClient.execute(
148 url,
149 "GET",
150 mapOf(
151 "Origin" to "https://web.whatsapp.com",
152 "Referer" to "https://web.whatsapp.com/",
153 "User-Agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
154 ),
155 connectTimeoutMs = MEDIA_CONNECT_TIMEOUT_MS,
156 readTimeoutMs = MEDIA_READ_TIMEOUT_MS,
157 )
158 if (!response.isSuccess) {
159 Log.error(TAG, "Media download failed: HTTP ${response.status}")
160 return@withContext null
161 }
162 val encrypted = response.bytes
163 if (encrypted.isEmpty()) return@withContext null
164 WhatsAppProtocol.decryptMedia(encrypted, mediaKey, mediaType)
165 } catch (expected: Exception) {
166 Log.error(TAG, "Media download/decrypt failed", expected)
167 null
168 }
169}
170
171fun WhatsAppClient.isLoggedIn(): Boolean {
172 return authData != null && stateMutable.value is State.Connected
173}
174
175/**
176 * Download + decrypt an incoming media message and cache it locally, returning a
177 * [com.vayunmathur.communicate.data.whatsapp.MessageAttachment] pointing at the decrypted file (file://
178 * URL) so the UI renders it inline. Returns null for non-media messages or on
179 * download/decrypt failure (the "[Image]"/"[Video]" placeholder body then remains).
180 * Ref whatsmeow Download.
181 */
182internal suspend fun WhatsAppClient.buildIncomingMediaAttachment(
183 e2e: WhatsAppE2EProto.Message,
184 msgId: String,
185): com.vayunmathur.communicate.data.whatsapp.MessageAttachment? {
186 val spec = mediaSpecFor(e2e) ?: return null
187 if (spec.mediaKey.isEmpty()) return null
188 val downloadUrl = downloadUrlFor(spec) ?: return null
189 val bytes = downloadMedia(downloadUrl, spec.mediaKey, spec.keyInfo) ?: return null
190 return cacheIncomingMedia(spec, msgId, bytes)
191}
192
193/** Media download/cache spec for an incoming message. */
194private data class IncomingMediaSpec(
195 val url: String,
196 val directPath: String,
197 val mediaKey: ByteArray,
198 val encSha: ByteArray,
199 val mime: String?,
200 val keyInfo: String,
201 val type: String,
202 val width: Int,
203 val height: Int,
204 val fileName: String?,
205 val ext: String,
206)
207
208/** Extract the media spec from the message, or null for non-media. */
209private fun mediaSpecFor(e2e: WhatsAppE2EProto.Message): IncomingMediaSpec? {
210 when {
211 e2e.hasImageMessage() -> e2e.imageMessage.let {
212 return IncomingMediaSpec(
213 url = it.url, directPath = it.directPath, mediaKey = it.mediaKey.toByteArray(),
214 encSha = it.fileEncSha256.toByteArray(), mime = it.mimetype.ifEmpty { "image/jpeg" },
215 keyInfo = WhatsAppProtocol.MEDIA_KEY_IMAGE, type = "image",
216 width = it.width, height = it.height, fileName = null, ext = "jpg")
217 }
218 e2e.hasStickerMessage() -> e2e.stickerMessage.let {
219 return IncomingMediaSpec(
220 url = it.url, directPath = it.directPath, mediaKey = it.mediaKey.toByteArray(),
221 encSha = it.fileEncSha256.toByteArray(), mime = it.mimetype.ifEmpty { "image/webp" },
222 keyInfo = WhatsAppProtocol.MEDIA_KEY_STICKER, type = "sticker",
223 width = it.width, height = it.height, fileName = null, ext = "webp")
224 }
225 e2e.hasVideoMessage() -> e2e.videoMessage.let {
226 return IncomingMediaSpec(
227 url = it.url, directPath = it.directPath, mediaKey = it.mediaKey.toByteArray(),
228 encSha = it.fileEncSha256.toByteArray(), mime = it.mimetype.ifEmpty { "video/mp4" },
229 keyInfo = WhatsAppProtocol.MEDIA_KEY_VIDEO, type = "video",
230 width = it.width, height = it.height, fileName = null, ext = "mp4")
231 }
232 e2e.hasAudioMessage() -> e2e.audioMessage.let {
233 return IncomingMediaSpec(
234 url = it.url, directPath = it.directPath, mediaKey = it.mediaKey.toByteArray(),
235 encSha = it.fileEncSha256.toByteArray(), mime = it.mimetype.ifEmpty { "audio/ogg" },
236 keyInfo = WhatsAppProtocol.MEDIA_KEY_AUDIO, type = "audio",
237 width = 0, height = 0, fileName = null, ext = "ogg")
238 }
239 e2e.hasDocumentMessage() -> e2e.documentMessage.let {
240 return IncomingMediaSpec(
241 url = it.url, directPath = it.directPath, mediaKey = it.mediaKey.toByteArray(),
242 encSha = it.fileEncSha256.toByteArray(), mime = it.mimetype.ifEmpty { null },
243 keyInfo = WhatsAppProtocol.MEDIA_KEY_DOCUMENT, type = "file",
244 width = 0, height = 0,
245 fileName = it.fileName.ifEmpty { it.title.ifEmpty { null } },
246 ext = it.fileName.substringAfterLast('.', "").ifEmpty { "bin" })
247 }
248 else -> return null
249 }
250}
251
252/** Resolve the download URL (direct or via media host). */
253private suspend fun WhatsAppClient.downloadUrlFor(
254 spec: IncomingMediaSpec,
255): String? {
256 if (spec.url.isNotEmpty()) return spec.url
257 if (spec.directPath.isEmpty()) return null
258 val host = mediaConn()?.first ?: return null
259 val mmsType = when (spec.type) {
260 "sticker", "image" -> "image"
261 "video" -> "video"
262 "audio" -> "audio"
263 else -> "document"
264 }
265 val hash = Base64.encodeToString(spec.encSha, Base64.URL_SAFE or Base64.NO_WRAP)
266 return "https://$host${spec.directPath}&hash=$hash&mms-type=$mmsType&__wa-mms="
267}
268
269/** Write downloaded bytes to the media cache and build the attachment. */
270private fun WhatsAppClient.cacheIncomingMedia(
271 spec: IncomingMediaSpec,
272 msgId: String,
273 bytes: ByteArray,
274): com.vayunmathur.communicate.data.whatsapp.MessageAttachment? {
275 return try {
276 val dir = java.io.File(appContext.cacheDir, "whatsapp_media")
277 dir.mkdirs()
278 val safeName = msgId.replace(Regex("[^A-Za-z0-9._-]"), "_")
279 val file = java.io.File(dir, "$safeName.${spec.ext}")
280 if (!(file.exists() && file.length() > 0)) file.writeBytes(bytes)
281 com.vayunmathur.communicate.data.whatsapp.MessageAttachment(
282 url = "file://${file.absolutePath}",
283 mimeType = spec.mime,
284 attachmentType = spec.type,
285 fileName = spec.fileName,
286 width = spec.width,
287 height = spec.height,
288 )
289 } catch (expected: Exception) {
290 Log.status(TAG, "Failed to cache incoming media for $msgId", expected)
291 null
292 }
293}
294
295/**
296 * Logout from WhatsApp server and clear local data.
297 * From whatsmeow LogoutRemote
298 */
299fun WhatsAppClient.logoutRemote() {
300 scope.launch {
301 val ws = webSocket
302 val ownJid = authData?.wid ?: ""
303 if (ws != null && ownJid.isNotEmpty()) {
304 val logoutNode = WhatsAppProtocol.Node(
305 tag = "iq",
306 attrs = mapOf(
307 "to" to "s.whatsapp.net",
308 "type" to "set",
309 "xmlns" to "md",
310 "id" to WhatsAppProtocol.generateMessageId(authData?.wid),
311 ),
312 content = listOf(
313 WhatsAppProtocol.Node(
314 tag = "remove-companion-device",
315 attrs = mapOf("jid" to ownJid, "reason" to "user_initiated")
316 )
317 )
318 )
319 try {
320 ws.send(WhatsAppProtocol.encodeNode(logoutNode))
321 } catch (expected: Exception) {
322 Log.error(TAG, "Failed to send logout", expected)
323 }
324 }
325 stop()
326 }
327}
328
329internal fun WhatsAppClient.extractJid(conversationId: String): String? {
330 // Conversation ID arrives double-prefixed: the bridge prepends the source idPrefix ("wa")
331 // to our already-"wa:"-prefixed id, giving "wa:wa:{jid}". Strip all leading "wa:".
332 var s = conversationId
333 while (s.startsWith("wa:")) s = s.removePrefix("wa:")
334 return s.ifEmpty { null }
335}
336
337/** Strip the DB source prefix ("wa:") from a stored message id to recover the raw
338 * WhatsApp message id that the wire protocol (receipts, reaction keys) expects. */
339internal fun WhatsAppClient.extractMessageId(messageId: String): String {
340 var s = messageId
341 while (s.startsWith("wa:")) s = s.removePrefix("wa:")
342 return s
343}
344
345/** True when [jid] refers to the local user's own account (phone wid or LID), comparing the
346 * bare user part so device/agent suffixes and PN/LID addressing don't matter. */
347internal fun WhatsAppClient.isOwnJid(jid: String?): Boolean {
348 if (jid.isNullOrEmpty()) return false
349 fun user(j: String?) = j?.substringBefore("@")?.substringBefore(":")?.substringBefore(".")
350 val u = user(jid) ?: return false
351 if (u.isEmpty()) return false
352 return u == user(authData?.wid) || u == user(authData?.lid)
353}
354
355internal fun WhatsAppClient.generateMessageId(): String {
356 return WhatsAppProtocol.generateMessageId(authData?.wid)
357}
358
359internal fun WhatsAppClient.generateRef(): String {
360 val bytes = ByteArray(16)
361 random.nextBytes(bytes)
362 return Base64.encodeToString(bytes, Base64.NO_WRAP)
363}
364
365internal fun WhatsAppClient.generateClientId(): String {
366 val bytes = ByteArray(16)
367 random.nextBytes(bytes)
368 return Base64.encodeToString(bytes, Base64.NO_WRAP)
369}
370
371internal fun WhatsAppClient.generateToken(): String {
372 val bytes = ByteArray(24)
373 random.nextBytes(bytes)
374 return Base64.encodeToString(bytes, Base64.NO_WRAP)
375}
376
377internal suspend fun WhatsAppClient.resolveName(jid: String): String {
378 // Bot accounts (Meta AI) have no phone number — give them a friendly name.
379 if (jid.contains("@bot")) return "Meta AI"
380 return nameCache.getOrPut(jid) {
381 // Display the phone number, stripping any device/agent/group suffixes
382 // ("1234:1@…", "1234.5@…", "[email protected]").
383 val phone = jid.substringBefore("@")
384 .substringBefore(":")
385 .substringBefore(".")
386 .substringBefore("-")
387 "+$phone"
388 }
389}
390
391/**
392 * Replace the raw "@<number>" mention tokens WhatsApp embeds in message text with the
393 * mentioned contact's display name (or "You" for the local user, "Meta AI" for the bot),
394 * using [WhatsAppMessage.mentionedJids] to know who each token refers to.
395 */
396internal suspend fun WhatsAppClient.resolveMentionsInBody(body: String, mentionedJids: List<String>): String {
397 if (mentionedJids.isEmpty() || !body.contains("@")) return body
398 var result = body
399 for (jid in mentionedJids) {
400 val userPart = jid.substringBefore("@").substringBefore(":").substringBefore(".")
401 if (userPart.isEmpty()) continue
402 val resolved = resolveJID(jid)
403 val name = when {
404 resolved == authData?.wid || resolved == authData?.lid -> "You"
405 else -> resolveName(resolved)
406 }
407 result = result.replace("@$userPart", "@$name")
408 }
409 return result
410}
411
412fun WhatsAppClient.getContactSuggestions(query: String): List<ContactSuggestion> {
413 // Return cached contacts matching query
414 return nameCache.entries
415 .filter { it.value.contains(query, ignoreCase = true) }
416 .map { ContactSuggestion(it.value, null, null, MessageSource.WHATSAPP) }
417 .take(MAX_SUGGESTIONS)
418}
419
420/** LID-routed sender plus whether the message is ours (sent from another linked device). */
421internal fun WhatsAppClient.resolveChatSender(message: WhatsAppMessage): Pair<String, Boolean> {
422 // LID routing (Go rerouteWAMessage)
423 val sender = resolveJID(message.participant ?: message.from)
424 // Treat the message as ours when it was sent by our own account from another
425 // device — either flagged during parse (DeviceSentMessage / recipient attr) or the
426 // sender JID resolves to our own user (the common group case: from=group,
427 // participant=ourJid). Otherwise it wrongly renders as an incoming bubble "from"
428 // ourselves.
429 val fromMe = message.isFromMe || isOwnJid(sender) ||
430 isOwnJid(message.participant ?: message.from)
431 return sender to fromMe
432}
433
434/** Cache push name from notify attr (Go syncGhost / PushName handling). */
435internal fun WhatsAppClient.cacheNotifyName(node: WhatsAppProtocol.Node, sender: String) {
436 val notifyName = node.attrs["notify"]
437 if (!notifyName.isNullOrEmpty()) {
438 nameCache[sender] = notifyName
439 }
440}
441
442/** Store poll options + secret for later vote encryption/decryption (Go handleWAMessage/poll case). */
443internal suspend fun WhatsAppClient.rememberInboundPoll(message: WhatsAppMessage) {
444 // Handle poll creation — store option hashes.
445 if (message.pollData != null && !message.pollData.isPollVote) {
446 storePollOptions(message.id, message.pollData.options)
447 }
448
449 // Store poll secrets from incoming polls for vote encryption/decryption.
450 if (message.pollData != null && !message.pollData.isPollVote && message.e2eMessage != null) {
451 val secret = message.e2eMessage.messageContextInfo?.messageSecret?.toByteArray()
452 if (secret != null) storePollSecret(message.id, secret)
453 }
454}
455
456private const val MAX_SUGGESTIONS = 10