Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / WhatsAppClientSendActions.kt
WhatsAppClientSendActions.kt505 lines · 20.9 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp |
| 2 | |
| 3 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient.State |
| 4 | import com.vayunmathur.communicate.data.whatsapp.buildChatPresence |
| 5 | import com.vayunmathur.communicate.data.whatsapp.buildContactProto |
| 6 | import com.vayunmathur.communicate.data.whatsapp.buildDisappearingTimerProto |
| 7 | import com.vayunmathur.communicate.data.whatsapp.buildEditProto |
| 8 | import com.vayunmathur.communicate.data.whatsapp.buildLocationProto |
| 9 | import com.vayunmathur.communicate.data.whatsapp.buildPollCreationProto |
| 10 | import com.vayunmathur.communicate.data.whatsapp.buildPollVoteMessage |
| 11 | import com.vayunmathur.communicate.data.whatsapp.buildReactionProto |
| 12 | import com.vayunmathur.communicate.data.whatsapp.buildReadReceipt |
| 13 | import com.vayunmathur.communicate.data.whatsapp.buildRevokeProto |
| 14 | import com.vayunmathur.communicate.data.whatsapp.encodeNode |
| 15 | import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket |
| 16 | import com.vayunmathur.communicate.data.whatsapp.generateMessageId |
| 17 | import com.vayunmathur.communicate.data.whatsapp.isRevokeFromMe |
| 18 | import com.vayunmathur.library.log.Log |
| 19 | |
| 20 | /** |
| 21 | * Mark messages as read with per-sender batching for group chats. |
| 22 | * From Go HandleMatrixReadReceipt — groups messages by sender. |
| 23 | */ |
| 24 | suspend fun WhatsAppClient.markRead( |
| 25 | conversationId: String, |
| 26 | messageIds: List<String> = emptyList(), |
| 27 | senderJids: Map<String, String> = emptyMap(), |
| 28 | ) { |
| 29 | val to = extractJid(conversationId) ?: return |
| 30 | val ws = webSocket ?: return |
| 31 | if (messageIds.isEmpty()) return |
| 32 | |
| 33 | // Filter out own messages by checking both JID and LID (Issue 4) |
| 34 | val ownJid = authData?.wid ?: "" |
| 35 | val ownLid = authData?.lid ?: "" |
| 36 | val filteredIds = messageIds.filter { msgId -> |
| 37 | val sender = senderJids[msgId] ?: "" |
| 38 | sender != ownJid && (ownLid.isEmpty() || sender != ownLid) |
| 39 | } |
| 40 | if (filteredIds.isEmpty()) return |
| 41 | |
| 42 | val isGroup = to.contains("@g.us") |
| 43 | if (isGroup && senderJids.isNotEmpty()) { |
| 44 | sendGroupReadReceipts(ws, to, filteredIds, senderJids) |
| 45 | } else { |
| 46 | val node = WhatsAppProtocol.buildReadReceipt(chatJid = to, messageIds = filteredIds) |
| 47 | ws.send(WhatsAppProtocol.encodeNode(node)) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | /** Batch group read receipts by sender (Go HandleMatrixReadReceipt). */ |
| 52 | private suspend fun WhatsAppClient.sendGroupReadReceipts( |
| 53 | ws: com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket, |
| 54 | to: String, |
| 55 | filteredIds: List<String>, |
| 56 | senderJids: Map<String, String>, |
| 57 | ) { |
| 58 | // Batch by sender for group chats (Go HandleMatrixReadReceipt) |
| 59 | val bySender = mutableMapOf<String, MutableList<String>>() |
| 60 | filteredIds.forEach { msgId -> |
| 61 | val sender = senderJids[msgId] ?: "" |
| 62 | bySender.getOrPut(sender) { mutableListOf() }.add(msgId) |
| 63 | } |
| 64 | bySender.forEach { (sender, ids) -> |
| 65 | val node = WhatsAppProtocol.buildReadReceipt( |
| 66 | chatJid = to, |
| 67 | messageIds = ids, |
| 68 | senderJid = sender.ifEmpty { null }, |
| 69 | ) |
| 70 | ws.send(WhatsAppProtocol.encodeNode(node)) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Send a WhatsApp read receipt (<receipt type="read">) up to [lastMessageId] when the user |
| 76 | * marks a thread read. No-op (returns true) when the account has read receipts disabled in |
| 77 | * privacy settings — so we honor the user's choice rather than leaking read state. Integrator |
| 78 | * broadcast contract. [lastTimestamp] is epoch ms (WhatsAppEvent convention) or s; both accepted. |
| 79 | */ |
| 80 | private const val MS_PER_SECOND = 1000L |
| 81 | private const val MS_THRESHOLD = 100_000_000_000L |
| 82 | |
| 83 | suspend fun WhatsAppClient.sendReadReceipt( |
| 84 | conversationId: String, |
| 85 | lastMessageId: String?, |
| 86 | lastTimestamp: Long, |
| 87 | senderJid: String? = null, |
| 88 | ): Boolean { |
| 89 | if (stateMutable.value !is State.Connected) return false |
| 90 | val ws = webSocket ?: return false |
| 91 | val to = extractJid(conversationId) ?: return false |
| 92 | if (lastMessageId.isNullOrEmpty()) return false |
| 93 | // Message ids arrive DB-prefixed ("wa:RAWID"); WhatsApp only matches the raw id. |
| 94 | val rawMessageId = extractMessageId(lastMessageId) |
| 95 | if (!readReceiptsEnabled) { |
| 96 | WhatsAppDiag.log(TAG, "read receipt suppressed (privacy off) for $to") |
| 97 | return true |
| 98 | } |
| 99 | val tSec = when { |
| 100 | lastTimestamp <= 0 -> System.currentTimeMillis() / MS_PER_SECOND |
| 101 | lastTimestamp > MS_THRESHOLD -> lastTimestamp / MS_PER_SECOND // ms → s |
| 102 | else -> lastTimestamp |
| 103 | } |
| 104 | val node = WhatsAppProtocol.buildReadReceipt( |
| 105 | chatJid = to, |
| 106 | messageIds = listOf(rawMessageId), |
| 107 | senderJid = senderJid?.ifEmpty { null }, |
| 108 | timestamp = tSec, |
| 109 | ) |
| 110 | val sent = ws.send(WhatsAppProtocol.encodeNode(node)) |
| 111 | WhatsAppDiag.log(TAG, "read receipt to=$to id=$rawMessageId sent=$sent") |
| 112 | return sent |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * Query the account privacy settings and cache whether read receipts are enabled. WhatsApp |
| 117 | * returns <privacy><category name="readreceipts" value="all|none"/>…</privacy>; "none" means |
| 118 | * the user turned read receipts off (and then cannot see others' either). Ref whatsmeow |
| 119 | * privacysettings.go GetPrivacySettings. Failures leave the default (enabled) in place. |
| 120 | */ |
| 121 | internal suspend fun WhatsAppClient.refreshPrivacySettings() { |
| 122 | val iq = WhatsAppProtocol.Node( |
| 123 | tag = "iq", |
| 124 | attrs = mapOf( |
| 125 | "id" to generateMessageId(), |
| 126 | "type" to "get", |
| 127 | "xmlns" to "privacy", |
| 128 | "to" to "s.whatsapp.net", |
| 129 | ), |
| 130 | content = listOf(WhatsAppProtocol.Node(tag = "privacy")), |
| 131 | ) |
| 132 | val resp = sendIqAndWait(iq, timeoutMs = 10_000) ?: return |
| 133 | val privacy = resp.getChildByTag("privacy") ?: return |
| 134 | privacy.getChildren() |
| 135 | .firstOrNull { it.tag == "category" && it.attrs["name"] == "readreceipts" } |
| 136 | ?.let { readReceiptsEnabled = it.attrs["value"] != "none" } |
| 137 | WhatsAppDiag.log(TAG, "privacy: readReceipts=${if (readReceiptsEnabled) "on" else "off"}") |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Send (or, with an empty [emoji], clear) a reaction on [messageId]. Routed through the same |
| 142 | * Signal encryption + multi-device fan-out as a normal message — an unencrypted reaction node |
| 143 | * is silently dropped by WhatsApp. The reaction key must point at the target message, so |
| 144 | * [targetFromMe] / [targetSenderJid] describe the ORIGINAL message being reacted to. |
| 145 | */ |
| 146 | suspend fun WhatsAppClient.sendReaction( |
| 147 | conversationId: String, |
| 148 | messageId: String, |
| 149 | emoji: String, |
| 150 | targetFromMe: Boolean, |
| 151 | targetSenderJid: String?, |
| 152 | ): Boolean { |
| 153 | if (stateMutable.value !is State.Connected) return false |
| 154 | val ws = webSocket ?: return false |
| 155 | val chatJid = extractJid(conversationId) ?: return false |
| 156 | val rawTargetId = extractMessageId(messageId) |
| 157 | val id = WhatsAppProtocol.generateMessageId(authData?.wid) |
| 158 | |
| 159 | val strippedEmoji = emoji.replace("\uFE0F", "") |
| 160 | val proto = WhatsAppProtocol.buildReactionProto( |
| 161 | chatJid = chatJid, |
| 162 | targetMessageId = rawTargetId, |
| 163 | emoji = strippedEmoji, |
| 164 | targetFromMe = targetFromMe, |
| 165 | targetSenderJid = targetSenderJid?.let { extractMessageId(it) }?.ifEmpty { null }, |
| 166 | ) |
| 167 | val node = if (chatJid.contains("@g.us")) { |
| 168 | buildEncryptedGroupMessageNode(chatJid, id, proto, type = "reaction") |
| 169 | } else { |
| 170 | buildEncryptedMessageNode(chatJid, id, proto, "reaction") |
| 171 | } ?: run { WhatsAppDiag.log(TAG, "reaction: build FAILED (no enc) for $chatJid"); return false } |
| 172 | |
| 173 | pendingMessageIDs.add(id) |
| 174 | val sent = ws.send(WhatsAppProtocol.encodeNode(node)) |
| 175 | if (!sent) pendingMessageIDs.remove(id) |
| 176 | WhatsAppDiag.log( |
| 177 | TAG, |
| 178 | "reaction to=$chatJid target=$rawTargetId emoji=${strippedEmoji.ifEmpty { "<remove>" }} sent=$sent") |
| 179 | return sent |
| 180 | } |
| 181 | |
| 182 | /** |
| 183 | * Remove a reaction from a message by sending an empty emoji. |
| 184 | * From Go HandleMatrixReactionRemove. |
| 185 | */ |
| 186 | suspend fun WhatsAppClient.removeReaction( |
| 187 | conversationId: String, |
| 188 | messageId: String, |
| 189 | targetFromMe: Boolean, |
| 190 | targetSenderJid: String?, |
| 191 | ): Boolean = sendReaction(conversationId, messageId, "", targetFromMe, targetSenderJid) |
| 192 | |
| 193 | /** |
| 194 | * Send a typing indicator (chat presence) with media type differentiation. |
| 195 | * From whatsmeow HandleMatrixTyping / SendChatPresence. |
| 196 | * Supports: text typing, audio recording, media uploading. |
| 197 | * (TypingType stays nested as WhatsAppClient.TypingType for API compatibility.) |
| 198 | */ |
| 199 | |
| 200 | suspend fun WhatsAppClient.sendTyping( |
| 201 | conversationId: String, |
| 202 | isTyping: Boolean, |
| 203 | typingType: WhatsAppClient.TypingType = WhatsAppClient.TypingType.TEXT, |
| 204 | ) { |
| 205 | if (stateMutable.value !is State.Connected) return |
| 206 | val ws = webSocket ?: return |
| 207 | val chatJid = extractJid(conversationId) ?: return |
| 208 | |
| 209 | // Go HandleMatrixTyping: UploadingMedia returns nil (not sent) |
| 210 | if (typingType == WhatsAppClient.TypingType.UPLOADING_MEDIA) return |
| 211 | |
| 212 | val isAudio = typingType == WhatsAppClient.TypingType.RECORDING_AUDIO |
| 213 | val node = WhatsAppProtocol.buildChatPresence(chatJid, isTyping, isAudio, authData?.wid ?: "") |
| 214 | ws.send(WhatsAppProtocol.encodeNode(node)) |
| 215 | } |
| 216 | |
| 217 | /** |
| 218 | * Edit a previously sent message. Builds a MESSAGE_EDIT ProtocolMessage proto and routes it |
| 219 | * through the normal Signal encryption + multi-device fan-out (1:1 or group sender-key) with a |
| 220 | * message-level `edit="1"` attribute. Previously this sent a plaintext `<enc>` that bypassed |
| 221 | * Signal fan-out and was undeliverable. |
| 222 | */ |
| 223 | suspend fun WhatsAppClient.sendEdit(conversationId: String, targetMessageId: String, newBody: String): Boolean { |
| 224 | if (stateMutable.value !is State.Connected) return false |
| 225 | val ws = webSocket ?: return false |
| 226 | val chatJid = extractJid(conversationId) ?: return false |
| 227 | val id = WhatsAppProtocol.generateMessageId(authData?.wid) |
| 228 | val rawTargetId = extractMessageId(targetMessageId) |
| 229 | |
| 230 | val proto = WhatsAppProtocol.buildEditProto(chatJid, rawTargetId, newBody) |
| 231 | val editAttrs = mapOf("edit" to "1") |
| 232 | val node = if (chatJid.contains("@g.us")) { |
| 233 | buildEncryptedGroupMessageNode(chatJid, id, proto, type = "text", messageAttrs = editAttrs) |
| 234 | } else { |
| 235 | buildEncryptedMessageNode(chatJid, id, proto, "text", messageAttrs = editAttrs) |
| 236 | } ?: run { WhatsAppDiag.log(TAG, "edit: build FAILED (no enc) for $chatJid"); return false } |
| 237 | |
| 238 | pendingMessageIDs.add(id) |
| 239 | val sent = ws.send(WhatsAppProtocol.encodeNode(node)) |
| 240 | if (!sent) pendingMessageIDs.remove(id) |
| 241 | WhatsAppDiag.log(TAG, "edit to=$chatJid target=$rawTargetId sent=$sent") |
| 242 | return sent |
| 243 | } |
| 244 | |
| 245 | /** |
| 246 | * Revoke (delete-for-everyone) a previously sent message. Builds a REVOKE ProtocolMessage |
| 247 | * proto and routes it through the normal Signal fan-out (1:1 or group sender-key) with the |
| 248 | * message-level `edit` attribute ("7" own / "8" other). Previously sent a plaintext `<enc>`. |
| 249 | */ |
| 250 | suspend fun WhatsAppClient.sendRevoke( |
| 251 | conversationId: String, |
| 252 | targetMessageId: String, |
| 253 | senderJid: String = ""): Boolean { |
| 254 | if (stateMutable.value !is State.Connected) return false |
| 255 | val ws = webSocket ?: return false |
| 256 | val chatJid = extractJid(conversationId) ?: return false |
| 257 | val id = WhatsAppProtocol.generateMessageId(authData?.wid) |
| 258 | val ownJid = authData?.wid ?: "" |
| 259 | val rawTargetId = extractMessageId(targetMessageId) |
| 260 | |
| 261 | val proto = WhatsAppProtocol.buildRevokeProto(chatJid, senderJid, rawTargetId, ownJid) |
| 262 | val isFromMe = WhatsAppProtocol.isRevokeFromMe(senderJid, ownJid) |
| 263 | val revokeAttrs = mapOf("edit" to if (isFromMe) "7" else "8") |
| 264 | val node = if (chatJid.contains("@g.us")) { |
| 265 | buildEncryptedGroupMessageNode(chatJid, id, proto, type = "text", messageAttrs = revokeAttrs) |
| 266 | } else { |
| 267 | buildEncryptedMessageNode(chatJid, id, proto, "text", messageAttrs = revokeAttrs) |
| 268 | } ?: run { WhatsAppDiag.log(TAG, "revoke: build FAILED (no enc) for $chatJid"); return false } |
| 269 | |
| 270 | pendingMessageIDs.add(id) |
| 271 | val sent = ws.send(WhatsAppProtocol.encodeNode(node)) |
| 272 | if (!sent) pendingMessageIDs.remove(id) |
| 273 | WhatsAppDiag.log(TAG, "revoke to=$chatJid target=$rawTargetId sent=$sent") |
| 274 | return sent |
| 275 | } |
| 276 | |
| 277 | /** |
| 278 | * Send a native WhatsApp poll (PollCreationMessage), routed through the normal multi-device |
| 279 | * fan-out (1:1) or sender-key path (groups). A fresh 32-byte messageSecret is generated and |
| 280 | * stored keyed by the message id so later votes can derive their encryption key. Mirrors |
| 281 | * whatsmeow BuildPollCreation. |
| 282 | */ |
| 283 | suspend fun WhatsAppClient.sendPollCreation( |
| 284 | conversationId: String, |
| 285 | question: String, |
| 286 | options: List<String>, |
| 287 | selectableCount: Int = 0, |
| 288 | ): String? { |
| 289 | WhatsAppDiag.log(TAG, "poll: sendPollCreation entry conv=$conversationId opts=${options.size}") |
| 290 | if (stateMutable.value !is State.Connected) { WhatsAppDiag.log(TAG, "poll: not connected"); return null } |
| 291 | val ws = webSocket ?: run { WhatsAppDiag.log(TAG, "poll: no websocket"); return null } |
| 292 | val to = extractJid(conversationId) ?: run { WhatsAppDiag.log(TAG, "poll: bad convId"); return null } |
| 293 | val id = WhatsAppProtocol.generateMessageId(authData?.wid) |
| 294 | |
| 295 | val messageSecret = ByteArray(32).also { random.nextBytes(it) } |
| 296 | val msg = WhatsAppProtocol.buildPollCreationProto(question, options, selectableCount, messageSecret) |
| 297 | // Polls use stanza type "poll" (not "text") — the server drops a poll sent as text. |
| 298 | // Ref whatsmeow send.go getTypeFromMessage. |
| 299 | WhatsAppDiag.log(TAG, "poll: start to=$to options=${options.size} group=${to.contains("@g.us")}") |
| 300 | val node = if (to.contains("@g.us")) { |
| 301 | buildEncryptedGroupMessageNode(to, id, msg, type = "poll") |
| 302 | } else { |
| 303 | buildEncryptedMessageNode(to, id, msg, "poll") |
| 304 | } ?: run { |
| 305 | WhatsAppDiag.log(TAG, "poll: build node FAILED (encryption produced no recipients)") |
| 306 | return null |
| 307 | } |
| 308 | |
| 309 | pendingMessageIDs.add(id) |
| 310 | val sent = ws.send(WhatsAppProtocol.encodeNode(node)) |
| 311 | WhatsAppDiag.log(TAG, "poll: stanza sent=$sent id=$id") |
| 312 | if (sent) { |
| 313 | storePollOptions(id, options) |
| 314 | storePollSecret(id, messageSecret) |
| 315 | } else { |
| 316 | pendingMessageIDs.remove(id) |
| 317 | } |
| 318 | // Return the real message id so the caller can reconcile its optimistic pending row — |
| 319 | // votes (and stored secret/options) are keyed by this id. |
| 320 | return if (sent) id else null |
| 321 | } |
| 322 | |
| 323 | /** |
| 324 | * Shared media-send contract poll entrypoint (called by MessagesSessionManager). Returns the |
| 325 | * real poll message id on success (null on failure) so the pending row can be reconciled. |
| 326 | * Maps [allowMultiple] to selectableCount (whatsmeow PollCreationMessage semantics). |
| 327 | */ |
| 328 | suspend fun WhatsAppClient.sendPoll( |
| 329 | conversationId: String, |
| 330 | question: String, |
| 331 | options: List<String>, |
| 332 | allowMultiple: Boolean, |
| 333 | ): String? = sendPollCreation( |
| 334 | conversationId = conversationId, |
| 335 | question = question, |
| 336 | options = options, |
| 337 | selectableCount = if (allowMultiple) options.size else 1, |
| 338 | ) |
| 339 | |
| 340 | /** |
| 341 | * Cast (or change) a poll vote. Encrypts the selected option hashes with the poll's |
| 342 | * messageSecret and sends a PollUpdateMessage via the normal fan-out (stanza type "poll"). |
| 343 | * [pollCreatorJid]/[pollFromMe] describe the ORIGINAL poll message (needed for key derivation |
| 344 | * + the vote's pollCreationMessageKey). Ref whatsmeow BuildPollVote. |
| 345 | */ |
| 346 | suspend fun WhatsAppClient.sendPollVote( |
| 347 | conversationId: String, |
| 348 | pollMessageId: String, |
| 349 | pollCreatorJid: String, |
| 350 | pollFromMe: Boolean, |
| 351 | selectedOptionNames: List<String>, |
| 352 | ): Boolean { |
| 353 | if (stateMutable.value !is State.Connected) return false |
| 354 | val ws = webSocket ?: return false |
| 355 | val chatJid = extractJid(conversationId) ?: return false |
| 356 | val rawPollId = extractMessageId(pollMessageId) |
| 357 | val secret = loadPollSecret(rawPollId) |
| 358 | ?: run { WhatsAppDiag.log(TAG, "poll vote: no secret for $rawPollId"); return false } |
| 359 | val ownJid = authData?.wid ?: "" |
| 360 | val id = WhatsAppProtocol.generateMessageId(authData?.wid) |
| 361 | |
| 362 | val optionHashes = selectedOptionNames.map { option -> |
| 363 | java.security.MessageDigest.getInstance("SHA-256") |
| 364 | .digest(option.toByteArray(Charsets.UTF_8)) |
| 365 | } |
| 366 | val creator = if (pollFromMe) ownJid else pollCreatorJid.ifEmpty { chatJid } |
| 367 | val proto = WhatsAppProtocol.buildPollVoteMessage( |
| 368 | chatJid = chatJid, |
| 369 | pollMessageId = rawPollId, |
| 370 | pollCreatorJid = creator, |
| 371 | pollFromMe = pollFromMe, |
| 372 | voterJid = ownJid, |
| 373 | optionHashes = optionHashes, |
| 374 | pollSecret = secret, |
| 375 | ) |
| 376 | val node = if (chatJid.contains("@g.us")) { |
| 377 | buildEncryptedGroupMessageNode(chatJid, id, proto, type = "poll") |
| 378 | } else { |
| 379 | buildEncryptedMessageNode(chatJid, id, proto, "poll") |
| 380 | } ?: return false |
| 381 | pendingMessageIDs.add(id) |
| 382 | val sent = ws.send(WhatsAppProtocol.encodeNode(node)) |
| 383 | if (!sent) pendingMessageIDs.remove(id) |
| 384 | return sent |
| 385 | } |
| 386 | |
| 387 | /** |
| 388 | * Send a location message natively (LocationMessage proto), routed through the normal |
| 389 | * multi-device Signal fan-out so it actually encrypts/delivers like a text message. |
| 390 | * From whatsmeow from-matrix.go location handling. |
| 391 | */ |
| 392 | suspend fun WhatsAppClient.sendLocation( |
| 393 | conversationId: String, |
| 394 | latitude: Double, |
| 395 | longitude: Double, |
| 396 | name: String? = null, |
| 397 | address: String? = null, |
| 398 | ): Boolean { |
| 399 | if (stateMutable.value !is State.Connected) return false |
| 400 | val ws = webSocket ?: return false |
| 401 | val to = extractJid(conversationId) ?: return false |
| 402 | val id = WhatsAppProtocol.generateMessageId(authData?.wid) |
| 403 | |
| 404 | val msg = WhatsAppProtocol.buildLocationProto(latitude, longitude, name, address) |
| 405 | val node = buildEncryptedMessageNode(to, id, msg, "text") ?: return false |
| 406 | pendingMessageIDs.add(id) |
| 407 | val sent = ws.send(WhatsAppProtocol.encodeNode(node)) |
| 408 | if (!sent) pendingMessageIDs.remove(id) |
| 409 | return sent |
| 410 | } |
| 411 | |
| 412 | /** |
| 413 | * Send a contact/vCard message. Routed through the normal Signal encryption + multi-device |
| 414 | * fan-out (1:1 or group sender-key) — previously emitted a plaintext `<enc>` that was dropped. |
| 415 | * From Go wa-contact.go convertContactMessage. |
| 416 | */ |
| 417 | suspend fun WhatsAppClient.sendContact( |
| 418 | conversationId: String, |
| 419 | displayName: String, |
| 420 | vcard: String, |
| 421 | ): Boolean { |
| 422 | if (stateMutable.value !is State.Connected) return false |
| 423 | val ws = webSocket ?: return false |
| 424 | val chatJid = extractJid(conversationId) ?: return false |
| 425 | val id = WhatsAppProtocol.generateMessageId(authData?.wid) |
| 426 | |
| 427 | val proto = WhatsAppProtocol.buildContactProto(displayName, vcard) |
| 428 | val node = if (chatJid.contains("@g.us")) { |
| 429 | buildEncryptedGroupMessageNode(chatJid, id, proto, type = "text") |
| 430 | } else { |
| 431 | buildEncryptedMessageNode(chatJid, id, proto, "text") |
| 432 | } ?: run { WhatsAppDiag.log(TAG, "contact: build FAILED (no enc) for $chatJid"); return false } |
| 433 | |
| 434 | pendingMessageIDs.add(id) |
| 435 | val sent = ws.send(WhatsAppProtocol.encodeNode(node)) |
| 436 | if (!sent) pendingMessageIDs.remove(id) |
| 437 | WhatsAppDiag.log(TAG, "contact to=$chatJid sent=$sent") |
| 438 | return sent |
| 439 | } |
| 440 | |
| 441 | /** |
| 442 | * Set disappearing messages timer. |
| 443 | * From Go HandleMatrixDisappearingTimer. |
| 444 | * Allowed values: 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d). |
| 445 | * |
| 446 | * 1:1 chats carry the setting as an EPHEMERAL_SETTING ProtocolMessage over the normal Signal |
| 447 | * fan-out. Groups instead use a `w:g2` IQ (`<ephemeral expiration=..>` / `<not_ephemeral/>`) |
| 448 | * so the whole group is updated server-side, matching whatsmeow SetDisappearingTimer. |
| 449 | */ |
| 450 | suspend fun WhatsAppClient.setDisappearingTimer(conversationId: String, timerSeconds: Long): Boolean { |
| 451 | if (stateMutable.value !is State.Connected) return false |
| 452 | val ws = webSocket ?: return false |
| 453 | val chatJid = extractJid(conversationId) ?: return false |
| 454 | |
| 455 | val allowedValues = setOf(0L, 86400L, 604800L, 7776000L) |
| 456 | if (timerSeconds !in allowedValues) { |
| 457 | Log.status(TAG, "Invalid disappearing timer value: $timerSeconds") |
| 458 | return false |
| 459 | } |
| 460 | |
| 461 | val id = WhatsAppProtocol.generateMessageId(authData?.wid) |
| 462 | if (chatJid.contains("@g.us")) { |
| 463 | return setGroupDisappearingTimer(chatJid, id, timerSeconds) |
| 464 | } |
| 465 | return sendDisappearingTimerMessage(ws, chatJid, id, timerSeconds) |
| 466 | } |
| 467 | |
| 468 | /** 1:1 disappearing timer via encrypted protocol message. */ |
| 469 | private suspend fun WhatsAppClient.sendDisappearingTimerMessage( |
| 470 | ws: WhatsAppSocket, |
| 471 | chatJid: String, |
| 472 | id: String, |
| 473 | timerSeconds: Long, |
| 474 | ): Boolean { |
| 475 | val proto = WhatsAppProtocol.buildDisappearingTimerProto(timerSeconds) |
| 476 | val node = buildEncryptedMessageNode(chatJid, id, proto, "text") |
| 477 | ?: run { WhatsAppDiag.log(TAG, "disappearing: build FAILED (no enc) for $chatJid"); return false } |
| 478 | pendingMessageIDs.add(id) |
| 479 | val sent = ws.send(WhatsAppProtocol.encodeNode(node)) |
| 480 | if (!sent) pendingMessageIDs.remove(id) |
| 481 | WhatsAppDiag.log(TAG, "disappearing to=$chatJid secs=$timerSeconds sent=$sent") |
| 482 | return sent |
| 483 | } |
| 484 | |
| 485 | /** Group disappearing timer via `w:g2` IQ. */ |
| 486 | private suspend fun WhatsAppClient.setGroupDisappearingTimer( |
| 487 | chatJid: String, |
| 488 | id: String, |
| 489 | timerSeconds: Long, |
| 490 | ): Boolean { |
| 491 | val child = if (timerSeconds == 0L) { |
| 492 | WhatsAppProtocol.Node(tag = "not_ephemeral") |
| 493 | } else { |
| 494 | WhatsAppProtocol.Node(tag = "ephemeral", attrs = mapOf("expiration" to timerSeconds.toString())) |
| 495 | } |
| 496 | val iq = WhatsAppProtocol.Node( |
| 497 | tag = "iq", |
| 498 | attrs = mapOf("id" to id, "type" to "set", "xmlns" to "w:g2", "to" to chatJid), |
| 499 | content = listOf(child), |
| 500 | ) |
| 501 | val resp = sendIqAndWait(iq, timeoutMs = 10_000) |
| 502 | val ok = resp != null && resp.attrs["type"] != "error" |
| 503 | WhatsAppDiag.log(TAG, "disappearing(group) to=$chatJid secs=$timerSeconds ok=$ok") |
| 504 | return ok |
| 505 | } |