1use super::*;
3
4pub struct AccountRequest<'a> {
9 transport: &'a NativeClient,
10 state: &'a mut AccountState,
11 spent: bool,
12}
13
14macro_rules! operation {
15 ($(#[$meta:meta])* $name:ident($($arg:ident: $ty:ty),*) -> $result:ty => $raw:ident) => {
16 $(#[$meta])*
17 pub fn $name(&mut self, $($arg: $ty),*) -> Result<$result> {
18 self.admit()?;
19 self.transport.$raw(self.state, $($arg),*)
20 }
21 };
22}
23
24impl AccountRequest<'_> {
25 pub fn upload_sticker_chunk(
28 &mut self,
29 source: &[u8],
30 offset: u32,
31 ) -> Result<crate::sticker_upload::StickerUploadAcknowledgement> {
32 self.admit()?;
33 self.transport
34 .upload_sticker_chunk_snapshot(self.state, source, offset)
35 }
36
37 pub fn custom_stickers_raw(&mut self, request: &[u8]) -> Result<Vec<u8>> {
40 self.admit()?;
41 ensure!(request.len() <= 65536, "sticker_request_limit");
42 self.transport.authenticated_rpc(
43 self.state,
44 697,
45 "/cgi-bin/micromsg-bin/mmbatchemojidownload",
46 request,
47 )
48 }
49 pub fn mutate_custom_sticker(
52 &mut self,
53 id: &str,
54 action: &crate::custom_stickers::CustomStickerMutation,
55 ) -> Result<Vec<u8>> {
56 let request = crate::custom_stickers::custom_sticker_mutation_request(id, action)?;
57 self.admit()?;
58 self.transport.authenticated_rpc(
59 self.state,
60 698,
61 "/cgi-bin/micromsg-bin/mmbackupemojioperate",
62 &request,
63 )
64 }
65 pub fn upload_sticker_chunk_raw(&mut self, source: &[u8], offset: u32) -> Result<Vec<u8>> {
68 let request = crate::sticker_upload::sticker_upload_request(source, offset)?;
69 self.admit()?;
70 self.transport.authenticated_rpc(
71 self.state,
72 703,
73 "/cgi-bin/micromsg-bin/mmemojiupload",
74 &request,
75 )
76 }
77
78 pub fn sticker_pack_page_raw(
80 &mut self,
81 feed: crate::sticker_packs::StickerPackFeed,
82 cursor: &[u8],
83 ) -> Result<Vec<u8>> {
84 let request = crate::sticker_packs::sticker_pack_list_request(self.state, feed, cursor)?;
85 self.admit()?;
86 self.transport
87 .sticker_pack_rpc_snapshot(self.state, 411, &request)
88 }
89 pub fn sticker_pack_detail_raw(&mut self, id: &str) -> Result<Vec<u8>> {
91 let request = crate::sticker_packs::sticker_pack_detail_request(self.state, id)?;
92 self.admit()?;
93 self.transport
94 .sticker_pack_rpc_snapshot(self.state, 412, &request)
95 }
96 pub fn sticker_pack_captions_raw(&mut self, id: &str) -> Result<Vec<u8>> {
98 let request = crate::sticker_packs::sticker_pack_captions_request(self.state, id)?;
99 self.admit()?;
100 self.transport
101 .sticker_pack_rpc_snapshot(self.state, 521, &request)
102 }
103 pub fn sticker_pack_membership_raw(&mut self, id: &str, added: bool) -> Result<Vec<u8>> {
107 let request = crate::sticker_packs::sticker_pack_membership_request(self.state, id, added)?;
108 self.admit()?;
109 self.transport
110 .sticker_pack_rpc_snapshot(self.state, 413, &request)
111 }
112
113 pub fn sticker_pack_acquisition_raw(&mut self, id: &str) -> Result<Vec<u8>> {
116 let request = crate::sticker_packs::sticker_pack_acquisition_request(self.state, id)?;
117 self.admit()?;
118 self.transport
119 .sticker_pack_rpc_snapshot(self.state, 423, &request)
120 }
121
122 pub fn send_sticker_chunk_raw(
125 &mut self,
126 chunk: &crate::sticker_send::StickerSendChunk<'_>,
127 ) -> Result<Vec<u8>> {
128 let request = crate::sticker_send::sticker_send_request(self.state, chunk)?;
129 self.admit()?;
130 self.transport.authenticated_rpc(
131 self.state,
132 175,
133 "/cgi-bin/micromsg-bin/sendemoji",
134 &request,
135 )
136 }
137
138 fn admit(&mut self) -> Result<()> {
139 ensure!(!self.spent, "Account request context already consumed");
142 self.spent = true;
143 Ok(())
144 }
145
146 pub fn account(&self) -> &AccountState {
149 self.state
150 }
151
152 pub fn lookup_openim_contact(
154 &mut self,
155 username: &str,
156 room: Option<&str>,
157 ticket: Option<&str>,
158 ) -> Result<crate::OpenImContact> {
159 self.admit()?;
160 self.transport
161 .openim_contact_snapshot(self.state, username, room, ticket)
162 }
163
164 pub fn lookup_openim_contact_raw(
166 &mut self,
167 username: &str,
168 room: Option<&str>,
169 ticket: Option<&str>,
170 ) -> Result<Vec<u8>> {
171 self.admit()?;
172 self.transport
173 .openim_contact_raw_snapshot(self.state, username, room, ticket)
174 }
175
176 operation!(sync(cursor: &[u8]) -> crate::SyncBatch => sync_snapshot);
177 operation!(sync_scene(cursor: &[u8], scene: u32) -> crate::SyncBatch => sync_scene_snapshot);
178 operation!(heartbeat(cursor: &[u8]) -> crate::Heartbeat => heartbeat_snapshot);
179 operation!(lookup_contacts(ids: &[String]) -> crate::ContactLookup => lookup_contacts_snapshot);
180 operation!(lookup_room(room: &str, version: u32) -> crate::RoomRoster => lookup_room_snapshot);
181 operation!(init_contacts(contact_sequence: u32, room_sequence: u32) -> crate::InitContactPage => init_contacts_snapshot);
182 operation!(download_avatars(ids: &[String]) -> Vec<crate::AvatarBytes> => download_avatars_snapshot);
183 operation!(download_voice_chunk(server_id: u64, length: u32, offset: u32) -> crate::VoiceChunk => download_voice_chunk_snapshot);
184 operation!(cdn_config() -> crate::media::CdnConfig => cdn_config_snapshot);
185 operation!(
186 channels_ticket() -> crate::ChannelsTicket => channels_ticket_snapshot);
188 operation!(
189 channels_page(post: &crate::ChannelsPost) -> crate::ChannelsPage => channels_page_snapshot);
191 operation!(
192 channels_media(post: &crate::ChannelsPost, ticket: &crate::ChannelsTicket, page: &crate::ChannelsPage) -> crate::ChannelsMedia => channels_media_snapshot);
195 operation!(large_cdn_config(route: crate::media::LargeCdnRoute) -> crate::media::CdnConfig => large_cdn_config_snapshot);
196 operation!(group_inventory(cursor: &[u8]) -> crate::GroupMetadataPage => group_inventory_snapshot);
197 operation!(lookup_contacts_raw(ids: &[String]) -> Vec<u8> => lookup_contacts_raw_snapshot);
198 operation!(lookup_contacts_receipt(ids: &[String]) -> crate::MetadataReply<crate::ContactLookup> => lookup_contacts_receipt_snapshot);
199 operation!(lookup_room_raw(room: &str, version: u32) -> Vec<u8> => lookup_room_raw_snapshot);
200 operation!(lookup_room_receipt(room: &str, version: u32) -> crate::MetadataReply<crate::RoomRoster> => lookup_room_receipt_snapshot);
201 operation!(init_contacts_receipt(contacts: u32, rooms: u32) -> crate::MetadataReply<crate::InitContactPage> => init_contacts_receipt_snapshot);
202 operation!(group_detail_raw(group: &str) -> Vec<u8> => group_detail_raw_snapshot);
203 operation!(group_mutation_raw(request: &crate::GroupRpc) -> Vec<u8> => group_mutation_raw_snapshot);
204 operation!(recall_message(request: &crate::MessageRecall) -> crate::MessageRecallReply => recall_message_snapshot);
205 operation!(notify_read_session(request: &crate::SessionReadNotification) -> crate::SessionReadReply => notify_read_session_snapshot);
206 operation!(contact_sync(cursor: &[u8], message_cursor: &[u8], continuation: bool) -> crate::contact_sync::ContactSyncBatch => contact_sync_snapshot);
207 operation!(send_share(destination: &str, client_id: &str, created_at: u32, content: &str) -> crate::media_send::MediaSendResult => send_share_snapshot);
208 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);
209 operation!(reserve_file_upload(destination: &str, client_id: &str, name: &str, length: usize, md5: &str) -> crate::file_upload::FileUploadReservation => reserve_file_upload_snapshot);
210 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);
211 pub fn send_image(
213 &mut self,
214 destination: &str,
215 client_id: &str,
216 upload: &crate::media::UploadedImage,
217 ) -> Result<crate::media_send::MediaSendResult> {
218 self.admit()?;
219 self.transport
220 .send_image_snapshot(self.state, destination, client_id, upload)
221 }
222
223 operation!(send_video(destination: &str, client_id: &str, upload: &crate::media::UploadedVideo, seconds: u32) -> crate::media_send::MediaSendResult => send_video_snapshot);
224 operation!(send_voice(destination: &str, client_id: &str, created_at: u32, duration_ms: u32, encoded: &[u8]) -> crate::media_send::MediaSendResult => send_voice_snapshot);
225
226 pub fn send_text(
227 &mut self,
228 destination: &str,
229 content: &str,
230 options: &TextSendOptions,
231 ) -> Result<crate::TextSendResult> {
232 self.send_text_guarded(destination, content, options, || Ok(()))
233 }
234
235 pub fn send_text_guarded(
236 &mut self,
237 destination: &str,
238 content: &str,
239 options: &TextSendOptions,
240 before_submit: impl FnOnce() -> Result<()>,
241 ) -> Result<crate::TextSendResult> {
242 self.admit()?;
243 let request = crate::wire::text_send_request_with_source(
244 destination,
245 content,
246 options.created_at,
247 options.client_message_id,
248 options.source.as_deref(),
249 )?;
250 let reply = self.transport.authenticated_rpc_guarded(
251 self.state,
252 522,
253 "/cgi-bin/micromsg-bin/newsendmsg",
254 &request,
255 before_submit,
256 )?;
257 crate::wire::decode_text_send(&reply, destination, options.client_message_id)
258 }
259
260 pub fn call_rpc(
261 &mut self,
262 route: crate::calls::host_policy::CallHostRoute,
263 request: &[u8],
264 before_submit: impl FnOnce() -> Result<()>,
265 retain_reply: impl FnOnce(&[u8]) -> Result<()>,
266 ) -> Result<Vec<u8>> {
267 self.admit()?;
268 let cookie = Zeroizing::new(self.state.cookie.clone());
269 let reply =
270 self.transport
271 .call_rpc_snapshot_guarded(self.state, route, request, before_submit)?;
272 if let Err(error) = retain_reply(&reply) {
273 zeroize::Zeroize::zeroize(&mut self.state.cookie);
276 self.state.cookie = cookie.to_vec();
277 return Err(error);
278 }
279 Ok(reply)
280 }
281
282 pub fn call_live_sync(
286 &mut self,
287 request: &[u8],
288 wait_timeout: Duration,
289 before_submit: impl FnOnce() -> Result<()>,
290 wait: impl for<'a> FnOnce(
291 std::pin::Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>>,
292 ) -> Result<Vec<u8>>,
293 retain_reply: impl FnOnce(&[u8]) -> Result<()>,
294 ) -> Result<Vec<u8>> {
295 self.admit()?;
296 let cookie = Zeroizing::new(self.state.cookie.clone());
297 let reply = self.transport.call_live_sync_snapshot_with_wait_timeout(
298 self.state,
299 request,
300 wait_timeout,
301 before_submit,
302 wait,
303 )?;
304 if let Err(error) = retain_reply(&reply) {
305 zeroize::Zeroize::zeroize(&mut self.state.cookie);
306 self.state.cookie = cookie.to_vec();
307 return Err(error);
308 }
309 Ok(reply)
310 }
311}
312
313impl NativeClient {
314 pub fn with_request_options(&self, options: NativeOptions) -> Result<Self> {
317 let mut handle = Self::new(options)?;
319 handle.account = Some(self.owned_account()?.clone());
320 Ok(handle)
321 }
322
323 pub fn request_blocking<T>(
327 &self,
328 operation: impl FnOnce(&mut AccountRequest<'_>) -> Result<T>,
329 ) -> Result<T> {
330 self.account_request_blocking(|transport, state, _| {
331 operation(&mut AccountRequest {
332 transport,
333 state,
334 spent: false,
335 })
336 })
337 }
338
339 pub fn renew_session_blocking(&self, computer_name: &str) -> Result<()> {
342 let (exchange, state) = self
343 .owned_account()?
344 .begin()
345 .map_err(|error| error.context(NativeRequestNotSubmitted))?;
346 let exchange = Arc::new(exchange);
347 let mut transport = Self::new(self.options.clone())?;
348 let submission = exchange.clone();
349 transport.submission_guard = Some(Arc::new(move || {
350 submission
351 .check()
352 .map_err(|error| error.context(NativeRequestNotSubmitted))
353 }));
354 let accepted = transport.renew_session_snapshot(&state, computer_name)?;
355 exchange.accept_credentials(accepted)
356 }
357
358 pub fn logout_blocking(&self) -> Result<crate::LogoutReply> {
362 self.prepare_logout()?.submit_blocking()
363 }
364
365 pub fn shutdown_blocking(&self) -> Result<()> {
368 self.owned_account()?.stop_and_drain_blocking()
369 }
370}
371
372#[cfg(test)]
373mod tests {
374 use super::*;
375
376 #[test]
377 fn scoped_requests_share_owner_and_cannot_submit_after_stop() {
378 let client = super::super::tests::client();
379 let other = client
380 .with_request_options(NativeOptions::default())
381 .unwrap();
382 other
383 .request_blocking(|request| {
384 assert_eq!(request.account().uin, 1);
385 request.admit()?;
386 request.state.cookie = vec![4];
387 Ok(())
388 })
389 .unwrap();
390 assert_eq!(client.export_account_state().unwrap().cookie, vec![4]);
391 client.stop().unwrap();
392 let entered = AtomicBool::new(false);
393 let error = other
394 .request_blocking(|_| {
395 entered.store(true, Ordering::Release);
396 Ok(())
397 })
398 .unwrap_err();
399 assert!(error.is::<NativeRequestNotSubmitted>());
400 assert!(!entered.load(Ordering::Acquire));
401 }
402
403 #[test]
404 fn scoped_context_cannot_turn_a_second_operation_into_an_unsent_retry() {
405 let client = super::super::tests::client();
406 let error = client
407 .request_blocking(|request| {
408 request.admit()?;
409 request.state.cookie = vec![7];
410 request.admit()
411 })
412 .unwrap_err();
413 assert!(!error.is::<NativeRequestNotSubmitted>());
414 assert_eq!(client.export_account_state().unwrap().cookie, vec![7]);
415 assert_eq!(client.account_status().unwrap().in_flight, 0);
416 }
417
418 #[tokio::test]
419 async fn blocking_workers_and_async_requests_share_one_response_order() {
420 let client = super::super::tests::client();
421 let old = client.clone();
422 let (ready, ready_rx) = tokio::sync::oneshot::channel();
423 let (finish, finish_rx) = std::sync::mpsc::channel();
424 let worker = tokio::task::spawn_blocking(move || {
425 old.request_blocking(|request| {
426 request.admit()?;
427 ready.send(()).unwrap();
428 finish_rx.recv()?;
429 request.state.cookie = vec![1];
430 Ok(())
431 })
432 });
433 ready_rx.await.unwrap();
434 client
435 .account_request(|_, state, _| {
436 state.cookie = vec![2];
437 Ok(())
438 })
439 .await
440 .unwrap();
441 finish.send(()).unwrap();
442 worker.await.unwrap().unwrap();
443 assert_eq!(client.export_account_state().unwrap().cookie, vec![2]);
444 }
445}