wacore 0.7.0

Core WhatsApp protocol implementation without runtime dependencies
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
//! Contact-related IQ specifications.
//!
//! ## Profile Picture Wire Format
//! ```xml
//! <!-- Request (with optional tctoken for privacy gating) -->
//! <iq xmlns="w:profile:picture" type="get" to="s.whatsapp.net" target="1234567890@s.whatsapp.net" id="...">
//!   <picture type="preview" query="url">
//!     <tctoken><!-- raw token bytes (optional) --></tctoken>
//!   </picture>
//! </iq>
//!
//! <!-- Response (success) -->
//! <iq from="s.whatsapp.net" id="..." type="result">
//!   <picture id="123456789" url="https://..." direct_path="/v/..."/>
//! </iq>
//!
//! <!-- Response (not found) -->
//! <iq from="s.whatsapp.net" id="..." type="result">
//!   <picture>
//!     <error code="404" text="item-not-found"/>
//!   </picture>
//! </iq>
//! ```

use crate::iq::spec::IqSpec;
use crate::iq::tctoken::build_tc_token_node;
use crate::request::InfoQuery;
use anyhow::anyhow;
use std::time::Duration;
use wacore_binary::builder::NodeBuilder;
use wacore_binary::{Jid, Server};
use wacore_binary::{NodeContent, NodeRef};

/// Profile picture information.
#[derive(Debug, Clone)]
pub struct ProfilePicture {
    pub id: String,
    pub url: String,
    pub direct_path: Option<String>,
    /// SHA-256 hash for integrity/cache validation.
    pub hash: Option<String>,
}

/// Profile picture type (preview thumbnail or full-size).
#[derive(Debug, Clone, Copy, PartialEq, Eq, crate::WireEnum)]
pub enum ProfilePictureType {
    #[wire = "preview"]
    Preview,
    #[wire = "image"]
    Full,
}

/// Fetches the profile picture URL for a given JID.
#[derive(Debug, Clone)]
pub struct ProfilePictureSpec {
    pub jid: Jid,
    pub picture_type: ProfilePictureType,
    /// Optional tctoken to include in the IQ for privacy gating.
    pub tc_token: Option<Vec<u8>>,
    /// Current known picture ID. When set, the server can skip re-sending
    /// if the picture hasn't changed (cache optimization).
    pub existing_id: Option<String>,
    /// Optional request timeout override.
    pub timeout: Option<Duration>,
}

impl ProfilePictureSpec {
    pub fn preview(jid: &Jid) -> Self {
        Self {
            jid: jid.clone(),
            picture_type: ProfilePictureType::Preview,
            tc_token: None,
            existing_id: None,
            timeout: None,
        }
    }

    pub fn full(jid: &Jid) -> Self {
        Self {
            jid: jid.clone(),
            picture_type: ProfilePictureType::Full,
            tc_token: None,
            existing_id: None,
            timeout: None,
        }
    }

    pub fn new(jid: &Jid, picture_type: ProfilePictureType) -> Self {
        Self {
            jid: jid.clone(),
            picture_type,
            tc_token: None,
            existing_id: None,
            timeout: None,
        }
    }

    /// Include a tctoken in the profile picture IQ for privacy gating.
    pub fn with_tc_token(mut self, token: Vec<u8>) -> Self {
        self.tc_token = Some(token);
        self
    }

    /// Override the default request timeout.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
}

impl IqSpec for ProfilePictureSpec {
    type Response = Option<ProfilePicture>;

    fn build_iq(&self) -> InfoQuery<'static> {
        let mut picture_builder = NodeBuilder::new("picture")
            .attr("type", self.picture_type.as_str())
            .attr("query", "url");

        if let Some(id) = &self.existing_id {
            picture_builder = picture_builder.attr("id", id);
        }

        // tctoken is a child of <picture>, matching WhatsApp Web's mixin merge pattern
        if let Some(token) = &self.tc_token {
            picture_builder = picture_builder.children([build_tc_token_node(token)]);
        }

