Skip to main content

ClientBuilder

Struct ClientBuilder 

Source
pub struct ClientBuilder { /* private fields */ }

Implementations§

Source§

impl ClientBuilder

Source

pub fn app_id(self, app_id: &str) -> Self

Source

pub fn app_key(self, app_key: &str) -> Self

Examples found in repository?
examples/user_info.rs (line 11)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    env_logger::init();
7
8    println!("=== Baidu NetDisk User Info Test ===\n");
9
10    let client = BaiduNetDiskClient::builder()
11        .app_key("your_app_key")
12        .app_secret("your_app_secret")
13        .build()?;
14    info!("Client created successfully");
15
16    client.load_token_from_env()?;
17    info!("Token loaded successfully");
18
19    println!("Getting user info...");
20    let user_info = client.user().get_user_info(Some("v2")).await?;
21
22    println!("\n=== User Information ===");
23    println!("Baidu Name:    {}", user_info.baidu_name);
24    println!("NetDisk Name:  {}", user_info.netdisk_name);
25    println!("Avatar URL:    {}", user_info.avatar_url);
26    println!(
27        "VIP Type:      {}",
28        match user_info.vip_type {
29            0 => "Regular user",
30            1 => "VIP member",
31            2 => "SVIP super member",
32            _ => "Unknown",
33        }
34    );
35    println!("User ID (uk):  {}", user_info.uk);
36
37    Ok(())
38}
Source

pub fn app_secret(self, app_secret: &str) -> Self

Examples found in repository?
examples/user_info.rs (line 12)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    env_logger::init();
7
8    println!("=== Baidu NetDisk User Info Test ===\n");
9
10    let client = BaiduNetDiskClient::builder()
11        .app_key("your_app_key")
12        .app_secret("your_app_secret")
13        .build()?;
14    info!("Client created successfully");
15
16    client.load_token_from_env()?;
17    info!("Token loaded successfully");
18
19    println!("Getting user info...");
20    let user_info = client.user().get_user_info(Some("v2")).await?;
21
22    println!("\n=== User Information ===");
23    println!("Baidu Name:    {}", user_info.baidu_name);
24    println!("NetDisk Name:  {}", user_info.netdisk_name);
25    println!("Avatar URL:    {}", user_info.avatar_url);
26    println!(
27        "VIP Type:      {}",
28        match user_info.vip_type {
29            0 => "Regular user",
30            1 => "VIP member",
31            2 => "SVIP super member",
32            _ => "Unknown",
33        }
34    );
35    println!("User ID (uk):  {}", user_info.uk);
36
37    Ok(())
38}
Source

pub fn app_name(self, app_name: &str) -> Self

Source

pub fn scope(self, scope: &str) -> Self

Source

pub fn timeout(self, timeout: Duration) -> Self

Examples found in repository?
examples/auth_flow.rs (line 12)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init();
7
8    println!("=== Baidu NetDisk Auth Flow Example ===");
9    println!();
10
11    let client = BaiduNetDiskClient::builder()
12        .timeout(Duration::from_secs(30))
13        .build()?;
14
15    println!("Client created successfully");
16    println!();
17
18    println!("Step 1: Getting device code...");
19    let device_code = client.authorize().get_device_code().await?;
20
21    println!("Device Code Info:");
22    println!("  User Code: {}", device_code.user_code);
23    println!("  Verification URL: {}", device_code.verification_url);
24    println!("  QR Code URL: {}", device_code.qrcode_url);
25    println!("  Interval: {} seconds", device_code.interval);
26    println!(
27        "  Expires in: {} seconds",
28        device_code.expires_at - chrono::Utc::now().timestamp() as u64
29    );
30    println!();
31
32    println!("Please visit the verification URL above and enter the user code to authorize.");
33    println!("Waiting for authorization...");
34    println!();
35
36    let max_attempts = 30;
37    let mut attempts = 0;
38
39    let access_token = loop {
40        attempts += 1;
41
42        if attempts > max_attempts {
43            return Err("Max attempts reached, authorization timeout".into());
44        }
45
46        println!("Attempt {}/{}", attempts, max_attempts);
47
48        match client.authorize().request_access_token(&device_code).await {
49            Ok(Some(token)) => {
50                println!();
51                println!("✅ Authorization successful!");
52                break token;
53            }
54            Ok(None) => {
55                println!("  Authorization pending, waiting...");
56                tokio::time::sleep(Duration::from_secs(device_code.interval as u64)).await;
57                continue;
58            }
59            Err(e) => {
60                println!("  Error: {}", e);
61                tokio::time::sleep(Duration::from_secs(device_code.interval as u64)).await;
62                continue;
63            }
64        }
65    };
66
67    println!();
68    println!("=== Access Token Info ===");
69    println!("Access Token: {}", access_token.access_token);
70    println!("Expires in: {} seconds", access_token.expires_in);
71    println!("Refresh Token: {}", access_token.refresh_token);
72    println!("Scope: {}", access_token.scope);
73    println!("Session Key: {}", access_token.session_key);
74    println!("Session Secret: {}", access_token.session_secret);
75    println!("Acquired At: {}", access_token.acquired_at);
76    println!();
77
78    println!("=== Auth Flow Completed Successfully ===");
79
80    Ok(())
81}
Source

