1use crate::{protobuf as p, AccountState, NativeClient};
4use anyhow::{ensure, Result};
5use serde::{Deserialize, Serialize};
6
7#[derive(Clone, Copy, Debug)]
9pub enum StickerPackFeed {
10 Catalog,
12 Added,
14}
15#[derive(Clone, Serialize, Deserialize)]
17pub struct StickerPackSummary {
18 pub id: String,
20 pub name: String,
22 pub description: String,
24 pub icon_url: String,
26 pub cover_url: String,
28 pub pack_type: u32,
30 pub flags: u32,
32 pub expiry: u32,
34 pub raw: Vec<u8>,
36}
37#[derive(Clone, Serialize, Deserialize)]
39pub struct StickerPackPage {
40 pub items: Vec<StickerPackSummary>,
42 pub next_cursor: Vec<u8>,
44 pub complete: bool,
46 pub restart: bool,
48 pub raw: Vec<u8>,
50}
51#[derive(Clone, Serialize, Deserialize)]
53pub struct StickerPackItem {
54 pub id: String,
56 pub original_url: String,
58 pub thumbnail_url: String,
60 pub raw: Vec<u8>,
62}
63#[derive(Clone, Serialize, Deserialize)]
65pub struct StickerPackDetail {
66 pub summary: StickerPackSummary,
68 pub items: Vec<StickerPackItem>,
70 pub raw: Vec<u8>,
72}
73#[derive(Clone, Serialize, Deserialize)]
75pub struct StickerPackCaption {
76 pub id: String,
78 pub captions: Vec<(String, String)>,
80}
81#[derive(Clone, Serialize, Deserialize)]
83pub struct StickerPackCaptions {
84 pub items: Vec<StickerPackCaption>,
86 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}
142pub 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}
160pub 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}
182pub 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}
192pub 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}
220pub 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}
228pub 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}
260pub 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}
273pub 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}
284pub 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}