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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! Sticker pack creation helpers.
//!
//! Same pattern as album messages: proto-level helpers, no dedicated send method.
//!
//! ```rust,ignore
//! let stickers = vec![
//!     StickerInput::new(&webp_bytes).with_emojis(vec!["😀".into()]),
//!     StickerInput::new(&webp_bytes_2),
//! ];
//! let zip_result = create_sticker_pack_zip("pack-id", &stickers, &cover_webp)?;
//!
//! // The pack zip and its thumbnail are independent uploads that share one
//! // media key. Generate the key up front and upload both concurrently instead
//! // of chaining the thumbnail behind the zip's result — two CDN round-trips
//! // collapse into one wall-clock. (`upload` takes `&self`, so concurrent calls
//! // are fine.)
//! let media_key: [u8; 32] = rand::random();
//! let (zip_upload, thumb_upload) = futures::try_join!(
//!     client.upload(zip_result.zip_bytes.clone(), MediaType::StickerPack,
//!         UploadOptions::new().with_media_key(media_key)),
//!     client.upload(thumbnail_jpeg, MediaType::StickerPackThumbnail,
//!         UploadOptions::new().with_media_key(media_key)),
//! )?;
//!
//! let metadata = StickerPackMetadata::new(pack_id, "My Pack".into(), "Me".into());
//! let msg = build_sticker_pack_message(&zip_result, &zip_upload.into(), &thumb_upload.into(), metadata)?;
//! client.send_message(jid, msg).await?;
//! ```
//!
//! Sticker format requirements (user's responsibility):
//! - Stickers: 512x512 WebP
//! - Cover: WebP, stored in ZIP as `{pack_id}.webp`
//! - Thumbnail: JPEG, uploaded separately with the same `media_key`

use crate::webp;
use crate::zip::ZipWriter;
use anyhow::{Result, bail};
use sha2::{Digest, Sha256};
use waproto::whatsapp as wa;

#[non_exhaustive]
pub struct StickerInput<'a> {
    pub data: &'a [u8],
    pub emojis: Vec<String>,
    pub accessibility_label: Option<String>,
}

impl<'a> StickerInput<'a> {
    pub fn new(data: &'a [u8]) -> Self {
        Self {
            data,
            emojis: Vec::new(),
            accessibility_label: None,
        }
    }

    pub fn with_emojis(mut self, emojis: Vec<String>) -> Self {
        self.emojis = emojis;
        self
    }

    pub fn with_accessibility_label(mut self, label: String) -> Self {
        self.accessibility_label = Some(label);
        self
    }
}

#[non_exhaustive]
pub struct StickerPackZipResult {
    pub zip_bytes: Vec<u8>,
    pub stickers: Vec<wa::message::sticker_pack_message::Sticker>,
    pub tray_icon_file_name: String,
}

#[non_exhaustive]
pub struct StickerPackMetadata {
    pub pack_id: String,
    pub name: String,
    pub publisher: String,
    pub description: Option<String>,
    pub caption: Option<String>,
}

impl StickerPackMetadata {
    pub fn new(pack_id: String, name: String, publisher: String) -> Self {
        Self {
            pack_id,
            name,
            publisher,
            description: None,
            caption: None,
        }
    }

    pub fn with_description(mut self, desc: String) -> Self {
        self.description = Some(desc);
        self
    }

    pub fn with_caption(mut self, caption: String) -> Self {
        self.caption = Some(caption);
        self
    }
}

/// Upload result fields for proto construction.
/// The high-level crate provides `From<UploadResponse>`.
#[non_exhaustive]
pub struct MediaUploadInfo {
    pub direct_path: String,
    pub media_key: [u8; 32],
    pub file_sha256: [u8; 32],
    pub file_enc_sha256: [u8; 32],
    pub file_length: u64,
    pub media_key_timestamp: i64,
}

