Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d95982fb54 | ||
|
|
17c9148556 | ||
|
|
6a1912c27b | ||
|
|
fa6ed75ed8 | ||
|
|
b0f8abef33 | ||
|
|
6f065b7575 | ||
|
|
5e59c553f3 | ||
|
|
c271054613 | ||
|
|
d99c87d6da | ||
|
|
211a8c8ec2 | ||
|
|
ef76ed25fa | ||
|
|
b687190105 | ||
|
|
fc03dd2cdb | ||
|
|
188fe30dbf | ||
|
|
2095a2982b | ||
|
|
3bca53c6a8 | ||
|
|
0bd711aa57 | ||
|
|
2851fbca25 | ||
|
|
d6c7b7465e | ||
|
|
33f3bac4b8 | ||
|
|
0a027b68e0 | ||
|
|
50ef5c43c7 | ||
|
|
8043690d38 | ||
|
|
0f793f84a2 | ||
|
|
577f25642e | ||
|
|
4fbd6c816d |
@@ -1,3 +1,4 @@
|
|||||||
|
Rocket.toml
|
||||||
/target
|
/target
|
||||||
**/*.rs.bk
|
**/*.rs.bk
|
||||||
.env
|
.env
|
||||||
|
|||||||
Generated
+1492
-1155
File diff suppressed because it is too large
Load Diff
+4
-3
@@ -1,14 +1,13 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt"
|
name = "revolt"
|
||||||
version = "0.1.0"
|
version = "0.2.3"
|
||||||
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
mongodb = "0.9.2"
|
mongodb = { version = "1.1.0-beta", default-features = false, features = ["sync"] } # FIXME: rewrite database with async API
|
||||||
bson = "0.14.1"
|
|
||||||
rocket = { version = "0.4.4", default-features = false }
|
rocket = { version = "0.4.4", default-features = false }
|
||||||
once_cell = "1.3.1"
|
once_cell = "1.3.1"
|
||||||
dotenv = "0.15.0"
|
dotenv = "0.15.0"
|
||||||
@@ -27,3 +26,5 @@ hashbrown = "0.7.1"
|
|||||||
serde_json = "1.0.51"
|
serde_json = "1.0.51"
|
||||||
rocket_cors = "0.5.2"
|
rocket_cors = "0.5.2"
|
||||||
bitfield = "0.13.2"
|
bitfield = "0.13.2"
|
||||||
|
lru = "0.5.3"
|
||||||
|
lazy_static = "1.4.0"
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|

