whatsapp-rust 0.5.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
use crate::client::Client;
use std::collections::HashMap;
use wacore::client::context::GroupInfo;
use wacore::iq::groups::{
    AcceptGroupInviteIq, AcceptGroupInviteV4Iq, AddParticipantsIq, DemoteParticipantsIq,
    GetGroupInviteInfoIq, GetGroupInviteLinkIq, GetMembershipRequestsIq, GroupCreateIq,
    GroupInfoResponse, GroupParticipantResponse, GroupParticipatingIq, GroupQueryIq, LeaveGroupIq,
    MembershipRequestActionIq, PromoteParticipantsIq, RemoveParticipantsIq, SetGroupAnnouncementIq,
    SetGroupDescriptionIq, SetGroupEphemeralIq, SetGroupLockedIq, SetGroupMembershipApprovalIq,
    SetGroupSubjectIq, SetMemberAddModeIq, normalize_participants,
};
use wacore::types::message::AddressingMode;
use wacore_binary::jid::Jid;

pub use wacore::iq::groups::{
    GroupCreateOptions, GroupDescription, GroupParticipantOptions, GroupSubject, JoinGroupResult,
    MemberAddMode, MemberLinkMode, MembershipApprovalMode, MembershipRequest,
    ParticipantChangeResponse,
};

#[derive(Debug, Clone)]
pub struct GroupMetadata {
    pub id: Jid,
    pub subject: String,
    pub participants: Vec<GroupParticipant>,
    pub addressing_mode: AddressingMode,
    /// Group creator JID.
    pub creator: Option<Jid>,
    /// Group creation timestamp (Unix seconds).
    pub creation_time: Option<u64>,
    /// Subject modification timestamp (Unix seconds).
    pub subject_time: Option<u64>,
    /// Subject owner JID.
    pub subject_owner: Option<Jid>,
    /// Group description body text.
    pub description: Option<String>,
    /// Description ID (for conflict detection when updating).
    pub description_id: Option<String>,
    /// Whether the group is locked (only admins can edit group info).
    pub is_locked: bool,
    /// Whether announcement mode is enabled (only admins can send messages).
    pub is_announcement: bool,
    /// Ephemeral message expiration in seconds (0 = disabled).
    pub ephemeral_expiration: u32,
    /// Whether membership approval is required to join.
    pub membership_approval: bool,
    /// Who can add members to the group.
    pub member_add_mode: Option<MemberAddMode>,
    /// Who can use invite links.
    pub member_link_mode: Option<MemberLinkMode>,
    /// Total participant count.
    pub size: Option<u32>,
    /// Whether this group is a community parent group.
    pub is_parent_group: bool,
    /// JID of the parent community (for subgroups).
    pub parent_group_jid: Option<Jid>,
    /// Whether this is the default announcement subgroup of a community.
    pub is_default_sub_group: bool,
    /// Whether this is the general chat subgroup of a community.
    pub is_general_chat: bool,
    /// Whether non-admin community members can create subgroups.
    pub allow_non_admin_sub_group_creation: bool,
}

#[derive(Debug, Clone)]
pub struct GroupParticipant {
    pub jid: Jid,
    pub phone_number: Option<Jid>,
    pub is_admin: bool,
}

impl From<GroupParticipantResponse> for GroupParticipant {
    fn from(p: GroupParticipantResponse) -> Self {
        Self {
            jid: p.jid,
            phone_number: p.phone_number,
            is_admin: p.participant_type.is_admin(),
        }
    }
}

impl From<GroupInfoResponse> for GroupMetadata {
    fn from(group: GroupInfoResponse) -> Self {
        Self {
            id: group.id,
            subject: group.subject.into_string(),
            participants: group.participants.into_iter().map(Into::into).collect(),
            addressing_mode: group.addressing_mode,
            creator: group.creator,
            creation_time: group.creation_time,
            subject_time: group.subject_time,
            subject_owner: group.subject_owner,
            description: group.description,
            description_id: group.description_id,
            is_locked: group.is_locked,
            is_announcement: group.is_announcement,
            ephemeral_expiration: group.ephemeral_expiration,
            membership_approval: group.membership_approval,
            member_add_mode: group.member_add_mode,
            member_link_mode: group.member_link_mode,
            size: group.size,
            is_parent_group: group.is_parent_group,
            parent_group_jid: group.parent_group_jid,
            is_default_sub_group: group.is_default_sub_group,
            is_general_chat: group.is_general_chat,
            allow_non_admin_sub_group_creation: group.allow_non_admin_sub_group_creation,
        }
    }
}

