use rocket::{ data::{FromDataSimple, Outcome}, http::Status, response::Responder, Data, Outcome::*, Request, }; use ruma_client_api::error::Error; use std::{ convert::{TryFrom, TryInto}, fmt, io::{Cursor, Read}, ops::Deref, }; const MESSAGE_LIMIT: u64 = 65535; pub struct Ruma { body: T, headers: http::HeaderMap, } impl>>> FromDataSimple for Ruma where T::Error: fmt::Debug, { type Error = (); fn from_data(request: &Request, data: Data) -> Outcome { let mut http_request = http::Request::builder() .uri(request.uri().to_string()) .method(&*request.method().to_string()); for header in request.headers().iter() { http_request = http_request.header(header.name.as_str(), &*header.value); } let mut handle = data.open().take(MESSAGE_LIMIT); let mut body = Vec::new(); handle.read_to_end(&mut body).unwrap(); let http_request = http_request.body(body).unwrap(); let headers = http_request.headers().clone(); log::info!("{:?}", http_request); match T::try_from(http_request) { Ok(t) => Success(Ruma { body: t, headers }), Err(e) => { log::error!("{:?}", e); Failure((Status::InternalServerError, ())) } } } } impl Deref for Ruma { type Target = T; fn deref(&self) -> &Self::Target { &self.body } } impl fmt::Debug for Ruma { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Ruma") .field("body", &self.body) .field("headers", &self.headers) .finish() } } pub struct MatrixResult(pub std::result::Result); impl>>> TryInto>> for MatrixResult { type Error = T::Error; fn try_into(self) -> Result>, T::Error> { match self.0 { Ok(t) => t.try_into(), Err(e) => Ok(e.into()), } } } impl<'r, T: TryInto>>> Responder<'r> for MatrixResult { fn respond_to(self, _: &Request) -> rocket::response::Result<'r> { let http_response: Result, _> = self.try_into(); match http_response { Ok(http_response) => { let mut response = rocket::response::Response::build(); response.sized_body(Cursor::new(http_response.body().clone())); for header in http_response.headers() { response .raw_header(header.0.to_string(), header.1.to_str().unwrap().to_owned()); } response.raw_header("Access-Control-Allow-Origin", "*"); response.raw_header( "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS", ); response.raw_header( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization", ); response.ok() } Err(_) => Err(Status::InternalServerError), } } }