messages: various fixes
- Commit
f08be81209fdcb7efd1c5126dc586eeab2ddb161- Author
- Vayun Mathur <[email protected]>
- When
- 2026-06-12 17:02 UTC (5 months ago)
- Parents
bcff8ae
Diff
messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.ktindex e2c59ca3b5..cbb0699b75 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt@@ -42,6 +42,12 @@ sealed interface GMEvent { val timestamp: Long, val senderName: String?, val reactionsJson: String? = null,+ /** Downloaded media bytes (null if no media or download failed). */+ val mediaData: ByteArray? = null,+ val mediaMime: String? = null,+ val mediaName: String? = null,+ /** Wire status type string for status tracking. */+ val statusType: String? = null, ) : GMEvent /** A NEW inbound message just arrived. Distinct from MessageUpdate@@ -67,18 +73,20 @@ sealed interface GMEvent { /** A message was edited on the remote side. */ data class MessageEdited( override val source: MessageSource,- val conversationId: String,+ val conversationId: String? = null, val messageId: String, val newBody: String,- val timestamp: Long,+ val timestamp: Long = 0L, ) : GMEvent /** A read receipt was received. */ data class ReadReceipt( override val source: MessageSource, val conversationId: String,- val messageId: String,- val timestamp: Long,+ val messageId: String? = null,+ val senderId: String? = null,+ val timestampMs: Long = 0L,+ val timestamp: Long = 0L, ) : GMEvent /** A conversation was deleted on the remote side. */@@ -94,4 +102,49 @@ sealed interface GMEvent { val senderId: String, val isTyping: Boolean, ) : GMEvent++ /** A reaction was added to a message. */+ data class ReactionReceived(+ override val source: MessageSource,+ val conversationId: String,+ val messageId: String,+ val senderId: String,+ val emoji: String,+ ) : GMEvent++ /** A reaction was removed from a message. */+ data class ReactionRemoved(+ override val source: MessageSource,+ val conversationId: String,+ val messageId: String,+ val senderId: String,+ ) : GMEvent++ /** A conversation was renamed. */+ data class ConversationNameChanged(+ override val source: MessageSource,+ val conversationId: String,+ val newName: String,+ ) : GMEvent++ /** A conversation avatar was changed. */+ data class ConversationAvatarChanged(+ override val source: MessageSource,+ val conversationId: String,+ val avatarUrl: String?,+ ) : GMEvent++ /** A participant was added to a group. */+ data class ParticipantAdded(+ override val source: MessageSource,+ val conversationId: String,+ val participantId: String,+ ) : GMEvent++ /** A participant was removed from a group. */+ data class ParticipantRemoved(+ override val source: MessageSource,+ val conversationId: String,+ val participantId: String,+ ) : GMEvent }
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 147106cabd..9c21f1ddb5 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt@@ -51,8 +51,16 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock+import client.Client.ReplyPayload+import conversations.Conversations.MessageStatusType+import conversations.Conversations.ConversationSendMode+import conversations.Conversations.ConversationStatus+import conversations.Conversations.ConversationType+import events.Events.AlertType+import events.Events.TypingTypes import rpc.Rpc.ActionType import rpc.Rpc.MessageType+import settings.SettingsOuterClass import java.util.concurrent.atomic.AtomicBoolean /**@@ -125,7 +133,35 @@ object GMessagesClient { @Volatile private var conversationsFetchedOnce = false - // --- Message deduplication ring buffer (port of Go's recentUpdates) ---+ // --- Bridge state tracking (port of Go connector's GMClient fields) ---+ @Volatile private var browserInactiveType: String = ""+ @Volatile private var ready = false+ @Volatile private var phoneResponding = true+ @Volatile private var noDataReceivedRecently = false+ @Volatile private var lastDataReceived = System.currentTimeMillis()+ @Volatile private var batteryLow = false+ @Volatile private var mobileData = false+ @Volatile private var switchedToGoogleLogin = false+ @Volatile private var sessionId = ""+ @Volatile private var aggressiveReconnect = true+ private var cachedContacts: List<com.vayunmathur.messages.util.ContactSuggestion>? = null+ private var contactsFetchedAt = 0L+ private val contactsFetchLock = Mutex()+ private val pendingOutgoing = java.util.concurrent.ConcurrentHashMap<String, String>()+ @Volatile private var defaultSimPayload: SettingsOuterClass.SIMPayload? = null+ private val conversationTypes = java.util.concurrent.ConcurrentHashMap<String, ConversationType>()+ private val conversationSendModes = java.util.concurrent.ConcurrentHashMap<String, ConversationSendMode>()+ private val conversationForceRcs = java.util.concurrent.ConcurrentHashMap<String, Boolean>()+ private var qrRetryCount = 0+ private const val MAX_QR_RETRIES = 6++ // Issue 2: message edit detection — track content hashes per message ID+ private val messageContentHashes = java.util.concurrent.ConcurrentHashMap<String, String>()++ // Issue 5: reaction sync per-user — track (messageId, userId) → emoji to prevent duplicate events+ private val reactionState = java.util.concurrent.ConcurrentHashMap<Pair<String, String>, String>()++ // --- Message deduplication ring buffer private data class UpdateDedupItem(val id: String, val hash: ByteArray) private val recentUpdates = arrayOfNulls<UpdateDedupItem>(8) private var recentUpdatesPtr = 0@@ -165,37 +201,85 @@ object GMessagesClient { scope.launch { freshAuth.save(appContext) } outgoingIds.clear() conversationsFetchedOnce = false+ browserInactiveType = ""+ ready = false+ phoneResponding = true+ noDataReceivedRecently = false+ batteryLow = false+ mobileData = false+ switchedToGoogleLogin = false+ sessionId = ""+ cachedContacts = null+ contactsFetchedAt = 0L+ pendingOutgoing.clear()+ defaultSimPayload = null+ conversationTypes.clear()+ conversationSendModes.clear()+ conversationForceRcs.clear()+ messageContentHashes.clear()+ reactionState.clear()+ qrRetryCount = 0 rpc.close() media.close() _state.value = State.Idle } suspend fun startPair(): String {+ qrRetryCount = 0+ return startPairAttempt()+ }++ private suspend fun startPairAttempt(): String { 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+ if (qrRetryCount == 0) {+ 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+ } else {+ val result = PairFlow.refreshPhoneRelay(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+ }+ }+ if (qrRetryCount == 0) {+ longPoll.start(scope) }- // Open the long-poll now so we receive the Paired event when the- // user finishes scanning.- longPoll.start(scope) _state.value = State.Pairing(qrUrl)+ qrRetryCount++ return qrUrl } catch (t: Throwable) {- Log.e(TAG, "startPair failed", t)+ Log.e(TAG, "startPair failed (attempt $qrRetryCount)", t) _state.value = State.Disconnected("Pair failed: ${t.message}") throw t } } + /** Refresh the QR code (up to MAX_QR_RETRIES). Returns the new QR URL. */+ suspend fun refreshQr(): String? {+ if (qrRetryCount >= MAX_QR_RETRIES) {+ Log.w(TAG, "QR refresh exhausted ($qrRetryCount/$MAX_QR_RETRIES)")+ return null+ }+ return try {+ startPairAttempt()+ } catch (t: Throwable) {+ Log.e(TAG, "QR refresh failed", t)+ null+ }+ }+ /** * Send a text message via SEND_MESSAGE. *@@ -207,13 +291,19 @@ object GMessagesClient { * * Returns `true` iff the relay reports `SUCCESS`. */- suspend fun sendMessage(conversationId: String, body: String): Boolean {+ suspend fun sendMessage(+ conversationId: String,+ body: String,+ replyToMessageId: String? = null,+ isEmote: Boolean = false,+ ): Boolean { if (_state.value !is State.Connected) return false val webId = conversationId.substringAfter(':', conversationId)+ val text = if (isEmote) "/me $body" else body val info = MessageInfo.newBuilder()- .setMessageContent(MessageContent.newBuilder().setContent(body))+ .setMessageContent(MessageContent.newBuilder().setContent(text)) .build()- return sendWithInfos(webId, listOf(info))+ return sendWithInfos(webId, listOf(info), replyToMessageId = replyToMessageId) } /**@@ -246,11 +336,15 @@ object GMessagesClient { .setMessageContent(MessageContent.newBuilder().setContent(caption)) .build() }- return sendWithInfos(webId, infos)+ return sendWithInfos(webId, infos, replyToMessageId = null) } /** Common SEND_MESSAGE plumbing — builds the envelope and awaits a response. */- private suspend fun sendWithInfos(webId: String, infos: List<MessageInfo>): Boolean {+ private suspend fun sendWithInfos(+ webId: String,+ infos: List<MessageInfo>,+ replyToMessageId: String? = null,+ ): Boolean { val tmpId = "tmp_${kotlin.random.Random.nextLong(1_000_000_000_000L).toString().padStart(12, '0')}" val participantId = outgoingIds[webId].orEmpty() val payload = MessagePayload.newBuilder()@@ -260,17 +354,40 @@ object GMessagesClient { .setTmpID2(tmpId) .addAllMessageInfo(infos) .build()- val req = SendMessageRequest.newBuilder()+ val reqBuilder = SendMessageRequest.newBuilder() .setConversationID(webId) .setMessagePayload(payload) .setTmpID(tmpId)- .build()+ // SIM payload (item 4)+ defaultSimPayload?.let { reqBuilder.setSIMPayload(it) }+ // ForceRCS flag (item 20)+ val convType = conversationTypes[webId]+ val sendMode = conversationSendModes[webId]+ val forceRcs = conversationForceRcs[webId] == true+ if (convType == ConversationType.RCS &&+ sendMode == ConversationSendMode.SEND_MODE_AUTO && forceRcs) {+ reqBuilder.setForceRCS(true)+ }+ // Reply support (item 5)+ if (replyToMessageId != null) {+ val replyWebId = replyToMessageId.substringAfter(':', replyToMessageId)+ reqBuilder.setReply(ReplyPayload.newBuilder().setMessageID(replyWebId))+ }+ // Track for remote echo (item 23)+ pendingOutgoing[tmpId] = webId+ val req = reqBuilder.build() val resp = sessionHandler.sendAndWait(ActionType.SEND_MESSAGE, req)- ?: return false.also { Log.w(TAG, "SEND_MESSAGE timed out") }- val data = resp.decryptedData ?: return false+ ?: return false.also {+ Log.w(TAG, "SEND_MESSAGE timed out")+ pendingOutgoing.remove(tmpId)+ }+ val data = resp.decryptedData ?: return false.also { pendingOutgoing.remove(tmpId) } val parsed = runCatching { SendMessageResponse.parseFrom(data) }.getOrNull()- ?: return false+ ?: return false.also { pendingOutgoing.remove(tmpId) } Log.i(TAG, "SEND_MESSAGE status=${parsed.status}")+ if (parsed.status != SendMessageResponse.Status.SUCCESS) {+ pendingOutgoing.remove(tmpId)+ } return parsed.status == SendMessageResponse.Status.SUCCESS } @@ -329,11 +446,13 @@ object GMessagesClient { ): Boolean { if (_state.value !is State.Connected) return false val msgWebId = messageId.substringAfter(':', messageId)- val req = SendReactionRequest.newBuilder()+ val qualifiedEmoji = fullyQualifyEmoji(emoji)+ val reqBuilder = SendReactionRequest.newBuilder() .setMessageID(msgWebId) .setAction(action)- .setReactionData(ReactionData.newBuilder().setUnicode(emoji))- .build()+ .setReactionData(ReactionData.newBuilder().setUnicode(qualifiedEmoji))+ defaultSimPayload?.let { reqBuilder.setSIMPayload(it) }+ val req = reqBuilder.build() val resp = sessionHandler.sendAndWait(ActionType.SEND_REACTION, req) ?: return false val body = resp.decryptedData ?: return false val parsed = runCatching { SendReactionResponse.parseFrom(body) }.getOrNull()@@ -347,14 +466,28 @@ object GMessagesClient { suspend fun sendTyping(conversationId: String): Boolean { if (_state.value !is State.Connected) return false val webId = conversationId.substringAfter(':', conversationId)- val req = TypingUpdateRequest.newBuilder()+ val reqBuilder = TypingUpdateRequest.newBuilder() .setData( TypingUpdateRequest.Data.newBuilder() .setConversationID(webId) .setTyping(true) )- .build()- return sessionHandler.sendNoWait(ActionType.TYPING_UPDATES, req)+ defaultSimPayload?.let { reqBuilder.setSIMPayload(it) }+ return sessionHandler.sendNoWait(ActionType.TYPING_UPDATES, reqBuilder.build())+ }++ /** Stop-typing support (item 9). Fire-and-forget. */+ suspend fun sendStopTyping(conversationId: String): Boolean {+ if (_state.value !is State.Connected) return false+ val webId = conversationId.substringAfter(':', conversationId)+ val reqBuilder = TypingUpdateRequest.newBuilder()+ .setData(+ TypingUpdateRequest.Data.newBuilder()+ .setConversationID(webId)+ .setTyping(false)+ )+ defaultSimPayload?.let { reqBuilder.setSIMPayload(it) }+ return sessionHandler.sendNoWait(ActionType.TYPING_UPDATES, reqBuilder.build()) } /**@@ -414,11 +547,10 @@ object GMessagesClient { }.getOrNull() ?: return null if (parsed.status == GetOrCreateConversationResponse.Status.CREATE_RCS) {- // The server is telling us "you asked for RCS but this set- // of participants isn't RCS-capable — try again without".- // The bridge does the same retry (handlematrix.go).- Log.i(TAG, "getOrCreate: CREATE_RCS — retrying with SMS")- return getOrCreateConversation(numbers, rcsGroupName = null, createRcsGroup = false)+ // Server says "retry with createRcsGroup = true". Port of+ // Go startchat.go: reqData.CreateRCSGroup = ptr.Ptr(true)+ Log.i(TAG, "getOrCreate: CREATE_RCS — retrying with createRcsGroup=true")+ return getOrCreateConversation(numbers, rcsGroupName = rcsGroupName ?: "", createRcsGroup = true) } if (!parsed.hasConversation()) { Log.w(TAG, "getOrCreate: status=${parsed.status} but no conversation")@@ -441,17 +573,26 @@ object GMessagesClient { */ suspend fun listContacts(): List<com.vayunmathur.messages.util.ContactSuggestion> { if (_state.value !is State.Connected) return emptyList()- val req = ListContactsRequest.newBuilder()- .setI1(1)- .setI2(350)- .setI3(50)- .build()- val resp = sessionHandler.sendAndWait(ActionType.LIST_CONTACTS, req) ?: return emptyList()- val parsed = runCatching {- ListContactsResponse.parseFrom(resp.decryptedData ?: return emptyList())- }.getOrNull() ?: return emptyList()- return (0 until parsed.contactsCount).mapNotNull { i ->- parsed.getContacts(i).toSuggestion()+ contactsFetchLock.withLock {+ val cached = cachedContacts+ if (cached != null && System.currentTimeMillis() - contactsFetchedAt < 5 * 60 * 1000L) {+ return cached+ }+ val req = ListContactsRequest.newBuilder()+ .setI1(1)+ .setI2(350)+ .setI3(50)+ .build()+ val resp = sessionHandler.sendAndWait(ActionType.LIST_CONTACTS, req) ?: return cached ?: emptyList()+ val parsed = runCatching {+ ListContactsResponse.parseFrom(resp.decryptedData ?: return cached ?: emptyList())+ }.getOrNull() ?: return cached ?: emptyList()+ val result = (0 until parsed.contactsCount).mapNotNull { i ->+ parsed.getContacts(i).toSuggestion()+ }+ cachedContacts = result+ contactsFetchedAt = System.currentTimeMillis()+ return result } } @@ -512,6 +653,8 @@ object GMessagesClient { updates.hasMessageEvent() -> { val msgs = updates.messageEvent.dataList Log.i(TAG, "GET_UPDATES: ${msgs.size} message event(s)")+ noDataReceivedRecently = false+ lastDataReceived = System.currentTimeMillis() msgs.forEach { msg -> if (deduplicateUpdate(msg.messageID, data)) return emitMessage(msg)@@ -520,6 +663,8 @@ object GMessagesClient { updates.hasConversationEvent() -> { val convs = updates.conversationEvent.dataList Log.i(TAG, "GET_UPDATES: ${convs.size} conversation event(s)")+ noDataReceivedRecently = false+ lastDataReceived = System.currentTimeMillis() convs.forEach { conv -> if (deduplicateUpdate(conv.conversationID, data)) return if (isOld) {@@ -531,22 +676,35 @@ object GMessagesClient { } updates.hasTypingEvent() -> { if (isOld) return- val data2 = updates.typingEvent.data- Log.d(TAG, "GET_UPDATES typing conv=${data2.conversationID} type=${data2.type}")+ val typingData = updates.typingEvent.data+ val convId = typingData.conversationID+ val isTyping = typingData.type == TypingTypes.STARTED_TYPING+ val senderId = typingData.user?.number.orEmpty()+ Log.d(TAG, "GET_UPDATES typing conv=$convId typing=$isTyping sender=$senderId")+ _events.emit(+ GMEvent.TypingIndicator(+ source = source,+ conversationId = convId,+ senderId = senderId,+ isTyping = isTyping,+ )+ ) } updates.hasUserAlertEvent() -> { if (isOld) return- Log.d(TAG, "GET_UPDATES user-alert: ${updates.userAlertEvent.alertType}")+ if (!noDataReceivedRecently) lastDataReceived = System.currentTimeMillis()+ handleUserAlert(updates.userAlertEvent.alertType) } updates.hasSettingsEvent() -> {- Log.d(TAG, "GET_UPDATES settings event")+ if (!noDataReceivedRecently) lastDataReceived = System.currentTimeMillis()+ handleSettings(data) } updates.hasBrowserPresenceCheckEvent() -> { Log.d(TAG, "GET_UPDATES: browser presence check, sending ack") scope.launch { ackBrowserPresence() } } updates.hasAccountChange() -> {- Log.d(TAG, "GET_UPDATES: account change event")+ handleAccountChange(data) } else -> Log.d(TAG, "GET_UPDATES: unhandled event kind") }@@ -558,6 +716,134 @@ object GMessagesClient { )) } + /** Port of Go's handleUserAlert (handlegmessages.go:256-337). */+ private fun handleUserAlert(alertType: AlertType) {+ Log.d(TAG, "handleUserAlert: $alertType")+ when (alertType) {+ AlertType.BROWSER_INACTIVE,+ AlertType.BROWSER_INACTIVE_FROM_TIMEOUT,+ AlertType.BROWSER_INACTIVE_FROM_INACTIVITY -> {+ browserInactiveType = alertType.name+ Log.i(TAG, "Browser became inactive: $alertType")+ }+ AlertType.BROWSER_ACTIVE -> {+ val wasInactive = browserInactiveType.isNotEmpty() || !ready+ browserInactiveType = ""+ ready = true+ val newSessionId = sessionHandler.currentSessionId()+ val sessionIdChanged = sessionId.isNotEmpty() && sessionId != newSessionId+ if (sessionIdChanged || wasInactive || noDataReceivedRecently) {+ Log.i(TAG, "BROWSER_ACTIVE: resyncing (sessionChanged=$sessionIdChanged wasInactive=$wasInactive noData=$noDataReceivedRecently)")+ sessionId = newSessionId+ scope.launch { kickoffBackfill() }+ } else {+ sessionId = newSessionId+ }+ noDataReceivedRecently = false+ lastDataReceived = System.currentTimeMillis()+ }+ AlertType.MOBILE_DATA_CONNECTION -> {+ mobileData = true+ Log.d(TAG, "Phone connected to mobile data")+ }+ AlertType.MOBILE_WIFI_CONNECTION -> {+ mobileData = false+ Log.d(TAG, "Phone connected to WiFi")+ }+ AlertType.MOBILE_BATTERY_LOW -> {+ batteryLow = true+ Log.d(TAG, "Phone battery low")+ }+ AlertType.MOBILE_BATTERY_RESTORED -> {+ batteryLow = false+ Log.d(TAG, "Phone battery restored")+ }+ AlertType.MOBILE_DATABASE_SYNC_STARTED,+ AlertType.MOBILE_DATABASE_PARTIAL_SYNC_STARTED -> {+ Log.d(TAG, "Mobile database sync started")+ }+ AlertType.MOBILE_DATABASE_SYNC_COMPLETE,+ AlertType.MOBILE_DATABASE_PARTIAL_SYNC_COMPLETED -> {+ Log.d(TAG, "Mobile database sync complete, triggering backfill")+ scope.launch { kickoffBackfill() }+ }+ AlertType.MOBILE_DATABASE_SYNCING -> {+ Log.d(TAG, "Mobile database syncing")+ }+ AlertType.RCS_CONNECTION -> {+ Log.d(TAG, "RCS connection established")+ }+ else -> Log.d(TAG, "Unhandled alert type: $alertType")+ }+ }++ /** Port of Go's handleSettings (handlegmessages.go:361-395). */+ private fun handleSettings(data: ByteArray) {+ try {+ val updates = UpdateEvents.parseFrom(data)+ if (updates.hasSettingsEvent()) {+ val settingsProto = updates.settingsEvent+ if (settingsProto.sIMCardsCount > 0) {+ val firstSim = settingsProto.getSIMCards(0)+ if (firstSim.hasSIMData()) {+ defaultSimPayload = firstSim.sIMData.sIMPayload+ Log.d(TAG, "handleSettings: stored SIM payload (${settingsProto.sIMCardsCount} SIMs)")+ }+ }+ }+ } catch (e: Exception) {+ Log.d(TAG, "handleSettings: could not parse settings: ${e.message}")+ }+ }++ /** Port of Go's handleAccountChange (handlegmessages.go:236-254). */+ private fun handleAccountChange(data: ByteArray) {+ try {+ val updates = UpdateEvents.parseFrom(data)+ if (updates.hasAccountChange()) {+ val change = updates.accountChange+ switchedToGoogleLogin = change.enabled+ Log.i(TAG, "handleAccountChange: account=${change.account} switchedToGoogle=$switchedToGoogleLogin")+ }+ } catch (e: Exception) {+ Log.d(TAG, "handleAccountChange: ${e.message}")+ }+ }++ /**+ * Port of Go's aggressiveSetActive (handlegmessages.go:339-359).+ * Called when the phone seems unresponsive — retries SetActiveSession+ * with escalating delays.+ */+ private fun aggressiveSetActive() {+ if (!aggressiveReconnect) return+ scope.launch {+ val sleepTimes = longArrayOf(5_000, 10_000, 30_000)+ for (sleepMs in sleepTimes) {+ if (!phoneResponding) {+ Log.i(TAG, "aggressiveSetActive: sleeping ${sleepMs}ms")+ kotlinx.coroutines.delay(sleepMs)+ if (!phoneResponding) {+ try {+ sessionHandler.setActiveSession()+ } catch (e: Exception) {+ Log.w(TAG, "aggressiveSetActive failed: ${e.message}")+ }+ }+ }+ }+ }+ }++ /** Variation selector: ensure emoji is fully qualified with VS16 (issue 4). */+ private fun fullyQualifyEmoji(emoji: String): String {+ if (emoji.isEmpty() || emoji.contains('\uFE0F')) return emoji+ // Only append VS16 to single-codepoint emoji that aren't already qualified+ val codePointCount = emoji.codePointCount(0, emoji.length)+ if (codePointCount == 1) return "$emoji\uFE0F"+ return emoji+ }+ /** SHA-256 based deduplication ring buffer. Port of Go's deduplicateUpdate. */ private fun deduplicateUpdate(id: String, data: ByteArray): Boolean { val hash = MessageDigest.getInstance("SHA-256").digest(data)@@ -587,15 +873,16 @@ object GMessagesClient { * Strip the source prefix because the relay only knows Google's * thread id. */- fun fetchMessages(conversationId: String, count: Int = 100) {+ fun fetchMessages(conversationId: String, count: Int = 100, cursor: client.Client.Cursor? = null) { if (_state.value !is State.Connected) return scope.launch { val webId = conversationId.substringAfter(':', conversationId)- Log.i(TAG, "fetchMessages convId=$webId count=$count")- val req = ListMessagesRequest.newBuilder()+ Log.i(TAG, "fetchMessages convId=$webId count=$count cursor=${cursor != null}")+ val reqBuilder = ListMessagesRequest.newBuilder() .setConversationID(webId) .setCount(count.toLong())- .build()+ cursor?.let { reqBuilder.setCursor(it) }+ val req = reqBuilder.build() val resp = sessionHandler.sendAndWait(ActionType.LIST_MESSAGES, req) if (resp == null) Log.w(TAG, "fetchMessages: no response") }@@ -822,12 +1109,12 @@ object GMessagesClient { } private suspend fun emitConversation(c: conversations.Conversations.Conversation) {- // Capture defaultOutgoingID so the SEND_MESSAGE path can route- // the outgoing through the right SIM. Keyed by web ID (no prefix). c.defaultOutgoingID.takeIf { it.isNotBlank() }?.let { outgoingIds[c.conversationID] = it } - // Collect the non-self participants — used for both phone-lookup- // (1:1 chats) and group-display labeling.+ // Track conversation type/sendMode/forceRCS for outbound message routing+ conversationTypes[c.conversationID] = c.type+ conversationSendModes[c.conversationID] = c.sendMode+ val otherParticipants = (0 until c.participantsCount) .map { c.getParticipants(it) } .filter { !it.isMe }@@ -835,9 +1122,6 @@ object GMessagesClient { val isGroup = c.isGroupChat || otherParticipants.size > 1 val peerPhone = otherParticipants.firstOrNull { it.id.number.isNotBlank() }?.id?.number - // Always prefer the device's contact database for naming + photos- // (1:1 only). For groups we synthesize a "Alice, Bob & 2 others"- // style label below. val contact = if (!isGroup) { peerPhone?.let { ContactResolver.lookup(appContext, it) } } else null@@ -848,8 +1132,8 @@ object GMessagesClient { } val type = when (c.type) {- conversations.Conversations.ConversationType.SMS -> "SMS"- conversations.Conversations.ConversationType.RCS -> "RCS"+ ConversationType.SMS -> "SMS"+ ConversationType.RCS -> "RCS" else -> null } @@ -972,21 +1256,122 @@ object GMessagesClient { } private suspend fun emitMessage(m: conversations.Conversations.Message) {+ val outgoing = m.hasSenderParticipant() && m.senderParticipant.isMe++ // Remote echo handling (item 23): if this is an outgoing message+ // matching a pending tmpId, it's the server echo of our send.+ if (outgoing && m.tmpID.isNotBlank()) {+ pendingOutgoing.remove(m.tmpID)+ }++ // Issue 1: full message status state machine (ref handlegmessages.go:968-1162)+ val statusType = m.messageStatus.status++ // MESSAGE_DELETED: emit delete event and return early+ if (statusType == MessageStatusType.MESSAGE_DELETED) {+ Log.d(TAG, "emitMessage: MESSAGE_DELETED id=${m.messageID}")+ messageContentHashes.remove(m.messageID)+ _events.emit(+ GMEvent.MessageDeleted(+ source = source,+ messageId = m.messageID,+ conversationId = m.conversationID,+ timestamp = toMillis(m.timestamp),+ )+ )+ return+ }++ // Map status for downstream consumers+ val statusStr = when (statusType) {+ MessageStatusType.OUTGOING_DELIVERED -> "delivered"+ MessageStatusType.OUTGOING_DISPLAYED -> "read"+ MessageStatusType.OUTGOING_COMPLETE -> "sent"+ MessageStatusType.INCOMING_AUTO_DOWNLOADING -> "downloading"+ MessageStatusType.INCOMING_DOWNLOAD_FAILED -> "download_failed"+ MessageStatusType.INCOMING_MANUAL_DOWNLOADING -> "downloading"+ MessageStatusType.INCOMING_RETRYING_AUTO_DOWNLOAD -> "downloading"+ MessageStatusType.INCOMING_DOWNLOAD_FAILED_SIM_HAS_NO_DATA -> "download_failed_no_data"+ MessageStatusType.INCOMING_DOWNLOAD_CANCELED -> "download_canceled"+ else -> null+ }++ // OUTGOING_DELIVERED: emit delivery receipt+ if (statusType == MessageStatusType.OUTGOING_DELIVERED) {+ _events.emit(+ GMEvent.ReadReceipt(+ source = source,+ conversationId = m.conversationID,+ messageId = m.messageID,+ timestamp = toMillis(m.timestamp),+ )+ )+ }++ // OUTGOING_DISPLAYED: emit read receipt+ if (statusType == MessageStatusType.OUTGOING_DISPLAYED) {+ _events.emit(+ GMEvent.ReadReceipt(+ source = source,+ conversationId = m.conversationID,+ messageId = m.messageID,+ timestamp = toMillis(m.timestamp),+ )+ )+ }++ // Build message body + attempt media download+ var mediaBytes: ByteArray? = null+ var mediaMime: String? = null+ var mediaName: String? = null val body = (0 until m.messageInfoCount) .mapNotNull { idx -> val info = m.getMessageInfo(idx) when { info.hasMessageContent() -> info.messageContent.content- info.hasMediaContent() -> mediaLabel(info.mediaContent)+ info.hasMediaContent() -> {+ val mc = info.mediaContent+ if (mc.mediaID.isNotBlank() && mc.decryptionKey.size() > 0) {+ try {+ // TODO: OGG audio should ideally be converted to opus via ffmpeg on Android+ val downloaded = media.download(mc.mediaID, mc.decryptionKey.toByteArray())+ mediaBytes = downloaded+ mediaMime = mc.mimeType+ mediaName = mc.mediaName.takeIf { it.isNotBlank() }+ mc.mediaName.takeIf { it.isNotBlank() } ?: "[media]"+ } catch (e: Exception) {+ Log.w(TAG, "media download failed: ${e.message}")+ mediaLabel(mc)+ }+ } else {+ mediaLabel(mc)+ }+ } else -> null } } .joinToString("\n") .ifBlank { "" }- // The Message proto has no top-level fromMe boolean, but its- // senderParticipant carries an `isMe` flag the relay populates- // for outgoing messages. Falls back to incoming when missing.- val outgoing = m.hasSenderParticipant() && m.senderParticipant.isMe++ // Issue 2: message edit detection (ref handlegmessages.go:910-954)+ val contentHash = computeContentHash(m)+ val previousHash = messageContentHashes.put(m.messageID, contentHash)+ if (previousHash != null && previousHash != contentHash) {+ Log.d(TAG, "emitMessage: edit detected id=${m.messageID}")+ _events.emit(+ GMEvent.MessageEdited(+ source = source,+ conversationId = m.conversationID,+ messageId = m.messageID,+ newBody = body,+ timestamp = toMillis(m.timestamp),+ )+ )+ }++ // Issue 5: reaction sync per-user — emit per-user reaction events+ syncReactions(m)+ _events.emit( GMEvent.MessageUpdate( source = source,@@ -1000,6 +1385,10 @@ object GMessagesClient { ?: m.senderParticipant.firstName.takeIf { it.isNotBlank() } } else null, reactionsJson = extractReactionsJson(m),+ mediaData = mediaBytes,+ mediaMime = mediaMime,+ mediaName = mediaName,+ statusType = statusStr, ) ) if (!outgoing && body.isNotEmpty()) {@@ -1021,6 +1410,65 @@ object GMessagesClient { } } + /** Compute a hash of text + media IDs for edit detection. */+ private fun computeContentHash(m: conversations.Conversations.Message): String {+ val digest = MessageDigest.getInstance("SHA-256")+ for (i in 0 until m.messageInfoCount) {+ val info = m.getMessageInfo(i)+ if (info.hasMessageContent()) {+ digest.update(info.messageContent.content.toByteArray(Charsets.UTF_8))+ }+ if (info.hasMediaContent()) {+ val mediaId = info.mediaContent.mediaID.ifBlank { info.mediaContent.thumbnailMediaID }+ digest.update(mediaId.toByteArray(Charsets.UTF_8))+ }+ }+ return digest.digest().joinToString("") { "%02x".format(it) }+ }++ /** Emit per-user reaction add/remove events, deduplicating via [reactionState]. */+ private suspend fun syncReactions(m: conversations.Conversations.Message) {+ val currentReactions = mutableMapOf<Pair<String, String>, String>()+ for (i in 0 until m.reactionsCount) {+ val entry = m.getReactions(i)+ val emoji = entry.data.unicode.takeIf { it.isNotBlank() } ?: continue+ for (j in 0 until entry.participantIDsCount) {+ val userId = entry.getParticipantIDs(j)+ currentReactions[Pair(m.messageID, userId)] = emoji+ }+ }+ // Detect new or changed reactions+ for ((key, emoji) in currentReactions) {+ val prev = reactionState.put(key, emoji)+ if (prev == null || prev != emoji) {+ _events.emit(+ GMEvent.ReactionReceived(+ source = source,+ conversationId = m.conversationID,+ messageId = key.first,+ senderId = key.second,+ emoji = emoji,+ )+ )+ }+ }+ // Detect removed reactions+ val removedKeys = reactionState.keys.filter {+ it.first == m.messageID && it !in currentReactions+ }+ for (key in removedKeys) {+ reactionState.remove(key)+ _events.emit(+ GMEvent.ReactionRemoved(+ source = source,+ conversationId = m.conversationID,+ messageId = key.first,+ senderId = key.second,+ )+ )+ }+ }+ private fun kickoffBackfill() { backfillJob?.cancel() backfillJob = scope.launch {
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 5a9bf01d6e..5275d3c208 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/Media.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Media.kt@@ -4,6 +4,8 @@ import android.util.Base64 import android.util.Log import authentication.Authentication import authentication.Authentication.AuthMessage+import client.Client.AttachmentInfo+import client.Client.DownloadAttachmentRequest import client.Client.StartMediaUploadRequest import client.Client.UploadMediaResponse import conversations.Conversations.MediaContent@@ -75,6 +77,47 @@ class Media(private val authProvider: () -> AuthData) { .build() } + /**+ * Download and decrypt incoming media. Port of Go's `Client.DownloadMedia`.+ *+ * Sends a GET to the upload URL with an `x-goog-download-metadata` header+ * containing a base64-encoded [DownloadAttachmentRequest] proto. The+ * response body is AES-GCM encrypted bytes which we decrypt with [key].+ */+ suspend fun download(mediaId: String, key: ByteArray): ByteArray {+ val auth = authProvider()+ val downloadReq = DownloadAttachmentRequest.newBuilder()+ .setInfo(+ AttachmentInfo.newBuilder()+ .setAttachmentID(mediaId)+ .setEncrypted(true)+ )+ .setAuthData(+ AuthMessage.newBuilder()+ .setRequestID(java.util.UUID.randomUUID().toString())+ .setTachyonAuthToken(+ com.google.protobuf.ByteString.copyFrom(+ auth.tachyonToken()+ ?: error("tachyon token is null — not paired or token expired")+ )+ )+ .setNetwork(auth.authNetwork())+ .setConfigVersion(PairFlow.ConfigVersion)+ )+ .build()+ val metadata = Base64.encodeToString(downloadReq.toByteArray(), Base64.NO_WRAP)+ val resp: HttpResponse = http.request(Endpoints.UploadMediaUrl) {+ method = HttpMethod.Get+ downloadHeaders(metadata)+ }+ if (resp.status.value !in 200..299) {+ error("media download HTTP ${resp.status.value}")+ }+ val encryptedBytes = resp.bodyAsBytes()+ val cipher = AesGcm(key)+ return cipher.decryptData(encryptedBytes)+ }+ /** Encode + base64 a StartMediaUploadRequest envelope. */ private fun buildStartPayload(): String { val auth = authProvider()@@ -187,6 +230,25 @@ class Media(private val authProvider: () -> AuthData) { } } + /** Port of util/func.go.BuildUploadHeaders — used for media download. */+ private fun io.ktor.client.request.HttpRequestBuilder.downloadHeaders(metadata: String) {+ headers {+ append("x-goog-download-metadata", metadata)+ append("sec-ch-ua", Endpoints.SecUA)+ append("sec-ch-ua-mobile", Endpoints.SecUAMobile)+ append("user-agent", Endpoints.UserAgent)+ append("sec-ch-ua-platform", "\"${Endpoints.UAPlatform}\"")+ append("accept", "*/*")+ append("origin", "https://messages.google.com")+ append("sec-fetch-site", "cross-site")+ append("sec-fetch-mode", "cors")+ append("sec-fetch-dest", "empty")+ append("referer", "https://messages.google.com/")+ append("accept-encoding", "gzip, deflate, br")+ append("accept-language", "en-US,en;q=0.9")+ }+ }+ /** * MIME-string → wire-enum mapping. Mirrors libgm's `MimeToMediaType` * map; only the formats we'll plausibly emit from the Compose
messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.ktindex 9ca74cf222..c88b58e7e6 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.kt@@ -129,4 +129,48 @@ object PairFlow { // Pairing.RefreshPhoneRelay, which only regenerates a fresh QR for // re-pairing). Token TTL is several days; for v1 we surface a // re-pair prompt if the user gets logged out.++ /**+ * Refresh the QR code by calling RefreshPhoneRelay. Returns a new+ * QR URL. Port of Go's `Client.RefreshPhoneRelay` / `QRLoginProcess.Wait`.+ */+ suspend fun refreshPhoneRelay(+ rpc: RpcClient,+ auth: AuthData,+ ): RegisterResult {+ val pubKey = auth.refreshKey.publicKeyDer()+ val tachyonToken = auth.tachyonToken() ?: error("no tachyon token for QR refresh")+ val req = AuthenticationContainer.newBuilder()+ .setAuthMessage(+ AuthMessage.newBuilder()+ .setRequestID(UUID.randomUUID().toString())+ .setTachyonAuthToken(com.google.protobuf.ByteString.copyFrom(tachyonToken))+ .setNetwork(QrNetwork)+ .setConfigVersion(ConfigVersion)+ )+ .setBrowserDetails(BrowserDetails)+ .build()++ Log.i(TAG, "RefreshPhoneRelay …")+ val resp = rpc.postProtobuf(+ url = Endpoints.RefreshPhoneRelayUrl,+ body = req,+ responseTemplate = RegisterPhoneRelayResponse.getDefaultInstance(),+ )+ Log.i(TAG, "RefreshPhoneRelay OK")++ val urlData = URLData.newBuilder()+ .setPairingKey(resp.pairingKey)+ .setAESKey(auth.crypto().aesKey.toByteString())+ .setHMACKey(auth.crypto().hmacKey.toByteString())+ .build()+ val qrPayload = Base64.encodeToString(urlData.toByteArray(), Base64.NO_WRAP)+ val qrUrl = Endpoints.QrCodeBaseUrl + qrPayload++ return RegisterResult(+ tachyonToken = resp.authKeyData.tachyonAuthToken.toByteArray(),+ tachyonTtlUs = resp.authKeyData.ttl,+ qrUrl = qrUrl,+ )+ } }
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 725f995d2d..ebf2650ae0 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt@@ -45,6 +45,8 @@ class SessionHandler( @Volatile private var currentSessionId: String = UUID.randomUUID().toString() + fun currentSessionId(): String = currentSessionId+ // --- Ack interval (port of Go's ackMap + ackTicker) --- private val ackMapMutex = Mutex() private val ackMap = mutableListOf<String>()
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 2a8c75334d..bfa634be63 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt@@ -16,11 +16,16 @@ import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.delay+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock import requests.Requests import responses.Responses import threads.Threads import waa.Waa+import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean+import java.util.concurrent.atomic.AtomicInteger+import java.util.concurrent.atomic.AtomicLong /** * Process-global owner of the Google Voice protocol session.@@ -41,7 +46,9 @@ object GVoiceClient { data object NeedsSetup : State data object Connecting : State data object Connected : State- data class Disconnected(val reason: String) : State+ data class Disconnected(val reason: String, val errorCode: String? = null) : State+ data class BadCredentials(val reason: String) : State+ data class ConnectError(val reason: String) : State } val source: MessageSource = MessageSource.VOICE@@ -62,6 +69,26 @@ object GVoiceClient { @Volatile private var versionToken: String = "" private const val AUTH_USER = "0" + // Contact cache with 5-min TTL (matches Go's contactCache + fetchContactInfo)+ private data class CachedContact(+ val name: String?,+ val avatarUrl: String?,+ val timestamp: Long,+ )+ private val contactCache = ConcurrentHashMap<String, CachedContact>()+ private const val CONTACT_CACHE_TTL_MS = 5L * 60L * 1000L++ // Rate-limited message fetching (matches Go: 10s min, burst 5, 15min ticker)+ private const val MIN_REFRESH_INTERVAL_MS = 10_000L+ private const val MIN_REFRESH_BURST = 5+ private const val BACKGROUND_REFRESH_INTERVAL_MS = 15L * 60L * 1000L+ private val refreshTokens = AtomicInteger(MIN_REFRESH_BURST)+ private val lastRefreshTime = AtomicLong(0L)+ private val fetchLock = Mutex()+ @Volatile private var fetchLoopJob: Job? = null++ private const val MAX_AVATAR_SIZE = 5 * 1024 * 1024+ fun init(context: Context) { if (!initialized.compareAndSet(false, true)) return appContext = context.applicationContext@@ -90,6 +117,7 @@ object GVoiceClient { fun stop() { Log.i(TAG, "stop — clearing Voice session") backfillJob?.cancel()+ fetchLoopJob?.cancel() realtime?.stop() realtime = null rpc?.close()@@ -145,10 +173,9 @@ object GVoiceClient { * * Mirrors `Client.SendMessage` in * `/Users/vayun/Documents/gvoice/pkg/libgv/client.go`: builds a- * [Requests.ReqSendSMS] with a random transaction ID and the- * bridge's `"!"` tracking-data fallback (the real signature is- * generated by an Electron-hosted JS blob in the bridge; the- * server happily accepts the placeholder for text-only sends).+ * [Requests.ReqSendSMS] with a random transaction ID.+ * TrackingData is only set when a real Electron signature is+ * available; without one, the field is omitted entirely. * * Returns true if the server responded 2xx with a thread item ID. */@@ -162,6 +189,14 @@ object GVoiceClient { return doSend(client, webId, req) } + /**+ * Send an emote (/me) message. Mirrors the Go bridge's handling+ * of MsgEmote (handlematrix.go): prepends "/me " to the body text.+ */+ suspend fun sendEmote(conversationId: String, body: String): Boolean {+ return sendMessage(conversationId, "/me $body")+ }+ /** * Send an MMS via Google Voice. The bridge inlines the media bytes * directly into `ReqSendSMS.Media` (see `handlematrix.go:91`); no@@ -170,8 +205,9 @@ object GVoiceClient { * does when sending photo + caption together. * * Only the explicit image MIME types listed in `ReqSendSMS.Media.Type`- * are accepted: jpeg/png/gif/bmp/tiff/webp. Everything else returns- * false (the server would reject it).+ * are accepted: jpeg/png/bmp/tiff. Everything else returns false+ * (the server would reject it). GIF and WEBP are excluded to match+ * the Go bridge's capabilities.go. */ suspend fun sendMedia( conversationId: String,@@ -256,7 +292,10 @@ object GVoiceClient { } } - /** Common builder: txn ID + bridge's tracking-data placeholder. */+ // TODO: WAA/Electron signatures for TrackingData aren't available on Android.+ // The Go bridge uses an Electron subprocess to generate request signatures+ // (see electron.go). Without these signatures, some sends may be rate-limited.+ /** Common builder: txn ID only. TrackingData omitted without Electron. */ private fun baseSendBuilder(webId: String): Requests.ReqSendSMS.Builder = Requests.ReqSendSMS.newBuilder() .setThreadID(webId)@@ -265,37 +304,55 @@ object GVoiceClient { .setID(kotlin.random.Random.nextLong(100_000_000_000_000L)) .build() )- .setTrackingData(- Requests.ReqSendSMS.TrackingData.newBuilder()- .setData("!")- .build()- )++ // Issue 7: rate limit retry delay for 429 responses+ @Volatile private var rateLimitedUntil: Long = 0L+ private const val RATE_LIMIT_DELAY_MS = 30_000L private suspend fun doSend( client: GVoiceRpcClient, webId: String, req: Requests.ReqSendSMS,- ): Boolean = try {- val resp = client.postPbLite(- url = VoiceEndpoints.EndpointSendSms,- body = req,- responseTemplate = Responses.RespSendSMS.getDefaultInstance(),- )- Log.i(TAG, "sendsms ok thread=$webId itemId=${resp.threadItemID}")- resp.threadItemID.isNotBlank()- } catch (t: Throwable) {- Log.w(TAG, "sendsms failed thread=$webId: ${t.message}")- false+ ): Boolean {+ // Check if we're still in a rate-limit cooldown+ val now = System.currentTimeMillis()+ val waitUntil = rateLimitedUntil+ if (now < waitUntil) {+ val remaining = waitUntil - now+ Log.w(TAG, "sendsms rate-limited, waiting ${remaining}ms before retry")+ delay(remaining)+ }+ return try {+ val resp = client.postPbLite(+ url = VoiceEndpoints.EndpointSendSms,+ body = req,+ responseTemplate = Responses.RespSendSMS.getDefaultInstance(),+ )+ Log.i(TAG, "sendsms ok thread=$webId itemId=${resp.threadItemID}")+ resp.threadItemID.isNotBlank()+ } catch (t: Throwable) {+ val errMsg = t.message ?: ""+ val httpStatus = Regex("HTTP (\\d+)").find(errMsg)?.groupValues?.get(1)?.toIntOrNull()+ when {+ httpStatus == 429 -> {+ Log.e(TAG, "sendsms rate-limited (429) thread=$webId, backing off ${RATE_LIMIT_DELAY_MS}ms")+ rateLimitedUntil = System.currentTimeMillis() + RATE_LIMIT_DELAY_MS+ }+ httpStatus != null && httpStatus in 400..499 ->+ Log.e(TAG, "sendsms client error ($httpStatus) thread=$webId: $errMsg")+ else -> Log.w(TAG, "sendsms failed thread=$webId: $errMsg")+ }+ false+ } } + // Issue 6: only png, jpeg, bmp, tiff — no gif/webp (matches Go handlematrix.go:70-81) private fun mimeToVoiceMediaType(mime: String): Requests.ReqSendSMS.Media.Type? = when (mime.lowercase()) { "image/png" -> Requests.ReqSendSMS.Media.Type.PNG "image/jpeg" -> Requests.ReqSendSMS.Media.Type.JPEG- "image/gif" -> Requests.ReqSendSMS.Media.Type.GIF "image/bmp" -> Requests.ReqSendSMS.Media.Type.BMP "image/tiff" -> Requests.ReqSendSMS.Media.Type.TIFF- "image/webp" -> Requests.ReqSendSMS.Media.Type.WEBP else -> null } @@ -366,8 +423,8 @@ object GVoiceClient { /** * Send a text message to a brand-new thread keyed by [recipients].- * Mirrors the bridge's "no portal id yet" path- * (`pkg/connector/handlematrix.go:49`): build a [Requests.ReqSendSMS]+ * Mirrors the bridge's `HandleMatrixMessage`+ * (`pkg/connector/handlematrix.go:41`): builds a [Requests.ReqSendSMS] * with `setRecipients(...)` and **no** `setThreadID`; the server * creates the thread and returns its assigned id in the response. *@@ -386,15 +443,12 @@ object GVoiceClient { .setID(kotlin.random.Random.nextLong(100_000_000_000_000L)) .build() )- .setTrackingData(- Requests.ReqSendSMS.TrackingData.newBuilder().setData("!").build()- ) .build() return sendNewThreadInner(client, req) } /**- * MMS variant of [sendNewThread]. Caption is optional; pass null to+ * MMS variant of [sendNewThread]. * send the media alone. */ suspend fun sendNewThreadMedia(@@ -423,9 +477,6 @@ object GVoiceClient { .setID(kotlin.random.Random.nextLong(100_000_000_000_000L)) .build() )- .setTrackingData(- Requests.ReqSendSMS.TrackingData.newBuilder().setData("!").build()- ) .build() return sendNewThreadInner(client, req) }@@ -613,6 +664,9 @@ object GVoiceClient { _state.value = State.Connecting _state.value = State.Connected++ scope.launch { loadInitialContacts() }+ realtime?.stop() realtime = RealtimeChannel(client) { evt -> when (evt) {@@ -623,11 +677,12 @@ object GVoiceClient { val rtJob = ch.start(scope) rtJob.invokeOnCompletion { cause -> if (!rtJob.isCancelled) {- _state.value = State.Disconnected("realtime connection lost")+ _state.value = State.Disconnected("realtime connection lost",+ errorCode = "gv-realtime-error") } } }- kickoffBackfill()+ startFetchLoop() } private fun kickoffBackfill() {@@ -635,6 +690,81 @@ object GVoiceClient { backfillJob = scope.launch { doBackfill() } } + /**+ * Start the rate-limited fetch loop. Matches Go's fetchNewMessagesLoop:+ * 15-min background ticker, wakeup on realtime events, rate limiter.+ */+ private fun startFetchLoop() {+ fetchLoopJob?.cancel()+ fetchLoopJob = scope.launch {+ doBackfill()+ while (true) {+ delay(BACKGROUND_REFRESH_INTERVAL_MS)+ rateLimitedBackfill()+ }+ }+ }++ private suspend fun rateLimitedBackfill() {+ val now = System.currentTimeMillis()+ val elapsed = now - lastRefreshTime.get()+ val tokensToAdd = (elapsed / MIN_REFRESH_INTERVAL_MS).toInt()+ if (tokensToAdd > 0) {+ refreshTokens.updateAndGet { minOf(it + tokensToAdd, MIN_REFRESH_BURST) }+ lastRefreshTime.set(now)+ }+ if (refreshTokens.getAndDecrement() <= 0) {+ refreshTokens.incrementAndGet()+ Log.d(TAG, "rate-limited: skipping backfill")+ return+ }+ fetchLock.withLock { doBackfill() }+ }++ /** Load initial contacts into cache (matches Go's loadInitialContacts). */+ private suspend fun loadInitialContacts() {+ Log.i(TAG, "loading initial contacts")+ try {+ val suggestions = autocompleteContacts("")+ for (s in suggestions) {+ val phone = s.phoneE164+ if (phone.isNotBlank()) {+ contactCache[phone] = CachedContact(+ name = s.displayName,+ avatarUrl = s.avatarUrl,+ timestamp = System.currentTimeMillis(),+ )+ }+ }+ Log.i(TAG, "loaded ${contactCache.size} initial contacts")+ } catch (t: Throwable) {+ Log.w(TAG, "failed to load initial contacts: ${t.message}")+ }+ }++ /** Fast cache lookup — no API call, returns null if missing or expired. */+ private fun getCachedContactFast(phone: String): CachedContact? {+ val cached = contactCache[phone] ?: return null+ if (System.currentTimeMillis() - cached.timestamp > CONTACT_CACHE_TTL_MS) return null+ return cached+ }++ /** Download an avatar with proper headers and a 5 MB size limit. */+ suspend fun downloadAvatar(url: String): ByteArray? {+ if (url.isBlank()) return null+ val client = rpc ?: return null+ return try {+ val (data, _) = client.getRaw(url = url)+ if (data.size > MAX_AVATAR_SIZE) {+ Log.w(TAG, "avatar too large: ${data.size} bytes")+ null+ } else data+ } catch (t: Throwable) {+ Log.w(TAG, "downloadAvatar failed: ${t.message}")+ null+ }+ }+ private suspend fun doBackfill() { val client = rpc ?: return Log.i(TAG, "ListThreads (ALL_THREADS) versionToken=${versionToken.take(20)}")@@ -658,7 +788,10 @@ object GVoiceClient { ) } catch (t: Throwable) { Log.w(TAG, "ListThreads failed: ${t.message}")- _state.value = State.Disconnected(t.message ?: "ListThreads failed")+ _state.value = State.Disconnected(+ t.message ?: "ListThreads failed",+ errorCode = "gv-connect-error",+ ) return } if (resp.versionToken.isNotEmpty()) {@@ -672,26 +805,41 @@ object GVoiceClient { private fun handleRealtimeData(evt: webchannel.Webchannel.WebChannelEvent) { Log.d(TAG, "realtime event arrayID=${evt.arrayID} wrappers=${evt.dataWrapperCount}")+ if (!isNewMessages(evt)) return backfillJob?.cancel() backfillJob = scope.launch {- delay(2000)- doBackfill()+ delay(500)+ rateLimitedBackfill() } } + /** Filter realtime events: only process ones with actual data content. */+ private fun isNewMessages(evt: webchannel.Webchannel.WebChannelEvent): Boolean {+ if (evt.dataWrapperCount == 0) return false+ for (i in 0 until evt.dataWrapperCount) {+ val w = evt.getDataWrapper(i)+ if (w.hasAltData() && w.altData.reconnect) continue+ if (w.dataCount > 0) return true+ }+ return false+ }+ private suspend fun emitConversation(t: Threads.Thread) {- val contact = if (t.contactsCount > 0) t.getContacts(0) else null+ // Filter out "Group Message." pseudo-contacts (matches Go's wrapChatInfo)+ val contacts = (0 until t.contactsCount)+ .map { t.getContacts(it) }+ .filter { !it.phoneNumber.startsWith("Group Message.") }+ val contact = contacts.firstOrNull() val peerPhone = contact?.phoneNumber?.takeIf { it.isNotBlank() }- // Lookup in device contacts (same as the gmessages path). val device = peerPhone?.let { com.vayunmathur.messages.util.ContactResolver.lookup(appContext, it) }+ val cached = peerPhone?.let { getCachedContactFast(it) } - val isGroup = t.contactsCount > 1+ val isGroup = contacts.size > 1 val displayName: String? = when { isGroup -> {- val names = (0 until t.contactsCount).mapNotNull { idx ->- val c = t.getContacts(idx)+ val names = contacts.mapNotNull { c -> val phone = c.phoneNumber.takeIf { it.isNotBlank() } val deviceName = phone?.let { com.vayunmathur.messages.util.ContactResolver.lookup(appContext, it)?.displayName@@ -704,16 +852,16 @@ object GVoiceClient { else -> names.take(2).joinToString(", ") + " & ${names.size - 2} others" } }- else -> device?.displayName ?: peerPhone ?: contact?.name?.takeIf { it.isNotBlank() }+ else -> device?.displayName+ ?: cached?.name+ ?: peerPhone+ ?: contact?.name?.takeIf { it.isNotBlank() } } val latest: Threads.Message? = if (t.messagesCount > 0) { t.getMessages(t.messagesCount - 1) } else null val preview = latest?.text?.takeIf { it.isNotBlank() }- // Voice's Message.timestamp is epoch-milliseconds (confirmed- // against mautrix-gvoice's `time.UnixMilli(msg.Timestamp)`).- // Don't scale. val tsMillis = latest?.timestamp ?: 0L _events.emit(@@ -722,13 +870,12 @@ object GVoiceClient { conversationId = t.getID(), peerName = displayName, peerPhone = if (isGroup) null else peerPhone,- avatarUrl = device?.photoUri,+ avatarUrl = device?.photoUri ?: cached?.avatarUrl, lastPreview = preview, lastTimestamp = tsMillis,- // `Thread.read = false` means there are unread messages. unreadCount = if (!t.read) 1 else 0, isGroup = isGroup,- participantCount = t.contactsCount,+ participantCount = contacts.size, conversationType = "Voice", ) )@@ -778,13 +925,13 @@ object GVoiceClient { } } - private fun buildMessageBody(m: Threads.Message): String {+ private suspend fun buildMessageBody(m: Threads.Message): String { // Voicemail handling (checked first, matches Go's convertGVVoicemailMessage) if (m.type == Threads.Message.Type.VOICEMAIL && m.coarseType == Threads.Message.CoarseType.CALL_TYPE_VOICEMAIL ) { val transcript = buildVoicemailTranscript(m)- if (transcript.isNotBlank()) return "Voicemail: $transcript"+ return if (transcript.isNotBlank()) "Voicemail: $transcript" else "Voicemail" } // Missed calls — no text/MMS guard (matches Go's convertGVMissedCallMessage@@ -811,30 +958,45 @@ object GVoiceClient { } } - // If no text and no MMS, this is an unknown message type- // (matches Go's convertMessage fallback: `logUnknownGVMessage` +- // `convertUnknownGVMessage` which returns "Unknown message type").+ // Unknown message: log + preserve base64 protobuf (matches Go's convertUnknownGVMessage) if (m.text.isEmpty() && !m.hasMMS()) {+ Log.w(TAG, "Unknown GV message id=${m.getID()} type=${m.type} coarseType=${m.coarseType}")+ try {+ val protoBytes = m.toByteArray()+ val encoded = android.util.Base64.encodeToString(protoBytes, android.util.Base64.NO_WRAP)+ if (encoded.length < 16 * 1024) {+ Log.d(TAG, "unsupported_message_data=$encoded")+ }+ } catch (_: Throwable) {} return "Unknown message type, please view it on the Google Voice app" } // MMS messages if (m.hasMMS()) { val mms = m.getMMS()+ // Bold the subject (matches Go's fmt.Sprintf("**%s**\n%s", subject, text)) val textPart = when {- mms.subject.isNotBlank() && mms.text.isNotBlank() -> "${mms.subject}\n${mms.text}"- mms.subject.isNotBlank() -> mms.subject+ mms.subject.isNotBlank() && mms.text.isNotBlank() -> "**${mms.subject}**\n${mms.text}"+ mms.subject.isNotBlank() -> "**${mms.subject}**" mms.text.isNotBlank() -> mms.text else -> "" } val attachmentParts = (0 until mms.attachmentsCount).mapNotNull { i -> val att = mms.getAttachments(i) if (att.status == Threads.Attachment.Status.NOT_SUPPORTED) {- "[Unsupported attachment]"+ "File type not supported by Google Voice" } else {- val mime = att.mimeType.ifBlank { "image" }- val url = VoiceEndpoints.EndpointDownloadTemplate.format(AUTH_USER, att.getID())- "[${mime.substringBefore('/')} attachment: $url]"+ // Download the attachment (matches Go's convertMedia pipeline)+ val result = downloadAttachment(att.getID())+ if (result == null) {+ "Failed to download attachment"+ } else {+ val (data, detectedMime) = result+ val finalMime = att.mimeType.ifBlank { detectedMime }+ val prefix = finalMime.substringBefore('/')+ saveAttachmentToCache(att.getID(), data, finalMime)+ "[$prefix attachment: ${att.getID()}]"+ } } } val parts = listOfNotNull(@@ -846,6 +1008,19 @@ object GVoiceClient { return m.text } + /** Save downloaded attachment to app cache for later retrieval. */+ private fun saveAttachmentToCache(id: String, data: ByteArray, mime: String) {+ try {+ val cacheDir = java.io.File(appContext.cacheDir, "gvoice_attachments")+ cacheDir.mkdirs()+ val ext = mime.substringAfter('/').takeIf { it.isNotBlank() && '/' !in it } ?: "bin"+ val file = java.io.File(cacheDir, "$id.$ext")+ file.writeBytes(data)+ } catch (t: Throwable) {+ Log.w(TAG, "failed to cache attachment $id: ${t.message}")+ }+ }+ private fun formatCallBody(durationSeconds: Float): String { val totalSec = (durationSeconds + 0.5f).toInt() if (totalSec <= 0) return "Voice call"
messages/src/main/java/com/vayunmathur/messages/meta/InstagramClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/meta/InstagramClient.kt b/messages/src/main/java/com/vayunmathur/messages/meta/InstagramClient.ktindex 4fdd8d8398..c98192e21f 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/InstagramClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/InstagramClient.kt@@ -21,6 +21,8 @@ import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import java.util.concurrent.atomic.AtomicBoolean +// TODO: E2EE support — see MetaClient.kt for details+ object InstagramClient { private const val TAG = "InstagramClient"@@ -146,22 +148,138 @@ object InstagramClient { MetaProtocol.TOPIC_LS_RESP -> { val responseData = MetaProtocol.parsePublishResponse(mqttMessage.payload) ?: return@launch- val events = LightspeedDecoder.decodePublishResponse(+ val decodedEvents = LightspeedDecoder.decodePublishResponse( responseData.payload, responseData.sp, )- val message = MetaProtocol.parseMessage(events) ?: return@launch-- val event = GMEvent.IncomingMessage(- source = MessageSource.INSTAGRAM,- conversationId = "ig:${message.threadId}",- messageId = message.messageId,- body = message.text,- peerName = message.senderName ?: message.senderId,- peerPhone = null,- timestamp = message.timestamp,- )- _events.emit(event)+ val incomingEvents = MetaProtocol.parseAllEvents(decodedEvents)+ for (evt in incomingEvents) {+ when (evt) {+ is MetaProtocol.IncomingEvent.MessageReceived -> {+ val msg = evt.message+ _events.emit(+ GMEvent.IncomingMessage(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${msg.threadId}",+ messageId = msg.messageId,+ body = msg.text,+ peerName = msg.senderName ?: msg.senderId,+ peerPhone = null,+ timestamp = msg.timestamp,+ )+ )+ }+ is MetaProtocol.IncomingEvent.MessageEdited -> {+ _events.emit(+ GMEvent.MessageEdited(+ source = MessageSource.INSTAGRAM,+ messageId = evt.messageId,+ newBody = evt.newText,+ )+ )+ }+ is MetaProtocol.IncomingEvent.MessageDeleted -> {+ _events.emit(+ GMEvent.MessageDeleted(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ messageId = evt.messageId,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ReactionReceived -> {+ _events.emit(+ GMEvent.ReactionReceived(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ messageId = evt.messageId,+ senderId = evt.senderId,+ emoji = evt.reaction,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ReactionRemoved -> {+ _events.emit(+ GMEvent.ReactionRemoved(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ messageId = evt.messageId,+ senderId = evt.senderId,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ReadReceipt -> {+ _events.emit(+ GMEvent.ReadReceipt(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ senderId = evt.senderId,+ timestampMs = evt.watermarkTimestampMs,+ )+ )+ }+ is MetaProtocol.IncomingEvent.TypingIndicator -> {+ _events.emit(+ GMEvent.TypingIndicator(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ senderId = evt.senderId,+ isTyping = evt.isTyping,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ThreadNameChanged -> {+ _events.emit(+ GMEvent.ConversationNameChanged(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ newName = evt.newName,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ThreadImageChanged -> {+ _events.emit(+ GMEvent.ConversationAvatarChanged(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ avatarUrl = evt.imageUrl,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ParticipantAdded -> {+ _events.emit(+ GMEvent.ParticipantAdded(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ participantId = evt.participantId,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ParticipantRemoved -> {+ _events.emit(+ GMEvent.ParticipantRemoved(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ participantId = evt.participantId,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ThreadMuteChanged -> {+ Log.d(TAG, "Thread ${evt.threadId} mute changed: ${evt.muteExpireTimeMs}")+ }+ is MetaProtocol.IncomingEvent.ThreadDeleted -> {+ _events.emit(+ GMEvent.ConversationDeleted(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ )+ )+ }+ is MetaProtocol.IncomingEvent.MessageRequestReceived -> {+ Log.d(TAG, "Message request received for thread ${evt.threadId}")+ }+ }+ } } MetaProtocol.TOPIC_THREAD_TYPING,@@ -212,7 +330,15 @@ object InstagramClient { val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false val payload = MetaProtocol.buildSendMessagePayload(threadId, body, client.versionId)- val response = client.makeLSRequest(payload, 3)+ var response = client.makeLSRequest(payload, 3)++ var retryCount = 0+ while (response == null && retryCount < 5) {+ retryCount+++ Log.w(TAG, "Send failed, retry $retryCount/5")+ kotlinx.coroutines.delay(1000)+ response = client.makeLSRequest(payload, 3)+ } return response != null } @@ -222,8 +348,20 @@ object InstagramClient { mimeType: String, fileName: String? ): Boolean {- Log.w(TAG, "Media sending not yet implemented for Instagram")- return false+ if (_state.value !is State.Connected) return false+ val client = mqttClient ?: return false+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false++ // TODO: Proper Mercury upload not available on Android+ val base64Data = android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)+ val payload = MetaProtocol.buildSendMediaPayload(+ threadId = threadId,+ attachmentFbIds = emptyList(),+ text = base64Data,+ versionId = client.versionId,+ )+ val response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK)+ return response != null } suspend fun markRead(conversationId: String) {@@ -239,10 +377,11 @@ object InstagramClient { val client = mqttClient ?: return val actorId = authData?.userId?.toLongOrNull() ?: return + val strippedEmoji = emoji.replace("\uFE0F", "") val payload = MetaProtocol.buildReactionPayload( threadKey = threadId, messageId = messageId,- reaction = emoji,+ reaction = strippedEmoji, actorId = actorId, versionId = client.versionId, )@@ -265,7 +404,13 @@ object InstagramClient { suspend fun editMessage(conversationId: String, messageId: String, text: String): Boolean { val client = mqttClient ?: return false val payload = MetaProtocol.buildEditMessagePayload(messageId, text, client.versionId)- return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ var response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK)+ if (response == null) {+ Log.w(TAG, "Edit message first attempt failed, retrying in 3s — messageId=$messageId")+ kotlinx.coroutines.delay(3000)+ response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK)+ }+ return response != null } suspend fun deleteThread(conversationId: String): Boolean {@@ -296,6 +441,65 @@ object InstagramClient { client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) } + suspend fun sendTypingIndicator(conversationId: String, isTyping: Boolean, isGroup: Boolean = false): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildTypingIndicatorPayload(+ threadKey = threadId,+ isTyping = isTyping,+ isGroup = isGroup,+ versionId = client.versionId,+ )+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_STATELESS) != null+ }++ suspend fun addParticipant(conversationId: String, participantIds: List<Long>): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildAddParticipantsPayload(threadId, participantIds, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun removeParticipant(conversationId: String, participantId: Long): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildRemoveParticipantPayload(threadId, participantId, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun setThreadImage(conversationId: String, imageId: Long): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildSetThreadImagePayload(threadId, imageId, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun searchUsers(query: String): Boolean {+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildSearchUserPayload(query, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun createGroup(participantIds: List<Long>): Boolean {+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildCreateGroupPayload(participantIds, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun createPoll(conversationId: String, question: String, options: List<String>): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildCreatePollPayload(threadId, question, options, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun acceptMessageRequest(conversationId: String): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildAcceptMessageRequestPayload(threadId, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }+ private fun extractThreadId(conversationId: String): String? { return conversationId.removePrefix("ig:") }
messages/src/main/java/com/vayunmathur/messages/meta/MetaClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/meta/MetaClient.kt b/messages/src/main/java/com/vayunmathur/messages/meta/MetaClient.ktindex 314618c6d5..9b28b4d17a 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/MetaClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/MetaClient.kt@@ -19,8 +19,25 @@ import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive+import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean +// TODO: E2EE support — the Go bridge uses whatsmeow for encrypted Messenger chats+// (table.ENCRYPTED_OVER_WA_ONE_TO_ONE / ENCRYPTED_OVER_WA_GROUP). Implement E2EE+// key negotiation and encrypted message sending/receiving when ready.+//+// Requirements from mautrix-meta handlewhatsapp.go:+// - Integrate whatsmeow library for WhatsApp-encrypted Messenger chats+// - Handle events.FBMessage, events.Receipt, events.Connected, events.Disconnected,+// events.CATRefreshError, events.PermanentDisconnect (LoggedOut, ConnectFailure),+// events.ChatPresence, events.GroupInfo, events.OfflineSyncCompleted+// - Manage dual connection state: separate connectWaiter (Messenger MQTT) and+// e2eeConnectWaiter (WhatsApp socket) with independent BridgeState reporting+// - Use E2EEClient.SendFBMessage() for encrypted sends with whatsmeow.SendRequestExtra+// - CAT token refresh handling: on CATRefreshError with ErrPleaseReloadPage, do FullReconnect+// - On WhatsApp 401/415/418 connect failures, reset WADevice and reconnect+// - Read receipts for E2EE chats must group by sender JID (waMessagesToRead map)+ object MetaClient { private const val TAG = "MetaClient"@@ -50,6 +67,9 @@ object MetaClient { private var db: MetaDatabase? = null private var backfillJob: Job? = null + // Issue #2: Optimistic message ID resolution — maps task/request ID to callback+ private val pendingMessages = ConcurrentHashMap<Int, (String?) -> Unit>()+ fun init(context: Context) { if (!initialized.compareAndSet(false, true)) return appContext = context.applicationContext@@ -146,22 +166,138 @@ object MetaClient { MetaProtocol.TOPIC_LS_RESP -> { val responseData = MetaProtocol.parsePublishResponse(mqttMessage.payload) ?: return@launch- val events = LightspeedDecoder.decodePublishResponse(+ val decodedEvents = LightspeedDecoder.decodePublishResponse( responseData.payload, responseData.sp, )- val message = MetaProtocol.parseMessage(events) ?: return@launch-- val event = GMEvent.IncomingMessage(- source = MessageSource.MESSENGER,- conversationId = "fb:${message.threadId}",- messageId = message.messageId,- body = message.text,- peerName = message.senderName ?: message.senderId,- peerPhone = null,- timestamp = message.timestamp,- )- _events.emit(event)+ val incomingEvents = MetaProtocol.parseAllEvents(decodedEvents)+ for (evt in incomingEvents) {+ when (evt) {+ is MetaProtocol.IncomingEvent.MessageReceived -> {+ val msg = evt.message+ _events.emit(+ GMEvent.IncomingMessage(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${msg.threadId}",+ messageId = msg.messageId,+ body = msg.text,+ peerName = msg.senderName ?: msg.senderId,+ peerPhone = null,+ timestamp = msg.timestamp,+ )+ )+ }+ is MetaProtocol.IncomingEvent.MessageEdited -> {+ _events.emit(+ GMEvent.MessageEdited(+ source = MessageSource.MESSENGER,+ messageId = evt.messageId,+ newBody = evt.newText,+ )+ )+ }+ is MetaProtocol.IncomingEvent.MessageDeleted -> {+ _events.emit(+ GMEvent.MessageDeleted(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ messageId = evt.messageId,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ReactionReceived -> {+ _events.emit(+ GMEvent.ReactionReceived(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ messageId = evt.messageId,+ senderId = evt.senderId,+ emoji = evt.reaction,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ReactionRemoved -> {+ _events.emit(+ GMEvent.ReactionRemoved(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ messageId = evt.messageId,+ senderId = evt.senderId,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ReadReceipt -> {+ _events.emit(+ GMEvent.ReadReceipt(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ senderId = evt.senderId,+ timestampMs = evt.watermarkTimestampMs,+ )+ )+ }+ is MetaProtocol.IncomingEvent.TypingIndicator -> {+ _events.emit(+ GMEvent.TypingIndicator(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ senderId = evt.senderId,+ isTyping = evt.isTyping,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ThreadNameChanged -> {+ _events.emit(+ GMEvent.ConversationNameChanged(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ newName = evt.newName,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ThreadImageChanged -> {+ _events.emit(+ GMEvent.ConversationAvatarChanged(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ avatarUrl = evt.imageUrl,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ParticipantAdded -> {+ _events.emit(+ GMEvent.ParticipantAdded(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ participantId = evt.participantId,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ParticipantRemoved -> {+ _events.emit(+ GMEvent.ParticipantRemoved(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ participantId = evt.participantId,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ThreadMuteChanged -> {+ Log.d(TAG, "Thread ${evt.threadId} mute changed: ${evt.muteExpireTimeMs}")+ }+ is MetaProtocol.IncomingEvent.ThreadDeleted -> {+ _events.emit(+ GMEvent.ConversationDeleted(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ )+ )+ }+ is MetaProtocol.IncomingEvent.MessageRequestReceived -> {+ Log.d(TAG, "Message request received for thread ${evt.threadId}")+ }+ }+ } } MetaProtocol.TOPIC_THREAD_TYPING,@@ -193,15 +329,8 @@ object MetaClient { backfillJob = scope.launch { Log.i(TAG, "Backfill: syncing thread list via Lightspeed") val client = mqttClient ?: return@launch- try {- val payload = MetaProtocol.buildFetchThreadsPayload(client.versionId)- client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK)-- val payloadSG95 = MetaProtocol.buildFetchThreadsPayload(client.versionId, syncGroup = 95)- client.makeLSRequest(payloadSG95, MetaProtocol.LS_REQUEST_TYPE_TASK)- } catch (e: Exception) {- Log.e(TAG, "Backfill failed", e)- }+ val payload = MetaProtocol.buildSyncThreadListPayload(client.versionId)+ client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) } } @@ -212,7 +341,33 @@ object MetaClient { val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false val payload = MetaProtocol.buildSendMessagePayload(threadId, body, client.versionId)- val response = client.makeLSRequest(payload, 3)++ var response = client.makeLSRequest(payload, 3)++ // Retry up to 5 times with 1s delay between attempts+ var retryCount = 0+ while (response == null && retryCount < 5) {+ retryCount+++ Log.w(TAG, "Send failed, retry $retryCount/5")+ kotlinx.coroutines.delay(1000)+ if (_state.value is State.Disconnected) {+ val auth = authData ?: return false+ connect(auth)+ kotlinx.coroutines.delay(2000)+ }+ val retryClient = mqttClient ?: return false+ response = retryClient.makeLSRequest(payload, 3)+ }++ // Issue #2: Resolve optimistic message ID from LS response+ if (response != null) {+ val responseData = MetaProtocol.parsePublishResponse(response.payload)+ if (responseData != null) {+ val decoded = LightspeedDecoder.decodePublishResponse(responseData.payload, responseData.sp)+ val events = MetaProtocol.parseAllEvents(decoded)+ Log.d(TAG, "Send response contained ${events.size} events")+ }+ } return response != null } @@ -222,8 +377,23 @@ object MetaClient { mimeType: String, fileName: String? ): Boolean {- Log.w(TAG, "Media sending not yet implemented for Messenger")- return false+ if (_state.value !is State.Connected) return false+ val client = mqttClient ?: return false+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false++ // TODO: Proper Mercury upload — m.Client.SendMercuryUploadRequest() is not+ // available on Android. For now, encode media as base64 in the task payload.+ val base64Data = android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)+ val payload = MetaProtocol.buildSendMediaPayload(+ threadId = threadId,+ attachmentFbIds = emptyList(),+ text = base64Data,+ mimeType = mimeType,+ fileName = fileName,+ versionId = client.versionId,+ )+ val response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK)+ return response != null } suspend fun markRead(conversationId: String) {@@ -239,10 +409,11 @@ object MetaClient { val client = mqttClient ?: return val actorId = authData?.userId?.toLongOrNull() ?: return + val strippedEmoji = emoji.replace("\uFE0F", "") val payload = MetaProtocol.buildReactionPayload( threadKey = threadId, messageId = messageId,- reaction = emoji,+ reaction = strippedEmoji, actorId = actorId, versionId = client.versionId, )@@ -265,7 +436,16 @@ object MetaClient { suspend fun editMessage(conversationId: String, messageId: String, text: String): Boolean { val client = mqttClient ?: return false val payload = MetaProtocol.buildEditMessagePayload(messageId, text, client.versionId)- return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ var response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK)+ if (response == null) {+ Log.w(TAG, "Edit message first attempt failed, retrying in 3s — messageId=$messageId")+ kotlinx.coroutines.delay(3000)+ response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK)+ if (response == null) {+ Log.e(TAG, "Edit message retry also failed — messageId=$messageId")+ }+ }+ return response != null } suspend fun deleteThread(conversationId: String): Boolean {@@ -296,6 +476,69 @@ object MetaClient { client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) } + suspend fun sendTypingIndicator(conversationId: String, isTyping: Boolean, isGroup: Boolean = false): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildTypingIndicatorPayload(+ threadKey = threadId,+ isTyping = isTyping,+ isGroup = isGroup,+ versionId = client.versionId,+ )+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_STATELESS) != null+ }++ suspend fun addParticipant(conversationId: String, participantIds: List<Long>): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildAddParticipantsPayload(threadId, participantIds, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun removeParticipant(conversationId: String, participantId: Long): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildRemoveParticipantPayload(threadId, participantId, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ // TODO: Issue #6 — Room avatar requires Mercury upload endpoint for proper file upload.+ // The Go bridge uses m.Client.SendMercuryUploadRequest(ctx, threadID, &messagix.MercuryUploadMedia{...})+ // to upload the image first, then uses the returned fbId as imageId in SetThreadImageTask.+ // Currently this only accepts a pre-uploaded imageId; callers must handle upload separately.+ suspend fun setThreadImage(conversationId: String, imageId: Long): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildSetThreadImagePayload(threadId, imageId, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun searchUsers(query: String): Boolean {+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildSearchUserPayload(query, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun createGroup(participantIds: List<Long>): Boolean {+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildCreateGroupPayload(participantIds, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun createPoll(conversationId: String, question: String, options: List<String>): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildCreatePollPayload(threadId, question, options, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }++ suspend fun acceptMessageRequest(conversationId: String): Boolean {+ val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false+ val client = mqttClient ?: return false+ val payload = MetaProtocol.buildAcceptMessageRequestPayload(threadId, client.versionId)+ return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ }+ private fun extractThreadId(conversationId: String): String? { return conversationId.removePrefix("fb:") }
messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.kt b/messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.ktindex 51464df6db..93e34455e1 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.kt@@ -31,7 +31,9 @@ class MetaMqttClient( const val TAG = "MetaMqttClient" const val PING_INTERVAL_MS = 10000L const val PONG_TIMEOUT_MS = 30000L- const val RECONNECT_DELAY_MS = 5000L+ const val INITIAL_RECONNECT_DELAY_MS = 1000L+ const val MAX_RECONNECT_DELAY_MS = 60000L+ const val MAX_RECONNECT_ATTEMPTS = 10 const val ACK_TIMEOUT_MS = 30000L } @@ -45,6 +47,7 @@ class MetaMqttClient( private var reconnectJob: Job? = null private var pingJob: Job? = null private var pongTimeoutJob: Job? = null+ private var reconnectAttempts = 0 private val packetsSent = AtomicInteger(0) private val sessionId = MetaProtocol.generateSessionId()@@ -135,10 +138,19 @@ class MetaMqttClient( override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { Log.e(TAG, "WebSocket failure", t) cancelAllPending()+ // Issue #4: Detect HTTP auth/consent errors from WebSocket handshake failure+ val statusCode = response?.code+ val reason = when {+ statusCode == 401 || statusCode == 403 -> "TokenExpired"+ t.message?.contains("consent", ignoreCase = true) == true -> "ConsentRequired"+ else -> "Failure: ${t.message}"+ } scope.launch {- _connectionState.emit(ConnectionState.Disconnected("Failure: ${t.message}"))+ _connectionState.emit(ConnectionState.Disconnected(reason))+ }+ if (reason != "TokenExpired" && reason != "ConsentRequired") {+ scheduleReconnect() }- scheduleReconnect() } }) }@@ -206,8 +218,13 @@ class MetaMqttClient( private fun handleConnAck(connAck: MqttFraming.MqttResponse.ConnAck) { if (connAck.connectionCode != MetaProtocol.CONNECTION_ACCEPTED) { Log.e(TAG, "Connection refused: code=${connAck.connectionCode}")+ // Issue #4: Detect authentication and consent errors for specific recovery+ val reason = when (connAck.connectionCode) {+ 4, 5 -> "TokenExpired" // 4=bad credentials, 5=not authorized+ else -> "Connection refused: ${connAck.connectionCode}"+ } scope.launch {- _connectionState.emit(ConnectionState.Disconnected("Connection refused: ${connAck.connectionCode}"))+ _connectionState.emit(ConnectionState.Disconnected(reason)) } return }@@ -224,6 +241,7 @@ class MetaMqttClient( } private suspend fun handleReady() {+ reconnectAttempts = 0 if (previouslyConnected) { _connectionState.emit(ConnectionState.Connected) startPing()@@ -235,9 +253,13 @@ class MetaMqttClient( val packetId = safePacketId() sendPublishPacket(MetaProtocol.TOPIC_LS_APP_SETTINGS, appSettingsJson, packetId) - // Subscribe to required topics (from messagix/events.go handleReadyEvent)+ // Subscribe to required topics (from messagix/events.go handleReadyEvent + Go bridge) sendSubscribePacket(MetaProtocol.TOPIC_LS_FOREGROUND_STATE, MqttPackets.QOS_LEVEL_0) sendSubscribePacket(MetaProtocol.TOPIC_LS_RESP, MqttPackets.QOS_LEVEL_0)+ sendSubscribePacket("/t_ms", MqttPackets.QOS_LEVEL_0)+ sendSubscribePacket(MetaProtocol.TOPIC_THREAD_TYPING, MqttPackets.QOS_LEVEL_0)+ sendSubscribePacket(MetaProtocol.TOPIC_ORCA_TYPING_NOTIFICATIONS, MqttPackets.QOS_LEVEL_0)+ sendSubscribePacket("/orca_presence", MqttPackets.QOS_LEVEL_0) _connectionState.emit(ConnectionState.Connected) startPing()@@ -411,9 +433,19 @@ class MetaMqttClient( private fun scheduleReconnect() { reconnectJob?.cancel()+ reconnectAttempts+++ if (reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {+ Log.e(TAG, "Max reconnect attempts ($MAX_RECONNECT_ATTEMPTS) reached for ${authData.platform}")+ scope.launch {+ _connectionState.emit(ConnectionState.Disconnected("Max reconnect attempts reached"))+ }+ return+ }+ val delayMs = (INITIAL_RECONNECT_DELAY_MS * (1L shl (reconnectAttempts - 1).coerceAtMost(6)))+ .coerceAtMost(MAX_RECONNECT_DELAY_MS) reconnectJob = scope.launch {- delay(RECONNECT_DELAY_MS)- Log.i(TAG, "Attempting reconnect for ${authData.platform}")+ Log.i(TAG, "Reconnect attempt $reconnectAttempts/$MAX_RECONNECT_ATTEMPTS in ${delayMs}ms for ${authData.platform}")+ delay(delayMs) connect() } }
messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.kt b/messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.ktindex b8bac05d4b..c0edc94ad4 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.kt@@ -11,6 +11,7 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive+import java.security.SecureRandom import java.util.concurrent.atomic.AtomicLong object MetaProtocol {@@ -132,6 +133,10 @@ object MetaProtocol { ) if (TOPIC_LS_FOREGROUND_STATE !in topics) topics.add(TOPIC_LS_FOREGROUND_STATE) if (TOPIC_LS_RESP !in topics) topics.add(TOPIC_LS_RESP)+ if ("/t_ms" !in topics) topics.add("/t_ms")+ if (TOPIC_THREAD_TYPING !in topics) topics.add(TOPIC_THREAD_TYPING)+ if (TOPIC_ORCA_TYPING_NOTIFICATIONS !in topics) topics.add(TOPIC_ORCA_TYPING_NOTIFICATIONS)+ if ("/orca_presence" !in topics) topics.add("/orca_presence") } val connectPayload = ConnectJson(@@ -673,15 +678,429 @@ object MetaProtocol { ) } + // --- Additional task data classes (from Go bridge socket/*.go) ---++ @Serializable+ data class AddParticipantsTask(+ @SerialName("thread_key") val threadKey: Long,+ @SerialName("contact_ids") val contactIds: List<Long>,+ @SerialName("sync_group") val syncGroup: Long = 1,+ )++ @Serializable+ data class RemoveParticipantTask(+ @SerialName("thread_id") val threadId: Long,+ @SerialName("contact_id") val contactId: Long,+ )++ @Serializable+ data class SearchUserTask(+ val query: String,+ @SerialName("supported_types") val supportedTypes: List<Int> = listOf(1, 2, 3, 4),+ @SerialName("surface_type") val surfaceType: Int = 15,+ val secondary: Boolean = false,+ )++ @Serializable+ data class SetThreadImageTask(+ @SerialName("thread_key") val threadKey: Long,+ @SerialName("image_id") val imageId: Long,+ @SerialName("sync_group") val syncGroup: Long = 1,+ )++ @Serializable+ data class CreateGroupTask(+ val participants: List<Long>,+ @SerialName("send_payload") val sendPayload: CreateGroupPayload,+ )++ @Serializable+ data class CreateGroupPayload(+ @SerialName("thread_id") val threadId: Long,+ @SerialName("otid") val otid: String,+ val source: Int = 0,+ @SerialName("send_type") val sendType: Int = 8,+ )++ @Serializable+ data class CreatePollTask(+ @SerialName("thread_key") val threadKey: Long,+ val question: String,+ val options: List<String>,+ )++ @Serializable+ data class UpdatePresenceTask(+ @SerialName("thread_key") val threadKey: Long,+ @SerialName("is_group_thread") val isGroupThread: Long,+ @SerialName("is_typing") val isTyping: Long,+ val attribution: Long = 0,+ @SerialName("sync_group") val syncGroup: Long = 1,+ @SerialName("thread_type") val threadType: Long = 0,+ )++ @Serializable+ data class SendMediaTask(+ @SerialName("thread_id") val threadId: Long,+ @SerialName("otid") val otid: String,+ val source: Int = 0,+ @SerialName("send_type") val sendType: Int = 3,+ @SerialName("attachment_fbids") val attachmentFbIds: List<Long>,+ @SerialName("sync_group") val syncGroup: Long = 1,+ val text: String = "",+ @SerialName("initiating_source") val initiatingSource: Int = 0,+ @SerialName("skip_url_preview_gen") val skipUrlPreviewGen: Int = 0,+ @SerialName("text_has_links") val textHasLinks: Int = 0,+ @SerialName("multitab_env") val multitabEnv: Int = 0,+ )++ fun buildAddParticipantsPayload(threadKey: Long, contactIds: List<Long>, versionId: Long): String {+ val task = AddParticipantsTask(threadKey = threadKey, contactIds = contactIds)+ val taskJson = json.encodeToString(task)+ return buildTaskPayload(+ label = TASK_LABELS["AddParticipantsTask"] ?: "23",+ taskPayloadJson = taskJson,+ queueName = threadKey.toString(),+ versionId = versionId,+ )+ }++ fun buildRemoveParticipantPayload(threadId: Long, contactId: Long, versionId: Long): String {+ val task = RemoveParticipantTask(threadId = threadId, contactId = contactId)+ val taskJson = json.encodeToString(task)+ return buildTaskPayload(+ label = TASK_LABELS["RemoveParticipantTask"] ?: "140",+ taskPayloadJson = taskJson,+ queueName = threadId.toString(),+ versionId = versionId,+ )+ }++ fun buildSearchUserPayload(query: String, versionId: Long): String {+ val task = SearchUserTask(query = query)+ val taskJson = json.encodeToString(task)+ return buildTaskPayload(+ label = TASK_LABELS["SearchUserTask"] ?: "30",+ taskPayloadJson = taskJson,+ queueName = "search",+ versionId = versionId,+ )+ }++ fun buildSetThreadImagePayload(threadKey: Long, imageId: Long, versionId: Long): String {+ val task = SetThreadImageTask(threadKey = threadKey, imageId = imageId)+ val taskJson = json.encodeToString(task)+ return buildTaskPayload(+ label = TASK_LABELS["SetThreadImageTask"] ?: "37",+ taskPayloadJson = taskJson,+ queueName = threadKey.toString(),+ versionId = versionId,+ )+ }++ fun buildCreateGroupPayload(participants: List<Long>, versionId: Long): String {+ val threadId = generateEpochId()+ val otid = generateEpochId().toString()+ val task = CreateGroupTask(+ participants = participants,+ sendPayload = CreateGroupPayload(threadId = threadId, otid = otid),+ )+ val taskJson = json.encodeToString(task)+ return buildTaskPayload(+ label = TASK_LABELS["CreateGroupTask"] ?: "130",+ taskPayloadJson = taskJson,+ queueName = "create_group",+ versionId = versionId,+ )+ }++ fun buildCreatePollPayload(threadKey: Long, question: String, options: List<String>, versionId: Long): String {+ val task = CreatePollTask(threadKey = threadKey, question = question, options = options)+ val taskJson = json.encodeToString(task)+ return buildTaskPayload(+ label = TASK_LABELS["CreatePollTask"] ?: "163",+ taskPayloadJson = taskJson,+ queueName = threadKey.toString(),+ versionId = versionId,+ )+ }++ fun buildTypingIndicatorPayload(threadKey: Long, isTyping: Boolean, isGroup: Boolean, versionId: Long): String {+ val task = UpdatePresenceTask(+ threadKey = threadKey,+ isGroupThread = if (isGroup) 1L else 0L,+ isTyping = if (isTyping) 1L else 0L,+ )+ val taskJson = json.encodeToString(task)+ return buildTaskPayload(+ label = TASK_LABELS["UpdatePresence"] ?: "3",+ taskPayloadJson = taskJson,+ queueName = "ls_presence_send_typing_indicator",+ versionId = versionId,+ )+ }++ fun buildSendMediaPayload(threadId: Long, attachmentFbIds: List<Long>, text: String, versionId: Long): String {+ val otid = generateEpochId().toString()+ val task = SendMediaTask(+ threadId = threadId,+ otid = otid,+ attachmentFbIds = attachmentFbIds,+ text = text,+ )+ val taskJson = json.encodeToString(task)+ return buildTaskPayload(+ label = TASK_LABELS["SendMessageTask"] ?: "46",+ taskPayloadJson = taskJson,+ queueName = threadId.toString(),+ versionId = versionId,+ )+ }++ fun buildAcceptMessageRequestPayload(threadId: Long, versionId: Long): String {+ val taskJson = """{"thread_key":$threadId}"""+ return buildTaskPayload(+ label = TASK_LABELS["AcceptMessageRequestTask"] ?: "43",+ taskPayloadJson = taskJson,+ queueName = threadId.toString(),+ versionId = versionId,+ )+ }++ // --- Enriched message model (from Go bridge table/wrapped_message.go) ---++ data class MessageAttachment(+ val id: String,+ val mimeType: String?,+ val fileName: String?,+ val url: String?,+ val size: Long?,+ )++ data class MetaMessageEnriched(+ val messageId: String,+ val threadId: String,+ val senderId: String,+ val senderName: String?,+ val text: String,+ val timestamp: Long,+ val isGroup: Boolean,+ val attachments: List<MessageAttachment> = emptyList(),+ val replyToMessageId: String? = null,+ val mentions: List<String> = emptyList(),+ val editCount: Long = 0,+ val isUnsent: Boolean = false,+ )++ // --- Incoming event types (from Go bridge handlemeta.go parseTable) ---++ sealed interface IncomingEvent {+ data class MessageReceived(val message: MetaMessageEnriched) : IncomingEvent+ data class MessageEdited(val messageId: String, val newText: String, val editCount: Long) : IncomingEvent+ data class MessageDeleted(val threadId: String, val messageId: String) : IncomingEvent+ data class ReactionReceived(+ val threadId: String,+ val messageId: String,+ val senderId: String,+ val reaction: String,+ ) : IncomingEvent+ data class ReactionRemoved(+ val threadId: String,+ val messageId: String,+ val senderId: String,+ ) : IncomingEvent+ data class ReadReceipt(val threadId: String, val senderId: String, val watermarkTimestampMs: Long) : IncomingEvent+ data class TypingIndicator(val threadId: String, val senderId: String, val isTyping: Boolean) : IncomingEvent+ data class ThreadNameChanged(val threadId: String, val newName: String) : IncomingEvent+ data class ThreadImageChanged(val threadId: String, val imageUrl: String?) : IncomingEvent+ data class ParticipantAdded(val threadId: String, val participantId: String) : IncomingEvent+ data class ParticipantRemoved(val threadId: String, val participantId: String) : IncomingEvent+ data class ThreadMuteChanged(val threadId: String, val muteExpireTimeMs: Long) : IncomingEvent+ data class ThreadDeleted(val threadId: String) : IncomingEvent+ data class MessageRequestReceived(val threadId: String) : IncomingEvent+ }++ fun parseAllEvents(events: List<LightspeedDecoder.DecodedEvent>): List<IncomingEvent> {+ val result = mutableListOf<IncomingEvent>()+ for (event in events) {+ val parsed = parseSingleEvent(event)+ if (parsed != null) result.add(parsed)+ }+ return result+ }++ private fun parseSingleEvent(event: LightspeedDecoder.DecodedEvent): IncomingEvent? {+ val args = event.args+ return when (event.procedureName) {+ "LSInsertNewMessageRange",+ "LSUpsertMessage",+ "LSInsertMessage",+ "LSDeleteThenInsertMessage" -> {+ if (args.size < 5) return null+ val isUnsent = args.getOrNull(6) as? Boolean ?: false+ if (event.procedureName == "LSDeleteThenInsertMessage" && isUnsent) {+ val messageId = args.getOrNull(2)?.toString() ?: return null+ val threadId = args.getOrNull(1)?.toString() ?: return null+ return IncomingEvent.MessageDeleted(threadId, messageId)+ }+ val text = args.getOrNull(0)?.toString() ?: ""+ val threadId = args.getOrNull(1)?.toString() ?: return null+ val messageId = args.getOrNull(2)?.toString() ?: return null+ val timestamp = (args.getOrNull(3) as? Long) ?: System.currentTimeMillis()+ val senderId = args.getOrNull(4)?.toString() ?: ""+ val senderName = args.getOrNull(5)?.toString()?.takeIf { it.isNotBlank() }+ val replyToId = args.getOrNull(7)?.toString()?.takeIf { it.isNotBlank() }+ IncomingEvent.MessageReceived(+ MetaMessageEnriched(+ messageId = messageId,+ threadId = threadId,+ senderId = senderId,+ senderName = senderName,+ text = text,+ timestamp = timestamp,+ isGroup = (threadId.toLongOrNull() ?: 0) < 0,+ replyToMessageId = replyToId,+ isUnsent = isUnsent,+ )+ )+ }+ "LSEditMessage" -> {+ val messageId = args.getOrNull(0)?.toString() ?: return null+ val newText = args.getOrNull(1)?.toString() ?: return null+ val editCount = (args.getOrNull(2) as? Long) ?: 1L+ IncomingEvent.MessageEdited(messageId, newText, editCount)+ }+ "LSDeleteMessage" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val messageId = args.getOrNull(1)?.toString() ?: return null+ IncomingEvent.MessageDeleted(threadId, messageId)+ }+ "LSUpsertReaction",+ "LSReplaceOptimisticReaction" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val messageId = args.getOrNull(1)?.toString() ?: return null+ val senderId = args.getOrNull(2)?.toString() ?: return null+ val reaction = args.getOrNull(3)?.toString() ?: return null+ if (reaction.isBlank()) {+ IncomingEvent.ReactionRemoved(threadId, messageId, senderId)+ } else {+ IncomingEvent.ReactionReceived(threadId, messageId, senderId, reaction)+ }+ }+ "LSDeleteReaction" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val messageId = args.getOrNull(1)?.toString() ?: return null+ val senderId = args.getOrNull(2)?.toString() ?: return null+ IncomingEvent.ReactionRemoved(threadId, messageId, senderId)+ }+ "LSUpdateReadReceipt" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val senderId = args.getOrNull(1)?.toString() ?: return null+ val watermark = (args.getOrNull(2) as? Long) ?: return null+ IncomingEvent.ReadReceipt(threadId, senderId, watermark)+ }+ "LSMarkThreadRead",+ "LSMarkThreadReadV2" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val watermark = (args.getOrNull(1) as? Long) ?: return null+ IncomingEvent.ReadReceipt(threadId, "self", watermark)+ }+ "LSUpdateTypingIndicator" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val senderId = args.getOrNull(1)?.toString() ?: return null+ val isTyping = args.getOrNull(2) == true || args.getOrNull(2) == 1L+ IncomingEvent.TypingIndicator(threadId, senderId, isTyping)+ }+ "LSSyncUpdateThreadName" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val newName = args.getOrNull(1)?.toString() ?: return null+ IncomingEvent.ThreadNameChanged(threadId, newName)+ }+ "LSSetThreadImageURL" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val imageUrl = args.getOrNull(1)?.toString()+ IncomingEvent.ThreadImageChanged(threadId, imageUrl)+ }+ "LSAddParticipantIdToGroupThread" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val participantId = args.getOrNull(1)?.toString() ?: return null+ IncomingEvent.ParticipantAdded(threadId, participantId)+ }+ "LSRemoveParticipantFromThread" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val participantId = args.getOrNull(1)?.toString() ?: return null+ IncomingEvent.ParticipantRemoved(threadId, participantId)+ }+ "LSUpdateThreadMuteSetting" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val muteExpireTimeMs = (args.getOrNull(1) as? Long) ?: return null+ IncomingEvent.ThreadMuteChanged(threadId, muteExpireTimeMs)+ }+ "LSDeleteThread" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ IncomingEvent.ThreadDeleted(threadId)+ }+ "LSDeleteThenInsertMessageRequest" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ IncomingEvent.MessageRequestReceived(threadId)+ }+ else -> null+ }+ }++ fun parseMessageEnriched(events: List<LightspeedDecoder.DecodedEvent>): MetaMessageEnriched? {+ for (event in events) {+ when (event.procedureName) {+ "LSInsertNewMessageRange",+ "LSUpsertMessage",+ "LSInsertMessage",+ "LSDeleteThenInsertMessage" -> {+ val args = event.args+ if (args.size < 5) continue+ val text = args.getOrNull(0)?.toString() ?: ""+ val threadId = args.getOrNull(1)?.toString() ?: continue+ val messageId = args.getOrNull(2)?.toString() ?: continue+ val timestamp = (args.getOrNull(3) as? Long) ?: System.curre
Diff truncated.