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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Account-owned asynchronous protocol operations.
use super::*;

impl NativeClient {
    /// Fetch one sync page using the owned account. The application still owns
    /// command retention, projection and committing the returned cursor.
    pub async fn sync(&self, cursor: &[u8]) -> Result<crate::SyncBatch> {
        let cursor = cursor.to_vec();
        self.account_request(move |transport, state, _| transport.sync_snapshot(state, &cursor))
            .await
    }

    pub async fn heartbeat(&self, cursor: &[u8]) -> Result<crate::Heartbeat> {
        let cursor = cursor.to_vec();
        self.account_request(move |transport, state, _| {
            transport.heartbeat_snapshot(state, &cursor)
        })
        .await
    }

    pub async fn sync_scene(&self, cursor: &[u8], scene: u32) -> Result<crate::SyncBatch> {
        let cursor = cursor.to_vec();
        self.account_request(move |transport, state, _| {
            transport.sync_scene_snapshot(state, &cursor, scene)
        })
        .await
    }

    pub async fn lookup_contacts(&self, usernames: &[String]) -> Result<crate::ContactLookup> {
        let usernames = usernames.to_vec();
        self.account_request(move |transport, state, _| {
            transport.lookup_contacts_snapshot(state, &usernames)
        })
        .await
    }

    pub async fn lookup_room(&self, room_id: &str, version: u32) -> Result<crate::RoomRoster> {
        let room_id = room_id.to_owned();
        self.account_request(move |transport, state, _| {
            transport.lookup_room_snapshot(state, &room_id, version)
        })
        .await
    }

    pub async fn init_contacts(
        &self,
        contact_sequence: u32,
        room_sequence: u32,
    ) -> Result<crate::InitContactPage> {
        self.account_request(move |transport, state, _| {
            transport.init_contacts_snapshot(state, contact_sequence, room_sequence)
        })
        .await
    }

    pub async fn download_avatars(&self, usernames: &[String]) -> Result<Vec<crate::AvatarBytes>> {
        let usernames = usernames.to_vec();
        self.account_request(move |transport, state, _| {
            transport.download_avatars_snapshot(state, &usernames)
        })
        .await
    }

    pub async fn download_voice_chunk(
        &self,
        server_message_id: u64,
        total_length: u32,
        offset: u32,
    ) -> Result<crate::VoiceChunk> {
        self.account_request(move |transport, state, _| {
            transport.download_voice_chunk_snapshot(state, server_message_id, total_length, offset)
        })
        .await
    }

    pub async fn cdn_config(&self) -> Result<crate::media::CdnConfig> {
        self.account_request(|transport, state, _| transport.cdn_config_snapshot(state))
            .await
    }

    pub async fn large_cdn_config(
        &self,
        route: crate::media::LargeCdnRoute,
    ) -> Result<crate::media::CdnConfig> {
        self.account_request(move |transport, state, _| {
            transport.large_cdn_config_snapshot(state, route)
        })
        .await
    }

    pub async fn group_inventory(&self, cursor: &[u8]) -> Result<crate::GroupMetadataPage> {
        let cursor = cursor.to_vec();
        self.account_request(move |transport, state, _| {
            transport.group_inventory_snapshot(state, &cursor)
        })
        .await
    }

    pub async fn lookup_contacts_raw(&self, usernames: &[String]) -> Result<Vec<u8>> {
        let usernames = usernames.to_vec();
        self.account_request(move |transport, state, _| {
            transport.lookup_contacts_raw_snapshot(state, &usernames)
        })
        .await
    }

    pub async fn lookup_contacts_receipt(
        &self,
        usernames: &[String],
    ) -> Result<crate::MetadataReply<crate::ContactLookup>> {
        let usernames = usernames.to_vec();
        self.account_request(move |transport, state, _| {
            transport.lookup_contacts_receipt_snapshot(state, &usernames)
        })
        .await
    }

    pub async fn lookup_room_receipt(
        &self,
        room_id: &str,
        version: u32,
    ) -> Result<crate::MetadataReply<crate::RoomRoster>> {
        let room_id = room_id.to_owned();
        self.account_request(move |transport, state, _| {
            transport.lookup_room_receipt_snapshot(state, &room_id, version)
        })
        .await
    }

