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
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;
use clap::{Parser, Subcommand};
#[derive(clap::ValueEnum, Clone, Debug)]
pub enum FileChangedAction {
Abort,
Restart,
}
#[derive(clap::ValueEnum, Clone, Debug)]
pub enum NotResumableAction {
Abort,
Restart,
}
#[derive(clap::ValueEnum, Clone, Debug)]
pub enum SameDownloadAction {
Abort,
Resume,
AddNumberToNameAndContinue,
}
#[derive(clap::ValueEnum, Clone, Debug)]
pub enum FinalFileAction {
Abort,
ReplaceAndContinue,
AddNumberToNameAndContinue,
}
fn parse_speed(s: &str) -> Result<u64, String> {
let s = s.trim();
if s.is_empty() {
return Err("empty speed string".to_string());
}
// Remove common trailing rate markers like `/s` or `bps` (case-insensitive)
let mut working = s.to_string();
let lower = working.to_lowercase();
if lower.ends_with("/s") {
working.truncate(working.len() - 2);
} else if lower.ends_with("bps") {
working.truncate(working.len() - 3);
}
let working = working.trim();
// split into numeric prefix and suffix
let mut idx = 0usize;
for (i, ch) in working.char_indices() {
if !(ch.is_ascii_digit() || ch == '.') {
idx = i;
break;
}
idx = i + ch.len_utf8();
}
let (num_part, suf_part) = if idx == 0 {
// no numeric prefix
return Err(format!("invalid speed '{}': missing numeric value", s));
} else if idx >= working.len() {
(working, "")
} else {
(working[..idx].trim(), working[idx..].trim())
};
let value =
f64::from_str(num_part).map_err(|e| format!("invalid number '{}': {}", num_part, e))?;
if value < 0.0 {
return Err("speed must be non-negative".to_string());
}
let suffix_owned = suf_part
.trim()
.trim_start_matches([' ', '\t', '\''])
.to_lowercase();
// Determine multiplier (all based on 1024)
let multiplier: f64 = match suffix_owned.as_str() {
"" | "b" | "byte" | "bytes" => 1.0,
"k" | "kb" | "kib" | "kibibyte" | "kb/s" => 1024f64,
"m" | "mb" | "mib" | "mibibyte" => 1024f64.powi(2),
"g" | "gb" | "gib" | "gibibyte" => 1024f64.powi(3),
// Allow common variants like "kib/s" trimmed earlier, also accept single-letter with optional trailing 'b'
other => {
// try to match prefixes (e.g., "kib", "kb", "k")
let o = other.trim();
if o.starts_with('k') {
1024f64
} else if o.starts_with('m') {
1024f64.powi(2)
} else if o.starts_with('g') {
1024f64.powi(3)
} else {
return Err(format!("unknown size suffix '{}'", other));
}
}
};
let bytes_f = value * multiplier;
if !bytes_f.is_finite() || bytes_f < 0.0 {
return Err("resulting speed is out of range".to_string());
}
let bytes = bytes_f as u128; // use wider intermediate to reduce overflow risk
if bytes > (u64::MAX as u128) {
return Err("speed too large".to_string());
}
Ok(bytes as u64)
}
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct Args {
/// The URL of the file to download, or a path to a file containing one URL per line.
/// Blank lines and lines starting with `#` or `//` are ignored.
/// Optional so subcommands (like `config`) can be used without providing an input.
pub input: Option<String>,
/// If true, tries to download the file at url and read it as a text file and then use it as input
#[arg(long, default_value_t = false)]
pub remote_list: bool,
/// Max connections that download manager can make in parallel for a single file
#[arg(long, value_name = "COUNT")]
pub max_connections: Option<u64>,
/// The maximum number of files that the download manager can download in parallel.
///
/// This controls the overall concurrency of downloads. For example, if set to 4, up to 4 files
/// will be downloaded at the same time, regardless of how many connections are used for each file.
///
/// Note: For controlling how many parts of a single file can be downloaded concurrently,
/// see the `max_connections` option.
#[arg(long, value_name = "COUNT")]
pub max_concurrent_downloads: Option<usize>,
/// When `input` is a URL, this specifies the output file path.
/// When `input` is a file containing URLs, this specifies the output directory for downloaded files.
/// Will use server provided name if not specified or if `input` is a file.
#[arg(short, long, value_name = "FILE|DIR")]
pub output: Option<PathBuf>,
/// This is the path where odl tracks download progress.
/// All data will be downloaded here first before being appended at the output location.
#[arg(short, long, value_name = "DIR")]
pub download_dir: Option<PathBuf>,
/// The config file to use. defaults to `odl/config.toml` inside user's appdata directory (varies based on OS)
#[arg(short, long, value_name = "FILE")]
pub config_file: Option<PathBuf>,
/// User agent to use for making requests. This option overrides random-user-agent.
#[arg(short = 'U', long)]
pub user_agent: Option<String>,
/// Should the user_agent be randomized for each request?
#[arg(long)]
pub randomize_user_agent: Option<bool>,
#[arg(long, value_name = "(http(s)|socks)://")]
pub proxy: Option<String>,
/// Connect timeout for requests. Accepts suffixes like `30s`, `5m`, `2h`, `1d` or long forms (`seconds`, `minutes`, `hours`, `days`). Default `5s`.
#[arg(short, long = "timeout", value_name = "DURATION", value_parser = humantime::parse_duration)]
pub timeout: Option<Duration>,
/// Max number of retries in case of a network error
#[arg(long, value_name = "COUNT")]
pub max_retries: Option<u32>,
/// Number of fixed (non-exponential) retries before exponential backoff starts
#[arg(long, value_name = "COUNT")]
pub n_fixed_retries: Option<u32>,
/// Wait number of seconds after a network error before retry. Fractions are supported.
#[arg(long, value_name = "DURATION", value_parser = humantime::parse_duration)]
pub wait_between_retries: Option<Duration>,
/// If true, sets the downloaded file's last-modified timestamp to match the server's value (if available).
#[arg(short, long)]
pub use_server_time: Option<bool>,
/// How to handle a server file-changed conflict. Possible values: `abort`, `restart`.
/// Default: `restart` (restart the download and warn).
#[arg(long, value_enum, default_value_t = FileChangedAction::Restart)]
pub on_file_changed: FileChangedAction,
/// How to handle a server not-resumable conflict. Possible values: `abort`, `restart`.
/// Default: `restart` (restart the download and warn).
#[arg(long, value_enum, default_value_t = NotResumableAction::Restart)]
pub on_not_resumable: NotResumableAction,
/// Should we accept invalid SSL certificates? Do not use unless you are absolutely sure of what you are doing.
#[arg(long)]
pub accept_invalid_certs: Option<bool>,
/// Custom HTTP headers to include in each request. Specify as `KEY:VALUE`.
#[arg(long = "header", value_name = "KEY:VALUE", num_args = 0.., action = clap::ArgAction::Append)]
pub headers: Vec<String>,
/// How to handle a save conflict when the same download structure exists. Possible values: `abort`, `resume`, `add-number-to-name-and-continue`.
/// Default: `resume`.
#[arg(long, value_enum, default_value_t = SameDownloadAction::Resume)]
pub on_same_download_exists: SameDownloadAction,
/// How to handle a save conflict when a final file already exists. Possible values: `abort`, `replace-and-continue`, `add-number-to-name-and-continue`.
/// Default: `replace-and-continue`.
#[arg(long, value_enum, default_value_t = FinalFileAction::ReplaceAndContinue)]
pub on_final_file_exists: FinalFileAction,
/// HTTP basic authentication username.
#[arg(long, value_name = "USER")]
pub http_user: Option<String>,
/// HTTP basic authentication password.
#[arg(long, value_name = "PASSWORD")]
pub http_password: Option<String>,
/// Maximum aggregate download speed per file in bytes per second.
/// Accepts human-readable values like `100KB`, `1.5MiB`, `2G` (all units parsed as base 1024).
/// When unset, downloads run at full speed.
#[arg(short, long, value_name = "BYTES_PER_SEC", value_parser = parse_speed)]
pub speed_limit: Option<u64>,
#[command(subcommand)]
pub command: Option<Commands>,
}
#[derive(Subcommand, Debug)]
pub enum Commands {
/// Configure persistent download-manager settings saved in odl/config.toml
Config {
/// Print current configuration path and content
#[arg(long)]
show: bool,
/// Config file to change (defaults to standard odl config path).
/// You can use this to configure different download managers.
#[arg(long, value_name = "FILE")]
config_file: Option<PathBuf>,
/// Where download manager keeps each download's parts and progress metadata
#[arg(long, value_name = "DIR")]
download_dir: Option<PathBuf>,
/// Set max connections per-file
#[arg(long, value_name = "COUNT")]
max_connections: Option<u64>,
/// Set maximum concurrent downloads
#[arg(long, value_name = "COUNT")]
max_concurrent_downloads: Option<usize>,
/// Set max retries
#[arg(long, value_name = "COUNT")]
max_retries: Option<u32>,
/// Number of fixed (non-exponential) retries before exponential backoff starts
#[arg(long, value_name = "COUNT")]
n_fixed_retries: Option<u32>,
/// Wait between retries. Accepts suffixes like `30s`, `5m`, `2h`, `1d` or long forms (`seconds`, `minutes`, `hours`, `days`). Default `5s`.
#[arg(long, value_name = "DURATION", value_parser = humantime::parse_duration)]
wait_between_retries: Option<Duration>,
/// Download speed limit (bytes/sec) e.g. 1MiB
#[arg(short, long, value_name = "BYTES_PER_SEC", value_parser = parse_speed)]
speed_limit: Option<u64>,
/// Custom user agent
#[arg(long)]
user_agent: Option<String>,
/// Randomize user agent
#[arg(long)]
randomize_user_agent: Option<bool>,
/// Proxy as string
#[arg(long)]
proxy: Option<String>,
/// Connect timeout for requests. Accepts suffixes like `30s`, `5m`, `2h`, `1d` or long forms (`seconds`, `minutes`, `hours`, `days`). Default `5s`.
#[arg(short, long = "timeout", value_name = "DURATION", value_parser = humantime::parse_duration)]
timeout: Option<Duration>,
/// Use server time when saving
#[arg(long)]
use_server_time: Option<bool>,
/// Accept invalid certs
#[arg(long)]
accept_invalid_certs: Option<bool>,
},
}
#[cfg(test)]
mod tests {
use super::parse_speed;
use std::time::Duration;
#[test]
fn test_simple_bytes() {
assert_eq!(parse_speed("100").unwrap(), 100);
assert_eq!(parse_speed("100B").unwrap(), 100);
}
#[test]
fn test_kilobytes() {
assert_eq!(parse_speed("1K").unwrap(), 1024);
assert_eq!(parse_speed("1KB").unwrap(), 1024);
assert_eq!(parse_speed("100kib").unwrap(), 100 * 1024);
}
#[test]
fn test_megabytes() {
assert_eq!(parse_speed("1M").unwrap(), 1024u64.pow(2));
assert_eq!(
parse_speed("1.5MB").unwrap(),
((1.5f64 * (1024f64.powi(2))) as u64)
);
}
#[test]
fn test_gigabytes() {
assert_eq!(parse_speed("2G").unwrap(), 2 * 1024u64.pow(3));
assert_eq!(parse_speed("2GiB").unwrap(), 2 * 1024u64.pow(3));
}
#[test]
fn test_suffix_with_per_second() {
assert_eq!(parse_speed("100KB/s").unwrap(), 100 * 1024);
assert_eq!(
parse_speed("1.5MiB/s").unwrap(),
((1.5f64 * (1024f64.powi(2))) as u64)
);
}
#[test]
fn test_parse_duration_seconds_and_variants() {
assert_eq!(
humantime::parse_duration("30s").unwrap(),
Duration::from_secs(30)
);
assert_eq!(
humantime::parse_duration("30sec").unwrap(),
Duration::from_secs(30)
);
assert_eq!(
humantime::parse_duration("30seconds").unwrap(),
Duration::from_secs(30)
);
}
#[test]
fn test_parse_duration_minutes_hours_days() {
assert_eq!(
humantime::parse_duration("2m").unwrap(),
Duration::from_secs(120)
);
assert_eq!(
humantime::parse_duration("2min").unwrap(),
Duration::from_secs(120)
);
assert_eq!(
humantime::parse_duration("1h").unwrap(),
Duration::from_secs(3600)
);
assert_eq!(
humantime::parse_duration("1d").unwrap(),
Duration::from_secs(86400)
);
// fractional hours
let d = humantime::parse_duration("1.5h").unwrap();
assert!((d.as_secs_f64() - 1.5 * 3600.0).abs() < 1e-6);
}
}