impl MediaUploadInfo {
    pub fn new(
        direct_path: String,
        media_key: [u8; 32],
        file_sha256: [u8; 32],
        file_enc_sha256: [u8; 32],
        file_length: u64,
        media_key_timestamp: i64,
    ) -> Self {
        Self {
            direct_path,
            media_key,
            file_sha256,
            file_enc_sha256,
            file_length,
            media_key_timestamp,
        }
    }
}

const MAX_STICKERS: usize = 60;

/// Bundles stickers into a store-only ZIP and builds proto metadata.
/// Filenames use `{base64url(sha256)}.webp`. Identical stickers are deduplicated.
pub fn create_sticker_pack_zip(
    pack_id: &str,
    stickers: &[StickerInput],
    cover: &[u8],
) -> Result<StickerPackZipResult> {
    if pack_id.is_empty()
        || pack_id.len() > 128
        || pack_id
            .bytes()
            .any(|b| b == b'/' || b == b'\\' || b == b'.' || b < 0x20)
    {
        bail!(
            "invalid pack_id: must be non-empty, <= 128 bytes, no path separators or control chars"
        );
    }
    if stickers.is_empty() {
        bail!("sticker pack must contain at least 1 sticker");
    }
    if stickers.len() > MAX_STICKERS {
        bail!(
            "sticker pack exceeds maximum of {} stickers (got {})",
            MAX_STICKERS,
            stickers.len()
        );
    }

    let mut zip = ZipWriter::new();
    let mut proto_stickers = Vec::with_capacity(stickers.len());

    let tray_icon_file_name = format!("{pack_id}.webp");
    zip.add_file(&tray_icon_file_name, cover);

    let mut seen_hashes = std::collections::HashSet::new();

    for input in stickers {
        let hash: [u8; 32] = Sha256::digest(input.data).into();
        let file_name = format!("{}.webp", base64url_encode(&hash));

        if seen_hashes.insert(hash) {
            zip.add_file(&file_name, input.data);
        }

        let is_animated = webp::is_animated(input.data);
        proto_stickers.push(wa::message::sticker_pack_message::Sticker {
            file_name: Some(file_name),
            is_animated: Some(is_animated),
            emojis: input.emojis.clone(),
            accessibility_label: input.accessibility_label.clone(),
            is_lottie: Some(false),
            mimetype: Some("image/webp".to_string()),
            ..Default::default()
        });
    }

    Ok(StickerPackZipResult {
        zip_bytes: zip.finish(),
        stickers: proto_stickers,
        tray_icon_file_name,
    })
}

/// Builds a `wa::Message` with `StickerPackMessage` from upload results.
///
/// Proto fields match WA Web's `GenerateStickerPackMessageProto.js` exactly.
/// Caller must supply a JPEG thumbnail uploaded with the same `media_key` as
/// the zip (via `UploadOptions::with_media_key(zip_upload.media_key)`).
///
/// # Errors
///
/// Returns an error if the thumbnail was uploaded with a different media key
/// than the zip, since the proto only carries one `media_key` for both.
pub fn build_sticker_pack_message(
    zip_result: &StickerPackZipResult,
    zip_upload: &MediaUploadInfo,
    thumb_upload: &MediaUploadInfo,
    metadata: StickerPackMetadata,
) -> Result<wa::Message> {
    if zip_upload.media_key != thumb_upload.media_key {
        bail!("thumbnail must be uploaded with the same media_key as the zip");
    }

    let pack_msg = wa::message::StickerPackMessage {
        sticker_pack_id: Some(metadata.pack_id),
        name: Some(metadata.name),
        publisher: Some(metadata.publisher),
        stickers: zip_result.stickers.clone(),
        file_length: Some(zip_upload.file_length),
        file_sha256: Some(zip_upload.file_sha256.to_vec()),
        file_enc_sha256: Some(zip_upload.file_enc_sha256.to_vec()),
        media_key: Some(zip_upload.media_key.to_vec()),
        direct_path: Some(zip_upload.direct_path.clone()),
        caption: metadata.caption,
        pack_description: metadata.description,
        thumbnail_sha256: Some(thumb_upload.file_sha256.to_vec()),
        thumbnail_enc_sha256: Some(thumb_upload.file_enc_sha256.to_vec()),
        thumbnail_direct_path: Some(thumb_upload.direct_path.clone()),
        sticker_pack_size: Some(zip_result.zip_bytes.len() as u64),
        tray_icon_file_name: Some(zip_result.tray_icon_file_name.clone()),
        ..Default::default()
    };

    Ok(wa::Message {
        sticker_pack_message: buffa::MessageField::some(pack_msg),
        ..Default::default()
    })
}

