Switch to async Rust and break all logic.
This commit is contained in:
1673
Cargo.lock
generated
1673
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
44
Cargo.toml
44
Cargo.toml
@@ -7,29 +7,35 @@ 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 = { version = "1.1.1", default-features = false, features = ["sync"] } # FIXME: rewrite database with async API
|
tokio = "0.2.22"
|
||||||
rocket = { version = "0.4.5", default-features = false }
|
many-to-many = "0.1.2"
|
||||||
|
#rauth = { git = "https://gitlab.insrt.uk/insert/rauth" }
|
||||||
|
|
||||||
|
hive_pubsub = { version = "0.4.1", features = ["mongo"] }
|
||||||
|
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors" }
|
||||||
|
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket" }
|
||||||
|
rocket = { git = "https://github.com/SergioBenitez/Rocket", default-features = false }
|
||||||
|
mongodb = { version = "1.1.1", features = ["tokio-runtime"], default-features = false }
|
||||||
|
|
||||||
once_cell = "1.4.1"
|
once_cell = "1.4.1"
|
||||||
dotenv = "0.15.0"
|
dotenv = "0.15.0"
|
||||||
ulid = "0.4.0"
|
ulid = "0.4.1"
|
||||||
|
|
||||||
serde = { version = "1.0.115", features = ["derive"] }
|
serde = { version = "1.0.115", features = ["derive"] }
|
||||||
rocket_contrib = "0.4.5"
|
|
||||||
validator = "0.10.1"
|
|
||||||
bcrypt = "0.8.2"
|
|
||||||
chrono = "0.4.15"
|
|
||||||
rand = "0.7.3"
|
|
||||||
time = "0.2.16"
|
|
||||||
reqwest = { version = "0.10.8", features = ["blocking", "json"] }
|
|
||||||
num_enum = "0.5.1"
|
|
||||||
ws = "0.9.1"
|
|
||||||
hashbrown = "0.8.2"
|
|
||||||
serde_json = "1.0.57"
|
serde_json = "1.0.57"
|
||||||
rocket_cors = "0.5.2"
|
validator = "0.10.1"
|
||||||
bitfield = "0.13.2"
|
bitfield = "0.13.2"
|
||||||
lru = "0.6.0"
|
|
||||||
|
reqwest = { version = "0.10.8", features = ["json"] }
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
log = "0.4.11"
|
num_enum = "0.5.1"
|
||||||
env_logger = "0.7.1"
|
chrono = "0.4.15"
|
||||||
|
bcrypt = "0.8.2"
|
||||||
|
time = "0.2.16"
|
||||||
|
rand = "0.7.3"
|
||||||
|
lru = "0.6.0"
|
||||||
|
ws = "0.9.1"
|
||||||
|
|
||||||
lettre = "0.10.0-alpha.1"
|
lettre = "0.10.0-alpha.1"
|
||||||
hive_pubsub = { version = "0.3.1", features = ["mongo"] }
|
env_logger = "0.7.1"
|
||||||
many-to-many = "0.1.2"
|
log = "0.4.11"
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use rocket::request::FromParam;
|
|||||||
use rocket_contrib::json::JsonValue;
|
use rocket_contrib::json::JsonValue;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
use rocket::futures::StreamExt;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct LastMessage {
|
pub struct LastMessage {
|
||||||
@@ -76,7 +77,7 @@ lazy_static! {
|
|||||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
pub async fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
||||||
{
|
{
|
||||||
if let Ok(mut cache) = CACHE.lock() {
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
let existing = cache.get(&id.to_string());
|
let existing = cache.get(&id.to_string());
|
||||||
@@ -90,7 +91,7 @@ pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let col = get_collection("channels");
|
let col = get_collection("channels");
|
||||||
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
if let Ok(result) = col.find_one(doc! { "_id": id }, None).await {
|
||||||
if let Some(doc) = result {
|
if let Some(doc) = result {
|
||||||
if let Ok(channel) = from_bson(Bson::Document(doc)) as Result<Channel, _> {
|
if let Ok(channel) = from_bson(Bson::Document(doc)) as Result<Channel, _> {
|
||||||
let mut cache = CACHE.lock().unwrap();
|
let mut cache = CACHE.lock().unwrap();
|
||||||
@@ -108,7 +109,7 @@ pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
|
pub async fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
|
||||||
let mut missing = vec![];
|
let mut missing = vec![];
|
||||||
let mut channels = vec![];
|
let mut channels = vec![];
|
||||||
|
|
||||||
@@ -133,8 +134,8 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let col = get_collection("channels");
|
let col = get_collection("channels");
|
||||||
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
if let Ok(mut result) = col.find(doc! { "_id": { "$in": missing } }, None).await {
|
||||||
for item in result {
|
while let Some(item) = result.next().await {
|
||||||
let mut cache = CACHE.lock().unwrap();
|
let mut cache = CACHE.lock().unwrap();
|
||||||
if let Ok(doc) = item {
|
if let Ok(doc) = item {
|
||||||
if let Ok(channel) = from_bson(Bson::Document(doc)) as Result<Channel, _> {
|
if let Ok(channel) = from_bson(Bson::Document(doc)) as Result<Channel, _> {
|
||||||
@@ -158,7 +159,8 @@ impl<'r> FromParam<'r> for Channel {
|
|||||||
type Error = &'r RawStr;
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||||
if let Ok(result) = fetch_channel(param) {
|
Err(param)
|
||||||
|
/*if let Ok(result) = fetch_channel(param).await {
|
||||||
if let Some(channel) = result {
|
if let Some(channel) = result {
|
||||||
Ok(channel)
|
Ok(channel)
|
||||||
} else {
|
} else {
|
||||||
@@ -166,7 +168,7 @@ impl<'r> FromParam<'r> for Channel {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Err(param)
|
Err(param)
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use super::channel::fetch_channels;
|
|||||||
use super::get_collection;
|
use super::get_collection;
|
||||||
|
|
||||||
use lru::LruCache;
|
use lru::LruCache;
|
||||||
|
use rocket::futures::StreamExt;
|
||||||
use mongodb::bson::{doc, from_bson, Bson};
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
use rocket::http::RawStr;
|
use rocket::http::RawStr;
|
||||||
use rocket::request::FromParam;
|
use rocket::request::FromParam;
|
||||||
@@ -61,13 +62,14 @@ impl Guild {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_channels(&self) -> Result<Vec<super::channel::Channel>, String> {
|
pub async fn fetch_channels(&self) -> Result<Vec<super::channel::Channel>, String> {
|
||||||
super::channel::fetch_channels(&self.channels)
|
super::channel::fetch_channels(&self.channels).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn seralise_with_channels(self) -> Result<JsonValue, String> {
|
pub async fn seralise_with_channels(self) -> Result<JsonValue, String> {
|
||||||
let channels = self
|
let channels = self
|
||||||
.fetch_channels()?
|
.fetch_channels()
|
||||||
|
.await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|x| x.serialise())
|
.map(|x| x.serialise())
|
||||||
.collect();
|
.collect();
|
||||||
@@ -91,7 +93,7 @@ lazy_static! {
|
|||||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
pub async fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
||||||
{
|
{
|
||||||
if let Ok(mut cache) = CACHE.lock() {
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
let existing = cache.get(&id.to_string());
|
let existing = cache.get(&id.to_string());
|
||||||
@@ -105,7 +107,7 @@ pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let col = get_collection("guilds");
|
let col = get_collection("guilds");
|
||||||
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
if let Ok(result) = col.find_one(doc! { "_id": id }, None).await {
|
||||||
if let Some(doc) = result {
|
if let Some(doc) = result {
|
||||||
dbg!(doc.to_string());
|
dbg!(doc.to_string());
|
||||||
if let Ok(guild) = from_bson(Bson::Document(doc)) as Result<Guild, _> {
|
if let Ok(guild) = from_bson(Bson::Document(doc)) as Result<Guild, _> {
|
||||||
@@ -124,7 +126,7 @@ pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
|
pub async fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
|
||||||
let mut missing = vec![];
|
let mut missing = vec![];
|
||||||
let mut guilds = vec![];
|
let mut guilds = vec![];
|
||||||
|
|
||||||
@@ -149,8 +151,8 @@ pub fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let col = get_collection("guilds");
|
let col = get_collection("guilds");
|
||||||
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
if let Ok(mut result) = col.find(doc! { "_id": { "$in": missing } }, None).await {
|
||||||
for item in result {
|
if let Some(item) = result.next().await {
|
||||||
let mut cache = CACHE.lock().unwrap();
|
let mut cache = CACHE.lock().unwrap();
|
||||||
if let Ok(doc) = item {
|
if let Ok(doc) = item {
|
||||||
dbg!(doc.to_string());
|
dbg!(doc.to_string());
|
||||||
@@ -171,11 +173,11 @@ pub fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue>, String> {
|
pub async fn serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue>, String> {
|
||||||
let guilds = fetch_guilds(&ids)?;
|
let guilds = fetch_guilds(&ids).await?;
|
||||||
let cids: Vec<String> = guilds.iter().flat_map(|x| x.channels.clone()).collect();
|
let cids: Vec<String> = guilds.iter().flat_map(|x| x.channels.clone()).collect();
|
||||||
|
|
||||||
let channels = fetch_channels(&cids)?;
|
let channels = fetch_channels(&cids).await?;
|
||||||
Ok(guilds
|
Ok(guilds
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|x| {
|
.map(|x| {
|
||||||
@@ -194,7 +196,7 @@ pub fn serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue
|
|||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
|
pub async fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
|
||||||
{
|
{
|
||||||
if let Ok(mut cache) = MEMBER_CACHE.lock() {
|
if let Ok(mut cache) = MEMBER_CACHE.lock() {
|
||||||
let existing = cache.get(&key);
|
let existing = cache.get(&key);
|
||||||
@@ -214,7 +216,7 @@ pub fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
|
|||||||
"_id.user": &key.1,
|
"_id.user": &key.1,
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
) {
|
).await {
|
||||||
if let Some(doc) = result {
|
if let Some(doc) = result {
|
||||||
if let Ok(member) = from_bson(Bson::Document(doc)) as Result<Member, _> {
|
if let Ok(member) = from_bson(Bson::Document(doc)) as Result<Member, _> {
|
||||||
let mut cache = MEMBER_CACHE.lock().unwrap();
|
let mut cache = MEMBER_CACHE.lock().unwrap();
|
||||||
@@ -236,7 +238,8 @@ impl<'r> FromParam<'r> for Guild {
|
|||||||
type Error = &'r RawStr;
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||||
if let Ok(result) = fetch_guild(param) {
|
Err(param)
|
||||||
|
/*if let Ok(result) = fetch_guild(param) {
|
||||||
if let Some(channel) = result {
|
if let Some(channel) = result {
|
||||||
Ok(channel)
|
Ok(channel)
|
||||||
} else {
|
} else {
|
||||||
@@ -244,11 +247,11 @@ impl<'r> FromParam<'r> for Guild {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Err(param)
|
Err(param)
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_invite<U: Into<Option<String>>>(
|
pub async fn get_invite<U: Into<Option<String>>>(
|
||||||
code: &String,
|
code: &String,
|
||||||
user: U,
|
user: U,
|
||||||
) -> Option<(String, String, Invite)> {
|
) -> Option<(String, String, Invite)> {
|
||||||
@@ -282,7 +285,7 @@ pub fn get_invite<U: Into<Option<String>>>(
|
|||||||
"invites.$": 1,
|
"invites.$": 1,
|
||||||
})
|
})
|
||||||
.build(),
|
.build(),
|
||||||
) {
|
).await {
|
||||||
if let Some(doc) = result {
|
if let Some(doc) = result {
|
||||||
let invite = doc
|
let invite = doc
|
||||||
.get_array("invites")
|
.get_array("invites")
|
||||||
|
|||||||
@@ -3,8 +3,10 @@ use crate::database::channel::Channel;
|
|||||||
use crate::pubsub::hive;
|
use crate::pubsub::hive;
|
||||||
use crate::routes::channel::ChannelType;
|
use crate::routes::channel::ChannelType;
|
||||||
|
|
||||||
use mongodb::bson::from_bson;
|
//use mongodb::bson::from_bson;
|
||||||
use mongodb::bson::{doc, to_bson, Bson, DateTime};
|
//use rocket::futures::StreamExt;
|
||||||
|
//use mongodb::bson::{doc, to_bson, Bson, DateTime};
|
||||||
|
use mongodb::bson::{doc, to_bson, DateTime};
|
||||||
use rocket::http::RawStr;
|
use rocket::http::RawStr;
|
||||||
use rocket::request::FromParam;
|
use rocket::request::FromParam;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -35,22 +37,12 @@ pub struct Message {
|
|||||||
// ? pub fn send_message();
|
// ? pub fn send_message();
|
||||||
// ? handle websockets?
|
// ? handle websockets?
|
||||||
impl Message {
|
impl Message {
|
||||||
pub fn send(&self, target: &Channel) -> bool {
|
pub async fn send(&self, target: &Channel) -> bool {
|
||||||
if get_collection("messages")
|
if get_collection("messages")
|
||||||
.insert_one(to_bson(&self).unwrap().as_document().unwrap().clone(), None)
|
.insert_one(to_bson(&self).unwrap().as_document().unwrap().clone(), None)
|
||||||
|
.await
|
||||||
.is_ok()
|
.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,
|
|
||||||
);*/
|
|
||||||
|
|
||||||
if hive::publish(
|
if hive::publish(
|
||||||
&target.id,
|
&target.id,
|
||||||
crate::pubsub::events::Notification::message_create(
|
crate::pubsub::events::Notification::message_create(
|
||||||
@@ -93,6 +85,7 @@ impl Message {
|
|||||||
|
|
||||||
if get_collection("channels")
|
if get_collection("channels")
|
||||||
.update_one(doc! { "_id": &target.id }, update, None)
|
.update_one(doc! { "_id": &target.id }, update, None)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
true
|
true
|
||||||
@@ -112,7 +105,8 @@ impl<'r> FromParam<'r> for Message {
|
|||||||
type Error = &'r RawStr;
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||||
let col = get_collection("messages");
|
Err(param)
|
||||||
|
/*let col = get_collection("messages");
|
||||||
let result = col
|
let result = col
|
||||||
.find_one(doc! { "_id": param.to_string() }, None)
|
.find_one(doc! { "_id": param.to_string() }, None)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -121,6 +115,6 @@ impl<'r> FromParam<'r> for Message {
|
|||||||
Ok(from_bson(Bson::Document(message)).expect("Failed to unwrap message."))
|
Ok(from_bson(Bson::Document(message)).expect("Failed to unwrap message."))
|
||||||
} else {
|
} else {
|
||||||
Err(param)
|
Err(param)
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,21 +5,32 @@ use log::info;
|
|||||||
use mongodb::bson::doc;
|
use mongodb::bson::doc;
|
||||||
use mongodb::options::CreateCollectionOptions;
|
use mongodb::options::CreateCollectionOptions;
|
||||||
|
|
||||||
pub fn create_database() {
|
pub async fn create_database() {
|
||||||
info!("Creating database.");
|
info!("Creating database.");
|
||||||
let db = get_db();
|
let db = get_db();
|
||||||
|
|
||||||
db.create_collection("users", None)
|
db.create_collection("users", None)
|
||||||
|
.await
|
||||||
.expect("Failed to create users collection.");
|
.expect("Failed to create users collection.");
|
||||||
|
|
||||||
db.create_collection("channels", None)
|
db.create_collection("channels", None)
|
||||||
|
.await
|
||||||
.expect("Failed to create channels collection.");
|
.expect("Failed to create channels collection.");
|
||||||
|
|
||||||
db.create_collection("guilds", None)
|
db.create_collection("guilds", None)
|
||||||
|
.await
|
||||||
.expect("Failed to create guilds collection.");
|
.expect("Failed to create guilds collection.");
|
||||||
|
|
||||||
db.create_collection("members", None)
|
db.create_collection("members", None)
|
||||||
|
.await
|
||||||
.expect("Failed to create members collection.");
|
.expect("Failed to create members collection.");
|
||||||
|
|
||||||
db.create_collection("messages", None)
|
db.create_collection("messages", None)
|
||||||
|
.await
|
||||||
.expect("Failed to create messages collection.");
|
.expect("Failed to create messages collection.");
|
||||||
|
|
||||||
db.create_collection("migrations", None)
|
db.create_collection("migrations", None)
|
||||||
|
.await
|
||||||
.expect("Failed to create migrations collection.");
|
.expect("Failed to create migrations collection.");
|
||||||
|
|
||||||
db.create_collection(
|
db.create_collection(
|
||||||
@@ -29,6 +40,7 @@ pub fn create_database() {
|
|||||||
.size(1_000_000)
|
.size(1_000_000)
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.expect("Failed to create pubsub collection.");
|
.expect("Failed to create pubsub collection.");
|
||||||
|
|
||||||
db.collection("migrations")
|
db.collection("migrations")
|
||||||
@@ -39,6 +51,7 @@ pub fn create_database() {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.expect("Failed to save migration info.");
|
.expect("Failed to save migration info.");
|
||||||
|
|
||||||
info!("Created database.");
|
info!("Created database.");
|
||||||
|
|||||||
@@ -3,16 +3,17 @@ use super::get_connection;
|
|||||||
pub mod init;
|
pub mod init;
|
||||||
pub mod scripts;
|
pub mod scripts;
|
||||||
|
|
||||||
pub fn run_migrations() {
|
pub async fn run_migrations() {
|
||||||
let client = get_connection();
|
let client = get_connection();
|
||||||
|
|
||||||
let list = client
|
let list = client
|
||||||
.list_database_names(None, None)
|
.list_database_names(None, None)
|
||||||
|
.await
|
||||||
.expect("Failed to fetch database names.");
|
.expect("Failed to fetch database names.");
|
||||||
|
|
||||||
if list.iter().position(|x| x == "revolt").is_none() {
|
if list.iter().position(|x| x == "revolt").is_none() {
|
||||||
init::create_database();
|
init::create_database().await;
|
||||||
} else {
|
} else {
|
||||||
scripts::migrate_database();
|
scripts::migrate_database().await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
use super::super::get_collection;
|
use super::super::get_collection;
|
||||||
|
|
||||||
use log::info;
|
use log::info;
|
||||||
use mongodb::bson::{doc, from_bson, Bson};
|
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::FindOptions;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use crate::rocket::futures::StreamExt;
|
||||||
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
struct MigrationInfo {
|
struct MigrationInfo {
|
||||||
@@ -13,17 +14,18 @@ struct MigrationInfo {
|
|||||||
|
|
||||||
pub const LATEST_REVISION: i32 = 2;
|
pub const LATEST_REVISION: i32 = 2;
|
||||||
|
|
||||||
pub fn migrate_database() {
|
pub async fn migrate_database() {
|
||||||
let migrations = get_collection("migrations");
|
let migrations = get_collection("migrations");
|
||||||
let data = migrations
|
let data = migrations
|
||||||
.find_one(None, None)
|
.find_one(None, None)
|
||||||
|
.await
|
||||||
.expect("Failed to fetch migration data.");
|
.expect("Failed to fetch migration data.");
|
||||||
|
|
||||||
if let Some(doc) = data {
|
if let Some(doc) = data {
|
||||||
let info: MigrationInfo =
|
let info: MigrationInfo =
|
||||||
from_bson(Bson::Document(doc)).expect("Failed to read migration information.");
|
from_bson(Bson::Document(doc)).expect("Failed to read migration information.");
|
||||||
|
|
||||||
let revision = run_migrations(info.revision);
|
let revision = run_migrations(info.revision).await;
|
||||||
|
|
||||||
migrations
|
migrations
|
||||||
.update_one(
|
.update_one(
|
||||||
@@ -37,6 +39,7 @@ pub fn migrate_database() {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.expect("Failed to commit migration information.");
|
.expect("Failed to commit migration information.");
|
||||||
|
|
||||||
info!("Migration complete. Currently at revision {}.", revision);
|
info!("Migration complete. Currently at revision {}.", revision);
|
||||||
@@ -45,7 +48,7 @@ pub fn migrate_database() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run_migrations(revision: i32) -> i32 {
|
pub async fn run_migrations(revision: i32) -> i32 {
|
||||||
info!("Starting database migration.");
|
info!("Starting database migration.");
|
||||||
|
|
||||||
if revision <= 0 {
|
if revision <= 0 {
|
||||||
@@ -56,14 +59,15 @@ pub fn run_migrations(revision: i32) -> i32 {
|
|||||||
info!("Running migration [revision 1]: Add channels to guild object.");
|
info!("Running migration [revision 1]: Add channels to guild object.");
|
||||||
|
|
||||||
let col = get_collection("guilds");
|
let col = get_collection("guilds");
|
||||||
let guilds = col
|
let mut guilds = col
|
||||||
.find(
|
.find(
|
||||||
None,
|
None,
|
||||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.expect("Failed to fetch guilds.");
|
.expect("Failed to fetch guilds.");
|
||||||
|
|
||||||
let result = get_collection("channels")
|
let mut result = get_collection("channels")
|
||||||
.find(
|
.find(
|
||||||
doc! {
|
doc! {
|
||||||
"type": 2
|
"type": 2
|
||||||
@@ -72,15 +76,17 @@ pub fn run_migrations(revision: i32) -> i32 {
|
|||||||
.projection(doc! { "_id": 1, "guild": 1 })
|
.projection(doc! { "_id": 1, "guild": 1 })
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.expect("Failed to fetch channels.");
|
.expect("Failed to fetch channels.");
|
||||||
|
|
||||||
let mut channels = vec![];
|
let mut channels = vec![];
|
||||||
for doc in result {
|
while let Some(doc) = result.next().await {
|
||||||
let channel = doc.expect("Failed to fetch channel.");
|
let channel = doc.expect("Failed to fetch channel.");
|
||||||
let id = channel
|
let id = channel
|
||||||
.get_str("_id")
|
.get_str("_id")
|
||||||
.expect("Failed to get channel id.")
|
.expect("Failed to get channel id.")
|
||||||
.to_string();
|
.to_string();
|
||||||
|
|
||||||
let gid = channel
|
let gid = channel
|
||||||
.get_str("guild")
|
.get_str("guild")
|
||||||
.expect("Failed to get guild id.")
|
.expect("Failed to get guild id.")
|
||||||
@@ -89,7 +95,7 @@ pub fn run_migrations(revision: i32) -> i32 {
|
|||||||
channels.push((id, gid));
|
channels.push((id, gid));
|
||||||
}
|
}
|
||||||
|
|
||||||
for doc in guilds {
|
while let Some(doc) = guilds.next().await {
|
||||||
let guild = doc.expect("Failed to fetch guild.");
|
let guild = doc.expect("Failed to fetch guild.");
|
||||||
let id = guild.get_str("_id").expect("Failed to get guild id.");
|
let id = guild.get_str("_id").expect("Failed to get guild id.");
|
||||||
|
|
||||||
@@ -110,6 +116,7 @@ pub fn run_migrations(revision: i32) -> i32 {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.expect("Failed to update guild.");
|
.expect("Failed to update guild.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
use crate::util::variables::MONGO_URI;
|
use crate::util::variables::MONGO_URI;
|
||||||
|
|
||||||
use mongodb::sync::{Client, Collection, Database};
|
use mongodb::{Client, Collection, Database};
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
|
|
||||||
static DBCONN: OnceCell<Client> = OnceCell::new();
|
static DBCONN: OnceCell<Client> = OnceCell::new();
|
||||||
|
|
||||||
pub fn connect() {
|
pub async fn connect() {
|
||||||
let client = Client::with_uri_str(&MONGO_URI).expect("Failed to init db connection.");
|
let client = Client::with_uri_str(&MONGO_URI)
|
||||||
|
.await
|
||||||
|
.expect("Failed to init db connection.");
|
||||||
|
|
||||||
DBCONN.set(client).unwrap();
|
DBCONN.set(client).unwrap();
|
||||||
migrations::run_migrations();
|
migrations::run_migrations().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_connection() -> &'static Client {
|
pub fn get_connection() -> &'static Client {
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
use super::{get_collection, MemberPermissions};
|
use super::{get_collection, MemberPermissions};
|
||||||
|
|
||||||
use mongodb::bson::doc;
|
use mongodb::bson::{doc, Document};
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::FindOptions;
|
||||||
|
use rocket::futures::StreamExt;
|
||||||
|
|
||||||
pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
pub async fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
||||||
let col = get_collection("members");
|
let col = get_collection("members");
|
||||||
if let Ok(result) = col.find(
|
if let Ok(mut result) = col.find(
|
||||||
doc! {
|
doc! {
|
||||||
"$and": [
|
"$and": [
|
||||||
{ "id": user_id },
|
{ "id": user_id },
|
||||||
@@ -13,10 +14,10 @@ pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||||
) {
|
).await {
|
||||||
let mut results = vec![];
|
let mut results = vec![];
|
||||||
|
|
||||||
for doc in result {
|
while let Some(doc) = result.next().await {
|
||||||
if let Ok(guild) = doc {
|
if let Ok(guild) = doc {
|
||||||
results.push(guild.get_str("_id").unwrap().to_string());
|
results.push(guild.get_str("_id").unwrap().to_string());
|
||||||
}
|
}
|
||||||
@@ -28,9 +29,9 @@ pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn find_mutual_friends(user_id: &str, target_id: &str) -> Vec<String> {
|
pub async fn find_mutual_friends(user_id: &str, target_id: &str) -> Vec<String> {
|
||||||
let col = get_collection("users");
|
let col = get_collection("users");
|
||||||
if let Ok(result) = col.find(
|
if let Ok(mut result) = col.find(
|
||||||
doc! {
|
doc! {
|
||||||
"$and": [
|
"$and": [
|
||||||
{ "relations": { "$elemMatch": { "id": user_id, "status": 0 } } },
|
{ "relations": { "$elemMatch": { "id": user_id, "status": 0 } } },
|
||||||
@@ -38,10 +39,10 @@ pub fn find_mutual_friends(user_id: &str, target_id: &str) -> Vec<String> {
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||||
) {
|
).await {
|
||||||
let mut results = vec![];
|
let mut results = vec![];
|
||||||
|
|
||||||
for doc in result {
|
while let Some(doc) = result.next().await {
|
||||||
if let Ok(user) = doc {
|
if let Ok(user) = doc {
|
||||||
results.push(user.get_str("_id").unwrap().to_string());
|
results.push(user.get_str("_id").unwrap().to_string());
|
||||||
}
|
}
|
||||||
@@ -53,9 +54,9 @@ pub fn find_mutual_friends(user_id: &str, target_id: &str) -> Vec<String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn find_mutual_groups(user_id: &str, target_id: &str) -> Vec<String> {
|
pub async fn find_mutual_groups(user_id: &str, target_id: &str) -> Vec<String> {
|
||||||
let col = get_collection("channels");
|
let col = get_collection("channels");
|
||||||
if let Ok(result) = col.find(
|
if let Ok(mut result) = col.find(
|
||||||
doc! {
|
doc! {
|
||||||
"type": 1,
|
"type": 1,
|
||||||
"$and": [
|
"$and": [
|
||||||
@@ -64,10 +65,10 @@ pub fn find_mutual_groups(user_id: &str, target_id: &str) -> Vec<String> {
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||||
) {
|
).await {
|
||||||
let mut results = vec![];
|
let mut results = vec![];
|
||||||
|
|
||||||
for doc in result {
|
while let Some(doc) = result.next().await {
|
||||||
if let Ok(group) = doc {
|
if let Ok(group) = doc {
|
||||||
results.push(group.get_str("_id").unwrap().to_string());
|
results.push(group.get_str("_id").unwrap().to_string());
|
||||||
}
|
}
|
||||||
@@ -79,7 +80,7 @@ pub fn find_mutual_groups(user_id: &str, target_id: &str) -> Vec<String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bool) -> bool {
|
pub async fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bool) -> bool {
|
||||||
let mut doc = doc! { "_id": 1 };
|
let mut doc = doc! { "_id": 1 };
|
||||||
|
|
||||||
if with_permission {
|
if with_permission {
|
||||||
@@ -88,7 +89,7 @@ pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bo
|
|||||||
|
|
||||||
let opt = FindOptions::builder().projection(doc);
|
let opt = FindOptions::builder().projection(doc);
|
||||||
|
|
||||||
if let Ok(result) = get_collection("guilds").find(
|
if let Ok(mut result) = get_collection("guilds").find(
|
||||||
doc! {
|
doc! {
|
||||||
"$and": [
|
"$and": [
|
||||||
{ "members": { "$elemMatch": { "id": user_id } } },
|
{ "members": { "$elemMatch": { "id": user_id } } },
|
||||||
@@ -100,9 +101,9 @@ pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bo
|
|||||||
} else {
|
} else {
|
||||||
opt.limit(1).build()
|
opt.limit(1).build()
|
||||||
},
|
},
|
||||||
) {
|
).await {
|
||||||
if with_permission {
|
if with_permission {
|
||||||
for item in result {
|
while let Some(item) = result.next().await {
|
||||||
// ? logic should match permissions.rs#calculate
|
// ? logic should match permissions.rs#calculate
|
||||||
if let Ok(guild) = item {
|
if let Ok(guild) = item {
|
||||||
if guild.get_str("owner").unwrap() == user_id {
|
if guild.get_str("owner").unwrap() == user_id {
|
||||||
@@ -118,7 +119,7 @@ pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bo
|
|||||||
}
|
}
|
||||||
|
|
||||||
false
|
false
|
||||||
} else if result.count() > 0 {
|
} else if result.collect::<Vec<Result<Document, _>>>().await.len() > 0 {
|
||||||
true
|
true
|
||||||
} else {
|
} else {
|
||||||
false
|
false
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ impl PermissionCalculator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_data(mut self) -> PermissionCalculator {
|
pub async fn fetch_data(mut self) -> PermissionCalculator {
|
||||||
let guild = if let Some(value) = self.guild {
|
let guild = if let Some(value) = self.guild {
|
||||||
Some(value)
|
Some(value)
|
||||||
} else if let Some(channel) = &self.channel {
|
} else if let Some(channel) = &self.channel {
|
||||||
@@ -123,7 +123,7 @@ impl PermissionCalculator {
|
|||||||
0..=1 => None,
|
0..=1 => None,
|
||||||
2 => {
|
2 => {
|
||||||
if let Some(id) = &channel.guild {
|
if let Some(id) = &channel.guild {
|
||||||
if let Ok(result) = fetch_guild(id) {
|
if let Ok(result) = fetch_guild(id).await {
|
||||||
result
|
result
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@@ -139,7 +139,7 @@ impl PermissionCalculator {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(guild) = &guild {
|
if let Some(guild) = &guild {
|
||||||
if let Ok(result) = fetch_member(MemberKey(guild.id.clone(), self.user.id.clone())) {
|
if let Ok(result) = fetch_member(MemberKey(guild.id.clone(), self.user.id.clone())).await {
|
||||||
self.member = result;
|
self.member = result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -148,7 +148,7 @@ impl PermissionCalculator {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn calculate(&self) -> u32 {
|
pub async fn calculate(&self) -> u32 {
|
||||||
let mut permissions: u32 = 0;
|
let mut permissions: u32 = 0;
|
||||||
if let Some(guild) = &self.guild {
|
if let Some(guild) = &self.guild {
|
||||||
if let Some(_member) = &self.member {
|
if let Some(_member) = &self.member {
|
||||||
@@ -185,7 +185,7 @@ impl PermissionCalculator {
|
|||||||
|| relationship == Relationship::BlockedOther
|
|| relationship == Relationship::BlockedOther
|
||||||
{
|
{
|
||||||
permissions = 1;
|
permissions = 1;
|
||||||
} else if has_mutual_connection(&self.user.id, other, true) {
|
} else if has_mutual_connection(&self.user.id, other, true).await {
|
||||||
permissions = 1024 + 128 + 32 + 16 + 1;
|
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||||
} else {
|
} else {
|
||||||
permissions = 1;
|
permissions = 1;
|
||||||
@@ -222,7 +222,7 @@ impl PermissionCalculator {
|
|||||||
permissions
|
permissions
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn as_permission(&self) -> MemberPermissions<[u32; 1]> {
|
pub async fn as_permission(&self) -> MemberPermissions<[u32; 1]> {
|
||||||
MemberPermissions([self.calculate()])
|
MemberPermissions([self.calculate().await])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
use super::channel::fetch_channels;
|
|
||||||
use super::get_collection;
|
use super::get_collection;
|
||||||
|
use super::channel::fetch_channels;
|
||||||
use super::guild::serialise_guilds_with_channels;
|
use super::guild::serialise_guilds_with_channels;
|
||||||
|
|
||||||
use lru::LruCache;
|
use lru::LruCache;
|
||||||
use mongodb::bson::{doc, from_bson, Bson, DateTime};
|
use rocket::futures::StreamExt;
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::FindOptions;
|
||||||
use rocket::http::{RawStr, Status};
|
use rocket::http::{RawStr, Status};
|
||||||
use rocket::request::{self, FromParam, FromRequest, Request};
|
|
||||||
use rocket::Outcome;
|
|
||||||
use rocket_contrib::json::JsonValue;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use rocket_contrib::json::JsonValue;
|
||||||
|
use mongodb::bson::{doc, from_bson, Bson, DateTime, Document};
|
||||||
|
use rocket::request::{self, FromParam, FromRequest, Request, Outcome};
|
||||||
|
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
@@ -60,7 +61,7 @@ impl User {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn find_guilds(&self) -> Result<Vec<String>, String> {
|
pub async fn find_guilds(&self) -> Result<Vec<String>, String> {
|
||||||
let members = get_collection("members")
|
let members = get_collection("members")
|
||||||
.find(
|
.find(
|
||||||
doc! {
|
doc! {
|
||||||
@@ -68,9 +69,12 @@ impl User {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.map_err(|_| "Failed to fetch members.")?;
|
.map_err(|_| "Failed to fetch members.")?;
|
||||||
|
|
||||||
Ok(members
|
Ok(members
|
||||||
|
.collect::<Vec<Result<Document, _>>>()
|
||||||
|
.await
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|x| match x {
|
.filter_map(|x| match x {
|
||||||
Ok(doc) => match doc.get_document("_id") {
|
Ok(doc) => match doc.get_document("_id") {
|
||||||
@@ -85,7 +89,7 @@ impl User {
|
|||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn find_dms(&self) -> Result<Vec<String>, String> {
|
pub async fn find_dms(&self) -> Result<Vec<String>, String> {
|
||||||
let channels = get_collection("channels")
|
let channels = get_collection("channels")
|
||||||
.find(
|
.find(
|
||||||
doc! {
|
doc! {
|
||||||
@@ -93,9 +97,12 @@ impl User {
|
|||||||
},
|
},
|
||||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.map_err(|_| "Failed to fetch channel ids.")?;
|
.map_err(|_| "Failed to fetch channel ids.")?;
|
||||||
|
|
||||||
Ok(channels
|
Ok(channels
|
||||||
|
.collect::<Vec<Result<Document, _>>>()
|
||||||
|
.await
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|x| x.ok())
|
.filter_map(|x| x.ok())
|
||||||
.filter_map(|x| match x.get_str("_id") {
|
.filter_map(|x| match x.get_str("_id") {
|
||||||
@@ -105,11 +112,11 @@ impl User {
|
|||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_payload(self) -> Result<JsonValue, String> {
|
pub async fn create_payload(self) -> Result<JsonValue, String> {
|
||||||
let v = vec![];
|
let v = vec![];
|
||||||
let relations = self.relations.as_ref().unwrap_or(&v);
|
let relations = self.relations.as_ref().unwrap_or(&v);
|
||||||
|
|
||||||
let users: Vec<JsonValue> = fetch_users(&relations.iter().map(|x| x.id.clone()).collect())?
|
let users: Vec<JsonValue> = fetch_users(&relations.iter().map(|x| x.id.clone()).collect()).await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|x| {
|
.map(|x| {
|
||||||
let id = x.id.clone();
|
let id = x.id.clone();
|
||||||
@@ -117,7 +124,7 @@ impl User {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let channels: Vec<JsonValue> = fetch_channels(&self.find_dms()?)?
|
let channels: Vec<JsonValue> = fetch_channels(&self.find_dms().await?).await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|x| x.serialise())
|
.map(|x| x.serialise())
|
||||||
.collect();
|
.collect();
|
||||||
@@ -125,7 +132,7 @@ impl User {
|
|||||||
Ok(json!({
|
Ok(json!({
|
||||||
"users": users,
|
"users": users,
|
||||||
"channels": channels,
|
"channels": channels,
|
||||||
"guilds": serialise_guilds_with_channels(&self.find_guilds()?)?,
|
"guilds": serialise_guilds_with_channels(&self.find_guilds().await?).await?,
|
||||||
"user": self.serialise(super::Relationship::SELF as i32)
|
"user": self.serialise(super::Relationship::SELF as i32)
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
@@ -136,7 +143,7 @@ lazy_static! {
|
|||||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_user(id: &str) -> Result<Option<User>, String> {
|
pub async fn fetch_user(id: &str) -> Result<Option<User>, String> {
|
||||||
{
|
{
|
||||||
if let Ok(mut cache) = CACHE.lock() {
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
let existing = cache.get(&id.to_string());
|
let existing = cache.get(&id.to_string());
|
||||||
@@ -150,7 +157,7 @@ pub fn fetch_user(id: &str) -> Result<Option<User>, String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let col = get_collection("users");
|
let col = get_collection("users");
|
||||||
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
if let Ok(result) = col.find_one(doc! { "_id": id }, None).await {
|
||||||
if let Some(doc) = result {
|
if let Some(doc) = result {
|
||||||
if let Ok(user) = from_bson(Bson::Document(doc)) as Result<User, _> {
|
if let Ok(user) = from_bson(Bson::Document(doc)) as Result<User, _> {
|
||||||
let mut cache = CACHE.lock().unwrap();
|
let mut cache = CACHE.lock().unwrap();
|
||||||
@@ -168,7 +175,7 @@ pub fn fetch_user(id: &str) -> Result<Option<User>, String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_users(ids: &Vec<String>) -> Result<Vec<User>, String> {
|
pub async fn fetch_users(ids: &Vec<String>) -> Result<Vec<User>, String> {
|
||||||
let mut missing = vec![];
|
let mut missing = vec![];
|
||||||
let mut users = vec![];
|
let mut users = vec![];
|
||||||
|
|
||||||
@@ -193,8 +200,8 @@ pub fn fetch_users(ids: &Vec<String>) -> Result<Vec<User>, String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let col = get_collection("users");
|
let col = get_collection("users");
|
||||||
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
if let Ok(mut result) = col.find(doc! { "_id": { "$in": missing } }, None).await {
|
||||||
for item in result {
|
while let Some(item) = result.next().await {
|
||||||
let mut cache = CACHE.lock().unwrap();
|
let mut cache = CACHE.lock().unwrap();
|
||||||
if let Ok(doc) = item {
|
if let Ok(doc) = item {
|
||||||
if let Ok(user) = from_bson(Bson::Document(doc)) as Result<User, _> {
|
if let Ok(user) = from_bson(Bson::Document(doc)) as Result<User, _> {
|
||||||
@@ -221,16 +228,17 @@ pub enum AuthError {
|
|||||||
Invalid,
|
Invalid,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[rocket::async_trait]
|
||||||
impl<'a, 'r> FromRequest<'a, 'r> for User {
|
impl<'a, 'r> FromRequest<'a, 'r> for User {
|
||||||
type Error = AuthError;
|
type Error = AuthError;
|
||||||
|
|
||||||
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
||||||
let u = request.headers().get("x-user").next();
|
let u = request.headers().get("x-user").next();
|
||||||
let t = request.headers().get("x-auth-token").next();
|
let t = request.headers().get("x-auth-token").next();
|
||||||
|
|
||||||
if let Some(uid) = u {
|
if let Some(uid) = u {
|
||||||
if let Some(token) = t {
|
if let Some(token) = t {
|
||||||
if let Ok(result) = fetch_user(uid) {
|
if let Ok(result) = fetch_user(uid).await {
|
||||||
if let Some(user) = result {
|
if let Some(user) = result {
|
||||||
if let Some(access_token) = &user.access_token {
|
if let Some(access_token) = &user.access_token {
|
||||||
if access_token == token {
|
if access_token == token {
|
||||||
@@ -260,7 +268,8 @@ impl<'r> FromParam<'r> for User {
|
|||||||
type Error = &'r RawStr;
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||||
if let Ok(result) = fetch_user(¶m.to_string()) {
|
Err(param)
|
||||||
|
/*if let Ok(result) = fetch_user(¶m.to_string()).await {
|
||||||
if let Some(user) = result {
|
if let Some(user) = result {
|
||||||
Ok(user)
|
Ok(user)
|
||||||
} else {
|
} else {
|
||||||
@@ -268,7 +277,7 @@ impl<'r> FromParam<'r> for User {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Err(param)
|
Err(param)
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
14
src/main.rs
14
src/main.rs
@@ -1,4 +1,5 @@
|
|||||||
#![feature(proc_macro_hygiene, decl_macro)]
|
#![feature(proc_macro_hygiene, decl_macro)]
|
||||||
|
#![feature(async_closure)]
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate rocket;
|
extern crate rocket;
|
||||||
@@ -17,17 +18,18 @@ pub mod util;
|
|||||||
use log::info;
|
use log::info;
|
||||||
use rocket_cors::AllowedOrigins;
|
use rocket_cors::AllowedOrigins;
|
||||||
|
|
||||||
fn main() {
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
dotenv::dotenv().ok();
|
dotenv::dotenv().ok();
|
||||||
env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", "info"));
|
env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", "info"));
|
||||||
|
|
||||||
info!("Starting REVOLT server.");
|
info!("Starting REVOLT server.");
|
||||||
|
|
||||||
util::variables::preflight_checks();
|
util::variables::preflight_checks();
|
||||||
database::connect();
|
database::connect().await;
|
||||||
|
|
||||||
pubsub::hive::init_hive();
|
pubsub::hive::init_hive();
|
||||||
pubsub::websocket::launch_server();
|
//pubsub::websocket::launch_server();
|
||||||
|
|
||||||
let cors = rocket_cors::CorsOptions {
|
let cors = rocket_cors::CorsOptions {
|
||||||
allowed_origins: AllowedOrigins::All,
|
allowed_origins: AllowedOrigins::All,
|
||||||
@@ -36,5 +38,9 @@ fn main() {
|
|||||||
.to_cors()
|
.to_cors()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
routes::mount(rocket::ignite()).attach(cors).launch();
|
routes::mount(rocket::ignite())
|
||||||
|
.attach(cors)
|
||||||
|
.launch()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use super::events::Notification;
|
use super::events::Notification;
|
||||||
use super::websocket;
|
// use super::websocket;
|
||||||
use crate::database::get_collection;
|
use crate::database::get_collection;
|
||||||
|
|
||||||
use hive_pubsub::backend::mongo::{listen_thread, MongodbPubSub};
|
use hive_pubsub::backend::mongo::MongodbPubSub;
|
||||||
use hive_pubsub::PubSub;
|
use hive_pubsub::PubSub;
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
use serde_json::to_string;
|
use serde_json::to_string;
|
||||||
@@ -12,12 +12,12 @@ static HIVE: OnceCell<MongodbPubSub<String, String, Notification>> = OnceCell::n
|
|||||||
|
|
||||||
pub fn init_hive() {
|
pub fn init_hive() {
|
||||||
let hive = MongodbPubSub::new(
|
let hive = MongodbPubSub::new(
|
||||||
|ids, notification| {
|
|_ids, notification| {
|
||||||
if let Ok(data) = to_string(¬ification) {
|
if let Ok(data) = to_string(¬ification) {
|
||||||
debug!("Pushing out notification. {}", data);
|
debug!("Pushing out notification. {}", data);
|
||||||
if let Err(err) = websocket::publish(ids, data) {
|
// if let Err(err) = websocket::publish(ids, data) {
|
||||||
error!("Failed to publish notification through WebSocket! {}", err);
|
// error!("Failed to publish notification through WebSocket! {}", err);
|
||||||
}
|
// }
|
||||||
} else {
|
} else {
|
||||||
error!("Failed to serialise notification.");
|
error!("Failed to serialise notification.");
|
||||||
}
|
}
|
||||||
@@ -25,7 +25,7 @@ pub fn init_hive() {
|
|||||||
get_collection("hive"),
|
get_collection("hive"),
|
||||||
);
|
);
|
||||||
|
|
||||||
listen_thread(hive.clone());
|
//listen_thread(hive.clone());
|
||||||
|
|
||||||
if HIVE.set(hive).is_err() {
|
if HIVE.set(hive).is_err() {
|
||||||
panic!("Failed to set global pubsub instance.");
|
panic!("Failed to set global pubsub instance.");
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
pub mod events;
|
pub mod events;
|
||||||
pub mod hive;
|
pub mod hive;
|
||||||
pub mod websocket;
|
// pub mod websocket;
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ impl Handler for Client {
|
|||||||
FindOneOptions::builder()
|
FindOneOptions::builder()
|
||||||
.projection(doc! { "_id": 1 })
|
.projection(doc! { "_id": 1 })
|
||||||
.build(),
|
.build(),
|
||||||
);
|
).await;
|
||||||
|
|
||||||
if let Ok(result) = user {
|
if let Ok(result) = user {
|
||||||
if let Some(doc) = result {
|
if let Some(doc) = result {
|
||||||
@@ -29,8 +29,8 @@ pub struct Create {
|
|||||||
/// (2) check email existence
|
/// (2) check email existence
|
||||||
/// (3) add user and send email verification
|
/// (3) add user and send email verification
|
||||||
#[post("/create", data = "<info>")]
|
#[post("/create", data = "<info>")]
|
||||||
pub fn create(info: Json<Create>) -> Response {
|
pub async fn create(info: Json<Create>) -> Response {
|
||||||
if let Err(error) = captcha::verify(&info.captcha) {
|
if let Err(error) = captcha::verify(&info.captcha).await {
|
||||||
return Response::BadRequest(json!({ "error": error }));
|
return Response::BadRequest(json!({ "error": error }));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,6 +58,7 @@ pub fn create(info: Json<Create>) -> Response {
|
|||||||
|
|
||||||
if let Some(_) = col
|
if let Some(_) = col
|
||||||
.find_one(doc! { "email": info.email.clone() }, None)
|
.find_one(doc! { "email": info.email.clone() }, None)
|
||||||
|
.await
|
||||||
.expect("Failed user lookup")
|
.expect("Failed user lookup")
|
||||||
{
|
{
|
||||||
return Response::Conflict(json!({ "error": "Email already in use!" }));
|
return Response::Conflict(json!({ "error": "Email already in use!" }));
|
||||||
@@ -65,6 +66,7 @@ pub fn create(info: Json<Create>) -> Response {
|
|||||||
|
|
||||||
if let Some(_) = col
|
if let Some(_) = col
|
||||||
.find_one(doc! { "username": info.username.clone() }, None)
|
.find_one(doc! { "username": info.username.clone() }, None)
|
||||||
|
.await
|
||||||
.expect("Failed user lookup")
|
.expect("Failed user lookup")
|
||||||
{
|
{
|
||||||
return Response::Conflict(json!({ "error": "Username already in use!" }));
|
return Response::Conflict(json!({ "error": "Username already in use!" }));
|
||||||
@@ -99,7 +101,8 @@ pub fn create(info: Json<Create>) -> Response {
|
|||||||
"email_verification": email_verification
|
"email_verification": email_verification
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
) {
|
)
|
||||||
|
.await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
if *USE_EMAIL {
|
if *USE_EMAIL {
|
||||||
let sent = email::send_verification_email(info.email.clone(), code);
|
let sent = email::send_verification_email(info.email.clone(), code);
|
||||||
@@ -128,11 +131,12 @@ pub fn create(info: Json<Create>) -> Response {
|
|||||||
/// (2) check if it expired yet
|
/// (2) check if it expired yet
|
||||||
/// (3) set account as verified
|
/// (3) set account as verified
|
||||||
#[get("/verify/<code>")]
|
#[get("/verify/<code>")]
|
||||||
pub fn verify_email(code: String) -> Response {
|
pub async fn verify_email(code: String) -> Response {
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
if let Some(u) = col
|
if let Some(u) = col
|
||||||
.find_one(doc! { "email_verification.code": code.clone() }, None)
|
.find_one(doc! { "email_verification.code": code.clone() }, None)
|
||||||
|
.await
|
||||||
.expect("Failed user lookup")
|
.expect("Failed user lookup")
|
||||||
{
|
{
|
||||||
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||||
@@ -161,6 +165,7 @@ pub fn verify_email(code: String) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.expect("Failed to update user!");
|
.expect("Failed to update user!");
|
||||||
|
|
||||||
if *USE_EMAIL {
|
if *USE_EMAIL {
|
||||||
@@ -187,8 +192,8 @@ pub struct Resend {
|
|||||||
/// (2) check for rate limit
|
/// (2) check for rate limit
|
||||||
/// (3) resend the email
|
/// (3) resend the email
|
||||||
#[post("/resend", data = "<info>")]
|
#[post("/resend", data = "<info>")]
|
||||||
pub fn resend_email(info: Json<Resend>) -> Response {
|
pub async fn resend_email(info: Json<Resend>) -> Response {
|
||||||
if let Err(error) = captcha::verify(&info.captcha) {
|
if let Err(error) = captcha::verify(&info.captcha).await {
|
||||||
return Response::BadRequest(json!({ "error": error }));
|
return Response::BadRequest(json!({ "error": error }));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,6 +204,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
doc! { "email_verification.target": info.email.clone() },
|
doc! { "email_verification.target": info.email.clone() },
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.expect("Failed user lookup.")
|
.expect("Failed user lookup.")
|
||||||
{
|
{
|
||||||
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||||
@@ -234,7 +240,9 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
).expect("Failed to update user!");
|
)
|
||||||
|
.await
|
||||||
|
.expect("Failed to update user!");
|
||||||
|
|
||||||
if let Err(err) = email::send_verification_email(info.email.clone(), code) {
|
if let Err(err) = email::send_verification_email(info.email.clone(), code) {
|
||||||
return Response::InternalServerError(json!({ "error": err }));
|
return Response::InternalServerError(json!({ "error": err }));
|
||||||
@@ -259,8 +267,8 @@ pub struct Login {
|
|||||||
/// (2) verify password
|
/// (2) verify password
|
||||||
/// (3) return access token
|
/// (3) return access token
|
||||||
#[post("/login", data = "<info>")]
|
#[post("/login", data = "<info>")]
|
||||||
pub fn login(info: Json<Login>) -> Response {
|
pub async fn login(info: Json<Login>) -> Response {
|
||||||
if let Err(error) = captcha::verify(&info.captcha) {
|
if let Err(error) = captcha::verify(&info.captcha).await {
|
||||||
return Response::BadRequest(json!({ "error": error }));
|
return Response::BadRequest(json!({ "error": error }));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,6 +276,7 @@ pub fn login(info: Json<Login>) -> Response {
|
|||||||
|
|
||||||
if let Some(u) = col
|
if let Some(u) = col
|
||||||
.find_one(doc! { "email": info.email.clone() }, None)
|
.find_one(doc! { "email": info.email.clone() }, None)
|
||||||
|
.await
|
||||||
.expect("Failed user lookup")
|
.expect("Failed user lookup")
|
||||||
{
|
{
|
||||||
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||||
@@ -286,6 +295,7 @@ pub fn login(info: Json<Login>) -> Response {
|
|||||||
doc! { "$set": { "access_token": token.clone() } },
|
doc! { "$set": { "access_token": token.clone() } },
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_err()
|
.is_err()
|
||||||
{
|
{
|
||||||
return Response::InternalServerError(
|
return Response::InternalServerError(
|
||||||
@@ -313,10 +323,10 @@ pub struct Token {
|
|||||||
|
|
||||||
/// login to a Revolt account via token
|
/// login to a Revolt account via token
|
||||||
#[post("/token", data = "<info>")]
|
#[post("/token", data = "<info>")]
|
||||||
pub fn token(info: Json<Token>) -> Response {
|
pub async fn token(info: Json<Token>) -> Response {
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
if let Ok(result) = col.find_one(doc! { "access_token": info.token.clone() }, None) {
|
if let Ok(result) = col.find_one(doc! { "access_token": info.token.clone() }, None).await {
|
||||||
if let Some(user) = result {
|
if let Some(user) = result {
|
||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
"id": user.get_str("_id").unwrap(),
|
"id": user.get_str("_id").unwrap(),
|
||||||
@@ -332,24 +342,3 @@ 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)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,11 +6,12 @@ use crate::database::{
|
|||||||
use crate::util::vec_to_set;
|
use crate::util::vec_to_set;
|
||||||
|
|
||||||
use chrono::prelude::*;
|
use chrono::prelude::*;
|
||||||
use mongodb::bson::{doc, from_bson, Bson};
|
use mongodb::bson::{doc, from_bson, Bson, Document};
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::FindOptions;
|
||||||
use num_enum::TryFromPrimitive;
|
use num_enum::TryFromPrimitive;
|
||||||
use rocket::request::Form;
|
use rocket::request::Form;
|
||||||
use rocket_contrib::json::Json;
|
use rocket_contrib::json::Json;
|
||||||
|
use rocket::futures::StreamExt;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
|
|
||||||
@@ -28,9 +29,10 @@ macro_rules! with_permissions {
|
|||||||
($user: expr, $target: expr) => {{
|
($user: expr, $target: expr) => {{
|
||||||
let permissions = PermissionCalculator::new($user.clone())
|
let permissions = PermissionCalculator::new($user.clone())
|
||||||
.channel($target.clone())
|
.channel($target.clone())
|
||||||
.fetch_data();
|
.fetch_data()
|
||||||
|
.await;
|
||||||
|
|
||||||
let value = permissions.as_permission();
|
let value = permissions.as_permission().await;
|
||||||
if !value.get_access() {
|
if !value.get_access() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -48,7 +50,7 @@ pub struct CreateGroup {
|
|||||||
|
|
||||||
/// create a new group
|
/// create a new group
|
||||||
#[post("/create", data = "<info>")]
|
#[post("/create", data = "<info>")]
|
||||||
pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
pub async fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
||||||
let name: String = info.name.chars().take(32).collect();
|
let name: String = info.name.chars().take(32).collect();
|
||||||
let nonce: String = info.nonce.chars().take(32).collect();
|
let nonce: String = info.nonce.chars().take(32).collect();
|
||||||
|
|
||||||
@@ -60,7 +62,7 @@ pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let col = database::get_collection("channels");
|
let col = database::get_collection("channels");
|
||||||
if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).unwrap() {
|
if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).await.unwrap() {
|
||||||
return Response::BadRequest(json!({ "error": "Group already created!" }));
|
return Response::BadRequest(json!({ "error": "Group already created!" }));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,8 +82,8 @@ pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
FindOptions::builder().limit(query.len() as i64).build(),
|
FindOptions::builder().limit(query.len() as i64).build(),
|
||||||
) {
|
).await {
|
||||||
if result.count() != query.len() {
|
if result.collect::<Vec<Result<Document, _>>>().await.len() != query.len() {
|
||||||
return Response::BadRequest(json!({ "error": "Specified non-existant user(s)." }));
|
return Response::BadRequest(json!({ "error": "Specified non-existant user(s)." }));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,6 +112,7 @@ pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Response::Success(json!({ "id": id }))
|
Response::Success(json!({ "id": id }))
|
||||||
@@ -123,14 +126,14 @@ pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
|||||||
|
|
||||||
/// fetch channel information
|
/// fetch channel information
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub fn channel(user: User, target: Channel) -> Option<Response> {
|
pub async fn channel(user: User, target: Channel) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
Some(Response::Success(target.serialise()))
|
Some(Response::Success(target.serialise()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [groups] add user to channel
|
/// [groups] add user to channel
|
||||||
#[put("/<target>/recipients/<member>")]
|
#[put("/<target>/recipients/<member>")]
|
||||||
pub fn add_member(user: User, target: Channel, member: User) -> Option<Response> {
|
pub async fn add_member(user: User, target: Channel, member: User) -> 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." })));
|
||||||
}
|
}
|
||||||
@@ -163,6 +166,7 @@ pub fn add_member(user: User, target: Channel, member: User) -> Option<Response>
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if (Message {
|
if (Message {
|
||||||
@@ -175,6 +179,7 @@ pub fn add_member(user: User, target: Channel, member: User) -> Option<Response>
|
|||||||
previous_content: vec![],
|
previous_content: vec![],
|
||||||
})
|
})
|
||||||
.send(&target)
|
.send(&target)
|
||||||
|
.await
|
||||||
{
|
{
|
||||||
/*notifications::send_message_given_channel(
|
/*notifications::send_message_given_channel(
|
||||||
Notification::group_user_join(UserJoin {
|
Notification::group_user_join(UserJoin {
|
||||||
@@ -204,7 +209,7 @@ pub fn add_member(user: User, target: Channel, member: User) -> Option<Response>
|
|||||||
|
|
||||||
/// [groups] remove user from channel
|
/// [groups] remove user from channel
|
||||||
#[delete("/<target>/recipients/<member>")]
|
#[delete("/<target>/recipients/<member>")]
|
||||||
pub fn remove_member(user: User, target: Channel, member: User) -> Option<Response> {
|
pub async fn remove_member(user: User, target: Channel, member: User) -> 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." })));
|
||||||
}
|
}
|
||||||
@@ -238,6 +243,7 @@ pub fn remove_member(user: User, target: Channel, member: User) -> Option<Respon
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if (Message {
|
if (Message {
|
||||||
@@ -250,6 +256,7 @@ pub fn remove_member(user: User, target: Channel, member: User) -> Option<Respon
|
|||||||
previous_content: vec![],
|
previous_content: vec![],
|
||||||
})
|
})
|
||||||
.send(&target)
|
.send(&target)
|
||||||
|
.await
|
||||||
{
|
{
|
||||||
/*notifications::send_message_given_channel(
|
/*notifications::send_message_given_channel(
|
||||||
Notification::group_user_leave(UserLeave {
|
Notification::group_user_leave(UserLeave {
|
||||||
@@ -276,7 +283,7 @@ pub fn remove_member(user: User, target: Channel, member: User) -> Option<Respon
|
|||||||
/// or leave group DM
|
/// or leave group DM
|
||||||
/// or close DM conversation
|
/// or close DM conversation
|
||||||
#[delete("/<target>")]
|
#[delete("/<target>")]
|
||||||
pub fn delete(user: User, target: Channel) -> Option<Response> {
|
pub async fn delete(user: User, 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() {
|
||||||
@@ -286,14 +293,15 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
|||||||
let col = database::get_collection("channels");
|
let col = database::get_collection("channels");
|
||||||
let target_id = target.id.clone();
|
let target_id = target.id.clone();
|
||||||
|
|
||||||
let try_delete = || {
|
let try_delete = async || {
|
||||||
let messages = database::get_collection("messages");
|
let messages = database::get_collection("messages");
|
||||||
|
|
||||||
if messages
|
if messages
|
||||||
.delete_many(doc! { "channel": &target_id }, None)
|
.delete_many(doc! { "channel": &target_id }, None)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if col.delete_one(doc! { "_id": &target_id }, None).is_ok() {
|
if col.delete_one(doc! { "_id": &target_id }, None).await.is_ok() {
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
@@ -315,6 +323,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
|||||||
doc! { "$set": { "active": false } },
|
doc! { "$set": { "active": false } },
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
@@ -334,7 +343,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
|||||||
let owner = target.owner.as_ref().expect("Missing owner 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().await
|
||||||
} else {
|
} else {
|
||||||
recipients.remove(&user.id);
|
recipients.remove(&user.id);
|
||||||
let new_owner = if owner == &user.id {
|
let new_owner = if owner == &user.id {
|
||||||
@@ -356,6 +365,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if (Message {
|
if (Message {
|
||||||
@@ -368,6 +378,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
|||||||
previous_content: vec![],
|
previous_content: vec![],
|
||||||
})
|
})
|
||||||
.send(&target)
|
.send(&target)
|
||||||
|
.await
|
||||||
{
|
{
|
||||||
/*notifications::send_message_given_channel(
|
/*notifications::send_message_given_channel(
|
||||||
Notification::group_user_leave(UserLeave {
|
Notification::group_user_leave(UserLeave {
|
||||||
@@ -405,6 +416,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -416,7 +428,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
|||||||
}), FIXME
|
}), FIXME
|
||||||
);*/
|
);*/
|
||||||
|
|
||||||
try_delete()
|
try_delete().await
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
json!({ "error": "Failed to remove invites." }),
|
json!({ "error": "Failed to remove invites." }),
|
||||||
@@ -438,7 +450,7 @@ pub struct MessageFetchOptions {
|
|||||||
|
|
||||||
/// fetch channel messages
|
/// fetch channel messages
|
||||||
#[get("/<target>/messages?<options..>")]
|
#[get("/<target>/messages?<options..>")]
|
||||||
pub fn messages(
|
pub async fn messages(
|
||||||
user: User,
|
user: User,
|
||||||
target: Channel,
|
target: Channel,
|
||||||
options: Form<MessageFetchOptions>,
|
options: Form<MessageFetchOptions>,
|
||||||
@@ -467,7 +479,7 @@ pub fn messages(
|
|||||||
};
|
};
|
||||||
|
|
||||||
let col = database::get_collection("messages");
|
let col = database::get_collection("messages");
|
||||||
let result = col
|
let mut result = col
|
||||||
.find(
|
.find(
|
||||||
query,
|
query,
|
||||||
FindOptions::builder()
|
FindOptions::builder()
|
||||||
@@ -477,10 +489,11 @@ pub fn messages(
|
|||||||
})
|
})
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let mut messages = Vec::new();
|
let mut messages = Vec::new();
|
||||||
for item in result {
|
while let Some(item) = result.next().await {
|
||||||
let message: Message =
|
let message: Message =
|
||||||
from_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!({
|
||||||
@@ -502,7 +515,7 @@ pub struct SendMessage {
|
|||||||
|
|
||||||
/// send a message to a channel
|
/// send a message to a channel
|
||||||
#[post("/<target>/messages", data = "<message>")]
|
#[post("/<target>/messages", data = "<message>")]
|
||||||
pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) -> Option<Response> {
|
pub async fn send_message(user: User, target: Channel, message: Json<SendMessage>) -> Option<Response> {
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_send_messages() {
|
if !permissions.get_send_messages() {
|
||||||
@@ -525,6 +538,7 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
|
|||||||
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)
|
||||||
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.is_some()
|
.is_some()
|
||||||
{
|
{
|
||||||
@@ -544,7 +558,7 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
|
|||||||
previous_content: vec![],
|
previous_content: vec![],
|
||||||
};
|
};
|
||||||
|
|
||||||
if message.send(&target) {
|
if message.send(&target).await {
|
||||||
Some(Response::Success(json!({ "id": id })))
|
Some(Response::Success(json!({ "id": id })))
|
||||||
} else {
|
} else {
|
||||||
Some(Response::BadRequest(
|
Some(Response::BadRequest(
|
||||||
@@ -555,7 +569,7 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
|
|||||||
|
|
||||||
/// get a message
|
/// get a message
|
||||||
#[get("/<target>/messages/<message>")]
|
#[get("/<target>/messages/<message>")]
|
||||||
pub fn get_message(user: User, target: Channel, message: Message) -> Option<Response> {
|
pub async fn get_message(user: User, 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() {
|
||||||
@@ -587,7 +601,7 @@ pub struct EditMessage {
|
|||||||
|
|
||||||
/// edit a message
|
/// edit a message
|
||||||
#[patch("/<target>/messages/<message>", data = "<edit>")]
|
#[patch("/<target>/messages/<message>", data = "<edit>")]
|
||||||
pub fn edit_message(
|
pub async fn edit_message(
|
||||||
user: User,
|
user: User,
|
||||||
target: Channel,
|
target: Channel,
|
||||||
message: Message,
|
message: Message,
|
||||||
@@ -624,7 +638,8 @@ pub fn edit_message(
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
) {
|
)
|
||||||
|
.await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
/*notifications::send_message_given_channel(
|
/*notifications::send_message_given_channel(
|
||||||
Notification::message_edit(Edit {
|
Notification::message_edit(Edit {
|
||||||
@@ -646,7 +661,7 @@ pub fn edit_message(
|
|||||||
|
|
||||||
/// delete a message
|
/// delete a message
|
||||||
#[delete("/<target>/messages/<message>")]
|
#[delete("/<target>/messages/<message>")]
|
||||||
pub fn delete_message(user: User, target: Channel, message: Message) -> Option<Response> {
|
pub async fn delete_message(user: User, target: Channel, message: Message) -> Option<Response> {
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_manage_messages() && message.author != user.id {
|
if !permissions.get_manage_messages() && message.author != user.id {
|
||||||
@@ -655,7 +670,7 @@ pub fn delete_message(user: User, target: Channel, message: Message) -> Option<R
|
|||||||
|
|
||||||
let col = database::get_collection("messages");
|
let col = database::get_collection("messages");
|
||||||
|
|
||||||
match col.delete_one(doc! { "_id": &message.id }, None) {
|
match col.delete_one(doc! { "_id": &message.id }, None).await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
/*notifications::send_message_given_channel(
|
/*notifications::send_message_given_channel(
|
||||||
Notification::message_delete(Delete {
|
Notification::message_delete(Delete {
|
||||||
@@ -671,24 +686,3 @@ pub fn delete_message(user: User, target: Channel, message: Message) -> Option<R
|
|||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ use mongodb::options::{FindOneOptions, FindOptions};
|
|||||||
use rocket::request::Form;
|
use rocket::request::Form;
|
||||||
use rocket_contrib::json::Json;
|
use rocket_contrib::json::Json;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use rocket::futures::StreamExt;
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
|
|
||||||
// ! FIXME: GET RID OF THIS
|
// ! FIXME: GET RID OF THIS
|
||||||
@@ -19,9 +20,10 @@ macro_rules! with_permissions {
|
|||||||
($user: expr, $target: expr) => {{
|
($user: expr, $target: expr) => {{
|
||||||
let permissions = PermissionCalculator::new($user.clone())
|
let permissions = PermissionCalculator::new($user.clone())
|
||||||
.guild($target.clone())
|
.guild($target.clone())
|
||||||
.fetch_data();
|
.fetch_data()
|
||||||
|
.await;
|
||||||
|
|
||||||
let value = permissions.as_permission();
|
let value = permissions.as_permission().await;
|
||||||
if !value.get_access() {
|
if !value.get_access() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -32,9 +34,9 @@ macro_rules! with_permissions {
|
|||||||
|
|
||||||
/// fetch your guilds
|
/// fetch your guilds
|
||||||
#[get("/@me")]
|
#[get("/@me")]
|
||||||
pub fn my_guilds(user: User) -> Response {
|
pub async fn my_guilds(user: User) -> Response {
|
||||||
if let Ok(gids) = user.find_guilds() {
|
if let Ok(gids) = user.find_guilds().await {
|
||||||
if let Ok(data) = serialise_guilds_with_channels(&gids) {
|
if let Ok(data) = serialise_guilds_with_channels(&gids).await {
|
||||||
Response::Success(json!(data))
|
Response::Success(json!(data))
|
||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(json!({ "error": "Failed to fetch guilds." }))
|
Response::InternalServerError(json!({ "error": "Failed to fetch guilds." }))
|
||||||
@@ -46,10 +48,10 @@ pub fn my_guilds(user: User) -> Response {
|
|||||||
|
|
||||||
/// fetch a guild
|
/// fetch a guild
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub fn guild(user: User, target: Guild) -> Option<Response> {
|
pub async fn guild(user: User, target: Guild) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if let Ok(result) = target.seralise_with_channels() {
|
if let Ok(result) = target.seralise_with_channels().await {
|
||||||
Some(Response::Success(result))
|
Some(Response::Success(result))
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
@@ -60,20 +62,20 @@ pub fn guild(user: User, target: Guild) -> Option<Response> {
|
|||||||
|
|
||||||
/// delete or leave a guild
|
/// delete or leave a guild
|
||||||
#[delete("/<target>")]
|
#[delete("/<target>")]
|
||||||
pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
pub async fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if user.id == target.owner {
|
if user.id == target.owner {
|
||||||
let channels = database::get_collection("channels");
|
let channels = database::get_collection("channels");
|
||||||
if let Ok(result) = channels.find(
|
if let Ok(mut result) = channels.find(
|
||||||
doc! {
|
doc! {
|
||||||
"type": 2,
|
"type": 2,
|
||||||
"guild": &target.id
|
"guild": &target.id
|
||||||
},
|
},
|
||||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||||
) {
|
).await {
|
||||||
let mut values = vec![];
|
let mut values = vec![];
|
||||||
for item in result {
|
while let Some(item) = result.next().await {
|
||||||
if let Ok(doc) = item {
|
if let Ok(doc) = item {
|
||||||
values.push(Bson::String(doc.get_str("_id").unwrap().to_string()));
|
values.push(Bson::String(doc.get_str("_id").unwrap().to_string()));
|
||||||
}
|
}
|
||||||
@@ -88,6 +90,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if channels
|
if channels
|
||||||
@@ -98,6 +101,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if database::get_collection("members")
|
if database::get_collection("members")
|
||||||
@@ -107,6 +111,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if database::get_collection("guilds")
|
if database::get_collection("guilds")
|
||||||
@@ -116,6 +121,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -160,6 +166,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -189,7 +196,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(user: User, target: Guild, info: Json<CreateChannel>) -> Option<Response> {
|
pub async fn create_channel(user: User, target: Guild, 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() {
|
||||||
@@ -208,6 +215,7 @@ pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> O
|
|||||||
|
|
||||||
if let Ok(result) =
|
if let Ok(result) =
|
||||||
database::get_collection("channels").find_one(doc! { "nonce": &nonce }, None)
|
database::get_collection("channels").find_one(doc! { "nonce": &nonce }, None)
|
||||||
|
.await
|
||||||
{
|
{
|
||||||
if result.is_some() {
|
if result.is_some() {
|
||||||
return Some(Response::BadRequest(
|
return Some(Response::BadRequest(
|
||||||
@@ -228,6 +236,7 @@ pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> O
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if database::get_collection("guilds")
|
if database::get_collection("guilds")
|
||||||
@@ -242,6 +251,7 @@ pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> O
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -280,7 +290,7 @@ pub struct InviteOptions {
|
|||||||
|
|
||||||
/// create a new invite
|
/// create a new invite
|
||||||
#[post("/<target>/channels/<channel>/invite", data = "<_options>")]
|
#[post("/<target>/channels/<channel>/invite", data = "<_options>")]
|
||||||
pub fn create_invite(
|
pub async fn create_invite(
|
||||||
user: User,
|
user: User,
|
||||||
target: Guild,
|
target: Guild,
|
||||||
channel: Channel,
|
channel: Channel,
|
||||||
@@ -307,6 +317,7 @@ pub fn create_invite(
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Some(Response::Success(json!({ "code": code })))
|
Some(Response::Success(json!({ "code": code })))
|
||||||
@@ -319,10 +330,10 @@ pub fn create_invite(
|
|||||||
|
|
||||||
/// remove an invite
|
/// remove an invite
|
||||||
#[delete("/<target>/invites/<code>")]
|
#[delete("/<target>/invites/<code>")]
|
||||||
pub fn remove_invite(user: User, target: Guild, code: String) -> Option<Response> {
|
pub async fn remove_invite(user: User, 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).await {
|
||||||
if invite.creator != user.id && !permissions.get_manage_server() {
|
if invite.creator != user.id && !permissions.get_manage_server() {
|
||||||
return Some(Response::LackingPermission(Permission::ManageServer));
|
return Some(Response::LackingPermission(Permission::ManageServer));
|
||||||
}
|
}
|
||||||
@@ -341,6 +352,7 @@ pub fn remove_invite(user: User, target: Guild, code: String) -> Option<Response
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
@@ -358,7 +370,7 @@ pub fn remove_invite(user: User, target: Guild, code: String) -> Option<Response
|
|||||||
|
|
||||||
/// fetch all guild invites
|
/// fetch all guild invites
|
||||||
#[get("/<target>/invites")]
|
#[get("/<target>/invites")]
|
||||||
pub fn fetch_invites(user: User, target: Guild) -> Option<Response> {
|
pub async fn fetch_invites(user: User, 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() {
|
||||||
@@ -370,9 +382,9 @@ pub fn fetch_invites(user: User, target: Guild) -> Option<Response> {
|
|||||||
|
|
||||||
/// 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: User, code: String) -> Response {
|
pub async fn fetch_invite(user: User, 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).await {
|
||||||
match fetch_channel(&invite.channel) {
|
match fetch_channel(&invite.channel).await {
|
||||||
Ok(result) => {
|
Ok(result) => {
|
||||||
if let Some(channel) = result {
|
if let Some(channel) = result {
|
||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
@@ -398,8 +410,8 @@ pub fn fetch_invite(user: User, code: String) -> Response {
|
|||||||
|
|
||||||
/// join a guild using an invite
|
/// join a guild using an invite
|
||||||
#[post("/join/<code>", rank = 1)]
|
#[post("/join/<code>", rank = 1)]
|
||||||
pub fn use_invite(user: User, code: String) -> Response {
|
pub async fn use_invite(user: User, code: String) -> Response {
|
||||||
if let Some((guild_id, _, invite)) = get_invite(&code, Some(user.id.clone())) {
|
if let Some((guild_id, _, invite)) = get_invite(&code, Some(user.id.clone())).await {
|
||||||
if let Ok(result) = database::get_collection("members").find_one(
|
if let Ok(result) = database::get_collection("members").find_one(
|
||||||
doc! {
|
doc! {
|
||||||
"_id.guild": &guild_id,
|
"_id.guild": &guild_id,
|
||||||
@@ -408,7 +420,8 @@ pub fn use_invite(user: User, code: String) -> Response {
|
|||||||
FindOneOptions::builder()
|
FindOneOptions::builder()
|
||||||
.projection(doc! { "_id": 1 })
|
.projection(doc! { "_id": 1 })
|
||||||
.build(),
|
.build(),
|
||||||
) {
|
)
|
||||||
|
.await {
|
||||||
if result.is_none() {
|
if result.is_none() {
|
||||||
if database::get_collection("members")
|
if database::get_collection("members")
|
||||||
.insert_one(
|
.insert_one(
|
||||||
@@ -420,6 +433,7 @@ pub fn use_invite(user: User, code: String) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -462,7 +476,7 @@ pub struct CreateGuild {
|
|||||||
|
|
||||||
/// create a new guild
|
/// create a new guild
|
||||||
#[post("/create", data = "<info>")]
|
#[post("/create", data = "<info>")]
|
||||||
pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
pub async fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||||
if !user.email_verification.verified {
|
if !user.email_verification.verified {
|
||||||
return Response::Unauthorized(json!({ "error": "Email not verified!" }));
|
return Response::Unauthorized(json!({ "error": "Email not verified!" }));
|
||||||
}
|
}
|
||||||
@@ -481,6 +495,7 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
|||||||
let col = database::get_collection("guilds");
|
let col = database::get_collection("guilds");
|
||||||
if col
|
if col
|
||||||
.find_one(doc! { "nonce": nonce.clone() }, None)
|
.find_one(doc! { "nonce": nonce.clone() }, None)
|
||||||
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.is_some()
|
.is_some()
|
||||||
{
|
{
|
||||||
@@ -500,6 +515,7 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_err()
|
.is_err()
|
||||||
{
|
{
|
||||||
return Response::InternalServerError(
|
return Response::InternalServerError(
|
||||||
@@ -517,6 +533,7 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_err()
|
.is_err()
|
||||||
{
|
{
|
||||||
return Response::InternalServerError(
|
return Response::InternalServerError(
|
||||||
@@ -539,12 +556,14 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Response::Success(json!({ "id": id }))
|
Response::Success(json!({ "id": id }))
|
||||||
} else {
|
} else {
|
||||||
channels
|
channels
|
||||||
.delete_one(doc! { "_id": channel_id }, None)
|
.delete_one(doc! { "_id": channel_id }, None)
|
||||||
|
.await
|
||||||
.expect("Failed to delete the channel we just made.");
|
.expect("Failed to delete the channel we just made.");
|
||||||
|
|
||||||
Response::InternalServerError(json!({ "error": "Failed to create guild." }))
|
Response::InternalServerError(json!({ "error": "Failed to create guild." }))
|
||||||
@@ -553,15 +572,16 @@ pub fn create_guild(user: User, 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: User, target: Guild) -> Option<Response> {
|
pub async fn fetch_members(user: User, target: Guild) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if let Ok(result) =
|
if let Ok(mut result) =
|
||||||
database::get_collection("members").find(doc! { "_id.guild": target.id }, None)
|
database::get_collection("members").find(doc! { "_id.guild": target.id }, None)
|
||||||
|
.await
|
||||||
{
|
{
|
||||||
let mut users = vec![];
|
let mut users = vec![];
|
||||||
|
|
||||||
for item in result {
|
while let Some(item) = result.next().await {
|
||||||
if let Ok(doc) = item {
|
if let Ok(doc) = item {
|
||||||
users.push(json!({
|
users.push(json!({
|
||||||
"id": doc.get_document("_id").unwrap().get_str("user").unwrap(),
|
"id": doc.get_document("_id").unwrap().get_str("user").unwrap(),
|
||||||
@@ -580,10 +600,10 @@ pub fn fetch_members(user: User, target: Guild) -> Option<Response> {
|
|||||||
|
|
||||||
/// fetch a guild member
|
/// fetch a guild member
|
||||||
#[get("/<target>/members/<other>")]
|
#[get("/<target>/members/<other>")]
|
||||||
pub fn fetch_member(user: User, target: Guild, other: String) -> Option<Response> {
|
pub async fn fetch_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if let Ok(result) = get_member(MemberKey(target.id, other)) {
|
if let Ok(result) = get_member(MemberKey(target.id, other)).await {
|
||||||
if let Some(member) = result {
|
if let Some(member) = result {
|
||||||
Some(Response::Success(json!({
|
Some(Response::Success(json!({
|
||||||
"id": member.id.user,
|
"id": member.id.user,
|
||||||
@@ -603,7 +623,7 @@ pub fn fetch_member(user: User, target: Guild, other: String) -> Option<Response
|
|||||||
|
|
||||||
/// kick a guild member
|
/// kick a guild member
|
||||||
#[delete("/<target>/members/<other>")]
|
#[delete("/<target>/members/<other>")]
|
||||||
pub fn kick_member(user: User, target: Guild, other: String) -> Option<Response> {
|
pub async fn kick_member(user: User, 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 {
|
||||||
@@ -616,7 +636,7 @@ pub fn kick_member(user: User, target: Guild, other: String) -> Option<Response>
|
|||||||
return Some(Response::LackingPermission(Permission::KickMembers));
|
return Some(Response::LackingPermission(Permission::KickMembers));
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())) {
|
if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())).await {
|
||||||
if result.is_none() {
|
if result.is_none() {
|
||||||
return Some(Response::BadRequest(
|
return Some(Response::BadRequest(
|
||||||
json!({ "error": "User not part of guild." }),
|
json!({ "error": "User not part of guild." }),
|
||||||
@@ -636,6 +656,7 @@ pub fn kick_member(user: User, target: Guild, other: String) -> Option<Response>
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -663,7 +684,7 @@ pub struct BanOptions {
|
|||||||
|
|
||||||
/// ban a guild member
|
/// ban a guild member
|
||||||
#[put("/<target>/members/<other>/ban?<options..>")]
|
#[put("/<target>/members/<other>/ban?<options..>")]
|
||||||
pub fn ban_member(
|
pub async fn ban_member(
|
||||||
user: User,
|
user: User,
|
||||||
target: Guild,
|
target: Guild,
|
||||||
other: String,
|
other: String,
|
||||||
@@ -688,7 +709,7 @@ pub fn ban_member(
|
|||||||
return Some(Response::LackingPermission(Permission::BanMembers));
|
return Some(Response::LackingPermission(Permission::BanMembers));
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())) {
|
if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())).await {
|
||||||
if result.is_none() {
|
if result.is_none() {
|
||||||
return Some(Response::BadRequest(
|
return Some(Response::BadRequest(
|
||||||
json!({ "error": "User not part of guild." }),
|
json!({ "error": "User not part of guild." }),
|
||||||
@@ -713,6 +734,7 @@ pub fn ban_member(
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_err()
|
.is_err()
|
||||||
{
|
{
|
||||||
return Some(Response::BadRequest(
|
return Some(Response::BadRequest(
|
||||||
@@ -728,6 +750,7 @@ pub fn ban_member(
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -750,7 +773,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: User, target: Guild, other: String) -> Option<Response> {
|
pub async fn unban_member(user: User, 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 {
|
||||||
@@ -783,6 +806,7 @@ pub fn unban_member(user: User, target: Guild, other: String) -> Option<Response
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
@@ -792,44 +816,3 @@ pub fn unban_member(user: User, target: Guild, other: String) -> Option<Response
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -49,21 +49,25 @@ use rocket::http::ContentType;
|
|||||||
use rocket::request::Request;
|
use rocket::request::Request;
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
|
|
||||||
impl<'a> rocket::response::Responder<'a> for Permission {
|
use rocket::response::{Responder, Result};
|
||||||
fn respond_to(self, _: &Request) -> rocket::response::Result<'a> {
|
|
||||||
rocket::response::Response::build()
|
impl<'a> Responder<'a, 'static> for Permission {
|
||||||
.header(ContentType::JSON)
|
fn respond_to(self, _: &Request) -> Result<'static> {
|
||||||
.sized_body(Cursor::new(format!(
|
let body = format!(
|
||||||
"{{\"error\":\"Lacking permission: {:?}.\",\"permission\":{}}}",
|
"{{\"error\":\"Lacking permission: {:?}.\",\"permission\":{}}}",
|
||||||
self, self as u32,
|
self, self as u32,
|
||||||
)))
|
);
|
||||||
|
|
||||||
|
rocket::response::Response::build()
|
||||||
|
.header(ContentType::JSON)
|
||||||
|
.sized_body(body.len(), Cursor::new(body))
|
||||||
.ok()
|
.ok()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mount(rocket: Rocket) -> Rocket {
|
pub fn mount(rocket: Rocket) -> Rocket {
|
||||||
rocket
|
rocket
|
||||||
.mount("/", routes![root::root, root::root_preflight, root::teapot])
|
.mount("/", routes![root::root, root::teapot])
|
||||||
.mount(
|
.mount(
|
||||||
"/account",
|
"/account",
|
||||||
routes![
|
routes![
|
||||||
@@ -72,11 +76,6 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
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(
|
||||||
@@ -93,12 +92,6 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
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(
|
||||||
@@ -114,11 +107,6 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
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(
|
||||||
@@ -139,16 +127,6 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
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,
|
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use mongodb::bson::doc;
|
|||||||
|
|
||||||
/// root
|
/// root
|
||||||
#[get("/")]
|
#[get("/")]
|
||||||
pub fn root() -> Response {
|
pub async fn root() -> Response {
|
||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
"revolt": "0.2.11",
|
"revolt": "0.2.11",
|
||||||
"features": {
|
"features": {
|
||||||
@@ -19,14 +19,9 @@ pub fn root() -> Response {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[options("/")]
|
|
||||||
pub fn root_preflight() -> Response {
|
|
||||||
Response::Result(super::Status::Ok)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// I'm a teapot.
|
/// I'm a teapot.
|
||||||
#[delete("/")]
|
#[delete("/")]
|
||||||
pub fn teapot() -> Response {
|
pub async fn teapot() -> Response {
|
||||||
Response::Teapot(json!({
|
Response::Teapot(json!({
|
||||||
"teapot": true,
|
"teapot": true,
|
||||||
"can_delete": false
|
"can_delete": false
|
||||||
|
|||||||
@@ -8,17 +8,18 @@ use mongodb::bson::doc;
|
|||||||
use mongodb::options::{Collation, FindOneOptions, 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 rocket::futures::StreamExt;
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
|
|
||||||
/// retrieve your user information
|
/// retrieve your user information
|
||||||
#[get("/@me")]
|
#[get("/@me")]
|
||||||
pub fn me(user: User) -> Response {
|
pub async fn me(user: User) -> Response {
|
||||||
Response::Success(user.serialise(Relationship::SELF as i32))
|
Response::Success(user.serialise(Relationship::SELF as i32))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// retrieve another user's information
|
/// retrieve another user's information
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub fn user(user: User, target: User) -> Response {
|
pub async fn user(user: User, target: User) -> Response {
|
||||||
let relationship = get_relationship(&user, &target) as i32;
|
let relationship = get_relationship(&user, &target) as i32;
|
||||||
Response::Success(user.serialise(relationship))
|
Response::Success(user.serialise(relationship))
|
||||||
}
|
}
|
||||||
@@ -30,7 +31,7 @@ pub struct UserQuery {
|
|||||||
|
|
||||||
/// find a user by their username
|
/// find a user by their username
|
||||||
#[post("/query", data = "<query>")]
|
#[post("/query", data = "<query>")]
|
||||||
pub fn query(user: User, query: Json<UserQuery>) -> Response {
|
pub async fn query(user: User, query: Json<UserQuery>) -> Response {
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
if let Ok(result) = col.find_one(
|
if let Ok(result) = col.find_one(
|
||||||
@@ -38,7 +39,8 @@ pub fn query(user: User, query: Json<UserQuery>) -> Response {
|
|||||||
FindOneOptions::builder()
|
FindOneOptions::builder()
|
||||||
.collation(Collation::builder().locale("en").strength(2).build())
|
.collation(Collation::builder().locale("en").strength(2).build())
|
||||||
.build(),
|
.build(),
|
||||||
) {
|
)
|
||||||
|
.await {
|
||||||
if let Some(doc) = result {
|
if let Some(doc) = result {
|
||||||
let id = doc.get_str("_id").unwrap();
|
let id = doc.get_str("_id").unwrap();
|
||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
@@ -96,10 +98,10 @@ pub fn lookup(user: User, query: Json<LookupQuery>) -> Response {
|
|||||||
|
|
||||||
/// retrieve all of your DMs
|
/// retrieve all of your DMs
|
||||||
#[get("/@me/dms")]
|
#[get("/@me/dms")]
|
||||||
pub fn dms(user: User) -> Response {
|
pub async fn dms(user: User) -> Response {
|
||||||
let col = database::get_collection("channels");
|
let col = database::get_collection("channels");
|
||||||
|
|
||||||
if let Ok(results) = col.find(
|
if let Ok(mut results) = col.find(
|
||||||
doc! {
|
doc! {
|
||||||
"$or": [
|
"$or": [
|
||||||
{
|
{
|
||||||
@@ -113,9 +115,10 @@ pub fn dms(user: User) -> Response {
|
|||||||
"recipients": user.id
|
"recipients": user.id
|
||||||
},
|
},
|
||||||
FindOptions::builder().projection(doc! {}).build(),
|
FindOptions::builder().projection(doc! {}).build(),
|
||||||
) {
|
)
|
||||||
|
.await {
|
||||||
let mut channels = Vec::new();
|
let mut channels = Vec::new();
|
||||||
for item in results {
|
while let Some(item) = results.next().await {
|
||||||
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 last_message = doc.get_document("last_message").unwrap();
|
||||||
@@ -153,13 +156,14 @@ pub fn dms(user: User) -> Response {
|
|||||||
|
|
||||||
/// open a DM with a user
|
/// open a DM with a user
|
||||||
#[get("/<target>/dm")]
|
#[get("/<target>/dm")]
|
||||||
pub fn dm(user: User, target: User) -> Response {
|
pub async fn dm(user: User, target: User) -> Response {
|
||||||
let col = database::get_collection("channels");
|
let col = database::get_collection("channels");
|
||||||
|
|
||||||
if let Ok(result) = col.find_one(
|
if let Ok(result) = col.find_one(
|
||||||
doc! { "type": channel::ChannelType::DM as i32, "recipients": { "$all": [ user.id.clone(), target.id.clone() ] } },
|
doc! { "type": channel::ChannelType::DM as i32, "recipients": { "$all": [ user.id.clone(), target.id.clone() ] } },
|
||||||
None
|
None
|
||||||
) {
|
)
|
||||||
|
.await {
|
||||||
if let Some(channel) = result {
|
if let Some(channel) = result {
|
||||||
Response::Success( json!({ "id": channel.get_str("_id").unwrap() }))
|
Response::Success( json!({ "id": channel.get_str("_id").unwrap() }))
|
||||||
} else {
|
} else {
|
||||||
@@ -173,7 +177,9 @@ pub fn dm(user: User, target: User) -> Response {
|
|||||||
"active": false
|
"active": false
|
||||||
},
|
},
|
||||||
None
|
None
|
||||||
).is_ok() {
|
)
|
||||||
|
.await
|
||||||
|
.is_ok() {
|
||||||
Response::Success(json!({ "id": id.to_string() }))
|
Response::Success(json!({ "id": id.to_string() }))
|
||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(json!({ "error": "Failed to create new channel." }))
|
Response::InternalServerError(json!({ "error": "Failed to create new channel." }))
|
||||||
@@ -186,7 +192,7 @@ pub fn dm(user: User, target: User) -> Response {
|
|||||||
|
|
||||||
/// retrieve all of your friends
|
/// retrieve all of your friends
|
||||||
#[get("/@me/friend")]
|
#[get("/@me/friend")]
|
||||||
pub fn get_friends(user: User) -> Response {
|
pub async fn get_friends(user: User) -> Response {
|
||||||
let mut results = Vec::new();
|
let mut results = Vec::new();
|
||||||
if let Some(arr) = user.relations {
|
if let Some(arr) = user.relations {
|
||||||
for item in arr {
|
for item in arr {
|
||||||
@@ -202,13 +208,13 @@ pub fn get_friends(user: User) -> Response {
|
|||||||
|
|
||||||
/// retrieve friend status with user
|
/// retrieve friend status with user
|
||||||
#[get("/<target>/friend")]
|
#[get("/<target>/friend")]
|
||||||
pub fn get_friend(user: User, target: User) -> Response {
|
pub async fn get_friend(user: User, target: User) -> Response {
|
||||||
Response::Success(json!({ "status": get_relationship(&user, &target) as i32 }))
|
Response::Success(json!({ "status": get_relationship(&user, &target) as i32 }))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// create or accept a friend request
|
/// create or accept a friend request
|
||||||
#[put("/<target>/friend")]
|
#[put("/<target>/friend")]
|
||||||
pub fn add_friend(user: User, target: User) -> Response {
|
pub async fn add_friend(user: User, target: User) -> Response {
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
match get_relationship(&user, &target) {
|
match get_relationship(&user, &target) {
|
||||||
@@ -230,6 +236,7 @@ pub fn add_friend(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if col
|
if col
|
||||||
@@ -245,6 +252,7 @@ pub fn add_friend(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -301,6 +309,7 @@ pub fn add_friend(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if col
|
if col
|
||||||
@@ -318,6 +327,7 @@ pub fn add_friend(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -360,7 +370,7 @@ pub fn add_friend(user: User, target: User) -> Response {
|
|||||||
|
|
||||||
/// remove a friend or deny a request
|
/// remove a friend or deny a request
|
||||||
#[delete("/<target>/friend")]
|
#[delete("/<target>/friend")]
|
||||||
pub fn remove_friend(user: User, target: User) -> Response {
|
pub async fn remove_friend(user: User, target: User) -> Response {
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
match get_relationship(&user, &target) {
|
match get_relationship(&user, &target) {
|
||||||
@@ -379,6 +389,7 @@ pub fn remove_friend(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if col
|
if col
|
||||||
@@ -395,6 +406,7 @@ pub fn remove_friend(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -438,7 +450,7 @@ pub fn remove_friend(user: User, target: User) -> Response {
|
|||||||
|
|
||||||
/// block a user
|
/// block a user
|
||||||
#[put("/<target>/block")]
|
#[put("/<target>/block")]
|
||||||
pub fn block_user(user: User, target: User) -> Response {
|
pub async fn block_user(user: User, target: User) -> Response {
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
match get_relationship(&user, &target) {
|
match get_relationship(&user, &target) {
|
||||||
@@ -456,6 +468,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if col
|
if col
|
||||||
@@ -471,6 +484,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -522,6 +536,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if col
|
if col
|
||||||
@@ -539,6 +554,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -590,6 +606,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -615,7 +632,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
|||||||
|
|
||||||
/// unblock a user
|
/// unblock a user
|
||||||
#[delete("/<target>/block")]
|
#[delete("/<target>/block")]
|
||||||
pub fn unblock_user(user: User, target: User) -> Response {
|
pub async fn unblock_user(user: User, target: User) -> Response {
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
match get_relationship(&user, &target) {
|
match get_relationship(&user, &target) {
|
||||||
@@ -634,6 +651,7 @@ pub fn unblock_user(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -668,6 +686,7 @@ pub fn unblock_user(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if col
|
if col
|
||||||
@@ -684,6 +703,7 @@ pub fn unblock_user(user: User, target: User) -> Response {
|
|||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
/*notifications::send_message_threaded(
|
/*notifications::send_message_threaded(
|
||||||
@@ -730,28 +750,3 @@ pub fn unblock_user(user: User, target: User) -> 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,6 +1,6 @@
|
|||||||
use crate::util::variables::{HCAPTCHA_KEY, USE_HCAPTCHA};
|
use crate::util::variables::{HCAPTCHA_KEY, USE_HCAPTCHA};
|
||||||
|
|
||||||
use reqwest::blocking::Client;
|
use reqwest::Client;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
@@ -9,7 +9,7 @@ struct CaptchaResponse {
|
|||||||
success: bool,
|
success: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn verify(user_token: &Option<String>) -> Result<(), String> {
|
pub async fn verify(user_token: &Option<String>) -> Result<(), String> {
|
||||||
if *USE_HCAPTCHA {
|
if *USE_HCAPTCHA {
|
||||||
if let Some(token) = user_token {
|
if let Some(token) = user_token {
|
||||||
let mut map = HashMap::new();
|
let mut map = HashMap::new();
|
||||||
@@ -21,9 +21,11 @@ pub fn verify(user_token: &Option<String>) -> Result<(), String> {
|
|||||||
.post("https://hcaptcha.com/siteverify")
|
.post("https://hcaptcha.com/siteverify")
|
||||||
.form(&map)
|
.form(&map)
|
||||||
.send()
|
.send()
|
||||||
|
.await
|
||||||
{
|
{
|
||||||
let result: CaptchaResponse = response
|
let result: CaptchaResponse = response
|
||||||
.json()
|
.json()
|
||||||
|
.await
|
||||||
.map_err(|_| "Failed to deserialise captcha result.".to_string())?;
|
.map_err(|_| "Failed to deserialise captcha result.".to_string())?;
|
||||||
|
|
||||||
if result.success {
|
if result.success {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use hashbrown::HashSet;
|
|
||||||
use rand::{distributions::Alphanumeric, Rng};
|
use rand::{distributions::Alphanumeric, Rng};
|
||||||
|
use std::collections::HashSet;
|
||||||
use std::iter::FromIterator;
|
use std::iter::FromIterator;
|
||||||
|
|
||||||
pub mod captcha;
|
pub mod captcha;
|
||||||
|
|||||||
Reference in New Issue
Block a user