whatsapp-rust 0.6.0

Rust client for WhatsApp Web
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Community feature.
//!
//! Communities are parent groups that contain linked subgroups.
//! Uses the `w:g2` IQ namespace for mutations and MEX (GraphQL) for metadata queries.

use crate::client::Client;
use crate::features::groups::GroupMetadata;
use crate::features::groups::GroupParticipant;
use crate::features::mex::{MexError, MexRequest};
use log::warn;
use serde_json::json;
use wacore::iq::groups::{
    DeleteCommunityIq, GetLinkedGroupsParticipantsIq, GroupCreateIq, GroupCreateOptions,
    JoinLinkedGroupIq, LinkSubgroupsIq, QueryLinkedGroupIq, UnlinkSubgroupsIq,
};
use wacore::iq::mex_ids::community as community_docs;
use wacore_binary::Jid;

// Types

/// Classification of a group within the community hierarchy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum GroupType {
    /// Regular standalone group (not part of a community).
    Default,
    /// Community parent group.
    Community,
    /// A subgroup linked to a community.
    LinkedSubgroup,
    /// The default announcement subgroup of a community.
    LinkedAnnouncementGroup,
    /// The general chat subgroup of a community.
    LinkedGeneralGroup,
}

/// Options for creating a new community.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateCommunityOptions {
    pub name: String,
    pub description: Option<String>,
    /// Whether the community is closed (requires approval to join).
    pub closed: bool,
    /// Allow non-admin members to create subgroups.
    pub allow_non_admin_sub_group_creation: bool,
    /// Create a general chat subgroup alongside the community.
    pub create_general_chat: bool,
}

impl CreateCommunityOptions {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: None,
            closed: false,
            allow_non_admin_sub_group_creation: false,
            create_general_chat: true,
        }
    }
}

/// Result of creating a community.
#[derive(Debug, Clone)]
pub struct CreateCommunityResult {
    pub metadata: GroupMetadata,
}

/// A subgroup within a community.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommunitySubgroup {
    pub id: Jid,
    pub subject: String,
    pub participant_count: Option<u32>,
    pub is_default_sub_group: bool,
    pub is_general_chat: bool,
}

/// Result of linking subgroups to a community.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkSubgroupsResult {
    pub linked_jids: Vec<Jid>,
    pub failed_groups: Vec<(Jid, u32)>,
}

/// Result of unlinking subgroups from a community.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnlinkSubgroupsResult {
    pub unlinked_jids: Vec<Jid>,
    pub failed_groups: Vec<(Jid, u32)>,
}

/// Determine the group type from metadata fields.
pub fn group_type(metadata: &GroupMetadata) -> GroupType {
    if metadata.is_default_sub_group {
        GroupType::LinkedAnnouncementGroup
    } else if metadata.is_general_chat {
        GroupType::LinkedGeneralGroup
    } else if metadata.parent_group_jid.is_some() {
        GroupType::LinkedSubgroup
    } else if metadata.is_parent_group {
        GroupType::Community
    } else {
        GroupType::Default
    }
}

// Feature handle

pub struct Community<'a> {
    client: &'a Client,
}

impl<'a> Community<'a> {
    pub(crate) fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// Create a new community.
    ///
    /// If a description is provided, it is set via a follow-up IQ after creation
    /// (the group create stanza does not support inline descriptions for communities).
    pub async fn create(
        &self,
        options: CreateCommunityOptions,
    ) -> Result<CreateCommunityResult, anyhow::Error> {
        let description = options.description.clone();

        let create_options = GroupCreateOptions {
            subject: options.name,
            is_parent: true,
            closed: options.closed,
            allow_non_admin_sub_group_creation: options.allow_non_admin_sub_group_creation,
            create_general_chat: options.create_general_chat,
            ..Default::default()
        };

        let group = self
            .client
            .execute(GroupCreateIq::new(create_options))
            .await?;
        let mut metadata = GroupMetadata::from(group);

        if let Some(desc_text) = description
            && let Ok(desc) = wacore::iq::groups::GroupDescription::new(&desc_text)
        {
            self.client
                .groups()
                .set_description(&metadata.id, Some(desc), None)
                .await?;
            metadata.description = Some(desc_text);
        }

        Ok(CreateCommunityResult { metadata })
    }

    /// Deactivate (delete) a community. Subgroups are unlinked but not deleted.
    pub async fn deactivate(&self, community_jid: &Jid) -> Result<(), anyhow::Error> {
        self.client
            .execute(DeleteCommunityIq::new(community_jid))
            .await?;
        Ok(())
    }

    /// Link existing groups as subgroups of a community.
    pub async fn link_subgroups(
        &self,
        community_jid: &Jid,
        subgroup_jids: &[Jid],
    ) -> Result<LinkSubgroupsResult, anyhow::Error> {
        let response = self
            .client
            .execute(LinkSubgroupsIq::new(community_jid, subgroup_jids))
            .await?;

        let mut linked_jids = Vec::with_capacity(response.groups.len());
        let mut failed_groups = Vec::with_capacity(response.groups.len());

        for group in response.groups {
            if let Some(error) = group.error {
                failed_groups.push((group.jid, error));
            } else {
                linked_jids.push(group.jid);
            }
        }

        Ok(LinkSubgroupsResult {
            linked_jids,
            failed_groups,
        })
    }