        let query = InfoQuery::get(
            "w:profile:picture",
            Jid::new("", Server::Pn),
            Some(NodeContent::Nodes(vec![picture_builder.build()])),
        )
        .with_target_ref(&self.jid);
        match self.timeout {
            Some(timeout) => query.with_timeout(timeout),
            None => query,
        }
    }

    fn parse_response(&self, response: &NodeRef<'_>) -> Result<Self::Response, anyhow::Error> {
        let picture_node = match response.get_optional_child("picture") {
            Some(p) => p,
            None => return Ok(None),
        };

        // Check for error response
        if let Some(error_node) = picture_node.get_optional_child("error") {
            let code = error_node.attrs().optional_string("code");
            let code_str = code.as_deref().unwrap_or("0");
            if code_str == "404" || code_str == "401" {
                return Ok(None);
            }
            let text = error_node.attrs().optional_string("text");
            let text_str = text.as_deref().unwrap_or("unknown error");
            return Err(anyhow!("Profile picture error {}: {}", code_str, text_str));
        }

        let id = match picture_node.attrs().optional_string("id") {
            Some(s) => s.to_string(),
            // Empty <picture/> with no attributes = cache hit (picture unchanged)
            None => return Ok(None),
        };

        let url = match picture_node.attrs().optional_string("url") {
            Some(s) => s.to_string(),
            // <picture id="..."/> with no url = cache hit variant
            None => return Ok(None),
        };

        let direct_path = picture_node
            .attrs()
            .optional_string("direct_path")
            .map(|s| s.to_string());

        let hash = picture_node
            .attrs()
            .optional_string("hash")
            .map(|s| s.to_string());

        Ok(Some(ProfilePicture {
            id,
            url,
            direct_path,
            hash,
        }))
    }
}

/// Response from setting a profile picture.
#[derive(Debug, Clone)]
pub struct SetProfilePictureResponse {
    /// The server-assigned picture ID.
    pub id: String,
}

/// Sets or removes a profile picture.
///
/// ## Wire Format (Set)
/// ```xml
/// <iq xmlns="w:profile:picture" type="set" to="s.whatsapp.net" id="...">
///   <picture type="image">{binary image data}</picture>
/// </iq>
/// ```
///
/// ## Wire Format (Remove)
/// ```xml
/// <iq xmlns="w:profile:picture" type="set" to="s.whatsapp.net" id="..."/>
/// ```
/// No `<picture>` child: `WAWebSendProfilePictureJob` emits an empty IQ.
///
/// ## Response
/// ```xml
/// <iq type="result" from="s.whatsapp.net" id="...">
///   <picture id="123456789"/>
/// </iq>
/// ```
#[derive(Debug, Clone)]
pub struct SetProfilePictureSpec {
    /// If Some, set picture for a group. If None, set for self.
    pub target: Option<Jid>,
    /// Image bytes. None means remove the picture.
    pub image_data: Option<Vec<u8>>,
}

impl SetProfilePictureSpec {
    /// Set own profile picture. Panics if `image_data` is empty (use `remove_own` instead).
    pub fn set_own(image_data: Vec<u8>) -> Self {
        assert!(
            !image_data.is_empty(),
            "image_data cannot be empty; use remove_own() to delete"
        );
        Self {
            target: None,
            image_data: Some(image_data),
        }
    }

    /// Remove own profile picture.
    pub fn remove_own() -> Self {
        Self {
            target: None,
            image_data: None,
        }
    }

    /// Set or remove the own picture from caller-supplied bytes. Empty bytes mean
    /// remove, matching WAWebSendProfilePictureJob (`a ? wap("picture",..) : null`).
    pub fn for_own(image_data: Vec<u8>) -> Self {
        if image_data.is_empty() {
            Self::remove_own()
        } else {
            Self::set_own(image_data)
        }
    }

    /// Set a group's profile picture. Panics if `image_data` is empty (use `remove_group` instead).
    pub fn set_group(group_jid: &Jid, image_data: Vec<u8>) -> Self {
        assert!(
            !image_data.is_empty(),
            "image_data cannot be empty; use remove_group() to delete"
        );
        Self {
            target: Some(group_jid.clone()),
            image_data: Some(image_data),
        }
    }

    /// Remove a group's profile picture.
    pub fn remove_group(group_jid: &Jid) -> Self {
        Self {
            target: Some(group_jid.clone()),
            image_data: None,
        }
    }

    /// Set or remove a group's picture from caller-supplied bytes. Empty bytes
    /// mean remove, mirroring [`Self::for_own`].
    pub fn for_group(group_jid: &Jid, image_data: Vec<u8>) -> Self {
        if image_data.is_empty() {
            Self::remove_group(group_jid)
        } else {
            Self::set_group(group_jid, image_data)
        }
    }
}

impl IqSpec for SetProfilePictureSpec {
    type Response = SetProfilePictureResponse;

    fn build_iq(&self) -> InfoQuery<'static> {
        // WAWebSendProfilePictureJob: emits `<picture type="image">{bytes}</picture>`
        // on set, NO `<picture>` child on remove.
        let content = self.image_data.as_ref().map(|data| {
            NodeContent::Nodes(vec![
                NodeBuilder::new("picture")
                    .attr("type", "image")
                    .bytes(data.clone())
                    .build(),
            ])
        });

        let mut iq = InfoQuery::set("w:profile:picture", Jid::new("", Server::Pn), content);

        if let Some(target) = &self.target {
            iq = iq.with_target_ref(target);
        }

