Skip to main content

wechat_protocol/
sticker_upload.rs

1//! Direct custom-sticker upload chunks. This operation does not send a chat message.
2use crate::{protobuf as p, NativeClient};
3use anyhow::{ensure, Result};
4
5/// Maximum plaintext bytes carried by one direct sticker upload request.
6pub const STICKER_UPLOAD_CHUNK_BYTES: usize = 98_304;
7/// A validated acknowledgement for one direct upload chunk.
8#[derive(Clone, Debug)]
9pub struct StickerUploadAcknowledgement {
10    /// First byte not yet acknowledged by the service.
11    pub next_offset: u32,
12    /// Source size echoed by the service.
13    pub total_bytes: u32,
14    /// Original response, including unassigned optional fields. Protect at rest.
15    pub raw: Vec<u8>,
16}
17/// Encode one direct upload chunk from an owned source. Unlike chat sticker
18/// sends this request carries raw bytes immediately, without a BaseRequest or
19/// a nested builtin buffer. Offsets are bounded signed-32-bit wire scalars.
20pub fn sticker_upload_request(source: &[u8], offset: u32) -> Result<Vec<u8>> {
21    ensure!(
22        !source.is_empty() && source.len() <= wechat_media::MAX_IMAGE_BYTES,
23        "sticker_source_size_limit"
24    );
25    let offset = usize::try_from(offset)?;
26    ensure!(offset < source.len(), "sticker_upload_offset_invalid");
27    let end = source.len().min(offset + STICKER_UPLOAD_CHUNK_BYTES);
28    let identity = hex::encode(crate::crypto::md5(source));
29    let item = p::message(&[
30        p::bytes(1, identity.as_bytes()),
31        p::uint(2, offset as u64),
32        p::uint(3, source.len() as u64),
33        p::bytes(4, &source[offset..end]),
34    ])?;
35    p::message(&[p::bytes(1, &item), p::uint(3, 1)])
36}
37/// Validate chunk progress or identity-bound completion of an existing upload.
38/// Rejected, stale, nonadvancing and mismatched replies never grant a resend.
39pub fn decode_sticker_upload(
40    raw: &[u8],
41    offset: u32,
42    total: u32,
43    expected_md5: &str,
44) -> Result<StickerUploadAcknowledgement> {
45    let fields = p::decode(raw)?;
46    ensure!(p::base_code(&fields)? == 0, "sticker_upload_rejected");
47    let items = fields
48        .iter()
49        .filter(|field| field.number == 2)
50        .collect::<Vec<_>>();
51    ensure!(items.len() == 1, "sticker_upload_reply_invalid");
52    let item = p::decode(p::data(&fields, 2)?)?;
53    ensure!(p::scalar(&item, 1)? == 0, "sticker_upload_item_rejected");
54    let identity = p::optional_data(&item, 4)?;
55    if let Some(identity) = identity {
56        ensure!(
57            std::str::from_utf8(identity)?.eq_ignore_ascii_case(expected_md5),
58            "sticker_upload_identity_mismatch"
59        );
60    }
61    let next_offset = u32::try_from(p::scalar(&item, 2)?)?;
62    let returned_total = u32::try_from(p::scalar(&item, 3)?)?;
63    // The service may already own the complete content. Only a successful
64    // full-length acknowledgement bound to the original MD5 can skip chunks;
65    // unassigned optional flags are not evidence of completion.
66    let verified_complete = next_offset == total
67        && identity
68            .is_some_and(|value| value.len() == 32 && value.iter().all(u8::is_ascii_hexdigit));
69    ensure!(
70        returned_total == total
71            && next_offset > offset
72            && next_offset <= total
73            && (next_offset - offset <= STICKER_UPLOAD_CHUNK_BYTES as u32 || verified_complete),
74        "sticker_upload_progress_invalid"
75    );
76    Ok(StickerUploadAcknowledgement {
77        next_offset,
78        total_bytes: total,
79        raw: raw.into(),
80    })
81}
82impl NativeClient {
83    pub(crate) fn upload_sticker_chunk_snapshot(
84        &self,
85        state: &mut crate::AccountState,
86        source: &[u8],
87        offset: u32,
88    ) -> Result<StickerUploadAcknowledgement> {
89        let request = sticker_upload_request(source, offset)?;
90        let reply =
91            self.authenticated_rpc(state, 703, "/cgi-bin/micromsg-bin/mmemojiupload", &request)?;
92        decode_sticker_upload(
93            &reply,
94            offset,
95            u32::try_from(source.len())?,
96            &hex::encode(crate::crypto::md5(source)),
97        )
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    // Synthetic successful upload replies use the independently established
105    // BaseResponse and item layout, rather than the request serializer.
106    fn acknowledgement(next: u32, total: u32, identity: Option<&str>) -> Vec<u8> {
107        let mut item = vec![
108            p::uint(1, 0),
109            p::uint(2, next.into()),
110            p::uint(3, total.into()),
111        ];
112        if let Some(identity) = identity {
113            item.push(p::bytes(4, identity.as_bytes()));
114        }
115        p::message(&[
116            p::bytes(1, &p::uint(1, 0)),
117            p::bytes(2, &p::message(&item).unwrap()),
118        ])
119        .unwrap()
120    }
121    #[test]
122    fn complete_owned_identity_can_acknowledge_previously_uploaded_bytes() {
123        let identity = "0123456789abcdef0123456789abcdef";
124        for offset in [0, 1024] {
125            let raw = acknowledgement(150_000, 150_000, Some(identity));
126            let reply = decode_sticker_upload(&raw, offset, 150_000, identity).unwrap();
127            assert_eq!(reply.next_offset, 150_000);
128            assert_eq!(reply.raw, raw);
129        }
130        // Completion without an identity, a mismatched identity, intermediate
131        // jumps, and impossible sizes remain unverified.
132        for (next, returned_total, echoed) in [
133            (150_000, 150_000, None),
134            (150_000, 150_000, Some("ffffffffffffffffffffffffffffffff")),
135            (120_000, 150_000, Some(identity)),
136            (150_001, 150_000, Some(identity)),
137            (150_000, 150_001, Some(identity)),
138            (0, 150_000, Some(identity)),
139        ] {
140            assert!(decode_sticker_upload(
141                &acknowledgement(next, returned_total, echoed),
142                0,
143                150_000,
144                identity,
145            )
146            .is_err());
147        }
148        assert!(decode_sticker_upload(
149            &acknowledgement(150_000, 150_000, Some(identity)),
150            150_000,
151            150_000,
152            identity
153        )
154        .is_err());
155        assert!(decode_sticker_upload(
156            &acknowledgement(150_000, 150_000, Some("")),
157            0,
158            150_000,
159            ""
160        )
161        .is_err());
162    }
163    #[test]
164    fn initial_continuation_and_final_shapes_keep_raw_chunk_boundaries() {
165        assert_eq!(hex::encode(sticker_upload_request(b"abc", 0).unwrap()), "0a2b0a2039303031353039383363643234666230643639363366376432386531376637321000180322036162631801");
166        assert_eq!(hex::encode(sticker_upload_request(b"abc", 1).unwrap()), "0a2a0a20393030313530393833636432346662306436393633663764323865313766373210011803220262631801");
167        let raw = hex::decode("0a0208001206080010031803").unwrap();
168        let reply = decode_sticker_upload(&raw, 0, 3, "900150983cd24fb0d6963f7d28e17f72").unwrap();
169        assert_eq!(reply.next_offset, 3);
170        assert_eq!(reply.raw, raw);
171        assert!(decode_sticker_upload(&raw, 3, 3, "900150983cd24fb0d6963f7d28e17f72").is_err());
172        assert!(decode_sticker_upload(&raw, 0, 4, "900150983cd24fb0d6963f7d28e17f72").is_err());
173        assert!(sticker_upload_request(b"abc", 3).is_err());
174    }
175    #[test]
176    fn oversized_advances_duplicate_results_and_rejections_are_not_success() {
177        for raw in [
178            "0a0208001206080010041803",
179            "0a0208001206080010001803",
180            "0a0208001206080110031803",
181            "0a0208011206080010031803",
182            "0a02080012060800100318031206080010031803",
183        ] {
184            assert!(decode_sticker_upload(
185                &hex::decode(raw).unwrap(),
186                0,
187                3,
188                "900150983cd24fb0d6963f7d28e17f72"
189            )
190            .is_err());
191        }
192        let bytes = vec![0x42; STICKER_UPLOAD_CHUNK_BYTES + 1];
193        let request = p::decode(&sticker_upload_request(&bytes, 0).unwrap()).unwrap();
194        let item = p::decode(p::data(&request, 1).unwrap()).unwrap();
195        assert_eq!(p::data(&item, 4).unwrap().len(), STICKER_UPLOAD_CHUNK_BYTES);
196        let request =
197            p::decode(&sticker_upload_request(&bytes, STICKER_UPLOAD_CHUNK_BYTES as u32).unwrap())
198                .unwrap();
199        let item = p::decode(p::data(&request, 1).unwrap()).unwrap();
200        assert_eq!(p::data(&item, 4).unwrap(), &[0x42]);
201    }
202}