pub struct FileClient { /* private fields */ }Expand description
Unified File Client
Provides access to all file operations through a single interface. Operations are implemented via extension traits in sub-modules.
§Examples
use baidu_netdisk_sdk::BaiduNetDiskClient;
let client = BaiduNetDiskClient::builder().build()?;
client.load_token_from_env()?;
// List files in directory
let files = client.file().list_directory("/").await?;
// Create a new folder
let folder = client.file().create_folder("/test").await?;Implementations§
Source§impl FileClient
impl FileClient
Sourcepub fn new(http_client: HttpClient, token_getter: Arc<dyn TokenGetter>) -> Self
pub fn new(http_client: HttpClient, token_getter: Arc<dyn TokenGetter>) -> Self
Create a new FileClient instance
Usually you don’t need to call this directly - use BaiduNetDiskClient::file() instead.
Sourcepub fn http_client(&self) -> &HttpClient
pub fn http_client(&self) -> &HttpClient
Get a reference to the internal HTTP client
Sourcepub async fn list_directory(&self, dir: &str) -> NetDiskResult<Vec<FileInfo>>
pub async fn list_directory(&self, dir: &str) -> NetDiskResult<Vec<FileInfo>>
List directory contents with default options
Examples found in repository?
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Initialize logger
8 env_logger::init();
9
10 println!("=== Baidu NetDisk File Management Test ===\n");
11
12 // Create client - will automatically load from .env file
13 let client = BaiduNetDiskClient::builder().build()?;
14 info!("Client created successfully");
15
16 // Load token from environment variables
17 client.load_token_from_env()?;
18 info!("Token loaded successfully");
19
20 // === Test 0: List root directory to verify permission ===
21 println!("=== Test 0: List Root Directory ===");
22 println!("Listing contents of root directory: /");
23 wait_for_enter();
24
25 match client.file().list_directory("/").await {
26 Ok(files) => {
27 println!("✓ Successfully listed root directory!");
28 println!(" Found {} items:", files.len());
29 for file in files {
30 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
31 let size_str = if let Some(s) = file.size {
32 format!("{} bytes", s)
33 } else {
34 "N/A".to_string()
35 };
36 println!(" [{}] {} ({})", type_str, file.name, size_str);
37 }
38 }
39 Err(e) => {
40 println!("! Failed to list root directory: {}", e);
41 println!(" Please check your token and permissions.");
42 return Ok(());
43 }
44 }
45
46 // Test folder and file paths
47 let test_folder = "/upload";
48 let test_file = "/upload/subscribe.json";
49 let test_folder_new = "/upload_new";
50 let test_file_new = "/upload_new/subscribe.json";
51 let test_file_renamed = "/upload_new/subscribe_renamed.json";
52
53 // === Test 1: Check if /upload folder exists ===
54 println!("\n=== Test 1: Check /upload folder ===");
55 println!("Checking folder: {}", test_folder);
56 wait_for_enter();
57
58 match client.file().get_file_info(test_folder).await {
59 Ok(info) => {
60 println!("✓ Folder /upload exists!");
61 println!(" fs_id: {:?}", info.fs_id);
62 println!(" path: {}", info.path);
63 println!(" isdir: {:?}", info.isdir);
64 println!(" ctime: {:?}", info.ctime);
65 println!(" mtime: {:?}", info.mtime);
66 }
67 Err(e) => {
68 println!(
69 "! Folder /upload does not exist or cannot be accessed: {}",
70 e
71 );
72 println!(" Please create the folder manually or check your permissions.");
73 return Ok(());
74 }
75 }
76
77 // === Test 2: List upload directory first ===
78 println!("\n=== Test 2: List /upload Directory ===");
79 println!("Listing contents of: {}", test_folder);
80 wait_for_enter();
81
82 let upload_files = match client.file().list_directory(test_folder).await {
83 Ok(files) => {
84 println!("✓ Directory listed successfully!");
85 println!(" Found {} items:", files.len());
86 for file in &files {
87 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
88 let size_str = if let Some(s) = file.size {
89 format!("{} bytes", s)
90 } else {
91 "N/A".to_string()
92 };
93 println!(" [{}] {} ({})", type_str, file.name, size_str);
94 }
95 Some(files)
96 }
97 Err(e) => {
98 println!("! Failed to list directory: {}", e);
99 None
100 }
101 };
102
103 // === Test 3: Check if subscribe.json exists ===
104 println!("\n=== Test 3: Check subscribe.json file ===");
105 println!("Checking file: {}", test_file);
106 wait_for_enter();
107
108 match client.file().get_file_info(test_file).await {
109 Ok(info) => {
110 println!("✓ File {} exists!", test_file);
111 println!(" fs_id: {:?}", info.fs_id);
112 println!(" path: {}", info.path);
113 println!(" name: {}", info.name);
114 println!(" size: {:?} bytes", info.size);
115 println!(" isdir: {:?}", info.isdir);
116 println!(" md5: {:?}", info.md5);
117 println!(" ctime: {:?}", info.ctime);
118 println!(" mtime: {:?}", info.mtime);
119 }
120 Err(e) => {
121 println!(
122 "! File {} does not exist or cannot be accessed: {}",
123 test_file, e
124 );
125 // If directory content is listed, show to user
126 if let Some(files) = upload_files {
127 println!(" Available files in /upload:");
128 for file in files {
129 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
130 println!(" [{}] {}", type_str, file.name);
131 }
132 }
133 return Ok(());
134 }
135 }
136
137 // === Test 4: Create new folder ===
138 println!("\n=== Test 4: Create Folder ===");
139 println!("Creating folder: {}", test_folder_new);
140 wait_for_enter();
141
142 match client.file().create_folder(test_folder_new).await {
143 Ok(folder) => {
144 println!("✓ Folder created successfully!");
145 println!(" fs_id: {:?}", folder.fs_id);
146 println!(" path: {}", folder.path);
147 println!(" ctime: {:?}", folder.ctime);
148 }
149 Err(e) => {
150 println!("! Failed to create folder: {}", e);
151 return Ok(());
152 }
153 }
154
155 // === Test 5: Copy file ===
156 println!("\n=== Test 5: Copy File ===");
157 println!("Copying file: {} -> {}", test_file, test_folder_new);
158 wait_for_enter();
159
160 match client.file().copy_file(test_file, test_folder_new).await {
161 Ok(_) => println!("✓ File copied successfully!"),
162 Err(e) => {
163 println!("! File copy failed: {}", e);
164 return Ok(());
165 }
166 }
167
168 // === Test 6: Verify copied file ===
169 println!("\n=== Test 6: Verify Copied File ===");
170 println!("Listing directory: {}", test_folder_new);
171 wait_for_enter();
172
173 let copied_files = match client.file().list_directory(test_folder_new).await {
174 Ok(files) => {
175 println!("✓ Directory listed!");
176 println!(" Found {} items:", files.len());
177 for file in &files {
178 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
179 let size_str = if let Some(s) = file.size {
180 format!("{} bytes", s)
181 } else {
182 "N/A".to_string()
183 };
184 println!(" [{}] {} ({})", type_str, file.name, size_str);
185 }
186 Some(files)
187 }
188 Err(e) => {
189 println!("! Failed to list directory: {}", e);
190 None
191 }
192 };
193
194 println!("\nChecking copied file: {}", test_file_new);
195 wait_for_enter();
196
197 match client.file().get_file_info(test_file_new).await {
198 Ok(info) => {
199 println!("✓ Copied file verified!");
200 println!(" name: {}", info.name);
201 println!(" size: {:?} bytes", info.size);
202 }
203 Err(e) => {
204 println!("! Failed to verify copied file: {}", e);
205 // If we listed the directory, show available files
206 if let Some(files) = copied_files {
207 println!(" Available files:");
208 for file in files {
209 println!(" {}", file.name);
210 }
211 }
212 return Ok(());
213 }
214 }
215
216 // === Test 7: Rename file ===
217 println!("\n=== Test 7: Rename File ===");
218 println!("Renaming file: {} -> {}", test_file_new, test_file_renamed);
219 wait_for_enter();
220
221 match client
222 .file()
223 .rename(test_file_new, "subscribe_renamed.json")
224 .await
225 {
226 Ok(_) => println!("✓ File renamed successfully!"),
227 Err(e) => {
228 println!("! File rename failed: {}", e);
229 return Ok(());
230 }
231 }
232
233 // === Test 8: Move file ===
234 println!("\n=== Test 8: Move File ===");
235 println!("Moving file: {} -> {}", test_file_renamed, test_folder);
236 wait_for_enter();
237
238 match client
239 .file()
240 .move_file(test_file_renamed, test_folder)
241 .await
242 {
243 Ok(_) => println!("✓ File moved successfully!"),
244 Err(e) => {
245 println!("! File move failed: {}", e);
246 return Ok(());
247 }
248 }
249
250 // === Test 9: Verify moved file ===
251 println!("\n=== Test 9: Verify Moved File ===");
252 let moved_file_path = "/upload/subscribe_renamed.json";
253 println!("Checking moved file: {}", moved_file_path);
254 wait_for_enter();
255
256 match client.file().get_file_info(moved_file_path).await {
257 Ok(info) => {
258 println!("✓ Moved file verified!");
259 println!(" name: {}", info.name);
260 println!(" path: {}", info.path);
261 }
262 Err(e) => {
263 println!("! Failed to verify moved file: {}", e);
264 return Ok(());
265 }
266 }
267
268 // === Test 10: Delete renamed file ===
269 println!("\n=== Test 10: Delete File ===");
270 println!("Deleting file: {}", moved_file_path);
271 wait_for_enter();
272
273 match client.file().delete(moved_file_path).await {
274 Ok(_) => println!("✓ File deleted successfully!"),
275 Err(e) => {
276 println!("! File deletion failed: {}", e);
277 return Ok(());
278 }
279 }
280
281 // === Test 11: Cleanup - Delete test folder ===
282 println!("\n=== Test 11: Cleanup ===");
283 println!("Deleting empty folder: {}", test_folder_new);
284 wait_for_enter();
285
286 match client.file().delete(test_folder_new).await {
287 Ok(_) => println!("✓ Test folder deleted successfully!"),
288 Err(e) => {
289 println!("! Failed to delete test folder: {}", e);
290 return Ok(());
291 }
292 }
293
294 // === Final verification ===
295 println!("\n=== Final Verification ===");
296 println!("Listing final contents of: {}", test_folder);
297 wait_for_enter();
298
299 match client.file().list_directory(test_folder).await {
300 Ok(files) => {
301 println!("✓ Final directory listing:");
302 println!(" Found {} items:", files.len());
303 for file in files {
304 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
305 println!(" [{}] {}", type_str, file.name);
306 }
307 }
308 Err(e) => {
309 println!("! Failed to list directory: {}", e);
310 return Ok(());
311 }
312 }
313
314 println!("\n=== All file management tests completed successfully! ===");
315
316 Ok(())
317}Sourcepub async fn list_directory_with_options(
&self,
dir: &str,
options: ListOptions,
) -> NetDiskResult<Vec<FileInfo>>
pub async fn list_directory_with_options( &self, dir: &str, options: ListOptions, ) -> NetDiskResult<Vec<FileInfo>>
List directory contents with custom options
Sourcepub async fn list_all(
&self,
path: &str,
start: i32,
limit: i32,
) -> NetDiskResult<ListAllResult>
pub async fn list_all( &self, path: &str, start: i32, limit: i32, ) -> NetDiskResult<ListAllResult>
List all files recursively with pagination
This method defaults to recursive mode and provides simple pagination.
For advanced options, use list_all_with_options() instead.
Examples found in repository?
17async fn main() -> Result<(), Box<dyn std::error::Error>> {
18 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
19
20 let client = BaiduNetDiskClient::builder().build()?;
21 info!("Client created successfully");
22
23 client.load_token_from_env()?;
24 info!("Token loaded successfully");
25
26 let test_dir = "/apps/chapters";
27 let page_size = 10;
28
29 println!("=== Baidu NetDisk ListAll Test ===");
30 println!("Directory: {}", test_dir);
31 println!("Page size: {}\n", page_size);
32
33 let mut start = 0;
34 let mut page_num = 1;
35 let mut total_files = 0;
36 let mut has_more = true;
37
38 while has_more {
39 // 使用简化的 list_all 方法,默认开启递归
40 match client.file().list_all(test_dir, start, page_size).await {
41 Ok(result) => {
42 has_more = result.has_more;
43
44 println!("--- Page {} ---", page_num);
45 println!("Found {} files in this page", result.list.len());
46
47 for file in &result.list {
48 let size_str = file
49 .size
50 .map(|s| format_size(s))
51 .unwrap_or_else(|| "N/A".to_string());
52 let is_dir = file.isdir.map(|i| i == 1).unwrap_or(false);
53 let file_type = if is_dir { "DIR" } else { "FILE" };
54
55 println!(" [{}] {} ({})", file_type, file.name, size_str);
56 }
57
58 total_files += result.list.len();
59
60 if has_more {
61 println!("\nPress Enter to continue to page {}...", page_num + 1);
62 println!("Next cursor: {:?}", result.cursor);
63 // 使用 cursor 作为下一页的 start,用户无需手动计算
64 if let Some(cursor) = result.cursor {
65 start = cursor as i32;
66 }
67 let mut input = String::new();
68 std::io::stdin().read_line(&mut input)?;
69 }
70 page_num += 1;
71 }
72 Err(e) => {
73 println!("Error: {}", e);
74 break;
75 }
76 }
77 }
78
79 println!("\n=== ListAll Test Completed ===");
80 println!("Total files found: {}", total_files);
81
82 Ok(())
83}Sourcepub async fn list_all_with_options(
&self,
path: &str,
options: ListAllOptions,
) -> NetDiskResult<ListAllResult>
pub async fn list_all_with_options( &self, path: &str, options: ListAllOptions, ) -> NetDiskResult<ListAllResult>
List all files recursively with custom options
Sourcepub async fn get_file_info(&self, path: &str) -> NetDiskResult<FileInfo>
pub async fn get_file_info(&self, path: &str) -> NetDiskResult<FileInfo>
Get file or folder information by path
Examples found in repository?
15async fn main() -> Result<(), Box<dyn std::error::Error>> {
16 // Initialize logger
17 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
18
19 // Create client
20 let client = BaiduNetDiskClient::builder().build()?;
21 info!("Client created successfully");
22
23 // Load token from environment
24 client.load_token_from_env()?;
25 info!("Token loaded successfully");
26
27 println!("=== Baidu NetDisk Download Test ===");
28 println!("Enter the remote file path to download (e.g., /upload/test.txt):");
29
30 let stdin = io::stdin();
31 let mut reader = stdin.lock();
32 let mut input = String::new();
33 reader.read_line(&mut input)?;
34 let remote_path = input.trim();
35
36 if remote_path.is_empty() {
37 eprintln!("Error: File path cannot be empty");
38 return Ok(());
39 }
40
41 // Step 1: Get file info (to obtain fs_id)
42 println!("\n--- Step 1: Get file info (to obtain fs_id) ---");
43 println!("Press Enter to continue...");
44 reader.read_line(&mut String::new())?;
45
46 let file_info = client.file().get_file_info(remote_path).await?;
47 let file_size = file_info.size.unwrap_or(0);
48 let fs_id = file_info.fs_id.ok_or_else(|| "File has no fs_id")?;
49 let file_meta = client.file().get_file_meta(fs_id).await?;
50
51 println!("File Info:");
52 println!(" Name: {}", file_info.name);
53 println!(" Path: {}", file_info.path);
54 println!(
55 " Size: {} bytes ({:.2} MB)",
56 file_size,
57 file_size as f64 / (1024.0 * 1024.0)
58 );
59 println!(" FS ID: {:?}", file_info.fs_id);
60
61 // Step 2: Single-threaded download (skip for large files > 50MB)
62 println!("\n--- Step 2: Single-threaded download ---");
63 if file_size > 50 * 1024 * 1024 {
64 println!(
65 "File size {} bytes exceeds 50MB, skipping single-threaded download...",
66 file_size
67 );
68 } else {
69 println!("Press Enter to continue...");
70 reader.read_line(&mut String::new())?;
71
72 let single_save_path = format!("./download_single_{}", file_info.name);
73 let start_time = Instant::now();
74
75 match client
76 .download()
77 .download_single(remote_path, &single_save_path)
78 .await
79 {
80 Ok(_) => {
81 let duration = start_time.elapsed();
82 print_download_stats("Single-threaded", file_size, duration);
83 println!("Single-threaded download successful: {}", single_save_path);
84 }
85 Err(e) => eprintln!("Single-threaded download failed: {}", e),
86 }
87 }
88
89 // Step 3: Producer-consumer parallel download (queue-based)
90 println!("\n--- Step 3: Parallel download (Producer-Consumer queue-based) ---");
91 println!("Press Enter to continue...");
92 reader.read_line(&mut String::new())?;
93
94 let parallel_save_path = format!("./download_parallel_{}", file_info.name);
95 let start_time = Instant::now();
96
97 match client
98 .download()
99 .download_parallel_multi_threaded(&file_meta, ¶llel_save_path, Some(12))
100 .await
101 {
102 Ok(_) => {
103 let duration = start_time.elapsed();
104 print_download_stats("Parallel (Producer-Consumer)", file_size, duration);
105 println!("Parallel download successful: {}", parallel_save_path);
106 }
107 Err(e) => eprintln!("Parallel download failed: {}", e),
108 }
109
110 // Step 4: Auto download (recommended)
111 println!("\n--- Step 4: Auto download (recommended) ---");
112 println!("Press Enter to continue...");
113 reader.read_line(&mut String::new())?;
114
115 let auto_save_path = format!("./download_auto_{}", file_info.name);
116 let start_time = Instant::now();
117
118 match client
119 .download()
120 .auto_download(remote_path, &auto_save_path)
121 .await
122 {
123 Ok(_) => {
124 let duration = start_time.elapsed();
125 print_download_stats("Auto download", file_size, duration);
126 println!("Auto download successful: {}", auto_save_path);
127 }
128 Err(e) => eprintln!("Auto download failed: {}", e),
129 }
130
131 println!("\n=== Download test completed ===");
132
133 Ok(())
134}More examples
8async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
9 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
10
11 let client = BaiduNetDiskClient::builder().build()?;
12 info!("Client created successfully");
13
14 client.load_token_from_env()?;
15 info!("Token loaded successfully");
16
17 println!("=== Baidu NetDisk Download Comparison Test ===");
18 println!();
19 println!(
20 "Enter the number of threads/concurrency to use (recommended: match your CPU core count)"
21 );
22 println!("Example: 4 for 4 cores, 8 for 8 cores, etc.");
23 let mut input = String::new();
24 std::io::stdin().read_line(&mut input)?;
25 let thread_num: usize = input.trim().parse().unwrap_or(4);
26 let concurrency = thread_num * 3;
27 println!();
28 println!("Thread count: {}", thread_num);
29 println!("Concurrency: {}", concurrency);
30 println!();
31
32 println!("=== Method 1: Streaming (Futures/Concurrency) ===");
33 println!("Enter the remote file path to download:");
34 let mut input = String::new();
35 std::io::stdin().read_line(&mut input)?;
36 let remote_path_streaming = input.trim();
37
38 if remote_path_streaming.is_empty() {
39 eprintln!("Error: File path cannot be empty");
40 return Ok(());
41 }
42
43 println!("\n--- Step 1: Get file info for Streaming ---");
44 let file_info_streaming = client.file().get_file_info(remote_path_streaming).await?;
45 let file_size_streaming = file_info_streaming.size.unwrap_or(0);
46 let fs_id_streaming = file_info_streaming.fs_id.ok_or("File has no fs_id")?;
47 let file_meta_streaming = client.file().get_file_meta(fs_id_streaming).await?;
48
49 println!("File: {}", file_info_streaming.name);
50 println!(
51 "Size: {} bytes ({:.2} MB)",
52 file_size_streaming,
53 file_size_streaming as f64 / (1024.0 * 1024.0)
54 );
55 let total_chunks_streaming = (file_size_streaming + CHUNK_SIZE - 1) / CHUNK_SIZE;
56 println!(
57 "Chunks: {} ({} bytes each)",
58 total_chunks_streaming, CHUNK_SIZE
59 );
60 println!();
61
62 println!("Press Enter to start Streaming download...");
63 std::io::stdin().read_line(&mut String::new())?;
64
65 let streaming_save_path = format!("./download_streaming_{}", file_info_streaming.name);
66 let start_streaming = std::time::Instant::now();
67
68 client
69 .download()
70 .download_streaming_with_meta(
71 &file_meta_streaming,
72 Path::new(&streaming_save_path),
73 concurrency,
74 )
75 .await?;
76
77 let duration_streaming = start_streaming.elapsed();
78 let streaming_mb = file_size_streaming as f64 / (1024.0 * 1024.0);
79 let streaming_sec = duration_streaming.as_secs_f64();
80 let streaming_speed = streaming_mb / streaming_sec;
81
82 println!();
83 println!("=== Method 2: Parallel (Multi-thread) ===");
84 println!("Enter the remote file path to download:");
85 let mut input = String::new();
86 std::io::stdin().read_line(&mut input)?;
87 let remote_path_parallel = input.trim();
88
89 if remote_path_parallel.is_empty() {
90 eprintln!("Error: File path cannot be empty");
91 return Ok(());
92 }
93
94 println!("\n--- Step 1: Get file info for Parallel ---");
95 let file_info_parallel = client.file().get_file_info(remote_path_parallel).await?;
96 let file_size_parallel = file_info_parallel.size.unwrap_or(0);
97 let fs_id_parallel = file_info_parallel.fs_id.ok_or("File has no fs_id")?;
98 let file_meta_parallel = client.file().get_file_meta(fs_id_parallel).await?;
99
100 println!("File: {}", file_info_parallel.name);
101 println!(
102 "Size: {} bytes ({:.2} MB)",
103 file_size_parallel,
104 file_size_parallel as f64 / (1024.0 * 1024.0)
105 );
106 let total_chunks_parallel = (file_size_parallel + CHUNK_SIZE - 1) / CHUNK_SIZE;
107 println!(
108 "Chunks: {} ({} bytes each)",
109 total_chunks_parallel, CHUNK_SIZE
110 );
111 println!();
112
113 println!("Press Enter to start Parallel download...");
114 std::io::stdin().read_line(&mut String::new())?;
115
116 let parallel_save_path = format!("./download_parallel_{}", file_info_parallel.name);
117 let start_parallel = std::time::Instant::now();
118
119 client
120 .download()
121 .download_parallel_multi_threaded(
122 &file_meta_parallel,
123 Path::new(¶llel_save_path),
124 Some(thread_num),
125 )
126 .await?;
127
128 let duration_parallel = start_parallel.elapsed();
129 let parallel_mb = file_size_parallel as f64 / (1024.0 * 1024.0);
130 let parallel_sec = duration_parallel.as_secs_f64();
131 let parallel_speed = parallel_mb / parallel_sec;
132
133 println!();
134 println!("╔══════════════════════════════════════════════════════════════════════════╗");
135 println!("║ DOWNLOAD COMPARISON RESULTS ║");
136 println!("╠══════════════════════════════════════════════════════════════════════════╣");
137 println!(
138 "║ Threads: {} │ Concurrency (Streaming): {} │ ║",
139 thread_num, concurrency
140 );
141 println!("╠══════════════════════════════════════════════════════════════════════════╣");
142 println!("║ Method │ Time │ Speed │ File ║");
143 println!("╠══════════════════════════════════════════════════════════════════════════╣");
144 println!(
145 "║ Streaming (Futures) │ {:>8.2}s │ {:>8.2} MB/s │ {:.15} ║",
146 streaming_sec, streaming_speed, file_info_streaming.name
147 );
148 println!(
149 "║ Parallel (Multi-thread) │ {:>8.2}s │ {:>8.2} MB/s │ {:.15} ║",
150 parallel_sec, parallel_speed, file_info_parallel.name
151 );
152 println!("╠══════════════════════════════════════════════════════════════════════════╣");
153 let speedup = if streaming_sec < parallel_sec {
154 parallel_sec / streaming_sec
155 } else {
156 streaming_sec / parallel_sec
157 };
158 let faster = if streaming_sec < parallel_sec {
159 "Streaming"
160 } else {
161 "Parallel"
162 };
163 println!(
164 "║ Faster: {} ({:.2}x) ║",
165 faster, speedup
166 );
167 println!("╠══════════════════════════════════════════════════════════════════════════╣");
168 println!("║ Note: Parallel mode works best with 6+ cores. On 4 cores, Streaming may ║");
169 println!("║ be 2x faster. Test with your actual core count for best results! ║");
170 println!("╚══════════════════════════════════════════════════════════════════════════╝");
171
172 println!();
173 println!("Output files:");
174 println!(" Parallel: {}", parallel_save_path);
175 println!(" Streaming: {}", streaming_save_path);
176
177 Ok(())
178}6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Initialize logger
8 env_logger::init();
9
10 println!("=== Baidu NetDisk File Management Test ===\n");
11
12 // Create client - will automatically load from .env file
13 let client = BaiduNetDiskClient::builder().build()?;
14 info!("Client created successfully");
15
16 // Load token from environment variables
17 client.load_token_from_env()?;
18 info!("Token loaded successfully");
19
20 // === Test 0: List root directory to verify permission ===
21 println!("=== Test 0: List Root Directory ===");
22 println!("Listing contents of root directory: /");
23 wait_for_enter();
24
25 match client.file().list_directory("/").await {
26 Ok(files) => {
27 println!("✓ Successfully listed root directory!");
28 println!(" Found {} items:", files.len());
29 for file in files {
30 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
31 let size_str = if let Some(s) = file.size {
32 format!("{} bytes", s)
33 } else {
34 "N/A".to_string()
35 };
36 println!(" [{}] {} ({})", type_str, file.name, size_str);
37 }
38 }
39 Err(e) => {
40 println!("! Failed to list root directory: {}", e);
41 println!(" Please check your token and permissions.");
42 return Ok(());
43 }
44 }
45
46 // Test folder and file paths
47 let test_folder = "/upload";
48 let test_file = "/upload/subscribe.json";
49 let test_folder_new = "/upload_new";
50 let test_file_new = "/upload_new/subscribe.json";
51 let test_file_renamed = "/upload_new/subscribe_renamed.json";
52
53 // === Test 1: Check if /upload folder exists ===
54 println!("\n=== Test 1: Check /upload folder ===");
55 println!("Checking folder: {}", test_folder);
56 wait_for_enter();
57
58 match client.file().get_file_info(test_folder).await {
59 Ok(info) => {
60 println!("✓ Folder /upload exists!");
61 println!(" fs_id: {:?}", info.fs_id);
62 println!(" path: {}", info.path);
63 println!(" isdir: {:?}", info.isdir);
64 println!(" ctime: {:?}", info.ctime);
65 println!(" mtime: {:?}", info.mtime);
66 }
67 Err(e) => {
68 println!(
69 "! Folder /upload does not exist or cannot be accessed: {}",
70 e
71 );
72 println!(" Please create the folder manually or check your permissions.");
73 return Ok(());
74 }
75 }
76
77 // === Test 2: List upload directory first ===
78 println!("\n=== Test 2: List /upload Directory ===");
79 println!("Listing contents of: {}", test_folder);
80 wait_for_enter();
81
82 let upload_files = match client.file().list_directory(test_folder).await {
83 Ok(files) => {
84 println!("✓ Directory listed successfully!");
85 println!(" Found {} items:", files.len());
86 for file in &files {
87 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
88 let size_str = if let Some(s) = file.size {
89 format!("{} bytes", s)
90 } else {
91 "N/A".to_string()
92 };
93 println!(" [{}] {} ({})", type_str, file.name, size_str);
94 }
95 Some(files)
96 }
97 Err(e) => {
98 println!("! Failed to list directory: {}", e);
99 None
100 }
101 };
102
103 // === Test 3: Check if subscribe.json exists ===
104 println!("\n=== Test 3: Check subscribe.json file ===");
105 println!("Checking file: {}", test_file);
106 wait_for_enter();
107
108 match client.file().get_file_info(test_file).await {
109 Ok(info) => {
110 println!("✓ File {} exists!", test_file);
111 println!(" fs_id: {:?}", info.fs_id);
112 println!(" path: {}", info.path);
113 println!(" name: {}", info.name);
114 println!(" size: {:?} bytes", info.size);
115 println!(" isdir: {:?}", info.isdir);
116 println!(" md5: {:?}", info.md5);
117 println!(" ctime: {:?}", info.ctime);
118 println!(" mtime: {:?}", info.mtime);
119 }
120 Err(e) => {
121 println!(
122 "! File {} does not exist or cannot be accessed: {}",
123 test_file, e
124 );
125 // If directory content is listed, show to user
126 if let Some(files) = upload_files {
127 println!(" Available files in /upload:");
128 for file in files {
129 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
130 println!(" [{}] {}", type_str, file.name);
131 }
132 }
133 return Ok(());
134 }
135 }
136
137 // === Test 4: Create new folder ===
138 println!("\n=== Test 4: Create Folder ===");
139 println!("Creating folder: {}", test_folder_new);
140 wait_for_enter();
141
142 match client.file().create_folder(test_folder_new).await {
143 Ok(folder) => {
144 println!("✓ Folder created successfully!");
145 println!(" fs_id: {:?}", folder.fs_id);
146 println!(" path: {}", folder.path);
147 println!(" ctime: {:?}", folder.ctime);
148 }
149 Err(e) => {
150 println!("! Failed to create folder: {}", e);
151 return Ok(());
152 }
153 }
154
155 // === Test 5: Copy file ===
156 println!("\n=== Test 5: Copy File ===");
157 println!("Copying file: {} -> {}", test_file, test_folder_new);
158 wait_for_enter();
159
160 match client.file().copy_file(test_file, test_folder_new).await {
161 Ok(_) => println!("✓ File copied successfully!"),
162 Err(e) => {
163 println!("! File copy failed: {}", e);
164 return Ok(());
165 }
166 }
167
168 // === Test 6: Verify copied file ===
169 println!("\n=== Test 6: Verify Copied File ===");
170 println!("Listing directory: {}", test_folder_new);
171 wait_for_enter();
172
173 let copied_files = match client.file().list_directory(test_folder_new).await {
174 Ok(files) => {
175 println!("✓ Directory listed!");
176 println!(" Found {} items:", files.len());
177 for file in &files {
178 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
179 let size_str = if let Some(s) = file.size {
180 format!("{} bytes", s)
181 } else {
182 "N/A".to_string()
183 };
184 println!(" [{}] {} ({})", type_str, file.name, size_str);
185 }
186 Some(files)
187 }
188 Err(e) => {
189 println!("! Failed to list directory: {}", e);
190 None
191 }
192 };
193
194 println!("\nChecking copied file: {}", test_file_new);
195 wait_for_enter();
196
197 match client.file().get_file_info(test_file_new).await {
198 Ok(info) => {
199 println!("✓ Copied file verified!");
200 println!(" name: {}", info.name);
201 println!(" size: {:?} bytes", info.size);
202 }
203 Err(e) => {
204 println!("! Failed to verify copied file: {}", e);
205 // If we listed the directory, show available files
206 if let Some(files) = copied_files {
207 println!(" Available files:");
208 for file in files {
209 println!(" {}", file.name);
210 }
211 }
212 return Ok(());
213 }
214 }
215
216 // === Test 7: Rename file ===
217 println!("\n=== Test 7: Rename File ===");
218 println!("Renaming file: {} -> {}", test_file_new, test_file_renamed);
219 wait_for_enter();
220
221 match client
222 .file()
223 .rename(test_file_new, "subscribe_renamed.json")
224 .await
225 {
226 Ok(_) => println!("✓ File renamed successfully!"),
227 Err(e) => {
228 println!("! File rename failed: {}", e);
229 return Ok(());
230 }
231 }
232
233 // === Test 8: Move file ===
234 println!("\n=== Test 8: Move File ===");
235 println!("Moving file: {} -> {}", test_file_renamed, test_folder);
236 wait_for_enter();
237
238 match client
239 .file()
240 .move_file(test_file_renamed, test_folder)
241 .await
242 {
243 Ok(_) => println!("✓ File moved successfully!"),
244 Err(e) => {
245 println!("! File move failed: {}", e);
246 return Ok(());
247 }
248 }
249
250 // === Test 9: Verify moved file ===
251 println!("\n=== Test 9: Verify Moved File ===");
252 let moved_file_path = "/upload/subscribe_renamed.json";
253 println!("Checking moved file: {}", moved_file_path);
254 wait_for_enter();
255
256 match client.file().get_file_info(moved_file_path).await {
257 Ok(info) => {
258 println!("✓ Moved file verified!");
259 println!(" name: {}", info.name);
260 println!(" path: {}", info.path);
261 }
262 Err(e) => {
263 println!("! Failed to verify moved file: {}", e);
264 return Ok(());
265 }
266 }
267
268 // === Test 10: Delete renamed file ===
269 println!("\n=== Test 10: Delete File ===");
270 println!("Deleting file: {}", moved_file_path);
271 wait_for_enter();
272
273 match client.file().delete(moved_file_path).await {
274 Ok(_) => println!("✓ File deleted successfully!"),
275 Err(e) => {
276 println!("! File deletion failed: {}", e);
277 return Ok(());
278 }
279 }
280
281 // === Test 11: Cleanup - Delete test folder ===
282 println!("\n=== Test 11: Cleanup ===");
283 println!("Deleting empty folder: {}", test_folder_new);
284 wait_for_enter();
285
286 match client.file().delete(test_folder_new).await {
287 Ok(_) => println!("✓ Test folder deleted successfully!"),
288 Err(e) => {
289 println!("! Failed to delete test folder: {}", e);
290 return Ok(());
291 }
292 }
293
294 // === Final verification ===
295 println!("\n=== Final Verification ===");
296 println!("Listing final contents of: {}", test_folder);
297 wait_for_enter();
298
299 match client.file().list_directory(test_folder).await {
300 Ok(files) => {
301 println!("✓ Final directory listing:");
302 println!(" Found {} items:", files.len());
303 for file in files {
304 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
305 println!(" [{}] {}", type_str, file.name);
306 }
307 }
308 Err(e) => {
309 println!("! Failed to list directory: {}", e);
310 return Ok(());
311 }
312 }
313
314 println!("\n=== All file management tests completed successfully! ===");
315
316 Ok(())
317}Sourcepub async fn get_file_meta(&self, fs_id: u64) -> NetDiskResult<FileMeta>
pub async fn get_file_meta(&self, fs_id: u64) -> NetDiskResult<FileMeta>
Get file metadata (including download link) by fs_id
Examples found in repository?
15async fn main() -> Result<(), Box<dyn std::error::Error>> {
16 // Initialize logger
17 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
18
19 // Create client
20 let client = BaiduNetDiskClient::builder().build()?;
21 info!("Client created successfully");
22
23 // Load token from environment
24 client.load_token_from_env()?;
25 info!("Token loaded successfully");
26
27 println!("=== Baidu NetDisk Download Test ===");
28 println!("Enter the remote file path to download (e.g., /upload/test.txt):");
29
30 let stdin = io::stdin();
31 let mut reader = stdin.lock();
32 let mut input = String::new();
33 reader.read_line(&mut input)?;
34 let remote_path = input.trim();
35
36 if remote_path.is_empty() {
37 eprintln!("Error: File path cannot be empty");
38 return Ok(());
39 }
40
41 // Step 1: Get file info (to obtain fs_id)
42 println!("\n--- Step 1: Get file info (to obtain fs_id) ---");
43 println!("Press Enter to continue...");
44 reader.read_line(&mut String::new())?;
45
46 let file_info = client.file().get_file_info(remote_path).await?;
47 let file_size = file_info.size.unwrap_or(0);
48 let fs_id = file_info.fs_id.ok_or_else(|| "File has no fs_id")?;
49 let file_meta = client.file().get_file_meta(fs_id).await?;
50
51 println!("File Info:");
52 println!(" Name: {}", file_info.name);
53 println!(" Path: {}", file_info.path);
54 println!(
55 " Size: {} bytes ({:.2} MB)",
56 file_size,
57 file_size as f64 / (1024.0 * 1024.0)
58 );
59 println!(" FS ID: {:?}", file_info.fs_id);
60
61 // Step 2: Single-threaded download (skip for large files > 50MB)
62 println!("\n--- Step 2: Single-threaded download ---");
63 if file_size > 50 * 1024 * 1024 {
64 println!(
65 "File size {} bytes exceeds 50MB, skipping single-threaded download...",
66 file_size
67 );
68 } else {
69 println!("Press Enter to continue...");
70 reader.read_line(&mut String::new())?;
71
72 let single_save_path = format!("./download_single_{}", file_info.name);
73 let start_time = Instant::now();
74
75 match client
76 .download()
77 .download_single(remote_path, &single_save_path)
78 .await
79 {
80 Ok(_) => {
81 let duration = start_time.elapsed();
82 print_download_stats("Single-threaded", file_size, duration);
83 println!("Single-threaded download successful: {}", single_save_path);
84 }
85 Err(e) => eprintln!("Single-threaded download failed: {}", e),
86 }
87 }
88
89 // Step 3: Producer-consumer parallel download (queue-based)
90 println!("\n--- Step 3: Parallel download (Producer-Consumer queue-based) ---");
91 println!("Press Enter to continue...");
92 reader.read_line(&mut String::new())?;
93
94 let parallel_save_path = format!("./download_parallel_{}", file_info.name);
95 let start_time = Instant::now();
96
97 match client
98 .download()
99 .download_parallel_multi_threaded(&file_meta, ¶llel_save_path, Some(12))
100 .await
101 {
102 Ok(_) => {
103 let duration = start_time.elapsed();
104 print_download_stats("Parallel (Producer-Consumer)", file_size, duration);
105 println!("Parallel download successful: {}", parallel_save_path);
106 }
107 Err(e) => eprintln!("Parallel download failed: {}", e),
108 }
109
110 // Step 4: Auto download (recommended)
111 println!("\n--- Step 4: Auto download (recommended) ---");
112 println!("Press Enter to continue...");
113 reader.read_line(&mut String::new())?;
114
115 let auto_save_path = format!("./download_auto_{}", file_info.name);
116 let start_time = Instant::now();
117
118 match client
119 .download()
120 .auto_download(remote_path, &auto_save_path)
121 .await
122 {
123 Ok(_) => {
124 let duration = start_time.elapsed();
125 print_download_stats("Auto download", file_size, duration);
126 println!("Auto download successful: {}", auto_save_path);
127 }
128 Err(e) => eprintln!("Auto download failed: {}", e),
129 }
130
131 println!("\n=== Download test completed ===");
132
133 Ok(())
134}More examples
8async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
9 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
10
11 let client = BaiduNetDiskClient::builder().build()?;
12 info!("Client created successfully");
13
14 client.load_token_from_env()?;
15 info!("Token loaded successfully");
16
17 println!("=== Baidu NetDisk Download Comparison Test ===");
18 println!();
19 println!(
20 "Enter the number of threads/concurrency to use (recommended: match your CPU core count)"
21 );
22 println!("Example: 4 for 4 cores, 8 for 8 cores, etc.");
23 let mut input = String::new();
24 std::io::stdin().read_line(&mut input)?;
25 let thread_num: usize = input.trim().parse().unwrap_or(4);
26 let concurrency = thread_num * 3;
27 println!();
28 println!("Thread count: {}", thread_num);
29 println!("Concurrency: {}", concurrency);
30 println!();
31
32 println!("=== Method 1: Streaming (Futures/Concurrency) ===");
33 println!("Enter the remote file path to download:");
34 let mut input = String::new();
35 std::io::stdin().read_line(&mut input)?;
36 let remote_path_streaming = input.trim();
37
38 if remote_path_streaming.is_empty() {
39 eprintln!("Error: File path cannot be empty");
40 return Ok(());
41 }
42
43 println!("\n--- Step 1: Get file info for Streaming ---");
44 let file_info_streaming = client.file().get_file_info(remote_path_streaming).await?;
45 let file_size_streaming = file_info_streaming.size.unwrap_or(0);
46 let fs_id_streaming = file_info_streaming.fs_id.ok_or("File has no fs_id")?;
47 let file_meta_streaming = client.file().get_file_meta(fs_id_streaming).await?;
48
49 println!("File: {}", file_info_streaming.name);
50 println!(
51 "Size: {} bytes ({:.2} MB)",
52 file_size_streaming,
53 file_size_streaming as f64 / (1024.0 * 1024.0)
54 );
55 let total_chunks_streaming = (file_size_streaming + CHUNK_SIZE - 1) / CHUNK_SIZE;
56 println!(
57 "Chunks: {} ({} bytes each)",
58 total_chunks_streaming, CHUNK_SIZE
59 );
60 println!();
61
62 println!("Press Enter to start Streaming download...");
63 std::io::stdin().read_line(&mut String::new())?;
64
65 let streaming_save_path = format!("./download_streaming_{}", file_info_streaming.name);
66 let start_streaming = std::time::Instant::now();
67
68 client
69 .download()
70 .download_streaming_with_meta(
71 &file_meta_streaming,
72 Path::new(&streaming_save_path),
73 concurrency,
74 )
75 .await?;
76
77 let duration_streaming = start_streaming.elapsed();
78 let streaming_mb = file_size_streaming as f64 / (1024.0 * 1024.0);
79 let streaming_sec = duration_streaming.as_secs_f64();
80 let streaming_speed = streaming_mb / streaming_sec;
81
82 println!();
83 println!("=== Method 2: Parallel (Multi-thread) ===");
84 println!("Enter the remote file path to download:");
85 let mut input = String::new();
86 std::io::stdin().read_line(&mut input)?;
87 let remote_path_parallel = input.trim();
88
89 if remote_path_parallel.is_empty() {
90 eprintln!("Error: File path cannot be empty");
91 return Ok(());
92 }
93
94 println!("\n--- Step 1: Get file info for Parallel ---");
95 let file_info_parallel = client.file().get_file_info(remote_path_parallel).await?;
96 let file_size_parallel = file_info_parallel.size.unwrap_or(0);
97 let fs_id_parallel = file_info_parallel.fs_id.ok_or("File has no fs_id")?;
98 let file_meta_parallel = client.file().get_file_meta(fs_id_parallel).await?;
99
100 println!("File: {}", file_info_parallel.name);
101 println!(
102 "Size: {} bytes ({:.2} MB)",
103 file_size_parallel,
104 file_size_parallel as f64 / (1024.0 * 1024.0)
105 );
106 let total_chunks_parallel = (file_size_parallel + CHUNK_SIZE - 1) / CHUNK_SIZE;
107 println!(
108 "Chunks: {} ({} bytes each)",
109 total_chunks_parallel, CHUNK_SIZE
110 );
111 println!();
112
113 println!("Press Enter to start Parallel download...");
114 std::io::stdin().read_line(&mut String::new())?;
115
116 let parallel_save_path = format!("./download_parallel_{}", file_info_parallel.name);
117 let start_parallel = std::time::Instant::now();
118
119 client
120 .download()
121 .download_parallel_multi_threaded(
122 &file_meta_parallel,
123 Path::new(¶llel_save_path),
124 Some(thread_num),
125 )
126 .await?;
127
128 let duration_parallel = start_parallel.elapsed();
129 let parallel_mb = file_size_parallel as f64 / (1024.0 * 1024.0);
130 let parallel_sec = duration_parallel.as_secs_f64();
131 let parallel_speed = parallel_mb / parallel_sec;
132
133 println!();
134 println!("╔══════════════════════════════════════════════════════════════════════════╗");
135 println!("║ DOWNLOAD COMPARISON RESULTS ║");
136 println!("╠══════════════════════════════════════════════════════════════════════════╣");
137 println!(
138 "║ Threads: {} │ Concurrency (Streaming): {} │ ║",
139 thread_num, concurrency
140 );
141 println!("╠══════════════════════════════════════════════════════════════════════════╣");
142 println!("║ Method │ Time │ Speed │ File ║");
143 println!("╠══════════════════════════════════════════════════════════════════════════╣");
144 println!(
145 "║ Streaming (Futures) │ {:>8.2}s │ {:>8.2} MB/s │ {:.15} ║",
146 streaming_sec, streaming_speed, file_info_streaming.name
147 );
148 println!(
149 "║ Parallel (Multi-thread) │ {:>8.2}s │ {:>8.2} MB/s │ {:.15} ║",
150 parallel_sec, parallel_speed, file_info_parallel.name
151 );
152 println!("╠══════════════════════════════════════════════════════════════════════════╣");
153 let speedup = if streaming_sec < parallel_sec {
154 parallel_sec / streaming_sec
155 } else {
156 streaming_sec / parallel_sec
157 };
158 let faster = if streaming_sec < parallel_sec {
159 "Streaming"
160 } else {
161 "Parallel"
162 };
163 println!(
164 "║ Faster: {} ({:.2}x) ║",
165 faster, speedup
166 );
167 println!("╠══════════════════════════════════════════════════════════════════════════╣");
168 println!("║ Note: Parallel mode works best with 6+ cores. On 4 cores, Streaming may ║");
169 println!("║ be 2x faster. Test with your actual core count for best results! ║");
170 println!("╚══════════════════════════════════════════════════════════════════════════╝");
171
172 println!();
173 println!("Output files:");
174 println!(" Parallel: {}", parallel_save_path);
175 println!(" Streaming: {}", streaming_save_path);
176
177 Ok(())
178}Sourcepub async fn search_files(
&self,
key: &str,
dir: &str,
) -> NetDiskResult<(Vec<FileInfo>, bool)>
pub async fn search_files( &self, key: &str, dir: &str, ) -> NetDiskResult<(Vec<FileInfo>, bool)>
Search files by keyword
Examples found in repository?
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}Sourcepub async fn search_files_with_options(
&self,
key: &str,
options: SearchOptions,
) -> NetDiskResult<(Vec<FileInfo>, bool)>
pub async fn search_files_with_options( &self, key: &str, options: SearchOptions, ) -> NetDiskResult<(Vec<FileInfo>, bool)>
Search files by keyword with custom options
Examples found in repository?
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}Sourcepub async fn semantic_search(&self, query: &str) -> NetDiskResult<Vec<FileInfo>>
pub async fn semantic_search(&self, query: &str) -> NetDiskResult<Vec<FileInfo>>
Semantic search for files (AI-powered search)
Examples found in repository?
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}Sourcepub async fn semantic_search_with_options(
&self,
query: &str,
options: SemanticSearchOptions,
) -> NetDiskResult<Vec<FileInfo>>
pub async fn semantic_search_with_options( &self, query: &str, options: SemanticSearchOptions, ) -> NetDiskResult<Vec<FileInfo>>
Semantic search with custom options
Examples found in repository?
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}Sourcepub async fn create_folder(&self, path: &str) -> NetDiskResult<FolderInfo>
pub async fn create_folder(&self, path: &str) -> NetDiskResult<FolderInfo>
Create a folder
Examples found in repository?
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Initialize logger
8 env_logger::init();
9
10 println!("=== Baidu NetDisk File Management Test ===\n");
11
12 // Create client - will automatically load from .env file
13 let client = BaiduNetDiskClient::builder().build()?;
14 info!("Client created successfully");
15
16 // Load token from environment variables
17 client.load_token_from_env()?;
18 info!("Token loaded successfully");
19
20 // === Test 0: List root directory to verify permission ===
21 println!("=== Test 0: List Root Directory ===");
22 println!("Listing contents of root directory: /");
23 wait_for_enter();
24
25 match client.file().list_directory("/").await {
26 Ok(files) => {
27 println!("✓ Successfully listed root directory!");
28 println!(" Found {} items:", files.len());
29 for file in files {
30 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
31 let size_str = if let Some(s) = file.size {
32 format!("{} bytes", s)
33 } else {
34 "N/A".to_string()
35 };
36 println!(" [{}] {} ({})", type_str, file.name, size_str);
37 }
38 }
39 Err(e) => {
40 println!("! Failed to list root directory: {}", e);
41 println!(" Please check your token and permissions.");
42 return Ok(());
43 }
44 }
45
46 // Test folder and file paths
47 let test_folder = "/upload";
48 let test_file = "/upload/subscribe.json";
49 let test_folder_new = "/upload_new";
50 let test_file_new = "/upload_new/subscribe.json";
51 let test_file_renamed = "/upload_new/subscribe_renamed.json";
52
53 // === Test 1: Check if /upload folder exists ===
54 println!("\n=== Test 1: Check /upload folder ===");
55 println!("Checking folder: {}", test_folder);
56 wait_for_enter();
57
58 match client.file().get_file_info(test_folder).await {
59 Ok(info) => {
60 println!("✓ Folder /upload exists!");
61 println!(" fs_id: {:?}", info.fs_id);
62 println!(" path: {}", info.path);
63 println!(" isdir: {:?}", info.isdir);
64 println!(" ctime: {:?}", info.ctime);
65 println!(" mtime: {:?}", info.mtime);
66 }
67 Err(e) => {
68 println!(
69 "! Folder /upload does not exist or cannot be accessed: {}",
70 e
71 );
72 println!(" Please create the folder manually or check your permissions.");
73 return Ok(());
74 }
75 }
76
77 // === Test 2: List upload directory first ===
78 println!("\n=== Test 2: List /upload Directory ===");
79 println!("Listing contents of: {}", test_folder);
80 wait_for_enter();
81
82 let upload_files = match client.file().list_directory(test_folder).await {
83 Ok(files) => {
84 println!("✓ Directory listed successfully!");
85 println!(" Found {} items:", files.len());
86 for file in &files {
87 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
88 let size_str = if let Some(s) = file.size {
89 format!("{} bytes", s)
90 } else {
91 "N/A".to_string()
92 };
93 println!(" [{}] {} ({})", type_str, file.name, size_str);
94 }
95 Some(files)
96 }
97 Err(e) => {
98 println!("! Failed to list directory: {}", e);
99 None
100 }
101 };
102
103 // === Test 3: Check if subscribe.json exists ===
104 println!("\n=== Test 3: Check subscribe.json file ===");
105 println!("Checking file: {}", test_file);
106 wait_for_enter();
107
108 match client.file().get_file_info(test_file).await {
109 Ok(info) => {
110 println!("✓ File {} exists!", test_file);
111 println!(" fs_id: {:?}", info.fs_id);
112 println!(" path: {}", info.path);
113 println!(" name: {}", info.name);
114 println!(" size: {:?} bytes", info.size);
115 println!(" isdir: {:?}", info.isdir);
116 println!(" md5: {:?}", info.md5);
117 println!(" ctime: {:?}", info.ctime);
118 println!(" mtime: {:?}", info.mtime);
119 }
120 Err(e) => {
121 println!(
122 "! File {} does not exist or cannot be accessed: {}",
123 test_file, e
124 );
125 // If directory content is listed, show to user
126 if let Some(files) = upload_files {
127 println!(" Available files in /upload:");
128 for file in files {
129 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
130 println!(" [{}] {}", type_str, file.name);
131 }
132 }
133 return Ok(());
134 }
135 }
136
137 // === Test 4: Create new folder ===
138 println!("\n=== Test 4: Create Folder ===");
139 println!("Creating folder: {}", test_folder_new);
140 wait_for_enter();
141
142 match client.file().create_folder(test_folder_new).await {
143 Ok(folder) => {
144 println!("✓ Folder created successfully!");
145 println!(" fs_id: {:?}", folder.fs_id);
146 println!(" path: {}", folder.path);
147 println!(" ctime: {:?}", folder.ctime);
148 }
149 Err(e) => {
150 println!("! Failed to create folder: {}", e);
151 return Ok(());
152 }
153 }
154
155 // === Test 5: Copy file ===
156 println!("\n=== Test 5: Copy File ===");
157 println!("Copying file: {} -> {}", test_file, test_folder_new);
158 wait_for_enter();
159
160 match client.file().copy_file(test_file, test_folder_new).await {
161 Ok(_) => println!("✓ File copied successfully!"),
162 Err(e) => {
163 println!("! File copy failed: {}", e);
164 return Ok(());
165 }
166 }
167
168 // === Test 6: Verify copied file ===
169 println!("\n=== Test 6: Verify Copied File ===");
170 println!("Listing directory: {}", test_folder_new);
171 wait_for_enter();
172
173 let copied_files = match client.file().list_directory(test_folder_new).await {
174 Ok(files) => {
175 println!("✓ Directory listed!");
176 println!(" Found {} items:", files.len());
177 for file in &files {
178 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
179 let size_str = if let Some(s) = file.size {
180 format!("{} bytes", s)
181 } else {
182 "N/A".to_string()
183 };
184 println!(" [{}] {} ({})", type_str, file.name, size_str);
185 }
186 Some(files)
187 }
188 Err(e) => {
189 println!("! Failed to list directory: {}", e);
190 None
191 }
192 };
193
194 println!("\nChecking copied file: {}", test_file_new);
195 wait_for_enter();
196
197 match client.file().get_file_info(test_file_new).await {
198 Ok(info) => {
199 println!("✓ Copied file verified!");
200 println!(" name: {}", info.name);
201 println!(" size: {:?} bytes", info.size);
202 }
203 Err(e) => {
204 println!("! Failed to verify copied file: {}", e);
205 // If we listed the directory, show available files
206 if let Some(files) = copied_files {
207 println!(" Available files:");
208 for file in files {
209 println!(" {}", file.name);
210 }
211 }
212 return Ok(());
213 }
214 }
215
216 // === Test 7: Rename file ===
217 println!("\n=== Test 7: Rename File ===");
218 println!("Renaming file: {} -> {}", test_file_new, test_file_renamed);
219 wait_for_enter();
220
221 match client
222 .file()
223 .rename(test_file_new, "subscribe_renamed.json")
224 .await
225 {
226 Ok(_) => println!("✓ File renamed successfully!"),
227 Err(e) => {
228 println!("! File rename failed: {}", e);
229 return Ok(());
230 }
231 }
232
233 // === Test 8: Move file ===
234 println!("\n=== Test 8: Move File ===");
235 println!("Moving file: {} -> {}", test_file_renamed, test_folder);
236 wait_for_enter();
237
238 match client
239 .file()
240 .move_file(test_file_renamed, test_folder)
241 .await
242 {
243 Ok(_) => println!("✓ File moved successfully!"),
244 Err(e) => {
245 println!("! File move failed: {}", e);
246 return Ok(());
247 }
248 }
249
250 // === Test 9: Verify moved file ===
251 println!("\n=== Test 9: Verify Moved File ===");
252 let moved_file_path = "/upload/subscribe_renamed.json";
253 println!("Checking moved file: {}", moved_file_path);
254 wait_for_enter();
255
256 match client.file().get_file_info(moved_file_path).await {
257 Ok(info) => {
258 println!("✓ Moved file verified!");
259 println!(" name: {}", info.name);
260 println!(" path: {}", info.path);
261 }
262 Err(e) => {
263 println!("! Failed to verify moved file: {}", e);
264 return Ok(());
265 }
266 }
267
268 // === Test 10: Delete renamed file ===
269 println!("\n=== Test 10: Delete File ===");
270 println!("Deleting file: {}", moved_file_path);
271 wait_for_enter();
272
273 match client.file().delete(moved_file_path).await {
274 Ok(_) => println!("✓ File deleted successfully!"),
275 Err(e) => {
276 println!("! File deletion failed: {}", e);
277 return Ok(());
278 }
279 }
280
281 // === Test 11: Cleanup - Delete test folder ===
282 println!("\n=== Test 11: Cleanup ===");
283 println!("Deleting empty folder: {}", test_folder_new);
284 wait_for_enter();
285
286 match client.file().delete(test_folder_new).await {
287 Ok(_) => println!("✓ Test folder deleted successfully!"),
288 Err(e) => {
289 println!("! Failed to delete test folder: {}", e);
290 return Ok(());
291 }
292 }
293
294 // === Final verification ===
295 println!("\n=== Final Verification ===");
296 println!("Listing final contents of: {}", test_folder);
297 wait_for_enter();
298
299 match client.file().list_directory(test_folder).await {
300 Ok(files) => {
301 println!("✓ Final directory listing:");
302 println!(" Found {} items:", files.len());
303 for file in files {
304 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
305 println!(" [{}] {}", type_str, file.name);
306 }
307 }
308 Err(e) => {
309 println!("! Failed to list directory: {}", e);
310 return Ok(());
311 }
312 }
313
314 println!("\n=== All file management tests completed successfully! ===");
315
316 Ok(())
317}Sourcepub async fn create_folder_with_options(
&self,
path: &str,
options: FolderCreateOptions,
) -> NetDiskResult<FolderInfo>
pub async fn create_folder_with_options( &self, path: &str, options: FolderCreateOptions, ) -> NetDiskResult<FolderInfo>
Create a folder with custom options
Sourcepub async fn rename(&self, path: &str, new_name: &str) -> NetDiskResult<()>
pub async fn rename(&self, path: &str, new_name: &str) -> NetDiskResult<()>
Rename a file or folder
Examples found in repository?
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Initialize logger
8 env_logger::init();
9
10 println!("=== Baidu NetDisk File Management Test ===\n");
11
12 // Create client - will automatically load from .env file
13 let client = BaiduNetDiskClient::builder().build()?;
14 info!("Client created successfully");
15
16 // Load token from environment variables
17 client.load_token_from_env()?;
18 info!("Token loaded successfully");
19
20 // === Test 0: List root directory to verify permission ===
21 println!("=== Test 0: List Root Directory ===");
22 println!("Listing contents of root directory: /");
23 wait_for_enter();
24
25 match client.file().list_directory("/").await {
26 Ok(files) => {
27 println!("✓ Successfully listed root directory!");
28 println!(" Found {} items:", files.len());
29 for file in files {
30 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
31 let size_str = if let Some(s) = file.size {
32 format!("{} bytes", s)
33 } else {
34 "N/A".to_string()
35 };
36 println!(" [{}] {} ({})", type_str, file.name, size_str);
37 }
38 }
39 Err(e) => {
40 println!("! Failed to list root directory: {}", e);
41 println!(" Please check your token and permissions.");
42 return Ok(());
43 }
44 }
45
46 // Test folder and file paths
47 let test_folder = "/upload";
48 let test_file = "/upload/subscribe.json";
49 let test_folder_new = "/upload_new";
50 let test_file_new = "/upload_new/subscribe.json";
51 let test_file_renamed = "/upload_new/subscribe_renamed.json";
52
53 // === Test 1: Check if /upload folder exists ===
54 println!("\n=== Test 1: Check /upload folder ===");
55 println!("Checking folder: {}", test_folder);
56 wait_for_enter();
57
58 match client.file().get_file_info(test_folder).await {
59 Ok(info) => {
60 println!("✓ Folder /upload exists!");
61 println!(" fs_id: {:?}", info.fs_id);
62 println!(" path: {}", info.path);
63 println!(" isdir: {:?}", info.isdir);
64 println!(" ctime: {:?}", info.ctime);
65 println!(" mtime: {:?}", info.mtime);
66 }
67 Err(e) => {
68 println!(
69 "! Folder /upload does not exist or cannot be accessed: {}",
70 e
71 );
72 println!(" Please create the folder manually or check your permissions.");
73 return Ok(());
74 }
75 }
76
77 // === Test 2: List upload directory first ===
78 println!("\n=== Test 2: List /upload Directory ===");
79 println!("Listing contents of: {}", test_folder);
80 wait_for_enter();
81
82 let upload_files = match client.file().list_directory(test_folder).await {
83 Ok(files) => {
84 println!("✓ Directory listed successfully!");
85 println!(" Found {} items:", files.len());
86 for file in &files {
87 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
88 let size_str = if let Some(s) = file.size {
89 format!("{} bytes", s)
90 } else {
91 "N/A".to_string()
92 };
93 println!(" [{}] {} ({})", type_str, file.name, size_str);
94 }
95 Some(files)
96 }
97 Err(e) => {
98 println!("! Failed to list directory: {}", e);
99 None
100 }
101 };
102
103 // === Test 3: Check if subscribe.json exists ===
104 println!("\n=== Test 3: Check subscribe.json file ===");
105 println!("Checking file: {}", test_file);
106 wait_for_enter();
107
108 match client.file().get_file_info(test_file).await {
109 Ok(info) => {
110 println!("✓ File {} exists!", test_file);
111 println!(" fs_id: {:?}", info.fs_id);
112 println!(" path: {}", info.path);
113 println!(" name: {}", info.name);
114 println!(" size: {:?} bytes", info.size);
115 println!(" isdir: {:?}", info.isdir);
116 println!(" md5: {:?}", info.md5);
117 println!(" ctime: {:?}", info.ctime);
118 println!(" mtime: {:?}", info.mtime);
119 }
120 Err(e) => {
121 println!(
122 "! File {} does not exist or cannot be accessed: {}",
123 test_file, e
124 );
125 // If directory content is listed, show to user
126 if let Some(files) = upload_files {
127 println!(" Available files in /upload:");
128 for file in files {
129 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
130 println!(" [{}] {}", type_str, file.name);
131 }
132 }
133 return Ok(());
134 }
135 }
136
137 // === Test 4: Create new folder ===
138 println!("\n=== Test 4: Create Folder ===");
139 println!("Creating folder: {}", test_folder_new);
140 wait_for_enter();
141
142 match client.file().create_folder(test_folder_new).await {
143 Ok(folder) => {
144 println!("✓ Folder created successfully!");
145 println!(" fs_id: {:?}", folder.fs_id);
146 println!(" path: {}", folder.path);
147 println!(" ctime: {:?}", folder.ctime);
148 }
149 Err(e) => {
150 println!("! Failed to create folder: {}", e);
151 return Ok(());
152 }
153 }
154
155 // === Test 5: Copy file ===
156 println!("\n=== Test 5: Copy File ===");
157 println!("Copying file: {} -> {}", test_file, test_folder_new);
158 wait_for_enter();
159
160 match client.file().copy_file(test_file, test_folder_new).await {
161 Ok(_) => println!("✓ File copied successfully!"),
162 Err(e) => {
163 println!("! File copy failed: {}", e);
164 return Ok(());
165 }
166 }
167
168 // === Test 6: Verify copied file ===
169 println!("\n=== Test 6: Verify Copied File ===");
170 println!("Listing directory: {}", test_folder_new);
171 wait_for_enter();
172
173 let copied_files = match client.file().list_directory(test_folder_new).await {
174 Ok(files) => {
175 println!("✓ Directory listed!");
176 println!(" Found {} items:", files.len());
177 for file in &files {
178 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
179 let size_str = if let Some(s) = file.size {
180 format!("{} bytes", s)
181 } else {
182 "N/A".to_string()
183 };
184 println!(" [{}] {} ({})", type_str, file.name, size_str);
185 }
186 Some(files)
187 }
188 Err(e) => {
189 println!("! Failed to list directory: {}", e);
190 None
191 }
192 };
193
194 println!("\nChecking copied file: {}", test_file_new);
195 wait_for_enter();
196
197 match client.file().get_file_info(test_file_new).await {
198 Ok(info) => {
199 println!("✓ Copied file verified!");
200 println!(" name: {}", info.name);
201 println!(" size: {:?} bytes", info.size);
202 }
203 Err(e) => {
204 println!("! Failed to verify copied file: {}", e);
205 // If we listed the directory, show available files
206 if let Some(files) = copied_files {
207 println!(" Available files:");
208 for file in files {
209 println!(" {}", file.name);
210 }
211 }
212 return Ok(());
213 }
214 }
215
216 // === Test 7: Rename file ===
217 println!("\n=== Test 7: Rename File ===");
218 println!("Renaming file: {} -> {}", test_file_new, test_file_renamed);
219 wait_for_enter();
220
221 match client
222 .file()
223 .rename(test_file_new, "subscribe_renamed.json")
224 .await
225 {
226 Ok(_) => println!("✓ File renamed successfully!"),
227 Err(e) => {
228 println!("! File rename failed: {}", e);
229 return Ok(());
230 }
231 }
232
233 // === Test 8: Move file ===
234 println!("\n=== Test 8: Move File ===");
235 println!("Moving file: {} -> {}", test_file_renamed, test_folder);
236 wait_for_enter();
237
238 match client
239 .file()
240 .move_file(test_file_renamed, test_folder)
241 .await
242 {
243 Ok(_) => println!("✓ File moved successfully!"),
244 Err(e) => {
245 println!("! File move failed: {}", e);
246 return Ok(());
247 }
248 }
249
250 // === Test 9: Verify moved file ===
251 println!("\n=== Test 9: Verify Moved File ===");
252 let moved_file_path = "/upload/subscribe_renamed.json";
253 println!("Checking moved file: {}", moved_file_path);
254 wait_for_enter();
255
256 match client.file().get_file_info(moved_file_path).await {
257 Ok(info) => {
258 println!("✓ Moved file verified!");
259 println!(" name: {}", info.name);
260 println!(" path: {}", info.path);
261 }
262 Err(e) => {
263 println!("! Failed to verify moved file: {}", e);
264 return Ok(());
265 }
266 }
267
268 // === Test 10: Delete renamed file ===
269 println!("\n=== Test 10: Delete File ===");
270 println!("Deleting file: {}", moved_file_path);
271 wait_for_enter();
272
273 match client.file().delete(moved_file_path).await {
274 Ok(_) => println!("✓ File deleted successfully!"),
275 Err(e) => {
276 println!("! File deletion failed: {}", e);
277 return Ok(());
278 }
279 }
280
281 // === Test 11: Cleanup - Delete test folder ===
282 println!("\n=== Test 11: Cleanup ===");
283 println!("Deleting empty folder: {}", test_folder_new);
284 wait_for_enter();
285
286 match client.file().delete(test_folder_new).await {
287 Ok(_) => println!("✓ Test folder deleted successfully!"),
288 Err(e) => {
289 println!("! Failed to delete test folder: {}", e);
290 return Ok(());
291 }
292 }
293
294 // === Final verification ===
295 println!("\n=== Final Verification ===");
296 println!("Listing final contents of: {}", test_folder);
297 wait_for_enter();
298
299 match client.file().list_directory(test_folder).await {
300 Ok(files) => {
301 println!("✓ Final directory listing:");
302 println!(" Found {} items:", files.len());
303 for file in files {
304 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
305 println!(" [{}] {}", type_str, file.name);
306 }
307 }
308 Err(e) => {
309 println!("! Failed to list directory: {}", e);
310 return Ok(());
311 }
312 }
313
314 println!("\n=== All file management tests completed successfully! ===");
315
316 Ok(())
317}Sourcepub async fn delete(&self, path: &str) -> NetDiskResult<()>
pub async fn delete(&self, path: &str) -> NetDiskResult<()>
Delete a file or folder
Examples found in repository?
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Initialize logger
8 env_logger::init();
9
10 println!("=== Baidu NetDisk File Management Test ===\n");
11
12 // Create client - will automatically load from .env file
13 let client = BaiduNetDiskClient::builder().build()?;
14 info!("Client created successfully");
15
16 // Load token from environment variables
17 client.load_token_from_env()?;
18 info!("Token loaded successfully");
19
20 // === Test 0: List root directory to verify permission ===
21 println!("=== Test 0: List Root Directory ===");
22 println!("Listing contents of root directory: /");
23 wait_for_enter();
24
25 match client.file().list_directory("/").await {
26 Ok(files) => {
27 println!("✓ Successfully listed root directory!");
28 println!(" Found {} items:", files.len());
29 for file in files {
30 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
31 let size_str = if let Some(s) = file.size {
32 format!("{} bytes", s)
33 } else {
34 "N/A".to_string()
35 };
36 println!(" [{}] {} ({})", type_str, file.name, size_str);
37 }
38 }
39 Err(e) => {
40 println!("! Failed to list root directory: {}", e);
41 println!(" Please check your token and permissions.");
42 return Ok(());
43 }
44 }
45
46 // Test folder and file paths
47 let test_folder = "/upload";
48 let test_file = "/upload/subscribe.json";
49 let test_folder_new = "/upload_new";
50 let test_file_new = "/upload_new/subscribe.json";
51 let test_file_renamed = "/upload_new/subscribe_renamed.json";
52
53 // === Test 1: Check if /upload folder exists ===
54 println!("\n=== Test 1: Check /upload folder ===");
55 println!("Checking folder: {}", test_folder);
56 wait_for_enter();
57
58 match client.file().get_file_info(test_folder).await {
59 Ok(info) => {
60 println!("✓ Folder /upload exists!");
61 println!(" fs_id: {:?}", info.fs_id);
62 println!(" path: {}", info.path);
63 println!(" isdir: {:?}", info.isdir);
64 println!(" ctime: {:?}", info.ctime);
65 println!(" mtime: {:?}", info.mtime);
66 }
67 Err(e) => {
68 println!(
69 "! Folder /upload does not exist or cannot be accessed: {}",
70 e
71 );
72 println!(" Please create the folder manually or check your permissions.");
73 return Ok(());
74 }
75 }
76
77 // === Test 2: List upload directory first ===
78 println!("\n=== Test 2: List /upload Directory ===");
79 println!("Listing contents of: {}", test_folder);
80 wait_for_enter();
81
82 let upload_files = match client.file().list_directory(test_folder).await {
83 Ok(files) => {
84 println!("✓ Directory listed successfully!");
85 println!(" Found {} items:", files.len());
86 for file in &files {
87 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
88 let size_str = if let Some(s) = file.size {
89 format!("{} bytes", s)
90 } else {
91 "N/A".to_string()
92 };
93 println!(" [{}] {} ({})", type_str, file.name, size_str);
94 }
95 Some(files)
96 }
97 Err(e) => {
98 println!("! Failed to list directory: {}", e);
99 None
100 }
101 };
102
103 // === Test 3: Check if subscribe.json exists ===
104 println!("\n=== Test 3: Check subscribe.json file ===");
105 println!("Checking file: {}", test_file);
106 wait_for_enter();
107
108 match client.file().get_file_info(test_file).await {
109 Ok(info) => {
110 println!("✓ File {} exists!", test_file);
111 println!(" fs_id: {:?}", info.fs_id);
112 println!(" path: {}", info.path);
113 println!(" name: {}", info.name);
114 println!(" size: {:?} bytes", info.size);
115 println!(" isdir: {:?}", info.isdir);
116 println!(" md5: {:?}", info.md5);
117 println!(" ctime: {:?}", info.ctime);
118 println!(" mtime: {:?}", info.mtime);
119 }
120 Err(e) => {
121 println!(
122 "! File {} does not exist or cannot be accessed: {}",
123 test_file, e
124 );
125 // If directory content is listed, show to user
126 if let Some(files) = upload_files {
127 println!(" Available files in /upload:");
128 for file in files {
129 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
130 println!(" [{}] {}", type_str, file.name);
131 }
132 }
133 return Ok(());
134 }
135 }
136
137 // === Test 4: Create new folder ===
138 println!("\n=== Test 4: Create Folder ===");
139 println!("Creating folder: {}", test_folder_new);
140 wait_for_enter();
141
142 match client.file().create_folder(test_folder_new).await {
143 Ok(folder) => {
144 println!("✓ Folder created successfully!");
145 println!(" fs_id: {:?}", folder.fs_id);
146 println!(" path: {}", folder.path);
147 println!(" ctime: {:?}", folder.ctime);
148 }
149 Err(e) => {
150 println!("! Failed to create folder: {}", e);
151 return Ok(());
152 }
153 }
154
155 // === Test 5: Copy file ===
156 println!("\n=== Test 5: Copy File ===");
157 println!("Copying file: {} -> {}", test_file, test_folder_new);
158 wait_for_enter();
159
160 match client.file().copy_file(test_file, test_folder_new).await {
161 Ok(_) => println!("✓ File copied successfully!"),
162 Err(e) => {
163 println!("! File copy failed: {}", e);
164 return Ok(());
165 }
166 }
167
168 // === Test 6: Verify copied file ===
169 println!("\n=== Test 6: Verify Copied File ===");
170 println!("Listing directory: {}", test_folder_new);
171 wait_for_enter();
172
173 let copied_files = match client.file().list_directory(test_folder_new).await {
174 Ok(files) => {
175 println!("✓ Directory listed!");
176 println!(" Found {} items:", files.len());
177 for file in &files {
178 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
179 let size_str = if let Some(s) = file.size {
180 format!("{} bytes", s)
181 } else {
182 "N/A".to_string()
183 };
184 println!(" [{}] {} ({})", type_str, file.name, size_str);
185 }
186 Some(files)
187 }
188 Err(e) => {
189 println!("! Failed to list directory: {}", e);
190 None
191 }
192 };
193
194 println!("\nChecking copied file: {}", test_file_new);
195 wait_for_enter();
196
197 match client.file().get_file_info(test_file_new).await {
198 Ok(info) => {
199 println!("✓ Copied file verified!");
200 println!(" name: {}", info.name);
201 println!(" size: {:?} bytes", info.size);
202 }
203 Err(e) => {
204 println!("! Failed to verify copied file: {}", e);
205 // If we listed the directory, show available files
206 if let Some(files) = copied_files {
207 println!(" Available files:");
208 for file in files {
209 println!(" {}", file.name);
210 }
211 }
212 return Ok(());
213 }
214 }
215
216 // === Test 7: Rename file ===
217 println!("\n=== Test 7: Rename File ===");
218 println!("Renaming file: {} -> {}", test_file_new, test_file_renamed);
219 wait_for_enter();
220
221 match client
222 .file()
223 .rename(test_file_new, "subscribe_renamed.json")
224 .await
225 {
226 Ok(_) => println!("✓ File renamed successfully!"),
227 Err(e) => {
228 println!("! File rename failed: {}", e);
229 return Ok(());
230 }
231 }
232
233 // === Test 8: Move file ===
234 println!("\n=== Test 8: Move File ===");
235 println!("Moving file: {} -> {}", test_file_renamed, test_folder);
236 wait_for_enter();
237
238 match client
239 .file()
240 .move_file(test_file_renamed, test_folder)
241 .await
242 {
243 Ok(_) => println!("✓ File moved successfully!"),
244 Err(e) => {
245 println!("! File move failed: {}", e);
246 return Ok(());
247 }
248 }
249
250 // === Test 9: Verify moved file ===
251 println!("\n=== Test 9: Verify Moved File ===");
252 let moved_file_path = "/upload/subscribe_renamed.json";
253 println!("Checking moved file: {}", moved_file_path);
254 wait_for_enter();
255
256 match client.file().get_file_info(moved_file_path).await {
257 Ok(info) => {
258 println!("✓ Moved file verified!");
259 println!(" name: {}", info.name);
260 println!(" path: {}", info.path);
261 }
262 Err(e) => {
263 println!("! Failed to verify moved file: {}", e);
264 return Ok(());
265 }
266 }
267
268 // === Test 10: Delete renamed file ===
269 println!("\n=== Test 10: Delete File ===");
270 println!("Deleting file: {}", moved_file_path);
271 wait_for_enter();
272
273 match client.file().delete(moved_file_path).await {
274 Ok(_) => println!("✓ File deleted successfully!"),
275 Err(e) => {
276 println!("! File deletion failed: {}", e);
277 return Ok(());
278 }
279 }
280
281 // === Test 11: Cleanup - Delete test folder ===
282 println!("\n=== Test 11: Cleanup ===");
283 println!("Deleting empty folder: {}", test_folder_new);
284 wait_for_enter();
285
286 match client.file().delete(test_folder_new).await {
287 Ok(_) => println!("✓ Test folder deleted successfully!"),
288 Err(e) => {
289 println!("! Failed to delete test folder: {}", e);
290 return Ok(());
291 }
292 }
293
294 // === Final verification ===
295 println!("\n=== Final Verification ===");
296 println!("Listing final contents of: {}", test_folder);
297 wait_for_enter();
298
299 match client.file().list_directory(test_folder).await {
300 Ok(files) => {
301 println!("✓ Final directory listing:");
302 println!(" Found {} items:", files.len());
303 for file in files {
304 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
305 println!(" [{}] {}", type_str, file.name);
306 }
307 }
308 Err(e) => {
309 println!("! Failed to list directory: {}", e);
310 return Ok(());
311 }
312 }
313
314 println!("\n=== All file management tests completed successfully! ===");
315
316 Ok(())
317}Sourcepub async fn move_file(&self, path: &str, dest: &str) -> NetDiskResult<()>
pub async fn move_file(&self, path: &str, dest: &str) -> NetDiskResult<()>
Move a file or folder
Examples found in repository?
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Initialize logger
8 env_logger::init();
9
10 println!("=== Baidu NetDisk File Management Test ===\n");
11
12 // Create client - will automatically load from .env file
13 let client = BaiduNetDiskClient::builder().build()?;
14 info!("Client created successfully");
15
16 // Load token from environment variables
17 client.load_token_from_env()?;
18 info!("Token loaded successfully");
19
20 // === Test 0: List root directory to verify permission ===
21 println!("=== Test 0: List Root Directory ===");
22 println!("Listing contents of root directory: /");
23 wait_for_enter();
24
25 match client.file().list_directory("/").await {
26 Ok(files) => {
27 println!("✓ Successfully listed root directory!");
28 println!(" Found {} items:", files.len());
29 for file in files {
30 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
31 let size_str = if let Some(s) = file.size {
32 format!("{} bytes", s)
33 } else {
34 "N/A".to_string()
35 };
36 println!(" [{}] {} ({})", type_str, file.name, size_str);
37 }
38 }
39 Err(e) => {
40 println!("! Failed to list root directory: {}", e);
41 println!(" Please check your token and permissions.");
42 return Ok(());
43 }
44 }
45
46 // Test folder and file paths
47 let test_folder = "/upload";
48 let test_file = "/upload/subscribe.json";
49 let test_folder_new = "/upload_new";
50 let test_file_new = "/upload_new/subscribe.json";
51 let test_file_renamed = "/upload_new/subscribe_renamed.json";
52
53 // === Test 1: Check if /upload folder exists ===
54 println!("\n=== Test 1: Check /upload folder ===");
55 println!("Checking folder: {}", test_folder);
56 wait_for_enter();
57
58 match client.file().get_file_info(test_folder).await {
59 Ok(info) => {
60 println!("✓ Folder /upload exists!");
61 println!(" fs_id: {:?}", info.fs_id);
62 println!(" path: {}", info.path);
63 println!(" isdir: {:?}", info.isdir);
64 println!(" ctime: {:?}", info.ctime);
65 println!(" mtime: {:?}", info.mtime);
66 }
67 Err(e) => {
68 println!(
69 "! Folder /upload does not exist or cannot be accessed: {}",
70 e
71 );
72 println!(" Please create the folder manually or check your permissions.");
73 return Ok(());
74 }
75 }
76
77 // === Test 2: List upload directory first ===
78 println!("\n=== Test 2: List /upload Directory ===");
79 println!("Listing contents of: {}", test_folder);
80 wait_for_enter();
81
82 let upload_files = match client.file().list_directory(test_folder).await {
83 Ok(files) => {
84 println!("✓ Directory listed successfully!");
85 println!(" Found {} items:", files.len());
86 for file in &files {
87 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
88 let size_str = if let Some(s) = file.size {
89 format!("{} bytes", s)
90 } else {
91 "N/A".to_string()
92 };
93 println!(" [{}] {} ({})", type_str, file.name, size_str);
94 }
95 Some(files)
96 }
97 Err(e) => {
98 println!("! Failed to list directory: {}", e);
99 None
100 }
101 };
102
103 // === Test 3: Check if subscribe.json exists ===
104 println!("\n=== Test 3: Check subscribe.json file ===");
105 println!("Checking file: {}", test_file);
106 wait_for_enter();
107
108 match client.file().get_file_info(test_file).await {
109 Ok(info) => {
110 println!("✓ File {} exists!", test_file);
111 println!(" fs_id: {:?}", info.fs_id);
112 println!(" path: {}", info.path);
113 println!(" name: {}", info.name);
114 println!(" size: {:?} bytes", info.size);
115 println!(" isdir: {:?}", info.isdir);
116 println!(" md5: {:?}", info.md5);
117 println!(" ctime: {:?}", info.ctime);
118 println!(" mtime: {:?}", info.mtime);
119 }
120 Err(e) => {
121 println!(
122 "! File {} does not exist or cannot be accessed: {}",
123 test_file, e
124 );
125 // If directory content is listed, show to user
126 if let Some(files) = upload_files {
127 println!(" Available files in /upload:");
128 for file in files {
129 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
130 println!(" [{}] {}", type_str, file.name);
131 }
132 }
133 return Ok(());
134 }
135 }
136
137 // === Test 4: Create new folder ===
138 println!("\n=== Test 4: Create Folder ===");
139 println!("Creating folder: {}", test_folder_new);
140 wait_for_enter();
141
142 match client.file().create_folder(test_folder_new).await {
143 Ok(folder) => {
144 println!("✓ Folder created successfully!");
145 println!(" fs_id: {:?}", folder.fs_id);
146 println!(" path: {}", folder.path);
147 println!(" ctime: {:?}", folder.ctime);
148 }
149 Err(e) => {
150 println!("! Failed to create folder: {}", e);
151 return Ok(());
152 }
153 }
154
155 // === Test 5: Copy file ===
156 println!("\n=== Test 5: Copy File ===");
157 println!("Copying file: {} -> {}", test_file, test_folder_new);
158 wait_for_enter();
159
160 match client.file().copy_file(test_file, test_folder_new).await {
161 Ok(_) => println!("✓ File copied successfully!"),
162 Err(e) => {
163 println!("! File copy failed: {}", e);
164 return Ok(());
165 }
166 }
167
168 // === Test 6: Verify copied file ===
169 println!("\n=== Test 6: Verify Copied File ===");
170 println!("Listing directory: {}", test_folder_new);
171 wait_for_enter();
172
173 let copied_files = match client.file().list_directory(test_folder_new).await {
174 Ok(files) => {
175 println!("✓ Directory listed!");
176 println!(" Found {} items:", files.len());
177 for file in &files {
178 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
179 let size_str = if let Some(s) = file.size {
180 format!("{} bytes", s)
181 } else {
182 "N/A".to_string()
183 };
184 println!(" [{}] {} ({})", type_str, file.name, size_str);
185 }
186 Some(files)
187 }
188 Err(e) => {
189 println!("! Failed to list directory: {}", e);
190 None
191 }
192 };
193
194 println!("\nChecking copied file: {}", test_file_new);
195 wait_for_enter();
196
197 match client.file().get_file_info(test_file_new).await {
198 Ok(info) => {
199 println!("✓ Copied file verified!");
200 println!(" name: {}", info.name);
201 println!(" size: {:?} bytes", info.size);
202 }
203 Err(e) => {
204 println!("! Failed to verify copied file: {}", e);
205 // If we listed the directory, show available files
206 if let Some(files) = copied_files {
207 println!(" Available files:");
208 for file in files {
209 println!(" {}", file.name);
210 }
211 }
212 return Ok(());
213 }
214 }
215
216 // === Test 7: Rename file ===
217 println!("\n=== Test 7: Rename File ===");
218 println!("Renaming file: {} -> {}", test_file_new, test_file_renamed);
219 wait_for_enter();
220
221 match client
222 .file()
223 .rename(test_file_new, "subscribe_renamed.json")
224 .await
225 {
226 Ok(_) => println!("✓ File renamed successfully!"),
227 Err(e) => {
228 println!("! File rename failed: {}", e);
229 return Ok(());
230 }
231 }
232
233 // === Test 8: Move file ===
234 println!("\n=== Test 8: Move File ===");
235 println!("Moving file: {} -> {}", test_file_renamed, test_folder);
236 wait_for_enter();
237
238 match client
239 .file()
240 .move_file(test_file_renamed, test_folder)
241 .await
242 {
243 Ok(_) => println!("✓ File moved successfully!"),
244 Err(e) => {
245 println!("! File move failed: {}", e);
246 return Ok(());
247 }
248 }
249
250 // === Test 9: Verify moved file ===
251 println!("\n=== Test 9: Verify Moved File ===");
252 let moved_file_path = "/upload/subscribe_renamed.json";
253 println!("Checking moved file: {}", moved_file_path);
254 wait_for_enter();
255
256 match client.file().get_file_info(moved_file_path).await {
257 Ok(info) => {
258 println!("✓ Moved file verified!");
259 println!(" name: {}", info.name);
260 println!(" path: {}", info.path);
261 }
262 Err(e) => {
263 println!("! Failed to verify moved file: {}", e);
264 return Ok(());
265 }
266 }
267
268 // === Test 10: Delete renamed file ===
269 println!("\n=== Test 10: Delete File ===");
270 println!("Deleting file: {}", moved_file_path);
271 wait_for_enter();
272
273 match client.file().delete(moved_file_path).await {
274 Ok(_) => println!("✓ File deleted successfully!"),
275 Err(e) => {
276 println!("! File deletion failed: {}", e);
277 return Ok(());
278 }
279 }
280
281 // === Test 11: Cleanup - Delete test folder ===
282 println!("\n=== Test 11: Cleanup ===");
283 println!("Deleting empty folder: {}", test_folder_new);
284 wait_for_enter();
285
286 match client.file().delete(test_folder_new).await {
287 Ok(_) => println!("✓ Test folder deleted successfully!"),
288 Err(e) => {
289 println!("! Failed to delete test folder: {}", e);
290 return Ok(());
291 }
292 }
293
294 // === Final verification ===
295 println!("\n=== Final Verification ===");
296 println!("Listing final contents of: {}", test_folder);
297 wait_for_enter();
298
299 match client.file().list_directory(test_folder).await {
300 Ok(files) => {
301 println!("✓ Final directory listing:");
302 println!(" Found {} items:", files.len());
303 for file in files {
304 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
305 println!(" [{}] {}", type_str, file.name);
306 }
307 }
308 Err(e) => {
309 println!("! Failed to list directory: {}", e);
310 return Ok(());
311 }
312 }
313
314 println!("\n=== All file management tests completed successfully! ===");
315
316 Ok(())
317}Sourcepub async fn copy_file(&self, path: &str, dest: &str) -> NetDiskResult<()>
pub async fn copy_file(&self, path: &str, dest: &str) -> NetDiskResult<()>
Copy a file or folder
Examples found in repository?
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Initialize logger
8 env_logger::init();
9
10 println!("=== Baidu NetDisk File Management Test ===\n");
11
12 // Create client - will automatically load from .env file
13 let client = BaiduNetDiskClient::builder().build()?;
14 info!("Client created successfully");
15
16 // Load token from environment variables
17 client.load_token_from_env()?;
18 info!("Token loaded successfully");
19
20 // === Test 0: List root directory to verify permission ===
21 println!("=== Test 0: List Root Directory ===");
22 println!("Listing contents of root directory: /");
23 wait_for_enter();
24
25 match client.file().list_directory("/").await {
26 Ok(files) => {
27 println!("✓ Successfully listed root directory!");
28 println!(" Found {} items:", files.len());
29 for file in files {
30 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
31 let size_str = if let Some(s) = file.size {
32 format!("{} bytes", s)
33 } else {
34 "N/A".to_string()
35 };
36 println!(" [{}] {} ({})", type_str, file.name, size_str);
37 }
38 }
39 Err(e) => {
40 println!("! Failed to list root directory: {}", e);
41 println!(" Please check your token and permissions.");
42 return Ok(());
43 }
44 }
45
46 // Test folder and file paths
47 let test_folder = "/upload";
48 let test_file = "/upload/subscribe.json";
49 let test_folder_new = "/upload_new";
50 let test_file_new = "/upload_new/subscribe.json";
51 let test_file_renamed = "/upload_new/subscribe_renamed.json";
52
53 // === Test 1: Check if /upload folder exists ===
54 println!("\n=== Test 1: Check /upload folder ===");
55 println!("Checking folder: {}", test_folder);
56 wait_for_enter();
57
58 match client.file().get_file_info(test_folder).await {
59 Ok(info) => {
60 println!("✓ Folder /upload exists!");
61 println!(" fs_id: {:?}", info.fs_id);
62 println!(" path: {}", info.path);
63 println!(" isdir: {:?}", info.isdir);
64 println!(" ctime: {:?}", info.ctime);
65 println!(" mtime: {:?}", info.mtime);
66 }
67 Err(e) => {
68 println!(
69 "! Folder /upload does not exist or cannot be accessed: {}",
70 e
71 );
72 println!(" Please create the folder manually or check your permissions.");
73 return Ok(());
74 }
75 }
76
77 // === Test 2: List upload directory first ===
78 println!("\n=== Test 2: List /upload Directory ===");
79 println!("Listing contents of: {}", test_folder);
80 wait_for_enter();
81
82 let upload_files = match client.file().list_directory(test_folder).await {
83 Ok(files) => {
84 println!("✓ Directory listed successfully!");
85 println!(" Found {} items:", files.len());
86 for file in &files {
87 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
88 let size_str = if let Some(s) = file.size {
89 format!("{} bytes", s)
90 } else {
91 "N/A".to_string()
92 };
93 println!(" [{}] {} ({})", type_str, file.name, size_str);
94 }
95 Some(files)
96 }
97 Err(e) => {
98 println!("! Failed to list directory: {}", e);
99 None
100 }
101 };
102
103 // === Test 3: Check if subscribe.json exists ===
104 println!("\n=== Test 3: Check subscribe.json file ===");
105 println!("Checking file: {}", test_file);
106 wait_for_enter();
107
108 match client.file().get_file_info(test_file).await {
109 Ok(info) => {
110 println!("✓ File {} exists!", test_file);
111 println!(" fs_id: {:?}", info.fs_id);
112 println!(" path: {}", info.path);
113 println!(" name: {}", info.name);
114 println!(" size: {:?} bytes", info.size);
115 println!(" isdir: {:?}", info.isdir);
116 println!(" md5: {:?}", info.md5);
117 println!(" ctime: {:?}", info.ctime);
118 println!(" mtime: {:?}", info.mtime);
119 }
120 Err(e) => {
121 println!(
122 "! File {} does not exist or cannot be accessed: {}",
123 test_file, e
124 );
125 // If directory content is listed, show to user
126 if let Some(files) = upload_files {
127 println!(" Available files in /upload:");
128 for file in files {
129 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
130 println!(" [{}] {}", type_str, file.name);
131 }
132 }
133 return Ok(());
134 }
135 }
136
137 // === Test 4: Create new folder ===
138 println!("\n=== Test 4: Create Folder ===");
139 println!("Creating folder: {}", test_folder_new);
140 wait_for_enter();
141
142 match client.file().create_folder(test_folder_new).await {
143 Ok(folder) => {
144 println!("✓ Folder created successfully!");
145 println!(" fs_id: {:?}", folder.fs_id);
146 println!(" path: {}", folder.path);
147 println!(" ctime: {:?}", folder.ctime);
148 }
149 Err(e) => {
150 println!("! Failed to create folder: {}", e);
151 return Ok(());
152 }
153 }
154
155 // === Test 5: Copy file ===
156 println!("\n=== Test 5: Copy File ===");
157 println!("Copying file: {} -> {}", test_file, test_folder_new);
158 wait_for_enter();
159
160 match client.file().copy_file(test_file, test_folder_new).await {
161 Ok(_) => println!("✓ File copied successfully!"),
162 Err(e) => {
163 println!("! File copy failed: {}", e);
164 return Ok(());
165 }
166 }
167
168 // === Test 6: Verify copied file ===
169 println!("\n=== Test 6: Verify Copied File ===");
170 println!("Listing directory: {}", test_folder_new);
171 wait_for_enter();
172
173 let copied_files = match client.file().list_directory(test_folder_new).await {
174 Ok(files) => {
175 println!("✓ Directory listed!");
176 println!(" Found {} items:", files.len());
177 for file in &files {
178 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
179 let size_str = if let Some(s) = file.size {
180 format!("{} bytes", s)
181 } else {
182 "N/A".to_string()
183 };
184 println!(" [{}] {} ({})", type_str, file.name, size_str);
185 }
186 Some(files)
187 }
188 Err(e) => {
189 println!("! Failed to list directory: {}", e);
190 None
191 }
192 };
193
194 println!("\nChecking copied file: {}", test_file_new);
195 wait_for_enter();
196
197 match client.file().get_file_info(test_file_new).await {
198 Ok(info) => {
199 println!("✓ Copied file verified!");
200 println!(" name: {}", info.name);
201 println!(" size: {:?} bytes", info.size);
202 }
203 Err(e) => {
204 println!("! Failed to verify copied file: {}", e);
205 // If we listed the directory, show available files
206 if let Some(files) = copied_files {
207 println!(" Available files:");
208 for file in files {
209 println!(" {}", file.name);
210 }
211 }
212 return Ok(());
213 }
214 }
215
216 // === Test 7: Rename file ===
217 println!("\n=== Test 7: Rename File ===");
218 println!("Renaming file: {} -> {}", test_file_new, test_file_renamed);
219 wait_for_enter();
220
221 match client
222 .file()
223 .rename(test_file_new, "subscribe_renamed.json")
224 .await
225 {
226 Ok(_) => println!("✓ File renamed successfully!"),
227 Err(e) => {
228 println!("! File rename failed: {}", e);
229 return Ok(());
230 }
231 }
232
233 // === Test 8: Move file ===
234 println!("\n=== Test 8: Move File ===");
235 println!("Moving file: {} -> {}", test_file_renamed, test_folder);
236 wait_for_enter();
237
238 match client
239 .file()
240 .move_file(test_file_renamed, test_folder)
241 .await
242 {
243 Ok(_) => println!("✓ File moved successfully!"),
244 Err(e) => {
245 println!("! File move failed: {}", e);
246 return Ok(());
247 }
248 }
249
250 // === Test 9: Verify moved file ===
251 println!("\n=== Test 9: Verify Moved File ===");
252 let moved_file_path = "/upload/subscribe_renamed.json";
253 println!("Checking moved file: {}", moved_file_path);
254 wait_for_enter();
255
256 match client.file().get_file_info(moved_file_path).await {
257 Ok(info) => {
258 println!("✓ Moved file verified!");
259 println!(" name: {}", info.name);
260 println!(" path: {}", info.path);
261 }
262 Err(e) => {
263 println!("! Failed to verify moved file: {}", e);
264 return Ok(());
265 }
266 }
267
268 // === Test 10: Delete renamed file ===
269 println!("\n=== Test 10: Delete File ===");
270 println!("Deleting file: {}", moved_file_path);
271 wait_for_enter();
272
273 match client.file().delete(moved_file_path).await {
274 Ok(_) => println!("✓ File deleted successfully!"),
275 Err(e) => {
276 println!("! File deletion failed: {}", e);
277 return Ok(());
278 }
279 }
280
281 // === Test 11: Cleanup - Delete test folder ===
282 println!("\n=== Test 11: Cleanup ===");
283 println!("Deleting empty folder: {}", test_folder_new);
284 wait_for_enter();
285
286 match client.file().delete(test_folder_new).await {
287 Ok(_) => println!("✓ Test folder deleted successfully!"),
288 Err(e) => {
289 println!("! Failed to delete test folder: {}", e);
290 return Ok(());
291 }
292 }
293
294 // === Final verification ===
295 println!("\n=== Final Verification ===");
296 println!("Listing final contents of: {}", test_folder);
297 wait_for_enter();
298
299 match client.file().list_directory(test_folder).await {
300 Ok(files) => {
301 println!("✓ Final directory listing:");
302 println!(" Found {} items:", files.len());
303 for file in files {
304 let type_str = if file.isdir == Some(1) { "DIR" } else { "FILE" };
305 println!(" [{}] {}", type_str, file.name);
306 }
307 }
308 Err(e) => {
309 println!("! Failed to list directory: {}", e);
310 return Ok(());
311 }
312 }
313
314 println!("\n=== All file management tests completed successfully! ===");
315
316 Ok(())
317}Sourcepub async fn get_category_file_count(&self, category: u32) -> NetDiskResult<u64>
pub async fn get_category_file_count(&self, category: u32) -> NetDiskResult<u64>
Get the count of files in a specific category (simple version)
Sourcepub async fn get_category_file_count_with_options(
&self,
category: u32,
options: CategoryCountOptions,
) -> NetDiskResult<u64>
pub async fn get_category_file_count_with_options( &self, category: u32, options: CategoryCountOptions, ) -> NetDiskResult<u64>
Get the count of files in a specific category (full parameters)
Sourcepub async fn search_category_files(
&self,
category: u32,
start: i32,
limit: i32,
) -> NetDiskResult<(Vec<FileInfo>, u64)>
pub async fn search_category_files( &self, category: u32, start: i32, limit: i32, ) -> NetDiskResult<(Vec<FileInfo>, u64)>
Search files in a specific category (simple version)
Sourcepub async fn search_category_files_with_options(
&self,
category: &str,
options: CategorySearchOptions,
) -> NetDiskResult<(Vec<FileInfo>, u64)>
pub async fn search_category_files_with_options( &self, category: &str, options: CategorySearchOptions, ) -> NetDiskResult<(Vec<FileInfo>, u64)>
Search files in a specific category (full parameters)
Examples found in repository?
42async fn test_global_counts(client: &BaiduNetDiskClient) -> Result<(), Box<dyn std::error::Error>> {
43 let categories = [
44 (Category::Video, "Video"),
45 (Category::Music, "Music"),
46 (Category::Image, "Image"),
47 (Category::Document, "Document"),
48 (Category::Application, "Application"),
49 (Category::Other, "Other"),
50 (Category::Torrent, "Torrent"),
51 ];
52
53 for (category, name) in categories {
54 let options = CategorySearchOptions::new()
55 .parent_path("/")
56 .recursion(1)
57 .limit(1);
58
59 match client
60 .file()
61 .search_category_files_with_options(&category.as_u32().to_string(), options)
62 .await
63 {
64 Ok((_, total)) => {
65 println!(" {}: {} files", name, total);
66 }
67 Err(e) => {
68 println!(" {}: Error - {}", name, e);
69 }
70 }
71
72 wait_for_rate_limit().await;
73 }
74
75 Ok(())
76}
77
78async fn test_directory_counts(
79 client: &BaiduNetDiskClient,
80 dir: &str,
81) -> Result<(), Box<dyn std::error::Error>> {
82 let categories = [
83 (Category::Video, "Video"),
84 (Category::Music, "Music"),
85 (Category::Image, "Image"),
86 (Category::Document, "Document"),
87 (Category::Application, "Application"),
88 (Category::Other, "Other"),
89 (Category::Torrent, "Torrent"),
90 ];
91
92 for (category, name) in categories {
93 let options = CategorySearchOptions::new()
94 .parent_path(dir)
95 .recursion(1)
96 .limit(1);
97
98 match client
99 .file()
100 .search_category_files_with_options(&category.as_u32().to_string(), options)
101 .await
102 {
103 Ok((_, total)) => {
104 println!(" {}: {} files", name, total);
105 }
106 Err(e) => {
107 println!(" {}: Error - {}", name, e);
108 }
109 }
110
111 wait_for_rate_limit().await;
112 }
113
114 Ok(())
115}
116
117async fn test_list_category_files(
118 client: &BaiduNetDiskClient,
119 dir: &str,
120) -> Result<(), Box<dyn std::error::Error>> {
121 let categories = [
122 (1, "Video"),
123 (2, "Music"),
124 (3, "Image"),
125 (4, "Document"),
126 (5, "Application"),
127 (6, "Other"),
128 (7, "Torrent"),
129 ];
130
131 for (category, name) in categories {
132 println!("\n [{}] Files:", name);
133
134 let options = CategorySearchOptions::new()
135 .parent_path(dir)
136 .recursion(1)
137 .limit(10);
138
139 match client
140 .file()
141 .search_category_files_with_options(&category.to_string(), options)
142 .await
143 {
144 Ok((files, total)) => {
145 if files.is_empty() {
146 println!(" (no files)");
147 } else {
148 for file in files.iter().take(5) {
149 let size_str = file
150 .size
151 .map(|s| format!("{:.2} MB", s as f64 / (1024.0 * 1024.0)))
152 .unwrap_or_else(|| "N/A".to_string());
153 println!(" - {} ({})", file.name, size_str);
154 }
155 if files.len() > 5 && total > 5 {
156 println!(" ... and {} more files", total - 5);
157 }
158 println!(" Total in this category: {}", total);
159 }
160 }
161 Err(e) => {
162 println!(" Error - {}", e);
163 }
164 }
165
166 wait_for_rate_limit().await;
167 }
168
169 Ok(())
170}Sourcepub async fn list_documents(
&self,
parent_path: &str,
page: i32,
num: i32,
) -> NetDiskResult<Vec<FileInfo>>
pub async fn list_documents( &self, parent_path: &str, page: i32, num: i32, ) -> NetDiskResult<Vec<FileInfo>>
List documents
Examples found in repository?
24async fn main() -> Result<(), Box<dyn std::error::Error>> {
25 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
26
27 let client = BaiduNetDiskClient::builder().build()?;
28 info!("Client created successfully");
29
30 client.load_token_from_env()?;
31 info!("Token loaded successfully");
32
33 let test_dir = "/apps/product";
34 let num_per_page = 5;
35
36 println!("=== Baidu NetDisk Fixed Category List Test ===");
37 println!("Directory: {}", test_dir);
38 println!("Items per page: {}\n", num_per_page);
39
40 println!("--- Part 1: Document List (doclist) ---");
41 match client
42 .file()
43 .list_documents(test_dir, 1, num_per_page)
44 .await
45 {
46 Ok(files) => {
47 println!("Found {} documents", files.len());
48 for file in &files {
49 let size_str = file
50 .size
51 .map(|s| format_size(s))
52 .unwrap_or_else(|| "N/A".to_string());
53 println!(" - {} ({})", file.name, size_str);
54 }
55 }
56 Err(e) => {
57 println!("Error: {}", e);
58 }
59 }
60 wait_for_rate_limit().await;
61
62 println!("\n--- Part 2: Image List (imagelist) ---");
63 match client.file().list_images(test_dir, 1, num_per_page).await {
64 Ok(files) => {
65 println!("Found {} images", files.len());
66 for file in &files {
67 let size_str = file
68 .size
69 .map(|s| format_size(s))
70 .unwrap_or_else(|| "N/A".to_string());
71 println!(" - {} ({})", file.name, size_str);
72 }
73 }
74 Err(e) => {
75 println!("Error: {}", e);
76 }
77 }
78 wait_for_rate_limit().await;
79
80 println!("\n--- Part 3: Video List (videolist) ---");
81 match client.file().list_videos(test_dir, 1, num_per_page).await {
82 Ok(files) => {
83 println!("Found {} videos", files.len());
84 for file in &files {
85 let size_str = file
86 .size
87 .map(|s| format_size(s))
88 .unwrap_or_else(|| "N/A".to_string());
89 println!(" - {} ({})", file.name, size_str);
90 }
91 }
92 Err(e) => {
93 println!("Error: {}", e);
94 }
95 }
96 wait_for_rate_limit().await;
97
98 println!("\n--- Part 4: BT List (btlist) ---");
99 match client.file().list_torrents(test_dir, 1, num_per_page).await {
100 Ok(files) => {
101 println!("Found {} torrent files", files.len());
102 for file in &files {
103 let size_str = file
104 .size
105 .map(|s| format_size(s))
106 .unwrap_or_else(|| "N/A".to_string());
107 println!(" - {} ({})", file.name, size_str);
108 }
109 }
110 Err(e) => {
111 println!("Error: {}", e);
112 }
113 }
114 wait_for_rate_limit().await;
115
116 println!("\n=== Test with Options (recursion=1) ===");
117 println!("Directory: {}\n", test_dir);
118
119 println!("--- Document List with recursion ---");
120 let options = DocumentListOptions::new(test_dir)
121 .recursion(1)
122 .num(num_per_page);
123 match client.file().list_documents_with_options(options).await {
124 Ok(files) => {
125 println!("Found {} documents", files.len());
126 for file in &files {
127 let size_str = file
128 .size
129 .map(|s| format_size(s))
130 .unwrap_or_else(|| "N/A".to_string());
131 println!(" - {} ({})", file.name, size_str);
132 }
133 }
134 Err(e) => {
135 println!("Error: {}", e);
136 }
137 }
138 wait_for_rate_limit().await;
139
140 println!("\n--- Image List with recursion ---");
141 let options = ImageListOptions::new(test_dir)
142 .recursion(1)
143 .num(num_per_page);
144 match client.file().list_images_with_options(options).await {
145 Ok(files) => {
146 println!("Found {} images", files.len());
147 for file in &files {
148 let size_str = file
149 .size
150 .map(|s| format_size(s))
151 .unwrap_or_else(|| "N/A".to_string());
152 println!(" - {} ({})", file.name, size_str);
153 }
154 }
155 Err(e) => {
156 println!("Error: {}", e);
157 }
158 }
159 wait_for_rate_limit().await;
160
161 println!("\n--- Video List with recursion ---");
162 let options = VideoListOptions::new(test_dir)
163 .recursion(1)
164 .num(num_per_page);
165 match client.file().list_videos_with_options(options).await {
166 Ok(files) => {
167 println!("Found {} videos", files.len());
168 for file in &files {
169 let size_str = file
170 .size
171 .map(|s| format_size(s))
172 .unwrap_or_else(|| "N/A".to_string());
173 println!(" - {} ({})", file.name, size_str);
174 }
175 }
176 Err(e) => {
177 println!("Error: {}", e);
178 }
179 }
180 wait_for_rate_limit().await;
181
182 println!("\n--- BT List with recursion ---");
183 let options = BtListOptions::new(test_dir).recursion(1).num(num_per_page);
184 match client.file().list_torrents_with_options(options).await {
185 Ok(files) => {
186 println!("Found {} torrent files", files.len());
187 for file in &files {
188 let size_str = file
189 .size
190 .map(|s| format_size(s))
191 .unwrap_or_else(|| "N/A".to_string());
192 println!(" - {} ({})", file.name, size_str);
193 }
194 }
195 Err(e) => {
196 println!("Error: {}", e);
197 }
198 }
199
200 println!("\n=== Test Completed ===");
201
202 Ok(())
203}Sourcepub async fn list_documents_with_options(
&self,
options: DocumentListOptions,
) -> NetDiskResult<Vec<FileInfo>>
pub async fn list_documents_with_options( &self, options: DocumentListOptions, ) -> NetDiskResult<Vec<FileInfo>>
List documents with custom options
Examples found in repository?
24async fn main() -> Result<(), Box<dyn std::error::Error>> {
25 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
26
27 let client = BaiduNetDiskClient::builder().build()?;
28 info!("Client created successfully");
29
30 client.load_token_from_env()?;
31 info!("Token loaded successfully");
32
33 let test_dir = "/apps/product";
34 let num_per_page = 5;
35
36 println!("=== Baidu NetDisk Fixed Category List Test ===");
37 println!("Directory: {}", test_dir);
38 println!("Items per page: {}\n", num_per_page);
39
40 println!("--- Part 1: Document List (doclist) ---");
41 match client
42 .file()
43 .list_documents(test_dir, 1, num_per_page)
44 .await
45 {
46 Ok(files) => {
47 println!("Found {} documents", files.len());
48 for file in &files {
49 let size_str = file
50 .size
51 .map(|s| format_size(s))
52 .unwrap_or_else(|| "N/A".to_string());
53 println!(" - {} ({})", file.name, size_str);
54 }
55 }
56 Err(e) => {
57 println!("Error: {}", e);
58 }
59 }
60 wait_for_rate_limit().await;
61
62 println!("\n--- Part 2: Image List (imagelist) ---");
63 match client.file().list_images(test_dir, 1, num_per_page).await {
64 Ok(files) => {
65 println!("Found {} images", files.len());
66 for file in &files {
67 let size_str = file
68 .size
69 .map(|s| format_size(s))
70 .unwrap_or_else(|| "N/A".to_string());
71 println!(" - {} ({})", file.name, size_str);
72 }
73 }
74 Err(e) => {
75 println!("Error: {}", e);
76 }
77 }
78 wait_for_rate_limit().await;
79
80 println!("\n--- Part 3: Video List (videolist) ---");
81 match client.file().list_videos(test_dir, 1, num_per_page).await {
82 Ok(files) => {
83 println!("Found {} videos", files.len());
84 for file in &files {
85 let size_str = file
86 .size
87 .map(|s| format_size(s))
88 .unwrap_or_else(|| "N/A".to_string());
89 println!(" - {} ({})", file.name, size_str);
90 }
91 }
92 Err(e) => {
93 println!("Error: {}", e);
94 }
95 }
96 wait_for_rate_limit().await;
97
98 println!("\n--- Part 4: BT List (btlist) ---");
99 match client.file().list_torrents(test_dir, 1, num_per_page).await {
100 Ok(files) => {
101 println!("Found {} torrent files", files.len());
102 for file in &files {
103 let size_str = file
104 .size
105 .map(|s| format_size(s))
106 .unwrap_or_else(|| "N/A".to_string());
107 println!(" - {} ({})", file.name, size_str);
108 }
109 }
110 Err(e) => {
111 println!("Error: {}", e);
112 }
113 }
114 wait_for_rate_limit().await;
115
116 println!("\n=== Test with Options (recursion=1) ===");
117 println!("Directory: {}\n", test_dir);
118
119 println!("--- Document List with recursion ---");
120 let options = DocumentListOptions::new(test_dir)
121 .recursion(1)
122 .num(num_per_page);
123 match client.file().list_documents_with_options(options).await {
124 Ok(files) => {
125 println!("Found {} documents", files.len());
126 for file in &files {
127 let size_str = file
128 .size
129 .map(|s| format_size(s))
130 .unwrap_or_else(|| "N/A".to_string());
131 println!(" - {} ({})", file.name, size_str);
132 }
133 }
134 Err(e) => {
135 println!("Error: {}", e);
136 }
137 }
138 wait_for_rate_limit().await;
139
140 println!("\n--- Image List with recursion ---");
141 let options = ImageListOptions::new(test_dir)
142 .recursion(1)
143 .num(num_per_page);
144 match client.file().list_images_with_options(options).await {
145 Ok(files) => {
146 println!("Found {} images", files.len());
147 for file in &files {
148 let size_str = file
149 .size
150 .map(|s| format_size(s))
151 .unwrap_or_else(|| "N/A".to_string());
152 println!(" - {} ({})", file.name, size_str);
153 }
154 }
155 Err(e) => {
156 println!("Error: {}", e);
157 }
158 }
159 wait_for_rate_limit().await;
160
161 println!("\n--- Video List with recursion ---");
162 let options = VideoListOptions::new(test_dir)
163 .recursion(1)
164 .num(num_per_page);
165 match client.file().list_videos_with_options(options).await {
166 Ok(files) => {
167 println!("Found {} videos", files.len());
168 for file in &files {
169 let size_str = file
170 .size
171 .map(|s| format_size(s))
172 .unwrap_or_else(|| "N/A".to_string());
173 println!(" - {} ({})", file.name, size_str);
174 }
175 }
176 Err(e) => {
177 println!("Error: {}", e);
178 }
179 }
180 wait_for_rate_limit().await;
181
182 println!("\n--- BT List with recursion ---");
183 let options = BtListOptions::new(test_dir).recursion(1).num(num_per_page);
184 match client.file().list_torrents_with_options(options).await {
185 Ok(files) => {
186 println!("Found {} torrent files", files.len());
187 for file in &files {
188 let size_str = file
189 .size
190 .map(|s| format_size(s))
191 .unwrap_or_else(|| "N/A".to_string());
192 println!(" - {} ({})", file.name, size_str);
193 }
194 }
195 Err(e) => {
196 println!("Error: {}", e);
197 }
198 }
199
200 println!("\n=== Test Completed ===");
201
202 Ok(())
203}Sourcepub async fn list_images(
&self,
parent_path: &str,
page: i32,
num: i32,
) -> NetDiskResult<Vec<FileInfo>>
pub async fn list_images( &self, parent_path: &str, page: i32, num: i32, ) -> NetDiskResult<Vec<FileInfo>>
List images
Examples found in repository?
24async fn main() -> Result<(), Box<dyn std::error::Error>> {
25 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
26
27 let client = BaiduNetDiskClient::builder().build()?;
28 info!("Client created successfully");
29
30 client.load_token_from_env()?;
31 info!("Token loaded successfully");
32
33 let test_dir = "/apps/product";
34 let num_per_page = 5;
35
36 println!("=== Baidu NetDisk Fixed Category List Test ===");
37 println!("Directory: {}", test_dir);
38 println!("Items per page: {}\n", num_per_page);
39
40 println!("--- Part 1: Document List (doclist) ---");
41 match client
42 .file()
43 .list_documents(test_dir, 1, num_per_page)
44 .await
45 {
46 Ok(files) => {
47 println!("Found {} documents", files.len());
48 for file in &files {
49 let size_str = file
50 .size
51 .map(|s| format_size(s))
52 .unwrap_or_else(|| "N/A".to_string());
53 println!(" - {} ({})", file.name, size_str);
54 }
55 }
56 Err(e) => {
57 println!("Error: {}", e);
58 }
59 }
60 wait_for_rate_limit().await;
61
62 println!("\n--- Part 2: Image List (imagelist) ---");
63 match client.file().list_images(test_dir, 1, num_per_page).await {
64 Ok(files) => {
65 println!("Found {} images", files.len());
66 for file in &files {
67 let size_str = file
68 .size
69 .map(|s| format_size(s))
70 .unwrap_or_else(|| "N/A".to_string());
71 println!(" - {} ({})", file.name, size_str);
72 }
73 }
74 Err(e) => {
75 println!("Error: {}", e);
76 }
77 }
78 wait_for_rate_limit().await;
79
80 println!("\n--- Part 3: Video List (videolist) ---");
81 match client.file().list_videos(test_dir, 1, num_per_page).await {
82 Ok(files) => {
83 println!("Found {} videos", files.len());
84 for file in &files {
85 let size_str = file
86 .size
87 .map(|s| format_size(s))
88 .unwrap_or_else(|| "N/A".to_string());
89 println!(" - {} ({})", file.name, size_str);
90 }
91 }
92 Err(e) => {
93 println!("Error: {}", e);
94 }
95 }
96 wait_for_rate_limit().await;
97
98 println!("\n--- Part 4: BT List (btlist) ---");
99 match client.file().list_torrents(test_dir, 1, num_per_page).await {
100 Ok(files) => {
101 println!("Found {} torrent files", files.len());
102 for file in &files {
103 let size_str = file
104 .size
105 .map(|s| format_size(s))
106 .unwrap_or_else(|| "N/A".to_string());
107 println!(" - {} ({})", file.name, size_str);
108 }
109 }
110 Err(e) => {
111 println!("Error: {}", e);
112 }
113 }
114 wait_for_rate_limit().await;
115
116 println!("\n=== Test with Options (recursion=1) ===");
117 println!("Directory: {}\n", test_dir);
118
119 println!("--- Document List with recursion ---");
120 let options = DocumentListOptions::new(test_dir)
121 .recursion(1)
122 .num(num_per_page);
123 match client.file().list_documents_with_options(options).await {
124 Ok(files) => {
125 println!("Found {} documents", files.len());
126 for file in &files {
127 let size_str = file
128 .size
129 .map(|s| format_size(s))
130 .unwrap_or_else(|| "N/A".to_string());
131 println!(" - {} ({})", file.name, size_str);
132 }
133 }
134 Err(e) => {
135 println!("Error: {}", e);
136 }
137 }
138 wait_for_rate_limit().await;
139
140 println!("\n--- Image List with recursion ---");
141 let options = ImageListOptions::new(test_dir)
142 .recursion(1)
143 .num(num_per_page);
144 match client.file().list_images_with_options(options).await {
145 Ok(files) => {
146 println!("Found {} images", files.len());
147 for file in &files {
148 let size_str = file
149 .size
150 .map(|s| format_size(s))
151 .unwrap_or_else(|| "N/A".to_string());
152 println!(" - {} ({})", file.name, size_str);
153 }
154 }
155 Err(e) => {
156 println!("Error: {}", e);
157 }
158 }
159 wait_for_rate_limit().await;
160
161 println!("\n--- Video List with recursion ---");
162 let options = VideoListOptions::new(test_dir)
163 .recursion(1)
164 .num(num_per_page);
165 match client.file().list_videos_with_options(options).await {
166 Ok(files) => {
167 println!("Found {} videos", files.len());
168 for file in &files {
169 let size_str = file
170 .size
171 .map(|s| format_size(s))
172 .unwrap_or_else(|| "N/A".to_string());
173 println!(" - {} ({})", file.name, size_str);
174 }
175 }
176 Err(e) => {
177 println!("Error: {}", e);
178 }
179 }
180 wait_for_rate_limit().await;
181
182 println!("\n--- BT List with recursion ---");
183 let options = BtListOptions::new(test_dir).recursion(1).num(num_per_page);
184 match client.file().list_torrents_with_options(options).await {
185 Ok(files) => {
186 println!("Found {} torrent files", files.len());
187 for file in &files {
188 let size_str = file
189 .size
190 .map(|s| format_size(s))
191 .unwrap_or_else(|| "N/A".to_string());
192 println!(" - {} ({})", file.name, size_str);
193 }
194 }
195 Err(e) => {
196 println!("Error: {}", e);
197 }
198 }
199
200 println!("\n=== Test Completed ===");
201
202 Ok(())
203}Sourcepub async fn list_images_with_options(
&self,
options: ImageListOptions,
) -> NetDiskResult<Vec<FileInfo>>
pub async fn list_images_with_options( &self, options: ImageListOptions, ) -> NetDiskResult<Vec<FileInfo>>
List images with custom options
Examples found in repository?
24async fn main() -> Result<(), Box<dyn std::error::Error>> {
25 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
26
27 let client = BaiduNetDiskClient::builder().build()?;
28 info!("Client created successfully");
29
30 client.load_token_from_env()?;
31 info!("Token loaded successfully");
32
33 let test_dir = "/apps/product";
34 let num_per_page = 5;
35
36 println!("=== Baidu NetDisk Fixed Category List Test ===");
37 println!("Directory: {}", test_dir);
38 println!("Items per page: {}\n", num_per_page);
39
40 println!("--- Part 1: Document List (doclist) ---");
41 match client
42 .file()
43 .list_documents(test_dir, 1, num_per_page)
44 .await
45 {
46 Ok(files) => {
47 println!("Found {} documents", files.len());
48 for file in &files {
49 let size_str = file
50 .size
51 .map(|s| format_size(s))
52 .unwrap_or_else(|| "N/A".to_string());
53 println!(" - {} ({})", file.name, size_str);
54 }
55 }
56 Err(e) => {
57 println!("Error: {}", e);
58 }
59 }
60 wait_for_rate_limit().await;
61
62 println!("\n--- Part 2: Image List (imagelist) ---");
63 match client.file().list_images(test_dir, 1, num_per_page).await {
64 Ok(files) => {
65 println!("Found {} images", files.len());
66 for file in &files {
67 let size_str = file
68 .size
69 .map(|s| format_size(s))
70 .unwrap_or_else(|| "N/A".to_string());
71 println!(" - {} ({})", file.name, size_str);
72 }
73 }
74 Err(e) => {
75 println!("Error: {}", e);
76 }
77 }
78 wait_for_rate_limit().await;
79
80 println!("\n--- Part 3: Video List (videolist) ---");
81 match client.file().list_videos(test_dir, 1, num_per_page).await {
82 Ok(files) => {
83 println!("Found {} videos", files.len());
84 for file in &files {
85 let size_str = file
86 .size
87 .map(|s| format_size(s))
88 .unwrap_or_else(|| "N/A".to_string());
89 println!(" - {} ({})", file.name, size_str);
90 }
91 }
92 Err(e) => {
93 println!("Error: {}", e);
94 }
95 }
96 wait_for_rate_limit().await;
97
98 println!("\n--- Part 4: BT List (btlist) ---");
99 match client.file().list_torrents(test_dir, 1, num_per_page).await {
100 Ok(files) => {
101 println!("Found {} torrent files", files.len());
102 for file in &files {
103 let size_str = file
104 .size
105 .map(|s| format_size(s))
106 .unwrap_or_else(|| "N/A".to_string());
107 println!(" - {} ({})", file.name, size_str);
108 }
109 }
110 Err(e) => {
111 println!("Error: {}", e);
112 }
113 }
114 wait_for_rate_limit().await;
115
116 println!("\n=== Test with Options (recursion=1) ===");
117 println!("Directory: {}\n", test_dir);
118
119 println!("--- Document List with recursion ---");
120 let options = DocumentListOptions::new(test_dir)
121 .recursion(1)
122 .num(num_per_page);
123 match client.file().list_documents_with_options(options).await {
124 Ok(files) => {
125 println!("Found {} documents", files.len());
126 for file in &files {
127 let size_str = file
128 .size
129 .map(|s| format_size(s))
130 .unwrap_or_else(|| "N/A".to_string());
131 println!(" - {} ({})", file.name, size_str);
132 }
133 }
134 Err(e) => {
135 println!("Error: {}", e);
136 }
137 }
138 wait_for_rate_limit().await;
139
140 println!("\n--- Image List with recursion ---");
141 let options = ImageListOptions::new(test_dir)
142 .recursion(1)
143 .num(num_per_page);
144 match client.file().list_images_with_options(options).await {
145 Ok(files) => {
146 println!("Found {} images", files.len());
147 for file in &files {
148 let size_str = file
149 .size
150 .map(|s| format_size(s))
151 .unwrap_or_else(|| "N/A".to_string());
152 println!(" - {} ({})", file.name, size_str);
153 }
154 }
155 Err(e) => {
156 println!("Error: {}", e);
157 }
158 }
159 wait_for_rate_limit().await;
160
161 println!("\n--- Video List with recursion ---");
162 let options = VideoListOptions::new(test_dir)
163 .recursion(1)
164 .num(num_per_page);
165 match client.file().list_videos_with_options(options).await {
166 Ok(files) => {
167 println!("Found {} videos", files.len());
168 for file in &files {
169 let size_str = file
170 .size
171 .map(|s| format_size(s))
172 .unwrap_or_else(|| "N/A".to_string());
173 println!(" - {} ({})", file.name, size_str);
174 }
175 }
176 Err(e) => {
177 println!("Error: {}", e);
178 }
179 }
180 wait_for_rate_limit().await;
181
182 println!("\n--- BT List with recursion ---");
183 let options = BtListOptions::new(test_dir).recursion(1).num(num_per_page);
184 match client.file().list_torrents_with_options(options).await {
185 Ok(files) => {
186 println!("Found {} torrent files", files.len());
187 for file in &files {
188 let size_str = file
189 .size
190 .map(|s| format_size(s))
191 .unwrap_or_else(|| "N/A".to_string());
192 println!(" - {} ({})", file.name, size_str);
193 }
194 }
195 Err(e) => {
196 println!("Error: {}", e);
197 }
198 }
199
200 println!("\n=== Test Completed ===");
201
202 Ok(())
203}Sourcepub async fn list_videos(
&self,
parent_path: &str,
page: i32,
num: i32,
) -> NetDiskResult<Vec<FileInfo>>
pub async fn list_videos( &self, parent_path: &str, page: i32, num: i32, ) -> NetDiskResult<Vec<FileInfo>>
List videos
Examples found in repository?
24async fn main() -> Result<(), Box<dyn std::error::Error>> {
25 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
26
27 let client = BaiduNetDiskClient::builder().build()?;
28 info!("Client created successfully");
29
30 client.load_token_from_env()?;
31 info!("Token loaded successfully");
32
33 let test_dir = "/apps/product";
34 let num_per_page = 5;
35
36 println!("=== Baidu NetDisk Fixed Category List Test ===");
37 println!("Directory: {}", test_dir);
38 println!("Items per page: {}\n", num_per_page);
39
40 println!("--- Part 1: Document List (doclist) ---");
41 match client
42 .file()
43 .list_documents(test_dir, 1, num_per_page)
44 .await
45 {
46 Ok(files) => {
47 println!("Found {} documents", files.len());
48 for file in &files {
49 let size_str = file
50 .size
51 .map(|s| format_size(s))
52 .unwrap_or_else(|| "N/A".to_string());
53 println!(" - {} ({})", file.name, size_str);
54 }
55 }
56 Err(e) => {
57 println!("Error: {}", e);
58 }
59 }
60 wait_for_rate_limit().await;
61
62 println!("\n--- Part 2: Image List (imagelist) ---");
63 match client.file().list_images(test_dir, 1, num_per_page).await {
64 Ok(files) => {
65 println!("Found {} images", files.len());
66 for file in &files {
67 let size_str = file
68 .size
69 .map(|s| format_size(s))
70 .unwrap_or_else(|| "N/A".to_string());
71 println!(" - {} ({})", file.name, size_str);
72 }
73 }
74 Err(e) => {
75 println!("Error: {}", e);
76 }
77 }
78 wait_for_rate_limit().await;
79
80 println!("\n--- Part 3: Video List (videolist) ---");
81 match client.file().list_videos(test_dir, 1, num_per_page).await {
82 Ok(files) => {
83 println!("Found {} videos", files.len());
84 for file in &files {
85 let size_str = file
86 .size
87 .map(|s| format_size(s))
88 .unwrap_or_else(|| "N/A".to_string());
89 println!(" - {} ({})", file.name, size_str);
90 }
91 }
92 Err(e) => {
93 println!("Error: {}", e);
94 }
95 }
96 wait_for_rate_limit().await;
97
98 println!("\n--- Part 4: BT List (btlist) ---");
99 match client.file().list_torrents(test_dir, 1, num_per_page).await {
100 Ok(files) => {
101 println!("Found {} torrent files", files.len());
102 for file in &files {
103 let size_str = file
104 .size
105 .map(|s| format_size(s))
106 .unwrap_or_else(|| "N/A".to_string());
107 println!(" - {} ({})", file.name, size_str);
108 }
109 }
110 Err(e) => {
111 println!("Error: {}", e);
112 }
113 }
114 wait_for_rate_limit().await;
115
116 println!("\n=== Test with Options (recursion=1) ===");
117 println!("Directory: {}\n", test_dir);
118
119 println!("--- Document List with recursion ---");
120 let options = DocumentListOptions::new(test_dir)
121 .recursion(1)
122 .num(num_per_page);
123 match client.file().list_documents_with_options(options).await {
124 Ok(files) => {
125 println!("Found {} documents", files.len());
126 for file in &files {
127 let size_str = file
128 .size
129 .map(|s| format_size(s))
130 .unwrap_or_else(|| "N/A".to_string());
131 println!(" - {} ({})", file.name, size_str);
132 }
133 }
134 Err(e) => {
135 println!("Error: {}", e);
136 }
137 }
138 wait_for_rate_limit().await;
139
140 println!("\n--- Image List with recursion ---");
141 let options = ImageListOptions::new(test_dir)
142 .recursion(1)
143 .num(num_per_page);
144 match client.file().list_images_with_options(options).await {
145 Ok(files) => {
146 println!("Found {} images", files.len());
147 for file in &files {
148 let size_str = file
149 .size
150 .map(|s| format_size(s))
151 .unwrap_or_else(|| "N/A".to_string());
152 println!(" - {} ({})", file.name, size_str);
153 }
154 }
155 Err(e) => {
156 println!("Error: {}", e);
157 }
158 }
159 wait_for_rate_limit().await;
160
161 println!("\n--- Video List with recursion ---");
162 let options = VideoListOptions::new(test_dir)
163 .recursion(1)
164 .num(num_per_page);
165 match client.file().list_videos_with_options(options).await {
166 Ok(files) => {
167 println!("Found {} videos", files.len());
168 for file in &files {
169 let size_str = file
170 .size
171 .map(|s| format_size(s))
172 .unwrap_or_else(|| "N/A".to_string());
173 println!(" - {} ({})", file.name, size_str);
174 }
175 }
176 Err(e) => {
177 println!("Error: {}", e);
178 }
179 }
180 wait_for_rate_limit().await;
181
182 println!("\n--- BT List with recursion ---");
183 let options = BtListOptions::new(test_dir).recursion(1).num(num_per_page);
184 match client.file().list_torrents_with_options(options).await {
185 Ok(files) => {
186 println!("Found {} torrent files", files.len());
187 for file in &files {
188 let size_str = file
189 .size
190 .map(|s| format_size(s))
191 .unwrap_or_else(|| "N/A".to_string());
192 println!(" - {} ({})", file.name, size_str);
193 }
194 }
195 Err(e) => {
196 println!("Error: {}", e);
197 }
198 }
199
200 println!("\n=== Test Completed ===");
201
202 Ok(())
203}Sourcepub async fn list_videos_with_options(
&self,
options: VideoListOptions,
) -> NetDiskResult<Vec<FileInfo>>
pub async fn list_videos_with_options( &self, options: VideoListOptions, ) -> NetDiskResult<Vec<FileInfo>>
List videos with custom options
Examples found in repository?
24async fn main() -> Result<(), Box<dyn std::error::Error>> {
25 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
26
27 let client = BaiduNetDiskClient::builder().build()?;
28 info!("Client created successfully");
29
30 client.load_token_from_env()?;
31 info!("Token loaded successfully");
32
33 let test_dir = "/apps/product";
34 let num_per_page = 5;
35
36 println!("=== Baidu NetDisk Fixed Category List Test ===");
37 println!("Directory: {}", test_dir);
38 println!("Items per page: {}\n", num_per_page);
39
40 println!("--- Part 1: Document List (doclist) ---");
41 match client
42 .file()
43 .list_documents(test_dir, 1, num_per_page)
44 .await
45 {
46 Ok(files) => {
47 println!("Found {} documents", files.len());
48 for file in &files {
49 let size_str = file
50 .size
51 .map(|s| format_size(s))
52 .unwrap_or_else(|| "N/A".to_string());
53 println!(" - {} ({})", file.name, size_str);
54 }
55 }
56 Err(e) => {
57 println!("Error: {}", e);
58 }
59 }
60 wait_for_rate_limit().await;
61
62 println!("\n--- Part 2: Image List (imagelist) ---");
63 match client.file().list_images(test_dir, 1, num_per_page).await {
64 Ok(files) => {
65 println!("Found {} images", files.len());
66 for file in &files {
67 let size_str = file
68 .size
69 .map(|s| format_size(s))
70 .unwrap_or_else(|| "N/A".to_string());
71 println!(" - {} ({})", file.name, size_str);
72 }
73 }
74 Err(e) => {
75 println!("Error: {}", e);
76 }
77 }
78 wait_for_rate_limit().await;
79
80 println!("\n--- Part 3: Video List (videolist) ---");
81 match client.file().list_videos(test_dir, 1, num_per_page).await {
82 Ok(files) => {
83 println!("Found {} videos", files.len());
84 for file in &files {
85 let size_str = file
86 .size
87 .map(|s| format_size(s))
88 .unwrap_or_else(|| "N/A".to_string());
89 println!(" - {} ({})", file.name, size_str);
90 }
91 }
92 Err(e) => {
93 println!("Error: {}", e);
94 }
95 }
96 wait_for_rate_limit().await;
97
98 println!("\n--- Part 4: BT List (btlist) ---");
99 match client.file().list_torrents(test_dir, 1, num_per_page).await {
100 Ok(files) => {
101 println!("Found {} torrent files", files.len());
102 for file in &files {
103 let size_str = file
104 .size
105 .map(|s| format_size(s))
106 .unwrap_or_else(|| "N/A".to_string());
107 println!(" - {} ({})", file.name, size_str);
108 }
109 }
110 Err(e) => {
111 println!("Error: {}", e);
112 }
113 }
114 wait_for_rate_limit().await;
115
116 println!("\n=== Test with Options (recursion=1) ===");
117 println!("Directory: {}\n", test_dir);
118
119 println!("--- Document List with recursion ---");
120 let options = DocumentListOptions::new(test_dir)
121 .recursion(1)
122 .num(num_per_page);
123 match client.file().list_documents_with_options(options).await {
124 Ok(files) => {
125 println!("Found {} documents", files.len());
126 for file in &files {
127 let size_str = file
128 .size
129 .map(|s| format_size(s))
130 .unwrap_or_else(|| "N/A".to_string());
131 println!(" - {} ({})", file.name, size_str);
132 }
133 }
134 Err(e) => {
135 println!("Error: {}", e);
136 }
137 }
138 wait_for_rate_limit().await;
139
140 println!("\n--- Image List with recursion ---");
141 let options = ImageListOptions::new(test_dir)
142 .recursion(1)
143 .num(num_per_page);
144 match client.file().list_images_with_options(options).await {
145 Ok(files) => {
146 println!("Found {} images", files.len());
147 for file in &files {
148 let size_str = file
149 .size
150 .map(|s| format_size(s))
151 .unwrap_or_else(|| "N/A".to_string());
152 println!(" - {} ({})", file.name, size_str);
153 }
154 }
155 Err(e) => {
156 println!("Error: {}", e);
157 }
158 }
159 wait_for_rate_limit().await;
160
161 println!("\n--- Video List with recursion ---");
162 let options = VideoListOptions::new(test_dir)
163 .recursion(1)
164 .num(num_per_page);
165 match client.file().list_videos_with_options(options).await {
166 Ok(files) => {
167 println!("Found {} videos", files.len());
168 for file in &files {
169 let size_str = file
170 .size
171 .map(|s| format_size(s))
172 .unwrap_or_else(|| "N/A".to_string());
173 println!(" - {} ({})", file.name, size_str);
174 }
175 }
176 Err(e) => {
177 println!("Error: {}", e);
178 }
179 }
180 wait_for_rate_limit().await;
181
182 println!("\n--- BT List with recursion ---");
183 let options = BtListOptions::new(test_dir).recursion(1).num(num_per_page);
184 match client.file().list_torrents_with_options(options).await {
185 Ok(files) => {
186 println!("Found {} torrent files", files.len());
187 for file in &files {
188 let size_str = file
189 .size
190 .map(|s| format_size(s))
191 .unwrap_or_else(|| "N/A".to_string());
192 println!(" - {} ({})", file.name, size_str);
193 }
194 }
195 Err(e) => {
196 println!("Error: {}", e);
197 }
198 }
199
200 println!("\n=== Test Completed ===");
201
202 Ok(())
203}Sourcepub async fn list_torrents(
&self,
parent_path: &str,
page: i32,
num: i32,
) -> NetDiskResult<Vec<FileInfo>>
pub async fn list_torrents( &self, parent_path: &str, page: i32, num: i32, ) -> NetDiskResult<Vec<FileInfo>>
List torrents
Examples found in repository?
24async fn main() -> Result<(), Box<dyn std::error::Error>> {
25 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
26
27 let client = BaiduNetDiskClient::builder().build()?;
28 info!("Client created successfully");
29
30 client.load_token_from_env()?;
31 info!("Token loaded successfully");
32
33 let test_dir = "/apps/product";
34 let num_per_page = 5;
35
36 println!("=== Baidu NetDisk Fixed Category List Test ===");
37 println!("Directory: {}", test_dir);
38 println!("Items per page: {}\n", num_per_page);
39
40 println!("--- Part 1: Document List (doclist) ---");
41 match client
42 .file()
43 .list_documents(test_dir, 1, num_per_page)
44 .await
45 {
46 Ok(files) => {
47 println!("Found {} documents", files.len());
48 for file in &files {
49 let size_str = file
50 .size
51 .map(|s| format_size(s))
52 .unwrap_or_else(|| "N/A".to_string());
53 println!(" - {} ({})", file.name, size_str);
54 }
55 }
56 Err(e) => {
57 println!("Error: {}", e);
58 }
59 }
60 wait_for_rate_limit().await;
61
62 println!("\n--- Part 2: Image List (imagelist) ---");
63 match client.file().list_images(test_dir, 1, num_per_page).await {
64 Ok(files) => {
65 println!("Found {} images", files.len());
66 for file in &files {
67 let size_str = file
68 .size
69 .map(|s| format_size(s))
70 .unwrap_or_else(|| "N/A".to_string());
71 println!(" - {} ({})", file.name, size_str);
72 }
73 }
74 Err(e) => {
75 println!("Error: {}", e);
76 }
77 }
78 wait_for_rate_limit().await;
79
80 println!("\n--- Part 3: Video List (videolist) ---");
81 match client.file().list_videos(test_dir, 1, num_per_page).await {
82 Ok(files) => {
83 println!("Found {} videos", files.len());
84 for file in &files {
85 let size_str = file
86 .size
87 .map(|s| format_size(s))
88 .unwrap_or_else(|| "N/A".to_string());
89 println!(" - {} ({})", file.name, size_str);
90 }
91 }
92 Err(e) => {
93 println!("Error: {}", e);
94 }
95 }
96 wait_for_rate_limit().await;
97
98 println!("\n--- Part 4: BT List (btlist) ---");
99 match client.file().list_torrents(test_dir, 1, num_per_page).await {
100 Ok(files) => {
101 println!("Found {} torrent files", files.len());
102 for file in &files {
103 let size_str = file
104 .size
105 .map(|s| format_size(s))
106 .unwrap_or_else(|| "N/A".to_string());
107 println!(" - {} ({})", file.name, size_str);
108 }
109 }
110 Err(e) => {
111 println!("Error: {}", e);
112 }
113 }
114 wait_for_rate_limit().await;
115
116 println!("\n=== Test with Options (recursion=1) ===");
117 println!("Directory: {}\n", test_dir);
118
119 println!("--- Document List with recursion ---");
120 let options = DocumentListOptions::new(test_dir)
121 .recursion(1)
122 .num(num_per_page);
123 match client.file().list_documents_with_options(options).await {
124 Ok(files) => {
125 println!("Found {} documents", files.len());
126 for file in &files {
127 let size_str = file
128 .size
129 .map(|s| format_size(s))
130 .unwrap_or_else(|| "N/A".to_string());
131 println!(" - {} ({})", file.name, size_str);
132 }
133 }
134 Err(e) => {
135 println!("Error: {}", e);
136 }
137 }
138 wait_for_rate_limit().await;
139
140 println!("\n--- Image List with recursion ---");
141 let options = ImageListOptions::new(test_dir)
142 .recursion(1)
143 .num(num_per_page);
144 match client.file().list_images_with_options(options).await {
145 Ok(files) => {
146 println!("Found {} images", files.len());
147 for file in &files {
148 let size_str = file
149 .size
150 .map(|s| format_size(s))
151 .unwrap_or_else(|| "N/A".to_string());
152 println!(" - {} ({})", file.name, size_str);
153 }
154 }
155 Err(e) => {
156 println!("Error: {}", e);
157 }
158 }
159 wait_for_rate_limit().await;
160
161 println!("\n--- Video List with recursion ---");
162 let options = VideoListOptions::new(test_dir)
163 .recursion(1)
164 .num(num_per_page);
165 match client.file().list_videos_with_options(options).await {
166 Ok(files) => {
167 println!("Found {} videos", files.len());
168 for file in &files {
169 let size_str = file
170 .size
171 .map(|s| format_size(s))
172 .unwrap_or_else(|| "N/A".to_string());
173 println!(" - {} ({})", file.name, size_str);
174 }
175 }
176 Err(e) => {
177 println!("Error: {}", e);
178 }
179 }
180 wait_for_rate_limit().await;
181
182 println!("\n--- BT List with recursion ---");
183 let options = BtListOptions::new(test_dir).recursion(1).num(num_per_page);
184 match client.file().list_torrents_with_options(options).await {
185 Ok(files) => {
186 println!("Found {} torrent files", files.len());
187 for file in &files {
188 let size_str = file
189 .size
190 .map(|s| format_size(s))
191 .unwrap_or_else(|| "N/A".to_string());
192 println!(" - {} ({})", file.name, size_str);
193 }
194 }
195 Err(e) => {
196 println!("Error: {}", e);
197 }
198 }
199
200 println!("\n=== Test Completed ===");
201
202 Ok(())
203}Sourcepub async fn list_torrents_with_options(
&self,
options: BtListOptions,
) -> NetDiskResult<Vec<FileInfo>>
pub async fn list_torrents_with_options( &self, options: BtListOptions, ) -> NetDiskResult<Vec<FileInfo>>
List torrents with custom options
Examples found in repository?
24async fn main() -> Result<(), Box<dyn std::error::Error>> {
25 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
26
27 let client = BaiduNetDiskClient::builder().build()?;
28 info!("Client created successfully");
29
30 client.load_token_from_env()?;
31 info!("Token loaded successfully");
32
33 let test_dir = "/apps/product";
34 let num_per_page = 5;
35
36 println!("=== Baidu NetDisk Fixed Category List Test ===");
37 println!("Directory: {}", test_dir);
38 println!("Items per page: {}\n", num_per_page);
39
40 println!("--- Part 1: Document List (doclist) ---");
41 match client
42 .file()
43 .list_documents(test_dir, 1, num_per_page)
44 .await
45 {
46 Ok(files) => {
47 println!("Found {} documents", files.len());
48 for file in &files {
49 let size_str = file
50 .size
51 .map(|s| format_size(s))
52 .unwrap_or_else(|| "N/A".to_string());
53 println!(" - {} ({})", file.name, size_str);
54 }
55 }
56 Err(e) => {
57 println!("Error: {}", e);
58 }
59 }
60 wait_for_rate_limit().await;
61
62 println!("\n--- Part 2: Image List (imagelist) ---");
63 match client.file().list_images(test_dir, 1, num_per_page).await {
64 Ok(files) => {
65 println!("Found {} images", files.len());
66 for file in &files {
67 let size_str = file
68 .size
69 .map(|s| format_size(s))
70 .unwrap_or_else(|| "N/A".to_string());
71 println!(" - {} ({})", file.name, size_str);
72 }
73 }
74 Err(e) => {
75 println!("Error: {}", e);
76 }
77 }
78 wait_for_rate_limit().await;
79
80 println!("\n--- Part 3: Video List (videolist) ---");
81 match client.file().list_videos(test_dir, 1, num_per_page).await {
82 Ok(files) => {
83 println!("Found {} videos", files.len());
84 for file in &files {
85 let size_str = file
86 .size
87 .map(|s| format_size(s))
88 .unwrap_or_else(|| "N/A".to_string());
89 println!(" - {} ({})", file.name, size_str);
90 }
91 }
92 Err(e) => {
93 println!("Error: {}", e);
94 }
95 }
96 wait_for_rate_limit().await;
97
98 println!("\n--- Part 4: BT List (btlist) ---");
99 match client.file().list_torrents(test_dir, 1, num_per_page).await {
100 Ok(files) => {
101 println!("Found {} torrent files", files.len());
102 for file in &files {
103 let size_str = file
104 .size
105 .map(|s| format_size(s))
106 .unwrap_or_else(|| "N/A".to_string());
107 println!(" - {} ({})", file.name, size_str);
108 }
109 }
110 Err(e) => {
111 println!("Error: {}", e);
112 }
113 }
114 wait_for_rate_limit().await;
115
116 println!("\n=== Test with Options (recursion=1) ===");
117 println!("Directory: {}\n", test_dir);
118
119 println!("--- Document List with recursion ---");
120 let options = DocumentListOptions::new(test_dir)
121 .recursion(1)
122 .num(num_per_page);
123 match client.file().list_documents_with_options(options).await {
124 Ok(files) => {
125 println!("Found {} documents", files.len());
126 for file in &files {
127 let size_str = file
128 .size
129 .map(|s| format_size(s))
130 .unwrap_or_else(|| "N/A".to_string());
131 println!(" - {} ({})", file.name, size_str);
132 }
133 }
134 Err(e) => {
135 println!("Error: {}", e);
136 }
137 }
138 wait_for_rate_limit().await;
139
140 println!("\n--- Image List with recursion ---");
141 let options = ImageListOptions::new(test_dir)
142 .recursion(1)
143 .num(num_per_page);
144 match client.file().list_images_with_options(options).await {
145 Ok(files) => {
146 println!("Found {} images", files.len());
147 for file in &files {
148 let size_str = file
149 .size
150 .map(|s| format_size(s))
151 .unwrap_or_else(|| "N/A".to_string());
152 println!(" - {} ({})", file.name, size_str);
153 }
154 }
155 Err(e) => {
156 println!("Error: {}", e);
157 }
158 }
159 wait_for_rate_limit().await;
160
161 println!("\n--- Video List with recursion ---");
162 let options = VideoListOptions::new(test_dir)
163 .recursion(1)
164 .num(num_per_page);
165 match client.file().list_videos_with_options(options).await {
166 Ok(files) => {
167 println!("Found {} videos", files.len());
168 for file in &files {
169 let size_str = file
170 .size
171 .map(|s| format_size(s))
172 .unwrap_or_else(|| "N/A".to_string());
173 println!(" - {} ({})", file.name, size_str);
174 }
175 }
176 Err(e) => {
177 println!("Error: {}", e);
178 }
179 }
180 wait_for_rate_limit().await;
181
182 println!("\n--- BT List with recursion ---");
183 let options = BtListOptions::new(test_dir).recursion(1).num(num_per_page);
184 match client.file().list_torrents_with_options(options).await {
185 Ok(files) => {
186 println!("Found {} torrent files", files.len());
187 for file in &files {
188 let size_str = file
189 .size
190 .map(|s| format_size(s))
191 .unwrap_or_else(|| "N/A".to_string());
192 println!(" - {} ({})", file.name, size_str);
193 }
194 }
195 Err(e) => {
196 println!("Error: {}", e);
197 }
198 }
199
200 println!("\n=== Test Completed ===");
201
202 Ok(())
203}Trait Implementations§
Source§impl Clone for FileClient
impl Clone for FileClient
Source§fn clone(&self) -> FileClient
fn clone(&self) -> FileClient
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more