Skip to main content

wechat_protocol/
account_operations.rs

1//! Account-owned asynchronous protocol operations.
2use super::*;
3
4impl NativeClient {
5    /// Fetch one sync page using the owned account. The application still owns
6    /// command retention, projection and committing the returned cursor.
7    pub async fn sync(&self, cursor: &[u8]) -> Result<crate::SyncBatch> {
8        let cursor = cursor.to_vec();
9        self.account_request(move |transport, state, _| transport.sync_snapshot(state, &cursor))
10            .await
11    }
12
13    pub async fn heartbeat(&self, cursor: &[u8]) -> Result<crate::Heartbeat> {
14        let cursor = cursor.to_vec();
15        self.account_request(move |transport, state, _| {
16            transport.heartbeat_snapshot(state, &cursor)
17        })
18        .await
19    }
20
21    pub async fn sync_scene(&self, cursor: &[u8], scene: u32) -> Result<crate::SyncBatch> {
22        let cursor = cursor.to_vec();
23        self.account_request(move |transport, state, _| {
24            transport.sync_scene_snapshot(state, &cursor, scene)
25        })
26        .await
27    }
28
29    pub async fn lookup_contacts(&self, usernames: &[String]) -> Result<crate::ContactLookup> {
30        let usernames = usernames.to_vec();
31        self.account_request(move |transport, state, _| {
32            transport.lookup_contacts_snapshot(state, &usernames)
33        })
34        .await
35    }
36
37    pub async fn lookup_room(&self, room_id: &str, version: u32) -> Result<crate::RoomRoster> {
38        let room_id = room_id.to_owned();
39        self.account_request(move |transport, state, _| {
40            transport.lookup_room_snapshot(state, &room_id, version)
41        })
42        .await
43    }
44
45    pub async fn init_contacts(
46        &self,
47        contact_sequence: u32,
48        room_sequence: u32,
49    ) -> Result<crate::InitContactPage> {
50        self.account_request(move |transport, state, _| {
51            transport.init_contacts_snapshot(state, contact_sequence, room_sequence)
52        })
53        .await
54    }
55
56    pub async fn download_avatars(&self, usernames: &[String]) -> Result<Vec<crate::AvatarBytes>> {
57        let usernames = usernames.to_vec();
58        self.account_request(move |transport, state, _| {
59            transport.download_avatars_snapshot(state, &usernames)
60        })
61        .await
62    }
63
64    pub async fn download_voice_chunk(
65        &self,
66        server_message_id: u64,
67        total_length: u32,
68        offset: u32,
69    ) -> Result<crate::VoiceChunk> {
70        self.account_request(move |transport, state, _| {
71            transport.download_voice_chunk_snapshot(state, server_message_id, total_length, offset)
72        })
73        .await
74    }
75
76    pub async fn cdn_config(&self) -> Result<crate::media::CdnConfig> {
77        self.account_request(|transport, state, _| transport.cdn_config_snapshot(state))
78            .await
79    }
80
81    pub async fn large_cdn_config(
82        &self,
83        route: crate::media::LargeCdnRoute,
84    ) -> Result<crate::media::CdnConfig> {
85        self.account_request(move |transport, state, _| {
86            transport.large_cdn_config_snapshot(state, route)
87        })
88        .await
89    }
90
91    pub async fn group_inventory(&self, cursor: &[u8]) -> Result<crate::GroupMetadataPage> {
92        let cursor = cursor.to_vec();
93        self.account_request(move |transport, state, _| {
94            transport.group_inventory_snapshot(state, &cursor)
95        })
96        .await
97    }
98
99    pub async fn lookup_contacts_raw(&self, usernames: &[String]) -> Result<Vec<u8>> {
100        let usernames = usernames.to_vec();
101        self.account_request(move |transport, state, _| {
102            transport.lookup_contacts_raw_snapshot(state, &usernames)
103        })
104        .await
105    }
106
107    pub async fn lookup_contacts_receipt(
108        &self,
109        usernames: &[String],
110    ) -> Result<crate::MetadataReply<crate::ContactLookup>> {
111        let usernames = usernames.to_vec();
112        self.account_request(move |transport, state, _| {
113            transport.lookup_contacts_receipt_snapshot(state, &usernames)
114        })
115        .await
116    }
117
118    pub async fn lookup_room_receipt(
119        &self,
120        room_id: &str,
121        version: u32,
122    ) -> Result<crate::MetadataReply<crate::RoomRoster>> {
123        let room_id = room_id.to_owned();
124        self.account_request(move |transport, state, _| {
125            transport.lookup_room_receipt_snapshot(state, &room_id, version)
126        })
127        .await
128    }
129
130    pub async fn lookup_room_raw(&self, room_id: &str, version: u32) -> Result<Vec<u8>> {
131        let room_id = room_id.to_owned();
132        self.account_request(move |transport, state, _| {
133            transport.lookup_room_raw_snapshot(state, &room_id, version)
134        })
135        .await
136    }
137
138    pub async fn init_contacts_receipt(
139        &self,
140        contact_sequence: u32,
141        room_sequence: u32,
142    ) -> Result<crate::MetadataReply<crate::InitContactPage>> {
143        self.account_request(move |transport, state, _| {
144            transport.init_contacts_receipt_snapshot(state, contact_sequence, room_sequence)
145        })
146        .await
147    }
148
149    pub async fn group_detail_raw(&self, group_id: &str) -> Result<Vec<u8>> {
150        let group_id = group_id.to_owned();
151        self.account_request(move |transport, state, _| {
152            transport.group_detail_raw_snapshot(state, &group_id)
153        })
154        .await
155    }
156
157    pub async fn group_mutation_raw(&self, request: &crate::GroupRpc) -> Result<Vec<u8>> {
158        let request = request.clone();
159        self.account_request(move |transport, state, _| {
160            transport.group_mutation_raw_snapshot(state, &request)
161        })
162        .await
163    }
164
165    pub async fn recall_message(
166        &self,
167        request: &crate::MessageRecall,
168    ) -> Result<crate::MessageRecallReply> {
169        let request = request.clone();
170        self.account_request(move |transport, state, _| {
171            transport.recall_message_snapshot(state, &request)
172        })
173        .await
174    }
175
176    pub async fn notify_read_session(
177        &self,
178        notification: &crate::SessionReadNotification,
179    ) -> Result<crate::SessionReadReply> {
180        let notification = notification.clone();
181        self.account_request(move |transport, state, _| {
182            transport.notify_read_session_snapshot(state, &notification)
183        })
184        .await
185    }
186
187    pub async fn contact_sync(
188        &self,
189        cursor: &[u8],
190        message_cursor: &[u8],
191        continuation: bool,
192    ) -> Result<crate::contact_sync::ContactSyncBatch> {
193        let cursor = cursor.to_vec();
194        let message_cursor = message_cursor.to_vec();
195        self.account_request(move |transport, state, _| {
196            transport.contact_sync_snapshot(state, &cursor, &message_cursor, continuation)
197        })
198        .await
199    }
200
201    pub async fn send_share(
202        &self,
203        destination: &str,
204        client_id: &str,
205        created_at: u32,
206        content: &str,
207    ) -> Result<crate::media_send::MediaSendResult> {
208        let (destination, client_id, content) = (
209            destination.to_owned(),
210            client_id.to_owned(),
211            content.to_owned(),
212        );
213        self.account_request(move |transport, state, _| {
214            transport.send_share_snapshot(state, &destination, &client_id, created_at, &content)
215        })
216        .await
217    }
218
219    pub async fn send_quote(
220        &self,
221        destination: &str,
222        client_id: &str,
223        created_at: u32,
224        content: &str,
225        source: Option<&str>,
226    ) -> Result<crate::media_send::MediaSendResult> {
227        let (destination, client_id, content) = (
228            destination.to_owned(),
229            client_id.to_owned(),
230            content.to_owned(),
231        );
232        let source = source.map(str::to_owned);
233        self.account_request(move |transport, state, _| {
234            transport.send_quote_with_source_snapshot(
235                state,
236                &destination,
237                &client_id,
238                created_at,
239                &content,
240                source.as_deref(),
241            )
242        })
243        .await
244    }
245
246    pub async fn reserve_file_upload(
247        &self,
248        destination: &str,
249        progress_client_id: &str,
250        file_name: &str,
251        plaintext_bytes: usize,
252        md5: &str,
253    ) -> Result<crate::file_upload::FileUploadReservation> {
254        let (destination, progress_client_id, file_name, md5) = (
255            destination.to_owned(),
256            progress_client_id.to_owned(),
257            file_name.to_owned(),
258            md5.to_owned(),
259        );
260        self.account_request(move |transport, state, _| {
261            transport.reserve_file_upload_snapshot(
262                state,
263                &destination,
264                &progress_client_id,
265                &file_name,
266                plaintext_bytes,
267                &md5,
268            )
269        })
270        .await
271    }
272
273    pub async fn send_file(
274        &self,
275        destination: &str,
276        client_id: &str,
277        created_at: u32,
278        upload: &crate::media::UploadedMedia,
279        reservation: Option<&crate::file_upload::FileUploadReservation>,
280    ) -> Result<crate::media_send::MediaSendResult> {
281        let (destination, client_id) = (destination.to_owned(), client_id.to_owned());
282        let upload = upload.clone();
283        let reservation = reservation.cloned();
284        self.account_request(move |transport, state, _| {
285            transport.send_file_with_reservation_snapshot(
286                state,
287                &destination,
288                &client_id,
289                created_at,
290                &upload,
291                reservation.as_ref(),
292            )
293        })
294        .await
295    }
296
297    /// Submit the uploaded standard and thumbnail copies, including an original when present.
298    pub async fn send_image(
299        &self,
300        destination: &str,
301        client_id: &str,
302        upload: &crate::media::UploadedImage,
303    ) -> Result<crate::media_send::MediaSendResult> {
304        let (destination, client_id) = (destination.to_owned(), client_id.to_owned());
305        let upload = upload.clone();
306        self.account_request(move |transport, state, _| {
307            transport.send_image_snapshot(state, &destination, &client_id, &upload)
308        })
309        .await
310    }
311
312    pub async fn send_video(
313        &self,
314        destination: &str,
315        client_id: &str,
316        upload: &crate::media::UploadedVideo,
317        play_seconds: u32,
318    ) -> Result<crate::media_send::MediaSendResult> {
319        let (destination, client_id) = (destination.to_owned(), client_id.to_owned());
320        let upload = upload.clone();
321        self.account_request(move |transport, state, _| {
322            transport.send_video_snapshot(state, &destination, &client_id, &upload, play_seconds)
323        })
324        .await
325    }
326
327    pub async fn send_voice(
328        &self,
329        destination: &str,
330        client_id: &str,
331        created_at: u32,
332        duration_ms: u32,
333        encoded: &[u8],
334    ) -> Result<crate::media_send::MediaSendResult> {
335        let (destination, client_id) = (destination.to_owned(), client_id.to_owned());
336        let encoded = encoded.to_vec();
337        self.account_request(move |transport, state, _| {
338            transport.send_voice_snapshot(
339                state,
340                &destination,
341                &client_id,
342                created_at,
343                duration_ms,
344                &encoded,
345            )
346        })
347        .await
348    }
349
350    /// Explicitly renew this account once. Concurrent requests from the prior
351    /// credential generation cannot submit or adopt responses after acceptance.
352    /// There is no QR fallback and no retry after an uncertain auth outcome.
353    pub async fn renew_session(&self, computer_name: &str) -> Result<()> {
354        let (exchange, state) = self.owned_account()?.begin()?;
355        let exchange = Arc::new(exchange);
356        let computer_name = computer_name.to_owned();
357        let options = self.options.clone();
358        let cancellation = Arc::new(AtomicBool::new(false));
359        let _cancel_on_drop = CancelOnDrop(cancellation.clone());
360        tokio::task::spawn_blocking(move || {
361            let mut transport = NativeClient::new(options)?;
362            let submission_exchange = exchange.clone();
363            transport.submission_guard = Some(Arc::new(move || {
364                ensure!(
365                    !cancellation.load(Ordering::Acquire),
366                    "Account authentication cancelled before submission"
367                );
368                submission_exchange.check()
369            }));
370            let returned = transport.renew_session_snapshot(&state, &computer_name)?;
371            exchange.accept_credentials(returned)
372        })
373        .await
374        .context("Account authentication worker failed")?
375    }
376
377    /// Fence admission, drain prior requests, then submit logout at most once.
378    /// The owner stays stopped after rejection, cancellation or uncertainty;
379    /// this operation does not revoke remembered-device trust or delete profiles.
380    pub async fn logout(&self) -> Result<crate::LogoutReply> {
381        self.prepare_logout()?.submit().await
382    }
383
384    /// Submit one text message without automatic renewal or retry. Inspect both
385    /// receipt correlation fields and acceptance before reporting success.
386    pub async fn send_text(
387        &self,
388        destination: &str,
389        content: &str,
390        options: TextSendOptions,
391    ) -> Result<crate::TextSendResult> {
392        self.send_text_guarded(destination, content, options, || Ok(()))
393            .await
394    }
395
396    pub async fn send_text_guarded<F>(
397        &self,
398        destination: &str,
399        content: &str,
400        options: TextSendOptions,
401        before_submit: F,
402    ) -> Result<crate::TextSendResult>
403    where
404        F: FnOnce() -> Result<()> + Send + 'static,
405    {
406        let destination = destination.to_owned();
407        let content = content.to_owned();
408        self.account_request(move |transport, state, _| {
409            let request = crate::wire::text_send_request_with_source(
410                &destination,
411                &content,
412                options.created_at,
413                options.client_message_id,
414                options.source.as_deref(),
415            )?;
416            let reply = transport.authenticated_rpc_guarded(
417                state,
418                522,
419                "/cgi-bin/micromsg-bin/newsendmsg",
420                &request,
421                before_submit,
422            )?;
423            crate::wire::decode_text_send(&reply, &destination, options.client_message_id)
424        })
425        .await
426    }
427
428    /// Execute one call request using this client's account. No automatic retry.
429    pub async fn call_rpc(
430        &self,
431        route: crate::calls::host_policy::CallHostRoute,
432        request: Vec<u8>,
433    ) -> Result<Vec<u8>> {
434        self.call_rpc_guarded(route, request, || Ok(())).await
435    }
436
437    /// Recheck account lifetime and caller authority immediately before transport
438    /// handoff. A returned error must not be interpreted as proof of no submission.
439    pub async fn call_rpc_guarded<F>(
440        &self,
441        route: crate::calls::host_policy::CallHostRoute,
442        request: Vec<u8>,
443        before_submit: F,
444    ) -> Result<Vec<u8>>
445    where
446        F: FnOnce() -> Result<()> + Send + 'static,
447    {
448        self.call_rpc_observed(route, request, before_submit, |_| Ok(()))
449            .await
450    }
451
452    /// Retain a verified call reply before adopting its cookie or returning it to
453    /// the calling runtime. The callback must protect these account-specific
454    /// bytes, must not log them, and must not reenter this client. Failure is an
455    /// uncertain submitted operation, not permission to submit another request.
456    pub async fn call_rpc_observed<F, O>(
457        &self,
458        route: crate::calls::host_policy::CallHostRoute,
459        request: Vec<u8>,
460        before_submit: F,
461        retain_reply: O,
462    ) -> Result<Vec<u8>>
463    where
464        F: FnOnce() -> Result<()> + Send + 'static,
465        O: Fn(&[u8]) -> Result<()> + Send + Sync + 'static,
466    {
467        self.account_request(move |transport, state, check| {
468            let mut transport = transport.clone();
469            transport.call_reply_observer = Some(Arc::new(retain_reply));
470            transport.call_rpc_snapshot_guarded(state, route, &request, || {
471                check()?;
472                before_submit()
473            })
474        })
475        .await
476    }
477
478    /// Poll call notifications with caller cancellation and account shutdown.
479    /// Interruption is not proof that the read-only request was never submitted.
480    pub async fn call_live_sync_guarded<F, C>(
481        &self,
482        request: Vec<u8>,
483        before_submit: F,
484        cancellation: C,
485    ) -> Result<Vec<u8>>
486    where
487        F: FnOnce() -> Result<()> + Send + 'static,
488        C: Future<Output = ()> + Send + 'static,
489    {
490        self.call_live_sync_with_wait_timeout(
491            request,
492            self.options.timeout,
493            before_submit,
494            cancellation,
495        )
496        .await
497    }
498
499    /// Keep the handshake deadline independent of the long read-only wait.
500    /// The caller owns any retry/reconciliation policy; this submits at most once.
501    pub async fn call_live_sync_with_wait_timeout<F, C>(
502        &self,
503        request: Vec<u8>,
504        wait_timeout: Duration,
505        before_submit: F,
506        cancellation: C,
507    ) -> Result<Vec<u8>>
508    where
509        F: FnOnce() -> Result<()> + Send + 'static,
510        C: Future<Output = ()> + Send + 'static,
511    {
512        self.call_live_sync_observed(request, wait_timeout, before_submit, cancellation, |_| {
513            Ok(())
514        })
515        .await
516    }
517
518    pub async fn call_live_sync_observed<F, C, O>(
519        &self,
520        request: Vec<u8>,
521        wait_timeout: Duration,
522        before_submit: F,
523        cancellation: C,
524        retain_reply: O,
525    ) -> Result<Vec<u8>>
526    where
527        F: FnOnce() -> Result<()> + Send + 'static,
528        C: Future<Output = ()> + Send + 'static,
529        O: Fn(&[u8]) -> Result<()> + Send + Sync + 'static,
530    {
531        ensure!(
532            !wait_timeout.is_zero() && wait_timeout <= Duration::from_secs(120),
533            "Invalid call poll wait timeout"
534        );
535        let runtime = tokio::runtime::Handle::current();
536        let account = self.owned_account()?.clone();
537        self.account_request(move |transport, state, check| {
538            let mut transport = transport.clone();
539            transport.call_reply_observer = Some(Arc::new(retain_reply));
540            transport.call_live_sync_snapshot_with_wait_timeout(
541                state,
542                &request,
543                wait_timeout,
544                || {
545                    check()?;
546                    before_submit()
547                },
548                |reply| runtime.block_on(wait_for_poll(reply, cancellation, account.stopped())),
549            )
550        })
551        .await
552    }
553}
554
555impl NativeClient {
556    /// Upload one direct custom-sticker chunk. Journal before submission and
557    /// retain the receipt; failure does not authorize an automatic resend.
558    pub async fn upload_sticker_chunk(
559        &self,
560        source: &[u8],
561        offset: u32,
562    ) -> Result<crate::sticker_upload::StickerUploadAcknowledgement> {
563        let source = source.to_vec();
564        self.account_request(move |transport, state, _| {
565            transport.upload_sticker_chunk_snapshot(state, &source, offset)
566        })
567        .await
568    }
569    /// Read one custom-list page. The caller checks advancing cursors, retains
570    /// the receipt and reconciles official-profile state after a complete list.
571    pub async fn custom_sticker_page(
572        &self,
573        index: u32,
574        data: &[u8],
575    ) -> Result<crate::custom_stickers::CustomStickerPage> {
576        let request = crate::custom_stickers::custom_sticker_list_request(index, data)?;
577        self.account_request(move |transport, state, _| {
578            transport.custom_sticker_read_snapshot(state, &request)
579        })
580        .await
581    }
582    /// Read transport metadata for known custom sticker identities.
583    pub async fn custom_sticker_metadata(
584        &self,
585        ids: &[String],
586    ) -> Result<crate::custom_stickers::CustomStickerPage> {
587        let request = crate::custom_stickers::custom_sticker_metadata_request(ids)?;
588        self.account_request(move |transport, state, _| {
589            transport.custom_sticker_read_snapshot(state, &request)
590        })
591        .await
592    }
593    /// Submit one journaled Saved mutation and return the original response even
594    /// on service rejection. Retain it before decoding and then refresh the list.
595    /// A transport error after submission leaves an uncertain outcome.
596    pub async fn mutate_custom_sticker(
597        &self,
598        id: &str,
599        action: &crate::custom_stickers::CustomStickerMutation,
600    ) -> Result<Vec<u8>> {
601        let request = crate::custom_stickers::custom_sticker_mutation_request(id, action)?;
602        self.account_request(move |transport, state, _| {
603            transport.authenticated_rpc(
604                state,
605                698,
606                "/cgi-bin/micromsg-bin/mmbackupemojioperate",
607                &request,
608            )
609        })
610        .await
611    }
612}
613
614impl NativeClient {
615    /// Read one public or account-added feed page. Check advancing cursors and
616    /// consume the complete added feed before replacing membership in a profile.
617    pub async fn sticker_pack_page(
618        &self,
619        feed: crate::sticker_packs::StickerPackFeed,
620        cursor: &[u8],
621    ) -> Result<crate::sticker_packs::StickerPackPage> {
622        let cursor = cursor.to_vec();
623        self.account_request(move |transport, state, _| {
624            let request = crate::sticker_packs::sticker_pack_list_request(state, feed, &cursor)?;
625            let raw = transport.sticker_pack_rpc_snapshot(state, 411, &request)?;
626            crate::sticker_packs::decode_sticker_pack_page(&raw)
627        })
628        .await
629    }
630    /// Read product details and content references without adding or downloading it.
631    pub async fn sticker_pack_detail(
632        &self,
633        id: &str,
634    ) -> Result<crate::sticker_packs::StickerPackDetail> {
635        let id = id.to_owned();
636        self.account_request(move |transport, state, _| {
637            let request = crate::sticker_packs::sticker_pack_detail_request(state, &id)?;
638            let raw = transport.sticker_pack_rpc_snapshot(state, 412, &request)?;
639            crate::sticker_packs::decode_sticker_pack_detail(&raw, &id)
640        })
641        .await
642    }
643    /// Read localized captions; their presence establishes neither membership nor entitlement.
644    pub async fn sticker_pack_captions(
645        &self,
646        id: &str,
647    ) -> Result<crate::sticker_packs::StickerPackCaptions> {
648        let id = id.to_owned();
649        self.account_request(move |transport, state, _| {
650            let request = crate::sticker_packs::sticker_pack_captions_request(state, &id)?;
651            let raw = transport.sticker_pack_rpc_snapshot(state, 521, &request)?;
652            crate::sticker_packs::decode_sticker_pack_captions(&raw)
653        })
654        .await
655    }
656    /// Submit a single journaled eligible-free membership intent and retain the
657    /// raw acknowledgement before interpreting acceptance. No automatic retry.
658    pub async fn set_sticker_pack_membership_raw(&self, id: &str, added: bool) -> Result<Vec<u8>> {
659        let id = id.to_owned();
660        self.account_request(move |transport, state, _| {
661            let request = crate::sticker_packs::sticker_pack_membership_request(state, &id, added)?;
662            transport.sticker_pack_rpc_snapshot(state, 413, &request)
663        })
664        .await
665    }
666}