pub fn connect_timeout(self, timeout: Duration) -> Self

Source

pub fn max_retries(self, max_retries: usize) -> Self

Source

pub fn user_agent(self, user_agent: &str) -> Self

Source

pub fn auto_refresh(self, auto_refresh: bool) -> Self

Examples found in repository?
examples/token_test.rs (line 19)
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}
More examples
Hide additional examples
examples/token_refresh.rs (line 16)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8    // Initialize logger
9    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init();
10
11    println!("=== Token Refresh Test ===");
12    println!();
13
14    // Create client with auto-refresh enabled
15    let client = BaiduNetDiskClient::builder()
16        .auto_refresh(true)
17        .refresh_ahead_seconds(60)
18        .build()?;
19
20    println!("Client created successfully");
21    println!();
22
23    // Step 1: Load token from environment
24    println!("Step 1: Loading token from environment...");
25    client.load_token_from_env()?;
26    println!("Token loaded successfully");
27
28    let original_token = client.get_valid_token().await?;
29    println!("Original Token: {:?}", original_token);
30    println!();
31
32    // Step 2: Test manual refresh
33    println!("Step 2: Testing manual token refresh...");
34    match client.token_provider().refresh_token().await {
35        Ok(new_token) => {
36            println!("✓ Token refreshed successfully!");
37            println!("  New Access Token: {}", new_token.access_token);
38            println!("  New Refresh Token: {}", new_token.refresh_token);
39            println!("  Expires in: {} seconds", new_token.expires_in);
40            println!();
41
42            // Verify the tokens are different
43            if new_token.access_token != original_token.access_token {
44                println!("✓ Access token changed after refresh");
45            } else {
46                println!("✗ Access token remains the same");
47            }
48
49            // Verify refresh token may have changed
50            if new_token.refresh_token != original_token.refresh_token {
51                println!("✓ Refresh token changed after refresh");
52            } else {
53                println!("Note: Refresh token remains the same (may be expected)");
54            }
55        }
56        Err(e) => {
57            println!("✗ Failed to refresh token: {}", e);
58            println!("Note: This may be due to invalid credentials or network issues");
59        }
60    }
61
62    println!();
63
64    // Step 3: Test auto-refresh with expired token simulation
65    println!("Step 3: Testing auto-refresh behavior...");
66
67    // Create an expired token to test auto-refresh
68    let expired_token = AccessToken {
69        access_token: "expired_access_token".to_string(),
70        expires_in: 60,                                      // 60 seconds
71        refresh_token: original_token.refresh_token.clone(), // Use real refresh token
72        scope: "basic netdisk".to_string(),
73        session_key: "".to_string(),
74        session_secret: "".to_string(),
75        acquired_at: SystemTime::now()
76            .duration_since(UNIX_EPOCH)
77            .unwrap_or_default()
78            .as_secs()
79            - 3600, // 1 hour ago (expired)
80    };
81
82    client.set_access_token(expired_token)?;
83
84    // Now try to get valid token - should trigger auto-refresh
85    match client.get_valid_token().await {
86        Ok(refreshed_token) => {
87            println!("✓ Auto-refresh triggered successfully!");
88            println!("  New Access Token: {}", refreshed_token.access_token);
89            println!(
90                "  Expires in: {} seconds",
91                refreshed_token.remaining_seconds()
92            );
93        }
94        Err(e) => {
95            println!("✗ Auto-refresh failed: {}", e);
96            println!("Note: This may be due to invalid credentials");
97        }
98    }
99
100    println!();
101    println!("=== Refresh test completed ===");
102    Ok(())
103}
Source

