communicate: WhatsApp primary client (registration, Noise login, 1:1 messaging)
- Commit
33dd602f5515d60fc078944bf1eba9d69de6e227- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-13 20:02 UTC (3 months ago)
- Parents
51850bd
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 0b75b74e14..fe42891790 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -371,6 +371,20 @@ dependencies = [ "memchr", ] +[[package]]+name = "communicate_signal"+version = "0.1.0"+dependencies = [+ "aes 0.8.4",+ "curve25519-dalek",+ "hmac 0.12.1",+ "jni",+ "rand_core 0.6.4",+ "sha2 0.10.9",+ "subtle",+ "x25519-dalek",+]+ [[package]] name = "const-oid" version = "0.9.6"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex e7b6fae9a5..f911d542a5 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -16,6 +16,7 @@ members = [ "library/vision/src/main/rust", "measure/src/main/rust", "messages/src/main/rust",+ "communicate/src/main/rust", "youpipe/src/main/rust", "web/src/main/rust", "third_party/om-file-format-sys",
communicate/build.gradle.kts
diff --git a/communicate/build.gradle.kts b/communicate/build.gradle.ktsindex 92d4585932..0e24b89e58 100644--- a/communicate/build.gradle.kts+++ b/communicate/build.gradle.kts@@ -1,5 +1,17 @@+import java.util.Locale+import javax.inject.Inject+import org.gradle.api.DefaultTask+import org.gradle.api.file.DirectoryProperty+import org.gradle.api.file.RegularFileProperty+import org.gradle.api.tasks.InputDirectory+import org.gradle.api.tasks.InputFile+import org.gradle.api.tasks.OutputDirectory+import org.gradle.api.tasks.TaskAction+import org.gradle.process.ExecOperations+ plugins { id("common-conventions-app")+ id("com.google.devtools.ksp") } launcherIcon {@@ -10,8 +22,135 @@ android { defaultConfig { applicationId = "com.vayunmathur.communicate" }+ compileOptions {+ isCoreLibraryDesugaringEnabled = true+ }+ packaging {+ resources {+ // libsignal-client bundles its desktop JNI natives (macOS .dylib,+ // Windows .dll) as Java resources. They can never load on Android and+ // add ~40 MB to the APK — strip them. The Android lib/arm64-v8a/+ // libsignal_jni.so is unaffected.+ excludes += setOf("**/*.dylib", "*.dylib", "**/*.dll", "*.dll")+ }+ jniLibs {+ // Test-only libsignal native (NativeTesting bridge); unused in prod.+ excludes += "**/libsignal_jni_testing.so"+ }+ }+}++dependencies {+ coreLibraryDesugaring(libs.desugar.jdk.libs)+}++// ----------------------------------------------------------------+// Protobuf code generation (manual)+// ----------------------------------------------------------------+//+// Both `com.squareup.wire` and `com.google.protobuf` Gradle plugins fail+// to apply to this module because they try to cast AGP 9's+// `ApplicationExtensionImpl` to the legacy `BaseExtension`, which AGP 9+// removed. Until those plugins catch up, we resolve `protoc` from Maven+// Central and invoke it directly. The resulting Java classes (lite+// runtime) are added to the variant's Java sources via the AGP+// `androidComponents` extension below.++val osClassifier: String = run {+ val osName = System.getProperty("os.name").lowercase(Locale.US)+ val arch = System.getProperty("os.arch").lowercase(Locale.US)+ val os = when {+ osName.contains("mac") || osName.contains("darwin") -> "osx"+ osName.contains("win") -> "windows"+ else -> "linux"+ }+ val cpu = when {+ arch.contains("aarch64") || arch.contains("arm64") -> "aarch_64"+ arch.contains("64") -> "x86_64"+ else -> "x86_32"+ }+ "$os-$cpu"+}++val protocConfig: Configuration = configurations.create("protocBinary") {+ isCanBeResolved = true+ isCanBeConsumed = false+}++dependencies {+ "protocBinary"("com.google.protobuf:protoc:${libs.versions.protoc.get()}:$osClassifier@exe")+}++val protoSrcDir = layout.projectDirectory.dir("src/main/proto")+val protoGenDir = layout.buildDirectory.dir("generated/source/proto/java")++// Custom task class so we can inject ExecOperations cleanly (the+// configuration cache rejects capturing the Project at execution time).+abstract class GenerateProtoTask @Inject constructor(+ private val exec: ExecOperations,+) : DefaultTask() {+ @get:InputFile+ abstract val protocBinary: RegularFileProperty++ @get:InputDirectory+ abstract val protoSourceDir: DirectoryProperty++ @get:OutputDirectory+ abstract val outputDir: DirectoryProperty++ @TaskAction+ fun run() {+ val binary = protocBinary.get().asFile+ binary.setExecutable(true)+ val out = outputDir.get().asFile+ out.deleteRecursively()+ out.mkdirs()+ val srcDir = protoSourceDir.get().asFile+ val protoFiles = srcDir.walkTopDown()+ .filter { it.isFile && it.extension == "proto" }+ .toList()+ if (protoFiles.isEmpty()) return+ exec.exec {+ commandLine = buildList {+ add(binary.absolutePath)+ add("--java_out=${out.absolutePath}")+ add("-I=${srcDir.absolutePath}")+ addAll(protoFiles.map { it.absolutePath })+ }+ }+ }+}++val generateProto = tasks.register<GenerateProtoTask>("generateProto") {+ protocBinary.set(layout.file(protocConfig.elements.map { it.single().asFile }))+ protoSourceDir.set(protoSrcDir)+ outputDir.set(protoGenDir)+}++// Make Kotlin/Java/KSP compilation wait on protoc. KSP runs ahead of+// compileKotlin so it has to be in this list too.+tasks.matching {+ it.name.startsWith("compile") &&+ (it.name.endsWith("Kotlin") || it.name.endsWith("JavaWithJavac")) ||+ it.name.startsWith("ksp")+}.configureEach {+ dependsOn(generateProto)+}++androidComponents {+ onVariants { variant ->+ // Wire proto gen sources + Rust JNI libs into each variant.+ variant.sources.java?.addStaticSourceDirectory(protoGenDir.get().asFile.absolutePath)+ val rustDir = layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+ variant.sources.jniLibs?.addStaticSourceDirectory(rustDir)+ } } +// Classic Signal protocol v3 (X3DH + Double Ratchet + Sender Keys) for the WhatsApp+// primary client — Rust impl. Unique crate name to avoid workspace collision with+// messages' whatsapp_signal.+rustNativeLib("communicate_signal", "communicate_signal")+ dependencies { // Google Voice virtual line: protojson RPCs + SIP-over-WSS transport go through // the repo's own Android-only HTTP/WebSocket stack (no OkHttp/Ktor).@@ -22,8 +161,31 @@ dependencies { implementation(libs.stream.webrtc.android) // E.164 normalization to reconcile SIM vs Google Voice numbers. implementation(libs.libphonenumber)- // Persist the Google Voice session (cookies, API key, authuser, GV number).+ // Persist the Google Voice / WhatsApp session (cookies, API key, auth, number). implementation(libs.androidx.datastore.preferences) // Document-start JS injection to hook fetch/XHR before the GV web app captures them. implementation(libs.androidx.webkit)++ // ---- WhatsApp primary client ----+ // Room — E2E state + message/thread/reaction/poll cache (communicate's first Room DB).+ implementation(libs.androidx.room.runtime)+ implementation(libs.androidx.room.ktx)+ ksp(libs.androidx.room.compiler)+ implementation(project(":library:room"))++ // Protobuf runtime — full Java variant. The lite runtime drops the+ // reflection API which we need for the PB-Lite encoder.+ implementation(libs.protobuf.java)++ // ZXing core — QR code encoding only (no scanner UI). Retained for parity with the+ // messages port; unused by the primary registration flow.+ implementation(libs.zxing.core)++ // Signal protocol crypto (Double Ratchet, sealed sender, pre-keys, etc.).+ // Also provides certificate verification (ECPublicKey.verifySignature) for the WhatsApp+ // Noise handshake cert chain.+ implementation(libs.libsignal.android)++ // kotlinx.serialization — session/auth data persistence + serviceData blob.+ implementation(libs.kotlinx.serialization.json) }
communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex c257bf408c..67305c9ace 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -22,6 +22,7 @@ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_PHONE_CALL" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />@@ -147,6 +148,11 @@ android:exported="false" android:foregroundServiceType="remoteMessaging" /> + <service+ android:name=".telephony.WhatsAppSyncService"+ android:exported="false"+ android:foregroundServiceType="remoteMessaging" />+ <service android:name=".telephony.GoogleVoiceCallForegroundService" android:exported="false"
communicate/src/main/assets/whatsapp/about_logo.png
diff --git a/communicate/src/main/assets/whatsapp/about_logo.png b/communicate/src/main/assets/whatsapp/about_logo.pngnew file mode 100644index 0000000000..33a53452c7Binary files /dev/null and b/communicate/src/main/assets/whatsapp/about_logo.png differ
communicate/src/main/assets/whatsapp/signing_cert.der
diff --git a/communicate/src/main/assets/whatsapp/signing_cert.der b/communicate/src/main/assets/whatsapp/signing_cert.dernew file mode 100644index 0000000000..7833c614b0Binary files /dev/null and b/communicate/src/main/assets/whatsapp/signing_cert.der differ
communicate/src/main/assets/whatsapp/signing_cert.pkcs7
diff --git a/communicate/src/main/assets/whatsapp/signing_cert.pkcs7 b/communicate/src/main/assets/whatsapp/signing_cert.pkcs7new file mode 100644index 0000000000..6b672fe78bBinary files /dev/null and b/communicate/src/main/assets/whatsapp/signing_cert.pkcs7 differ
communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.ktindex 0013640e87..9ba821ff0b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -35,6 +35,9 @@ import com.vayunmathur.communicate.ui.DialerScreen import com.vayunmathur.communicate.ui.MessagesScreen import com.vayunmathur.communicate.ui.call.CallScreen import com.vayunmathur.communicate.ui.googlevoice.GoogleVoiceSignInScreen+import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationScreen+import com.vayunmathur.communicate.telephony.WhatsAppSyncService+import com.vayunmathur.communicate.data.whatsapp.WhatsAppLineSession import androidx.compose.ui.platform.LocalContext import kotlinx.serialization.Serializable @@ -44,6 +47,8 @@ sealed interface Route : NavKey { @Serializable data object CallLogs : Route @Serializable data object Accounts : Route @Serializable data object GoogleVoiceSignIn : Route+ @Serializable data object WhatsAppRegistration : Route+ @Serializable data object WhatsAppBackupImport : Route @Serializable data class Conversation(@@ -84,8 +89,15 @@ private fun CommunicateApp() { val context = LocalContext.current val session = remember { GoogleVoiceSession.get(context) } val gvSignedIn by session.signedInFlow.collectAsState(initial = false)+ val waSession = remember { WhatsAppLineSession.get(context) }+ val waSignedIn by waSession.signedInFlow.collectAsState(initial = false) val callState by GoogleVoiceCallManager.state.collectAsState() + // Own the WhatsApp always-on receive state via its foreground sync service.+ LaunchedEffect(waSignedIn) {+ if (waSignedIn) WhatsAppSyncService.start(context) else WhatsAppSyncService.stop(context)+ }+ // Keep the Telecom account fresh, but let the foreground service own always-on receive state. LaunchedEffect(gvSignedIn) { GoogleVoiceCallManager.init(context)@@ -104,6 +116,8 @@ private fun CommunicateApp() { val currentRoot = when (currentPage) { is Route.Conversation -> Route.Messages is Route.Accounts, is Route.GoogleVoiceSignIn -> Route.Messages+ is Route.WhatsAppRegistration -> Route.Messages+ is Route.WhatsAppBackupImport -> Route.Messages else -> currentPage } val pages = listOf(@@ -146,6 +160,8 @@ private fun CommunicateApp() { AccountsScreen( onBack = { backStack.pop() }, onSignIn = { backStack.add(Route.GoogleVoiceSignIn) },+ onRegisterWhatsApp = { backStack.add(Route.WhatsAppRegistration) },+ onImportBackup = { backStack.add(Route.WhatsAppBackupImport) }, ) } entry<Route.GoogleVoiceSignIn> {@@ -154,6 +170,17 @@ private fun CommunicateApp() { onSignedIn = { backStack.pop() }, ) }+ entry<Route.WhatsAppRegistration> {+ WhatsAppRegistrationScreen(+ onBack = { backStack.pop() },+ onRegistered = { backStack.pop() },+ )+ }+ entry<Route.WhatsAppBackupImport> {+ com.vayunmathur.communicate.ui.whatsapp.WhatsAppBackupImportScreen(+ onBack = { backStack.pop() },+ )+ } entry<Route.Conversation> { route -> ConversationScreen( threadId = route.threadId,
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.ktindex 5d9cdf802c..775b045795 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt@@ -8,6 +8,7 @@ package com.vayunmathur.communicate.data enum class CommunicateLine { Sim, GoogleVoice,+ WhatsApp, } /**@@ -26,6 +27,11 @@ sealed interface LineChoice { override val label = "Google Voice" override val category get() = CommunicateLine.GoogleVoice }++ data object WhatsApp : LineChoice {+ override val label = "WhatsApp"+ override val category get() = CommunicateLine.WhatsApp+ } } data class CommunicateContact(@@ -82,6 +88,10 @@ data class SmsThread( */ val remoteId: String? = null, val subscriptionId: Int? = null,+ /** WhatsApp (and future group-capable lines): true for group chats. */+ val isGroup: Boolean = false,+ /** Optional avatar URL/path for the thread (WhatsApp contact/group photo). */+ val avatarUrl: String? = null, ) data class SmsMessage(@@ -96,4 +106,9 @@ data class SmsMessage( val remoteId: String? = null, val attachments: List<CommunicateAttachment> = emptyList(), val subscriptionId: Int? = null,+ /**+ * Line-specific rich payload as JSON. For WhatsApp this is [WhatsAppServiceData]+ * (reactions/polls/edited/revoked/quoted/group). Null for SIM/GV.+ */+ val serviceData: String? = null, )
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.ktindex 400f70a5a8..aa61579d77 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -9,6 +9,7 @@ import android.os.Bundle import android.provider.CallLog import android.provider.ContactsContract import android.provider.Telephony+import android.telephony.TelephonyManager import android.telecom.PhoneAccount import android.telecom.TelecomManager import androidx.core.content.ContextCompat@@ -21,6 +22,14 @@ import com.vayunmathur.communicate.data.googlevoice.GvCall import com.vayunmathur.communicate.data.googlevoice.GvCallType import com.vayunmathur.communicate.data.googlevoice.GvMessage import com.vayunmathur.communicate.data.googlevoice.GvThread+import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient+import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase+import com.vayunmathur.communicate.data.whatsapp.WhatsAppLineSession+import com.vayunmathur.communicate.data.whatsapp.WhatsAppServiceData+import com.vayunmathur.communicate.data.whatsapp.WhatsAppCachedMessage+import com.vayunmathur.communicate.data.whatsapp.WhatsAppConversation+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext import com.vayunmathur.library.ui.ExternalIntents object CommunicateRepository {@@ -288,7 +297,8 @@ object CommunicateRepository { suspend fun loadSmsThreadsMerged(context: Context): List<SmsThread> { val sim = loadSmsThreads(context) val gv = loadGoogleVoiceThreads(context)- return (sim + gv).sortedByDescending { it.timestampMillis }+ val wa = loadWhatsAppThreads(context)+ return (sim + gv + wa).sortedByDescending { it.timestampMillis } } /** Route by line: SIM threads read the provider; GV threads hit `api2thread/get`. */@@ -302,6 +312,12 @@ object CommunicateRepository { .map { it.toSmsMessage(thread.threadId, context) } }.getOrDefault(emptyList()) }+ CommunicateLine.WhatsApp -> {+ // New conversations have no remoteId yet — derive the JID from the address so the+ // outgoing echo (cached under the same normalized JID) shows immediately.+ val jid = thread.remoteId?.takeIf { it.isNotBlank() } ?: toWhatsAppJid(context, thread.address)+ loadWhatsAppMessages(context, jid)+ } } /** Merged call history: device call log + Google Voice calls, newest first. */@@ -344,6 +360,23 @@ object CommunicateRepository { GoogleVoiceClient.get(context).sendPreparedSms(sendBody) true }.getOrDefault(false)+ LineChoice.WhatsApp -> withContext(Dispatchers.IO) {+ runCatching {+ // For WhatsApp the conversation is addressed by JID: use the thread's remoteId when+ // replying to an existing chat, else derive a 1:1 JID from the phone number.+ val jid = threadRemoteId ?: toWhatsAppJid(context, address)+ val ok = if (attachments.isEmpty()) {+ WhatsAppClient.sendMessage(jid, body)+ } else {+ // Media send goes through the dedicated path; here just send any caption text.+ if (body.isNotBlank()) WhatsAppClient.sendMessage(jid, body) else true+ }+ // Echo the outgoing message into the local cache so it shows in our own thread+ // (a primary-only line gets no server echo of its own sends).+ if (ok && body.isNotBlank()) cacheOutgoingWhatsApp(context, jid, body)+ ok+ }.getOrDefault(false)+ } } /** Send an SMS from a specific SIM subscription and store it in the Sent box. */@@ -407,6 +440,197 @@ object CommunicateRepository { /** Stable positive Long key for a GV remote id, kept clear of provider thread ids. */ fun stableThreadId(remoteId: String): Long = (remoteId.hashCode().toLong() and 0xFFFFFFFFL) or 0x1_0000_0000L + // ------------------------------------------------------------------+ // WhatsApp primary line: threads/messages read from the local Room cache+ // (populated by WhatsAppEventProcessor), rich actions delegate to WhatsAppClient.+ // ------------------------------------------------------------------++ /** Virtual (network-backed) lines that don't map to a physical SIM subscription. */+ val isVirtualLine = setOf(CommunicateLine.GoogleVoice, CommunicateLine.WhatsApp)++ private suspend fun loadWhatsAppThreads(context: Context): List<SmsThread> {+ if (!WhatsAppLineSession.get(context).isSignedIn()) return emptyList()+ return runCatching {+ val db = WhatsAppDatabase.getDatabase(context)+ db.cachedMessageDao().getLatestPerConversation().map { m ->+ val sd = WhatsAppServiceData.parse(m.serviceData)+ val jid = m.conversationJid+ val isGroup = sd?.isGroup ?: jid.endsWith("@g.us")+ val unread = db.conversationDao().getConversation(jid)?.unreadCount ?: 0+ SmsThread(+ threadId = stableThreadId(jid),+ address = jidToDisplayAddress(jid),+ displayName = whatsAppDisplayName(context, jid, sd),+ snippet = if (m.isRevoked) "This message was deleted" else m.body,+ timestampMillis = m.timestamp,+ unreadCount = unread,+ line = CommunicateLine.WhatsApp,+ remoteId = jid,+ isGroup = isGroup,+ avatarUrl = null,+ )+ }+ }.getOrDefault(emptyList())+ }++ private suspend fun loadWhatsAppMessages(context: Context, jid: String): List<SmsMessage> =+ runCatching {+ val db = WhatsAppDatabase.getDatabase(context)+ db.cachedMessageDao().getForConversation(jid).map { m ->+ SmsMessage(+ id = (m.messageId.hashCode().toLong() and 0xFFFFFFFFL),+ threadId = stableThreadId(jid),+ address = jidToDisplayAddress(jid),+ body = if (m.isRevoked) "" else m.body,+ timestampMillis = m.timestamp,+ outgoing = m.outgoing,+ read = true,+ line = CommunicateLine.WhatsApp,+ remoteId = m.messageId,+ serviceData = m.serviceData,+ )+ }+ }.getOrDefault(emptyList())++ // -- WhatsApp rich actions (delegate to the client) --++ suspend fun sendWhatsAppReaction(+ jid: String,+ messageId: String,+ emoji: String,+ targetFromMe: Boolean,+ targetSenderJid: String?,+ ): Boolean = withContext(Dispatchers.IO) {+ WhatsAppClient.sendReaction(jid, messageId, emoji, targetFromMe, targetSenderJid)+ }++ suspend fun editWhatsAppMessage(jid: String, messageId: String, newBody: String): Boolean =+ withContext(Dispatchers.IO) { WhatsAppClient.sendEdit(jid, messageId, newBody) }++ suspend fun revokeWhatsAppMessage(jid: String, messageId: String, senderJid: String = ""): Boolean =+ withContext(Dispatchers.IO) { WhatsAppClient.sendRevoke(jid, messageId, senderJid) }++ suspend fun sendWhatsAppPollVote(+ jid: String,+ pollMessageId: String,+ pollCreatorJid: String,+ pollFromMe: Boolean,+ selectedOptionNames: List<String>,+ ): Boolean = withContext(Dispatchers.IO) {+ WhatsAppClient.sendPollVote(jid, pollMessageId, pollCreatorJid, pollFromMe, selectedOptionNames)+ }++ suspend fun createWhatsAppPoll(+ jid: String,+ question: String,+ options: List<String>,+ selectableCount: Int = 0,+ ): String? = withContext(Dispatchers.IO) {+ WhatsAppClient.sendPollCreation(jid, question, options, selectableCount)+ }++ suspend fun sendWhatsAppMedia(jid: String, bytes: ByteArray, mimeType: String, fileName: String?): Boolean =+ withContext(Dispatchers.IO) { WhatsAppClient.sendMedia(jid, bytes, mimeType, fileName) }++ suspend fun sendWhatsAppReadReceipt(+ jid: String,+ lastMessageId: String?,+ lastTimestamp: Long,+ senderJid: String? = null,+ ): Boolean = withContext(Dispatchers.IO) {+ WhatsAppClient.sendReadReceipt(jid, lastMessageId, lastTimestamp, senderJid)+ }++ /**+ * Mark a WhatsApp conversation read: clear the local unread badge and send a `read` receipt for+ * the latest inbound message (blue ticks on the sender's side). [alreadyReadId] is the last+ * message we already receipted, so the foreground poll doesn't re-send. Returns the id now+ * marked read (or [alreadyReadId] when there is nothing newer).+ */+ suspend fun markWhatsAppRead(+ context: Context,+ remoteId: String?,+ address: String,+ alreadyReadId: String?,+ ): String? = withContext(Dispatchers.IO) {+ val jid = remoteId?.takeIf { it.isNotBlank() } ?: toWhatsAppJid(context, address)+ val db = WhatsAppDatabase.getDatabase(context)+ runCatching {+ db.conversationDao().getConversation(jid)?.let {+ if (it.unreadCount != 0) db.conversationDao().upsert(it.copy(unreadCount = 0))+ }+ }+ val lastInbound = runCatching {+ db.cachedMessageDao().getForConversation(jid).lastOrNull { !it.outgoing }+ }.getOrNull() ?: return@withContext alreadyReadId+ if (lastInbound.messageId == alreadyReadId) return@withContext alreadyReadId+ // For groups the receipt needs the participant; 1:1 goes to the chat JID itself.+ val sender = if (jid.endsWith("@g.us")) lastInbound.senderJid.takeIf { it.isNotBlank() } else null+ runCatching {+ WhatsAppClient.sendReadReceipt(jid, lastInbound.messageId, lastInbound.timestamp / 1000, sender)+ }+ lastInbound.messageId+ }++ /** numeric local part of a JID (strips :device and .agent suffixes). */+ private fun jidLocalPart(jid: String): String =+ jid.substringBefore("@").substringBefore(":").substringBefore(".")++ private fun jidToDisplayAddress(jid: String): String {+ if (jid.endsWith("@g.us")) return jid+ val phone = jidLocalPart(jid)+ return if (phone.isNotEmpty() && phone.all { it.isDigit() }) "+$phone" else phone+ }++ private fun whatsAppDisplayName(context: Context, jid: String, sd: WhatsAppServiceData?): String? {+ if (jid.endsWith("@g.us")) return sd?.senderName // group display name not cached in v1+ val phone = jidLocalPart(jid)+ return findContactName(context, "+$phone") ?: sd?.senderName+ }++ /**+ * Build a 1:1 WhatsApp JID from a phone number / address. WhatsApp JIDs require the FULL+ * international number (country code, no '+'), so a nationally-typed number like "2134774209"+ * must be normalized to "12134774209" — otherwise usync returns 0 devices and the message goes+ * nowhere. Uses libphonenumber with the SIM/locale region to infer the country code.+ */+ private fun toWhatsAppJid(context: Context, address: String): String {+ if (address.contains("@")) return address+ val region = runCatching {+ val tm = context.getSystemService(TelephonyManager::class.java)+ (tm?.simCountryIso?.takeIf { it.isNotBlank() } ?: tm?.networkCountryIso)?.uppercase()+ }.getOrNull()?.takeIf { it.isNotBlank() }+ ?: context.resources.configuration.locales[0].country.ifEmpty { "US" }+ val e164 = runCatching {+ val util = com.google.i18n.phonenumbers.PhoneNumberUtil.getInstance()+ val parsed = util.parse(address, region)+ util.format(parsed, com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat.E164)+ }.getOrNull()+ val normalized = (e164 ?: address).filter { it.isDigit() }+ return "[email protected]"+ }++ /** Insert an outgoing WhatsApp message into the local cache so it shows in our own thread. */+ private suspend fun cacheOutgoingWhatsApp(context: Context, jid: String, body: String) {+ runCatching {+ val db = WhatsAppDatabase.getDatabase(context)+ val now = System.currentTimeMillis()+ db.cachedMessageDao().upsert(+ WhatsAppCachedMessage(+ messageId = "local-${java.util.UUID.randomUUID()}",+ conversationJid = jid,+ body = body,+ timestamp = now,+ outgoing = true,+ ),+ )+ val existing = db.conversationDao().getConversation(jid)+ db.conversationDao().upsert(+ (existing ?: WhatsAppConversation(chatJid = jid)).copy(lastMessageTimestamp = now),+ )+ }+ }+ private fun GvThread.toSmsThread(context: Context): SmsThread = SmsThread( threadId = stableThreadId(id), address = phoneNumber,
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.ktnew file mode 100644index 0000000000..4e883493db--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt@@ -0,0 +1,82 @@+package com.vayunmathur.communicate.data.whatsapp++import android.content.Context+import androidx.core.content.edit+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json as KotlinJson++/**+ * Persistent auth data for the WhatsApp **primary client** (own phone-number registration).+ *+ * Pruned vs. the messages companion port: dropped `advSecretKey`, `accountSignedDeviceIdentity`+ * and `lid` (QR/linked-device only). Extended with the `/v2/register` outputs (`new_jid`,+ * `server_time`, `login` token) needed to bring up the primary Noise session.+ *+ * Persisted under the `communicate_whatsapp_auth` namespace so it never collides with the+ * companion's `whatsapp_auth` in the messages module.+ */+@Serializable+data class WhatsAppAuthData(+ val phoneNumber: String,+ val pushName: String,+ // Primary JID assigned by /v2/register (`new_jid`), e.g. "[email protected]".+ val wid: String,+ // Noise key pair (X25519) — used in every handshake.+ val noisePrivateKey: String, // Base64+ val noisePublicKey: String, // Base64+ // Signal identity key pair (Curve25519) — used for E2E encryption.+ val identityPrivateKey: String, // Base64+ val identityPublicKey: String, // Base64+ // Signal Protocol registration ID.+ val registrationId: Int,+ // Signal signed pre-key.+ val signedPreKeyId: Int,+ val signedPreKeyPublic: String, // Base64+ val signedPreKeyPrivate: String, // Base64+ val signedPreKeySignature: String, // Base64+ // Primary device id is always 0 (the phone itself, not a companion).+ val deviceId: Int = 0,+ // ---- /v2/register outputs ----+ // Server-side login token (`login`) returned by register/security; replayed on subsequent calls.+ val loginToken: String = "",+ // Server clock at registration (`server_time`), seconds.+ val serverTime: Long = 0L,+ // Whether /v2/register returned ok (primary line is live).+ val registered: Boolean = false,+ // Timezone reported to the server on login.+ val timezone: String = "",+ val loggedInAt: Long = 0L,+ val platformType: String = "ANDROID",+ // Vestigial for the primary client (populated only by companion/QR pairing, which we don't use).+ // Kept so the ported message engine compiles; both remain empty for a primary line.+ val lid: String = "",+ val accountSignedDeviceIdentity: String = "",+) {+ companion object {+ // Distinct from the companion's "whatsapp_auth" in the messages module.+ private const val PREFS_NAME = "communicate_whatsapp_auth"+ private const val KEY_AUTH_DATA = "auth_data"++ fun load(context: Context): WhatsAppAuthData? {+ val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ val json = prefs.getString(KEY_AUTH_DATA, null) ?: return null+ return try {+ KotlinJson.decodeFromString<WhatsAppAuthData>(json)+ } catch (e: Exception) {+ null+ }+ }++ fun save(context: Context, authData: WhatsAppAuthData) {+ val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ val json = KotlinJson.encodeToString(authData)+ prefs.edit { putString(KEY_AUTH_DATA, json) }+ }++ fun clear(context: Context) {+ val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ prefs.edit { remove(KEY_AUTH_DATA) }+ }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.ktnew file mode 100644index 0000000000..9ca27a650d--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt@@ -0,0 +1,3324 @@+@file:OptIn(kotlin.concurrent.atomics.ExperimentalAtomicApi::class)++package com.vayunmathur.communicate.data.whatsapp++import kotlin.time.Duration.Companion.seconds+import kotlin.concurrent.atomics.*+import android.app.Application+import android.content.Context+import android.net.ConnectivityManager+import android.net.Network+import android.util.Base64+import android.util.Log+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E+import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket+import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallSignaling+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asSharedFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull+import org.json.JSONObject+import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E.ParsedPreKeyBundle+import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto+import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppAppStateProto+import java.security.SecureRandom+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import androidx.core.content.edit+import androidx.core.graphics.scale+import java.io.ByteArrayOutputStream+import java.util.Collections+import java.util.concurrent.ConcurrentHashMap++object WhatsAppClient {++ private const val TAG = "WhatsAppClient"++ // HistorySync.syncType values (ref whatsmeow HistorySync_HistorySyncType).+ private const val SYNC_INITIAL_BOOTSTRAP = 0+ private const val SYNC_ON_DEMAND = 6++ // Number of older messages to request per on-demand page.+ private const val ON_DEMAND_PAGE_SIZE = 50+ // Safety cap on on-demand pages per chat so a misbehaving peer can't loop forever+ // (ON_DEMAND_PAGE_SIZE * this ≈ upper bound on backfilled messages per chat).+ private const val MAX_ON_DEMAND_PAGES_PER_CHAT = 400++ // When true, on-demand history keeps paginating older messages until the phone reports+ // end-of-history (an empty/anchor-only response). When false, only the recent pushed+ // history is kept (no backfill of "not downloaded" messages).+ @Volatile+ var fullHistorySync: Boolean = true++ sealed interface State {+ data object Idle : State+ data object NeedsSetup : State+ data object Connecting : State+ data object Connected : State+ data class Disconnected(val reason: String) : State+ }++ val source: MessageSource = MessageSource.WHATSAPP++ private val _state = MutableStateFlow<State>(State.Idle)+ val state: StateFlow<State> = _state.asStateFlow()++ private val _events = MutableSharedFlow<WhatsAppEvent>(extraBufferCapacity = 256)+ val events: SharedFlow<WhatsAppEvent> = _events.asSharedFlow()++ private val initialized = AtomicBoolean(false)+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val random = SecureRandom()++ private lateinit var appContext: Application+ private var authData: WhatsAppAuthData? = null+ // Use WebView-based WebSocket to bypass TLS fingerprinting+ // WhatsApp blocks non-browser TLS fingerprints (JA3). WebView uses Chromium's+ // network stack which is indistinguishable from Chrome browser.+ private var webSocket: WhatsAppSocket? = null+ // Collector jobs for the current socket; cancelled on teardown so old (zombie) sockets+ // don't keep running keepalives or trigger reconnects, which causes self-conflicts.+ private var socketCollectorJobs: MutableList<Job> = mutableListOf()+ // Set when the server tells us this session is terminal (conflict/replaced/device removed),+ // so the disconnect handler does not start a pointless reconnect loop.+ private var suppressReconnect = false+ private var db: WhatsAppDatabase? = null+ private var e2e: WhatsAppE2E? = null+ private var backfillJob: Job? = null+ private var qrJob: Job? = null+ private var qrRotateJob: Job? = null++ // Pending IQ request/response correlation (by stanza id) for prekey fetch/upload/count.+ private val pendingIqs = ConcurrentHashMap<String, CompletableDeferred<WhatsAppProtocol.Node>>()++ private val nameCache = ConcurrentHashMap<String, String>()+ private val lidToPhoneMap = ConcurrentHashMap<String, String>()+ private val undecryptableTracker = ConcurrentHashMap<String, Int>()+ private val pendingMessageIDs: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())+ private val processedEditIDs: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())+ // Groups we've already fetched metadata for this session, so we publish the group's+ // ConversationUpdate (name / isGroup / participants) at most once instead of on every event.+ private val knownGroups: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())+ private var reconnectJob: Job? = null+ private var reconnectAttempts = 0+ // True while a connect() attempt is actively setting up / handshaking, so the network-available+ // callback doesn't tear down an in-progress attempt (it fires right after registration).+ private val connectInProgress = AtomicBoolean(false)+ // Watches for the network coming back so we can reconnect immediately instead of waiting out+ // the backoff (or staying dead after a long offline stretch).+ private var connectivityCallback: ConnectivityManager.NetworkCallback? = null+ private val pollSecrets = ConcurrentHashMap<String, ByteArray>()+ // Cached media upload connection (host, auth, expiryEpochMs) from the w:m media_conn IQ.+ private var mediaConnCache: Triple<String, String, Long>? = null++ // Recently sent 1:1 messages (id -> padded plaintext + own-device DSM), kept so we can+ // re-encrypt and resend to a specific device when the peer asks for a retry+ // (<receipt type="retry">). Without this, a message the recipient can't decrypt is acked+ // locally (send "succeeds") but is never actually delivered.+ private data class SentDM(+ val to: String,+ val type: String,+ val msgPlaintextPadded: ByteArray,+ val dsmPlaintextPadded: ByteArray?,+ )+ private val recentSentDMs: MutableMap<String, SentDM> = Collections.synchronizedMap(+ object : LinkedHashMap<String, SentDM>(64, 0.75f, false) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, SentDM>?): Boolean = size > 200+ }+ )+ // Per-(messageId|deviceJid) resend cap so a stuck peer can't loop us forever.+ private val retryResendCounts = ConcurrentHashMap<String, Int>()++ // Whether this account has read receipts enabled (privacy setting). Default true (WhatsApp+ // default); refreshed from the server after <success>. When false we must not send read+ // receipts (the user turned them off).+ @Volatile private var readReceiptsEnabled = true++ private const val INITIAL_RECONNECT_DELAY_MS = 1000L+ private const val MAX_RECONNECT_DELAY_MS = 60_000L+ private const val MAX_FILE_SIZE = 50L * 1024 * 1024++ // Media upload/download run on library:network (HttpURLConnection).+ private val MEDIA_CONNECT_TIMEOUT_MS = 30.seconds.inWholeMilliseconds+ private val MEDIA_READ_TIMEOUT_MS = 60.seconds.inWholeMilliseconds++ fun init(context: Context) {+ if (!initialized.compareAndSet(false, true)) return+ appContext = context.applicationContext as Application+ db = WhatsAppDatabase.getDatabase(appContext)+ Log.i(TAG, "init")+ runBlocking {+ val auth = WhatsAppAuthData.load(appContext)+ if (auth != null) {+ authData = auth+ _state.value = State.Connecting+ registerNetworkMonitor()+ } else {+ _state.value = State.NeedsSetup+ }+ }+ }++ fun start() {+ if (!initialized.load()) return+ // Only skip if fully connected. (Connecting is intentionally NOT skipped: a stale/stuck+ // Connecting state must be able to retry; connect() calls teardownSocket() first so an+ // overlapping attempt can't leave two live sockets.)+ if (_state.value is State.Connected) return+ scope.launch {+ val auth = WhatsAppAuthData.load(appContext) ?: run {+ _state.value = State.NeedsSetup+ return@launch+ }+ authData = auth+ connect(auth)+ }+ }++ fun stop() {+ // Never touch appContext / DAOs before init(); the sync service + MainActivity can call+ // stop() at startup (waSignedIn=false) before the client was ever initialized.+ if (!initialized.load()) return+ Log.i(TAG, "stop — disconnecting WhatsApp session")+ backfillJob?.cancel()+ qrJob?.cancel()+ qrRotateJob?.cancel()+ reconnectJob?.cancel()+ reconnectAttempts = 0+ suppressReconnect = true+ unregisterNetworkMonitor()+ webSocket?.disconnect()+ webSocket = null+ nameCache.clear()+ knownGroups.clear()+ // NOTE: credentials are intentionally NOT cleared here — that would wipe the registration+ // every time the foreground service stops. Sign-out (which clears auth) is owned by+ // WhatsAppLineSession.signOut().+ _state.value = State.NeedsSetup+ }++ /**+ * User-triggered "force resync" (settings button): drop any existing socket and reconnect from+ * scratch, regardless of current state. This is the recovery path when the socket has silently+ * died — resetting attempts and calling connect() (which tears down the old socket first).+ * No-op if there is no saved session.+ */+ fun forceResync() {+ if (!initialized.load()) return+ val auth = authData ?: run {+ WhatsAppDiag.log(TAG, "forceResync: no session, ignoring")+ return+ }+ WhatsAppDiag.log(TAG, "forceResync: forcing full reconnect")+ reconnectAttempts = 0+ reconnectJob?.cancel()+ suppressReconnect = false+ scope.launch {+ try {+ connect(auth)+ } catch (e: Exception) {+ Log.e(TAG, "forceResync connect failed", e)+ scheduleReconnect()+ }+ }+ }++ private fun scheduleReconnect() {+ // Never permanently give up: a companion device must keep retrying so it recovers after a+ // long offline stretch (device asleep, no Wi-Fi/data) without a manual app restart. The+ // backoff is capped, and registerNetworkMonitor() short-circuits the wait when the network+ // actually returns.+ if (suppressReconnect || authData == null) return+ reconnectJob?.cancel()+ reconnectJob = scope.launch {+ // Exponential backoff capped at MAX_RECONNECT_DELAY_MS. Cap the shift too so the left+ // shift can't overflow/wrap once attempts grow large.+ val shift = reconnectAttempts.coerceAtMost(16)+ val delayMs = minOf(INITIAL_RECONNECT_DELAY_MS shl shift, MAX_RECONNECT_DELAY_MS)+ Log.i(TAG, "Reconnecting in ${delayMs}ms (attempt ${reconnectAttempts + 1})")+ _state.value = State.Connecting+ delay(delayMs)+ reconnectAttempts+++ val auth = authData ?: return@launch+ try {+ connect(auth)+ } catch (e: Exception) {+ Log.e(TAG, "Reconnection failed", e)+ scheduleReconnect()+ }+ }+ }++ /**+ * Register a default-network callback so a returning network triggers an immediate reconnect,+ * instead of waiting out the (up to 60s) backoff or staying disconnected indefinitely. Idempotent.+ */+ private fun registerNetworkMonitor() {+ if (connectivityCallback != null) return+ val cm = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return+ val cb = object : ConnectivityManager.NetworkCallback() {+ override fun onAvailable(network: Network) {+ if (authData == null || suppressReconnect) return+ if (_state.value is State.Connected) return+ if (connectInProgress.load()) return+ WhatsAppDiag.log(TAG, "network available — reconnecting now")+ reconnectAttempts = 0+ reconnectJob?.cancel()+ reconnectJob = scope.launch {+ val auth = authData ?: return@launch+ try {+ connect(auth)+ } catch (e: Exception) {+ Log.e(TAG, "reconnect on network-available failed", e)+ scheduleReconnect()+ }+ }+ }+ }+ connectivityCallback = cb+ try {+ cm.registerDefaultNetworkCallback(cb)+ } catch (e: Exception) {+ Log.e(TAG, "registerDefaultNetworkCallback failed", e)+ connectivityCallback = null+ }+ }++ private fun unregisterNetworkMonitor() {+ val cb = connectivityCallback ?: return+ connectivityCallback = null+ try {+ (appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager)+ ?.unregisterNetworkCallback(cb)+ } catch (e: Exception) {+ Log.e(TAG, "unregisterNetworkCallback failed", e)+ }+ }++ /** Compact human-readable summary of a decoded binary-XML node for on-screen diagnostics. */+ private fun nodeSummary(node: WhatsAppProtocol.Node): String {+ val attrs = if (node.attrs.isEmpty()) "" else " " + node.attrs.entries.joinToString(" ") { "${it.key}=${it.value}" }+ val kids = node.getChildren()+ val kidPart = if (kids.isEmpty()) "" else " {" + kids.joinToString(",") { it.tag } + "}"+ return "<${node.tag}$attrs>$kidPart"+ }++ private fun concat(vararg parts: ByteArray): ByteArray {+ val out = ByteArray(parts.sumOf { it.size })+ var off = 0+ for (p in parts) {+ System.arraycopy(p, 0, out, off, p.size)+ off += p.size+ }+ return out+ }++ private fun ensureE2E(auth: WhatsAppAuthData): WhatsAppE2E? {+ val database = db ?: return null+ var inst = e2e+ if (inst == null) {+ inst = WhatsAppE2E(database, auth)+ inst.ensureSignedPreKeyStored()+ e2e = inst+ }+ return inst+ }++ /**+ * Send an <iq> stanza and await its result/error response by id.+ * Returns the response node, or null on timeout.+ */+ private suspend fun sendIqAndWait(node: WhatsAppProtocol.Node, timeoutMs: Long = 30_000): WhatsAppProtocol.Node? {+ val ws = webSocket ?: return null+ val id = node.attrs["id"] ?: return null+ val deferred = CompletableDeferred<WhatsAppProtocol.Node>()+ pendingIqs[id] = deferred+ return try {+ if (!ws.send(WhatsAppProtocol.encodeNode(node))) {+ pendingIqs.remove(id)+ return null+ }+ withTimeoutOrNull(timeoutMs) { deferred.await() }+ } finally {+ pendingIqs.remove(id)+ }+ }++ /**+ * Upload one-time + signed prekeys to the server.+ * Ref whatsmeow prekeys.go uploadPreKeys. [initialUpload] uploads a large batch after pair.+ */+ /**+ * Upload prekeys on connect if the server is likely low. Does an initial large batch+ * when the local prekey store is empty (freshly paired). Ref whatsmeow prekeys.go.+ */+ private suspend fun maybeUploadPreKeys() {+ val database = db ?: return+ val count = try { database.e2ePreKeyDao().getCount() } catch (e: Exception) { return }+ val unuploaded = try { database.e2ePreKeyDao().getUnuploaded().size } catch (e: Exception) { 0 }+ WhatsAppDiag.log(TAG, "prekeys: local count=$count unuploaded=$unuploaded")+ when {+ count == 0 -> uploadPreKeys(initialUpload = true)+ unuploaded > 0 -> uploadPreKeys(initialUpload = false)+ else -> WhatsAppDiag.log(TAG, "prekeys: nothing to upload")+ }+ }++ /**+ * Upload one-time + signed prekeys to the server.+ * Ref whatsmeow prekeys.go uploadPreKeys. [initialUpload] uploads a large batch after pair.+ */+ private suspend fun uploadPreKeys(initialUpload: Boolean) {+ val auth = authData ?: return+ val crypto = ensureE2E(auth) ?: return+ val content = crypto.buildPreKeyUploadContent(initialUpload)+ val iq = WhatsAppProtocol.Node(+ tag = "iq",+ attrs = mapOf(+ "id" to generateMessageId(),+ "type" to "set",+ "xmlns" to "encrypt",+ "to" to "s.whatsapp.net",+ ),+ content = content,+ )+ WhatsAppDiag.log(TAG, "prekeys: uploading (initial=$initialUpload, ${content.size} nodes)…")+ val resp = sendIqAndWait(iq)+ if (resp != null && resp.attrs["type"] != "error") {+ crypto.markPreKeysUploaded()+ WhatsAppDiag.log(TAG, "prekeys: upload OK (initial=$initialUpload)")+ } else {+ WhatsAppDiag.log(TAG, "prekeys: upload FAILED/timeout (resp=${resp?.attrs?.get("type") ?: "null"})")+ }+ }++ /**+ * Fetch a peer's prekey bundle and establish an outbound session if none exists.+ * Ref whatsmeow prekeys.go fetchPreKeys + send.go encryptMessageForDevice.+ */+ private suspend fun ensureSession(jid: String): Boolean {+ val auth = authData ?: return false+ val crypto = ensureE2E(auth) ?: return false+ if (crypto.hasSession(jid)) return true++ val device = jid.substringBefore("@").substringAfter(":", "0").toIntOrNull() ?: 0+ val iq = WhatsAppProtocol.Node(+ tag = "iq",+ attrs = mapOf(+ "id" to generateMessageId(),+ "type" to "get",+ "xmlns" to "encrypt",+ "to" to "s.whatsapp.net",+ ),+ content = listOf(+ WhatsAppProtocol.Node(+ tag = "key",+ content = listOf(+ WhatsAppProtocol.Node(+ tag = "user",+ attrs = mapOf("jid" to jid, "reason" to "identity"),+ )+ ),+ )+ ),+ )+ val resp = sendIqAndWait(iq) ?: return false+ val list = resp.getChildByTag("list") ?: return false+ val userNode = list.getChildren().firstOrNull { it.tag == "user" } ?: return false+ val bundle: ParsedPreKeyBundle = crypto.parsePreKeyBundleNode(device, userNode) ?: return false+ return try {+ crypto.processPreKeyBundle(jid, bundle)+ true+ } catch (e: Exception) {+ Log.e(TAG, "Failed to process prekey bundle for $jid", e)+ false+ }+ }++ /**+ * Resolve the device list for the given (bare) user JIDs via a usync query.+ * Ref whatsmeow user.go GetUserDevices. Returns wire device JIDs ("user@server" for device 0,+ * "user:N@server" otherwise). Returns empty on failure (callers fall back to the bare JID).+ */+ private suspend fun getUserDevices(userJids: List<String>): List<String> {+ if (userJids.isEmpty()) return emptyList()+ val bareUsers = userJids.map { it.substringBefore(":").let { u -> if (u.contains("@")) u else "[email protected]" } }+ val iq = WhatsAppProtocol.buildUsyncDevicesQuery(bareUsers, generateMessageId(), generateMessageId())+ val resp = sendIqAndWait(iq, timeoutMs = 10_000) ?: run {+ WhatsAppDiag.log(TAG, "usync: no response for $bareUsers (timeout)")+ return emptyList()+ }+ val list = resp.getChildByTag("usync")?.getChildByTag("list") ?: run {+ WhatsAppDiag.log(TAG, "usync: malformed response (no list) for $bareUsers")+ return emptyList()+ }+ val devices = mutableListOf<String>()+ list.getChildren().filter { it.tag == "user" }.forEach { user ->+ val userJid = user.attrs["jid"] ?: return@forEach+ val bareUser = userJid.substringBefore("@").substringBefore(":")+ val server = userJid.substringAfter("@", "s.whatsapp.net")+ val deviceList = user.getChildByTag("devices")?.getChildByTag("device-list") ?: return@forEach+ deviceList.getChildren().filter { it.tag == "device" }.forEach { d ->+ if (d.attrs["is_hosted"] == "true") return@forEach+ val devId = d.attrs["id"]?.toIntOrNull() ?: return@forEach+ devices.add(if (devId == 0) "$bareUser@$server" else "$bareUser:$devId@$server")+ }+ }+ WhatsAppDiag.log(TAG, "usync: $bareUsers -> ${devices.size} device(s)")+ return devices+ }++ /**+ * Query a group's participant JIDs via an interactive w:g2 query.+ * Ref whatsmeow group.go getGroupInfo.+ */+ private suspend fun queryGroupParticipants(groupJid: String): List<String> {+ val iq = WhatsAppProtocol.buildGroupParticipantsQuery(groupJid, generateMessageId())+ val resp = sendIqAndWait(iq) ?: return emptyList()+ val group = resp.getChildByTag("group") ?: return emptyList()+ return group.getChildren().filter { it.tag == "participant" }.mapNotNull { it.attrs["jid"] }+ }++ /**+ * Fetch a group's subject + participants (w:g2 interactive query) and publish a+ * [WhatsAppEvent.ConversationUpdate] so the thread shows up named + flagged as a group. Freshly+ * joined groups aren't in history sync, so without this the conversation never appears (and+ * group messages, which only upsert a bare row, look nameless / like a 1:1). Fetched at most+ * once per group per session ([knownGroups]); does NOT touch the unread badge on re-entry.+ * Ref whatsmeow group.go GetGroupInfo.+ */+ private suspend fun fetchAndEmitGroupInfo(groupJid: String) {+ if (!groupJid.contains("@g.us")) return+ if (!knownGroups.add(groupJid)) return+ val iq = WhatsAppProtocol.buildGroupParticipantsQuery(groupJid, generateMessageId())+ val resp = sendIqAndWait(iq) ?: run { knownGroups.remove(groupJid); return }+ val group = resp.getChildByTag("group") ?: run { knownGroups.remove(groupJid); return }+ val subject = group.attrs["subject"]?.ifEmpty { null }+ val participantJids = group.getChildren()+ .filter { it.tag == "participant" }+ .mapNotNull { it.attrs["jid"] }+ val participantNames = participantJids.map { resolveName(it) }+ val serviceData = if (participantNames.isNotEmpty()) {+ org.json.JSONObject()+ .put("participantNames", org.json.JSONArray(participantNames))+ .toString()+ } else null+ _events.emit(WhatsAppEvent.ConversationUpdate(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:$groupJid",+ peerName = subject,+ peerPhone = null,+ avatarUrl = null,+ lastPreview = null,+ lastTimestamp = 0L,+ unreadCount = 0,+ isGroup = true,+ participantCount = participantJids.size,+ serviceData = serviceData,+ ))+ }++ /**+ * Fetch (and cache) the media upload host + auth token via the w:m media_conn IQ.+ * Ref whatsmeow mediaconn.go queryMediaConn. Returns (host, auth) or null.+ */+ private suspend fun mediaConn(): Pair<String, String>? {+ mediaConnCache?.let { if (System.currentTimeMillis() < it.third) return it.first to it.second }+ val iq = WhatsAppProtocol.buildMediaConnQuery(generateMessageId())+ val resp = sendIqAndWait(iq) ?: return null+ val mc = resp.getChildByTag("media_conn") ?: return null+ val auth = mc.attrs["auth"] ?: return null+ val ttl = mc.attrs["ttl"]?.toLongOrNull() ?: 300L+ val host = mc.getChildren().firstOrNull { it.tag == "host" }?.attrs?.get("hostname") ?: return null+ mediaConnCache = Triple(host, auth, System.currentTimeMillis() + ttl * 1000)+ return host to auth+ }++ /**+ * Establish sessions and Signal-encrypt a (padded) plaintext for each device, skipping our own+ * current device. Own other devices get [dsmPlaintextPadded] (the DeviceSentMessage); everyone+ * else gets [msgPlaintextPadded]. Mirrors whatsmeow send.go encryptMessageForDevices.+ */+ private suspend fun encryptForDevices(+ crypto: WhatsAppE2E,+ devices: List<String>,+ ownUser: String,+ ownDeviceJid: String,+ msgPlaintextPadded: ByteArray,+ dsmPlaintextPadded: ByteArray?,+ ): Pair<List<WhatsAppProtocol.ParticipantEnc>, Boolean> {+ val encs = mutableListOf<WhatsAppProtocol.ParticipantEnc>()+ var includeIdentity = false+ // Our own device number (from wid "user.agent:device@..."). usync returns devices as+ // "user:device@..." (no agent), so comparing against the raw wid never matches and we'd+ // fan out to OURSELVES — which the server rejects with <conflict type=device_removed>.+ val ownDeviceNum = ownDeviceJid.substringBefore("@").substringAfter(":", "0").toIntOrNull() ?: 0+ for (dev in devices.distinct()) {+ val devUser = dev.substringBefore("@").substringBefore(":").substringBefore(".")+ val devNum = dev.substringBefore("@").substringAfter(":", "0").toIntOrNull() ?: 0+ if (devUser == ownUser && devNum == ownDeviceNum) continue // skip our own device+ val plaintext = if (devUser == ownUser && dsmPlaintextPadded != null) dsmPlaintextPadded else msgPlaintextPadded+ if (!ensureSession(dev)) {+ Log.w(TAG, "No session for device $dev; skipping in fan-out")+ continue+ }+ val enc = try {+ crypto.encryptDM(dev, plaintext)+ } catch (e: Exception) {+ Log.w(TAG, "Encrypt failed for device $dev", e)+ continue+ }+ if (enc.type == "pkmsg") includeIdentity = true+ encs.add(WhatsAppProtocol.ParticipantEnc(dev, enc.type, enc.data))+ }+ return encs to includeIdentity+ }++ /** Cancel the current socket's collectors and disconnect it, so only one socket is ever live. */+ private fun teardownSocket() {+ socketCollectorJobs.forEach { it.cancel() }+ socketCollectorJobs.clear()+ webSocket?.disconnect()+ webSocket = null+ }++ private suspend fun connect(auth: WhatsAppAuthData) {+ _state.value = State.Connecting+ suppressReconnect = false+ connectInProgress.store(true)+ registerNetworkMonitor()+ // Ensure no previous socket (provisioning or a prior login attempt) is still alive,+ // otherwise overlapping sessions make the server reject us with <stream:error><conflict>.+ teardownSocket()++ // Use WebView-based WebSocket to bypass TLS fingerprinting+ val ws = WhatsAppSocket(auth)+ webSocket = ws+ socketCollectorJobs.add(+ scope.launch {+ ws.connectionState.collect { state ->+ when (state) {+ is WhatsAppSocket.ConnectionState.Connected -> {+ WhatsAppDiag.log(TAG, "login socket: Noise connected, awaiting <success>")+ connectInProgress.store(false)+ ensureE2E(auth)+ }+ is WhatsAppSocket.ConnectionState.Disconnected -> {+ WhatsAppDiag.log(TAG, "login socket: Disconnected (${state.reason})")+ connectInProgress.store(false)+ if (authData != null && !suppressReconnect) {+ scheduleReconnect()+ } else {+ _state.value = State.Disconnected(state.reason)+ }+ }+ else -> {}+ }+ }+ }+ )+ socketCollectorJobs.add(+ scope.launch {+ ws.messages.collect { data ->+ handleIncomingMessage(data)+ }+ }+ )+ ws.connect()+ }++ private fun handleIncomingMessage(data: ByteArray) {+ scope.launch {+ try {+ val node = WhatsAppProtocol.decodeNode(data)+ WhatsAppDiag.log(TAG, "← login stanza ${nodeSummary(node)}")++ // Server ack for an outbound stanza. An ack with an `error` attr means the server+ // REJECTED the message (it will never be delivered) — surface it prominently so a+ // "sent but not delivered" report can be diagnosed from logs.+ if (node.tag == "ack") {+ val ackErr = node.attrs["error"]+ if (ackErr != null) {+ WhatsAppDiag.log(TAG, "← ack REJECTED class=${node.attrs["class"]} id=${node.attrs["id"]} error=$ackErr")+ }+ }++ // Ack messages, notifications, receipts AND calls (whatsmeow/receipt.go ++ // call.go). Calls MUST be acked too: during the post-login offline flush the server+ // is flow-controlled and head-of-line — if the offline <call> offers aren't acked it+ // stops delivering, so queued <message> stanzas never arrive ("stuck syncing").+ if (node.tag == "message" || node.tag == "notification" ||+ node.tag == "receipt" || node.tag == "call"+ ) {+ val ack = WhatsAppProtocol.buildAck(+ nodeClass = node.tag,+ nodeId = node.attrs["id"] ?: "",+ from = node.attrs["from"] ?: "",+ participant = node.attrs["participant"],+ recipient = node.attrs["recipient"],+ type = if (node.tag != "message") node.attrs["type"] else null,+ )+ webSocket?.send(WhatsAppProtocol.encodeNode(ack))+ }++ // Complete any pending IQ request awaiting this response (prekey fetch/upload).+ if (node.tag == "iq") {+ val iqId = node.attrs["id"]+ val pending = if (iqId != null) pendingIqs.remove(iqId) else null+ if (pending != null) {+ pending.complete(node)+ return@launch+ }+ }++ // Handle connection failure events (Go handleWALogout, ClientOutdated, TemporaryBan)+ if (node.tag == "failure") {+ val reason = node.attrs["reason"] ?: "unknown"+ WhatsAppDiag.log(TAG, "login <failure> reason=$reason full=${nodeSummary(node)}")+ when (reason) {+ "401" -> {+ _state.value = State.Disconnected("Logged out from WhatsApp")+ scope.launch { WhatsAppAuthData.clear(appContext) }+ authData = null+ }+ "405" -> _state.value = State.Disconnected("Client outdated — update required")+ "503" -> _state.value = State.Disconnected("Temporarily banned")+ else -> _state.value = State.Disconnected("Connection failed: $reason")+ }+ return@launch+ }++ if (node.tag == "stream:error") {+ val errorNode = node.content.firstOrNull()+ val code = node.attrs["code"]+ val conflict = node.getChildByTag("conflict")+ val conflictType = conflict?.attrs?.get("type")+ WhatsAppDiag.log(TAG, "login stream:error code=$code child=${errorNode?.tag} conflictType=$conflictType")+ when {+ // Device removed from the account on the phone, or another session took over.+ conflict != null || code == "401" -> {+ suppressReconnect = true+ if (conflictType == "device_removed" || code == "401") {+ WhatsAppDiag.log(TAG, "device removed/logged out — clearing credentials")+ scope.launch { WhatsAppAuthData.clear(appContext) }+ authData = null+ _state.value = State.NeedsSetup+ scope.launch { _events.emit(WhatsAppEvent.SourceLoggedOut(source)) }+ } else {+ // "replaced" or other conflict: another WhatsApp session is active.+ _state.value = State.Disconnected("Session replaced by another device")+ }+ }+ // 515 = restart required (normal after first pair-login); allow reconnect.+ code == "515" -> _state.value = State.Disconnected("Restart required")+ else -> _state.value = State.Disconnected("Stream error${if (code != null) " $code" else ""}")+ }+ return@launch+ }++ // Handle the server <success> stanza — the real authentication signal+ // (Go connectionevents.go handleConnectSuccess). Until this arrives the Noise+ // transport is up but the login is not yet authenticated.+ if (node.tag == "success") {+ handleConnectSuccess(node)+ return@launch+ }++ // Handle receipts with per-sender batching (Go handleWAReceipt)+ if (node.tag == "receipt") {+ handleReceipt(node)+ return@launch+ }++ // Handle chat presence with media type differentiation (Go handleWAChatPresence)+ if (node.tag == "chatstate") {+ handleChatPresence(node)+ return@launch+ }++ // Handle notifications (group changes, mute/pin/archive)+ if (node.tag == "notification") {+ handleNotification(node)+ return@launch+ }++ // <ib> info blocks: respond to <dirty> with <clean> so the phone finishes "syncing".+ if (node.tag == "ib") {+ node.getChildByTag("dirty")?.let { handleDirty(it) }+ node.getChildByTag("offline_preview")?.let {+ WhatsAppDiag.log(TAG, "offline preview: count=${it.attrs["count"]} msg=${it.attrs["message"]} notif=${it.attrs["notification"]} receipt=${it.attrs["receipt"]}")+ }+ node.getChildByTag("offline")?.let {+ WhatsAppDiag.log(TAG, "offline sync completed: count=${it.attrs["count"]}")+ }+ return@launch+ }++ if (node.tag != "message") return@launch++ // Check for undecryptable messages (Go handleWAUndecryptableMessage)+ val encNode = node.getChildByTag("enc")+ if (encNode?.data == null && node.attrs["type"] == "text") {+ // No ciphertext at all (a decrypt-fail placeholder). Track it AND ask the+ // sender to re-encrypt, otherwise this first-of-session message is lost for+ // good. sendRetryReceipt is self-capped at 5 attempts.+ trackUndecryptable(node)+ sendRetryReceipt(node)+ return@launch+ }++ val crypto = authData?.let { ensureE2E(it) }+ var decryptFailed = false+ val message = WhatsAppProtocol.parseMessage(node) { senderJid, encType, data ->+ if (crypto == null) {+ decryptFailed = true+ return@parseMessage null+ }+ val result = try {+ when (encType) {+ "pkmsg" -> crypto.decryptDM(senderJid, isPreKey = true, ciphertext = data)+ "msg" -> crypto.decryptDM(senderJid, isPreKey = false, ciphertext = data)+ "skmsg" -> crypto.decryptGroup(node.attrs["from"] ?: "", senderJid, data)+ else -> null+ }+ } catch (e: Exception) {+ Log.e(TAG, "E2E decrypt failed ($encType) from $senderJid", e)+ null+ }+ if (result == null) decryptFailed = true+ result+ } ?: return@launch++ // Decrypt failure: ask the sender to re-encrypt (Go decryptMessages -> sendRetryReceipt).+ if (decryptFailed) {+ val encTypes = node.getChildren()+ .filter { it.tag == "enc" }+ .mapNotNull { it.attrs["type"] }+ WhatsAppDiag.log(TAG, "recv: DECRYPT FAILED id=${node.attrs["id"]} type=${node.attrs["type"]} from=${node.attrs["from"]} encs=$encTypes")+ sendRetryReceipt(node)+ return@launch+ }++ if (node.attrs["type"] == "poll" || WhatsAppProtocol.pollCreation(message.e2eMessage) != null ||+ message.e2eMessage?.hasPollUpdateMessage() == true+ ) {+ WhatsAppDiag.log(+ TAG,+ "poll recv: id=${message.id} parsedType=${message.messageType} " ++ "create=${WhatsAppProtocol.pollCreation(message.e2eMessage) != null} " ++ "vote=${message.e2eMessage?.hasPollUpdateMessage()} " ++ "q=${message.pollData?.question} opts=${message.pollData?.options?.size} " ++ "fromMe=${message.isFromMe}",+ )+ }++ // History sync: the phone pushes message history as a protocolMessage notification+ // (inline for the initial bootstrap, or a downloadable encrypted blob otherwise).+ val histNotif = message.e2eMessage+ ?.takeIf { it.hasProtocolMessage() && it.protocolMessage.hasHistorySyncNotification() }+ ?.protocolMessage?.historySyncNotification+ if (histNotif != null) {+ scope.launch { handleHistorySync(histNotif, message.id) }+ return@launch+ }++ // App-state sync keys, shared by our primary as a peer protocolMessage.+ val keyShare = message.e2eMessage+ ?.takeIf { it.hasProtocolMessage() && it.protocolMessage.hasAppStateSyncKeyShare() }+ ?.protocolMessage?.appStateSyncKeyShare+ if (keyShare != null) {+ scope.launch { handleAppStateKeyShare(keyShare) }+ return@launch+ }++ // Process inbound sender-key distribution so future group skmsg decrypt.+ // UNVERIFIED: group sender-key wire mapping not runtime-tested.+ val skdm = message.e2eMessage?.takeIf { it.hasSenderKeyDistributionMessage() }+ ?.senderKeyDistributionMessage+ if (skdm != null && crypto != null) {+ try {+ crypto.processSenderKeyDistribution(+ message.from,+ message.participant ?: message.from,+ skdm.axolotlSenderKeyDistributionMessage.toByteArray(),+ )+ } catch (e: Exception) {+ Log.w(TAG, "Failed to process SKDM", e)+ }+ // A SKDM-only message carries no user-visible content (types as "ignore"); once+ // the key is stored there's nothing to display, so stop before emitting a blank+ // bubble. Messages that bundle the SKDM with real content fall through to render.+ if (message.messageType == "ignore") return@launch+ }++ // Skip status broadcasts (Go handleWAMessage status@broadcast check)+ if (message.from.startsWith("status@broadcast")) {+ Log.d(TAG, "Skipping status broadcast from ${message.participant}")+ return@launch+ }++ // Pending message dedup (Go handleWAMessage pendingMessages check)+ if (pendingMessageIDs.remove(message.id)) {+ Log.d(TAG, "Ignoring pending message ${message.id}")+ return@launch+ }++ // LID routing (Go rerouteWAMessage)+ val sender = resolveJID(message.participant ?: message.from)++ // Treat the message as ours when it was sent by our own account from another+ // device — either flagged during parse (DeviceSentMessage / recipient attr) or the+ // sender JID resolves to our own user (the common group case: from=group,+ // participant=ourJid). Otherwise it wrongly renders as an incoming bubble "from"+ // ourselves.+ val fromMe = message.isFromMe || isOwnJid(sender) ||+ isOwnJid(message.participant ?: message.from)++ // Cache push name from notify attr (Go syncGhost / PushName handling)+ val notifyName = node.attrs["notify"]+ if (!notifyName.isNullOrEmpty()) {+ nameCache[sender] = notifyName+ }++ // Handle revoke (message deletion) from Go handleWAMessage/revoke case+ if (message.isRevoke && message.revokeTargetId != null) {+ _events.emit(WhatsAppEvent.MessageDeleted(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:${message.from}",+ messageId = message.revokeTargetId,+ timestamp = message.timestamp * 1000,+ ))+ return@launch+ }++ // Handle edit from Go handleWAMessage/edit case+ if (message.isEdit && message.editTargetId != null) {+ // Edit dedup (Go events.go ConvertEdit meta.Edits check)+ if (!processedEditIDs.add(message.id)) {+ Log.d(TAG, "Ignoring duplicate edit ${message.id}")+ return@launch+ }+ _events.emit(WhatsAppEvent.MessageEdited(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:${message.from}",+ messageId = message.editTargetId,+ newBody = message.body,+ timestamp = message.timestamp * 1000,+ ))+ return@launch+ }++ // Handle disappearing timer change (Go handleWAMessage/ephemeral case)+ if (message.disappearingTimer != null) {+ _events.emit(WhatsAppEvent.IncomingMessage(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:${message.from}",+ messageId = message.id,+ body = message.body,+ peerName = resolveName(sender),+ peerPhone = null,+ timestamp = message.timestamp * 1000,+ ))+ return@launch+ }++ // Handle poll creation — store option hashes (Go handleWAMessage/poll case)+ if (message.pollData != null && !message.pollData.isPollVote) {+ storePollOptions(message.id, message.pollData.options)+ }++ // Prepend forwarded indicator (Go from-whatsapp.go addForwardedFlag)+ val displayBody = buildString {+ if (message.isViewOnce) append("\u26A0\uFE0F View once: ")+ if (message.isHD) append("[HD] ")+ if (message.isForwarded) {+ append("↷ Forwarded\n")+ }+ append(message.body)+ }.let { resolveMentionsInBody(it, message.mentionedJids) }++ // Store poll secrets from incoming polls for vote encryption/decryption.+ if (message.pollData != null && !message.pollData.isPollVote && message.e2eMessage != null) {+ val secret = message.e2eMessage.messageContextInfo?.messageSecret?.toByteArray()+ if (secret != null) storePollSecret(message.id, secret)+ }++ // Handle incoming poll votes (PollUpdateMessage): decrypt the selected option+ // hashes, map them back to names, and emit a tally update. Ref whatsmeow+ // DecryptPollVote.+ if (message.e2eMessage?.hasPollUpdateMessage() == true) {+ val update = message.e2eMessage.pollUpdateMessage+ val key = update.pollCreationMessageKey+ val pollId = key.id+ val voter = if (fromMe) (authData?.wid ?: "") else sender+ val creator = when {+ key.fromMe -> voter+ key.participant.isNotEmpty() -> key.participant+ else -> key.remoteJid+ }+ val secret = loadPollSecret(pollId)+ if (secret != null) {+ val hashes = WhatsAppProtocol.decryptPollVote(update, pollId, creator, voter, secret)+ if (hashes != null) {+ val dao = db?.pollOptionDao()+ val names = hashes.mapNotNull { h ->+ val hex = h.joinToString("") { "%02x".format(it) }+ dao?.getByHash(pollId, hex)?.optionName+ }+ _events.emit(WhatsAppEvent.PollVote(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:${message.from}",+ pollMessageId = pollId,+ voterId = if (fromMe) "self" else sender,+ optionNames = names,+ ))+ }+ }+ return@launch+ }++ // Handle reactions separately (Go handleWAMessage reaction case)+ if (message.e2eMessage?.hasReactionMessage() == true) {+ val reaction = message.e2eMessage.reactionMessage+ val emoji = reaction.text?.replace("\uFE0F", "") ?: ""+ val targetId = reaction.key?.id ?: ""+ // A reaction the user made on another device echoes back as fromMe;+ // tag its sender "self" so it isn't misattributed to the chat peer.+ val reactorId = if (fromMe) "self" else sender+ if (emoji.isEmpty()) {+ _events.emit(WhatsAppEvent.ReactionRemoved(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:${message.from}",+ messageId = targetId,+ senderId = reactorId,+ ))+ } else {+ _events.emit(WhatsAppEvent.ReactionReceived(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:${message.from}",+ messageId = targetId,+ senderId = reactorId,+ emoji = emoji,+ ))+ }+ return@launch+ }++ // For group chats, make sure the conversation exists (named + flagged as a+ // group) before we store the message — a freshly joined group isn't in history+ // sync, so otherwise it would only ever be a nameless bare row. Deduped ++ // awaited so the metadata lands before the message's unread bump.+ if (message.from.contains("@g.us")) {+ fetchAndEmitGroupInfo(message.from)+ }++ // Download + decrypt any inline media so it renders in-thread instead of as a+ // bare "[Image]"/"[Video]" placeholder. Null for non-media or on failure.+ val mediaAttachment = message.e2eMessage?.let {+ buildIncomingMediaAttachment(it, message.id)+ }+ val mediaAttachments = listOfNotNull(mediaAttachment)++ // Messages the user sent from another linked device (fromMe) are synced+ // to us as outgoing, not incoming — emit a MessageUpdate so they render on+ // the sent side instead of as an incoming (previously blank) bubble.+ if (fromMe) {+ _events.emit(WhatsAppEvent.MessageUpdate(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:${message.from}",+ messageId = message.id,+ body = displayBody,+ outgoing = true,+ timestamp = message.timestamp * 1000,+ senderName = null,+ attachments = mediaAttachments,+ ))+ return@launch+ }++ // In group chats, attribute the message to the actual participant so+ // the UI can show who sent each bubble. `sender` is the participant JID+ // (resolveJID(participant ?: from)); for 1:1 chats it's the peer, so we+ // leave sender fields null and fall back to the conversation peer.+ val isGroupChat = message.from.contains("@g.us")+ _events.emit(WhatsAppEvent.IncomingMessage(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:${message.from}",+ messageId = message.id,+ body = displayBody,+ peerName = resolveName(sender),+ peerPhone = null,+ timestamp = message.timestamp * 1000,+ senderName = if (isGroupChat) resolveName(sender) else null,+ senderId = if (isGroupChat) sender else null,+ attachments = mediaAttachments,+ pollQuestion = message.pollData?.takeIf { !it.isPollVote }?.question,+ pollOptions = message.pollData?.takeIf { !it.isPollVote }?.options ?: emptyList(),+ ))++ // Send delivery receipt+ val receiptAttrs = mutableMapOf(+ "id" to message.id,+ "to" to message.from+ )+ node.attrs["participant"]?.let { receiptAttrs["participant"] = it }+ node.attrs["recipient"]?.let { receiptAttrs["recipient"] = it }+ val receipt = WhatsAppProtocol.Node(tag = "receipt", attrs = receiptAttrs)+ webSocket?.send(WhatsAppProtocol.encodeNode(receipt))++ } catch (e: Exception) {+ Log.e(TAG, "Failed to handle incoming message", e)+ }+ }+ }++ /**+ * Handle identity change notification (security code change).+ * From Go handleWAIdentityChange.+ */+ private suspend fun handleIdentityChange(node: WhatsAppProtocol.Node, from: String) {+ val identityNode = node.getChildByTag("identity")+ if (identityNode != null) {+ val jid = node.attrs["participant"] ?: from+ val ts = node.attrs["t"]?.toLongOrNull() ?: (System.currentTimeMillis() / 1000)+ Log.i(TAG, "Identity/security code changed for $jid")+ _events.emit(WhatsAppEvent.IncomingMessage(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:$from",+ messageId = "idchange-$from-$jid-$ts",+ body = "\uD83D\uDD12 Security code changed for ${resolveName(jid)}",+ peerName = resolveName(jid),+ peerPhone = null,+ timestamp = ts * 1000,+ ))+ }+ }++ /**+ * Handle picture update notification (avatar changes).+ * From Go handleWAPictureUpdate.+ */+ private suspend fun handlePictureUpdate(node: WhatsAppProtocol.Node, from: String) {+ val pictureNode = node.getChildByTag("set") ?: node.getChildByTag("delete")+ if (pictureNode != null) {+ val isRemoved = pictureNode.tag == "delete"+ Log.d(TAG, "Picture ${if (isRemoved) "removed" else "updated"} for $from")+ }+ }++ /**+ * Handle account sync notification (push name updates).+ * From Go PushNameSetting / PushName events.+ */+ private suspend fun handleAccountSync(node: WhatsAppProtocol.Node) {+ node.content.filterIsInstance<WhatsAppProtocol.Node>().forEach { child ->+ when (child.tag) {+ "push" -> {+ val pushName = child.attrs["name"]+ val jid = child.attrs["jid"] ?: node.attrs["from"]+ if (pushName != null && jid != null) {+ nameCache[jid] = pushName+ Log.d(TAG, "Push name updated: $jid -> $pushName")+ }+ }+ "contact" -> {+ val contactName = child.attrs["name"]+ val jid = child.attrs["jid"] ?: node.attrs["from"]+ if (contactName != null && jid != null) {+ nameCache[jid] = contactName+ }+ }+ }+ }+ }++ /**+ * Handle receipt with per-sender batching for group chats.+ * From Go handleWAReceipt — groups messages by sender.+ */+ private suspend fun handleReceipt(node: WhatsAppProtocol.Node) {+ val receiptType = node.attrs["type"]+ // The peer couldn't decrypt a message we sent and wants it re-encrypted. This is the+ // outbound counterpart of sendRetryReceipt and is required for delivery to actually+ // happen when a session is desynced.+ if (receiptType == "retry") {+ handleRetryReceipt(node)+ return+ }+ val isRead = receiptType == "read" || receiptType == "read-self"+ val isDelivered = receiptType == null || receiptType.isEmpty()+ if (!isRead && !isDelivered) return++ // Log delivery receipts (Go handleWAReceipt ReceiptTypeDelivered)+ if (isDelivered) {+ Log.d(TAG, "Delivery receipt from ${node.attrs["from"]} for ${node.attrs["id"]}")+ return+ }++ val from = node.attrs["from"] ?: return+ val participant = node.attrs["participant"]++ // Reroute LID sender+ val sender = resolveJID(participant ?: from)++ val messageId = node.attrs["id"] ?: return+ val timestamp = (node.attrs["t"]?.toLongOrNull() ?: System.currentTimeMillis() / 1000) * 1000++ _events.emit(WhatsAppEvent.ReadReceipt(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:$from",+ messageId = messageId,+ timestamp = timestamp,+ ))++ // Handle additional message IDs in list node+ val listNode = node.getChildByTag("list")+ listNode?.content?.filterIsInstance<WhatsAppProtocol.Node>()?.forEach { item ->+ val itemId = item.attrs["id"] ?: return@forEach+ _events.emit(WhatsAppEvent.ReadReceipt(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:$from",+ messageId = itemId,+ timestamp = timestamp,+ ))+ }+ }++ /**+ * Handle chat presence with media type differentiation.+ * From Go handleWAChatPresence — differentiates text/audio/media typing.+ */+ private suspend fun handleChatPresence(node: WhatsAppProtocol.Node) {+ val from = node.attrs["from"] ?: return+ val participant = node.attrs["participant"]+ val sender = resolveJID(participant ?: from)++ val composingNode = node.getChildByTag("composing")+ val pausedNode = node.getChildByTag("paused")++ val isTyping = composingNode != null+ val mediaAttr = composingNode?.attrs?.get("media")++ _events.emit(WhatsAppEvent.TypingIndicator(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:$from",+ senderId = sender,+ isTyping = isTyping,+ ))+ }++ /**+ * Handle notification events (group changes, mute, pin, archive).+ * From Go handleWAGroupInfoChange, handleWAMute, handleWAArchive, handleWAPin.+ */+ private suspend fun handleNotification(node: WhatsAppProtocol.Node) {+ val notifType = node.attrs["type"] ?: return+ val from = node.attrs["from"] ?: return++ when (notifType) {+ "w:gp2" -> handleGroupNotification(node, from)+ "server_sync" -> handleServerSync(node, from)+ "call" -> handleCallNotification(node, from)+ "encrypt" -> handleIdentityChange(node, from)+ "picture" -> handlePictureUpdate(node, from)+ "account_sync" -> handleAccountSync(node)+ "devices" -> {} // Device list update — Go ignores silently+ "mediaretry" -> {} // Media retry — Go handles but requires bridge infra+ }+ }++ /**+ * Handle group info change notifications.+ * From Go handleWAGroupInfoChange.+ */+ private suspend fun handleGroupNotification(node: WhatsAppProtocol.Node, groupJid: String) {+ val timestamp = (node.attrs["t"]?.toLongOrNull() ?: System.currentTimeMillis() / 1000) * 1000+ val actor = resolveName(node.attrs["participant"] ?: groupJid)+ val msgId = node.attrs["id"] ?: ""++ // Any group notification (being added, subject/participant changes, …) implies the+ // group should exist locally. Fetch + publish its metadata so the conversation appears+ // named and flagged as a group even when we were just added and have no history for it.+ fetchAndEmitGroupInfo(groupJid)++ node.content.filterIsInstance<WhatsAppProtocol.Node>().forEach { child ->+ val body = when (child.tag) {+ "subject" -> {+ val newName = child.attrs["subject"] ?: child.data?.let { String(it, Charsets.UTF_8) } ?: return@forEach+ "[Group name changed to: $newName]"+ }+ "description" -> {+ val newDesc = child.data?.let { String(it, Charsets.UTF_8) } ?: ""+ "[Group description changed: $newDesc]"+ }+ "add", "remove", "promote", "demote" -> {+ val participants = child.content.filterIsInstance<WhatsAppProtocol.Node>()+ .mapNotNull { it.attrs["jid"] }+ "[Group: ${participants.joinToString()} ${child.tag}ed]"+ }+ // Go wrapGroupInfoChange: ephemeral setting+ "ephemeral" -> {+ val expiration = child.attrs["expiration"]?.toLongOrNull() ?: 0+ if (expiration > 0) {+ val duration = when {+ expiration >= 86400 * 7 -> "${expiration / (86400 * 7)} week(s)"+ expiration >= 86400 -> "${expiration / 86400} day(s)"+ expiration >= 3600 -> "${expiration / 3600} hour(s)"+ else -> "$expiration seconds"+ }+ "[Disappearing messages set to $duration]"+ } else {+ "[Disappearing messages turned off]"+ }+ }+ // Go wrapGroupInfoChange: announce mode+ "announce" -> {+ val isAnnounce = child.attrs["announce"] == "true" || child.attrs["value"] == "on"+ if (isAnnounce) "[Only admins can send messages now]"+ else "[All participants can send messages now]"+ }+ // Go wrapGroupInfoChange: locked (restrict edit to admins)+ "locked" -> {+ val isLocked = child.attrs["locked"] == "true" || child.attrs["value"] == "on"+ if (isLocked) "[Only admins can edit group info now]"+ else "[All participants can edit group info now]"+ }+ // Go wrapGroupInfoChange: link/unlink community+ "link" -> {+ val linkedGroup = child.attrs["link_type"]+ "[Group linked: $linkedGroup]"+ }+ "unlink" -> {+ val unlinkedGroup = child.attrs["unlink_type"]+ "[Group unlinked: $unlinkedGroup]"+ }+ else -> null+ }++ if (body != null) {+ _events.emit(WhatsAppEvent.IncomingMessage(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:$groupJid",+ messageId = msgId,+ body = body,+ peerName = actor,+ peerPhone = null,+ timestamp = timestamp,+ ))+ }+ }+ }++ /**+ * Handle server sync notifications (mute, pin, archive).+ * From Go handleWAMute, handleWAArchive, handleWAPin.+ */+ /**+ * Respond to a server <dirty> info block with <clean> (MarkNotDirty) so the primary phone+ * stops showing "syncing / keep WhatsApp open". Ref whatsmeow appstate.go MarkNotDirty.+ * <iq to=s.whatsapp.net type=set xmlns=urn:xmpp:whatsapp:dirty><clean type=.. timestamp=../></iq>+ */+ private suspend fun handleDirty(dirty: WhatsAppProtocol.Node) {+ val type = dirty.attrs["type"] ?: return+ val ts = dirty.attrs["timestamp"]+ // account_sync dirty is cleared automatically by the server once we've synced; whatsmeow+ // only explicitly cleans non-account_sync types, but cleaning is harmless and idempotent.+ val cleanAttrs = mutableMapOf("type" to type)+ if (ts != null) cleanAttrs["timestamp"] = ts+ val iq = WhatsAppProtocol.Node(+ tag = "iq",+ attrs = mapOf(+ "id" to generateMessageId(), "type" to "set",+ "xmlns" to "urn:xmpp:whatsapp:dirty", "to" to "s.whatsapp.net",+ ),+ content = listOf(WhatsAppProtocol.Node(tag = "clean", attrs = cleanAttrs)),+ )+ webSocket?.send(WhatsAppProtocol.encodeNode(iq))+ WhatsAppDiag.log(TAG, "cleaned dirty state: $type")+ }++ private suspend fun handleServerSync(node: WhatsAppProtocol.Node, from: String) {+ node.getChildren().filter { it.tag == "collection" }.forEach { coll ->+ val name = coll.attrs["name"] ?: return@forEach+ if (name in APP_STATE_COLLECTIONS) {+ scope.launch { fetchAppStateCollection(name, fullSync = appStateVersion(name) == 0L) }+ }+ }+ }++ /**+ * Handle incoming call notification.+ * From Go handleWACallStart.+ */+ private suspend fun handleCallNotification(node: WhatsAppProtocol.Node, from: String) {+ val offer = node.getChildByTag("offer")+ if (offer != null) {+ // Go handleWACallStart: ignore calls older than 15 minutes+ val callTimestamp = node.attrs["t"]?.toLongOrNull() ?: (System.currentTimeMillis() / 1000)+ val ageSeconds = (System.currentTimeMillis() / 1000) - callTimestamp+ if (ageSeconds > 15 * 60) {+ Log.d(TAG, "Ignoring old call notification (${ageSeconds}s old)")+ return+ }++ val caller = node.attrs["participant"] ?: from+ val callId = node.attrs["id"] ?: ""+ val callType = offer.attrs["call-type"] ?: "voice"+ val callLabel = when {+ callType.contains("video") -> "video call"+ callType.contains("group") -> "group call"+ else -> "voice call"+ }+ _events.emit(WhatsAppEvent.IncomingMessage(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:$from",+ messageId = "call-$callId",+ body = "\u260E Incoming $callLabel",+ peerName = resolveName(caller),+ peerPhone = null,+ timestamp = callTimestamp * 1000,+ ))+ }+ }++ /**+ * Handle app state patch mutations (mute, pin, archive, unread).+ * From Go handleWAMute / handleWAArchive / handleWAPin / handleWAMarkChatAsRead.+ */+ // App-state collections to sync (ref whatsmeow appstate AllPatchNames).+ private val APP_STATE_COLLECTIONS = listOf(+ "critical_block", "critical_unblock_low", "regular_high", "regular", "regular_low",+ )+ private val appStateCollectionsFetching = java.util.Collections.synchronizedSet(HashSet<String>())+ private val appStatePrefs by lazy {+ appContext.getSharedPreferences("wa_appstate", android.content.Context.MODE_PRIVATE)+ }++ private fun appStateKeyId64(keyId: ByteArray) = Base64.encodeToString(keyId, Base64.NO_WRAP)+ private fun storeAppStateKey(keyId: ByteArray, keyData: ByteArray) {+ appStatePrefs.edit { putString("key_${appStateKeyId64(keyId)}", Base64.encodeToString(keyData, Base64.NO_WRAP)) }+ }+ private fun getAppStateKey(keyId: ByteArray): ByteArray? {+ val s = appStatePrefs.getString("key_${appStateKeyId64(keyId)}", null) ?: return null+ return try { Base64.decode(s, Base64.NO_WRAP) } catch (e: Exception) { null }+ }+ private fun appStateVersion(name: String): Long = appStatePrefs.getLong("ver_$name", 0L)+ private fun setAppStateVersion(name: String, v: Long) { appStatePrefs.edit { putLong("ver_$name", v) } }++ /** Store app-state sync keys shared by our primary, then fetch all collections. */+ private suspend fun handleAppStateKeyShare(share: WhatsAppE2EProto.AppStateSyncKeyShare) {+ var stored = 0+ for (k in share.keysList) {+ val id = k.keyId.keyId.toByteArray()+ val data = k.keyData.keyData.toByteArray()+ if (id.isNotEmpty() && data.isNotEmpty()) { storeAppStateKey(id, data); stored++ }+ }+ WhatsAppDiag.log(TAG, "app-state: stored $stored sync key(s); fetching collections")+ for (name in APP_STATE_COLLECTIONS) {+ fetchAppStateCollection(name, fullSync = appStateVersion(name) == 0L)+ }+ }++ /**+ * Fetch + decode + apply one app-state collection (snapshot then incremental patches).+ * Ref whatsmeow appstate.go fetchAppState. MAC/LTHash verification is skipped.+ */+ private suspend fun fetchAppStateCollection(name: String, fullSync: Boolean) {+ if (!appStateCollectionsFetching.add(name)) return+ try {+ var version = if (fullSync) 0L else appStateVersion(name)+ var wantSnapshot = fullSync || version == 0L+ var more = true+ var guard = 0+ while (more && guard++ < 12) {+ val collAttrs = mutableMapOf("name" to name, "return_snapshot" to wantSnapshot.toString())+ if (!wantSnapshot) collAttrs["version"] = version.toString()+ val iq = WhatsAppProtocol.Node(+ tag = "iq",+ attrs = mapOf(+ "id" to generateMessageId(), "type" to "set",+ "xmlns" to "w:sync:app:state", "to" to "s.whatsapp.net",+ ),+ content = listOf(+ WhatsAppProtocol.Node(+ tag = "sync",+ content = listOf(WhatsAppProtocol.Node(tag = "collection", attrs = collAttrs)),+ )+ ),+ )+ val resp = sendIqAndWait(iq) ?: break+ val coll = resp.getChildByTag("sync")?.getChildByTag("collection") ?: break++ val snapNode = coll.getChildByTag("snapshot")+ var recCount = 0+ snapNode?.data?.let { snapData ->+ val ext = WhatsAppAppStateProto.ExternalBlobReference.parseFrom(snapData)+ val blob = downloadAppStateBlob(ext)+ if (blob == null) {+ WhatsAppDiag.log(TAG, "app-state $name: snapshot blob download FAILED (path=${ext.directPath.take(40)})")+ } else {+ val snap = WhatsAppAppStateProto.SyncdSnapshot.parseFrom(blob)+ recCount = snap.recordsCount+ for (rec in snap.recordsList) applyAppStateRecord(name, rec, isSet = true)+ if (snap.hasVersion()) version = snap.version.version+ }+ }+ val patchNodes = coll.getChildByTag("patches")?.getChildren()?.filter { it.tag == "patch" } ?: emptyList()+ patchNodes.forEach { p ->+ p.data?.let { pd ->+ val patch = WhatsAppAppStateProto.SyncdPatch.parseFrom(pd)+ val muts = if (patch.hasExternalMutations()) {+ downloadAppStateBlob(patch.externalMutations)?.let {+ WhatsAppAppStateProto.SyncdMutations.parseFrom(it).mutationsList+ } ?: emptyList()+ } else patch.mutationsList+ for (m in muts) applyAppStateRecord(+ name, m.record,+ isSet = m.operation == WhatsAppAppStateProto.SyncdMutation.SyncdOperation.SET,+ )+ if (patch.hasVersion()) version = patch.version.version+ }+ }+ WhatsAppDiag.log(TAG, "app-state $name: snapshot=${snapNode != null} records=$recCount patches=${patchNodes.size} more=${coll.attrs["has_more_patches"]} -> v$version")+ more = coll.attrs["has_more_patches"] == "true"+ wantSnapshot = false+ }+ setAppStateVersion(name, version)+ WhatsAppDiag.log(TAG, "app-state: $name synced to v$version")+ } catch (e: Exception) {+ WhatsAppDiag.log(TAG, "app-state $name failed: ${e.javaClass.simpleName}: ${e.message}")+ } finally {+ appStateCollectionsFetching.remove(name)+ }+ }++ /** Download + decrypt an app-state external blob (snapshot/mutations) via the media CDN. */+ private suspend fun downloadAppStateBlob(ext: WhatsAppAppStateProto.ExternalBlobReference): ByteArray? {+ val directPath = ext.directPath+ if (directPath.isEmpty()) return null+ val host = mediaConn()?.first ?: return null+ val hash = Base64.encodeToString(ext.fileEncSha256.toByteArray(), Base64.URL_SAFE or Base64.NO_WRAP)+ val url = "https://$host$directPath&hash=$hash&mms-type=md-app-state&__wa-mms="+ return downloadMedia(url, ext.mediaKey.toByteArray(), WhatsAppProtocol.MEDIA_KEY_APP_STATE)+ }++ /** Decrypt one app-state record and apply it (contact names, mute/pin/archive). */+ private suspend fun applyAppStateRecord(+ collection: String,+ record: WhatsAppAppStateProto.SyncdRecord,+ isSet: Boolean,+ ) {+ if (!isSet) return+ val keyId = record.keyId.id.toByteArray()+ val keyData = getAppStateKey(keyId) ?: run {+ requestAppStateKey(keyId); return+ }+ val expanded = WhatsAppProtocol.expandAppStateKeys(keyData)+ val plain = WhatsAppProtocol.decryptAppStateValue(record.value.blob.toByteArray(), expanded[1]) ?: return+ val sad = try { WhatsAppAppStateProto.SyncActionData.parseFrom(plain) } catch (e: Exception) { return }+ val index = try { org.json.JSONArray(String(sad.index.toByteArray(), Charsets.UTF_8)) } catch (e: Exception) { return }+ if (index.length() == 0) return+ val action = index.optString(0)+ val jid = if (index.length() > 1) index.optString(1) else ""+ val value = sad.value+ when (action) {+ "contact" -> {+ val name = value.contactAction.fullName.ifEmpty { value.contactAction.firstName }+ if (name.isNotEmpty() && jid.isNotEmpty()) {+ // Cache name for live messages / future conversations. We do NOT emit a+ // ConversationUpdate here because the consumer upserts (would create empty rows+ // for every contact). History rows already use device-contact lookup for names.+ nameCache[resolveJID(jid)] = name+ nameCache[jid] = name+ }+ }+ "mute" -> if (jid.isNotEmpty()) db?.conversationDao()?.updateMuteEndTime(jid, value.muteAction.muteEndTimestamp)+ "pin_v1" -> if (jid.isNotEmpty()) db?.conversationDao()?.updatePinned(jid, value.pinAction.pinned)+ "archive" -> if (jid.isNotEmpty()) db?.conversationDao()?.updateArchived(jid, value.archiveChatAction.archived)+ "markChatAsRead" -> if (jid.isNotEmpty()) db?.conversationDao()?.updateMarkedAsUnread(jid, !value.markChatAsReadAction.read)+ }+ }++ /** Request a missing app-state sync key from our primary (deduped). */+ private suspend fun requestAppStateKey(keyId: ByteArray) {+ val id64 = appStateKeyId64(keyId)+ if (!appStateKeyRequested.add(id64)) return+ val auth = authData ?: return+ try {+ val req = WhatsAppE2EProto.AppStateSyncKeyRequest.newBuilder()+ .addKeyIds(+ WhatsAppE2EProto.AppStateSyncKeyId.newBuilder()+ .setKeyId(com.google.protobuf.ByteString.copyFrom(keyId))+ )+ val proto = WhatsAppE2EProto.ProtocolMessage.newBuilder()+ .setType(WhatsAppE2EProto.ProtocolMessage.Type.APP_STATE_SYNC_KEY_REQUEST)+ .setAppStateSyncKeyRequest(req)+ val msg = WhatsAppE2EProto.Message.newBuilder().setProtocolMessage(proto).build()+ val ownUser = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".")+ val node = buildEncryptedMessageNode("[email protected]", generateMessageId(), msg, "text") ?: return+ webSocket?.send(WhatsAppProtocol.encodeNode(node))+ WhatsAppDiag.log(TAG, "app-state: requested missing key $id64")+ } catch (e: Exception) {+ WhatsAppDiag.log(TAG, "app-state key request failed: ${e.message}")+ }+ }++ private val appStateKeyRequested = java.util.Collections.synchronizedSet(HashSet<String>())++ /**+ * Send a retry receipt asking the sender to re-encrypt an undecryptable message.+ * Ref whatsmeow retry.go sendRetryReceipt. Retries are capped at 5; the identity/prekey <keys>+ * node is included from the 2nd retry onward.+ */+ private suspend fun sendRetryReceipt(node: WhatsAppProtocol.Node) {+ val auth = authData ?: return+ val crypto = ensureE2E(auth) ?: return+ val ws = webSocket ?: return+ val msgId = node.attrs["id"] ?: return+ val count = undecryptableTracker.merge("retry:$msgId", 1) { a, b -> a + b } ?: 1+ if (count > 5) {+ Log.w(TAG, "Not sending more retry receipts for $msgId")+ return+ }+ val keysNode = if (count > 1) {+ try { crypto.buildRetryReceiptKeysNode(accountDeviceIdentity()) } catch (e: Exception) {+ Log.w(TAG, "Failed to build retry keys node", e); null+ }+ } else null+ val receipt = WhatsAppProtocol.buildRetryReceipt(node, auth.registrationId, count, keysNode)+ ws.send(WhatsAppProtocol.encodeNode(receipt))+ Log.d(TAG, "Sent retry receipt #$count for $msgId")+ }++ /**+ * Handle an inbound <receipt type="retry">: the peer failed to decrypt a message we sent and+ * is asking us to re-encrypt and resend it. Rebuild the session from the fresh keys included+ * in the receipt (present from the 2nd retry), then re-encrypt the cached plaintext for just+ * the requesting device and resend with the same message id. Ref whatsmeow retry.go+ * handleRetryReceipt. 1:1 only — group skmsg resends are not cached.+ */+ private suspend fun handleRetryReceipt(node: WhatsAppProtocol.Node) {+ val auth = authData ?: return+ val crypto = ensureE2E(auth) ?: return+ val ws = webSocket ?: return+ val msgId = node.attrs["id"] ?: return+ val from = node.attrs["from"] ?: return+ // The specific device that couldn't decrypt: participant if present, else the chat peer.+ val deviceJid = node.attrs["participant"] ?: from+ if (deviceJid.contains("@g.us")) {+ WhatsAppDiag.log(TAG, "retry: ignoring group retry for $msgId (not cached)")+ return+ }+ val cached = recentSentDMs[msgId] ?: run {+ WhatsAppDiag.log(TAG, "retry: no cached message for $msgId; cannot resend")+ return+ }+ val resendKey = "$msgId|$deviceJid"+ val resendCount = retryResendCounts.merge(resendKey, 1) { a, b -> a + b } ?: 1+ if (resendCount > 5) {+ WhatsAppDiag.log(TAG, "retry: giving up on $msgId for $deviceJid after $resendCount attempts")+ return+ }++ // Rebuild the session from the keys the peer attached (identity + prekeys), if any.+ val deviceNum = deviceJid.substringBefore("@").substringAfter(":", "0").toIntOrNull() ?: 0+ if (node.getChildByTag("keys") != null) {+ try {+ // parsePreKeyBundleNode reads <registration> + <keys> from the node it is given.+ val bundle = crypto.parsePreKeyBundleNode(deviceNum, node)+ if (bundle != null) {+ crypto.deleteSession(deviceJid)+ crypto.processPreKeyBundle(deviceJid, bundle)+ WhatsAppDiag.log(TAG, "retry: rebuilt session for $deviceJid from receipt keys")+ }+ } catch (e: Exception) {+ WhatsAppDiag.log(TAG, "retry: failed to process receipt keys for $deviceJid: ${e.message}")+ }+ }+ if (!ensureSession(deviceJid)) {+ WhatsAppDiag.log(TAG, "retry: no session for $deviceJid; cannot resend $msgId")+ return+ }++ val ownUser = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".")+ val devUser = deviceJid.substringBefore("@").substringBefore(":").substringBefore(".")+ val plaintext = if (devUser == ownUser && cached.dsmPlaintextPadded != null)+ cached.dsmPlaintextPadded else cached.msgPlaintextPadded+ val enc = try {+ crypto.encryptDM(deviceJid, plaintext)+ } catch (e: Exception) {+ WhatsAppDiag.log(TAG, "retry: re-encrypt failed for $deviceJid: ${e.message}")+ return+ }+ val includeIdentity = enc.type == "pkmsg"+ val resend = WhatsAppProtocol.buildFanOutMessageNode(+ to = cached.to,+ id = msgId,+ type = cached.type,+ participantEncs = listOf(WhatsAppProtocol.ParticipantEnc(deviceJid, enc.type, enc.data)),+ includeDeviceIdentity = includeIdentity,+ deviceIdentity = if (includeIdentity) accountDeviceIdentity() else null,+ )+ val sent = ws.send(WhatsAppProtocol.encodeNode(resend))+ WhatsAppDiag.log(TAG, "retry: resent $msgId to $deviceJid (attempt $resendCount type=${enc.type}) sent=$sent")+ }++ /**+ * Track undecryptable messages.+ * From Go handleWAUndecryptableMessage / trackUndecryptable.+ */+ private fun trackUndecryptable(node: WhatsAppProtocol.Node) {+ val from = node.attrs["from"] ?: return+ val count = undecryptableTracker.merge(from, 1) { old, new -> old + new } ?: 1+ Log.w(TAG, "Undecryptable message from $from (count: $count)")+ }++ /**+ * Resolve JID: convert LID JIDs to phone number JIDs.+ * Handles DM sender LID, own message LID, broadcast, and bot cases.+ * From Go resolveJID / rerouteWAMessage — 5 distinct rerouting cases.+ */+ private fun resolveJID(jid: String): String {+ // Case 1: Not a LID — no rerouting needed+ if (!jid.contains("@lid")) return jid++ // Case 2: Direct LID→phone mapping from cache+ lidToPhoneMap[jid]?.let { return it }++ // Case 3: Own LID matches+ val ownLid = authData?.lid+ if (ownLid != null && ownLid.isNotEmpty() && jid == ownLid) {+ return authData?.wid ?: jid+ }++ // Case 4: Bot server JIDs (Go rerouteWAMessage bot server case)+ if (jid.contains("@bot")) {+ return jid // Bot JIDs are valid as-is+ }++ // Case 5: Extract user part and check LID map without server suffix+ val userPart = jid.substringBefore("@")+ lidToPhoneMap.entries.find { it.key.startsWith("$userPart@") }?.let { return it.value }++ return jid+ }++ /**+ * Store poll option hashes for later vote resolution.+ * From Go wadb.PollOption.+ */+ private suspend fun storePollOptions(messageId: String, options: List<String>) {+ val dao = db?.pollOptionDao() ?: return+ val pollOptions = options.map { option ->+ val hash = java.security.MessageDigest.getInstance("SHA-256")+ .digest(option.toByteArray(Charsets.UTF_8))+ WhatsAppPollOption(+ msgId = messageId,+ optionHash = hash.joinToString("") { "%02x".format(it) },+ optionName = option,+ )+ }+ dao.upsertAll(pollOptions)+ }++ private fun kickoffBackfill() {+ // History is PUSHED by the phone after linking as encrypted <message> stanzas carrying a+ // protocolMessage.historySyncNotification (gated by DeviceProps.HistorySyncConfig sent at+ // pairing). There is no w:web "initial" request in the multidevice protocol, so we just+ // wait for those messages here. Ref whatsmeow appstate/history sync.+ WhatsAppDiag.log(TAG, "awaiting pushed history sync messages from phone")+ }++ /**+ * Download (or read inline), decompress and parse a HistorySync blob, then emit the contained+ * messages as backfill. Ref whatsmeow message.go DownloadHistorySync + download.go.+ */+ private suspend fun handleHistorySync(+ notif: WhatsAppE2EProto.HistorySyncNotification,+ msgId: String,+ ) {+ try {+ val raw: ByteArray = if (notif.hasInitialHistBootstrapInlinePayload() &&+ !notif.initialHistBootstrapInlinePayload.isEmpty+ ) {+ // Initial bootstrap chunk is inlined in the notification (DeviceProps requested it).+ notif.initialHistBootstrapInlinePayload.toByteArray()+ } else {+ val host = mediaConn()?.first ?: run {+ WhatsAppDiag.log(TAG, "history sync: no media host"); sendHistorySyncReceipt(msgId); return+ }+ val directPath = notif.directPath+ if (directPath.isEmpty()) { WhatsAppDiag.log(TAG, "history sync: no directPath"); sendHistorySyncReceipt(msgId); return }+ val hash = Base64.encodeToString(+ notif.fileEncSha256.toByteArray(), Base64.URL_SAFE or Base64.NO_WRAP+ )+ val url = "https://$host$directPath&hash=$hash&mms-type=md-msg-hist&__wa-mms="+ downloadMedia(url, notif.mediaKey.toByteArray(), WhatsAppProtocol.MEDIA_KEY_HISTORY)+ ?: run { WhatsAppDiag.log(TAG, "history sync: download failed"); sendHistorySyncReceipt(msgId); return }+ }++ val inflated = inflateZlib(raw)+ val hs = WhatsAppE2EProto.HistorySync.parseFrom(inflated)+ // Populate LID->phone mappings so conversations addressed by LID resolve to a phone JID.+ for (m in hs.phoneNumberToLidMappingsList) {+ if (m.lidJid.isNotEmpty() && m.pnJid.isNotEmpty()) lidToPhoneMap[m.lidJid] = m.pnJid+ }+ WhatsAppDiag.log(+ TAG,+ "history sync: type=${hs.syncType} chunk=${hs.chunkOrder} conversations=${hs.conversationsCount} lidMaps=${hs.phoneNumberToLidMappingsCount} (blob=${raw.size}B inflated=${inflated.size}B)",+ )++ // Backfill continues (paginates older messages) from the initial bootstrap and from+ // each on-demand response, so full history is pulled page by page. RECENT/FULL/etc are+ // terminal pushes and don't trigger further requests.+ val requestMore = fullHistorySync &&+ (hs.syncType == SYNC_INITIAL_BOOTSTRAP || hs.syncType == SYNC_ON_DEMAND)+ var emitted = 0+ for (conv in hs.conversationsList) {+ val chatJid = conv.newJid.ifEmpty { conv.id }+ WhatsAppDiag.log(TAG, " conv '${conv.name}' ${chatJid} msgs=${conv.messagesCount}")+ if (chatJid.isEmpty() || chatJid.startsWith("status@broadcast")) continue+ emitted += emitHistoryConversation(conv, chatJid, requestMore)+ }+ WhatsAppDiag.log(TAG, "history sync: emitted $emitted message(s)")+ } catch (e: Exception) {+ WhatsAppDiag.log(TAG, "history sync failed: ${e.javaClass.simpleName}: ${e.message}")+ Log.e(TAG, "history sync failed", e)+ }+ // Acknowledge the chunk so the phone advances to the next one and finishes "syncing".+ sendHistorySyncReceipt(msgId)+ }++ /**+ * Send the history-sync receipt so the phone stops waiting ("syncing, keep WhatsApp open") and+ * sends the next chunk. Ref whatsmeow SendProtocolMessageReceipt(id, ReceiptTypeHistorySync).+ * <receipt id="{notifMsgId}" type="hist_sync" to="{ownUserJID}"/>+ */+ private fun sendHistorySyncReceipt(msgId: String) {+ if (msgId.isEmpty()) return+ val ownUser = (authData?.wid ?: return).substringBefore("@").substringBefore(":").substringBefore(".")+ if (ownUser.isEmpty()) return+ val receipt = WhatsAppProtocol.Node(+ tag = "receipt",+ attrs = mapOf("id" to msgId, "type" to "hist_sync", "to" to "[email protected]"),+ )+ webSocket?.send(WhatsAppProtocol.encodeNode(receipt))+ WhatsAppDiag.log(TAG, "history sync: sent hist_sync receipt for $msgId")+ }++ /** Emit one backfilled history message as an IncomingMessage. Returns true if emitted. */+ /**+ * Backfill one conversation: emit a MessageUpdate (outgoing-aware) for each message with a+ * body, then a ConversationUpdate so the chat row appears with its last preview. Returns the+ * number of messages emitted. MessageUpdate is the backfill path (no notifications); IncomingMessage+ * is reserved for live messages.+ */+ private suspend fun emitHistoryConversation(+ conv: WhatsAppE2EProto.HsConversation,+ rawChatJid: String,+ requestMore: Boolean,+ ): Int {+ // Resolve LID-addressed chats to a phone JID so they match live conversations and have a+ // displayable number/name (instead of "unknown").+ val chatJid = resolveJID(rawChatJid)+ val convId = "wa:$chatJid"+ // E.164 (with +) so device-contact lookup (ContactsContract.PhoneLookup) matches.+ val phone = if (chatJid.endsWith("@s.whatsapp.net"))+ "+" + chatJid.substringBefore("@").substringBefore(":").substringBefore(".") else null+ val contactName = resolveDeviceContactName(phone)+ // Collect displayable messages first so we can register the conversation row BEFORE the+ // messages (the message table has a FK to the conversation).+ data class HMsg(val id: String, val body: String, val outgoing: Boolean, val ts: Long, val sender: String?)+ val msgs = ArrayList<HMsg>()+ var lastBody = ""+ var lastTs = conv.conversationTimestamp * 1000+ var peerPush = ""+ for (hsMsg in conv.messagesList) {+ if (!hsMsg.hasMessage()) continue+ val wmi = hsMsg.message+ if (!wmi.hasMessage()) continue+ val body = WhatsAppProtocol.extractMessageBody(wmi.message)+ if (body.isEmpty()) continue+ val key = wmi.key+ val tsMs = wmi.messageTimestamp * 1000+ if (!key.fromMe && wmi.pushName.isNotEmpty()) peerPush = wmi.pushName+ val senderName = if (key.fromMe) null+ else wmi.pushName.ifEmpty { conv.name.ifEmpty { contactName ?: phone } }+ msgs.add(HMsg(key.id, body, key.fromMe, tsMs, senderName))+ if (tsMs >= lastTs) { lastTs = tsMs; lastBody = body }+ }+ if (msgs.isEmpty()) return 0++ // Register the conversation row first.+ _events.emit(+ WhatsAppEvent.ConversationUpdate(+ source = MessageSource.WHATSAPP,+ conversationId = convId,+ peerName = conv.name.ifEmpty { contactName ?: peerPush.ifEmpty { phone } },+ peerPhone = phone,+ avatarUrl = null,+ lastPreview = lastBody,+ lastTimestamp = lastTs,+ unreadCount = conv.unreadCount,+ )+ )+ // Then backfill its messages.+ for (m in msgs) {+ _events.emit(+ WhatsAppEvent.MessageUpdate(+ source = MessageSource.WHATSAPP,+ conversationId = convId,+ messageId = m.id,+ body = m.body,+ outgoing = m.outgoing,+ timestamp = m.ts,+ senderName = m.sender,+ )+ )+ }+ // Pull the next older page on demand. Fire-and-forget: the request fans out via usync (a+ // slow IQ) and must NOT block the conversation backfill loop, or only the first chat would+ // appear promptly. Pagination walks backwards one page at a time — each on-demand response+ // re-enters handleHistorySync with a new (older) oldest message, until the phone returns an+ // empty/anchor-only chunk (msgs.isEmpty above → no further request), i.e. end of history.+ if (requestMore) {+ val oldest = msgs.minByOrNull { it.ts }+ if (oldest != null) {+ scope.launch {+ sendHistoryOnDemandRequest(rawChatJid, oldest.id, oldest.outgoing, oldest.ts / 1000)+ }+ }+ }+ return msgs.size+ }++ // Cursors ("chatJid|oldestMsgId") already requested, so a repeated response for the same anchor+ // stops the walk instead of looping. Distinct (older) cursors are allowed through so pagination+ // can continue.+ private val onDemandRequested = Collections.synchronizedSet(HashSet<String>())+ // Pages requested per chat, to bound pagination (see MAX_ON_DEMAND_PAGES_PER_CHAT).+ private val onDemandPageCount = ConcurrentHashMap<String, Int>()++ /** Look up a device contact display name for an E.164 number (null if none / no permission). */+ private fun resolveDeviceContactName(phoneE164: String?): String? {+ if (phoneE164.isNullOrEmpty()) return null+ return try {+ val uri = android.net.Uri.withAppendedPath(+ android.provider.ContactsContract.PhoneLookup.CONTENT_FILTER_URI,+ android.net.Uri.encode(phoneE164),+ )+ appContext.contentResolver.query(+ uri,+ arrayOf(android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME),+ null, null, null,+ )?.use { c -> if (c.moveToFirst()) c.getString(0)?.takeIf { it.isNotBlank() } else null }+ } catch (e: Exception) {+ null+ }+ }++ /**+ * Ask our own account to stream older history for a chat. Ref whatsmeow BuildHistorySyncRequest+ * — a HISTORY_SYNC_ON_DEMAND peer-data-operation message sent E2E to self. Deduped per+ * (chat, oldest-message) cursor so a repeated/anchor-only response ends the walk, while genuinely+ * older responses keep paginating. Bounded by MAX_ON_DEMAND_PAGES_PER_CHAT. Best-effort.+ */+ private suspend fun sendHistoryOnDemandRequest(+ chatJid: String,+ oldestMsgId: String,+ oldestFromMe: Boolean,+ oldestTsSec: Long,+ ) {+ if (oldestMsgId.isEmpty() || chatJid.isEmpty()) return+ // Stop if we've already asked for this exact cursor (prevents same-page loops).+ if (!onDemandRequested.add("$chatJid|$oldestMsgId")) return+ // Bound total pages per chat.+ val pages = onDemandPageCount.merge(chatJid, 1, Int::plus) ?: 1+ if (pages > MAX_ON_DEMAND_PAGES_PER_CHAT) {+ WhatsAppDiag.log(TAG, "on-demand history: hit page cap for $chatJid, stopping")+ return+ }+ val auth = auth
Diff truncated.