fn base64url_encode(data: &[u8]) -> String {
    use base64::engine::{Engine, general_purpose::URL_SAFE_NO_PAD};
    URL_SAFE_NO_PAD.encode(data)
}

// --- First-party sticker pack fetch (download side) ---

use crate::download::{Downloadable, MediaType};
use serde::Deserialize;

/// Static CDN endpoint serving first-party sticker pack metadata.
const STICKER_CDN_BASE: &str = "https://static.whatsapp.net/sticker";

/// Build the URL that returns a pack's metadata + sticker list as JSON.
///
/// WA Web: `WAWebFetchFirstPartyStickerPacksAction` queries the same endpoint
/// with `cat=sticker_pack_data&id=<pack>&lg=<locale>`; `lottie=1` (from
/// `getStickerFetchParamsFromABConfig`) makes lottie packs return lottie data.
pub fn sticker_pack_data_url(pack_id: &str, locale: &str) -> String {
    format!("{STICKER_CDN_BASE}?lottie=1&cat=sticker_pack_data&id={pack_id}&lg={locale}")
}

/// Base64-standard JSON string into bytes; absent/empty becomes `None`.
/// The CDN encodes `media-key`/`file-hash`/`enc-file-hash` as base64 strings
/// (matching Go's `[]byte` JSON unmarshalling in whatsmeow).
fn de_b64_opt<'de, D>(d: D) -> Result<Option<Vec<u8>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use base64::engine::{Engine, general_purpose::STANDARD};
    let raw = Option::<String>::deserialize(d)?;
    match raw {
        Some(s) if !s.is_empty() => STANDARD
            .decode(s)
            .map(Some)
            .map_err(serde::de::Error::custom),
        _ => Ok(None),
    }
}

/// One sticker inside a first-party pack, as returned by the CDN.
///
/// Implements [`Downloadable`] (as a `Sticker`) so each entry can be fetched
/// directly. Unknown JSON fields are ignored.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct StickerPackItem {
    #[serde(default, rename = "media-key", deserialize_with = "de_b64_opt")]
    pub media_key: Option<Vec<u8>>,
    #[serde(default, rename = "file-hash", deserialize_with = "de_b64_opt")]
    pub file_hash: Option<Vec<u8>>,
    #[serde(default, rename = "enc-file-hash", deserialize_with = "de_b64_opt")]
    pub enc_file_hash: Option<Vec<u8>>,
    #[serde(default, rename = "direct-path")]
    pub direct_path: Option<String>,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default, rename = "file-size")]
    pub file_size: Option<u64>,
    #[serde(default)]
    pub mimetype: Option<String>,
    #[serde(default)]
    pub width: Option<u32>,
    #[serde(default)]
    pub height: Option<u32>,
    #[serde(default)]
    pub emojis: Vec<String>,
    #[serde(default, rename = "accessibility-text")]
    pub accessibility_text: Option<String>,
}