        iq
    }

    fn parse_response(&self, response: &NodeRef<'_>) -> Result<Self::Response, anyhow::Error> {
        if self.image_data.is_some() {
            // Set operation: server must return <picture id="..."/>
            let picture_node = response
                .get_optional_child("picture")
                .ok_or_else(|| anyhow!("Set picture response missing 'picture' child"))?;
            let id = picture_node
                .attrs()
                .optional_string("id")
                .map(|s| s.to_string())
                .ok_or_else(|| anyhow!("Set picture response missing 'id' attribute"))?;
            Ok(SetProfilePictureResponse { id })
        } else {
            // Remove operation: server may return an empty result
            let id = response
                .get_optional_child("picture")
                .and_then(|p| p.attrs().optional_string("id").map(|s| s.to_string()))
                .unwrap_or_default();
            Ok(SetProfilePictureResponse { id })
        }
    }
}

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

    #[test]
    fn for_own_routes_empty_to_remove() {
        // WA Web treats empty bytes as a removal.
        assert!(
            SetProfilePictureSpec::for_own(Vec::new())
                .image_data
                .is_none()
        );
        assert_eq!(
            SetProfilePictureSpec::for_own(vec![1, 2, 3]).image_data,
            Some(vec![1, 2, 3])
        );
    }

    #[test]
    fn for_group_routes_empty_to_remove() {
        let group_jid: Jid = "123456789@g.us".parse().unwrap();
        let removed = SetProfilePictureSpec::for_group(&group_jid, Vec::new());
        assert!(removed.image_data.is_none());
        assert_eq!(removed.target.as_ref(), Some(&group_jid));

        let set = SetProfilePictureSpec::for_group(&group_jid, vec![1, 2, 3]);
        assert_eq!(set.image_data, Some(vec![1, 2, 3]));
        assert_eq!(set.target.as_ref(), Some(&group_jid));
    }

    #[test]
    fn test_profile_picture_spec_preview() {
        let jid: Jid = "1234567890@s.whatsapp.net".parse().unwrap();
        let spec = ProfilePictureSpec::preview(&jid);

        assert_eq!(spec.picture_type, ProfilePictureType::Preview);

        let iq = spec.build_iq();
        assert_eq!(iq.namespace, "w:profile:picture");
        assert_eq!(iq.target, Some(jid));

        if let Some(NodeContent::Nodes(nodes)) = &iq.content {
            assert_eq!(nodes[0].tag, "picture");
            assert!(nodes[0].attrs.get("type").is_some_and(|s| s == "preview"));
        }
    }

    #[test]
    fn test_profile_picture_spec_full() {
        let jid: Jid = "1234567890@s.whatsapp.net".parse().unwrap();
        let spec = ProfilePictureSpec::full(&jid);

        assert_eq!(spec.picture_type, ProfilePictureType::Full);

        let iq = spec.build_iq();
        if let Some(NodeContent::Nodes(nodes)) = &iq.content {
            assert!(nodes[0].attrs.get("type").is_some_and(|s| s == "image"));
        }
    }

    #[test]
    fn test_profile_picture_spec_timeout_override() {
        let jid: Jid = "1234567890@s.whatsapp.net".parse().unwrap();
        let timeout = Duration::from_millis(1_250);
        let iq = ProfilePictureSpec::preview(&jid)
            .with_timeout(timeout)
            .build_iq();
        assert_eq!(iq.timeout, Some(timeout));
    }

    #[test]
    fn test_profile_picture_spec_parse_success() {
        let jid: Jid = "1234567890@s.whatsapp.net".parse().unwrap();
        let spec = ProfilePictureSpec::preview(&jid);

        let response = NodeBuilder::new("iq")
            .attr("type", "result")
            .children([NodeBuilder::new("picture")
                .attr("id", "123456789")
                .attr("url", "https://example.com/pic.jpg")
                .attr("direct_path", "/v/pic.jpg")
                .build()])
            .build();

        let result = spec.parse_response(&response.as_node_ref()).unwrap();
        assert!(result.is_some());

        let pic = result.unwrap();
        assert_eq!(pic.id, "123456789");
        assert_eq!(pic.url, "https://example.com/pic.jpg");
        assert_eq!(pic.direct_path, Some("/v/pic.jpg".to_string()));
    }

    #[test]
    fn test_profile_picture_spec_parse_not_found() {
        let jid: Jid = "1234567890@s.whatsapp.net".parse().unwrap();
        let spec = ProfilePictureSpec::preview(&jid);

        let response = NodeBuilder::new("iq")
            .attr("type", "result")
            .children([NodeBuilder::new("picture")
                .children([NodeBuilder::new("error")
                    .attr("code", "404")
                    .attr("text", "item-not-found")
                    .build()])
                .build()])
            .build();

        let result = spec.parse_response(&response.as_node_ref()).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_profile_picture_spec_parse_no_picture_node() {
        let jid: Jid = "1234567890@s.whatsapp.net".parse().unwrap();
        let spec = ProfilePictureSpec::preview(&jid);

        let response = NodeBuilder::new("iq").attr("type", "result").build();

        let result = spec.parse_response(&response.as_node_ref()).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_profile_picture_spec_with_tc_token() {
        let jid: Jid = "1234567890@s.whatsapp.net".parse().unwrap();
        let spec = ProfilePictureSpec::preview(&jid).with_tc_token(vec![0xCA, 0xFE, 0xBA, 0xBE]);

        let iq = spec.build_iq();
        if let Some(NodeContent::Nodes(nodes)) = &iq.content {
            assert_eq!(nodes.len(), 1, "IQ should have one child: picture");
            let picture = &nodes[0];
            assert_eq!(picture.tag, "picture");

            // tctoken is a child of picture (matching WhatsApp Web's mixin merge)
            let tctoken_children: Vec<_> = picture.get_children_by_tag("tctoken").collect();
            assert_eq!(tctoken_children.len(), 1);
            match &tctoken_children[0].content {
                Some(NodeContent::Bytes(data)) => {
                    assert_eq!(data, &[0xCA, 0xFE, 0xBA, 0xBE]);
                }
                _ => panic!("Expected binary content in tctoken node"),
            }
        } else {
            panic!("Expected NodeContent::Nodes");
        }
    }

    #[test]
    fn test_profile_picture_spec_without_tc_token() {
        let jid: Jid = "1234567890@s.whatsapp.net".parse().unwrap();
        let spec = ProfilePictureSpec::preview(&jid);

        let iq = spec.build_iq();
        if let Some(NodeContent::Nodes(nodes)) = &iq.content {
            assert_eq!(nodes.len(), 1, "IQ should have one child: picture");
            let picture = &nodes[0];
            assert_eq!(picture.tag, "picture");
            let tctoken_children: Vec<_> = picture.get_children_by_tag("tctoken").collect();
            assert_eq!(tctoken_children.len(), 0, "No tctoken without token");
        } else {
            panic!("Expected NodeContent::Nodes");
        }
    }

    #[test]
    fn test_set_profile_picture_spec_own() {
        let spec = SetProfilePictureSpec::set_own(vec![0xFF, 0xD8, 0xFF]);
        let iq = spec.build_iq();

        assert_eq!(iq.namespace, "w:profile:picture");
        assert_eq!(iq.query_type.as_str(), "set");
        assert!(iq.target.is_none(), "Own picture should not have target");

        if let Some(NodeContent::Nodes(nodes)) = &iq.content {
            let picture = &nodes[0];
            assert_eq!(picture.tag, "picture");
            assert!(picture.attrs.get("type").is_some_and(|v| v == "image"));
            match &picture.content {
                Some(NodeContent::Bytes(data)) => {
                    assert_eq!(data, &[0xFF, 0xD8, 0xFF]);
                }
                _ => panic!("Expected binary content in picture node"),
            }
        } else {
            panic!("Expected NodeContent::Nodes");
        }
    }

    #[test]
    fn test_set_profile_picture_spec_group() {
        let group_jid: Jid = "123456789@g.us".parse().unwrap();
        let spec = SetProfilePictureSpec::set_group(&group_jid, vec![0x89, 0x50, 0x4E]);
        let iq = spec.build_iq();

        assert_eq!(iq.namespace, "w:profile:picture");
        assert_eq!(iq.target, Some(group_jid));
    }

    #[test]
    fn test_set_profile_picture_spec_remove_own_emits_no_picture_child() {
        // WAWebSendProfilePictureJob: removal IQ has no `<picture>` child at all.
        let spec = SetProfilePictureSpec::remove_own();
        let iq = spec.build_iq();
        assert!(
            iq.content.is_none(),
            "Remove must emit an empty <iq> with no <picture> child; got {:?}",
            iq.content
        );
    }

    #[test]
    fn test_set_profile_picture_spec_remove_group_emits_no_picture_child() {
        let group_jid: Jid = "123456789@g.us".parse().unwrap();
        let spec = SetProfilePictureSpec::remove_group(&group_jid);
        let iq = spec.build_iq();
        assert!(iq.content.is_none(), "Remove group: no <picture> child");
        assert_eq!(iq.target, Some(group_jid));
    }

    #[test]
    fn test_set_profile_picture_spec_parse_response() {
        let spec = SetProfilePictureSpec::set_own(vec![0xFF, 0xD8]);
        let response = NodeBuilder::new("iq")
            .attr("type", "result")
            .children([NodeBuilder::new("picture").attr("id", "987654321").build()])
            .build();

        let result = spec.parse_response(&response.as_node_ref()).unwrap();
        assert_eq!(result.id, "987654321");
    }
}