#[derive(Debug, Clone)]
pub struct CreateGroupResult {
    pub gid: Jid,
}

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

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

    pub async fn query_info(&self, jid: &Jid) -> Result<GroupInfo, anyhow::Error> {
        if let Some(cached) = self.client.get_group_cache().await.get(jid).await {
            return Ok(cached);
        }

        let group = self.client.execute(GroupQueryIq::new(jid)).await?;

        let participants: Vec<Jid> = group.participants.iter().map(|p| p.jid.clone()).collect();

        let lid_to_pn_map: HashMap<String, Jid> = if group.addressing_mode == AddressingMode::Lid {
            group
                .participants
                .iter()
                .filter_map(|p| {
                    p.phone_number
                        .as_ref()
                        .map(|pn| (p.jid.user.clone(), pn.clone()))
                })
                .collect()
        } else {
            HashMap::new()
        };

        let mut info = GroupInfo::new(participants, group.addressing_mode);
        if !lid_to_pn_map.is_empty() {
            info.set_lid_to_pn_map(lid_to_pn_map);
        }

        self.client
            .get_group_cache()
            .await
            .insert(jid.clone(), info.clone())
            .await;

        Ok(info)
    }

    pub async fn get_participating(&self) -> Result<HashMap<String, GroupMetadata>, anyhow::Error> {
        let response = self.client.execute(GroupParticipatingIq::new()).await?;

        let result = response
            .groups
            .into_iter()
            .map(|group| {
                let key = group.id.to_string();
                let metadata = GroupMetadata::from(group);
                (key, metadata)
            })
            .collect();

        Ok(result)
    }

    pub async fn get_metadata(&self, jid: &Jid) -> Result<GroupMetadata, anyhow::Error> {
        let group = self.client.execute(GroupQueryIq::new(jid)).await?;
        Ok(GroupMetadata::from(group))
    }

    pub async fn create_group(
        &self,
        mut options: GroupCreateOptions,
    ) -> Result<CreateGroupResult, anyhow::Error> {
        // Resolve phone numbers for LID participants that don't have one
        let mut resolved_participants = Vec::with_capacity(options.participants.len());

        for participant in options.participants {
            let resolved = if participant.jid.is_lid() && participant.phone_number.is_none() {
                let phone_number = self
                    .client
                    .get_phone_number_from_lid(&participant.jid.user)
                    .await
                    .ok_or_else(|| {
                        anyhow::anyhow!("Missing phone number mapping for LID {}", participant.jid)
                    })?;
                participant.with_phone_number(Jid::pn(phone_number))
            } else {
                participant
            };
            resolved_participants.push(resolved);
        }

        options.participants = normalize_participants(&resolved_participants);

        let gid = self.client.execute(GroupCreateIq::new(options)).await?;

        Ok(CreateGroupResult { gid })
    }

    pub async fn set_subject(&self, jid: &Jid, subject: GroupSubject) -> Result<(), anyhow::Error> {
        Ok(self
            .client
            .execute(SetGroupSubjectIq::new(jid, subject))
            .await?)
    }

    /// Sets or deletes a group's description.
    ///
    /// `prev` is the current description ID (from group metadata) used for
    /// conflict detection. Pass `None` if unknown.
    pub async fn set_description(
        &self,
        jid: &Jid,
        description: Option<GroupDescription>,
        prev: Option<String>,
    ) -> Result<(), anyhow::Error> {
        Ok(self
            .client
            .execute(SetGroupDescriptionIq::new(jid, description, prev))
            .await?)
    }

    pub async fn leave(&self, jid: &Jid) -> Result<(), anyhow::Error> {
        self.client.execute(LeaveGroupIq::new(jid)).await?;
        self.client.get_group_cache().await.invalidate(jid).await;
        Ok(())
    }

    pub async fn add_participants(
        &self,
        jid: &Jid,
        participants: &[Jid],
    ) -> Result<Vec<ParticipantChangeResponse>, anyhow::Error> {
        let result = self
            .client
            .execute(AddParticipantsIq::new(jid, participants))
            .await?;
        // Patch cache with only the participants the server accepted (status 200).
        // Note: the get→mutate→insert is not atomic; a concurrent notification
        // for the same group could race.  This is acceptable — the cache is
        // best-effort and a full refetch on next query_info() corrects it.
        let accepted: Vec<_> = result
            .iter()
            .filter(|r| r.status.as_deref() == Some("200"))
            .map(|r| (r.jid.clone(), None))
            .collect();
        if !accepted.is_empty() {
            let group_cache = self.client.get_group_cache().await;
            if let Some(mut info) = group_cache.get(jid).await {
                info.add_participants(&accepted);
                group_cache.insert(jid.clone(), info).await;
            }
        }
        Ok(result)
    }

    pub async fn remove_participants(
        &self,
        jid: &Jid,
        participants: &[Jid],
    ) -> Result<Vec<ParticipantChangeResponse>, anyhow::Error> {
        let result = self
            .client
            .execute(RemoveParticipantsIq::new(jid, participants))
            .await?;
        // Patch cache with only the participants the server accepted.
        let accepted: Vec<&str> = result
            .iter()
            .filter(|r| r.status.as_deref() == Some("200"))
            .map(|r| r.jid.user.as_str())
            .collect();
        if !accepted.is_empty() {
            let group_cache = self.client.get_group_cache().await;
            if let Some(mut info) = group_cache.get(jid).await {
                info.remove_participants(&accepted);
                group_cache.insert(jid.clone(), info).await;
            }
        }
        Ok(result)
    }

    pub async fn promote_participants(
        &self,
        jid: &Jid,
        participants: &[Jid],
    ) -> Result<(), anyhow::Error> {
        Ok(self
            .client
            .execute(PromoteParticipantsIq::new(jid, participants))
            .await?)
    }

    pub async fn demote_participants(
        &self,
        jid: &Jid,
        participants: &[Jid],
    ) -> Result<(), anyhow::Error> {
        Ok(self
            .client
            .execute(DemoteParticipantsIq::new(jid, participants))
            .await?)
    }

    pub async fn get_invite_link(&self, jid: &Jid, reset: bool) -> Result<String, anyhow::Error> {
        Ok(self
            .client
            .execute(GetGroupInviteLinkIq::new(jid, reset))
            .await?)
    }

    /// Lock the group so only admins can change group info.
    pub async fn set_locked(&self, jid: &Jid, locked: bool) -> Result<(), anyhow::Error> {
        let spec = if locked {
            SetGroupLockedIq::lock(jid)
        } else {
            SetGroupLockedIq::unlock(jid)
        };
        Ok(self.client.execute(spec).await?)
    }

    /// Set announcement mode. When enabled, only admins can send messages.
    pub async fn set_announce(&self, jid: &Jid, announce: bool) -> Result<(), anyhow::Error> {
        let spec = if announce {
            SetGroupAnnouncementIq::announce(jid)
        } else {
            SetGroupAnnouncementIq::unannounce(jid)
        };
        Ok(self.client.execute(spec).await?)
    }

    /// Set ephemeral (disappearing) messages timer on the group.
    ///
    /// Common values: 86400 (24h), 604800 (7d), 7776000 (90d).
    /// Pass 0 to disable.
    pub async fn set_ephemeral(&self, jid: &Jid, expiration: u32) -> Result<(), anyhow::Error> {
        let spec = match std::num::NonZeroU32::new(expiration) {
            Some(exp) => SetGroupEphemeralIq::enable(jid, exp),
            None => SetGroupEphemeralIq::disable(jid),
        };
        Ok(self.client.execute(spec).await?)
    }

    /// Set membership approval mode. When on, new members must be approved by an admin.
    pub async fn set_membership_approval(
        &self,
        jid: &Jid,
        mode: MembershipApprovalMode,
    ) -> Result<(), anyhow::Error> {
        Ok(self
            .client
            .execute(SetGroupMembershipApprovalIq::new(jid, mode))
            .await?)
    }

    /// Join a group using an invite code.
    pub async fn join_with_invite_code(
        &self,
        code: &str,
    ) -> Result<JoinGroupResult, anyhow::Error> {
        let code = strip_invite_url(code);
        Ok(self.client.execute(AcceptGroupInviteIq::new(code)).await?)
    }

    /// Accept a V4 invite (received as a GroupInviteMessage, not a link).
    pub async fn join_with_invite_v4(
        &self,
        group_jid: &Jid,
        code: &str,
        expiration: i64,
        admin_jid: &Jid,
    ) -> Result<JoinGroupResult, anyhow::Error> {
        if expiration > 0 {
            let now = wacore::time::now_millis() / 1000;
            if expiration < now {
                anyhow::bail!("V4 invite has expired (expiration={expiration}, now={now})");
            }
        }
        Ok(self
            .client
            .execute(AcceptGroupInviteV4Iq::new(
                group_jid.clone(),
                code.to_string(),
                expiration,
                admin_jid.clone(),
            ))
            .await?)
    }

    /// Get group metadata from an invite code without joining.
    pub async fn get_invite_info(&self, code: &str) -> Result<GroupMetadata, anyhow::Error> {
        let code = strip_invite_url(code);
        let group = self.client.execute(GetGroupInviteInfoIq::new(code)).await?;
        Ok(GroupMetadata::from(group))
    }

    /// Get pending membership approval requests.
    pub async fn get_membership_requests(
        &self,
        jid: &Jid,
    ) -> Result<Vec<MembershipRequest>, anyhow::Error> {
        Ok(self
            .client
            .execute(GetMembershipRequestsIq::new(jid))
            .await?)
    }

    /// Approve pending membership requests.
    pub async fn approve_membership_requests(
        &self,
        jid: &Jid,
        participants: &[Jid],
    ) -> Result<Vec<ParticipantChangeResponse>, anyhow::Error> {
        Ok(self
            .client
            .execute(MembershipRequestActionIq::approve(jid, participants))
            .await?)
    }

    /// Reject pending membership requests.
    pub async fn reject_membership_requests(
        &self,
        jid: &Jid,
        participants: &[Jid],
    ) -> Result<Vec<ParticipantChangeResponse>, anyhow::Error> {
        Ok(self
            .client
            .execute(MembershipRequestActionIq::reject(jid, participants))
            .await?)
    }

    /// Set who can add members to the group.
    pub async fn set_member_add_mode(
        &self,
        jid: &Jid,
        mode: MemberAddMode,
    ) -> Result<(), anyhow::Error> {
        Ok(self
            .client
            .execute(SetMemberAddModeIq::new(jid, mode))
            .await?)
    }
}

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

