From 5cc0e7e17862005f6310b86f1820fc26fe3a1bef Mon Sep 17 00:00:00 2001 From: Adrian Malacoda Date: Wed, 25 Oct 2017 21:37:20 -0500 Subject: [PATCH] add Downloader --- Cargo.lock | 4 ---- Cargo.toml | 3 +++ src/lib.rs | 36 ++++++++++++++++++++++++++++++++++-- 3 files changed, 37 insertions(+), 6 deletions(-) delete mode 100644 Cargo.lock diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index c28b8b3..0000000 --- a/Cargo.lock +++ /dev/null @@ -1,4 +0,0 @@ -[root] -name = "plushie-narwhal" -version = "0.0.1" - diff --git a/Cargo.toml b/Cargo.toml index f45d8c1..1f22cd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,3 +2,6 @@ name = "plushie-narwhal" version = "0.0.1" authors = ["A. Malacoda "] + +[dependencies] +reqwest = "0.8.0" diff --git a/src/lib.rs b/src/lib.rs index 652d039..b2446b3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,12 @@ +extern crate reqwest; + use std::process::Command; use std::env; use std::path::{Path, PathBuf}; use std::fs::canonicalize; -use std::fs::File; -use std::io::Write; +use std::fs::{File, create_dir_all}; +use std::io::{Write, copy}; pub fn yarn_install () { Command::new("yarn").output().expect("failed to execute yarn process"); @@ -137,3 +139,33 @@ pub struct ResourceMount { endpoint: &'static str, content_type: &'static str } + +pub struct Downloader { + cache: PathBuf +} + +impl Downloader { + pub fn new>(cache: P) -> Downloader { + Downloader { + cache: cache.as_ref().to_path_buf() + } + } + + pub fn get(&self, url: &str) -> PathBuf { + 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")..)).expect("failed to parse filename"); + let mut out_path = self.cache.clone(); + out_path.push(filename); + + if !out_path.exists() { + let mut res = reqwest::get(url).expect("failed to download url"); + let mut file = File::open(out_path.as_path()).expect("failed to open file"); + copy(&mut res, &mut file).expect("failed to write file"); + } + + out_path + } +}