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,28 +1,28 @@
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()
.sample_iter(&Alphanumeric)
.take(l)
.collect::<String>()
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(l)
.collect::<String>()
}
#[derive(Serialize, Deserialize)]
pub struct Create {
username: String,
password: String,
email: String,
username: String,
password: String,
email: String,
}
/// create a new Revolt account
@@ -34,73 +34,79 @@ pub struct Create {
/// (3) add user and send email verification
#[post("/create", data = "<info>")]
pub fn create(info: Json<Create>) -> JsonValue {
let col = database::get_collection("users");
let col = database::get_collection("users");
if info.username.len() < 2 || info.username.len() > 32 {
return json!({
"success": false,
"error": "Username requirements not met! Must be between 2 and 32 characters.",
})
}
if info.username.len() < 2 || info.username.len() > 32 {
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 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 !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") {
return json!({
"success": false,
"error": "Email already in use!",
})
}
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);
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! {
"_id": Ulid::new().to_string(),
"email": info.email.clone(),
"username": info.username.clone(),
"password": hashed,
"access_token": access_token,
"email_verification": {
"verified": false,
"target": info.email.clone(),
"expiry": UtcDatetime(Utc::now() + chrono::Duration::days(1)),
"rate_limit": UtcDatetime(Utc::now() + chrono::Duration::minutes(1)),
"code": code.clone(),
}
}, None) {
Ok(_) => {
let sent = email::send_verification_email(info.email.clone(), code);
match col.insert_one(
doc! {
"_id": Ulid::new().to_string(),
"email": info.email.clone(),
"username": info.username.clone(),
"password": hashed,
"access_token": access_token,
"email_verification": {
"verified": false,
"target": info.email.clone(),
"expiry": UtcDatetime(Utc::now() + chrono::Duration::days(1)),
"rate_limit": UtcDatetime(Utc::now() + chrono::Duration::minutes(1)),
"code": code.clone(),
}
},
None,
) {
Ok(_) => {
let sent = email::send_verification_email(info.email.clone(), code);
json!({
"success": true,
"email_sent": sent,
})
},
Err(_) => json!({
"success": false,
"error": "Failed to create account!",
})
}
} else {
json!({
"success": false,
"error": "Failed to hash password!",
})
}
json!({
"success": true,
"email_sent": sent,
})
}
Err(_) => json!({
"success": false,
"error": "Failed to create account!",
}),
}
} else {
json!({
"success": false,
"error": "Failed to hash password!",
})
}
}
/// verify an email for a Revolt account
@@ -109,57 +115,57 @@ pub fn create(info: Json<Create>) -> JsonValue {
/// (3) set account as verified
#[get("/verify/<code>")]
pub fn verify_email(code: String) -> JsonValue {
let col = database::get_collection("users");
let col = database::get_collection("users");
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;
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;
if Utc::now() > *ev.expiry.unwrap() {
json!({
"success": false,
"error": "Token has expired!",
})
} else {
let target = ev.target.unwrap();
col.update_one(
doc! { "_id": user.id },
doc! {
"$unset": {
"email_verification.code": "",
"email_verification.expiry": "",
"email_verification.target": "",
"email_verification.rate_limit": "",
},
"$set": {
"email_verification.verified": true,
"email": target.clone(),
},
},
None,
).expect("Failed to update user!");
if Utc::now() > *ev.expiry.unwrap() {
json!({
"success": false,
"error": "Token has expired!",
})
} else {
let target = ev.target.unwrap();
col.update_one(
doc! { "_id": user.id },
doc! {
"$unset": {
"email_verification.code": "",
"email_verification.expiry": "",
"email_verification.target": "",
"email_verification.rate_limit": "",
},
"$set": {
"email_verification.verified": true,
"email": target.clone(),
},
},
None,
)
.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
})
}
} else {
json!({
"success": false,
"error": "Invalid code!",
})
}
json!({
"success": true
})
}
} else {
json!({
"success": false,
"error": "Invalid code!",
})
}
}
#[derive(Serialize, Deserialize)]
pub struct Resend {
email: String,
email: String,
}
/// resend a verification email
@@ -168,36 +174,41 @@ pub struct Resend {
/// (3) resend the email
#[post("/resend", data = "<info>")]
pub fn resend_email(info: Json<Resend>) -> JsonValue {
let col = database::get_collection("users");
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") {
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
let ev = user.email_verification;
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;
let expiry = ev.expiry.unwrap();
let rate_limit = ev.rate_limit.unwrap();
let expiry = ev.expiry.unwrap();
let rate_limit = ev.rate_limit.unwrap();
if Utc::now() < *rate_limit {
json!({
"success": false,
"error": "Hit rate limit! Please try again in a minute or so.",
})
} else {
let mut new_expiry = UtcDatetime(Utc::now() + chrono::Duration::days(1));
if info.email.clone() != user.email {
if Utc::now() > *expiry {
return json!({
"success": "false",
"error": "For security reasons, please login and change your email again.",
})
}
if Utc::now() < *rate_limit {
json!({
"success": false,
"error": "Hit rate limit! Please try again in a minute or so.",
})
} else {
let mut new_expiry = UtcDatetime(Utc::now() + chrono::Duration::days(1));
if info.email.clone() != user.email {
if Utc::now() > *expiry {
return json!({
"success": "false",
"error": "For security reasons, please login and change your email again.",
});
}
new_expiry = UtcDatetime(*expiry);
}
new_expiry = UtcDatetime(*expiry);
}
let code = gen_token(48);
col.update_one(
let code = gen_token(48);
col.update_one(
doc! { "_id": user.id },
doc! {
"$set": {
@@ -209,31 +220,28 @@ pub fn resend_email(info: Json<Resend>) -> JsonValue {
None,
).expect("Failed to update user!");
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 {
json!({
"success": false,
"error": "Email not pending verification!",
})
}
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 {
json!({
"success": false,
"error": "Email not pending verification!",
})
}
}
#[derive(Serialize, Deserialize)]
pub struct Login {
email: String,
password: String,
email: String,
password: String,
}
/// login to a Revolt account
@@ -242,69 +250,73 @@ pub struct Login {
/// (3) return access token
#[post("/login", data = "<info>")]
pub fn login(info: Json<Login>) -> JsonValue {
let col = database::get_collection("users");
let col = database::get_collection("users");
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.");
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.") {
true => {
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");
token
}
};
match verify(info.password.clone(), &user.password)
.expect("Failed to check hash of password.")
{
true => {
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");
token
}
};
json!({
"success": true,
"access_token": token,
"id": user.id
})
},
false => json!({
"success": false,
"error": "Invalid password."
})
}
} else {
json!({
"success": false,
"error": "Email is not registered.",
})
}
json!({
"success": true,
"access_token": token,
"id": user.id
})
}
false => json!({
"success": false,
"error": "Invalid password."
}),
}
} else {
json!({
"success": false,
"error": "Email is not registered.",
})
}
}
#[derive(Serialize, Deserialize)]
pub struct Token {
token: String,
token: String,
}
/// login to a Revolt account via token
#[post("/token", data = "<info>")]
pub fn token(info: Json<Token>) -> JsonValue {
let col = database::get_collection("users");
let col = database::get_collection("users");
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(),
})
} else {
json!({
"success": false,
"error": "Invalid token!",
})
}
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(),
})
} else {
json!({
"success": false,
"error": "Invalid token!",
})
}
}