|
||||||
|
|
||||||
|
Delta is a **blazing fast API server** built with Rust for the REVOLT platform.
|
||||||
|
|
||||||
|
Features:
|
||||||
|
- Robust and efficient API routes for running a chat platform.
|
||||||
|
- Distributed notification system, allowing any node to be seamlessly connected.
|
||||||
|
- Simple deployment, based mostly on pure Rust code and libraries.
|
||||||
|
- Hooks up to a MongoDB deployment, provide URI and no extra work needed.
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
[development]
|
|
||||||
address = "192.168.0.10"
|
|
||||||
port = 5500
|
|
||||||
|
|
||||||
[production]
|
|
||||||
address = "192.168.0.10"
|
|
||||||
port = 5500
|
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 3.9 KiB |
+151
-10
@@ -1,33 +1,174 @@
|
|||||||
|
use super::get_collection;
|
||||||
|
|
||||||
|
use lru::LruCache;
|
||||||
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
|
use rocket::http::RawStr;
|
||||||
|
use rocket::request::FromParam;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct LastMessage {
|
pub struct LastMessage {
|
||||||
|
// message id
|
||||||
id: String,
|
id: String,
|
||||||
|
// author's id
|
||||||
user_id: String,
|
user_id: String,
|
||||||
|
// truncated content with author's name prepended (for GDM / GUILD)
|
||||||
short_content: String,
|
short_content: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
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,
|
||||||
|
|
||||||
// for Direct Messages
|
// DM: whether the DM is active
|
||||||
pub active: Option<bool>,
|
pub active: Option<bool>,
|
||||||
|
// DM + GDM: last message in channel
|
||||||
// for DMs / GDMs
|
|
||||||
pub last_message: Option<LastMessage>,
|
pub last_message: Option<LastMessage>,
|
||||||
|
// DM + GDM: recipients for channel
|
||||||
pub recipients: Option<Vec<String>>,
|
pub recipients: Option<Vec<String>>,
|
||||||
|
// GDM: owner of group
|
||||||
// for GDMs
|
|
||||||
pub owner: Option<String>,
|
pub owner: Option<String>,
|
||||||
|
// GUILD: channel parent
|
||||||
// for Guilds
|
|
||||||
pub guild: Option<String>,
|
pub guild: Option<String>,
|
||||||
|
// GUILD + GDM: channel name
|
||||||
// for Guilds and Group DMs
|
|
||||||
pub name: Option<String>,
|
pub name: Option<String>,
|
||||||
|
// GUILD + GDM: channel description
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
static ref CACHE: Arc<Mutex<LruCache<String, Channel>>> =
|
||||||
|
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
||||||
|
{
|
||||||
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
|
let existing = cache.get(&id.to_string());
|
||||||
|
|
||||||
|
if let Some(channel) = existing {
|
||||||
|
return Ok(Some((*channel).clone()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err("Failed to lock cache.".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let col = get_collection("channels");
|
||||||
|
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
if let Ok(channel) = from_bson(Bson::Document(doc)) as Result<Channel, _> {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
cache.put(id.to_string(), channel.clone());
|
||||||
|
|
||||||
|
Ok(Some(channel))
|
||||||
|
} else {
|
||||||
|
Err("Failed to deserialize channel!".to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err("Failed to fetch channel from database.".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String> {
|
||||||
|
let mut missing = vec![];
|
||||||
|
let mut channels = vec![];
|
||||||
|
|
||||||
|
{
|
||||||
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
|
for gid in ids {
|
||||||
|
let existing = cache.get(gid);
|
||||||
|
|
||||||
|
if let Some(channel) = existing {
|
||||||
|
channels.push((*channel).clone());
|
||||||
|
} else {
|
||||||
|
missing.push(gid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err("Failed to lock cache.".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if missing.len() == 0 {
|
||||||
|
return Ok(Some(channels));
|
||||||
|
}
|
||||||
|
|
||||||
|
let col = get_collection("channels");
|
||||||
|
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
||||||
|
for item in result {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
if let Ok(doc) = item {
|
||||||
|
if let Ok(channel) = from_bson(Bson::Document(doc)) as Result<Channel, _> {
|
||||||
|
cache.put(channel.id.clone(), channel.clone());
|
||||||
|
channels.push(channel);
|
||||||
|
} else {
|
||||||
|
return Err("Failed to deserialize channel!".to_string());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err("Failed to fetch channel.".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Some(channels))
|
||||||
|
} else {
|
||||||
|
Err("Failed to fetch channel from database.".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'r> FromParam<'r> for Channel {
|
||||||
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
|
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||||
|
if let Ok(result) = fetch_channel(param) {
|
||||||
|
if let Some(channel) = result {
|
||||||
|
Ok(channel)
|
||||||
|
} else {
|
||||||
|
Err(param)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err(param)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*pub fn test() {
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
let now = Instant::now();
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
println!("I'm about to write 4 million entries to cache.");
|
||||||
|
for i in 0..4_000_000 {
|
||||||
|
let c = Channel {
|
||||||
|
id: "potato".to_string(),
|
||||||
|
channel_type: 0,
|
||||||
|
|
||||||
|
active: None,
|
||||||
|
last_message: None,
|
||||||
|
description: None,
|
||||||
|
guild: None,
|
||||||
|
name: None,
|
||||||
|
owner: None,
|
||||||
|
recipients: None
|
||||||
|
};
|
||||||
|
|
||||||
|
cache.put(format!("{}", i), c);
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("It took {} seconds, roughly {}ms per entry.", now.elapsed().as_secs_f64(), now.elapsed().as_millis() as f64 / 1_000_000.0);
|
||||||
|
|
||||||
|
let now = Instant::now();
|
||||||
|
println!("Now I'm going to read every entry and immediately dispose of it.");
|
||||||
|
for i in 0..4_000_000 {
|
||||||
|
cache.get(&format!("{}", i));
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("It took {} seconds, roughly {}ms per entry.", now.elapsed().as_secs_f64(), now.elapsed().as_millis() as f64 / 1_000_000.0);
|
||||||
|
}*/
|
||||||
|
|||||||
+141
-6
@@ -1,20 +1,26 @@
|
|||||||
use bson::doc;
|
use super::get_collection;
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
use lru::LruCache;
|
||||||
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
|
use rocket::http::RawStr;
|
||||||
|
use rocket::request::FromParam;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct MemberRef {
|
pub struct MemberRef {
|
||||||
pub guild: String,
|
pub guild: String,
|
||||||
pub user: String,
|
pub user: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct Member {
|
pub struct Member {
|
||||||
#[serde(rename = "_id")]
|
#[serde(rename = "_id")]
|
||||||
pub id: MemberRef,
|
pub id: MemberRef,
|
||||||
pub nickname: Option<String>,
|
pub nickname: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct Invite {
|
pub struct Invite {
|
||||||
pub code: String,
|
pub code: String,
|
||||||
pub creator: String,
|
pub creator: String,
|
||||||
@@ -27,7 +33,7 @@ pub struct Ban {
|
|||||||
pub reason: String,
|
pub reason: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct Guild {
|
pub struct Guild {
|
||||||
#[serde(rename = "_id")]
|
#[serde(rename = "_id")]
|
||||||
pub id: String,
|
pub id: String,
|
||||||
@@ -41,3 +47,132 @@ pub struct Guild {
|
|||||||
|
|
||||||
pub default_permissions: u32,
|
pub default_permissions: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
static ref CACHE: Arc<Mutex<LruCache<String, Guild>>> =
|
||||||
|
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
||||||
|
{
|
||||||
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
|
let existing = cache.get(&id.to_string());
|
||||||
|
|
||||||
|
if let Some(guild) = existing {
|
||||||
|
return Ok(Some((*guild).clone()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err("Failed to lock cache.".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let col = get_collection("guilds");
|
||||||
|
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
if let Ok(guild) = from_bson(Bson::Document(doc)) as Result<Guild, _> {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
cache.put(id.to_string(), guild.clone());
|
||||||
|
|
||||||
|
Ok(Some(guild))
|
||||||
|
} else {
|
||||||
|
Err("Failed to deserialize guild!".to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err("Failed to fetch guild from database.".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'r> FromParam<'r> for Guild {
|
||||||
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
|
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||||
|
if let Ok(result) = fetch_guild(param) {
|
||||||
|
if let Some(channel) = result {
|
||||||
|
Ok(channel)
|
||||||
|
} else {
|
||||||
|
Err(param)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err(param)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_member(guild_id: &String, member: &String) -> Option<Member> {
|
||||||
|
if let Ok(result) = get_collection("members").find_one(
|
||||||
|
doc! {
|
||||||
|
"_id.guild": &guild_id,
|
||||||
|
"_id.user": &member,
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
) {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
Some(from_bson(Bson::Document(doc)).expect("Failed to unwrap member."))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_invite<U: Into<Option<String>>>(
|
||||||
|
code: &String,
|
||||||
|
user: U,
|
||||||
|
) -> Option<(String, String, Invite)> {
|
||||||
|
let mut doc = doc! {
|
||||||
|
"invites": {
|
||||||
|
"$elemMatch": {
|
||||||
|
"code": &code
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(user_id) = user.into() {
|
||||||
|
doc.insert(
|
||||||
|
"bans",
|
||||||
|
doc! {
|
||||||
|
"$not": {
|
||||||
|
"$elemMatch": {
|
||||||
|
"id": user_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(result) = get_collection("guilds").find_one(
|
||||||
|
doc,
|
||||||
|
mongodb::options::FindOneOptions::builder()
|
||||||
|
.projection(doc! {
|
||||||
|
"_id": 1,
|
||||||
|
"name": 1,
|
||||||
|
"invites.$": 1,
|
||||||
|
})
|
||||||
|
.build(),
|
||||||
|
) {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
let invite = doc
|
||||||
|
.get_array("invites")
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.as_document()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
Some((
|
||||||
|
doc.get_str("_id").unwrap().to_string(),
|
||||||
|
doc.get_str("name").unwrap().to_string(),
|
||||||
|
from_bson(Bson::Document(invite.clone())).unwrap(),
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+88
-5
@@ -1,26 +1,109 @@
|
|||||||
use bson::UtcDateTime;
|
use super::get_collection;
|
||||||
|
use crate::database::channel::Channel;
|
||||||
|
use crate::notifications;
|
||||||
|
use crate::notifications::events::message::Create;
|
||||||
|
use crate::notifications::events::Notification;
|
||||||
|
use crate::routes::channel::ChannelType;
|
||||||
|
|
||||||
|
use mongodb::bson::from_bson;
|
||||||
|
use mongodb::bson::{doc, to_bson, Bson, DateTime};
|
||||||
|
use rocket::http::RawStr;
|
||||||
|
use rocket::request::FromParam;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct PreviousEntry {
|
pub struct PreviousEntry {
|
||||||
pub content: String,
|
pub content: String,
|
||||||
pub time: UtcDateTime,
|
pub time: DateTime,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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: Option<String>,
|
||||||
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<DateTime>,
|
||||||
|
|
||||||
pub previous_content: Option<Vec<PreviousEntry>>,
|
pub previous_content: Vec<PreviousEntry>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// ? TODO: write global send message
|
// ? TODO: write global send message
|
||||||
// ? pub fn send_message();
|
// ? pub fn send_message();
|
||||||
// ? handle websockets?
|
// ? handle websockets?
|
||||||
|
impl Message {
|
||||||
|
pub fn send(&self, target: &Channel) -> bool {
|
||||||
|
if get_collection("messages")
|
||||||
|
.insert_one(to_bson(&self).unwrap().as_document().unwrap().clone(), None)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
notifications::send_message_given_channel(
|
||||||
|
Notification::message_create(Create {
|
||||||
|
id: self.id.clone(),
|
||||||
|
nonce: self.nonce.clone(),
|
||||||
|
channel: self.channel.clone(),
|
||||||
|
author: self.author.clone(),
|
||||||
|
content: self.content.clone(),
|
||||||
|
}),
|
||||||
|
&target,
|
||||||
|
);
|
||||||
|
|
||||||
|
let short_content: String = self.content.chars().take(24).collect();
|
||||||
|
|
||||||
|
// !! this stuff can be async
|
||||||
|
if target.channel_type == ChannelType::DM as u8
|
||||||
|
|| target.channel_type == ChannelType::GROUPDM as u8
|
||||||
|
{
|
||||||
|
let mut update = doc! {
|
||||||
|
"$set": {
|
||||||
|
"last_message": {
|
||||||
|
"id": &self.id,
|
||||||
|
"user_id": &self.author,
|
||||||
|
"short_content": short_content,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if target.channel_type == ChannelType::DM as u8 {
|
||||||
|
update
|
||||||
|
.get_document_mut("$set")
|
||||||
|
.unwrap()
|
||||||
|
.insert("active", true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if get_collection("channels")
|
||||||
|
.update_one(doc! { "_id": &target.id }, update, None)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'r> FromParam<'r> for Message {
|
||||||
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
|
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||||
|
let col = get_collection("messages");
|
||||||
|
let result = col
|
||||||
|
.find_one(doc! { "_id": param.to_string() }, None)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
if let Some(message) = result {
|
||||||
|
Ok(from_bson(Bson::Document(message)).expect("Failed to unwrap message."))
|
||||||
|
} else {
|
||||||
|
Err(param)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+8
-1
@@ -1,4 +1,5 @@
|
|||||||
use mongodb::{Client, Collection, Database};
|
use mongodb::bson::doc;
|
||||||
|
use mongodb::sync::{Client, Collection, Database};
|
||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
@@ -9,6 +10,12 @@ pub fn connect() {
|
|||||||
Client::with_uri_str(&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.");
|
||||||
|
|
||||||
|
client
|
||||||
|
.database("revolt")
|
||||||
|
.collection("migrations")
|
||||||
|
.find(doc! {}, None)
|
||||||
|
.expect("Failed to get migration data from database.");
|
||||||
|
|
||||||
DBCONN.set(client).unwrap();
|
DBCONN.set(client).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use super::{get_collection, MemberPermissions};
|
use super::{get_collection, MemberPermissions};
|
||||||
|
|
||||||
use bson::doc;
|
use mongodb::bson::doc;
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::FindOptions;
|
||||||
|
|
||||||
pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
||||||
@@ -111,7 +111,7 @@ pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bo
|
|||||||
|
|
||||||
let permissions = guild.get_i32("default_permissions").unwrap() as u32;
|
let permissions = guild.get_i32("default_permissions").unwrap() as u32;
|
||||||
|
|
||||||
if MemberPermissions([ permissions ]).get_send_direct_messages() {
|
if MemberPermissions([permissions]).get_send_direct_messages() {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-10
@@ -1,9 +1,8 @@
|
|||||||
use super::mutual::has_mutual_connection;
|
use super::mutual::has_mutual_connection;
|
||||||
use crate::database::guild::Member;
|
use crate::database::channel::Channel;
|
||||||
|
use crate::database::guild::{fetch_guild, get_member, Guild, Member};
|
||||||
use crate::database::user::UserRelationship;
|
use crate::database::user::UserRelationship;
|
||||||
use crate::guards::auth::UserRef;
|
use crate::guards::auth::UserRef;
|
||||||
use crate::guards::channel::ChannelRef;
|
|
||||||
use crate::guards::guild::{get_member, GuildRef};
|
|
||||||
|
|
||||||
use num_enum::TryFromPrimitive;
|
use num_enum::TryFromPrimitive;
|
||||||
|
|
||||||
@@ -88,8 +87,8 @@ pub fn get_relationship(a: &UserRef, b: &UserRef) -> Relationship {
|
|||||||
|
|
||||||
pub struct PermissionCalculator {
|
pub struct PermissionCalculator {
|
||||||
pub user: UserRef,
|
pub user: UserRef,
|
||||||
pub channel: Option<ChannelRef>,
|
pub channel: Option<Channel>,
|
||||||
pub guild: Option<GuildRef>,
|
pub guild: Option<Guild>,
|
||||||
pub member: Option<Member>,
|
pub member: Option<Member>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,14 +102,14 @@ impl PermissionCalculator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn channel(self, channel: ChannelRef) -> PermissionCalculator {
|
pub fn channel(self, channel: Channel) -> PermissionCalculator {
|
||||||
PermissionCalculator {
|
PermissionCalculator {
|
||||||
channel: Some(channel),
|
channel: Some(channel),
|
||||||
..self
|
..self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn guild(self, guild: GuildRef) -> PermissionCalculator {
|
pub fn guild(self, guild: Guild) -> PermissionCalculator {
|
||||||
PermissionCalculator {
|
PermissionCalculator {
|
||||||
guild: Some(guild),
|
guild: Some(guild),
|
||||||
..self
|
..self
|
||||||
@@ -125,7 +124,11 @@ impl PermissionCalculator {
|
|||||||
0..=1 => None,
|
0..=1 => None,
|
||||||
2 => {
|
2 => {
|
||||||
if let Some(id) = &channel.guild {
|
if let Some(id) = &channel.guild {
|
||||||
GuildRef::from(id.clone())
|
if let Ok(result) = fetch_guild(id) {
|
||||||
|
result
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -168,18 +171,23 @@ impl PermissionCalculator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ? In this case, it is a "self DM".
|
||||||
|
if other_user == "" {
|
||||||
|
return 1024 + 128 + 32 + 16 + 1;
|
||||||
|
}
|
||||||
|
|
||||||
let relationships = self.user.fetch_relationships();
|
let relationships = self.user.fetch_relationships();
|
||||||
let relationship =
|
let relationship =
|
||||||
get_relationship_internal(&self.user.id, &other_user, &relationships);
|
get_relationship_internal(&self.user.id, &other_user, &relationships);
|
||||||
|
|
||||||
if relationship == Relationship::Friend {
|
if relationship == Relationship::Friend {
|
||||||
permissions = 177;
|
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||||
} else if relationship == Relationship::Blocked
|
} else if relationship == Relationship::Blocked
|
||||||
|| relationship == Relationship::BlockedOther
|
|| relationship == Relationship::BlockedOther
|
||||||
{
|
{
|
||||||
permissions = 1;
|
permissions = 1;
|
||||||
} else if has_mutual_connection(&self.user.id, other_user, true) {
|
} else if has_mutual_connection(&self.user.id, other_user, true) {
|
||||||
permissions = 177;
|
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||||
} else {
|
} else {
|
||||||
permissions = 1;
|
permissions = 1;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
use bson::UtcDateTime;
|
use mongodb::bson::DateTime;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
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<DateTime>,
|
||||||
pub rate_limit: Option<UtcDateTime>,
|
pub rate_limit: Option<DateTime>,
|
||||||
pub code: Option<String>,
|
pub code: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,6 +23,7 @@ pub struct User {
|
|||||||
pub email: String,
|
pub email: String,
|
||||||
pub username: String,
|
pub username: String,
|
||||||
pub password: String,
|
pub password: String,
|
||||||
|
pub display_name: 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>>,
|
||||||
|
|||||||
+20
-9
@@ -2,6 +2,14 @@ use reqwest::blocking::Client;
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
|
fn public_uri() -> String {
|
||||||
|
env::var("PUBLIC_URI").expect("PUBLIC_URI not in environment variables!")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn portal() -> String {
|
||||||
|
env::var("PORTAL_URL").expect("PORTAL_URL not in environment variables!")
|
||||||
|
}
|
||||||
|
|
||||||
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());
|
||||||
@@ -10,20 +18,12 @@ pub fn send_email(target: String, subject: String, body: String, html: String) -
|
|||||||
map.insert("html", html);
|
map.insert("html", html);
|
||||||
|
|
||||||
let client = Client::new();
|
let client = Client::new();
|
||||||
match client
|
match client.post(&portal()).json(&map).send() {
|
||||||
.post("http://192.168.0.26:3838/send")
|
|
||||||
.json(&map)
|
|
||||||
.send()
|
|
||||||
{
|
|
||||||
Ok(_) => Ok(()),
|
Ok(_) => Ok(()),
|
||||||
Err(_) => Err(()),
|
Err(_) => Err(()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn public_uri() -> String {
|
|
||||||
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(
|
||||||
@@ -35,6 +35,17 @@ pub fn send_verification_email(email: String, code: String) -> bool {
|
|||||||
.is_ok()
|
.is_ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn send_password_reset(email: String, code: String) -> bool {
|
||||||
|
let url = format!("{}/api/account/reset/{}", public_uri(), code);
|
||||||
|
send_email(
|
||||||
|
email,
|
||||||
|
"Reset your password.".to_string(),
|
||||||
|
format!("Reset your password here: {}", url),
|
||||||
|
format!("<a href=\"{}\">Click to reset your password!</a>", url),
|
||||||
|
)
|
||||||
|
.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,
|
||||||
|
|||||||
+7
-2
@@ -1,4 +1,4 @@
|
|||||||
use bson::{doc, from_bson, Document};
|
use mongodb::bson::{doc, from_bson, Bson, Document};
|
||||||
use mongodb::options::FindOneOptions;
|
use mongodb::options::FindOneOptions;
|
||||||
use rocket::http::{RawStr, Status};
|
use rocket::http::{RawStr, Status};
|
||||||
use rocket::request::{self, FromParam, FromRequest, Request};
|
use rocket::request::{self, FromParam, FromRequest, Request};
|
||||||
@@ -12,6 +12,7 @@ use database::user::{User, UserRelationship};
|
|||||||
pub struct UserRef {
|
pub struct UserRef {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub username: String,
|
pub username: String,
|
||||||
|
pub display_name: String,
|
||||||
pub email_verified: bool,
|
pub email_verified: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,6 +24,7 @@ impl UserRef {
|
|||||||
.projection(doc! {
|
.projection(doc! {
|
||||||
"_id": 1,
|
"_id": 1,
|
||||||
"username": 1,
|
"username": 1,
|
||||||
|
"display_name": 1,
|
||||||
"email_verification.verified": 1,
|
"email_verification.verified": 1,
|
||||||
})
|
})
|
||||||
.build(),
|
.build(),
|
||||||
@@ -31,6 +33,7 @@ impl UserRef {
|
|||||||
Some(doc) => Some(UserRef {
|
Some(doc) => Some(UserRef {
|
||||||
id: doc.get_str("_id").unwrap().to_string(),
|
id: doc.get_str("_id").unwrap().to_string(),
|
||||||
username: doc.get_str("username").unwrap().to_string(),
|
username: doc.get_str("username").unwrap().to_string(),
|
||||||
|
display_name: doc.get_str("display_name").unwrap().to_string(),
|
||||||
email_verified: doc
|
email_verified: doc
|
||||||
.get_document("email_verification")
|
.get_document("email_verification")
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -99,6 +102,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for UserRef {
|
|||||||
.projection(doc! {
|
.projection(doc! {
|
||||||
"_id": 1,
|
"_id": 1,
|
||||||
"username": 1,
|
"username": 1,
|
||||||
|
"display_name": 1,
|
||||||
"email_verification.verified": 1,
|
"email_verification.verified": 1,
|
||||||
})
|
})
|
||||||
.build(),
|
.build(),
|
||||||
@@ -109,6 +113,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for UserRef {
|
|||||||
Outcome::Success(UserRef {
|
Outcome::Success(UserRef {
|
||||||
id: user.get_str("_id").unwrap().to_string(),
|
id: user.get_str("_id").unwrap().to_string(),
|
||||||
username: user.get_str("username").unwrap().to_string(),
|
username: user.get_str("username").unwrap().to_string(),
|
||||||
|
display_name: user.get_str("display_name").unwrap().to_string(),
|
||||||
email_verified: user
|
email_verified: user
|
||||||
.get_document("email_verification")
|
.get_document("email_verification")
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -138,7 +143,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for User {
|
|||||||
|
|
||||||
if let Some(user) = result {
|
if let Some(user) = result {
|
||||||
Outcome::Success(
|
Outcome::Success(
|
||||||
from_bson(bson::Bson::Document(user)).expect("Failed to unwrap user."),
|
from_bson(Bson::Document(user)).expect("Failed to unwrap user."),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Outcome::Failure((Status::Forbidden, AuthError::Invalid))
|
Outcome::Failure((Status::Forbidden, AuthError::Invalid))
|
||||||
|
|||||||
@@ -1,91 +0,0 @@
|
|||||||
use bson::{doc, from_bson, Document};
|
|
||||||
use mongodb::options::FindOneOptions;
|
|
||||||
use rocket::http::RawStr;
|
|
||||||
use rocket::request::FromParam;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::database;
|
|
||||||
|
|
||||||
use database::channel::LastMessage;
|
|
||||||
use database::message::Message;
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
|
||||||
pub struct ChannelRef {
|
|
||||||
#[serde(rename = "_id")]
|
|
||||||
pub id: String,
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
pub channel_type: u8,
|
|
||||||
|
|
||||||
pub name: Option<String>,
|
|
||||||
pub last_message: Option<LastMessage>,
|
|
||||||
|
|
||||||
// information required for permission calculations
|
|
||||||
pub recipients: Option<Vec<String>>,
|
|
||||||
pub guild: Option<String>,
|
|
||||||
pub owner: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ChannelRef {
|
|
||||||
pub fn from(id: String) -> Option<ChannelRef> {
|
|
||||||
match database::get_collection("channels").find_one(
|
|
||||||
doc! { "_id": id },
|
|
||||||
FindOneOptions::builder()
|
|
||||||
.projection(doc! {
|
|
||||||
"_id": 1,
|
|
||||||
"type": 1,
|
|
||||||
"name": 1,
|
|
||||||
"last_message": 1,
|
|
||||||
"recipients": 1,
|
|
||||||
"guild": 1,
|
|
||||||
"owner": 1,
|
|
||||||
})
|
|
||||||
.build(),
|
|
||||||
) {
|
|
||||||
Ok(result) => match result {
|
|
||||||
Some(doc) => {
|
|
||||||
Some(from_bson(bson::Bson::Document(doc)).expect("Failed to unwrap channel."))
|
|
||||||
}
|
|
||||||
None => None,
|
|
||||||
},
|
|
||||||
Err(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn fetch_data(&self, projection: Document) -> Option<Document> {
|
|
||||||
database::get_collection("channels")
|
|
||||||
.find_one(
|
|
||||||
doc! { "_id": &self.id },
|
|
||||||
FindOneOptions::builder().projection(projection).build(),
|
|
||||||
)
|
|
||||||
.expect("Failed to fetch channel from database.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'r> FromParam<'r> for ChannelRef {
|
|
||||||
type Error = &'r RawStr;
|
|
||||||
|
|
||||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
|
||||||
if let Some(channel) = ChannelRef::from(param.to_string()) {
|
|
||||||
Ok(channel)
|
|
||||||
} else {
|
|
||||||
Err(param)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'r> FromParam<'r> for Message {
|
|
||||||
type Error = &'r RawStr;
|
|
||||||
|
|
||||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
|
||||||
let col = database::get_collection("messages");
|
|
||||||
let result = col
|
|
||||||
.find_one(doc! { "_id": param.to_string() }, None)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
if let Some(message) = result {
|
|
||||||
Ok(from_bson(bson::Bson::Document(message)).expect("Failed to unwrap message."))
|
|
||||||
} else {
|
|
||||||
Err(param)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+4
-4
@@ -1,4 +1,4 @@
|
|||||||
use bson::{doc, from_bson, Bson, Document};
|
use mongodb::bson::{doc, from_bson, Bson, Document};
|
||||||
use mongodb::options::FindOneOptions;
|
use mongodb::options::FindOneOptions;
|
||||||
use rocket::http::RawStr;
|
use rocket::http::RawStr;
|
||||||
use rocket::request::FromParam;
|
use rocket::request::FromParam;
|
||||||
@@ -36,7 +36,7 @@ impl GuildRef {
|
|||||||
) {
|
) {
|
||||||
Ok(result) => match result {
|
Ok(result) => match result {
|
||||||
Some(doc) => {
|
Some(doc) => {
|
||||||
Some(from_bson(bson::Bson::Document(doc)).expect("Failed to unwrap guild."))
|
Some(from_bson(mongodb::bson::mongodb::bson::Document(doc)).expect("Failed to unwrap guild."))
|
||||||
}
|
}
|
||||||
None => None,
|
None => None,
|
||||||
},
|
},
|
||||||
@@ -85,7 +85,7 @@ pub fn get_member(guild_id: &String, member: &String) -> Option<Member> {
|
|||||||
None,
|
None,
|
||||||
) {
|
) {
|
||||||
if let Some(doc) = result {
|
if let Some(doc) = result {
|
||||||
Some(from_bson(Bson::Document(doc)).expect("Failed to unwrap member."))
|
Some(from_bson(mongodb::bson::Document(doc)).expect("Failed to unwrap member."))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -142,7 +142,7 @@ pub fn get_invite<U: Into<Option<String>>>(
|
|||||||
Some((
|
Some((
|
||||||
doc.get_str("_id").unwrap().to_string(),
|
doc.get_str("_id").unwrap().to_string(),
|
||||||
doc.get_str("name").unwrap().to_string(),
|
doc.get_str("name").unwrap().to_string(),
|
||||||
from_bson(Bson::Document(invite.clone())).unwrap(),
|
from_bson(mongodb::bson::Document(invite.clone())).unwrap(),
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
|
|||||||
@@ -1,3 +1 @@
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod channel;
|
|
||||||
pub mod guild;
|
|
||||||
|
|||||||
+10
-2
@@ -1,17 +1,20 @@
|
|||||||
#![feature(proc_macro_hygiene, decl_macro)]
|
#![feature(proc_macro_hygiene, decl_macro)]
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate rocket;
|
extern crate rocket;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate rocket_contrib;
|
extern crate rocket_contrib;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate bitfield;
|
extern crate bitfield;
|
||||||
|
#[macro_use]
|
||||||
|
extern crate lazy_static;
|
||||||
|
|
||||||
pub mod database;
|
pub mod database;
|
||||||
pub mod email;
|
pub mod email;
|
||||||
pub mod guards;
|
pub mod guards;
|
||||||
|
pub mod notifications;
|
||||||
pub mod routes;
|
pub mod routes;
|
||||||
pub mod util;
|
pub mod util;
|
||||||
pub mod websocket;
|
|
||||||
|
|
||||||
use dotenv;
|
use dotenv;
|
||||||
use rocket_cors::AllowedOrigins;
|
use rocket_cors::AllowedOrigins;
|
||||||
@@ -20,9 +23,14 @@ use std::thread;
|
|||||||
fn main() {
|
fn main() {
|
||||||
dotenv::dotenv().ok();
|
dotenv::dotenv().ok();
|
||||||
database::connect();
|
database::connect();
|
||||||
|
notifications::start_worker();
|
||||||
|
|
||||||
thread::spawn(|| {
|
thread::spawn(|| {
|
||||||
websocket::launch_server();
|
notifications::pubsub::launch_subscriber();
|
||||||
|
});
|
||||||
|
|
||||||
|
thread::spawn(|| {
|
||||||
|
notifications::ws::launch_server();
|
||||||
});
|
});
|
||||||
|
|
||||||
let cors = rocket_cors::CorsOptions {
|
let cors = rocket_cors::CorsOptions {
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct UserJoin {
|
||||||
|
pub id: String,
|
||||||
|
pub user: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct UserLeave {
|
||||||
|
pub id: String,
|
||||||
|
pub user: String,
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct UserJoin {
|
||||||
|
pub id: String,
|
||||||
|
pub user: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct UserLeave {
|
||||||
|
pub id: String,
|
||||||
|
pub user: String,
|
||||||
|
pub banned: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct ChannelCreate {
|
||||||
|
pub id: String,
|
||||||
|
pub channel: String,
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct ChannelDelete {
|
||||||
|
pub id: String,
|
||||||
|
pub channel: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct Delete {
|
||||||
|
pub id: String,
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct Create {
|
||||||
|
pub id: String,
|
||||||
|
pub nonce: Option<String>,
|
||||||
|
pub channel: String,
|
||||||
|
pub author: String,
|
||||||
|
pub content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct Edit {
|
||||||
|
pub id: String,
|
||||||
|
pub channel: String,
|
||||||
|
pub author: String,
|
||||||
|
pub content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct Delete {
|
||||||
|
pub id: String,
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
|
pub mod groups;
|
||||||
|
pub mod guilds;
|
||||||
|
pub mod message;
|
||||||
|
pub mod users;
|
||||||
|
|
||||||
|
#[allow(non_camel_case_types)]
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub enum Notification {
|
||||||
|
message_create(message::Create),
|
||||||
|
message_edit(message::Edit),
|
||||||
|
message_delete(message::Delete),
|
||||||
|
group_user_join(groups::UserJoin),
|
||||||
|
group_user_leave(groups::UserLeave),
|
||||||
|
guild_user_join(guilds::UserJoin),
|
||||||
|
guild_user_leave(guilds::UserLeave),
|
||||||
|
guild_channel_create(guilds::ChannelCreate),
|
||||||
|
guild_channel_delete(guilds::ChannelDelete),
|
||||||
|
guild_delete(guilds::Delete),
|
||||||
|
user_friend_status(users::FriendStatus),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Notification {
|
||||||
|
pub fn serialize(self) -> String {
|
||||||
|
if let Value::Object(obj) = json!(self) {
|
||||||
|
let (key, value) = obj.iter().next().unwrap();
|
||||||
|
|
||||||
|
if let Value::Object(data) = value {
|
||||||
|
let mut data = data.clone();
|
||||||
|
data.insert("type".to_string(), Value::String(key.to_string()));
|
||||||
|
json!(data).to_string()
|
||||||
|
} else {
|
||||||
|
unreachable!()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
unreachable!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
pub struct FriendStatus {
|
||||||
|
pub id: String,
|
||||||
|
pub status: i32,
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
use crate::database::channel::Channel;
|
||||||
|
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
|
use std::sync::mpsc::{channel, Sender};
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
|
pub mod events;
|
||||||
|
pub mod pubsub;
|
||||||
|
pub mod state;
|
||||||
|
pub mod ws;
|
||||||
|
|
||||||
|
pub fn send_message<U: Into<Option<Vec<String>>>, G: Into<Option<String>>>(
|
||||||
|
users: U,
|
||||||
|
guild: G,
|
||||||
|
data: events::Notification,
|
||||||
|
) -> bool {
|
||||||
|
let users = users.into();
|
||||||
|
let guild = guild.into();
|
||||||
|
|
||||||
|
if pubsub::send_message(users.clone(), guild.clone(), data.clone()) {
|
||||||
|
state::send_message(users, guild, data.serialize());
|
||||||
|
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct NotificationArguments {
|
||||||
|
users: Option<Vec<String>>,
|
||||||
|
guild: Option<String>,
|
||||||
|
data: events::Notification,
|
||||||
|
}
|
||||||
|
|
||||||
|
static mut SENDER: OnceCell<Sender<NotificationArguments>> = OnceCell::new();
|
||||||
|
|
||||||
|
pub fn start_worker() {
|
||||||
|
let (sender, receiver) = channel();
|
||||||
|
unsafe {
|
||||||
|
SENDER.set(sender).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
thread::spawn(move || {
|
||||||
|
while let Ok(data) = receiver.recv() {
|
||||||
|
send_message(data.users, data.guild, data.data);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_message_threaded<U: Into<Option<Vec<String>>>, G: Into<Option<String>>>(
|
||||||
|
users: U,
|
||||||
|
guild: G,
|
||||||
|
data: events::Notification,
|
||||||
|
) -> bool {
|
||||||
|
unsafe {
|
||||||
|
SENDER
|
||||||
|
.get()
|
||||||
|
.unwrap()
|
||||||
|
.send(NotificationArguments {
|
||||||
|
users: users.into(),
|
||||||
|
guild: guild.into(),
|
||||||
|
data,
|
||||||
|
})
|
||||||
|
.is_ok()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_message_given_channel(data: events::Notification, channel: &Channel) {
|
||||||
|
match channel.channel_type {
|
||||||
|
0..=1 => send_message_threaded(channel.recipients.clone(), None, data),
|
||||||
|
2 => send_message_threaded(None, channel.guild.clone(), data),
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
use super::events::Notification;
|
||||||
|
use crate::database::get_collection;
|
||||||
|
|
||||||
|
use mongodb::bson::{doc, from_bson, to_bson, Bson};
|
||||||
|
use mongodb::options::{CursorType, FindOneOptions, FindOptions};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::time::Duration;
|
||||||
|
use ulid::Ulid;
|
||||||
|
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
|
static SOURCEID: OnceCell<String> = OnceCell::new();
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
pub struct PubSubMessage {
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
id: String,
|
||||||
|
source: String,
|
||||||
|
|
||||||
|
user_recipients: Option<Vec<String>>,
|
||||||
|
target_guild: Option<String>,
|
||||||
|
data: Notification,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_message(users: Option<Vec<String>>, guild: Option<String>, data: Notification) -> bool {
|
||||||
|
let message = PubSubMessage {
|
||||||
|
id: Ulid::new().to_string(),
|
||||||
|
source: SOURCEID.get().unwrap().to_string(),
|
||||||
|
user_recipients: users.into(),
|
||||||
|
target_guild: guild.into(),
|
||||||
|
data,
|
||||||
|
};
|
||||||
|
|
||||||
|
if get_collection("pubsub")
|
||||||
|
.insert_one(
|
||||||
|
to_bson(&message)
|
||||||
|
.expect("Failed to serialize pubsub message.")
|
||||||
|
.as_document()
|
||||||
|
.expect("Failed to convert to a document.")
|
||||||
|
.clone(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn launch_subscriber() {
|
||||||
|
let source = Ulid::new().to_string();
|
||||||
|
SOURCEID
|
||||||
|
.set(source.clone())
|
||||||
|
.expect("Failed to create and set source ID.");
|
||||||
|
|
||||||
|
let pubsub = get_collection("pubsub");
|
||||||
|
if let Ok(result) = pubsub.find_one(
|
||||||
|
doc! {},
|
||||||
|
FindOneOptions::builder().sort(doc! { "_id": -1 }).build(),
|
||||||
|
) {
|
||||||
|
let query = if let Some(doc) = result {
|
||||||
|
doc! { "_id": { "$gt": doc.get_str("_id").unwrap() } }
|
||||||
|
} else {
|
||||||
|
doc! {}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Ok(mut cursor) = pubsub.find(
|
||||||
|
query,
|
||||||
|
FindOptions::builder()
|
||||||
|
.cursor_type(CursorType::TailableAwait)
|
||||||
|
.no_cursor_timeout(true)
|
||||||
|
.max_await_time(Duration::from_secs(1200))
|
||||||
|
.build(),
|
||||||
|
) {
|
||||||
|
loop {
|
||||||
|
while let Some(item) = cursor.next() {
|
||||||
|
if let Ok(doc) = item {
|
||||||
|
if let Ok(message) =
|
||||||
|
from_bson(Bson::Document(doc)) as Result<PubSubMessage, _>
|
||||||
|
{
|
||||||
|
if &message.source != &source {
|
||||||
|
super::state::send_message(
|
||||||
|
message.user_recipients,
|
||||||
|
message.target_guild,
|
||||||
|
message.data.serialize(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
eprintln!("Failed to deserialize pubsub message.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
eprintln!("Failed to unwrap a document from pubsub.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
eprintln!("Failed to open subscriber cursor.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
eprintln!("Failed to fetch latest document from pubsub collection.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
use crate::database;
|
||||||
|
use crate::util::vec_to_set;
|
||||||
|
|
||||||
|
use hashbrown::{HashMap, HashSet};
|
||||||
|
use mongodb::bson::doc;
|
||||||
|
use mongodb::options::FindOneOptions;
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
|
use std::sync::RwLock;
|
||||||
|
use ws::Sender;
|
||||||
|
|
||||||
|
pub enum StateResult {
|
||||||
|
DatabaseError,
|
||||||
|
InvalidToken,
|
||||||
|
Success(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
static mut CONNECTIONS: OnceCell<RwLock<HashMap<String, Sender>>> = OnceCell::new();
|
||||||
|
|
||||||
|
pub fn add_connection(id: String, sender: Sender) {
|
||||||
|
unsafe {
|
||||||
|
CONNECTIONS
|
||||||
|
.get()
|
||||||
|
.unwrap()
|
||||||
|
.write()
|
||||||
|
.unwrap()
|
||||||
|
.insert(id, sender);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct User {
|
||||||
|
connections: HashSet<String>,
|
||||||
|
guilds: HashSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl User {
|
||||||
|
pub fn new() -> User {
|
||||||
|
User {
|
||||||
|
connections: HashSet::new(),
|
||||||
|
guilds: HashSet::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Guild {
|
||||||
|
users: HashSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Guild {
|
||||||
|
pub fn new() -> Guild {
|
||||||
|
Guild {
|
||||||
|
users: HashSet::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct GlobalState {
|
||||||
|
users: HashMap<String, User>,
|
||||||
|
guilds: HashMap<String, Guild>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GlobalState {
|
||||||
|
pub fn new() -> GlobalState {
|
||||||
|
GlobalState {
|
||||||
|
users: HashMap::new(),
|
||||||
|
guilds: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push_to_guild(&mut self, guild: String, user: String) {
|
||||||
|
if !self.guilds.contains_key(&guild) {
|
||||||
|
self.guilds.insert(guild.clone(), Guild::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
self.guilds.get_mut(&guild).unwrap().users.insert(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn try_authenticate(&mut self, connection: String, access_token: String) -> StateResult {
|
||||||
|
if let Ok(result) = database::get_collection("users").find_one(
|
||||||
|
doc! {
|
||||||
|
"access_token": access_token,
|
||||||
|
},
|
||||||
|
FindOneOptions::builder()
|
||||||
|
.projection(doc! { "_id": 1 })
|
||||||
|
.build(),
|
||||||
|
) {
|
||||||
|
if let Some(user) = result {
|
||||||
|
let user_id = user.get_str("_id").unwrap();
|
||||||
|
|
||||||
|
if self.users.contains_key(user_id) {
|
||||||
|
self.users
|
||||||
|
.get_mut(user_id)
|
||||||
|
.unwrap()
|
||||||
|
.connections
|
||||||
|
.insert(connection);
|
||||||
|
|
||||||
|
return StateResult::Success(user_id.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(results) =
|
||||||
|
database::get_collection("members").find(doc! { "_id.user": &user_id }, None)
|
||||||
|
{
|
||||||
|
let mut guilds = vec![];
|
||||||
|
for result in results {
|
||||||
|
if let Ok(entry) = result {
|
||||||
|
guilds.push(
|
||||||
|
entry
|
||||||
|
.get_document("_id")
|
||||||
|
.unwrap()
|
||||||
|
.get_str("guild")
|
||||||
|
.unwrap()
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut user = User::new();
|
||||||
|
for guild in guilds {
|
||||||
|
user.guilds.insert(guild.clone());
|
||||||
|
self.push_to_guild(guild, user_id.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
user.connections.insert(connection);
|
||||||
|
self.users.insert(user_id.to_string(), user);
|
||||||
|
|
||||||
|
StateResult::Success(user_id.to_string())
|
||||||
|
} else {
|
||||||
|
StateResult::DatabaseError
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
StateResult::InvalidToken
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
StateResult::DatabaseError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn disconnect<U: Into<Option<String>>>(&mut self, user_id: U, connection: String) {
|
||||||
|
if let Some(user_id) = user_id.into() {
|
||||||
|
let user = self.users.get_mut(&user_id).unwrap();
|
||||||
|
user.connections.remove(&connection);
|
||||||
|
|
||||||
|
if user.connections.len() == 0 {
|
||||||
|
for guild in &user.guilds {
|
||||||
|
self.guilds.get_mut(guild).unwrap().users.remove(&user_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.users.remove(&user_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
CONNECTIONS
|
||||||
|
.get()
|
||||||
|
.unwrap()
|
||||||
|
.write()
|
||||||
|
.unwrap()
|
||||||
|
.remove(&connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static mut DATA: OnceCell<RwLock<GlobalState>> = OnceCell::new();
|
||||||
|
|
||||||
|
pub fn init() {
|
||||||
|
unsafe {
|
||||||
|
if CONNECTIONS.set(RwLock::new(HashMap::new())).is_err() {
|
||||||
|
panic!("Failed to set global connections map.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if DATA.set(RwLock::new(GlobalState::new())).is_err() {
|
||||||
|
panic!("Failed to set global state.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_message(users: Option<Vec<String>>, guild: Option<String>, data: String) {
|
||||||
|
let state = unsafe { DATA.get().unwrap().read().unwrap() };
|
||||||
|
let mut connections = HashSet::new();
|
||||||
|
|
||||||
|
let mut users = vec_to_set(&users.unwrap_or(vec![]));
|
||||||
|
if let Some(guild) = guild {
|
||||||
|
if let Some(entry) = state.guilds.get(&guild) {
|
||||||
|
for user in &entry.users {
|
||||||
|
users.insert(user.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for user in users {
|
||||||
|
if let Some(entry) = state.users.get(&user) {
|
||||||
|
for connection in &entry.connections {
|
||||||
|
connections.insert(connection.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let targets = unsafe { CONNECTIONS.get().unwrap().read().unwrap() };
|
||||||
|
for conn in connections {
|
||||||
|
if let Some(sender) = targets.get(&conn) {
|
||||||
|
if sender.send(data.clone()).is_err() {
|
||||||
|
eprintln!("Failed to send a notification to a websocket. [{}]", &conn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
use super::state::{self, StateResult};
|
||||||
|
|
||||||
|
use serde_json::{from_str, json, Value};
|
||||||
|
use std::env;
|
||||||
|
use ulid::Ulid;
|
||||||
|
use ws::{listen, CloseCode, Error, Handler, Handshake, Message, Result, Sender};
|
||||||
|
|
||||||
|
struct Server {
|
||||||
|
sender: Sender,
|
||||||
|
user_id: Option<String>,
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Handler for Server {
|
||||||
|
fn on_open(&mut self, _: Handshake) -> Result<()> {
|
||||||
|
state::add_connection(self.id.clone(), self.sender.clone());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_message(&mut self, msg: Message) -> Result<()> {
|
||||||
|
if let Message::Text(text) = msg {
|
||||||
|
if let Ok(data) = from_str(&text) as std::result::Result<Value, _> {
|
||||||
|
if let Value::String(packet_type) = &data["type"] {
|
||||||
|
if packet_type == "authenticate" {
|
||||||
|
if self.user_id.is_some() {
|
||||||
|
self.sender.send(
|
||||||
|
json!({
|
||||||
|
"type": "authenticate",
|
||||||
|
"success": false,
|
||||||
|
"error": "Already authenticated!"
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
} else if let Value::String(token) = &data["token"] {
|
||||||
|
let mut state = unsafe { state::DATA.get().unwrap().write().unwrap() };
|
||||||
|
|
||||||
|
match state.try_authenticate(self.id.clone(), token.to_string()) {
|
||||||
|
StateResult::Success(user_id) => {
|
||||||
|
self.user_id = Some(user_id);
|
||||||
|
self.sender.send(
|
||||||
|
json!({
|
||||||
|
"type": "authenticate",
|
||||||
|
"success": true,
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
StateResult::DatabaseError => self.sender.send(
|
||||||
|
json!({
|
||||||
|
"type": "authenticate",
|
||||||
|
"success": false,
|
||||||
|
"error": "Had database error."
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
StateResult::InvalidToken => self.sender.send(
|
||||||
|
json!({
|
||||||
|
"type": "authenticate",
|
||||||
|
"success": false,
|
||||||
|
"error": "Invalid token."
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.sender.send(
|
||||||
|
json!({
|
||||||
|
"type": "authenticate",
|
||||||
|
"success": false,
|
||||||
|
"error": "Token not present."
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_close(&mut self, _code: CloseCode, _reason: &str) {
|
||||||
|
unsafe {
|
||||||
|
state::DATA
|
||||||
|
.get()
|
||||||
|
.unwrap()
|
||||||
|
.write()
|
||||||
|
.unwrap()
|
||||||
|
.disconnect(self.user_id.clone(), self.id.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("User disconnected. [{}]", self.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_error(&mut self, err: Error) {
|
||||||
|
println!("The server encountered an error: {:?}", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn launch_server() {
|
||||||
|
state::init();
|
||||||
|
|
||||||
|
listen(
|
||||||
|
env::var("WS_HOST").unwrap_or("0.0.0.0:9999".to_string()),
|
||||||
|
|sender| Server {
|
||||||
|
sender,
|
||||||
|
user_id: None,
|
||||||
|
id: Ulid::new().to_string(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
+41
-17
@@ -4,9 +4,9 @@ use crate::email;
|
|||||||
use crate::util::gen_token;
|
use crate::util::gen_token;
|
||||||
|
|
||||||
use bcrypt::{hash, verify};
|
use bcrypt::{hash, verify};
|
||||||
use bson::{doc, from_bson, Bson::UtcDatetime};
|
|
||||||
use chrono::prelude::*;
|
use chrono::prelude::*;
|
||||||
use database::user::User;
|
use database::user::User;
|
||||||
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
use rocket_contrib::json::Json;
|
use rocket_contrib::json::Json;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
@@ -53,6 +53,13 @@ pub fn create(info: Json<Create>) -> Response {
|
|||||||
return Response::Conflict(json!({ "error": "Email already in use!" }));
|
return Response::Conflict(json!({ "error": "Email already in use!" }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(_) = col
|
||||||
|
.find_one(doc! { "username": info.username.clone() }, None)
|
||||||
|
.expect("Failed user lookup")
|
||||||
|
{
|
||||||
|
return Response::Conflict(json!({ "error": "Username 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);
|
||||||
@@ -62,13 +69,14 @@ pub fn create(info: Json<Create>) -> Response {
|
|||||||
"_id": Ulid::new().to_string(),
|
"_id": Ulid::new().to_string(),
|
||||||
"email": info.email.clone(),
|
"email": info.email.clone(),
|
||||||
"username": info.username.clone(),
|
"username": info.username.clone(),
|
||||||
|
"display_name": info.username.clone(),
|
||||||
"password": hashed,
|
"password": hashed,
|
||||||
"access_token": access_token,
|
"access_token": access_token,
|
||||||
"email_verification": {
|
"email_verification": {
|
||||||
"verified": false,
|
"verified": false,
|
||||||
"target": info.email.clone(),
|
"target": info.email.clone(),
|
||||||
"expiry": UtcDatetime(Utc::now() + chrono::Duration::days(1)),
|
"expiry": Bson::DateTime(Utc::now() + chrono::Duration::days(1)),
|
||||||
"rate_limit": UtcDatetime(Utc::now() + chrono::Duration::minutes(1)),
|
"rate_limit": Bson::DateTime(Utc::now() + chrono::Duration::minutes(1)),
|
||||||
"code": code.clone(),
|
"code": code.clone(),
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -78,7 +86,6 @@ pub fn create(info: Json<Create>) -> Response {
|
|||||||
let sent = email::send_verification_email(info.email.clone(), code);
|
let sent = email::send_verification_email(info.email.clone(), code);
|
||||||
|
|
||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
"success": true,
|
|
||||||
"email_sent": sent,
|
"email_sent": sent,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
@@ -103,7 +110,7 @@ pub fn verify_email(code: String) -> Response {
|
|||||||
.find_one(doc! { "email_verification.code": code.clone() }, None)
|
.find_one(doc! { "email_verification.code": code.clone() }, None)
|
||||||
.expect("Failed user lookup")
|
.expect("Failed user lookup")
|
||||||
{
|
{
|
||||||
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
|
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||||
let ev = user.email_verification;
|
let ev = user.email_verification;
|
||||||
|
|
||||||
if Utc::now() > *ev.expiry.unwrap() {
|
if Utc::now() > *ev.expiry.unwrap() {
|
||||||
@@ -133,9 +140,7 @@ pub fn verify_email(code: String) -> Response {
|
|||||||
|
|
||||||
email::send_welcome_email(target.to_string(), user.username);
|
email::send_welcome_email(target.to_string(), user.username);
|
||||||
|
|
||||||
Response::Redirect(
|
Response::Redirect(super::Redirect::to("https://app.revolt.chat"))
|
||||||
super::Redirect::to("https://example.com"), // ! FIXME; redirect to landing page
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Response::BadRequest(json!({ "error": "Invalid code." }))
|
Response::BadRequest(json!({ "error": "Invalid code." }))
|
||||||
@@ -162,7 +167,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
)
|
)
|
||||||
.expect("Failed user lookup.")
|
.expect("Failed user lookup.")
|
||||||
{
|
{
|
||||||
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
|
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||||
let ev = user.email_verification;
|
let ev = user.email_verification;
|
||||||
|
|
||||||
let expiry = ev.expiry.unwrap();
|
let expiry = ev.expiry.unwrap();
|
||||||
@@ -173,7 +178,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
json!({ "error": "You are being rate limited, please try again in a while." }),
|
json!({ "error": "You are being rate limited, please try again in a while." }),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
let mut new_expiry = UtcDatetime(Utc::now() + chrono::Duration::days(1));
|
let mut new_expiry = Bson::DateTime(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 Response::Gone(
|
return Response::Gone(
|
||||||
@@ -181,7 +186,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
new_expiry = UtcDatetime(*expiry);
|
new_expiry = Bson::DateTime(*expiry);
|
||||||
}
|
}
|
||||||
|
|
||||||
let code = gen_token(48);
|
let code = gen_token(48);
|
||||||
@@ -191,7 +196,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
"$set": {
|
"$set": {
|
||||||
"email_verification.code": code.clone(),
|
"email_verification.code": code.clone(),
|
||||||
"email_verification.expiry": new_expiry,
|
"email_verification.expiry": new_expiry,
|
||||||
"email_verification.rate_limit": UtcDatetime(Utc::now() + chrono::Duration::minutes(1)),
|
"email_verification.rate_limit": Bson::DateTime(Utc::now() + chrono::Duration::minutes(1)),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
@@ -200,14 +205,12 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
match email::send_verification_email(info.email.to_string(), code) {
|
match email::send_verification_email(info.email.to_string(), code) {
|
||||||
true => Response::Result(super::Status::Ok),
|
true => Response::Result(super::Status::Ok),
|
||||||
false => Response::InternalServerError(
|
false => Response::InternalServerError(
|
||||||
json!({ "success": false, "error": "Failed to send email! Likely an issue with the backend API." }),
|
json!({ "error": "Failed to send email! Likely an issue with the backend API." }),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Response::NotFound(
|
Response::NotFound(json!({ "error": "Email not found or pending verification!" }))
|
||||||
json!({ "success": false, "error": "Email not found or pending verification!" }),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,7 +232,7 @@ pub fn login(info: Json<Login>) -> Response {
|
|||||||
.find_one(doc! { "email": info.email.clone() }, None)
|
.find_one(doc! { "email": info.email.clone() }, None)
|
||||||
.expect("Failed user lookup")
|
.expect("Failed user lookup")
|
||||||
{
|
{
|
||||||
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
|
let user: User = from_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.")
|
||||||
@@ -291,3 +294,24 @@ pub fn token(info: Json<Token>) -> Response {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[options("/create")]
|
||||||
|
pub fn create_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/verify/<_code>")]
|
||||||
|
pub fn verify_email_preflight(_code: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/resend")]
|
||||||
|
pub fn resend_email_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/login")]
|
||||||
|
pub fn login_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/token")]
|
||||||
|
pub fn token_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
|||||||
+250
-164
@@ -1,16 +1,20 @@
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::database::{
|
use crate::database::{
|
||||||
self, get_relationship, get_relationship_internal, message::Message, Permission,
|
self, channel::Channel, get_relationship, get_relationship_internal, message::Message,
|
||||||
PermissionCalculator, Relationship,
|
Permission, PermissionCalculator, Relationship,
|
||||||
};
|
};
|
||||||
use crate::guards::auth::UserRef;
|
use crate::guards::auth::UserRef;
|
||||||
use crate::guards::channel::ChannelRef;
|
use crate::notifications::{
|
||||||
|
self,
|
||||||
|
events::{groups::*, guilds::ChannelDelete, message::*, Notification},
|
||||||
|
};
|
||||||
use crate::util::vec_to_set;
|
use crate::util::vec_to_set;
|
||||||
|
|
||||||
use bson::{doc, from_bson, Bson, Bson::UtcDatetime};
|
|
||||||
use chrono::prelude::*;
|
use chrono::prelude::*;
|
||||||
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::FindOptions;
|
||||||
use num_enum::TryFromPrimitive;
|
use num_enum::TryFromPrimitive;
|
||||||
|
use rocket::request::Form;
|
||||||
use rocket_contrib::json::Json;
|
use rocket_contrib::json::Json;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
@@ -125,7 +129,7 @@ pub fn create_group(user: UserRef, info: Json<CreateGroup>) -> Response {
|
|||||||
|
|
||||||
/// fetch channel information
|
/// fetch channel information
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub fn channel(user: UserRef, target: ChannelRef) -> Option<Response> {
|
pub fn channel(user: UserRef, target: Channel) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
match target.channel_type {
|
match target.channel_type {
|
||||||
@@ -136,39 +140,39 @@ pub fn channel(user: UserRef, target: ChannelRef) -> Option<Response> {
|
|||||||
"recipients": target.recipients,
|
"recipients": target.recipients,
|
||||||
}))),
|
}))),
|
||||||
1 => {
|
1 => {
|
||||||
if let Some(info) = target.fetch_data(doc! {
|
/*if let Some(info) = target.fetch_data(doc! {
|
||||||
"name": 1,
|
"name": 1,
|
||||||
"description": 1,
|
"description": 1,
|
||||||
"owner": 1,
|
"owner": 1,
|
||||||
}) {
|
}) {*/
|
||||||
Some(Response::Success(json!({
|
Some(Response::Success(json!({
|
||||||
"id": target.id,
|
"id": target.id,
|
||||||
"type": target.channel_type,
|
"type": target.channel_type,
|
||||||
"last_message": target.last_message,
|
"last_message": target.last_message,
|
||||||
"recipients": target.recipients,
|
"recipients": target.recipients,
|
||||||
"name": info.get_str("name").unwrap(),
|
"name": target.name,
|
||||||
"owner": info.get_str("owner").unwrap(),
|
"owner": target.owner,
|
||||||
"description": info.get_str("description").unwrap_or(""),
|
"description": target.description,
|
||||||
})))
|
})))
|
||||||
} else {
|
/*} else {
|
||||||
None
|
None
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
2 => {
|
2 => {
|
||||||
if let Some(info) = target.fetch_data(doc! {
|
/*if let Some(info) = target.fetch_data(doc! {
|
||||||
"name": 1,
|
"name": 1,
|
||||||
"description": 1,
|
"description": 1,
|
||||||
}) {
|
}) {*/
|
||||||
Some(Response::Success(json!({
|
Some(Response::Success(json!({
|
||||||
"id": target.id,
|
"id": target.id,
|
||||||
"type": target.channel_type,
|
"type": target.channel_type,
|
||||||
"guild": target.guild,
|
"guild": target.guild,
|
||||||
"name": info.get_str("name").unwrap(),
|
"name": target.name,
|
||||||
"description": info.get_str("description").unwrap_or(""),
|
"description": target.description,
|
||||||
})))
|
})))
|
||||||
} else {
|
/*} else {
|
||||||
None
|
None
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
@@ -176,14 +180,14 @@ pub fn channel(user: UserRef, target: ChannelRef) -> Option<Response> {
|
|||||||
|
|
||||||
/// [groups] add user to channel
|
/// [groups] add user to channel
|
||||||
#[put("/<target>/recipients/<member>")]
|
#[put("/<target>/recipients/<member>")]
|
||||||
pub fn add_member(user: UserRef, target: ChannelRef, member: UserRef) -> Option<Response> {
|
pub fn add_member(user: UserRef, target: Channel, member: UserRef) -> Option<Response> {
|
||||||
if target.channel_type != 1 {
|
if target.channel_type != 1 {
|
||||||
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
||||||
}
|
}
|
||||||
|
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
let recp = target.recipients.unwrap();
|
let recp = target.recipients.as_ref().unwrap();
|
||||||
if recp.len() == 50 {
|
if recp.len() == 50 {
|
||||||
return Some(Response::BadRequest(
|
return Some(Response::BadRequest(
|
||||||
json!({ "error": "Maximum group size is 50." }),
|
json!({ "error": "Maximum group size is 50." }),
|
||||||
@@ -201,7 +205,7 @@ pub fn add_member(user: UserRef, target: ChannelRef, member: UserRef) -> Option<
|
|||||||
Relationship::Friend => {
|
Relationship::Friend => {
|
||||||
if database::get_collection("channels")
|
if database::get_collection("channels")
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! { "_id": &target.id },
|
doc! { "_id": target.id.clone() },
|
||||||
doc! {
|
doc! {
|
||||||
"$push": {
|
"$push": {
|
||||||
"recipients": &member.id
|
"recipients": &member.id
|
||||||
@@ -211,7 +215,31 @@ pub fn add_member(user: UserRef, target: ChannelRef, member: UserRef) -> Option<
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Some(Response::Result(super::Status::Ok))
|
if (Message {
|
||||||
|
id: Ulid::new().to_string(),
|
||||||
|
nonce: None,
|
||||||
|
channel: target.id.clone(),
|
||||||
|
author: "system".to_string(),
|
||||||
|
content: format!("<@{}> added <@{}> to the group.", &user.id, &member.id),
|
||||||
|
edited: None,
|
||||||
|
previous_content: vec![],
|
||||||
|
})
|
||||||
|
.send(&target)
|
||||||
|
{
|
||||||
|
notifications::send_message_given_channel(
|
||||||
|
Notification::group_user_join(UserJoin {
|
||||||
|
id: target.id.clone(),
|
||||||
|
user: member.id.clone(),
|
||||||
|
}),
|
||||||
|
&target,
|
||||||
|
);
|
||||||
|
|
||||||
|
Some(Response::Result(super::Status::Ok))
|
||||||
|
} else {
|
||||||
|
Some(Response::PartialStatus(
|
||||||
|
json!({ "error": "Failed to send join message, but user has been added." }),
|
||||||
|
))
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
json!({ "error": "Failed to add user to group." }),
|
json!({ "error": "Failed to add user to group." }),
|
||||||
@@ -226,7 +254,7 @@ pub fn add_member(user: UserRef, target: ChannelRef, member: UserRef) -> Option<
|
|||||||
|
|
||||||
/// [groups] remove user from channel
|
/// [groups] remove user from channel
|
||||||
#[delete("/<target>/recipients/<member>")]
|
#[delete("/<target>/recipients/<member>")]
|
||||||
pub fn remove_member(user: UserRef, target: ChannelRef, member: UserRef) -> Option<Response> {
|
pub fn remove_member(user: UserRef, target: Channel, member: UserRef) -> Option<Response> {
|
||||||
if target.channel_type != 1 {
|
if target.channel_type != 1 {
|
||||||
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
||||||
}
|
}
|
||||||
@@ -243,7 +271,7 @@ pub fn remove_member(user: UserRef, target: ChannelRef, member: UserRef) -> Opti
|
|||||||
return Some(Response::LackingPermission(Permission::KickMembers));
|
return Some(Response::LackingPermission(Permission::KickMembers));
|
||||||
}
|
}
|
||||||
|
|
||||||
let set = vec_to_set(&target.recipients.unwrap());
|
let set = vec_to_set(target.recipients.as_ref().unwrap());
|
||||||
if set.get(&member.id).is_none() {
|
if set.get(&member.id).is_none() {
|
||||||
return Some(Response::BadRequest(
|
return Some(Response::BadRequest(
|
||||||
json!({ "error": "User not in group!" }),
|
json!({ "error": "User not in group!" }),
|
||||||
@@ -262,7 +290,31 @@ pub fn remove_member(user: UserRef, target: ChannelRef, member: UserRef) -> Opti
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Some(Response::Result(super::Status::Ok))
|
if (Message {
|
||||||
|
id: Ulid::new().to_string(),
|
||||||
|
nonce: None,
|
||||||
|
channel: target.id.clone(),
|
||||||
|
author: "system".to_string(),
|
||||||
|
content: format!("<@{}> removed <@{}> from the group.", &user.id, &member.id),
|
||||||
|
edited: None,
|
||||||
|
previous_content: vec![],
|
||||||
|
})
|
||||||
|
.send(&target)
|
||||||
|
{
|
||||||
|
notifications::send_message_given_channel(
|
||||||
|
Notification::group_user_leave(UserLeave {
|
||||||
|
id: target.id.clone(),
|
||||||
|
user: member.id.clone(),
|
||||||
|
}),
|
||||||
|
&target,
|
||||||
|
);
|
||||||
|
|
||||||
|
Some(Response::Result(super::Status::Ok))
|
||||||
|
} else {
|
||||||
|
Some(Response::PartialStatus(
|
||||||
|
json!({ "error": "Failed to send join message, but user has been removed." }),
|
||||||
|
))
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
json!({ "error": "Failed to add user to group." }),
|
json!({ "error": "Failed to add user to group." }),
|
||||||
@@ -274,7 +326,7 @@ pub fn remove_member(user: UserRef, target: ChannelRef, member: UserRef) -> Opti
|
|||||||
/// or leave group DM
|
/// or leave group DM
|
||||||
/// or close DM conversation
|
/// or close DM conversation
|
||||||
#[delete("/<target>")]
|
#[delete("/<target>")]
|
||||||
pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
pub fn delete(user: UserRef, target: Channel) -> Option<Response> {
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_manage_channels() {
|
if !permissions.get_manage_channels() {
|
||||||
@@ -295,7 +347,7 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
|||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
json!({ "error": "Failed to delete group." }),
|
json!({ "error": "Failed to delete channel." }),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -323,15 +375,19 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
1 => {
|
1 => {
|
||||||
let mut recipients =
|
let mut recipients = vec_to_set(
|
||||||
vec_to_set(&target.recipients.expect("Missing recipients on Group DM."));
|
target
|
||||||
let owner = target.owner.expect("Missing owner on Group DM.");
|
.recipients
|
||||||
|
.as_ref()
|
||||||
|
.expect("Missing recipients on Group DM."),
|
||||||
|
);
|
||||||
|
let owner = target.owner.as_ref().expect("Missing owner on Group DM.");
|
||||||
|
|
||||||
if recipients.len() == 1 {
|
if recipients.len() == 1 {
|
||||||
try_delete()
|
try_delete()
|
||||||
} else {
|
} else {
|
||||||
recipients.remove(&user.id);
|
recipients.remove(&user.id);
|
||||||
let new_owner = if owner == user.id {
|
let new_owner = if owner == &user.id {
|
||||||
recipients.iter().next().unwrap()
|
recipients.iter().next().unwrap()
|
||||||
} else {
|
} else {
|
||||||
&owner
|
&owner
|
||||||
@@ -352,7 +408,31 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Some(Response::Result(super::Status::Ok))
|
if (Message {
|
||||||
|
id: Ulid::new().to_string(),
|
||||||
|
nonce: None,
|
||||||
|
channel: target.id.clone(),
|
||||||
|
author: "system".to_string(),
|
||||||
|
content: format!("<@{}> left the group.", &user.id),
|
||||||
|
edited: None,
|
||||||
|
previous_content: vec![],
|
||||||
|
})
|
||||||
|
.send(&target)
|
||||||
|
{
|
||||||
|
notifications::send_message_given_channel(
|
||||||
|
Notification::group_user_leave(UserLeave {
|
||||||
|
id: target.id.clone(),
|
||||||
|
user: user.id.clone(),
|
||||||
|
}),
|
||||||
|
&target,
|
||||||
|
);
|
||||||
|
|
||||||
|
Some(Response::Result(super::Status::Ok))
|
||||||
|
} else {
|
||||||
|
Some(Response::PartialStatus(
|
||||||
|
json!({ "error": "Failed to send leave message, but you have left the group." }),
|
||||||
|
))
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
json!({ "error": "Failed to remove you from the group." }),
|
json!({ "error": "Failed to remove you from the group." }),
|
||||||
@@ -361,9 +441,10 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
2 => {
|
2 => {
|
||||||
|
let guild_id = target.guild.unwrap();
|
||||||
if database::get_collection("guilds")
|
if database::get_collection("guilds")
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! { "_id": target.guild.unwrap() },
|
doc! { "_id": &guild_id },
|
||||||
doc! {
|
doc! {
|
||||||
"$pull": {
|
"$pull": {
|
||||||
"invites": {
|
"invites": {
|
||||||
@@ -375,6 +456,15 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
None,
|
||||||
|
guild_id.clone(),
|
||||||
|
Notification::guild_channel_delete(ChannelDelete {
|
||||||
|
id: guild_id.clone(),
|
||||||
|
channel: target.id.clone(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
try_delete()
|
try_delete()
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
@@ -388,22 +478,60 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, FromForm)]
|
||||||
|
pub struct MessageFetchOptions {
|
||||||
|
limit: Option<i64>,
|
||||||
|
before: Option<String>,
|
||||||
|
after: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
/// fetch channel messages
|
/// fetch channel messages
|
||||||
#[get("/<target>/messages")]
|
#[get("/<target>/messages?<options..>")]
|
||||||
pub fn messages(user: UserRef, target: ChannelRef) -> Option<Response> {
|
pub fn messages(
|
||||||
|
user: UserRef,
|
||||||
|
target: Channel,
|
||||||
|
options: Form<MessageFetchOptions>,
|
||||||
|
) -> Option<Response> {
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_read_messages() {
|
if !permissions.get_read_messages() {
|
||||||
return Some(Response::LackingPermission(Permission::ReadMessages));
|
return Some(Response::LackingPermission(Permission::ReadMessages));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ! FIXME: update wiki to reflect changes
|
||||||
|
let mut query = doc! { "channel": target.id };
|
||||||
|
|
||||||
|
if let Some(before) = &options.before {
|
||||||
|
query.insert("_id", doc! { "$lt": before });
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(after) = &options.after {
|
||||||
|
query.insert("_id", doc! { "$gt": after });
|
||||||
|
}
|
||||||
|
|
||||||
|
let limit = if let Some(limit) = options.limit {
|
||||||
|
limit.min(100).max(0)
|
||||||
|
} else {
|
||||||
|
50
|
||||||
|
};
|
||||||
|
|
||||||
let col = database::get_collection("messages");
|
let col = database::get_collection("messages");
|
||||||
let result = col.find(doc! { "channel": target.id }, None).unwrap();
|
let result = col
|
||||||
|
.find(
|
||||||
|
query,
|
||||||
|
FindOptions::builder()
|
||||||
|
.limit(limit)
|
||||||
|
.sort(doc! {
|
||||||
|
"_id": -1
|
||||||
|
})
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let mut messages = Vec::new();
|
let mut messages = Vec::new();
|
||||||
for item in result {
|
for item in result {
|
||||||
let message: Message =
|
let message: Message =
|
||||||
from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap message.");
|
from_bson(Bson::Document(item.unwrap())).expect("Failed to unwrap message.");
|
||||||
messages.push(json!({
|
messages.push(json!({
|
||||||
"id": message.id,
|
"id": message.id,
|
||||||
"author": message.author,
|
"author": message.author,
|
||||||
@@ -425,7 +553,7 @@ pub struct SendMessage {
|
|||||||
#[post("/<target>/messages", data = "<message>")]
|
#[post("/<target>/messages", data = "<message>")]
|
||||||
pub fn send_message(
|
pub fn send_message(
|
||||||
user: UserRef,
|
user: UserRef,
|
||||||
target: ChannelRef,
|
target: Channel,
|
||||||
message: Json<SendMessage>,
|
message: Json<SendMessage>,
|
||||||
) -> Option<Response> {
|
) -> Option<Response> {
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
@@ -441,6 +569,12 @@ pub fn send_message(
|
|||||||
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();
|
||||||
|
|
||||||
|
if content.len() == 0 {
|
||||||
|
return Some(Response::NotAcceptable(
|
||||||
|
json!({ "error": "No message content!" }),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
let col = database::get_collection("messages");
|
let col = database::get_collection("messages");
|
||||||
if col
|
if col
|
||||||
.find_one(doc! { "nonce": nonce.clone() }, None)
|
.find_one(doc! { "nonce": nonce.clone() }, None)
|
||||||
@@ -453,109 +587,49 @@ pub fn send_message(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let id = Ulid::new().to_string();
|
let id = Ulid::new().to_string();
|
||||||
Some(
|
let message = Message {
|
||||||
if col
|
id: id.clone(),
|
||||||
.insert_one(
|
nonce: Some(nonce),
|
||||||
doc! {
|
channel: target.id.clone(),
|
||||||
"_id": &id,
|
author: user.id,
|
||||||
"nonce": nonce,
|
content,
|
||||||
"channel": &target.id,
|
edited: None,
|
||||||
"author": &user.id,
|
previous_content: vec![],
|
||||||
"content": &content,
|
};
|
||||||
},
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
let short_content: String = content.chars().take(24).collect();
|
|
||||||
let col = database::get_collection("channels");
|
|
||||||
|
|
||||||
// !! this stuff can be async
|
if message.send(&target) {
|
||||||
if target.channel_type == ChannelType::DM as u8
|
Some(Response::Success(json!({ "id": id })))
|
||||||
|| target.channel_type == ChannelType::GROUPDM as u8
|
} else {
|
||||||
{
|
Some(Response::BadRequest(
|
||||||
let mut update = doc! {
|
json!({ "error": "Failed to send message." }),
|
||||||
"$set": {
|
))
|
||||||
"last_message": {
|
}
|
||||||
"id": &id,
|
|
||||||
"user_id": &user.id,
|
|
||||||
"short_content": short_content,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if target.channel_type == ChannelType::DM as u8 {
|
|
||||||
update
|
|
||||||
.get_document_mut("$set")
|
|
||||||
.unwrap()
|
|
||||||
.insert("active", true);
|
|
||||||
}
|
|
||||||
|
|
||||||
if col
|
|
||||||
.update_one(doc! { "_id": &target.id }, update, None)
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
Response::Success(json!({ "id": id }))
|
|
||||||
} else {
|
|
||||||
Response::InternalServerError(json!({ "error": "Failed to update channel." }))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Response::Success(json!({ "id": id }))
|
|
||||||
}
|
|
||||||
|
|
||||||
/*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(),
|
|
||||||
);*/
|
|
||||||
} else {
|
|
||||||
Response::InternalServerError(json!({
|
|
||||||
"error": "Failed database query."
|
|
||||||
}))
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// get a message
|
/// get a message
|
||||||
#[get("/<target>/messages/<message>")]
|
#[get("/<target>/messages/<message>")]
|
||||||
pub fn get_message(user: UserRef, target: ChannelRef, message: Message) -> Option<Response> {
|
pub fn get_message(user: UserRef, target: Channel, message: Message) -> Option<Response> {
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_read_messages() {
|
if !permissions.get_read_messages() {
|
||||||
return Some(Response::LackingPermission(Permission::ReadMessages));
|
return Some(Response::LackingPermission(Permission::ReadMessages));
|
||||||
}
|
}
|
||||||
|
|
||||||
let prev =
|
// ! CHECK IF USER HAS PERMISSION TO VIEW EDITS OF MESSAGES
|
||||||
// ! CHECK IF USER HAS PERMISSION TO VIEW EDITS OF MESSAGES
|
let mut entries = vec![];
|
||||||
if let Some(previous) = message.previous_content {
|
for entry in message.previous_content {
|
||||||
let mut entries = vec![];
|
entries.push(json!({
|
||||||
for entry in previous {
|
"content": entry.content,
|
||||||
entries.push(json!({
|
"time": entry.time.timestamp(),
|
||||||
"content": entry.content,
|
}));
|
||||||
"time": entry.time.timestamp(),
|
}
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(entries)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
Some(Response::Success(json!({
|
Some(Response::Success(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": entries,
|
||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -568,7 +642,7 @@ pub struct EditMessage {
|
|||||||
#[patch("/<target>/messages/<message>", data = "<edit>")]
|
#[patch("/<target>/messages/<message>", data = "<edit>")]
|
||||||
pub fn edit_message(
|
pub fn edit_message(
|
||||||
user: UserRef,
|
user: UserRef,
|
||||||
target: ChannelRef,
|
target: Channel,
|
||||||
message: Message,
|
message: Message,
|
||||||
edit: Json<EditMessage>,
|
edit: Json<EditMessage>,
|
||||||
) -> Option<Response> {
|
) -> Option<Response> {
|
||||||
@@ -592,12 +666,12 @@ pub fn edit_message(
|
|||||||
doc! { "_id": message.id.clone() },
|
doc! { "_id": message.id.clone() },
|
||||||
doc! {
|
doc! {
|
||||||
"$set": {
|
"$set": {
|
||||||
"content": edit.content.clone(),
|
"content": &edit.content,
|
||||||
"edited": UtcDatetime(edited)
|
"edited": Bson::DateTime(edited)
|
||||||
},
|
},
|
||||||
"$push": {
|
"$push": {
|
||||||
"previous_content": {
|
"previous_content": {
|
||||||
"content": message.content,
|
"content": &message.content,
|
||||||
"time": time,
|
"time": time,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -605,19 +679,15 @@ pub fn edit_message(
|
|||||||
None,
|
None,
|
||||||
) {
|
) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
/*websocket::queue_message(
|
notifications::send_message_given_channel(
|
||||||
get_recipients(&target),
|
Notification::message_edit(Edit {
|
||||||
json!({
|
id: message.id.clone(),
|
||||||
"type": "message_update",
|
channel: target.id.clone(),
|
||||||
"data": {
|
author: message.author.clone(),
|
||||||
"id": message.id,
|
content: edit.content.clone(),
|
||||||
"channel": target.id,
|
}),
|
||||||
"content": edit.content.clone(),
|
&target,
|
||||||
"edited": edited.timestamp()
|
);
|
||||||
},
|
|
||||||
})
|
|
||||||
.to_string(),
|
|
||||||
);*/
|
|
||||||
|
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
}
|
}
|
||||||
@@ -629,7 +699,7 @@ pub fn edit_message(
|
|||||||
|
|
||||||
/// delete a message
|
/// delete a message
|
||||||
#[delete("/<target>/messages/<message>")]
|
#[delete("/<target>/messages/<message>")]
|
||||||
pub fn delete_message(user: UserRef, target: ChannelRef, message: Message) -> Option<Response> {
|
pub fn delete_message(user: UserRef, target: Channel, message: Message) -> Option<Response> {
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_manage_messages() {
|
if !permissions.get_manage_messages() {
|
||||||
@@ -642,17 +712,12 @@ pub fn delete_message(user: UserRef, target: ChannelRef, message: Message) -> Op
|
|||||||
|
|
||||||
match col.delete_one(doc! { "_id": &message.id }, None) {
|
match col.delete_one(doc! { "_id": &message.id }, None) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
/*websocket::queue_message(
|
notifications::send_message_given_channel(
|
||||||
get_recipients(&target),
|
Notification::message_delete(Delete {
|
||||||
json!({
|
id: message.id.clone(),
|
||||||
"type": "message_delete",
|
}),
|
||||||
"data": {
|
&target,
|
||||||
"id": message.id,
|
);
|
||||||
"channel": target.id
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.to_string(),
|
|
||||||
);*/
|
|
||||||
|
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
}
|
}
|
||||||
@@ -661,3 +726,24 @@ pub fn delete_message(user: UserRef, target: ChannelRef, message: Message) -> Op
|
|||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[options("/create")]
|
||||||
|
pub fn create_group_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>")]
|
||||||
|
pub fn channel_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/recipients/<_member>")]
|
||||||
|
pub fn member_preflight(_target: String, _member: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/messages")]
|
||||||
|
pub fn messages_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/messages/<_message>")]
|
||||||
|
pub fn message_preflight(_target: String, _message: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
|||||||
+161
-64
@@ -1,12 +1,17 @@
|
|||||||
use super::channel::ChannelType;
|
use super::channel::ChannelType;
|
||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::database::{self, channel::Channel, Permission, PermissionCalculator};
|
use crate::database::guild::{get_invite, get_member, Guild};
|
||||||
|
use crate::database::{
|
||||||
|
self, channel::fetch_channel, channel::Channel, Permission, PermissionCalculator,
|
||||||
|
};
|
||||||
use crate::guards::auth::UserRef;
|
use crate::guards::auth::UserRef;
|
||||||
use crate::guards::channel::ChannelRef;
|
use crate::notifications::{
|
||||||
use crate::guards::guild::{get_invite, get_member, GuildRef};
|
self,
|
||||||
|
events::{guilds::*, Notification},
|
||||||
|
};
|
||||||
use crate::util::gen_token;
|
use crate::util::gen_token;
|
||||||
|
|
||||||
use bson::{doc, from_bson, Bson};
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
use mongodb::options::{FindOneOptions, FindOptions};
|
use mongodb::options::{FindOneOptions, FindOptions};
|
||||||
use rocket::request::Form;
|
use rocket::request::Form;
|
||||||
use rocket_contrib::json::Json;
|
use rocket_contrib::json::Json;
|
||||||
@@ -88,7 +93,7 @@ pub fn my_guilds(user: UserRef) -> Response {
|
|||||||
|
|
||||||
/// fetch a guild
|
/// fetch a guild
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub fn guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
pub fn guild(user: UserRef, target: Guild) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
let col = database::get_collection("channels");
|
let col = database::get_collection("channels");
|
||||||
@@ -103,9 +108,7 @@ pub fn guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
|||||||
let mut channels = vec![];
|
let mut channels = vec![];
|
||||||
for item in results {
|
for item in results {
|
||||||
if let Ok(entry) = item {
|
if let Ok(entry) = item {
|
||||||
if let Ok(channel) =
|
if let Ok(channel) = from_bson(Bson::Document(entry)) as Result<Channel, _> {
|
||||||
from_bson(bson::Bson::Document(entry)) as Result<Channel, _>
|
|
||||||
{
|
|
||||||
channels.push(json!({
|
channels.push(json!({
|
||||||
"id": channel.id,
|
"id": channel.id,
|
||||||
"name": channel.name,
|
"name": channel.name,
|
||||||
@@ -131,7 +134,7 @@ pub fn guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
|||||||
|
|
||||||
/// delete or leave a guild
|
/// delete or leave a guild
|
||||||
#[delete("/<target>")]
|
#[delete("/<target>")]
|
||||||
pub fn remove_guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
pub fn remove_guild(user: UserRef, target: Guild) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if user.id == target.owner {
|
if user.id == target.owner {
|
||||||
@@ -171,19 +174,41 @@ pub fn remove_guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if database::get_collection("guilds")
|
if database::get_collection("members")
|
||||||
.delete_one(
|
.delete_many(
|
||||||
doc! {
|
doc! {
|
||||||
"_id": &target.id
|
"_id.guild": &target.id,
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Some(Response::Result(super::Status::Ok))
|
if database::get_collection("guilds")
|
||||||
|
.delete_one(
|
||||||
|
doc! {
|
||||||
|
"_id": &target.id
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
None,
|
||||||
|
target.id.clone(),
|
||||||
|
Notification::guild_delete(Delete {
|
||||||
|
id: target.id.clone(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
Some(Response::Result(super::Status::Ok))
|
||||||
|
} else {
|
||||||
|
Some(Response::InternalServerError(
|
||||||
|
json!({ "error": "Failed to delete guild." }),
|
||||||
|
))
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
json!({ "error": "Failed to delete guild." }),
|
json!({ "error": "Failed to delete guild members." }),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -212,6 +237,16 @@ pub fn remove_guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
None,
|
||||||
|
target.id.clone(),
|
||||||
|
Notification::guild_user_leave(UserLeave {
|
||||||
|
id: target.id.clone(),
|
||||||
|
user: user.id.clone(),
|
||||||
|
banned: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
@@ -230,11 +265,7 @@ pub struct CreateChannel {
|
|||||||
|
|
||||||
/// create a new channel
|
/// create a new channel
|
||||||
#[post("/<target>/channels", data = "<info>")]
|
#[post("/<target>/channels", data = "<info>")]
|
||||||
pub fn create_channel(
|
pub fn create_channel(user: UserRef, target: Guild, info: Json<CreateChannel>) -> Option<Response> {
|
||||||
user: UserRef,
|
|
||||||
target: GuildRef,
|
|
||||||
info: Json<CreateChannel>,
|
|
||||||
) -> Option<Response> {
|
|
||||||
let (permissions, _) = with_permissions!(user, target);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_manage_channels() {
|
if !permissions.get_manage_channels() {
|
||||||
@@ -268,13 +299,24 @@ pub fn create_channel(
|
|||||||
"nonce": &nonce,
|
"nonce": &nonce,
|
||||||
"type": 2,
|
"type": 2,
|
||||||
"guild": &target.id,
|
"guild": &target.id,
|
||||||
"name": name,
|
"name": &name,
|
||||||
"description": description,
|
"description": &description,
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
None,
|
||||||
|
target.id.clone(),
|
||||||
|
Notification::guild_channel_create(ChannelCreate {
|
||||||
|
id: target.id.clone(),
|
||||||
|
channel: id.clone(),
|
||||||
|
name: name.clone(),
|
||||||
|
description: description.clone(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
Some(Response::Success(json!({ "id": &id })))
|
Some(Response::Success(json!({ "id": &id })))
|
||||||
} else {
|
} else {
|
||||||
Some(Response::BadRequest(
|
Some(Response::BadRequest(
|
||||||
@@ -297,8 +339,8 @@ pub struct InviteOptions {
|
|||||||
#[post("/<target>/channels/<channel>/invite", data = "<_options>")]
|
#[post("/<target>/channels/<channel>/invite", data = "<_options>")]
|
||||||
pub fn create_invite(
|
pub fn create_invite(
|
||||||
user: UserRef,
|
user: UserRef,
|
||||||
target: GuildRef,
|
target: Guild,
|
||||||
channel: ChannelRef,
|
channel: Channel,
|
||||||
_options: Json<InviteOptions>,
|
_options: Json<InviteOptions>,
|
||||||
) -> Option<Response> {
|
) -> Option<Response> {
|
||||||
let (permissions, _) = with_permissions!(user, target);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
@@ -334,7 +376,7 @@ pub fn create_invite(
|
|||||||
|
|
||||||
/// remove an invite
|
/// remove an invite
|
||||||
#[delete("/<target>/invites/<code>")]
|
#[delete("/<target>/invites/<code>")]
|
||||||
pub fn remove_invite(user: UserRef, target: GuildRef, code: String) -> Option<Response> {
|
pub fn remove_invite(user: UserRef, target: Guild, code: String) -> Option<Response> {
|
||||||
let (permissions, _) = with_permissions!(user, target);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if let Some((guild_id, _, invite)) = get_invite(&code, None) {
|
if let Some((guild_id, _, invite)) = get_invite(&code, None) {
|
||||||
@@ -375,41 +417,38 @@ pub fn remove_invite(user: UserRef, target: GuildRef, code: String) -> Option<Re
|
|||||||
|
|
||||||
/// fetch all guild invites
|
/// fetch all guild invites
|
||||||
#[get("/<target>/invites")]
|
#[get("/<target>/invites")]
|
||||||
pub fn fetch_invites(user: UserRef, target: GuildRef) -> Option<Response> {
|
pub fn fetch_invites(user: UserRef, target: Guild) -> Option<Response> {
|
||||||
let (permissions, _) = with_permissions!(user, target);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_manage_server() {
|
if !permissions.get_manage_server() {
|
||||||
return Some(Response::LackingPermission(Permission::ManageServer));
|
return Some(Response::LackingPermission(Permission::ManageServer));
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(doc) = target.fetch_data(doc! {
|
Some(Response::Success(json!(target.invites)))
|
||||||
"invites": 1,
|
|
||||||
}) {
|
|
||||||
Some(Response::Success(json!(doc.get_array("invites").unwrap())))
|
|
||||||
} else {
|
|
||||||
Some(Response::InternalServerError(
|
|
||||||
json!({ "error": "Failed to fetch invites." }),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// view an invite before joining
|
/// view an invite before joining
|
||||||
#[get("/join/<code>", rank = 1)]
|
#[get("/join/<code>", rank = 1)]
|
||||||
pub fn fetch_invite(user: UserRef, code: String) -> Response {
|
pub fn fetch_invite(user: UserRef, code: String) -> Response {
|
||||||
if let Some((guild_id, name, invite)) = get_invite(&code, user.id) {
|
if let Some((guild_id, name, invite)) = get_invite(&code, user.id) {
|
||||||
if let Some(channel) = ChannelRef::from(invite.channel) {
|
match fetch_channel(&invite.channel) {
|
||||||
Response::Success(json!({
|
Ok(result) => {
|
||||||
"guild": {
|
if let Some(channel) = result {
|
||||||
"id": guild_id,
|
Response::Success(json!({
|
||||||
"name": name,
|
"guild": {
|
||||||
},
|
"id": guild_id,
|
||||||
"channel": {
|
"name": name,
|
||||||
"id": channel.id,
|
},
|
||||||
"name": channel.name,
|
"channel": {
|
||||||
|
"id": channel.id,
|
||||||
|
"name": channel.name,
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
} else {
|
||||||
|
Response::NotFound(json!({ "error": "Channel does not exist." }))
|
||||||
}
|
}
|
||||||
}))
|
}
|
||||||
} else {
|
Err(err) => Response::InternalServerError(json!({ "error": err })),
|
||||||
Response::BadRequest(json!({ "error": "Failed to fetch channel." }))
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Response::NotFound(json!({ "error": "Failed to fetch invite or code is invalid." }))
|
Response::NotFound(json!({ "error": "Failed to fetch invite or code is invalid." }))
|
||||||
@@ -442,6 +481,15 @@ pub fn use_invite(user: UserRef, code: String) -> Response {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
None,
|
||||||
|
guild_id.clone(),
|
||||||
|
Notification::guild_user_join(UserJoin {
|
||||||
|
id: guild_id.clone(),
|
||||||
|
user: user.id.clone(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
"guild": &guild_id,
|
"guild": &guild_id,
|
||||||
"channel": &invite.channel,
|
"channel": &invite.channel,
|
||||||
@@ -563,7 +611,7 @@ pub fn create_guild(user: UserRef, info: Json<CreateGuild>) -> Response {
|
|||||||
|
|
||||||
/// fetch a guild's member
|
/// fetch a guild's member
|
||||||
#[get("/<target>/members")]
|
#[get("/<target>/members")]
|
||||||
pub fn fetch_members(user: UserRef, target: GuildRef) -> Option<Response> {
|
pub fn fetch_members(user: UserRef, target: Guild) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if let Ok(result) =
|
if let Ok(result) =
|
||||||
@@ -590,7 +638,7 @@ pub fn fetch_members(user: UserRef, target: GuildRef) -> Option<Response> {
|
|||||||
|
|
||||||
/// fetch a guild member
|
/// fetch a guild member
|
||||||
#[get("/<target>/members/<other>")]
|
#[get("/<target>/members/<other>")]
|
||||||
pub fn fetch_member(user: UserRef, target: GuildRef, other: String) -> Option<Response> {
|
pub fn fetch_member(user: UserRef, target: Guild, other: String) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if let Some(member) = get_member(&target.id, &other) {
|
if let Some(member) = get_member(&target.id, &other) {
|
||||||
@@ -607,7 +655,7 @@ pub fn fetch_member(user: UserRef, target: GuildRef, other: String) -> Option<Re
|
|||||||
|
|
||||||
/// kick a guild member
|
/// kick a guild member
|
||||||
#[delete("/<target>/members/<other>")]
|
#[delete("/<target>/members/<other>")]
|
||||||
pub fn kick_member(user: UserRef, target: GuildRef, other: String) -> Option<Response> {
|
pub fn kick_member(user: UserRef, target: Guild, other: String) -> Option<Response> {
|
||||||
let (permissions, _) = with_permissions!(user, target);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if user.id == other {
|
if user.id == other {
|
||||||
@@ -636,6 +684,16 @@ pub fn kick_member(user: UserRef, target: GuildRef, other: String) -> Option<Res
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
None,
|
||||||
|
target.id.clone(),
|
||||||
|
Notification::guild_user_leave(UserLeave {
|
||||||
|
id: target.id.clone(),
|
||||||
|
user: other.clone(),
|
||||||
|
banned: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
@@ -653,7 +711,7 @@ pub struct BanOptions {
|
|||||||
#[put("/<target>/members/<other>/ban?<options..>")]
|
#[put("/<target>/members/<other>/ban?<options..>")]
|
||||||
pub fn ban_member(
|
pub fn ban_member(
|
||||||
user: UserRef,
|
user: UserRef,
|
||||||
target: GuildRef,
|
target: Guild,
|
||||||
other: String,
|
other: String,
|
||||||
options: Form<BanOptions>,
|
options: Form<BanOptions>,
|
||||||
) -> Option<Response> {
|
) -> Option<Response> {
|
||||||
@@ -712,6 +770,16 @@ pub fn ban_member(
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
None,
|
||||||
|
target.id.clone(),
|
||||||
|
Notification::guild_user_leave(UserLeave {
|
||||||
|
id: target.id.clone(),
|
||||||
|
user: other.clone(),
|
||||||
|
banned: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
@@ -722,7 +790,7 @@ pub fn ban_member(
|
|||||||
|
|
||||||
/// unban a guild member
|
/// unban a guild member
|
||||||
#[delete("/<target>/members/<other>/ban")]
|
#[delete("/<target>/members/<other>/ban")]
|
||||||
pub fn unban_member(user: UserRef, target: GuildRef, other: String) -> Option<Response> {
|
pub fn unban_member(user: UserRef, target: Guild, other: String) -> Option<Response> {
|
||||||
let (permissions, _) = with_permissions!(user, target);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if user.id == other {
|
if user.id == other {
|
||||||
@@ -735,19 +803,7 @@ pub fn unban_member(user: UserRef, target: GuildRef, other: String) -> Option<Re
|
|||||||
return Some(Response::LackingPermission(Permission::BanMembers));
|
return Some(Response::LackingPermission(Permission::BanMembers));
|
||||||
}
|
}
|
||||||
|
|
||||||
if target
|
if target.bans.iter().any(|v| v.id == other) {
|
||||||
.fetch_data_given(
|
|
||||||
doc! {
|
|
||||||
"bans": {
|
|
||||||
"$elemMatch": {
|
|
||||||
"id": &other
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
doc! {},
|
|
||||||
)
|
|
||||||
.is_none()
|
|
||||||
{
|
|
||||||
return Some(Response::BadRequest(json!({ "error": "User not banned." })));
|
return Some(Response::BadRequest(json!({ "error": "User not banned." })));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -776,3 +832,44 @@ pub fn unban_member(user: UserRef, target: GuildRef, other: String) -> Option<Re
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[options("/<_target>")]
|
||||||
|
pub fn guild_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/channels")]
|
||||||
|
pub fn create_channel_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/channels/<_channel>/invite")]
|
||||||
|
pub fn create_invite_preflight(_target: String, _channel: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/invites/<_code>")]
|
||||||
|
pub fn remove_invite_preflight(_target: String, _code: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/invites")]
|
||||||
|
pub fn fetch_invites_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/join/<_code>", rank = 1)]
|
||||||
|
pub fn invite_preflight(_code: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/create")]
|
||||||
|
pub fn create_guild_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/members")]
|
||||||
|
pub fn fetch_members_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/members/<_other>")]
|
||||||
|
pub fn fetch_member_preflight(_target: String, _other: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/members/<_other>/ban")]
|
||||||
|
pub fn ban_member_preflight(_target: String, _other: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
|||||||
+41
-12
@@ -19,6 +19,8 @@ pub enum Response {
|
|||||||
Success(JsonValue),
|
Success(JsonValue),
|
||||||
#[response()]
|
#[response()]
|
||||||
Redirect(Redirect),
|
Redirect(Redirect),
|
||||||
|
#[response(status = 207)]
|
||||||
|
PartialStatus(JsonValue),
|
||||||
#[response(status = 400)]
|
#[response(status = 400)]
|
||||||
BadRequest(JsonValue),
|
BadRequest(JsonValue),
|
||||||
#[response(status = 401)]
|
#[response(status = 401)]
|
||||||
@@ -33,6 +35,8 @@ pub enum Response {
|
|||||||
Conflict(JsonValue),
|
Conflict(JsonValue),
|
||||||
#[response(status = 410)]
|
#[response(status = 410)]
|
||||||
Gone(JsonValue),
|
Gone(JsonValue),
|
||||||
|
#[response(status = 418)]
|
||||||
|
Teapot(JsonValue),
|
||||||
#[response(status = 422)]
|
#[response(status = 422)]
|
||||||
UnprocessableEntity(JsonValue),
|
UnprocessableEntity(JsonValue),
|
||||||
#[response(status = 429)]
|
#[response(status = 429)]
|
||||||
@@ -51,8 +55,7 @@ impl<'a> rocket::response::Responder<'a> for Permission {
|
|||||||
.header(ContentType::JSON)
|
.header(ContentType::JSON)
|
||||||
.sized_body(Cursor::new(format!(
|
.sized_body(Cursor::new(format!(
|
||||||
"{{\"error\":\"Lacking permission: {:?}.\",\"permission\":{}}}",
|
"{{\"error\":\"Lacking permission: {:?}.\",\"permission\":{}}}",
|
||||||
self,
|
self, self as u32,
|
||||||
self as u32,
|
|
||||||
)))
|
)))
|
||||||
.ok()
|
.ok()
|
||||||
}
|
}
|
||||||
@@ -60,23 +63,28 @@ impl<'a> rocket::response::Responder<'a> for Permission {
|
|||||||
|
|
||||||
pub fn mount(rocket: Rocket) -> Rocket {
|
pub fn mount(rocket: Rocket) -> Rocket {
|
||||||
rocket
|
rocket
|
||||||
.mount("/api", routes![root::root])
|
.mount("/", routes![root::root, root::root_preflight, root::teapot])
|
||||||
.mount(
|
.mount(
|
||||||
"/api/account",
|
"/account",
|
||||||
routes![
|
routes![
|
||||||
account::create,
|
account::create,
|
||||||
account::verify_email,
|
account::verify_email,
|
||||||
account::resend_email,
|
account::resend_email,
|
||||||
account::login,
|
account::login,
|
||||||
account::token
|
account::token,
|
||||||
|
account::create_preflight,
|
||||||
|
account::verify_email_preflight,
|
||||||
|
account::resend_email_preflight,
|
||||||
|
account::login_preflight,
|
||||||
|
account::token_preflight,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
.mount(
|
.mount(
|
||||||
"/api/users",
|
"/users",
|
||||||
routes![
|
routes![
|
||||||
user::me,
|
user::me,
|
||||||
user::user,
|
user::user,
|
||||||
user::lookup,
|
user::query,
|
||||||
user::dms,
|
user::dms,
|
||||||
user::dm,
|
user::dm,
|
||||||
user::get_friends,
|
user::get_friends,
|
||||||
@@ -84,11 +92,17 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
user::add_friend,
|
user::add_friend,
|
||||||
user::remove_friend,
|
user::remove_friend,
|
||||||
user::block_user,
|
user::block_user,
|
||||||
user::unblock_user
|
user::unblock_user,
|
||||||
|
user::user_preflight,
|
||||||
|
user::query_preflight,
|
||||||
|
user::dms_preflight,
|
||||||
|
user::dm_preflight,
|
||||||
|
user::friend_preflight,
|
||||||
|
user::block_user_preflight,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
.mount(
|
.mount(
|
||||||
"/api/channels",
|
"/channels",
|
||||||
routes![
|
routes![
|
||||||
channel::create_group,
|
channel::create_group,
|
||||||
channel::channel,
|
channel::channel,
|
||||||
@@ -99,11 +113,16 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
channel::get_message,
|
channel::get_message,
|
||||||
channel::send_message,
|
channel::send_message,
|
||||||
channel::edit_message,
|
channel::edit_message,
|
||||||
channel::delete_message
|
channel::delete_message,
|
||||||
|
channel::create_group_preflight,
|
||||||
|
channel::channel_preflight,
|
||||||
|
channel::member_preflight,
|
||||||
|
channel::messages_preflight,
|
||||||
|
channel::message_preflight,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
.mount(
|
.mount(
|
||||||
"/api/guild",
|
"/guild",
|
||||||
routes![
|
routes![
|
||||||
guild::my_guilds,
|
guild::my_guilds,
|
||||||
guild::guild,
|
guild::guild,
|
||||||
@@ -119,7 +138,17 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
guild::fetch_member,
|
guild::fetch_member,
|
||||||
guild::kick_member,
|
guild::kick_member,
|
||||||
guild::ban_member,
|
guild::ban_member,
|
||||||
guild::unban_member
|
guild::unban_member,
|
||||||
|
guild::guild_preflight,
|
||||||
|
guild::create_channel_preflight,
|
||||||
|
guild::create_invite_preflight,
|
||||||
|
guild::remove_invite_preflight,
|
||||||
|
guild::fetch_invites_preflight,
|
||||||
|
guild::invite_preflight,
|
||||||
|
guild::create_guild_preflight,
|
||||||
|
guild::fetch_members_preflight,
|
||||||
|
guild::fetch_member_preflight,
|
||||||
|
guild::ban_member_preflight,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-2
@@ -1,11 +1,25 @@
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
|
|
||||||
use bson::doc;
|
use mongodb::bson::doc;
|
||||||
|
|
||||||
/// root
|
/// root
|
||||||
#[get("/")]
|
#[get("/")]
|
||||||
pub fn root() -> Response {
|
pub fn root() -> Response {
|
||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
"revolt": "0.0.1"
|
"revolt": "0.2.3"
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[options("/")]
|
||||||
|
pub fn root_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// I'm a teapot.
|
||||||
|
#[delete("/")]
|
||||||
|
pub fn teapot() -> Response {
|
||||||
|
Response::Teapot(json!({
|
||||||
|
"teapot": true,
|
||||||
|
"can_delete": false
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|||||||
+268
-27
@@ -1,10 +1,14 @@
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::database::{self, get_relationship, get_relationship_internal, mutual, Relationship};
|
use crate::database::{self, get_relationship, get_relationship_internal, mutual, Relationship};
|
||||||
use crate::guards::auth::UserRef;
|
use crate::guards::auth::UserRef;
|
||||||
|
use crate::notifications::{
|
||||||
|
self,
|
||||||
|
events::{users::*, Notification},
|
||||||
|
};
|
||||||
use crate::routes::channel;
|
use crate::routes::channel;
|
||||||
|
|
||||||
use bson::doc;
|
use mongodb::bson::doc;
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::{Collation, FindOneOptions, FindOptions};
|
||||||
use rocket_contrib::json::Json;
|
use rocket_contrib::json::Json;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
@@ -16,6 +20,7 @@ pub fn me(user: UserRef) -> Response {
|
|||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
"id": user.id,
|
"id": user.id,
|
||||||
"username": user.username,
|
"username": user.username,
|
||||||
|
"display_name": user.display_name,
|
||||||
"email": info.get_str("email").unwrap(),
|
"email": info.get_str("email").unwrap(),
|
||||||
"verified": user.email_verified,
|
"verified": user.email_verified,
|
||||||
}))
|
}))
|
||||||
@@ -32,7 +37,8 @@ pub fn user(user: UserRef, target: UserRef) -> Response {
|
|||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
"id": target.id,
|
"id": target.id,
|
||||||
"username": target.username,
|
"username": target.username,
|
||||||
"relationship": get_relationship(&user, &target) as u8,
|
"display_name": target.display_name,
|
||||||
|
"relationship": get_relationship(&user, &target) as i32,
|
||||||
"mutual": {
|
"mutual": {
|
||||||
"guilds": mutual::find_mutual_guilds(&user.id, &target.id),
|
"guilds": mutual::find_mutual_guilds(&user.id, &target.id),
|
||||||
"friends": mutual::find_mutual_friends(&user.id, &target.id),
|
"friends": mutual::find_mutual_friends(&user.id, &target.id),
|
||||||
@@ -42,6 +48,41 @@ pub fn user(user: UserRef, target: UserRef) -> Response {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct UserQuery {
|
||||||
|
username: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// find a user by their username
|
||||||
|
#[post("/query", data = "<query>")]
|
||||||
|
pub fn query(user: UserRef, query: Json<UserQuery>) -> Response {
|
||||||
|
let relationships = user.fetch_relationships();
|
||||||
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
|
if let Ok(result) = col.find_one(
|
||||||
|
doc! { "username": query.username.clone() },
|
||||||
|
FindOneOptions::builder()
|
||||||
|
.collation(Collation::builder().locale("en").strength(2).build())
|
||||||
|
.build(),
|
||||||
|
) {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
let id = doc.get_str("_id").unwrap();
|
||||||
|
Response::Success(json!({
|
||||||
|
"id": id,
|
||||||
|
"username": doc.get_str("username").unwrap(),
|
||||||
|
"display_name": doc.get_str("display_name").unwrap(),
|
||||||
|
"relationship": get_relationship_internal(&user.id, &id, &relationships) as i32
|
||||||
|
}))
|
||||||
|
} else {
|
||||||
|
Response::NotFound(json!({
|
||||||
|
"error": "User not found!"
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Response::InternalServerError(json!({ "error": "Failed database query." }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*#[derive(Serialize, Deserialize)]
|
||||||
pub struct LookupQuery {
|
pub struct LookupQuery {
|
||||||
username: String,
|
username: String,
|
||||||
}
|
}
|
||||||
@@ -67,7 +108,7 @@ pub fn lookup(user: UserRef, query: Json<LookupQuery>) -> Response {
|
|||||||
results.push(json!({
|
results.push(json!({
|
||||||
"id": id,
|
"id": id,
|
||||||
"username": doc.get_str("username").unwrap(),
|
"username": doc.get_str("username").unwrap(),
|
||||||
"relationship": get_relationship_internal(&user.id, &id, &relationships) as u8
|
"relationship": get_relationship_internal(&user.id, &id, &relationships) as i32
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -76,7 +117,7 @@ pub fn lookup(user: UserRef, query: Json<LookupQuery>) -> Response {
|
|||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(json!({ "error": "Failed database query." }))
|
Response::InternalServerError(json!({ "error": "Failed database query." }))
|
||||||
}
|
}
|
||||||
}
|
}*/
|
||||||
|
|
||||||
/// retrieve all of your DMs
|
/// retrieve all of your DMs
|
||||||
#[get("/@me/dms")]
|
#[get("/@me/dms")]
|
||||||
@@ -87,7 +128,8 @@ pub fn dms(user: UserRef) -> Response {
|
|||||||
doc! {
|
doc! {
|
||||||
"$or": [
|
"$or": [
|
||||||
{
|
{
|
||||||
"type": channel::ChannelType::DM as i32
|
"type": channel::ChannelType::DM as i32,
|
||||||
|
"active": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": channel::ChannelType::GROUPDM as i32
|
"type": channel::ChannelType::GROUPDM as i32
|
||||||
@@ -101,6 +143,7 @@ pub fn dms(user: UserRef) -> Response {
|
|||||||
for item in results {
|
for item in results {
|
||||||
if let Ok(doc) = item {
|
if let Ok(doc) = item {
|
||||||
let id = doc.get_str("_id").unwrap();
|
let id = doc.get_str("_id").unwrap();
|
||||||
|
let last_message = doc.get_document("last_message").unwrap();
|
||||||
let recipients = doc.get_array("recipients").unwrap();
|
let recipients = doc.get_array("recipients").unwrap();
|
||||||
|
|
||||||
match doc.get_i32("type").unwrap() {
|
match doc.get_i32("type").unwrap() {
|
||||||
@@ -108,6 +151,7 @@ pub fn dms(user: UserRef) -> Response {
|
|||||||
channels.push(json!({
|
channels.push(json!({
|
||||||
"id": id,
|
"id": id,
|
||||||
"type": 0,
|
"type": 0,
|
||||||
|
"last_message": last_message,
|
||||||
"recipients": recipients,
|
"recipients": recipients,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -186,7 +230,7 @@ pub fn get_friends(user: UserRef) -> Response {
|
|||||||
/// retrieve friend status with user
|
/// retrieve friend status with user
|
||||||
#[get("/<target>/friend")]
|
#[get("/<target>/friend")]
|
||||||
pub fn get_friend(user: UserRef, target: UserRef) -> Response {
|
pub fn get_friend(user: UserRef, target: UserRef) -> Response {
|
||||||
Response::Success(json!({ "status": get_relationship(&user, &target) as u8 }))
|
Response::Success(json!({ "status": get_relationship(&user, &target) as i32 }))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// create or accept a friend request
|
/// create or accept a friend request
|
||||||
@@ -218,8 +262,8 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
if col
|
if col
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! {
|
doc! {
|
||||||
"_id": target.id,
|
"_id": target.id.clone(),
|
||||||
"relations.id": user.id
|
"relations.id": user.id.clone()
|
||||||
},
|
},
|
||||||
doc! {
|
doc! {
|
||||||
"$set": {
|
"$set": {
|
||||||
@@ -230,7 +274,25 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Response::Success(json!({ "status": Relationship::Friend as u8 }))
|
notifications::send_message_threaded(
|
||||||
|
vec![target.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: user.id.clone(),
|
||||||
|
status: Relationship::Friend as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
vec![user.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: target.id.clone(),
|
||||||
|
status: Relationship::Friend as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
Response::Success(json!({ "status": Relationship::Friend as i32 }))
|
||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(
|
Response::InternalServerError(
|
||||||
json!({ "error": "Failed to commit! Try re-adding them as a friend." }),
|
json!({ "error": "Failed to commit! Try re-adding them as a friend." }),
|
||||||
@@ -269,12 +331,12 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
if col
|
if col
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! {
|
doc! {
|
||||||
"_id": target.id
|
"_id": target.id.clone()
|
||||||
},
|
},
|
||||||
doc! {
|
doc! {
|
||||||
"$push": {
|
"$push": {
|
||||||
"relations": {
|
"relations": {
|
||||||
"id": user.id,
|
"id": user.id.clone(),
|
||||||
"status": Relationship::Incoming as i32
|
"status": Relationship::Incoming as i32
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -283,7 +345,25 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Response::Success(json!({ "status": Relationship::Outgoing as u8 }))
|
notifications::send_message_threaded(
|
||||||
|
vec![user.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: target.id.clone(),
|
||||||
|
status: Relationship::Outgoing as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
vec![target.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: user.id.clone(),
|
||||||
|
status: Relationship::Incoming as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
Response::Success(json!({ "status": Relationship::Outgoing as i32 }))
|
||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(
|
Response::InternalServerError(
|
||||||
json!({ "error": "Failed to commit! Try re-adding them as a friend." }),
|
json!({ "error": "Failed to commit! Try re-adding them as a friend." }),
|
||||||
@@ -327,12 +407,12 @@ pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
if col
|
if col
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! {
|
doc! {
|
||||||
"_id": target.id
|
"_id": target.id.clone()
|
||||||
},
|
},
|
||||||
doc! {
|
doc! {
|
||||||
"$pull": {
|
"$pull": {
|
||||||
"relations": {
|
"relations": {
|
||||||
"id": user.id
|
"id": user.id.clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -340,7 +420,25 @@ pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Response::Success(json!({ "status": Relationship::NONE as u8 }))
|
notifications::send_message_threaded(
|
||||||
|
vec![user.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: target.id.clone(),
|
||||||
|
status: Relationship::NONE as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
vec![target.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: user.id.clone(),
|
||||||
|
status: Relationship::NONE as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
Response::Success(json!({ "status": Relationship::NONE as i32 }))
|
||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(
|
Response::InternalServerError(
|
||||||
json!({ "error": "Failed to commit! Target remains in same state." }),
|
json!({ "error": "Failed to commit! Target remains in same state." }),
|
||||||
@@ -384,8 +482,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
if col
|
if col
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! {
|
doc! {
|
||||||
"_id": target.id,
|
"_id": target.id.clone(),
|
||||||
"relations.id": user.id
|
"relations.id": user.id.clone()
|
||||||
},
|
},
|
||||||
doc! {
|
doc! {
|
||||||
"$set": {
|
"$set": {
|
||||||
@@ -396,7 +494,91 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Response::Success(json!({ "status": Relationship::Blocked as u8 }))
|
notifications::send_message_threaded(
|
||||||
|
vec![user.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: target.id.clone(),
|
||||||
|
status: Relationship::Blocked as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
vec![target.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: user.id.clone(),
|
||||||
|
status: Relationship::BlockedOther as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
Response::Success(json!({ "status": Relationship::Blocked as i32 }))
|
||||||
|
} else {
|
||||||
|
Response::InternalServerError(
|
||||||
|
json!({ "error": "Failed to commit! Try blocking the user again, remove it first." }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Response::InternalServerError(
|
||||||
|
json!({ "error": "Failed to commit to database, try again." }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Relationship::NONE => {
|
||||||
|
if col
|
||||||
|
.update_one(
|
||||||
|
doc! {
|
||||||
|
"_id": user.id.clone(),
|
||||||
|
},
|
||||||
|
doc! {
|
||||||
|
"$push": {
|
||||||
|
"relations": {
|
||||||
|
"id": target.id.clone(),
|
||||||
|
"status": Relationship::Blocked as i32,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
if col
|
||||||
|
.update_one(
|
||||||
|
doc! {
|
||||||
|
"_id": target.id.clone(),
|
||||||
|
},
|
||||||
|
doc! {
|
||||||
|
"$push": {
|
||||||
|
"relations": {
|
||||||
|
"id": user.id.clone(),
|
||||||
|
"status": Relationship::BlockedOther as i32,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
vec![user.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: target.id.clone(),
|
||||||
|
status: Relationship::Blocked as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
vec![target.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: user.id.clone(),
|
||||||
|
status: Relationship::BlockedOther as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
Response::Success(json!({ "status": Relationship::Blocked as i32 }))
|
||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(
|
Response::InternalServerError(
|
||||||
json!({ "error": "Failed to commit! Try blocking the user again, remove it first." }),
|
json!({ "error": "Failed to commit! Try blocking the user again, remove it first." }),
|
||||||
@@ -427,16 +609,23 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Response::Success(json!({ "status": Relationship::Blocked as u8 }))
|
notifications::send_message_threaded(
|
||||||
|
vec![user.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: target.id.clone(),
|
||||||
|
status: Relationship::Blocked as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
Response::Success(json!({ "status": Relationship::Blocked as i32 }))
|
||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(
|
Response::InternalServerError(
|
||||||
json!({ "error": "Failed to commit to database, try again." }),
|
json!({ "error": "Failed to commit to database, try again." }),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Relationship::SELF | Relationship::NONE => {
|
Relationship::SELF => Response::BadRequest(json!({ "error": "This has no effect." })),
|
||||||
Response::BadRequest(json!({ "error": "This has no effect." }))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -463,7 +652,16 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Response::Success(json!({ "status": Relationship::BlockedOther as u8 }))
|
notifications::send_message_threaded(
|
||||||
|
vec![user.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: target.id.clone(),
|
||||||
|
status: Relationship::BlockedOther as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
Response::Success(json!({ "status": Relationship::BlockedOther as i32 }))
|
||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(
|
Response::InternalServerError(
|
||||||
json!({ "error": "Failed to commit to database, try again." }),
|
json!({ "error": "Failed to commit to database, try again." }),
|
||||||
@@ -490,12 +688,12 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
if col
|
if col
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! {
|
doc! {
|
||||||
"_id": target.id
|
"_id": target.id.clone()
|
||||||
},
|
},
|
||||||
doc! {
|
doc! {
|
||||||
"$pull": {
|
"$pull": {
|
||||||
"relations": {
|
"relations": {
|
||||||
"id": user.id
|
"id": user.id.clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -503,7 +701,25 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Response::Success(json!({ "status": Relationship::NONE as u8 }))
|
notifications::send_message_threaded(
|
||||||
|
vec![user.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: target.id.clone(),
|
||||||
|
status: Relationship::NONE as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
vec![target.id.clone()],
|
||||||
|
None,
|
||||||
|
Notification::user_friend_status(FriendStatus {
|
||||||
|
id: user.id.clone(),
|
||||||
|
status: Relationship::NONE as i32,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
Response::Success(json!({ "status": Relationship::NONE as i32 }))
|
||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(
|
Response::InternalServerError(
|
||||||
json!({ "error": "Failed to commit! Target remains in same state." }),
|
json!({ "error": "Failed to commit! Target remains in same state." }),
|
||||||
@@ -527,3 +743,28 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
| Relationship::NONE => Response::BadRequest(json!({ "error": "This has no effect." })),
|
| Relationship::NONE => Response::BadRequest(json!({ "error": "This has no effect." })),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[options("/<_target>")]
|
||||||
|
pub fn user_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/query")]
|
||||||
|
pub fn query_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/@me/dms")]
|
||||||
|
pub fn dms_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/dm")]
|
||||||
|
pub fn dm_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/friend")]
|
||||||
|
pub fn friend_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/block")]
|
||||||
|
pub fn block_user_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,193 +0,0 @@
|
|||||||
extern crate ws;
|
|
||||||
|
|
||||||
use crate::database;
|
|
||||||
|
|
||||||
use hashbrown::HashMap;
|
|
||||||
use std::sync::RwLock;
|
|
||||||
use ulid::Ulid;
|
|
||||||
|
|
||||||
use bson::doc;
|
|
||||||
use serde_json::{from_str, json, Value};
|
|
||||||
|
|
||||||
use ws::{listen, CloseCode, Error, Handler, Handshake, Message, Result, Sender};
|
|
||||||
|
|
||||||
struct Cell {
|
|
||||||
id: String,
|
|
||||||
out: Sender,
|
|
||||||
}
|
|
||||||
|
|
||||||
use once_cell::sync::OnceCell;
|
|
||||||
static mut CLIENTS: OnceCell<RwLock<HashMap<String, Vec<Cell>>>> = OnceCell::new();
|
|
||||||
|
|
||||||
struct Server {
|
|
||||||
out: Sender,
|
|
||||||
id: Option<String>,
|
|
||||||
internal: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Handler for Server {
|
|
||||||
fn on_open(&mut self, _: Handshake) -> Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_message(&mut self, msg: Message) -> Result<()> {
|
|
||||||
if let Message::Text(text) = msg {
|
|
||||||
let data: Value = from_str(&text).unwrap();
|
|
||||||
|
|
||||||
if let Value::String(packet_type) = &data["type"] {
|
|
||||||
match packet_type.as_str() {
|
|
||||||
"authenticate" => {
|
|
||||||
if self.id.is_some() {
|
|
||||||
self.out.send(
|
|
||||||
json!({
|
|
||||||
"type": "authenticate",
|
|
||||||
"success": false,
|
|
||||||
"error": "Already authenticated!"
|
|
||||||
})
|
|
||||||
.to_string(),
|
|
||||||
)
|
|
||||||
} else if let Value::String(token) = &data["token"] {
|
|
||||||
let col = database::get_collection("users");
|
|
||||||
|
|
||||||
match col.find_one(doc! { "access_token": token }, None).unwrap() {
|
|
||||||
Some(u) => {
|
|
||||||
let id = u.get_str("_id").expect("Missing id.");
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
let mut map = CLIENTS.get_mut().unwrap().write().unwrap();
|
|
||||||
let cell = Cell {
|
|
||||||
id: self.internal.clone(),
|
|
||||||
out: self.out.clone(),
|
|
||||||
};
|
|
||||||
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
|
|
||||||
);
|
|
||||||
|
|
||||||
self.id = Some(id.to_string());
|
|
||||||
self.out.send(
|
|
||||||
json!({
|
|
||||||
"type": "authenticate",
|
|
||||||
"success": true
|
|
||||||
})
|
|
||||||
.to_string(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
None => self.out.send(
|
|
||||||
json!({
|
|
||||||
"type": "authenticate",
|
|
||||||
"success": false,
|
|
||||||
"error": "Invalid authentication token."
|
|
||||||
})
|
|
||||||
.to_string(),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
self.out.send(
|
|
||||||
json!({
|
|
||||||
"type": "authenticate",
|
|
||||||
"success": false,
|
|
||||||
"error": "Missing authentication token."
|
|
||||||
})
|
|
||||||
.to_string(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => Ok(()),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_close(&mut self, code: CloseCode, reason: &str) {
|
|
||||||
match code {
|
|
||||||
CloseCode::Normal => println!("The client is done with the connection."),
|
|
||||||
CloseCode::Away => println!("The client is leaving the site."),
|
|
||||||
CloseCode::Abnormal => {
|
|
||||||
println!("Closing handshake failed! Unable to obtain closing status from client.")
|
|
||||||
}
|
|
||||||
_ => println!("The client encountered an error: {}", reason),
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(id) = &self.id {
|
|
||||||
println!(
|
|
||||||
"Websocket client disconnected. [ID: {} // {}]",
|
|
||||||
id, self.internal
|
|
||||||
);
|
|
||||||
unsafe {
|
|
||||||
let mut map = CLIENTS.get_mut().unwrap().write().unwrap();
|
|
||||||
let arr = map.get_mut(&id.clone()).unwrap();
|
|
||||||
|
|
||||||
if arr.len() == 1 {
|
|
||||||
map.remove(&id.clone());
|
|
||||||
} else {
|
|
||||||
let index = arr.iter().position(|x| x.id == self.internal).unwrap();
|
|
||||||
arr.remove(index);
|
|
||||||
println!(
|
|
||||||
"User [{}] is still connected {} times",
|
|
||||||
self.id.as_ref().unwrap(),
|
|
||||||
arr.len()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_error(&mut self, err: Error) {
|
|
||||||
println!("The server encountered an error: {:?}", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn launch_server() {
|
|
||||||
unsafe {
|
|
||||||
if CLIENTS.set(RwLock::new(HashMap::new())).is_err() {
|
|
||||||
panic!("Failed to set CLIENTS map!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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<(), ()> {
|
|
||||||
unsafe {
|
|
||||||
let map = CLIENTS.get().unwrap().read().unwrap();
|
|
||||||
if map.contains_key(&id) {
|
|
||||||
let arr = map.get(&id).unwrap();
|
|
||||||
|
|
||||||
for item in arr {
|
|
||||||
if item.out.send(message.clone()).is_err() {
|
|
||||||
return Err(());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ! TODO: WRITE THREADED QUEUE SYSTEM
|
|
||||||
// ! FETCH RECIPIENTS HERE INSTEAD OF IN METHOD
|
|
||||||
|
|
||||||
pub fn queue_message(ids: Vec<String>, message: String) {
|
|
||||||
for id in ids {
|
|
||||||
send_message(id, message.clone())
|
|
||||||
.expect("uhhhhhhhhhh can i get uhhhhhhhhhhhhhhhhhh mcdonald cheese burger with fries");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user