whatsapp-rust 0.7.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! 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::GroupError;
use crate::features::groups::GroupMetadata;
use crate::features::groups::GroupParticipant;
use crate::features::groups::GroupParticipantOptions;
use crate::features::groups::ParticipantChangeResponse;
use crate::features::groups::PreviousDescription;
use crate::features::mex::{MexError, mex_request};
use crate::request::IqError;
use log::warn;
use thiserror::Error;
use wacore::iq::groups::{
    CommunityParticipatingIq, DeleteCommunityIq, GetLinkedGroupsParticipantsIq, GroupCreateOptions,
    JoinLinkedGroupIq, LinkSubgroupsIq, QueryLinkedGroupIq, UnlinkSubgroupsIq,
};
use wacore::iq::mex_operations::{fetch_all_subgroups, query_subgroup_participant_count};
use wacore_binary::Jid;

/// Error returned by community operations.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum CommunityError {
    /// A `w:g2` IQ to the server failed.
    #[error("{0}")]
    Iq(#[from] IqError),
    /// A MEX (GraphQL) metadata query/mutation failed or returned bad data.
    #[error("{0}")]
    Mex(#[from] MexError),
    /// A delegated group operation failed (e.g. setting the community description).
    #[error("{0}")]
    Group(#[from] GroupError),
    /// The request was malformed or the server response was missing required data.
    #[error("invalid community request: {0}")]
    InvalidRequest(String),
}

// 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)]
#[non_exhaustive]
pub struct CreateCommunityResult {
    pub metadata: GroupMetadata,
}

/// A subgroup within a community.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CommunitySubgroup {
    pub id: Jid,
    pub subject: String,
    pub participant_count: Option<u32>,
    /// Server-reported subgroup creation timestamp, when available.
    pub creation: Option<u64>,
    /// Server-reported subgroup creator, when available.
    pub owner: Option<Jid>,
    pub is_default_sub_group: bool,
    pub is_general_chat: bool,
}

/// Result of linking subgroups to a community.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
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)]
#[non_exhaustive]
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, CommunityError> {
        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 mut metadata = self
            .client
            .groups()
            .create_group(create_options)
            .await?
            .metadata;

        if let Some(desc_text) = description
            && let Ok(desc) = wacore::iq::groups::GroupDescription::new(&desc_text)
        {
            self.client
                .groups()
                // The group was just created, so nothing can have set a
                // description ahead of us.
                .set_description(&metadata.id, Some(desc), PreviousDescription::Absent)
                .await?;
            metadata.description = Some(desc_text);
        }

        Ok(CreateCommunityResult { metadata })
    }

    /// Create a subgroup already linked to a parent group.
    pub async fn create_subgroup(
        &self,
        name: impl Into<String>,
        participants: &[Jid],
        parent_jid: impl Into<Jid>,
    ) -> Result<CreateCommunityResult, CommunityError> {
        let options = GroupCreateOptions {
            subject: name.into(),
            participants: participants
                .iter()
                .cloned()
                .map(GroupParticipantOptions::new)
                .collect(),
            linked_parent: Some(parent_jid.into()),
            ..Default::default()
        };
        let metadata = self.client.groups().create_group(options).await?.metadata;
        Ok(CreateCommunityResult { metadata })
    }

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

    /// Remove participants from the parent and all linked groups.
    pub async fn remove_participants(
        &self,
        community_jid: impl Into<Jid>,
        participants: &[Jid],
    ) -> Result<Vec<ParticipantChangeResponse>, CommunityError> {
        Ok(self
            .client
            .groups()
            .remove_participants_including_linked_groups(community_jid, participants)
            .await?)
    }

    /// Link existing groups as subgroups of a community.
    pub async fn link_subgroups(
        &self,
        community_jid: impl Into<Jid>,
        subgroup_jids: &[Jid],
    ) -> Result<LinkSubgroupsResult, CommunityError> {
        let community_jid = &community_jid.into();
        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: impl Into<Jid>,
        subgroup_jids: &[Jid],
        remove_orphan_members: bool,
    ) -> Result<UnlinkSubgroupsResult, CommunityError> {
        let community_jid = &community_jid.into();
        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>, CommunityError> {
        let response = self
            .client
            .mex()
            .query(mex_request!(fetch_all_subgroups {
                group_id: Some(community_jid.to_string()),
                ..Default::default()
            }))
            .await?;

        let data = response.data.ok_or_else(|| {
            CommunityError::InvalidRequest("MEX response 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 all parent groups the account currently participates in.
    pub async fn get_participating(
        &self,
    ) -> Result<std::collections::HashMap<Jid, GroupMetadata>, CommunityError> {
        let response = self.client.execute(CommunityParticipatingIq::new()).await?;
        let mut result: std::collections::HashMap<Jid, GroupMetadata> = response
            .groups
            .into_iter()
            .map(|community| {
                let id = community.id.clone();
                (id, GroupMetadata::from(community))
            })
            .collect();

        for metadata in result.values_mut() {
            self.client.groups().fill_participant_pns(metadata).await;
        }

        Ok(result)
    }

    /// Fetch participant counts per subgroup via MEX (GraphQL).
    pub async fn get_subgroup_participant_counts(
        &self,
        community_jid: &Jid,
    ) -> Result<Vec<(Jid, u32)>, CommunityError> {
        let response = self
            .client
            .mex()
            .query(mex_request!(query_subgroup_participant_count {
                input: Some(query_subgroup_participant_count::Input {
                    group_jid: Some(community_jid.to_string()),
                    ..Default::default()
                }),
            }))
            .await?;

        let data = response.data.ok_or_else(|| {
            CommunityError::InvalidRequest("MEX response 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: impl Into<Jid>,
        subgroup_jid: impl Into<Jid>,
    ) -> Result<GroupMetadata, CommunityError> {
        let community_jid = &community_jid.into();
        let subgroup_jid = &subgroup_jid.into();
        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: impl Into<Jid>,
        subgroup_jid: impl Into<Jid>,
    ) -> Result<GroupMetadata, CommunityError> {
        let community_jid = &community_jid.into();
        let subgroup_jid = &subgroup_jid.into();
        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: impl Into<Jid>,
    ) -> Result<Vec<GroupParticipant>, CommunityError> {
        let community_jid = &community_jid.into();
        let response = self
            .client
            .execute(GetLinkedGroupsParticipantsIq::new(community_jid))
            .await?;
        Ok(response.into_iter().map(Into::into).collect())
    }
}

fn json_u64(value: &serde_json::Value) -> Option<u64> {
    value
        .as_u64()
        .or_else(|| value.as_str()?.parse::<u64>().ok())
}

fn json_jid(value: &serde_json::Value) -> Option<Jid> {
    if let Some(value) = value.as_str() {
        return value.parse().ok();
    }

    let object = value.as_object()?;
    ["id", "lid", "pn"]
        .into_iter()
        .filter_map(|field| object.get(field)?.as_str())
        .find_map(|value| value.parse().ok())
}

fn json_bool(value: &serde_json::Value) -> Option<bool> {
    value.as_bool().or_else(|| match value.as_str()? {
        "1" | "true" => Some(true),
        "0" | "false" => Some(false),
        _ => None,
    })
}

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(json_u64)
        .and_then(|count| u32::try_from(count).ok());

    let creation = node
        .get("creation")
        .or_else(|| node.get("creation_time"))
        .and_then(json_u64)
        .or_else(|| node.get("subject")?.get("creation_time").and_then(json_u64));
    let owner = node
        .get("creator")
        .or_else(|| node.get("owner"))
        .and_then(json_jid)
        .or_else(|| node.get("subject")?.get("creator").and_then(json_jid));

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

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

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn subgroup_parser_preserves_typed_metadata() {
        let node = serde_json::json!({
            "id": "120363000000000002@g.us",
            "subject": {
                "value": "Fictitious subgroup",
                "creation_time": "1700000012"
            },
            "creator": {
                "id": "100000000000002@lid",
                "pn": "15550000002@s.whatsapp.net"
            },
            "total_participants_count": 42,
            "properties": { "general_chat": "1" }
        });

        let subgroup = parse_subgroup_node(&node, false).expect("valid subgroup");
        assert_eq!(subgroup.subject, "Fictitious subgroup");
        assert_eq!(subgroup.creation, Some(1_700_000_012));
        assert_eq!(subgroup.participant_count, Some(42));
        assert_eq!(subgroup.owner, Some("100000000000002@lid".parse().unwrap()));
        assert!(subgroup.is_general_chat);
        assert!(!subgroup.is_default_sub_group);
    }

    #[test]
    fn subgroup_parser_accepts_legacy_scalar_metadata() {
        let node = serde_json::json!({
            "id": "120363000000000003@g.us",
            "subject": "Legacy subgroup",
            "creation": 1700000024,
            "owner": "15550000003@s.whatsapp.net",
            "properties": { "general_chat": false }
        });

        let subgroup = parse_subgroup_node(&node, true).expect("valid subgroup");
        assert_eq!(subgroup.creation, Some(1_700_000_024));
        assert_eq!(
            subgroup.owner,
            Some("15550000003@s.whatsapp.net".parse().unwrap())
        );
        assert!(!subgroup.is_general_chat);
        assert!(subgroup.is_default_sub_group);
    }
}