    /// Unlink subgroups from a community.
    pub async fn unlink_subgroups(
        &self,
        community_jid: &Jid,
        subgroup_jids: &[Jid],
        remove_orphan_members: bool,
    ) -> Result<UnlinkSubgroupsResult, anyhow::Error> {
        let response = self
            .client
            .execute(UnlinkSubgroupsIq::new(
                community_jid,
                subgroup_jids,
                remove_orphan_members,
            ))
            .await?;

        let mut unlinked_jids = Vec::with_capacity(response.groups.len());
        let mut failed_groups = Vec::with_capacity(response.groups.len());

        for group in response.groups {
            if let Some(error) = group.error {
                failed_groups.push((group.jid, error));
            } else {
                unlinked_jids.push(group.jid);
            }
        }

        Ok(UnlinkSubgroupsResult {
            unlinked_jids,
            failed_groups,
        })
    }

    /// Fetch all subgroups of a community via MEX (GraphQL).
    pub async fn get_subgroups(
        &self,
        community_jid: &Jid,
    ) -> Result<Vec<CommunitySubgroup>, MexError> {
        let response = self
            .client
            .mex()
            .query(MexRequest {
                doc: community_docs::FETCH_ALL_SUBGROUPS,
                variables: json!({
                    "group_id": community_jid.to_string()
                }),
            })
            .await?;

        let data = response
            .data
            .ok_or_else(|| MexError::PayloadParsing("missing data field".into()))?;

        let group_query = &data["xwa2_group_query_by_id"];
        let mut subgroups = Vec::new();

        // Parse default subgroup
        if let Some(default_sub) = group_query.get("default_sub_group")
            && !default_sub.is_null()
            && let Some(sg) = parse_subgroup_node(default_sub, true)
        {
            subgroups.push(sg);
        }

        // Parse regular subgroups
        if let Some(sub_groups) = group_query.get("sub_groups")
            && let Some(edges) = sub_groups.get("edges").and_then(|e| e.as_array())
        {
            for edge in edges {
                if let Some(node) = edge.get("node")
                    && let Some(sg) = parse_subgroup_node(node, false)
                {
                    subgroups.push(sg);
                }
            }
        }

        Ok(subgroups)
    }

    /// Fetch participant counts per subgroup via MEX (GraphQL).
    pub async fn get_subgroup_participant_counts(
        &self,
        community_jid: &Jid,
    ) -> Result<Vec<(Jid, u32)>, MexError> {
        let response = self
            .client
            .mex()
            .query(MexRequest {
                doc: community_docs::FETCH_SUBGROUP_PARTICIPANT_COUNT,
                variables: json!({
                    "input": {
                        "group_jid": community_jid.to_string()
                    }
                }),
            })
            .await?;

        let data = response
            .data
            .ok_or_else(|| MexError::PayloadParsing("missing data field".into()))?;

        let group_query = &data["xwa2_group_query_by_id"];
        let edges_ref = group_query
            .get("sub_groups")
            .and_then(|s| s.get("edges"))
            .and_then(|e| e.as_array());
        let mut counts = Vec::with_capacity(edges_ref.map_or(0, |e| e.len()));

        if let Some(edges) = edges_ref {
            for edge in edges {
                if let Some(node) = edge.get("node") {
                    let id_str = node["id"].as_str().unwrap_or_default();
                    let count = node
                        .get("total_participants_count")
                        .or_else(|| node.get("participants_count"))
                        .and_then(|c| c.as_u64())
                        .unwrap_or(0) as u32;
                    match id_str.parse::<Jid>() {
                        Ok(jid) => counts.push((jid, count)),
                        Err(_) => warn!(
                            "community: skipping subgroup with unparseable id: {:?}",
                            id_str
                        ),
                    }
                }
            }
        }

        Ok(counts)
    }

    /// Query a linked subgroup's metadata from the parent community.
    pub async fn query_linked_group(
        &self,
        community_jid: &Jid,
        subgroup_jid: &Jid,
    ) -> Result<GroupMetadata, anyhow::Error> {
        let response = self
            .client
            .execute(QueryLinkedGroupIq::new(community_jid, subgroup_jid))
            .await?;
        Ok(GroupMetadata::from(response))
    }

    /// Join a linked subgroup via the parent community.
    pub async fn join_subgroup(
        &self,
        community_jid: &Jid,
        subgroup_jid: &Jid,
    ) -> Result<GroupMetadata, anyhow::Error> {
        let response = self
            .client
            .execute(JoinLinkedGroupIq::new(community_jid, subgroup_jid))
            .await?;
        Ok(GroupMetadata::from(response))
    }

    /// Get all participants across all linked groups of a community.
    pub async fn get_linked_groups_participants(
        &self,
        community_jid: &Jid,
    ) -> Result<Vec<GroupParticipant>, anyhow::Error> {
        let response = self
            .client
            .execute(GetLinkedGroupsParticipantsIq::new(community_jid))
            .await?;
        Ok(response.into_iter().map(Into::into).collect())
    }
}

fn parse_subgroup_node(node: &serde_json::Value, is_default: bool) -> Option<CommunitySubgroup> {
    let id_str = node.get("id")?.as_str()?;
    let jid: Jid = id_str.parse().ok()?;

    // Subject can be a plain string or an object {"value": "..."}
    let subject = node
        .get("subject")
        .and_then(|s| {
            s.as_str().map(|v| v.to_string()).or_else(|| {
                s.get("value")
                    .and_then(|v| v.as_str())
                    .map(|v| v.to_string())
            })
        })
        .unwrap_or_default();

    let participant_count = node
        .get("participants_count")
        .or_else(|| node.get("total_participants_count"))
        .and_then(|c| c.as_u64())
        .map(|c| c as u32);

    // Check if properties indicate general chat
    let is_general_from_props = node
        .get("properties")
        .and_then(|p| p.get("general_chat"))
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    Some(CommunitySubgroup {
        id: jid,
        subject,
        participant_count,
        is_default_sub_group: is_default,
        is_general_chat: is_general_from_props,
    })
}

impl Client {
    pub fn community(&self) -> Community<'_> {
        Community::new(self)
    }
}