impl Downloadable for StickerPackItem {
    fn direct_path(&self) -> Option<&str> {
        self.direct_path.as_deref()
    }
    fn media_key(&self) -> Option<&[u8]> {
        self.media_key.as_deref()
    }
    fn file_enc_sha256(&self) -> Option<&[u8]> {
        self.enc_file_hash.as_deref()
    }
    fn file_sha256(&self) -> Option<&[u8]> {
        self.file_hash.as_deref()
    }
    fn file_length(&self) -> Option<u64> {
        self.file_size
    }
    fn app_info(&self) -> MediaType {
        MediaType::Sticker
    }
}

/// A first-party sticker pack fetched from the CDN.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct StickerPack {
    #[serde(default, rename = "sticker-pack-id")]
    pub sticker_pack_id: Option<String>,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub publisher: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default, rename = "file-size")]
    pub file_size: Option<String>,
    #[serde(default, rename = "image-data-hash")]
    pub image_data_hash: Option<String>,
    #[serde(default)]
    pub stickers: Vec<StickerPackItem>,
    #[serde(default)]
    pub animated: i32,
    #[serde(default)]
    pub lottie: i32,
    #[serde(default, rename = "preview-image-ids")]
    pub preview_image_ids: Vec<String>,
    #[serde(default, rename = "tray-image-id")]
    pub tray_image_id: Option<String>,
    #[serde(default, rename = "tray-image-preview")]
    pub tray_image_preview: Option<String>,
}

