feat: simple endpoint handlers

This commit is contained in:
timokoesters 2020-02-18 22:07:57 +01:00
parent 6264628c11
commit cd777af41c
4 changed files with 181 additions and 30 deletions

View file

@ -2,25 +2,111 @@
mod ruma_wrapper;
use {
rocket::{get, post, routes},
ruma_client_api::r0::account::register,
ruma_wrapper::Ruma,
rocket::{get, post, put, routes},
ruma_client_api::{
error::{Error, ErrorKind},
r0::{
account::register, alias::get_alias, membership::join_room_by_id,
message::create_message_event,
},
unversioned::get_supported_versions,
},
ruma_wrapper::{MatrixResult, Ruma},
std::convert::TryInto,
};
#[get("/_matrix/client/versions")]
fn get_supported_versions_route() -> MatrixResult<get_supported_versions::Response> {
MatrixResult(Ok(get_supported_versions::Response {
versions: vec!["r0.6.0".to_owned()],
}))
}
#[post("/_matrix/client/r0/register", data = "<body>")]
fn register_route(body: Ruma<register::Request>) -> Ruma<register::Response> {
Ruma(register::Response {
access_token: "42".to_owned(),
home_server: "deprecated".to_owned(),
user_id: "@yourrequestedid:homeserver.com".try_into().unwrap(),
device_id: body.device_id.clone().unwrap_or_default(),
})
fn register_route(body: Ruma<register::Request>) -> MatrixResult<register::Response> {
let user_id = match (*format!(
"@{}:localhost",
body.username.clone().unwrap_or("randomname".to_owned())
))
.try_into()
{
Err(_) => {
return MatrixResult(Err(Error {
kind: ErrorKind::InvalidUsername,
message: "Username was invalid. ".to_owned(),
status_code: http::StatusCode::BAD_REQUEST,
}))
}
Ok(user_id) => user_id,
};
MatrixResult(Ok(register::Response {
access_token: "randomtoken".to_owned(),
home_server: "localhost".to_owned(),
user_id,
device_id: body.device_id.clone().unwrap_or("randomid".to_owned()),
}))
}
#[get("/_matrix/client/r0/directory/room/<room_alias>")]
fn get_alias_route(room_alias: String) -> MatrixResult<get_alias::Response> {
let room_id = match &*room_alias {
"#room:localhost" => "!xclkjvdlfj:localhost",
_ => {
return MatrixResult(Err(Error {
kind: ErrorKind::NotFound,
message: "Room not found.".to_owned(),
status_code: http::StatusCode::NOT_FOUND,
}))
}
}
.try_into()
.unwrap();
MatrixResult(Ok(get_alias::Response {
room_id,
servers: vec!["localhost".to_owned()],
}))
}
#[post("/_matrix/client/r0/rooms/<_room_id>/join", data = "<body>")]
fn join_room_by_id_route(
_room_id: String,
body: Ruma<join_room_by_id::Request>,
) -> MatrixResult<join_room_by_id::Response> {
MatrixResult(Ok(join_room_by_id::Response {
room_id: body.room_id.clone(),
}))
}
#[put(
"/_matrix/client/r0/rooms/<_room_id>/send/<_event_type>/<_txn_id>",
data = "<body>"
)]
fn create_message_event_route(
_room_id: String,
_event_type: String,
_txn_id: String,
body: Ruma<create_message_event::IncomingRequest>,
) -> MatrixResult<create_message_event::Response> {
dbg!(body.0);
MatrixResult(Ok(create_message_event::Response {
event_id: "$randomeventid".try_into().unwrap(),
}))
}
fn main() {
pretty_env_logger::init();
rocket::ignite()
.mount("/", routes![register_route])
.mount(
"/",
routes![
get_supported_versions_route,
register_route,
get_alias_route,
join_room_by_id_route,
create_message_event_route,
],
)
.launch();
}

View file

@ -4,6 +4,8 @@ use {
rocket::response::Responder,
rocket::Request,
rocket::{Data, Outcome::*},
ruma_client_api::error::Error,
std::fmt::Debug,
std::ops::Deref,
std::{
convert::{TryFrom, TryInto},
@ -14,24 +16,33 @@ use {
const MESSAGE_LIMIT: u64 = 65535;
pub struct Ruma<T>(pub T);
impl<T: TryFrom<http::Request<Vec<u8>>>> FromDataSimple for Ruma<T> {
impl<T: TryFrom<http::Request<Vec<u8>>>> FromDataSimple for Ruma<T>
where
T::Error: Debug,
{
type Error = ();
fn from_data(request: &Request, data: Data) -> Outcome<Self, Self::Error> {
let mut handle = data.open().take(MESSAGE_LIMIT);
let mut body = Vec::new();
handle.read_to_end(&mut body).unwrap();
dbg!(&body);
let mut http_request = http::Request::builder().uri(request.uri().to_string());
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();
log::info!("{:?}", http_request);
match T::try_from(http_request) {
Ok(r) => Success(Ruma(r)),
Err(_) => Failure((Status::InternalServerError, ())),
Err(e) => {
log::error!("{:?}", e);
Failure((Status::InternalServerError, ()))
}
}
}
}
@ -44,9 +55,22 @@ impl<T> Deref for Ruma<T> {
}
}
impl<'r, T: TryInto<http::Response<Vec<u8>>>> Responder<'r> for Ruma<T> {
pub struct MatrixResult<T>(pub std::result::Result<T, Error>);
impl<T: TryInto<http::Response<Vec<u8>>>> TryInto<http::Response<Vec<u8>>> for MatrixResult<T> {
type Error = T::Error;
fn try_into(self) -> Result<http::Response<Vec<u8>>, T::Error> {
match self.0 {
Ok(t) => t.try_into(),
Err(e) => Ok(e.into()),
}
}
}
impl<'r, T: TryInto<http::Response<Vec<u8>>>> Responder<'r> for MatrixResult<T> {
fn respond_to(self, _: &Request) -> rocket::response::Result<'r> {
match self.0.try_into() {
let http_response: Result<http::Response<_>, _> = 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()));