use std::collections::HashMap; use std::io::{Error, ErrorKind}; use futures::{future, Future, Stream}; use gotham::handler::{HandlerFuture, IntoHandlerError}; use gotham::helpers::http::response::create_response; use gotham::state::{FromState, State}; use hyper::Response; use hyper::{Body, StatusCode}; use mime; use url::form_urlencoded; use crate::config::Config; use crate::paste::Paste; pub fn put(mut state: State) -> Box { Box::new({ Body::take_from(&mut state).concat2().then(|body| { let config = Config::take_from(&mut state); match body { Ok(b) => { let body_content = b.into_bytes(); let text = String::from_utf8(body_content.as_ref().to_vec()).unwrap(); match Paste::from_text(text, config.salt) { Ok(paste) => { let mut path = config.data_directory.clone(); path.push(paste.id.clone()); if let Err(e) = paste.to_file(path) { let err = Error::new(ErrorKind::Other, e.description()); future::err((state, err.into_handler_error())) } else { let res = create_response( &state, StatusCode::OK, mime::TEXT_PLAIN, format!("{}/{}\n", config.url, paste.id), ); future::ok((state, res)) } } Err(e) => { let err = Error::new(ErrorKind::Other, e.description()); future::err((state, err.into_handler_error())) } } } Err(e) => future::err((state, e.into_handler_error())), } }) }) } pub fn post(mut state: State) -> Box { Box::new({ Body::take_from(&mut state).concat2().then(|body| { let config = Config::take_from(&mut state); match body { Ok(b) => { let body_content = b.into_bytes(); let form_map: HashMap = form_urlencoded::parse(&body_content) .into_owned() .map(|x| x) .collect(); if let Ok(paste) = Paste::from_form(form_map, config.salt) { let mut path = config.data_directory; path.push(paste.id.clone()); if let Err(e) = paste.to_file(path) { let err = Error::new(ErrorKind::Other, e.description()); return future::err((state, err.into_handler_error())); } let res = Response::builder() .status(303) .header("Location", format!("/{}", paste.id)) .body(Body::empty()) .unwrap(); future::ok((state, res)) } else { let res = create_response(&state, StatusCode::OK, mime::TEXT_PLAIN, "ERR"); future::ok((state, res)) } } Err(e) => future::err((state, e.into_handler_error())), } }) }) }