    pub async fn lookup_room_raw(&self, room_id: &str, version: u32) -> Result<Vec<u8>> {
        let room_id = room_id.to_owned();
        self.account_request(move |transport, state, _| {
            transport.lookup_room_raw_snapshot(state, &room_id, version)
        })
        .await
    }

    pub async fn init_contacts_receipt(
        &self,
        contact_sequence: u32,
        room_sequence: u32,
    ) -> Result<crate::MetadataReply<crate::InitContactPage>> {
        self.account_request(move |transport, state, _| {
            transport.init_contacts_receipt_snapshot(state, contact_sequence, room_sequence)
        })
        .await
    }

    pub async fn group_detail_raw(&self, group_id: &str) -> Result<Vec<u8>> {
        let group_id = group_id.to_owned();
        self.account_request(move |transport, state, _| {
            transport.group_detail_raw_snapshot(state, &group_id)
        })
        .await
    }

    pub async fn group_mutation_raw(&self, request: &crate::GroupRpc) -> Result<Vec<u8>> {
        let request = request.clone();
        self.account_request(move |transport, state, _| {
            transport.group_mutation_raw_snapshot(state, &request)
        })
        .await
    }

    pub async fn recall_message(
        &self,
        request: &crate::MessageRecall,
    ) -> Result<crate::MessageRecallReply> {
        let request = request.clone();
        self.account_request(move |transport, state, _| {
            transport.recall_message_snapshot(state, &request)
        })
        .await
    }

    pub async fn notify_read_session(
        &self,
        notification: &crate::SessionReadNotification,
    ) -> Result<crate::SessionReadReply> {
        let notification = notification.clone();
        self.account_request(move |transport, state, _| {
            transport.notify_read_session_snapshot(state, &notification)
        })
        .await
    }

    pub async fn contact_sync(
        &self,
        cursor: &[u8],
        message_cursor: &[u8],
        continuation: bool,
    ) -> Result<crate::contact_sync::ContactSyncBatch> {
        let cursor = cursor.to_vec();
        let message_cursor = message_cursor.to_vec();
        self.account_request(move |transport, state, _| {
            transport.contact_sync_snapshot(state, &cursor, &message_cursor, continuation)
        })
        .await
    }

    pub async fn send_share(
        &self,
        destination: &str,
        client_id: &str,
        created_at: u32,
        content: &str,
    ) -> Result<crate::media_send::MediaSendResult> {
        let (destination, client_id, content) = (
            destination.to_owned(),
            client_id.to_owned(),
            content.to_owned(),
        );
        self.account_request(move |transport, state, _| {
            transport.send_share_snapshot(state, &destination, &client_id, created_at, &content)
        })
        .await
    }

    pub async fn send_quote(
        &self,
        destination: &str,
        client_id: &str,
        created_at: u32,
        content: &str,
        source: Option<&str>,
    ) -> Result<crate::media_send::MediaSendResult> {
        let (destination, client_id, content) = (
            destination.to_owned(),
            client_id.to_owned(),
            content.to_owned(),
        );
        let source = source.map(str::to_owned);
        self.account_request(move |transport, state, _| {
            transport.send_quote_with_source_snapshot(
                state,
                &destination,
                &client_id,
                created_at,
                &content,
                source.as_deref(),
            )
        })
        .await
    }

    pub async fn reserve_file_upload(
        &self,
        destination: &str,
        progress_client_id: &str,
        file_name: &str,
        plaintext_bytes: usize,
        md5: &str,
    ) -> Result<crate::file_upload::FileUploadReservation> {
        let (destination, progress_client_id, file_name, md5) = (
            destination.to_owned(),
            progress_client_id.to_owned(),
            file_name.to_owned(),
            md5.to_owned(),
        );
        self.account_request(move |transport, state, _| {
            transport.reserve_file_upload_snapshot(
                state,
                &destination,
                &progress_client_id,
                &file_name,
                plaintext_bytes,
                &md5,
            )
        })
        .await
    }

