Run rust fmt.

This commit is contained in:
Paul Makles
2020-04-06 13:07:05 +01:00
parent 8e908ce105
commit ec1e91aee1
16 changed files with 1094 additions and 1025 deletions

View File

@@ -1,4 +1,4 @@
use serde::{ Deserialize, Serialize }; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct Channel { pub struct Channel {

View File

@@ -1,4 +1,4 @@
use serde::{ Deserialize, Serialize }; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct Member { pub struct Member {

View File

@@ -1,5 +1,5 @@
use serde::{ Deserialize, Serialize }; use bson::UtcDateTime;
use bson::{ UtcDateTime }; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct PreviousEntry { pub struct PreviousEntry {
@@ -18,5 +18,5 @@ pub struct Message {
pub content: String, pub content: String,
pub edited: Option<UtcDateTime>, pub edited: Option<UtcDateTime>,
pub previous_content: Option<Vec<PreviousEntry>> pub previous_content: Option<Vec<PreviousEntry>>,
} }

View File

@@ -1,12 +1,12 @@
use mongodb::{ Client, Collection, Database }; use mongodb::{Client, Collection, Database};
use std::env; use std::env;
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
static DBCONN: OnceCell<Client> = OnceCell::new(); static DBCONN: OnceCell<Client> = OnceCell::new();
pub fn connect() { pub fn connect() {
let client = Client::with_uri_str( let client =
&env::var("DB_URI").expect("DB_URI not in environment variables!")) Client::with_uri_str(&env::var("DB_URI").expect("DB_URI not in environment variables!"))
.expect("Failed to init db connection."); .expect("Failed to init db connection.");
DBCONN.set(client).unwrap(); DBCONN.set(client).unwrap();
@@ -24,7 +24,7 @@ pub fn get_collection(collection: &str) -> Collection {
get_db().collection(collection) get_db().collection(collection)
} }
pub mod user;
pub mod channel; pub mod channel;
pub mod message;
pub mod guild; pub mod guild;
pub mod message;
pub mod user;

View File

@@ -1,5 +1,5 @@
use serde::{ Deserialize, Serialize };
use bson::UtcDateTime; use bson::UtcDateTime;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct UserEmailVerification { pub struct UserEmailVerification {

View File

@@ -10,11 +10,13 @@ pub fn send_email(target: String, subject: String, body: String, html: String) -
map.insert("html", html); map.insert("html", html);
let client = Client::new(); let client = Client::new();
match client.post("http://192.168.0.26:3838/send") match client
.post("http://192.168.0.26:3838/send")
.json(&map) .json(&map)
.send() { .send()
{
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(_) => Err(()) Err(_) => Err(()),
} }
} }
@@ -28,8 +30,9 @@ pub fn send_verification_email(email: String, code: String) -> bool {
email, email,
"Verify your email!".to_string(), "Verify your email!".to_string(),
format!("Verify your email here: {}", url), format!("Verify your email here: {}", url),
format!("<a href=\"{}\">Click to verify your email!</a>", url) format!("<a href=\"{}\">Click to verify your email!</a>", url),
).is_ok() )
.is_ok()
} }
pub fn send_welcome_email(email: String, username: String) -> bool { pub fn send_welcome_email(email: String, username: String) -> bool {
@@ -37,6 +40,11 @@ pub fn send_welcome_email(email: String, username: String) -> bool {
email, email,
"Welcome to REVOLT!".to_string(), "Welcome to REVOLT!".to_string(),
format!("Welcome, {}! You can now use REVOLT.", username.clone()), format!("Welcome, {}! You can now use REVOLT.", username.clone()),
format!("<b>Welcome, {}!</b><br/>You can now use REVOLT.<br/><a href=\"{}\">Go to REVOLT</a>", username.clone(), public_uri()) format!(
).is_ok() "<b>Welcome, {}!</b><br/>You can now use REVOLT.<br/><a href=\"{}\">Go to REVOLT</a>",
username.clone(),
public_uri()
),
)
.is_ok()
} }

View File

@@ -1,8 +1,8 @@
use rocket::http::{RawStr, Status};
use rocket::request::{self, FromParam, FromRequest, Request};
use rocket::Outcome; use rocket::Outcome;
use rocket::http::{ Status, RawStr };
use rocket::request::{ self, Request, FromRequest, FromParam };
use bson::{ bson, doc, from_bson }; use bson::{bson, doc, from_bson};
use crate::database; use crate::database;
use database::user::User; use database::user::User;
@@ -27,11 +27,13 @@ impl<'a, 'r> FromRequest<'a, 'r> for User {
let result = col.find_one(doc! { "access_token": key }, None).unwrap(); let result = col.find_one(doc! { "access_token": key }, None).unwrap();
if let Some(user) = result { if let Some(user) = result {
Outcome::Success(from_bson(bson::Bson::Document(user)).expect("Failed to unwrap user.")) Outcome::Success(
from_bson(bson::Bson::Document(user)).expect("Failed to unwrap user."),
)
} else { } else {
Outcome::Failure((Status::Forbidden, AuthError::Invalid)) Outcome::Failure((Status::Forbidden, AuthError::Invalid))
} }
}, }
_ => Outcome::Failure((Status::BadRequest, AuthError::BadCount)), _ => Outcome::Failure((Status::BadRequest, AuthError::BadCount)),
} }
} }
@@ -42,7 +44,9 @@ impl<'r> FromParam<'r> for User {
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> { fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
let col = database::get_db().collection("users"); let col = database::get_db().collection("users");
let result = col.find_one(doc! { "_id": param.to_string() }, None).unwrap(); let result = col
.find_one(doc! { "_id": param.to_string() }, None)
.unwrap();
if let Some(user) = result { if let Some(user) = result {
Ok(from_bson(bson::Bson::Document(user)).expect("Failed to unwrap user.")) Ok(from_bson(bson::Bson::Document(user)).expect("Failed to unwrap user."))

View File

@@ -1,6 +1,6 @@
use rocket::http::{ RawStr }; use bson::{bson, doc, from_bson};
use rocket::request::{ FromParam }; use rocket::http::RawStr;
use bson::{ bson, doc, from_bson }; use rocket::request::FromParam;
use crate::database; use crate::database;
@@ -12,7 +12,9 @@ impl<'r> FromParam<'r> for Channel {
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> { fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
let col = database::get_db().collection("channels"); let col = database::get_db().collection("channels");
let result = col.find_one(doc! { "_id": param.to_string() }, None).unwrap(); let result = col
.find_one(doc! { "_id": param.to_string() }, None)
.unwrap();
if let Some(channel) = result { if let Some(channel) = result {
Ok(from_bson(bson::Bson::Document(channel)).expect("Failed to unwrap channel.")) Ok(from_bson(bson::Bson::Document(channel)).expect("Failed to unwrap channel."))
@@ -27,7 +29,9 @@ impl<'r> FromParam<'r> for Message {
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> { fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
let col = database::get_db().collection("messages"); let col = database::get_db().collection("messages");
let result = col.find_one(doc! { "_id": param.to_string() }, None).unwrap(); let result = col
.find_one(doc! { "_id": param.to_string() }, None)
.unwrap();
if let Some(message) = result { if let Some(message) = result {
Ok(from_bson(bson::Bson::Document(message)).expect("Failed to unwrap message.")) Ok(from_bson(bson::Bson::Document(message)).expect("Failed to unwrap message."))

View File

@@ -1,16 +1,18 @@
#![feature(proc_macro_hygiene, decl_macro)] #![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket; #[macro_use]
#[macro_use] extern crate rocket_contrib; extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
pub mod websocket;
pub mod database; pub mod database;
pub mod email;
pub mod guards; pub mod guards;
pub mod routes; pub mod routes;
pub mod email; pub mod websocket;
use dotenv; use dotenv;
use std::thread;
use rocket_cors::AllowedOrigins; use rocket_cors::AllowedOrigins;
use std::thread;
fn main() { fn main() {
dotenv::dotenv().ok(); dotenv::dotenv().ok();
@@ -23,9 +25,9 @@ fn main() {
let cors = rocket_cors::CorsOptions { let cors = rocket_cors::CorsOptions {
allowed_origins: AllowedOrigins::All, allowed_origins: AllowedOrigins::All,
..Default::default() ..Default::default()
}.to_cors().unwrap(); }
.to_cors()
.unwrap();
routes::mount(rocket::ignite()) routes::mount(rocket::ignite()).attach(cors).launch();
.attach(cors)
.launch();
} }

View File

@@ -1,15 +1,15 @@
use crate::database; use crate::database;
use crate::email; use crate::email;
use bson::{ bson, doc, Bson::UtcDatetime, from_bson }; use bcrypt::{hash, verify};
use rand::{ Rng, distributions::Alphanumeric }; use bson::{bson, doc, from_bson, Bson::UtcDatetime};
use rocket_contrib::json::{ Json, JsonValue };
use serde::{ Serialize, Deserialize };
use validator::validate_email;
use bcrypt::{ hash, verify };
use database::user::User;
use chrono::prelude::*; use chrono::prelude::*;
use database::user::User;
use rand::{distributions::Alphanumeric, Rng};
use rocket_contrib::json::{Json, JsonValue};
use serde::{Deserialize, Serialize};
use ulid::Ulid; use ulid::Ulid;
use validator::validate_email;
fn gen_token(l: usize) -> String { fn gen_token(l: usize) -> String {
rand::thread_rng() rand::thread_rng()
@@ -40,35 +40,39 @@ pub fn create(info: Json<Create>) -> JsonValue {
return json!({ return json!({
"success": false, "success": false,
"error": "Username requirements not met! Must be between 2 and 32 characters.", "error": "Username requirements not met! Must be between 2 and 32 characters.",
}) });
} }
if info.password.len() < 8 || info.password.len() > 72 { if info.password.len() < 8 || info.password.len() > 72 {
return json!({ return json!({
"success": false, "success": false,
"error": "Password requirements not met! Must be between 8 and 72 characters.", "error": "Password requirements not met! Must be between 8 and 72 characters.",
}) });
} }
if !validate_email(info.email.clone()) { if !validate_email(info.email.clone()) {
return json!({ return json!({
"success": false, "success": false,
"error": "Invalid email provided!", "error": "Invalid email provided!",
}) });
} }
if let Some(_) = col.find_one(doc! { "email": info.email.clone() }, None).expect("Failed user lookup") { if let Some(_) = col
.find_one(doc! { "email": info.email.clone() }, None)
.expect("Failed user lookup")
{
return json!({ return json!({
"success": false, "success": false,
"error": "Email already in use!", "error": "Email already in use!",
}) });
} }
if let Ok(hashed) = hash(info.password.clone(), 10) { if let Ok(hashed) = hash(info.password.clone(), 10) {
let access_token = gen_token(92); let access_token = gen_token(92);
let code = gen_token(48); let code = gen_token(48);
match col.insert_one(doc! { match col.insert_one(
doc! {
"_id": Ulid::new().to_string(), "_id": Ulid::new().to_string(),
"email": info.email.clone(), "email": info.email.clone(),
"username": info.username.clone(), "username": info.username.clone(),
@@ -81,7 +85,9 @@ pub fn create(info: Json<Create>) -> JsonValue {
"rate_limit": UtcDatetime(Utc::now() + chrono::Duration::minutes(1)), "rate_limit": UtcDatetime(Utc::now() + chrono::Duration::minutes(1)),
"code": code.clone(), "code": code.clone(),
} }
}, None) { },
None,
) {
Ok(_) => { Ok(_) => {
let sent = email::send_verification_email(info.email.clone(), code); let sent = email::send_verification_email(info.email.clone(), code);
@@ -89,11 +95,11 @@ pub fn create(info: Json<Create>) -> JsonValue {
"success": true, "success": true,
"email_sent": sent, "email_sent": sent,
}) })
}, }
Err(_) => json!({ Err(_) => json!({
"success": false, "success": false,
"error": "Failed to create account!", "error": "Failed to create account!",
}) }),
} }
} else { } else {
json!({ json!({
@@ -111,8 +117,10 @@ pub fn create(info: Json<Create>) -> JsonValue {
pub fn verify_email(code: String) -> JsonValue { pub fn verify_email(code: String) -> JsonValue {
let col = database::get_collection("users"); let col = database::get_collection("users");
if let Some(u) = if let Some(u) = col
col.find_one(doc! { "email_verification.code": code.clone() }, None).expect("Failed user lookup") { .find_one(doc! { "email_verification.code": code.clone() }, None)
.expect("Failed user lookup")
{
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user."); let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
let ev = user.email_verification; let ev = user.email_verification;
@@ -138,12 +146,10 @@ pub fn verify_email(code: String) -> JsonValue {
}, },
}, },
None, None,
).expect("Failed to update user!"); )
.expect("Failed to update user!");
email::send_welcome_email( email::send_welcome_email(target.to_string(), user.username);
target.to_string(),
user.username
);
json!({ json!({
"success": true "success": true
@@ -170,8 +176,13 @@ pub struct Resend {
pub fn resend_email(info: Json<Resend>) -> JsonValue { pub fn resend_email(info: Json<Resend>) -> JsonValue {
let col = database::get_collection("users"); let col = database::get_collection("users");
if let Some(u) = if let Some(u) = col
col.find_one(doc! { "email_verification.target": info.email.clone() }, None).expect("Failed user lookup") { .find_one(
doc! { "email_verification.target": info.email.clone() },
None,
)
.expect("Failed user lookup")
{
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user."); let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
let ev = user.email_verification; let ev = user.email_verification;
@@ -190,7 +201,7 @@ pub fn resend_email(info: Json<Resend>) -> JsonValue {
return json!({ return json!({
"success": "false", "success": "false",
"error": "For security reasons, please login and change your email again.", "error": "For security reasons, please login and change your email again.",
}) });
} }
new_expiry = UtcDatetime(*expiry); new_expiry = UtcDatetime(*expiry);
@@ -209,17 +220,14 @@ pub fn resend_email(info: Json<Resend>) -> JsonValue {
None, None,
).expect("Failed to update user!"); ).expect("Failed to update user!");
match email::send_verification_email( match email::send_verification_email(info.email.to_string(), code) {
info.email.to_string(),
code,
) {
true => json!({ true => json!({
"success": true, "success": true,
}), }),
false => json!({ false => json!({
"success": false, "success": false,
"error": "Failed to send email! Likely an issue with the backend API.", "error": "Failed to send email! Likely an issue with the backend API.",
}) }),
} }
} }
} else { } else {
@@ -244,23 +252,26 @@ pub struct Login {
pub fn login(info: Json<Login>) -> JsonValue { pub fn login(info: Json<Login>) -> JsonValue {
let col = database::get_collection("users"); let col = database::get_collection("users");
if let Some(u) = if let Some(u) = col
col.find_one(doc! { "email": info.email.clone() }, None).expect("Failed user lookup") { .find_one(doc! { "email": info.email.clone() }, None)
.expect("Failed user lookup")
{
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user."); let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
match verify(info.password.clone(), &user.password) match verify(info.password.clone(), &user.password)
.expect("Failed to check hash of password.") { .expect("Failed to check hash of password.")
{
true => { true => {
let token = let token = match user.access_token {
match user.access_token {
Some(t) => t.to_string(), Some(t) => t.to_string(),
None => { None => {
let token = gen_token(92); let token = gen_token(92);
col.update_one( col.update_one(
doc! { "_id": &user.id }, doc! { "_id": &user.id },
doc! { "$set": { "access_token": token.clone() } }, doc! { "$set": { "access_token": token.clone() } },
None None,
).expect("Failed to update user object"); )
.expect("Failed to update user object");
token token
} }
}; };
@@ -270,11 +281,11 @@ pub fn login(info: Json<Login>) -> JsonValue {
"access_token": token, "access_token": token,
"id": user.id "id": user.id
}) })
}, }
false => json!({ false => json!({
"success": false, "success": false,
"error": "Invalid password." "error": "Invalid password."
}) }),
} }
} else { } else {
json!({ json!({
@@ -284,7 +295,6 @@ pub fn login(info: Json<Login>) -> JsonValue {
} }
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct Token { pub struct Token {
token: String, token: String,
@@ -295,8 +305,10 @@ pub struct Token {
pub fn token(info: Json<Token>) -> JsonValue { pub fn token(info: Json<Token>) -> JsonValue {
let col = database::get_collection("users"); let col = database::get_collection("users");
if let Some(u) = if let Some(u) = col
col.find_one(doc! { "access_token": info.token.clone() }, None).expect("Failed user lookup") { .find_one(doc! { "access_token": info.token.clone() }, None)
.expect("Failed user lookup")
{
json!({ json!({
"success": true, "success": true,
"id": u.get_str("_id").unwrap(), "id": u.get_str("_id").unwrap(),

View File

@@ -1,11 +1,11 @@
use crate::database::{ self, user::User, channel::Channel, message::Message }; use crate::database::{self, channel::Channel, message::Message, user::User};
use crate::websocket; use crate::websocket;
use bson::{ bson, doc, from_bson, Bson::UtcDatetime }; use bson::{bson, doc, from_bson, Bson::UtcDatetime};
use rocket_contrib::json::{ JsonValue, Json };
use serde::{ Serialize, Deserialize };
use num_enum::TryFromPrimitive;
use chrono::prelude::*; use chrono::prelude::*;
use num_enum::TryFromPrimitive;
use rocket_contrib::json::{Json, JsonValue};
use serde::{Deserialize, Serialize};
use ulid::Ulid; use ulid::Ulid;
#[derive(Debug, TryFromPrimitive)] #[derive(Debug, TryFromPrimitive)]
@@ -28,18 +28,16 @@ fn has_permission(user: &User, target: &Channel) -> bool {
} }
false false
}, }
2 => 2 => false,
false, _ => false,
_ =>
false
} }
} }
fn get_recipients(target: &Channel) -> Vec<String> { fn get_recipients(target: &Channel) -> Vec<String> {
match target.channel_type { match target.channel_type {
0..=1 => target.recipients.clone().unwrap(), 0..=1 => target.recipients.clone().unwrap(),
_ => vec![] _ => vec![],
} }
} }
@@ -47,11 +45,10 @@ fn get_recipients(target: &Channel) -> Vec<String> {
#[get("/<target>")] #[get("/<target>")]
pub fn channel(user: User, target: Channel) -> Option<JsonValue> { pub fn channel(user: User, target: Channel) -> Option<JsonValue> {
if !has_permission(&user, &target) { if !has_permission(&user, &target) {
return None return None;
} }
Some( Some(json!({
json!({
"id": target.id, "id": target.id,
"type": target.channel_type, "type": target.channel_type,
"recipients": get_recipients(&target), "recipients": get_recipients(&target),
@@ -65,7 +62,7 @@ pub fn channel(user: User, target: Channel) -> Option<JsonValue> {
#[delete("/<target>")] #[delete("/<target>")]
pub fn delete(user: User, target: Channel) -> Option<JsonValue> { pub fn delete(user: User, target: Channel) -> Option<JsonValue> {
if !has_permission(&user, &target) { if !has_permission(&user, &target) {
return None return None;
} }
let col = database::get_collection("channels"); let col = database::get_collection("channels");
@@ -74,31 +71,31 @@ pub fn delete(user: User, target: Channel) -> Option<JsonValue> {
col.update_one( col.update_one(
doc! { "_id": target.id }, doc! { "_id": target.id },
doc! { "$set": { "active": false } }, doc! { "$set": { "active": false } },
None None,
).expect("Failed to update channel."); )
.expect("Failed to update channel.");
json!({ json!({
"success": true "success": true
}) })
}, }
1 => { 1 => {
// ? TODO: group dm // ? TODO: group dm
json!({ json!({
"success": true "success": true
}) })
}, }
2 => { 2 => {
// ? TODO: guild // ? TODO: guild
json!({ json!({
"success": true "success": true
}) })
}, }
_ => _ => json!({
json!({
"success": false "success": false
}) }),
}) })
} }
@@ -106,26 +103,22 @@ pub fn delete(user: User, target: Channel) -> Option<JsonValue> {
#[get("/<target>/messages")] #[get("/<target>/messages")]
pub fn messages(user: User, target: Channel) -> Option<JsonValue> { pub fn messages(user: User, target: Channel) -> Option<JsonValue> {
if !has_permission(&user, &target) { if !has_permission(&user, &target) {
return None return None;
} }
let col = database::get_collection("messages"); let col = database::get_collection("messages");
let result = col.find( let result = col.find(doc! { "channel": target.id }, None).unwrap();
doc! { "channel": target.id },
None
).unwrap();
let mut messages = Vec::new(); let mut messages = Vec::new();
for item in result { for item in result {
let message: Message = from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap message."); let message: Message =
messages.push( from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap message.");
json!({ messages.push(json!({
"id": message.id, "id": message.id,
"author": message.author, "author": message.author,
"content": message.content, "content": message.content,
"edited": if let Some(t) = message.edited { Some(t.timestamp()) } else { None } "edited": if let Some(t) = message.edited { Some(t.timestamp()) } else { None }
}) }));
);
} }
Some(json!(messages)) Some(json!(messages))
@@ -141,7 +134,7 @@ pub struct SendMessage {
#[post("/<target>/messages", data = "<message>")] #[post("/<target>/messages", data = "<message>")]
pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) -> Option<JsonValue> { pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) -> Option<JsonValue> {
if !has_permission(&user, &target) { if !has_permission(&user, &target) {
return None return None;
} }
let content: String = message.content.chars().take(2000).collect(); let content: String = message.content.chars().take(2000).collect();
@@ -149,16 +142,16 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
let col = database::get_collection("messages"); let col = database::get_collection("messages");
if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).unwrap() { if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).unwrap() {
return Some( return Some(json!({
json!({
"success": false, "success": false,
"error": "Message already sent!" "error": "Message already sent!"
}) }));
)
} }
let id = Ulid::new().to_string(); let id = Ulid::new().to_string();
Some(if col.insert_one( Some(
if col
.insert_one(
doc! { doc! {
"_id": id.clone(), "_id": id.clone(),
"nonce": nonce.clone(), "nonce": nonce.clone(),
@@ -166,15 +159,18 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
"author": user.id.clone(), "author": user.id.clone(),
"content": content.clone(), "content": content.clone(),
}, },
None None,
).is_ok() { )
.is_ok()
{
if target.channel_type == ChannelType::DM as u8 { if target.channel_type == ChannelType::DM as u8 {
let col = database::get_collection("channels"); let col = database::get_collection("channels");
col.update_one( col.update_one(
doc! { "_id": target.id.clone() }, doc! { "_id": target.id.clone() },
doc! { "$set": { "active": true } }, doc! { "$set": { "active": true } },
None None,
).unwrap(); )
.unwrap();
} }
websocket::queue_message( websocket::queue_message(
@@ -188,7 +184,8 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
"author": user.id, "author": user.id,
"content": content, "content": content,
}, },
}).to_string() })
.to_string(),
); );
json!({ json!({
@@ -200,14 +197,15 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
"success": false, "success": false,
"error": "Failed database query." "error": "Failed database query."
}) })
}) },
)
} }
/// get a message /// get a message
#[get("/<target>/messages/<message>")] #[get("/<target>/messages/<message>")]
pub fn get_message(user: User, target: Channel, message: Message) -> Option<JsonValue> { pub fn get_message(user: User, target: Channel, message: Message) -> Option<JsonValue> {
if !has_permission(&user, &target) { if !has_permission(&user, &target) {
return None return None;
} }
let prev = let prev =
@@ -226,15 +224,13 @@ pub fn get_message(user: User, target: Channel, message: Message) -> Option<Json
None None
}; };
Some( Some(json!({
json!({
"id": message.id, "id": message.id,
"author": message.author, "author": message.author,
"content": message.content, "content": message.content,
"edited": if let Some(t) = message.edited { Some(t.timestamp()) } else { None }, "edited": if let Some(t) = message.edited { Some(t.timestamp()) } else { None },
"previous_content": prev, "previous_content": prev,
}) }))
)
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@@ -244,13 +240,17 @@ pub struct EditMessage {
/// edit a message /// edit a message
#[patch("/<target>/messages/<message>", data = "<edit>")] #[patch("/<target>/messages/<message>", data = "<edit>")]
pub fn edit_message(user: User, target: Channel, message: Message, edit: Json<EditMessage>) -> Option<JsonValue> { pub fn edit_message(
user: User,
target: Channel,
message: Message,
edit: Json<EditMessage>,
) -> Option<JsonValue> {
if !has_permission(&user, &target) { if !has_permission(&user, &target) {
return None return None;
} }
Some( Some(if message.author != user.id {
if message.author != user.id {
json!({ json!({
"success": false, "success": false,
"error": "You did not send this message." "error": "You did not send this message."
@@ -258,8 +258,7 @@ pub fn edit_message(user: User, target: Channel, message: Message, edit: Json<Ed
} else { } else {
let col = database::get_collection("messages"); let col = database::get_collection("messages");
let time = let time = if let Some(edited) = message.edited {
if let Some(edited) = message.edited {
edited.0 edited.0
} else { } else {
Ulid::from_string(&message.id).unwrap().datetime() Ulid::from_string(&message.id).unwrap().datetime()
@@ -280,7 +279,7 @@ pub fn edit_message(user: User, target: Channel, message: Message, edit: Json<Ed
} }
}, },
}, },
None None,
) { ) {
Ok(_) => { Ok(_) => {
websocket::queue_message( websocket::queue_message(
@@ -293,32 +292,30 @@ pub fn edit_message(user: User, target: Channel, message: Message, edit: Json<Ed
"content": edit.content.clone(), "content": edit.content.clone(),
"edited": edited.timestamp() "edited": edited.timestamp()
}, },
}).to_string() })
.to_string(),
); );
json!({ json!({
"success": true "success": true
}) })
}, }
Err(_) => Err(_) => json!({
json!({
"success": false, "success": false,
"error": "Failed to update message." "error": "Failed to update message."
}),
}
}) })
}
}
)
} }
/// delete a message /// delete a message
#[delete("/<target>/messages/<message>")] #[delete("/<target>/messages/<message>")]
pub fn delete_message(user: User, target: Channel, message: Message) -> Option<JsonValue> { pub fn delete_message(user: User, target: Channel, message: Message) -> Option<JsonValue> {
if !has_permission(&user, &target) { if !has_permission(&user, &target) {
return None return None;
} }
Some( Some(if message.author != user.id {
if message.author != user.id {
json!({ json!({
"success": false, "success": false,
"error": "You did not send this message." "error": "You did not send this message."
@@ -326,10 +323,7 @@ pub fn delete_message(user: User, target: Channel, message: Message) -> Option<J
} else { } else {
let col = database::get_collection("messages"); let col = database::get_collection("messages");
match col.delete_one( match col.delete_one(doc! { "_id": message.id.clone() }, None) {
doc! { "_id": message.id.clone() },
None
) {
Ok(_) => { Ok(_) => {
websocket::queue_message( websocket::queue_message(
get_recipients(&target), get_recipients(&target),
@@ -339,19 +333,18 @@ pub fn delete_message(user: User, target: Channel, message: Message) -> Option<J
"id": message.id, "id": message.id,
"channel": target.id "channel": target.id
}, },
}).to_string() })
.to_string(),
); );
json!({ json!({
"success": true "success": true
}) })
}, }
Err(_) => Err(_) => json!({
json!({
"success": false, "success": false,
"error": "Failed to delete message." "error": "Failed to delete message."
}),
}
}) })
}
}
)
} }

View File

@@ -1,8 +1,8 @@
use crate::database::{ self, user::User }; use crate::database::{self, user::User};
use bson::{ bson, doc }; use bson::{bson, doc};
use rocket_contrib::json::{ JsonValue, Json }; use rocket_contrib::json::{Json, JsonValue};
use serde::{ Serialize, Deserialize }; use serde::{Deserialize, Serialize};
use ulid::Ulid; use ulid::Ulid;
use super::channel::ChannelType; use super::channel::ChannelType;
@@ -25,7 +25,13 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> JsonValue {
} }
let name: String = info.name.chars().take(32).collect(); let name: String = info.name.chars().take(32).collect();
let description: String = info.description.clone().unwrap_or("No description.".to_string()).chars().take(255).collect(); let description: String = info
.description
.clone()
.unwrap_or("No description.".to_string())
.chars()
.take(255)
.collect();
let nonce: String = info.nonce.chars().take(32).collect(); let nonce: String = info.nonce.chars().take(32).collect();
let channels = database::get_collection("channels"); let channels = database::get_collection("channels");
@@ -34,7 +40,7 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> JsonValue {
return json!({ return json!({
"success": false, "success": false,
"error": "Guild already created!" "error": "Guild already created!"
}) });
} }
let channel_id = Ulid::new().to_string(); let channel_id = Ulid::new().to_string();
@@ -44,15 +50,17 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> JsonValue {
"channel_type": ChannelType::GUILDCHANNEL as u32, "channel_type": ChannelType::GUILDCHANNEL as u32,
"name": "general", "name": "general",
}, },
None) { None,
) {
return json!({ return json!({
"success": false, "success": false,
"error": "Failed to create guild channel." "error": "Failed to create guild channel."
}) });
} }
let id = Ulid::new().to_string(); let id = Ulid::new().to_string();
if col.insert_one( if col
.insert_one(
doc! { doc! {
"_id": id.clone(), "_id": id.clone(),
"nonce": nonce, "nonce": nonce,
@@ -67,14 +75,18 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> JsonValue {
], ],
"invites": [], "invites": [],
}, },
None None,
).is_ok() { )
.is_ok()
{
json!({ json!({
"success": true, "success": true,
"id": id, "id": id,
}) })
} else { } else {
channels.delete_one(doc! { "_id": channel_id }, None).expect("Failed to delete the channel we just made."); channels
.delete_one(doc! { "_id": channel_id }, None)
.expect("Failed to delete the channel we just made.");
json!({ json!({
"success": false, "success": false,

View File

@@ -1,16 +1,49 @@
use rocket::Rocket; use rocket::Rocket;
pub mod root;
pub mod account; pub mod account;
pub mod user;
pub mod channel; pub mod channel;
pub mod guild; pub mod guild;
pub mod root;
pub mod user;
pub fn mount(rocket: Rocket) -> Rocket { pub fn mount(rocket: Rocket) -> Rocket {
rocket rocket
.mount("/api", routes![ root::root ]) .mount("/api", routes![root::root])
.mount("/api/account", routes![ account::create, account::verify_email, account::resend_email, account::login, account::token ]) .mount(
.mount("/api/users", routes![ user::me, user::user, user::lookup, user::dms, user::dm, user::get_friends, user::get_friend, user::add_friend, user::remove_friend ]) "/api/account",
.mount("/api/channels", routes![ channel::channel, channel::delete, channel::messages, channel::get_message, channel::send_message, channel::edit_message, channel::delete_message ]) routes![
.mount("/api/guild", routes![ guild::create_guild ]) account::create,
account::verify_email,
account::resend_email,
account::login,
account::token
],
)
.mount(
"/api/users",
routes![
user::me,
user::user,
user::lookup,
user::dms,
user::dm,
user::get_friends,
user::get_friend,
user::add_friend,
user::remove_friend
],
)
.mount(
"/api/channels",
routes![
channel::channel,
channel::delete,
channel::messages,
channel::get_message,
channel::send_message,
channel::edit_message,
channel::delete_message
],
)
.mount("/api/guild", routes![guild::create_guild])
} }

View File

@@ -1,5 +1,5 @@
use rocket_contrib::json::{ JsonValue }; use bson::doc;
use bson::{ doc }; use rocket_contrib::json::JsonValue;
/// root /// root
#[get("/")] #[get("/")]

View File

@@ -1,10 +1,10 @@
use crate::database::{ self, user::User, channel::Channel }; use crate::database::{self, channel::Channel, user::User};
use crate::routes::channel; use crate::routes::channel;
use rocket_contrib::json::{ Json, JsonValue }; use bson::{bson, doc, from_bson};
use serde::{ Serialize, Deserialize };
use bson::{ bson, doc, from_bson };
use mongodb::options::FindOptions; use mongodb::options::FindOptions;
use rocket_contrib::json::{Json, JsonValue};
use serde::{Deserialize, Serialize};
use ulid::Ulid; use ulid::Ulid;
/// retrieve your user information /// retrieve your user information
@@ -39,21 +39,22 @@ pub struct Query {
pub fn lookup(user: User, query: Json<Query>) -> JsonValue { pub fn lookup(user: User, query: Json<Query>) -> JsonValue {
let col = database::get_collection("users"); let col = database::get_collection("users");
let users = col.find( let users = col
.find(
doc! { "username": query.username.clone() }, doc! { "username": query.username.clone() },
FindOptions::builder().limit(10).build() FindOptions::builder().limit(10).build(),
).expect("Failed user lookup"); )
.expect("Failed user lookup");
let mut results = Vec::new(); let mut results = Vec::new();
for item in users { for item in users {
let u: User = from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap user."); let u: User =
results.push( from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap user.");
json!({ results.push(json!({
"id": u.id, "id": u.id,
"username": u.username, "username": u.username,
"relationship": get_relationship(&user, &u) as u8 "relationship": get_relationship(&user, &u) as u8
}) }));
);
} }
json!(results) json!(results)
@@ -64,7 +65,8 @@ pub fn lookup(user: User, query: Json<Query>) -> JsonValue {
pub fn dms(user: User) -> JsonValue { pub fn dms(user: User) -> JsonValue {
let col = database::get_collection("channels"); let col = database::get_collection("channels");
let results = col.find( let results = col
.find(
doc! { doc! {
"$or": [ "$or": [
{ {
@@ -76,21 +78,21 @@ pub fn dms(user: User) -> JsonValue {
], ],
"recipients": user.id "recipients": user.id
}, },
None None,
).expect("Failed channel lookup"); )
.expect("Failed channel lookup");
let mut channels = Vec::new(); let mut channels = Vec::new();
for item in results { for item in results {
let channel: Channel = from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap channel."); let channel: Channel =
from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap channel.");
channels.push( channels.push(json!({
json!({
"id": channel.id, "id": channel.id,
"type": channel.channel_type, "type": channel.channel_type,
"recipients": channel.recipients, "recipients": channel.recipients,
"active": channel.active.unwrap() "active": channel.active.unwrap()
}) }));
);
} }
json!(channels) json!(channels)
@@ -143,31 +145,19 @@ enum Relationship {
fn get_relationship(a: &User, b: &User) -> Relationship { fn get_relationship(a: &User, b: &User) -> Relationship {
if a.id == b.id { if a.id == b.id {
return Relationship::SELF return Relationship::SELF;
} }
if let Some(arr) = &b.relations { if let Some(arr) = &b.relations {
for entry in arr { for entry in arr {
if entry.id == a.id { if entry.id == a.id {
match entry.status { match entry.status {
0 => { 0 => return Relationship::FRIEND,
return Relationship::FRIEND 1 => return Relationship::INCOMING,
}, 2 => return Relationship::OUTGOING,
1 => { 3 => return Relationship::BLOCKEDOTHER,
return Relationship::INCOMING 4 => return Relationship::BLOCKED,
}, _ => return Relationship::NONE,
2 => {
return Relationship::OUTGOING
},
3 => {
return Relationship::BLOCKEDOTHER
},
4 => {
return Relationship::BLOCKED
},
_ => {
return Relationship::NONE
}
} }
} }
} }
@@ -182,12 +172,10 @@ pub fn get_friends(user: User) -> JsonValue {
let mut results = Vec::new(); let mut results = Vec::new();
if let Some(arr) = user.relations { if let Some(arr) = user.relations {
for item in arr { for item in arr {
results.push( results.push(json!({
json!({
"id": item.id, "id": item.id,
"status": item.status "status": item.status
}) }))
)
} }
} }
@@ -212,13 +200,11 @@ pub fn add_friend(user: User, target: User) -> JsonValue {
let relationship = get_relationship(&user, &target); let relationship = get_relationship(&user, &target);
match relationship { match relationship {
Relationship::FRIEND => Relationship::FRIEND => json!({
json!({
"success": false, "success": false,
"error": "Already friends." "error": "Already friends."
}), }),
Relationship::OUTGOING => Relationship::OUTGOING => json!({
json!({
"success": false, "success": false,
"error": "Already sent a friend request." "error": "Already sent a friend request."
}), }),
@@ -233,8 +219,9 @@ pub fn add_friend(user: User, target: User) -> JsonValue {
"relations.$.status": Relationship::FRIEND as i32 "relations.$.status": Relationship::FRIEND as i32
} }
}, },
None None,
).expect("Failed update query."); )
.expect("Failed update query.");
col.update_one( col.update_one(
doc! { doc! {
@@ -246,21 +233,20 @@ pub fn add_friend(user: User, target: User) -> JsonValue {
"relations.$.status": Relationship::FRIEND as i32 "relations.$.status": Relationship::FRIEND as i32
} }
}, },
None None,
).expect("Failed update query."); )
.expect("Failed update query.");
json!({ json!({
"success": true, "success": true,
"status": Relationship::FRIEND as u8, "status": Relationship::FRIEND as u8,
}) })
}, }
Relationship::BLOCKED => Relationship::BLOCKED => json!({
json!({
"success": false, "success": false,
"error": "You have blocked this person." "error": "You have blocked this person."
}), }),
Relationship::BLOCKEDOTHER => Relationship::BLOCKEDOTHER => json!({
json!({
"success": false, "success": false,
"error": "You have been blocked by this person." "error": "You have been blocked by this person."
}), }),
@@ -277,8 +263,9 @@ pub fn add_friend(user: User, target: User) -> JsonValue {
} }
} }
}, },
None None,
).expect("Failed update query."); )
.expect("Failed update query.");
col.update_one( col.update_one(
doc! { doc! {
@@ -292,19 +279,19 @@ pub fn add_friend(user: User, target: User) -> JsonValue {
} }
} }
}, },
None None,
).expect("Failed update query."); )
.expect("Failed update query.");
json!({ json!({
"success": true, "success": true,
"status": Relationship::OUTGOING as u8, "status": Relationship::OUTGOING as u8,
}) })
}, }
Relationship::SELF => Relationship::SELF => json!({
json!({
"success": false, "success": false,
"error": "Cannot add yourself as a friend." "error": "Cannot add yourself as a friend."
}) }),
} }
} }
@@ -315,9 +302,7 @@ pub fn remove_friend(user: User, target: User) -> JsonValue {
let relationship = get_relationship(&user, &target); let relationship = get_relationship(&user, &target);
match relationship { match relationship {
Relationship::FRIEND | Relationship::FRIEND | Relationship::OUTGOING | Relationship::INCOMING => {
Relationship::OUTGOING |
Relationship::INCOMING => {
col.update_one( col.update_one(
doc! { doc! {
"_id": user.id.clone() "_id": user.id.clone()
@@ -329,8 +314,9 @@ pub fn remove_friend(user: User, target: User) -> JsonValue {
} }
} }
}, },
None None,
).expect("Failed update query."); )
.expect("Failed update query.");
col.update_one( col.update_one(
doc! { doc! {
@@ -343,20 +329,20 @@ pub fn remove_friend(user: User, target: User) -> JsonValue {
} }
} }
}, },
None None,
).expect("Failed update query."); )
.expect("Failed update query.");
json!({ json!({
"success": true "success": true
}) })
}, }
Relationship::BLOCKED | Relationship::BLOCKED
Relationship::BLOCKEDOTHER | | Relationship::BLOCKEDOTHER
Relationship::NONE | | Relationship::NONE
Relationship::SELF => | Relationship::SELF => json!({
json!({
"success": false, "success": false,
"error": "This has no effect." "error": "This has no effect."
}) }),
} }
} }

View File

@@ -2,14 +2,14 @@ extern crate ws;
use crate::database; use crate::database;
use ulid::Ulid;
use std::sync::RwLock;
use hashbrown::HashMap; use hashbrown::HashMap;
use std::sync::RwLock;
use ulid::Ulid;
use bson::{ bson, doc }; use bson::{bson, doc};
use serde_json::{ Value, from_str, json }; use serde_json::{from_str, json, Value};
use ws::{ listen, Handler, Sender, Result, Message, Handshake, CloseCode, Error }; use ws::{listen, CloseCode, Error, Handler, Handshake, Message, Result, Sender};
struct Cell { struct Cell {
id: String, id: String,
@@ -44,31 +44,33 @@ impl Handler for Server {
"success": false, "success": false,
"error": "Already authenticated!" "error": "Already authenticated!"
}) })
.to_string() .to_string(),
) )
} else if let Value::String(token) = &data["token"] { } else if let Value::String(token) = &data["token"] {
let col = database::get_collection("users"); let col = database::get_collection("users");
match col.find_one( match col.find_one(doc! { "access_token": token }, None).unwrap() {
doc! { "access_token": token },
None
).unwrap() {
Some(u) => { Some(u) => {
let id = u.get_str("_id").expect("Missing id."); let id = u.get_str("_id").expect("Missing id.");
unsafe { unsafe {
let mut map = CLIENTS.get_mut().unwrap().write().unwrap(); let mut map = CLIENTS.get_mut().unwrap().write().unwrap();
let cell = Cell { id: self.internal.clone(), out: self.out.clone() }; let cell = Cell {
id: self.internal.clone(),
out: self.out.clone(),
};
if map.contains_key(&id.to_string()) { if map.contains_key(&id.to_string()) {
map.get_mut(&id.to_string()) map.get_mut(&id.to_string()).unwrap().push(cell);
.unwrap()
.push(cell);
} else { } else {
map.insert(id.to_string(), vec![cell]); map.insert(id.to_string(), vec![cell]);
} }
} }
println!("Websocket client connected. [ID: {} // {}]", id.to_string(), self.internal); println!(
"Websocket client connected. [ID: {} // {}]",
id.to_string(),
self.internal
);
self.id = Some(id.to_string()); self.id = Some(id.to_string());
self.out.send( self.out.send(
@@ -76,18 +78,17 @@ impl Handler for Server {
"type": "authenticate", "type": "authenticate",
"success": true "success": true
}) })
.to_string() .to_string(),
) )
}, }
None => None => self.out.send(
self.out.send(
json!({ json!({
"type": "authenticate", "type": "authenticate",
"success": false, "success": false,
"error": "Invalid authentication token." "error": "Invalid authentication token."
}) })
.to_string() .to_string(),
) ),
} }
} else { } else {
self.out.send( self.out.send(
@@ -96,11 +97,11 @@ impl Handler for Server {
"success": false, "success": false,
"error": "Missing authentication token." "error": "Missing authentication token."
}) })
.to_string() .to_string(),
) )
} }
}, }
_ => Ok(()) _ => Ok(()),
} }
} else { } else {
Ok(()) Ok(())
@@ -114,13 +115,17 @@ impl Handler for Server {
match code { match code {
CloseCode::Normal => println!("The client is done with the connection."), CloseCode::Normal => println!("The client is done with the connection."),
CloseCode::Away => println!("The client is leaving the site."), CloseCode::Away => println!("The client is leaving the site."),
CloseCode::Abnormal => println!( CloseCode::Abnormal => {
"Closing handshake failed! Unable to obtain closing status from client."), println!("Closing handshake failed! Unable to obtain closing status from client.")
}
_ => println!("The client encountered an error: {}", reason), _ => println!("The client encountered an error: {}", reason),
} }
if let Some(id) = &self.id { if let Some(id) = &self.id {
println!("Websocket client disconnected. [ID: {} // {}]", id, self.internal); println!(
"Websocket client disconnected. [ID: {} // {}]",
id, self.internal
);
unsafe { unsafe {
let mut map = CLIENTS.get_mut().unwrap().write().unwrap(); let mut map = CLIENTS.get_mut().unwrap().write().unwrap();
let arr = map.get_mut(&id.clone()).unwrap(); let arr = map.get_mut(&id.clone()).unwrap();
@@ -130,7 +135,11 @@ impl Handler for Server {
} else { } else {
let index = arr.iter().position(|x| x.id == self.internal).unwrap(); let index = arr.iter().position(|x| x.id == self.internal).unwrap();
arr.remove(index); arr.remove(index);
println!("User [{}] is still connected {} times", self.id.as_ref().unwrap(), arr.len()); println!(
"User [{}] is still connected {} times",
self.id.as_ref().unwrap(),
arr.len()
);
} }
} }
} }
@@ -148,7 +157,12 @@ pub fn launch_server() {
} }
} }
listen("192.168.0.10:9999", |out| { Server { out: out, id: None, internal: Ulid::new().to_string() } }).unwrap() listen("192.168.0.10:9999", |out| Server {
out: out,
id: None,
internal: Ulid::new().to_string(),
})
.unwrap()
} }
pub fn send_message(id: String, message: String) -> std::result::Result<(), ()> { pub fn send_message(id: String, message: String) -> std::result::Result<(), ()> {
@@ -173,6 +187,7 @@ pub fn send_message(id: String, message: String) -> std::result::Result<(), ()>
pub fn queue_message(ids: Vec<String>, message: String) { pub fn queue_message(ids: Vec<String>, message: String) {
for id in ids { for id in ids {
send_message(id, message.clone()).expect("uhhhhhhhhhh can i get uhhhhhhhhhhhhhhhhhh mcdonald cheese burger with fries"); send_message(id, message.clone())
.expect("uhhhhhhhhhh can i get uhhhhhhhhhhhhhhhhhh mcdonald cheese burger with fries");
} }
} }