Skip to content

Instantly share code, notes, and snippets.

@kardeiz
Created December 8, 2017 18:52
Show Gist options
  • Save kardeiz/31b83e47f6c694d72be205f621c9eabf to your computer and use it in GitHub Desktop.
Save kardeiz/31b83e47f6c694d72be205f621c9eabf to your computer and use it in GitHub Desktop.
#[async]
pub fn extract_multipart(req: Request) -> err::Result<(String, HashMap<String, Vec<PathBuf>>, SaveDir)> {
use multipart::server::{Multipart};
use std::io::Cursor;
pub fn get_boundary(req: &Request) -> Option<String> {
fn get_boundary_mime(mime: &::hyper::mime::Mime) -> Option<String> {
use ::hyper::mime;
if mime.type_() == mime::MULTIPART && mime.subtype() == mime::FORM_DATA {
mime.get_param(mime::BOUNDARY).map(|n|n.as_ref().into())
} else {
None
}
}
req.headers().get::<header::ContentType>()
.and_then(|&header::ContentType(ref mime)| get_boundary_mime(mime))
}
let boundary = get_boundary(&req).ok_or("No boundary")?;
let body = req.into_inner().body();
let bytes = await!(body.concat2())?;
let mut multipart = Multipart::with_body(Cursor::new(bytes), boundary);
let out = match multipart.save().temp().into_result_strict() {
Ok(entries) => {
let recode = ::url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(entries.fields.iter())
.finish();
let files = entries.files.into_iter()
.map(|(k, vs)| {
(k, vs.into_iter().filter(|x| x.size > 0).map(|v| {
let mut path = v.path;
if let Some(ext) = v.filename.as_ref().and_then(|x| Path::new(x).extension() ) {
let mut new_path = path.clone();
new_path.set_extension(ext);
if let Ok(_) = ::std::fs::rename(&path, &new_path) {
path = new_path;
}
}
path
})
.collect())
})
.collect();
Ok((recode, files, entries.save_dir))
},
Err(e) => Err(e).chain_err(|| "Couldn't save files")
};
out
}
pub fn checksum<T: AsRef<Path>>(path: T) -> err::Result<String> {
const CAP: usize = 1024 * 128;
let mut buffer = [0u8; CAP];
let mut file = File::open(path).chain_err(|| "Couldn't open file")?;
let mut md5 = ::md5::Context::new();
loop {
let n = file.read(&mut buffer).chain_err(|| "Couldn't read file")?;
if n == 0 { break; }
md5.consume(&buffer[..n]);
}
let digest = md5.compute();
Ok(format!("{:X}", digest))
}
pub fn seconds_to_hms(secs: f64) -> String {
let secs = secs.round() as u64;
let h = secs / 3600;
let m = (secs % 3600) / 60;
let s = secs % 60;
format!("{:02}:{:02}:{:02}", h, m, s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment