messages: whatsapp improvements
- Commit
87a0dbbf11bdc673958bfcc0683fee4a957e8bdc- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-10 16:19 UTC (4 months ago)
- Parents
a28b447
Diff
messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.ktindex 74d2c13e2e..26a8e0c191 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt@@ -85,6 +85,12 @@ sealed interface GMEvent { val senderId: String? = null, /** Inline media attachments to render (URL-based). Empty = none. */ val attachments: List<MessageAttachment> = emptyList(),+ /** Service-specific JSON metadata to persist on the message row. */+ val serviceData: String? = null,+ /** When this message is a poll, the poll question. Null for non-poll messages. */+ val pollQuestion: String? = null,+ /** Poll option names (when [pollQuestion] is set). */+ val pollOptions: List<String> = emptyList(), ) : GMEvent /** A message was deleted on the remote side (or by us). */@@ -146,6 +152,17 @@ sealed interface GMEvent { val senderId: String, ) : GMEvent + /** A poll vote was cast (or changed). [optionNames] is the voter's full current selection+ * (empty = they cleared their vote). [voterId] is a stable per-voter key ("self" for the+ * local user) so tallies replace rather than accumulate. */+ data class PollVote(+ override val source: MessageSource,+ val conversationId: String,+ val pollMessageId: String,+ val voterId: String,+ val optionNames: List<String>,+ ) : GMEvent+ /** A conversation was renamed. */ data class ConversationNameChanged( override val source: MessageSource,
messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.ktindex 28957dabb7..fd9c7d767d 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt@@ -18,6 +18,8 @@ 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.height+import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth@@ -84,6 +86,8 @@ import com.vayunmathur.messages.util.CameraCapture import com.vayunmathur.messages.util.FindFamilyLocation import com.vayunmathur.messages.util.MessagesViewModel import com.vayunmathur.messages.util.ReactionAction+import com.vayunmathur.messages.util.PollView+import com.vayunmathur.messages.util.pollFromServiceData import com.vayunmathur.messages.util.isMessageRequest import com.vayunmathur.messages.util.mediaCapabilities import com.vayunmathur.messages.util.participantNames@@ -403,6 +407,9 @@ fun ConversationScreen( onLongPress = if (canReact) { { reactingTo = item.message } } else null,+ onPollVote = { options ->+ vm.sendPollVote(item.message.id, options)+ }, ) } }@@ -699,6 +706,7 @@ private fun MessageBubble( isFirstInRun: Boolean, isLastInRun: Boolean, onLongPress: (() -> Unit)? = null,+ onPollVote: (List<String>) -> Unit = {}, ) { val isOutgoing = msg.direction == MessageDirection.OUTGOING val bubbleColor = if (isOutgoing) MaterialTheme.colorScheme.primary@@ -732,9 +740,11 @@ private fun MessageBubble( ) } val attachments = remember(msg.mediaJson) { parseAttachments(msg.mediaJson) }+ val poll = remember(msg.serviceData) { pollFromServiceData(msg.serviceData) } // Suppress a bare "[Image]"/"[Attachment]" placeholder body once the- // real media is available; keep genuine captions.- val showBody = msg.body.isNotBlank() &&+ // real media is available; keep genuine captions. Poll messages render+ // their own body, so suppress the text there too.+ val showBody = poll == null && msg.body.isNotBlank() && !(attachments.isNotEmpty() && isPlaceholderBody(msg.body)) Surface( color = bubbleColor,@@ -754,6 +764,9 @@ private fun MessageBubble( ) { Column { attachments.forEach { AttachmentView(it) }+ if (poll != null) {+ PollBody(poll, onVote = onPollVote)+ } if (showBody) { Text( msg.body,@@ -861,6 +874,50 @@ private fun ReactionPickerDialog( ) } +@Composable+private fun PollBody(poll: PollView, onVote: (List<String>) -> Unit) {+ Column(+ modifier = Modifier+ .padding(horizontal = 14.dp, vertical = 10.dp)+ .widthIn(min = 200.dp),+ ) {+ Text(poll.question, fontSize = 15.sp, fontWeight = FontWeight.SemiBold)+ Spacer(Modifier.height(6.dp))+ poll.options.forEach { opt ->+ val count = poll.counts[opt] ?: 0+ val selected = opt in poll.myVotes+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .fillMaxWidth()+ .padding(vertical = 3.dp)+ .clickable {+ val newVotes = when {+ // Single-choice polls: tap replaces (tap again to clear).+ poll.selectable <= 1 -> if (selected) emptyList() else listOf(opt)+ selected -> (poll.myVotes - opt).toList()+ else -> (poll.myVotes + opt).toList()+ }+ onVote(newVotes)+ },+ ) {+ Text(if (selected) "β" else "β", fontSize = 15.sp)+ Spacer(Modifier.width(8.dp))+ Text(opt, fontSize = 14.sp, modifier = Modifier.weight(1f))+ Text("$count", fontSize = 13.sp, fontWeight = FontWeight.Medium)+ }+ }+ if (poll.totalVoters > 0) {+ Spacer(Modifier.height(2.dp))+ Text(+ "${poll.totalVoters} vote${if (poll.totalVoters == 1) "" else "s"}",+ fontSize = 11.sp,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+}+ @Composable private fun ReactionsRow(json: String?, alignToEnd: Boolean) { if (json.isNullOrBlank()) return
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 37400ec0fb..4e9d1746be 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt@@ -290,15 +290,37 @@ object MessagesSessionManager { state = MessageState.PENDING, timestamp = System.currentTimeMillis(), senderName = null,+ serviceData = buildPollServiceData(+ null, question, options, if (allowMultiple) options.size else 1,+ ), ) ) touchConversationOutgoing(conversationId, "π $question")+ // WhatsApp returns the REAL poll message id so we can reconcile the optimistic pending+ // row onto it β votes (and the stored poll secret/options) are keyed by that id, so the+ // row the user taps must carry it. Also prevents a later echo from duplicating the poll.+ if (source == MessageSource.WHATSAPP) {+ val realId = WhatsAppClient.sendPoll(conversationId, question, options, allowMultiple)+ if (realId == null) {+ db.messageDao().updateState(pendingId, MessageState.FAILED)+ return false+ }+ val realDbId = "${source.idPrefix}:$realId"+ val pending = db.messageDao().get(pendingId)+ if (pending != null && db.messageDao().get(realDbId) == null) {+ db.messageDao().deleteById(pendingId)+ db.messageDao().upsert(pending.copy(id = realDbId, state = MessageState.SENT))+ } else {+ db.messageDao().updateState(pendingId, MessageState.SENT)+ }+ return true+ } val ok = when (source) { MessageSource.MESSAGES_WEB -> GMessagesClient.sendPoll(conversationId, question, options, allowMultiple) MessageSource.VOICE -> GVoiceClient.sendPoll(conversationId, question, options, allowMultiple) MessageSource.TELEGRAM -> TelegramClient.sendPoll(conversationId, question, options, allowMultiple) MessageSource.SIGNAL -> SignalClient.sendPoll(conversationId, question, options, allowMultiple)- MessageSource.WHATSAPP -> WhatsAppClient.sendPoll(conversationId, question, options, allowMultiple)+ MessageSource.WHATSAPP -> false // handled above MessageSource.MESSENGER -> MetaClient.sendPoll(conversationId, question, options, allowMultiple) MessageSource.INSTAGRAM -> InstagramClient.sendPoll(conversationId, question, options, allowMultiple) }@@ -507,6 +529,32 @@ object MessagesSessionManager { } } + /**+ * Cast/update the local user's vote on a poll. Only WhatsApp supports this today. Routes to+ * the platform client, then optimistically records the local user's selection ("self") on the+ * poll message so the tally updates immediately.+ */+ suspend fun sendPollVote(pollMessageId: String, optionNames: List<String>): Boolean {+ val msg = db.messageDao().get(pollMessageId) ?: return false+ val source = sourceFor(msg.conversationId) ?: return false+ val ok = when (source) {+ MessageSource.WHATSAPP -> WhatsAppClient.sendPollVote(+ conversationId = msg.conversationId,+ pollMessageId = pollMessageId,+ pollCreatorJid = msg.senderId ?: "",+ pollFromMe = msg.direction == MessageDirection.OUTGOING,+ selectedOptionNames = optionNames,+ )+ else -> false+ }+ if (ok) {+ db.messageDao().upsert(+ msg.copy(serviceData = applyPollVote(msg.serviceData, "self", optionNames))+ )+ }+ return ok+ }+ /** * Notify the peer that the local user is typing. * Only Google Messages exposes a typing endpoint; Voice has none.@@ -931,6 +979,20 @@ object MessagesSessionManager { senderName = event.senderName, senderId = event.senderId, mediaJson = attachmentsToJson(event.attachments),+ // Poll messages carry their structure so the UI renders interactive+ // options; votes get merged into this JSON as they arrive.+ serviceData = if (event.pollQuestion != null) {+ buildPollServiceData(+ db.messageDao().get(msgId)?.serviceData,+ event.pollQuestion,+ event.pollOptions,+ // selectable count isn't carried on the event; default to+ // single-choice unless the poll clearly allows more.+ 1,+ )+ } else {+ db.messageDao().get(msgId)?.serviceData+ }, ) ) if (backfillComplete[event.source] == true && !alreadySeen) {@@ -980,6 +1042,19 @@ object MessagesSessionManager { null, ) }+ is GMEvent.PollVote -> {+ val pollDbId = "${event.source.idPrefix}:${event.pollMessageId}"+ val msg = db.messageDao().get(pollDbId)+ if (msg != null) {+ db.messageDao().upsert(+ msg.copy(+ serviceData = applyPollVote(+ msg.serviceData, event.voterId, event.optionNames,+ )+ )+ )+ }+ } else -> Unit } }
messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt b/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.ktindex 2a17efdece..d0cdddda72 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt@@ -92,6 +92,16 @@ class MessagesViewModel(application: Application) : AndroidViewModel(application } } + fun sendPollVote(+ pollMessageId: String,+ optionNames: List<String>,+ onResult: (Boolean) -> Unit = {},+ ) {+ viewModelScope.launch {+ onResult(MessagesSessionManager.sendPollVote(pollMessageId, optionNames))+ }+ }+ /** * Share a location on [conversationId]. [text] is the FindFamily share * URL minted at send time; sent as a normal message on every platform.
messages/src/main/java/com/vayunmathur/messages/util/Polls.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/Polls.kt b/messages/src/main/java/com/vayunmathur/messages/util/Polls.ktnew file mode 100644index 0000000000..d5745fe998--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/util/Polls.kt@@ -0,0 +1,75 @@+package com.vayunmathur.messages.util++import org.json.JSONArray+import org.json.JSONObject++/**+ * Poll state stored inside a poll message's+ * [com.vayunmathur.messages.data.Message.serviceData] JSON (key "poll"), so no Room schema+ * migration is needed. Shape:+ * ```+ * { "poll": { "question": "...", "options": ["A","B"], "selectable": 1,+ * "votes": { "<voterId>": ["A"], ... } } }+ * ```+ * Counts for the UI are derived from the per-voter `votes` map so a voter changing their choice+ * replaces (not accumulates) their vote.+ */+private const val POLL_KEY = "poll"++/** A parsed poll for rendering: options with vote counts, plus the local user's current picks. */+data class PollView(+ val question: String,+ val options: List<String>,+ val selectable: Int,+ val counts: Map<String, Int>,+ val myVotes: Set<String>,+ val totalVoters: Int,+)++/** Build the initial poll serviceData JSON (no votes yet), preserving any unrelated keys. */+fun buildPollServiceData(serviceData: String?, question: String, options: List<String>, selectable: Int): String {+ val obj = runCatching {+ if (serviceData.isNullOrBlank()) JSONObject() else JSONObject(serviceData)+ }.getOrDefault(JSONObject())+ val poll = obj.optJSONObject(POLL_KEY) ?: JSONObject()+ poll.put("question", question)+ poll.put("options", JSONArray(options))+ poll.put("selectable", selectable)+ if (!poll.has("votes")) poll.put("votes", JSONObject())+ obj.put(POLL_KEY, poll)+ return obj.toString()+}++/** Record [voterId]'s current selection ([optionNames]; empty clears it). Returns updated JSON. */+fun applyPollVote(serviceData: String?, voterId: String, optionNames: List<String>): String {+ val obj = runCatching {+ if (serviceData.isNullOrBlank()) JSONObject() else JSONObject(serviceData)+ }.getOrDefault(JSONObject())+ val poll = obj.optJSONObject(POLL_KEY) ?: JSONObject().also { obj.put(POLL_KEY, it) }+ val votes = poll.optJSONObject("votes") ?: JSONObject().also { poll.put("votes", it) }+ if (optionNames.isEmpty()) votes.remove(voterId) else votes.put(voterId, JSONArray(optionNames))+ return obj.toString()+}++/** Parse poll state for rendering, or null if [serviceData] has no poll. */+fun pollFromServiceData(serviceData: String?): PollView? {+ if (serviceData.isNullOrBlank()) return null+ val poll = runCatching { JSONObject(serviceData).optJSONObject(POLL_KEY) }.getOrNull() ?: return null+ val question = poll.optString("question")+ val optionsArr = poll.optJSONArray("options") ?: return null+ val options = (0 until optionsArr.length()).map { optionsArr.optString(it) }+ val selectable = poll.optInt("selectable", 1)+ val votes = poll.optJSONObject("votes") ?: JSONObject()+ val counts = LinkedHashMap<String, Int>()+ options.forEach { counts[it] = 0 }+ val myVotes = mutableSetOf<String>()+ for (voter in votes.keys()) {+ val picks = votes.optJSONArray(voter) ?: continue+ for (i in 0 until picks.length()) {+ val opt = picks.optString(i)+ counts[opt] = (counts[opt] ?: 0) + 1+ if (voter == "self") myVotes.add(opt)+ }+ }+ return PollView(question, options, selectable, counts, myVotes, votes.length())+}
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 b3763a8d49..cb76fa136a 100644--- a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt@@ -90,6 +90,9 @@ object WhatsAppClient { private val undecryptableTracker = ConcurrentHashMap<String, Int>() private val pendingMessageIDs: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap()) private val processedEditIDs: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())+ // Groups we've already fetched metadata for this session, so we publish the group's+ // ConversationUpdate (name / isGroup / participants) at most once instead of on every event.+ private val knownGroups: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap()) private var reconnectJob: Job? = null private var reconnectAttempts = 0 private val pollSecrets = ConcurrentHashMap<String, ByteArray>()@@ -174,6 +177,7 @@ object WhatsAppClient { webSocket?.disconnect() webSocket = null nameCache.clear()+ knownGroups.clear() scope.launch { WhatsAppAuthData.clear(appContext) } _state.value = State.NeedsSetup }@@ -690,6 +694,45 @@ object WhatsAppClient { return group.getChildren().filter { it.tag == "participant" }.mapNotNull { it.attrs["jid"] } } + /**+ * Fetch a group's subject + participants (w:g2 interactive query) and publish a+ * [GMEvent.ConversationUpdate] so the thread shows up named + flagged as a group. Freshly+ * joined groups aren't in history sync, so without this the conversation never appears (and+ * group messages, which only upsert a bare row, look nameless / like a 1:1). Fetched at most+ * once per group per session ([knownGroups]); does NOT touch the unread badge on re-entry.+ * Ref whatsmeow group.go GetGroupInfo.+ */+ private suspend fun fetchAndEmitGroupInfo(groupJid: String) {+ if (!groupJid.contains("@g.us")) return+ if (!knownGroups.add(groupJid)) return+ val iq = WhatsAppProtocol.buildGroupParticipantsQuery(groupJid, generateMessageId())+ val resp = sendIqAndWait(iq) ?: run { knownGroups.remove(groupJid); return }+ val group = resp.getChildByTag("group") ?: run { knownGroups.remove(groupJid); return }+ val subject = group.attrs["subject"]?.ifEmpty { null }+ val participantJids = group.getChildren()+ .filter { it.tag == "participant" }+ .mapNotNull { it.attrs["jid"] }+ val participantNames = participantJids.map { resolveName(it) }+ val serviceData = if (participantNames.isNotEmpty()) {+ org.json.JSONObject()+ .put("participantNames", org.json.JSONArray(participantNames))+ .toString()+ } else null+ _events.emit(GMEvent.ConversationUpdate(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:$groupJid",+ peerName = subject,+ peerPhone = null,+ avatarUrl = null,+ lastPreview = null,+ lastTimestamp = 0L,+ unreadCount = 0,+ isGroup = true,+ participantCount = participantJids.size,+ serviceData = serviceData,+ ))+ }+ /** * Fetch (and cache) the media upload host + auth token via the w:m media_conn IQ. * Ref whatsmeow mediaconn.go queryMediaConn. Returns (host, auth) or null.@@ -991,6 +1034,10 @@ object WhatsAppClient { } catch (e: Exception) { Log.w(TAG, "Failed to process SKDM", e) }+ // A SKDM-only message carries no user-visible content (types as "ignore"); once+ // the key is stored there's nothing to display, so stop before emitting a blank+ // bubble. Messages that bundle the SKDM with real content fall through to render.+ if (message.messageType == "ignore") return@launch } // Skip status broadcasts (Go handleWAMessage status@broadcast check)@@ -1069,12 +1116,46 @@ object WhatsAppClient { append("β· Forwarded\n") } append(message.body)- }+ }.let { resolveMentionsInBody(it, message.mentionedJids) } - // Store poll secrets from incoming polls for vote encryption+ // Store poll secrets from incoming polls for vote encryption/decryption. if (message.pollData != null && !message.pollData.isPollVote && message.e2eMessage != null) { val secret = message.e2eMessage.messageContextInfo?.messageSecret?.toByteArray()- if (secret != null) pollSecrets[message.id] = secret+ if (secret != null) storePollSecret(message.id, secret)+ }++ // Handle incoming poll votes (PollUpdateMessage): decrypt the selected option+ // hashes, map them back to names, and emit a tally update. Ref whatsmeow+ // DecryptPollVote.+ if (message.e2eMessage?.hasPollUpdateMessage() == true) {+ val update = message.e2eMessage.pollUpdateMessage+ val key = update.pollCreationMessageKey+ val pollId = key.id+ val voter = if (message.isFromMe) (authData?.wid ?: "") else sender+ val creator = when {+ key.fromMe -> voter+ key.participant.isNotEmpty() -> key.participant+ else -> key.remoteJid+ }+ val secret = loadPollSecret(pollId)+ if (secret != null) {+ val hashes = WhatsAppProtocol.decryptPollVote(update, pollId, creator, voter, secret)+ if (hashes != null) {+ val dao = db?.pollOptionDao()+ val names = hashes.mapNotNull { h ->+ val hex = h.joinToString("") { "%02x".format(it) }+ dao?.getByHash(pollId, hex)?.optionName+ }+ _events.emit(GMEvent.PollVote(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:${message.from}",+ pollMessageId = pollId,+ voterId = if (message.isFromMe) "self" else sender,+ optionNames = names,+ ))+ }+ }+ return@launch } // Handle reactions separately (Go handleWAMessage reaction case)@@ -1104,6 +1185,21 @@ object WhatsAppClient { return@launch } + // For group chats, make sure the conversation exists (named + flagged as a+ // group) before we store the message β a freshly joined group isn't in history+ // sync, so otherwise it would only ever be a nameless bare row. Deduped ++ // awaited so the metadata lands before the message's unread bump.+ if (message.from.contains("@g.us")) {+ fetchAndEmitGroupInfo(message.from)+ }++ // Download + decrypt any inline media so it renders in-thread instead of as a+ // bare "[Image]"/"[Video]" placeholder. Null for non-media or on failure.+ val mediaAttachment = message.e2eMessage?.let {+ buildIncomingMediaAttachment(it, message.id)+ }+ val mediaAttachments = listOfNotNull(mediaAttachment)+ // Messages the user sent from another linked device (fromMe) are synced // to us as outgoing, not incoming β emit a MessageUpdate so they render on // the sent side instead of as an incoming (previously blank) bubble.@@ -1116,6 +1212,7 @@ object WhatsAppClient { outgoing = true, timestamp = message.timestamp * 1000, senderName = null,+ attachments = mediaAttachments, )) return@launch }@@ -1135,6 +1232,9 @@ object WhatsAppClient { timestamp = message.timestamp * 1000, senderName = if (isGroupChat) resolveName(sender) else null, senderId = if (isGroupChat) sender else null,+ attachments = mediaAttachments,+ pollQuestion = message.pollData?.takeIf { !it.isPollVote }?.question,+ pollOptions = message.pollData?.takeIf { !it.isPollVote }?.options ?: emptyList(), )) // Send delivery receipt@@ -1317,6 +1417,11 @@ object WhatsAppClient { val actor = resolveName(node.attrs["participant"] ?: groupJid) val msgId = node.attrs["id"] ?: "" + // Any group notification (being added, subject/participant changes, β¦) implies the+ // group should exist locally. Fetch + publish its metadata so the conversation appears+ // named and flagged as a group even when we were just added and have no history for it.+ fetchAndEmitGroupInfo(groupJid)+ node.content?.filterIsInstance<WhatsAppProtocol.Node>()?.forEach { child -> val body = when (child.tag) { "subject" -> {@@ -2065,6 +2170,7 @@ object WhatsAppClient { id: String, msg: WhatsAppE2EProto.Message, type: String,+ extraEncAttrs: Map<String, String> = emptyMap(), ): WhatsAppProtocol.Node? { val auth = authData ?: return null val crypto = ensureE2E(auth) ?: return null@@ -2098,6 +2204,7 @@ object WhatsAppClient { participantEncs = encs, includeDeviceIdentity = includeIdentity, deviceIdentity = deviceIdentity,+ extraEncAttrs = extraEncAttrs, ) } @@ -2120,6 +2227,7 @@ object WhatsAppClient { id: String, msg: WhatsAppE2EProto.Message, type: String = "text",+ extraEncAttrs: Map<String, String> = emptyMap(), ): WhatsAppProtocol.Node? { val auth = authData ?: return null val crypto = ensureE2E(auth) ?: return null@@ -2136,9 +2244,18 @@ object WhatsAppClient { WhatsAppProtocol.senderKeyDistributionPlaintext(groupJid, skdmBytes) ) - val participants = queryGroupParticipants(groupJid)+ // Meta AI / bots participate in a group via a special "hosted"/"bot" server and are NOT+ // part of the group's end-to-end sender-key encryption β you literally cannot send them+ // the group sender key, and including them aborts the whole send. The reference+ // (whatsmeow prepareMessageNode) deletes hosted/hosted.lid devices for group sends for+ // exactly this reason; the bot instead receives @mentions over its own message-secret+ // channel. Keep every real user (phone + LID); drop only bot/hosted servers.+ val participants = queryGroupParticipants(groupJid).filter { jid ->+ val server = jid.substringAfter("@", "")+ server != "bot" && server != "hosted" && server != "hosted.lid"+ } if (participants.isEmpty()) {- Log.w(TAG, "No participants resolved for group $groupJid; cannot fan out SKDM")+ Log.w(TAG, "No user participants resolved for group $groupJid; cannot fan out SKDM") return null } val devices = getUserDevices(participants).ifEmpty { participants }@@ -2164,6 +2281,7 @@ object WhatsAppClient { includeDeviceIdentity = includeIdentity, deviceIdentity = deviceIdentity, extraEnc = skMsg,+ extraEncAttrs = extraEncAttrs, ) } @@ -2189,11 +2307,14 @@ object WhatsAppClient { // whatsmeow upload.go: mmsType "image"/"video"/"audio"/"document"; stickers use the image bucket. val mmsType = if (mediaType == "sticker") "image" else mediaType val encAuth = java.net.URLEncoder.encode(auth, "UTF-8")- val uploadUrl = "https://$host/mms/$mmsType/$token?auth=$encAuth&token=$token"+ val encToken = java.net.URLEncoder.encode(token, "UTF-8")+ val uploadUrl = "https://$host/mms/$mmsType/$token?auth=$encAuth&token=$encToken" val requestBody = encryptedData.toRequestBody(null)+ // WhatsApp's rupload endpoint expects POST (whatsmeow upload.go rawUpload). A PUT here+ // returns 404, which is why media send was failing. val request = Request.Builder() .url(uploadUrl)- .put(requestBody)+ .post(requestBody) .header("Origin", "https://web.whatsapp.com") .header("Referer", "https://web.whatsapp.com/") .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36")@@ -2243,18 +2364,35 @@ object WhatsAppClient { return false } return try {+ WhatsAppDiag.log(TAG, "media: start type=$mediaType size=${bytes.size} to=$to") val enc = WhatsAppProtocol.encryptMedia(bytes, mediaKeyStr) val token = Base64.encodeToString(enc.fileEncSha256, Base64.URL_SAFE or Base64.NO_WRAP)+ WhatsAppDiag.log(TAG, "media: encrypted, uploadingβ¦") val upload = uploadMedia(enc.encryptedData, mediaType, token)- val node = WhatsAppProtocol.buildMediaMessage(- to, id, upload.url, upload.directPath,+ WhatsAppDiag.log(TAG, "media: uploaded url=${upload.url.take(40)}")+ val proto = WhatsAppProtocol.buildMediaProto(+ upload.url, upload.directPath, enc.mediaKey, enc.fileSha256, enc.fileEncSha256, enc.fileLength, mimeType, fileName, mediaType )+ // Media must be Signal-encrypted + fanned out like any other message (an+ // unencrypted node is dropped) and carry stanza type "media" + a "mediatype"+ // enc attr. Ref whatsmeow send.go getTypeFromMessage / prepareMessageNode.+ val encAttrs = mapOf("mediatype" to mediaType)+ val node = if (to.contains("@g.us")) {+ buildEncryptedGroupMessageNode(to, id, proto, type = "media", extraEncAttrs = encAttrs)+ } else {+ buildEncryptedMessageNode(to, id, proto, "media", extraEncAttrs = encAttrs)+ } ?: run {+ WhatsAppDiag.log(TAG, "media: build node FAILED (encryption produced no recipients)")+ pendingMessageIDs.remove(id); return false+ } val sent = ws.send(WhatsAppProtocol.encodeNode(node))+ WhatsAppDiag.log(TAG, "media: stanza sent=$sent id=$id") if (!sent) pendingMessageIDs.remove(id) sent } catch (e: Exception) {+ WhatsAppDiag.log(TAG, "media: FAILED ${e.message}") Log.e(TAG, "Failed to send media", e) pendingMessageIDs.remove(id) false@@ -2547,33 +2685,43 @@ object WhatsAppClient { question: String, options: List<String>, selectableCount: Int = 0,- ): Boolean {- if (_state.value !is State.Connected) return false- val ws = webSocket ?: return false- val to = extractJid(conversationId) ?: return false+ ): String? {+ if (_state.value !is State.Connected) return null+ val ws = webSocket ?: return null+ val to = extractJid(conversationId) ?: return null val id = WhatsAppProtocol.generateMessageId(authData?.wid) val messageSecret = ByteArray(32).also { random.nextBytes(it) } val msg = WhatsAppProtocol.buildPollCreationProto(question, options, selectableCount, messageSecret)+ // Polls use stanza type "poll" (not "text") β the server drops a poll sent as text.+ // Ref whatsmeow send.go getTypeFromMessage.+ WhatsAppDiag.log(TAG, "poll: start to=$to options=${options.size} group=${to.contains("@g.us")}") val node = if (to.contains("@g.us")) {- buildEncryptedGroupMessageNode(to, id, msg)+ buildEncryptedGroupMessageNode(to, id, msg, type = "poll") } else {- buildEncryptedMessageNode(to, id, msg, "text")- } ?: return false+ buildEncryptedMessageNode(to, id, msg, "poll")+ } ?: run {+ WhatsAppDiag.log(TAG, "poll: build node FAILED (encryption produced no recipients)")+ return null+ } pendingMessageIDs.add(id) val sent = ws.send(WhatsAppProtocol.encodeNode(node))+ WhatsAppDiag.log(TAG, "poll: stanza sent=$sent id=$id") if (sent) { storePollOptions(id, options)- pollSecrets[id] = messageSecret+ storePollSecret(id, messageSecret) } else { pendingMessageIDs.remove(id) }- return sent+ // Return the real message id so the caller can reconcile its optimistic pending row β+ // votes (and stored secret/options) are keyed by this id.+ return if (sent) id else null } /**- * Shared media-send contract poll entrypoint (called by MessagesSessionManager).+ * Shared media-send contract poll entrypoint (called by MessagesSessionManager). Returns the+ * real poll message id on success (null on failure) so the pending row can be reconciled. * Maps [allowMultiple] to selectableCount (whatsmeow PollCreationMessage semantics). */ suspend fun sendPoll(@@ -2581,7 +2729,7 @@ object WhatsAppClient { question: String, options: List<String>, allowMultiple: Boolean,- ): Boolean = sendPollCreation(+ ): String? = sendPollCreation( conversationId = conversationId, question = question, options = options,@@ -2592,38 +2740,69 @@ object WhatsAppClient { * Send a poll vote. * From Go HandleMatrixPollVote / PollVoteToWhatsApp. */+ /**+ * Cast (or change) a poll vote. Encrypts the selected option hashes with the poll's+ * messageSecret and sends a PollUpdateMessage via the normal fan-out (stanza type "poll").+ * [pollCreatorJid]/[pollFromMe] describe the ORIGINAL poll message (needed for key derivation+ * + the vote's pollCreationMessageKey). Ref whatsmeow BuildPollVote.+ */ suspend fun sendPollVote( conversationId: String, pollMessageId: String,- pollSenderJid: String,+ pollCreatorJid: String,+ pollFromMe: Boolean, selectedOptionNames: List<String>, ): Boolean { if (_state.value !is State.Connected) return false val ws = webSocket ?: return false val chatJid = extractJid(conversationId) ?: return false- val id = WhatsAppProtocol.generateMessageId(authData?.wid)+ val rawPollId = extractMessageId(pollMessageId)+ val secret = loadPollSecret(rawPollId)+ ?: run { WhatsAppDiag.log(TAG, "poll vote: no secret for $rawPollId"); return false } val ownJid = authData?.wid ?: ""+ val id = WhatsAppProtocol.generateMessageId(authData?.wid) val optionHashes = selectedOptionNames.map { option -> java.security.MessageDigest.getInstance("SHA-256") .digest(option.toByteArray(Charsets.UTF_8)) }-- val node = WhatsAppProtocol.buildPollVoteMessage(+ val creator = if (pollFromMe) ownJid else pollCreatorJid.ifEmpty { chatJid }+ val proto = WhatsAppProtocol.buildPollVoteMessage( chatJid = chatJid,- pollMessageId = pollMessageId,- pollSenderJid = pollSenderJid,+ pollMessageId = rawPollId,+ pollCreatorJid = creator,+ pollFromMe = pollFromMe,+ voterJid = ownJid, optionHashes = optionHashes,- ownJid = ownJid,- id = id,- pollSecret = pollSecrets[pollMessageId],+ pollSecret = secret, )+ val node = if (chatJid.contains("@g.us")) {+ buildEncryptedGroupMessageNode(chatJid, id, proto, type = "poll")+ } else {+ buildEncryptedMessageNode(chatJid, id, proto, "poll")+ } ?: return false pendingMessageIDs.add(id) val sent = ws.send(WhatsAppProtocol.encodeNode(node)) if (!sent) pendingMessageIDs.remove(id) return sent } + /** Persist a poll's shared secret (in-memory + DB) so votes can be encrypted/decrypted later. */+ private suspend fun storePollSecret(msgId: String, secret: ByteArray) {+ pollSecrets[msgId] = secret+ db?.pollSecretDao()?.upsert(+ WhatsAppPollSecret(msgId, secret.joinToString("") { "%02x".format(it) })+ )+ }++ private suspend fun loadPollSecret(msgId: String): ByteArray? {+ pollSecrets[msgId]?.let { return it }+ val hex = db?.pollSecretDao()?.get(msgId) ?: return null+ return runCatching {+ hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()+ }.getOrNull()?.also { pollSecrets[msgId] = it }+ }+ /** * Send a location message natively (LocationMessage proto), routed through the normal * multi-device Signal fan-out so it actually encrypts/delivers like a text message.@@ -3033,6 +3212,89 @@ object WhatsAppClient { return authData != null && _state.value is State.Connected } + /**+ * Download + decrypt an incoming media message and cache it locally, returning a+ * [com.vayunmathur.messages.data.MessageAttachment] pointing at the decrypted file (file://+ * URL) so the UI renders it inline. Returns null for non-media messages or on+ * download/decrypt failure (the "[Image]"/"[Video]" placeholder body then remains).+ * Ref whatsmeow Download.+ */+ private suspend fun buildIncomingMediaAttachment(+ e2e: WhatsAppE2EProto.Message,+ msgId: String,+ ): com.vayunmathur.messages.data.MessageAttachment? {+ val url: String; val directPath: String; val mediaKey: ByteArray; val encSha: ByteArray+ val mime: String?; val keyInfo: String; val type: String+ val width: Int; val height: Int; val fileName: String?; val ext: String+ when {+ e2e.hasImageMessage() -> e2e.imageMessage.let {+ url = it.url; directPath = it.directPath; mediaKey = it.mediaKey.toByteArray()+ encSha = it.fileEncSha256.toByteArray(); mime = it.mimetype.ifEmpty { "image/jpeg" }+ keyInfo = WhatsAppProtocol.MEDIA_KEY_IMAGE; type = "image"+ width = it.width; height = it.height; fileName = null; ext = "jpg"+ }+ e2e.hasStickerMessage() -> e2e.stickerMessage.let {+ url = it.url; directPath = it.directPath; mediaKey = it.mediaKey.toByteArray()+ encSha = it.fileEncSha256.toByteArray(); mime = it.mimetype.ifEmpty { "image/webp" }+ keyInfo = WhatsAppProtocol.MEDIA_KEY_STICKER; type = "sticker"+ width = it.width; height = it.height; fileName = null; ext = "webp"+ }+ e2e.hasVideoMessage() -> e2e.videoMessage.let {+ url = it.url; directPath = it.directPath; mediaKey = it.mediaKey.toByteArray()+ encSha = it.fileEncSha256.toByteArray(); mime = it.mimetype.ifEmpty { "video/mp4" }+ keyInfo = WhatsAppProtocol.MEDIA_KEY_VIDEO; type = "video"+ width = it.width; height = it.height; fileName = null; ext = "mp4"+ }+ e2e.hasAudioMessage() -> e2e.audioMessage.let {+ url = it.url; directPath = it.directPath; mediaKey = it.mediaKey.toByteArray()+ encSha = it.fileEncSha256.toByteArray(); mime = it.mimetype.ifEmpty { "audio/ogg" }+ keyInfo = WhatsAppProtocol.MEDIA_KEY_AUDIO; type = "audio"+ width = 0; height = 0; fileName = null; ext = "ogg"+ }+ e2e.hasDocumentMessage() -> e2e.documentMessage.let {+ url = it.url; directPath = it.directPath; mediaKey = it.mediaKey.toByteArray()+ encSha = it.fileEncSha256.toByteArray(); mime = it.mimetype.ifEmpty { null }+ keyInfo = WhatsAppProtocol.MEDIA_KEY_DOCUMENT; type = "file"+ width = 0; height = 0+ fileName = it.fileName.ifEmpty { it.title.ifEmpty { null } }+ ext = it.fileName.substringAfterLast('.', "").ifEmpty { "bin" }+ }+ else -> return null+ }+ if (mediaKey.isEmpty()) return null+ val downloadUrl = url.ifEmpty {+ if (directPath.isEmpty()) return null+ val host = mediaConn()?.first ?: return null+ val mmsType = when (type) {+ "sticker", "image" -> "image"+ "video" -> "video"+ "audio" -> "audio"+ else -> "document"+ }+ val hash = Base64.encodeToString(encSha, Base64.URL_SAFE or Base64.NO_WRAP)+ "https://$host$directPath&hash=$hash&mms-type=$mmsType&__wa-mms="+ }+ val bytes = downloadMedia(downloadUrl, mediaKey, keyInfo) ?: return null+ return try {+ val dir = java.io.File(appContext.cacheDir, "whatsapp_media")+ dir.mkdirs()+ val safeName = msgId.replace(Regex("[^A-Za-z0-9._-]"), "_")+ val file = java.io.File(dir, "$safeName.$ext")+ if (!(file.exists() && file.length() > 0)) file.writeBytes(bytes)+ com.vayunmathur.messages.data.MessageAttachment(+ url = "file://${file.absolutePath}",+ mimeType = mime,+ attachmentType = type,+ fileName = fileName,+ width = width,+ height = height,+ )+ } catch (e: Exception) {+ Log.w(TAG, "Failed to cache incoming media for $msgId", e)+ null+ }+ }+ /** * Logout from WhatsApp server and clear local data. * From whatsmeow LogoutRemote@@ -3106,14 +3368,40 @@ object WhatsAppClient { } private suspend fun resolveName(jid: String): String {+ // Bot accounts (Meta AI) have no phone number β give them a friendly name.+ if (jid.contains("@bot")) return "Meta AI" return nameCache.getOrPut(jid) {- // Extract phone number from JID for display- // Format: "[email protected]" or "[email protected]"- val phone = jid.substringBefore("@").substringBefore("-")+ // Display the phone number, stripping any device/agent/group suffixes+ // ("1234:1@β¦", "1234.5@β¦", "[email protected]").+ val phone = jid.substringBefore("@")+ .substringBefore(":")+ .substringBefore(".")+ .substringBefore("-") "+$phone" } } + /**+ * Replace the raw "@<number>" mention tokens WhatsApp embeds in message text with the+ * mentioned contact's display name (or "You" for the local user, "Meta AI" for the bot),+ * using [WhatsAppMessage.mentionedJids] to know who each token refers to.+ */+ private suspend fun resolveMentionsInBody(body: String, mentionedJids: List<String>): String {+ if (mentionedJids.isEmpty() || !body.contains("@")) return body+ var result = body+ for (jid in mentionedJids) {+ val userPart = jid.substringBefore("@").substringBefore(":").substringBefore(".")+ if (userPart.isEmpty()) continue+ val resolved = resolveJID(jid)+ val name = when {+ resolved == authData?.wid || resolved == authData?.lid -> "You"+ else -> resolveName(resolved)+ }+ result = result.replace("@$userPart", "@$name")+ }+ return result+ }+ fun getContactSuggestions(query: String): List<ContactSuggestion> { // Return cached contacts matching query return nameCache.entries
messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppDatabase.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppDatabase.kt b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppDatabase.ktindex 9aafd6a639..59cd439645 100644--- a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppDatabase.kt+++ b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppDatabase.kt@@ -27,6 +27,7 @@ import androidx.room.TypeConverters WhatsAppMediaRequest::class, WhatsAppAvatarCache::class, WhatsAppPollOption::class,+ WhatsAppPollSecret::class, // libsignal-backed E2E protocol stores WhatsAppE2ESession::class, WhatsAppE2EIdentity::class,@@ -34,7 +35,7 @@ import androidx.room.TypeConverters WhatsAppE2ESignedPreKey::class, WhatsAppE2ESenderKey::class, ],- version = 5,+ version = 6, exportSchema = false ) @TypeConverters(WhatsAppTypeConverters::class)@@ -45,6 +46,7 @@ abstract class WhatsAppDatabase : RoomDatabase() { abstract fun mediaRequestDao(): WhatsAppMediaRequestDao abstract fun avatarCacheDao(): WhatsAppAvatarCacheDao abstract fun pollOptionDao(): WhatsAppPollOptionDao+ abstract fun pollSecretDao(): WhatsAppPollSecretDao abstract fun e2eSessionDao(): WhatsAppE2ESessionDao abstract fun e2eIdentityDao(): WhatsAppE2EIdentityDao abstract fun e2ePreKeyDao(): WhatsAppE2EPreKeyDao@@ -217,6 +219,26 @@ interface WhatsAppPollOptionDao { suspend fun deleteByMessageId(msgId: String) } +/**+ * Per-poll shared secret (MessageContextInfo.messageSecret, hex-encoded), keyed by the poll+ * creation message id. Needed to encrypt our votes and decrypt incoming votes; persisted so+ * voting works after a restart, not just within the session.+ */+@Entity(tableName = "whatsapp_poll_secret")+data class WhatsAppPollSecret(+ @PrimaryKey val msgId: String,+ val secret: String,+)++@Dao+interface WhatsAppPollSecretDao {+ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(secret: WhatsAppPollSecret)++ @Query("SELECT secret FROM whatsapp_poll_secret WHERE msgId = :msgId")+ suspend fun get(msgId: String): String?+}+ // -- libsignal-backed E2E protocol stores (whatsmeow signal store equivalents) -- /** Signal session record keyed by (signalAddress, deviceId). */
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 d5c1838a96..3895ab7685 100644--- a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt+++ b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt@@ -1229,9 +1229,7 @@ object WhatsAppProtocol { * Build a media message node. * From whatsmeow/send.go + upload.go */- fun buildMediaMessage(- to: String,- id: String,+ fun buildMediaProto( url: String, directPath: String, mediaKey: ByteArray,@@ -1240,8 +1238,8 @@ object WhatsAppProtocol { fileLength: Long, mimeType: String, caption: String?,- mediaType: String, // "image", "video", "audio", "document"- ): Node {+ mediaType: String, // "image", "video", "audio", "document", "sticker"+ ): com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.Message { val e2eBuilder = com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder() when (mediaType) {@@ -1304,34 +1302,8 @@ object WhatsAppProtocol { } } - val plaintext = e2eBuilder.build().toByteArray()-- val encMediaType = when (mediaType) {- "image" -> "image"- "video" -> "video"- "audio" -> "audio"- "document" -> "document"- "sticker" -> "sticker"- else -> ""- }- val encAttrs = mutableMapOf("v" to "2", "type" to "msg")- if (encMediaType.isNotEmpty()) encAttrs["mediatype"] = encMediaType-- return Node(- tag = "message",- attrs = mapOf(- "to" to to,- "id" to id,- "type" to "media"- ),- content = listOf(- Node(- tag = "enc",- attrs = encAttrs,- data = padMessage(plaintext)- )- )- )+ val plaintext = e2eBuilder.build()+ return plaintext } /**@@ -1835,47 +1807,117 @@ object WhatsAppProtocol { } /**- * Reroute LID JIDs to phone number JIDs.- * From whatsmeow handlewhatsapp.go rerouteWAMessage()+ * Build an encrypted poll vote (PollUpdateMessage) as a Message proto, routed through the+ * normal send path. Selected options are SHA-256 hashes of the chosen option names; the vote+ * payload is AES-256-GCM encrypted with a key derived from the poll's messageSecret.+ * Ref whatsmeow msgsecret.go BuildPollVote / EncryptPollVote. */ fun buildPollVoteMessage( chatJid: String, pollMessageId: String,- pollSenderJid: String,+ pollCreatorJid: String,+ pollFromMe: Boolean,+ voterJid: String, optionHashes: List<ByteArray>,- ownJid: String,- id: String,- pollSecret: ByteArray? = null,- ): Node {- throw UnsupportedOperationException("PollVoteMessage/PollUpdateMessage is not available in the current protobuf schema")+ pollSecret: ByteArray,+ ): com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.Message {+ val vote = com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.PollVoteMessage.newBuilder()+ optionHashes.forEach { vote.addSelectedOptions(com.google.protobuf.ByteString.copyFrom(it)) }+ val plaintext = vote.build().toByteArray()++ val (key, aad) = pollVoteKeyAndAad(pollSecret, pollMessageId, pollCreatorJid, voterJid)+ val iv = ByteArray(12).also { java.security.SecureRandom().nextBytes(it) }+ val ciphertext = aesGcm(Cipher.ENCRYPT_MODE, key, iv, plaintext, aad)++ val msgKey = com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.MessageKey.newBuilder()+ .setFromMe(pollFromMe)+ .setId(pollMessageId)+ .setRemoteJid(chatJid)+ if (!pollFromMe && chatJid.contains("@g.us") && pollCreatorJid.isNotEmpty()) {+ msgKey.setParticipant(pollCreatorJid)+ }+ val update = com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.PollUpdateMessage.newBuilder()+ .setPollCreationMessageKey(msgKey.build())+ .setVote(+ com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.PollEncValue.newBuilder()+ .setEncPayload(com.google.protobuf.ByteString.copyFrom(ciphertext))+ .setEncIV(com.google.protobuf.ByteString.copyFrom(iv))+ )+ .setSenderTimestampMS(System.currentTimeMillis())+ return com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder()+ .setPollUpdateMessage(update.build())+ .build() } /**- * Encrypt poll vote using AES-256-GCM with HKDF-derived key.- * From Go whatsmeow/poll.go EncryptPollVote.- * Key material: HKDF(secret=messageSecret, info="Poll Vote" + pollMsgID + voterJID)+ * Decrypt an incoming poll vote, returning the SHA-256 option hashes the voter selected (or+ * null on failure). The caller maps hashes back to option names via the stored poll options. */- private fun encryptPollVote(- votePayload: ByteArray,- pollSecret: ByteArray,+ fun decryptPollVote(+ update: com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.PollUpdateMessage, pollMessageId: String,+ pollCreatorJid: String, voterJid: String,- iv: ByteArray,- ): ByteArray {- val info = "Poll Vote".toByteArray(Charsets.UTF_8) +- pollMessageId.toByteArray(Charsets.UTF_8) +- voterJid.toByteArray(Charsets.UTF_8)+ pollSecret: ByteArray,+ ): List<ByteArray>? {+ return try {+ val (key, aad) = pollVoteKeyAndAad(pollSecret, pollMessageId, pollCreatorJid, voterJid)+ val plaintext = aesGcm(+ Cipher.DECRYPT_MODE, key,+ update.vote.encIV.toByteArray(),+ update.vote.encPayload.toByteArray(),+ aad,+ )+ com.vayunmathur.messages.whatsapp.proto.WhatsAppE2EProto.PollVoteMessage+ .parseFrom(plaintext)+ .selectedOptionsList+ .map { it.toByteArray() }+ } catch (e: Exception) {+ Log.w(TAG, "Poll vote decrypt failed", e)+ null+ }+ } + /**+ * Derive the poll-vote key + GCM additional-data, matching whatsmeow generateMsgSecretKey for+ * the "Poll Vote" use case:+ * key = HKDF-SHA256(pollSecret, salt=nil, info = pollMsgId + creatorJid + voterJid + "Poll Vote")+ * aad = pollMsgId + 0x00 + voterJid+ * JIDs are normalized to bare user@server (no device/agent) to match the peer.+ */+ private fun pollVoteKeyAndAad(+ pollSecret: ByteArray,+ pollMessageId: String,+ pollCreatorJid: String,+ voterJid: String,+ ): Pair<ByteArray, ByteArray> {+ val creator = normalizeJidForSecret(pollCreatorJid)+ val voter = normalizeJidForSecret(voterJid)+ val info = pollMessageId.toByteArray(Charsets.UTF_8) ++ creator.toByteArray(Charsets.UTF_8) ++ voter.toByteArray(Charsets.UTF_8) ++ "Poll Vote".toByteArray(Charsets.UTF_8) val hkdf = HKDFBytesGenerator(SHA256Digest()) hkdf.init(HKDFParameters(pollSecret, null, info))- val encKey = ByteArray(32)- hkdf.generateBytes(encKey, 0, 32)+ val key = ByteArray(32)+ hkdf.generateBytes(key, 0, 32)+ val aad = pollMessageId.toByteArray(Charsets.UTF_8) ++ byteArrayOf(0) ++ voter.toByteArray(Charsets.UTF_8)+ return key to aad+ } + private fun normalizeJidForSecret(jid: String): String {+ val user = jid.substringBefore("@").substringBefore(":").substringBefore(".")+ val server = jid.substringAfter("@", "s.whatsapp.net")+ return "$user@$server"+ }++ private fun aesGcm(mode: Int, key: ByteArray, iv: ByteArray, data: ByteArray, aad: ByteArray): ByteArray { val cipher = Cipher.getInstance("AES/GCM/NoPadding")- val keySpec = SecretKeySpec(encKey, "AES")- val spec = GCMParameterSpec(128, iv)- cipher.init(Cipher.ENCRYPT_MODE, keySpec, spec)- return cipher.doFinal(votePayload)+ cipher.init(mode, SecretKeySpec(key, "AES"), GCMParameterSpec(128, iv))+ cipher.updateAAD(aad)+ return cipher.doFinal(data) } // WA text formatting regexes (from Go wa-text.go)@@ -2031,6 +2073,7 @@ object WhatsAppProtocol { e2eMessage.hasDocumentMessage() -> "document ${e2eMessage.documentMessage.mimetype}" e2eMessage.hasContactMessage() -> "contact" e2eMessage.hasLocationMessage() -> "location"+ e2eMessage.hasPollCreationMessage() -> "poll" e2eMessage.hasReactionMessage() -> { if (e2eMessage.reactionMessage.text.isNullOrEmpty()) "reaction remove" else "reaction" }@@ -2155,7 +2198,15 @@ object WhatsAppProtocol { val parsedType = getMessageType(e2eMessage)- if (parsedType == "ignore" || parsedType.startsWith("unknown_protocol_")) {+ // A message carrying only a SenderKeyDistributionMessage types as "ignore", but we+ // MUST still process it β it's what establishes the group sender key so subsequent+ // skmsg group messages can be decrypted. Let it through here; the caller processes+ // the key and then stops (see handleIncomingMessage). Other "ignore" / unknown+ // protocol messages are still dropped.+ val hasSenderKeyDistribution = e2eMessage.hasSenderKeyDistributionMessage()+ if ((parsedType == "ignore" && !hasSenderKeyDistribution) ||+ parsedType.startsWith("unknown_protocol_")+ ) { return null } @@ -2184,6 +2235,14 @@ object WhatsAppProtocol { "Location: $name\n${loc.address}\n$mapsUrl" } e2eMessage.hasReactionMessage() -> e2eMessage.reactionMessage.text+ e2eMessage.hasPollCreationMessage() -> {+ val poll = e2eMessage.pollCreationMessage+ buildString {+ append("π ")+ append(poll.name)+ poll.optionsList.forEach { append("\nβ’ "); append(it.optionName) }+ }+ } e2eMessage.hasProtocolMessage() -> { when (parsedType) { "revoke" -> "[Message Deleted]"@@ -2230,7 +2289,14 @@ object WhatsAppProtocol { else -> null } - val pollData: PollData? = null+ val pollData: PollData? = if (e2eMessage.hasPollCreationMessage()) {+ val poll = e2eMessage.pollCreationMessage+ 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 280eb696c5..5882be80c3 100644--- a/messages/src/main/proto/whatsapp_e2e.proto+++ b/messages/src/main/proto/whatsapp_e2e.proto@@ -41,6 +41,7 @@ message Message { optional LocationMessage locationMessage = 16; optional ReactionMessage reactionMessage = 46; optional PollCreationMessage pollCreationMessage = 49;+ optional PollUpdateMessage pollUpdateMessage = 80; optional ProtocolMessage protocolMessage = 12; optional SenderKeyDistributionMessage senderKeyDistributionMessage = 2; optional DeviceSentMessage deviceSentMessage = 31;@@ -314,3 +315,23 @@ message PollCreationMessage { optional uint32 selectableOptionsCount = 4; optional ContextInfo contextInfo = 5; }++// A cast poll vote. Mirrors whatsmeow waE2E.PollVoteMessage: the selected options are SHA-256+// hashes of the option names, encrypted (see PollUpdateMessage) so only poll participants see them.+message PollVoteMessage {+ repeated bytes selectedOptions = 1;+}++// Encrypted poll-vote payload (AES-256-GCM). Mirrors whatsmeow waE2E.PollEncValue.+message PollEncValue {+ optional bytes encPayload = 1;+ optional bytes encIV = 2;+}++// Wraps an encrypted poll vote, pointing back at the poll it belongs to. Mirrors whatsmeow+// waE2E.PollUpdateMessage.+message PollUpdateMessage {+ optional MessageKey pollCreationMessageKey = 1;+ optional PollEncValue vote = 2;+ optional int64 senderTimestampMS = 4;+}