Run rust fmt.
This commit is contained in:
@@ -1,18 +1,18 @@
|
|||||||
use serde::{ Deserialize, Serialize };
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct Channel {
|
pub struct Channel {
|
||||||
#[serde(rename = "_id")]
|
#[serde(rename = "_id")]
|
||||||
pub id: String,
|
pub id: String,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type")]
|
||||||
pub channel_type: u8,
|
pub channel_type: u8,
|
||||||
|
|
||||||
pub last_message: Option<String>,
|
pub last_message: Option<String>,
|
||||||
|
|
||||||
// for Direct Messages
|
// for Direct Messages
|
||||||
pub recipients: Option<Vec<String>>,
|
pub recipients: Option<Vec<String>>,
|
||||||
pub active: Option<bool>,
|
pub active: Option<bool>,
|
||||||
|
|
||||||
// for Guilds
|
// for Guilds
|
||||||
pub name: Option<String>,
|
pub name: Option<String>,
|
||||||
|
|
||||||
|
|||||||
@@ -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 {
|
||||||
@@ -16,7 +16,7 @@ pub struct Invite {
|
|||||||
pub struct Guild {
|
pub struct Guild {
|
||||||
#[serde(rename = "_id")]
|
#[serde(rename = "_id")]
|
||||||
pub id: String,
|
pub id: String,
|
||||||
// pub nonce: String, used internally
|
// pub nonce: String, used internally
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub description: String,
|
pub description: String,
|
||||||
pub owner: String,
|
pub owner: String,
|
||||||
|
|||||||
@@ -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 {
|
||||||
@@ -10,13 +10,13 @@ pub struct PreviousEntry {
|
|||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct Message {
|
pub struct Message {
|
||||||
#[serde(rename = "_id")]
|
#[serde(rename = "_id")]
|
||||||
pub id: String,
|
pub id: String,
|
||||||
// pub nonce: String, used internally
|
// pub nonce: String, used internally
|
||||||
pub channel: String,
|
pub channel: String,
|
||||||
pub author: String,
|
pub author: String,
|
||||||
|
|
||||||
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>>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +1,30 @@
|
|||||||
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_connection() -> &'static Client {
|
pub fn get_connection() -> &'static Client {
|
||||||
DBCONN.get().unwrap()
|
DBCONN.get().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_db() -> Database {
|
pub fn get_db() -> Database {
|
||||||
get_connection().database("revolt")
|
get_connection().database("revolt")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_collection(collection: &str) -> Collection {
|
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;
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
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 {
|
||||||
pub verified: bool,
|
pub verified: bool,
|
||||||
pub target: Option<String>,
|
pub target: Option<String>,
|
||||||
pub expiry: Option<UtcDateTime>,
|
pub expiry: Option<UtcDateTime>,
|
||||||
pub rate_limit: Option<UtcDateTime>,
|
pub rate_limit: Option<UtcDateTime>,
|
||||||
pub code: Option<String>,
|
pub code: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct UserRelationship {
|
pub struct UserRelationship {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub status: u8,
|
pub status: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
@@ -21,9 +21,9 @@ pub struct User {
|
|||||||
#[serde(rename = "_id")]
|
#[serde(rename = "_id")]
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub username: String,
|
pub username: String,
|
||||||
pub password: String,
|
pub password: String,
|
||||||
pub access_token: Option<String>,
|
pub access_token: Option<String>,
|
||||||
pub email_verification: UserEmailVerification,
|
pub email_verification: UserEmailVerification,
|
||||||
pub relations: Option<Vec<UserRelationship>>,
|
pub relations: Option<Vec<UserRelationship>>,
|
||||||
}
|
}
|
||||||
|
|||||||
60
src/email.rs
60
src/email.rs
@@ -3,40 +3,48 @@ use std::collections::HashMap;
|
|||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
pub fn send_email(target: String, subject: String, body: String, html: String) -> Result<(), ()> {
|
pub fn send_email(target: String, subject: String, body: String, html: String) -> Result<(), ()> {
|
||||||
let mut map = HashMap::new();
|
let mut map = HashMap::new();
|
||||||
map.insert("target", target.clone());
|
map.insert("target", target.clone());
|
||||||
map.insert("subject", subject);
|
map.insert("subject", subject);
|
||||||
map.insert("body", body);
|
map.insert("body", body);
|
||||||
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
|
||||||
.json(&map)
|
.post("http://192.168.0.26:3838/send")
|
||||||
.send() {
|
.json(&map)
|
||||||
Ok(_) => Ok(()),
|
.send()
|
||||||
Err(_) => Err(())
|
{
|
||||||
}
|
Ok(_) => Ok(()),
|
||||||
|
Err(_) => Err(()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn public_uri() -> String {
|
fn public_uri() -> String {
|
||||||
env::var("PUBLIC_URI").expect("PUBLIC_URI not in environment variables!")
|
env::var("PUBLIC_URI").expect("PUBLIC_URI not in environment variables!")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn send_verification_email(email: String, code: String) -> bool {
|
pub fn send_verification_email(email: String, code: String) -> bool {
|
||||||
let url = format!("{}/api/account/verify/{}", public_uri(), code);
|
let url = format!("{}/api/account/verify/{}", public_uri(), code);
|
||||||
send_email(
|
send_email(
|
||||||
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 {
|
||||||
send_email(
|
send_email(
|
||||||
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()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -20,18 +20,20 @@ impl<'a, 'r> FromRequest<'a, 'r> for User {
|
|||||||
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
||||||
let keys: Vec<_> = request.headers().get("x-auth-token").collect();
|
let keys: Vec<_> = request.headers().get("x-auth-token").collect();
|
||||||
match keys.len() {
|
match keys.len() {
|
||||||
0 => Outcome::Failure((Status::Forbidden, AuthError::Missing)),
|
0 => Outcome::Failure((Status::Forbidden, AuthError::Missing)),
|
||||||
1 => {
|
1 => {
|
||||||
let key = keys[0];
|
let key = keys[0];
|
||||||
let col = database::get_db().collection("users");
|
let col = database::get_db().collection("users");
|
||||||
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(
|
||||||
} else {
|
from_bson(bson::Bson::Document(user)).expect("Failed to unwrap user."),
|
||||||
Outcome::Failure((Status::Forbidden, AuthError::Invalid))
|
)
|
||||||
}
|
} else {
|
||||||
},
|
Outcome::Failure((Status::Forbidden, AuthError::Invalid))
|
||||||
|
}
|
||||||
|
}
|
||||||
_ => Outcome::Failure((Status::BadRequest, AuthError::BadCount)),
|
_ => Outcome::Failure((Status::BadRequest, AuthError::BadCount)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -41,13 +43,15 @@ impl<'r> FromParam<'r> for User {
|
|||||||
type Error = &'r RawStr;
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
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."))
|
||||||
} else {
|
} else {
|
||||||
Err(param)
|
Err(param)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
@@ -11,14 +11,16 @@ impl<'r> FromParam<'r> for Channel {
|
|||||||
type Error = &'r RawStr;
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
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."))
|
||||||
} else {
|
} else {
|
||||||
Err(param)
|
Err(param)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,13 +28,15 @@ impl<'r> FromParam<'r> for Message {
|
|||||||
type Error = &'r RawStr;
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
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."))
|
||||||
} else {
|
} else {
|
||||||
Err(param)
|
Err(param)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
30
src/main.rs
30
src/main.rs
@@ -1,31 +1,33 @@
|
|||||||
#![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();
|
||||||
database::connect();
|
database::connect();
|
||||||
|
|
||||||
thread::spawn(|| {
|
thread::spawn(|| {
|
||||||
websocket::launch_server();
|
websocket::launch_server();
|
||||||
});
|
});
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,28 +1,28 @@
|
|||||||
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()
|
||||||
.sample_iter(&Alphanumeric)
|
.sample_iter(&Alphanumeric)
|
||||||
.take(l)
|
.take(l)
|
||||||
.collect::<String>()
|
.collect::<String>()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct Create {
|
pub struct Create {
|
||||||
username: String,
|
username: String,
|
||||||
password: String,
|
password: String,
|
||||||
email: String,
|
email: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// create a new Revolt account
|
/// create a new Revolt account
|
||||||
@@ -34,73 +34,79 @@ pub struct Create {
|
|||||||
/// (3) add user and send email verification
|
/// (3) add user and send email verification
|
||||||
#[post("/create", data = "<info>")]
|
#[post("/create", data = "<info>")]
|
||||||
pub fn create(info: Json<Create>) -> JsonValue {
|
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 {
|
if info.username.len() < 2 || info.username.len() > 32 {
|
||||||
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
|
||||||
return json!({
|
.find_one(doc! { "email": info.email.clone() }, None)
|
||||||
"success": false,
|
.expect("Failed user lookup")
|
||||||
"error": "Email already in use!",
|
{
|
||||||
})
|
return json!({
|
||||||
}
|
"success": false,
|
||||||
|
"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(
|
||||||
"_id": Ulid::new().to_string(),
|
doc! {
|
||||||
"email": info.email.clone(),
|
"_id": Ulid::new().to_string(),
|
||||||
"username": info.username.clone(),
|
"email": info.email.clone(),
|
||||||
"password": hashed,
|
"username": info.username.clone(),
|
||||||
"access_token": access_token,
|
"password": hashed,
|
||||||
"email_verification": {
|
"access_token": access_token,
|
||||||
"verified": false,
|
"email_verification": {
|
||||||
"target": info.email.clone(),
|
"verified": false,
|
||||||
"expiry": UtcDatetime(Utc::now() + chrono::Duration::days(1)),
|
"target": info.email.clone(),
|
||||||
"rate_limit": UtcDatetime(Utc::now() + chrono::Duration::minutes(1)),
|
"expiry": UtcDatetime(Utc::now() + chrono::Duration::days(1)),
|
||||||
"code": code.clone(),
|
"rate_limit": UtcDatetime(Utc::now() + chrono::Duration::minutes(1)),
|
||||||
}
|
"code": code.clone(),
|
||||||
}, None) {
|
}
|
||||||
Ok(_) => {
|
},
|
||||||
let sent = email::send_verification_email(info.email.clone(), code);
|
None,
|
||||||
|
) {
|
||||||
|
Ok(_) => {
|
||||||
|
let sent = email::send_verification_email(info.email.clone(), code);
|
||||||
|
|
||||||
json!({
|
json!({
|
||||||
"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!({
|
||||||
"success": false,
|
"success": false,
|
||||||
"error": "Failed to hash password!",
|
"error": "Failed to hash password!",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// verify an email for a Revolt account
|
/// verify an email for a Revolt account
|
||||||
@@ -109,57 +115,57 @@ pub fn create(info: Json<Create>) -> JsonValue {
|
|||||||
/// (3) set account as verified
|
/// (3) set account as verified
|
||||||
#[get("/verify/<code>")]
|
#[get("/verify/<code>")]
|
||||||
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)
|
||||||
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
|
.expect("Failed user lookup")
|
||||||
let ev = user.email_verification;
|
{
|
||||||
|
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() {
|
if Utc::now() > *ev.expiry.unwrap() {
|
||||||
json!({
|
json!({
|
||||||
"success": false,
|
"success": false,
|
||||||
"error": "Token has expired!",
|
"error": "Token has expired!",
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
let target = ev.target.unwrap();
|
let target = ev.target.unwrap();
|
||||||
col.update_one(
|
col.update_one(
|
||||||
doc! { "_id": user.id },
|
doc! { "_id": user.id },
|
||||||
doc! {
|
doc! {
|
||||||
"$unset": {
|
"$unset": {
|
||||||
"email_verification.code": "",
|
"email_verification.code": "",
|
||||||
"email_verification.expiry": "",
|
"email_verification.expiry": "",
|
||||||
"email_verification.target": "",
|
"email_verification.target": "",
|
||||||
"email_verification.rate_limit": "",
|
"email_verification.rate_limit": "",
|
||||||
},
|
},
|
||||||
"$set": {
|
"$set": {
|
||||||
"email_verification.verified": true,
|
"email_verification.verified": true,
|
||||||
"email": target.clone(),
|
"email": target.clone(),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
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
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
json!({
|
json!({
|
||||||
"success": false,
|
"success": false,
|
||||||
"error": "Invalid code!",
|
"error": "Invalid code!",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct Resend {
|
pub struct Resend {
|
||||||
email: String,
|
email: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// resend a verification email
|
/// resend a verification email
|
||||||
@@ -168,36 +174,41 @@ pub struct Resend {
|
|||||||
/// (3) resend the email
|
/// (3) resend the email
|
||||||
#[post("/resend", data = "<info>")]
|
#[post("/resend", data = "<info>")]
|
||||||
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(
|
||||||
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
|
doc! { "email_verification.target": info.email.clone() },
|
||||||
let ev = user.email_verification;
|
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 expiry = ev.expiry.unwrap();
|
||||||
let rate_limit = ev.rate_limit.unwrap();
|
let rate_limit = ev.rate_limit.unwrap();
|
||||||
|
|
||||||
if Utc::now() < *rate_limit {
|
if Utc::now() < *rate_limit {
|
||||||
json!({
|
json!({
|
||||||
"success": false,
|
"success": false,
|
||||||
"error": "Hit rate limit! Please try again in a minute or so.",
|
"error": "Hit rate limit! Please try again in a minute or so.",
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
let mut new_expiry = UtcDatetime(Utc::now() + chrono::Duration::days(1));
|
let mut new_expiry = UtcDatetime(Utc::now() + chrono::Duration::days(1));
|
||||||
if info.email.clone() != user.email {
|
if info.email.clone() != user.email {
|
||||||
if Utc::now() > *expiry {
|
if Utc::now() > *expiry {
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
let code = gen_token(48);
|
let code = gen_token(48);
|
||||||
col.update_one(
|
col.update_one(
|
||||||
doc! { "_id": user.id },
|
doc! { "_id": user.id },
|
||||||
doc! {
|
doc! {
|
||||||
"$set": {
|
"$set": {
|
||||||
@@ -209,31 +220,28 @@ 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(),
|
true => json!({
|
||||||
code,
|
"success": true,
|
||||||
) {
|
}),
|
||||||
true => json!({
|
false => json!({
|
||||||
"success": true,
|
"success": false,
|
||||||
}),
|
"error": "Failed to send email! Likely an issue with the backend API.",
|
||||||
false => json!({
|
}),
|
||||||
"success": false,
|
}
|
||||||
"error": "Failed to send email! Likely an issue with the backend API.",
|
}
|
||||||
})
|
} else {
|
||||||
}
|
json!({
|
||||||
}
|
"success": false,
|
||||||
} else {
|
"error": "Email not pending verification!",
|
||||||
json!({
|
})
|
||||||
"success": false,
|
}
|
||||||
"error": "Email not pending verification!",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct Login {
|
pub struct Login {
|
||||||
email: String,
|
email: String,
|
||||||
password: String,
|
password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// login to a Revolt account
|
/// login to a Revolt account
|
||||||
@@ -242,69 +250,73 @@ pub struct Login {
|
|||||||
/// (3) return access token
|
/// (3) return access token
|
||||||
#[post("/login", data = "<info>")]
|
#[post("/login", data = "<info>")]
|
||||||
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)
|
||||||
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
|
.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)
|
match verify(info.password.clone(), &user.password)
|
||||||
.expect("Failed to check hash of password.") {
|
.expect("Failed to check hash of password.")
|
||||||
true => {
|
{
|
||||||
let token =
|
true => {
|
||||||
match user.access_token {
|
let 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");
|
)
|
||||||
token
|
.expect("Failed to update user object");
|
||||||
}
|
token
|
||||||
};
|
}
|
||||||
|
};
|
||||||
|
|
||||||
json!({
|
json!({
|
||||||
"success": true,
|
"success": true,
|
||||||
"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!({
|
||||||
"success": false,
|
"success": false,
|
||||||
"error": "Email is not registered.",
|
"error": "Email is not registered.",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct Token {
|
pub struct Token {
|
||||||
token: String,
|
token: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// login to a Revolt account via token
|
/// login to a Revolt account via token
|
||||||
#[post("/token", data = "<info>")]
|
#[post("/token", data = "<info>")]
|
||||||
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)
|
||||||
json!({
|
.expect("Failed user lookup")
|
||||||
"success": true,
|
{
|
||||||
"id": u.get_str("_id").unwrap(),
|
json!({
|
||||||
})
|
"success": true,
|
||||||
} else {
|
"id": u.get_str("_id").unwrap(),
|
||||||
json!({
|
})
|
||||||
"success": false,
|
} else {
|
||||||
"error": "Invalid token!",
|
json!({
|
||||||
})
|
"success": false,
|
||||||
}
|
"error": "Invalid token!",
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 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)]
|
||||||
#[repr(usize)]
|
#[repr(usize)]
|
||||||
pub enum ChannelType {
|
pub enum ChannelType {
|
||||||
DM = 0,
|
DM = 0,
|
||||||
GROUPDM = 1,
|
GROUPDM = 1,
|
||||||
GUILDCHANNEL = 2,
|
GUILDCHANNEL = 2,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn has_permission(user: &User, target: &Channel) -> bool {
|
fn has_permission(user: &User, target: &Channel) -> bool {
|
||||||
match target.channel_type {
|
match target.channel_type {
|
||||||
0..=1 => {
|
0..=1 => {
|
||||||
if let Some(arr) = &target.recipients {
|
if let Some(arr) = &target.recipients {
|
||||||
for item in arr {
|
for item in arr {
|
||||||
if item == &user.id {
|
if item == &user.id {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// fetch channel information
|
/// fetch channel information
|
||||||
#[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),
|
}
|
||||||
}
|
))
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// delete channel
|
/// delete channel
|
||||||
@@ -64,152 +61,153 @@ pub fn channel(user: User, target: Channel) -> Option<JsonValue> {
|
|||||||
/// or close DM conversation
|
/// or close DM conversation
|
||||||
#[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");
|
||||||
Some(match target.channel_type {
|
Some(match target.channel_type {
|
||||||
0 => {
|
0 => {
|
||||||
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
|
}),
|
||||||
})
|
})
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// fetch channel messages
|
/// fetch channel messages
|
||||||
#[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))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct SendMessage {
|
pub struct SendMessage {
|
||||||
content: String,
|
content: String,
|
||||||
nonce: String,
|
nonce: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// send a message to a channel
|
/// send a message to a channel
|
||||||
#[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();
|
||||||
let nonce: String = message.nonce.chars().take(32).collect();
|
let nonce: String = message.nonce.chars().take(32).collect();
|
||||||
|
|
||||||
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,
|
|
||||||
"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,
|
"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 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 =
|
||||||
// ! CHECK IF USER HAS PERMISSION TO VIEW EDITS OF MESSAGES
|
// ! CHECK IF USER HAS PERMISSION TO VIEW EDITS OF MESSAGES
|
||||||
if let Some(previous) = message.previous_content {
|
if let Some(previous) = message.previous_content {
|
||||||
@@ -226,132 +224,127 @@ 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)]
|
||||||
pub struct EditMessage {
|
pub struct EditMessage {
|
||||||
content: String,
|
content: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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(
|
||||||
if !has_permission(&user, &target) {
|
user: User,
|
||||||
return None
|
target: Channel,
|
||||||
}
|
message: Message,
|
||||||
|
edit: Json<EditMessage>,
|
||||||
|
) -> Option<JsonValue> {
|
||||||
|
if !has_permission(&user, &target) {
|
||||||
|
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."
|
})
|
||||||
})
|
} 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()
|
};
|
||||||
};
|
|
||||||
|
|
||||||
let edited = Utc::now();
|
let edited = Utc::now();
|
||||||
match col.update_one(
|
match col.update_one(
|
||||||
doc! { "_id": message.id.clone() },
|
doc! { "_id": message.id.clone() },
|
||||||
doc! {
|
doc! {
|
||||||
"$set": {
|
"$set": {
|
||||||
"content": edit.content.clone(),
|
"content": edit.content.clone(),
|
||||||
"edited": UtcDatetime(edited.clone())
|
"edited": UtcDatetime(edited.clone())
|
||||||
},
|
},
|
||||||
"$push": {
|
"$push": {
|
||||||
"previous_content": {
|
"previous_content": {
|
||||||
"content": message.content,
|
"content": message.content,
|
||||||
"time": time,
|
"time": time,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
None
|
None,
|
||||||
) {
|
) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
websocket::queue_message(
|
websocket::queue_message(
|
||||||
get_recipients(&target),
|
get_recipients(&target),
|
||||||
json!({
|
json!({
|
||||||
"type": "message_update",
|
"type": "message_update",
|
||||||
"data": {
|
"data": {
|
||||||
"id": message.id,
|
"id": message.id,
|
||||||
"channel": target.id,
|
"channel": target.id,
|
||||||
"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."
|
})
|
||||||
})
|
} 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() },
|
Ok(_) => {
|
||||||
None
|
websocket::queue_message(
|
||||||
) {
|
get_recipients(&target),
|
||||||
Ok(_) => {
|
json!({
|
||||||
websocket::queue_message(
|
"type": "message_delete",
|
||||||
get_recipients(&target),
|
"data": {
|
||||||
json!({
|
"id": message.id,
|
||||||
"type": "message_delete",
|
"channel": target.id
|
||||||
"data": {
|
},
|
||||||
"id": message.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."
|
}),
|
||||||
})
|
}
|
||||||
}
|
})
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,16 +25,22 @@ 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");
|
||||||
let col = database::get_collection("guilds");
|
let col = database::get_collection("guilds");
|
||||||
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 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,37 +50,43 @@ 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
|
||||||
doc! {
|
.insert_one(
|
||||||
"_id": id.clone(),
|
doc! {
|
||||||
"nonce": nonce,
|
"_id": id.clone(),
|
||||||
"name": name,
|
"nonce": nonce,
|
||||||
"description": description,
|
"name": name,
|
||||||
"owner": user.id.clone(),
|
"description": description,
|
||||||
"channels": [
|
"owner": user.id.clone(),
|
||||||
channel_id.clone()
|
"channels": [
|
||||||
],
|
channel_id.clone()
|
||||||
"members": [
|
],
|
||||||
user.id
|
"members": [
|
||||||
],
|
user.id
|
||||||
"invites": [],
|
],
|
||||||
},
|
"invites": [],
|
||||||
None
|
},
|
||||||
).is_ok() {
|
None,
|
||||||
|
)
|
||||||
|
.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,
|
||||||
|
|||||||
@@ -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])
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
use rocket_contrib::json::{ JsonValue };
|
use bson::doc;
|
||||||
use bson::{ doc };
|
use rocket_contrib::json::JsonValue;
|
||||||
|
|
||||||
/// root
|
/// root
|
||||||
#[get("/")]
|
#[get("/")]
|
||||||
pub fn root() -> JsonValue {
|
pub fn root() -> JsonValue {
|
||||||
json!({
|
json!({
|
||||||
"revolt": "0.0.1"
|
"revolt": "0.0.1"
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 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
|
||||||
#[get("/@me")]
|
#[get("/@me")]
|
||||||
pub fn me(user: User) -> JsonValue {
|
pub fn me(user: User) -> JsonValue {
|
||||||
json!({
|
json!({
|
||||||
"id": user.id,
|
"id": user.id,
|
||||||
"username": user.username,
|
"username": user.username,
|
||||||
"email": user.email,
|
"email": user.email,
|
||||||
"verified": user.email_verification.verified,
|
"verified": user.email_verification.verified,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// retrieve another user's information
|
/// retrieve another user's information
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub fn user(user: User, target: User) -> JsonValue {
|
pub fn user(user: User, target: User) -> JsonValue {
|
||||||
json!({
|
json!({
|
||||||
"id": target.id,
|
"id": target.id,
|
||||||
"username": target.username,
|
"username": target.username,
|
||||||
"relationship": get_relationship(&user, &target) as u8
|
"relationship": get_relationship(&user, &target) as u8
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct Query {
|
pub struct Query {
|
||||||
username: String,
|
username: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// lookup a user on Revolt
|
/// lookup a user on Revolt
|
||||||
/// currently only supports exact username searches
|
/// currently only supports exact username searches
|
||||||
#[post("/lookup", data = "<query>")]
|
#[post("/lookup", data = "<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
|
||||||
doc! { "username": query.username.clone() },
|
.find(
|
||||||
FindOptions::builder().limit(10).build()
|
doc! { "username": query.username.clone() },
|
||||||
).expect("Failed user lookup");
|
FindOptions::builder().limit(10).build(),
|
||||||
|
)
|
||||||
|
.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)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// retrieve all of your DMs
|
/// retrieve all of your DMs
|
||||||
#[get("/@me/dms")]
|
#[get("/@me/dms")]
|
||||||
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
|
||||||
doc! {
|
.find(
|
||||||
"$or": [
|
doc! {
|
||||||
{
|
"$or": [
|
||||||
"type": channel::ChannelType::DM as i32
|
{
|
||||||
},
|
"type": channel::ChannelType::DM as i32
|
||||||
{
|
},
|
||||||
"type": channel::ChannelType::GROUPDM as i32
|
{
|
||||||
}
|
"type": channel::ChannelType::GROUPDM as i32
|
||||||
],
|
}
|
||||||
"recipients": user.id
|
],
|
||||||
},
|
"recipients": user.id
|
||||||
None
|
},
|
||||||
).expect("Failed channel lookup");
|
None,
|
||||||
|
)
|
||||||
|
.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(
|
|
||||||
json!({
|
|
||||||
"id": channel.id,
|
|
||||||
"type": channel.channel_type,
|
|
||||||
"recipients": channel.recipients,
|
|
||||||
"active": channel.active.unwrap()
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
/// open a DM with a user
|
||||||
#[get("/<target>/dm")]
|
#[get("/<target>/dm")]
|
||||||
pub fn dm(user: User, target: User) -> JsonValue {
|
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() ] } },
|
doc! { "type": channel::ChannelType::DM as i32, "recipients": { "$all": [ user.id.clone(), target.id.clone() ] } },
|
||||||
None
|
None
|
||||||
).expect("Failed channel lookup") {
|
).expect("Failed channel lookup") {
|
||||||
@@ -132,231 +134,215 @@ pub fn dm(user: User, target: User) -> JsonValue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
enum Relationship {
|
enum Relationship {
|
||||||
FRIEND = 0,
|
FRIEND = 0,
|
||||||
OUTGOING = 1,
|
OUTGOING = 1,
|
||||||
INCOMING = 2,
|
INCOMING = 2,
|
||||||
BLOCKED = 3,
|
BLOCKED = 3,
|
||||||
BLOCKEDOTHER = 4,
|
BLOCKEDOTHER = 4,
|
||||||
NONE = 5,
|
NONE = 5,
|
||||||
SELF = 6,
|
SELF = 6,
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Relationship::NONE
|
Relationship::NONE
|
||||||
}
|
}
|
||||||
|
|
||||||
/// retrieve all of your friends
|
/// retrieve all of your friends
|
||||||
#[get("/@me/friend")]
|
#[get("/@me/friend")]
|
||||||
pub fn get_friends(user: User) -> JsonValue {
|
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
|
}))
|
||||||
})
|
}
|
||||||
)
|
}
|
||||||
}
|
|
||||||
}
|
json!(results)
|
||||||
|
|
||||||
json!(results)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// retrieve friend status with user
|
/// retrieve friend status with user
|
||||||
#[get("/<target>/friend")]
|
#[get("/<target>/friend")]
|
||||||
pub fn get_friend(user: User, target: User) -> JsonValue {
|
pub fn get_friend(user: User, target: User) -> JsonValue {
|
||||||
let relationship = get_relationship(&user, &target);
|
let relationship = get_relationship(&user, &target);
|
||||||
|
|
||||||
json!({
|
json!({
|
||||||
"id": target.id,
|
"id": target.id,
|
||||||
"status": relationship as u8
|
"status": relationship as u8
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// create or accept a friend request
|
/// create or accept a friend request
|
||||||
#[put("/<target>/friend")]
|
#[put("/<target>/friend")]
|
||||||
pub fn add_friend(user: User, target: User) -> JsonValue {
|
pub fn add_friend(user: User, target: User) -> JsonValue {
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
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 => json!({
|
||||||
Relationship::OUTGOING =>
|
"success": false,
|
||||||
json!({
|
"error": "Already sent a friend request."
|
||||||
"success": false,
|
}),
|
||||||
"error": "Already sent a friend request."
|
Relationship::INCOMING => {
|
||||||
}),
|
col.update_one(
|
||||||
Relationship::INCOMING => {
|
doc! {
|
||||||
col.update_one(
|
"_id": user.id.clone(),
|
||||||
doc! {
|
"relations.id": target.id.clone()
|
||||||
"_id": user.id.clone(),
|
},
|
||||||
"relations.id": target.id.clone()
|
doc! {
|
||||||
},
|
"$set": {
|
||||||
doc! {
|
"relations.$.status": Relationship::FRIEND as i32
|
||||||
"$set": {
|
}
|
||||||
"relations.$.status": Relationship::FRIEND as i32
|
},
|
||||||
}
|
None,
|
||||||
},
|
)
|
||||||
None
|
.expect("Failed update query.");
|
||||||
).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!({
|
col.update_one(
|
||||||
"success": true,
|
doc! {
|
||||||
"status": Relationship::FRIEND as u8,
|
"_id": target.id,
|
||||||
})
|
"relations.id": user.id
|
||||||
},
|
},
|
||||||
Relationship::BLOCKED =>
|
doc! {
|
||||||
json!({
|
"$set": {
|
||||||
"success": false,
|
"relations.$.status": Relationship::FRIEND as i32
|
||||||
"error": "You have blocked this person."
|
}
|
||||||
}),
|
},
|
||||||
Relationship::BLOCKEDOTHER =>
|
None,
|
||||||
json!({
|
)
|
||||||
"success": false,
|
.expect("Failed update query.");
|
||||||
"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!({
|
json!({
|
||||||
"success": true,
|
"success": true,
|
||||||
"status": Relationship::OUTGOING as u8,
|
"status": Relationship::FRIEND as u8,
|
||||||
})
|
})
|
||||||
},
|
}
|
||||||
Relationship::SELF =>
|
Relationship::BLOCKED => json!({
|
||||||
json!({
|
"success": false,
|
||||||
"success": false,
|
"error": "You have blocked this person."
|
||||||
"error": "Cannot add yourself as a friend."
|
}),
|
||||||
})
|
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
|
/// remove a friend or deny a request
|
||||||
#[delete("/<target>/friend")]
|
#[delete("/<target>/friend")]
|
||||||
pub fn remove_friend(user: User, target: User) -> JsonValue {
|
pub fn remove_friend(user: User, target: User) -> JsonValue {
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
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 |
|
col.update_one(
|
||||||
Relationship::INCOMING => {
|
doc! {
|
||||||
col.update_one(
|
"_id": user.id.clone()
|
||||||
doc! {
|
},
|
||||||
"_id": user.id.clone()
|
doc! {
|
||||||
},
|
"$pull": {
|
||||||
doc! {
|
"relations": {
|
||||||
"$pull": {
|
"id": target.id.clone()
|
||||||
"relations": {
|
}
|
||||||
"id": target.id.clone()
|
}
|
||||||
}
|
},
|
||||||
}
|
None,
|
||||||
},
|
)
|
||||||
None
|
.expect("Failed update query.");
|
||||||
).expect("Failed update query.");
|
|
||||||
|
|
||||||
col.update_one(
|
col.update_one(
|
||||||
doc! {
|
doc! {
|
||||||
"_id": target.id
|
"_id": target.id
|
||||||
},
|
},
|
||||||
doc! {
|
doc! {
|
||||||
"$pull": {
|
"$pull": {
|
||||||
"relations": {
|
"relations": {
|
||||||
"id": user.id
|
"id": user.id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
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."
|
}),
|
||||||
})
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,138 +2,147 @@ 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,
|
||||||
out: Sender,
|
out: Sender,
|
||||||
}
|
}
|
||||||
|
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
static mut CLIENTS: OnceCell<RwLock<HashMap<String, Vec<Cell>>>> = OnceCell::new();
|
static mut CLIENTS: OnceCell<RwLock<HashMap<String, Vec<Cell>>>> = OnceCell::new();
|
||||||
|
|
||||||
struct Server {
|
struct Server {
|
||||||
out: Sender,
|
out: Sender,
|
||||||
id: Option<String>,
|
id: Option<String>,
|
||||||
internal: String,
|
internal: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Handler for Server {
|
impl Handler for Server {
|
||||||
fn on_open(&mut self, _: Handshake) -> Result<()> {
|
fn on_open(&mut self, _: Handshake) -> Result<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_message(&mut self, msg: Message) -> Result<()> {
|
fn on_message(&mut self, msg: Message) -> Result<()> {
|
||||||
if let Message::Text(text) = msg {
|
if let Message::Text(text) = msg {
|
||||||
let data: Value = from_str(&text).unwrap();
|
let data: Value = from_str(&text).unwrap();
|
||||||
|
|
||||||
if let Value::String(packet_type) = &data["type"] {
|
if let Value::String(packet_type) = &data["type"] {
|
||||||
match packet_type.as_str() {
|
match packet_type.as_str() {
|
||||||
"authenticate" => {
|
"authenticate" => {
|
||||||
if let Some(_) = self.id {
|
if let Some(_) = self.id {
|
||||||
self.out.send(
|
self.out.send(
|
||||||
json!({
|
json!({
|
||||||
"type": "authenticate",
|
"type": "authenticate",
|
||||||
"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(
|
|
||||||
doc! { "access_token": token },
|
|
||||||
None
|
|
||||||
).unwrap() {
|
|
||||||
Some(u) => {
|
|
||||||
let id = u.get_str("_id").expect("Missing id.");
|
|
||||||
|
|
||||||
unsafe {
|
match col.find_one(doc! { "access_token": token }, None).unwrap() {
|
||||||
let mut map = CLIENTS.get_mut().unwrap().write().unwrap();
|
Some(u) => {
|
||||||
let cell = Cell { id: self.internal.clone(), out: self.out.clone() };
|
let id = u.get_str("_id").expect("Missing id.");
|
||||||
if map.contains_key(&id.to_string()) {
|
|
||||||
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);
|
unsafe {
|
||||||
|
let mut map = CLIENTS.get_mut().unwrap().write().unwrap();
|
||||||
|
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);
|
||||||
|
} else {
|
||||||
|
map.insert(id.to_string(), vec![cell]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
self.id = Some(id.to_string());
|
println!(
|
||||||
self.out.send(
|
"Websocket client connected. [ID: {} // {}]",
|
||||||
json!({
|
id.to_string(),
|
||||||
"type": "authenticate",
|
self.internal
|
||||||
"success": true
|
);
|
||||||
})
|
|
||||||
.to_string()
|
self.id = Some(id.to_string());
|
||||||
)
|
self.out.send(
|
||||||
},
|
json!({
|
||||||
None =>
|
"type": "authenticate",
|
||||||
self.out.send(
|
"success": true
|
||||||
json!({
|
})
|
||||||
"type": "authenticate",
|
.to_string(),
|
||||||
"success": false,
|
)
|
||||||
"error": "Invalid authentication token."
|
}
|
||||||
})
|
None => self.out.send(
|
||||||
.to_string()
|
json!({
|
||||||
)
|
"type": "authenticate",
|
||||||
}
|
"success": false,
|
||||||
} else {
|
"error": "Invalid authentication token."
|
||||||
self.out.send(
|
})
|
||||||
json!({
|
.to_string(),
|
||||||
"type": "authenticate",
|
),
|
||||||
"success": false,
|
}
|
||||||
"error": "Missing authentication token."
|
} else {
|
||||||
})
|
self.out.send(
|
||||||
.to_string()
|
json!({
|
||||||
)
|
"type": "authenticate",
|
||||||
}
|
"success": false,
|
||||||
},
|
"error": "Missing authentication token."
|
||||||
_ => Ok(())
|
})
|
||||||
}
|
.to_string(),
|
||||||
} else {
|
)
|
||||||
Ok(())
|
}
|
||||||
}
|
}
|
||||||
} else {
|
_ => Ok(()),
|
||||||
Ok(())
|
}
|
||||||
}
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_close(&mut self, code: CloseCode, reason: &str) {
|
fn on_close(&mut self, code: CloseCode, reason: &str) {
|
||||||
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!(
|
||||||
unsafe {
|
"Websocket client disconnected. [ID: {} // {}]",
|
||||||
let mut map = CLIENTS.get_mut().unwrap().write().unwrap();
|
id, self.internal
|
||||||
let arr = map.get_mut(&id.clone()).unwrap();
|
);
|
||||||
|
unsafe {
|
||||||
|
let mut map = CLIENTS.get_mut().unwrap().write().unwrap();
|
||||||
|
let arr = map.get_mut(&id.clone()).unwrap();
|
||||||
|
|
||||||
if arr.len() == 1 {
|
if arr.len() == 1 {
|
||||||
map.remove(&id.clone());
|
map.remove(&id.clone());
|
||||||
} 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()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_error(&mut self, err: Error) {
|
fn on_error(&mut self, err: Error) {
|
||||||
@@ -142,37 +151,43 @@ impl Handler for Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn launch_server() {
|
pub fn launch_server() {
|
||||||
unsafe {
|
unsafe {
|
||||||
if let Err(_) = CLIENTS.set(RwLock::new(HashMap::new())) {
|
if let Err(_) = CLIENTS.set(RwLock::new(HashMap::new())) {
|
||||||
panic!("Failed to set CLIENTS map!");
|
panic!("Failed to set CLIENTS map!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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<(), ()> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let map = CLIENTS.get().unwrap().read().unwrap();
|
let map = CLIENTS.get().unwrap().read().unwrap();
|
||||||
if map.contains_key(&id) {
|
if map.contains_key(&id) {
|
||||||
let arr = map.get(&id).unwrap();
|
let arr = map.get(&id).unwrap();
|
||||||
|
|
||||||
for item in arr {
|
for item in arr {
|
||||||
if let Err(_) = item.out.send(message.clone()) {
|
if let Err(_) = item.out.send(message.clone()) {
|
||||||
return Err(());
|
return Err(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ! TODO: WRITE THREADED QUEUE SYSTEM
|
// ! TODO: WRITE THREADED QUEUE SYSTEM
|
||||||
// ! FETCH RECIPIENTS HERE INSTEAD OF IN METHOD
|
// ! FETCH RECIPIENTS HERE INSTEAD OF IN METHOD
|
||||||
|
|
||||||
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");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user