pub fn refresh_ahead_seconds(self, seconds: u64) -> Self

Examples found in repository?
examples/token_test.rs (line 20)
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}
More examples
Hide additional examples
examples/token_refresh.rs (line 17)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8    // Initialize logger
9    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init();
10
11    println!("=== Token Refresh Test ===");
12    println!();
13
14    // Create client with auto-refresh enabled
15    let client = BaiduNetDiskClient::builder()
16        .auto_refresh(true)
17        .refresh_ahead_seconds(60)
18        .build()?;
19
20    println!("Client created successfully");
21    println!();
22
23    // Step 1: Load token from environment
24    println!("Step 1: Loading token from environment...");
25    client.load_token_from_env()?;
26    println!("Token loaded successfully");
27
28    let original_token = client.get_valid_token().await?;
29    println!("Original Token: {:?}", original_token);
30    println!();
31
32    // Step 2: Test manual refresh
33    println!("Step 2: Testing manual token refresh...");
34    match client.token_provider().refresh_token().await {
35        Ok(new_token) => {
36            println!("✓ Token refreshed successfully!");
37            println!("  New Access Token: {}", new_token.access_token);
38            println!("  New Refresh Token: {}", new_token.refresh_token);
39            println!("  Expires in: {} seconds", new_token.expires_in);
40            println!();
41
42            // Verify the tokens are different
43            if new_token.access_token != original_token.access_token {
44                println!("✓ Access token changed after refresh");
45            } else {
46                println!("✗ Access token remains the same");
47            }
48
49            // Verify refresh token may have changed
50            if new_token.refresh_token != original_token.refresh_token {
51                println!("✓ Refresh token changed after refresh");
52            } else {
53                println!("Note: Refresh token remains the same (may be expected)");
54            }
55        }
56        Err(e) => {
57            println!("✗ Failed to refresh token: {}", e);
58            println!("Note: This may be due to invalid credentials or network issues");
59        }
60    }
61
62    println!();
63
64    // Step 3: Test auto-refresh with expired token simulation
65    println!("Step 3: Testing auto-refresh behavior...");
66
67    // Create an expired token to test auto-refresh
68    let expired_token = AccessToken {
69        access_token: "expired_access_token".to_string(),
70        expires_in: 60,                                      // 60 seconds
71        refresh_token: original_token.refresh_token.clone(), // Use real refresh token
72        scope: "basic netdisk".to_string(),
73        session_key: "".to_string(),
74        session_secret: "".to_string(),
75        acquired_at: SystemTime::now()
76            .duration_since(UNIX_EPOCH)
77            .unwrap_or_default()
78            .as_secs()
79            - 3600, // 1 hour ago (expired)
80    };
81
82    client.set_access_token(expired_token)?;
83
84    // Now try to get valid token - should trigger auto-refresh
85    match client.get_valid_token().await {
86        Ok(refreshed_token) => {
87            println!("✓ Auto-refresh triggered successfully!");
88            println!("  New Access Token: {}", refreshed_token.access_token);
89            println!(
90                "  Expires in: {} seconds",
91                refreshed_token.remaining_seconds()
92            );
93        }
94        Err(e) => {
95            println!("✗ Auto-refresh failed: {}", e);
96            println!("Note: This may be due to invalid credentials");
97        }
98    }
99
100    println!();
101    println!("=== Refresh test completed ===");
102    Ok(())
103}
Source

pub fn build(self) -> NetDiskResult<BaiduNetDiskClient>

