add way to supply downloaded file name, expose whether it's cached in return value

This commit is contained in:
Adrian Malacoda 2017-12-04 01:22:39 -06:00
parent b488413f96
commit 9becb6e3a7

View File

@ -170,21 +170,34 @@ impl Downloader {
}
}
pub fn get(&self, url: &str) -> PathBuf {
pub fn get(&self, url: &str) -> DownloaderResult {
let filename = url.get((url.rfind('/').expect("not a valid url") + 1..)).expect("failed to parse filename");
self.get_to(url, filename)
}
pub fn get_to(&self, url: &str, filename: &str) -> DownloaderResult {
if !self.cache.exists() {
create_dir_all(self.cache.as_path()).expect("failed to create cache directory");
}
let filename = url.get((url.rfind('/').expect("not a valid url") + 1..)).expect("failed to parse filename");
let mut out_path = self.cache.clone();
out_path.push(filename);
if !out_path.exists() {
let was_cached = out_path.exists();
if !was_cached {
let mut result = reqwest::get(url).expect("failed to download url");
let mut file = File::create(out_path.as_path()).expect("failed to open file");
copy(&mut result, &mut file).expect("failed to write file");
}
out_path
DownloaderResult {
out_path: out_path,
was_cached: was_cached
}
}
}
pub struct DownloaderResult {
pub out_path: PathBuf,
pub was_cached: bool
}