Created
September 7, 2018 08:23
-
-
Save yaymukund/0547cdfed9e4c03523f687adf8b38c2b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use super::downloader::HttpClient; | |
use hyper; | |
use hyper::rt::{Future, Stream}; | |
use std::error::Error; | |
use std::io::{Error as IOError, Read}; | |
use std::sync::{atomic, mpsc, Arc}; | |
pub struct Download { | |
uri: String, | |
body: mpsc::Receiver<hyper::Chunk>, | |
downloaded_bytes: Arc<atomic::AtomicUsize>, | |
buffer: Vec<u8>, | |
} | |
fn log_error(err: impl Error) { | |
println!("Error: {}", err.to_string()); | |
} | |
impl Download { | |
pub fn fetch(uri: &str, client: &HttpClient) -> (Download, impl Future<Item = (), Error = ()>) { | |
let (sender, receiver) = mpsc::channel(); | |
let download = Download { | |
uri: uri.to_owned(), | |
body: receiver, | |
downloaded_bytes: Arc::new(atomic::AtomicUsize::new(0)), | |
buffer: Vec::new(), | |
}; | |
let uri = download.uri.parse().unwrap(); | |
let future = client.get(uri).map_err(log_error).and_then(move |res| { | |
res.into_body() | |
.map_err(log_error) | |
.for_each(move |chunk| sender.send(chunk).map_err(log_error)) | |
}); | |
(download, future) | |
} | |
// pub fn make_future(&mut self, client: &HttpClient) -> impl Future<Item = (), Error = ()> { | |
// let parsed_uri: Uri = self.uri.parse().unwrap(); | |
// let debug_uri = parsed_uri.clone(); | |
// let (sender, receiver) = mpsc::channel(); | |
// self.body = Some(receiver); | |
// client.get(parsed_uri).map_err(|_| ()).and_then(move |res| { | |
// let body = res.into_body().inspect(move |chunk| { | |
// println!("chunk received: {} {} bytes", debug_uri, chunk.len()); | |
// }); | |
// body.for_each(move |chunk| { | |
// sender.send(chunk); | |
// Ok(()) | |
// }).map_err(|_| ()) | |
// }) | |
// } | |
} | |
// impl Read for Download { | |
// fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> { | |
// let receiver = self.body.as_ref().unwrap(); | |
// return Ok(1); | |
// } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment