Skip to main content

search/
search.rs

1use baidu_netdisk_sdk::{BaiduNetDiskClient, SearchOptions, SemanticSearchOptions};
2use log::info;
3use tokio::time::{sleep, Duration};
4
5async fn wait_for_rate_limit() {
6    sleep(Duration::from_millis(500)).await;
7}
8
9fn format_size(bytes: u64) -> String {
10    if bytes < 1024 {
11        format!("{} B", bytes)
12    } else if bytes < 1024 * 1024 {
13        format!("{:.2} KB", bytes as f64 / 1024.0)
14    } else if bytes < 1024 * 1024 * 1024 {
15        format!("{:.2} MB", bytes as f64 / (1024.0 * 1024.0))
16    } else {
17        format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
18    }
19}
20
21fn print_file_list(files: &[baidu_netdisk_sdk::FileInfo], title: &str) {
22    println!("{}", title);
23    if files.is_empty() {
24        println!("  (No files found)");
25        return;
26    }
27    for file in files.iter().take(10) {
28        let size_str = file
29            .size
30            .map(|s| format_size(s))
31            .unwrap_or_else(|| "N/A".to_string());
32        let file_type = if file.isdir == Some(1) {
33            "[DIR]"
34        } else {
35            "[FILE]"
36        };
37        println!("  {} {} ({})", file_type, file.name, size_str);
38    }
39    if files.len() > 10 {
40        println!("  ... and {} more files", files.len() - 10);
41    }
42}
43
44#[tokio::main]
45async fn main() -> Result<(), Box<dyn std::error::Error>> {
46    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
47
48    let client = BaiduNetDiskClient::builder().build()?;
49    info!("Client created successfully");
50
51    client.load_token_from_env()?;
52    info!("Token loaded successfully");
53
54    println!("=== Baidu NetDisk Search API Test ===");
55    println!();
56
57    // Part 1: Keyword Search (simple)
58    println!("--- Part 1: Keyword Search (simple) ---");
59    let (files, has_more) = client
60        .file()
61        .search_files("test", "/")
62        .await
63        .map_err(|e| format!("Search failed: {}", e))?;
64    print_file_list(&files, &format!("Results (has_more: {}):", has_more));
65    wait_for_rate_limit().await;
66
67    // Part 2: Keyword Search with category filter
68    println!("\n--- Part 2: Keyword Search with Category Filter ---");
69    println!("Searching for '*' in category 4 (Documents):");
70    let options = SearchOptions::new("/").category(4);
71
72    let (files, has_more) = client
73        .file()
74        .search_files_with_options("*", options)
75        .await
76        .map_err(|e| format!("Search failed: {}", e))?;
77    print_file_list(&files, &format!("Results (has_more: {}):", has_more));
78    wait_for_rate_limit().await;
79
80    // Part 3: Keyword Search with recursion
81    println!("\n--- Part 3: Keyword Search with Recursion ---");
82    println!("Recursive search for '*':");
83    let options = SearchOptions::new("/").recursion(true);
84    let (files, has_more) = client
85        .file()
86        .search_files_with_options("*", options)
87        .await
88        .map_err(|e| format!("Search failed: {}", e))?;
89    print_file_list(&files, &format!("Results (has_more: {}):", has_more));
90    wait_for_rate_limit().await;
91
92    // Part 4: Semantic Search (simple)
93    println!("\n--- Part 4: Semantic Search (simple query) ---");
94    println!("Query: \"find text files\"");
95    let files = client
96        .file()
97        .semantic_search("find text files")
98        .await
99        .map_err(|e| format!("Semantic search failed: {}", e))?;
100    print_file_list(&files, "Results:");
101
102    // Part 5: Semantic Search with options
103    println!("\n--- Part 5: Semantic Search with Options ---");
104    println!("Query: \"search for images\" (semantic mode)");
105    let options = SemanticSearchOptions::new().search_type(1);
106    let files = client
107        .file()
108        .semantic_search_with_options("search for images", options)
109        .await
110        .map_err(|e| format!("Semantic search failed: {}", e))?;
111    print_file_list(&files, "Results:");
112
113    // Part 6: Semantic Search with auto mode
114    println!("\n--- Part 6: Semantic Search (auto mode) ---");
115    println!("Query: \"video files\" (auto: uses keyword for short queries)");
116    let options = SemanticSearchOptions::new().search_type(2);
117    let files = client
118        .file()
119        .semantic_search_with_options("video files", options)
120        .await
121        .map_err(|e| format!("Semantic search failed: {}", e))?;
122    print_file_list(&files, "Results:");
123
124    println!("\n=== Test Completed ===");
125
126    Ok(())
127}