wechat-protocol 2.4.1

Native WeChat transport, authentication and protocol codecs
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
//! Scoped operations for embedders that already execute on blocking workers.
use super::*;

/// A single logical operation borrowing this client's temporary request state.
/// It is not an account owner and cannot outlive request_blocking. No operation
/// accepts an independently mutable AccountState. Use ordinary async client
/// methods unless the embedding application already owns a blocking worker.
pub struct AccountRequest<'a> {
    transport: &'a NativeClient,
    state: &'a mut AccountState,
    spent: bool,
}

macro_rules! operation {
    ($name:ident($($arg:ident: $ty:ty),*) -> $result:ty => $raw:ident) => {
        pub fn $name(&mut self, $($arg: $ty),*) -> Result<$result> {
            self.admit()?;
            self.transport.$raw(self.state, $($arg),*)
        }
    };
}

impl AccountRequest<'_> {
    /// Submit one direct sticker upload chunk. Journal the attempt before calling;
    /// an error after submission has an uncertain outcome and is not a retry grant.
    pub fn upload_sticker_chunk(
        &mut self,
        source: &[u8],
        offset: u32,
    ) -> Result<crate::sticker_upload::StickerUploadAcknowledgement> {
        self.admit()?;
        self.transport
            .upload_sticker_chunk_snapshot(self.state, source, offset)
    }

    /// Return one custom-list or metadata reply for caller-owned receipt retention.
    /// The request must come from the bounded custom-sticker builders.
    pub fn custom_stickers_raw(&mut self, request: &[u8]) -> Result<Vec<u8>> {
        self.admit()?;
        ensure!(request.len() <= 65536, "sticker_request_limit");
        self.transport.authenticated_rpc(
            self.state,
            697,
            "/cgi-bin/micromsg-bin/mmbatchemojidownload",
            request,
        )
    }
    /// Submit one journaled Saved membership/placement intent, returning even a
    /// rejected service reply before decoding. A transport error is uncertain.
    pub fn mutate_custom_sticker(
        &mut self,
        id: &str,
        action: &crate::custom_stickers::CustomStickerMutation,
    ) -> Result<Vec<u8>> {
        let request = crate::custom_stickers::custom_sticker_mutation_request(id, action)?;
        self.admit()?;
        self.transport.authenticated_rpc(
            self.state,
            698,
            "/cgi-bin/micromsg-bin/mmbackupemojioperate",
            &request,
        )
    }
    /// Submit one direct upload chunk and return its raw acknowledgement for
    /// retention before validation. Callers must journal each attempted offset.
    pub fn upload_sticker_chunk_raw(&mut self, source: &[u8], offset: u32) -> Result<Vec<u8>> {
        let request = crate::sticker_upload::sticker_upload_request(source, offset)?;
        self.admit()?;
        self.transport.authenticated_rpc(
            self.state,
            703,
            "/cgi-bin/micromsg-bin/mmemojiupload",
            &request,
        )
    }

    /// Read a native pack-list page for durable caller-owned receipt storage.
    pub fn sticker_pack_page_raw(
        &mut self,
        feed: crate::sticker_packs::StickerPackFeed,
        cursor: &[u8],
    ) -> Result<Vec<u8>> {
        let request = crate::sticker_packs::sticker_pack_list_request(self.state, feed, cursor)?;
        self.admit()?;
        self.transport
            .sticker_pack_rpc_snapshot(self.state, 411, &request)
    }
    /// Read full metadata/content references for one product without acquiring media.
    pub fn sticker_pack_detail_raw(&mut self, id: &str) -> Result<Vec<u8>> {
        let request = crate::sticker_packs::sticker_pack_detail_request(self.state, id)?;
        self.admit()?;
        self.transport
            .sticker_pack_rpc_snapshot(self.state, 412, &request)
    }
    /// Read localized caption rows for one product, retaining the complete reply.
    pub fn sticker_pack_captions_raw(&mut self, id: &str) -> Result<Vec<u8>> {
        let request = crate::sticker_packs::sticker_pack_captions_request(self.state, id)?;
        self.admit()?;
        self.transport
            .sticker_pack_rpc_snapshot(self.state, 521, &request)
    }
    /// Submit one journaled eligible-free membership change. The caller checks
    /// eligibility before adding, retains this reply and reconciles membership.
    /// A transport error is uncertain and never an automatic retry grant.
    pub fn sticker_pack_membership_raw(&mut self, id: &str, added: bool) -> Result<Vec<u8>> {
        let request = crate::sticker_packs::sticker_pack_membership_request(self.state, id, added)?;
        self.admit()?;
        self.transport
            .sticker_pack_rpc_snapshot(self.state, 413, &request)
    }

    /// Acquire one archive locator without changing pack membership. Journal the
    /// attempt before calling and retain the raw reply before decoding it.
    pub fn sticker_pack_acquisition_raw(&mut self, id: &str) -> Result<Vec<u8>> {
        let request = crate::sticker_packs::sticker_pack_acquisition_request(self.state, id)?;
        self.admit()?;
        self.transport
            .sticker_pack_rpc_snapshot(self.state, 423, &request)
    }

    /// Submit one journaled probe or byte continuation for a single sticker send.
    /// Return raw bytes for durable retention before validating acknowledgement.
    pub fn send_sticker_chunk_raw(
        &mut self,
        chunk: &crate::sticker_send::StickerSendChunk<'_>,
    ) -> Result<Vec<u8>> {
        let request = crate::sticker_send::sticker_send_request(self.state, chunk)?;
        self.admit()?;
        self.transport.authenticated_rpc(
            self.state,
            175,
            "/cgi-bin/micromsg-bin/sendemoji",
            &request,
        )
    }

    fn admit(&mut self) -> Result<()> {
        // A second operation must not label the first possibly accepted one
        // "not submitted". Each logical request has its own outcome/journal.
        ensure!(!self.spent, "Account request context already consumed");
        self.spent = true;
        Ok(())
    }

    /// Read-only request context for protocol preparation and journal binding.
    /// These secret bytes are not an independent account owner or a handoff.
    pub fn account(&self) -> &AccountState {
        self.state
    }

    /// Read one exact OpenIM contact using optional group context and a supplied ticket.
    pub fn lookup_openim_contact(
        &mut self,
        username: &str,
        room: Option<&str>,
        ticket: Option<&str>,
    ) -> Result<crate::OpenImContact> {
        self.admit()?;
        self.transport
            .openim_contact_snapshot(self.state, username, room, ticket)
    }

    /// Return the authenticated OpenIM reply bytes for caller-owned receipt storage and decoding.
    pub fn lookup_openim_contact_raw(
        &mut self,
        username: &str,
        room: Option<&str>,
        ticket: Option<&str>,
    ) -> Result<Vec<u8>> {
        self.admit()?;
        self.transport
            .openim_contact_raw_snapshot(self.state, username, room, ticket)
    }

    operation!(sync(cursor: &[u8]) -> crate::SyncBatch => sync_snapshot);
    operation!(sync_scene(cursor: &[u8], scene: u32) -> crate::SyncBatch => sync_scene_snapshot);
    operation!(heartbeat(cursor: &[u8]) -> crate::Heartbeat => heartbeat_snapshot);
    operation!(lookup_contacts(ids: &[String]) -> crate::ContactLookup => lookup_contacts_snapshot);
    operation!(lookup_room(room: &str, version: u32) -> crate::RoomRoster => lookup_room_snapshot);
    operation!(init_contacts(contact_sequence: u32, room_sequence: u32) -> crate::InitContactPage => init_contacts_snapshot);
    operation!(download_avatars(ids: &[String]) -> Vec<crate::AvatarBytes> => download_avatars_snapshot);
    operation!(download_voice_chunk(server_id: u64, length: u32, offset: u32) -> crate::VoiceChunk => download_voice_chunk_snapshot);
    operation!(cdn_config() -> crate::media::CdnConfig => cdn_config_snapshot);
    operation!(large_cdn_config(route: crate::media::LargeCdnRoute) -> crate::media::CdnConfig => large_cdn_config_snapshot);
    operation!(group_inventory(cursor: &[u8]) -> crate::GroupMetadataPage => group_inventory_snapshot);
    operation!(lookup_contacts_raw(ids: &[String]) -> Vec<u8> => lookup_contacts_raw_snapshot);
    operation!(lookup_contacts_receipt(ids: &[String]) -> crate::MetadataReply<crate::ContactLookup> => lookup_contacts_receipt_snapshot);
    operation!(lookup_room_raw(room: &str, version: u32) -> Vec<u8> => lookup_room_raw_snapshot);
    operation!(lookup_room_receipt(room: &str, version: u32) -> crate::MetadataReply<crate::RoomRoster> => lookup_room_receipt_snapshot);
    operation!(init_contacts_receipt(contacts: u32, rooms: u32) -> crate::MetadataReply<crate::InitContactPage> => init_contacts_receipt_snapshot);
    operation!(group_detail_raw(group: &str) -> Vec<u8> => group_detail_raw_snapshot);
    operation!(group_mutation_raw(request: &crate::GroupRpc) -> Vec<u8> => group_mutation_raw_snapshot);
    operation!(recall_message(request: &crate::MessageRecall) -> crate::MessageRecallReply => recall_message_snapshot);
    operation!(notify_read_session(request: &crate::SessionReadNotification) -> crate::SessionReadReply => notify_read_session_snapshot);
    operation!(contact_sync(cursor: &[u8], message_cursor: &[u8], continuation: bool) -> crate::contact_sync::ContactSyncBatch => contact_sync_snapshot);
    operation!(send_share(destination: &str, client_id: &str, created_at: u32, content: &str) -> crate::media_send::MediaSendResult => send_share_snapshot);
    operation!(send_quote(destination: &str, client_id: &str, created_at: u32, content: &str, source: Option<&str>) -> crate::media_send::MediaSendResult => send_quote_with_source_snapshot);
    operation!(reserve_file_upload(destination: &str, client_id: &str, name: &str, length: usize, md5: &str) -> crate::file_upload::FileUploadReservation => reserve_file_upload_snapshot);
    operation!(send_file(destination: &str, client_id: &str, created_at: u32, upload: &crate::media::UploadedMedia, reservation: Option<&crate::file_upload::FileUploadReservation>) -> crate::media_send::MediaSendResult => send_file_with_reservation_snapshot);
    /// Submit the uploaded standard and thumbnail copies, including an original when present.
    pub fn send_image(
        &mut self,
        destination: &str,
        client_id: &str,
        upload: &crate::media::UploadedImage,
    ) -> Result<crate::media_send::MediaSendResult> {
        self.admit()?;
        self.transport
            .send_image_snapshot(self.state, destination, client_id, upload)
    }

    operation!(send_video(destination: &str, client_id: &str, upload: &crate::media::UploadedVideo, seconds: u32) -> crate::media_send::MediaSendResult => send_video_snapshot);
    operation!(send_voice(destination: &str, client_id: &str, created_at: u32, duration_ms: u32, encoded: &[u8]) -> crate::media_send::MediaSendResult => send_voice_snapshot);

    pub fn send_text(
        &mut self,
        destination: &str,
        content: &str,
        options: &TextSendOptions,
    ) -> Result<crate::TextSendResult> {
        self.send_text_guarded(destination, content, options, || Ok(()))
    }

    pub fn send_text_guarded(
        &mut self,
        destination: &str,
        content: &str,
        options: &TextSendOptions,
        before_submit: impl FnOnce() -> Result<()>,
    ) -> Result<crate::TextSendResult> {
        self.admit()?;
        let request = crate::wire::text_send_request_with_source(
            destination,
            content,
            options.created_at,
            options.client_message_id,
            options.source.as_deref(),
        )?;
        let reply = self.transport.authenticated_rpc_guarded(
            self.state,
            522,
            "/cgi-bin/micromsg-bin/newsendmsg",
            &request,
            before_submit,
        )?;
        crate::wire::decode_text_send(&reply, destination, options.client_message_id)
    }

    pub fn call_rpc(
        &mut self,
        route: crate::calls::host_policy::CallHostRoute,
        request: &[u8],
        before_submit: impl FnOnce() -> Result<()>,
        retain_reply: impl FnOnce(&[u8]) -> Result<()>,
    ) -> Result<Vec<u8>> {
        self.admit()?;
        let cookie = Zeroizing::new(self.state.cookie.clone());
        let reply =
            self.transport
                .call_rpc_snapshot_guarded(self.state, route, request, before_submit)?;
        if let Err(error) = retain_reply(&reply) {
            // Retention failure cannot publish this request's new cookie. A
            // concurrent accepted account update is still protected by revision.
            zeroize::Zeroize::zeroize(&mut self.state.cookie);
            self.state.cookie = cookie.to_vec();
            return Err(error);
        }
        Ok(reply)
    }

    /// Read-only call polling on an existing blocking worker. The caller owns
    /// the async wait/cancellation mechanism; this context retains the account
    /// lease until that transport future is dropped or completes.
    pub fn call_live_sync(
        &mut self,
        request: &[u8],
        wait_timeout: Duration,
        before_submit: impl FnOnce() -> Result<()>,
        wait: impl for<'a> FnOnce(
            std::pin::Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>>,
        ) -> Result<Vec<u8>>,
        retain_reply: impl FnOnce(&[u8]) -> Result<()>,
    ) -> Result<Vec<u8>> {
        self.admit()?;
        let cookie = Zeroizing::new(self.state.cookie.clone());
        let reply = self.transport.call_live_sync_snapshot_with_wait_timeout(
            self.state,
            request,
            wait_timeout,
            before_submit,
            wait,
        )?;
        if let Err(error) = retain_reply(&reply) {
            zeroize::Zeroize::zeroize(&mut self.state.cookie);
            self.state.cookie = cookie.to_vec();
            return Err(error);
        }
        Ok(reply)
    }
}