    pub async fn send_file(
        &self,
        destination: &str,
        client_id: &str,
        created_at: u32,
        upload: &crate::media::UploadedMedia,
        reservation: Option<&crate::file_upload::FileUploadReservation>,
    ) -> Result<crate::media_send::MediaSendResult> {
        let (destination, client_id) = (destination.to_owned(), client_id.to_owned());
        let upload = upload.clone();
        let reservation = reservation.cloned();
        self.account_request(move |transport, state, _| {
            transport.send_file_with_reservation_snapshot(
                state,
                &destination,
                &client_id,
                created_at,
                &upload,
                reservation.as_ref(),
            )
        })
        .await
    }

    /// Submit the uploaded standard and thumbnail copies, including an original when present.
    pub async fn send_image(
        &self,
        destination: &str,
        client_id: &str,
        upload: &crate::media::UploadedImage,
    ) -> Result<crate::media_send::MediaSendResult> {
        let (destination, client_id) = (destination.to_owned(), client_id.to_owned());
        let upload = upload.clone();
        self.account_request(move |transport, state, _| {
            transport.send_image_snapshot(state, &destination, &client_id, &upload)
        })
        .await
    }

    pub async fn send_video(
        &self,
        destination: &str,
        client_id: &str,
        upload: &crate::media::UploadedVideo,
        play_seconds: u32,
    ) -> Result<crate::media_send::MediaSendResult> {
        let (destination, client_id) = (destination.to_owned(), client_id.to_owned());
        let upload = upload.clone();
        self.account_request(move |transport, state, _| {
            transport.send_video_snapshot(state, &destination, &client_id, &upload, play_seconds)
        })
        .await
    }

    pub async fn send_voice(
        &self,
        destination: &str,
        client_id: &str,
        created_at: u32,
        duration_ms: u32,
        encoded: &[u8],
    ) -> Result<crate::media_send::MediaSendResult> {
        let (destination, client_id) = (destination.to_owned(), client_id.to_owned());
        let encoded = encoded.to_vec();
        self.account_request(move |transport, state, _| {
            transport.send_voice_snapshot(
                state,
                &destination,
                &client_id,
                created_at,
                duration_ms,
                &encoded,
            )
        })
        .await
    }

    /// Explicitly renew this account once. Concurrent requests from the prior
    /// credential generation cannot submit or adopt responses after acceptance.
    /// There is no QR fallback and no retry after an uncertain auth outcome.
    pub async fn renew_session(&self, computer_name: &str) -> Result<()> {
        let (exchange, state) = self.owned_account()?.begin()?;
        let exchange = Arc::new(exchange);
        let computer_name = computer_name.to_owned();
        let options = self.options.clone();
        let cancellation = Arc::new(AtomicBool::new(false));
        let _cancel_on_drop = CancelOnDrop(cancellation.clone());
        tokio::task::spawn_blocking(move || {
            let mut transport = NativeClient::new(options)?;
            let submission_exchange = exchange.clone();
            transport.submission_guard = Some(Arc::new(move || {
                ensure!(
                    !cancellation.load(Ordering::Acquire),
                    "Account authentication cancelled before submission"
                );
                submission_exchange.check()
            }));
            let returned = transport.renew_session_snapshot(&state, &computer_name)?;
            exchange.accept_credentials(returned)
        })
        .await
        .context("Account authentication worker failed")?
    }

    /// Fence admission, drain prior requests, then submit logout at most once.
    /// The owner stays stopped after rejection, cancellation or uncertainty;
    /// this operation does not revoke remembered-device trust or delete profiles.
    pub async fn logout(&self) -> Result<crate::LogoutReply> {
        self.prepare_logout()?.submit().await
    }

    /// Submit one text message without automatic renewal or retry. Inspect both
    /// receipt correlation fields and acceptance before reporting success.
    pub async fn send_text(
        &self,
        destination: &str,
        content: &str,
        options: TextSendOptions,
    ) -> Result<crate::TextSendResult> {
        self.send_text_guarded(destination, content, options, || Ok(()))
            .await
    }

    pub async fn send_text_guarded<F>(
        &self,
        destination: &str,
        content: &str,
        options: TextSendOptions,
        before_submit: F,
    ) -> Result<crate::TextSendResult>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
    {
        let destination = destination.to_owned();
        let content = content.to_owned();
        self.account_request(move |transport, state, _| {
            let request = crate::wire::text_send_request_with_source(
                &destination,
                &content,
                options.created_at,
                options.client_message_id,
                options.source.as_deref(),
            )?;
            let reply = transport.authenticated_rpc_guarded(
                state,
                522,
                "/cgi-bin/micromsg-bin/newsendmsg",
                &request,
                before_submit,
            )?;
            crate::wire::decode_text_send(&reply, &destination, options.client_message_id)
        })
        .await
    }

