messages: fix whatsapp polls
- Commit
37a2c0dd5b35e28071ec39e645bafc78af16e666- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-10 21:34 UTC (4 months ago)
- Parents
a471937
Diff
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 4e9d1746be..7ed628af8d 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt@@ -201,6 +201,10 @@ object MessagesSessionManager { val previewBody = caption?.takeIf { it.isNotBlank() } ?: "[Image]" val pendingId = "${source.idPrefix}:pending:${System.currentTimeMillis()}" val now = System.currentTimeMillis()+ // Cache the outgoing bytes locally and attach them so the sent bubble shows the actual+ // image/video instead of a bare "[Image]" placeholder (the UI suppresses the placeholder+ // once an attachment is present).+ val localMediaJson = buildOutgoingMediaJson(pendingId, bytes, mime, fileName) db.messageDao().upsert( Message( id = pendingId,@@ -210,6 +214,7 @@ object MessagesSessionManager { state = MessageState.PENDING, timestamp = now, senderName = null,+ mediaJson = localMediaJson, ) ) touchConversationOutgoing(conversationId, previewBody)@@ -1074,6 +1079,60 @@ object MessagesSessionManager { if (attachments.isEmpty()) null else Json.encodeToString(ListSerializer(MessageAttachment.serializer()), attachments) + /**+ * Cache outgoing media bytes to disk and return a one-item attachments JSON pointing at the+ * local file, so the sent bubble renders the actual image/video/etc. Returns null on failure+ * (the bubble then falls back to the text placeholder).+ */+ private fun buildOutgoingMediaJson(+ pendingId: String,+ bytes: ByteArray,+ mime: String,+ fileName: String,+ ): String? {+ val attachmentType = when {+ mime == "image/webp" -> "sticker"+ mime.startsWith("image/") -> "image"+ mime.startsWith("video/") -> "video"+ mime.startsWith("audio/") -> "audio"+ else -> "file"+ }+ return runCatching {+ val dir = java.io.File(appContext.cacheDir, "outgoing_media")+ dir.mkdirs()+ val ext = fileName.substringAfterLast('.', "").ifEmpty {+ when (attachmentType) {+ "image" -> "jpg"; "video" -> "mp4"; "audio" -> "ogg"+ "sticker" -> "webp"; else -> "bin"+ }+ }+ val safe = pendingId.replace(Regex("[^A-Za-z0-9._-]"), "_")+ val file = java.io.File(dir, "$safe.$ext")+ file.writeBytes(bytes)+ // Decode image bounds for a correct aspect ratio (cheap, bounds-only).+ var w = 0+ var h = 0+ if (attachmentType == "image" || attachmentType == "sticker") {+ val opts = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }+ android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)+ w = opts.outWidth.coerceAtLeast(0)+ h = opts.outHeight.coerceAtLeast(0)+ }+ attachmentsToJson(+ listOf(+ MessageAttachment(+ url = "file://${file.absolutePath}",+ mimeType = mime,+ attachmentType = attachmentType,+ fileName = fileName,+ width = w,+ height = h,+ )+ )+ )+ }.getOrNull()+ }+ /** * Coerce any platform timestamp to epoch-MILLISECONDS. The inbox is * sorted by each thread's most recent message timestamp, so every
messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.ktindex cb76fa136a..c1e966d230 100644--- a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt@@ -997,10 +997,27 @@ object WhatsAppClient { // Decrypt failure: ask the sender to re-encrypt (Go decryptMessages -> sendRetryReceipt). if (decryptFailed) {+ val encTypes = node.getChildren()+ .filter { it.tag == "enc" }+ .mapNotNull { it.attrs["type"] }+ WhatsAppDiag.log(TAG, "recv: DECRYPT FAILED id=${node.attrs["id"]} type=${node.attrs["type"]} from=${node.attrs["from"]} encs=$encTypes") sendRetryReceipt(node) return@launch } + if (node.attrs["type"] == "poll" || WhatsAppProtocol.pollCreation(message.e2eMessage) != null ||+ message.e2eMessage?.hasPollUpdateMessage() == true+ ) {+ WhatsAppDiag.log(+ TAG,+ "poll recv: id=${message.id} parsedType=${message.messageType} " ++ "create=${WhatsAppProtocol.pollCreation(message.e2eMessage) != null} " ++ "vote=${message.e2eMessage?.hasPollUpdateMessage()} " ++ "q=${message.pollData?.question} opts=${message.pollData?.options?.size} " ++ "fromMe=${message.isFromMe}",+ )+ }+ // History sync: the phone pushes message history as a protocolMessage notification // (inline for the initial bootstrap, or a downloadable encrypted blob otherwise). val histNotif = message.e2eMessage@@ -2686,9 +2703,10 @@ object WhatsAppClient { options: List<String>, selectableCount: Int = 0, ): String? {- if (_state.value !is State.Connected) return null- val ws = webSocket ?: return null- val to = extractJid(conversationId) ?: return null+ WhatsAppDiag.log(TAG, "poll: sendPollCreation entry conv=$conversationId opts=${options.size}")+ if (_state.value !is State.Connected) { WhatsAppDiag.log(TAG, "poll: not connected"); return null }+ val ws = webSocket ?: run { WhatsAppDiag.log(TAG, "poll: no websocket"); return null }+ val to = extractJid(conversationId) ?: run { WhatsAppDiag.log(TAG, "poll: bad convId"); return null } val id = WhatsAppProtocol.generateMessageId(authData?.wid) val messageSecret = ByteArray(32).also { random.nextBytes(it) }
messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.ktindex 3895ab7685..df64c9e1e3 100644--- a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt+++ b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt@@ -1613,7 +1613,7 @@ object WhatsAppProtocol { val ctx = com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.MessageContextInfo.newBuilder() .setMessageSecret(com.google.protobuf.ByteString.copyFrom(messageSecret)) return com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder()- .setPollCreationMessage(poll.build())+ .setPollCreationMessageV3(poll.build()) .setMessageContextInfo(ctx.build()) .build() }@@ -2062,6 +2062,21 @@ object WhatsAppProtocol { return phoneJid ?: senderJid } + /**+ * Return the effective PollCreationMessage from a message regardless of version โ modern+ * WhatsApp sends polls as pollCreationMessageV3 (field 64) or V2 (60), older ones as V1 (49).+ * Returns null if the message isn't a poll creation.+ */+ fun pollCreation(+ e2eMessage: com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.Message?,+ ): com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.PollCreationMessage? = when {+ e2eMessage == null -> null+ e2eMessage.hasPollCreationMessageV3() -> e2eMessage.pollCreationMessageV3+ e2eMessage.hasPollCreationMessageV2() -> e2eMessage.pollCreationMessageV2+ e2eMessage.hasPollCreationMessage() -> e2eMessage.pollCreationMessage+ else -> null+ }+ fun getMessageType(e2eMessage: com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.Message?): String { return when { e2eMessage == null -> "ignore"@@ -2073,7 +2088,7 @@ object WhatsAppProtocol { e2eMessage.hasDocumentMessage() -> "document ${e2eMessage.documentMessage.mimetype}" e2eMessage.hasContactMessage() -> "contact" e2eMessage.hasLocationMessage() -> "location"- e2eMessage.hasPollCreationMessage() -> "poll"+ pollCreation(e2eMessage) != null -> "poll" e2eMessage.hasReactionMessage() -> { if (e2eMessage.reactionMessage.text.isNullOrEmpty()) "reaction remove" else "reaction" }@@ -2235,8 +2250,8 @@ object WhatsAppProtocol { "Location: $name\n${loc.address}\n$mapsUrl" } e2eMessage.hasReactionMessage() -> e2eMessage.reactionMessage.text- e2eMessage.hasPollCreationMessage() -> {- val poll = e2eMessage.pollCreationMessage+ pollCreation(e2eMessage) != null -> {+ val poll = pollCreation(e2eMessage)!! buildString { append("๐ ") append(poll.name)@@ -2289,14 +2304,13 @@ object WhatsAppProtocol { else -> null } - val pollData: PollData? = if (e2eMessage.hasPollCreationMessage()) {- val poll = e2eMessage.pollCreationMessage+ val pollData: PollData? = pollCreation(e2eMessage)?.let { poll -> PollData( question = poll.name, options = poll.optionsList.map { it.optionName }, selectableOptionCount = poll.selectableOptionsCount, )- } else null+ } val groupInviteData: GroupInviteMeta? = null
messages/src/main/proto/whatsapp_e2e.proto
diff --git a/messages/src/main/proto/whatsapp_e2e.proto b/messages/src/main/proto/whatsapp_e2e.protoindex 5882be80c3..c676066988 100644--- a/messages/src/main/proto/whatsapp_e2e.proto+++ b/messages/src/main/proto/whatsapp_e2e.proto@@ -41,6 +41,8 @@ message Message { optional LocationMessage locationMessage = 16; optional ReactionMessage reactionMessage = 46; optional PollCreationMessage pollCreationMessage = 49;+ optional PollCreationMessage pollCreationMessageV2 = 60;+ optional PollCreationMessage pollCreationMessageV3 = 64; optional PollUpdateMessage pollUpdateMessage = 80; optional ProtocolMessage protocolMessage = 12; optional SenderKeyDistributionMessage senderKeyDistributionMessage = 2;