messages: various fixes
- Commit
5847d6ed0bc927ef22ec1dbfe2f4511495243e41- Author
- Vayun Mathur <[email protected]>
- When
- 2026-06-09 03:04 UTC (6 months ago)
- Parents
1521d51
Diff
messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.ktindex b217c29044..54dacc57f0 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt@@ -48,7 +48,8 @@ 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.sync.Mutex+import kotlinx.coroutines.sync.withLock import rpc.Rpc.ActionType import rpc.Rpc.MessageType import java.util.concurrent.atomic.AtomicBoolean@@ -105,6 +106,7 @@ object GMessagesClient { private lateinit var appContext: Context private val rpc = RpcClient() @Volatile private var auth: AuthData = AuthData.generateInitial()+ private val authMutex = Mutex() private val sessionHandler = SessionHandler(rpc) { auth } private val media = Media { auth } private val longPoll = LongPoll(@@ -127,14 +129,14 @@ object GMessagesClient { if (!initialized.compareAndSet(false, true)) return appContext = context.applicationContext Log.i(TAG, "init")- runBlocking {+ scope.launch { AuthData.load(appContext)?.let { auth = it }- }- if (auth.isPaired()) {- Log.i(TAG, "found persisted pair, resuming long-poll")- longPoll.start(scope)- _state.value = State.Connected- scope.launch { postConnect() }+ if (auth.isPaired()) {+ Log.i(TAG, "found persisted pair, resuming long-poll")+ longPoll.start(scope)+ _state.value = State.Connected+ postConnect()+ } } } @@ -152,26 +154,40 @@ object GMessagesClient { backfillJob?.cancel() longPoll.stop() sessionHandler.cancelAll()- auth = AuthData.generateInitial()- scope.launch { auth.save(appContext) }+ val freshAuth = AuthData.generateInitial()+ auth = freshAuth+ scope.launch { freshAuth.save(appContext) }+ outgoingIds.clear()+ conversationsFetchedOnce = false+ rpc.close()+ media.close() _state.value = State.Idle } suspend fun startPair(): String {- // Fresh keys for a fresh pair.- auth = AuthData.generateInitial()- val result = PairFlow.registerAndBuildQrUrl(rpc, auth)- val ttlUs = result.tachyonTtlUs.let { if (it == 0L) DEFAULT_TTL_US else it }- auth = auth.copy(- tachyonAuthTokenB64 = android.util.Base64.encodeToString(result.tachyonToken, android.util.Base64.NO_WRAP),- tachyonTtlUs = ttlUs,- tachyonExpiryMs = System.currentTimeMillis() + (ttlUs / 1000),- )- // Open the long-poll now so we receive the Paired event when the- // user finishes scanning.- longPoll.start(scope)- _state.value = State.Pairing(result.qrUrl)- return result.qrUrl+ try {+ val qrUrl = authMutex.withLock {+ // Fresh keys for a fresh pair.+ auth = AuthData.generateInitial()+ val result = PairFlow.registerAndBuildQrUrl(rpc, auth)+ val ttlUs = result.tachyonTtlUs.let { if (it == 0L) DEFAULT_TTL_US else it }+ auth = auth.copy(+ tachyonAuthTokenB64 = android.util.Base64.encodeToString(result.tachyonToken, android.util.Base64.NO_WRAP),+ tachyonTtlUs = ttlUs,+ tachyonExpiryMs = System.currentTimeMillis() + (ttlUs / 1000),+ )+ result.qrUrl+ }+ // Open the long-poll now so we receive the Paired event when the+ // user finishes scanning.+ longPoll.start(scope)+ _state.value = State.Pairing(qrUrl)+ return qrUrl+ } catch (t: Throwable) {+ Log.e(TAG, "startPair failed", t)+ _state.value = State.Disconnected("Pair failed: ${t.message}")+ throw t+ } } /**@@ -624,12 +640,14 @@ object GMessagesClient { if (newTtlUs == 0L) { newTtlUs = DEFAULT_TTL_US }- auth = currentAuth.copy(- tachyonAuthTokenB64 = Base64.encodeToString(newToken.toByteArray(), Base64.NO_WRAP),- tachyonTtlUs = newTtlUs,- tachyonExpiryMs = System.currentTimeMillis() + (newTtlUs / 1000)- )- auth.save(appContext)+ authMutex.withLock {+ auth = currentAuth.copy(+ tachyonAuthTokenB64 = Base64.encodeToString(newToken.toByteArray(), Base64.NO_WRAP),+ tachyonTtlUs = newTtlUs,+ tachyonExpiryMs = System.currentTimeMillis() + (newTtlUs / 1000)+ )+ auth.save(appContext)+ } Log.i(TAG, "Auth token refreshed successfully, new expiry in ${newTtlUs / 1000 / 1000}s") } catch (e: Exception) {@@ -660,14 +678,16 @@ object GMessagesClient { private suspend fun handlePaired(p: LongPollEvent.Paired) { Log.i(TAG, "received Paired event — switching to Connected (ttlUs=${p.tachyonTtlUs})") val ttlUs = p.tachyonTtlUs.let { if (it == 0L) DEFAULT_TTL_US else it }- auth = auth.copy(- mobileDeviceB64 = p.mobileDeviceB64,- browserDeviceB64 = p.browserDeviceB64,- tachyonAuthTokenB64 = p.tachyonTokenB64,- tachyonTtlUs = ttlUs,- tachyonExpiryMs = System.currentTimeMillis() + (ttlUs / 1000),- )- auth.save(appContext)+ authMutex.withLock {+ auth = auth.copy(+ mobileDeviceB64 = p.mobileDeviceB64,+ browserDeviceB64 = p.browserDeviceB64,+ tachyonAuthTokenB64 = p.tachyonTokenB64,+ tachyonTtlUs = ttlUs,+ tachyonExpiryMs = System.currentTimeMillis() + (ttlUs / 1000),+ )+ auth.save(appContext)+ } _state.value = State.Connected // CRITICAL: the long-poll that received this Paired event is
messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.ktindex ae02a371da..d06e046ae5 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt@@ -9,6 +9,7 @@ import com.google.protobuf.InvalidProtocolBufferException import events.Events.RPCPairData import io.ktor.client.statement.bodyAsChannel import io.ktor.utils.io.readAvailable+import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay@@ -60,6 +61,8 @@ class LongPoll( } val ok = try { openAndRead()+ } catch (e: CancellationException) {+ throw e } catch (t: Throwable) { Log.w(TAG, "long-poll error: ${t.message}") false
messages/src/main/java/com/vayunmathur/messages/gmessages/Media.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/Media.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/Media.ktindex fdc14ca7ed..91af03b3d7 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/Media.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Media.kt@@ -86,7 +86,10 @@ class Media(private val authProvider: () -> AuthData) { AuthMessage.newBuilder() .setRequestID(java.util.UUID.randomUUID().toString()) .setTachyonAuthToken(- com.google.protobuf.ByteString.copyFrom(auth.tachyonToken()!!)+ com.google.protobuf.ByteString.copyFrom(+ auth.tachyonToken()+ ?: error("tachyon token is null — not paired or token expired")+ ) ) .setNetwork(PairFlow.QrNetwork) .setConfigVersion(PairFlow.ConfigVersion)@@ -141,9 +144,12 @@ class Media(private val authProvider: () -> AuthData) { error("finalize-upload HTTP ${resp.status.value}") } var bodyBytes = resp.bodyAsBytes()- // Sometimes the response is base64-encoded protobuf, sometimes- // raw protobuf. Detect by attempting standard base64 parsing.- if (isLikelyBase64(bodyBytes)) {+ // The response may be base64-encoded protobuf or raw protobuf.+ // Use Content-Type to decide rather than inspecting the bytes.+ val isBinaryContent = resp.contentType()?.let { ct ->+ ct.contentType == "application"+ } ?: false+ if (!isBinaryContent) { bodyBytes = runCatching { Base64.decode(bodyBytes, Base64.NO_WRAP) }.getOrDefault(bodyBytes)@@ -155,16 +161,7 @@ class Media(private val authProvider: () -> AuthData) { ) } - private fun isLikelyBase64(b: ByteArray): Boolean {- if (b.isEmpty() || b.size % 4 != 0) return false- return b.all { c ->- val ch = c.toInt() and 0xFF- (ch in 'A'.code..'Z'.code) || (ch in 'a'.code..'z'.code) ||- (ch in '0'.code..'9'.code) || ch == '+'.code || ch == '/'.code || ch == '='.code- }- }-- /**+ companion object { * Apply the upload header bundle (port of util/func.go.NewMediaUploadHeaders). * The relay's anti-abuse layer inspects these alongside the URL + * Origin to decide whether the request looks like a real browser.
messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.ktindex 9898462ec1..038f92c0b6 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt@@ -187,7 +187,8 @@ class SessionHandler( .setAuth( OutgoingRPCMessage.Auth.newBuilder() .setRequestID(requestId)- .setTachyonAuthToken(auth.tachyonToken()!!.toByteString())+ .setTachyonAuthToken((auth.tachyonToken()+ ?: error("tachyon token is null — not paired or token expired")).toByteString()) .setConfigVersion(PairFlow.ConfigVersion) )
messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.ktindex 4f41462bf0..aa9824f3d1 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt@@ -15,7 +15,7 @@ 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.delay import requests.Requests import responses.Responses import threads.Threads@@ -63,7 +63,7 @@ object GVoiceClient { if (!initialized.compareAndSet(false, true)) return appContext = context.applicationContext Log.i(TAG, "init")- runBlocking {+ scope.launch { val auth = VoiceAuthData.load(appContext) if (auth?.hasRequired() == true) { Log.i(TAG, "resuming from persisted cookies")@@ -516,7 +516,7 @@ object GVoiceClient { if (!resp.hasThread()) return@launch val thread = resp.thread for (i in 0 until thread.messagesCount) {- emitMessage(thread.getID(), thread.getMessages(i))+ emitMessage(thread.getID(), thread.getMessages(i), fromBackfill = true) } } }@@ -530,6 +530,7 @@ object GVoiceClient { client.updateCookies(auth.cookies) rpc = client + _state.value = State.Connecting _state.value = State.Connected realtime?.stop() realtime = RealtimeChannel(client) { evt ->@@ -537,49 +538,58 @@ object GVoiceClient { RealtimeEvent.Connected -> Log.i(TAG, "realtime connected") is RealtimeEvent.Data -> handleRealtimeData(evt.event) }- }.also { it.start(scope) }+ }.also { ch ->+ val rtJob = ch.start(scope)+ rtJob.invokeOnCompletion { cause ->+ if (!rtJob.isCancelled) {+ _state.value = State.Disconnected("realtime connection lost")+ }+ }+ } kickoffBackfill() } private fun kickoffBackfill() { backfillJob?.cancel()- backfillJob = scope.launch {- val client = rpc ?: return@launch- Log.i(TAG, "ListThreads (TEXT_THREADS)")- val req = Requests.ReqListThreads.newBuilder()- .setFolder(Threads.ThreadFolder.TEXT_THREADS)- // libgv hard-codes these "unknown" fields — 20 on the- // first call (10 on subsequent), 15 for the second.- // Without them the server returns 0 threads even though- // the account has real conversations.- .setUnknownInt2(20)- .setUnknownInt3(15)- .build()- val resp = try {- client.postPbLite(- url = VoiceEndpoints.EndpointListThreads,- body = req,- responseTemplate = Responses.RespListThreads.getDefaultInstance(),- )- } catch (t: Throwable) {- Log.w(TAG, "ListThreads failed: ${t.message}")- _state.value = State.Disconnected(t.message ?: "ListThreads failed")- return@launch- }- Log.i(TAG, "ListThreads: ${resp.threadsCount} threads")- for (i in 0 until resp.threadsCount) {- emitConversation(resp.getThreads(i))- }+ backfillJob = scope.launch { doBackfill() }+ }++ private suspend fun doBackfill() {+ val client = rpc ?: return+ Log.i(TAG, "ListThreads (TEXT_THREADS)")+ val req = Requests.ReqListThreads.newBuilder()+ .setFolder(Threads.ThreadFolder.TEXT_THREADS)+ // libgv hard-codes these "unknown" fields — 20 on the+ // first call (10 on subsequent), 15 for the second.+ // Without them the server returns 0 threads even though+ // the account has real conversations.+ .setUnknownInt2(20)+ .setUnknownInt3(15)+ .build()+ val resp = try {+ client.postPbLite(+ url = VoiceEndpoints.EndpointListThreads,+ body = req,+ responseTemplate = Responses.RespListThreads.getDefaultInstance(),+ )+ } catch (t: Throwable) {+ Log.w(TAG, "ListThreads failed: ${t.message}")+ _state.value = State.Disconnected(t.message ?: "ListThreads failed")+ return+ }+ Log.i(TAG, "ListThreads: ${resp.threadsCount} threads")+ for (i in 0 until resp.threadsCount) {+ emitConversation(resp.getThreads(i)) } } - private suspend fun handleRealtimeData(evt: webchannel.Webchannel.WebChannelEvent) {- // Each realtime event can carry thread updates / new message- // notifications. The shape is deeply nested; for v1 just- // re-trigger the backfill on any event — it's cheap and- // guarantees consistency until we wire per-event decoding.+ private fun handleRealtimeData(evt: webchannel.Webchannel.WebChannelEvent) { Log.d(TAG, "realtime event arrayID=${evt.arrayID} wrappers=${evt.dataWrapperCount}")- kickoffBackfill()+ backfillJob?.cancel()+ backfillJob = scope.launch {+ delay(2000)+ doBackfill()+ } } private suspend fun emitConversation(t: Threads.Thread) {@@ -637,7 +647,7 @@ object GVoiceClient { ) } - private suspend fun emitMessage(threadId: String, m: Threads.Message) {+ private suspend fun emitMessage(threadId: String, m: Threads.Message, fromBackfill: Boolean = false) { // Skip non-text messages (calls / voicemail / etc.) for v1. if (m.text.isBlank()) return val outgoing = m.type == Threads.Message.Type.SMS_OUT@@ -654,7 +664,7 @@ object GVoiceClient { senderName = if (m.hasContact()) m.contact.name.takeIf { it.isNotBlank() } else null, ) )- if (!outgoing) {+ if (!outgoing && !fromBackfill) { _events.emit( GMEvent.IncomingMessage( source = source,
messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.ktindex 26fea56249..f88ac75d62 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt@@ -37,9 +37,10 @@ class RealtimeChannel( ) { private var job: Job? = null - fun start(scope: CoroutineScope) {- if (job?.isActive == true) return+ fun start(scope: CoroutineScope): Job {+ if (job?.isActive == true) return job!! job = scope.launch { runLoop() }+ return job!! } fun stop() {
messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt b/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.ktindex a49966d90a..b52dbaa8f1 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt@@ -31,6 +31,7 @@ import com.vayunmathur.messages.signal.web.SignalHttpClient import com.vayunmathur.messages.signal.web.SignalWebSocket import com.vayunmathur.messages.signal.proto.SignalServiceProtos import com.vayunmathur.messages.signal.proto.WebSocketProtos+import com.vayunmathur.messages.data.buildMessagesDatabase import com.vayunmathur.messages.util.ContactSuggestion import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope@@ -44,8 +45,8 @@ import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch-import kotlinx.coroutines.runBlocking import org.signal.libsignal.protocol.IdentityKeyPair import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean@@ -97,7 +98,7 @@ object SignalClient { if (!initialized.compareAndSet(false, true)) return appContext = context.applicationContext Log.i(TAG, "init")- runBlocking {+ scope.launch { val auth = SignalAuthData.load(appContext) if (auth != null) { authData = auth@@ -228,7 +229,10 @@ object SignalClient { val sender = messageSender ?: return false val recipientAci = resolveRecipient(extractAci(conversationId) ?: return false) ?: return false return try {- val content = ContentBuilders.readReceipt(listOf(System.currentTimeMillis()))+ val messagesDb = buildMessagesDatabase(appContext)+ val messages = messagesDb.messageDao().observeForConversation(conversationId).first()+ val timestamps = messages.map { it.timestamp }.takeIf { it.isNotEmpty() } ?: return true+ val content = ContentBuilders.readReceipt(timestamps) sender.sendMessage(recipientAci, content, System.currentTimeMillis()) true } catch (t: Throwable) {@@ -238,6 +242,7 @@ object SignalClient { } suspend fun deleteThread(conversationId: String): Boolean {+ _events.emit(GMEvent.ConversationDeleted(source, conversationId)) return true } @@ -328,7 +333,7 @@ object SignalClient { contactManager = ContactManager(recipientStore) contactDiscovery = ContactDiscovery(recipientStore, auth.aci, auth.deviceId, auth.password, appContext) profileManager = ProfileManager(ws, recipientStore)- groupManager = GroupManager(ws, SignalGroupStore(database))+ groupManager = GroupManager(ws, SignalGroupStore(database), auth.aci, auth.password) ws.incomingRequestHandler = { request -> handleIncomingRequest(request, auth, sessStore, idStore, pkStore, skStore)@@ -336,6 +341,17 @@ object SignalClient { _state.value = State.Connected Log.i(TAG, "Connected to Signal")++ scope.launch {+ try {+ val aciKeyPair = IdentityKeyPair(Base64.decode(auth.aciIdentityKeyPair, Base64.NO_WRAP))+ val pniKeyPair = IdentityKeyPair(Base64.decode(auth.pniIdentityKeyPair, Base64.NO_WRAP))+ PreKeyManager.generateAndUploadPreKeys(ws, pkStore, aciKeyPair, pniKeyPair)+ } catch (t: Throwable) {+ Log.w(TAG, "Initial pre-key upload failed: ${t.message}")+ }+ }+ kickoffBackfill() scope.launch {@@ -354,6 +370,8 @@ object SignalClient { } } }+ } catch (e: CancellationException) {+ throw e } catch (e: Exception) { Log.e(TAG, "bootSession failed", e) _state.value = State.Disconnected("Boot failed: ${e.message}")@@ -430,6 +448,12 @@ object SignalClient { if (syncContent is MessageContent.TextMessage) { val msgId = "${destAci}_${content.timestamp}" _events.emit(GMEvent.MessageUpdate(source, destAci, msgId, syncContent.body, true, content.timestamp, null))+ _events.emit(GMEvent.ConversationUpdate(+ source = source, conversationId = destAci,+ peerName = resolveDisplayName(destAci), peerPhone = null, avatarUrl = null,+ lastPreview = syncContent.body, lastTimestamp = content.timestamp,+ unreadCount = 0, conversationType = "Signal",+ )) } } is MessageContent.Typing -> {}@@ -463,6 +487,24 @@ object SignalClient { peerName = null, peerPhone = null, avatarUrl = null, lastPreview = null, lastTimestamp = 0, unreadCount = 0, ))++ val sender = messageSender ?: return@launch+ try {+ val syncRequest = SignalServiceProtos.SyncMessage.Request.newBuilder()+ .setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS)+ .build()+ val syncMessage = SignalServiceProtos.SyncMessage.newBuilder()+ .setRequest(syncRequest)+ .build()+ val content = SignalServiceProtos.Content.newBuilder()+ .setSyncMessage(syncMessage)+ .build()+ val auth = authData ?: return@launch+ sender.sendMessage(auth.aci, content, System.currentTimeMillis())+ Log.d(TAG, "Sent contacts sync request to primary device")+ } catch (t: Throwable) {+ Log.w(TAG, "Contacts sync request failed: ${t.message}")+ } } }
messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.ktindex cee2e18295..33d5827414 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt@@ -2,7 +2,7 @@ package com.vayunmathur.messages.signal.auth import android.util.Base64 import android.util.Log-import com.vayunmathur.messages.signal.store.SignalDeviceData+import com.vayunmathur.messages.signal.store.SignalPreKeyStore import com.vayunmathur.messages.signal.web.SignalWebSocket import org.json.JSONArray import org.json.JSONObject@@ -12,6 +12,9 @@ import org.signal.libsignal.protocol.ecc.ECPublicKey import org.signal.libsignal.protocol.ecc.ECPrivateKey import org.signal.libsignal.protocol.kem.KEMKeyPair import org.signal.libsignal.protocol.kem.KEMKeyType+import org.signal.libsignal.protocol.state.KyberPreKeyRecord+import org.signal.libsignal.protocol.state.PreKeyRecord+import org.signal.libsignal.protocol.state.SignedPreKeyRecord import java.io.IOException import java.security.SecureRandom @@ -22,18 +25,18 @@ object PreKeyManager { suspend fun generateAndUploadPreKeys( ws: SignalWebSocket,- deviceData: SignalDeviceData,+ preKeyStore: SignalPreKeyStore, aciIdentityKeyPair: IdentityKeyPair, pniIdentityKeyPair: IdentityKeyPair, ) {- uploadKeysForIdentity(ws, "aci", aciIdentityKeyPair)- uploadKeysForIdentity(ws, "pni", pniIdentityKeyPair)+ uploadKeysForIdentity(ws, preKeyStore, "aci", aciIdentityKeyPair)+ uploadKeysForIdentity(ws, preKeyStore, "pni", pniIdentityKeyPair) Log.d(TAG, "Pre-keys uploaded for both identities") } suspend fun checkAndRefreshIfNeeded( ws: SignalWebSocket,- deviceData: SignalDeviceData,+ preKeyStore: SignalPreKeyStore, aciIdentityKeyPair: IdentityKeyPair, pniIdentityKeyPair: IdentityKeyPair, ) {@@ -42,10 +45,10 @@ object PreKeyManager { Log.d(TAG, "Pre-key counts: aci=$aciCount, pni=$pniCount") if (aciCount < MIN_KEY_COUNT) {- uploadKeysForIdentity(ws, "aci", aciIdentityKeyPair)+ uploadKeysForIdentity(ws, preKeyStore, "aci", aciIdentityKeyPair) } if (pniCount < MIN_KEY_COUNT) {- uploadKeysForIdentity(ws, "pni", pniIdentityKeyPair)+ uploadKeysForIdentity(ws, preKeyStore, "pni", pniIdentityKeyPair) } } @@ -57,6 +60,7 @@ object PreKeyManager { private suspend fun uploadKeysForIdentity( ws: SignalWebSocket,+ preKeyStore: SignalPreKeyStore, identity: String, identityKeyPair: IdentityKeyPair, ) {@@ -67,17 +71,23 @@ object PreKeyManager { val preKeys = JSONArray().apply { for (i in 0 until BATCH_SIZE) { val kp = ECKeyPair.generate()+ val id = preKeyBase + i+ val record = PreKeyRecord(id, kp)+ preKeyStore.storePreKey(id, record) put(JSONObject().apply {- put("keyId", preKeyBase + i)+ put("keyId", id) put("publicKey", Base64.encodeToString(kp.publicKey.serialize(), Base64.NO_WRAP)) }) } } + val spkId = random.nextInt(Int.MAX_VALUE) val spkKeyPair = ECKeyPair.generate() val spkSignature = identityKeyPair.privateKey.calculateSignature(spkKeyPair.publicKey.serialize())+ val spkRecord = SignedPreKeyRecord(spkId, System.currentTimeMillis(), spkKeyPair, spkSignature)+ preKeyStore.storeSignedPreKey(spkId, spkRecord) val signedPreKey = JSONObject().apply {- put("keyId", random.nextInt(Int.MAX_VALUE))+ put("keyId", spkId) put("publicKey", Base64.encodeToString(spkKeyPair.publicKey.serialize(), Base64.NO_WRAP)) put("signature", Base64.encodeToString(spkSignature, Base64.NO_WRAP)) }@@ -86,8 +96,11 @@ object PreKeyManager { for (i in 0 until BATCH_SIZE) { val kemKp = KEMKeyPair.generate(KEMKeyType.KYBER_1024) val sig = identityKeyPair.privateKey.calculateSignature(kemKp.publicKey.serialize())+ val id = pqKeyBase + i+ val record = KyberPreKeyRecord(id, System.currentTimeMillis(), kemKp, sig)+ preKeyStore.storeKyberPreKey(id, record) put(JSONObject().apply {- put("keyId", pqKeyBase + i)+ put("keyId", id) put("publicKey", Base64.encodeToString(kemKp.publicKey.serialize(), Base64.NO_WRAP)) put("signature", Base64.encodeToString(sig, Base64.NO_WRAP)) })
messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt b/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.ktindex fff677a14c..fd44a8519c 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt@@ -6,7 +6,9 @@ import android.util.Base64 import android.util.Log import com.vayunmathur.messages.signal.proto.ProvisioningProtos import com.vayunmathur.messages.signal.proto.SignalServiceProtos+import com.vayunmathur.messages.signal.store.SignalDatabase import com.vayunmathur.messages.signal.store.SignalDeviceData+import com.vayunmathur.messages.signal.store.SignalPreKeyStore import com.vayunmathur.messages.signal.web.SignalHttpClient import com.vayunmathur.messages.signal.web.SignalWebSocket import kotlinx.coroutines.channels.Channel@@ -111,6 +113,14 @@ object Provisioning { val aciPqLastResort = generateKyberPreKey(1, aciIdentityKeyPair) val pniPqLastResort = generateKyberPreKey(1, pniIdentityKeyPair) + // Store generated keys in the local protocol stores+ val database = SignalDatabase.getInstance(context)+ val preKeyStore = SignalPreKeyStore(database)+ preKeyStore.storeSignedPreKey(aciSignedPreKey.id, aciSignedPreKey)+ preKeyStore.storeSignedPreKey(pniSignedPreKey.id, pniSignedPreKey)+ preKeyStore.storeLastResortKyberPreKey(aciPqLastResort.id, aciPqLastResort)+ preKeyStore.storeLastResortKyberPreKey(pniPqLastResort.id, pniPqLastResort)+ // Step 8: Encrypt device name val encryptedName = encryptDeviceName("Android", aciIdentityKeyPair.publicKey.publicKey)
messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.ktindex a21a7d9aaa..238d059fdb 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt@@ -15,6 +15,8 @@ import javax.crypto.spec.SecretKeySpec class GroupManager( private val ws: SignalWebSocket, private val groupStore: SignalGroupStore,+ private val aci: String,+ private val password: String, ) { data class SignalGroup( val groupId: String,@@ -28,7 +30,11 @@ class GroupManager( suspend fun fetchGroup(groupId: String, masterKey: ByteArray): SignalGroup? { return try {- val response = ws.sendRequest("GET", "/v1/groups/")+ val authHeader = GroupAuth.authHeader(aci, password)+ val response = ws.sendRequest(+ "GET", "/v1/groups",+ headers = mapOf("Authorization" to authHeader),+ ) if (response.status !in 200..299) return null val groupProto = Group.parseFrom(response.body)
messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.ktindex 7f5ad56624..3c1ec92d59 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt@@ -43,7 +43,7 @@ object AttachmentManager { val uploadResponse = SignalHttpClient.request( host = uploadUrl.substringAfter("://").substringBefore("/"), method = "PUT",- path = uploadUrl.substringAfter(uploadUrl.substringBefore("/", "/")),+ path = "/" + uploadUrl.substringAfter("://").substringAfter("/"), body = encrypted, contentType = contentType, )
messages/src/main/java/com/vayunmathur/messages/signal/store/SignalDatabase.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalDatabase.kt b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalDatabase.ktindex 698e11bb9b..d84c635a5c 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalDatabase.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalDatabase.kt@@ -183,6 +183,9 @@ interface SignalRecipientDao { @Query("SELECT * FROM signal_recipients WHERE profileName LIKE '%' || :query || '%' OR e164 LIKE '%' || :query || '%'") suspend fun search(query: String): List<SignalRecipientEntity>++ @Query("SELECT * FROM signal_recipients")+ suspend fun getAll(): List<SignalRecipientEntity> } @Dao
messages/src/main/java/com/vayunmathur/messages/signal/store/SignalIdentityKeyStore.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalIdentityKeyStore.kt b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalIdentityKeyStore.ktindex 03592ebe9d..ec405a10b5 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalIdentityKeyStore.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalIdentityKeyStore.kt@@ -26,7 +26,7 @@ class SignalIdentityKeyStore( SignalIdentityKeyEntity(address.name, identityKey.serialize(), true) ) }- return if (existing == null || !existing.identityKey.contentEquals(identityKey.serialize())) {+ return if (existing != null && !existing.identityKey.contentEquals(identityKey.serialize())) { IdentityKeyStore.IdentityChange.REPLACED_EXISTING } else { IdentityKeyStore.IdentityChange.NEW_OR_UNCHANGED
messages/src/main/java/com/vayunmathur/messages/signal/store/SignalRecipientStore.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalRecipientStore.kt b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalRecipientStore.ktindex 229d8a99a4..78f7df27c1 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalRecipientStore.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalRecipientStore.kt@@ -19,6 +19,6 @@ class SignalRecipientStore(private val db: SignalDatabase) { } suspend fun getAllRecipients(): List<SignalRecipientEntity> {- return db.recipientDao().search("")+ return db.recipientDao().getAll() } }
messages/src/main/java/com/vayunmathur/messages/telegram/TelegramClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/TelegramClient.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/TelegramClient.ktindex 19189c992f..c136839fd3 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/TelegramClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/TelegramClient.kt@@ -27,7 +27,6 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch-import kotlinx.coroutines.runBlocking import java.security.SecureRandom import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean@@ -79,7 +78,7 @@ object TelegramClient { if (!initialized.compareAndSet(false, true)) return appContext = context.applicationContext Log.i(TAG, "init")- runBlocking {+ scope.launch { val auth = TelegramAuthData.load(appContext) if (auth?.loggedIn == true && auth.authKey != null) { Log.i(TAG, "resuming from persisted session")@@ -106,9 +105,9 @@ object TelegramClient { updateJob?.cancel() scope.launch { runCatching { apiClient?.invoke(AuthLogOut) { TlRegistry.decode(it) } }+ apiClient?.disconnect()+ apiClient = null }- apiClient?.disconnect()- apiClient = null pendingPhone = null phoneCodeHash = null peerCache.clear()@@ -399,6 +398,7 @@ object TelegramClient { private suspend fun ensureClient(): TelegramApiClient { apiClient?.let { if (it.isConnected) return it } val client = TelegramApiClient()+ client.onDisconnected = { handleDisconnect() } client.connect() apiClient = client startUpdateListener(client)@@ -419,6 +419,7 @@ object TelegramClient { existingSessionId = null, ) apiClient = client+ client.onDisconnected = { handleDisconnect() } _state.value = State.Connected startUpdateListener(client) kickoffBackfill()@@ -456,6 +457,23 @@ object TelegramClient { } } + private fun handleDisconnect() {+ if (_state.value !is State.Connected) return+ _state.value = State.Disconnected("Connection lost")+ scope.launch {+ val client = apiClient ?: return@launch+ try {+ client.reconnect()+ _state.value = State.Connected+ startUpdateListener(client)+ kickoffBackfill()+ } catch (e: Exception) {+ Log.e(TAG, "Auto-reconnect failed: ${e.message}")+ _state.value = State.Disconnected("Reconnect failed: ${e.message}")+ }+ }+ }+ private suspend fun handleUpdate(update: TlObject) { when (update) { is Updates -> {@@ -517,7 +535,7 @@ object TelegramClient { } is UpdateDeleteMessages -> { for (id in update.messages) {- _events.emit(GMEvent.MessageDeleted(source, "_$id"))+ _events.emit(GMEvent.MessageDeleted(source, id.toString())) } currentPts = update.pts }@@ -681,7 +699,10 @@ object TelegramClient { peerCache[peer.chatId] = InputPeerChat(peer.chatId) } is PeerChannel -> {- // Needs access hash from channel, try cache+ val cached = peerCache[peer.channelId]+ if (cached is InputPeerChannel) {+ peerCache[peer.channelId] = cached+ } } } }
messages/src/main/java/com/vayunmathur/messages/telegram/api/TlRegistry.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/api/TlRegistry.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/api/TlRegistry.ktindex 47aa43a8df..6d743a80ab 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/api/TlRegistry.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/api/TlRegistry.kt@@ -54,8 +54,12 @@ object TlRegistry { 0xc776ba4e.toInt() -> decodeMessagesChannelMessages(buf) 0xb3134d9d.toInt() -> decodeContactsFound(buf) - // UpdatesState+ // UpdatesState / UpdatesDifference 0xa56c2a3e.toInt() -> UpdatesState.decode(buf)+ 0x00f49d37 -> decodeUpdatesDifference(buf)++ // Auth export/import+ 0xb434e2b8.toInt() -> AuthExportedAuthorization.decode(buf) else -> { Log.w(TAG, "Unknown type: 0x${typeId.toUInt().toString(16)}")@@ -242,6 +246,17 @@ object TlRegistry { val users = decodeVector(buf) { decodeUser(it) } return ContactsFound(myResults, results, chats, users) }++ private fun decodeUpdatesDifference(buf: TlBuffer): UpdatesDifference {+ val newMessages = decodeVector(buf) { decodeMessage(it) }+ val newEncryptedMessages = decodeVector(buf) { val id = it.int32(); decodeById(id, it) }+ val otherUpdates = decodeVector(buf) { val id = it.int32(); decodeById(id, it) }+ val chats = decodeVector(buf) { decodeChat(it) }+ val users = decodeVector(buf) { decodeUser(it) }+ val stateId = buf.int32() // UpdatesState constructor+ val state = UpdatesState.decode(buf)+ return UpdatesDifference(newMessages, newEncryptedMessages, otherUpdates, chats, users, state)+ } } data class UnknownObject(val actualTypeId: Int, val rawData: ByteArray) : TlObject {
messages/src/main/java/com/vayunmathur/messages/telegram/api/types/Messages.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/api/types/Messages.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/api/types/Messages.ktindex b054d77a14..e992441873 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/api/types/Messages.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/api/types/Messages.kt@@ -31,11 +31,26 @@ data class Message( TlSkip.skipMessageFwdHeader(buf) } if (flags.has(11)) buf.int64() // via_bot_id- if (flags.has(22)) buf.int64() // via_business_bot_id+ if (flags2.has(0)) buf.int64() // via_business_bot_id if (flags.has(3)) TlSkip.skipReplyTo(buf) // reply_to val date = buf.int32() val message = buf.string() val mediaTypeId = if (flags.has(9)) buf.peekId() else 0+ // Consume media and all remaining optional fields+ if (flags.has(9)) TlSkip.skipBoxedType(buf) // media+ if (flags.has(6)) TlSkip.skipReplyMarkup(buf) // reply_markup+ if (flags.has(7)) TlSkip.skipVector(buf) { TlSkip.skipMessageEntity(it) } // entities+ if (flags.has(10)) { buf.int32(); buf.int32() } // views, forwards+ if (flags.has(23)) TlSkip.skipMessageReplies(buf) // replies+ if (flags.has(15)) buf.int32() // edit_date+ if (flags.has(16)) buf.string() // post_author+ if (flags.has(17)) buf.int64() // grouped_id+ if (flags.has(20)) TlSkip.skipReactions(buf) // reactions+ if (flags.has(22)) TlSkip.skipVector(buf) { TlSkip.skipRestrictionReason(it) } // restriction_reason+ if (flags.has(25)) buf.int32() // ttl_period+ if (flags.has(30)) buf.int32() // quick_reply_shortcut_id+ if (flags2.has(2)) buf.int64() // effect+ if (flags2.has(3)) TlSkip.skipFactCheck(buf) // factcheck return Message(id, fromId, peerId, date, message, out, mediaTypeId) } }@@ -67,8 +82,10 @@ data class MessageService( val id = buf.int32() val fromId = if (flags.has(8)) decodePeer(buf) else null val peerId = decodePeer(buf)- if (flags.has(3)) { buf.int32(); buf.int32() }+ if (flags.has(3)) TlSkip.skipReplyTo(buf) // reply_to val date = buf.int32()+ TlSkip.skipMessageAction(buf) // action (mandatory)+ if (flags.has(25)) buf.int32() // ttl_period return MessageService(id, peerId, date, out) } }
messages/src/main/java/com/vayunmathur/messages/telegram/api/types/TlSkip.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/api/types/TlSkip.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/api/types/TlSkip.ktindex ded152a445..b148a3c3c3 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/api/types/TlSkip.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/api/types/TlSkip.kt@@ -1,10 +1,13 @@ package com.vayunmathur.messages.telegram.api.types +import android.util.Log import com.vayunmathur.messages.telegram.mtproto.tl.Fields import com.vayunmathur.messages.telegram.mtproto.tl.TlBuffer object TlSkip { + private const val TAG = "TlSkip"+ fun skipMessageFwdHeader(buf: TlBuffer) { val flags = Fields.decode(buf) if (flags.has(0)) decodePeer(buf) // from_id@@ -115,20 +118,85 @@ object TlSkip { private fun skipByTypeId(typeId: Int, buf: TlBuffer) { when (typeId) {+ // ---- MessageMedia ---- 0x3ded6320.toInt() -> {} // messageMediaEmpty 0x695150d7.toInt() -> { // messageMediaPhoto val flags = Fields.decode(buf) if (flags.has(0)) skipBoxedType(buf) // photo if (flags.has(2)) buf.int32() // ttl_seconds }- 0x56e0d474.toInt() -> { // messageMediaGeo- skipBoxedType(buf) // geo+ 0x4cf4d72d.toInt() -> { // messageMediaDocument+ val flags = Fields.decode(buf)+ if (flags.has(0)) skipBoxedType(buf) // document+ if (flags.has(5)) skipBoxedType(buf) // alt_document+ if (flags.has(9)) skipBoxedType(buf) // video_cover (Photo)+ if (flags.has(10)) buf.int32() // video_timestamp+ if (flags.has(2)) buf.int32() // ttl_seconds }+ 0x56e0d474.toInt() -> skipBoxedType(buf) // messageMediaGeo: geo 0x70322949.toInt() -> { // messageMediaContact buf.string(); buf.string(); buf.string(); buf.string(); buf.int64() }+ 0x9f84f49e.toInt() -> {} // messageMediaUnsupported+ 0x2ec0533f.toInt() -> { // messageMediaVenue+ skipBoxedType(buf) // geo+ buf.string(); buf.string(); buf.string(); buf.string(); buf.string()+ }+ 0xfdb19008.toInt() -> skipBoxedType(buf) // messageMediaGame: game+ 0x3f7ee58b.toInt() -> { buf.int32(); buf.string() } // messageMediaDice: value emoticon+ 0xddf10c3b.toInt() -> { // messageMediaWebPage+ Fields.decode(buf) // flags+ skipWebPage(buf)+ }++ // ---- Photo ----+ 0x2331b22d.toInt() -> buf.int64() // photoEmpty: id+ 0xfb197a65.toInt() -> { // photo+ val flags = Fields.decode(buf)+ buf.int64() // id+ buf.int64() // access_hash+ buf.bytes() // file_reference+ buf.int32() // date+ skipVector(buf) { skipPhotoSize(it) } // sizes+ if (flags.has(1)) skipVector(buf) { skipVideoSize(it) } // video_sizes+ buf.int32() // dc_id+ }++ // ---- GeoPoint ----+ 0x1117dd5f.toInt() -> {} // geoPointEmpty+ 0xb2a2f663.toInt() -> { // geoPoint+ val f = Fields.decode(buf)+ buf.double(); buf.double(); buf.int64() // long lat access_hash+ if (f.has(0)) buf.int32() // accuracy_radius+ }++ // ---- Document ----+ 0x36f8c871.toInt() -> buf.int64() // documentEmpty: id+ 0x8fd4c4d8.toInt() -> { // document+ val flags = Fields.decode(buf)+ buf.int64() // id+ buf.int64() // access_hash+ buf.bytes() // file_reference+ buf.int32() // date+ buf.string() // mime_type+ buf.int64() // size+ if (flags.has(0)) skipVector(buf) { skipPhotoSize(it) } // thumbs+ if (flags.has(1)) skipVector(buf) { skipVideoSize(it) } // video_thumbs+ buf.int32() // dc_id+ skipVector(buf) { skipDocumentAttribute(it) } // attributes+ }++ // ---- Game ----+ 0xbdf9653b.toInt() -> { // game+ val flags = Fields.decode(buf)+ buf.int64(); buf.int64() // id access_hash+ buf.string(); buf.string(); buf.string() // short_name title description+ skipBoxedType(buf) // photo+ if (flags.has(0)) skipBoxedType(buf) // document+ }+ else -> {- // For unknown types, consume remaining buffer cautiously+ Log.w(TAG, "skipByTypeId: unknown type 0x${typeId.toUInt().toString(16)}, buffer may be corrupted") } } }@@ -140,4 +208,351 @@ object TlSkip { skipBoxedType(buf) } }++ fun skipVector(buf: TlBuffer, elementSkip: (TlBuffer) -> Unit) {+ buf.int32() // vector constructor id+ val count = buf.int32()+ repeat(count) { elementSkip(buf) }+ }++ // ---- PhotoSize ----++ private fun skipPhotoSize(buf: TlBuffer) {+ val typeId = buf.int32()+ when (typeId) {+ 0xe17e23c0.toInt() -> buf.string() // photoSizeEmpty: type+ 0x75c78e60.toInt() -> { buf.string(); buf.int32(); buf.int32(); buf.int32() } // photoSize+ 0x021e1ad6.toInt() -> { buf.string(); buf.int32(); buf.int32(); buf.bytes() } // photoCachedSize+ 0xe0b0bc2e.toInt() -> { buf.string(); buf.bytes() } // photoStrippedSize+ 0xfa3efb95.toInt() -> { // photoSizeProgressive+ buf.string(); buf.int32(); buf.int32()+ val c = buf.int32(); buf.int32() // vector header+ repeat(c) { buf.int32() }+ }+ 0xd8214d41.toInt() -> { buf.string(); buf.bytes() } // photoPathSize+ else -> Log.w(TAG, "Unknown PhotoSize: 0x${typeId.toUInt().toString(16)}")+ }+ }++ private fun skipVideoSize(buf: TlBuffer) {+ val typeId = buf.int32()+ when (typeId) {+ 0xde33b094.toInt() -> { // videoSize+ val flags = Fields.decode(buf)+ buf.string(); buf.int32(); buf.int32(); buf.int32() // type w h size+ if (flags.has(0)) buf.double() // video_start_ts+ }+ 0x0f85c68f.toInt() -> { // videoSizeEmojiMarkup+ buf.int64() // emoji_id+ skipVector(buf) { it.int32() } // background_colors+ }+ 0x0da082fe.toInt() -> { // videoSizeStickerMarkup+ skipInputStickerSet(buf)+ buf.int64() // sticker_id+ skipVector(buf) { it.int32() } // background_colors+ }+ else -> Log.w(TAG, "Unknown VideoSize: 0x${typeId.toUInt().toString(16)}")+ }+ }++ // ---- DocumentAttribute ----++ private fun skipDocumentAttribute(buf: TlBuffer) {+ val typeId = buf.int32()+ when (typeId) {+ 0x6c37c15c.toInt() -> { buf.int32(); buf.int32() } // imageSize: w h+ 0x11b58939.toInt() -> {} // animated+ 0x6319d612.toInt() -> { // sticker+ val flags = Fields.decode(buf)+ buf.string() // alt+ skipInputStickerSet(buf)+ if (flags.has(0)) { // mask_coords+ buf.int32() // constructor+ buf.int32(); buf.double(); buf.double(); buf.double() // n x y zoom+ }+ }+ 0x17399fad.toInt() -> { // video+ val flags = Fields.decode(buf)+ buf.double(); buf.int32(); buf.int32() // duration w h+ if (flags.has(2)) buf.int32() // preload_prefix_size+ if (flags.has(4)) buf.double() // video_start_ts+ if (flags.has(5)) buf.string() // video_codec+ }+ 0x9852f9c6.toInt() -> { // audio+ val flags = Fields.decode(buf)+ buf.int32() // duration+ if (flags.has(0)) buf.string() // title+ if (flags.has(1)) buf.string() // performer+ if (flags.has(2)) buf.bytes() // waveform+ }+ 0x15590068.toInt() -> buf.string() // filename+ 0x9801d2f7.toInt() -> {} // hasStickers+ 0xfd149899.toInt() -> { // customEmoji+ Fields.decode(buf)+ buf.string() // alt+ skipInputStickerSet(buf)+ }+ else -> Log.w(TAG, "Unknown DocumentAttribute: 0x${typeId.toUInt().toString(16)}")+ }+ }++ private fun skipInputStickerSet(buf: TlBuffer) {+ val typeId = buf.int32()+ when (typeId) {+ 0xffb62b95.toInt() -> {} // empty+ 0x9de7a269.toInt() -> { buf.int64(); buf.int64() } // ID+ 0x861cc8a0.toInt() -> buf.string() // shortName+ 0xe67f520e.toInt() -> buf.string() // dice: emoticon+ else -> {} // most other variants are parameterless+ }+ }++ // ---- WebPage ----++ private fun skipWebPage(buf: TlBuffer) {+ val typeId = buf.int32()+ when (typeId) {+ 0x211a1788.toInt() -> buf.int64() // webPageEmpty: id+ 0xb0d13e47.toInt() -> { // webPagePending+ val flags = Fields.decode(buf)+ buf.int64() // id+ if (flags.has(0)) buf.string() // url+ buf.int32() // date+ }+ 0xe89c45b2.toInt() -> { // webPage+ val flags = Fields.decode(buf)+ buf.int64() // id+ buf.string() // url+ buf.string() // display_url+ buf.int32() // hash+ if (flags.has(0)) buf.string() // type+ if (flags.has(1)) buf.string() // site_name+ if (flags.has(2)) buf.string() // title+ if (flags.has(3)) buf.string() // description+ if (flags.has(4)) skipBoxedType(buf) // photo+ if (flags.has(5)) { buf.string(); buf.string() } // embed_url embed_type+ if (flags.has(6)) { buf.int32(); buf.int32() } // embed_width embed_height+ if (flags.has(7)) buf.int32() // duration+ if (flags.has(8)) buf.string() // author+ if (flags.has(9)) skipBoxedType(buf) // document+ if (flags.has(10)) {+ Log.w(TAG, "Skipping cached_page in webPage — complex type, may corrupt buffer")+ skipBoxedType(buf)+ }+ if (flags.has(12)) skipVectorBoxed(buf) // attributes+ }+ 0x7311ca11.toInt() -> {} // webPageNotModified (flags only if present)+ else -> Log.w(TAG, "Unknown WebPage: 0x${typeId.toUInt().toString(16)}")+ }+ }++ // ---- MessageEntity ----++ fun skipMessageEntity(buf: TlBuffer) {+ val typeId = buf.int32()+ when (typeId) {+ // Simple: offset length+ 0xbb92ba95.toInt(), // unknown+ 0xfa04579d.toInt(), // mention+ 0x6f635b0d.toInt(), // hashtag+ 0x6cef8ac7.toInt(), // botCommand+ 0x6ed02538.toInt(), // url+ 0x64e475c2.toInt(), // email+ 0xbd610bc9.toInt(), // bold+ 0x826f8b60.toInt(), // italic+ 0x28a20571.toInt(), // code+ 0x9b69e34b.toInt(), // phone+ 0x4c4e743f.toInt(), // cashtag+ 0x9c4e7e8b.toInt(), // underline+ 0xbf0693d4.toInt(), // strike+ 0x32ca960f.toInt(), // spoiler+ 0x761e6af4.toInt(), // bankCard+ -> { buf.int32(); buf.int32() }++ 0x73924be0.toInt() -> { buf.int32(); buf.int32(); buf.string() } // pre: offset length language+ 0x76a6d327.toInt() -> { buf.int32(); buf.int32(); buf.string() } // textUrl: offset length url+ 0xdc7b1140.toInt() -> { buf.int32(); buf.int32(); buf.int64() } // mentionName: offset length user_id+ 0xc8cf05f8.toInt() -> { buf.int32(); buf.int32(); buf.int64() } // customEmoji: offset length document_id+ 0xf1ccaaac.toInt() -> { Fields.decode(buf); buf.int32(); buf.int32() } // blockquote: flags offset length++ else -> {+ Log.w(TAG, "Unknown MessageEntity 0x${typeId.toUInt().toString(16)}, assuming offset+length")+ buf.int32(); buf.int32()+ }+ }+ }++ // ---- ReplyMarkup ----++ fun skipReplyMarkup(buf: TlBuffer) {+ val typeId = buf.int32()+ when (typeId) {+ 0xa03e5b85.toInt() -> Fields.decode(buf) // replyKeyboardHide+ 0x86b40b08.toInt() -> { // replyKeyboardForceReply+ val flags = Fields.decode(buf)+ if (flags.has(3)) buf.string() // placeholder+ }+ 0x85dd99d1.toInt() -> { // replyKeyboardMarkup+ val flags = Fields.decode(buf)+ skipVector(buf) { skipKeyboardButtonRow(it) }+ if (flags.has(3)) buf.string() // placeholder+ }+ 0x48a30254.toInt() -> { // replyInlineMarkup+ skipVector(buf) { skipKeyboardButtonRow(it) }+ }+ else -> Log.w(TAG, "Unknown ReplyMarkup: 0x${typeId.toUInt().toString(16)}")+ }+ }++ private fun skipKeyboardButtonRow(buf: TlBuffer) {+ buf.int32() // constructor 0x77608b83+ skipVector(buf) { skipKeyboardButton(it) }+ }++ private fun skipKeyboardButton(buf: TlBuffer) {+ val typeId = buf.int32()+ when (typeId) {+ 0xa2fa4880.toInt() -> buf.string() // keyboardButton: text+ 0x258aff05.toInt() -> { buf.string(); buf.string() } // keyboardButtonUrl: text url+ 0x35bbdb6b.toInt() -> { Fields.decode(buf); buf.string(); buf.bytes() } // callback: flags text data+ 0xb16a6c29.toInt() -> buf.string() // requestPhone: text+ 0xfc796b3f.toInt() -> buf.string() // requestGeoLocation: text+ 0x93b9fbb5.toInt() -> { // switchInline+ val flags = Fields.decode(buf)+ buf.string(); buf.string() // text query+ if (flags.has(1)) skipVectorBoxed(buf) // peer_types+ }+ 0x50f41ccf.toInt() -> buf.string() // game: text+ 0xafd93fbb.toInt() -> buf.string() // buy: text+ 0x10b78d29.toInt() -> { // urlAuth+ val flags = Fields.decode(buf)+ buf.string() // text+ if (flags.has(0)) buf.string() // fwd_text+ buf.string() // url+ buf.int32() // button_id+ }+ 0xbbc7515d.toInt() -> { // requestPoll+ val flags = Fields.decode(buf)+ if (flags.has(0)) buf.int32() // quiz Bool+ buf.string() // text+ }+ 0x13767230.toInt() -> { buf.string(); buf.string() } // webView: text url+ 0xa0c0505c.toInt() -> { buf.string(); buf.string() } // simpleWebView: text url+ 0x53d7bfd8.toInt() -> { // requestPeer+ buf.string(); buf.int32() // text button_id+ skipBoxedType(buf) // peer_type+ buf.int32() // max_quantity+ }+ else -> Log.w(TAG, "Unknown KeyboardButton: 0x${typeId.toUInt().toString(16)}")+ }+ }++ // ---- MessageReplies ----++ fun skipMessageReplies(buf: TlBuffer) {+ val typeId = buf.int32() // 0x83d60fc2+ val flags = Fields.decode(buf)+ buf.int32() // replies+ buf.int32() // replies_pts+ if (flags.has(1)) skipVector(buf) { decodePeer(it) } // recent_repliers+ if (flags.has(0)) buf.int64() // channel_id+ if (flags.has(2)) buf.int32() // max_id+ if (flags.has(3)) buf.int32() // read_max_id+ }++ // ---- Reactions ----++ fun skipReactions(buf: TlBuffer) {+ val typeId = buf.int32()+ if (typeId == 0x4f474992.toInt()) { // messageReactions+ val flags = Fields.decode(buf)+ skipVector(buf) { skipReactionCount(it) } // results+ if (flags.has(1)) skipVector(buf) { skipMessagePeerReaction(it) } // recent_reactions+ }+ }++ private fun skipReactionCount(buf: TlBuffer) {+ buf.int32() // constructor+ val flags = Fields.decode(buf)+ if (flags.has(0)) buf.int32() // chosen_order+ skipReaction(buf) // reaction+ buf.int32() // count+ }++ private fun skipReaction(buf: TlBuffer) {+ val typeId = buf.int32()+ when (typeId) {+ 0x1b2286b8.toInt() -> buf.string() // reactionEmoji: emoticon+ 0x8935fc73.toInt() -> buf.int64() // reactionCustomEmoji: document_id+ 0x79f5d419.toInt() -> {} // reactionEmpty+ 0x523f7fb5.toInt() -> {} // reactionPaid+ else -> Log.w(TAG, "Unknown Reaction: 0x${typeId.toUInt().toString(16)}")+ }+ }++ private fun skipMessagePeerReaction(buf: TlBuffer) {+ buf.int32() // constructor+ val flags = Fields.decode(buf)+ skipReaction(buf) // reaction+ buf.int32() // date+ decodePeer(buf) // peer_id+ }++ // ---- RestrictionReason ----++ fun skipRestrictionReason(buf: TlBuffer) {+ buf.int32() // constructor+ buf.string(); buf.string(); buf.string() // platform reason text+ }++ // ---- FactCheck ----++ fun skipFactCheck(buf: TlBuffer) {+ buf.int32() // constructor+ val flags = Fields.decode(buf)+ if (flags.has(1)) buf.string() // country+ if (flags.has(0)) { // text: TextWithEntities+ buf.int32() // TextWithEntities constructor+ buf.string() // text+ skipVector(buf) { skipMessageEntity(it) } // entities+ }+ buf.int64() // hash+ }++ // ---- MessageAction (for MessageService) ----++ fun skipMessageAction(buf: TlBuffer) {+ val typeId = buf.int32()+ when (typeId) {+ 0xb6aef7b0.toInt() -> {} // messageActionEmpty+ 0xbd47cbad.toInt() -> { // messageActionChatCreate+ buf.string() // title+ skipVector(buf) { it.int64() } // users+ }+ 0xb5a1ce5a.toInt() -> buf.string() // messageActionChatEditTitle+ 0x7fcb13a8.toInt() -> skipBoxedType(buf) // messageActionChatEditPhoto: photo+ 0x95e3fbef.toInt() -> {} // messageActionChatDeletePhoto+ 0x15cefd00.toInt() -> skipVector(buf) { it.int64() } // messageActionChatAddUser+ 0xa43f30cc.toInt() -> buf.int64() // messageActionChatDeleteUser+ 0x031224c3.toInt() -> buf.int64() // messageActionChatJoinedByLink: inviter_id+ 0x95d2ac92.toInt() -> buf.string() // messageActionChannelCreate: title+ 0xe1037f92.toInt() -> buf.int64() // messageActionChatMigrateTo: channel_id+ 0xea3948e9.toInt() -> { buf.string(); buf.int64() } // messageActionChannelMigrateFrom+ 0x94bd38ed.toInt() -> {} // messageActionPinMessage+ 0x9fbab604.toInt() -> {} // messageActionHistoryClear+ 0x80e11a7f.toInt() -> { // messageActionPhoneCall+ val flags = Fields.decode(buf)+ buf.int64() // call_id+ if (flags.has(0)) buf.int32() // reason (PhoneCallDiscardReason type id)+ if (flags.has(1)) buf.int32() // duration+ }+ 0xf3f25f76.toInt() -> {} // messageActionContactSignUp+ 0x3c134d7b.toInt() -> { // messageActionSetMessagesTTL+ val flags = Fields.decode(buf)+ buf.int32() // period+ if (flags.has(0)) buf.int64() // auto_setting_from+ }+ else -> Log.w(TAG, "Unknown MessageAction: 0x${typeId.toUInt().toString(16)}")+ }+ } }
messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/MtProtoConnection.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/MtProtoConnection.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/MtProtoConnection.ktindex 8f8959345f..b2ff0311b9 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/MtProtoConnection.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/MtProtoConnection.kt@@ -22,6 +22,7 @@ class MtProtoConnection( private val port: Int, private val dc: Int, private val onUpdate: suspend (TlObject) -> Unit,+ private val onDisconnected: (suspend () -> Unit)? = null, ) { private val TAG = "MtProtoConn" private val transport = TcpTransport()@@ -105,6 +106,7 @@ class MtProtoConnection( Log.e(TAG, "Read loop error: ${e.message}") connected = false rpcEngine.dropAll(e)+ onDisconnected?.let { scope?.launch { it() } } } } }@@ -159,8 +161,14 @@ class MtProtoConnection( buf.int32() val bss = MessageFraming.parseBadServerSalt(buf) salt = bss.newSalt- Log.d(TAG, "Updated server salt")- // Re-send the failed message is handled at RPC level+ Log.d(TAG, "Updated server salt, re-sending msgId=${bss.badMsgId}")+ rpcEngine.getPendingPayload(bss.badMsgId)?.let { payload ->+ try {+ send(payload, true)+ } catch (e: Exception) {+ Log.w(TAG, "Re-send after salt update failed: ${e.message}")+ }+ } } MessageFraming.TYPE_NEW_SESSION -> { buf.int32()
messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/TelegramApiClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/TelegramApiClient.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/TelegramApiClient.ktindex d9b4e98b15..8f7cedb2bf 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/TelegramApiClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/TelegramApiClient.kt@@ -1,6 +1,10 @@ package com.vayunmathur.messages.telegram.mtproto import android.util.Log+import com.vayunmathur.messages.telegram.api.TlRegistry+import com.vayunmathur.messages.telegram.api.functions.AuthExportAuthorization+import com.vayunmathur.messages.telegram.api.functions.AuthImportAuthorization+import com.vayunmathur.messages.telegram.api.types.AuthExportedAuthorization import com.vayunmathur.messages.telegram.mtproto.rpc.RpcException import com.vayunmathur.messages.telegram.mtproto.tl.TlBuffer import com.vayunmathur.messages.telegram.mtproto.tl.TlMethod@@ -9,6 +13,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow+import java.security.SecureRandom class TelegramApiClient { private val TAG = "TelegramApiClient"@@ -30,6 +35,8 @@ class TelegramApiClient { private set val isConnected: Boolean get() = connection?.connected == true + var onDisconnected: (suspend () -> Unit)? = null+ companion object { val DC_ADDRESSES = mapOf( 1 to ("149.154.175.53" to 443),@@ -44,12 +51,15 @@ class TelegramApiClient { currentDc = dc val (address, port) = DC_ADDRESSES[dc] ?: throw IllegalArgumentException("Unknown DC: $dc") - val conn = MtProtoConnection(address, port, dc) { update ->+ val conn = MtProtoConnection(address, port, dc, { update -> _updates.emit(update)- }+ }, {+ onDisconnected?.invoke()+ }) - if (existingAuthKey != null && existingAuthKeyId != null && existingSalt != null && existingSessionId != null) {- conn.setAuthData(existingAuthKey, existingAuthKeyId, existingSalt, existingSessionId)+ if (existingAuthKey != null && existingAuthKeyId != null && existingSalt != null) {+ val sid = existingSessionId ?: SecureRandom().nextLong()+ conn.setAuthData(existingAuthKey, existingAuthKeyId, existingSalt, sid) } conn.connect()@@ -68,8 +78,38 @@ class TelegramApiClient { if (isMigrateError(e.message)) { val newDc = extractMigrateDc(e.message) Log.i(TAG, "Migrating to DC $newDc")+ // Export auth from current DC before migrating+ var exportedAuth: AuthExportedAuthorization? = null+ try {+ exportedAuth = conn.rpcEngine.execute(+ AuthExportAuthorization(newDc),+ { data, _ -> conn.send(data, true) },+ { TlRegistry.decode(it) }+ ) as? AuthExportedAuthorization+ } catch (ex: Exception) {+ Log.w(TAG, "Auth export failed: ${ex.message}")+ } disconnect() connect(newDc)+ // Import auth into new DC+ if (exportedAuth != null) {+ try {+ val newConn = connection ?: throw IllegalStateException("Not connected after migration")+ newConn.rpcEngine.execute(+ AuthImportAuthorization(exportedAuth.id, exportedAuth.bytes),+ { data, _ -> newConn.send(data, true) },+ { TlRegistry.decode(it) }+ )+ } catch (ex: Exception) {+ Log.w(TAG, "Auth import failed: ${ex.message}")+ }+ }+ return invoke(method, decoder)+ }+ if (isFloodWait(e.message)) {+ val waitSeconds = extractFloodWaitDelay(e.message)+ Log.w(TAG, "FLOOD_WAIT: waiting ${waitSeconds}s")+ delay(waitSeconds * 1000L) return invoke(method, decoder) } throw e@@ -89,7 +129,7 @@ class TelegramApiClient { var backoff = 1000L for (attempt in 1..10) { try {- connect(currentDc, key, keyId, s, null)+ connect(currentDc, key, keyId, s) Log.i(TAG, "Reconnected on attempt $attempt") return } catch (e: Exception) {@@ -108,4 +148,12 @@ class TelegramApiClient { val regex = Regex("_(\\d+)$") return regex.find(msg)?.groupValues?.get(1)?.toIntOrNull() ?: currentDc }++ private fun isFloodWait(msg: String): Boolean =+ msg.contains("FLOOD_WAIT_") || msg.contains("FLOOD_PREMIUM_WAIT_")++ private fun extractFloodWaitDelay(msg: String): Int {+ val regex = Regex("FLOOD_(?:PREMIUM_)?WAIT_(\\d+)")+ return regex.find(msg)?.groupValues?.get(1)?.toIntOrNull() ?: 5+ } }
messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/rpc/RpcEngine.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/rpc/RpcEngine.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/rpc/RpcEngine.ktindex e807a849a8..1f72c0b6dd 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/rpc/RpcEngine.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/rpc/RpcEngine.kt@@ -24,6 +24,7 @@ class RpcEngine { val deferred = CompletableDeferred<TlBuffer>() val msgId = sendFn(buf.raw, 0) pending[msgId] = deferred+ payloads[msgId] = buf.raw return try { val result = withTimeout(30_000) { deferred.await() }@@ -35,6 +36,7 @@ class RpcEngine { } fun notifyResult(msgId: Long, buffer: TlBuffer) {+ payloads.remove(msgId) val deferred = pending.remove(msgId) if (deferred != null) { deferred.complete(buffer)@@ -44,6 +46,7 @@ class RpcEngine { } fun notifyError(msgId: Long, code: Int, message: String) {+ payloads.remove(msgId) val deferred = pending.remove(msgId) if (deferred != null) { deferred.completeExceptionally(RpcException(code, message))@@ -57,10 +60,19 @@ class RpcEngine { fun dropAll(error: Exception) { val entries = pending.entries.toList() pending.clear()+ payloads.clear() for ((_, deferred) in entries) { deferred.completeExceptionally(error) } } fun hasPending(msgId: Long): Boolean = pending.containsKey(msgId)++ private val payloads = ConcurrentHashMap<Long, ByteArray>()++ fun storePayload(msgId: Long, data: ByteArray) {+ payloads[msgId] = data+ }++ fun getPendingPayload(msgId: Long): ByteArray? = payloads.remove(msgId) }
messages/src/main/java/com/vayunmathur/messages/ui/ComposeScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/ComposeScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/ComposeScreen.ktindex 53af41c3c4..94a7c9bddf 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/ComposeScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/ComposeScreen.kt@@ -195,7 +195,7 @@ fun ComposeScreen( singleLine = true, shape = RoundedCornerShape(24.dp), )- LazyColumn(modifier = Modifier.weight(1f, fill = false)) {+ LazyColumn(modifier = Modifier.weight(1f)) { items(suggestions, key = { (it.phoneE164 ?: it.displayName) + "|" + (it.source?.name ?: "device") }) { sug -> SuggestionRow(sug) { selectedRecipient = sug@@ -217,64 +217,66 @@ fun ComposeScreen( } } - Spacer(Modifier.weight(1f))+ if (selectedRecipient != null) {+ Spacer(Modifier.weight(1f)) - // Compose row reuses the conversation-screen pattern.- ComposeRow(- draft = draft,- onDraftChange = { draft = it },- sending = sending,- onSend = {- val source = chosenSource- val recipient = selectedRecipient?.phoneE164 ?: query.trim().takeIf { it.isNotEmpty() }- when {- recipient == null -> scope.launch {- snackbar.showSnackbar("Pick a recipient first")- }- source == null -> scope.launch {- snackbar.showSnackbar("Choose a source (Voice or Messages)")- }- // Voice supports image MMS only. Anything else- // (video / audio / file) goes through gmessages- // only. We check the first attachment's mime to- // decide; mixed attachments are out of scope.- else -> scope.launch {- val mediaPart = media.firstOrNull()?.let { vm.readUri(it) }- if (source == MessageSource.VOICE &&- mediaPart != null &&- !mediaPart.mime.startsWith("image/")- ) {- snackbar.showSnackbar(- "Voice supports image MMS only — pick Messages, or remove the attachment."- )- return@launch+ // Compose row reuses the conversation-screen pattern.+ ComposeRow(+ draft = draft,+ onDraftChange = { draft = it },+ sending = sending,+ onSend = {+ val source = chosenSource+ val recipient = selectedRecipient?.phoneE164 ?: query.trim().takeIf { it.isNotEmpty() }+ when {+ recipient == null -> scope.launch {+ snackbar.showSnackbar("Pick a recipient first") }- sending = true- vm.sendNewMessage(- source = source,- recipients = listOf(recipient),- body = draft.trim().takeIf { it.isNotEmpty() },- media = mediaPart,- ) { newConvId ->- sending = false- if (newConvId == null) {- scope.launch { snackbar.showSnackbar("Send failed") }- } else {- backStack.pop()- backStack.add(Route.Conversation(newConvId))+ source == null -> scope.launch {+ snackbar.showSnackbar("Choose a source (Voice or Messages)")+ }+ // Voice supports image MMS only. Anything else+ // (video / audio / file) goes through gmessages+ // only. We check the first attachment's mime to+ // decide; mixed attachments are out of scope.+ else -> scope.launch {+ val mediaPart = media.firstOrNull()?.let { vm.readUri(it) }+ if (source == MessageSource.VOICE &&+ mediaPart != null &&+ !mediaPart.mime.startsWith("image/")+ ) {+ snackbar.showSnackbar(+ "Voice supports image MMS only — pick Messages, or remove the attachment."+ )+ return@launch+ }+ sending = true+ vm.sendNewMessage(+ source = source,+ recipients = listOf(recipient),+ body = draft.trim().takeIf { it.isNotEmpty() },+ media = mediaPart,+ ) { newConvId ->+ sending = false+ if (newConvId == null) {+ scope.launch { snackbar.showSnackbar("Send failed") }+ } else {+ backStack.pop()+ backStack.add(Route.Conversation(newConvId))+ } } } }- }- },- onAttach = {- pickImage.launch(- PickVisualMediaRequest(- ActivityResultContracts.PickVisualMedia.ImageAndVideo+ },+ onAttach = {+ pickImage.launch(+ PickVisualMediaRequest(+ ActivityResultContracts.PickVisualMedia.ImageAndVideo+ ) )- )- },- )+ },+ )+ } } } }
messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.ktindex e5cdbcf395..3bd2865966 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt@@ -195,7 +195,12 @@ fun ConversationScreen( // Fire a typing notification on each edit (gmessages // only — voice has no typing endpoint). Cheap: it's // a fire-and-forget on a coroutine.- if (conversation?.source == MessageSource.MESSAGES_WEB) {+ if (conversation?.source in setOf(+ MessageSource.MESSAGES_WEB,+ MessageSource.TELEGRAM,+ MessageSource.SIGNAL,+ )+ ) { vm.sendTyping(conversationId) } },@@ -243,7 +248,14 @@ fun ConversationScreen( // we feed it the chronological list REVERSED: newest first. val items = remember(messages) { buildItems(messages).asReversed() } val isGroup = conversation?.isGroup == true- val canReact = conversation?.source == MessageSource.MESSAGES_WEB+ val canReact = conversation?.source in setOf(+ MessageSource.MESSAGES_WEB,+ MessageSource.TELEGRAM,+ MessageSource.SIGNAL,+ MessageSource.WHATSAPP,+ MessageSource.MESSENGER,+ MessageSource.INSTAGRAM,+ ) LazyColumn( state = listState, reverseLayout = true,
messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.ktindex abdf370646..6b365111f3 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt@@ -110,6 +110,9 @@ fun InboxScreen( onSetupVoice = { backStack.add(Route.LoginVoice) }, onSetupTelegram = { backStack.add(Route.LoginTelegram) }, onSetupSignal = { backStack.add(Route.LoginSignal) },+ onSetupWhatsApp = { backStack.add(Route.LoginWhatsApp) },+ onSetupMessenger = { backStack.add(Route.LoginMessenger) },+ onSetupInstagram = { backStack.add(Route.LoginInstagram) }, ) if (conversations.isEmpty()) {@@ -157,6 +160,18 @@ fun InboxScreen( showSourcePicker = false backStack.add(Route.Compose(initialSource = MessageSource.SIGNAL.name)) }, modifier = Modifier.fillMaxWidth()) { Text("Signal") }+ androidx.compose.material3.TextButton(onClick = {+ showSourcePicker = false+ backStack.add(Route.Compose(initialSource = MessageSource.WHATSAPP.name))+ }, modifier = Modifier.fillMaxWidth()) { Text("WhatsApp") }+ androidx.compose.material3.TextButton(onClick = {+ showSourcePicker = false+ backStack.add(Route.Compose(initialSource = MessageSource.MESSENGER.name))+ }, modifier = Modifier.fillMaxWidth()) { Text("Messenger") }+ androidx.compose.material3.TextButton(onClick = {+ showSourcePicker = false+ backStack.add(Route.Compose(initialSource = MessageSource.INSTAGRAM.name))+ }, modifier = Modifier.fillMaxWidth()) { Text("Instagram") } } }, confirmButton = {},@@ -202,6 +217,9 @@ private fun SetupPrompts( onSetupVoice: () -> Unit, onSetupTelegram: () -> Unit, onSetupSignal: () -> Unit,+ onSetupWhatsApp: () -> Unit,+ onSetupMessenger: () -> Unit,+ onSetupInstagram: () -> Unit, ) { val msgsState = states[MessageSource.MESSAGES_WEB] if (msgsState is SourceConnectionState.NeedsSetup || msgsState is SourceConnectionState.Disconnected) {@@ -239,6 +257,33 @@ private fun SetupPrompts( onAction = onSetupSignal, ) }+ val whatsappState = states[MessageSource.WHATSAPP]+ if (whatsappState is SourceConnectionState.NeedsSetup || whatsappState is SourceConnectionState.Disconnected) {+ SetupCard(+ title = stringResource(R.string.inbox_setup_whatsapp_title),+ description = stringResource(R.string.inbox_setup_whatsapp_desc),+ actionLabel = stringResource(R.string.inbox_setup_whatsapp_action),+ onAction = onSetupWhatsApp,+ )+ }+ val messengerState = states[MessageSource.MESSENGER]+ if (messengerState is SourceConnectionState.NeedsSetup || messengerState is SourceConnectionState.Disconnected) {+ SetupCard(+ title = stringResource(R.string.inbox_setup_messenger_title),+ description = stringResource(R.string.inbox_setup_messenger_desc),+ actionLabel = stringResource(R.string.inbox_setup_messenger_action),+ onAction = onSetupMessenger,+ )+ }+ val instagramState = states[MessageSource.INSTAGRAM]+ if (instagramState is SourceConnectionState.NeedsSetup || instagramState is SourceConnectionState.Disconnected) {+ SetupCard(+ title = stringResource(R.string.inbox_setup_instagram_title),+ description = stringResource(R.string.inbox_setup_instagram_desc),+ actionLabel = stringResource(R.string.inbox_setup_instagram_action),+ onAction = onSetupInstagram,+ )+ } } @Composable
messages/src/main/java/com/vayunmathur/messages/util/MessagesService.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/MessagesService.kt b/messages/src/main/java/com/vayunmathur/messages/util/MessagesService.ktindex efde0cc4c3..ac51d64fa9 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesService.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesService.kt@@ -169,17 +169,23 @@ class MessagesService : Service() { } private fun describeStates(states: Map<MessageSource, SourceConnectionState>): String {- val msgsConnected = states[MessageSource.MESSAGES_WEB] is SourceConnectionState.Connected- val voiceConnected = states[MessageSource.VOICE] is SourceConnectionState.Connected- return when {- msgsConnected && voiceConnected ->- getString(R.string.notification_sync_text_both)- msgsConnected ->- getString(R.string.notification_sync_text_messages)- voiceConnected ->- getString(R.string.notification_sync_text_voice)- else ->- getString(R.string.notification_sync_text_none)+ val connected = states.entries+ .filter { it.value is SourceConnectionState.Connected }+ .map {+ when (it.key) {+ MessageSource.MESSAGES_WEB -> "Phone"+ MessageSource.VOICE -> "Voice"+ MessageSource.TELEGRAM -> "Telegram"+ MessageSource.SIGNAL -> "Signal"+ MessageSource.WHATSAPP -> "WhatsApp"+ MessageSource.MESSENGER -> "Messenger"+ MessageSource.INSTAGRAM -> "Instagram"+ }+ }+ return if (connected.isEmpty()) {+ getString(R.string.notification_sync_text_none)+ } else {+ "Connected to ${connected.joinToString(" + ")}" } }
messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.ktindex 3ccdf0bc31..b9b856149e 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt@@ -12,8 +12,11 @@ import com.vayunmathur.messages.data.buildMessagesDatabase import com.vayunmathur.messages.gmessages.GMEvent import com.vayunmathur.messages.gmessages.GMessagesClient import com.vayunmathur.messages.gvoice.GVoiceClient+import com.vayunmathur.messages.meta.InstagramClient+import com.vayunmathur.messages.meta.MetaClient import com.vayunmathur.messages.signal.SignalClient import com.vayunmathur.messages.telegram.TelegramClient+import com.vayunmathur.messages.whatsapp.WhatsAppClient import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -671,6 +674,33 @@ object MessagesSessionManager { collectorJobs += scope.launch { SignalClient.events.collect { handleEvent(it) } }+ collectorJobs += scope.launch {+ WhatsAppClient.state.collect { s ->+ _connectionStates.value =+ _connectionStates.value + (MessageSource.WHATSAPP to s.toUnified())+ }+ }+ collectorJobs += scope.launch {+ MetaClient.state.collect { s ->+ _connectionStates.value =+ _connectionStates.value + (MessageSource.MESSENGER to s.toUnified())+ }+ }+ collectorJobs += scope.launch {+ InstagramClient.state.collect { s ->+ _connectionStates.value =+ _connectionStates.value + (MessageSource.INSTAGRAM to s.toUnified())+ }+ }+ collectorJobs += scope.launch {+ WhatsAppClient.events.collect { handleEvent(it) }+ }+ collectorJobs += scope.launch {+ MetaClient.events.collect { handleEvent(it) }+ }+ collectorJobs += scope.launch {+ InstagramClient.events.collect { handleEvent(it) }+ } } private suspend fun handleEvent(event: GMEvent) {
messages/src/main/java/com/vayunmathur/messages/util/SourceConnectionState.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/SourceConnectionState.kt b/messages/src/main/java/com/vayunmathur/messages/util/SourceConnectionState.ktindex c852567526..aded467daa 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/SourceConnectionState.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/SourceConnectionState.kt@@ -2,8 +2,11 @@ package com.vayunmathur.messages.util import com.vayunmathur.messages.gmessages.GMessagesClient import com.vayunmathur.messages.gvoice.GVoiceClient+import com.vayunmathur.messages.meta.InstagramClient+import com.vayunmathur.messages.meta.MetaClient import com.vayunmathur.messages.signal.SignalClient import com.vayunmathur.messages.telegram.TelegramClient+import com.vayunmathur.messages.whatsapp.WhatsAppClient /** * Source-agnostic connection state.@@ -60,3 +63,28 @@ fun SignalClient.State.toUnified(): SourceConnectionState = when (this) { SignalClient.State.Connected -> SourceConnectionState.Connected is SignalClient.State.Disconnected -> SourceConnectionState.Disconnected(reason) }++fun WhatsAppClient.State.toUnified(): SourceConnectionState = when (this) {+ WhatsAppClient.State.Idle -> SourceConnectionState.Idle+ WhatsAppClient.State.NeedsSetup -> SourceConnectionState.NeedsSetup("Link device")+ is WhatsAppClient.State.AwaitingQrScan -> SourceConnectionState.Pairing(qrData)+ WhatsAppClient.State.Connecting -> SourceConnectionState.Connecting+ WhatsAppClient.State.Connected -> SourceConnectionState.Connected+ is WhatsAppClient.State.Disconnected -> SourceConnectionState.Disconnected(reason)+}++fun MetaClient.State.toUnified(): SourceConnectionState = when (this) {+ MetaClient.State.Idle -> SourceConnectionState.Idle+ MetaClient.State.NeedsSetup -> SourceConnectionState.NeedsSetup("Sign in")+ MetaClient.State.Connecting -> SourceConnectionState.Connecting+ MetaClient.State.Connected -> SourceConnectionState.Connected+ is MetaClient.State.Disconnected -> SourceConnectionState.Disconnected(reason)+}++fun InstagramClient.State.toUnified(): SourceConnectionState = when (this) {+ InstagramClient.State.Idle -> SourceConnectionState.Idle+ InstagramClient.State.NeedsSetup -> SourceConnectionState.NeedsSetup("Sign in")+ InstagramClient.State.Connecting -> SourceConnectionState.Connecting+ InstagramClient.State.Connected -> SourceConnectionState.Connected+ is InstagramClient.State.Disconnected -> SourceConnectionState.Disconnected(reason)+}
messages/src/main/java/com/vayunmathur/messages/whatsapp/WebViewWebSocket.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WebViewWebSocket.kt b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WebViewWebSocket.ktindex ff2c2a1b21..dcb529550c 100644--- a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WebViewWebSocket.kt+++ b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WebViewWebSocket.kt@@ -58,6 +58,7 @@ class WebViewWebSocket( private var handshakeJob: Job? = null private var ephemeralPrivateKey: ByteArray? = null private var ephemeralPublicKey: ByteArray? = null+ private var scriptInjected = false /** * JavaScript interface for communicating with WebView@@ -138,8 +139,10 @@ class WebViewWebSocket( override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url) Log.d(TAG, "WebView page finished loading: $url")- // Inject WebSocket JavaScript after page loads- injectWebSocketScript()+ if (!scriptInjected) {+ scriptInjected = true+ injectWebSocketScript()+ } } override fun onReceivedError(@@ -168,7 +171,6 @@ class WebViewWebSocket( "UTF-8", null )- loadUrl("about:blank") } Log.d(TAG, "WebView setup complete") }@@ -240,6 +242,7 @@ class WebViewWebSocket( } isConnected = false isHandshakeComplete = false+ scriptInjected = false noiseHandshake = null handshakeJob?.cancel() _connectionState.emit(ConnectionState.Disconnected("Client disconnect"))@@ -395,16 +398,42 @@ class WebViewWebSocket( Log.d(TAG, "Certificate decrypted (${certDecrypted.size} bytes), skipping verification for now") - // TODO: Send ClientFinish message- // For now, mark handshake as complete- // In full implementation, need to:- // 1. Encrypt client static public key- // 2. Mix shared secret with noise private key- // 3. Encrypt ClientPayload- // 4. Send ClientFinish protobuf- // 5. Call noiseHandshake.finish() to get final keys+ // Send ClientFinish (from whatsmeow/handshake.go lines 89-119)+ // 1. Encrypt client's noise static public key+ val noiseKeyPair = authData?.let {+ WhatsAppProtocol.generateX25519KeyPair()+ } ?: WhatsAppProtocol.generateX25519KeyPair()+ val (noisePriv, noisePub) = noiseKeyPair+ + val encryptedPubkey = handshake.encrypt(noisePub)+ + // 2. Mix shared secret: noise private key × server ephemeral+ handshake.mixSharedSecretIntoKey(noisePriv, serverEphemeral)+ + // 3. Build and encrypt ClientPayload+ // For a new device pairing, we send a minimal companion payload+ val clientPayloadBytes = buildClientPayload()+ val encryptedPayload = handshake.encrypt(clientPayloadBytes)+ + // 4. Build and send ClientFinish HandshakeMessage+ val clientFinishMessage = com.vayunmathur.messages.whatsapp.proto.WhatsAppHandshakeProto.HandshakeMessage.newBuilder()+ .setClientFinish(+ com.vayunmathur.messages.whatsapp.proto.WhatsAppHandshakeProto.HandshakeMessage.ClientFinish.newBuilder()+ .setStatic(com.google.protobuf.ByteString.copyFrom(encryptedPubkey))+ .setPayload(com.google.protobuf.ByteString.copyFrom(encryptedPayload))+ .build()+ )+ .build()+ val clientFinishBytes = clientFinishMessage.toByteArray()+ val framedFinish = buildFramedMessage(clientFinishBytes, null)+ sendRaw(framedFinish) - Log.i(TAG, "Handshake processed (partial implementation), marking as complete")+ Log.i(TAG, "Sent ClientFinish (${clientFinishBytes.size} bytes)")+ + // 5. Derive final encryption keys+ val (writeKey, readKey) = handshake.finish()+ + Log.i(TAG, "Noise handshake complete, derived read/write keys") isHandshakeComplete = true isConnected = true scope.launch {@@ -420,6 +449,13 @@ class WebViewWebSocket( } } + private fun buildClientPayload(): ByteArray {+ // Minimal companion device registration payload+ // In production, this should be a proper ClientPayload protobuf+ // For now, return an empty payload which the server will process for pairing+ return ByteArray(0)+ }+ private fun buildFramedMessage(data: ByteArray, header: ByteArray?): ByteArray { val headerLength = header?.size ?: 0 val dataLength = data.size@@ -442,7 +478,6 @@ class WebViewWebSocket( } private fun sendRaw(data: ByteArray): Boolean {- if (!isConnected) return false return try { val base64 = Base64.encodeToString(data, Base64.NO_WRAP) val js = """
messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.ktindex 07f4e0d6f3..96a3a4b56b 100644--- a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt@@ -9,8 +9,7 @@ import com.vayunmathur.messages.util.ContactSuggestion import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.delay+import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow@@ -105,36 +104,53 @@ object WhatsAppClient { qrJob?.cancel() qrJob = scope.launch { try {- // Generate QR code data for WhatsApp Web pairing- val ref = generateRef()- val publicKey = generatePublicKey()- val clientId = generateClientId()-- val qrData = "$ref,$publicKey,$clientId"+ // 1. Generate real X25519 key pairs for Noise and identity+ val (noisePriv, noisePub) = WhatsAppProtocol.generateX25519KeyPair()+ val (identityPriv, identityPub) = WhatsAppProtocol.generateX25519KeyPair()+ val advSecretKey = ByteArray(32).apply { random.nextBytes(this) }+ + // 2. Connect WebSocket and wait for Noise handshake to complete+ webSocket = WebViewWebSocket(appContext, null).apply {+ val ws = this+ scope.launch {+ connectionState.collect { connState ->+ when (connState) {+ is WebViewWebSocket.ConnectionState.Connected -> {+ Log.i(TAG, "WebSocket connected, waiting for ref from server")+ }+ is WebViewWebSocket.ConnectionState.Disconnected -> {+ if (_state.value is State.AwaitingQrScan || _state.value is State.Connecting) {+ _state.value = State.Disconnected(connState.reason)+ }+ }+ else -> {}+ }+ }+ }+ + scope.launch {+ messages.collect { data ->+ handleProvisioningMessage(data, noisePub, identityPub, advSecretKey)+ }+ }+ + connect()+ }+ + // 3. Generate QR data with real keys+ // Format: ref,base64(noisePublicKey),base64(identityPublicKey),base64(advSecretKey)+ // Use a placeholder ref until the server sends one+ val refBytes = ByteArray(16).apply { random.nextBytes(this) }+ val ref = Base64.encodeToString(refBytes, Base64.NO_WRAP)+ val qrData = listOf(+ ref,+ Base64.encodeToString(noisePub, Base64.NO_WRAP),+ Base64.encodeToString(identityPub, Base64.NO_WRAP),+ Base64.encodeToString(advSecretKey, Base64.NO_WRAP)+ ).joinToString(",") _state.value = State.AwaitingQrScan(qrData)-- // Poll for successful pairing- // In a real implementation, this would wait for the phone to scan the QR- // and complete the Noise protocol handshake- delay(30000) // Simulate waiting for scan-- // For now, simulate successful pairing- // Real implementation would receive keys from the phone via the handshake- val simulatedAuth = WhatsAppAuthData(- deviceId = clientId,- phoneNumber = "+1234567890",- pushName = "User",- clientId = clientId,- serverToken = generateToken(),- clientToken = generateToken(),- encKey = Base64.encodeToString(ByteArray(32).apply { random.nextBytes(this) }, Base64.NO_WRAP),- macKey = Base64.encodeToString(ByteArray(32).apply { random.nextBytes(this) }, Base64.NO_WRAP),- wid = "[email protected]"- )-- WhatsAppAuthData.save(appContext, simulatedAuth)- authData = simulatedAuth- connect(simulatedAuth)+ + Log.i(TAG, "QR code generated, waiting for phone to scan") } catch (e: Exception) { Log.e(TAG, "Provisioning failed", e)@@ -142,6 +158,42 @@ object WhatsAppClient { } } }+ + private fun handleProvisioningMessage(+ data: ByteArray,+ noisePub: ByteArray,+ identityPub: ByteArray,+ advSecretKey: ByteArray,+ ) {+ scope.launch {+ try {+ val node = WhatsAppProtocol.decodeNode(data)+ Log.d(TAG, "Provisioning message: tag=${node.tag}")+ + if (node.tag == "success") {+ // Phone scanned QR and server confirmed pairing+ val wid = node.attrs["wid"] ?: ""+ val auth = WhatsAppAuthData(+ deviceId = Base64.encodeToString(ByteArray(16).apply { random.nextBytes(this) }, Base64.NO_WRAP),+ phoneNumber = wid.substringBefore("@"),+ pushName = node.attrs["pushname"] ?: "User",+ clientId = Base64.encodeToString(noisePub.copyOfRange(0, 16), Base64.NO_WRAP),+ serverToken = node.attrs["server_token"] ?: "",+ clientToken = node.attrs["client_token"] ?: "",+ encKey = Base64.encodeToString(advSecretKey, Base64.NO_WRAP),+ macKey = Base64.encodeToString(identityPub, Base64.NO_WRAP),+ wid = wid+ )+ WhatsAppAuthData.save(appContext, auth)+ authData = auth+ _state.value = State.Connected+ kickoffBackfill()+ }+ } catch (e: Exception) {+ Log.e(TAG, "Failed to handle provisioning message", e)+ }+ }+ } private suspend fun connect(auth: WhatsAppAuthData) { _state.value = State.Connecting@@ -269,12 +321,6 @@ object WhatsAppClient { return Base64.encodeToString(bytes, Base64.NO_WRAP) } - private fun generatePublicKey(): String {- val bytes = ByteArray(32)- random.nextBytes(bytes)- return Base64.encodeToString(bytes, Base64.NO_WRAP)- }- private fun generateClientId(): String { val bytes = ByteArray(16) random.nextBytes(bytes)
messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.ktindex c9865cda96..b5f9a0cd19 100644--- a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt+++ b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt@@ -1,10 +1,6 @@ package com.vayunmathur.messages.whatsapp -import android.util.Base64 import android.util.Log-import kotlinx.serialization.Serializable-import kotlinx.serialization.encodeToString-import kotlinx.serialization.json.Json as KotlinJson import java.nio.ByteBuffer import java.nio.ByteOrder import java.security.MessageDigest@@ -48,12 +44,10 @@ object WhatsAppProtocol { /** * Noise protocol handshake message. */- @Serializable data class HandshakeMessage( val clientHello: ClientHello, ) - @Serializable data class ClientHello( val ephemeral: String, // Base64 encoded public key val static: String?, // Base64 encoded static key (optional)@@ -287,40 +281,374 @@ object WhatsAppProtocol { } /**- * Encode node to binary format.- * Simplified implementation - full binary protocol is complex.+ * WhatsApp binary XML token constants.+ * From whatsmeow/binary/token/token.go */- fun encodeNode(node: Node): ByteArray {- // Simplified JSON-based encoding for initial implementation- // Full binary protocol requires implementing WhatsApp's binary XML format- val json = KotlinJson.encodeToString(node.toMap())- return json.toByteArray(Charsets.UTF_8)+ private object BinaryToken {+ const val LIST_EMPTY: Byte = 0+ const val DICTIONARY_0: Int = 236+ const val DICTIONARY_1: Int = 237+ const val DICTIONARY_2: Int = 238+ const val DICTIONARY_3: Int = 239+ const val LIST_8: Byte = 248.toByte()+ const val LIST_16: Byte = 249.toByte()+ const val JID_PAIR: Byte = 250.toByte()+ const val HEX_8: Int = 251+ const val BINARY_8: Byte = 252.toByte()+ const val BINARY_20: Byte = 253.toByte()+ const val BINARY_32: Byte = 254.toByte()+ const val NIBBLE_8: Int = 255+ const val PACKED_MAX = 127+ const val SINGLE_BYTE_MAX = 256++ val singleByteTokens = arrayOf("", "xmlstreamstart", "xmlstreamend", "s.whatsapp.net", "type", "participant", "from", "receipt", "id", "notification", "disappearing_mode", "status", "jid", "broadcast", "user", "devices", "device_hash", "to", "offline", "message", "result", "class", "xmlns", "duration", "notify", "iq", "t", "ack", "g.us", "enc", "urn:xmpp:whatsapp:push", "presence", "config_value", "picture", "verified_name", "config_code", "key-index-list", "contact", "mediatype", "routing_info", "edge_routing", "get", "read", "urn:xmpp:ping", "fallback_hostname", "0", "chatstate", "business_hours_config", "unavailable", "download_buckets", "skmsg", "verified_level", "composing", "handshake", "device-list", "media", "text", "fallback_ip4", "media_conn", "device", "creation", "location", "config", "item", "fallback_ip6", "count", "w:profile:picture", "image", "business", "2", "hostname", "call-creator", "display_name", "relaylatency", "platform", "abprops", "success", "msg", "offline_preview", "prop", "key-index", "v", "day_of_week", "pkmsg", "version", "1", "ping", "w:p", "download", "video", "set", "specific_hours", "props", "primary", "unknown", "hash", "commerce_experience", "last", "subscribe", "max_buckets", "call", "profile", "member_since_text", "close_time", "call-id", "sticker", "mode", "participants", "value", "query", "profile_options", "open_time", "code", "list", "host", "ts", "contacts", "upload", "lid", "preview", "update", "usync", "w:stats", "delivery", "auth_ttl", "context", "fail", "cart_enabled", "appdata", "category", "atn", "direct_connection", "decrypt-fail", "relay_id", "mmg-fallback.whatsapp.net", "target", "available", "name", "last_id", "mmg.whatsapp.net", "categories", "401", "is_new", "index", "tctoken", "ip4", "token_id", "latency", "recipient", "edit", "ip6", "add", "thumbnail-document", "26", "paused", "true", "identity", "stream:error", "key", "sidelist", "background", "audio", "3", "thumbnail-image", "biz-cover-photo", "cat", "gcm", "thumbnail-video", "error", "auth", "deny", "serial", "in", "registration", "thumbnail-link", "remove", "00", "gif", "thumbnail-gif", "tag", "capability", "multicast", "item-not-found", "description", "business_hours", "config_expo_key", "md-app-state", "expiration", "fallback", "ttl", "300", "md-msg-hist", "device_orientation", "out", "w:m", "open_24h", "side_list", "token", "inactive", "01", "document", "te2", "played", "encrypt", "msgr", "hide", "direct_path", "12", "state", "not-authorized", "url", "terminate", "signature", "status-revoke-delay", "02", "te", "linked_accounts", "trusted_contact", "timezone", "ptt", "kyc-id", "privacy_token", "readreceipts", "appointment_only", "address", "expected_ts", "privacy", "7", "android", "interactive", "device-identity", "enabled", "attribute_padding", "1080", "03", "screen_height")++ private val singleByteIndex: Map<String, Byte> by lazy {+ val map = HashMap<String, Byte>(singleByteTokens.size)+ for (i in singleByteTokens.indices) {+ if (singleByteTokens[i].isNotEmpty()) {+ map[singleByteTokens[i]] = i.toByte()+ }+ }+ map+ }++ fun indexOfSingleToken(token: String): Int {+ return singleByteIndex[token]?.toInt()?.and(0xFF) ?: -1+ } } /**- * Decode binary data to node.+ * Binary XML encoder — encodes Nodes to WhatsApp binary wire format.+ * From whatsmeow/binary/encoder.go */- fun decodeNode(data: ByteArray): Node {- val json = String(data, Charsets.UTF_8)- val map = KotlinJson.decodeFromString<Map<String, Any>>(json)- return map.toNode()+ private class BinaryEncoder {+ private val data = mutableListOf<Byte>(0) // starts with 0 flag byte++ fun getData(): ByteArray = data.toByteArray()++ private fun pushByte(b: Byte) { data.add(b) }+ private fun pushByte(b: Int) { data.add(b.toByte()) }+ private fun pushBytes(bytes: ByteArray) { bytes.forEach { data.add(it) } }++ private fun pushInt8(value: Int) {+ pushByte((value and 0xFF).toByte())+ }++ private fun pushInt16(value: Int) {+ pushByte((value shr 8 and 0xFF).toByte())+ pushByte((value and 0xFF).toByte())+ }++ private fun pushInt20(value: Int) {+ pushByte(((value shr 16) and 0x0F).toByte())+ pushByte(((value shr 8) and 0xFF).toByte())+ pushByte((value and 0xFF).toByte())+ }++ private fun pushInt32(value: Int) {+ pushByte((value shr 24 and 0xFF).toByte())+ pushByte((value shr 16 and 0xFF).toByte())+ pushByte((value shr 8 and 0xFF).toByte())+ pushByte((value and 0xFF).toByte())+ }++ private fun writeByteLength(length: Int) {+ when {+ length < 256 -> { pushByte(BinaryToken.BINARY_8); pushInt8(length) }+ length < (1 shl 20) -> { pushByte(BinaryToken.BINARY_20); pushInt20(length) }+ else -> { pushByte(BinaryToken.BINARY_32); pushInt32(length) }+ }+ }++ fun writeNode(n: Node) {+ if (n.tag == "0") {+ pushByte(BinaryToken.LIST_8)+ pushByte(BinaryToken.LIST_EMPTY)+ return+ }++ val hasContent = if (n.data != null || n.content.isNotEmpty()) 1 else 0+ val attrCount = n.attrs.count { it.value.isNotEmpty() }+ writeListStart(2 * attrCount + 1 + hasContent)+ writeString(n.tag)+ writeAttributes(n.attrs)+ if (n.data != null) {+ writeBytes(n.data)+ } else if (n.content.isNotEmpty()) {+ writeListStart(n.content.size)+ for (child in n.content) {+ writeNode(child)+ }+ }+ }++ private fun writeString(value: String) {+ val tokenIndex = BinaryToken.indexOfSingleToken(value)+ if (tokenIndex >= 0) {+ pushByte(tokenIndex)+ } else if (validateNibble(value)) {+ writePackedBytes(value, BinaryToken.NIBBLE_8)+ } else if (validateHex(value)) {+ writePackedBytes(value, BinaryToken.HEX_8)+ } else {+ writeStringRaw(value)+ }+ }++ private fun writeBytes(value: ByteArray) {+ writeByteLength(value.size)+ pushBytes(value)+ }++ private fun writeStringRaw(value: String) {+ val bytes = value.toByteArray(Charsets.UTF_8)+ writeByteLength(bytes.size)+ pushBytes(bytes)+ }++ private fun writeAttributes(attrs: Map<String, String>) {+ for ((key, value) in attrs) {+ if (value.isEmpty()) continue+ writeString(key)+ writeString(value)+ }+ }++ private fun writeListStart(size: Int) {+ when {+ size == 0 -> pushByte(BinaryToken.LIST_EMPTY)+ size < 256 -> { pushByte(BinaryToken.LIST_8); pushInt8(size) }+ else -> { pushByte(BinaryToken.LIST_16); pushInt16(size) }+ }+ }++ private fun validateNibble(value: String): Boolean {+ if (value.length > BinaryToken.PACKED_MAX) return false+ return value.all { it in '0'..'9' || it == '-' || it == '.' }+ }++ private fun validateHex(value: String): Boolean {+ if (value.length > BinaryToken.PACKED_MAX) return false+ return value.all { it in '0'..'9' || it in 'A'..'F' }+ }++ private fun writePackedBytes(value: String, dataType: Int) {+ pushByte(dataType)+ val roundedLength = ((value.length + 1) / 2)+ val flag = if (value.length % 2 != 0) (roundedLength or 128) else roundedLength+ pushByte(flag)+ val packer = if (dataType == BinaryToken.NIBBLE_8) ::packNibble else ::packHex+ var i = 0+ while (i < value.length / 2) {+ pushByte(((packer(value[2 * i]) shl 4) or packer(value[2 * i + 1])).toByte())+ i+++ }+ if (value.length % 2 != 0) {+ pushByte(((packer(value.last()) shl 4) or packer('\u0000')).toByte())+ }+ }++ private fun packNibble(c: Char): Int = when (c) {+ in '0'..'9' -> c - '0'+ '-' -> 10+ '.' -> 11+ '\u0000' -> 15+ else -> throw IllegalArgumentException("Invalid nibble char: $c")+ }++ private fun packHex(c: Char): Int = when (c) {+ in '0'..'9' -> c - '0'+ in 'A'..'F' -> 10 + (c - 'A')+ '\u0000' -> 15+ else -> throw IllegalArgumentException("Invalid hex char: $c")+ }+ }++ /**+ * Binary XML decoder — decodes WhatsApp binary wire format to Nodes.+ * From whatsmeow/binary/decoder.go+ */+ private class BinaryDecoder(private val data: ByteArray) {+ private var index = 0++ private fun checkEOS(length: Int) {+ if (index + length > data.size) throw IllegalStateException("End of stream")+ }++ private fun readByte(): Int {+ checkEOS(1)+ return data[index++].toInt() and 0xFF+ }++ private fun readInt8(): Int = readByte()++ private fun readInt16(): Int {+ checkEOS(2)+ val v = ((data[index].toInt() and 0xFF) shl 8) or (data[index + 1].toInt() and 0xFF)+ index += 2+ return v+ }++ private fun readInt20(): Int {+ checkEOS(3)+ val v = ((data[index].toInt() and 0x0F) shl 16) or+ ((data[index + 1].toInt() and 0xFF) shl 8) or+ (data[index + 2].toInt() and 0xFF)+ index += 3+ return v+ }++ private fun readInt32(): Int {+ checkEOS(4)+ val v = ((data[index].toInt() and 0xFF) shl 24) or+ ((data[index + 1].toInt() and 0xFF) shl 16) or+ ((data[index + 2].toInt() and 0xFF) shl 8) or+ (data[index + 3].toInt() and 0xFF)+ index += 4+ return v+ }++ private fun readRaw(length: Int): ByteArray {+ checkEOS(length)+ val result = data.copyOfRange(index, index + length)+ index += length+ return result+ }++ private fun readPacked8(tag: Int): String {+ val startByte = readByte()+ val sb = StringBuilder()+ for (i in 0 until (startByte and 127)) {+ val currByte = readByte()+ sb.append(unpackByte(tag, (currByte shr 4) and 0x0F))+ sb.append(unpackByte(tag, currByte and 0x0F))+ }+ var result = sb.toString()+ if ((startByte shr 7) != 0) {+ result = result.dropLast(1)+ }+ return result+ }++ private fun unpackByte(tag: Int, value: Int): Char = when (tag) {+ BinaryToken.NIBBLE_8 -> unpackNibble(value)+ BinaryToken.HEX_8 -> unpackHex(value)+ else -> throw IllegalArgumentException("Unknown packed tag: $tag")+ }++ private fun unpackNibble(value: Int): Char = when {+ value < 10 -> ('0' + value)+ value == 10 -> '-'+ value == 11 -> '.'+ value == 15 -> '\u0000'+ else -> throw IllegalArgumentException("Invalid nibble: $value")+ }++ private fun unpackHex(value: Int): Char = when {+ value < 10 -> ('0' + value)+ value < 16 -> ('A' + value - 10)+ else -> throw IllegalArgumentException("Invalid hex: $value")+ }++ private fun readListSize(tag: Int): Int = when (tag) {+ BinaryToken.LIST_EMPTY.toInt() and 0xFF -> 0+ BinaryToken.LIST_8.toInt() and 0xFF -> readInt8()+ BinaryToken.LIST_16.toInt() and 0xFF -> readInt16()+ else -> throw IllegalArgumentException("Unknown list tag: $tag")+ }++ private fun read(asString: Boolean): Any? {+ val tag = readByte()+ return when (tag) {+ BinaryToken.LIST_EMPTY.toInt() and 0xFF -> null+ BinaryToken.LIST_8.toInt() and 0xFF,+ BinaryToken.LIST_16.toInt() and 0xFF -> readList(tag)+ BinaryToken.BINARY_8.toInt() and 0xFF -> {+ val size = readInt8()+ if (asString) String(readRaw(size), Charsets.UTF_8) else readRaw(size)+ }+ BinaryToken.BINARY_20.toInt() and 0xFF -> {+ val size = readInt20()+ if (asString) String(readRaw(size), Charsets.UTF_8) else readRaw(size)+ }+ BinaryToken.BINARY_32.toInt() and 0xFF -> {+ val size = readInt32()+ if (asString) String(readRaw(size), Charsets.UTF_8) else readRaw(size)+ }+ in BinaryToken.DICTIONARY_0..BinaryToken.DICTIONARY_3 -> {+ // Double byte token — skip for now, return placeholder+ val idx = readInt8()+ "dict_${tag - BinaryToken.DICTIONARY_0}_$idx"+ }+ BinaryToken.JID_PAIR.toInt() and 0xFF -> {+ val user = read(true) as? String+ val server = read(true) as? String ?: throw IllegalStateException("JID missing server")+ if (user != null) "$user@$server" else "@$server"+ }+ BinaryToken.NIBBLE_8, BinaryToken.HEX_8 -> readPacked8(tag)+ else -> {+ if (tag in 1 until BinaryToken.singleByteTokens.size) {+ BinaryToken.singleByteTokens[tag]+ } else {+ throw IllegalArgumentException("Invalid token $tag at position $index")+ }+ }+ }+ }++ private fun readList(tag: Int): List<Node> {+ val size = readListSize(tag)+ return (0 until size).map { readNode() }+ }++ fun readNode(): Node {+ val listTag = readInt8()+ val listSize = readListSize(listTag)+ val tag = read(true) as? String ?: throw IllegalStateException("Node tag is not a string")+ if (listSize == 0 || tag.isEmpty()) throw IllegalStateException("Invalid node")++ val attrCount = (listSize - 1) shr 1+ val attrs = mutableMapOf<String, String>()+ for (i in 0 until attrCount) {+ val key = read(true) as? String ?: continue+ val value = read(true)+ attrs[key] = value?.toString() ?: ""+ }++ val content = mutableListOf<Node>()+ var nodeData: ByteArray? = null+ if (listSize % 2 == 0) {+ val contentData = read(false)+ when (contentData) {+ is List<*> -> {+ @Suppress("UNCHECKED_CAST")+ content.addAll(contentData as List<Node>)+ }+ is ByteArray -> nodeData = contentData+ is String -> nodeData = contentData.toByteArray(Charsets.UTF_8)+ }+ }++ return Node(tag, attrs, content, nodeData)+ } } - private fun Node.toMap(): Map<String, Any> {- val map = mutableMapOf<String, Any>()- map["tag"] = tag- if (attrs.isNotEmpty()) map["attrs"] = attrs- if (content.isNotEmpty()) map["content"] = content.map { it.toMap() }- data?.let { map["data"] = Base64.encodeToString(it, Base64.NO_WRAP) }- return map+ /**+ * Encode node to WhatsApp binary XML format.+ */+ fun encodeNode(node: Node): ByteArray {+ val encoder = BinaryEncoder()+ encoder.writeNode(node)+ return encoder.getData() } - private fun Map<String, Any>.toNode(): Node {- val tag = this["tag"] as String- val attrs = (this["attrs"] as? Map<String, String>) ?: emptyMap()- val content = (this["content"] as? List<Map<String, Any>>)?.map { it.toNode() } ?: emptyList()- val data = (this["data"] as? String)?.let { Base64.decode(it, Base64.NO_WRAP) }- return Node(tag, attrs, content, data)+ /**+ * Decode binary data to node.+ */+ fun decodeNode(data: ByteArray): Node {+ val decoder = BinaryDecoder(data)+ return decoder.readNode() } /**
messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppWebSocket.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppWebSocket.kt b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppWebSocket.ktindex 7fce6abeb9..623901f5b4 100644--- a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppWebSocket.kt+++ b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppWebSocket.kt@@ -222,25 +222,45 @@ class WhatsAppWebSocket( } private fun handleHandshakeMessage(data: ByteArray) {- // Parse ServerHello and complete handshake- // This is a simplified version - full implementation needs:- // 1. Parse protobuf HandshakeMessage with ServerHello- // 2. Extract server ephemeral key, encrypted static key, encrypted cert- // 3. Verify certificate using WA_CERT_PUBKEY- // 4. Derive shared secrets and complete handshake- // 5. Create NoiseSocket for encrypted communication- Log.i(TAG, "Received handshake response (${data.size} bytes)") - // For now, mark handshake as complete (stub)- // Real implementation would process the ServerHello here- isHandshakeComplete = true- noiseSocket = NoiseSocket()- - scope.launch {- _connectionState.emit(ConnectionState.Connected)+ try {+ val handshakeMessage = com.vayunmathur.messages.whatsapp.proto.WhatsAppHandshakeProto.HandshakeMessage.parseFrom(data)+ val serverHello = handshakeMessage.serverHello+ + if (serverHello == null) {+ Log.e(TAG, "ServerHello is null")+ scope.launch { _connectionState.emit(ConnectionState.Disconnected("Invalid ServerHello")) }+ disconnect()+ return+ }+ + val handshake = noiseHandshake ?: run {+ Log.e(TAG, "Noise handshake not initialized")+ return+ }++ // Process ServerHello and derive keys (mirrors WebViewWebSocket logic)+ val serverEphemeral = serverHello.ephemeral.toByteArray()+ val serverStaticCiphertext = serverHello.getStatic().toByteArray()+ val certificateCiphertext = serverHello.payload.toByteArray()+ + // TODO: full ServerHello processing would go here+ // For now, derive keys and create encrypted socket+ val (writeKey, readKey) = handshake.finish()+ + isHandshakeComplete = true+ noiseSocket = NoiseSocket(writeKey, readKey)+ + scope.launch {+ _connectionState.emit(ConnectionState.Connected)+ }+ startPing()+ } catch (e: Exception) {+ Log.e(TAG, "Failed to process handshake response", e)+ scope.launch { _connectionState.emit(ConnectionState.Disconnected("Handshake failed: ${e.message}")) }+ disconnect() }- startPing() } private fun buildClientHello(ephemeralPub: ByteArray): ByteArray {@@ -301,18 +321,40 @@ class WhatsAppWebSocket( } /**- * Simplified NoiseSocket for encrypted communication- * Real implementation would use the keys derived from handshake+ * Encrypted socket using AES-256-GCM with counter-based IVs.+ * Keys are derived from the Noise handshake finish() call. */- private inner class NoiseSocket {+ private inner class NoiseSocket(+ private val writeKey: javax.crypto.spec.SecretKeySpec,+ private val readKey: javax.crypto.spec.SecretKeySpec,+ ) {+ private var writeCounter: UInt = 0u+ private var readCounter: UInt = 0u++ private fun generateIV(counter: UInt): ByteArray {+ val iv = ByteArray(12)+ java.nio.ByteBuffer.wrap(iv, 4, 8)+ .order(java.nio.ByteOrder.BIG_ENDIAN)+ .putLong(counter.toLong())+ return iv+ }+ fun encrypt(plaintext: ByteArray): ByteArray {- // Stub - real implementation uses AES-GCM with derived keys- return plaintext+ val cipher = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding")+ val spec = javax.crypto.spec.GCMParameterSpec(128, generateIV(writeCounter))+ cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, writeKey, spec)+ val ciphertext = cipher.doFinal(plaintext)+ writeCounter+++ return ciphertext } fun decrypt(ciphertext: ByteArray): ByteArray {- // Stub - real implementation uses AES-GCM with derived keys- return ciphertext+ val cipher = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding")+ val spec = javax.crypto.spec.GCMParameterSpec(128, generateIV(readCounter))+ cipher.init(javax.crypto.Cipher.DECRYPT_MODE, readKey, spec)+ val plaintext = cipher.doFinal(ciphertext)+ readCounter+++ return plaintext } } }
messages/src/main/res/values/strings.xml
diff --git a/messages/src/main/res/values/strings.xml b/messages/src/main/res/values/strings.xmlindex 812f8e2783..7725b34cc7 100644--- a/messages/src/main/res/values/strings.xml+++ b/messages/src/main/res/values/strings.xml@@ -74,6 +74,21 @@ <string name="inbox_setup_signal_action">Link device</string> <string name="source_signal">Signal</string> + <!-- WhatsApp setup -->+ <string name="inbox_setup_whatsapp_title">Link WhatsApp</string>+ <string name="inbox_setup_whatsapp_desc">Link your WhatsApp account to see your messages here.</string>+ <string name="inbox_setup_whatsapp_action">Link device</string>++ <!-- Messenger setup -->+ <string name="inbox_setup_messenger_title">Sign in to Messenger</st
Diff truncated.