Skip to main content

wechat_protocol/
sticker_packs.rs

1//! Official pack metadata reads and membership requests. Media acquisition and
2//! profile installation are separate operations; these records contain private URLs.
3use crate::{protobuf as p, AccountState, NativeClient};
4use anyhow::{ensure, Result};
5use serde::{Deserialize, Serialize};
6
7/// Feed selected by the supported Linux pack-list producer.
8#[derive(Clone, Copy, Debug)]
9pub enum StickerPackFeed {
10    /// Available public feed; reaching its end does not imply a global inventory.
11    Catalog,
12    /// Complete account membership, including packs absent from the public feed.
13    Added,
14}
15/// Transport-level summary. Protect URLs and the retained original record.
16#[derive(Clone, Serialize, Deserialize)]
17pub struct StickerPackSummary {
18    /// Official product ID.
19    pub id: String,
20    /// Display name.
21    pub name: String,
22    /// Display description, independent of the Linux SQL introduction column.
23    pub description: String,
24    /// Private pack icon source.
25    pub icon_url: String,
26    /// Private cover source.
27    pub cover_url: String,
28    /// Numbered type flags; only the corroborated free class is eligible.
29    pub pack_type: u32,
30    /// Native flags; do not infer entitlement from a price string.
31    pub flags: u32,
32    /// Native expiry, zero when unspecified.
33    pub expiry: u32,
34    /// Full original summary for exact profile mapping and unknown extensions.
35    pub raw: Vec<u8>,
36}
37/// One list page. Callers enforce cursor progress, aggregate limits and deduplication.
38#[derive(Clone, Serialize, Deserialize)]
39pub struct StickerPackPage {
40    /// Returned summaries in the service's order.
41    pub items: Vec<StickerPackSummary>,
42    /// Opaque continuation bytes from the native buffer.
43    pub next_cursor: Vec<u8>,
44    /// Only BaseResponse.Ret zero establishes a complete list.
45    pub complete: bool,
46    /// Ret3 invalidates this pagination sequence; restart as a new read.
47    pub restart: bool,
48    /// Complete reply, to retain before projection.
49    pub raw: Vec<u8>,
50}
51/// One remote pack item. Dimensions and byte lengths require verified media.
52#[derive(Clone, Serialize, Deserialize)]
53pub struct StickerPackItem {
54    /// Original media identity.
55    pub id: String,
56    /// Private original source URL.
57    pub original_url: String,
58    /// Private thumbnail source URL.
59    pub thumbnail_url: String,
60    /// Full item record including unsupported alternate representations.
61    pub raw: Vec<u8>,
62}
63/// Pack detail, independent of account membership and downloaded content.
64#[derive(Clone, Serialize, Deserialize)]
65pub struct StickerPackDetail {
66    /// Product metadata, decoded with the detail field layout.
67    pub summary: StickerPackSummary,
68    /// Complete supplied content list; an empty result is not invented content.
69    pub items: Vec<StickerPackItem>,
70    /// Original full response.
71    pub raw: Vec<u8>,
72}
73/// Localized captions supplied for one pack item.
74#[derive(Clone, Serialize, Deserialize)]
75pub struct StickerPackCaption {
76    /// Content MD5 used to join the row to an item.
77    pub id: String,
78    /// Official language/text pairs; empty values are omitted.
79    pub captions: Vec<(String, String)>,
80}
81/// Caption response retained separately from pack content readiness.
82#[derive(Clone, Serialize, Deserialize)]
83pub struct StickerPackCaptions {
84    /// Caption rows in service order.
85    pub items: Vec<StickerPackCaption>,
86    /// Original response, retaining unassigned flags.
87    pub raw: Vec<u8>,
88}
89fn product(id: &str) -> Result<()> {
90    ensure!(
91        !id.is_empty() && id.len() <= 1024 && !id.chars().any(char::is_control),
92        "invalid_sticker_pack_id"
93    );
94    Ok(())
95}
96fn md5(id: &str) -> Result<()> {
97    ensure!(
98        id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit()),
99        "invalid_sticker_id"
100    );
101    Ok(())
102}
103fn string(fields: &[p::Field], n: u32) -> Result<String> {
104    let bytes = p::optional_data(fields, n)?.unwrap_or_default();
105    ensure!(bytes.len() <= 16384, "sticker_metadata_limit");
106    Ok(std::str::from_utf8(bytes)?.into())
107}
108fn scalar(fields: &[p::Field], n: u32) -> Result<u32> {
109    match p::optional(fields, n)? {
110        Some(p::Value::Varint(value)) => Ok(u32::try_from(*value)?),
111        None => Ok(0),
112        _ => anyhow::bail!("invalid_sticker_pack_scalar"),
113    }
114}
115fn repeated(fields: &[p::Field], n: u32) -> Result<Vec<&[u8]>> {
116    let mut items = vec![];
117    for field in fields.iter().filter(|field| field.number == n) {
118        ensure!(items.len() < 1000, "sticker_pack_item_limit");
119        let p::Value::Bytes(bytes) = &field.value else {
120            anyhow::bail!("invalid_sticker_pack_record")
121        };
122        items.push(bytes.as_slice());
123    }
124    Ok(items)
125}
126fn summary(raw: &[u8], detail: bool) -> Result<StickerPackSummary> {
127    let fields = p::decode(raw)?;
128    let id = string(&fields, 1)?;
129    product(&id)?;
130    Ok(StickerPackSummary {
131        id,
132        name: string(&fields, 3)?,
133        description: string(&fields, 4)?,
134        icon_url: string(&fields, 2)?,
135        cover_url: string(&fields, if detail { 11 } else { 9 })?,
136        pack_type: scalar(&fields, 7)?,
137        flags: scalar(&fields, 8)?,
138        expiry: scalar(&fields, if detail { 12 } else { 10 })?,
139        raw: raw.into(),
140    })
141}
142/// Encode an initial or continuation feed read with native mode/context pairs.
143pub fn sticker_pack_list_request(
144    state: &AccountState,
145    feed: StickerPackFeed,
146    cursor: &[u8],
147) -> Result<Vec<u8>> {
148    ensure!(cursor.len() <= 65536, "sticker_cursor_limit");
149    let (mode, context) = match feed {
150        StickerPackFeed::Catalog => (5, 5),
151        StickerPackFeed::Added => (8, 13),
152    };
153    p::message(&[
154        p::bytes(1, &crate::wire::base_request(&state.device, state.uin, 0)?),
155        p::bytes(2, &p::buffer(cursor)),
156        p::uint(3, mode),
157        p::uint(4, context),
158    ])
159}
160/// Decode list completion from BaseResponse.Ret, preserving a restart outcome.
161pub fn decode_sticker_pack_page(raw: &[u8]) -> Result<StickerPackPage> {
162    let fields = p::decode(raw)?;
163    let code = p::base_code(&fields)?;
164    ensure!(matches!(code, 0 | 2 | 3), "sticker_pack_list_rejected");
165    let items = repeated(&fields, 4)?
166        .into_iter()
167        .map(|raw| summary(raw, false))
168        .collect::<Result<Vec<_>>>()?;
169    let cursor = p::optional_data(&fields, 2)?
170        .map(p::unbuffer)
171        .transpose()?
172        .unwrap_or_default();
173    ensure!(cursor.len() <= 65536, "sticker_cursor_limit");
174    Ok(StickerPackPage {
175        items,
176        next_cursor: cursor,
177        complete: code == 0,
178        restart: code == 3,
179        raw: raw.into(),
180    })
181}
182/// Encode detail read; field4 is signed int32 minus one, not uint32 max.
183pub fn sticker_pack_detail_request(state: &AccountState, id: &str) -> Result<Vec<u8>> {
184    product(id)?;
185    p::message(&[
186        p::bytes(1, &crate::wire::base_request(&state.device, state.uin, 0)?),
187        p::bytes(2, id.as_bytes()),
188        p::uint(3, 3),
189        p::int32(4, -1),
190    ])
191}
192/// Decode a detail and its per-item extension, checking requested product identity.
193pub fn decode_sticker_pack_detail(raw: &[u8], expected: &str) -> Result<StickerPackDetail> {
194    let fields = p::decode(raw)?;
195    ensure!(p::base_code(&fields)? == 0, "sticker_pack_detail_rejected");
196    let summary = summary(p::data(&fields, 2)?, true)?;
197    ensure!(summary.id == expected, "sticker_pack_identity_mismatch");
198    let mut items = vec![];
199    for raw in repeated(&fields, 3)? {
200        let fields = p::decode(raw)?;
201        let id = string(&fields, 1)?.to_ascii_lowercase();
202        md5(&id)?;
203        ensure!(
204            !items.iter().any(|item: &StickerPackItem| item.id == id),
205            "sticker_pack_duplicate_item"
206        );
207        items.push(StickerPackItem {
208            id,
209            original_url: string(&fields, 2)?,
210            thumbnail_url: string(&fields, 3)?,
211            raw: raw.into(),
212        });
213    }
214    Ok(StickerPackDetail {
215        summary,
216        items,
217        raw: raw.into(),
218    })
219}
220/// Encode a localized-caption read without starting any media acquisition.
221pub fn sticker_pack_captions_request(state: &AccountState, id: &str) -> Result<Vec<u8>> {
222    product(id)?;
223    p::message(&[
224        p::bytes(1, &crate::wire::base_request(&state.device, state.uin, 0)?),
225        p::bytes(2, id.as_bytes()),
226    ])
227}
228/// Decode captions by MD5/language rather than assuming positional correspondence.
229pub fn decode_sticker_pack_captions(raw: &[u8]) -> Result<StickerPackCaptions> {
230    let fields = p::decode(raw)?;
231    ensure!(
232        p::base_code(&fields)? == 0,
233        "sticker_pack_captions_rejected"
234    );
235    let mut items = vec![];
236    for raw in repeated(&fields, 3)? {
237        let fields = p::decode(raw)?;
238        let id = string(&fields, 1)?.to_ascii_lowercase();
239        md5(&id)?;
240        let mut captions = vec![];
241        for raw in repeated(&fields, 3)? {
242            let pair = p::decode(raw)?;
243            let lang = string(&pair, 1)?;
244            let text = string(&pair, 2)?;
245            if !lang.is_empty() && !text.is_empty() {
246                ensure!(
247                    !captions.iter().any(|(l, _)| l == &lang),
248                    "sticker_caption_duplicate_language"
249                );
250                captions.push((lang, text));
251            }
252        }
253        items.push(StickerPackCaption { id, captions });
254    }
255    Ok(StickerPackCaptions {
256        items,
257        raw: raw.into(),
258    })
259}
260/// Encode free-pack membership. This is neither a purchase nor content download.
261pub fn sticker_pack_membership_request(
262    state: &AccountState,
263    id: &str,
264    added: bool,
265) -> Result<Vec<u8>> {
266    product(id)?;
267    p::message(&[
268        p::bytes(1, &crate::wire::base_request(&state.device, state.uin, 0)?),
269        p::bytes(2, id.as_bytes()),
270        p::uint(3, if added { 1 } else { 2 }),
271    ])
272}
273/// Request an archive locator for one eligible free pack. This does not add
274/// membership. Retain the raw acknowledgement before interpreting its locator.
275pub fn sticker_pack_acquisition_request(state: &AccountState, id: &str) -> Result<Vec<u8>> {
276    product(id)?;
277    p::message(&[
278        p::bytes(1, &crate::wire::base_request(&state.device, state.uin, 0)?),
279        p::bytes(2, id.as_bytes()),
280        p::uint(4, 0),
281        p::uint(5, 0),
282    ])
283}
284/// Decode the response-bound file-ID, AES key and exact plaintext archive size.
285/// The result contains credentials and must not appear in logs or public results.
286pub fn decode_sticker_pack_acquisition(raw: &[u8]) -> Result<crate::media::MediaDescriptor> {
287    let fields = p::decode(raw)?;
288    ensure!(
289        p::base_code(&fields)? == 0,
290        "sticker_pack_acquisition_rejected"
291    );
292    let locator = p::decode(p::data(&fields, 2)?)?;
293    let file_id = string(&locator, 1)?;
294    let key = string(&locator, 2)?;
295    let size = u32::try_from(p::scalar(&locator, 3)?)?;
296    ensure!(
297        !file_id.is_empty()
298            && file_id.len() <= 8192
299            && !file_id.chars().any(char::is_control)
300            && key.len() == 32
301            && key.bytes().all(|b| b.is_ascii_hexdigit())
302            && size > 0
303            && size <= 16 * 1024 * 1024,
304        "invalid_sticker_pack_locator"
305    );
306    Ok(crate::media::MediaDescriptor {
307        file_id,
308        aes_key: hex::decode(key)?,
309        quality: crate::media::MediaQuality::File,
310        expected_bytes: Some(u64::from(size)),
311        expected_md5: None,
312        strict_size: true,
313        expires_at: None,
314    })
315}
316impl NativeClient {
317    pub(crate) fn sticker_pack_rpc_snapshot(
318        &self,
319        state: &mut AccountState,
320        cgi: u16,
321        request: &[u8],
322    ) -> Result<Vec<u8>> {
323        let path = match cgi {
324            411 => "/cgi-bin/micromsg-bin/getemotionlist",
325            412 => "/cgi-bin/micromsg-bin/getemotiondetail",
326            521 => "/cgi-bin/micromsg-bin/getemotiondesc",
327            413 => "/cgi-bin/micromsg-bin/modemotionpack",
328            423 => "/cgi-bin/micromsg-bin/exchangeemotionpack",
329            _ => anyhow::bail!("unsupported_sticker_pack_request"),
330        };
331        self.authenticated_rpc(state, cgi, path, request)
332    }
333}
334#[cfg(test)]
335mod tests {
336    use super::*;
337    #[test]
338    fn list_ret_controls_continuation_and_unknown_fields_survive() {
339        let item = p::message(&[
340            p::bytes(1, b"pack.fixture"),
341            p::bytes(2, b"https://example.invalid/icon"),
342            p::bytes(3, b"Fixture"),
343            p::uint(7, 4),
344            p::uint(8, 0),
345            p::bytes(13, b"gray"),
346        ])
347        .unwrap();
348        let raw = p::message(&[
349            p::bytes(1, &p::int32(1, 2)),
350            p::bytes(2, &p::buffer(b"next")),
351            p::uint(3, 0),
352            p::bytes(4, &item),
353            p::uint(99, 7),
354        ])
355        .unwrap();
356        let page = decode_sticker_pack_page(&raw).unwrap();
357        assert!(!page.complete);
358        assert_eq!(page.next_cursor, b"next");
359        assert_eq!(page.items[0].name, "Fixture");
360        assert_eq!(page.raw, raw);
361        let done = p::message(&[p::bytes(1, &p::int32(1, 0)), p::uint(3, 999)]).unwrap();
362        assert!(decode_sticker_pack_page(&done).unwrap().complete);
363    }
364    #[test]
365    fn detail_tail_and_item_identity_use_their_own_layout() {
366        let id = "00000000000000000000000000000000";
367        let detail = p::message(&[
368            p::bytes(1, b"pack.fixture"),
369            p::bytes(11, b"cover"),
370            p::uint(12, 99),
371        ])
372        .unwrap();
373        let item = p::message(&[
374            p::bytes(1, id.as_bytes()),
375            p::bytes(2, b"original"),
376            p::bytes(3, b"thumb"),
377        ])
378        .unwrap();
379        let raw = p::message(&[
380            p::bytes(1, &p::int32(1, 0)),
381            p::bytes(2, &detail),
382            p::bytes(3, &item),
383        ])
384        .unwrap();
385        let parsed = decode_sticker_pack_detail(&raw, "pack.fixture").unwrap();
386        assert_eq!(parsed.summary.cover_url, "cover");
387        assert_eq!(parsed.summary.expiry, 99);
388        assert_eq!(parsed.items[0].id, id);
389        assert!(decode_sticker_pack_detail(&raw, "other").is_err());
390        assert_eq!(hex::encode(p::int32(4, -1)), "20ffffffffffffffffff01");
391    }
392}