fn strip_invite_url(code: &str) -> &str {
    let code = code.trim().trim_end_matches('/');
    code.strip_prefix("https://chat.whatsapp.com/")
        .or_else(|| code.strip_prefix("http://chat.whatsapp.com/"))
        .unwrap_or(code)
}

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

    #[test]
    fn test_group_metadata_struct() {
        let jid: Jid = "123456789@g.us"
            .parse()
            .expect("test group JID should be valid");
        let participant_jid: Jid = "1234567890@s.whatsapp.net"
            .parse()
            .expect("test participant JID should be valid");

        let metadata = GroupMetadata {
            id: jid.clone(),
            subject: "Test Group".to_string(),
            participants: vec![GroupParticipant {
                jid: participant_jid,
                phone_number: None,
                is_admin: true,
            }],
            addressing_mode: AddressingMode::Pn,
            creator: None,
            creation_time: None,
            subject_time: None,
            subject_owner: None,
            description: None,
            description_id: None,
            is_locked: false,
            is_announcement: false,
            ephemeral_expiration: 0,
            membership_approval: false,
            member_add_mode: None,
            member_link_mode: None,
            size: None,
            is_parent_group: false,
            parent_group_jid: None,
            is_default_sub_group: false,
            is_general_chat: false,
            allow_non_admin_sub_group_creation: false,
        };

        assert_eq!(metadata.subject, "Test Group");
        assert_eq!(metadata.participants.len(), 1);
        assert!(metadata.participants[0].is_admin);
    }

    // Protocol-level tests (node building, parsing, validation) are in wacore/src/iq/groups.rs
}