1use baidu_netdisk_sdk::{AccessToken, BaiduNetDiskClient, TokenStatus};
10use std::time::{SystemTime, UNIX_EPOCH};
11
12#[tokio::main]
13async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
14 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init();
15
16 println!("=== Baidu NetDisk Token Test ===\n");
17
18 let client = BaiduNetDiskClient::builder()
19 .auto_refresh(true)
20 .refresh_ahead_seconds(300)
21 .build()?;
22
23 println!("--- Part 1: Create AccessToken using builder ---");
24 let token = AccessToken::new(
25 "your_access_token".to_string(),
26 "your_refresh_token".to_string(),
27 2592000,
28 "basic netdisk".to_string(),
29 );
30 println!("✓ Created AccessToken");
31 println!(" Valid for: {} seconds", token.remaining_seconds());
32
33 println!("\n--- Part 2: Load Token from Environment ---");
34 client.load_token_from_env()?;
35
36 match client.get_valid_token().await {
37 Ok(token) => {
38 println!("✓ Token loaded from environment");
39 println!(" Scope: {}", token.scope);
40 println!(" Valid for: {} seconds", token.remaining_seconds());
41 }
42 Err(e) => {
43 println!("✗ Failed to load token: {}", e);
44 println!("\nSet these environment variables:");
45 println!(" BD_NETDISK_ACCESS_TOKEN");
46 println!(" BD_NETDISK_REFRESH_TOKEN");
47 println!(" BD_NETDISK_EXPIRES_IN");
48 }
49 }
50
51 println!("\n--- Part 3: Validate Token Status ---");
52 match client.validate_token() {
53 Ok(status) => match status {
54 TokenStatus::Valid => println!("✓ Token is valid"),
55 TokenStatus::ExpiringSoon => println!("⚠ Token is expiring soon (< 5 min)"),
56 TokenStatus::Expired => println!("✗ Token is expired"),
57 },
58 Err(e) => println!("✗ No token set: {}", e),
59 }
60
61 println!("\n--- Part 4: Test Expired Token Auto-Refresh ---");
62 let now = SystemTime::now()
63 .duration_since(UNIX_EPOCH)
64 .unwrap_or_default()
65 .as_secs();
66
67 let expired_token = AccessToken::with_all(
68 "test_access_token".to_string(),
69 "test_refresh_token".to_string(),
70 2592000,
71 "basic netdisk".to_string(),
72 String::new(),
73 String::new(),
74 now - 2592000 - 3600,
75 );
76
77 println!("Created expired token:");
78 println!(" Acquired: {} seconds ago", 2592000 + 3600);
79 match expired_token.validate() {
80 TokenStatus::Expired => println!(" Status: Expired ✓"),
81 _ => println!(" Status: Unexpected"),
82 }
83
84 client.set_access_token(expired_token)?;
85
86 println!("\nAttempting to get valid token (will try auto-refresh)...");
87 match client.get_valid_token().await {
88 Ok(new_token) => {
89 println!("✓ Auto-refresh succeeded!");
90 println!(
91 " New token valid for: {} seconds",
92 new_token.remaining_seconds()
93 );
94 }
95 Err(e) => {
96 println!("✗ Auto-refresh failed: {}", e);
97 println!(" → Need to re-authenticate via device code flow");
98 }
99 }
100
101 println!("\n=== Test Complete ===");
102 Ok(())
103}