    /// Execute one call request using this client's account. No automatic retry.
    pub async fn call_rpc(
        &self,
        route: crate::calls::host_policy::CallHostRoute,
        request: Vec<u8>,
    ) -> Result<Vec<u8>> {
        self.call_rpc_guarded(route, request, || Ok(())).await
    }

    /// Recheck account lifetime and caller authority immediately before transport
    /// handoff. A returned error must not be interpreted as proof of no submission.
    pub async fn call_rpc_guarded<F>(
        &self,
        route: crate::calls::host_policy::CallHostRoute,
        request: Vec<u8>,
        before_submit: F,
    ) -> Result<Vec<u8>>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
    {
        self.call_rpc_observed(route, request, before_submit, |_| Ok(()))
            .await
    }

    /// Retain a verified call reply before adopting its cookie or returning it to
    /// the calling runtime. The callback must protect these account-specific
    /// bytes, must not log them, and must not reenter this client. Failure is an
    /// uncertain submitted operation, not permission to submit another request.
    pub async fn call_rpc_observed<F, O>(
        &self,
        route: crate::calls::host_policy::CallHostRoute,
        request: Vec<u8>,
        before_submit: F,
        retain_reply: O,
    ) -> Result<Vec<u8>>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
        O: Fn(&[u8]) -> Result<()> + Send + Sync + 'static,
    {
        self.account_request(move |transport, state, check| {
            let mut transport = transport.clone();
            transport.call_reply_observer = Some(Arc::new(retain_reply));
            transport.call_rpc_snapshot_guarded(state, route, &request, || {
                check()?;
                before_submit()
            })
        })
        .await
    }

    /// Poll call notifications with caller cancellation and account shutdown.
    /// Interruption is not proof that the read-only request was never submitted.
    pub async fn call_live_sync_guarded<F, C>(
        &self,
        request: Vec<u8>,
        before_submit: F,
        cancellation: C,
    ) -> Result<Vec<u8>>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
        C: Future<Output = ()> + Send + 'static,
    {
        self.call_live_sync_with_wait_timeout(
            request,
            self.options.timeout,
            before_submit,
            cancellation,
        )
        .await
    }

    /// Keep the handshake deadline independent of the long read-only wait.
    /// The caller owns any retry/reconciliation policy; this submits at most once.
    pub async fn call_live_sync_with_wait_timeout<F, C>(
        &self,
        request: Vec<u8>,
        wait_timeout: Duration,
        before_submit: F,
        cancellation: C,
    ) -> Result<Vec<u8>>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
        C: Future<Output = ()> + Send + 'static,
    {
        self.call_live_sync_observed(request, wait_timeout, before_submit, cancellation, |_| {
            Ok(())
        })
        .await
    }

    pub async fn call_live_sync_observed<F, C, O>(
        &self,
        request: Vec<u8>,
        wait_timeout: Duration,
        before_submit: F,
        cancellation: C,
        retain_reply: O,
    ) -> Result<Vec<u8>>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
        C: Future<Output = ()> + Send + 'static,
        O: Fn(&[u8]) -> Result<()> + Send + Sync + 'static,
    {
        ensure!(
            !wait_timeout.is_zero() && wait_timeout <= Duration::from_secs(120),
            "Invalid call poll wait timeout"
        );
        let runtime = tokio::runtime::Handle::current();
        let account = self.owned_account()?.clone();
        self.account_request(move |transport, state, check| {
            let mut transport = transport.clone();
            transport.call_reply_observer = Some(Arc::new(retain_reply));
            transport.call_live_sync_snapshot_with_wait_timeout(
                state,
                &request,
                wait_timeout,
                || {
                    check()?;
                    before_submit()
                },
                |reply| runtime.block_on(wait_for_poll(reply, cancellation, account.stopped())),
            )
        })
        .await
    }
}

