pub struct NativeClient { /* private fields */ }Expand description
Native account client and login bootstrap for supported WeChat operations.
Use Self::new for login bootstrap, then transfer accepted AccountState
into Self::from_account. Cloned account handles share accepted credentials
and lifecycle; methods such as Self::send_text and Self::sync run
blocking transport on Tokio workers without holding the state lock across
network waits. This client does not own a daemon, profile, send queue or
recovery journal. Explicit state export is secret data, not a second writer.
Implementations§
Source§impl NativeClient
impl NativeClient
Sourcepub fn with_request_options(&self, options: NativeOptions) -> Result<Self>
pub fn with_request_options(&self, options: NativeOptions) -> Result<Self>
Change transport deadlines/budgets for a handle while retaining the same account owner and admission rules. This never imports credential state.
Sourcepub fn request_blocking<T>(
&self,
operation: impl FnOnce(&mut AccountRequest<'_>) -> Result<T>,
) -> Result<T>
pub fn request_blocking<T>( &self, operation: impl FnOnce(&mut AccountRequest<'_>) -> Result<T>, ) -> Result<T>
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.
Sourcepub fn renew_session_blocking(&self, computer_name: &str) -> Result<()>
pub fn renew_session_blocking(&self, computer_name: &str) -> Result<()>
Explicit authentication renewal on an existing blocking worker. This never retries the operation whose rejection prompted the caller to renew.
Sourcepub fn logout_blocking(&self) -> Result<LogoutReply>
pub fn logout_blocking(&self) -> Result<LogoutReply>
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.
Sourcepub fn shutdown_blocking(&self) -> Result<()>
pub fn shutdown_blocking(&self) -> Result<()>
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.
Source§impl NativeClient
impl NativeClient
Sourcepub fn open_push_connection_blocking(&self) -> Result<AccountPushConnection>
pub fn open_push_connection_blocking(&self) -> Result<AccountPushConnection>
Open an authenticated notification transport on the caller’s blocking worker. Creating the transport does not start a hidden executor or loop.
Source§impl NativeClient
impl NativeClient
Sourcepub async fn sync(&self, cursor: &[u8]) -> Result<SyncBatch>
pub async fn sync(&self, cursor: &[u8]) -> Result<SyncBatch>
Fetch one sync page using the owned account. The application still owns command retention, projection and committing the returned cursor.
Examples found in repository?
5async fn main() -> anyhow::Result<()> {
6 if std::env::args().skip(1).any(|arg| arg == "--help") {
7 println!("sync_once: approve a test-account QR login and summarize one initial sync page.");
8 return Ok(());
9 }
10 let client = tokio::task::spawn_blocking(support::login).await??;
11 let identity = client.account_identity()?;
12 let batch = client.sync(&[]).await?;
13 let mut messages = 0;
14 for command in &batch.commands {
15 if command.id == 5 {
16 let _message = wechat_protocol::wire::decode_add_message(
17 &command.payload,
18 &identity.own_username,
19 )?;
20 messages += 1;
21 }
22 }
23 println!(
24 "commands={} add_messages={} other_commands={} continuation={}",
25 batch.commands.len(),
26 messages,
27 batch.commands.len() - messages,
28 batch.continuation
29 );
30 // This is a preview, not a sync consumer: all raw commands remain in `batch`,
31 // and we never save its returned cursor. A persistent client must retain and
32 // handle every required command before committing that cursor.
33 println!("Preview only. No history or sync cursor was saved.");
34 client.shutdown().await?;
35 Ok(())
36}pub async fn heartbeat(&self, cursor: &[u8]) -> Result<Heartbeat>
pub async fn sync_scene(&self, cursor: &[u8], scene: u32) -> Result<SyncBatch>
pub async fn lookup_contacts( &self, usernames: &[String], ) -> Result<ContactLookup>
pub async fn lookup_room( &self, room_id: &str, version: u32, ) -> Result<RoomRoster>
pub async fn init_contacts( &self, contact_sequence: u32, room_sequence: u32, ) -> Result<InitContactPage>
pub async fn download_avatars( &self, usernames: &[String], ) -> Result<Vec<AvatarBytes>>
pub async fn download_voice_chunk( &self, server_message_id: u64, total_length: u32, offset: u32, ) -> Result<VoiceChunk>
pub async fn cdn_config(&self) -> Result<CdnConfig>
pub async fn large_cdn_config(&self, route: LargeCdnRoute) -> Result<CdnConfig>
pub async fn group_inventory(&self, cursor: &[u8]) -> Result<GroupMetadataPage>
pub async fn lookup_contacts_raw(&self, usernames: &[String]) -> Result<Vec<u8>>
pub async fn lookup_contacts_receipt( &self, usernames: &[String], ) -> Result<MetadataReply<ContactLookup>>
pub async fn lookup_room_receipt( &self, room_id: &str, version: u32, ) -> Result<MetadataReply<RoomRoster>>
pub async fn lookup_room_raw( &self, room_id: &str, version: u32, ) -> Result<Vec<u8>>
pub async fn init_contacts_receipt( &self, contact_sequence: u32, room_sequence: u32, ) -> Result<MetadataReply<InitContactPage>>
pub async fn group_detail_raw(&self, group_id: &str) -> Result<Vec<u8>>
pub async fn group_mutation_raw(&self, request: &GroupRpc) -> Result<Vec<u8>>
pub async fn recall_message( &self, request: &MessageRecall, ) -> Result<MessageRecallReply>
pub async fn notify_read_session( &self, notification: &SessionReadNotification, ) -> Result<SessionReadReply>
pub async fn contact_sync( &self, cursor: &[u8], message_cursor: &[u8], continuation: bool, ) -> Result<ContactSyncBatch>
pub async fn send_quote( &self, destination: &str, client_id: &str, created_at: u32, content: &str, source: Option<&str>, ) -> Result<MediaSendResult>
pub async fn reserve_file_upload( &self, destination: &str, progress_client_id: &str, file_name: &str, plaintext_bytes: usize, md5: &str, ) -> Result<FileUploadReservation>
pub async fn send_file( &self, destination: &str, client_id: &str, created_at: u32, upload: &UploadedMedia, reservation: Option<&FileUploadReservation>, ) -> Result<MediaSendResult>
Sourcepub async fn send_image(
&self,
destination: &str,
client_id: &str,
upload: &UploadedImage,
) -> Result<MediaSendResult>
pub async fn send_image( &self, destination: &str, client_id: &str, upload: &UploadedImage, ) -> Result<MediaSendResult>
Submit the uploaded standard and thumbnail copies, including an original when present.
pub async fn send_video( &self, destination: &str, client_id: &str, upload: &UploadedVideo, play_seconds: u32, ) -> Result<MediaSendResult>
pub async fn send_voice( &self, destination: &str, client_id: &str, created_at: u32, duration_ms: u32, encoded: &[u8], ) -> Result<MediaSendResult>
Sourcepub async fn renew_session(&self, computer_name: &str) -> Result<()>
pub async fn renew_session(&self, computer_name: &str) -> Result<()>
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.
Sourcepub async fn logout(&self) -> Result<LogoutReply>
pub async fn logout(&self) -> Result<LogoutReply>
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.
Sourcepub async fn send_text(
&self,
destination: &str,
content: &str,
options: TextSendOptions,
) -> Result<TextSendResult>
pub async fn send_text( &self, destination: &str, content: &str, options: TextSendOptions, ) -> Result<TextSendResult>
Submit one text message without automatic renewal or retry. Inspect both receipt correlation fields and acceptance before reporting success.
Examples found in repository?
8async fn main() -> anyhow::Result<()> {
9 let args: Vec<_> = std::env::args().skip(1).collect();
10 if args.iter().any(|arg| arg == "--help") {
11 println!("send_text RECIPIENT TASK_ID TEXT\nUses a fresh test-account QR login and submits once.");
12 return Ok(());
13 }
14 ensure!(args.len() == 3, "Usage: send_text RECIPIENT TASK_ID TEXT");
15 let (recipient, task_id, text) = (&args[0], &args[1], &args[2]);
16 let client_id = wire::client_message_id(task_id.as_bytes());
17 ensure!(client_id != 0, "Choose another nonempty task ID");
18 // Validate arguments before requesting any login. A real application records
19 // this operation and timestamp before submitting it, and retains its result.
20 wire::text_send_request(recipient, text, wire::unix_time()?, client_id)?;
21 let client = tokio::task::spawn_blocking(support::login).await??;
22 let created_at = wire::unix_time()?;
23 let receipt = client
24 .send_text(
25 recipient,
26 text,
27 TextSendOptions {
28 created_at,
29 client_message_id: client_id,
30 source: None,
31 },
32 )
33 .await
34 .context(
35 "Send outcome may be uncertain. Investigate before submitting this operation again",
36 )?;
37 println!("{}", serde_json::to_string_pretty(&receipt)?);
38 ensure!(receipt.accepted, "The server rejected this text send");
39 ensure!(
40 receipt.returned_destination_matches && receipt.returned_client_id_matches,
41 "Receipt identity mismatch; investigate before submitting again"
42 );
43 client.shutdown().await?;
44 Ok(())
45}pub async fn send_text_guarded<F>( &self, destination: &str, content: &str, options: TextSendOptions, before_submit: F, ) -> Result<TextSendResult>
Sourcepub async fn call_rpc(
&self,
route: CallHostRoute,
request: Vec<u8>,
) -> Result<Vec<u8>>
pub async fn call_rpc( &self, route: CallHostRoute, request: Vec<u8>, ) -> Result<Vec<u8>>
Execute one call request using this client’s account. No automatic retry.
Sourcepub async fn call_rpc_guarded<F>(
&self,
route: CallHostRoute,
request: Vec<u8>,
before_submit: F,
) -> Result<Vec<u8>>
pub async fn call_rpc_guarded<F>( &self, route: CallHostRoute, request: Vec<u8>, before_submit: F, ) -> Result<Vec<u8>>
Recheck account lifetime and caller authority immediately before transport handoff. A returned error must not be interpreted as proof of no submission.
Sourcepub async fn call_rpc_observed<F, O>(
&self,
route: CallHostRoute,
request: Vec<u8>,
before_submit: F,
retain_reply: O,
) -> Result<Vec<u8>>
pub async fn call_rpc_observed<F, O>( &self, route: CallHostRoute, request: Vec<u8>, before_submit: F, retain_reply: O, ) -> Result<Vec<u8>>
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.
Sourcepub async fn call_live_sync_guarded<F, C>(
&self,
request: Vec<u8>,
before_submit: F,
cancellation: C,
) -> Result<Vec<u8>>
pub async fn call_live_sync_guarded<F, C>( &self, request: Vec<u8>, before_submit: F, cancellation: C, ) -> Result<Vec<u8>>
Poll call notifications with caller cancellation and account shutdown. Interruption is not proof that the read-only request was never submitted.
Sourcepub 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>>
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>>
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_observed<F, C, O>( &self, request: Vec<u8>, wait_timeout: Duration, before_submit: F, cancellation: C, retain_reply: O, ) -> Result<Vec<u8>>
Source§impl NativeClient
impl NativeClient
Sourcepub async fn upload_sticker_chunk(
&self,
source: &[u8],
offset: u32,
) -> Result<StickerUploadAcknowledgement>
pub async fn upload_sticker_chunk( &self, source: &[u8], offset: u32, ) -> Result<StickerUploadAcknowledgement>
Upload one direct custom-sticker chunk. Journal before submission and retain the receipt; failure does not authorize an automatic resend.
Sourcepub async fn custom_sticker_page(
&self,
index: u32,
data: &[u8],
) -> Result<CustomStickerPage>
pub async fn custom_sticker_page( &self, index: u32, data: &[u8], ) -> Result<CustomStickerPage>
Read one custom-list page. The caller checks advancing cursors, retains the receipt and reconciles official-profile state after a complete list.
Sourcepub async fn custom_sticker_metadata(
&self,
ids: &[String],
) -> Result<CustomStickerPage>
pub async fn custom_sticker_metadata( &self, ids: &[String], ) -> Result<CustomStickerPage>
Read transport metadata for known custom sticker identities.
Sourcepub async fn mutate_custom_sticker(
&self,
id: &str,
action: &CustomStickerMutation,
) -> Result<Vec<u8>>
pub async fn mutate_custom_sticker( &self, id: &str, action: &CustomStickerMutation, ) -> Result<Vec<u8>>
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.
Source§impl NativeClient
impl NativeClient
Sourcepub async fn sticker_pack_page(
&self,
feed: StickerPackFeed,
cursor: &[u8],
) -> Result<StickerPackPage>
pub async fn sticker_pack_page( &self, feed: StickerPackFeed, cursor: &[u8], ) -> Result<StickerPackPage>
Read one public or account-added feed page. Check advancing cursors and consume the complete added feed before replacing membership in a profile.
Sourcepub async fn sticker_pack_detail(&self, id: &str) -> Result<StickerPackDetail>
pub async fn sticker_pack_detail(&self, id: &str) -> Result<StickerPackDetail>
Read product details and content references without adding or downloading it.
Sourcepub async fn sticker_pack_captions(
&self,
id: &str,
) -> Result<StickerPackCaptions>
pub async fn sticker_pack_captions( &self, id: &str, ) -> Result<StickerPackCaptions>
Read localized captions; their presence establishes neither membership nor entitlement.
Source§impl NativeClient
impl NativeClient
Sourcepub fn from_account(state: AccountState, options: NativeOptions) -> Result<Self>
pub fn from_account(state: AccountState, options: NativeOptions) -> Result<Self>
Bind an accepted account to this client. Clones share the same owner; construction performs no network operation or credential persistence.
Examples found in repository?
12pub fn login() -> Result<NativeClient> {
13 let client = NativeClient::new(NativeOptions::default())?;
14 let device = DeviceProfile::generate("UnifiedPCLinux x86_64".into())?;
15 let qr_directory = wechat_platform::private_tempdir("wechat-protocol-example-")?;
16 let qr_path = qr_directory.path().join("login.png");
17 let mut attempt = client.start_qr_login(device, "Rust protocol example")?;
18 let mut qr = wechat_platform::OpenOptions::new()
19 .write(true)
20 .create_new(true)
21 .mode(0o600)
22 .open(&qr_path)?;
23 qr.write_all(&attempt.qr_png)?;
24 drop(qr);
25 eprintln!("Scan the private QR image: {}", qr_path.display());
26 eprintln!("Approve this example on the test account's phone.");
27 let deadline = Instant::now() + Duration::from_secs(600);
28 loop {
29 ensure!(Instant::now() < deadline, "Login example timed out");
30 match client.poll_login_guarded(&mut attempt, deadline, || false) {
31 Ok(LoginStatus::Approved) => {
32 let state = client.complete_login(&mut attempt)?;
33 eprintln!("Login complete; credentials remain in memory.");
34 return NativeClient::from_account(state, NativeOptions::default());
35 }
36 Ok(LoginStatus::Pending | LoginStatus::Scanned) => {}
37 Ok(status) => bail!("Login stopped: {status:?}"),
38 Err(error) if is_retryable_login_poll_error(&error) => {}
39 Err(error) => return Err(error),
40 }
41 // Only polling an already issued challenge is repeated. QR creation,
42 // credential exchange and sends are never automatically resubmitted.
43 thread::sleep(Duration::from_secs(2));
44 }
45}Sourcepub fn from_account_with_persistence(
state: AccountState,
options: NativeOptions,
persistence: Arc<dyn AccountPersistence>,
) -> Result<Self>
pub fn from_account_with_persistence( state: AccountState, options: NativeOptions, persistence: Arc<dyn AccountPersistence>, ) -> Result<Self>
Use a data-only storage callback for accepted updates. The supplied state must already be loaded from accepted storage; construction does not write it back or treat importing bytes as a new authentication acceptance.
pub fn account_status(&self) -> Result<AccountStatus>
Sourcepub fn account_identity(&self) -> Result<AccountIdentity>
pub fn account_identity(&self) -> Result<AccountIdentity>
Examples found in repository?
5async fn main() -> anyhow::Result<()> {
6 if std::env::args().skip(1).any(|arg| arg == "--help") {
7 println!("sync_once: approve a test-account QR login and summarize one initial sync page.");
8 return Ok(());
9 }
10 let client = tokio::task::spawn_blocking(support::login).await??;
11 let identity = client.account_identity()?;
12 let batch = client.sync(&[]).await?;
13 let mut messages = 0;
14 for command in &batch.commands {
15 if command.id == 5 {
16 let _message = wechat_protocol::wire::decode_add_message(
17 &command.payload,
18 &identity.own_username,
19 )?;
20 messages += 1;
21 }
22 }
23 println!(
24 "commands={} add_messages={} other_commands={} continuation={}",
25 batch.commands.len(),
26 messages,
27 batch.commands.len() - messages,
28 batch.continuation
29 );
30 // This is a preview, not a sync consumer: all raw commands remain in `batch`,
31 // and we never save its returned cursor. A persistent client must retain and
32 // handle every required command before committing that cursor.
33 println!("Preview only. No history or sync cursor was saved.");
34 client.shutdown().await?;
35 Ok(())
36}pub fn account_lease(&self) -> Result<AccountLease>
Sourcepub fn export_account_state(&self) -> Result<AccountState>
pub fn export_account_state(&self) -> Result<AccountState>
Export secret state for persistence. This snapshot does not transfer ownership or authorize another writer; use quiesce_and_export for handoff.
Sourcepub async fn shutdown(&self) -> Result<()>
pub async fn shutdown(&self) -> Result<()>
Stop account-bound admission and wait for admitted network workers to finish. Cancelling this future does not reopen admission.
Examples found in repository?
5async fn main() -> anyhow::Result<()> {
6 if std::env::args().skip(1).any(|arg| arg == "--help") {
7 println!("sync_once: approve a test-account QR login and summarize one initial sync page.");
8 return Ok(());
9 }
10 let client = tokio::task::spawn_blocking(support::login).await??;
11 let identity = client.account_identity()?;
12 let batch = client.sync(&[]).await?;
13 let mut messages = 0;
14 for command in &batch.commands {
15 if command.id == 5 {
16 let _message = wechat_protocol::wire::decode_add_message(
17 &command.payload,
18 &identity.own_username,
19 )?;
20 messages += 1;
21 }
22 }
23 println!(
24 "commands={} add_messages={} other_commands={} continuation={}",
25 batch.commands.len(),
26 messages,
27 batch.commands.len() - messages,
28 batch.continuation
29 );
30 // This is a preview, not a sync consumer: all raw commands remain in `batch`,
31 // and we never save its returned cursor. A persistent client must retain and
32 // handle every required command before committing that cursor.
33 println!("Preview only. No history or sync cursor was saved.");
34 client.shutdown().await?;
35 Ok(())
36}More examples
8async fn main() -> anyhow::Result<()> {
9 let args: Vec<_> = std::env::args().skip(1).collect();
10 if args.iter().any(|arg| arg == "--help") {
11 println!("send_text RECIPIENT TASK_ID TEXT\nUses a fresh test-account QR login and submits once.");
12 return Ok(());
13 }
14 ensure!(args.len() == 3, "Usage: send_text RECIPIENT TASK_ID TEXT");
15 let (recipient, task_id, text) = (&args[0], &args[1], &args[2]);
16 let client_id = wire::client_message_id(task_id.as_bytes());
17 ensure!(client_id != 0, "Choose another nonempty task ID");
18 // Validate arguments before requesting any login. A real application records
19 // this operation and timestamp before submitting it, and retains its result.
20 wire::text_send_request(recipient, text, wire::unix_time()?, client_id)?;
21 let client = tokio::task::spawn_blocking(support::login).await??;
22 let created_at = wire::unix_time()?;
23 let receipt = client
24 .send_text(
25 recipient,
26 text,
27 TextSendOptions {
28 created_at,
29 client_message_id: client_id,
30 source: None,
31 },
32 )
33 .await
34 .context(
35 "Send outcome may be uncertain. Investigate before submitting this operation again",
36 )?;
37 println!("{}", serde_json::to_string_pretty(&receipt)?);
38 ensure!(receipt.accepted, "The server rejected this text send");
39 ensure!(
40 receipt.returned_destination_matches && receipt.returned_client_id_matches,
41 "Receipt identity mismatch; investigate before submitting again"
42 );
43 client.shutdown().await?;
44 Ok(())
45}Sourcepub fn stop(&self) -> Result<()>
pub fn stop(&self) -> Result<()>
Fence new submissions immediately. Network requests already handed off retain their uncertain outcome; shutdown waits for their workers to exit.
Sourcepub fn prepare_logout(&self) -> Result<PendingLogout>
pub fn prepare_logout(&self) -> Result<PendingLogout>
Reserve one terminal operation before the embedding application commits its own local inhibition. No network work is started by reservation.
Sourcepub async fn stopped(&self) -> Result<()>
pub async fn stopped(&self) -> Result<()>
Completes when this account owner stops, including through another clone.
Sourcepub async fn quiesce_and_export(&self) -> Result<AccountState>
pub async fn quiesce_and_export(&self) -> Result<AccountState>
Stop and drain the client, then move its credentials out exactly once. All cloned handles remain stopped and cannot export the transferred state.
Source§impl NativeClient
impl NativeClient
Sourcepub fn new(options: NativeOptions) -> Result<Self>
pub fn new(options: NativeOptions) -> Result<Self>
Validate transport options. Construction itself makes no network request.
Examples found in repository?
12pub fn login() -> Result<NativeClient> {
13 let client = NativeClient::new(NativeOptions::default())?;
14 let device = DeviceProfile::generate("UnifiedPCLinux x86_64".into())?;
15 let qr_directory = wechat_platform::private_tempdir("wechat-protocol-example-")?;
16 let qr_path = qr_directory.path().join("login.png");
17 let mut attempt = client.start_qr_login(device, "Rust protocol example")?;
18 let mut qr = wechat_platform::OpenOptions::new()
19 .write(true)
20 .create_new(true)
21 .mode(0o600)
22 .open(&qr_path)?;
23 qr.write_all(&attempt.qr_png)?;
24 drop(qr);
25 eprintln!("Scan the private QR image: {}", qr_path.display());
26 eprintln!("Approve this example on the test account's phone.");
27 let deadline = Instant::now() + Duration::from_secs(600);
28 loop {
29 ensure!(Instant::now() < deadline, "Login example timed out");
30 match client.poll_login_guarded(&mut attempt, deadline, || false) {
31 Ok(LoginStatus::Approved) => {
32 let state = client.complete_login(&mut attempt)?;
33 eprintln!("Login complete; credentials remain in memory.");
34 return NativeClient::from_account(state, NativeOptions::default());
35 }
36 Ok(LoginStatus::Pending | LoginStatus::Scanned) => {}
37 Ok(status) => bail!("Login stopped: {status:?}"),
38 Err(error) if is_retryable_login_poll_error(&error) => {}
39 Err(error) => return Err(error),
40 }
41 // Only polling an already issued challenge is repeated. QR creation,
42 // credential exchange and sends are never automatically resubmitted.
43 thread::sleep(Duration::from_secs(2));
44 }
45}Sourcepub fn start_qr_login(
&self,
device: DeviceProfile,
computer_name: &str,
) -> Result<LoginAttempt>
pub fn start_qr_login( &self, device: DeviceProfile, computer_name: &str, ) -> Result<LoginAttempt>
Request one QR challenge for the supplied device. Display
LoginAttempt::qr_png privately, poll for phone approval, then call
Self::complete_login. This does not grant authorization by itself.
Examples found in repository?
12pub fn login() -> Result<NativeClient> {
13 let client = NativeClient::new(NativeOptions::default())?;
14 let device = DeviceProfile::generate("UnifiedPCLinux x86_64".into())?;
15 let qr_directory = wechat_platform::private_tempdir("wechat-protocol-example-")?;
16 let qr_path = qr_directory.path().join("login.png");
17 let mut attempt = client.start_qr_login(device, "Rust protocol example")?;
18 let mut qr = wechat_platform::OpenOptions::new()
19 .write(true)
20 .create_new(true)
21 .mode(0o600)
22 .open(&qr_path)?;
23 qr.write_all(&attempt.qr_png)?;
24 drop(qr);
25 eprintln!("Scan the private QR image: {}", qr_path.display());
26 eprintln!("Approve this example on the test account's phone.");
27 let deadline = Instant::now() + Duration::from_secs(600);
28 loop {
29 ensure!(Instant::now() < deadline, "Login example timed out");
30 match client.poll_login_guarded(&mut attempt, deadline, || false) {
31 Ok(LoginStatus::Approved) => {
32 let state = client.complete_login(&mut attempt)?;
33 eprintln!("Login complete; credentials remain in memory.");
34 return NativeClient::from_account(state, NativeOptions::default());
35 }
36 Ok(LoginStatus::Pending | LoginStatus::Scanned) => {}
37 Ok(status) => bail!("Login stopped: {status:?}"),
38 Err(error) if is_retryable_login_poll_error(&error) => {}
39 Err(error) => return Err(error),
40 }
41 // Only polling an already issued challenge is repeated. QR creation,
42 // credential exchange and sends are never automatically resubmitted.
43 thread::sleep(Duration::from_secs(2));
44 }
45}Sourcepub fn start_profile_qr_login(
&self,
device: DeviceProfile,
computer_name: &str,
key_info: &[u8],
) -> Result<LoginAttempt>
pub fn start_profile_qr_login( &self, device: DeviceProfile, computer_name: &str, key_info: &[u8], ) -> Result<LoginAttempt>
QR approval for an existing installation retains its selected key-info. This neither bypasses phone approval nor imports active authorization.
Sourcepub fn start_saved_device_login(
&self,
state: &AccountState,
computer_name: &str,
) -> Result<LoginAttempt>
pub fn start_saved_device_login( &self, state: &AccountState, computer_name: &str, ) -> Result<LoginAttempt>
Initiates phone approval for an existing remembered device without a QR. The caller chooses this fallback explicitly; no automatic auth retries occur.
Sourcepub fn start_profile_saved_device_login(
&self,
device: &DeviceProfile,
username: &str,
auto_auth_key: &[u8],
cookie: &[u8],
key_info: &[u8],
computer_name: &str,
) -> Result<LoginAttempt>
pub fn start_profile_saved_device_login( &self, device: &DeviceProfile, username: &str, auto_auth_key: &[u8], cookie: &[u8], key_info: &[u8], computer_name: &str, ) -> Result<LoginAttempt>
Use remembered official-profile trust without inventing active session keys.
Sourcepub fn poll_login(&self, attempt: &mut LoginAttempt) -> Result<LoginStatus>
pub fn poll_login(&self, attempt: &mut LoginAttempt) -> Result<LoginStatus>
Poll an existing challenge. Only LoginStatus::Approved permits
Self::complete_login; expired/rejected/cancelled attempts must stop.
Sourcepub fn poll_login_guarded(
&self,
attempt: &mut LoginAttempt,
deadline: Instant,
cancelled: impl Fn() -> bool + Send + Sync + 'static,
) -> Result<LoginStatus>
pub fn poll_login_guarded( &self, attempt: &mut LoginAttempt, deadline: Instant, cancelled: impl Fn() -> bool + Send + Sync + 'static, ) -> Result<LoginStatus>
The guard bounds the temporary LAN listener even while a blocking poll or upload is in flight. It must not perform blocking work itself.
Examples found in repository?
12pub fn login() -> Result<NativeClient> {
13 let client = NativeClient::new(NativeOptions::default())?;
14 let device = DeviceProfile::generate("UnifiedPCLinux x86_64".into())?;
15 let qr_directory = wechat_platform::private_tempdir("wechat-protocol-example-")?;
16 let qr_path = qr_directory.path().join("login.png");
17 let mut attempt = client.start_qr_login(device, "Rust protocol example")?;
18 let mut qr = wechat_platform::OpenOptions::new()
19 .write(true)
20 .create_new(true)
21 .mode(0o600)
22 .open(&qr_path)?;
23 qr.write_all(&attempt.qr_png)?;
24 drop(qr);
25 eprintln!("Scan the private QR image: {}", qr_path.display());
26 eprintln!("Approve this example on the test account's phone.");
27 let deadline = Instant::now() + Duration::from_secs(600);
28 loop {
29 ensure!(Instant::now() < deadline, "Login example timed out");
30 match client.poll_login_guarded(&mut attempt, deadline, || false) {
31 Ok(LoginStatus::Approved) => {
32 let state = client.complete_login(&mut attempt)?;
33 eprintln!("Login complete; credentials remain in memory.");
34 return NativeClient::from_account(state, NativeOptions::default());
35 }
36 Ok(LoginStatus::Pending | LoginStatus::Scanned) => {}
37 Ok(status) => bail!("Login stopped: {status:?}"),
38 Err(error) if is_retryable_login_poll_error(&error) => {}
39 Err(error) => return Err(error),
40 }
41 // Only polling an already issued challenge is repeated. QR creation,
42 // credential exchange and sends are never automatically resubmitted.
43 thread::sleep(Duration::from_secs(2));
44 }
45}Sourcepub fn complete_login(&self, attempt: &mut LoginAttempt) -> Result<AccountState>
pub fn complete_login(&self, attempt: &mut LoginAttempt) -> Result<AccountState>
Exchange an approved challenge for secret account credentials once. Keep the returned state in memory or an encrypted application vault.
Examples found in repository?
12pub fn login() -> Result<NativeClient> {
13 let client = NativeClient::new(NativeOptions::default())?;
14 let device = DeviceProfile::generate("UnifiedPCLinux x86_64".into())?;
15 let qr_directory = wechat_platform::private_tempdir("wechat-protocol-example-")?;
16 let qr_path = qr_directory.path().join("login.png");
17 let mut attempt = client.start_qr_login(device, "Rust protocol example")?;
18 let mut qr = wechat_platform::OpenOptions::new()
19 .write(true)
20 .create_new(true)
21 .mode(0o600)
22 .open(&qr_path)?;
23 qr.write_all(&attempt.qr_png)?;
24 drop(qr);
25 eprintln!("Scan the private QR image: {}", qr_path.display());
26 eprintln!("Approve this example on the test account's phone.");
27 let deadline = Instant::now() + Duration::from_secs(600);
28 loop {
29 ensure!(Instant::now() < deadline, "Login example timed out");
30 match client.poll_login_guarded(&mut attempt, deadline, || false) {
31 Ok(LoginStatus::Approved) => {
32 let state = client.complete_login(&mut attempt)?;
33 eprintln!("Login complete; credentials remain in memory.");
34 return NativeClient::from_account(state, NativeOptions::default());
35 }
36 Ok(LoginStatus::Pending | LoginStatus::Scanned) => {}
37 Ok(status) => bail!("Login stopped: {status:?}"),
38 Err(error) if is_retryable_login_poll_error(&error) => {}
39 Err(error) => return Err(error),
40 }
41 // Only polling an already issued challenge is repeated. QR creation,
42 // credential exchange and sends are never automatically resubmitted.
43 thread::sleep(Duration::from_secs(2));
44 }
45}Sourcepub fn refresh_qr_login(&self, attempt: &LoginAttempt) -> Result<LoginAttempt>
pub fn refresh_qr_login(&self, attempt: &LoginAttempt) -> Result<LoginAttempt>
Replace an expired, unscanned QR while preserving installation key-info.