messages: fix instagram read status
- Commit
7f4177183026c7c078e2367cdf986c4c2fcbd262- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-06 19:38 UTC (5 months ago)
- Parents
1357483
Diff
messages/src/main/java/com/vayunmathur/messages/data/Entities.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/data/Entities.kt b/messages/src/main/java/com/vayunmathur/messages/data/Entities.ktindex 32268fc74c..510f248626 100644--- a/messages/src/main/java/com/vayunmathur/messages/data/Entities.kt+++ b/messages/src/main/java/com/vayunmathur/messages/data/Entities.kt@@ -24,8 +24,6 @@ data class Conversation( @ColumnInfo(name = "peer_phone_e164") val peerPhoneE164: String?, @ColumnInfo(name = "avatar_url") val avatarUrl: String?, @ColumnInfo(name = "last_preview") val lastMessagePreview: String?,- /** Timestamp of the last message in the thread, epoch-ms. */- @ColumnInfo(name = "last_ts") val lastMessageTimestamp: Long, @ColumnInfo(name = "unread_count") val unreadCount: Int, /** Whether this thread has > 2 participants. Drives both the avatar * treatment (group glyph vs single photo) and the row title format. */
messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt b/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.ktindex 55d3613490..ae0d9a7f9a 100644--- a/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt+++ b/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt@@ -1,6 +1,8 @@ package com.vayunmathur.messages.data +import androidx.room.ColumnInfo import androidx.room.Dao+import androidx.room.Embedded import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.TypeConverter@@ -16,8 +18,16 @@ interface ConversationDao { @Upsert suspend fun upsertAll(conversations: List<Conversation>) - @Query("SELECT * FROM conversations ORDER BY last_ts DESC")- fun observeAll(): Flow<List<Conversation>>+ @Query(+ """+ SELECT c.*, COALESCE(MAX(m.timestamp), 0) AS last_ts+ FROM conversations c+ LEFT JOIN messages m ON m.conversation_id = c.id+ GROUP BY c.id+ ORDER BY last_ts DESC+ """+ )+ fun observeAll(): Flow<List<ConversationWithLastMessage>> @Query("SELECT * FROM conversations WHERE id = :id LIMIT 1") fun observe(id: String): Flow<Conversation?>@@ -62,6 +72,17 @@ interface MessageDao { suspend fun deleteAllForConvPrefix(prefix: String) } +/**+ * A [Conversation] plus the timestamp (epoch-ms) of its most recent+ * message, derived at query time from the messages table rather than+ * stored on the conversation row. `last_ts` is 0 when the thread has no+ * messages yet.+ */+data class ConversationWithLastMessage(+ @Embedded val conversation: Conversation,+ @ColumnInfo(name = "last_ts") val lastMessageTimestamp: Long,+)+ /** * Room can store our enums as their `.name` strings via a single * generic-style converter pair. Keeps migrations stable if enum order@@ -86,7 +107,7 @@ class MessagesConverters { @androidx.room.Database( entities = [Conversation::class, Message::class],- version = 7,+ version = 8, exportSchema = false, ) @TypeConverters(MessagesConverters::class)
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 b8403c8a62..f6b0020813 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/InstagramClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/InstagramClient.kt@@ -503,7 +503,11 @@ object InstagramClient { val threadId = extractThreadId(conversationId)?.toLongOrNull() ?: return false val client = mqttClient ?: return false if (!readReceiptsEnabled) return true- val watermark = (lastMessageId?.let { MetaProtocol.parseMessageId(it) })+ // The stored id is source-prefixed ("ig:mid.$…"); strip the prefix so parseMessageId+ // (which expects a bare "mid.$…") can read the embedded timestamp instead of failing+ // and silently falling back to the row timestamp.+ val rawMessageId = lastMessageId?.substringAfter(':', lastMessageId)+ val watermark = (rawMessageId?.let { MetaProtocol.parseMessageId(it) }) ?: lastTimestamp.takeIf { it > 0 } ?: System.currentTimeMillis() val payload = MetaProtocol.buildMarkReadPayload(threadId, client.versionId, watermark)@@ -680,6 +684,10 @@ object InstagramClient { } private fun extractThreadId(conversationId: String): String? {- return conversationId.removePrefix("ig:")+ // Conversation rows are source-prefixed, and Instagram emits its own+ // "ig:" prefix which handleEvent prefixes again ("ig:ig:<threadId>").+ // Take the final segment so we get the bare numeric thread id whether+ // the id is singly or doubly prefixed.+ return conversationId.substringAfterLast(':') } }
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 550fc43820..6a9ad02675 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/MetaClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/MetaClient.kt@@ -522,7 +522,10 @@ object MetaClient { if (!readReceiptsEnabled) return true // Watermark is the last-read message timestamp in ms (Go: fbMessageToReadTS.UnixMilli()). // Prefer the message id's embedded timestamp, fall back to the row timestamp, then now.- val watermark = (lastMessageId?.let { MetaProtocol.parseMessageId(it) })+ // The stored id is source-prefixed ("fb:mid.$…"); strip the prefix so parseMessageId+ // (which expects a bare "mid.$…") can read the embedded timestamp instead of failing.+ val rawMessageId = lastMessageId?.substringAfter(':', lastMessageId)+ val watermark = (rawMessageId?.let { MetaProtocol.parseMessageId(it) }) ?: lastTimestamp.takeIf { it > 0 } ?: System.currentTimeMillis() val payload = MetaProtocol.buildMarkReadPayload(threadId, client.versionId, watermark)@@ -706,6 +709,10 @@ object MetaClient { } private fun extractThreadId(conversationId: String): String? {- return conversationId.removePrefix("fb:")+ // Conversation rows are source-prefixed, and Messenger emits its own+ // "fb:" prefix which handleEvent prefixes again ("fb:fb:<threadId>").+ // Take the final segment so we get the bare numeric thread id whether+ // the id is singly or doubly prefixed.+ return conversationId.substringAfterLast(':') } }
messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.ktindex 9bf3b77be4..46f6913322 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt@@ -6,6 +6,7 @@ import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize@@ -114,12 +115,16 @@ fun InboxScreen( ) } } else {- LazyColumn {- items(conversations, key = { it.id }) { conv ->+ LazyColumn(+ // Room for the FAB so it doesn't cover the last row.+ contentPadding = PaddingValues(bottom = 88.dp),+ ) {+ items(conversations, key = { it.conversation.id }) { conv -> ConversationRow(- conversation = conv,- onClick = { backStack.add(Route.Conversation(conv.id)) },- onLongPress = { pendingDelete = conv },+ conversation = conv.conversation,+ lastMessageTimestamp = conv.lastMessageTimestamp,+ onClick = { backStack.add(Route.Conversation(conv.conversation.id)) },+ onLongPress = { pendingDelete = conv.conversation }, ) HorizontalDivider(Modifier.padding(horizontal = 16.dp)) }@@ -313,6 +318,7 @@ private fun sourceLabel(source: MessageSource): String = when (source) { @Composable private fun ConversationRow( conversation: Conversation,+ lastMessageTimestamp: Long, onClick: () -> Unit, onLongPress: () -> Unit = {}, ) {@@ -343,10 +349,12 @@ private fun ConversationRow( }, trailingContent = { Column(horizontalAlignment = Alignment.End) {- Text(- formatTimestamp(conversation.lastMessageTimestamp),- style = MaterialTheme.typography.labelSmall,- )+ if (lastMessageTimestamp > 0L) {+ Text(+ formatTimestamp(lastMessageTimestamp),+ style = MaterialTheme.typography.labelSmall,+ )+ } if (conversation.unreadCount > 0) { Spacer(Modifier.height(4.dp)) UnreadBadge(conversation.unreadCount)
messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.ktindex 5c4dd55805..ce8a6f9d5d 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt@@ -167,7 +167,7 @@ object MessagesSessionManager { senderName = null, ) )- touchConversationOutgoing(conversationId, body, now)+ touchConversationOutgoing(conversationId, body) val ok = when (source) { MessageSource.MESSAGES_WEB -> GMessagesClient.sendMessage(conversationId, body) MessageSource.VOICE -> GVoiceClient.sendMessage(conversationId, body)@@ -212,7 +212,7 @@ object MessagesSessionManager { senderName = null, ) )- touchConversationOutgoing(conversationId, previewBody, now)+ touchConversationOutgoing(conversationId, previewBody) val ok = when (source) { MessageSource.MESSAGES_WEB -> GMessagesClient.sendMedia( conversationId = conversationId,@@ -292,7 +292,7 @@ object MessagesSessionManager { senderName = null, ) )- touchConversationOutgoing(conversationId, "📊 $question", System.currentTimeMillis())+ touchConversationOutgoing(conversationId, "📊 $question") val ok = when (source) { MessageSource.MESSAGES_WEB -> GMessagesClient.sendPoll(conversationId, question, options, allowMultiple) MessageSource.VOICE -> GVoiceClient.sendPoll(conversationId, question, options, allowMultiple)@@ -608,6 +608,7 @@ object MessagesSessionManager { val needle = normalizePhone(phoneE164) val all = db.conversationDao().observeAll().firstOrNull().orEmpty() return all.asSequence()+ .map { it.conversation } .filter { !it.isGroup && it.peerPhoneE164 != null } .filter { normalizePhone(it.peerPhoneE164!!) == needle } .map { it.source }@@ -807,14 +808,6 @@ object MessagesSessionManager { is GMEvent.ConversationUpdate -> { val id = "${event.source.idPrefix}:${event.conversationId}" val existing = db.conversationDao().get(id)- // One-shot guard: rows persisted before the gmessages- // microseconds→milliseconds fix have last_ts > 1e14- // (≈ year 5138 in ms). Treat those as "no existing- // timestamp" so the first refresh after the fix lands- // immediately re-anchors to the correct scale rather- // than holding the stale huge value via maxOf.- val priorTs = existing?.lastMessageTimestamp- ?.takeIf { it < STALE_MICROSECOND_THRESHOLD_MS } ?: 0L // Persist the message-request flag into serviceData JSON // (no schema bump). Sources that signal via serviceData // directly (Signal) already carry it; honor the dedicated@@ -835,7 +828,6 @@ object MessagesSessionManager { peerPhoneE164 = event.peerPhone ?: existing?.peerPhoneE164, avatarUrl = event.avatarUrl ?: existing?.avatarUrl, lastMessagePreview = event.lastPreview ?: existing?.lastMessagePreview,- lastMessageTimestamp = maxOf(toEpochMillis(event.lastTimestamp), priorTs), unreadCount = event.unreadCount, isGroup = event.isGroup, participantCount = event.participantCount,@@ -892,7 +884,6 @@ object MessagesSessionManager { peerPhoneE164 = event.peerPhone ?: existing?.peerPhoneE164, avatarUrl = existing?.avatarUrl, lastMessagePreview = event.body,- lastMessageTimestamp = maxOf(toEpochMillis(event.timestamp), existing?.lastMessageTimestamp ?: 0L), // Don't re-count a message we've already seen — otherwise a // history re-sync inflates the unread badge on every reconnect. unreadCount = (existing?.unreadCount ?: 0) + if (alreadySeen) 0 else 1,@@ -941,6 +932,18 @@ object MessagesSessionManager { ) } }+ is GMEvent.ReadReceipt -> {+ // A "self" read receipt means the thread was read on another of+ // the user's own devices (e.g. Meta LSMarkThreadRead) — clear+ // the local unread badge to match. Peer read receipts (senderId+ // is a contact) are "Seen" indicators for our OUTGOING messages+ // and must not touch our own unread count. The convId is built+ // exactly as the other handlers store it.+ if (event.senderId == "self") {+ db.conversationDao()+ .markRead("${event.source.idPrefix}:${event.conversationId}")+ }+ } else -> Unit } }@@ -960,16 +963,11 @@ object MessagesSessionManager { if (attachments.isEmpty()) null else Json.encodeToString(ListSerializer(MessageAttachment.serializer()), attachments) - /** ≈ year 5138 in epoch-ms. Any persisted `last_ts` larger than this- * is almost certainly a stale microsecond value from before the- * gmessages timestamp fix; treat it as missing. */- private const val STALE_MICROSECOND_THRESHOLD_MS = 100_000_000_000_000L- /** * Coerce any platform timestamp to epoch-MILLISECONDS. The inbox is- * sorted purely by `last_ts DESC`, so every persisted timestamp must- * share one scale or the ordering interleaves and stops being- * newest-first. Platforms currently normalize at emission (Telegram/+ * sorted by each thread's most recent message timestamp, so every+ * persisted message timestamp must share one scale or the ordering+ * interleaves and stops being newest-first. Platforms currently * WhatsApp `*1000`, gmessages `µs/1000`, Signal/Meta/GVoice native * ms), but this is the single choke point that guarantees it — and * protects against a future source that forgets. Scales down from@@ -984,17 +982,16 @@ object MessagesSessionManager { } /**- * Bump a conversation's last-message time + preview when the LOCAL- * user sends. Outgoing sends otherwise only insert a message row and- * never touch `last_ts`, so a thread you just replied in wouldn't- * re-sort to the top of the inbox. Forward-only via maxOf.+ * Refresh a conversation's preview when the LOCAL user sends. The+ * inbox's sort order and displayed time now derive from the message+ * rows themselves (the outgoing row is inserted with the send time),+ * so we only need to keep the preview text in sync here. */- private suspend fun touchConversationOutgoing(conversationId: String, preview: String, nowMs: Long) {+ private suspend fun touchConversationOutgoing(conversationId: String, preview: String) { val existing = db.conversationDao().get(conversationId) ?: return db.conversationDao().upsert( existing.copy( lastMessagePreview = preview,- lastMessageTimestamp = maxOf(existing.lastMessageTimestamp, nowMs), ) ) }