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
use std::env::current_dir;
use std::fs::create_dir_all;
#[cfg(feature = "archive")]
use std::io::Error as IoError;
use std::path::{self, Path, PathBuf};
use std::sync::{Arc, Mutex};
use clap::ArgMatches;
use failure::Fail;
use ffsend_api::action::download::{Download as ApiDownload, Error as DownloadError};
use ffsend_api::action::exists::{Error as ExistsError, Exists as ApiExists};
use ffsend_api::action::metadata::{Error as MetadataError, Metadata as ApiMetadata};
use ffsend_api::action::version::Error as VersionError;
use ffsend_api::file::remote_file::{FileParseError, RemoteFile};
use ffsend_api::pipe::ProgressReporter;
#[cfg(feature = "archive")]
use tempfile::{Builder as TempBuilder, NamedTempFile};
use super::select_api_version;
#[cfg(feature = "archive")]
use crate::archive::archive::Archive;
use crate::client::create_config;
use crate::cmd::matcher::{download::DownloadMatcher, main::MainMatcher, Matcher};
#[cfg(feature = "history")]
use crate::history_tool;
use crate::progress::ProgressBar;
use crate::util::{
ensure_enough_space, ensure_password, follow_url, print_error, prompt_yes, quit, quit_error,
quit_error_msg, ErrorHints,
};
/// A file download action.
pub struct Download<'a> {
cmd_matches: &'a ArgMatches<'a>,
}
impl<'a> Download<'a> {
/// Construct a new download action.
pub fn new(cmd_matches: &'a ArgMatches<'a>) -> Self {
Self { cmd_matches }
}
/// Invoke the download action.
// TODO: create a trait for this method
pub fn invoke(&self) -> Result<(), Error> {
// Create the command matchers
let matcher_main = MainMatcher::with(self.cmd_matches).unwrap();
let matcher_download = DownloadMatcher::with(self.cmd_matches).unwrap();
// Create a regular client
let client_config = create_config(&matcher_main);
let client = client_config.clone().client(false);
// Get the share URL, attempt to follow it
let url = matcher_download.url();
let url = match follow_url(&client, &url) {
Ok(url) => url,
Err(err) => {
print_error(err.context("failed to follow share URL, ignoring").compat());
url
}
};
// Guess the host
let host = matcher_download.guess_host(Some(url.clone()));
// Determine the API version to use
let mut desired_version = matcher_main.api();
select_api_version(&client, host, &mut desired_version)?;
let api_version = desired_version.version().unwrap();
// Parse the remote file based on the share URL
let file = RemoteFile::parse_url(url, None)?;
// Get the target file or directory, and the password
let target = matcher_download.output();
let mut password = matcher_download.password();
// Check whether the file exists
let exists = ApiExists::new(&file).invoke(&client)?;
if !exists.exists() {
// Remove the file from the history manager if it does not exist
#[cfg(feature = "history")]
history_tool::remove(&matcher_main, &file);
return Err(Error::Expired);
}
// Ensure a password is set when required
ensure_password(
&mut password,
exists.requires_password(),
&matcher_main,
false,
);
// Fetch the file metadata
let metadata = ApiMetadata::new(&file, password.clone(), false).invoke(&client)?;
// A temporary archive file, only used when archiving
// The temporary file is stored here, to ensure it's lifetime exceeds the upload process
#[cfg(feature = "archive")]
let mut tmp_archive: Option<NamedTempFile> = None;
// Check whether to extract
#[cfg(feature = "archive")]
let mut extract = matcher_download.extract();
#[cfg(feature = "archive")]
{
// Ask to extract if downloading an archive
if !extract && metadata.metadata().is_archive() {
if prompt_yes(
"You're downloading an archive, extract it into the selected directory?",
Some(true),
&matcher_main,
) {
extract = true;
}
}
}
// Prepare the download target and output path to use
#[cfg(feature = "archive")]
let output_dir = !extract;
#[cfg(not(feature = "archive"))]
let output_dir = false;
#[allow(unused_mut)]
let mut target = Self::prepare_path(
&target,
metadata.metadata().name(),
&matcher_main,
output_dir,
);
#[cfg(feature = "archive")]
let output_path = target.clone();
#[cfg(feature = "archive")]
{
// Allocate an archive file, and update the download and target paths
if extract {
// TODO: select the extension dynamically
let archive_extention = ".tar";
// Allocate a temporary file to download the archive to
tmp_archive = Some(
TempBuilder::new()
.prefix(&format!(".{}-archive-", crate_name!()))
.suffix(archive_extention)
.tempfile()
.map_err(ExtractError::TempFile)?,
);
if let Some(tmp_archive) = &tmp_archive {
target = tmp_archive.path().to_path_buf();
}
}
}
// Ensure there is enough disk space available when not being forced
if !matcher_main.force() {
ensure_enough_space(target.parent().unwrap(), metadata.size());
}
// Create a progress bar reporter
let progress_bar = Arc::new(Mutex::new(ProgressBar::new_download()));
let progress_reader: Arc<Mutex<dyn ProgressReporter>> = progress_bar;
// Create a transfer client
let transfer_client = client_config.client(true);
// Execute an download action
let progress = if !matcher_main.quiet() {
Some(progress_reader)
} else {
None
};
ApiDownload::new(api_version, &file, target, password, false, Some(metadata))
.invoke(&transfer_client, progress)?;
// Extract the downloaded file if working with an archive
#[cfg(feature = "archive")]
{
if extract {
eprintln!("Extracting...");
// Extract the downloaded file
Archive::new(tmp_archive.unwrap().into_file())
.extract(output_path)
.map_err(ExtractError::Extract)?;
}
}
// Add the file to the history
#[cfg(feature = "history")]
history_tool::add(&matcher_main, file, true);
// TODO: open the file, or it's location
// TODO: copy the file location
Ok(())
}
/// This methods prepares a full file path to use for the file to
/// download, based on the current directory, the original file name,
/// and the user input.
/// If `file` is set to false, no file name is included and the path
/// will point to a directory.
///
/// If no file name was given, the original file name is used.
///
/// The full path including the name is returned.
///
/// This method will check whether a file is overwritten, and whether
/// parent directories must be created.
///
/// The program will quit with an error message if a problem occurs.
fn prepare_path(
target: &PathBuf,
name_hint: &str,
main_matcher: &MainMatcher,
file: bool,
) -> PathBuf {
// Sanitize the server-provided file name to its bare basename. A
// malicious uploader can set the metadata filename to an absolute path
// (e.g. /etc/passwd) or one containing `..` segments, which would
// otherwise escape the user's chosen output directory via PathBuf::join.
let safe_name = Path::new(name_hint)
.file_name()
.and_then(|n| n.to_str())
.filter(|n| !n.is_empty() && *n != "." && *n != "..")
.unwrap_or_else(|| {
quit_error_msg(
"remote file name is invalid or unsafe, refusing to download",
ErrorHints::default(),
)
});
// Select the path to use
let mut target = Self::select_path(&target, safe_name);
// Use the parent directory, if we don't want a file
if !file {
target = target.parent().unwrap().to_path_buf();
}
// Ask to overwrite
if file && target.exists() && !main_matcher.force() {
eprintln!(
"The path '{}' already exists",
target.to_str().unwrap_or("?"),
);
if !prompt_yes("Overwrite?", None, main_matcher) {
println!("Download cancelled");
quit();
}
}
{
// Get the deepest directory, as we have to ensure it exists
let dir = if file {
match target.parent() {
Some(parent) => parent,
None => quit_error_msg("invalid output file path", ErrorHints::default()),
}
} else {
&target
};
// Ensure the directory exists
if !dir.is_dir() {
// Prompt to create them if not forced
if !main_matcher.force() {
eprintln!(
"The directory '{}' doesn't exists",
dir.to_str().unwrap_or("?"),
);
if !prompt_yes("Create it?", Some(true), main_matcher) {
println!("Download cancelled");
quit();
}
}
// Create the parent directories
if let Err(err) = create_dir_all(dir) {
quit_error(
err.context("failed to create parent directories for output file"),
ErrorHints::default(),
);
}
}
}
target
}
/// This methods prepares a full file path to use for the file to
/// download, based on the current directory, the original file name,
/// and the user input.
///
/// If no file name was given, the original file name is used.
///
/// The full path including the file name will be returned.
fn select_path(target: &PathBuf, name_hint: &str) -> PathBuf {
// If we're already working with a file, canonicalize and return
if target.is_file() {
match target.canonicalize() {
Ok(target) => return target,
Err(err) => quit_error(
err.context("failed to canonicalize target path"),
ErrorHints::default(),
),
}
}
// Append the name hint if this is a directory, canonicalize and return
if target.is_dir() {
match target.canonicalize() {
Ok(target) => return target.join(name_hint),
Err(err) => quit_error(
err.context("failed to canonicalize target path"),
ErrorHints::default(),
),
}
}
// TODO: canonicalize parent if it exists
// Get the path string
let path = target.to_str();
// If the path is empty, use the working directory with the name hint
let use_workdir = path.map(|path| path.trim().is_empty()).unwrap_or(true);
if use_workdir {
match current_dir() {
Ok(target) => return target.join(name_hint),
Err(err) => quit_error(
err.context("failed to determine working directory to use for the output file"),
ErrorHints::default(),
),
}
}
let path = path.unwrap();
// Make the target mutable
let mut target = target.clone();
// If the path ends with a separator, append the name hint
if path.trim().ends_with(path::is_separator) {
target = target.join(name_hint);
}
// If relative, use the working directory as base
if target.is_relative() {
match current_dir() {
Ok(workdir) => target = workdir.join(target),
Err(err) => quit_error(
err.context("failed to determine working directory to use for the output file"),
ErrorHints::default(),
),
}
}
target
}
}
#[derive(Debug, Fail)]
pub enum Error {
/// Selecting the API version to use failed.
// TODO: enable `api` hint!
#[fail(display = "failed to select API version to use")]
Version(#[cause] VersionError),
/// Failed to parse a share URL, it was invalid.
/// This error is not related to a specific action.
#[fail(display = "invalid share link")]
InvalidUrl(#[cause] FileParseError),
/// An error occurred while checking if the file exists.
#[fail(display = "failed to check whether the file exists")]
Exists(#[cause] ExistsError),
/// An error occurred while fetching metadata.
#[fail(display = "failed to fetch file metadata")]
Metadata(#[cause] MetadataError),
/// An error occurred while downloading the file.
#[fail(display = "")]
Download(#[cause] DownloadError),
/// An error occurred while extracting the file.
#[cfg(feature = "archive")]
#[fail(display = "failed the extraction procedure")]
Extract(#[cause] ExtractError),
/// The given Send file has expired, or did never exist in the first place.
#[fail(display = "the file has expired or did never exist")]
Expired,
}
impl From<VersionError> for Error {
fn from(err: VersionError) -> Error {
Error::Version(err)
}
}
impl From<FileParseError> for Error {
fn from(err: FileParseError) -> Error {
Error::InvalidUrl(err)
}
}
impl From<ExistsError> for Error {
fn from(err: ExistsError) -> Error {
Error::Exists(err)
}
}
impl From<MetadataError> for Error {
fn from(err: MetadataError) -> Error {
Error::Metadata(err)
}
}
impl From<DownloadError> for Error {
fn from(err: DownloadError) -> Error {
Error::Download(err)
}
}
#[cfg(feature = "archive")]
impl From<ExtractError> for Error {
fn from(err: ExtractError) -> Error {
Error::Extract(err)
}
}
#[cfg(feature = "archive")]
#[derive(Debug, Fail)]
pub enum ExtractError {
/// An error occurred while creating the temporary archive file.
#[fail(display = "failed to create temporary archive file")]
TempFile(#[cause] IoError),
/// Failed to extract the file contents to the target directory.
#[fail(display = "failed to extract archive contents to target directory")]
Extract(#[cause] IoError),
}