/// Parse the CDN response (a JSON array) and return its first pack.
///
/// WA Web treats an empty array as an error; so do we.
pub fn parse_sticker_pack_response(body: &[u8]) -> Result<StickerPack> {
    let packs: Vec<StickerPack> = serde_json::from_slice(body)
        .map_err(|e| anyhow::anyhow!("failed to parse sticker pack response: {e}"))?;
    packs
        .into_iter()
        .next()
        .ok_or_else(|| anyhow::anyhow!("no sticker pack found in response"))
}

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

    fn dummy_webp(extra: u8) -> Vec<u8> {
        // Minimal valid-ish WebP (just RIFF+WEBP+VP8 header, not animated)
        let mut buf = Vec::new();
        buf.extend_from_slice(b"RIFF");
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(b"WEBP");
        buf.extend_from_slice(b"VP8 ");
        buf.extend_from_slice(&4u32.to_le_bytes());
        buf.extend_from_slice(&[extra, 0, 0, 0]);
        let riff_size = (buf.len() - 8) as u32;
        buf[4..8].copy_from_slice(&riff_size.to_le_bytes());
        buf
    }

    #[test]
    fn create_zip_basic() {
        let s1 = dummy_webp(1);
        let s2 = dummy_webp(2);
        let cover = dummy_webp(0);

        let stickers = vec![StickerInput::new(&s1), StickerInput::new(&s2)];
        let result = create_sticker_pack_zip("test-pack", &stickers, &cover).unwrap();

        assert_eq!(result.stickers.len(), 2);
        assert_eq!(result.tray_icon_file_name, "test-pack.webp");
        assert!(
            result.stickers[0]
                .file_name
                .as_ref()
                .unwrap()
                .ends_with(".webp")
        );
        assert!(
            result.stickers[1]
                .file_name
                .as_ref()
                .unwrap()
                .ends_with(".webp")
        );
        assert_ne!(result.stickers[0].file_name, result.stickers[1].file_name);
        // ZIP should start with local file header magic
        assert_eq!(&result.zip_bytes[0..4], &[0x50, 0x4B, 0x03, 0x04]);
    }

    #[test]
    fn create_zip_deduplication() {
        let s1 = dummy_webp(1);
        let cover = dummy_webp(0);

        // Two identical stickers
        let stickers = vec![StickerInput::new(&s1), StickerInput::new(&s1)];
        let result = create_sticker_pack_zip("dedup-test", &stickers, &cover).unwrap();

        // Both proto entries exist with same filename
        assert_eq!(result.stickers.len(), 2);
        assert_eq!(result.stickers[0].file_name, result.stickers[1].file_name);

        // But ZIP should be smaller than if we added both (only 2 entries: cover + 1 sticker)
        let s2 = dummy_webp(2);
        let non_dedup_stickers = vec![StickerInput::new(&s1), StickerInput::new(&s2)];
        let non_dedup =
            create_sticker_pack_zip("dedup-test2", &non_dedup_stickers, &cover).unwrap();
        assert!(result.zip_bytes.len() < non_dedup.zip_bytes.len());
    }

    #[test]
    fn create_zip_empty_rejected() {
        let cover = dummy_webp(0);
        let result = create_sticker_pack_zip("empty", &[], &cover);
        assert!(result.is_err());
    }

    #[test]
    fn create_zip_too_many_rejected() {
        let sticker = dummy_webp(1);
        let cover = dummy_webp(0);
        let stickers: Vec<_> = (0..61).map(|_| StickerInput::new(&sticker)).collect();
        let result = create_sticker_pack_zip("big", &stickers, &cover);
        assert!(result.is_err());
    }

    #[test]
    fn create_zip_with_emojis() {
        let s1 = dummy_webp(1);
        let cover = dummy_webp(0);

        let stickers = vec![
            StickerInput::new(&s1)
                .with_emojis(vec!["😀".into(), "🎉".into()])
                .with_accessibility_label("happy face".into()),
        ];
        let result = create_sticker_pack_zip("emoji-test", &stickers, &cover).unwrap();

        let sticker = &result.stickers[0];
        assert_eq!(sticker.emojis, vec!["😀", "🎉"]);
        assert_eq!(sticker.accessibility_label.as_deref(), Some("happy face"));
    }

    #[test]
    fn invalid_pack_id_rejected() {
        let s = dummy_webp(1);
        let cover = dummy_webp(0);
        let stickers = vec![StickerInput::new(&s)];

        assert!(create_sticker_pack_zip("", &stickers, &cover).is_err());
        assert!(create_sticker_pack_zip("../evil", &stickers, &cover).is_err());
        assert!(create_sticker_pack_zip("a/b", &stickers, &cover).is_err());
        assert!(create_sticker_pack_zip("a\\b", &stickers, &cover).is_err());
        assert!(create_sticker_pack_zip("has.dot", &stickers, &cover).is_err());
        assert!(create_sticker_pack_zip("valid-pack_id", &stickers, &cover).is_ok());
    }

    #[test]
    fn build_message_fields() {
        let s1 = dummy_webp(1);
        let cover = dummy_webp(0);
        let stickers = vec![StickerInput::new(&s1)];
        let zip_result = create_sticker_pack_zip("msg-test", &stickers, &cover).unwrap();

        let zip_upload = MediaUploadInfo::new(
            "/mms/sticker-pack/abc".into(),
            [0u8; 32],
            [1u8; 32],
            [2u8; 32],
            zip_result.zip_bytes.len() as u64,
            1234567890,
        );
        let thumb_upload = MediaUploadInfo::new(
            "/mms/thumbnail-sticker-pack/def".into(),
            [0u8; 32],
            [3u8; 32],
            [4u8; 32],
            1000,
            1234567890,
        );

        let metadata = StickerPackMetadata::new(
            "msg-test".into(),
            "Test Pack".into(),
            "Test Publisher".into(),
        )
        .with_description("A test pack".into());

        let msg =
            build_sticker_pack_message(&zip_result, &zip_upload, &thumb_upload, metadata).unwrap();
        let pack = msg.sticker_pack_message.as_option().unwrap();

        assert_eq!(pack.sticker_pack_id.as_deref(), Some("msg-test"));
        assert_eq!(pack.name.as_deref(), Some("Test Pack"));
        assert_eq!(pack.publisher.as_deref(), Some("Test Publisher"));
        assert_eq!(pack.pack_description.as_deref(), Some("A test pack"));
        assert_eq!(pack.stickers.len(), 1);
        assert_eq!(pack.direct_path.as_deref(), Some("/mms/sticker-pack/abc"));
        assert_eq!(
            pack.thumbnail_direct_path.as_deref(),
            Some("/mms/thumbnail-sticker-pack/def")
        );
        assert_eq!(pack.tray_icon_file_name.as_deref(), Some("msg-test.webp"));
        // WA Web doesn't set these on outgoing sticker packs
        assert_eq!(pack.thumbnail_height, None);
        assert_eq!(pack.thumbnail_width, None);
        assert_eq!(pack.sticker_pack_origin, None);
        assert_eq!(pack.media_key_timestamp, None);
        assert_eq!(pack.image_data_hash, None);
    }

    #[test]
    fn sticker_pack_data_url_matches_wa_web_shape() {
        let url = sticker_pack_data_url("PACK123", "en");
        assert_eq!(
            url,
            "https://static.whatsapp.net/sticker?lottie=1&cat=sticker_pack_data&id=PACK123&lg=en"
        );
    }

    #[test]
    fn parse_sticker_pack_response_decodes_items() {
        use base64::engine::{Engine, general_purpose::STANDARD};
        let media_key = STANDARD.encode([1u8; 32]);
        let file_hash = STANDARD.encode([2u8; 32]);
        let enc_file_hash = STANDARD.encode([3u8; 32]);
        let body = format!(
            r#"[{{
                "sticker-pack-id": "PACK123",
                "name": "Cats",
                "publisher": "Me",
                "file-size": "1234",
                "animated": 1,
                "lottie": 0,
                "preview-image-ids": ["a", "b"],
                "tray-image-id": "tray1",
                "stickers": [{{
                    "media-key": "{media_key}",
                    "file-hash": "{file_hash}",
                    "enc-file-hash": "{enc_file_hash}",
                    "direct-path": "/mms/sticker/abc",
                    "url": "https://mmg.whatsapp.net/x",
                    "file-size": 555,
                    "mimetype": "image/webp",
                    "width": 512,
                    "height": 512,
                    "emojis": ["🐱"],
                    "accessibility-text": "a cat",
                    "some-unknown-field": "ignored"
                }}]
            }}]"#
        );

        let pack = parse_sticker_pack_response(body.as_bytes()).unwrap();
        assert_eq!(pack.sticker_pack_id.as_deref(), Some("PACK123"));
        assert_eq!(pack.name.as_deref(), Some("Cats"));
        assert_eq!(pack.file_size.as_deref(), Some("1234"));
        assert_eq!(pack.animated, 1);
        assert_eq!(pack.preview_image_ids, vec!["a", "b"]);
        assert_eq!(pack.stickers.len(), 1);

        let item = &pack.stickers[0];
        assert_eq!(item.media_key.as_deref(), Some(&[1u8; 32][..]));
        assert_eq!(item.file_hash.as_deref(), Some(&[2u8; 32][..]));
        assert_eq!(item.enc_file_hash.as_deref(), Some(&[3u8; 32][..]));
        assert_eq!(item.file_size, Some(555));
        assert_eq!(item.emojis, vec!["🐱"]);

        // Downloadable mapping feeds the standard sticker media download.
        assert_eq!(item.direct_path(), Some("/mms/sticker/abc"));
        assert_eq!(item.media_key(), Some(&[1u8; 32][..]));
        assert_eq!(item.file_sha256(), Some(&[2u8; 32][..]));
        assert_eq!(item.file_enc_sha256(), Some(&[3u8; 32][..]));
        assert_eq!(item.file_length(), Some(555));
        assert_eq!(item.app_info(), MediaType::Sticker);
        assert!(item.is_encrypted());
    }

    #[test]
    fn parse_sticker_pack_response_rejects_empty_array() {
        assert!(parse_sticker_pack_response(b"[]").is_err());
    }
}