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)]
pub struct Channel {

View File

@@ -1,4 +1,4 @@
use serde::{ Deserialize, Serialize };
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
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)]
pub struct PreviousEntry {
@@ -18,5 +18,5 @@ pub struct Message {
pub content: String,
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 once_cell::sync::OnceCell;
static DBCONN: OnceCell<Client> = OnceCell::new();
pub fn connect() {
let client = Client::with_uri_str(
&env::var("DB_URI").expect("DB_URI not in environment variables!"))
let client =
Client::with_uri_str(&env::var("DB_URI").expect("DB_URI not in environment variables!"))
.expect("Failed to init db connection.");
DBCONN.set(client).unwrap();
@@ -24,7 +24,7 @@ pub fn get_collection(collection: &str) -> Collection {
get_db().collection(collection)
}
pub mod user;
pub mod channel;
pub mod message;
pub mod guild;
pub mod message;
pub mod user;

View File

@@ -1,5 +1,5 @@
use serde::{ Deserialize, Serialize };
use bson::UtcDateTime;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
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);
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)
.send() {
.send()
{
Ok(_) => Ok(()),
Err(_) => Err(())
Err(_) => Err(()),
}
}
@@ -28,8 +30,9 @@ pub fn send_verification_email(email: String, code: String) -> bool {
email,
"Verify your email!".to_string(),
format!("Verify your email here: {}", url),
format!("<a href=\"{}\">Click to verify your email!</a>", url)
).is_ok()
format!("<a href=\"{}\">Click to verify your email!</a>", url),
)
.is_ok()
}
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,
"Welcome to REVOLT!".to_string(),
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())
).is_ok()
format!(
"<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::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 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();
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 {
Outcome::Failure((Status::Forbidden, AuthError::Invalid))
}
},
}
_ => 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> {
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 {
Ok(from_bson(bson::Bson::Document(user)).expect("Failed to unwrap user."))

View File

@@ -1,6 +1,6 @@
use rocket::http::{ RawStr };
use rocket::request::{ FromParam };
use bson::{ bson, doc, from_bson };
use bson::{bson, doc, from_bson};
use rocket::http::RawStr;
use rocket::request::FromParam;
use crate::database;
@@ -12,7 +12,9 @@ impl<'r> FromParam<'r> for Channel {
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
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 {
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> {
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 {
Ok(from_bson(bson::Bson::Document(message)).expect("Failed to unwrap message."))

View File

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

View File

@@ -1,15 +1,15 @@
use crate::database;
use crate::email;
use bson::{ bson, doc, Bson::UtcDatetime, from_bson };
use rand::{ Rng, distributions::Alphanumeric };
use rocket_contrib::json::{ Json, JsonValue };
use serde::{ Serialize, Deserialize };
use validator::validate_email;
use bcrypt::{ hash, verify };
use database::user::User;
use bcrypt::{hash, verify};
use bson::{bson, doc, from_bson, Bson::UtcDatetime};
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 validator::validate_email;
fn gen_token(l: usize) -> String {
rand::thread_rng()
@@ -40,35 +40,39 @@ pub fn create(info: Json<Create>) -> JsonValue {
return json!({
"success": false,
"error": "Username requirements not met! Must be between 2 and 32 characters.",
})
});
}
if info.password.len() < 8 || info.password.len() > 72 {
return json!({
"success": false,
"error": "Password requirements not met! Must be between 8 and 72 characters.",
})
});
}
if !validate_email(info.email.clone()) {
return json!({
"success": false,
"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!({
"success": false,
"error": "Email already in use!",
})
});
}
if let Ok(hashed) = hash(info.password.clone(), 10) {
let access_token = gen_token(92);
let code = gen_token(48);
match col.insert_one(doc! {
match col.insert_one(
doc! {
"_id": Ulid::new().to_string(),
"email": info.email.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)),
"code": code.clone(),
}
}, None) {
},
None,
) {
Ok(_) => {
let sent = email::send_verification_email(info.email.clone(), code);
@@ -89,11 +95,11 @@ pub fn create(info: Json<Create>) -> JsonValue {
"success": true,
"email_sent": sent,
})
},
}
Err(_) => json!({
"success": false,
"error": "Failed to create account!",
})
}),
}
} else {
json!({
@@ -111,8 +117,10 @@ pub fn create(info: Json<Create>) -> JsonValue {
pub fn verify_email(code: String) -> JsonValue {
let col = database::get_collection("users");
if let Some(u) =
col.find_one(doc! { "email_verification.code": code.clone() }, None).expect("Failed user lookup") {
if let Some(u) = col
.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 ev = user.email_verification;
@@ -138,12 +146,10 @@ pub fn verify_email(code: String) -> JsonValue {
},
},
None,
).expect("Failed to update user!");
)
.expect("Failed to update user!");
email::send_welcome_email(
target.to_string(),
user.username
);
email::send_welcome_email(target.to_string(), user.username);
json!({
"success": true
@@ -170,8 +176,13 @@ pub struct Resend {
pub fn resend_email(info: Json<Resend>) -> JsonValue {
let col = database::get_collection("users");
if let Some(u) =
col.find_one(doc! { "email_verification.target": info.email.clone() }, None).expect("Failed user lookup") {
if let Some(u) = col
.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 ev = user.email_verification;
@@ -190,7 +201,7 @@ pub fn resend_email(info: Json<Resend>) -> JsonValue {
return json!({
"success": "false",
"error": "For security reasons, please login and change your email again.",
})
});
}
new_expiry = UtcDatetime(*expiry);
@@ -209,17 +220,14 @@ pub fn resend_email(info: Json<Resend>) -> JsonValue {
None,
).expect("Failed to update user!");
match email::send_verification_email(
info.email.to_string(),
code,
) {
match email::send_verification_email(info.email.to_string(), code) {
true => json!({
"success": true,
}),
false => json!({
"success": false,
"error": "Failed to send email! Likely an issue with the backend API.",
})
}),
}
}
} else {
@@ -244,23 +252,26 @@ pub struct Login {
pub fn login(info: Json<Login>) -> JsonValue {
let col = database::get_collection("users");
if let Some(u) =
col.find_one(doc! { "email": info.email.clone() }, None).expect("Failed user lookup") {
if let Some(u) = col
.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.");
match verify(info.password.clone(), &user.password)
.expect("Failed to check hash of password.") {
.expect("Failed to check hash of password.")
{
true => {
let token =
match user.access_token {
let token = match user.access_token {
Some(t) => t.to_string(),
None => {
let token = gen_token(92);
col.update_one(
doc! { "_id": &user.id },
doc! { "$set": { "access_token": token.clone() } },
None
).expect("Failed to update user object");
None,
)
.expect("Failed to update user object");
token
}
};
@@ -270,11 +281,11 @@ pub fn login(info: Json<Login>) -> JsonValue {
"access_token": token,
"id": user.id
})
},
}
false => json!({
"success": false,
"error": "Invalid password."
})
}),
}
} else {
json!({
@@ -284,7 +295,6 @@ pub fn login(info: Json<Login>) -> JsonValue {
}
}
#[derive(Serialize, Deserialize)]
pub struct Token {
token: String,
@@ -295,8 +305,10 @@ pub struct Token {
pub fn token(info: Json<Token>) -> JsonValue {
let col = database::get_collection("users");
if let Some(u) =
col.find_one(doc! { "access_token": info.token.clone() }, None).expect("Failed user lookup") {
if let Some(u) = col
.find_one(doc! { "access_token": info.token.clone() }, None)
.expect("Failed user lookup")
{
json!({
"success": true,
"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 bson::{ bson, doc, from_bson, Bson::UtcDatetime };
use rocket_contrib::json::{ JsonValue, Json };
use serde::{ Serialize, Deserialize };
use num_enum::TryFromPrimitive;
use bson::{bson, doc, from_bson, Bson::UtcDatetime};
use chrono::prelude::*;
use num_enum::TryFromPrimitive;
use rocket_contrib::json::{Json, JsonValue};
use serde::{Deserialize, Serialize};
use ulid::Ulid;
#[derive(Debug, TryFromPrimitive)]
@@ -28,18 +28,16 @@ fn has_permission(user: &User, target: &Channel) -> bool {
}
false
},
2 =>
false,
_ =>
false
}
2 => false,
_ => false,
}
}
fn get_recipients(target: &Channel) -> Vec<String> {
match target.channel_type {
0..=1 => target.recipients.clone().unwrap(),
_ => vec![]
_ => vec![],
}
}
@@ -47,11 +45,10 @@ fn get_recipients(target: &Channel) -> Vec<String> {
#[get("/<target>")]
pub fn channel(user: User, target: Channel) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None
return None;
}
Some(
json!({
Some(json!({
"id": target.id,
"type": target.channel_type,
"recipients": get_recipients(&target),
@@ -65,7 +62,7 @@ pub fn channel(user: User, target: Channel) -> Option<JsonValue> {
#[delete("/<target>")]
pub fn delete(user: User, target: Channel) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None
return None;
}
let col = database::get_collection("channels");
@@ -74,31 +71,31 @@ pub fn delete(user: User, target: Channel) -> Option<JsonValue> {
col.update_one(
doc! { "_id": target.id },
doc! { "$set": { "active": false } },
None
).expect("Failed to update channel.");
None,
)
.expect("Failed to update channel.");
json!({
"success": true
})
},
}
1 => {
// ? TODO: group dm
json!({
"success": true
})
},
}
2 => {
// ? TODO: guild
json!({
"success": true
})
},
_ =>
json!({
}
_ => json!({
"success": false
})
}),
})
}
@@ -106,26 +103,22 @@ pub fn delete(user: User, target: Channel) -> Option<JsonValue> {
#[get("/<target>/messages")]
pub fn messages(user: User, target: Channel) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None
return None;
}
let col = database::get_collection("messages");
let result = col.find(
doc! { "channel": target.id },
None
).unwrap();
let result = col.find(doc! { "channel": target.id }, None).unwrap();
let mut messages = Vec::new();
for item in result {
let message: Message = from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap message.");
messages.push(
json!({
let message: Message =
from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap message.");
messages.push(json!({
"id": message.id,
"author": message.author,
"content": message.content,
"edited": if let Some(t) = message.edited { Some(t.timestamp()) } else { None }
})
);
}));
}
Some(json!(messages))
@@ -141,7 +134,7 @@ pub struct SendMessage {
#[post("/<target>/messages", data = "<message>")]
pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None
return None;
}
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");
if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).unwrap() {
return Some(
json!({
return Some(json!({
"success": false,
"error": "Message already sent!"
})
)
}));
}
let id = Ulid::new().to_string();
Some(if col.insert_one(
Some(
if col
.insert_one(
doc! {
"_id": id.clone(),
"nonce": nonce.clone(),
@@ -166,15 +159,18 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
"author": user.id.clone(),
"content": content.clone(),
},
None
).is_ok() {
None,
)
.is_ok()
{
if target.channel_type == ChannelType::DM as u8 {
let col = database::get_collection("channels");
col.update_one(
doc! { "_id": target.id.clone() },
doc! { "$set": { "active": true } },
None
).unwrap();
None,
)
.unwrap();
}
websocket::queue_message(
@@ -188,7 +184,8 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
"author": user.id,
"content": content,
},
}).to_string()
})
.to_string(),
);
json!({
@@ -200,14 +197,15 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
"success": false,
"error": "Failed database query."
})
})
},
)
}
/// get a message
#[get("/<target>/messages/<message>")]
pub fn get_message(user: User, target: Channel, message: Message) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None
return None;
}
let prev =
@@ -226,15 +224,13 @@ pub fn get_message(user: User, target: Channel, message: Message) -> Option<Json
None
};
Some(
json!({
Some(json!({
"id": message.id,
"author": message.author,
"content": message.content,
"edited": if let Some(t) = message.edited { Some(t.timestamp()) } else { None },
"previous_content": prev,
})
)
}))
}
#[derive(Serialize, Deserialize)]
@@ -244,13 +240,17 @@ pub struct EditMessage {
/// edit a message
#[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) {
return None
return None;
}
Some(
if message.author != user.id {
Some(if message.author != user.id {
json!({
"success": false,
"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 {
let col = database::get_collection("messages");
let time =
if let Some(edited) = message.edited {
let time = if let Some(edited) = message.edited {
edited.0
} else {
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(_) => {
websocket::queue_message(
@@ -293,32 +292,30 @@ pub fn edit_message(user: User, target: Channel, message: Message, edit: Json<Ed
"content": edit.content.clone(),
"edited": edited.timestamp()
},
}).to_string()
})
.to_string(),
);
json!({
"success": true
})
},
Err(_) =>
json!({
}
Err(_) => json!({
"success": false,
"error": "Failed to update message."
}),
}
})
}
}
)
}
/// delete a message
#[delete("/<target>/messages/<message>")]
pub fn delete_message(user: User, target: Channel, message: Message) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None
return None;
}
Some(
if message.author != user.id {
Some(if message.author != user.id {
json!({
"success": false,
"error": "You did not send this message."
@@ -326,10 +323,7 @@ pub fn delete_message(user: User, target: Channel, message: Message) -> Option<J
} else {
let col = database::get_collection("messages");
match col.delete_one(
doc! { "_id": message.id.clone() },
None
) {
match col.delete_one(doc! { "_id": message.id.clone() }, None) {
Ok(_) => {
websocket::queue_message(
get_recipients(&target),
@@ -339,19 +333,18 @@ pub fn delete_message(user: User, target: Channel, message: Message) -> Option<J
"id": message.id,
"channel": target.id
},
}).to_string()
})
.to_string(),
);
json!({
"success": true
})
},
Err(_) =>
json!({
}
Err(_) => json!({
"success": false,
"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 rocket_contrib::json::{ JsonValue, Json };
use serde::{ Serialize, Deserialize };
use bson::{bson, doc};
use rocket_contrib::json::{Json, JsonValue};
use serde::{Deserialize, Serialize};
use ulid::Ulid;
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 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 channels = database::get_collection("channels");
@@ -34,7 +40,7 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> JsonValue {
return json!({
"success": false,
"error": "Guild already created!"
})
});
}
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,
"name": "general",
},
None) {
None,
) {
return json!({
"success": false,
"error": "Failed to create guild channel."
})
});
}
let id = Ulid::new().to_string();
if col.insert_one(
if col
.insert_one(
doc! {
"_id": id.clone(),
"nonce": nonce,
@@ -67,14 +75,18 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> JsonValue {
],
"invites": [],
},
None
).is_ok() {
None,
)
.is_ok()
{
json!({
"success": true,
"id": id,
})
} 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!({
"success": false,

View File

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

View File

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