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

WhatsAppClient.kt748 lines · 33.1 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import android.app.Application
4import android.content.Context
5import android.net.ConnectivityManager
6import android.net.Network
7import com.vayunmathur.library.log.Log
8import com.vayunmathur.communicate.data.whatsapp.buildMediaConnQuery
9import com.vayunmathur.communicate.data.whatsapp.buildMexQuery
10import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager
11import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E
12import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E.ParsedPreKeyBundle
13import com.vayunmathur.communicate.data.whatsapp.encodeNode
14import com.vayunmathur.communicate.data.whatsapp.mex.MexResult
15import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket
16import java.security.SecureRandom
17import java.util.Collections
18import java.util.concurrent.ConcurrentHashMap
19import kotlin.concurrent.atomics.AtomicBoolean
20import kotlin.concurrent.atomics.ExperimentalAtomicApi
21import kotlin.time.Duration.Companion.seconds
22import kotlinx.coroutines.CompletableDeferred
23import kotlinx.coroutines.CoroutineScope
24import kotlinx.coroutines.Dispatchers
25import kotlinx.coroutines.Job
26import kotlinx.coroutines.SupervisorJob
27import kotlinx.coroutines.delay
28import kotlinx.coroutines.flow.MutableSharedFlow
29import kotlinx.coroutines.flow.MutableStateFlow
30import kotlinx.coroutines.flow.SharedFlow
31import kotlinx.coroutines.flow.StateFlow
32import kotlinx.coroutines.flow.asSharedFlow
33import kotlinx.coroutines.flow.asStateFlow
34import kotlinx.coroutines.launch
35import kotlinx.coroutines.withTimeoutOrNull
36
37/** The WhatsApp primary client: owns the socket, E2E stores and event stream for the WhatsApp line. */
38@OptIn(ExperimentalAtomicApi::class)
39object WhatsAppClient {
40
41 internal const val TAG = "WhatsAppClient"
42
43 // HistorySync.syncType values (ref whatsmeow HistorySync_HistorySyncType).
44 internal const val SYNC_INITIAL_BOOTSTRAP = 0
45 internal const val SYNC_ON_DEMAND = 6
46
47 // Number of older messages to request per on-demand page.
48 internal const val ON_DEMAND_PAGE_SIZE = 50
49 // Safety cap on on-demand pages per chat so a misbehaving peer can't loop forever
50 // (ON_DEMAND_PAGE_SIZE * this ≈ upper bound on backfilled messages per chat).
51 internal const val MAX_ON_DEMAND_PAGES_PER_CHAT = 400
52
53 // When true, on-demand history keeps paginating older messages until the phone reports
54 // end-of-history (an empty/anchor-only response). When false, only the recent pushed
55 // history is kept (no backfill of "not downloaded" messages).
56 @Volatile
57 var fullHistorySync: Boolean = true
58
59 /** Lifecycle state of the WhatsApp line. */
60 sealed interface State {
61 /** Not yet connected. */
62 data object Idle : State
63 /** The line has no registered account yet. */
64 data object NeedsSetup : State
65 /** The socket is connecting / logging in. */
66 data object Connecting : State
67 /** Connected and logged in. */
68 data object Connected : State
69 /** Disconnected, with the reason. */
70 data class Disconnected(val reason: String) : State
71 }
72
73 val source: MessageSource = MessageSource.WHATSAPP
74
75 /** True only when the Noise socket is logged in (`<success>`). Group/message ops require it. */
76 fun isConnected(): Boolean = stateMutable.value is State.Connected
77
78 val stateMutable = MutableStateFlow<State>(State.Idle)
79 val state: StateFlow<State> = stateMutable.asStateFlow()
80
81 internal val eventsMutable = MutableSharedFlow<WhatsAppEvent>(extraBufferCapacity = 256)
82 val events: SharedFlow<WhatsAppEvent> = eventsMutable.asSharedFlow()
83
84 internal val initialized = AtomicBoolean(false)
85 internal val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
86 internal val random = SecureRandom()
87
88 lateinit var appContext: Application
89 var authData: WhatsAppAuthData? = null
90 // Use WebView-based WebSocket to bypass TLS fingerprinting
91 // WhatsApp blocks non-browser TLS fingerprints (JA3). WebView uses Chromium's
92 // network stack which is indistinguishable from Chrome browser.
93 var webSocket: WhatsAppSocket? = null
94 // Collector jobs for the current socket; cancelled on teardown so old (zombie) sockets
95 // don't keep running keepalives or trigger reconnects, which causes self-conflicts.
96 private var socketCollectorJobs: MutableList<Job> = mutableListOf()
97 // Set when the server tells us this session is terminal (conflict/replaced/device removed),
98 // so the disconnect handler does not start a pointless reconnect loop.
99 var suppressReconnect = false
100 var db: WhatsAppDatabase? = null
101 private var e2e: WhatsAppE2E? = null
102 private var backfillJob: Job? = null
103 private var qrJob: Job? = null
104 private var qrRotateJob: Job? = null
105
106 // Pending IQ request/response correlation (by stanza id) for prekey fetch/upload/count.
107 val pendingIqs = ConcurrentHashMap<String, CompletableDeferred<WhatsAppProtocol.Node>>()
108
109 val nameCache = ConcurrentHashMap<String, String>()
110 internal val lidToPhoneMap = ConcurrentHashMap<String, String>()
111 val undecryptableTracker = ConcurrentHashMap<String, Int>()
112 val pendingMessageIDs: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())
113 internal val processedEditIDs: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())
114 // Groups we've already fetched metadata for this session, so we publish the group's
115 // ConversationUpdate (name / isGroup / participants) at most once instead of on every event.
116 val knownGroups: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())
117 private var reconnectJob: Job? = null
118 private var reconnectAttempts = 0
119 // True while a connect() attempt is actively setting up / handshaking, so the network-available
120 // callback doesn't tear down an in-progress attempt (it fires right after registration).
121 private val connectInProgress = AtomicBoolean(false)
122 // Watches for the network coming back so we can reconnect immediately instead of waiting out
123 // the backoff (or staying dead after a long offline stretch).
124 private var connectivityCallback: ConnectivityManager.NetworkCallback? = null
125 internal val pollSecrets = ConcurrentHashMap<String, ByteArray>()
126 // Cached media upload connection (host, auth, expiryEpochMs) from the w:m media_conn IQ.
127 private var mediaConnCache: Triple<String, String, Long>? = null
128
129 val recentSentDMs: MutableMap<String, SentDM> = Collections.synchronizedMap(
130 object : LinkedHashMap<String, SentDM>(64, 0.75f, false) {
131 override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, SentDM>?): Boolean = size > 200
132 }
133 )
134 // Per-(messageId|deviceJid) resend cap so a stuck peer can't loop us forever.
135 val retryResendCounts = ConcurrentHashMap<String, Int>()
136
137 // Whether this account has read receipts enabled (privacy setting). Default true (WhatsApp
138 // default); refreshed from the server after <success>. When false we must not send read
139 // receipts (the user turned them off).
140 @Volatile var readReceiptsEnabled = true
141
142 private const val INITIAL_RECONNECT_DELAY_MS = 1000L
143 private const val MAX_RECONNECT_DELAY_MS = 60_000L
144 internal const val MAX_FILE_SIZE = 50L * 1024 * 1024
145
146 // Media upload/download run on library:network (HttpURLConnection).
147 internal val MEDIA_CONNECT_TIMEOUT_MS = 30.seconds.inWholeMilliseconds
148 internal val MEDIA_READ_TIMEOUT_MS = 60.seconds.inWholeMilliseconds
149
150 // App-state collections to sync (ref whatsmeow appstate AllPatchNames).
151 internal val APP_STATE_COLLECTIONS = listOf(
152 "critical_block", "critical_unblock_low", "regular_high", "regular", "regular_low",
153 )
154 internal val appStateCollectionsFetching = java.util.Collections.synchronizedSet(HashSet<String>())
155 internal val appStatePrefs by lazy {
156 appContext.getSharedPreferences("wa_appstate", android.content.Context.MODE_PRIVATE)
157 }
158 internal val appStateKeyRequested = java.util.Collections.synchronizedSet(HashSet<String>())
159
160 // Cursors ("chatJid|oldestMsgId") already requested, so a repeated response for the same anchor
161 // stops the walk instead of looping. Distinct (older) cursors are allowed through so pagination
162 // can continue.
163 internal val onDemandRequested = Collections.synchronizedSet(HashSet<String>())
164 // Pages requested per chat, to bound pagination (see MAX_ON_DEMAND_PAGES_PER_CHAT).
165 internal val onDemandPageCount = ConcurrentHashMap<String, Int>()
166
167 // The one-shot saved-auth load launched by init(); joinable so a suspend
168 // caller (registration) can wait for it without blocking its own thread.
169 @Volatile
170 private var initAuthJob: Job? = null
171
172 fun init(context: Context) {
173 if (!initialized.compareAndSet(false, true)) return
174 appContext = context.applicationContext as Application
175 db = WhatsAppDatabase.getDatabase(appContext)
176 WhatsAppCallManager.init(appContext, callBridge)
177 Log.status(TAG, "init")
178 // Load saved auth off the caller's thread: init() is reachable from
179 // Main-adjacent registration scopes, and SharedPreferences + JSON
180 // decode must not block there. State/authData land asynchronously;
181 // suspend callers that must observe them use awaitInitAuth().
182 initAuthJob = scope.launch {
183 val auth = WhatsAppAuthData.load(appContext)
184 if (auth != null) {
185 authData = auth
186 stateMutable.value = State.Connecting
187 registerNetworkMonitor()
188 } else {
189 stateMutable.value = State.NeedsSetup
190 }
191 }
192 }
193
194 /** Wait (suspending, never blocking) until init()'s saved-auth load has landed. */
195 internal suspend fun awaitInitAuth() {
196 initAuthJob?.join()
197 }
198
199 fun start() {
200 if (!initialized.load()) return
201 // Only skip if fully connected. (Connecting is intentionally NOT skipped: a stale/stuck
202 // Connecting state must be able to retry; connect() calls teardownSocket() first so an
203 // overlapping attempt can't leave two live sockets.)
204 if (stateMutable.value is State.Connected) return
205 scope.launch {
206 val auth = WhatsAppAuthData.load(appContext) ?: run {
207 stateMutable.value = State.NeedsSetup
208 return@launch
209 }
210 authData = auth
211 connect(auth)
212 }
213 }
214
215 fun stop() {
216 // Never touch appContext / DAOs before init(); the sync service + MainActivity can call
217 // stop() at startup (waSignedIn=false) before the client was ever initialized.
218 if (!initialized.load()) return
219 Log.status(TAG, "stop — disconnecting WhatsApp session")
220 backfillJob?.cancel()
221 qrJob?.cancel()
222 qrRotateJob?.cancel()
223 reconnectJob?.cancel()
224 reconnectAttempts = 0
225 suppressReconnect = true
226 unregisterNetworkMonitor()
227 webSocket?.disconnect()
228 webSocket = null
229 nameCache.clear()
230 knownGroups.clear()
231 // NOTE: credentials are intentionally NOT cleared here — that would wipe the registration
232 // every time the foreground service stops. Sign-out (which clears auth) is owned by
233 // WhatsAppLineSession.signOut().
234 stateMutable.value = State.NeedsSetup
235 }
236
237 /**
238 * User-triggered "force resync" (settings button): drop any existing socket and reconnect from
239 * scratch, regardless of current state. This is the recovery path when the socket has silently
240 * died — resetting attempts and calling connect() (which tears down the old socket first).
241 * No-op if there is no saved session.
242 */
243 fun forceResync() {
244 if (!initialized.load()) return
245 val auth = authData ?: run {
246 WhatsAppDiag.log(TAG, "forceResync: no session, ignoring")
247 return
248 }
249 WhatsAppDiag.log(TAG, "forceResync: forcing full reconnect")
250 reconnectAttempts = 0
251 reconnectJob?.cancel()
252 suppressReconnect = false
253 scope.launch {
254 try {
255 connect(auth)
256 } catch (expected: Exception) {
257 Log.error(TAG, "forceResync connect failed", expected)
258 scheduleReconnect()
259 }
260 }
261 }
262
263 private fun scheduleReconnect() {
264 // Never permanently give up: a companion device must keep retrying so it recovers after a
265 // long offline stretch (device asleep, no Wi-Fi/data) without a manual app restart. The
266 // backoff is capped, and registerNetworkMonitor() short-circuits the wait when the network
267 // actually returns.
268 if (suppressReconnect || authData == null) return
269 reconnectJob?.cancel()
270 reconnectJob = scope.launch {
271 // Exponential backoff capped at MAX_RECONNECT_DELAY_MS. Cap the shift too so the left
272 // shift can't overflow/wrap once attempts grow large.
273 val shift = reconnectAttempts.coerceAtMost(16)
274 val delayMs = minOf(INITIAL_RECONNECT_DELAY_MS shl shift, MAX_RECONNECT_DELAY_MS)
275 Log.status(TAG, "Reconnecting in ${delayMs}ms (attempt ${reconnectAttempts + 1})")
276 stateMutable.value = State.Connecting
277 delay(delayMs)
278 reconnectAttempts++
279 val auth = authData ?: return@launch
280 try {
281 connect(auth)
282 } catch (expected: Exception) {
283 Log.error(TAG, "Reconnection failed", expected)
284 scheduleReconnect()
285 }
286 }
287 }
288
289 /**
290 * Register a default-network callback so a returning network triggers an immediate reconnect,
291 * instead of waiting out the (up to 60s) backoff or staying disconnected indefinitely. Idempotent.
292 */
293 private fun registerNetworkMonitor() {
294 if (connectivityCallback != null) return
295 val cm = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return
296 val cb = object : ConnectivityManager.NetworkCallback() {
297 override fun onAvailable(network: Network) {
298 if (authData == null || suppressReconnect) return
299 if (stateMutable.value is State.Connected) return
300 if (connectInProgress.load()) return
301 WhatsAppDiag.log(TAG, "network available — reconnecting now")
302 reconnectAttempts = 0
303 reconnectJob?.cancel()
304 reconnectJob = scope.launch {
305 val auth = authData ?: return@launch
306 try {
307 connect(auth)
308 } catch (expected: Exception) {
309 Log.error(TAG, "reconnect on network-available failed", expected)
310 scheduleReconnect()
311 }
312 }
313 }
314 }
315 connectivityCallback = cb
316 try {
317 cm.registerDefaultNetworkCallback(cb)
318 } catch (expected: Exception) {
319 Log.error(TAG, "registerDefaultNetworkCallback failed", expected)
320 connectivityCallback = null
321 }
322 }
323
324 private fun unregisterNetworkMonitor() {
325 val cb = connectivityCallback ?: return
326 connectivityCallback = null
327 try {
328 (appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager)
329 ?.unregisterNetworkCallback(cb)
330 } catch (expected: Exception) {
331 Log.error(TAG, "unregisterNetworkCallback failed", expected)
332 }
333 }
334
335 /** Compact human-readable summary of a decoded binary-XML node for on-screen diagnostics. */
336 internal fun nodeSummary(node: WhatsAppProtocol.Node): String {
337 val attrs =
338 if (node.attrs.isEmpty()) "" else " " + node.attrs.entries.joinToString(" ") { "${it.key}=${it.value}" }
339 val kids = node.getChildren()
340 val kidPart = if (kids.isEmpty()) "" else " {" + kids.joinToString(",") { it.tag } + "}"
341 return "<${node.tag}$attrs>$kidPart"
342 }
343
344 private fun concat(vararg parts: ByteArray): ByteArray {
345 val out = ByteArray(parts.sumOf { it.size })
346 var off = 0
347 for (p in parts) {
348 System.arraycopy(p, 0, out, off, p.size)
349 off += p.size
350 }
351 return out
352 }
353
354 fun ensureE2E(auth: WhatsAppAuthData): WhatsAppE2E? {
355 val database = db ?: return null
356 var inst = e2e
357 if (inst == null) {
358 inst = WhatsAppE2E(database, auth)
359 inst.ensureSignedPreKeyStored()
360 e2e = inst
361 }
362 return inst
363 }
364
365 /**
366 * Send an <iq> stanza and await its result/error response by id.
367 * Returns the response node, or null on timeout.
368 */
369 internal suspend fun sendIqAndWait(node: WhatsAppProtocol.Node, timeoutMs: Long = 30_000): WhatsAppProtocol.Node? {
370 val ws = webSocket ?: return null
371 val id = node.attrs["id"] ?: return null
372 val deferred = CompletableDeferred<WhatsAppProtocol.Node>()
373 pendingIqs[id] = deferred
374 return try {
375 if (!ws.send(WhatsAppProtocol.encodeNode(node))) {
376 pendingIqs.remove(id)
377 return null
378 }
379 withTimeoutOrNull(timeoutMs) { deferred.await() }
380 } finally {
381 pendingIqs.remove(id)
382 }
383 }
384
385 /**
386 * Perform a MEX (`w:mex`) GraphQL call over the existing Noise/XMPP socket (w2.md §5.2). Resolves
387 * the persisted-query [operationName] → doc_id via [MexPersistedQueryProvider]; when the id isn't
388 * in the bundled JSON returns a typed `no_persisted_id:<op>` transport failure (never crashes,
389 * unlike the official debug client). Builds the `{"queryId":…,"variables":…}` envelope, sends the
390 * `<iq xmlns="w:mex">`, waits (32s per §1.5), then extracts the `<result>` node's
391 * `{"data":…,"errors":…}` envelope into a [MexResult].
392 *
393 * Dev-only: guarded by [WhatsAppFeature.enabled] at the repository layer; requires an active
394 * connection (use [com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMex] to fall back to WWW
395 * HTTP when disconnected).
396 */
397 suspend fun mexCall(
398 operationName: String,
399 variablesJson: String,
400 type: String = "get",
401 ): com.vayunmathur.communicate.data.whatsapp.mex.MexResult {
402 val docId = com.vayunmathur.communicate.data.whatsapp.mex.MexPersistedQueryProvider
403 .docIdFor(appContext, operationName)
404 ?: run {
405 WhatsAppDiag.log(TAG, "mex[$operationName]: no persisted doc_id (add it to mex_persist_ids.json)")
406 return MexResult.transport("no_persisted_id:$operationName")
407 }
408 val id = generateMessageId()
409 val queryJson = com.vayunmathur.communicate.data.whatsapp.mex.MexEnvelope.buildQueryJson(docId, variablesJson)
410 val node = WhatsAppProtocol.buildMexQuery(docId, queryJson, id, type)
411 val resp = sendIqAndWait(node, timeoutMs = 32_000)
412 ?: return MexResult.transport("timeout")
413 if (resp.attrs["type"] == "error") {
414 val code = resp.getChildByTag("error")?.attrs?.get("code")
415 WhatsAppDiag.log(TAG, "mex[$operationName]: iq error code=${code ?: "unknown"}")
416 return MexResult.transport("iq_error:${code ?: "unknown"}")
417 }
418 val envelope = resp.getChildByTag("result")?.data?.toString(Charsets.UTF_8)
419 ?: return MexResult.transport("no_result")
420 val out = MexResult.fromEnvelope(envelope)
421 WhatsAppDiag.log(TAG, "mex[$operationName]: success=${out.isSuccess} errors=${out.errors.size}")
422 return out
423 }
424
425 /**
426 * Upload one-time + signed prekeys to the server.
427 * Ref whatsmeow prekeys.go uploadPreKeys. [initialUpload] uploads a large batch after pair.
428 */
429 /**
430 * Upload prekeys on connect if the server is likely low. Does an initial large batch
431 * when the local prekey store is empty (freshly paired). Ref whatsmeow prekeys.go.
432 */
433 internal suspend fun maybeUploadPreKeys() {
434 val database = db ?: return
435 val count = try { database.e2ePreKeyDao().getCount() } catch (ignored: Exception) { return }
436 val unuploaded = try { database.e2ePreKeyDao().getUnuploaded().size } catch (ignored: Exception) { 0 }
437 WhatsAppDiag.log(TAG, "prekeys: local count=$count unuploaded=$unuploaded")
438 when {
439 count == 0 -> uploadPreKeys(initialUpload = true)
440 unuploaded > 0 -> uploadPreKeys(initialUpload = false)
441 else -> WhatsAppDiag.log(TAG, "prekeys: nothing to upload")
442 }
443 }
444
445 /**
446 * Upload one-time + signed prekeys to the server.
447 * Ref whatsmeow prekeys.go uploadPreKeys. [initialUpload] uploads a large batch after pair.
448 */
449 internal suspend fun uploadPreKeys(initialUpload: Boolean) {
450 val auth = authData ?: return
451 val crypto = ensureE2E(auth) ?: return
452 val content = crypto.buildPreKeyUploadContent(initialUpload)
453 val iq = WhatsAppProtocol.Node(
454 tag = "iq",
455 attrs = mapOf(
456 "id" to generateMessageId(),
457 "type" to "set",
458 "xmlns" to "encrypt",
459 "to" to "s.whatsapp.net",
460 ),
461 content = content,
462 )
463 WhatsAppDiag.log(TAG, "prekeys: uploading (initial=$initialUpload, ${content.size} nodes)…")
464 val resp = sendIqAndWait(iq)
465 if (resp != null && resp.attrs["type"] != "error") {
466 crypto.markPreKeysUploaded()
467 WhatsAppDiag.log(TAG, "prekeys: upload OK (initial=$initialUpload)")
468 } else {
469 WhatsAppDiag.log(TAG, "prekeys: upload FAILED/timeout (resp=${resp?.attrs?.get("type") ?: "null"})")
470 }
471 }
472
473 /**
474 * Fetch a peer's prekey bundle and establish an outbound session if none exists.
475 * Ref whatsmeow prekeys.go fetchPreKeys + send.go encryptMessageForDevice.
476 */
477 internal suspend fun ensureSession(jid: String): Boolean {
478 val auth = authData ?: return false
479 val crypto = ensureE2E(auth) ?: return false
480 if (crypto.hasSession(jid)) return true
481 val bundle = fetchPreKeyBundle(jid) ?: return false
482 return try {
483 crypto.processPreKeyBundle(jid, bundle)
484 true
485 } catch (expected: Exception) {
486 Log.error(TAG, "Failed to process prekey bundle for $jid", expected)
487 false
488 }
489 }
490
491 /** Fetch and parse the peer's pre-key bundle, or null when unavailable. */
492 private suspend fun fetchPreKeyBundle(jid: String): ParsedPreKeyBundle? {
493 val device = jid.substringBefore("@").substringAfter(":", "0").toIntOrNull() ?: 0
494 val iq = WhatsAppProtocol.Node(
495 tag = "iq",
496 attrs = mapOf(
497 "id" to generateMessageId(),
498 "type" to "get",
499 "xmlns" to "encrypt",
500 "to" to "s.whatsapp.net",
501 ),
502 content = listOf(
503 WhatsAppProtocol.Node(
504 tag = "key",
505 content = listOf(
506 WhatsAppProtocol.Node(
507 tag = "user",
508 attrs = mapOf("jid" to jid, "reason" to "identity"),
509 )
510 ),
511 )
512 ),
513 )
514 val resp = sendIqAndWait(iq) ?: return null
515 val list = resp.getChildByTag("list") ?: return null
516 val userNode = list.getChildren().firstOrNull { it.tag == "user" } ?: return null
517 val auth = authData ?: return null
518 return ensureE2E(auth)?.parsePreKeyBundleNode(device, userNode)
519 }
520
521 /**
522 * Refresh a peer's presence via `xwa2_presence_data_platform_get_online_or_last_status` and emit
523 * [WhatsAppEvent.PresenceUpdate] (Phase F 1e). Dev-gated + best-effort. [conversationId] may be a
524 * `wa:<jid>` id or a bare JID.
525 */
526 suspend fun refreshPresence(conversationId: String) {
527 if (!WhatsAppFeature.enabled) return
528 val jid = extractJid(conversationId) ?: return
529 val payload = fetchPresencePayload(jid) ?: return
530 val presences = payload.optJSONArray("presences") ?: return
531 if (presences.length() == 0) return
532 val p = presences.optJSONObject(0) ?: return
533 val lastSeen = p.optString("last_seen").toLongOrNull() ?: 0L
534 eventsMutable.emit(WhatsAppEvent.PresenceUpdate(
535 conversationId = "wa:$jid",
536 isOnline = lastSeen == 0L, // online payloads omit last_seen; last-status carries it
537 lastSeen = lastSeen,
538 ))
539 }
540
541 /** Presence payload for [jid], or null when unavailable. */
542 private suspend fun fetchPresencePayload(jid: String): org.json.JSONObject? {
543 val res = runCatching {
544 com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.getOnlineOrLastStatus(
545 appContext,
546 listOf(jid),
547 null)
548 }.getOrNull() ?: return null
549 if (!res.isSuccess) return null
550 val data = res.data ?: return null
551 return data.optJSONObject("xwa2_presence_data_platform_get_online_or_last_status")
552 }
553
554 /**
555 * Fetch (and cache) the media upload host + auth token via the w:m media_conn IQ.
556 * Ref whatsmeow mediaconn.go queryMediaConn. Returns (host, auth) or null.
557 */
558 private const val MS_PER_SECOND = 1000L
559
560 internal suspend fun mediaConn(): Pair<String, String>? {
561 mediaConnCache?.let { if (System.currentTimeMillis() < it.third) return it.first to it.second }
562 val iq = WhatsAppProtocol.buildMediaConnQuery(generateMessageId())
563 val resp = sendIqAndWait(iq) ?: return null
564 val mc = resp.getChildByTag("media_conn") ?: return null
565 val auth = mc.attrs["auth"] ?: return null
566 val ttl = mc.attrs["ttl"]?.toLongOrNull() ?: 300L
567 val host = mc.getChildren().firstOrNull { it.tag == "host" }?.attrs?.get("hostname") ?: return null
568
569 mediaConnCache = Triple(host, auth, System.currentTimeMillis() + ttl * MS_PER_SECOND)
570 return host to auth
571 }
572
573
574
575 /** Cancel the current socket's collectors and disconnect it, so only one socket is ever live. */
576 private fun teardownSocket() {
577 socketCollectorJobs.forEach { it.cancel() }
578 socketCollectorJobs.clear()
579 webSocket?.disconnect()
580 webSocket = null
581 }
582
583 private suspend fun connect(auth: WhatsAppAuthData) {
584 stateMutable.value = State.Connecting
585 suppressReconnect = false
586 connectInProgress.store(true)
587 registerNetworkMonitor()
588 // Ensure no previous socket (provisioning or a prior login attempt) is still alive,
589 // otherwise overlapping sessions make the server reject us with <stream:error><conflict>.
590 teardownSocket()
591
592 // Use WebView-based WebSocket to bypass TLS fingerprinting
593 val ws = WhatsAppSocket(auth)
594 webSocket = ws
595 socketCollectorJobs.add(
596 scope.launch {
597 ws.connectionState.collect { state ->
598 when (state) {
599 is WhatsAppSocket.ConnectionState.Connected -> {
600 WhatsAppDiag.log(TAG, "login socket: Noise connected, awaiting <success>")
601 connectInProgress.store(false)
602 ensureE2E(auth)
603 }
604 is WhatsAppSocket.ConnectionState.Disconnected -> {
605 WhatsAppDiag.log(TAG, "login socket: Disconnected (${state.reason})")
606 connectInProgress.store(false)
607 if (authData != null && !suppressReconnect) {
608 scheduleReconnect()
609 } else {
610 stateMutable.value = State.Disconnected(state.reason)
611 }
612 }
613 else -> {}
614 }
615 }
616 }
617 )
618 socketCollectorJobs.add(
619 scope.launch {
620 ws.messages.collect { data ->
621 handleIncomingMessage(data)
622 }
623 }
624 )
625 ws.connect()
626 }
627
628 /**
629 * Transport bridge for [WhatsAppCallManager]: lets the call state machine send `<call>` stanzas
630 * and encrypt/decrypt the per-device call key without depending on the socket/Signal internals.
631 */
632 private val callBridge = object : WhatsAppCallManager.Bridge {
633 override val ownJid: String get() = authData?.wid ?: ""
634
635 override fun newId(): String = generateMessageId()
636
637 override suspend fun sendCallStanza(node: WhatsAppProtocol.Node): Boolean {
638 val ws = webSocket ?: return false
639 return ws.send(WhatsAppProtocol.encodeNode(node))
640 }
641
642 override suspend fun encryptCallKey(
643 toJid: String,
644 paddedCallKey: ByteArray,
645 ): List<WhatsAppProtocol.ParticipantEnc> {
646 val auth = authData ?: return emptyList()
647 val crypto = ensureE2E(auth) ?: return emptyList()
648 val ownUser = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".")
649 val devices = (getUserDevices(listOf(toJid)).ifEmpty { listOf(toJid) } +
650 getUserDevices(listOf("[email protected]"))).distinct()
651 return encryptForDevices(crypto, devices, ownUser, auth.wid, paddedCallKey, null).first
652 }
653
654 override suspend fun decryptCallKey(
655 senderJid: String,
656 encType: String,
657 ciphertext: ByteArray,
658 ): ByteArray? {
659 val auth = authData ?: return null
660 val crypto = ensureE2E(auth) ?: return null
661 return try {
662 crypto.decryptDM(senderJid, isPreKey = encType == "pkmsg", ciphertext = ciphertext)
663 } catch (expected: Exception) {
664 Log.status(TAG, "call key decrypt failed from $senderJid", expected)
665 null
666 }
667 }
668
669 override fun emit(event: WhatsAppEvent) {
670 scope.launch { eventsMutable.emit(event) }
671 }
672
673 override fun resolveName(jid: String): String? {
674 // Non-suspend, best-effort: the phone form of the JID. Full name resolution happens
675 // later off the emitted event (resolveName is suspend / DB-backed).
676 val local = jid.substringBefore("@").substringBefore(":").substringBefore(".")
677 return if (local.isNotEmpty() && local.all { it.isDigit() }) "+$local" else null
678 }
679 }
680
681 /**
682 * Send a typing indicator (chat presence) with media type differentiation.
683 * From whatsmeow HandleMatrixTyping / SendChatPresence.
684 * Supports: text typing, audio recording, media uploading.
685 */
686 enum class TypingType { TEXT, RECORDING_AUDIO, UPLOADING_MEDIA }
687
688 /**
689 * Handle the server <success> stanza: the point at which login is actually authenticated.
690 * Mirrors whatsmeow connectionevents.go handleConnectSuccess — persists the server-assigned
691 * LID, sends SetPassive(false) so the companion leaves passive mode and receives the full
692 * event stream, then uploads prekeys if low, sends unavailable presence and starts backfill.
693 */
694 internal suspend fun handleConnectSuccess(node: WhatsAppProtocol.Node) {
695 WhatsAppDiag.log(TAG, "AUTHENTICATED (<success>) — login complete")
696 reconnectAttempts = 0
697 stateMutable.value = State.Connected
698 val lid = node.attrs["lid"]
699 val current = authData
700 if (!lid.isNullOrEmpty() && current != null && current.lid.isEmpty()) {
701 val updated = current.copy(lid = lid)
702 authData = updated
703 WhatsAppAuthData.save(appContext, updated)
704 }
705 scope.launch { maybeUploadPreKeys() }
706 scope.launch { refreshPrivacySettings() }
707 // Phase C 2f: best-effort device-contact sync after login (dev-gated, needs READ_CONTACTS).
708 scope.launch { runCatching { WhatsAppContactSync.sync(appContext) } }
709 val pas = setPassiveActive()
710 WhatsAppDiag.log(TAG, "post-success: SetPassive(active) ${if (pas) "OK" else "FAILED"}")
711 sendUnavailablePresence()
712 kickoffBackfill()
713 }
714
715 /**
716 * Tell the server this device is active (not passive) so it pushes the full event stream.
717 * Ref whatsmeow connectionevents.go SetPassive(false):
718 * <iq xmlns="passive" type="set"><active/></iq>. Login sends passive=true, so this is
719 * required after <success> or the companion never receives messages.
720 */
721 internal suspend fun setPassiveActive(): Boolean {
722 val node = WhatsAppProtocol.Node(
723 tag = "iq",
724 attrs = mapOf(
725 "id" to generateMessageId(),
726 "type" to "set",
727 "xmlns" to "passive",
728 "to" to "s.whatsapp.net",
729 ),
730 content = listOf(WhatsAppProtocol.Node(tag = "active")),
731 )
732 val resp = sendIqAndWait(node, timeoutMs = 10_000)
733 return resp != null && resp.attrs["type"] != "error"
734 }
735
736 /**
737 * Send unavailable presence on connect.
738 * Go client.go Connected handler sends PresenceUnavailable.
739 */
740 internal fun sendUnavailablePresence() {
741 val ws = webSocket ?: return
742 val node = WhatsAppProtocol.Node(
743 tag = "presence",
744 attrs = mapOf("type" to "unavailable"),
745 )
746 ws.send(WhatsAppProtocol.encodeNode(node))
747 }
748}