use std::cell::RefCell;
use std::net::SocketAddr;
use std::fmt;
use term_painter::Color::*;
use term_painter::ToStyle;
use state::Container;
use error::Error;
use super::{FromParam, FromSegments};
use router::Route;
use http::uri::{URI, Segments};
use http::{Method, ContentType, Header, HeaderMap, Cookie, Cookies};
use http::hyper;
pub struct Request<'r> {
method: Method,
uri: URI<'r>,
headers: HeaderMap<'r>,
remote: Option<SocketAddr>,
params: RefCell<Vec<(usize, usize)>>,
cookies: Cookies,
state: Option<&'r Container>,
}
impl<'r> Request<'r> {
pub fn new<U: Into<URI<'r>>>(method: Method, uri: U) -> Request<'r> {
Request {
method: method,
uri: uri.into(),
headers: HeaderMap::new(),
remote: None,
params: RefCell::new(Vec::new()),
cookies: Cookies::new(&[]),
state: None
}
}
#[inline(always)]
pub fn method(&self) -> Method {
self.method
}
#[inline(always)]
pub fn set_method(&mut self, method: Method) {
self.method = method;
}
#[inline(always)]
pub fn uri(&self) -> &URI {
&self.uri
}
#[inline(always)]
pub fn set_uri<'u: 'r, U: Into<URI<'u>>>(&mut self, uri: U) {
self.uri = uri.into();
self.params = RefCell::new(Vec::new());
}
#[inline(always)]
pub fn remote(&self) -> Option<SocketAddr> {
self.remote
}
#[doc(hidden)]
#[inline(always)]
pub fn set_remote(&mut self, address: SocketAddr) {
self.remote = Some(address);
}
#[inline(always)]
pub fn headers(&self) -> &HeaderMap<'r> {
&self.headers
}
#[inline(always)]
pub fn add_header<H: Into<Header<'r>>>(&mut self, header: H) {
self.headers.add(header.into());
}
#[inline(always)]
pub fn replace_header<H: Into<Header<'r>>>(&mut self, header: H) {
self.headers.replace(header.into());
}
#[inline(always)]
pub fn cookies(&self) -> &Cookies {
&self.cookies
}
#[inline]
pub(crate) fn set_cookies(&mut self, cookies: Cookies) {
self.cookies = cookies;
}
#[inline(always)]
pub fn content_type(&self) -> Option<ContentType> {
self.headers().get_one("Content-Type")
.and_then(|value| value.parse().ok())
}
pub fn get_param<'a, T: FromParam<'a>>(&'a self, n: usize) -> Result<T, Error> {
let param = self.get_param_str(n).ok_or(Error::NoKey)?;
T::from_param(param).map_err(|_| Error::BadParse)
}
#[inline]
pub(crate) fn set_params(&self, route: &Route) {
*self.params.borrow_mut() = route.get_param_indexes(self.uri());
}
#[doc(hidden)]
pub fn get_param_str(&self, n: usize) -> Option<&str> {
let params = self.params.borrow();
if n >= params.len() {
debug!("{} is >= param count {}", n, params.len());
return None;
}
let (i, j) = params[n];
let path = self.uri.path();
if j > path.len() {
error!("Couldn't retrieve parameter: internal count incorrect.");
return None;
}
Some(&path[i..j])
}
pub fn get_segments<'a, T: FromSegments<'a>>(&'a self, n: usize)
-> Result<T, Error> {
let segments = self.get_raw_segments(n).ok_or(Error::NoKey)?;
T::from_segments(segments).map_err(|_| Error::BadParse)
}
#[doc(hidden)]
pub fn get_raw_segments(&self, n: usize) -> Option<Segments> {
let params = self.params.borrow();
if n >= params.len() {
debug!("{} is >= param (segments) count {}", n, params.len());
return None;
}
let (i, j) = params[n];
let path = self.uri.path();
if j > path.len() {
error!("Couldn't retrieve segments: internal count incorrect.");
return None;
}
Some(Segments(&path[i..j]))
}
#[inline]
pub(crate) fn get_state(&self) -> Option<&'r Container> {
self.state
}
#[inline]
pub(crate) fn set_state(&mut self, state: &'r Container) {
self.state = Some(state);
}
pub(crate) fn from_hyp(h_method: hyper::Method,
h_headers: hyper::header::Headers,
h_uri: hyper::RequestUri,
h_addr: SocketAddr,
) -> Result<Request<'r>, String> {
let uri = match h_uri {
hyper::RequestUri::AbsolutePath(s) => s,
_ => return Err(format!("Bad URI: {}", h_uri)),
};
let method = match Method::from_hyp(&h_method) {
Some(method) => method,
None => return Err(format!("Invalid method: {}", h_method))
};
let mut request = Request::new(method, uri);
if let Some(cookie_headers) = h_headers.get_raw("Cookie") {
let mut cookies = Cookies::new(&[]);
for header in cookie_headers {
let raw_str = match ::std::str::from_utf8(header) {
Ok(string) => string,
Err(_) => continue
};
for cookie_str in raw_str.split(";") {
let cookie = match Cookie::parse_encoded(cookie_str.to_string()) {
Ok(cookie) => cookie,
Err(_) => continue
};
cookies.add_original(cookie);
}
}
request.set_cookies(cookies);
}
for hyp in h_headers.iter() {
let header = Header::new(hyp.name().to_string(), hyp.value_string());
request.add_header(header);
}
request.set_remote(h_addr);
Ok(request)
}
}
impl<'r> fmt::Display for Request<'r> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", Green.paint(&self.method), Blue.paint(&self.uri))?;
if let Some(content_type) = self.content_type() {
if self.method.supports_payload() {
write!(f, " {}", Yellow.paint(content_type))?;
}
}
Ok(())
}
}