Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / WhatsAppClientInbound.kt
WhatsAppClientInbound.kt710 lines · 27.8 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp |
| 2 | |
| 3 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient.State |
| 4 | import com.vayunmathur.communicate.data.whatsapp.buildAck |
| 5 | import com.vayunmathur.communicate.data.whatsapp.decodeNode |
| 6 | import com.vayunmathur.communicate.data.whatsapp.decryptPollVote |
| 7 | import com.vayunmathur.communicate.data.whatsapp.encodeNode |
| 8 | import com.vayunmathur.communicate.data.whatsapp.parseMessage |
| 9 | import com.vayunmathur.communicate.data.whatsapp.pollCreation |
| 10 | import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto |
| 11 | import com.vayunmathur.library.log.Log |
| 12 | import kotlinx.coroutines.launch |
| 13 | |
| 14 | private const val MS_PER_SECOND = 1000L |
| 15 | |
| 16 | /** Stanza tags that require an ack (messages + calls during offline flush). */ |
| 17 | private val ACKED_TAGS = setOf("message", "notification", "receipt", "call") |
| 18 | |
| 19 | fun WhatsAppClient.handleIncomingMessage(data: ByteArray) { |
| 20 | scope.launch { |
| 21 | try { |
| 22 | val node = WhatsAppProtocol.decodeNode(data) |
| 23 | WhatsAppDiag.log(TAG, "← login stanza ${nodeSummary(node)}") |
| 24 | |
| 25 | handleAckStanza(node) |
| 26 | if (handleIqResponse(node)) return@launch |
| 27 | if (handleControlStanza(node)) return@launch |
| 28 | if (node.tag != "message") return@launch |
| 29 | handleChatMessage(node) |
| 30 | } catch (expected: Exception) { |
| 31 | Log.error(TAG, "Failed to handle incoming message", expected) |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /** Log server acks for outbound stanzas and ack inbound ones. */ |
| 37 | private fun WhatsAppClient.handleAckStanza(node: WhatsAppProtocol.Node) { |
| 38 | // Server ack for an outbound stanza. An ack with an `error` attr means the server |
| 39 | // REJECTED the message (it will never be delivered) — surface it prominently so a |
| 40 | // "sent but not delivered" report can be diagnosed from logs. |
| 41 | if (node.tag == "ack") { |
| 42 | val ackErr = node.attrs["error"] |
| 43 | if (ackErr != null) { |
| 44 | WhatsAppDiag.log( |
| 45 | TAG, |
| 46 | "← ack REJECTED class=${node.attrs["class"]} id=${node.attrs["id"]} error=$ackErr") |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | // Ack messages, notifications, receipts AND calls (whatsmeow/receipt.go + |
| 51 | // call.go). Calls MUST be acked too: during the post-login offline flush the server |
| 52 | // is flow-controlled and head-of-line — if the offline <call> offers aren't acked it |
| 53 | // stops delivering, so queued <message> stanzas never arrive ("stuck syncing"). |
| 54 | if (node.tag in ACKED_TAGS) { |
| 55 | val ack = WhatsAppProtocol.buildAck( |
| 56 | nodeClass = node.tag, |
| 57 | nodeId = node.attrs["id"] ?: "", |
| 58 | from = node.attrs["from"] ?: "", |
| 59 | participant = node.attrs["participant"], |
| 60 | recipient = node.attrs["recipient"], |
| 61 | type = if (node.tag != "message") node.attrs["type"] else null, |
| 62 | ) |
| 63 | webSocket?.send(WhatsAppProtocol.encodeNode(ack)) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /** Complete a pending IQ request; true when the stanza was consumed. */ |
| 68 | private fun WhatsAppClient.handleIqResponse(node: WhatsAppProtocol.Node): Boolean { |
| 69 | // Complete any pending IQ request awaiting this response (prekey fetch/upload). |
| 70 | if (node.tag == "iq") { |
| 71 | val iqId = node.attrs["id"] |
| 72 | val pending = if (iqId != null) pendingIqs.remove(iqId) else null |
| 73 | if (pending != null) { |
| 74 | pending.complete(node) |
| 75 | return true |
| 76 | } |
| 77 | } |
| 78 | return false |
| 79 | } |
| 80 | |
| 81 | /** Connection/control stanzas; true when the stanza was consumed. */ |
| 82 | private suspend fun WhatsAppClient.handleControlStanza(node: WhatsAppProtocol.Node): Boolean { |
| 83 | // Handle connection failure events (Go handleWALogout, ClientOutdated, TemporaryBan) |
| 84 | if (node.tag == "failure") { |
| 85 | handleFailureStanza(node) |
| 86 | return true |
| 87 | } |
| 88 | |
| 89 | if (node.tag == "stream:error") { |
| 90 | handleStreamError(node) |
| 91 | return true |
| 92 | } |
| 93 | |
| 94 | // Handle the server <success> stanza — the real authentication signal |
| 95 | // (Go connectionevents.go handleConnectSuccess). Until this arrives the Noise |
| 96 | // transport is up but the login is not yet authenticated. |
| 97 | if (node.tag == "success") { |
| 98 | handleConnectSuccess(node) |
| 99 | return true |
| 100 | } |
| 101 | |
| 102 | // Handle receipts with per-sender batching (Go handleWAReceipt) |
| 103 | if (node.tag == "receipt") { |
| 104 | handleReceipt(node) |
| 105 | return true |
| 106 | } |
| 107 | |
| 108 | // Handle chat presence with media type differentiation (Go handleWAChatPresence) |
| 109 | if (node.tag == "chatstate") { |
| 110 | handleChatPresence(node) |
| 111 | return true |
| 112 | } |
| 113 | |
| 114 | return handleNotificationStanza(node) |
| 115 | } |
| 116 | |
| 117 | /** Login <failure> stanza → disconnected state. */ |
| 118 | private fun WhatsAppClient.handleFailureStanza(node: WhatsAppProtocol.Node) { |
| 119 | val reason = node.attrs["reason"] ?: "unknown" |
| 120 | WhatsAppDiag.log(TAG, "login <failure> reason=$reason full=${nodeSummary(node)}") |
| 121 | when (reason) { |
| 122 | "401" -> { |
| 123 | stateMutable.value = State.Disconnected("Logged out from WhatsApp") |
| 124 | scope.launch { WhatsAppAuthData.clear(appContext) } |
| 125 | authData = null |
| 126 | } |
| 127 | "405" -> stateMutable.value = State.Disconnected("Client outdated — update required") |
| 128 | "503" -> stateMutable.value = State.Disconnected("Temporarily banned") |
| 129 | else -> stateMutable.value = State.Disconnected("Connection failed: $reason") |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /** stream:error → logout/replace/restart handling. */ |
| 134 | private suspend fun WhatsAppClient.handleStreamError(node: WhatsAppProtocol.Node) { |
| 135 | val errorNode = node.content.firstOrNull() |
| 136 | val code = node.attrs["code"] |
| 137 | val conflict = node.getChildByTag("conflict") |
| 138 | val conflictType = conflict?.attrs?.get("type") |
| 139 | WhatsAppDiag.log( |
| 140 | TAG, |
| 141 | "login stream:error code=$code child=${errorNode?.tag} conflictType=$conflictType") |
| 142 | when { |
| 143 | // Device removed from the account on the phone, or another session took over. |
| 144 | conflict != null || code == "401" -> { |
| 145 | suppressReconnect = true |
| 146 | if (conflictType == "device_removed" || code == "401") { |
| 147 | WhatsAppDiag.log(TAG, "device removed/logged out — clearing credentials") |
| 148 | scope.launch { WhatsAppAuthData.clear(appContext) } |
| 149 | authData = null |
| 150 | stateMutable.value = State.NeedsSetup |
| 151 | scope.launch { eventsMutable.emit(WhatsAppEvent.SourceLoggedOut(source)) } |
| 152 | } else { |
| 153 | // "replaced" or other conflict: another WhatsApp session is active. |
| 154 | stateMutable.value = State.Disconnected("Session replaced by another device") |
| 155 | } |
| 156 | } |
| 157 | // 515 = restart required (normal after first pair-login); allow reconnect. |
| 158 | code == "515" -> stateMutable.value = State.Disconnected("Restart required") |
| 159 | else -> stateMutable.value = State.Disconnected("Stream error${if (code != null) " $code" else ""}") |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /** Notification + ib stanzas; true when consumed. */ |
| 164 | private suspend fun WhatsAppClient.handleNotificationStanza(node: WhatsAppProtocol.Node): Boolean { |
| 165 | // Handle notifications (group changes, mute/pin/archive) |
| 166 | if (node.tag == "notification") { |
| 167 | handleNotification(node) |
| 168 | return true |
| 169 | } |
| 170 | |
| 171 | // <ib> info blocks: respond to <dirty> with <clean> so the phone finishes "syncing". |
| 172 | if (node.tag == "ib") { |
| 173 | node.getChildByTag("dirty")?.let { handleDirty(it) } |
| 174 | node.getChildByTag("offline_preview")?.let { |
| 175 | val count = it.attrs["count"] |
| 176 | val msg = it.attrs["message"] |
| 177 | val notif = it.attrs["notification"] |
| 178 | val receipt = it.attrs["receipt"] |
| 179 | WhatsAppDiag.log(TAG, "offline preview: count=$count msg=$msg notif=$notif receipt=$receipt") |
| 180 | } |
| 181 | node.getChildByTag("offline")?.let { |
| 182 | WhatsAppDiag.log(TAG, "offline sync completed: count=${it.attrs["count"]}") |
| 183 | } |
| 184 | return true |
| 185 | } |
| 186 | return false |
| 187 | } |
| 188 | |
| 189 | /** Message stanzas: decrypt, route poll/history/key-share, emit. */ |
| 190 | private suspend fun WhatsAppClient.handleChatMessage(node: WhatsAppProtocol.Node) { |
| 191 | |
| 192 | if (node.tag != "message") return |
| 193 | val message = decryptChatMessage(node) ?: return |
| 194 | if (handleProtocolMessage(node, message)) return |
| 195 | emitChatMessage(node, message) |
| 196 | } |
| 197 | |
| 198 | /** Decrypt the stanza; null when undecryptable or undecrypted. */ |
| 199 | private suspend fun WhatsAppClient.decryptChatMessage(node: WhatsAppProtocol.Node): WhatsAppMessage? { |
| 200 | // Check for undecryptable messages (Go handleWAUndecryptableMessage) |
| 201 | val encNode = node.getChildByTag("enc") |
| 202 | if (encNode?.data == null && node.attrs["type"] == "text") { |
| 203 | // No ciphertext at all (a decrypt-fail placeholder). Track it AND ask the |
| 204 | // sender to re-encrypt, otherwise this first-of-session message is lost for |
| 205 | // good. sendRetryReceipt is self-capped at 5 attempts. |
| 206 | trackUndecryptable(node) |
| 207 | sendRetryReceipt(node) |
| 208 | return null |
| 209 | } |
| 210 | |
| 211 | val crypto = authData?.let { ensureE2E(it) } |
| 212 | var decryptFailed = false |
| 213 | val message = WhatsAppProtocol.parseMessage(node) { senderJid, encType, data -> |
| 214 | if (crypto == null) { |
| 215 | decryptFailed = true |
| 216 | return@parseMessage null |
| 217 | } |
| 218 | val result = try { |
| 219 | when (encType) { |
| 220 | "pkmsg" -> crypto.decryptDM(senderJid, isPreKey = true, ciphertext = data) |
| 221 | "msg" -> crypto.decryptDM(senderJid, isPreKey = false, ciphertext = data) |
| 222 | "skmsg" -> crypto.decryptGroup(node.attrs["from"] ?: "", senderJid, data) |
| 223 | else -> null |
| 224 | } |
| 225 | } catch (expected: Exception) { |
| 226 | Log.error(TAG, "E2E decrypt failed ($encType) from $senderJid", expected) |
| 227 | null |
| 228 | } |
| 229 | if (result == null) decryptFailed = true |
| 230 | result |
| 231 | } ?: return null |
| 232 | |
| 233 | // Decrypt failure: ask the sender to re-encrypt (Go decryptMessages -> sendRetryReceipt). |
| 234 | if (decryptFailed) { |
| 235 | val encTypes = node.getChildren() |
| 236 | .filter { it.tag == "enc" } |
| 237 | .mapNotNull { it.attrs["type"] } |
| 238 | WhatsAppDiag.log(TAG, "recv: DECRYPT FAILED id=${node.attrs["id"]}" + |
| 239 | "type=${node.attrs["type"]} from=${node.attrs["from"]} encs=$encTypes") |
| 240 | sendRetryReceipt(node) |
| 241 | return null |
| 242 | } |
| 243 | return message |
| 244 | } |
| 245 | |
| 246 | /** |
| 247 | * Protocol-level routing (poll log, history sync, key share, SKDM, status, dedup). |
| 248 | * True when the message was consumed. |
| 249 | */ |
| 250 | private suspend fun WhatsAppClient.handleProtocolMessage( |
| 251 | node: WhatsAppProtocol.Node, |
| 252 | message: WhatsAppMessage, |
| 253 | ): Boolean { |
| 254 | if (node.attrs["type"] == "poll" || WhatsAppProtocol.pollCreation(message.e2eMessage) != null || |
| 255 | message.e2eMessage?.hasPollUpdateMessage() == true |
| 256 | ) { |
| 257 | WhatsAppDiag.log( |
| 258 | TAG, |
| 259 | "poll recv: id=${message.id} parsedType=${message.messageType} " + |
| 260 | "create=${WhatsAppProtocol.pollCreation(message.e2eMessage) != null} " + |
| 261 | "vote=${message.e2eMessage?.hasPollUpdateMessage()} " + |
| 262 | "q=${message.pollData?.question} opts=${message.pollData?.options?.size} " + |
| 263 | "fromMe=${message.isFromMe}", |
| 264 | ) |
| 265 | } |
| 266 | |
| 267 | // History sync: the phone pushes message history as a protocolMessage notification |
| 268 | // (inline for the initial bootstrap, or a downloadable encrypted blob otherwise). |
| 269 | val histNotif = message.e2eMessage |
| 270 | ?.takeIf { it.hasProtocolMessage() && it.protocolMessage.hasHistorySyncNotification() } |
| 271 | ?.protocolMessage?.historySyncNotification |
| 272 | if (histNotif != null) { |
| 273 | scope.launch { handleHistorySync(histNotif, message.id) } |
| 274 | return true |
| 275 | } |
| 276 | |
| 277 | // App-state sync keys, shared by our primary as a peer protocolMessage. |
| 278 | val keyShare = message.e2eMessage |
| 279 | ?.takeIf { it.hasProtocolMessage() && it.protocolMessage.hasAppStateSyncKeyShare() } |
| 280 | ?.protocolMessage?.appStateSyncKeyShare |
| 281 | if (keyShare != null) { |
| 282 | scope.launch { handleAppStateKeyShare(keyShare) } |
| 283 | return true |
| 284 | } |
| 285 | |
| 286 | // Process inbound sender-key distribution so future group skmsg decrypt. |
| 287 | // UNVERIFIED: group sender-key wire mapping not runtime-tested. |
| 288 | val skdm = message.e2eMessage?.takeIf { it.hasSenderKeyDistributionMessage() } |
| 289 | ?.senderKeyDistributionMessage |
| 290 | if (skdm != null) { |
| 291 | processSkdm(message, skdm) |
| 292 | // A SKDM-only message carries no user-visible content (types as "ignore"); once |
| 293 | // the key is stored there's nothing to display, so stop before emitting a blank |
| 294 | // bubble. Messages that bundle the SKDM with real content fall through to render. |
| 295 | if (message.messageType == "ignore") return true |
| 296 | } |
| 297 | |
| 298 | // Skip status broadcasts (Go handleWAMessage status@broadcast check) |
| 299 | if (message.from.startsWith("status@broadcast")) { |
| 300 | Log.dev(TAG, "Skipping status broadcast from ${message.participant}") |
| 301 | return true |
| 302 | } |
| 303 | |
| 304 | // Pending message dedup (Go handleWAMessage pendingMessages check) |
| 305 | if (pendingMessageIDs.remove(message.id)) { |
| 306 | Log.dev(TAG, "Ignoring pending message ${message.id}") |
| 307 | return true |
| 308 | } |
| 309 | return false |
| 310 | } |
| 311 | |
| 312 | /** Process an inbound sender-key distribution message. */ |
| 313 | private suspend fun WhatsAppClient.processSkdm( |
| 314 | message: WhatsAppMessage, |
| 315 | skdm: WhatsAppE2EProto.SenderKeyDistributionMessage, |
| 316 | ) { |
| 317 | val crypto = authData?.let { ensureE2E(it) } ?: return |
| 318 | try { |
| 319 | crypto.processSenderKeyDistribution( |
| 320 | message.from, |
| 321 | message.participant ?: message.from, |
| 322 | skdm.axolotlSenderKeyDistributionMessage.toByteArray(), |
| 323 | ) |
| 324 | } catch (expected: Exception) { |
| 325 | Log.status(TAG, "Failed to process SKDM", expected) |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | /** Emit the user-visible message (revoke/edit/timer/poll/reaction/regular). */ |
| 330 | private suspend fun WhatsAppClient.emitChatMessage( |
| 331 | node: WhatsAppProtocol.Node, |
| 332 | message: WhatsAppMessage, |
| 333 | ) { |
| 334 | val (sender, fromMe) = resolveChatSender(message) |
| 335 | cacheNotifyName(node, sender) |
| 336 | |
| 337 | // Revoke/edit/ephemeral consume the message outright. |
| 338 | if (emitSpecialMessage(message, sender)) return |
| 339 | |
| 340 | rememberInboundPoll(message) |
| 341 | val displayBody = resolveDisplayBody(message) |
| 342 | |
| 343 | // Poll votes + reactions consume the message outright. |
| 344 | if (emitPollOrReaction(message, sender, fromMe)) return |
| 345 | |
| 346 | // For group chats, make sure the conversation exists (named + flagged as a |
| 347 | // group) before we store the message — a freshly joined group isn't in history |
| 348 | // sync, so otherwise it would only ever be a nameless bare row. Deduped + |
| 349 | // awaited so the metadata lands before the message's unread bump. |
| 350 | if (message.from.contains("@g.us")) { |
| 351 | fetchAndEmitGroupInfo(message.from) |
| 352 | } |
| 353 | |
| 354 | // Download + decrypt any inline media so it renders in-thread instead of as a |
| 355 | // bare "[Image]"/"[Video]" placeholder. Null for non-media or on failure. |
| 356 | val mediaAttachment = message.e2eMessage?.let { |
| 357 | buildIncomingMediaAttachment(it, message.id) |
| 358 | } |
| 359 | val mediaAttachments = listOfNotNull(mediaAttachment) |
| 360 | |
| 361 | // Messages the user sent from another linked device (fromMe) are synced |
| 362 | // to us as outgoing, not incoming — emit a MessageUpdate so they render on |
| 363 | // the sent side instead of as an incoming (previously blank) bubble. |
| 364 | if (fromMe) { |
| 365 | emitOwnDeviceMessage(message, displayBody, mediaAttachments) |
| 366 | return |
| 367 | } |
| 368 | |
| 369 | emitIncomingChat(node, message, sender, displayBody, mediaAttachments) |
| 370 | } |
| 371 | |
| 372 | /** Echo of our own message from another device — renders on the sent side. */ |
| 373 | private suspend fun WhatsAppClient.emitOwnDeviceMessage( |
| 374 | message: WhatsAppMessage, |
| 375 | displayBody: String, |
| 376 | mediaAttachments: List<com.vayunmathur.communicate.data.whatsapp.MessageAttachment>, |
| 377 | ) { |
| 378 | eventsMutable.emit(WhatsAppEvent.MessageUpdate( |
| 379 | source = MessageSource.WHATSAPP, |
| 380 | conversationId = "wa:${message.from}", |
| 381 | messageId = message.id, |
| 382 | body = displayBody, |
| 383 | outgoing = true, |
| 384 | timestamp = message.timestamp * MS_PER_SECOND, |
| 385 | senderName = null, |
| 386 | attachments = mediaAttachments, |
| 387 | )) |
| 388 | } |
| 389 | |
| 390 | /** Poll votes + reactions; true when consumed. */ |
| 391 | private suspend fun WhatsAppClient.emitPollOrReaction( |
| 392 | message: WhatsAppMessage, |
| 393 | sender: String, |
| 394 | fromMe: Boolean, |
| 395 | ): Boolean { |
| 396 | // Handle incoming poll votes (PollUpdateMessage): decrypt the selected option |
| 397 | // hashes, map them back to names, and emit a tally update. Ref whatsmeow |
| 398 | // DecryptPollVote. |
| 399 | if (message.e2eMessage?.hasPollUpdateMessage() == true) { |
| 400 | handlePollVoteMessage(message, sender, fromMe) |
| 401 | return true |
| 402 | } |
| 403 | |
| 404 | // Handle reactions separately (Go handleWAMessage reaction case) |
| 405 | if (message.e2eMessage?.hasReactionMessage() == true) { |
| 406 | handleReactionMessage(message, sender, fromMe) |
| 407 | return true |
| 408 | } |
| 409 | return false |
| 410 | } |
| 411 | |
| 412 | /** Display body with forwarded/view-once/HD markers + mention resolution. */ |
| 413 | private suspend fun WhatsAppClient.resolveDisplayBody(message: WhatsAppMessage): String { |
| 414 | // Prepend forwarded indicator (Go from-whatsapp.go addForwardedFlag) |
| 415 | return buildString { |
| 416 | if (message.isViewOnce) append("\u26A0\uFE0F View once: ") |
| 417 | if (message.isHD) append("[HD] ") |
| 418 | if (message.isForwarded) { |
| 419 | append("↷ Forwarded\n") |
| 420 | } |
| 421 | append(message.body) |
| 422 | }.let { resolveMentionsInBody(it, message.mentionedJids) } |
| 423 | } |
| 424 | |
| 425 | /** Emit an incoming (not from-me) chat message + delivery receipt. */ |
| 426 | private suspend fun WhatsAppClient.emitIncomingChat( |
| 427 | node: WhatsAppProtocol.Node, |
| 428 | message: WhatsAppMessage, |
| 429 | sender: String, |
| 430 | displayBody: String, |
| 431 | mediaAttachments: List<com.vayunmathur.communicate.data.whatsapp.MessageAttachment>, |
| 432 | ) { |
| 433 | // In group chats, attribute the message to the actual participant so |
| 434 | // the UI can show who sent each bubble. `sender` is the participant JID |
| 435 | // (resolveJID(participant ?: from)); for 1:1 chats it's the peer, so we |
| 436 | // leave sender fields null and fall back to the conversation peer. |
| 437 | val isGroupChat = message.from.contains("@g.us") |
| 438 | eventsMutable.emit(WhatsAppEvent.IncomingMessage( |
| 439 | source = MessageSource.WHATSAPP, |
| 440 | conversationId = "wa:${message.from}", |
| 441 | messageId = message.id, |
| 442 | body = displayBody, |
| 443 | peerName = resolveName(sender), |
| 444 | peerPhone = null, |
| 445 | timestamp = message.timestamp * MS_PER_SECOND, |
| 446 | senderName = if (isGroupChat) resolveName(sender) else null, |
| 447 | senderId = if (isGroupChat) sender else null, |
| 448 | attachments = mediaAttachments, |
| 449 | pollQuestion = message.pollData?.takeIf { !it.isPollVote }?.question, |
| 450 | pollOptions = message.pollData?.takeIf { !it.isPollVote }?.options ?: emptyList(), |
| 451 | )) |
| 452 | |
| 453 | // Send delivery receipt |
| 454 | val receiptAttrs = mutableMapOf( |
| 455 | "id" to message.id, |
| 456 | "to" to message.from |
| 457 | ) |
| 458 | node.attrs["participant"]?.let { receiptAttrs["participant"] = it } |
| 459 | node.attrs["recipient"]?.let { receiptAttrs["recipient"] = it } |
| 460 | val receipt = WhatsAppProtocol.Node(tag = "receipt", attrs = receiptAttrs) |
| 461 | webSocket?.send(WhatsAppProtocol.encodeNode(receipt)) |
| 462 | } |
| 463 | |
| 464 | /** Revoke/edit/ephemeral messages; true when consumed. */ |
| 465 | private suspend fun WhatsAppClient.emitSpecialMessage(message: WhatsAppMessage, sender: String): Boolean { |
| 466 | // Handle revoke (message deletion) from Go handleWAMessage/revoke case |
| 467 | if (message.isRevoke && message.revokeTargetId != null) { |
| 468 | eventsMutable.emit(WhatsAppEvent.MessageDeleted( |
| 469 | source = MessageSource.WHATSAPP, |
| 470 | conversationId = "wa:${message.from}", |
| 471 | messageId = message.revokeTargetId, |
| 472 | timestamp = message.timestamp * MS_PER_SECOND, |
| 473 | )) |
| 474 | return true |
| 475 | } |
| 476 | |
| 477 | // Handle edit from Go handleWAMessage/edit case |
| 478 | if (message.isEdit && message.editTargetId != null) { |
| 479 | emitEditMessage(message) |
| 480 | return true |
| 481 | } |
| 482 | |
| 483 | // Handle disappearing timer change (Go handleWAMessage/ephemeral case) |
| 484 | if (message.disappearingTimer != null) { |
| 485 | eventsMutable.emit(WhatsAppEvent.IncomingMessage( |
| 486 | source = MessageSource.WHATSAPP, |
| 487 | conversationId = "wa:${message.from}", |
| 488 | messageId = message.id, |
| 489 | body = message.body, |
| 490 | peerName = resolveName(sender), |
| 491 | peerPhone = null, |
| 492 | timestamp = message.timestamp * MS_PER_SECOND, |
| 493 | )) |
| 494 | return true |
| 495 | } |
| 496 | return false |
| 497 | } |
| 498 | |
| 499 | /** Edit message with dedup (Go events.go ConvertEdit meta.Edits check). */ |
| 500 | private suspend fun WhatsAppClient.emitEditMessage(message: WhatsAppMessage) { |
| 501 | // Edit dedup (Go events.go ConvertEdit meta.Edits check) |
| 502 | if (!processedEditIDs.add(message.id)) { |
| 503 | Log.dev(TAG, "Ignoring duplicate edit ${message.id}") |
| 504 | return |
| 505 | } |
| 506 | val targetId = message.editTargetId ?: return |
| 507 | eventsMutable.emit(WhatsAppEvent.MessageEdited( |
| 508 | source = MessageSource.WHATSAPP, |
| 509 | conversationId = "wa:${message.from}", |
| 510 | messageId = targetId, |
| 511 | newBody = message.body, |
| 512 | timestamp = message.timestamp * MS_PER_SECOND, |
| 513 | )) |
| 514 | } |
| 515 | |
| 516 | /** Poll vote: decrypt selected hashes, map to names, emit tally. */ |
| 517 | private suspend fun WhatsAppClient.handlePollVoteMessage( |
| 518 | message: WhatsAppMessage, |
| 519 | sender: String, |
| 520 | fromMe: Boolean, |
| 521 | ) { |
| 522 | val update = message.e2eMessage?.pollUpdateMessage ?: return |
| 523 | val key = update.pollCreationMessageKey |
| 524 | val pollId = key.id |
| 525 | val voter = if (fromMe) (authData?.wid ?: "") else sender |
| 526 | val creator = when { |
| 527 | key.fromMe -> voter |
| 528 | key.participant.isNotEmpty() -> key.participant |
| 529 | else -> key.remoteJid |
| 530 | } |
| 531 | val secret = loadPollSecret(pollId) ?: return |
| 532 | val hashes = WhatsAppProtocol.decryptPollVote(update, pollId, creator, voter, secret) ?: return |
| 533 | val dao = db?.pollOptionDao() |
| 534 | val names = hashes.mapNotNull { h -> |
| 535 | val hex = h.joinToString("") { "%02x".format(it) } |
| 536 | dao?.getByHash(pollId, hex)?.optionName |
| 537 | } |
| 538 | eventsMutable.emit(WhatsAppEvent.PollVote( |
| 539 | source = MessageSource.WHATSAPP, |
| 540 | conversationId = "wa:${message.from}", |
| 541 | pollMessageId = pollId, |
| 542 | voterId = if (fromMe) "self" else sender, |
| 543 | optionNames = names, |
| 544 | )) |
| 545 | } |
| 546 | |
| 547 | /** Reaction add/remove. */ |
| 548 | private suspend fun WhatsAppClient.handleReactionMessage( |
| 549 | message: WhatsAppMessage, |
| 550 | sender: String, |
| 551 | fromMe: Boolean, |
| 552 | ) { |
| 553 | val reaction = message.e2eMessage?.reactionMessage ?: return |
| 554 | val emoji = reaction.text?.replace("\uFE0F", "") ?: "" |
| 555 | val targetId = reaction.key?.id ?: "" |
| 556 | // A reaction the user made on another device echoes back as fromMe; |
| 557 | // tag its sender "self" so it isn't misattributed to the chat peer. |
| 558 | val reactorId = if (fromMe) "self" else sender |
| 559 | if (emoji.isEmpty()) { |
| 560 | eventsMutable.emit(WhatsAppEvent.ReactionRemoved( |
| 561 | source = MessageSource.WHATSAPP, |
| 562 | conversationId = "wa:${message.from}", |
| 563 | messageId = targetId, |
| 564 | senderId = reactorId, |
| 565 | )) |
| 566 | } else { |
| 567 | eventsMutable.emit(WhatsAppEvent.ReactionReceived( |
| 568 | source = MessageSource.WHATSAPP, |
| 569 | conversationId = "wa:${message.from}", |
| 570 | messageId = targetId, |
| 571 | senderId = reactorId, |
| 572 | emoji = emoji, |
| 573 | )) |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | /** |
| 578 | * Handle identity change notification (security code change). |
| 579 | * From Go handleWAIdentityChange. |
| 580 | */ |
| 581 | internal suspend fun WhatsAppClient.handleIdentityChange(node: WhatsAppProtocol.Node, from: String) { |
| 582 | val identityNode = node.getChildByTag("identity") |
| 583 | if (identityNode != null) { |
| 584 | val jid = node.attrs["participant"] ?: from |
| 585 | val ts = node.attrs["t"]?.toLongOrNull() ?: (System.currentTimeMillis() / 1000) |
| 586 | Log.status(TAG, "Identity/security code changed for $jid") |
| 587 | eventsMutable.emit(WhatsAppEvent.IncomingMessage( |
| 588 | source = MessageSource.WHATSAPP, |
| 589 | conversationId = "wa:$from", |
| 590 | messageId = "idchange-$from-$jid-$ts", |
| 591 | body = "\uD83D\uDD12 Security code changed for ${resolveName(jid)}", |
| 592 | peerName = resolveName(jid), |
| 593 | peerPhone = null, |
| 594 | timestamp = ts * MS_PER_SECOND, |
| 595 | )) |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | /** |
| 600 | * Handle picture update notification (avatar changes). |
| 601 | * From Go handleWAPictureUpdate. |
| 602 | */ |
| 603 | internal suspend fun WhatsAppClient.handlePictureUpdate(node: WhatsAppProtocol.Node, from: String) { |
| 604 | val pictureNode = node.getChildByTag("set") ?: node.getChildByTag("delete") |
| 605 | if (pictureNode != null) { |
| 606 | val isRemoved = pictureNode.tag == "delete" |
| 607 | Log.dev(TAG, "Picture ${if (isRemoved) "removed" else "updated"} for $from") |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | /** |
| 612 | * Handle account sync notification (push name updates). |
| 613 | * From Go PushNameSetting / PushName events. |
| 614 | */ |
| 615 | internal suspend fun WhatsAppClient.handleAccountSync(node: WhatsAppProtocol.Node) { |
| 616 | node.content.filterIsInstance<WhatsAppProtocol.Node>().forEach { child -> |
| 617 | when (child.tag) { |
| 618 | "push" -> { |
| 619 | val pushName = child.attrs["name"] |
| 620 | val jid = child.attrs["jid"] ?: node.attrs["from"] |
| 621 | if (pushName != null && jid != null) { |
| 622 | nameCache[jid] = pushName |
| 623 | Log.dev(TAG, "Push name updated: $jid -> $pushName") |
| 624 | } |
| 625 | } |
| 626 | "contact" -> { |
| 627 | val contactName = child.attrs["name"] |
| 628 | val jid = child.attrs["jid"] ?: node.attrs["from"] |
| 629 | if (contactName != null && jid != null) { |
| 630 | nameCache[jid] = contactName |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | /** |
| 638 | * Handle receipt with per-sender batching for group chats. |
| 639 | * From Go handleWAReceipt — groups messages by sender. |
| 640 | */ |
| 641 | internal suspend fun WhatsAppClient.handleReceipt(node: WhatsAppProtocol.Node) { |
| 642 | val receiptType = node.attrs["type"] |
| 643 | // The peer couldn't decrypt a message we sent and wants it re-encrypted. This is the |
| 644 | // outbound counterpart of sendRetryReceipt and is required for delivery to actually |
| 645 | // happen when a session is desynced. |
| 646 | if (receiptType == "retry") { |
| 647 | handleRetryReceipt(node) |
| 648 | return |
| 649 | } |
| 650 | val isRead = receiptType == "read" || receiptType == "read-self" |
| 651 | val isDelivered = receiptType == null || receiptType.isEmpty() |
| 652 | if (!isRead && !isDelivered) return |
| 653 | |
| 654 | val from = node.attrs["from"] ?: return |
| 655 | val participant = node.attrs["participant"] |
| 656 | |
| 657 | // Reroute LID sender |
| 658 | val sender = resolveJID(participant ?: from) |
| 659 | |
| 660 | val messageId = node.attrs["id"] ?: return |
| 661 | val timestamp = (node.attrs["t"]?.toLongOrNull() ?: System.currentTimeMillis() / 1000) * 1000 |
| 662 | |
| 663 | // Delivery (type absent/empty) advances our sent message to "delivered" (grey ✓✓); a |
| 664 | // read/read-self receipt advances to "read" (blue ✓✓). Both are surfaced as ReadReceipt. |
| 665 | eventsMutable.emit(WhatsAppEvent.ReadReceipt( |
| 666 | source = MessageSource.WHATSAPP, |
| 667 | conversationId = "wa:$from", |
| 668 | messageId = messageId, |
| 669 | senderId = sender, |
| 670 | timestamp = timestamp, |
| 671 | isDelivery = isDelivered, |
| 672 | )) |
| 673 | |
| 674 | // Handle additional message IDs in list node |
| 675 | val listNode = node.getChildByTag("list") |
| 676 | listNode?.content?.filterIsInstance<WhatsAppProtocol.Node>()?.forEach { item -> |
| 677 | val itemId = item.attrs["id"] ?: return@forEach |
| 678 | eventsMutable.emit(WhatsAppEvent.ReadReceipt( |
| 679 | source = MessageSource.WHATSAPP, |
| 680 | conversationId = "wa:$from", |
| 681 | messageId = itemId, |
| 682 | senderId = sender, |
| 683 | timestamp = timestamp, |
| 684 | isDelivery = isDelivered, |
| 685 | )) |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | /** |
| 690 | * Handle chat presence with media type differentiation. |
| 691 | * From Go handleWAChatPresence — differentiates text/audio/media typing. |
| 692 | */ |
| 693 | internal suspend fun WhatsAppClient.handleChatPresence(node: WhatsAppProtocol.Node) { |
| 694 | val from = node.attrs["from"] ?: return |
| 695 | val participant = node.attrs["participant"] |
| 696 | val sender = resolveJID(participant ?: from) |
| 697 | |
| 698 | val composingNode = node.getChildByTag("composing") |
| 699 | val pausedNode = node.getChildByTag("paused") |
| 700 | |
| 701 | val isTyping = composingNode != null |
| 702 | val mediaAttr = composingNode?.attrs?.get("media") |
| 703 | |
| 704 | eventsMutable.emit(WhatsAppEvent.TypingIndicator( |
| 705 | source = MessageSource.WHATSAPP, |
| 706 | conversationId = "wa:$from", |
| 707 | senderId = sender, |
| 708 | isTyping = isTyping, |
| 709 | )) |
| 710 | } |