View File

@@ -1,62 +1,59 @@
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)]
#[repr(usize)]
pub enum ChannelType {
DM = 0,
GROUPDM = 1,
GUILDCHANNEL = 2,
DM = 0,
GROUPDM = 1,
GUILDCHANNEL = 2,
}
fn has_permission(user: &User, target: &Channel) -> bool {
match target.channel_type {
0..=1 => {
if let Some(arr) = &target.recipients {
for item in arr {
if item == &user.id {
return true;
}
}
}
match target.channel_type {
0..=1 => {
if let Some(arr) = &target.recipients {
for item in arr {
if item == &user.id {
return true;
}
}
}
false
},
2 =>
false,
_ =>
false
}
false
}
2 => false,
_ => false,
}
}
fn get_recipients(target: &Channel) -> Vec<String> {
match target.channel_type {
0..=1 => target.recipients.clone().unwrap(),
_ => vec![]
}
match target.channel_type {
0..=1 => target.recipients.clone().unwrap(),
_ => vec![],
}
}
/// fetch channel information
#[get("/<target>")]
pub fn channel(user: User, target: Channel) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None
}
if !has_permission(&user, &target) {
return None;
}
Some(
json!({
"id": target.id,
"type": target.channel_type,
"recipients": get_recipients(&target),
}
))
Some(json!({
"id": target.id,
"type": target.channel_type,
"recipients": get_recipients(&target),
}
))
}
/// delete channel
@@ -64,152 +61,153 @@ pub fn channel(user: User, target: Channel) -> Option<JsonValue> {
/// or close DM conversation
#[delete("/<target>")]
pub fn delete(user: User, target: Channel) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None
}
if !has_permission(&user, &target) {
return None;
}
let col = database::get_collection("channels");
Some(match target.channel_type {
0 => {
col.update_one(
doc! { "_id": target.id },
doc! { "$set": { "active": false } },
None
).expect("Failed to update channel.");
let col = database::get_collection("channels");
Some(match target.channel_type {
0 => {
col.update_one(
doc! { "_id": target.id },
doc! { "$set": { "active": false } },
None,
)
.expect("Failed to update channel.");
json!({
"success": true
})
},
1 => {
// ? TODO: group dm
json!({
"success": true
})
}
1 => {
// ? TODO: group dm
json!({
"success": true
})
},
2 => {
// ? TODO: guild
json!({
"success": true
})
}
2 => {
// ? TODO: guild
json!({
"success": true
})
},
_ =>
json!({
"success": false
})
})
json!({
"success": true
})
}
_ => json!({
"success": false
}),
})
}
/// fetch channel messages
#[get("/<target>/messages")]
pub fn messages(user: User, target: Channel) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None
}
if !has_permission(&user, &target) {
return None;
}
let col = database::get_collection("messages");
let result = col.find(
doc! { "channel": target.id },
None
).unwrap();
let col = database::get_collection("messages");
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!({
"id": message.id,
"author": message.author,
"content": message.content,
"edited": if let Some(t) = message.edited { Some(t.timestamp()) } else { None }
})
);
}
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!({
"id": message.id,
"author": message.author,
"content": message.content,
"edited": if let Some(t) = message.edited { Some(t.timestamp()) } else { None }
}));
}
Some(json!(messages))
Some(json!(messages))
}
#[derive(Serialize, Deserialize)]
pub struct SendMessage {
content: String,
nonce: String,
content: String,
nonce: String,
}
/// send a message to a channel
#[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
}
if !has_permission(&user, &target) {
return None;
}
let content: String = message.content.chars().take(2000).collect();
let nonce: String = message.nonce.chars().take(32).collect();
let content: String = message.content.chars().take(2000).collect();
let nonce: String = message.nonce.chars().take(32).collect();
let col = database::get_collection("messages");
if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).unwrap() {
return Some(
json!({
"success": false,
"error": "Message already sent!"
})
)
}
let id = Ulid::new().to_string();
Some(if col.insert_one(
doc! {
"_id": id.clone(),
"nonce": nonce.clone(),
"channel": target.id.clone(),
"author": user.id.clone(),
"content": content.clone(),
},
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();
}
websocket::queue_message(
get_recipients(&target),
json!({
"type": "message",
"data": {
"id": id.clone(),
"nonce": nonce,
"channel": target.id,
"author": user.id,
"content": content,
},
}).to_string()
);
json!({
"success": true,
"id": id
})
} else {
json!({
let col = database::get_collection("messages");
if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).unwrap() {
return Some(json!({
"success": false,
"error": "Failed database query."
})
})
"error": "Message already sent!"
}));
}
let id = Ulid::new().to_string();
Some(
if col
.insert_one(
doc! {
"_id": id.clone(),
"nonce": nonce.clone(),
"channel": target.id.clone(),
"author": user.id.clone(),
"content": content.clone(),
},
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();
}
websocket::queue_message(
get_recipients(&target),
json!({
"type": "message",
"data": {
"id": id.clone(),
"nonce": nonce,
"channel": target.id,
"author": user.id,
"content": content,
},
})
.to_string(),
);
json!({
"success": true,
"id": id
})
} else {
json!({
"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
if !has_permission(&user, &target) {
return None;
}
let prev =
// ! CHECK IF USER HAS PERMISSION TO VIEW EDITS OF MESSAGES
if let Some(previous) = message.previous_content {
@@ -226,132 +224,127 @@ pub fn get_message(user: User, target: Channel, message: Message) -> Option<Json
None
};
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,
})
)
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)]
pub struct EditMessage {
content: String,
content: String,
}
/// edit a message
#[patch("/<target>/messages/<message>", data = "<edit>")]
pub fn edit_message(user: User, target: Channel, message: Message, edit: Json<EditMessage>) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None
}
pub fn edit_message(
user: User,
target: Channel,
message: Message,
edit: Json<EditMessage>,
) -> Option<JsonValue> {
if !has_permission(&user, &target) {
return None;
}
Some(
if message.author != user.id {
json!({
"success": false,
"error": "You did not send this message."
})
} else {
let col = database::get_collection("messages");
Some(if message.author != user.id {
json!({
"success": false,
"error": "You did not send this message."
})
} else {
let col = database::get_collection("messages");
let time =
if let Some(edited) = message.edited {
edited.0
} else {
Ulid::from_string(&message.id).unwrap().datetime()
};
let time = if let Some(edited) = message.edited {
edited.0
} else {
Ulid::from_string(&message.id).unwrap().datetime()
};
let edited = Utc::now();
match col.update_one(
doc! { "_id": message.id.clone() },
doc! {
"$set": {
"content": edit.content.clone(),
"edited": UtcDatetime(edited.clone())
},
"$push": {
"previous_content": {
"content": message.content,
"time": time,
}
},
},
None
) {
Ok(_) => {
websocket::queue_message(
get_recipients(&target),
json!({
"type": "message_update",
"data": {
"id": message.id,
"channel": target.id,
"content": edit.content.clone(),
"edited": edited.timestamp()
},
}).to_string()
);
let edited = Utc::now();
match col.update_one(
doc! { "_id": message.id.clone() },
doc! {
"$set": {
"content": edit.content.clone(),
"edited": UtcDatetime(edited.clone())
},
"$push": {
"previous_content": {
"content": message.content,
"time": time,
}
},
},
None,
) {
Ok(_) => {
websocket::queue_message(
get_recipients(&target),
json!({
"type": "message_update",
"data": {
"id": message.id,
"channel": target.id,
"content": edit.content.clone(),
"edited": edited.timestamp()
},
})
.to_string(),
);
json!({
"success": true
})
},
Err(_) =>
json!({
"success": false,
"error": "Failed to update message."
})
}
}
)
json!({
"success": true
})
}
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
}
if !has_permission(&user, &target) {
return None;
}
Some(
if message.author != user.id {
json!({
"success": false,
"error": "You did not send this message."
})
} else {
let col = database::get_collection("messages");
Some(if message.author != user.id {
json!({
"success": false,
"error": "You did not send this message."
})
} else {
let col = database::get_collection("messages");
match col.delete_one(
doc! { "_id": message.id.clone() },
None
) {
Ok(_) => {
websocket::queue_message(
get_recipients(&target),
json!({
"type": "message_delete",
"data": {
"id": message.id,
"channel": target.id
},
}).to_string()
);
match col.delete_one(doc! { "_id": message.id.clone() }, None) {
Ok(_) => {
websocket::queue_message(
get_recipients(&target),
json!({
"type": "message_delete",
"data": {
"id": message.id,
"channel": target.id
},
})
.to_string(),
);
json!({
"success": true
})
},
Err(_) =>
json!({
"success": false,
"error": "Failed to delete message."
})
}
}
)
json!({
"success": true
})
}
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,16 +25,22 @@ 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");
let col = database::get_collection("guilds");
if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).unwrap() {
return json!({
"success": false,
"error": "Guild already created!"
})
let channels = database::get_collection("channels");
let col = database::get_collection("guilds");
if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).unwrap() {
return json!({
"success": false,
"error": "Guild already created!"
});
}
let channel_id = Ulid::new().to_string();
@@ -44,37 +50,43 @@ 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(
doc! {
"_id": id.clone(),
"nonce": nonce,
"name": name,
"description": description,
"owner": user.id.clone(),
"channels": [
channel_id.clone()
],
"members": [
user.id
],
"invites": [],
},
None
).is_ok() {
let id = Ulid::new().to_string();
if col
.insert_one(
doc! {
"_id": id.clone(),
"nonce": nonce,
"name": name,
"description": description,
"owner": user.id.clone(),
"channels": [
channel_id.clone()
],
"members": [
user.id
],
"invites": [],
},
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 ])
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])
}

View File

@@ -1,10 +1,10 @@
use rocket_contrib::json::{ JsonValue };
use bson::{ doc };
use bson::doc;
use rocket_contrib::json::JsonValue;
/// root
#[get("/")]
pub fn root() -> JsonValue {
json!({
"revolt": "0.0.1"
})
json!({
"revolt": "0.0.1"
})
}

View File

@@ -1,107 +1,109 @@
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
#[get("/@me")]
pub fn me(user: User) -> JsonValue {
json!({
"id": user.id,
"username": user.username,
"email": user.email,
"verified": user.email_verification.verified,
})
json!({
"id": user.id,
"username": user.username,
"email": user.email,
"verified": user.email_verification.verified,
})
}
/// retrieve another user's information
#[get("/<target>")]
pub fn user(user: User, target: User) -> JsonValue {
json!({
"id": target.id,
"username": target.username,
"relationship": get_relationship(&user, &target) as u8
})
json!({
"id": target.id,
"username": target.username,
"relationship": get_relationship(&user, &target) as u8
})
}
#[derive(Serialize, Deserialize)]
pub struct Query {
username: String,
username: String,
}
/// lookup a user on Revolt
/// currently only supports exact username searches
#[post("/lookup", data = "<query>")]
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(
doc! { "username": query.username.clone() },
FindOptions::builder().limit(10).build()
).expect("Failed user lookup");
let users = col
.find(
doc! { "username": query.username.clone() },
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!({
"id": u.id,
"username": u.username,
"relationship": get_relationship(&user, &u) as u8
})
);
}
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!({
"id": u.id,
"username": u.username,
"relationship": get_relationship(&user, &u) as u8
}));
}
json!(results)
json!(results)
}
/// retrieve all of your DMs
#[get("/@me/dms")]
pub fn dms(user: User) -> JsonValue {
let col = database::get_collection("channels");
let col = database::get_collection("channels");
let results = col.find(
doc! {
"$or": [
{
"type": channel::ChannelType::DM as i32
},
{
"type": channel::ChannelType::GROUPDM as i32
}
],
"recipients": user.id
},
None
).expect("Failed channel lookup");
let results = col
.find(
doc! {
"$or": [
{
"type": channel::ChannelType::DM as i32
},
{
"type": channel::ChannelType::GROUPDM as i32
}
],
"recipients": user.id
},
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.");
channels.push(
json!({
"id": channel.id,
"type": channel.channel_type,
"recipients": channel.recipients,
"active": channel.active.unwrap()
})
);
}
let mut channels = Vec::new();
for item in results {
let channel: Channel =
from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap channel.");
json!(channels)
channels.push(json!({
"id": channel.id,
"type": channel.channel_type,
"recipients": channel.recipients,
"active": channel.active.unwrap()
}));
}
json!(channels)
}
/// open a DM with a user
#[get("/<target>/dm")]
pub fn dm(user: User, target: User) -> JsonValue {
let col = database::get_collection("channels");
let col = database::get_collection("channels");
match col.find_one(
match col.find_one(
doc! { "type": channel::ChannelType::DM as i32, "recipients": { "$all": [ user.id.clone(), target.id.clone() ] } },
None
).expect("Failed channel lookup") {
@@ -132,231 +134,215 @@ pub fn dm(user: User, target: User) -> JsonValue {
}
enum Relationship {
FRIEND = 0,
OUTGOING = 1,
INCOMING = 2,
BLOCKED = 3,
BLOCKEDOTHER = 4,
NONE = 5,
SELF = 6,
FRIEND = 0,
OUTGOING = 1,
INCOMING = 2,
BLOCKED = 3,
BLOCKEDOTHER = 4,
NONE = 5,
SELF = 6,
}
fn get_relationship(a: &User, b: &User) -> Relationship {
if a.id == b.id {
return Relationship::SELF
}
if a.id == b.id {
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
}
}
}
}
}
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,
}
}
}
}
Relationship::NONE
Relationship::NONE
}
/// retrieve all of your friends
#[get("/@me/friend")]
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!({
"id": item.id,
"status": item.status
})
)
}
}
json!(results)
let mut results = Vec::new();
if let Some(arr) = user.relations {
for item in arr {
results.push(json!({
"id": item.id,
"status": item.status
}))
}
}
json!(results)
}
/// retrieve friend status with user
#[get("/<target>/friend")]
pub fn get_friend(user: User, target: User) -> JsonValue {
let relationship = get_relationship(&user, &target);
let relationship = get_relationship(&user, &target);
json!({
"id": target.id,
"status": relationship as u8
})
json!({
"id": target.id,
"status": relationship as u8
})
}
/// create or accept a friend request
#[put("/<target>/friend")]
pub fn add_friend(user: User, target: User) -> JsonValue {
let col = database::get_collection("users");
let relationship = get_relationship(&user, &target);
let col = database::get_collection("users");
let relationship = get_relationship(&user, &target);
match relationship {
Relationship::FRIEND =>
json!({
"success": false,
"error": "Already friends."
}),
Relationship::OUTGOING =>
json!({
"success": false,
"error": "Already sent a friend request."
}),
Relationship::INCOMING => {
col.update_one(
doc! {
"_id": user.id.clone(),
"relations.id": target.id.clone()
},
doc! {
"$set": {
"relations.$.status": Relationship::FRIEND as i32
}
},
None
).expect("Failed update query.");
col.update_one(
doc! {
"_id": target.id,
"relations.id": user.id
},
doc! {
"$set": {
"relations.$.status": Relationship::FRIEND as i32
}
},
None
).expect("Failed update query.");
match relationship {
Relationship::FRIEND => json!({
"success": false,
"error": "Already friends."
}),
Relationship::OUTGOING => json!({
"success": false,
"error": "Already sent a friend request."
}),
Relationship::INCOMING => {
col.update_one(
doc! {
"_id": user.id.clone(),
"relations.id": target.id.clone()
},
doc! {
"$set": {
"relations.$.status": Relationship::FRIEND as i32
}
},
None,
)
.expect("Failed update query.");
json!({
"success": true,
"status": Relationship::FRIEND as u8,
})
},
Relationship::BLOCKED =>
json!({
"success": false,
"error": "You have blocked this person."
}),
Relationship::BLOCKEDOTHER =>
json!({
"success": false,
"error": "You have been blocked by this person."
}),
Relationship::NONE => {
col.update_one(
doc! {
"_id": user.id.clone()
},
doc! {
"$push": {
"relations": {
"id": target.id.clone(),
"status": Relationship::OUTGOING as i32
}
}
},
None
).expect("Failed update query.");
col.update_one(
doc! {
"_id": target.id
},
doc! {
"$push": {
"relations": {
"id": user.id,
"status": Relationship::INCOMING as i32
}
}
},
None
).expect("Failed update query.");
col.update_one(
doc! {
"_id": target.id,
"relations.id": user.id
},
doc! {
"$set": {
"relations.$.status": Relationship::FRIEND as i32
}
},
None,
)
.expect("Failed update query.");
json!({
"success": true,
"status": Relationship::OUTGOING as u8,
})
},
Relationship::SELF =>
json!({
"success": false,
"error": "Cannot add yourself as a friend."
})
}
json!({
"success": true,
"status": Relationship::FRIEND as u8,
})
}
Relationship::BLOCKED => json!({
"success": false,
"error": "You have blocked this person."
}),
Relationship::BLOCKEDOTHER => json!({
"success": false,
"error": "You have been blocked by this person."
}),
Relationship::NONE => {
col.update_one(
doc! {
"_id": user.id.clone()
},
doc! {
"$push": {
"relations": {
"id": target.id.clone(),
"status": Relationship::OUTGOING as i32
}
}
},
None,
)
.expect("Failed update query.");
col.update_one(
doc! {
"_id": target.id
},
doc! {
"$push": {
"relations": {
"id": user.id,
"status": Relationship::INCOMING as i32
}
}
},
None,
)
.expect("Failed update query.");
json!({
"success": true,
"status": Relationship::OUTGOING as u8,
})
}
Relationship::SELF => json!({
"success": false,
"error": "Cannot add yourself as a friend."
}),
}
}
/// remove a friend or deny a request
#[delete("/<target>/friend")]
pub fn remove_friend(user: User, target: User) -> JsonValue {
let col = database::get_collection("users");
let relationship = get_relationship(&user, &target);
let col = database::get_collection("users");
let relationship = get_relationship(&user, &target);
match relationship {
Relationship::FRIEND |
Relationship::OUTGOING |
Relationship::INCOMING => {
col.update_one(
doc! {
"_id": user.id.clone()
},
doc! {
"$pull": {
"relations": {
"id": target.id.clone()
}
}
},
None
).expect("Failed update query.");
match relationship {
Relationship::FRIEND | Relationship::OUTGOING | Relationship::INCOMING => {
col.update_one(
doc! {
"_id": user.id.clone()
},
doc! {
"$pull": {
"relations": {
"id": target.id.clone()
}
}
},
None,
)
.expect("Failed update query.");
col.update_one(
doc! {
"_id": target.id
},
doc! {
"$pull": {
"relations": {
"id": user.id
}
}
},
None
).expect("Failed update query.");
col.update_one(
doc! {
"_id": target.id
},
doc! {
"$pull": {
"relations": {
"id": user.id
}
}
},
None,
)
.expect("Failed update query.");
json!({
"success": true
})
},
Relationship::BLOCKED |
Relationship::BLOCKEDOTHER |
Relationship::NONE |
Relationship::SELF =>
json!({
"success": false,
"error": "This has no effect."
})
}
json!({
"success": true
})
}
Relationship::BLOCKED
| Relationship::BLOCKEDOTHER
| Relationship::NONE
| Relationship::SELF => json!({
"success": false,
"error": "This has no effect."
}),
}
}