You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
conduit/src/main.rs

265 lines
8.1 KiB
Rust

4 years ago
#![feature(proc_macro_hygiene, decl_macro)]
mod data;
mod database;
4 years ago
mod ruma_wrapper;
mod utils;
4 years ago
pub use data::Data;
pub use database::Database;
use log::debug;
use rocket::{get, post, put, routes, State};
use ruma_client_api::{
error::{Error, ErrorKind},
r0::{
account::register, alias::get_alias, membership::join_room_by_id,
message::create_message_event, session::login,
},
unversioned::get_supported_versions,
4 years ago
};
use ruma_events::{collections::all::Event, room::message::MessageEvent};
use ruma_identifiers::{EventId, UserId};
use ruma_wrapper::{MatrixResult, Ruma};
4 years ago
use serde_json::map::Map;
use std::{
collections::HashMap,
convert::{TryFrom, TryInto},
};
4 years ago
#[get("/_matrix/client/versions")]
fn get_supported_versions_route() -> MatrixResult<get_supported_versions::Response> {
MatrixResult(Ok(get_supported_versions::Response {
versions: vec![
"r0.0.1".to_owned(),
"r0.1.0".to_owned(),
"r0.2.0".to_owned(),
"r0.3.0".to_owned(),
"r0.4.0".to_owned(),
"r0.5.0".to_owned(),
"r0.6.0".to_owned(),
],
unstable_features: HashMap::new(),
}))
}
4 years ago
#[post("/_matrix/client/r0/register", data = "<body>")]
4 years ago
fn register_route(
data: State<Data>,
4 years ago
body: Ruma<register::Request>,
) -> MatrixResult<register::Response> {
4 years ago
// Validate user id
4 years ago
let user_id: UserId = match (*format!(
"@{}:{}",
body.username.clone().unwrap_or("randomname".to_owned()),
data.hostname()
))
.try_into()
{
Err(_) => {
4 years ago
debug!("Username invalid");
return MatrixResult(Err(Error {
kind: ErrorKind::InvalidUsername,
4 years ago
message: "Username was invalid.".to_owned(),
status_code: http::StatusCode::BAD_REQUEST,
4 years ago
}));
}
Ok(user_id) => user_id,
};
4 years ago
// Check if username is creative enough
if data.user_exists(&user_id) {
4 years ago
debug!("ID already taken");
4 years ago
return MatrixResult(Err(Error {
kind: ErrorKind::UserInUse,
message: "Desired user ID is already taken.".to_owned(),
status_code: http::StatusCode::BAD_REQUEST,
}));
}
4 years ago
// Create user
data.user_add(&user_id, body.password.clone());
// Generate new device id if the user didn't specify one
let device_id = body
.device_id
.clone()
.unwrap_or_else(|| "TODO:randomdeviceid".to_owned());
// Add device
data.device_add(&user_id, &device_id);
// Generate new token for the device
let token = "TODO:randomtoken".to_owned();
data.token_replace(&user_id, &device_id, token.clone());
4 years ago
MatrixResult(Ok(register::Response {
4 years ago
access_token: token,
home_server: data.hostname().to_owned(),
user_id,
4 years ago
device_id,
}))
}
4 years ago
#[post("/_matrix/client/r0/login", data = "<body>")]
fn login_route(data: State<Data>, body: Ruma<login::Request>) -> MatrixResult<login::Response> {
4 years ago
// Validate login method
let user_id =
if let (login::UserInfo::MatrixId(mut username), login::LoginInfo::Password { password }) =
(body.user.clone(), body.login_info.clone())
{
if !username.contains(':') {
username = format!("@{}:{}", username, data.hostname());
}
if let Ok(user_id) = (*username).try_into() {
if !data.user_exists(&user_id) {}
// Check password
if let Some(correct_password) = data.password_get(&user_id) {
if password == correct_password {
// Success!
user_id
} else {
debug!("Invalid password.");
return MatrixResult(Err(Error {
kind: ErrorKind::Unknown,
message: "".to_owned(),
status_code: http::StatusCode::FORBIDDEN,
}));
}
} else {
debug!("UserId does not exist (has no assigned password). Can't log in.");
return MatrixResult(Err(Error {
kind: ErrorKind::Forbidden,
message: "".to_owned(),
status_code: http::StatusCode::FORBIDDEN,
}));
}
} else {
debug!("Invalid UserId.");
return MatrixResult(Err(Error {
4 years ago
kind: ErrorKind::Unknown,
message: "Bad login type.".to_owned(),
status_code: http::StatusCode::BAD_REQUEST,
}));
}
} else {
4 years ago
debug!("Bad login type");
4 years ago
return MatrixResult(Err(Error {
kind: ErrorKind::Unknown,
message: "Bad login type.".to_owned(),
4 years ago
status_code: http::StatusCode::BAD_REQUEST,
}));
4 years ago
};
// Generate new device id if the user didn't specify one
let device_id = body
.device_id
.clone()
.unwrap_or("TODO:randomdeviceid".to_owned());
// Add device
4 years ago
data.device_add(&user_id, &device_id);
// Generate a new token for the device
let token = "TODO:randomtoken".to_owned();
data.token_replace(&user_id, &device_id, token.clone());
4 years ago
return MatrixResult(Ok(login::Response {
4 years ago
user_id,
access_token: token,
home_server: Some(data.hostname().to_owned()),
4 years ago
device_id,
4 years ago
well_known: None,
}));
}
#[get("/_matrix/client/r0/directory/room/<room_alias>")]
fn get_alias_route(room_alias: String) -> MatrixResult<get_alias::Response> {
4 years ago
// TODO
let room_id = match &*room_alias {
"#room:localhost" => "!xclkjvdlfj:localhost",
_ => {
4 years ago
debug!("Room not found.");
return MatrixResult(Err(Error {
kind: ErrorKind::NotFound,
message: "Room not found.".to_owned(),
status_code: http::StatusCode::NOT_FOUND,
4 years ago
}));
}
}
.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> {
4 years ago
// TODO
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(
data: State<Data>,
_room_id: String,
_event_type: String,
_txn_id: String,
body: Ruma<create_message_event::Request>,
) -> MatrixResult<create_message_event::Response> {
// Construct event
let event = Event::RoomMessage(MessageEvent {
content: body.data.clone().into_result().unwrap(),
event_id: event_id.clone(),
origin_server_ts: utils::millis_since_unix_epoch(),
room_id: Some(body.room_id.clone()),
sender: body.user_id.clone().expect("user is authenticated"),
unsigned: Map::default(),
});
// Generate event id
dbg!(ruma_signatures::reference_hash(event));
4 years ago
let event_id = EventId::try_from("$TODOrandomeventid:localhost").unwrap();
data.event_add(&body.room_id, &event_id, &event);
4 years ago
MatrixResult(Ok(create_message_event::Response { event_id }))
4 years ago
}
fn main() {
// Log info by default
if let Err(_) = std::env::var("RUST_LOG") {
std::env::set_var("RUST_LOG", "info");
}
4 years ago
pretty_env_logger::init();
let data = Data::load_or_create("localhost");
data.debug();
4 years ago
4 years ago
rocket::ignite()
.mount(
"/",
routes![
get_supported_versions_route,
register_route,
4 years ago
login_route,
get_alias_route,
join_room_by_id_route,
create_message_event_route,
],
)
.manage(data)
4 years ago
.launch();
}