impl NativeClient {
    /// Upload one direct custom-sticker chunk. Journal before submission and
    /// retain the receipt; failure does not authorize an automatic resend.
    pub async fn upload_sticker_chunk(
        &self,
        source: &[u8],
        offset: u32,
    ) -> Result<crate::sticker_upload::StickerUploadAcknowledgement> {
        let source = source.to_vec();
        self.account_request(move |transport, state, _| {
            transport.upload_sticker_chunk_snapshot(state, &source, offset)
        })
        .await
    }
    /// Read one custom-list page. The caller checks advancing cursors, retains
    /// the receipt and reconciles official-profile state after a complete list.
    pub async fn custom_sticker_page(
        &self,
        index: u32,
        data: &[u8],
    ) -> Result<crate::custom_stickers::CustomStickerPage> {
        let request = crate::custom_stickers::custom_sticker_list_request(index, data)?;
        self.account_request(move |transport, state, _| {
            transport.custom_sticker_read_snapshot(state, &request)
        })
        .await
    }
    /// Read transport metadata for known custom sticker identities.
    pub async fn custom_sticker_metadata(
        &self,
        ids: &[String],
    ) -> Result<crate::custom_stickers::CustomStickerPage> {
        let request = crate::custom_stickers::custom_sticker_metadata_request(ids)?;
        self.account_request(move |transport, state, _| {
            transport.custom_sticker_read_snapshot(state, &request)
        })
        .await
    }
    /// Submit one journaled Saved mutation and return the original response even
    /// on service rejection. Retain it before decoding and then refresh the list.
    /// A transport error after submission leaves an uncertain outcome.
    pub async fn mutate_custom_sticker(
        &self,
        id: &str,
        action: &crate::custom_stickers::CustomStickerMutation,
    ) -> Result<Vec<u8>> {
        let request = crate::custom_stickers::custom_sticker_mutation_request(id, action)?;
        self.account_request(move |transport, state, _| {
            transport.authenticated_rpc(
                state,
                698,
                "/cgi-bin/micromsg-bin/mmbackupemojioperate",
                &request,
            )
        })
        .await
    }
}

impl NativeClient {
    /// Read one public or account-added feed page. Check advancing cursors and
    /// consume the complete added feed before replacing membership in a profile.
    pub async fn sticker_pack_page(
        &self,
        feed: crate::sticker_packs::StickerPackFeed,
        cursor: &[u8],
    ) -> Result<crate::sticker_packs::StickerPackPage> {
        let cursor = cursor.to_vec();
        self.account_request(move |transport, state, _| {
            let request = crate::sticker_packs::sticker_pack_list_request(state, feed, &cursor)?;
            let raw = transport.sticker_pack_rpc_snapshot(state, 411, &request)?;
            crate::sticker_packs::decode_sticker_pack_page(&raw)
        })
        .await
    }
    /// Read product details and content references without adding or downloading it.
    pub async fn sticker_pack_detail(
        &self,
        id: &str,
    ) -> Result<crate::sticker_packs::StickerPackDetail> {
        let id = id.to_owned();
        self.account_request(move |transport, state, _| {
            let request = crate::sticker_packs::sticker_pack_detail_request(state, &id)?;
            let raw = transport.sticker_pack_rpc_snapshot(state, 412, &request)?;
            crate::sticker_packs::decode_sticker_pack_detail(&raw, &id)
        })
        .await
    }
    /// Read localized captions; their presence establishes neither membership nor entitlement.
    pub async fn sticker_pack_captions(
        &self,
        id: &str,
    ) -> Result<crate::sticker_packs::StickerPackCaptions> {
        let id = id.to_owned();
        self.account_request(move |transport, state, _| {
            let request = crate::sticker_packs::sticker_pack_captions_request(state, &id)?;
            let raw = transport.sticker_pack_rpc_snapshot(state, 521, &request)?;
            crate::sticker_packs::decode_sticker_pack_captions(&raw)
        })
        .await
    }
    /// Submit a single journaled eligible-free membership intent and retain the
    /// raw acknowledgement before interpreting acceptance. No automatic retry.
    pub async fn set_sticker_pack_membership_raw(&self, id: &str, added: bool) -> Result<Vec<u8>> {
        let id = id.to_owned();
        self.account_request(move |transport, state, _| {
            let request = crate::sticker_packs::sticker_pack_membership_request(state, &id, added)?;
            transport.sticker_pack_rpc_snapshot(state, 413, &request)
        })
        .await
    }
}