Initial prototype of a downloader.

This commit is contained in:
Jordan Petridis 2017-10-02 16:02:39 +03:00
parent 42cef658fc
commit f75d282f80
No known key found for this signature in database
GPG Key ID: CEABAD9F5683B9A6
4 changed files with 51 additions and 2 deletions

View File

@ -1,7 +1,7 @@
use structopt::StructOpt;
use loggerv;
use errors::*;
// use models::NewPodcast;
use downloader;
#[derive(StructOpt, Debug)]
#[structopt(name = "example", about = "An example of StructOpt usage.")]
@ -20,6 +20,7 @@ pub fn run() -> Result<()> {
info!("{:?}", foo);
::init()?;
downloader::download_to("./foo", "http://traffic.megaphone.fm/FL8700626063.mp3")?;
// ::index_feed::foo();
Ok(())

46
src/downloader.rs Normal file
View File

@ -0,0 +1,46 @@
use reqwest;
use hyper::header::*;
use std::fs::File;
use std::io::{BufWriter, Read, Write};
use errors::*;
// Adapted from https://github.com/mattgathu/rget .
pub fn download_to(target: &str, url: &str) -> Result<()> {
let mut resp = reqwest::get(url)?;
info!("GET request to: {}", url);
if resp.status().is_success() {
let headers = resp.headers().clone();
let ct_len = headers.get::<ContentLength>().map(|ct_len| **ct_len);
let ct_type = headers.get::<ContentType>().unwrap();
ct_len.map(|x| info!("File Lenght: {}", x));
info!("Content Type: {:?}", ct_type);
// FIXME
let out_file = target.to_owned() + "/bar.mp3";
info!("Save destination: {}", out_file);
let chunk_size = match ct_len {
Some(x) => x as usize / 99,
None => 1024usize, // default chunk size
};
// let foo_file =
let mut writer = BufWriter::new(File::create(out_file)?);
loop {
let mut buffer = vec![0; chunk_size];
let bcount = resp.read(&mut buffer[..]).unwrap();
buffer.truncate(bcount);
if !buffer.is_empty() {
writer.write(buffer.as_slice()).unwrap();
} else {
break;
}
}
}
Ok(())
}

View File

@ -211,7 +211,6 @@ mod tests {
use std::io::{stdout, BufReader};
use std::path::PathBuf;
use std::fs;
use std::collections::HashMap;
use super::*;

View File

@ -35,6 +35,7 @@ pub mod models;
pub mod feedparser;
pub mod index_feed;
pub mod dbqueries;
pub mod downloader;
pub mod errors {
@ -48,6 +49,7 @@ pub mod errors {
use regex;
use std::io;
// use std::option;
// use std::sync;
error_chain! {
@ -62,6 +64,7 @@ pub mod errors {
DurationError(time::OutOfRangeError);
HyperError(hyper::error::Error);
RegexError(regex::Error);
// NoneError(option::NoneError);
// MutexPoison(sync::PoisonError);
}
}