use std::any::Any;
use std::collections::{BTreeMap, HashMap};
use std::fmt::{Debug, Display};
use std::sync::Arc;
use std::time::SystemTime;
use bytes::Bytes;
use chrono::{DateTime, FixedOffset};
use maplit::hashmap;
use crate::headers::HeaderValue;
#[derive(Debug, Clone, PartialEq)]
pub struct WebmachineRequest {
pub request_path: String,
pub base_path: String,
pub sub_path: Option<String>,
pub path_vars: HashMap<String, String>,
pub method: String,
pub headers: HashMap<String, Vec<HeaderValue>>,
pub body: Option<Bytes>,
pub query: HashMap<String, Vec<String>>
}
impl Default for WebmachineRequest {
fn default() -> WebmachineRequest {
WebmachineRequest {
request_path: "/".to_string(),
base_path: "/".to_string(),
sub_path: None,
path_vars: Default::default(),
method: "GET".to_string(),
headers: HashMap::new(),
body: None,
query: HashMap::new()
}
}
}
impl WebmachineRequest {
pub fn content_type(&self) -> HeaderValue {
match self.headers.keys().find(|k| k.to_uppercase() == "CONTENT-TYPE") {
Some(header) => match self.headers.get(header).unwrap().first() {
Some(value) => value.clone(),
None => HeaderValue::json()
},
None => HeaderValue::json()
}
}
pub fn is_put_or_post(&self) -> bool {
["PUT", "POST"].contains(&self.method.to_uppercase().as_str())
}
pub fn is_get_or_head(&self) -> bool {
["GET", "HEAD"].contains(&self.method.to_uppercase().as_str())
}
pub fn is_get(&self) -> bool {
self.method.to_uppercase() == "GET"
}
pub fn is_options(&self) -> bool {
self.method.to_uppercase() == "OPTIONS"
}
pub fn is_put(&self) -> bool {
self.method.to_uppercase() == "PUT"
}
pub fn is_post(&self) -> bool {
self.method.to_uppercase() == "POST"
}
pub fn is_delete(&self) -> bool {
self.method.to_uppercase() == "DELETE"
}
pub fn has_accept_header(&self) -> bool {
self.has_header("ACCEPT")
}
pub fn accept(&self) -> Vec<HeaderValue> {
self.find_header("ACCEPT")
}
pub fn has_accept_language_header(&self) -> bool {
self.has_header("ACCEPT-LANGUAGE")
}
pub fn accept_language(&self) -> Vec<HeaderValue> {
self.find_header("ACCEPT-LANGUAGE")
}
pub fn has_accept_charset_header(&self) -> bool {
self.has_header("ACCEPT-CHARSET")
}
pub fn accept_charset(&self) -> Vec<HeaderValue> {
self.find_header("ACCEPT-CHARSET")
}
pub fn has_accept_encoding_header(&self) -> bool {
self.has_header("ACCEPT-ENCODING")
}
pub fn accept_encoding(&self) -> Vec<HeaderValue> {
self.find_header("ACCEPT-ENCODING")
}
pub fn has_header(&self, header: &str) -> bool {
self.headers.keys().find(|k| k.to_uppercase() == header.to_uppercase()).is_some()
}
pub fn find_header(&self, header: &str) -> Vec<HeaderValue> {
match self.headers.keys().find(|k| k.to_uppercase() == header.to_uppercase()) {
Some(header) => self.headers.get(header).unwrap().clone(),
None => Vec::new()
}
}
pub fn has_header_value(&self, header: &str, value: &str) -> bool {
match self.headers.keys().find(|k| k.to_uppercase() == header.to_uppercase()) {
Some(header) => match self.headers.get(header).unwrap().iter().find(|val| *val == value) {
Some(_) => true,
None => false
},
None => false
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct WebmachineResponse {
pub status: u16,
pub headers: BTreeMap<String, Vec<HeaderValue>>,
pub body: Option<Bytes>
}
impl WebmachineResponse {
pub fn default() -> WebmachineResponse {
WebmachineResponse {
status: 200,
headers: BTreeMap::new(),
body: None
}
}
pub fn has_header(&self, header: &str) -> bool {
self.headers.keys().find(|k| k.to_uppercase() == header.to_uppercase()).is_some()
}
pub fn add_header(&mut self, header: &str, values: Vec<HeaderValue>) {
self.headers.insert(header.to_string(), values);
}
pub fn add_headers(&mut self, headers: HashMap<String, Vec<String>>) {
for (k, v) in headers {
self.headers.insert(k, v.iter().map(HeaderValue::basic).collect());
}
}
pub fn add_cors_headers(&mut self, allowed_methods: &[&str]) {
let cors_headers = WebmachineResponse::cors_headers(allowed_methods);
for (k, v) in cors_headers {
self.add_header(k.as_str(), v.iter().map(HeaderValue::basic).collect());
}
}
pub fn cors_headers(allowed_methods: &[&str]) -> HashMap<String, Vec<String>> {
hashmap!{
"Access-Control-Allow-Origin".to_string() => vec!["*".to_string()],
"Access-Control-Allow-Methods".to_string() => allowed_methods.iter().map(|v| v.to_string()).collect(),
"Access-Control-Allow-Headers".to_string() => vec!["Content-Type".to_string()]
}
}
pub fn has_body(&self) -> bool {
match &self.body {
None => false,
Some(body) => !body.is_empty()
}
}
}
pub trait MetaDataThing: Any + Debug {}
#[derive(Debug, Clone)]
pub enum MetaDataValue {
Empty,
String(String),
UInteger(u64),
Integer(i64),
Anything(Arc<dyn MetaDataThing + Send + Sync>)
}
impl MetaDataValue {
pub fn is_empty(&self) -> bool {
match self {
MetaDataValue::Empty => true,
_ => false
}
}
pub fn as_string(&self) -> Option<String> {
match self {
MetaDataValue::String(s) => Some(s.clone()),
_ => None
}
}
pub fn as_uint(&self) -> Option<u64> {
match self {
MetaDataValue::UInteger(u) => Some(*u),
_ => None
}
}
pub fn as_int(&self) -> Option<i64> {
match self {
MetaDataValue::Integer(i) => Some(*i),
_ => None
}
}
pub fn as_anything(&self) -> Option<&(dyn Any + Send + Sync)> {
match self {
MetaDataValue::Anything(thing) => Some(thing.as_ref()),
_ => None
}
}
}
impl Display for MetaDataValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MetaDataValue::String(s) => write!(f, "{}", s.as_str()),
MetaDataValue::UInteger(u) => write!(f, "{}", *u),
MetaDataValue::Integer(i) => write!(f, "{}", *i),
MetaDataValue::Empty => Ok(()),
MetaDataValue::Anything(thing) => write!(f, "any({:?})", thing)
}
}
}
impl Default for MetaDataValue {
fn default() -> Self {
MetaDataValue::Empty
}
}
impl Default for &MetaDataValue {
fn default() -> Self {
&MetaDataValue::Empty
}
}
impl From<String> for MetaDataValue {
fn from(value: String) -> Self {
MetaDataValue::String(value)
}
}
impl From<&String> for MetaDataValue {
fn from(value: &String) -> Self {
MetaDataValue::String(value.clone())
}
}
impl From<&str> for MetaDataValue {
fn from(value: &str) -> Self {
MetaDataValue::String(value.to_string())
}
}
impl From<u16> for MetaDataValue {
fn from(value: u16) -> Self {
MetaDataValue::UInteger(value as u64)
}
}
impl From<i16> for MetaDataValue {
fn from(value: i16) -> Self {
MetaDataValue::Integer(value as i64)
}
}
impl From<u64> for MetaDataValue {
fn from(value: u64) -> Self {
MetaDataValue::UInteger(value)
}
}
impl From<i64> for MetaDataValue {
fn from(value: i64) -> Self {
MetaDataValue::Integer(value)
}
}
#[derive(Debug, Clone)]
pub struct WebmachineContext {
pub request: WebmachineRequest,
pub response: WebmachineResponse,
pub selected_media_type: Option<String>,
pub selected_language: Option<String>,
pub selected_charset: Option<String>,
pub selected_encoding: Option<String>,
pub if_unmodified_since: Option<DateTime<FixedOffset>>,
pub if_modified_since: Option<DateTime<FixedOffset>>,
pub redirect: bool,
pub new_resource: bool,
pub metadata: HashMap<String, MetaDataValue>,
pub start_time: SystemTime
}
impl WebmachineContext {
pub fn downcast_metadata_value<'a, T: 'static>(&'a self, key: &'a str) -> Option<&'a T> {
self.metadata.get(key)
.and_then(|value| value.as_anything())
.and_then(|value| value.downcast_ref())
}
}
impl Default for WebmachineContext {
fn default() -> WebmachineContext {
WebmachineContext {
request: WebmachineRequest::default(),
response: WebmachineResponse::default(),
selected_media_type: None,
selected_language: None,
selected_charset: None,
selected_encoding: None,
if_unmodified_since: None,
if_modified_since: None,
redirect: false,
new_resource: false,
metadata: HashMap::new(),
start_time: SystemTime::now()
}
}
}
#[cfg(test)]
mod tests {
use expectest::prelude::*;
use crate::headers::*;
use super::*;
#[test]
fn request_does_not_have_header_test() {
let request = WebmachineRequest {
.. WebmachineRequest::default()
};
expect!(request.has_header("Vary")).to(be_false());
expect!(request.has_header_value("Vary", "*")).to(be_false());
}
#[test]
fn request_with_empty_header_test() {
let request = WebmachineRequest {
headers: hashmap!{ "HeaderA".to_string() => Vec::new() },
.. WebmachineRequest::default()
};
expect!(request.has_header("HeaderA")).to(be_true());
expect!(request.has_header_value("HeaderA", "*")).to(be_false());
}
#[test]
fn request_with_header_single_value_test() {
let request = WebmachineRequest {
headers: hashmap!{ "HeaderA".to_string() => vec![h!("*")] },
.. WebmachineRequest::default()
};
expect!(request.has_header("HeaderA")).to(be_true());
expect!(request.has_header_value("HeaderA", "*")).to(be_true());
expect!(request.has_header_value("HeaderA", "other")).to(be_false());
}
#[test]
fn request_with_header_multiple_value_test() {
let request = WebmachineRequest {
headers: hashmap!{ "HeaderA".to_string() => vec![h!("*"), h!("other")]},
.. WebmachineRequest::default()
};
expect!(request.has_header("HeaderA")).to(be_true());
expect!(request.has_header_value("HeaderA", "*")).to(be_true());
expect!(request.has_header_value("HeaderA", "other")).to(be_true());
expect!(request.has_header_value("HeaderA", "other2")).to(be_false());
}
}