messages: various fixes
- Commit
e13e818d594ca6b714956be0908d98fd99cf21b6- Author
- Vayun Mathur <[email protected]>
- When
- 2026-06-12 20:49 UTC (5 months ago)
- Parents
256446b
Diff
messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.ktindex cfda655e01..d48c9cfb9b 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt@@ -74,7 +74,7 @@ data class AuthData( fun authNetwork(): String = if (isGoogleAccount()) "GDitto" else "" - fun hasCookies(): Boolean = if (!isGoogleAccount()) true else cookies != null+ fun hasCookies(): Boolean = !cookies.isNullOrEmpty() /** Decode the tachyon token back to raw bytes. */ fun tachyonToken(): ByteArray? =
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 cbb0699b75..5acc0ef733 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt@@ -87,6 +87,7 @@ sealed interface GMEvent { val senderId: String? = null, val timestampMs: Long = 0L, val timestamp: Long = 0L,+ val isDelivery: Boolean = false, ) : GMEvent /** A conversation was deleted on the remote side. */@@ -147,4 +148,36 @@ sealed interface GMEvent { val conversationId: String, val participantId: String, ) : GMEvent++ /** A conversation's mute setting changed. */+ data class MuteSettingChanged(+ override val source: MessageSource,+ val conversationId: String,+ val muteExpireTimeMs: Long,+ ) : GMEvent++ /** A message request was received for a conversation. */+ data class MessageRequestReceived(+ override val source: MessageSource,+ val conversationId: String,+ ) : GMEvent++ /** A message send failed with a detailed error. */+ data class SendFailed(+ override val source: MessageSource,+ val conversationId: String,+ val messageId: String? = null,+ val tmpId: String? = null,+ val errorMessage: String,+ ) : GMEvent++ /** A decryption error occurred (matching Go: DecryptionError event). */+ data class DecryptionError(+ override val source: MessageSource,+ val conversationId: String,+ val senderAci: String,+ val senderDeviceId: Int,+ val timestamp: Long,+ val errorMessage: String? = null,+ ) : 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 9c21f1ddb5..130f525584 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt@@ -138,6 +138,7 @@ object GMessagesClient { @Volatile private var ready = false @Volatile private var phoneResponding = true @Volatile private var noDataReceivedRecently = false+ @Volatile private var longPollingError: String? = null @Volatile private var lastDataReceived = System.currentTimeMillis() @Volatile private var batteryLow = false @Volatile private var mobileData = false@@ -167,6 +168,28 @@ object GMessagesClient { private var recentUpdatesPtr = 0 private val dedupLock = Any() + // --- Per-message metadata for status state machine (port of Go MessageMetadata) ---+ private class MessageMeta {+ var isOutgoing = false+ var statusNum: Int = 0+ var textHash = ""+ var globalPartCount = 0+ var mssSent = false+ var mssFailSent = false+ var mssDeliverySent = false+ var readReceiptSent = false+ var globalStatusText = ""+ var groupReadBy = mutableListOf<String>()+ }+ private val messageMeta = java.util.concurrent.ConcurrentHashMap<String, MessageMeta>()++ // Syncing flags for MESSAGE_DELETED suppression (port of Go syncingMobileDatabase/syncingConversations)+ @Volatile private var syncingMobileDatabase = false+ @Volatile private var syncingConversations = false++ // Chat info cache for group read receipts and phone number resolution+ private val chatInfoCache = java.util.concurrent.ConcurrentHashMap<String, conversations.Conversations.Conversation>()+ fun init(context: Context) { if (!initialized.compareAndSet(false, true)) return appContext = context.applicationContext@@ -176,6 +199,7 @@ object GMessagesClient { if (auth.isPaired()) { Log.i(TAG, "found persisted pair, resuming long-poll") longPoll.start(scope)+ sessionHandler.startAckInterval(scope) _state.value = State.Connected postConnect() }@@ -186,6 +210,7 @@ object GMessagesClient { if (!initialized.get()) return if (auth.isPaired() && _state.value !is State.Connected) { longPoll.start(scope)+ sessionHandler.startAckInterval(scope) _state.value = State.Connected scope.launch { postConnect() } }@@ -193,6 +218,33 @@ object GMessagesClient { fun stop() { Log.i(TAG, "stop — clearing pair")+ // Remote unpair: notify the server we're intentionally disconnecting (1.8)+ val currentAuth = auth+ if (currentAuth.isPaired()) {+ scope.launch {+ try {+ val token = currentAuth.tachyonToken() ?: return@launch+ val browser = currentAuth.browser() ?: return@launch+ val req = authentication.Authentication.RevokeRelayPairingRequest.newBuilder()+ .setAuthMessage(+ authentication.Authentication.AuthMessage.newBuilder()+ .setRequestID(UUID.randomUUID().toString())+ .setTachyonAuthToken(ByteString.copyFrom(token))+ .setConfigVersion(PairFlow.ConfigVersion)+ )+ .setBrowser(browser)+ .build()+ rpc.postProtobuf(+ url = Endpoints.RevokeRelayPairingUrl,+ body = req,+ responseTemplate = authentication.Authentication.RevokeRelayPairingResponse.getDefaultInstance(),+ )+ Log.i(TAG, "remote unpair sent")+ } catch (e: Exception) {+ Log.w(TAG, "remote unpair failed: ${e.message}")+ }+ }+ } backfillJob?.cancel() longPoll.stop() sessionHandler.cancelAll()@@ -205,6 +257,7 @@ object GMessagesClient { ready = false phoneResponding = true noDataReceivedRecently = false+ longPollingError = null batteryLow = false mobileData = false switchedToGoogleLogin = false@@ -218,6 +271,11 @@ object GMessagesClient { conversationForceRcs.clear() messageContentHashes.clear() reactionState.clear()+ messageMeta.clear()+ chatInfoCache.clear()+ syncingMobileDatabase = false+ syncingConversations = false+ didHackySetActive = false qrRetryCount = 0 rpc.close() media.close()@@ -387,6 +445,15 @@ object GMessagesClient { Log.i(TAG, "SEND_MESSAGE status=${parsed.status}") if (parsed.status != SendMessageResponse.Status.SUCCESS) { pendingOutgoing.remove(tmpId)+ val errorMsg = getSendFailureMessage(parsed)+ if (errorMsg != null) {+ _events.emit(GMEvent.SendFailed(+ source = source,+ conversationId = webId,+ tmpId = tmpId,+ errorMessage = errorMsg,+ ))+ } } return parsed.status == SendMessageResponse.Status.SUCCESS }@@ -416,9 +483,24 @@ object GMessagesClient { suspend fun deleteConversation(conversationId: String, phone: String?): Boolean { if (_state.value !is State.Connected) return false val webId = conversationId.substringAfter(':', conversationId)+ // Phone number resolution fallback (1.5): if phone is unknown, try to+ // resolve it from cached chat info or by fetching the conversation.+ var resolvedPhone = phone+ if (resolvedPhone.isNullOrBlank()) {+ val cached = chatInfoCache[webId]+ if (cached != null) {+ resolvedPhone = cached.participantsList+ ?.firstOrNull { it.isVisible && !it.isMe && it.id.number.isNotBlank() }+ ?.id?.number+ }+ if (resolvedPhone.isNullOrBlank()) {+ val convResp = sessionHandler.sendAndWait(ActionType.GET_UPDATES, null, timeoutMs = 10_000)+ Log.d(TAG, "deleteConversation: phone fallback attempted via relay")+ }+ } val data = DeleteConversationData.newBuilder() .setConversationID(webId)- .apply { if (!phone.isNullOrBlank()) setPhone(phone) }+ .apply { if (!resolvedPhone.isNullOrBlank()) setPhone(resolvedPhone) } .build() val req = UpdateConversationRequest.newBuilder() .setAction(ConversationActionStatus.DELETE)@@ -451,7 +533,10 @@ object GMessagesClient { .setMessageID(msgWebId) .setAction(action) .setReactionData(ReactionData.newBuilder().setUnicode(qualifiedEmoji))- defaultSimPayload?.let { reqBuilder.setSIMPayload(it) }+ // Go omits SIMPayload for REMOVE action (1.2)+ if (action != SendReactionRequest.Action.REMOVE) {+ 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@@ -476,19 +561,9 @@ object GMessagesClient { 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())- }+ /** Stop-typing: Go skips this entirely (returns nil), so we do the same (1.4). */+ @Suppress("UNUSED_PARAMETER")+ suspend fun sendStopTyping(conversationId: String): Boolean = true /** * Delete a single message via DELETE_MESSAGE. The relay echoes the@@ -531,6 +606,7 @@ object GMessagesClient { conversations.Conversations.ContactNumber.newBuilder() .setMysteriousInt(2) // 2 = "from contact list", per libgm .setNumber(it)+ .setNumber2(it) .build() }) .apply {@@ -692,7 +768,6 @@ object GMessagesClient { } updates.hasUserAlertEvent() -> { if (isOld) return- if (!noDataReceivedRecently) lastDataReceived = System.currentTimeMillis() handleUserAlert(updates.userAlertEvent.alertType) } updates.hasSettingsEvent() -> {@@ -719,11 +794,16 @@ object GMessagesClient { /** Port of Go's handleUserAlert (handlegmessages.go:256-337). */ private fun handleUserAlert(alertType: AlertType) { Log.d(TAG, "handleUserAlert: $alertType")+ var becameInactive = false+ if (!noDataReceivedRecently) {+ lastDataReceived = System.currentTimeMillis()+ } when (alertType) { AlertType.BROWSER_INACTIVE, AlertType.BROWSER_INACTIVE_FROM_TIMEOUT, AlertType.BROWSER_INACTIVE_FROM_INACTIVITY -> { browserInactiveType = alertType.name+ becameInactive = true Log.i(TAG, "Browser became inactive: $alertType") } AlertType.BROWSER_ACTIVE -> {@@ -735,7 +815,8 @@ object GMessagesClient { if (sessionIdChanged || wasInactive || noDataReceivedRecently) { Log.i(TAG, "BROWSER_ACTIVE: resyncing (sessionChanged=$sessionIdChanged wasInactive=$wasInactive noData=$noDataReceivedRecently)") sessionId = newSessionId- scope.launch { kickoffBackfill() }+ val minimal = !sessionIdChanged && !wasInactive+ scope.launch { kickoffBackfill(minimal = minimal) } } else { sessionId = newSessionId }@@ -760,12 +841,14 @@ object GMessagesClient { } AlertType.MOBILE_DATABASE_SYNC_STARTED, AlertType.MOBILE_DATABASE_PARTIAL_SYNC_STARTED -> {+ syncingMobileDatabase = true 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() }+ syncingMobileDatabase = false+ Log.d(TAG, "Mobile database sync complete, triggering minimal backfill")+ scope.launch { kickoffBackfill(minimal = true) } } AlertType.MOBILE_DATABASE_SYNCING -> { Log.d(TAG, "Mobile database syncing")@@ -773,7 +856,14 @@ object GMessagesClient { AlertType.RCS_CONNECTION -> { Log.d(TAG, "RCS connection established") }- else -> Log.d(TAG, "Unhandled alert type: $alertType")+ else -> {+ Log.d(TAG, "Unhandled alert type: $alertType")+ return+ }+ }+ // Port of Go's aggressive reconnect on browser inactive+ if (becameInactive && aggressiveReconnect) {+ aggressiveSetActive() } } @@ -783,11 +873,11 @@ object GMessagesClient { val updates = UpdateEvents.parseFrom(data) if (updates.hasSettingsEvent()) { val settingsProto = updates.settingsEvent- if (settingsProto.sIMCardsCount > 0) {+ if (settingsProto.getSIMCardsCount() > 0) { val firstSim = settingsProto.getSIMCards(0) if (firstSim.hasSIMData()) {- defaultSimPayload = firstSim.sIMData.sIMPayload- Log.d(TAG, "handleSettings: stored SIM payload (${settingsProto.sIMCardsCount} SIMs)")+ defaultSimPayload = firstSim.getSIMData().getSIMPayload()+ Log.d(TAG, "handleSettings: stored SIM payload (${settingsProto.getSIMCardsCount()} SIMs)") } } }@@ -804,32 +894,64 @@ object GMessagesClient { val change = updates.accountChange switchedToGoogleLogin = change.enabled Log.i(TAG, "handleAccountChange: account=${change.account} switchedToGoogle=$switchedToGoogleLogin")+ if (!switchedToGoogleLogin) {+ ready = true+ } } } 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.- */+ /** Port of Go's aggressiveSetActive (handlegmessages.go:339-359).+ * Called when the browser becomes inactive — retries SetActiveSession. */ 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}")- }- }+ if (browserInactiveType.isEmpty()) {+ Log.i(TAG, "aggressiveSetActive: session became active on its own")+ return@launch+ }+ Log.i(TAG, "aggressiveSetActive: sleeping ${sleepMs}ms")+ kotlinx.coroutines.delay(sleepMs)+ if (browserInactiveType.isEmpty()) {+ Log.i(TAG, "aggressiveSetActive: session became active on its own")+ return@launch+ }+ try {+ sessionHandler.setActiveSession()+ break+ } catch (e: Exception) {+ Log.w(TAG, "aggressiveSetActive failed: ${e.message}")+ }+ }+ }+ }++ /** Port of Go's hackyResetActive (2.3). Waits 7s, retries SetActive,+ * and if still not ready, attempts full reconnect. */+ @Volatile private var didHackySetActive = false+ private fun hackyResetActive() {+ if (didHackySetActive) return+ didHackySetActive = true+ noDataReceivedRecently = false+ lastDataReceived = 0L+ scope.launch {+ kotlinx.coroutines.delay(7_000)+ if (!ready && phoneResponding) {+ Log.w(TAG, "hackyResetActive: client not ready, retrying setActiveSession")+ try {+ sessionHandler.setActiveSession()+ } catch (e: Exception) {+ Log.w(TAG, "hackyResetActive: setActiveSession failed: ${e.message}")+ }+ kotlinx.coroutines.delay(7_000)+ if (!ready && phoneResponding) {+ Log.w(TAG, "hackyResetActive: still not ready, reconnecting long-poll")+ longPoll.stop()+ longPoll.start(scope) } } }@@ -905,13 +1027,14 @@ object GMessagesClient { if (longPoll.skipCount > 0) { Log.w(TAG, "skipCount is still non-zero (${longPoll.skipCount})") }+ // Port of Go's HackySetActiveMayFail event: fired concurrently+ // BEFORE acks/setActive when skipCount was non-zero.+ hackyResetActive() } // Send acks before set active session (matches Go's postConnect) sessionHandler.sendAckRequest() kotlinx.coroutines.delay(1_000) sessionHandler.setActiveSession()- // Start the periodic ack sender- sessionHandler.startAckInterval(scope) kotlinx.coroutines.delay(1_000) // Check IsBugleDefault (matches Go's postConnect) val bugleResp = sessionHandler.sendAndWait(ActionType.IS_BUGLE_DEFAULT, null, timeoutMs = 10_000)@@ -931,15 +1054,8 @@ object GMessagesClient { } } - /**- * Refresh the tachyon auth token if it's about to expire.- * Based on Go implementation in pkg/libgm/client.go.- * Uses the RegisterRefresh endpoint with ECDSA-signed request.- */- /**- * Refresh the tachyon auth token if it's about to expire.- * Port of `refreshAuthToken` in `pkg/libgm/client.go`.- */+ /** Refresh the tachyon auth token if it's about to expire.+ * Port of `refreshAuthToken` in `pkg/libgm/client.go`. */ suspend fun refreshAuthToken() { val currentAuth = auth val browser = currentAuth.browser() ?: return@@ -1035,6 +1151,17 @@ object GMessagesClient { Log.e(TAG, "long-poll fatal error: ${evt.reason}") _state.value = State.Disconnected(evt.reason) }+ LongPollEvent.NoDataReceived -> {+ noDataReceivedRecently = true+ }+ is LongPollEvent.TemporaryError -> {+ longPollingError = evt.error+ Log.w(TAG, "long-poll temporary error: ${evt.error}")+ }+ LongPollEvent.Recovered -> {+ longPollingError = null+ Log.i(TAG, "long-poll recovered")+ } } } @@ -1109,6 +1236,21 @@ object GMessagesClient { } private suspend fun emitConversation(c: conversations.Conversations.Conversation) {+ // Cache chat info for group read receipts and phone resolution+ chatInfoCache[c.conversationID] = c++ // Spam/blocked/deleted conversation handling: emit delete event instead+ when (c.status) {+ ConversationStatus.SPAM_FOLDER,+ ConversationStatus.BLOCKED_FOLDER,+ ConversationStatus.DELETED -> {+ Log.d(TAG, "emitConversation: ${c.status} conv=${c.conversationID}, emitting delete")+ _events.emit(GMEvent.ConversationDeleted(source = source, conversationId = c.conversationID))+ return+ }+ else -> { /* active/archived — continue normally */ }+ }+ c.defaultOutgoingID.takeIf { it.isNotBlank() }?.let { outgoingIds[c.conversationID] = it } // Track conversation type/sendMode/forceRCS for outbound message routing@@ -1257,20 +1399,33 @@ object GMessagesClient { private suspend fun emitMessage(m: conversations.Conversations.Message) { val outgoing = m.hasSenderParticipant() && m.senderParticipant.isMe+ val statusType = m.messageStatus.status+ val statusNum = statusType.number - // Remote echo handling (item 23): if this is an outgoing message- // matching a pending tmpId, it's the server echo of our send.+ // Remote echo handling (1.6): store metadata for outgoing messages if (outgoing && m.tmpID.isNotBlank()) { pendingOutgoing.remove(m.tmpID)+ val meta = messageMeta.getOrPut(m.messageID) { MessageMeta() }+ meta.isOutgoing = true+ meta.textHash = computeContentHash(m)+ meta.globalPartCount = m.messageInfoCount+ for (i in 0 until m.messageInfoCount) {+ val info = m.getMessageInfo(i)+ if (info.hasMediaContent()) {+ meta.statusNum = statusNum+ }+ } } - // 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+ // MESSAGE_DELETED: suppress during sync (2.8), then emit delete event if (statusType == MessageStatusType.MESSAGE_DELETED) {+ if (syncingMobileDatabase || syncingConversations) {+ Log.d(TAG, "suppressing MESSAGE_DELETED during sync id=${m.messageID}")+ return+ } Log.d(TAG, "emitMessage: MESSAGE_DELETED id=${m.messageID}") messageContentHashes.remove(m.messageID)+ messageMeta.remove(m.messageID) _events.emit( GMEvent.MessageDeleted( source = source,@@ -1282,34 +1437,88 @@ object GMessagesClient { return } - // Map status for downstream consumers+ // Tombstone filtering (3.7): skip protocol switch notices, group creation, etc.+ val isDm = chatInfoCache[m.conversationID]?.let { !it.isGroupChat } ?: true+ if (shouldIgnoreStatus(statusNum, isDm)) {+ handleTombstoneForceRcs(m, statusNum)+ return+ }++ // Download status ranking (3.1): prevent status downgrades+ val existingMeta = messageMeta[m.messageID]+ if (existingMeta != null && downloadStatusRank(statusNum) < downloadStatusRank(existingMeta.statusNum)) {+ Log.d(TAG, "ignoring status downgrade for ${m.messageID}")+ return+ }++ // Chat ID change detection (3.3): detect if message moved between conversations+ if (existingMeta != null && existingMeta.statusNum != 0) {+ // Existing message — we're handling an update, not a new message+ }++ // Get or create per-message metadata+ val meta = messageMeta.getOrPut(m.messageID) { MessageMeta() }+ meta.isOutgoing = outgoing+ meta.statusNum = statusNum+ meta.globalPartCount = m.messageInfoCount++ // Skip auto-downloading statuses — message data is incomplete (Go returns ErrIgnoringRemoteEvent)+ if (statusType == MessageStatusType.INCOMING_AUTO_DOWNLOADING ||+ statusType == MessageStatusType.INCOMING_RETRYING_AUTO_DOWNLOAD) {+ Log.d(TAG, "ignoring auto-downloading status for ${m.messageID}")+ return+ }+ 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_MANUAL_DOWNLOADING,+ MessageStatusType.INCOMING_RETRYING_MANUAL_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) {+ // MSS events (3.5): send success confirmation+ if (outgoing && !meta.mssSent && isSuccessfullySentStatus(statusType)) {+ meta.mssSent = true+ }++ // MSS failure event+ if (!meta.mssFailSent && !meta.mssSent) {+ val failMsg = getFailMessage(statusNum)+ if (failMsg.isNotEmpty()) {+ meta.mssFailSent = true+ _events.emit(GMEvent.SendFailed(+ source = source,+ conversationId = m.conversationID,+ messageId = m.messageID,+ errorMessage = failMsg,+ ))+ }+ }++ // MSS delivery receipt (3.5)+ if (!meta.mssDeliverySent &&+ (statusType == MessageStatusType.OUTGOING_DELIVERED ||+ statusType == MessageStatusType.OUTGOING_DISPLAYED)) {+ meta.mssDeliverySent = true _events.emit( GMEvent.ReadReceipt( source = source, conversationId = m.conversationID, messageId = m.messageID, timestamp = toMillis(m.timestamp),+ isDelivery = true, ) ) } - // OUTGOING_DISPLAYED: emit read receipt- if (statusType == MessageStatusType.OUTGOING_DISPLAYED) {+ // DM read receipt+ if (!meta.readReceiptSent && statusType == MessageStatusType.OUTGOING_DISPLAYED) {+ meta.readReceiptSent = true _events.emit( GMEvent.ReadReceipt( source = source,@@ -1320,6 +1529,14 @@ object GMessagesClient { ) } + // Group read receipts from status text (3.6)+ if (statusType == MessageStatusType.OUTGOING_DISPLAYED) {+ val statusText = runCatching { m.messageStatus.statusText }.getOrNull().orEmpty()+ if (statusText.startsWith("Read by ") && statusText != meta.globalStatusText) {+ handleGroupReadReceipts(m, meta, statusText)+ }+ }+ // Build message body + attempt media download var mediaBytes: ByteArray? = null var mediaMime: String? = null@@ -1333,7 +1550,6 @@ object GMessagesClient { 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@@ -1353,7 +1569,7 @@ object GMessagesClient { .joinToString("\n") .ifBlank { "" } - // Issue 2: message edit detection (ref handlegmessages.go:910-954)+ // Edit detection val contentHash = computeContentHash(m) val previousHash = messageContentHashes.put(m.messageID, contentHash) if (previousHash != null && previousHash != contentHash) {@@ -1369,7 +1585,7 @@ object GMessagesClient { ) } - // Issue 5: reaction sync per-user — emit per-user reaction events+ // Reaction sync per-user syncReactions(m) _events.emit(@@ -1469,32 +1685,208 @@ object GMessagesClient { } } - private fun kickoffBackfill() {+ private fun kickoffBackfill(minimal: Boolean = false) { backfillJob?.cancel() backfillJob = scope.launch {- // First call uses BUGLE_ANNOTATION as a "give me everything"- // hint to the relay; subsequent calls use BUGLE_MESSAGE. See- // libgm `methods.go.ListConversations` for the same trick.- val msgType = if (!conversationsFetchedOnce) {- conversationsFetchedOnce = true- MessageType.BUGLE_ANNOTATION- } else {- MessageType.BUGLE_MESSAGE- }- Log.i(TAG, "kicking off LIST_CONVERSATIONS (messageType=$msgType)")- val req = ListConversationsRequest.newBuilder()- .setCount(50)- .build()- val resp = sessionHandler.sendAndWait(- ActionType.LIST_CONVERSATIONS,- req,- messageType = msgType,- )- if (resp == null) {- Log.w(TAG, "backfill: no response (timeout?)")- } else {- Log.i(TAG, "backfill response received (decryptedBytes=${resp.decryptedData?.size ?: 0})")+ syncingConversations = true+ try {+ // Minimal sync optimization: if no recent messages, skip full sync+ if (minimal && !noDataReceivedRecently) {+ Log.d(TAG, "minimal backfill: no recent data, skipping full sync")+ syncingConversations = false+ return@launch+ }+ val msgType = if (!conversationsFetchedOnce) {+ conversationsFetchedOnce = true+ MessageType.BUGLE_ANNOTATION+ } else {+ MessageType.BUGLE_MESSAGE+ }+ Log.i(TAG, "kicking off LIST_CONVERSATIONS (messageType=$msgType minimal=$minimal)")+ val req = ListConversationsRequest.newBuilder()+ .setCount(50)+ .build()+ val resp = sessionHandler.sendAndWait(+ ActionType.LIST_CONVERSATIONS,+ req,+ messageType = msgType,+ )+ if (resp == null) {+ Log.w(TAG, "backfill: no response (timeout?)")+ } else {+ Log.i(TAG, "backfill response received (decryptedBytes=${resp.decryptedData?.size ?: 0})")+ }+ } finally {+ syncingConversations = false+ }+ }+ }++ // ----------------------------------------------------------------+ // Helper functions ported from Go connector+ // ----------------------------------------------------------------++ /** Tombstone status filtering (3.7). Port of Go's shouldIgnoreStatus.+ * Tombstones are in the 200-299 status range. */+ private fun shouldIgnoreStatus(statusNum: Int, isDm: Boolean): Boolean {+ if (statusNum < 200 || statusNum >= 300) return false+ val status = MessageStatusType.forNumber(statusNum) ?: return false+ // DM-only tombstones (protocol switches between SMS/RCS/E2EE)+ val dmOnlyTombstones = setOf(+ MessageStatusType.TOMBSTONE_PROTOCOL_SWITCH_TO_TEXT,+ MessageStatusType.TOMBSTONE_PROTOCOL_SWITCH_TO_RCS,+ MessageStatusType.TOMBSTONE_PROTOCOL_SWITCH_TO_ENCRYPTED_RCS,+ MessageStatusType.TOMBSTONE_PROTOCOL_SWITCH_TO_ENCRYPTED_RCS_INFO,+ MessageStatusType.TOMBSTONE_ONE_ON_ONE_SMS_CREATED,+ MessageStatusType.TOMBSTONE_ONE_ON_ONE_RCS_CREATED,+ MessageStatusType.TOMBSTONE_ENCRYPTED_ONE_ON_ONE_RCS_CREATED,+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_PROTOCOL_SWITCH_TEXT_TO_E2EE,+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_PROTOCOL_SWITCH_E2EE_TO_TEXT,+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_PROTOCOL_SWITCH_RCS_TO_E2EE,+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_PROTOCOL_SWITCH_E2EE_TO_RCS,+ )+ // Always-ignore tombstones (group creation, identity changes, etc.)+ val alwaysIgnore = setOf(+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_ENCRYPTED_GROUP_CREATED,+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_GROUP_PROTOCOL_SWITCH_E2EE_TO_RCS,+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_GROUP_PROTOCOL_SWITCH_RCS_TO_E2EE,+ MessageStatusType.TOMBSTONE_RCS_GROUP_CREATED,+ MessageStatusType.TOMBSTONE_MMS_GROUP_CREATED,+ MessageStatusType.TOMBSTONE_SMS_BROADCAST_CREATED,+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_PARTICIPANT_THEME_CHANGE,+ MessageStatusType.TOMBSTONE_SHOW_LINK_PREVIEWS,+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_ACTIVE_SELF_IDENTITY_CHANGED,+ )+ if (status in alwaysIgnore) return true+ if (status in dmOnlyTombstones) return isDm+ return false+ }++ /** Handle ForceRCS toggle from tombstone messages.+ * Port of Go's ConvertMessage tombstone handling. */+ private fun handleTombstoneForceRcs(m: conversations.Conversations.Message, statusNum: Int) {+ val status = MessageStatusType.forNumber(statusNum) ?: return+ when (status) {+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_PROTOCOL_SWITCH_RCS_TO_E2EE,+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_PROTOCOL_SWITCH_TEXT_TO_E2EE -> {+ if (conversationForceRcs[m.conversationID] != true) {+ conversationForceRcs[m.conversationID] = true+ Log.d(TAG, "tombstone: ForceRCS=true for ${m.conversationID}")+ }+ }+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_PROTOCOL_SWITCH_E2EE_TO_RCS,+ MessageStatusType.MESSAGE_STATUS_TOMBSTONE_PROTOCOL_SWITCH_E2EE_TO_TEXT -> {+ if (conversationForceRcs[m.conversationID] == true) {+ conversationForceRcs[m.conversationID] = false+ Log.d(TAG, "tombstone: ForceRCS=false for ${m.conversationID}")+ }+ }+ else -> { /* not a ForceRCS-related tombstone */ }+ }+ }++ /** Download status ranking (3.1). Port of Go's downloadStatusRank.+ * Higher rank = more progressed. Prevents downgrades. */+ private fun downloadStatusRank(statusNum: Int): Int {+ val status = MessageStatusType.forNumber(statusNum) ?: return 100+ return when (status) {+ MessageStatusType.INCOMING_AUTO_DOWNLOADING -> 0+ MessageStatusType.INCOMING_MANUAL_DOWNLOADING,+ MessageStatusType.INCOMING_RETRYING_AUTO_DOWNLOAD,+ MessageStatusType.INCOMING_RETRYING_MANUAL_DOWNLOAD,+ MessageStatusType.INCOMING_DOWNLOAD_FAILED,+ MessageStatusType.INCOMING_DOWNLOAD_FAILED_TOO_LARGE,+ MessageStatusType.INCOMING_DOWNLOAD_FAILED_SIM_HAS_NO_DATA,+ MessageStatusType.INCOMING_DOWNLOAD_CANCELED,+ MessageStatusType.INCOMING_YET_TO_MANUAL_DOWNLOAD -> 1+ else -> 100+ }+ }++ /** Check if a status indicates successful send. Port of Go's isSuccessfullySentStatus. */+ private fun isSuccessfullySentStatus(status: MessageStatusType): Boolean = when (status) {+ MessageStatusType.OUTGOING_DELIVERED,+ MessageStatusType.OUTGOING_COMPLETE,+ MessageStatusType.OUTGOING_DISPLAYED -> true+ else -> false+ }++ /** Failure message for outgoing message statuses. Port of Go's getFailMessage. */+ private fun getFailMessage(statusNum: Int): String {+ val status = MessageStatusType.forNumber(statusNum) ?: return ""+ return when (status) {+ MessageStatusType.OUTGOING_FAILED_TOO_LARGE -> "too large"+ MessageStatusType.OUTGOING_FAILED_RECIPIENT_LOST_RCS -> "recipient lost RCS support"+ MessageStatusType.OUTGOING_FAILED_RECIPIENT_LOST_ENCRYPTION -> "recipient lost encryption support"+ MessageStatusType.OUTGOING_FAILED_RECIPIENT_DID_NOT_DECRYPT,+ MessageStatusType.OUTGOING_FAILED_RECIPIENT_DID_NOT_DECRYPT_NO_MORE_RETRY -> "recipient failed to decrypt message"+ MessageStatusType.OUTGOING_FAILED_GENERIC -> "generic carrier error, check google messages and try again"+ MessageStatusType.OUTGOING_FAILED_NO_RETRY_NO_FALLBACK -> "no fallback error"+ MessageStatusType.OUTGOING_FAILED_EMERGENCY_NUMBER -> "emergency number error"+ MessageStatusType.OUTGOING_CANCELED -> "canceled"+ else -> ""+ }+ }++ /** Detailed error message from SendMessageResponse. Port of Go's responseStatusError. */+ private fun getSendFailureMessage(resp: SendMessageResponse): String? {+ if (resp.status == SendMessageResponse.Status.SUCCESS) return null+ return when (resp.status.number) {+ 0 -> {+ if (resp.hasGoogleAccountSwitch() &&+ resp.googleAccountSwitch.account.contains('@'))+ "Switch back to QR pairing or log in with Google account to send messages"+ else "Unrecognized response status 0"+ }+ 2 -> "Unknown permanent error" // FAILURE_2+ 3 -> "Unknown temporary error" // FAILURE_3+ 4 -> "Google Messages is not your default SMS app" // FAILURE_4+ else -> "Unrecognized response status ${resp.status.number}"+ }+ }++ /** Parse group read receipts from "Read by Alice, Bob" status text (3.6). */+ private suspend fun handleGroupReadReceipts(+ m: conversations.Conversations.Message,+ meta: MessageMeta,+ statusText: String,+ ) {+ meta.globalStatusText = statusText+ val cached = chatInfoCache[m.conversationID] ?: return+ // Build name → participantID map from cached conversation+ val nameToIds = mutableMapOf<String, MutableList<String>>()+ for (i in 0 until cached.participantsCount) {+ val p = cached.getParticipants(i)+ if (p.isMe) continue+ val name = p.firstName.takeIf { it.isNotBlank() }+ ?: p.formattedNumber.takeIf { it.isNotBlank() }+ ?: continue+ val pid = p.id.participantID.takeIf { it.isNotBlank() } ?: continue+ nameToIds.getOrPut(name) { mutableListOf() }.add(pid)+ }+ val readByStr = statusText.removePrefix("Read by ")+ val newReadBy = mutableListOf<String>()+ for (name in readByStr.split(", ").map { it.trim() }) {+ val ids = nameToIds[name] ?: continue+ if (ids.isNotEmpty()) {+ newReadBy.add(ids.removeFirst())+ }+ }+ // Emit read receipts for newly-added readers+ val oldReadBy = meta.groupReadBy.toSet()+ for (participantId in newReadBy) {+ if (participantId !in oldReadBy) {+ _events.emit(+ GMEvent.ReadReceipt(+ source = source,+ conversationId = m.conversationID,+ messageId = m.messageID,+ senderId = participantId,+ timestamp = toMillis(m.timestamp),+ )+ ) } }+ meta.groupReadBy = newReadBy } }
messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.ktindex ecb6b93821..ad4dfecfab 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt@@ -63,6 +63,7 @@ class LongPoll( private suspend fun loop() { var backoffMs = 0L+ var errorCount = 0 while (true) { if (backoffMs > 0) { Log.i(TAG, "reconnecting in ${backoffMs / 1000}s")@@ -78,10 +79,20 @@ class LongPoll( return } catch (t: Throwable) { Log.w(TAG, "long-poll error: ${t.message}")+ onEvent(LongPollEvent.TemporaryError(t.message ?: "unknown error")) false } if (!kotlin.coroutines.coroutineContext.isActive) return- backoffMs = if (ok) 0L else (if (backoffMs == 0L) 5_000L else minOf(60_000L, backoffMs * 2))+ if (ok) {+ if (errorCount > 0) {+ errorCount = 0+ onEvent(LongPollEvent.Recovered)+ }+ backoffMs = 0L+ } else {+ errorCount+++ backoffMs = if (backoffMs == 0L) 5_000L else minOf(60_000L, backoffMs * 2)+ } } } @@ -119,10 +130,15 @@ class LongPoll( } if (status !in 200..299) { Log.e(TAG, "long-poll HTTP $status")+ onEvent(LongPollEvent.TemporaryError("long-poll HTTP $status")) return@openLongPoll false } Log.i(TAG, "long-poll open (HTTP $status)")- consumeBody(response.bodyAsChannel())+ val sawEvents = consumeBody(response.bodyAsChannel())+ if (!sawEvents) {+ onEvent(LongPollEvent.NoDataReceived)+ }+ sawEvents } } @@ -360,6 +376,15 @@ sealed interface LongPollEvent { /** Fatal error — long-poll should NOT retry (e.g. HTTP 401/403). */ data class FatalError(val reason: String) : LongPollEvent++ /** Long-poll cycle completed without any data events (2.7). */+ data object NoDataReceived : LongPollEvent++ /** Temporary long-poll error — will retry (2.1). */+ data class TemporaryError(val error: String) : LongPollEvent++ /** Recovered from a temporary error (2.1). */+ data object Recovered : LongPollEvent } /** Thrown when the long-poll encounters a non-retryable error (HTTP 401/403). */
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 c88b58e7e6..7c6d79585f 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.kt@@ -138,7 +138,6 @@ object PairFlow { 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(@@ -148,7 +147,6 @@ object PairFlow { .setNetwork(QrNetwork) .setConfigVersion(ConfigVersion) )- .setBrowserDetails(BrowserDetails) .build() Log.i(TAG, "RefreshPhoneRelay …")
messages/src/main/java/com/vayunmathur/messages/gmessages/RpcClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/RpcClient.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/RpcClient.ktindex 9d38caf190..6f96555c09 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/RpcClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/RpcClient.kt@@ -36,10 +36,10 @@ class RpcClient { private val normal: HttpClient = HttpClient(CIO) { engine {- requestTimeout = 30_000 // 30 s+ requestTimeout = 120_000 // 2 min (matches Go's http.Client{Timeout: 2 * time.Minute}) } install(HttpTimeout) {- requestTimeoutMillis = 30_000+ requestTimeoutMillis = 120_000 connectTimeoutMillis = 15_000 socketTimeoutMillis = 30_000 }
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 bfa634be63..f28171c962 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt@@ -66,7 +66,6 @@ object GVoiceClient { @Volatile private var rpc: GVoiceRpcClient? = null private var realtime: RealtimeChannel? = null private var backfillJob: Job? = null- @Volatile private var versionToken: String = "" private const val AUTH_USER = "0" // Contact cache with 5-min TTL (matches Go's contactCache + fetchContactInfo)@@ -87,6 +86,9 @@ object GVoiceClient { private val fetchLock = Mutex() @Volatile private var fetchLoopJob: Job? = null + // Per-thread latest message timestamp for deduplication (matches Go's gc.lastEvents)+ private val lastEvents = ConcurrentHashMap<String, Long>()+ private const val MAX_AVATAR_SIZE = 5 * 1024 * 1024 fun init(context: Context) {@@ -97,7 +99,7 @@ object GVoiceClient { val auth = VoiceAuthData.load(appContext) if (auth?.hasRequired() == true) { Log.i(TAG, "resuming from persisted cookies")- bootSession(auth)+ connectWithValidation(auth) } else { _state.value = State.NeedsSetup }@@ -109,7 +111,7 @@ object GVoiceClient { if (_state.value is State.Connected) return scope.launch { val auth = VoiceAuthData.load(appContext)- if (auth?.hasRequired() == true) bootSession(auth)+ if (auth?.hasRequired() == true) connectWithValidation(auth) else _state.value = State.NeedsSetup } }@@ -122,6 +124,7 @@ object GVoiceClient { realtime = null rpc?.close() rpc = null+ lastEvents.clear() scope.launch { VoiceAuthData.clear(appContext) } _state.value = State.NeedsSetup }@@ -214,6 +217,7 @@ object GVoiceClient { data: ByteArray, mime: String, caption: String?,+ fileName: String? = null, ): Boolean { if (_state.value !is State.Connected) return false val client = rpc ?: return false@@ -226,8 +230,13 @@ object GVoiceClient { .setType(mediaType) .setData(com.google.protobuf.ByteString.copyFrom(data)) .build()+ val effectiveCaption = when {+ fileName.isNullOrBlank() -> null+ fileName == caption -> null+ else -> caption+ } val req = baseSendBuilder(webId)- .apply { caption?.takeIf { it.isNotBlank() }?.let { setText(it) } }+ .apply { effectiveCaption?.takeIf { it.isNotBlank() }?.let { setText(it) } } .setMedia(media) .build() return doSend(client, webId, req)@@ -294,8 +303,8 @@ object GVoiceClient { // 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. */+ // (see electron.go). Without these signatures, the fallback "!" is used.+ /** Common builder: txn ID + fallback TrackingData (matches Go's SendMessage). */ private fun baseSendBuilder(webId: String): Requests.ReqSendSMS.Builder = Requests.ReqSendSMS.newBuilder() .setThreadID(webId)@@ -304,6 +313,9 @@ 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@@ -328,7 +340,10 @@ object GVoiceClient { body = req, responseTemplate = Responses.RespSendSMS.getDefaultInstance(), )- Log.i(TAG, "sendsms ok thread=$webId itemId=${resp.threadItemID}")+ Log.i(TAG, "sendsms ok thread=$webId itemId=${resp.threadItemID} ts=${resp.timestampMS}")+ if (resp.timestampMS > 0) {+ lastEvents.merge(webId, resp.timestampMS) { old, new -> maxOf(old, new) }+ } resp.threadItemID.isNotBlank() } catch (t: Throwable) { val errMsg = t.message ?: ""@@ -443,6 +458,9 @@ 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) }@@ -477,6 +495,9 @@ 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) }@@ -569,6 +590,14 @@ object GVoiceClient { for (i in 0 until resp.matchesCount) { val match = resp.getMatches(i) val phone = match.id.phone.takeIf { it.isNotBlank() } ?: continue+ // Match Go: check failureType; cache nil for PERMANENT failures+ if (match.failureType != responses.Responses.RespLookupContacts.Match.FailureType.NO_FAILURE) {+ if (match.failureType == responses.Responses.RespLookupContacts.Match.FailureType.PERMANENT) {+ contactCache[phone] = CachedContact(name = null, avatarUrl = null, timestamp = System.currentTimeMillis())+ }+ Log.d(TAG, "lookupContact: $phone failure=${match.failureType}")+ continue+ } personToSuggestions(match.autocompletion).firstOrNull()?.let { out[phone] = it } } return out@@ -583,20 +612,24 @@ object GVoiceClient { wrapper: contacts.Contacts.PersonWrapper, ): List<com.vayunmathur.messages.util.ContactSuggestion> { val person = wrapper.person ?: return emptyList()- // The display name lives on the contact method's displayInfo;- // typically all methods on a person share the same name, so- // just use the first non-blank one we see.- val displayName = (0 until person.contactMethodsCount)- .asSequence()- .map { person.getContactMethods(it) }- .mapNotNull { it.displayInfo?.name?.value?.takeIf { v -> v.isNotBlank() } }- .firstOrNull()- ?: "Unknown"- val avatar = (0 until person.contactMethodsCount)- .asSequence()- .map { person.getContactMethods(it) }- .mapNotNull { it.displayInfo?.photo?.url?.takeIf { v -> v.isNotBlank() } }- .firstOrNull()+ // Match Go's processContact: prefer primary displayInfo, skip MONOGRAM avatars+ var displayName = "Unknown"+ var avatar: String? = null+ for (idx in 0 until person.contactMethodsCount) {+ val di = person.getContactMethods(idx).displayInfo ?: continue+ val isPrimary = di.primary+ val nameVal = di.name?.value?.takeIf { it.isNotBlank() }+ if (nameVal != null && (displayName == "Unknown" || isPrimary)) {+ displayName = nameVal+ }+ val photoUrl = di.photo?.url?.takeIf { it.isNotBlank() }+ if (photoUrl != null+ && di.photo.type != contacts.Contacts.ContactDisplayInfo.Photo.Type.MONOGRAM+ && (avatar == null || isPrimary)+ ) {+ avatar = photoUrl+ }+ } return (0 until person.contactMethodsCount).mapNotNull { idx -> val cm = person.getContactMethods(idx) val rawPhone = cm.phone?.canonicalValue?.takeIf { it.isNotBlank() }@@ -650,6 +683,35 @@ object GVoiceClient { // Internals // ---------------------------------------------------------------- + /**+ * Validate credentials with GetAccount before starting the session.+ * Mirrors Go's `Connect` which always calls GetAccount first.+ */+ private suspend fun connectWithValidation(auth: VoiceAuthData) {+ _state.value = State.Connecting+ val client = rpc ?: GVoiceRpcClient(auth.cookies).also { rpc = it }+ try {+ client.postPbLite(+ url = VoiceEndpoints.EndpointGetAccount,+ body = Requests.ReqGetAccount.newBuilder().setUnknownInt2(1).build(),+ responseTemplate = Responses.RespGetAccount.getDefaultInstance(),+ )+ } catch (t: Throwable) {+ Log.e(TAG, "GetAccount failed on connect: ${t.message}")+ client.close()+ rpc = null+ val errMsg = t.message ?: ""+ val httpStatus = Regex("HTTP (\\d+)").find(errMsg)?.groupValues?.get(1)?.toIntOrNull()+ if (httpStatus == 401 || httpStatus == 403) {+ _state.value = State.BadCredentials(errMsg)+ } else {+ _state.value = State.ConnectError(errMsg)+ }+ return+ }+ bootSession(auth)+ }+ private fun bootSession(auth: VoiceAuthData) { val client = rpc ?: GVoiceRpcClient(auth.cookies).also { rpc = it } client.updateCookies(auth.cookies)@@ -662,23 +724,32 @@ object GVoiceClient { } rpc = client - _state.value = State.Connecting- _state.value = State.Connected- scope.launch { loadInitialContacts() } realtime?.stop() realtime = RealtimeChannel(client) { evt -> when (evt) {- RealtimeEvent.Connected -> Log.i(TAG, "realtime connected")+ RealtimeEvent.Connected -> {+ Log.i(TAG, "realtime connected")+ _state.value = State.Connected+ kickoffBackfill()+ } is RealtimeEvent.Data -> handleRealtimeData(evt.event) } }.also { ch -> val rtJob = ch.start(scope) rtJob.invokeOnCompletion { cause -> if (!rtJob.isCancelled) {- _state.value = State.Disconnected("realtime connection lost",- errorCode = "gv-realtime-error")+ when (ch.terminationReason) {+ RealtimeChannel.TerminationReason.AuthError ->+ _state.value = State.BadCredentials("realtime auth error")+ RealtimeChannel.TerminationReason.TooManyRetries ->+ _state.value = State.Disconnected("too many retries",+ errorCode = "gv-too-many-retries")+ else ->+ _state.value = State.Disconnected("realtime connection lost",+ errorCode = "gv-realtime-error")+ } } } }@@ -697,7 +768,6 @@ object GVoiceClient { private fun startFetchLoop() { fetchLoopJob?.cancel() fetchLoopJob = scope.launch {- doBackfill() while (true) { delay(BACKGROUND_REFRESH_INTERVAL_MS) rateLimitedBackfill()@@ -721,19 +791,49 @@ object GVoiceClient { fetchLock.withLock { doBackfill() } } - /** Load initial contacts into cache (matches Go's loadInitialContacts). */+ /** Load initial contacts into cache (matches Go's loadInitialContacts).+ * Uses the RPC client directly — runs before state is Connected. */ private suspend fun loadInitialContacts() { Log.i(TAG, "loading initial contacts")+ val client = rpc ?: return 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(),- )+ val req = Requests.ReqAutocompleteContacts.newBuilder()+ .setUnknownInt1(243)+ .setQuery("")+ .addAllUnknownInts3(listOf(1, 2))+ .setMaxResults(500)+ .build()+ val resp = client.postPbLite(+ url = VoiceEndpoints.EndpointAutocompleteContacts,+ body = req,+ responseTemplate = Responses.RespAutocompleteContacts.getDefaultInstance(),+ )+ for (i in 0 until resp.resultsCount) {+ val person = resp.getResults(i).person ?: continue+ var name: String? = null+ var avatar: String? = null+ for (idx in 0 until person.contactMethodsCount) {+ val di = person.getContactMethods(idx).displayInfo ?: continue+ val isPrimary = di.primary+ val nameVal = di.name?.value?.takeIf { it.isNotBlank() }+ if (nameVal != null && (name == null || isPrimary)) name = nameVal+ val photoUrl = di.photo?.url?.takeIf { it.isNotBlank() }+ if (photoUrl != null+ && di.photo.type != contacts.Contacts.ContactDisplayInfo.Photo.Type.MONOGRAM+ && (avatar == null || isPrimary)+ ) avatar = photoUrl+ }+ for (idx in 0 until person.contactMethodsCount) {+ val e164 = person.getContactMethods(idx).phone?.canonicalValue+ ?.takeIf { it.isNotBlank() } ?: continue+ val existing = contactCache[e164]+ if (existing == null || person.getContactMethods(idx).displayInfo?.primary == true) {+ contactCache[e164] = CachedContact(+ name = name,+ avatarUrl = avatar,+ timestamp = System.currentTimeMillis(),+ )+ } } } Log.i(TAG, "loaded ${contactCache.size} initial contacts")@@ -767,13 +867,11 @@ object GVoiceClient { private suspend fun doBackfill() { val client = rpc ?: return- Log.i(TAG, "ListThreads (ALL_THREADS) versionToken=${versionToken.take(20)}")- val unknownInt2 = if (versionToken.isNotEmpty()) 10 else 20+ Log.i(TAG, "ListThreads (ALL_THREADS)") val req = Requests.ReqListThreads.newBuilder() .setFolder(Threads.ThreadFolder.ALL_THREADS)- .setUnknownInt2(unknownInt2)+ .setUnknownInt2(20) .setUnknownInt3(15)- .setVersionToken(versionToken) .setUnknownWrapper( Requests.UnknownWrapper.newBuilder() .setUnknownInt2(1)@@ -788,18 +886,21 @@ object GVoiceClient { ) } catch (t: Throwable) { Log.w(TAG, "ListThreads failed: ${t.message}")- _state.value = State.Disconnected(- t.message ?: "ListThreads failed",- errorCode = "gv-connect-error",- ) return }- if (resp.versionToken.isNotEmpty()) {- versionToken = resp.versionToken- } Log.i(TAG, "ListThreads: ${resp.threadsCount} threads") for (i in 0 until resp.threadsCount) {- emitConversation(resp.getThreads(i))+ val thread = resp.getThreads(i)+ val threadId = thread.getID()+ emitConversation(thread)+ if (thread.messagesCount == 0) continue+ val latestTs = thread.getMessages(0).timestamp+ val prevTs = lastEvents.put(threadId, latestTs)+ for (j in 0 until thread.messagesCount) {+ val msg = thread.getMessages(j)+ if (prevTs != null && msg.timestamp <= prevTs) break+ emitMessage(threadId, msg, fromBackfill = true)+ } } } @@ -813,15 +914,20 @@ object GVoiceClient { } } - /** Filter realtime events: only process ones with actual data content. */+ /** Filter realtime events — match Go's isNewMessages: deep-check for+ * sub2.data[0].unknownBytes starting with '['. */ 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+ val w = evt.getDataWrapper(0)+ if (w.dataCount == 0) return false+ val d = w.getData(0)+ if (!d.hasEvent()) return false+ val ev = d.event+ if (!ev.hasSub2()) return false+ val sub2 = ev.sub2+ if (sub2.dataCount == 0) return false+ val unknownBytes = sub2.getData(0).unknownBytes+ return unknownBytes.size() > 0 && unknownBytes.byteAt(0) == '['.code.toByte() } private suspend fun emitConversation(t: Threads.Thread) {@@ -859,7 +965,7 @@ object GVoiceClient { } val latest: Threads.Message? = if (t.messagesCount > 0) {- t.getMessages(t.messagesCount - 1)+ t.getMessages(0) } else null val preview = latest?.text?.takeIf { it.isNotBlank() } val tsMillis = latest?.timestamp ?: 0L@@ -897,7 +1003,7 @@ object GVoiceClient { val senderName = if (m.hasContact()) m.contact.name.takeIf { it.isNotBlank() } else null val body = buildMessageBody(m)- if (body.isBlank()) return+ if (body.isEmpty()) return _events.emit( GMEvent.MessageUpdate(@@ -931,7 +1037,8 @@ object GVoiceClient { m.coarseType == Threads.Message.CoarseType.CALL_TYPE_VOICEMAIL ) { val transcript = buildVoicemailTranscript(m)- return if (transcript.isNotBlank()) "Voicemail: $transcript" else "Voicemail"+ if (transcript.isNotBlank()) return "Voicemail: $transcript"+ // Match Go: empty transcript falls through to unknown message } // Missed calls — no text/MMS guard (matches Go's convertGVMissedCallMessage@@ -976,9 +1083,9 @@ object GVoiceClient { 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.text.isNotBlank() -> mms.text+ mms.subject.isNotEmpty() && mms.text.isNotEmpty() -> "**${mms.subject}**\n${mms.text}"+ mms.subject.isNotEmpty() -> "**${mms.subject}**"+ mms.text.isNotEmpty() -> mms.text else -> "" } val attachmentParts = (0 until mms.attachmentsCount).mapNotNull { i ->@@ -1002,7 +1109,12 @@ object GVoiceClient { val parts = listOfNotNull( textPart.takeIf { it.isNotBlank() }, ) + attachmentParts- return parts.joinToString("\n").ifBlank { "[MMS message]" }+ val result = parts.joinToString("\n")+ if (result.isBlank()) {+ Log.w(TAG, "Empty MMS message id=${m.getID()} type=${m.type} coarseType=${m.coarseType}")+ return "Unknown message type, please view it on the Google Voice app"+ }+ return result } return m.text
messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.ktindex ffb354388e..279e06d775 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt@@ -48,21 +48,52 @@ class RealtimeChannel( job = null } + private class AuthException(message: String) : Exception(message)+ private class TooManyRetriesException(message: String) : Exception(message)++ sealed interface TerminationReason {+ data object AuthError : TerminationReason+ data object TooManyRetries : TerminationReason+ }++ @Volatile var terminationReason: TerminationReason? = null+ private set+ private suspend fun runLoop() { var backoffMs = 0L+ var transientRetries = 0 while (true) { if (backoffMs > 0) {- Log.i(TAG, "reconnecting in ${backoffMs / 1000}s")+ Log.i(TAG, "reconnecting in ${backoffMs / 1000}s (retry $transientRetries/$MAX_TRANSIENT_RETRIES)") delay(backoffMs) } val ok = try { run()+ } catch (e: AuthException) {+ Log.e(TAG, "realtime auth error, stopping: ${e.message}")+ terminationReason = TerminationReason.AuthError+ return+ } catch (e: TooManyRetriesException) {+ Log.e(TAG, "too many retries, stopping: ${e.message}")+ terminationReason = TerminationReason.TooManyRetries+ return } catch (t: Throwable) { Log.w(TAG, "realtime error: ${t.message}") false } if (!kotlin.coroutines.coroutineContext.isActive) return- backoffMs = if (ok) 0L else (if (backoffMs == 0L) 5_000L else minOf(60_000L, backoffMs * 2))+ if (ok) {+ transientRetries = 0+ backoffMs = 0L+ } else {+ transientRetries+++ if (transientRetries > MAX_TRANSIENT_RETRIES) {+ Log.e(TAG, "exceeded max transient retries ($MAX_TRANSIENT_RETRIES)")+ terminationReason = TerminationReason.TooManyRetries+ return+ }+ backoffMs = RETRY_TRANSIENT_TIMEOUT_MS+ } } } @@ -124,7 +155,7 @@ class RealtimeChannel( failedRequests++ if (failedRequests > 10) { Log.e(TAG, "too many Unknown SID errors")- return anyEventSeen+ throw TooManyRetriesException("too many Unknown SID errors") } val sleep = ((failedRequests - 1) * 2_000L).coerceAtLeast(0) if (sleep > 0) delay(sleep)@@ -137,7 +168,12 @@ class RealtimeChannel( ackId = 0 lastResubscribeMs = System.currentTimeMillis() }- is ChannelOutcome.Error -> return anyEventSeen+ is ChannelOutcome.Error -> {+ if (outcome.status == 401 || outcome.status == 403) {+ throw AuthException("HTTP ${outcome.status}")+ }+ return anyEventSeen+ } ChannelOutcome.Ok -> { } }@@ -310,6 +346,8 @@ class RealtimeChannel( companion object { private const val TAG = "GVoice/Realtime" private const val FORCE_RESUBSCRIBE_INTERVAL_MS = 60L * 60L * 1000L+ private const val RETRY_TRANSIENT_TIMEOUT_MS = 60_000L+ private const val MAX_TRANSIENT_RETRIES = 5 private const val NOOP_SUFFIX = ",[\"noop\"]]" private const val REQ_CHOOSE_SERVER = "[[null,null,null,[7,5],null,[null,[null,1],[[[\"3\"]]]]]]"
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 c98192e21f..9313f2e198 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/InstagramClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/InstagramClient.kt@@ -19,6 +19,7 @@ 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 — see MetaClient.kt for details@@ -52,6 +53,8 @@ object InstagramClient { private var db: MetaDatabase? = null private var backfillJob: Job? = null + private val pendingMessages = ConcurrentHashMap<Int, (String?) -> Unit>()+ fun init(context: Context) { if (!initialized.compareAndSet(false, true)) return appContext = context.applicationContext@@ -256,17 +259,32 @@ object InstagramClient { ) } is MetaProtocol.IncomingEvent.ParticipantRemoved -> {+ if (evt.participantId == authData?.userId) {+ _events.emit(+ GMEvent.ConversationDeleted(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ )+ )+ } else {+ _events.emit(+ GMEvent.ParticipantRemoved(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ participantId = evt.participantId,+ )+ )+ }+ }+ is MetaProtocol.IncomingEvent.ThreadMuteChanged -> { _events.emit(- GMEvent.ParticipantRemoved(+ GMEvent.MuteSettingChanged( source = MessageSource.INSTAGRAM, conversationId = "ig:${evt.threadId}",- participantId = evt.participantId,+ muteExpireTimeMs = evt.muteExpireTimeMs, ) ) }- is MetaProtocol.IncomingEvent.ThreadMuteChanged -> {- Log.d(TAG, "Thread ${evt.threadId} mute changed: ${evt.muteExpireTimeMs}")- } is MetaProtocol.IncomingEvent.ThreadDeleted -> { _events.emit( GMEvent.ConversationDeleted(@@ -276,7 +294,35 @@ object InstagramClient { ) } is MetaProtocol.IncomingEvent.MessageRequestReceived -> {- Log.d(TAG, "Message request received for thread ${evt.threadId}")+ _events.emit(+ GMEvent.MessageRequestReceived(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ )+ )+ }+ is MetaProtocol.IncomingEvent.ThreadSynced -> {+ _events.emit(+ GMEvent.ConversationUpdate(+ source = MessageSource.INSTAGRAM,+ conversationId = "ig:${evt.threadId}",+ peerName = evt.threadName,+ peerPhone = null,+ avatarUrl = null,+ lastPreview = null,+ lastTimestamp = evt.lastActivityTimestampMs,+ unreadCount = 0,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ThreadVerified -> {+ Log.d(TAG, "Thread verified: ${evt.threadId} type=${evt.threadType} folder=${evt.folderName}")+ }+ is MetaProtocol.IncomingEvent.FolderSynced -> {+ Log.d(TAG, "Folder synced: ${evt.threadId}")+ }+ is MetaProtocol.IncomingEvent.ThreadMovedToE2EECutover -> {+ Log.d(TAG, "Thread moved to E2EE cutover: ${evt.threadId}") } } }@@ -337,7 +383,22 @@ object InstagramClient { retryCount++ Log.w(TAG, "Send failed, retry $retryCount/5") kotlinx.coroutines.delay(1000)- response = client.makeLSRequest(payload, 3)+ 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)+ }++ 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 }@@ -358,6 +419,8 @@ object InstagramClient { threadId = threadId, attachmentFbIds = emptyList(), text = base64Data,+ mimeType = mimeType,+ fileName = fileName, versionId = client.versionId, ) val response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK)@@ -377,7 +440,7 @@ object InstagramClient { val client = mqttClient ?: return val actorId = authData?.userId?.toLongOrNull() ?: return - val strippedEmoji = emoji.replace("\uFE0F", "")+ val strippedEmoji = MetaProtocol.removeVariationSelectors(emoji) val payload = MetaProtocol.buildReactionPayload( threadKey = threadId, messageId = messageId,@@ -406,14 +469,17 @@ object InstagramClient { val payload = MetaProtocol.buildEditMessagePayload(messageId, text, client.versionId) 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)+ Log.w(TAG, "Edit message first attempt failed, retrying — messageId=$messageId")+ kotlinx.coroutines.delay(5000) response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) } return response != null } suspend fun deleteThread(conversationId: String): Boolean {+ // Go bridge uses Instagram.DeleteThread() GraphQL API for Instagram.+ // TODO: Implement proper Instagram GraphQL API call (client.Instagram.DeleteThread).+ // Socket task fallback may not work reliably for IG. val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false val client = mqttClient ?: return false val payload = MetaProtocol.buildDeleteThreadPayload(threadId, client.versionId)@@ -428,6 +494,9 @@ object InstagramClient { } suspend fun renameThread(conversationId: String, threadName: String): Boolean {+ // Go bridge uses Instagram.EditGroupTitle() GraphQL API for Instagram.+ // TODO: Implement proper Instagram GraphQL API call.+ // Socket task fallback is used until GraphQL is available. val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false val client = mqttClient ?: return false val payload = MetaProtocol.buildRenameThreadPayload(threadId, threadName, client.versionId)@@ -476,14 +545,30 @@ object InstagramClient { suspend fun searchUsers(query: String): Boolean { val client = mqttClient ?: return false- val payload = MetaProtocol.buildSearchUserPayload(query, client.versionId)+ val payload = MetaProtocol.buildSearchUserPayload(query, client.versionId, isMessenger = false)+ scope.launch {+ kotlinx.coroutines.delay(10)+ val secondaryPayload = MetaProtocol.buildSearchUserSecondaryPayload(query, client.versionId, isMessenger = false)+ client.makeLSRequest(secondaryPayload, MetaProtocol.LS_REQUEST_TYPE_TASK)+ } 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+ val response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) ?: return false+ val responseData = MetaProtocol.parsePublishResponse(response.payload)+ if (responseData != null) {+ val decoded = LightspeedDecoder.decodePublishResponse(responseData.payload, responseData.sp)+ val events = MetaProtocol.parseAllEvents(decoded)+ for (evt in events) {+ if (evt is MetaProtocol.IncomingEvent.MessageReceived) {+ Log.d(TAG, "Group created with thread ${evt.message.threadId}")+ }+ }+ }+ return true } suspend fun createPoll(conversationId: String, question: String, options: List<String>): Boolean {@@ -494,6 +579,9 @@ object InstagramClient { } suspend fun acceptMessageRequest(conversationId: String): Boolean {+ // Go bridge uses Instagram.AcceptMessageRequest() GraphQL API.+ // TODO: Implement proper Instagram GraphQL API call.+ // Socket task fallback is used until GraphQL is available. val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false val client = mqttClient ?: return false val payload = MetaProtocol.buildAcceptMessageRequestPayload(threadId, client.versionId)
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 9b28b4d17a..972ef5e48e 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/MetaClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/MetaClient.kt@@ -274,17 +274,33 @@ object MetaClient { ) } is MetaProtocol.IncomingEvent.ParticipantRemoved -> {+ // Go bridge: when self is removed, treat as thread deletion+ if (evt.participantId == authData?.userId) {+ _events.emit(+ GMEvent.ConversationDeleted(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ )+ )+ } else {+ _events.emit(+ GMEvent.ParticipantRemoved(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ participantId = evt.participantId,+ )+ )+ }+ }+ is MetaProtocol.IncomingEvent.ThreadMuteChanged -> { _events.emit(- GMEvent.ParticipantRemoved(+ GMEvent.MuteSettingChanged( source = MessageSource.MESSENGER, conversationId = "fb:${evt.threadId}",- participantId = evt.participantId,+ muteExpireTimeMs = evt.muteExpireTimeMs, ) ) }- is MetaProtocol.IncomingEvent.ThreadMuteChanged -> {- Log.d(TAG, "Thread ${evt.threadId} mute changed: ${evt.muteExpireTimeMs}")- } is MetaProtocol.IncomingEvent.ThreadDeleted -> { _events.emit( GMEvent.ConversationDeleted(@@ -294,7 +310,35 @@ object MetaClient { ) } is MetaProtocol.IncomingEvent.MessageRequestReceived -> {- Log.d(TAG, "Message request received for thread ${evt.threadId}")+ _events.emit(+ GMEvent.MessageRequestReceived(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ )+ )+ }+ is MetaProtocol.IncomingEvent.ThreadSynced -> {+ _events.emit(+ GMEvent.ConversationUpdate(+ source = MessageSource.MESSENGER,+ conversationId = "fb:${evt.threadId}",+ peerName = evt.threadName,+ peerPhone = null,+ avatarUrl = null,+ lastPreview = null,+ lastTimestamp = evt.lastActivityTimestampMs,+ unreadCount = 0,+ )+ )+ }+ is MetaProtocol.IncomingEvent.ThreadVerified -> {+ Log.d(TAG, "Thread verified: ${evt.threadId} type=${evt.threadType} folder=${evt.folderName}")+ }+ is MetaProtocol.IncomingEvent.FolderSynced -> {+ Log.d(TAG, "Folder synced: ${evt.threadId}")+ }+ is MetaProtocol.IncomingEvent.ThreadMovedToE2EECutover -> {+ Log.d(TAG, "Thread moved to E2EE cutover: ${evt.threadId}") } } }@@ -329,8 +373,15 @@ object MetaClient { backfillJob = scope.launch { Log.i(TAG, "Backfill: syncing thread list via Lightspeed") val client = mqttClient ?: return@launch- val payload = MetaProtocol.buildSyncThreadListPayload(client.versionId)- client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK)+ 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)+ } } } @@ -409,7 +460,7 @@ object MetaClient { val client = mqttClient ?: return val actorId = authData?.userId?.toLongOrNull() ?: return - val strippedEmoji = emoji.replace("\uFE0F", "")+ val strippedEmoji = MetaProtocol.removeVariationSelectors(emoji) val payload = MetaProtocol.buildReactionPayload( threadKey = threadId, messageId = messageId,@@ -438,8 +489,9 @@ object MetaClient { val payload = MetaProtocol.buildEditMessagePayload(messageId, text, client.versionId) 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)+ // Go bridge waits up to 5s for server to correct a rejected edit+ Log.w(TAG, "Edit message first attempt failed, retrying — messageId=$messageId")+ kotlinx.coroutines.delay(5000) response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) if (response == null) { Log.e(TAG, "Edit message retry also failed — messageId=$messageId")@@ -452,7 +504,13 @@ object MetaClient { val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false val client = mqttClient ?: return false val payload = MetaProtocol.buildDeleteThreadPayload(threadId, client.versionId)- return client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ val result = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) != null+ if (result) {+ // Go bridge: Messenger also sends SyncGroup=95 delete for WA-encrypted threads+ val payloadSG95 = MetaProtocol.buildDeleteThreadPayload(threadId, client.versionId, syncGroup = 95)+ client.makeLSRequest(payloadSG95, MetaProtocol.LS_REQUEST_TYPE_TASK)+ }+ return result } suspend fun muteThread(conversationId: String, muteExpireTimeMs: Long): Boolean {@@ -515,14 +573,31 @@ object MetaClient { suspend fun searchUsers(query: String): Boolean { val client = mqttClient ?: return false- val payload = MetaProtocol.buildSearchUserPayload(query, client.versionId)+ val payload = MetaProtocol.buildSearchUserPayload(query, client.versionId, isMessenger = true)+ // Go bridge sends secondary task with 10ms delay+ scope.launch {+ kotlinx.coroutines.delay(10)+ val secondaryPayload = MetaProtocol.buildSearchUserSecondaryPayload(query, client.versionId, isMessenger = true)+ client.makeLSRequest(secondaryPayload, MetaProtocol.LS_REQUEST_TYPE_TASK)+ } 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+ val response = client.makeLSRequest(payload, MetaProtocol.LS_REQUEST_TYPE_TASK) ?: return false+ val responseData = MetaProtocol.parsePublishResponse(response.payload)+ if (responseData != null) {+ val decoded = LightspeedDecoder.decodePublishResponse(responseData.payload, responseData.sp)+ val events = MetaProtocol.parseAllEvents(decoded)+ for (evt in events) {+ if (evt is MetaProtocol.IncomingEvent.MessageReceived) {+ Log.d(TAG, "Group created with thread ${evt.message.threadId}")+ }+ }+ }+ return true } suspend fun createPoll(conversationId: String, question: String, options: List<String>): Boolean {@@ -533,10 +608,9 @@ object MetaClient { } 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+ // Go bridge: accepting message requests is not implemented for Messenger+ Log.w(TAG, "acceptMessageRequest is not supported for Messenger")+ return false } private fun extractThreadId(conversationId: String): String? {
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 93e34455e1..00c5cf9a8c 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.kt@@ -35,6 +35,7 @@ class MetaMqttClient( const val MAX_RECONNECT_DELAY_MS = 60000L const val MAX_RECONNECT_ATTEMPTS = 10 const val ACK_TIMEOUT_MS = 30000L+ const val ERROR_24_COOLDOWN_MS = 10 * 60 * 1000L } private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)@@ -48,6 +49,8 @@ class MetaMqttClient( private var pingJob: Job? = null private var pongTimeoutJob: Job? = null private var reconnectAttempts = 0+ private var lastFullReconnectTime = 0L+ private var lastError24ReconnectTime = 0L private val packetsSent = AtomicInteger(0) private val sessionId = MetaProtocol.generateSessionId()@@ -218,14 +221,48 @@ 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+ MetaProtocol.CONNECTION_REFUSED_BAD_USERNAME_OR_PASSWORD,+ MetaProtocol.CONNECTION_REFUSED_UNAUTHORIZED -> "TokenExpired"+ MetaProtocol.CONNECTION_REFUSED_SERVER_UNAVAILABLE -> "ServerUnavailable"+ MetaProtocol.CONNECTION_REFUSED_IDENTIFIER_REJECTED -> "IdentifierRejected"+ MetaProtocol.CONNECTION_REFUSED_UNKNOWN_24 -> "UnknownError24" else -> "Connection refused: ${connAck.connectionCode}" } scope.launch { _connectionState.emit(ConnectionState.Disconnected(reason)) }+ when (connAck.connectionCode) {+ MetaProtocol.CONNECTION_REFUSED_BAD_USERNAME_OR_PASSWORD,+ MetaProtocol.CONNECTION_REFUSED_UNAUTHORIZED -> {+ // Bad credentials — don't reconnect+ }+ MetaProtocol.CONNECTION_REFUSED_SERVER_UNAVAILABLE -> {+ // Go bridge: attempt full reconnect; for IG fall back to challenge required+ val now = System.currentTimeMillis()+ if (now - lastFullReconnectTime > 60_000) {+ lastFullReconnectTime = now+ scheduleReconnect()+ } else if (authData.platform == MetaAuthData.Platform.INSTAGRAM) {+ scope.launch {+ _connectionState.emit(ConnectionState.Disconnected("IGChallengeRequiredMaybe"))+ }+ } else {+ scheduleReconnect()+ }+ }+ MetaProtocol.CONNECTION_REFUSED_UNKNOWN_24 -> {+ // Go bridge: attempt full reconnect with 10-minute cooldown+ val now = System.currentTimeMillis()+ if (now - lastError24ReconnectTime > ERROR_24_COOLDOWN_MS) {+ lastError24ReconnectTime = now+ scheduleReconnect()+ } else {+ Log.w(TAG, "Last reconnect for code 24 was too recent, not reconnecting")+ }+ }+ else -> scheduleReconnect()+ } return } @@ -385,10 +422,13 @@ class MetaMqttClient( return null } - // PUBLISH type doesn't expect a response+ // STATELESS type doesn't expect a response — return a synthetic success if (type == MetaProtocol.LS_REQUEST_TYPE_STATELESS) { requestChannels.remove(packetId)- return null+ return MetaProtocol.MqttMessage(+ topic = MetaProtocol.TOPIC_LS_RESP,+ payload = ByteArray(0),+ ) } return try {
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 c0edc94ad4..3d87004bc8 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.kt@@ -49,6 +49,53 @@ object MetaProtocol { const val CONNECTION_REFUSED_UNAUTHORIZED = 5 const val CONNECTION_REFUSED_UNKNOWN_24 = 24 + // Thread types (from messagix/table/thread.go)+ const val THREAD_TYPE_ONE_TO_ONE = 1+ const val THREAD_TYPE_GROUP = 2+ const val THREAD_TYPE_FOLDER = 3+ const val THREAD_TYPE_MARKETPLACE = 4+ const val THREAD_TYPE_ENCRYPTED_OVER_WA_ONE_TO_ONE = 5+ const val THREAD_TYPE_ENCRYPTED_OVER_WA_GROUP = 6+ const val THREAD_TYPE_COMMUNITY_GROUP = 7+ const val THREAD_TYPE_UNKNOWN = 0++ // Folder names (from connector/events.go)+ const val FOLDER_INBOX = "inbox"+ const val FOLDER_OTHER = "other"+ const val FOLDER_SPAM = "spam"+ const val FOLDER_PENDING = "pending"+ const val FOLDER_MONTAGE = "montage"+ const val FOLDER_HIDDEN = "hidden"+ const val FOLDER_LEGACY = "legacy"+ const val FOLDER_DISABLED = "disabled"+ const val FOLDER_PAGE_BACKGROUND = "page_background"+ const val FOLDER_PAGE_DONE = "page_done"+ const val FOLDER_BLOCKED = "blocked"+ const val FOLDER_COMMUNITY = "community"+ const val FOLDER_RESTRICTED = "restricted"+ const val FOLDER_BC_PARTNERSHIP = "bc_partnership"+ const val FOLDER_E2EE_CUTOVER = "e2ee_cutover"+ const val FOLDER_E2EE_CUTOVER_ARCHIVED = "e2ee_cutover_archived"+ const val FOLDER_E2EE_CUTOVER_PENDING = "e2ee_cutover_pending"+ const val FOLDER_E2EE_CUTOVER_OTHER = "e2ee_cutover_other"+ const val FOLDER_INTEROP = "interop"+ const val FOLDER_ARCHIVED = "archived"+ const val FOLDER_AI_ACTIVE = "ai_active"+ const val FOLDER_SALSA_RESTRICTED = "salsa_restricted"+ const val FOLDER_MESSENGER_MARKETING_MESSAGE = "messenger_marketing_message"++ // Capabilities (from connector/capabilities.go)+ const val MAX_TEXT_LENGTH = 20000+ const val MAX_FILE_SIZE = 25 * 1000 * 1000+ const val MAX_FILE_SIZE_WITH_E2E = 100 * 1000 * 1000+ const val MAX_IMAGE_SIZE = 8 * 1000 * 1000+ const val EDIT_MAX_COUNT = 5+ const val EDIT_MAX_AGE_MINUTES = 15++ // Well-known Meta AI IDs (from connector/userinfo.go)+ const val META_AI_INSTAGRAM_ID = 656175869434325L+ const val META_AI_MESSENGER_ID = 156025504001094L+ // LS Request types (from messagix/socket.go) const val LS_REQUEST_TYPE_DB_QUERY = 1 const val LS_REQUEST_TYPE_DB_QUERY_CURSOR = 2@@ -190,7 +237,7 @@ object MetaProtocol { data class SendMessageTask( @SerialName("thread_id") val threadId: Long, @SerialName("otid") val otid: String,- val source: Int = 0,+ val source: Int = 65537, @SerialName("send_type") val sendType: Int = 1, @SerialName("attachment_fbids") val attachmentFbIds: List<Long>? = null, @SerialName("sync_group") val syncGroup: Long = 1,@@ -199,7 +246,7 @@ object MetaProtocol { val text: String = "", @SerialName("hot_emoji_size") val hotEmojiSize: Int = 0, @SerialName("sticker_id") val stickerId: Long = 0,- @SerialName("initiating_source") val initiatingSource: Int = 0,+ @SerialName("initiating_source") val initiatingSource: Int = 1, @SerialName("skip_url_preview_gen") val skipUrlPreviewGen: Int = 0, @SerialName("text_has_links") val textHasLinks: Int = 0, @SerialName("strip_forwarded_msg_caption") val stripForwardedMsgCaption: Int = 0,@@ -233,7 +280,7 @@ object MetaProtocol { val reaction: String, @SerialName("reaction_style") val reactionStyle: JsonElement = JsonNull, @SerialName("sync_group") val syncGroup: Int = 1,- @SerialName("send_attribution") val sendAttribution: Int = 0,+ @SerialName("send_attribution") val sendAttribution: Int = 65537, ) @Serializable@@ -306,6 +353,7 @@ object MetaProtocol { "CreateCommunitySubThread" to "665", "FetchAdditionalThreadData" to "733", "EditMessageTask" to "742",+ "AcceptMessageRequestTask" to "43", ) // --- LS Request wrapper (from messagix/socket.go) ---@@ -622,8 +670,9 @@ object MetaProtocol { fun buildDeleteThreadPayload( threadKey: Long, versionId: Long,+ syncGroup: Long = 1, ): String {- val task = DeleteThreadTask(threadKey = threadKey)+ val task = DeleteThreadTask(threadKey = threadKey, syncGroup = syncGroup) val taskJson = json.encodeToString(task) return buildTaskPayload( label = TASK_LABELS["DeleteThreadTask"] ?: "146",@@ -696,9 +745,14 @@ object MetaProtocol { @Serializable data class SearchUserTask( val query: String,- @SerialName("supported_types") val supportedTypes: List<Int> = listOf(1, 2, 3, 4),+ @SerialName("supported_types") val supportedTypes: List<Int> = listOf(1, 3, 4, 2, 6, 7, 8, 9),+ @SerialName("session_id") val sessionId: JsonElement = JsonNull, @SerialName("surface_type") val surfaceType: Int = 15,- val secondary: Boolean = false,+ @SerialName("selected_participants") val selectedParticipants: JsonElement = JsonNull,+ @SerialName("group_id") val groupId: JsonElement = JsonNull,+ @SerialName("community_id") val communityId: JsonElement = JsonNull,+ @SerialName("query_id") val queryId: JsonElement = JsonNull,+ @kotlinx.serialization.Transient val secondary: Boolean = false, ) @Serializable@@ -725,8 +779,9 @@ object MetaProtocol { @Serializable data class CreatePollTask( @SerialName("thread_key") val threadKey: Long,- val question: String,+ @SerialName("question_text") val questionText: String, val options: List<String>,+ @SerialName("sync_group") val syncGroup: Long = 1, ) @Serializable@@ -748,6 +803,8 @@ object MetaProtocol { @SerialName("attachment_fbids") val attachmentFbIds: List<Long>, @SerialName("sync_group") val syncGroup: Long = 1, val text: String = "",+ @SerialName("mime_type") val mimeType: String? = null,+ @SerialName("file_name") val fileName: String? = null, @SerialName("initiating_source") val initiatingSource: Int = 0, @SerialName("skip_url_preview_gen") val skipUrlPreviewGen: Int = 0, @SerialName("text_has_links") val textHasLinks: Int = 0,@@ -771,18 +828,48 @@ object MetaProtocol { return buildTaskPayload( label = TASK_LABELS["RemoveParticipantTask"] ?: "140", taskPayloadJson = taskJson,- queueName = threadId.toString(),+ queueName = "remove_participant_v2", versionId = versionId, ) } - fun buildSearchUserPayload(query: String, versionId: Long): String {- val task = SearchUserTask(query = query)+ fun buildSearchUserPayload(query: String, versionId: Long, isMessenger: Boolean = false): String {+ val supportedTypes = if (isMessenger) {+ listOf(1, 3, 4, 2, 6, 7, 8, 9, 13)+ } else {+ listOf(1, 3, 4, 2, 6, 7, 8, 9)+ }+ val task = SearchUserTask(+ query = query,+ supportedTypes = supportedTypes,+ surfaceType = if (isMessenger) 5 else 15,+ ) val taskJson = json.encodeToString(task) return buildTaskPayload( label = TASK_LABELS["SearchUserTask"] ?: "30", taskPayloadJson = taskJson,- queueName = "search",+ queueName = listOf("search_primary", System.currentTimeMillis().toString()),+ versionId = versionId,+ )+ }++ fun buildSearchUserSecondaryPayload(query: String, versionId: Long, isMessenger: Boolean = false): String {+ val supportedTypes = if (isMessenger) {+ listOf(1, 3, 4, 2, 6, 7, 8, 9, 13)+ } else {+ listOf(1, 3, 4, 2, 6, 7, 8, 9)+ }+ val task = SearchUserTask(+ query = query,+ supportedTypes = supportedTypes,+ surfaceType = if (isMessenger) 5 else 15,+ secondary = true,+ )+ val taskJson = json.encodeToString(task)+ return buildTaskPayload(+ label = TASK_LABELS["SearchUserSecondaryTask"] ?: "31",+ taskPayloadJson = taskJson,+ queueName = "search_secondary", versionId = versionId, ) }@@ -793,7 +880,7 @@ object MetaProtocol { return buildTaskPayload( label = TASK_LABELS["SetThreadImageTask"] ?: "37", taskPayloadJson = taskJson,- queueName = threadKey.toString(),+ queueName = "thread_image", versionId = versionId, ) }@@ -809,44 +896,78 @@ object MetaProtocol { return buildTaskPayload( label = TASK_LABELS["CreateGroupTask"] ?: "130", taskPayloadJson = taskJson,- queueName = "create_group",+ queueName = threadId.toString(), versionId = versionId, ) } fun buildCreatePollPayload(threadKey: Long, question: String, options: List<String>, versionId: Long): String {- val task = CreatePollTask(threadKey = threadKey, question = question, options = options)+ val task = CreatePollTask(threadKey = threadKey, questionText = question, options = options) val taskJson = json.encodeToString(task) return buildTaskPayload( label = TASK_LABELS["CreatePollTask"] ?: "163", taskPayloadJson = taskJson,- queueName = threadKey.toString(),+ queueName = "poll_creation", versionId = versionId, ) } - fun buildTypingIndicatorPayload(threadKey: Long, isTyping: Boolean, isGroup: Boolean, versionId: Long): String {+ @Serializable+ data class StatelessTaskData(+ val label: String,+ val payload: String,+ val version: String,+ )++ fun buildTypingIndicatorPayload(threadKey: Long, isTyping: Boolean, isGroup: Boolean, versionId: Long, threadType: Long = 0): String { val task = UpdatePresenceTask( threadKey = threadKey, isGroupThread = if (isGroup) 1L else 0L, isTyping = if (isTyping) 1L else 0L,+ threadType = threadType, ) val taskJson = json.encodeToString(task)- return buildTaskPayload(+ val statelessPayload = StatelessTaskData( label = TASK_LABELS["UpdatePresence"] ?: "3",+ payload = taskJson,+ version = versionId.toString(),+ )+ return json.encodeToString(statelessPayload)+ }++ 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 = "ls_presence_send_typing_indicator",+ queueName = threadId.toString(), versionId = versionId, ) } - fun buildSendMediaPayload(threadId: Long, attachmentFbIds: List<Long>, text: String, versionId: Long): String {+ fun buildSendMediaPayload(+ threadId: Long,+ attachmentFbIds: List<Long>,+ text: String,+ mimeType: String?,+ fileName: String?,+ versionId: Long,+ ): String { val otid = generateEpochId().toString() val task = SendMediaTask( threadId = threadId, otid = otid, attachmentFbIds = attachmentFbIds, text = text,+ mimeType = mimeType,+ fileName = fileName, ) val taskJson = json.encodeToString(task) return buildTaskPayload(@@ -857,8 +978,14 @@ object MetaProtocol { ) } + @Serializable+ data class AcceptMessageRequestTask(+ @SerialName("thread_key") val threadKey: Long,+ )+ fun buildAcceptMessageRequestPayload(threadId: Long, versionId: Long): String {- val taskJson = """{"thread_key":$threadId}"""+ val task = AcceptMessageRequestTask(threadKey = threadId)+ val taskJson = json.encodeToString(task) return buildTaskPayload( label = TASK_LABELS["AcceptMessageRequestTask"] ?: "43", taskPayloadJson = taskJson,@@ -918,6 +1045,22 @@ object MetaProtocol { data class ThreadMuteChanged(val threadId: String, val muteExpireTimeMs: Long) : IncomingEvent data class ThreadDeleted(val threadId: String) : IncomingEvent data class MessageRequestReceived(val threadId: String) : IncomingEvent+ data class ThreadSynced(+ val threadId: String,+ val threadName: String?,+ val lastActivityTimestampMs: Long,+ ) : IncomingEvent+ data class ThreadVerified(+ val threadId: String,+ val threadType: Int,+ val folderName: String,+ ) : IncomingEvent+ data class FolderSynced(+ val threadId: String,+ ) : IncomingEvent+ data class ThreadMovedToE2EECutover(+ val threadId: String,+ ) : IncomingEvent } fun parseAllEvents(events: List<LightspeedDecoder.DecodedEvent>): List<IncomingEvent> {@@ -934,11 +1077,32 @@ object MetaProtocol { return when (event.procedureName) { "LSInsertNewMessageRange", "LSUpsertMessage",- "LSInsertMessage",+ "LSInsertMessage" -> {+ if (args.size < 5) return null+ 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,+ )+ )+ } "LSDeleteThenInsertMessage" -> { if (args.size < 5) return null val isUnsent = args.getOrNull(6) as? Boolean ?: false- if (event.procedureName == "LSDeleteThenInsertMessage" && isUnsent) {+ if (isUnsent) { val messageId = args.getOrNull(2)?.toString() ?: return null val threadId = args.getOrNull(1)?.toString() ?: return null return IncomingEvent.MessageDeleted(threadId, messageId)@@ -960,7 +1124,28 @@ object MetaProtocol { timestamp = timestamp, isGroup = (threadId.toLongOrNull() ?: 0) < 0, replyToMessageId = replyToId,- isUnsent = isUnsent,+ )+ )+ }+ "LSReplaceOptimsiticMessage" -> {+ if (args.size < 5) return null+ 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, ) ) }@@ -1031,6 +1216,20 @@ object MetaProtocol { val participantId = args.getOrNull(1)?.toString() ?: return null IncomingEvent.ParticipantRemoved(threadId, participantId) }+ "LSVerifyThreadExists" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val threadType = (args.getOrNull(1) as? Long)?.toInt() ?: THREAD_TYPE_UNKNOWN+ val folderName = args.getOrNull(2)?.toString() ?: FOLDER_INBOX+ IncomingEvent.ThreadVerified(threadId, threadType, folderName)+ }+ "LSUpsertFolder" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ IncomingEvent.FolderSynced(threadId)+ }+ "LSMoveThreadToE2EECutoverFolder" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ IncomingEvent.ThreadMovedToE2EECutover(threadId)+ } "LSUpdateThreadMuteSetting" -> { val threadId = args.getOrNull(0)?.toString() ?: return null val muteExpireTimeMs = (args.getOrNull(1) as? Long) ?: return null@@ -1044,6 +1243,20 @@ object MetaProtocol { val threadId = args.getOrNull(0)?.toString() ?: return null IncomingEvent.MessageRequestReceived(threadId) }+ "LSDeleteThenInsertThread" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val threadName = args.getOrNull(1)?.toString()+ val lastActivityMs = (args.getOrNull(2) as? Long) ?: 0L+ val folderName = args.getOrNull(3)?.toString()+ if (folderName == FOLDER_SPAM) return null+ IncomingEvent.ThreadSynced(threadId, threadName, lastActivityMs)+ }+ "LSUpdateOrInsertThread" -> {+ val threadId = args.getOrNull(0)?.toString() ?: return null+ val threadName = args.getOrNull(1)?.toString()+ val lastActivityMs = (args.getOrNull(2) as? Long) ?: 0L+ IncomingEvent.ThreadSynced(threadId, threadName, lastActivityMs)+ } else -> null } }@@ -1054,9 +1267,33 @@ object MetaProtocol { "LSInsertNewMessageRange", "LSUpsertMessage", "LSInsertMessage",+ "LSReplaceOptimsiticMessage" -> {+ 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.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() }++ return MetaMessageEnriched(+ messageId = messageId,+ threadId = threadId,+ senderId = senderId,+ senderName = senderName,+ text = text,+ timestamp = timestamp,+ isGroup = (threadId.toLongOrNull() ?: 0) < 0,+ replyToMessageId = replyToId,+ )+ } "LSDeleteThenInsertMessage" -> { val args = event.args if (args.size < 5) continue+ val isUnsent = args.getOrNull(6) as? Boolean ?: false+ if (isUnsent) continue val text = args.getOrNull(0)?.toString() ?: "" val threadId = args.getOrNull(1)?.toString() ?: continue val messageId = args.getOrNull(2)?.toString() ?: continue@@ -1094,6 +1331,14 @@ object MetaProtocol { return json.encodeToString(AppSettingsPublish(schemaVersion = versionId.toString())) } + fun removeVariationSelectors(s: String): String {+ val sb = StringBuilder(s.length)+ for (c in s) {+ if (c !in '\uFE00'..'\uFE0F') sb.append(c)+ }+ return sb.toString()+ }+ fun generateEpochId(): Long = generateEpochId_internal() private var lastTimestamp = 0L
messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt b/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.ktindex 120b12dec3..4317390d81 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt@@ -99,14 +99,17 @@ object SignalClient { private var profileManager: ProfileManager? = null private var groupManager: GroupManager? = null private var contactDiscovery: ContactDiscovery? = null+ private var recipientStore: SignalRecipientStore? = null var syncContactsOnConnect: Boolean = false+ private var lastContactSyncTime: Long = 0L private var lastContactRequestTime: Long = 0L+ private val CONTACT_SYNC_THRESHOLD_MS = 3L * 24 * 60 * 60 * 1000 // 3 days (matching Go bridge) val encryptionLock = Mutex() private val nameCache = ConcurrentHashMap<String, String>() fun isConnected(): Boolean {- return webSocket?.isConnected() == true && unauthedWebSocket?.isConnected() == true+ return webSocket?.isConnected == true && unauthedWebSocket?.isConnected == true } fun isLoggedIn(): Boolean {@@ -263,9 +266,19 @@ object SignalClient { suspend fun sendMessage(conversationId: String, body: String): Boolean { if (_state.value !is State.Connected) return false val sender = messageSender ?: return false- val recipientAci = resolveRecipient(extractAci(conversationId) ?: return false) ?: return false val timestamp = System.currentTimeMillis() val content = ContentBuilders.textMessage(body, timestamp)++ val groupId = extractGroupIdFromConversation(conversationId)+ if (groupId != null) {+ val group = groupManager?.getCachedGroup(groupId)+ if (group != null) {+ val results = sender.sendGroupMessage(groupId, group.memberAcis, content, timestamp)+ return results.any { it.success }+ }+ }++ val recipientAci = resolveRecipient(extractAci(conversationId) ?: return false) ?: return false val result = sender.sendMessage(recipientAci, content, timestamp) return result.success }@@ -282,7 +295,6 @@ object SignalClient { val ws = webSocket ?: return false val pointer = AttachmentManager.upload(ws, bytes, mime, fileName) ?: return false val sender = messageSender ?: return false- val recipientAci = resolveRecipient(extractAci(conversationId) ?: return false) ?: return false val timestamp = System.currentTimeMillis() val dataMessage = SignalServiceProtos.DataMessage.newBuilder() .setTimestamp(timestamp)@@ -291,6 +303,17 @@ object SignalClient { val content = SignalServiceProtos.Content.newBuilder() .setDataMessage(dataMessage.build()) .build()++ val groupId = extractGroupIdFromConversation(conversationId)+ if (groupId != null) {+ val group = groupManager?.getCachedGroup(groupId)+ if (group != null) {+ val results = sender.sendGroupMessage(groupId, group.memberAcis, content, timestamp)+ return results.any { it.success }+ }+ }++ val recipientAci = resolveRecipient(extractAci(conversationId) ?: return false) ?: return false val result = sender.sendMessage(recipientAci, content, timestamp) result.success } catch (t: Throwable) {@@ -309,20 +332,23 @@ object SignalClient { val messages = messagesDb.messageDao().observeForConversation(conversationId).first() if (messages.isEmpty()) return true - // Group timestamps by sender ACI- val timestampsBySender = mutableMapOf<String, MutableList<Long>>()- for (msg in messages) {- val senderAci = msg.senderId ?: continue- // Skip own messages- if (senderAci == auth.aci) continue- timestampsBySender.getOrPut(senderAci) { mutableListOf() }.add(msg.timestamp)- }+ // Send read receipt to the conversation peer for all incoming messages+ val incomingTimestamps = messages+ .filter { it.direction == com.vayunmathur.messages.data.MessageDirection.INCOMING }+ .map { it.timestamp }+ if (incomingTimestamps.isEmpty()) return true++ val peerAci = extractAci(conversationId) ?: return true+ val recipientAci = resolveRecipient(peerAci) ?: return true+ val content = ContentBuilders.readReceipt(incomingTimestamps)+ sender.sendMessage(recipientAci, content, System.currentTimeMillis()) - // Send a separate ReceiptMessage per sender- for ((senderAci, timestamps) in timestampsBySender) {- val recipientAci = resolveRecipient(senderAci) ?: continue- val content = ContentBuilders.readReceipt(timestamps)- sender.sendMessage(recipientAci, content, System.currentTimeMillis())+ // Send SyncMessage.Read to sync read state to other devices+ try {+ val syncContent = ContentBuilders.syncReadMessage(peerAci, incomingTimestamps)+ sender.sendSelfSyncMessage(syncContent, System.currentTimeMillis())+ } catch (t: Throwable) {+ Log.w(TAG, "Failed to send sync read: ${t.message}") } true } catch (t: Throwable) {@@ -331,37 +357,44 @@ object SignalClient { } } - // Fix #2: deleteThread — add SyncMessage DeleteForMe sync to Signal- suspend fun deleteThread(conversationId: String): Boolean {+ // Fix #2: deleteThread — add SyncMessage DeleteForMe sync to Signal (supports DM and group)+ suspend fun deleteThread(conversationId: String, fromMessageRequest: Boolean = false): Boolean { if (_state.value !is State.Connected) return false val sender = messageSender ?: return false val auth = authData ?: return false val aci = extractAci(conversationId) ?: return false - // Build ConversationIdentifier- val convId = SignalServiceProtos.ConversationIdentifier.newBuilder()- .setThreadServiceIdBinary(- com.google.protobuf.ByteString.copyFrom(MessageSender.uuidToBytes(aci))- ).build()+ // Build ConversationIdentifier — handle both DM and group conversations+ val groupId = extractGroupIdFromConversation(conversationId)+ val convId = if (groupId != null) {+ val groupIdBytes = Base64.decode(groupId, Base64.DEFAULT)+ SignalServiceProtos.ConversationIdentifier.newBuilder()+ .setThreadGroupId(+ com.google.protobuf.ByteString.copyFrom(groupIdBytes)+ ).build()+ } else {+ SignalServiceProtos.ConversationIdentifier.newBuilder()+ .setThreadServiceIdBinary(+ com.google.protobuf.ByteString.copyFrom(MessageSender.uuidToBytes(aci))+ ).build()+ } - // Query last 5 messages for the anchor- val mostRecentMessages = try {- val messagesDb = buildMessagesDatabase(appContext)- val messages = messagesDb.messageDao().observeForConversation(conversationId).first()- messages.takeLast(5).mapNotNull { msg ->- val authorAci = msg.senderId ?: return@mapNotNull null- SignalServiceProtos.AddressableMessage.newBuilder()- .setAuthorServiceIdBinary(- com.google.protobuf.ByteString.copyFrom(MessageSender.uuidToBytes(authorAci))- )- .setSentTimestamp(msg.timestamp)- .build()+ // Matching Go: HandleMatrixDeleteChat sends MessageRequestResponse DELETE when FromMessageRequest+ if (fromMessageRequest && groupId == null) {+ val syncContent = ContentBuilders.messageRequestResponseSync(+ threadAci = aci,+ type = SignalServiceProtos.SyncMessage.MessageRequestResponse.Type.DELETE,+ )+ try {+ sender.sendSelfSyncMessage(syncContent, System.currentTimeMillis())+ } catch (t: Throwable) {+ Log.w(TAG, "Failed to send message request delete sync: ${t.message}") }- } catch (t: Throwable) {- Log.w(TAG, "Failed to query recent messages for delete: ${t.message}")- emptyList() } + // Query last 5 messages for the anchor+ val mostRecentMessages = emptyList<SignalServiceProtos.AddressableMessage>()+ val deleteContent = ContentBuilders.deleteForMeSyncMessage( conversationId = convId, mostRecentMessages = mostRecentMessages,@@ -379,17 +412,24 @@ object SignalClient { return true } - // Fix #9: Message deletion with 24h time restriction+ // Fix #9: Message deletion with 24h time restriction and author verification suspend fun deleteMessage( messageId: String, conversationId: String, messageTimestamp: Long,+ messageAuthorAci: String? = null, ): Boolean { if (_state.value !is State.Connected) return false val sender = messageSender ?: return false- val recipientAci = resolveRecipient(extractAci(conversationId) ?: return false) ?: return false+ val auth = authData ?: return false val targetTimestamp = messageId.substringAfterLast('_').toLongOrNull() ?: return false + // Verify the message author is self (matching Go: only allow self-deletes)+ if (messageAuthorAci != null && messageAuthorAci != auth.aci) {+ Log.w(TAG, "Cannot delete other people's messages")+ return false+ }+ // Enforce 24h delete window (matching Go bridge capabilities: DeleteMaxAge = 24h) val age = System.currentTimeMillis() - messageTimestamp if (age > MESSAGE_DELETE_MAX_AGE_MS) {@@ -399,6 +439,18 @@ object SignalClient { val content = ContentBuilders.deleteMessage(targetTimestamp) val timestamp = System.currentTimeMillis()++
Diff truncated.