blob: 537dae3cb9b7cb4a4bb05499f021c6294c7bc208 (
plain)
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
|
use std::path::{Path, PathBuf};
use anyhow::Error;
use fehler::throws;
use hyper::{body::HttpBody, Client, header::CONTENT_TYPE, Uri};
use tokio::fs;
use tokio::io::AsyncWriteExt;
use super::Args;
#[throws]
pub(crate) async fn download(url: Uri, args: &Args) {
let output_file_path = if let Some(output) = &args.output_document {
Some(output.clone())
} else {
let url_path = Path::new(url.path());
match (url_path.file_name(), url.path().ends_with('/')) {
(Some(file_name), false) => Some(PathBuf::from(file_name)),
_ => None,
}
};
let client = Client::new();
let mut response = client.get(url.clone()).await?;
if !response.status().is_success() {
panic!("non-success response code {} in URL {}", response.status(), url);
}
let output_file_path = if let Some(path) = output_file_path {
path
} else {
let content_type = response.headers().get(CONTENT_TYPE);
let extension = content_type
.and_then(|mime_type| mime_type.to_str().ok())
.and_then(|mime_type| mime2ext::mime2ext(mime_type))
.map(|x| format!(".{}", x))
.unwrap_or_default();
PathBuf::from(format!("index{}", extension))
};
let mut output_file = fs::File::create(output_file_path).await.expect("couldn't open output file!");
while let Some(data) = response.body_mut().data().await {
output_file.write_all(&data?).await?;
}
}
|