Skip to main content

NativeClient

Struct NativeClient 

Source
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

Source

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.

Source

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.

Source

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.

Source

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.

Source

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

Source

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

Source

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?
examples/sync_once.rs (line 12)
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}
Source

pub async fn heartbeat(&self, cursor: &[u8]) -> Result<Heartbeat>

Source

pub async fn sync_scene(&self, cursor: &[u8], scene: u32) -> Result<SyncBatch>

Source

pub async fn lookup_contacts( &self, usernames: &[String], ) -> Result<ContactLookup>

Source

pub async fn lookup_room( &self, room_id: &str, version: u32, ) -> Result<RoomRoster>

Source

pub async fn init_contacts( &self, contact_sequence: u32, room_sequence: u32, ) -> Result<InitContactPage>

Source

pub async fn download_avatars( &self, usernames: &[String], ) -> Result<Vec<AvatarBytes>>

Source

pub async fn download_voice_chunk( &self, server_message_id: u64, total_length: u32, offset: u32, ) -> Result<VoiceChunk>

Source

pub async fn cdn_config(&self) -> Result<CdnConfig>

Source

pub async fn large_cdn_config(&self, route: LargeCdnRoute) -> Result<CdnConfig>

Source

pub async fn group_inventory(&self, cursor: &[u8]) -> Result<GroupMetadataPage>

Source

pub async fn lookup_contacts_raw(&self, usernames: &[String]) -> Result<Vec<u8>>

Source

pub async fn lookup_contacts_receipt( &self, usernames: &[String], ) -> Result<MetadataReply<ContactLookup>>

Source

pub async fn lookup_room_receipt( &self, room_id: &str, version: u32, ) -> Result<MetadataReply<RoomRoster>>

Source

pub async fn lookup_room_raw( &self, room_id: &str, version: u32, ) -> Result<Vec<u8>>

Source

pub async fn init_contacts_receipt( &self, contact_sequence: u32, room_sequence: u32, ) -> Result<MetadataReply<InitContactPage>>

Source

pub async fn group_detail_raw(&self, group_id: &str) -> Result<Vec<u8>>

Source

pub async fn group_mutation_raw(&self, request: &GroupRpc) -> Result<Vec<u8>>

Source

pub async fn recall_message( &self, request: &MessageRecall, ) -> Result<MessageRecallReply>

Source

pub async fn notify_read_session( &self, notification: &SessionReadNotification, ) -> Result<SessionReadReply>

Source

pub async fn contact_sync( &self, cursor: &[u8], message_cursor: &[u8], continuation: bool, ) -> Result<ContactSyncBatch>

Source

pub async fn send_share( &self, destination: &str, client_id: &str, created_at: u32, content: &str, ) -> Result<MediaSendResult>

Source

pub async fn send_quote( &self, destination: &str, client_id: &str, created_at: u32, content: &str, source: Option<&str>, ) -> Result<MediaSendResult>

Source

pub async fn reserve_file_upload( &self, destination: &str, progress_client_id: &str, file_name: &str, plaintext_bytes: usize, md5: &str, ) -> Result<FileUploadReservation>

Source

pub async fn send_file( &self, destination: &str, client_id: &str, created_at: u32, upload: &UploadedMedia, reservation: Option<&FileUploadReservation>, ) -> Result<MediaSendResult>

Source

pub async fn send_image( &self, destination: &str, client_id: &str, upload: &UploadedImage, ) -> Result<MediaSendResult>

Source

pub async fn send_video( &self, destination: &str, client_id: &str, upload: &UploadedVideo, play_seconds: u32, ) -> Result<MediaSendResult>

Source

pub async fn send_voice( &self, destination: &str, client_id: &str, created_at: u32, duration_ms: u32, encoded: &[u8], ) -> Result<MediaSendResult>

Source

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.

Source

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.

Source

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?
examples/send_text.rs (lines 24-32)
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}
Source

pub async fn send_text_guarded<F>( &self, destination: &str, content: &str, options: TextSendOptions, before_submit: F, ) -> Result<TextSendResult>
where F: FnOnce() -> Result<()> + Send + 'static,

Source

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.

Source

pub async fn call_rpc_guarded<F>( &self, route: CallHostRoute, request: Vec<u8>, before_submit: F, ) -> Result<Vec<u8>>
where F: FnOnce() -> Result<()> + Send + 'static,

Recheck account lifetime and caller authority immediately before transport handoff. A returned error must not be interpreted as proof of no submission.

Source

pub async fn call_rpc_observed<F, O>( &self, route: 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,

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.

Source

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,

Poll call notifications with caller cancellation and account shutdown. Interruption is not proof that the read-only request was never submitted.

Source

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,

Keep the handshake deadline independent of the long read-only wait. The caller owns any retry/reconciliation policy; this submits at most once.

Source

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,

Source§

impl NativeClient

Source

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?
examples/support/mod.rs (line 34)
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}
Source

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.

Source

pub fn account_status(&self) -> Result<AccountStatus>

Source

pub fn account_identity(&self) -> Result<AccountIdentity>

Examples found in repository?
examples/sync_once.rs (line 11)
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}
Source

pub fn account_lease(&self) -> Result<AccountLease>

Source

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.

Source

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?
examples/sync_once.rs (line 34)
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
Hide additional examples
examples/send_text.rs (line 43)
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}
Source

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.

Source

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.

Source

pub async fn stopped(&self) -> Result<()>

Completes when this account owner stops, including through another clone.

Source

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

Source

pub fn new(options: NativeOptions) -> Result<Self>

Validate transport options. Construction itself makes no network request.

Examples found in repository?
examples/support/mod.rs (line 13)
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}
Source

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?
examples/support/mod.rs (line 17)
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}
Source

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.

Source

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.

Source

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.

Source

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.

Source

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?
examples/support/mod.rs (line 30)
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}
Source

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?
examples/support/mod.rs (line 32)
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}
Source

pub fn refresh_qr_login(&self, attempt: &LoginAttempt) -> Result<LoginAttempt>

Replace an expired, unscanned QR while preserving installation key-info.

Trait Implementations§

Source§

impl Clone for NativeClient

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more