Examples found in repository?
examples/user_info.rs (line 13)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    env_logger::init();
7
8    println!("=== Baidu NetDisk User Info Test ===\n");
9
10    let client = BaiduNetDiskClient::builder()
11        .app_key("your_app_key")
12        .app_secret("your_app_secret")
13        .build()?;
14    info!("Client created successfully");
15
16    client.load_token_from_env()?;
17    info!("Token loaded successfully");
18
19    println!("Getting user info...");
20    let user_info = client.user().get_user_info(Some("v2")).await?;
21
22    println!("\n=== User Information ===");
23    println!("Baidu Name:    {}", user_info.baidu_name);
24    println!("NetDisk Name:  {}", user_info.netdisk_name);
25    println!("Avatar URL:    {}", user_info.avatar_url);
26    println!(
27        "VIP Type:      {}",
28        match user_info.vip_type {
29            0 => "Regular user",
30            1 => "VIP member",
31            2 => "SVIP super member",
32            _ => "Unknown",
33        }
34    );
35    println!("User ID (uk):  {}", user_info.uk);
36
37    Ok(())
38}
More examples
Hide additional examples
examples/category.rs (line 13)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
12
13    let client = BaiduNetDiskClient::builder().build()?;
14    info!("Client created successfully");
15
16    client.load_token_from_env()?;
17    info!("Token loaded successfully");
18
19    let test_dir = "/apps/product";
20
21    println!("=== Baidu NetDisk Category Test ===\n");
22
23    println!("Testing directory: {}\n", test_dir);
24
25    println!("=== Part 1: Global Category Counts (All files) ===");
26    println!("----------------------------------------");
27    test_global_counts(&client).await?;
28
29    println!("\n\n=== Part 2: Category Counts in {} ===", test_dir);
30    println!("----------------------------------------");
31    test_directory_counts(&client, &test_dir).await?;
32
33    println!("\n\n=== Part 3: List Files in Each Category ===");
34    println!("----------------------------------------");
35    test_list_category_files(&client, &test_dir).await?;
36
37    println!("\n\n=== Category Test Completed ===");
38
39    Ok(())
40}
examples/upload_file.rs (line 8)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    env_logger::init();
7
8    let client = BaiduNetDiskClient::builder().build()?;
9    info!("Client created successfully");
10
11    client.load_token_from_env()?;
12    info!("Token loaded successfully");
13
14    let args: Vec<String> = std::env::args().collect();
15
16    if args.len() < 3 {
17        println!("Usage: {} <local_file> <remote_path>", args[0]);
18        println!("Example: {} test.txt /apps/test/test.txt", args[0]);
19        return Ok(());
20    }
21
22    let local_file = &args[1];
23    let remote_path = &args[2];
24
25    println!("=== Baidu NetDisk File Upload (Simple) ===");
26    println!("Local file: {}", local_file);
27    println!("Remote path: {}", remote_path);
28    println!();
29
30    let start_time = std::time::Instant::now();
31
32    let response = client.upload().upload_file(local_file, remote_path).await?;
33
34    println!("File uploaded successfully!");
35    println!("  FS ID: {}", response.fs_id);
36    println!("  Server filename: {:?}", response.server_filename);
37    println!("  Path: {}", response.path);
38    println!("  Size: {} bytes", response.size);
39    println!("  Category: {}", response.category);
40    println!("  MD5: {}", response.md5.unwrap_or_default());
41    println!("  Upload time: {:?}", start_time.elapsed());
42
43    Ok(())
44}
examples/upload_bytes.rs (line 8)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    env_logger::init();
7
8    let client = BaiduNetDiskClient::builder().build()?;
9    info!("Client created successfully");
10
11    client.load_token_from_env()?;
12    info!("Token loaded successfully");
13
14    let args: Vec<String> = std::env::args().collect();
15
16    let remote_path = if args.len() >= 2 {
17        &args[1]
18    } else {
19        "/upload/hello_bytes.txt"
20    };
21
22    println!("=== Baidu NetDisk Bytes Upload (Simple) ===");
23    println!("Remote path: {}", remote_path);
24    println!();
25
26    let test_data = b"Hello from upload_bytes! This is a simple byte array upload test.";
27    println!("Uploading {} bytes of data...", test_data.len());
28
29    let start_time = std::time::Instant::now();
30
31    let response = client.upload().upload_bytes(test_data, remote_path).await?;
32
33    println!("Bytes uploaded successfully!");
34    println!("  FS ID: {}", response.fs_id);
35    println!("  Server filename: {:?}", response.server_filename);
36    println!("  Path: {}", response.path);
37    println!("  Size: {} bytes", response.size);
38    println!("  Category: {}", response.category);
39    println!("  MD5: {}", response.md5.unwrap_or_default());
40    println!("  Upload time: {:?}", start_time.elapsed());
41
42    Ok(())
43}
examples/upload_reader.rs (line 9)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    env_logger::init();
8
9    let client = BaiduNetDiskClient::builder().build()?;
10    info!("Client created successfully");
11
12    client.load_token_from_env()?;
13    info!("Token loaded successfully");
14
15    let args: Vec<String> = std::env::args().collect();
16
17    let local_file = if args.len() >= 2 {
18        &args[1]
19    } else {
20        println!("Usage: {} <local_file> [remote_path]", args[0]);
21        println!("Example: {} test.txt /upload/test.txt", args[0]);
22        return Ok(());
23    };
24
25    let remote_path = if args.len() >= 3 {
26        &args[2]
27    } else {
28        "/upload/test_reader.txt"
29    };
30
31    println!("=== Baidu NetDisk Reader Upload ===");
32    println!("Local file: {}", local_file);
33    println!("Remote path: {}", remote_path);
34    println!();
35
36    let file = std::fs::File::open(local_file)?;
37    let metadata = file.metadata()?;
38    let file_size = metadata.len();
39
40    println!("File size: {} bytes", file_size);
41
42    let mut reader = BufReader::new(file);
43
44    let start_time = std::time::Instant::now();
45
46    let response = client
47        .upload()
48        .upload_reader(&mut reader, file_size, remote_path)
49        .await?;
50
51    println!("File uploaded successfully!");
52    println!("  FS ID: {}", response.fs_id);
53    println!("  Server filename: {:?}", response.server_filename);
54    println!("  Path: {}", response.path);
55    println!("  Size: {} bytes", response.size);
56    println!("  Category: {}", response.category);
57    println!("  MD5: {}", response.md5.unwrap_or_default());
58    println!("  Upload time: {:?}", start_time.elapsed());
59
60    Ok(())
61}
examples/upload_precreate.rs (line 46)
43async fn main() -> Result<(), Box<dyn std::error::Error>> {
44    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
45
46    let client = BaiduNetDiskClient::builder().build()?;
47    info!("Client created successfully");
48
49    client.load_token_from_env()?;
50    info!("Token loaded successfully");
51
52    let args: Vec<String> = std::env::args().collect();
53
54    if args.len() < 3 {
55        println!("Usage: {} <local_file> <remote_path>", args[0]);
56        println!("Example: {} test.txt /apps/test/test.txt", args[0]);
57        return Ok(());
58    }
59
60    let local_file = &args[1];
61    let remote_path = &args[2];
62
63    println!("=== Baidu NetDisk Preupload Test ===");
64    println!("Local file: {}", local_file);
65    println!("Remote path: {}", remote_path);
66    println!();
67
68    let (file_size, block_list) = get_file_md5blocks(local_file, 4 * 1024 * 1024)?;
69    let file_md5 = calculate_md5(local_file)?;
70
71    println!("File size: {} bytes", file_size);
72    println!("File MD5: {}", file_md5);
73    println!("Block count: {}", block_list.len());
74    println!("Block list: {:?}", block_list);
75    println!();
76
77    let options = PrecreateOptions::new(remote_path, file_size, block_list)
78        .content_md5(&file_md5)
79        .rtype(1);
80
81    println!("Sending precreate request...");
82    match client.upload().precreate(options).await {
83        Ok(response) => {
84            println!("Precreate success!");
85            println!("  Upload ID: {}", response.uploadid);
86            println!("  Path: {:?}", response.path);
87            println!("  Return type: {}", response.return_type);
88            println!("  Block list to upload: {:?}", response.block_list);
89        }
90        Err(e) => {
91            println!("Precreate failed: {}", e);
92        }
93    }
94
95    Ok(())
96}

Trait Implementations§

Source§

impl Clone for ClientBuilder

Source§

fn clone(&self) -> ClientBuilder

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
Source§

impl Debug for ClientBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ClientBuilder

Source§

fn default() -> ClientBuilder

Returns the “default value” for a type. 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: 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: 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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