impl NativeClient {
    /// Change transport deadlines/budgets for a handle while retaining the same
    /// account owner and admission rules. This never imports credential state.
    pub fn with_request_options(&self, options: NativeOptions) -> Result<Self> {
        // Reuse constructor validation without replacing the account owner.
        let mut handle = Self::new(options)?;
        handle.account = Some(self.owned_account()?.clone());
        Ok(handle)
    }

    /// Execute one scoped account operation on the caller's blocking worker.
    /// Uses the same admission, generation, storage and handoff barriers as async
    /// operations. No executor or independent credential owner is constructed.
    pub fn request_blocking<T>(
        &self,
        operation: impl FnOnce(&mut AccountRequest<'_>) -> Result<T>,
    ) -> Result<T> {
        self.account_request_blocking(|transport, state, _| {
            operation(&mut AccountRequest {
                transport,
                state,
                spent: false,
            })
        })
    }

    /// Explicit authentication renewal on an existing blocking worker. This
    /// never retries the operation whose rejection prompted the caller to renew.
    pub fn renew_session_blocking(&self, computer_name: &str) -> Result<()> {
        let (exchange, state) = self
            .owned_account()?
            .begin()
            .map_err(|error| error.context(NativeRequestNotSubmitted))?;
        let exchange = Arc::new(exchange);
        let mut transport = Self::new(self.options.clone())?;
        let submission = exchange.clone();
        transport.submission_guard = Some(Arc::new(move || {
            submission
                .check()
                .map_err(|error| error.context(NativeRequestNotSubmitted))
        }));
        let accepted = transport.renew_session_snapshot(&state, computer_name)?;
        exchange.accept_credentials(accepted)
    }

    /// As [`Self::logout`], on the caller's blocking worker. No Tokio runtime
    /// is needed. Logout is submitted at most once and the owner stays stopped
    /// after rejection or uncertainty.
    pub fn logout_blocking(&self) -> Result<crate::LogoutReply> {
        self.prepare_logout()?.submit_blocking()
    }

    /// As [`Self::shutdown`], on the caller's blocking worker. Do not call it
    /// from inside an account request: it waits for every request to finish.
    pub fn shutdown_blocking(&self) -> Result<()> {
        self.owned_account()?.stop_and_drain_blocking()
    }
}

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

