Skip to main content

wechat_protocol/
custom_stickers.rs

1//! Custom collection reads and mutations, separate from sticker chat sends.
2use crate::{protobuf as p, AccountState, NativeClient};
3use anyhow::{ensure, Result};
4use serde::{Deserialize, Serialize};
5
6fn valid_id(id: &str) -> bool {
7    id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit())
8}
9fn string(fields: &[p::Field], number: u32) -> Result<Option<String>> {
10    p::optional_data(fields, number)?
11        .map(|bytes| {
12            ensure!(bytes.len() <= 16384, "sticker_metadata_limit");
13            Ok(std::str::from_utf8(bytes)?.to_owned())
14        })
15        .transpose()
16}
17/// Private transport metadata. These URLs and keys must not be exposed by an API.
18#[derive(Clone, Serialize, Deserialize)]
19pub struct CustomStickerMetadata {
20    /// Content MD5.
21    pub id: String,
22    /// Original source URL, if supplied.
23    pub original_url: Option<String>,
24    /// Thumbnail source URL, if supplied.
25    pub thumbnail_url: Option<String>,
26    /// Full original record, retaining unassigned transport and extension fields.
27    pub raw: Vec<u8>,
28}
29/// One custom-collection response, retained before profile writeback.
30#[derive(Clone, Serialize, Deserialize)]
31pub struct CustomStickerPage {
32    /// Content identities in server order.
33    pub ids: Vec<String>,
34    /// Available per-item metadata; match by identity, not array position.
35    pub metadata: Vec<CustomStickerMetadata>,
36    /// Native continuation index; absence remains absence.
37    pub next_index: Option<u32>,
38    /// Native opaque continuation bytes.
39    pub next_data: Vec<u8>,
40    /// True only when the completion predicate is satisfied.
41    pub complete: bool,
42    /// Server version extension, used only after a complete list.
43    pub version: Option<String>,
44    /// Original response, including fields unknown to this decoder.
45    pub raw: Vec<u8>,
46}
47/// Encode a custom-list page. Initial cursor is index zero with empty data.
48pub fn custom_sticker_list_request(index: u32, data: &[u8]) -> Result<Vec<u8>> {
49    ensure!(data.len() <= 65536, "sticker_cursor_limit");
50    p::message(&[
51        p::uint(1, index.into()),
52        p::uint(2, 2),
53        p::uint(4, 0),
54        p::bytes(5, data),
55    ])
56}
57/// Encode a bounded metadata request for known collection identities.
58pub fn custom_sticker_metadata_request(ids: &[String]) -> Result<Vec<u8>> {
59    ensure!(
60        !ids.is_empty() && ids.len() <= 100 && ids.iter().all(|id| valid_id(id)),
61        "invalid_sticker_ids"
62    );
63    let mut fields = vec![p::uint(1, 0), p::uint(2, 1)];
64    fields.extend(ids.iter().map(|id| p::bytes(3, id.as_bytes())));
65    p::message(&fields)
66}
67/// Decode the shared list/metadata response without requiring generated fields
68/// that the service omits. Callers enforce advancing cursors and page limits.
69pub fn decode_custom_stickers(raw: &[u8]) -> Result<CustomStickerPage> {
70    let fields = p::decode(raw)?;
71    ensure!(p::base_code(&fields)? == 0, "custom_stickers_rejected");
72    let mut ids = Vec::new();
73    let mut metadata = Vec::new();
74    for field in &fields {
75        if field.number == 3 {
76            let p::Value::Bytes(bytes) = &field.value else {
77                anyhow::bail!("invalid_sticker_id");
78            };
79            let id = std::str::from_utf8(bytes)?.to_ascii_lowercase();
80            ensure!(
81                valid_id(&id) && ids.len() < 10000 && !ids.contains(&id),
82                "invalid_sticker_id"
83            );
84            ids.push(id);
85        }
86        if field.number == 5 {
87            let p::Value::Bytes(bytes) = &field.value else {
88                anyhow::bail!("invalid_sticker_metadata");
89            };
90            ensure!(metadata.len() < 10000, "sticker_metadata_limit");
91            let item = p::decode(bytes)?;
92            let id = string(&item, 1)?.unwrap_or_default().to_ascii_lowercase();
93            ensure!(
94                valid_id(&id)
95                    && !metadata
96                        .iter()
97                        .any(|item: &CustomStickerMetadata| item.id == id),
98                "invalid_sticker_id"
99            );
100            metadata.push(CustomStickerMetadata {
101                id,
102                original_url: string(&item, 2)?,
103                thumbnail_url: string(&item, 3)?,
104                raw: bytes.clone(),
105            });
106        }
107    }
108    let next_index = p::optional(&fields, 2)?
109        .map(|value| match value {
110            p::Value::Varint(value) => Ok(u32::try_from(*value)?),
111            _ => anyhow::bail!("invalid_sticker_cursor"),
112        })
113        .transpose()?;
114    let complete = ids.is_empty()
115        || match p::optional(&fields, 4)? {
116            Some(p::Value::Varint(value)) => *value != 0,
117            None => false,
118            _ => anyhow::bail!("invalid_sticker_completion"),
119        };
120    let next_data = p::optional_data(&fields, 6)?.unwrap_or_default().to_vec();
121    ensure!(next_data.len() <= 65536, "sticker_cursor_limit");
122    Ok(CustomStickerPage {
123        ids,
124        metadata,
125        next_index,
126        next_data,
127        complete,
128        version: string(&fields, 8)?,
129        raw: raw.into(),
130    })
131}
132/// One membership or placement intent. It is not an automatic retry policy.
133#[derive(Clone, Serialize, Deserialize)]
134pub enum CustomStickerMutation {
135    /// Save an uploaded/existing sticker identity.
136    Add,
137    /// Remove Saved membership for the identity.
138    Remove,
139    /// Move the identity to the front.
140    First,
141    /// Move after an anchor using a fresh complete-list server version.
142    After {
143        /// Identity immediately before the requested placement.
144        anchor: String,
145        /// Current version from a completed fresh custom-list response.
146        version: String,
147        /// Fresh correlation value for this operation, retained for its lifetime.
148        update_id: String,
149    },
150}
151/// Encode one custom membership/placement operation, without a BaseRequest.
152pub fn custom_sticker_mutation_request(
153    id: &str,
154    action: &CustomStickerMutation,
155) -> Result<Vec<u8>> {
156    ensure!(valid_id(id), "invalid_sticker_id");
157    let operation = match action {
158        CustomStickerMutation::Add => 4,
159        CustomStickerMutation::Remove => 2,
160        CustomStickerMutation::First => 3,
161        CustomStickerMutation::After { .. } => 5,
162    };
163    let mut fields = vec![
164        p::bytes(1, id.as_bytes()),
165        p::uint(2, operation),
166        p::uint(3, 0),
167    ];
168    if let CustomStickerMutation::After {
169        anchor,
170        version,
171        update_id,
172    } = action
173    {
174        ensure!(
175            valid_id(anchor)
176                && !anchor.eq_ignore_ascii_case(id)
177                && !version.is_empty()
178                && version.len() <= 16384
179                && !update_id.is_empty()
180                && update_id.len() <= 256,
181            "invalid_sticker_placement"
182        );
183        fields.extend([
184            p::bytes(4, anchor.as_bytes()),
185            p::bytes(5, version.as_bytes()),
186            p::bytes(6, update_id.as_bytes()),
187        ]);
188    }
189    p::message(&fields)
190}
191impl NativeClient {
192    pub(crate) fn custom_sticker_read_snapshot(
193        &self,
194        state: &mut AccountState,
195        request: &[u8],
196    ) -> Result<CustomStickerPage> {
197        let raw = self.authenticated_rpc(
198            state,
199            697,
200            "/cgi-bin/micromsg-bin/mmbatchemojidownload",
201            request,
202        )?;
203        decode_custom_stickers(&raw)
204    }
205}
206#[cfg(test)]
207mod tests {
208    use super::*;
209    #[test]
210    fn initial_list_and_metadata_use_distinct_presence() {
211        assert_eq!(
212            hex::encode(custom_sticker_list_request(0, &[]).unwrap()),
213            "0800100220002a00"
214        );
215        let id = "00000000000000000000000000000000".to_string();
216        let request = p::decode(&custom_sticker_metadata_request(&[id]).unwrap()).unwrap();
217        assert_eq!(p::scalar(&request, 2).unwrap(), 1);
218        assert!(p::optional(&request, 4).unwrap().is_none());
219        assert!(p::optional(&request, 5).unwrap().is_none());
220    }
221    #[test]
222    fn omitted_generated_fields_do_not_hide_an_incomplete_nonempty_list() {
223        let base = p::bytes(1, &p::uint(1, 0));
224        let id = p::bytes(3, b"00000000000000000000000000000000");
225        let raw = p::message(&[base.clone(), id.clone(), p::bytes(8, b"fresh-version")]).unwrap();
226        let page = decode_custom_stickers(&raw).unwrap();
227        assert!(!page.complete);
228        assert_eq!(page.next_index, None);
229        let raw = p::message(&[base, id, p::uint(4, 1)]).unwrap();
230        let page = decode_custom_stickers(&raw).unwrap();
231        assert!(page.complete);
232        assert!(page.version.is_none());
233    }
234    #[test]
235    fn after_anchor_requires_distinct_identity_and_fresh_version() {
236        let id = "00000000000000000000000000000000";
237        let action = CustomStickerMutation::After {
238            anchor: "11111111111111111111111111111111".into(),
239            version: "fresh".into(),
240            update_id: "synthetic_uuid_1234".into(),
241        };
242        let raw = custom_sticker_mutation_request(id, &action).unwrap();
243        let fields = p::decode(&raw).unwrap();
244        assert_eq!(p::scalar(&fields, 2).unwrap(), 5);
245        assert_eq!(
246            p::data(&fields, 4).unwrap(),
247            b"11111111111111111111111111111111"
248        );
249        assert_eq!(p::data(&fields, 5).unwrap(), b"fresh");
250        assert!(
251            custom_sticker_mutation_request("11111111111111111111111111111111", &action).is_err()
252        );
253    }
254}