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

WhatsAppClientRetry.kt150 lines · 6.2 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import com.vayunmathur.library.log.Log
4import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E
5import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket
6
7/**
8 * Retry-receipt handling (split from WhatsAppClientSync.kt for file length).
9 * Behavior identical, call sites unchanged.
10 */
11
12suspend fun WhatsAppClient.sendRetryReceipt(node: WhatsAppProtocol.Node) {
13 val auth = authData ?: return
14 val crypto = ensureE2E(auth) ?: return
15 val ws = webSocket ?: return
16 val msgId = node.attrs["id"] ?: return
17 val count = undecryptableTracker.merge("retry:$msgId", 1) { a, b -> a + b } ?: 1
18 if (count > MAX_RETRY_RECEIPTS) {
19 Log.status(TAG, "Not sending more retry receipts for $msgId")
20 return
21 }
22 val keysNode = if (count > 1) {
23 try { crypto.buildRetryReceiptKeysNode(accountDeviceIdentity()) } catch (expected: Exception) {
24 Log.status(TAG, "Failed to build retry keys node", expected); null
25 }
26 } else null
27 val receipt = WhatsAppProtocol.buildRetryReceipt(node, auth.registrationId, count, keysNode)
28 ws.send(WhatsAppProtocol.encodeNode(receipt))
29 Log.dev(TAG, "Sent retry receipt #$count for $msgId")
30}
31
32/**
33 * Handle an inbound <receipt type="retry">: the peer failed to decrypt a message we sent and
34 * is asking us to re-encrypt and resend it. Rebuild the session from the fresh keys included
35 * in the receipt (present from the 2nd retry), then re-encrypt the cached plaintext for just
36 * the requesting device and resend with the same message id. Ref whatsmeow retry.go
37 * handleRetryReceipt. 1:1 only — group skmsg resends are not cached.
38 */
39suspend fun WhatsAppClient.handleRetryReceipt(node: WhatsAppProtocol.Node) {
40 val auth = authData ?: return
41 val crypto = ensureE2E(auth) ?: return
42 val ws = webSocket ?: return
43 val msgId = node.attrs["id"] ?: return
44 val deviceJid = retryDeviceJid(node, msgId) ?: return
45 val cached = recentSentDMs[msgId]
46 if (cached == null) {
47 WhatsAppDiag.log(TAG, "retry: no cached message for $msgId; cannot resend")
48 }
49 val ready = cached != null && checkResendBudget(msgId, deviceJid)
50 val sessionReady = ready && rebuildRetrySessionFor(crypto, node, deviceJid, msgId)
51 if (sessionReady) {
52 val resendCount = retryResendCounts["$msgId|$deviceJid"] ?: 1
53 resendRetryMessage(auth, crypto, ws, msgId, deviceJid, cached!!, resendCount)
54 }
55}
56
57/** Rebuild + verify the session; false when unusable. */
58private suspend fun WhatsAppClient.rebuildRetrySessionFor(
59 crypto: WhatsAppE2E,
60 node: WhatsAppProtocol.Node,
61 deviceJid: String,
62 msgId: String,
63): Boolean {
64 rebuildRetrySession(crypto, node, deviceJid, deviceJid.substringBefore("@").substringAfter(":", "0"))
65 if (!ensureSession(deviceJid)) {
66 WhatsAppDiag.log(TAG, "retry: no session for $deviceJid; cannot resend $msgId")
67 return false
68 }
69 return true
70}
71
72/** The target device JID, or null with a log when the retry is not actionable. */
73private fun WhatsAppClient.retryDeviceJid(node: WhatsAppProtocol.Node, msgId: String): String? {
74 val from = node.attrs["from"] ?: return null
75 // The specific device that couldn't decrypt: participant if present, else the chat peer.
76 val deviceJid = node.attrs["participant"] ?: from
77 if (deviceJid.contains("@g.us")) {
78 WhatsAppDiag.log(TAG, "retry: ignoring group retry for $msgId (not cached)")
79 return null
80 }
81 return deviceJid
82}
83
84/** Increment the resend counter; false when the budget is exhausted. */
85private fun WhatsAppClient.checkResendBudget(msgId: String, deviceJid: String): Boolean {
86 val resendKey = "$msgId|$deviceJid"
87 val resendCount = retryResendCounts.merge(resendKey, 1) { a, b -> a + b } ?: 1
88 if (resendCount > MAX_RETRY_RECEIPTS) {
89 WhatsAppDiag.log(TAG, "retry: giving up on $msgId for $deviceJid after $resendCount attempts")
90 return false
91 }
92 return true
93}
94
95/** Rebuild the session from receipt keys, when the peer attached them. */
96private suspend fun WhatsAppClient.rebuildRetrySession(
97 crypto: WhatsAppE2E,
98 node: WhatsAppProtocol.Node,
99 deviceJid: String,
100 deviceNumRaw: String,
101) {
102 if (node.getChildByTag("keys") == null) return
103 try {
104 // parsePreKeyBundleNode reads <registration> + <keys> from the node it is given.
105 val bundle = crypto.parsePreKeyBundleNode(deviceNumRaw.toIntOrNull() ?: 0, node)
106 if (bundle != null) {
107 crypto.deleteSession(deviceJid)
108 crypto.processPreKeyBundle(deviceJid, bundle)
109 WhatsAppDiag.log(TAG, "retry: rebuilt session for $deviceJid from receipt keys")
110 }
111 } catch (expected: Exception) {
112 WhatsAppDiag.log(TAG, "retry: failed to process receipt keys for $deviceJid: ${expected.message}")
113 }
114}
115
116/** Re-encrypt the cached plaintext for the requesting device and resend. */
117private suspend fun WhatsAppClient.resendRetryMessage(
118 auth: WhatsAppAuthData,
119 crypto: WhatsAppE2E,
120 ws: WhatsAppSocket,
121 msgId: String,
122 deviceJid: String,
123 cached: SentDM,
124 resendCount: Int,
125) {
126 val ownUser = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".")
127 val devUser = deviceJid.substringBefore("@").substringBefore(":").substringBefore(".")
128 val plaintext = if (devUser == ownUser && cached.dsmPlaintextPadded != null) {
129 cached.dsmPlaintextPadded
130 } else {
131 cached.msgPlaintextPadded
132 }
133 val enc = try {
134 crypto.encryptDM(deviceJid, plaintext)
135 } catch (expected: Exception) {
136 WhatsAppDiag.log(TAG, "retry: re-encrypt failed for $deviceJid: ${expected.message}")
137 return
138 }
139 val includeIdentity = enc.type == "pkmsg"
140 val resend = WhatsAppProtocol.buildFanOutMessageNode(
141 to = cached.to,
142 id = msgId,
143 type = cached.type,
144 participantEncs = listOf(WhatsAppProtocol.ParticipantEnc(deviceJid, enc.type, enc.data)),
145 includeDeviceIdentity = includeIdentity,
146 deviceIdentity = if (includeIdentity) accountDeviceIdentity() else null,
147 )
148 val sent = ws.send(WhatsAppProtocol.encodeNode(resend))
149 WhatsAppDiag.log(TAG, "retry: resent $msgId to $deviceJid (attempt $resendCount type=${enc.type}) sent=$sent")
150}