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

WhatsAppClientSync.kt513 lines · 23.1 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient.State
4import com.vayunmathur.communicate.data.whatsapp.buildFanOutMessageNode
5import com.vayunmathur.communicate.data.whatsapp.buildHistoryOnDemandRequest
6import com.vayunmathur.communicate.data.whatsapp.buildRetryReceipt
7import com.vayunmathur.communicate.data.whatsapp.decryptAppStateValue
8import com.vayunmathur.communicate.data.whatsapp.encodeNode
9import com.vayunmathur.communicate.data.whatsapp.expandAppStateKeys
10import com.vayunmathur.communicate.data.whatsapp.extractMessageBody
11import com.vayunmathur.communicate.data.whatsapp.generateMessageId
12import android.util.Base64
13import com.vayunmathur.library.log.Log
14import androidx.core.content.edit
15import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppAppStateProto
16import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto
17import kotlinx.coroutines.launch
18
19internal fun WhatsAppClient.appStateKeyId64(keyId: ByteArray) = Base64.encodeToString(keyId, Base64.NO_WRAP)
20fun WhatsAppClient.storeAppStateKey(keyId: ByteArray, keyData: ByteArray) {
21 appStatePrefs.edit { putString("key_${appStateKeyId64(keyId)}", Base64.encodeToString(keyData, Base64.NO_WRAP)) }
22}
23internal fun WhatsAppClient.getAppStateKey(keyId: ByteArray): ByteArray? {
24 val s = appStatePrefs.getString("key_${appStateKeyId64(keyId)}", null) ?: return null
25 return try { Base64.decode(s, Base64.NO_WRAP) } catch (ignored: Exception) { null }
26}
27internal fun WhatsAppClient.appStateVersion(name: String): Long = appStatePrefs.getLong("ver_$name", 0L)
28internal fun WhatsAppClient.setAppStateVersion(name: String, v: Long) { appStatePrefs.edit { putLong("ver_$name", v) } }
29
30/** Store app-state sync keys shared by our primary, then fetch all collections. */
31internal suspend fun WhatsAppClient.handleAppStateKeyShare(share: WhatsAppE2EProto.AppStateSyncKeyShare) {
32 var stored = 0
33 for (k in share.keysList) {
34 val id = k.keyId.keyId.toByteArray()
35 val data = k.keyData.keyData.toByteArray()
36 if (id.isNotEmpty() && data.isNotEmpty()) { storeAppStateKey(id, data); stored++ }
37 }
38 WhatsAppDiag.log(TAG, "app-state: stored $stored sync key(s); fetching collections")
39 for (name in APP_STATE_COLLECTIONS) {
40 fetchAppStateCollection(name, fullSync = appStateVersion(name) == 0L)
41 }
42}
43
44/**
45 * Fetch + decode + apply one app-state collection (snapshot then incremental patches).
46 * Ref whatsmeow appstate.go fetchAppState. MAC/LTHash verification is skipped.
47 */
48private const val SYNC_PAGE_GUARD = 12
49internal const val MAX_RETRY_RECEIPTS = 5
50private const val MS_PER_SECOND = 1000L
51private const val HEX_RADIX = 16
52private const val HEX_PAIR = 2
53private const val LOG_PATH_PREFIX_LENGTH = 40
54
55internal suspend fun WhatsAppClient.fetchAppStateCollection(name: String, fullSync: Boolean) {
56 if (!appStateCollectionsFetching.add(name)) return
57 try {
58 var version = if (fullSync) 0L else appStateVersion(name)
59 var wantSnapshot = fullSync || version == 0L
60 var more = true
61 var guard = 0
62 while (more && guard++ < SYNC_PAGE_GUARD) {
63 val coll = fetchAppStateCollectionPage(name, wantSnapshot, version) ?: break
64 val page = applyAppStatePage(name, coll, version)
65 version = page.first
66 more = page.second
67 wantSnapshot = false
68 }
69 setAppStateVersion(name, version)
70 WhatsAppDiag.log(TAG, "app-state: $name synced to v$version")
71 } catch (expected: Exception) {
72 WhatsAppDiag.log(TAG, "app-state $name failed: ${expected.javaClass.simpleName}: ${expected.message}")
73 } finally {
74 appStateCollectionsFetching.remove(name)
75 }
76}
77
78/** Apply one page (snapshot + patches); returns (version, more). */
79private suspend fun WhatsAppClient.applyAppStatePage(
80 name: String,
81 coll: WhatsAppProtocol.Node,
82 version: Long,
83): Pair<Long, Boolean> {
84 var v = version
85 val snapNode = coll.getChildByTag("snapshot")
86 var recCount = 0
87 snapNode?.data?.let { snapData ->
88 val ext = WhatsAppAppStateProto.ExternalBlobReference.parseFrom(snapData)
89 val blob = downloadAppStateBlob(ext)
90 if (blob == null) {
91 WhatsAppDiag.log(
92 TAG,
93 "app-state $name: snapshot blob download FAILED " +
94 "(path=${ext.directPath.take(LOG_PATH_PREFIX_LENGTH)})")
95 } else {
96 val snap = WhatsAppAppStateProto.SyncdSnapshot.parseFrom(blob)
97 recCount = snap.recordsCount
98 for (rec in snap.recordsList) applyAppStateRecord(rec, isSet = true)
99 if (snap.hasVersion()) v = snap.version.version
100 }
101 }
102 v = applyAppStatePatches(coll, v)
103 val patchNodes = coll.getChildByTag("patches")?.getChildren()?.filter { it.tag == "patch" } ?: emptyList()
104 WhatsAppDiag.log(TAG, "app-state $name: snapshot=${snapNode != null} records=$recCount" +
105 "patches=${patchNodes.size} more=${coll.attrs["has_more_patches"]} -> v$v")
106 return v to (coll.attrs["has_more_patches"] == "true")
107}
108
109/** Fetch one app-state collection page, or null on transport failure. */
110private suspend fun WhatsAppClient.fetchAppStateCollectionPage(
111 name: String,
112 wantSnapshot: Boolean,
113 version: Long,
114): WhatsAppProtocol.Node? {
115 val collAttrs = mutableMapOf("name" to name, "return_snapshot" to wantSnapshot.toString())
116 if (!wantSnapshot) collAttrs["version"] = version.toString()
117 val iq = WhatsAppProtocol.Node(
118 tag = "iq",
119 attrs = mapOf(
120 "id" to generateMessageId(), "type" to "set",
121 "xmlns" to "w:sync:app:state", "to" to "s.whatsapp.net",
122 ),
123 content = listOf(
124 WhatsAppProtocol.Node(
125 tag = "sync",
126 content = listOf(WhatsAppProtocol.Node(tag = "collection", attrs = collAttrs)),
127 )
128 ),
129 )
130 val resp = sendIqAndWait(iq) ?: return null
131 return resp.getChildByTag("sync")?.getChildByTag("collection")
132}
133
134/** Apply patch nodes; returns the updated version. */
135private suspend fun WhatsAppClient.applyAppStatePatches(
136 coll: WhatsAppProtocol.Node,
137 version: Long,
138): Long {
139 var v = version
140 val patchNodes = coll.getChildByTag("patches")?.getChildren()?.filter { it.tag == "patch" } ?: emptyList()
141 patchNodes.forEach { p ->
142 p.data?.let { pd ->
143 val patch = WhatsAppAppStateProto.SyncdPatch.parseFrom(pd)
144 val muts = if (patch.hasExternalMutations()) {
145 downloadAppStateBlob(patch.externalMutations)?.let {
146 WhatsAppAppStateProto.SyncdMutations.parseFrom(it).mutationsList
147 } ?: emptyList()
148 } else patch.mutationsList
149 for (m in muts) applyAppStateRecord(
150 m.record,
151 isSet = m.operation == WhatsAppAppStateProto.SyncdMutation.SyncdOperation.SET,
152 )
153 if (patch.hasVersion()) v = patch.version.version
154 }
155 }
156 return v
157}
158
159/** Download + decrypt an app-state external blob (snapshot/mutations) via the media CDN. */
160internal suspend fun WhatsAppClient.downloadAppStateBlob(ext: WhatsAppAppStateProto.ExternalBlobReference): ByteArray? {
161 val directPath = ext.directPath
162 if (directPath.isEmpty()) return null
163 val host = mediaConn()?.first ?: return null
164 val hash = Base64.encodeToString(ext.fileEncSha256.toByteArray(), Base64.URL_SAFE or Base64.NO_WRAP)
165 val url = "https://$host$directPath&hash=$hash&mms-type=md-app-state&__wa-mms="
166 return downloadMedia(url, ext.mediaKey.toByteArray(), WhatsAppProtocol.MEDIA_KEY_APP_STATE)
167}
168
169/** Decrypt one app-state record and apply it (contact names, mute/pin/archive). */
170suspend fun WhatsAppClient.applyAppStateRecord(
171 record: WhatsAppAppStateProto.SyncdRecord,
172 isSet: Boolean,
173) {
174 if (!isSet) return
175 val keyId = record.keyId.id.toByteArray()
176 val keyData = getAppStateKey(keyId) ?: run {
177 requestAppStateKey(keyId); return
178 }
179 val expanded = WhatsAppProtocol.expandAppStateKeys(keyData)
180 val plain = WhatsAppProtocol.decryptAppStateValue(record.value.blob.toByteArray(), expanded[1]) ?: return
181 val sad = try { WhatsAppAppStateProto.SyncActionData.parseFrom(plain) } catch (ignored: Exception) { return }
182 val index = try { org.json.JSONArray(String(
183 sad.index.toByteArray(),
184 Charsets.UTF_8)) } catch (ignored: Exception) { return }
185 if (index.length() == 0) return
186 applyAppStateAction(index, sad)
187}
188
189/** Route one app-state sync action to its store update. */
190private suspend fun WhatsAppClient.applyAppStateAction(
191 index: org.json.JSONArray,
192 sad: WhatsAppAppStateProto.SyncActionData,
193) {
194 val action = index.optString(0)
195 val jid = if (index.length() > 1) index.optString(1) else ""
196 val value = sad.value
197 when (action) {
198 "contact" -> {
199 val name = value.contactAction.fullName.ifEmpty { value.contactAction.firstName }
200 if (name.isNotEmpty() && jid.isNotEmpty()) {
201 // Cache name for live messages / future conversations. We do NOT emit a
202 // ConversationUpdate here because the consumer upserts (would create empty rows
203 // for every contact). History rows already use device-contact lookup for names.
204 nameCache[resolveJID(jid)] = name
205 nameCache[jid] = name
206 }
207 }
208 "mute" -> if (jid.isNotEmpty()) db?.conversationDao()?.updateMuteEndTime(jid, value.muteAction.muteEndTimestamp)
209 "pin_v1" -> if (jid.isNotEmpty()) db?.conversationDao()?.updatePinned(jid, value.pinAction.pinned)
210 "archive" -> if (jid.isNotEmpty()) db?.conversationDao()?.updateArchived(jid, value.archiveChatAction.archived)
211 "markChatAsRead" -> if (jid.isNotEmpty()) db?.conversationDao()?.updateMarkedAsUnread(
212 jid,
213 !value.markChatAsReadAction.read)
214 }
215}
216
217/** Download the history-sync blob (inline or via media host); null with receipt sent on failure. */
218private suspend fun WhatsAppClient.historySyncBytes(
219 notif: WhatsAppE2EProto.HistorySyncNotification,
220 msgId: String,
221): ByteArray? {
222 if (notif.hasInitialHistBootstrapInlinePayload() &&
223 !notif.initialHistBootstrapInlinePayload.isEmpty
224 ) {
225 // Initial bootstrap chunk is inlined in the notification (DeviceProps requested it).
226 return notif.initialHistBootstrapInlinePayload.toByteArray()
227 }
228 val host = mediaConn()?.first ?: run {
229 WhatsAppDiag.log(TAG, "history sync: no media host"); sendHistorySyncReceipt(msgId); return null
230 }
231 val directPath = notif.directPath
232 if (directPath.isEmpty()) {
233 WhatsAppDiag.log(TAG, "history sync: no directPath")
234 sendHistorySyncReceipt(msgId)
235 return null
236 }
237 val hash = Base64.encodeToString(
238 notif.fileEncSha256.toByteArray(), Base64.URL_SAFE or Base64.NO_WRAP
239 )
240 val url = "https://$host$directPath&hash=$hash&mms-type=md-msg-hist&__wa-mms="
241 return downloadMedia(url, notif.mediaKey.toByteArray(), WhatsAppProtocol.MEDIA_KEY_HISTORY)
242 ?: run {
243 WhatsAppDiag.log(TAG, "history sync: download failed")
244 sendHistorySyncReceipt(msgId)
245 null
246 }
247}
248
249/** Request a missing app-state sync key from our primary (deduped). */
250internal suspend fun WhatsAppClient.requestAppStateKey(keyId: ByteArray) {
251 val id64 = appStateKeyId64(keyId)
252 if (!appStateKeyRequested.add(id64)) return
253 val auth = authData ?: return
254 try {
255 val req = WhatsAppE2EProto.AppStateSyncKeyRequest.newBuilder()
256 .addKeyIds(
257 WhatsAppE2EProto.AppStateSyncKeyId.newBuilder()
258 .setKeyId(com.google.protobuf.ByteString.copyFrom(keyId))
259 )
260 val proto = WhatsAppE2EProto.ProtocolMessage.newBuilder()
261 .setType(WhatsAppE2EProto.ProtocolMessage.Type.APP_STATE_SYNC_KEY_REQUEST)
262 .setAppStateSyncKeyRequest(req)
263 val msg = WhatsAppE2EProto.Message.newBuilder().setProtocolMessage(proto).build()
264 val ownUser = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".")
265 val node = buildEncryptedMessageNode("[email protected]", generateMessageId(), msg, "text") ?: return
266 webSocket?.send(WhatsAppProtocol.encodeNode(node))
267 WhatsAppDiag.log(TAG, "app-state: requested missing key $id64")
268 } catch (expected: Exception) {
269 WhatsAppDiag.log(TAG, "app-state key request failed: ${expected.message}")
270 }
271}
272
273/**
274 * Send a retry receipt asking the sender to re-encrypt an undecryptable message.
275 * Ref whatsmeow retry.go sendRetryReceipt. Retries are capped at 5; the identity/prekey <keys>
276 * node is included from the 2nd retry onward.
277 */
278
279/**
280 * Store poll option hashes for later vote resolution.
281 * From Go wadb.PollOption.
282 */
283internal suspend fun WhatsAppClient.storePollOptions(messageId: String, options: List<String>) {
284 val dao = db?.pollOptionDao() ?: return
285 val pollOptions = options.map { option ->
286 val hash = java.security.MessageDigest.getInstance("SHA-256")
287 .digest(option.toByteArray(Charsets.UTF_8))
288 WhatsAppPollOption(
289 msgId = messageId,
290 optionHash = hash.joinToString("") { "%02x".format(it) },
291 optionName = option,
292 )
293 }
294 dao.upsertAll(pollOptions)
295}
296
297/** Persist a poll's shared secret (in-memory + DB) so votes can be encrypted/decrypted later. */
298internal suspend fun WhatsAppClient.storePollSecret(msgId: String, secret: ByteArray) {
299 pollSecrets[msgId] = secret
300 db?.pollSecretDao()?.upsert(
301 WhatsAppPollSecret(msgId, secret.joinToString("") { "%02x".format(it) })
302 )
303}
304
305internal suspend fun WhatsAppClient.loadPollSecret(msgId: String): ByteArray? {
306 pollSecrets[msgId]?.let { return it }
307 val hex = db?.pollSecretDao()?.get(msgId) ?: return null
308 return runCatching {
309 hex.chunked(HEX_PAIR).map { it.toInt(HEX_RADIX).toByte() }.toByteArray()
310 }.getOrNull()?.also { pollSecrets[msgId] = it }
311}
312
313internal fun WhatsAppClient.kickoffBackfill() {
314 // History is PUSHED by the phone after linking as encrypted <message> stanzas carrying a
315 // protocolMessage.historySyncNotification (gated by DeviceProps.HistorySyncConfig sent at
316 // pairing). There is no w:web "initial" request in the multidevice protocol, so we just
317 // wait for those messages here. Ref whatsmeow appstate/history sync.
318 WhatsAppDiag.log(TAG, "awaiting pushed history sync messages from phone")
319}
320
321/**
322 * Download (or read inline), decompress and parse a HistorySync blob, then emit the contained
323 * messages as backfill. Ref whatsmeow message.go DownloadHistorySync + download.go.
324 */
325internal suspend fun WhatsAppClient.handleHistorySync(
326 notif: WhatsAppE2EProto.HistorySyncNotification,
327 msgId: String,
328) {
329 try {
330 val raw: ByteArray = historySyncBytes(notif, msgId) ?: return
331
332 val inflated = inflateZlib(raw)
333 val hs = WhatsAppE2EProto.HistorySync.parseFrom(inflated)
334 // Populate LID->phone mappings so conversations addressed by LID resolve to a phone JID.
335 for (m in hs.phoneNumberToLidMappingsList) {
336 if (m.lidJid.isNotEmpty() && m.pnJid.isNotEmpty()) lidToPhoneMap[m.lidJid] = m.pnJid
337 }
338 WhatsAppDiag.log(
339 TAG,
340 "history sync: type=${hs.syncType} chunk=${hs.chunkOrder} conversations=${hs.conversationsCount}" +
341 "lidMaps=${hs.phoneNumberToLidMappingsCount} (blob=${raw.size}B inflated=${inflated.size}B)",
342 )
343
344 // Backfill continues (paginates older messages) from the initial bootstrap and from
345 // each on-demand response, so full history is pulled page by page. RECENT/FULL/etc are
346 // terminal pushes and don't trigger further requests.
347 val requestMore = fullHistorySync &&
348 (hs.syncType == SYNC_INITIAL_BOOTSTRAP || hs.syncType == SYNC_ON_DEMAND)
349 var emitted = 0
350 for (conv in hs.conversationsList) {
351 val chatJid = conv.newJid.ifEmpty { conv.id }
352 WhatsAppDiag.log(TAG, " conv '${conv.name}' ${chatJid} msgs=${conv.messagesCount}")
353 if (chatJid.isEmpty() || chatJid.startsWith("status@broadcast")) continue
354 emitted += emitHistoryConversation(conv, chatJid, requestMore)
355 }
356 WhatsAppDiag.log(TAG, "history sync: emitted $emitted message(s)")
357 } catch (expected: Exception) {
358 WhatsAppDiag.log(TAG, "history sync failed: ${expected.javaClass.simpleName}: ${expected.message}")
359 Log.error(TAG, "history sync failed", expected)
360 }
361 // Acknowledge the chunk so the phone advances to the next one and finishes "syncing".
362 sendHistorySyncReceipt(msgId)
363}
364
365/**
366 * Send the history-sync receipt so the phone stops waiting ("syncing, keep WhatsApp open") and
367 * sends the next chunk. Ref whatsmeow SendProtocolMessageReceipt(id, ReceiptTypeHistorySync).
368 * <receipt id="{notifMsgId}" type="hist_sync" to="{ownUserJID}"/>
369 */
370internal fun WhatsAppClient.sendHistorySyncReceipt(msgId: String) {
371 if (msgId.isEmpty()) return
372 val ownUser = (authData?.wid ?: return).substringBefore("@").substringBefore(":").substringBefore(".")
373 if (ownUser.isEmpty()) return
374 val receipt = WhatsAppProtocol.Node(
375 tag = "receipt",
376 attrs = mapOf("id" to msgId, "type" to "hist_sync", "to" to "[email protected]"),
377 )
378 webSocket?.send(WhatsAppProtocol.encodeNode(receipt))
379 WhatsAppDiag.log(TAG, "history sync: sent hist_sync receipt for $msgId")
380}
381
382/**
383 * Backfill one conversation: emit a MessageUpdate (outgoing-aware) for each message with a
384 * body, then a ConversationUpdate so the chat row appears with its last preview. Returns the
385 * number of messages emitted. MessageUpdate is the backfill path (no notifications); IncomingMessage
386 * is reserved for live messages.
387 */
388/** Displayable body + wrapper for a history message, or null when skipped. */
389private fun extractHistoryBody(
390 hsMsg: WhatsAppE2EProto.HistorySyncMsg,
391): Pair<String, WhatsAppE2EProto.WebMessageInfo>? {
392 if (!hsMsg.hasMessage()) return null
393 val wmi = hsMsg.message
394 if (!wmi.hasMessage()) return null
395 val body = WhatsAppProtocol.extractMessageBody(wmi.message)
396 if (body.isEmpty()) return null
397 return body to wmi
398}
399
400internal suspend fun WhatsAppClient.emitHistoryConversation(
401 conv: WhatsAppE2EProto.HsConversation,
402 rawChatJid: String,
403 requestMore: Boolean,
404): Int {
405 // Resolve LID-addressed chats to a phone JID so they match live conversations and have a
406 // displayable number/name (instead of "unknown").
407 val chatJid = resolveJID(rawChatJid)
408 val convId = "wa:$chatJid"
409 // E.164 (with +) so device-contact lookup (ContactsContract.PhoneLookup) matches.
410 val phone = if (chatJid.endsWith("@s.whatsapp.net"))
411 "+" + chatJid.substringBefore("@").substringBefore(":").substringBefore(".") else null
412 val contactName = resolveDeviceContactName(phone)
413 // Collect displayable messages first so we can register the conversation row BEFORE the
414 // messages (the message table has a FK to the conversation).
415 data class HMsg(val id: String, val body: String, val outgoing: Boolean, val ts: Long, val sender: String?)
416 val msgs = ArrayList<HMsg>()
417 var lastBody = ""
418 var lastTs = conv.conversationTimestamp * 1000
419 var peerPush = ""
420 for (hsMsg in conv.messagesList) {
421 extractHistoryBody(hsMsg)?.let { (body, wmi) ->
422 val key = wmi.key
423 val tsMs = wmi.messageTimestamp * 1000
424 if (!key.fromMe && wmi.pushName.isNotEmpty()) peerPush = wmi.pushName
425 val senderName = if (key.fromMe) null
426 else wmi.pushName.ifEmpty { conv.name.ifEmpty { contactName ?: phone } }
427 msgs.add(HMsg(key.id, body, key.fromMe, tsMs, senderName))
428 if (tsMs >= lastTs) { lastTs = tsMs; lastBody = body }
429 }
430 }
431 if (msgs.isEmpty()) return 0
432
433 // Register the conversation row first.
434 val isGroupChat = chatJid.endsWith("@g.us")
435 eventsMutable.emit(
436 WhatsAppEvent.ConversationUpdate(
437 source = MessageSource.WHATSAPP,
438 conversationId = convId,
439 peerName = conv.name.ifEmpty { contactName ?: peerPush.ifEmpty { phone } },
440 peerPhone = phone,
441 avatarUrl = null,
442 lastPreview = lastBody,
443 lastTimestamp = lastTs,
444 unreadCount = conv.unreadCount,
445 isGroup = isGroupChat,
446 )
447 )
448 // Then backfill its messages.
449 for (m in msgs) {
450 eventsMutable.emit(
451 WhatsAppEvent.MessageUpdate(
452 source = MessageSource.WHATSAPP,
453 conversationId = convId,
454 messageId = m.id,
455 body = m.body,
456 outgoing = m.outgoing,
457 timestamp = m.ts,
458 senderName = m.sender,
459 )
460 )
461 }
462 // Pull the next older page on demand. Fire-and-forget: the request fans out via usync (a
463 // slow IQ) and must NOT block the conversation backfill loop, or only the first chat would
464 // appear promptly. Pagination walks backwards one page at a time — each on-demand response
465 // re-enters handleHistorySync with a new (older) oldest message, until the phone returns an
466 // empty/anchor-only chunk (msgs.isEmpty above → no further request), i.e. end of history.
467 if (requestMore) {
468 val oldest = msgs.minByOrNull { it.ts }
469 if (oldest != null) {
470 scope.launch {
471 sendHistoryOnDemandRequest(rawChatJid, oldest.id, oldest.outgoing, oldest.ts / MS_PER_SECOND)
472 }
473 }
474 }
475 return msgs.size
476}
477
478/**
479 * Ask our own account to stream older history for a chat. Ref whatsmeow BuildHistorySyncRequest
480 * — a HISTORY_SYNC_ON_DEMAND peer-data-operation message sent E2E to self. Deduped per
481 * (chat, oldest-message) cursor so a repeated/anchor-only response ends the walk, while genuinely
482 * older responses keep paginating. Bounded by MAX_ON_DEMAND_PAGES_PER_CHAT. Best-effort.
483 */
484internal suspend fun WhatsAppClient.sendHistoryOnDemandRequest(
485 chatJid: String,
486 oldestMsgId: String,
487 oldestFromMe: Boolean,
488 oldestTsSec: Long,
489) {
490 if (oldestMsgId.isEmpty() || chatJid.isEmpty()) return
491 // Stop if we've already asked for this exact cursor (prevents same-page loops).
492 if (!onDemandRequested.add("$chatJid|$oldestMsgId")) return
493 // Bound total pages per chat.
494 val pages = onDemandPageCount.merge(chatJid, 1, Int::plus) ?: 1
495 if (pages > MAX_ON_DEMAND_PAGES_PER_CHAT) {
496 WhatsAppDiag.log(TAG, "on-demand history: hit page cap for $chatJid, stopping")
497 return
498 }
499 val auth = authData ?: return
500 try {
501 val ownUser = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".")
502 val ownJid = "[email protected]"
503 val msg = WhatsAppProtocol.buildHistoryOnDemandRequest(
504 chatJid, oldestMsgId, oldestFromMe, oldestTsSec, ON_DEMAND_PAGE_SIZE,
505 )
506 val id = WhatsAppProtocol.generateMessageId(auth.wid)
507 val node = buildEncryptedMessageNode(ownJid, id, msg, "text") ?: return
508 webSocket?.send(WhatsAppProtocol.encodeNode(node))
509 WhatsAppDiag.log(TAG, "on-demand history requested for $chatJid (page $pages, oldest=$oldestMsgId)")
510 } catch (expected: Exception) {
511 WhatsAppDiag.log(TAG, "on-demand request failed: ${expected.message}")
512 }
513}