1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use clap::{Parser, Subcommand};
use std::path::PathBuf;
use vielpork::{
base::enums::DownloadResource,
base::structs::DownloadOptions,
config::{Config, ConfigManager},
downloader::Downloader,
reporters::boardcast_mpsc::ReporterBoardcastMpsc,
resolvers::url::UrlResolver,
};
type DownloadConfig = (String, PathBuf, u32, u64, bool, Option<String>, u32);
#[derive(Parser, Debug)]
#[command(
name = "vielpork-cli",
version = "0.1.3",
author = "Hako Chest <zoneherobrine@gmail.com>",
about = "A high-performance multi-threaded HTTP downloader",
long_about = "vielpork is a high-performance multi-threaded HTTP downloader with extensible reporting and resolution strategies."
)]
struct Cli {
#[command(subcommand)]
command: Option<Commands>,
/// URL to download (shorthand for download command)
#[arg(value_name = "URL", global = true)]
url: Option<String>,
/// Directory to save the file
#[arg(
short,
long,
value_name = "PATH",
help = "Directory to save the downloaded file",
global = true
)]
save_dir: Option<PathBuf>,
/// Number of concurrent connections
#[arg(
short,
long,
value_name = "NUM",
help = "Number of concurrent connections for downloads",
global = true
)]
concurrency: Option<u32>,
/// Request timeout in seconds
#[arg(
short,
long,
value_name = "SECONDS",
help = "Request timeout in seconds",
global = true
)]
timeout: Option<u64>,
/// Enable verbose output
#[arg(short, long, help = "Enable verbose output", global = true)]
verbose: bool,
/// Custom User-Agent
#[arg(
short,
long,
value_name = "USER_AGENT",
help = "Custom User-Agent header for requests",
global = true
)]
user_agent: Option<String>,
/// Max retries for failed downloads
#[arg(
short,
long,
value_name = "NUM",
help = "Maximum number of retries for failed downloads",
global = true
)]
retries: Option<u32>,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Download a file from a URL
Download {
/// URL to download
#[arg(value_name = "URL", required = true)]
url: String,
/// Directory to save the file
#[arg(
short,
long,
value_name = "PATH",
help = "Directory to save the downloaded file"
)]
save_dir: Option<PathBuf>,
/// Number of concurrent connections
#[arg(
short,
long,
value_name = "NUM",
help = "Number of concurrent connections for downloads"
)]
concurrency: Option<u32>,
/// Request timeout in seconds
#[arg(
short,
long,
value_name = "SECONDS",
help = "Request timeout in seconds"
)]
timeout: Option<u64>,
/// Enable verbose output
#[arg(short, long, help = "Enable verbose output")]
verbose: bool,
/// Custom User-Agent
#[arg(
short,
long,
value_name = "USER_AGENT",
help = "Custom User-Agent header for requests"
)]
user_agent: Option<String>,
/// Max retries for failed downloads
#[arg(
short,
long,
value_name = "NUM",
help = "Maximum number of retries for failed downloads"
)]
retries: Option<u32>,
},
/// Manage configuration
Config {
#[command(subcommand)]
action: ConfigAction,
},
}
#[derive(Subcommand, Debug)]
enum ConfigAction {
/// Show current configuration
Show,
/// Get a configuration value
Get {
/// Configuration key
#[arg(value_name = "KEY")]
key: String,
},
/// Set a configuration value
Set {
/// Configuration key
#[arg(value_name = "KEY")]
key: String,
/// Configuration value
#[arg(value_name = "VALUE")]
value: String,
},
/// Reset to default configuration
Reset,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
// Handle commands
match cli.command {
Some(Commands::Config { action }) => {
handle_config(action)?;
return Ok(());
}
Some(Commands::Download {
url,
save_dir,
concurrency,
timeout,
verbose,
user_agent,
retries,
}) => {
let (url, save_dir, concurrency, timeout, verbose, user_agent, retries) =
merge_download_args(
url,
save_dir,
concurrency,
timeout,
verbose,
user_agent,
retries,
)?;
perform_download(
url,
save_dir,
concurrency,
timeout,
verbose,
user_agent,
retries,
)
.await?;
return Ok(());
}
None => {
// If no subcommand and URL is provided, treat it as a download
if let Some(url) = cli.url {
let (url, save_dir, concurrency, timeout, verbose, user_agent, retries) =
merge_download_args(
url,
cli.save_dir,
cli.concurrency,
cli.timeout,
cli.verbose,
cli.user_agent,
cli.retries,
)?;
perform_download(
url,
save_dir,
concurrency,
timeout,
verbose,
user_agent,
retries,
)
.await?;
return Ok(());
} else {
// No command and no URL - show brief help
eprintln!("Usage: vielpork-cli <URL> [OPTIONS]");
eprintln!(" vielpork-cli <COMMAND> [OPTIONS]");
eprintln!("\nRun 'vielpork-cli --help' for more information");
return Ok(());
}
}
}
}
fn handle_config(action: ConfigAction) -> Result<(), Box<dyn std::error::Error>> {
match action {
ConfigAction::Show => {
let config = ConfigManager::load()?;
ConfigManager::display(&config);
}
ConfigAction::Get { key } => {
let config = ConfigManager::load()?;
match ConfigManager::get(&config, &key) {
Some(value) => println!("{}: {}", key, value),
None => println!("❌ Unknown config key: {}", key),
}
}
ConfigAction::Set { key, value } => {
let mut config = ConfigManager::load()?;
ConfigManager::set(&mut config, &key, &value)?;
ConfigManager::save(&config)?;
println!("✅ Config updated: {} = {}", key, value);
}
ConfigAction::Reset => {
let default_config = Config::default();
ConfigManager::save(&default_config)?;
println!("✅ Configuration reset to defaults");
ConfigManager::display(&default_config);
}
}
Ok(())
}
/// Normalize URL by adding https:// prefix if protocol is missing
fn normalize_url(url: &str) -> String {
let url = url.trim();
// Check if URL already has a protocol
if url.starts_with("http://") || url.starts_with("https://") || url.starts_with("ftp://") {
url.to_string()
} else {
// Add https:// prefix for protocol-less URLs
format!("https://{}", url)
}
}
fn merge_download_args(
url: String,
save_dir_arg: Option<PathBuf>,
concurrency_arg: Option<u32>,
timeout_arg: Option<u64>,
verbose_arg: bool,
user_agent_arg: Option<String>,
retries_arg: Option<u32>,
) -> Result<DownloadConfig, Box<dyn std::error::Error>> {
let config = ConfigManager::load()?;
// Normalize URL - add https:// if protocol is missing
let normalized_url = normalize_url(&url);
let save_dir = save_dir_arg.unwrap_or_else(|| PathBuf::from(&config.download_dir));
let concurrency = concurrency_arg.unwrap_or(config.concurrency);
let timeout = timeout_arg.unwrap_or(config.timeout);
let retries = retries_arg.unwrap_or(config.max_retries);
let user_agent = user_agent_arg.or(config.user_agent);
Ok((
normalized_url,
save_dir,
concurrency,
timeout,
verbose_arg,
user_agent,
retries,
))
}
async fn perform_download(
url: String,
save_dir: PathBuf,
concurrency: u32,
timeout: u64,
verbose: bool,
user_agent: Option<String>,
retries: u32,
) -> Result<(), Box<dyn std::error::Error>> {
if verbose {
println!("🚀 Starting vielpork downloader");
println!("📥 URL: {}", url);
println!("📁 Save directory: {}", save_dir.display());
println!("🔄 Concurrency: {}", concurrency);
println!("⏱️ Timeout: {}s", timeout);
println!();
}
// Create save directory if it doesn't exist
tokio::fs::create_dir_all(&save_dir).await?;
// Configure download options
let options = DownloadOptions {
save_path: save_dir.to_string_lossy().to_string(),
concurrency,
timeout,
max_retries: retries,
user_agent,
..Default::default()
};
// Initialize resolver and reporter
let resolver = Box::new(UrlResolver::new());
let reporter = Box::new(ReporterBoardcastMpsc::new(128));
// Create downloader
let downloader = Downloader::new(options, resolver, reporter.clone());
if verbose {
println!("✨ Downloader initialized");
}
// Create a channel for the monitor task to signal completion
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
// Create a broadcast channel to signal monitor task to stop waiting
let (stop_tx, mut stop_rx) = tokio::sync::broadcast::channel::<()>(1);
// Set up progress monitoring in a separate task
let reporter_clone = reporter.clone();
let _monitor_handle = tokio::spawn(async move {
let mut rx = reporter_clone.subscribe_mpsc();
let mut download_started = false;
let mut finished_count = 0;
let mut last_event_time = std::time::Instant::now();
let expected_count = 1; // We're downloading 1 URL
// Timeout for no events: 30 seconds without any event = failure
// This allows arbitrarily long downloads as long as there are periodic updates
let event_idle_timeout = tokio::time::Duration::from_secs(30);
loop {
// Calculate time remaining since last event
let elapsed_since_last_event = last_event_time.elapsed();
let timeout_duration = if elapsed_since_last_event >= event_idle_timeout {
// Already exceeded idle timeout - fail immediately
tokio::time::Duration::from_secs(0)
} else {
// Wait for remaining time
event_idle_timeout - elapsed_since_last_event
};
tokio::select! {
// Monitor for progress events
result = tokio::time::timeout(timeout_duration, rx.recv()) => {
match result {
Ok(Some(event)) => {
last_event_time = std::time::Instant::now(); // Reset idle timer on any event
match event {
vielpork::base::enums::ProgressEvent::Start { task_id, total } => {
download_started = true;
println!(
"\n📦 Task {}: Starting download ({} bytes)",
task_id,
format_bytes(total)
);
}
vielpork::base::enums::ProgressEvent::Update { task_id, progress } => {
let downloaded = format_bytes(progress.bytes_downloaded);
let total = format_bytes(progress.total_bytes);
let rate = format_bytes(progress.rate as u64);
print!(
"\r📥 Task {}: {} / {} ({:.1}%) - {}/s",
task_id,
downloaded,
total,
progress.progress_percentage,
rate
);
let _ = std::io::Write::flush(&mut std::io::stdout());
}
vielpork::base::enums::ProgressEvent::Finish { task_id, finish } => {
println!(); // New line after progress
finished_count += 1;
match finish {
vielpork::base::enums::DownloadResult::Success {
path,
size,
duration,
} => {
println!(
"✅ Task {}: Completed! Saved to: {}",
task_id,
path.display()
);
println!(
" Size: {}, Time: {:.2}s",
format_bytes(size),
duration.as_secs_f64()
);
}
vielpork::base::enums::DownloadResult::Failed {
error,
retryable,
} => {
println!("❌ Task {}: Failed! Error: {}{}", task_id, error, if
retryable
{
" (retryable)"
} else {
""
});
}
vielpork::base::enums::DownloadResult::Canceled => {
println!("⏹️ Task {}: Canceled", task_id);
}
}
// Exit after all tasks are finished and signal completion
if finished_count >= expected_count {
let _ = tx.send(()); // Signal main task that download is complete
break;
}
}
vielpork::base::enums::ProgressEvent::OperationResult {
operation,
task_id,
code,
message,
} => {
if code == 0 {
println!("\nℹ️ Task {}: {} - {}", task_id, operation, message);
} else {
println!(
"\n⚠️ Task {}: {} - {} (code: {})",
task_id,
operation,
message,
code
);
}
if !download_started && code != 0 {
let _ = tx.send(()); // Signal error completion
break;
}
}
}
}
Ok(None) => {
// Channel closed (no more events will be sent)
let _ = tx.send(());
break;
}
Err(_) => {
// Timeout occurred - no events received within idle timeout
// This indicates the download is stuck/stalled
let _ = tx.send(());
break;
}
}
}
// Stop signal from main task - exit monitoring
_ = stop_rx.recv() => {
break;
}
}
}
});
// Perform download with timeout to prevent hanging
let download_result = tokio::time::timeout(
tokio::time::Duration::from_secs(timeout),
downloader.download_multi(vec![DownloadResource::Url(url.clone())]),
)
.await;
match download_result {
Ok(Ok(())) => {
// Download completed successfully - let monitor task report it
}
Ok(Err(e)) => {
if verbose {
eprintln!("\n❌ Download error: {}", e);
}
// Still give monitor task time to report Finish event if any
}
Err(_) => {
if verbose {
eprintln!("\n⏱️ Download timeout after {} seconds", timeout);
}
// Immediately stop monitor on timeout
let _ = stop_tx.send(());
}
}
// Wait for the monitor task to finish and report completion
// Give extra time for monitor to process remaining events
let _ = tokio::time::timeout(tokio::time::Duration::from_secs(5), rx).await;
if verbose {
println!("✨ Download operation completed");
}
Ok(())
}
/// Format bytes to human readable string
fn format_bytes(bytes: u64) -> String {
const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
let mut size = bytes as f64;
let mut unit_idx = 0;
while size >= 1024.0 && unit_idx < UNITS.len() - 1 {
size /= 1024.0;
unit_idx += 1;
}
if unit_idx == 0 {
format!("{} {}", size as u64, UNITS[unit_idx])
} else {
format!("{:.2} {}", size, UNITS[unit_idx])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normalize_url_with_https() {
let url = "https://example.com";
assert_eq!(normalize_url(url), "https://example.com");
}
#[test]
fn test_normalize_url_with_http() {
let url = "http://example.com";
assert_eq!(normalize_url(url), "http://example.com");
}
#[test]
fn test_normalize_url_with_ftp() {
let url = "ftp://example.com";
assert_eq!(normalize_url(url), "ftp://example.com");
}
#[test]
fn test_normalize_url_without_protocol() {
let url = "example.com";
assert_eq!(normalize_url(url), "https://example.com");
}
#[test]
fn test_normalize_url_without_protocol_www() {
let url = "www.example.com";
assert_eq!(normalize_url(url), "https://www.example.com");
}
#[test]
fn test_normalize_url_with_whitespace() {
let url = " example.com ";
assert_eq!(normalize_url(url), "https://example.com");
}
#[test]
fn test_format_bytes() {
assert_eq!(format_bytes(512), "512 B");
assert_eq!(format_bytes(1024), "1.00 KB");
assert_eq!(format_bytes(1024 * 1024), "1.00 MB");
}
}