    #[test]
    fn scoped_requests_share_owner_and_cannot_submit_after_stop() {
        let client = super::super::tests::client();
        let other = client
            .with_request_options(NativeOptions::default())
            .unwrap();
        other
            .request_blocking(|request| {
                assert_eq!(request.account().uin, 1);
                request.admit()?;
                request.state.cookie = vec![4];
                Ok(())
            })
            .unwrap();
        assert_eq!(client.export_account_state().unwrap().cookie, vec![4]);
        client.stop().unwrap();
        let entered = AtomicBool::new(false);
        let error = other
            .request_blocking(|_| {
                entered.store(true, Ordering::Release);
                Ok(())
            })
            .unwrap_err();
        assert!(error.is::<NativeRequestNotSubmitted>());
        assert!(!entered.load(Ordering::Acquire));
    }

    #[test]
    fn scoped_context_cannot_turn_a_second_operation_into_an_unsent_retry() {
        let client = super::super::tests::client();
        let error = client
            .request_blocking(|request| {
                request.admit()?;
                request.state.cookie = vec![7];
                request.admit()
            })
            .unwrap_err();
        assert!(!error.is::<NativeRequestNotSubmitted>());
        assert_eq!(client.export_account_state().unwrap().cookie, vec![7]);
        assert_eq!(client.account_status().unwrap().in_flight, 0);
    }

    #[tokio::test]
    async fn blocking_workers_and_async_requests_share_one_response_order() {
        let client = super::super::tests::client();
        let old = client.clone();
        let (ready, ready_rx) = tokio::sync::oneshot::channel();
        let (finish, finish_rx) = std::sync::mpsc::channel();
        let worker = tokio::task::spawn_blocking(move || {
            old.request_blocking(|request| {
                request.admit()?;
                ready.send(()).unwrap();
                finish_rx.recv()?;
                request.state.cookie = vec![1];
                Ok(())
            })
        });
        ready_rx.await.unwrap();
        client
            .account_request(|_, state, _| {
                state.cookie = vec![2];
                Ok(())
            })
            .await
            .unwrap();
        finish.send(()).unwrap();
        worker.await.unwrap().unwrap();
        assert_eq!(client.export_account_state().unwrap().cookie, vec![2]);
    }
}