Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / WhatsAppClientGroups.kt

WhatsAppClientGroups.kt256 lines · 10.9 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient.State
4import com.vayunmathur.communicate.data.whatsapp.buildCreateGroup
5import com.vayunmathur.communicate.data.whatsapp.buildGroupInfoChange
6import com.vayunmathur.communicate.data.whatsapp.buildGroupParticipantChange
7import com.vayunmathur.communicate.data.whatsapp.buildGroupParticipantsQuery
8import com.vayunmathur.communicate.data.whatsapp.buildSetGroupTopic
9import com.vayunmathur.communicate.data.whatsapp.encodeNode
10import com.vayunmathur.communicate.data.whatsapp.generateMessageId
11import android.graphics.Bitmap
12import android.graphics.BitmapFactory
13import androidx.core.graphics.scale
14import java.io.ByteArrayOutputStream
15import kotlinx.coroutines.Dispatchers
16import kotlinx.coroutines.withContext
17
18/**
19 * Query a group's participant JIDs via an interactive w:g2 query.
20 * Ref whatsmeow group.go getGroupInfo.
21 */
22internal suspend fun WhatsAppClient.queryGroupParticipants(groupJid: String): List<String> {
23 val iq = WhatsAppProtocol.buildGroupParticipantsQuery(groupJid, generateMessageId())
24 val resp = sendIqAndWait(iq) ?: return emptyList()
25 val group = resp.getChildByTag("group") ?: return emptyList()
26 return group.getChildren().filter { it.tag == "participant" }.mapNotNull { it.attrs["jid"] }
27}
28
29/**
30 * Fetch a group's subject + participants (w:g2 interactive query) and publish a
31 * [WhatsAppEvent.ConversationUpdate] so the thread shows up named + flagged as a group. Freshly
32 * joined groups aren't in history sync, so without this the conversation never appears (and
33 * group messages, which only upsert a bare row, look nameless / like a 1:1). Fetched at most
34 * once per group per session ([knownGroups]); does NOT touch the unread badge on re-entry.
35 * Ref whatsmeow group.go GetGroupInfo.
36 */
37suspend fun WhatsAppClient.fetchAndEmitGroupInfo(groupJid: String) {
38 if (!groupJid.contains("@g.us")) return
39 if (!knownGroups.add(groupJid)) return
40 val iq = WhatsAppProtocol.buildGroupParticipantsQuery(groupJid, generateMessageId())
41 val resp = sendIqAndWait(iq) ?: run { knownGroups.remove(groupJid); return }
42 val group = resp.getChildByTag("group") ?: run { knownGroups.remove(groupJid); return }
43 val subject = group.attrs["subject"]?.ifEmpty { null }
44 val participantJids = group.getChildren()
45 .filter { it.tag == "participant" }
46 .mapNotNull { it.attrs["jid"] }
47 val participantNames = participantJids.map { resolveName(it) }
48 val serviceData = if (participantNames.isNotEmpty()) {
49 org.json.JSONObject()
50 .put("participantNames", org.json.JSONArray(participantNames))
51 .toString()
52 } else null
53 eventsMutable.emit(WhatsAppEvent.ConversationUpdate(
54 source = MessageSource.WHATSAPP,
55 conversationId = "wa:$groupJid",
56 peerName = subject,
57 peerPhone = null,
58 avatarUrl = null,
59 lastPreview = null,
60 lastTimestamp = 0L,
61 unreadCount = 0,
62 isGroup = true,
63 participantCount = participantJids.size,
64 serviceData = serviceData,
65 ))
66 // Phase F 1e: best-effort MEX enrichment beyond the classic w:g2 path (subject/description).
67 // Dev-gated; no-ops when the op's doc_id isn't in the bundled persist map.
68 if (WhatsAppFeature.enabled && subject == null) {
69 runCatching { enrichGroupFromMex(groupJid, participantJids.size) }
70 }
71}
72
73/**
74 * Enrich a group thread via `xwa2_group_query_by_id` (Phase F 1e). Emits a follow-up
75 * [WhatsAppEvent.ConversationUpdate] with the MEX-reported subject when available. Best-effort:
76 * silently returns on transport error / missing doc_id.
77 */
78suspend fun WhatsAppClient.enrichGroupFromMex(groupJid: String, participantCount: Int) {
79 val res = com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.groupQueryById(appContext, groupJid)
80 if (!res.isSuccess) return
81 val data = res.data ?: return
82 val group = data.optJSONObject("xwa2_group_query_by_id") ?: return
83 val subject = group.optJSONObject("subject")?.optString("subject")?.ifEmpty { null }
84 ?: group.optString("subject").ifEmpty { null } ?: return
85 eventsMutable.emit(WhatsAppEvent.ConversationUpdate(
86 source = MessageSource.WHATSAPP,
87 conversationId = "wa:$groupJid",
88 peerName = subject,
89 peerPhone = null,
90 avatarUrl = null,
91 lastPreview = null,
92 lastTimestamp = 0L,
93 unreadCount = 0,
94 isGroup = true,
95 participantCount = participantCount,
96 ))
97}
98
99/**
100 * Set group name.
101 * From Go HandleMatrixRoomName / SetGroupName.
102 */
103suspend fun WhatsAppClient.setGroupName(conversationId: String, name: String): Boolean {
104 if (stateMutable.value !is State.Connected) return false
105 val ws = webSocket ?: return false
106 val groupJid = extractJid(conversationId) ?: return false
107 if (!groupJid.contains("@g.us")) return false
108
109 val id = WhatsAppProtocol.generateMessageId(authData?.wid)
110 val node = WhatsAppProtocol.buildGroupInfoChange(groupJid, "subject", name, id)
111 return ws.send(WhatsAppProtocol.encodeNode(node))
112}
113
114/**
115 * Set group topic/description with old/new ID tracking.
116 * From Go HandleMatrixRoomTopic / SetGroupTopic.
117 */
118suspend fun WhatsAppClient.setGroupTopic(
119 conversationId: String,
120 topic: String,
121 previousTopicId: String? = null,
122): Boolean {
123 if (stateMutable.value !is State.Connected) return false
124 val ws = webSocket ?: return false
125 val groupJid = extractJid(conversationId) ?: return false
126 if (!groupJid.contains("@g.us")) return false
127
128 val id = WhatsAppProtocol.generateMessageId(authData?.wid)
129 val node = WhatsAppProtocol.buildSetGroupTopic(groupJid, topic, id, previousTopicId)
130 return ws.send(WhatsAppProtocol.encodeNode(node))
131}
132
133/**
134 * Set group avatar with crop/resize/JPEG conversion.
135 * Crops to square, scales between 190-720px, encodes as JPEG quality 75.
136 * From Go HandleMatrixRoomAvatar / convertRoomAvatar.
137 */
138suspend fun WhatsAppClient.setGroupAvatar(conversationId: String, imageBytes: ByteArray): Boolean {
139 if (stateMutable.value !is State.Connected) return false
140 val ws = webSocket ?: return false
141 val groupJid = extractJid(conversationId) ?: return false
142 if (!groupJid.contains("@g.us")) return false
143
144 val processed = withContext(Dispatchers.Default) {
145 cropResizeAvatar(imageBytes)
146 } ?: return false
147
148 val id = WhatsAppProtocol.generateMessageId(authData?.wid)
149 val node = WhatsAppProtocol.Node(
150 tag = "iq",
151 attrs = mapOf(
152 "id" to id,
153 "type" to "set",
154 "xmlns" to "w:profile:picture",
155 "to" to groupJid,
156 ),
157 content = listOf(
158 WhatsAppProtocol.Node(
159 tag = "picture",
160 attrs = mapOf("type" to "image"),
161 data = processed,
162 )
163 ),
164 )
165 return ws.send(WhatsAppProtocol.encodeNode(node))
166}
167
168private const val GROUP_ICON_MIN_DIM = 190
169private const val GROUP_ICON_MAX_DIM = 720
170private const val GROUP_ICON_JPEG_QUALITY = 75
171
172internal fun WhatsAppClient.cropResizeAvatar(imageBytes: ByteArray): ByteArray? {
173 val original = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) ?: return null
174 val size = minOf(original.width, original.height)
175 val x = (original.width - size) / 2
176 val y = (original.height - size) / 2
177 val cropped = Bitmap.createBitmap(original, x, y, size, size)
178 // Go: min=190, max=720, BiLinear scaling
179 val targetDim = size.coerceIn(GROUP_ICON_MIN_DIM, GROUP_ICON_MAX_DIM)
180 val scaled = if (size != targetDim) {
181 cropped.scale(targetDim, targetDim).also {
182 if (it !== cropped) cropped.recycle()
183 }
184 } else cropped
185 val out = ByteArrayOutputStream()
186 scaled.compress(Bitmap.CompressFormat.JPEG, GROUP_ICON_JPEG_QUALITY, out)
187 if (scaled !== original) scaled.recycle()
188 if (original !== cropped && original !== scaled) original.recycle()
189 return out.toByteArray()
190}
191
192/**
193 * Add or remove group members.
194 * From Go HandleMatrixMembership / UpdateGroupParticipants.
195 */
196suspend fun WhatsAppClient.updateGroupParticipants(
197 conversationId: String,
198 participantJids: List<String>,
199 action: String,
200): Boolean {
201 if (stateMutable.value !is State.Connected) return false
202 val ws = webSocket ?: return false
203 val groupJid = extractJid(conversationId) ?: return false
204 if (!groupJid.contains("@g.us")) return false
205
206 val validActions = setOf("add", "remove", "promote", "demote")
207 if (action !in validActions) return false
208
209 val id = WhatsAppProtocol.generateMessageId(authData?.wid)
210 val node = WhatsAppProtocol.buildGroupParticipantChange(groupJid, participantJids, action, id)
211 return ws.send(WhatsAppProtocol.encodeNode(node))
212}
213
214/**
215 * Create a new group with [subject] and [participantJids] (full user JIDs, e.g.
216 * `[email protected]`). Sends the `w:g2` create IQ, awaits the `<group>` result, and
217 * returns the new group's `@g.us` JID (or null on failure). On success it also fetches + emits
218 * the group info so the thread appears named + flagged with its participants persisted.
219 * Ref whatsmeow group.go CreateGroup.
220 */
221suspend fun WhatsAppClient.createGroup(subject: String, participantJids: List<String>): String? {
222 if (stateMutable.value !is State.Connected) { WhatsAppDiag.log(TAG, "createGroup: not connected"); return null }
223 if (participantJids.isEmpty()) { WhatsAppDiag.log(TAG, "createGroup: no participants"); return null }
224
225 val id = generateMessageId()
226 // whatsmeow uses a client-chosen unique key (unix seconds) echoed back in the response.
227 val key = (System.currentTimeMillis() / 1000).toString()
228 val iq = WhatsAppProtocol.buildCreateGroup(subject, participantJids, id, key)
229 val resp = sendIqAndWait(iq) ?: run { WhatsAppDiag.log(TAG, "createGroup: no response"); return null }
230 if (resp.attrs["type"] == "error") {
231 logGroupError(resp)
232 return null
233 }
234 return extractGroupJid(resp)
235}
236
237/** Log a group-management server error. */
238private fun WhatsAppClient.logGroupError(resp: WhatsAppProtocol.Node) {
239 val err = resp.getChildByTag("error")
240 WhatsAppDiag.log(
241 TAG,
242 "createGroup: server error code=${err?.attrs?.get("code")} text=${err?.attrs?.get("text")}",
243 )
244}
245
246/** New group JID from a create response, or null (logged) when absent. */
247private suspend fun WhatsAppClient.extractGroupJid(resp: WhatsAppProtocol.Node): String? {
248 val group = resp.getChildByTag("group") ?: run { WhatsAppDiag.log(TAG, "createGroup: no <group>"); return null }
249 // Response group node carries the new JID either as `jid` or as a bare `id` local-part.
250 val groupJid = group.attrs["jid"]
251 ?: group.attrs["id"]?.let { if (it.contains("@")) it else "[email protected]" }
252 ?: run { WhatsAppDiag.log(TAG, "createGroup: no group jid in resp"); return null }
253 WhatsAppDiag.log(TAG, "createGroup: created $groupJid")
254 runCatching { fetchAndEmitGroupInfo(groupJid) }
255 return groupJid
256}