mirror of
https://github.com/stoatchat/stoatchat.git
synced 2026-07-06 03:06:04 +00:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e7eb34f65 | ||
|
|
74b4238f04 | ||
|
|
a8eb403280 | ||
|
|
750f8c6738 | ||
|
|
83ee9253fe | ||
|
|
0b90145b31 | ||
|
|
8cb697dfcd | ||
|
|
cd5c7ce02c | ||
|
|
6504f78518 | ||
|
|
11ce7c9e30 | ||
|
|
8956400e44 | ||
|
|
aba0db268a |
43
Cargo.lock
generated
43
Cargo.lock
generated
@@ -509,6 +509,19 @@ dependencies = [
|
||||
"syn 1.0.37",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "env_logger"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36"
|
||||
dependencies = [
|
||||
"atty",
|
||||
"humantime",
|
||||
"log 0.4.11",
|
||||
"regex",
|
||||
"termcolor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "err-derive"
|
||||
version = "0.2.4"
|
||||
@@ -888,6 +901,15 @@ version = "1.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9"
|
||||
|
||||
[[package]]
|
||||
name = "humantime"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f"
|
||||
dependencies = [
|
||||
"quick-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "0.10.16"
|
||||
@@ -1885,14 +1907,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "revolt"
|
||||
version = "0.2.3"
|
||||
version = "0.2.8"
|
||||
dependencies = [
|
||||
"bcrypt",
|
||||
"bitfield",
|
||||
"chrono",
|
||||
"dotenv",
|
||||
"env_logger",
|
||||
"hashbrown 0.7.2",
|
||||
"lazy_static",
|
||||
"log 0.4.11",
|
||||
"lru",
|
||||
"mongodb",
|
||||
"num_enum",
|
||||
@@ -2423,6 +2447,15 @@ dependencies = [
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "termcolor"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f"
|
||||
dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.20"
|
||||
@@ -2586,9 +2619,9 @@ checksum = "e987b6bf443f4b5b3b6f38704195592cca41c5bb7aedd3c3693c7081f8289860"
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.18"
|
||||
version = "0.1.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0aae59226cf195d8e74d4b34beae1859257efb4e5fed3f147d2dc2c7d372178"
|
||||
checksum = "6d79ca061b032d6ce30c660fded31189ca0b9922bf483cd70759f13a2d86786c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"log 0.4.11",
|
||||
@@ -2597,9 +2630,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.12"
|
||||
version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2734b5a028fa697686f16c6d18c2c6a3c7e41513f9a213abb6754c4acb3c8d7"
|
||||
checksum = "db63662723c316b43ca36d833707cc93dff82a02ba3d7e354f342682cc8b3545"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "revolt"
|
||||
version = "0.2.3"
|
||||
version = "0.2.8"
|
||||
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
@@ -28,3 +28,5 @@ rocket_cors = "0.5.2"
|
||||
bitfield = "0.13.2"
|
||||
lru = "0.5.3"
|
||||
lazy_static = "1.4.0"
|
||||
log = "0.4.11"
|
||||
env_logger = "0.7.1"
|
||||
|
||||
@@ -4,6 +4,7 @@ use lru::LruCache;
|
||||
use mongodb::bson::{doc, from_bson, Bson};
|
||||
use rocket::http::RawStr;
|
||||
use rocket::request::FromParam;
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -40,6 +41,40 @@ pub struct Channel {
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
impl Channel {
|
||||
pub fn serialise(self) -> JsonValue {
|
||||
match self.channel_type {
|
||||
0 => json!({
|
||||
"id": self.id,
|
||||
"type": self.channel_type,
|
||||
"last_message": self.last_message,
|
||||
"recipients": self.recipients,
|
||||
}),
|
||||
1 => {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"type": self.channel_type,
|
||||
"last_message": self.last_message,
|
||||
"recipients": self.recipients,
|
||||
"name": self.name,
|
||||
"owner": self.owner,
|
||||
"description": self.description,
|
||||
})
|
||||
}
|
||||
2 => {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"type": self.channel_type,
|
||||
"guild": self.guild,
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
})
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref CACHE: Arc<Mutex<LruCache<String, Channel>>> =
|
||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||
@@ -77,19 +112,19 @@ pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String> {
|
||||
pub fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
|
||||
let mut missing = vec![];
|
||||
let mut channels = vec![];
|
||||
|
||||
{
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
for gid in ids {
|
||||
let existing = cache.get(gid);
|
||||
for id in ids {
|
||||
let existing = cache.get(id);
|
||||
|
||||
if let Some(channel) = existing {
|
||||
channels.push((*channel).clone());
|
||||
} else {
|
||||
missing.push(gid);
|
||||
missing.push(id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -98,7 +133,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
|
||||
}
|
||||
|
||||
if missing.len() == 0 {
|
||||
return Ok(Some(channels));
|
||||
return Ok(channels);
|
||||
}
|
||||
|
||||
let col = get_collection("channels");
|
||||
@@ -117,7 +152,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(channels))
|
||||
Ok(channels)
|
||||
} else {
|
||||
Err("Failed to fetch channel from database.".to_string())
|
||||
}
|
||||
@@ -139,36 +174,46 @@ impl<'r> FromParam<'r> for Channel {
|
||||
}
|
||||
}
|
||||
|
||||
/*pub fn test() {
|
||||
use std::time::Instant;
|
||||
use crate::notifications::events::Notification;
|
||||
|
||||
let now = Instant::now();
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
println!("I'm about to write 4 million entries to cache.");
|
||||
for i in 0..4_000_000 {
|
||||
let c = Channel {
|
||||
id: "potato".to_string(),
|
||||
channel_type: 0,
|
||||
|
||||
active: None,
|
||||
last_message: None,
|
||||
description: None,
|
||||
guild: None,
|
||||
name: None,
|
||||
owner: None,
|
||||
recipients: None
|
||||
};
|
||||
|
||||
cache.put(format!("{}", i), c);
|
||||
pub fn process_event(event: &Notification) {
|
||||
match event {
|
||||
Notification::group_user_join(ev) => {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
if let Some(channel) = cache.peek_mut(&ev.id) {
|
||||
channel.recipients.as_mut().unwrap().push(ev.user.clone());
|
||||
}
|
||||
}
|
||||
Notification::group_user_leave(ev) => {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
if let Some(channel) = cache.peek_mut(&ev.id) {
|
||||
let recipients = channel.recipients.as_mut().unwrap();
|
||||
if let Some(pos) = recipients.iter().position(|x| *x == ev.user) {
|
||||
recipients.remove(pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
Notification::guild_channel_create(ev) => {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
cache.put(
|
||||
ev.id.clone(),
|
||||
Channel {
|
||||
id: ev.channel.clone(),
|
||||
channel_type: 2,
|
||||
active: None,
|
||||
last_message: None,
|
||||
recipients: None,
|
||||
owner: None,
|
||||
guild: Some(ev.id.clone()),
|
||||
name: Some(ev.name.clone()),
|
||||
description: Some(ev.description.clone()),
|
||||
},
|
||||
);
|
||||
}
|
||||
Notification::guild_channel_delete(ev) => {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
cache.pop(&ev.channel);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
println!("It took {} seconds, roughly {}ms per entry.", now.elapsed().as_secs_f64(), now.elapsed().as_millis() as f64 / 1_000_000.0);
|
||||
|
||||
let now = Instant::now();
|
||||
println!("Now I'm going to read every entry and immediately dispose of it.");
|
||||
for i in 0..4_000_000 {
|
||||
cache.get(&format!("{}", i));
|
||||
}
|
||||
|
||||
println!("It took {} seconds, roughly {}ms per entry.", now.elapsed().as_secs_f64(), now.elapsed().as_millis() as f64 / 1_000_000.0);
|
||||
}*/
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use lru::LruCache;
|
||||
use mongodb::bson::{doc, from_bson, Bson};
|
||||
use rocket::http::RawStr;
|
||||
use rocket::request::FromParam;
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -42,15 +43,47 @@ pub struct Guild {
|
||||
pub description: String,
|
||||
pub owner: String,
|
||||
|
||||
pub channels: Vec<String>,
|
||||
pub invites: Vec<Invite>,
|
||||
pub bans: Vec<Ban>,
|
||||
|
||||
pub default_permissions: u32,
|
||||
}
|
||||
|
||||
impl Guild {
|
||||
pub fn serialise(self) -> JsonValue {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
"owner": self.owner
|
||||
})
|
||||
}
|
||||
|
||||
pub fn fetch_channels(&self) -> Result<Vec<super::channel::Channel>, String> {
|
||||
super::channel::fetch_channels(&self.channels)
|
||||
}
|
||||
|
||||
pub fn seralise_with_channels(self) -> Result<JsonValue, String> {
|
||||
let channels = self.fetch_channels()?
|
||||
.into_iter()
|
||||
.map(|x| x.serialise())
|
||||
.collect();
|
||||
|
||||
let mut value = self.serialise();
|
||||
value.as_object_mut().unwrap().insert("channels".to_string(), channels);
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Hash, Eq, PartialEq)]
|
||||
pub struct MemberKey(pub String, pub String);
|
||||
|
||||
lazy_static! {
|
||||
static ref CACHE: Arc<Mutex<LruCache<String, Guild>>> =
|
||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||
static ref MEMBER_CACHE: Arc<Mutex<LruCache<MemberKey, Member>>> =
|
||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||
}
|
||||
|
||||
pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
||||
@@ -85,6 +118,90 @@ pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
|
||||
let mut missing = vec![];
|
||||
let mut guilds = vec![];
|
||||
|
||||
{
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
for id in ids {
|
||||
let existing = cache.get(id);
|
||||
|
||||
if let Some(guild) = existing {
|
||||
guilds.push((*guild).clone());
|
||||
} else {
|
||||
missing.push(id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err("Failed to lock cache.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
if missing.len() == 0 {
|
||||
return Ok(guilds);
|
||||
}
|
||||
|
||||
let col = get_collection("guilds");
|
||||
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
||||
for item in result {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
if let Ok(doc) = item {
|
||||
if let Ok(guild) = from_bson(Bson::Document(doc)) as Result<Guild, _> {
|
||||
cache.put(guild.id.clone(), guild.clone());
|
||||
guilds.push(guild);
|
||||
} else {
|
||||
return Err("Failed to deserialize guild!".to_string());
|
||||
}
|
||||
} else {
|
||||
return Err("Failed to fetch guild.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(guilds)
|
||||
} else {
|
||||
Err("Failed to fetch channel from database.".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
|
||||
{
|
||||
if let Ok(mut cache) = MEMBER_CACHE.lock() {
|
||||
let existing = cache.get(&key);
|
||||
|
||||
if let Some(member) = existing {
|
||||
return Ok(Some((*member).clone()));
|
||||
}
|
||||
} else {
|
||||
return Err("Failed to lock cache.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let col = get_collection("members");
|
||||
if let Ok(result) = col.find_one(
|
||||
doc! {
|
||||
"_id.guild": &key.0,
|
||||
"_id.user": &key.1,
|
||||
},
|
||||
None,
|
||||
) {
|
||||
if let Some(doc) = result {
|
||||
if let Ok(member) = from_bson(Bson::Document(doc)) as Result<Member, _> {
|
||||
let mut cache = MEMBER_CACHE.lock().unwrap();
|
||||
cache.put(key, member.clone());
|
||||
|
||||
Ok(Some(member))
|
||||
} else {
|
||||
Err("Failed to deserialize member!".to_string())
|
||||
}
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
} else {
|
||||
Err("Failed to fetch member from database.".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> FromParam<'r> for Guild {
|
||||
type Error = &'r RawStr;
|
||||
|
||||
@@ -101,24 +218,6 @@ impl<'r> FromParam<'r> for Guild {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_member(guild_id: &String, member: &String) -> Option<Member> {
|
||||
if let Ok(result) = get_collection("members").find_one(
|
||||
doc! {
|
||||
"_id.guild": &guild_id,
|
||||
"_id.user": &member,
|
||||
},
|
||||
None,
|
||||
) {
|
||||
if let Some(doc) = result {
|
||||
Some(from_bson(Bson::Document(doc)).expect("Failed to unwrap member."))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_invite<U: Into<Option<String>>>(
|
||||
code: &String,
|
||||
user: U,
|
||||
@@ -176,3 +275,34 @@ pub fn get_invite<U: Into<Option<String>>>(
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
use crate::notifications::events::Notification;
|
||||
|
||||
pub fn process_event(event: &Notification) {
|
||||
match event {
|
||||
Notification::guild_channel_create(_ev) => {} // ? for later use
|
||||
Notification::guild_channel_delete(_ev) => {} // ? for later use
|
||||
Notification::guild_delete(ev) => {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
cache.pop(&ev.id);
|
||||
}
|
||||
Notification::guild_user_join(ev) => {
|
||||
let mut cache = MEMBER_CACHE.lock().unwrap();
|
||||
cache.put(
|
||||
MemberKey ( ev.id.clone(), ev.user.clone() ),
|
||||
Member {
|
||||
id: MemberRef {
|
||||
guild: ev.id.clone(),
|
||||
user: ev.user.clone()
|
||||
},
|
||||
nickname: None
|
||||
}
|
||||
);
|
||||
}
|
||||
Notification::guild_user_leave(ev) => {
|
||||
let mut cache = MEMBER_CACHE.lock().unwrap();
|
||||
cache.pop(&MemberKey ( ev.id.clone(), ev.user.clone() ));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
39
src/database/migrations/init.rs
Normal file
39
src/database/migrations/init.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use super::super::get_db;
|
||||
use super::scripts::LATEST_REVISION;
|
||||
|
||||
use mongodb::options::CreateCollectionOptions;
|
||||
use mongodb::bson::doc;
|
||||
use log::info;
|
||||
|
||||
pub fn create_database() {
|
||||
info!("Creating database.");
|
||||
let db = get_db();
|
||||
|
||||
db.create_collection("users", None).expect("Failed to create users collection.");
|
||||
db.create_collection("channels", None).expect("Failed to create channels collection.");
|
||||
db.create_collection("guilds", None).expect("Failed to create guilds collection.");
|
||||
db.create_collection("members", None).expect("Failed to create members collection.");
|
||||
db.create_collection("messages", None).expect("Failed to create messages collection.");
|
||||
db.create_collection("migrations", None).expect("Failed to create migrations collection.");
|
||||
|
||||
db.create_collection(
|
||||
"pubsub",
|
||||
CreateCollectionOptions::builder()
|
||||
.capped(true)
|
||||
.size(1_000_000)
|
||||
.build()
|
||||
)
|
||||
.expect("Failed to create pubsub collection.");
|
||||
|
||||
db.collection("migrations")
|
||||
.insert_one(
|
||||
doc! {
|
||||
"_id": 0,
|
||||
"revision": LATEST_REVISION
|
||||
},
|
||||
None
|
||||
)
|
||||
.expect("Failed to save migration info.");
|
||||
|
||||
info!("Created database.");
|
||||
}
|
||||
19
src/database/migrations/mod.rs
Normal file
19
src/database/migrations/mod.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
use super::get_connection;
|
||||
|
||||
pub mod init;
|
||||
pub mod scripts;
|
||||
|
||||
pub fn run_migrations() {
|
||||
let client = get_connection();
|
||||
|
||||
let list = client.list_database_names(
|
||||
None,
|
||||
None
|
||||
).expect("Failed to fetch database names.");
|
||||
|
||||
if list.iter().position(|x| x == "revolt").is_none() {
|
||||
init::create_database();
|
||||
} else {
|
||||
scripts::migrate_database();
|
||||
}
|
||||
}
|
||||
108
src/database/migrations/scripts.rs
Normal file
108
src/database/migrations/scripts.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
use super::super::get_collection;
|
||||
|
||||
use serde::{Serialize, Deserialize};
|
||||
use mongodb::bson::{Bson, from_bson, doc};
|
||||
use mongodb::options::FindOptions;
|
||||
use log::info;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct MigrationInfo {
|
||||
_id: i32,
|
||||
revision: i32
|
||||
}
|
||||
|
||||
pub const LATEST_REVISION: i32 = 2;
|
||||
|
||||
pub fn migrate_database() {
|
||||
let migrations = get_collection("migrations");
|
||||
let data = migrations.find_one(None, None)
|
||||
.expect("Failed to fetch migration data.");
|
||||
|
||||
if let Some(doc) = data {
|
||||
let info: MigrationInfo = from_bson(Bson::Document(doc))
|
||||
.expect("Failed to read migration information.");
|
||||
|
||||
let revision = run_migrations(info.revision);
|
||||
|
||||
migrations.update_one(
|
||||
doc! {
|
||||
"_id": info._id
|
||||
},
|
||||
doc! {
|
||||
"$set": {
|
||||
"revision": revision
|
||||
}
|
||||
},
|
||||
None
|
||||
).expect("Failed to commit migration information.");
|
||||
|
||||
info!("Migration complete. Currently at revision {}.", revision);
|
||||
} else {
|
||||
panic!("Database was configured incorrectly, possibly because initalization failed.")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_migrations(revision: i32) -> i32 {
|
||||
info!("Starting database migration.");
|
||||
|
||||
if revision <= 0 {
|
||||
info!("Running migration [revision 0]: Test migration system.");
|
||||
}
|
||||
|
||||
if revision <= 1 {
|
||||
info!("Running migration [revision 1]: Add channels to guild object.");
|
||||
|
||||
let col = get_collection("guilds");
|
||||
let guilds = col.find(
|
||||
None,
|
||||
FindOptions::builder()
|
||||
.projection(doc! { "_id": 1 })
|
||||
.build()
|
||||
)
|
||||
.expect("Failed to fetch guilds.");
|
||||
|
||||
let result = get_collection("channels").find(
|
||||
doc! {
|
||||
"type": 2
|
||||
},
|
||||
FindOptions::builder()
|
||||
.projection(doc! { "_id": 1, "guild": 1 })
|
||||
.build()
|
||||
).expect("Failed to fetch channels.");
|
||||
|
||||
let mut channels = vec![];
|
||||
for doc in result {
|
||||
let channel = doc.expect("Failed to fetch channel.");
|
||||
let id = channel.get_str("_id").expect("Failed to get channel id.").to_string();
|
||||
let gid = channel.get_str("guild").expect("Failed to get guild id.").to_string();
|
||||
|
||||
channels.push(( id, gid ));
|
||||
}
|
||||
|
||||
for doc in guilds {
|
||||
let guild = doc.expect("Failed to fetch guild.");
|
||||
let id = guild.get_str("_id").expect("Failed to get guild id.");
|
||||
|
||||
let list: Vec<String> = channels
|
||||
.iter()
|
||||
.filter(|x| x.1 == id)
|
||||
.map(|x| x.0.clone())
|
||||
.collect();
|
||||
|
||||
col.update_one(
|
||||
doc! {
|
||||
"_id": id
|
||||
},
|
||||
doc! {
|
||||
"$set": {
|
||||
"channels": list
|
||||
}
|
||||
},
|
||||
None
|
||||
).expect("Failed to update guild.");
|
||||
}
|
||||
}
|
||||
|
||||
// Reminder to update LATEST_REVISION when adding new migrations.
|
||||
LATEST_REVISION
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
use mongodb::bson::doc;
|
||||
use mongodb::sync::{Client, Collection, Database};
|
||||
use std::env;
|
||||
|
||||
@@ -10,13 +9,8 @@ pub fn connect() {
|
||||
Client::with_uri_str(&env::var("DB_URI").expect("DB_URI not in environment variables!"))
|
||||
.expect("Failed to init db connection.");
|
||||
|
||||
client
|
||||
.database("revolt")
|
||||
.collection("migrations")
|
||||
.find(doc! {}, None)
|
||||
.expect("Failed to get migration data from database.");
|
||||
|
||||
DBCONN.set(client).unwrap();
|
||||
migrations::run_migrations();
|
||||
}
|
||||
|
||||
pub fn get_connection() -> &'static Client {
|
||||
@@ -31,6 +25,8 @@ pub fn get_collection(collection: &str) -> Collection {
|
||||
get_db().collection(collection)
|
||||
}
|
||||
|
||||
pub mod migrations;
|
||||
|
||||
pub mod channel;
|
||||
pub mod guild;
|
||||
pub mod message;
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use super::mutual::has_mutual_connection;
|
||||
use crate::database::channel::Channel;
|
||||
use crate::database::guild::{fetch_guild, get_member, Guild, Member};
|
||||
use crate::database::user::UserRelationship;
|
||||
use crate::guards::auth::UserRef;
|
||||
use crate::database::guild::{fetch_guild, fetch_member, Guild, Member, MemberKey};
|
||||
use crate::database::user::{User, UserRelationship};
|
||||
|
||||
use num_enum::TryFromPrimitive;
|
||||
|
||||
@@ -77,23 +76,23 @@ pub fn get_relationship_internal(
|
||||
Relationship::NONE
|
||||
}
|
||||
|
||||
pub fn get_relationship(a: &UserRef, b: &UserRef) -> Relationship {
|
||||
pub fn get_relationship(a: &User, b: &User) -> Relationship {
|
||||
if a.id == b.id {
|
||||
return Relationship::SELF;
|
||||
}
|
||||
|
||||
get_relationship_internal(&a.id, &b.id, &a.fetch_relationships())
|
||||
get_relationship_internal(&a.id, &b.id, &a.relations)
|
||||
}
|
||||
|
||||
pub struct PermissionCalculator {
|
||||
pub user: UserRef,
|
||||
pub user: User,
|
||||
pub channel: Option<Channel>,
|
||||
pub guild: Option<Guild>,
|
||||
pub member: Option<Member>,
|
||||
}
|
||||
|
||||
impl PermissionCalculator {
|
||||
pub fn new(user: UserRef) -> PermissionCalculator {
|
||||
pub fn new(user: User) -> PermissionCalculator {
|
||||
PermissionCalculator {
|
||||
user,
|
||||
channel: None,
|
||||
@@ -140,7 +139,9 @@ impl PermissionCalculator {
|
||||
};
|
||||
|
||||
if let Some(guild) = &guild {
|
||||
self.member = get_member(&guild.id, &self.user.id);
|
||||
if let Ok(result) = fetch_member(MemberKey(guild.id.clone(), self.user.id.clone())) {
|
||||
self.member = result;
|
||||
}
|
||||
}
|
||||
|
||||
self.guild = guild;
|
||||
@@ -164,32 +165,31 @@ impl PermissionCalculator {
|
||||
match channel.channel_type {
|
||||
0 => {
|
||||
if let Some(arr) = &channel.recipients {
|
||||
let mut other_user = "";
|
||||
let mut other_user = None;
|
||||
for item in arr {
|
||||
if item != &self.user.id {
|
||||
other_user = item;
|
||||
other_user = Some(item);
|
||||
}
|
||||
}
|
||||
|
||||
// ? In this case, it is a "self DM".
|
||||
if other_user == "" {
|
||||
return 1024 + 128 + 32 + 16 + 1;
|
||||
}
|
||||
|
||||
let relationships = self.user.fetch_relationships();
|
||||
let relationship =
|
||||
get_relationship_internal(&self.user.id, &other_user, &relationships);
|
||||
|
||||
if relationship == Relationship::Friend {
|
||||
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||
} else if relationship == Relationship::Blocked
|
||||
|| relationship == Relationship::BlockedOther
|
||||
{
|
||||
permissions = 1;
|
||||
} else if has_mutual_connection(&self.user.id, other_user, true) {
|
||||
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||
if let Some(other) = other_user {
|
||||
let relationship =
|
||||
get_relationship_internal(&self.user.id, &other, &self.user.relations);
|
||||
|
||||
if relationship == Relationship::Friend {
|
||||
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||
} else if relationship == Relationship::Blocked
|
||||
|| relationship == Relationship::BlockedOther
|
||||
{
|
||||
permissions = 1;
|
||||
} else if has_mutual_connection(&self.user.id, other, true) {
|
||||
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||
} else {
|
||||
permissions = 1;
|
||||
}
|
||||
} else {
|
||||
permissions = 1;
|
||||
// ? In this case, it is a "self DM".
|
||||
return 1024 + 128 + 32 + 16 + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
use mongodb::bson::DateTime;
|
||||
use super::get_collection;
|
||||
use super::guild::{Guild, fetch_guilds};
|
||||
use super::channel::{Channel, fetch_channels};
|
||||
|
||||
use lru::LruCache;
|
||||
use mongodb::bson::{doc, from_bson, Bson, DateTime};
|
||||
use mongodb::options::FindOptions;
|
||||
use rocket::http::{RawStr, Status};
|
||||
use rocket::request::{self, FromParam, FromRequest, Request};
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use rocket::Outcome;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
@@ -28,3 +39,285 @@ pub struct User {
|
||||
pub email_verification: UserEmailVerification,
|
||||
pub relations: Option<Vec<UserRelationship>>,
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub fn serialise(self, relationship: i32) -> JsonValue {
|
||||
if relationship == super::Relationship::SELF as i32 {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"username": self.username,
|
||||
"display_name": self.display_name,
|
||||
"email": self.email,
|
||||
"verified": self.email_verification.verified,
|
||||
})
|
||||
} else {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"username": self.username,
|
||||
"display_name": self.display_name,
|
||||
"relationship": relationship
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_guilds(&self) -> Result<Vec<String>, String> {
|
||||
let members = get_collection("members")
|
||||
.find(
|
||||
doc! {
|
||||
"_id.user": &self.id
|
||||
},
|
||||
None
|
||||
).map_err(|_| "Failed to fetch members.")?;
|
||||
|
||||
Ok(members.into_iter()
|
||||
.filter_map(|x| match x {
|
||||
Ok(doc) => {
|
||||
match doc.get_document("_id") {
|
||||
Ok(id) => {
|
||||
match id.get_str("guild") {
|
||||
Ok(value) => Some(value.to_string()),
|
||||
Err(_) => None
|
||||
}
|
||||
}
|
||||
Err(_) => None
|
||||
}
|
||||
}
|
||||
Err(_) => None
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn find_dms(&self) -> Result<Vec<String>, String> {
|
||||
let channels = get_collection("channels")
|
||||
.find(
|
||||
doc! {
|
||||
"recipients": &self.id
|
||||
},
|
||||
FindOptions::builder()
|
||||
.projection(doc! { "_id": 1 })
|
||||
.build()
|
||||
).map_err(|_| "Failed to fetch channel ids.")?;
|
||||
|
||||
Ok(channels.into_iter()
|
||||
.filter_map(|x| x.ok())
|
||||
.filter_map(|x| {
|
||||
match x.get_str("_id") {
|
||||
Ok(value) => Some(value.to_string()),
|
||||
Err(_) => None
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn create_payload(self) -> Result<JsonValue, String> {
|
||||
let v = vec![];
|
||||
let relations = self.relations.as_ref().unwrap_or(&v);
|
||||
|
||||
let users: Vec<JsonValue> = fetch_users(
|
||||
&relations
|
||||
.iter()
|
||||
.map(|x| x.id.clone())
|
||||
.collect()
|
||||
)?
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
let id = x.id.clone();
|
||||
x.serialise(
|
||||
relations.iter()
|
||||
.find(|y| y.id == id)
|
||||
.unwrap()
|
||||
.status as i32
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let channels: Vec<JsonValue> = fetch_channels(&self.find_dms()?)?
|
||||
.into_iter()
|
||||
.map(|x| x.serialise())
|
||||
.collect();
|
||||
|
||||
let guilds: Vec<JsonValue> = fetch_guilds(&self.find_guilds()?)?
|
||||
.into_iter()
|
||||
.map(|x| x.serialise())
|
||||
.collect();
|
||||
|
||||
Ok(json!({
|
||||
"users": users,
|
||||
"channels": channels,
|
||||
"guilds": guilds,
|
||||
"user": self.serialise(super::Relationship::SELF as i32)
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref CACHE: Arc<Mutex<LruCache<String, User>>> =
|
||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||
}
|
||||
|
||||
pub fn fetch_user(id: &str) -> Result<Option<User>, String> {
|
||||
{
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
let existing = cache.get(&id.to_string());
|
||||
|
||||
if let Some(user) = existing {
|
||||
return Ok(Some((*user).clone()));
|
||||
}
|
||||
} else {
|
||||
return Err("Failed to lock cache.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let col = get_collection("users");
|
||||
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
||||
if let Some(doc) = result {
|
||||
if let Ok(user) = from_bson(Bson::Document(doc)) as Result<User, _> {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
cache.put(id.to_string(), user.clone());
|
||||
|
||||
Ok(Some(user))
|
||||
} else {
|
||||
Err("Failed to deserialize user!".to_string())
|
||||
}
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
} else {
|
||||
Err("Failed to fetch user from database.".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_users(ids: &Vec<String>) -> Result<Vec<User>, String> {
|
||||
let mut missing = vec![];
|
||||
let mut users = vec![];
|
||||
|
||||
{
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
for id in ids {
|
||||
let existing = cache.get(id);
|
||||
|
||||
if let Some(user) = existing {
|
||||
users.push((*user).clone());
|
||||
} else {
|
||||
missing.push(id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err("Failed to lock cache.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
if missing.len() == 0 {
|
||||
return Ok(users);
|
||||
}
|
||||
|
||||
let col = get_collection("users");
|
||||
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
||||
for item in result {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
if let Ok(doc) = item {
|
||||
if let Ok(user) = from_bson(Bson::Document(doc)) as Result<User, _> {
|
||||
cache.put(user.id.clone(), user.clone());
|
||||
users.push(user);
|
||||
} else {
|
||||
return Err("Failed to deserialize user!".to_string());
|
||||
}
|
||||
} else {
|
||||
return Err("Failed to fetch user.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(users)
|
||||
} else {
|
||||
Err("Failed to fetch user from database.".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AuthError {
|
||||
Failed,
|
||||
Missing,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
impl<'a, 'r> FromRequest<'a, 'r> for User {
|
||||
type Error = AuthError;
|
||||
|
||||
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
||||
let u = request.headers().get("x-user").next();
|
||||
let t = request.headers().get("x-auth-token").next();
|
||||
|
||||
if let Some(uid) = u {
|
||||
if let Some(token) = t {
|
||||
if let Ok(result) = fetch_user(uid) {
|
||||
if let Some(user) = result {
|
||||
if let Some(access_token) = &user.access_token {
|
||||
if access_token == token {
|
||||
Outcome::Success(user)
|
||||
} else {
|
||||
Outcome::Failure((Status::Forbidden, AuthError::Invalid))
|
||||
}
|
||||
} else {
|
||||
Outcome::Failure((Status::Forbidden, AuthError::Invalid))
|
||||
}
|
||||
} else {
|
||||
Outcome::Failure((Status::Forbidden, AuthError::Invalid))
|
||||
}
|
||||
} else {
|
||||
Outcome::Failure((Status::Forbidden, AuthError::Failed))
|
||||
}
|
||||
} else {
|
||||
Outcome::Failure((Status::Forbidden, AuthError::Missing))
|
||||
}
|
||||
} else {
|
||||
Outcome::Failure((Status::Forbidden, AuthError::Missing))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> FromParam<'r> for User {
|
||||
type Error = &'r RawStr;
|
||||
|
||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||
if let Ok(result) = fetch_user(¶m.to_string()) {
|
||||
if let Some(user) = result {
|
||||
Ok(user)
|
||||
} else {
|
||||
Err(param)
|
||||
}
|
||||
} else {
|
||||
Err(param)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use crate::notifications::events::Notification;
|
||||
|
||||
pub fn process_event(event: &Notification) {
|
||||
match event {
|
||||
Notification::user_friend_status(ev) => {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
if let Some(user) = cache.peek_mut(&ev.id) {
|
||||
if let Some(relations) = user.relations.as_mut() {
|
||||
if ev.status == 0 {
|
||||
if let Some(pos) = relations.iter().position(|x| x.id == ev.user) {
|
||||
relations.remove(pos);
|
||||
}
|
||||
} else {
|
||||
if let Some(entry) = relations.iter_mut().find(|x| x.id == ev.user) {
|
||||
entry.status = ev.status as u8;
|
||||
} else {
|
||||
relations.push(
|
||||
UserRelationship {
|
||||
id: ev.id.clone(),
|
||||
status: ev.status as u8
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
use mongodb::bson::{doc, from_bson, Bson, Document};
|
||||
use mongodb::options::FindOneOptions;
|
||||
use rocket::http::{RawStr, Status};
|
||||
use rocket::request::{self, FromParam, FromRequest, Request};
|
||||
use rocket::Outcome;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::database;
|
||||
use database::user::{User, UserRelationship};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct UserRef {
|
||||
pub id: String,
|
||||
pub username: String,
|
||||
pub display_name: String,
|
||||
pub email_verified: bool,
|
||||
}
|
||||
|
||||
impl UserRef {
|
||||
pub fn from(id: String) -> Option<UserRef> {
|
||||
match database::get_collection("users").find_one(
|
||||
doc! { "_id": id },
|
||||
FindOneOptions::builder()
|
||||
.projection(doc! {
|
||||
"_id": 1,
|
||||
"username": 1,
|
||||
"display_name": 1,
|
||||
"email_verification.verified": 1,
|
||||
})
|
||||
.build(),
|
||||
) {
|
||||
Ok(result) => match result {
|
||||
Some(doc) => Some(UserRef {
|
||||
id: doc.get_str("_id").unwrap().to_string(),
|
||||
username: doc.get_str("username").unwrap().to_string(),
|
||||
display_name: doc.get_str("display_name").unwrap().to_string(),
|
||||
email_verified: doc
|
||||
.get_document("email_verification")
|
||||
.unwrap()
|
||||
.get_bool("verified")
|
||||
.unwrap(),
|
||||
}),
|
||||
None => None,
|
||||
},
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_data(&self, projection: Document) -> Option<Document> {
|
||||
database::get_collection("users")
|
||||
.find_one(
|
||||
doc! { "_id": &self.id },
|
||||
FindOneOptions::builder().projection(projection).build(),
|
||||
)
|
||||
.expect("Failed to fetch user from database.")
|
||||
}
|
||||
|
||||
pub fn fetch_relationships(&self) -> Option<Vec<UserRelationship>> {
|
||||
let user = database::get_collection("users")
|
||||
.find_one(
|
||||
doc! { "_id": &self.id },
|
||||
FindOneOptions::builder()
|
||||
.projection(doc! { "relations": 1 })
|
||||
.build(),
|
||||
)
|
||||
.expect("Failed to fetch user relationships from database.")
|
||||
.expect("Missing user document.");
|
||||
|
||||
if let Ok(arr) = user.get_array("relations") {
|
||||
let mut relationships = vec![];
|
||||
for item in arr {
|
||||
relationships.push(from_bson(item.clone()).unwrap());
|
||||
}
|
||||
|
||||
Some(relationships)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AuthError {
|
||||
BadCount,
|
||||
Missing,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
impl<'a, 'r> FromRequest<'a, 'r> for UserRef {
|
||||
type Error = AuthError;
|
||||
|
||||
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
||||
let keys: Vec<_> = request.headers().get("x-auth-token").collect();
|
||||
match keys.len() {
|
||||
0 => Outcome::Failure((Status::Forbidden, AuthError::Missing)),
|
||||
1 => {
|
||||
let key = keys[0];
|
||||
let result = database::get_collection("users")
|
||||
.find_one(
|
||||
doc! { "access_token": key },
|
||||
FindOneOptions::builder()
|
||||
.projection(doc! {
|
||||
"_id": 1,
|
||||
"username": 1,
|
||||
"display_name": 1,
|
||||
"email_verification.verified": 1,
|
||||
})
|
||||
.build(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
if let Some(user) = result {
|
||||
Outcome::Success(UserRef {
|
||||
id: user.get_str("_id").unwrap().to_string(),
|
||||
username: user.get_str("username").unwrap().to_string(),
|
||||
display_name: user.get_str("display_name").unwrap().to_string(),
|
||||
email_verified: user
|
||||
.get_document("email_verification")
|
||||
.unwrap()
|
||||
.get_bool("verified")
|
||||
.unwrap(),
|
||||
})
|
||||
} else {
|
||||
Outcome::Failure((Status::Forbidden, AuthError::Invalid))
|
||||
}
|
||||
}
|
||||
_ => Outcome::Failure((Status::BadRequest, AuthError::BadCount)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'r> FromRequest<'a, 'r> for User {
|
||||
type Error = AuthError;
|
||||
|
||||
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
||||
let keys: Vec<_> = request.headers().get("x-auth-token").collect();
|
||||
match keys.len() {
|
||||
0 => Outcome::Failure((Status::Forbidden, AuthError::Missing)),
|
||||
1 => {
|
||||
let key = keys[0];
|
||||
let col = database::get_collection("users");
|
||||
let result = col.find_one(doc! { "access_token": key }, None).unwrap();
|
||||
|
||||
if let Some(user) = result {
|
||||
Outcome::Success(
|
||||
from_bson(Bson::Document(user)).expect("Failed to unwrap user."),
|
||||
)
|
||||
} else {
|
||||
Outcome::Failure((Status::Forbidden, AuthError::Invalid))
|
||||
}
|
||||
}
|
||||
_ => Outcome::Failure((Status::BadRequest, AuthError::BadCount)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> FromParam<'r> for UserRef {
|
||||
type Error = &'r RawStr;
|
||||
|
||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||
if let Some(user) = UserRef::from(param.to_string()) {
|
||||
Ok(user)
|
||||
} else {
|
||||
Err(param)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
use mongodb::bson::{doc, from_bson, Bson, Document};
|
||||
use mongodb::options::FindOneOptions;
|
||||
use rocket::http::RawStr;
|
||||
use rocket::request::FromParam;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::database;
|
||||
use crate::database::guild::{Ban, Invite, Member};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildRef {
|
||||
#[serde(rename = "_id")]
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub owner: String,
|
||||
|
||||
pub bans: Vec<Ban>,
|
||||
|
||||
pub default_permissions: i32,
|
||||
}
|
||||
|
||||
impl GuildRef {
|
||||
pub fn from(id: String) -> Option<GuildRef> {
|
||||
match database::get_collection("guilds").find_one(
|
||||
doc! { "_id": id },
|
||||
FindOneOptions::builder()
|
||||
.projection(doc! {
|
||||
"name": 1,
|
||||
"description": 1,
|
||||
"owner": 1,
|
||||
"bans": 1,
|
||||
"default_permissions": 1
|
||||
})
|
||||
.build(),
|
||||
) {
|
||||
Ok(result) => match result {
|
||||
Some(doc) => {
|
||||
Some(from_bson(mongodb::bson::mongodb::bson::Document(doc)).expect("Failed to unwrap guild."))
|
||||
}
|
||||
None => None,
|
||||
},
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_data(&self, projection: Document) -> Option<Document> {
|
||||
database::get_collection("guilds")
|
||||
.find_one(
|
||||
doc! { "_id": &self.id },
|
||||
FindOneOptions::builder().projection(projection).build(),
|
||||
)
|
||||
.expect("Failed to fetch guild from database.")
|
||||
}
|
||||
|
||||
pub fn fetch_data_given(&self, mut filter: Document, projection: Document) -> Option<Document> {
|
||||
filter.insert("_id", self.id.clone());
|
||||
database::get_collection("guilds")
|
||||
.find_one(
|
||||
filter,
|
||||
FindOneOptions::builder().projection(projection).build(),
|
||||
)
|
||||
.expect("Failed to fetch guild from database.")
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> FromParam<'r> for GuildRef {
|
||||
type Error = &'r RawStr;
|
||||
|
||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||
if let Some(guild) = GuildRef::from(param.to_string()) {
|
||||
Ok(guild)
|
||||
} else {
|
||||
Err(param)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_member(guild_id: &String, member: &String) -> Option<Member> {
|
||||
if let Ok(result) = database::get_collection("members").find_one(
|
||||
doc! {
|
||||
"_id.guild": &guild_id,
|
||||
"_id.user": &member,
|
||||
},
|
||||
None,
|
||||
) {
|
||||
if let Some(doc) = result {
|
||||
Some(from_bson(mongodb::bson::Document(doc)).expect("Failed to unwrap member."))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_invite<U: Into<Option<String>>>(
|
||||
code: &String,
|
||||
user: U,
|
||||
) -> Option<(String, String, Invite)> {
|
||||
let mut doc = doc! {
|
||||
"invites": {
|
||||
"$elemMatch": {
|
||||
"code": &code
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(user_id) = user.into() {
|
||||
doc.insert(
|
||||
"bans",
|
||||
doc! {
|
||||
"$not": {
|
||||
"$elemMatch": {
|
||||
"id": user_id
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if let Ok(result) = database::get_collection("guilds").find_one(
|
||||
doc,
|
||||
FindOneOptions::builder()
|
||||
.projection(doc! {
|
||||
"_id": 1,
|
||||
"name": 1,
|
||||
"invites.$": 1,
|
||||
})
|
||||
.build(),
|
||||
) {
|
||||
if let Some(doc) = result {
|
||||
let invite = doc
|
||||
.get_array("invites")
|
||||
.unwrap()
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap()
|
||||
.as_document()
|
||||
.unwrap();
|
||||
|
||||
Some((
|
||||
doc.get_str("_id").unwrap().to_string(),
|
||||
doc.get_str("name").unwrap().to_string(),
|
||||
from_bson(mongodb::bson::Document(invite.clone())).unwrap(),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
pub mod auth;
|
||||
@@ -9,11 +9,10 @@ extern crate bitfield;
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
|
||||
pub mod database;
|
||||
pub mod email;
|
||||
pub mod guards;
|
||||
pub mod notifications;
|
||||
pub mod database;
|
||||
pub mod routes;
|
||||
pub mod email;
|
||||
pub mod util;
|
||||
|
||||
use dotenv;
|
||||
@@ -22,6 +21,7 @@ use std::thread;
|
||||
|
||||
fn main() {
|
||||
dotenv::dotenv().ok();
|
||||
env_logger::init();
|
||||
database::connect();
|
||||
notifications::start_worker();
|
||||
|
||||
|
||||
@@ -38,4 +38,10 @@ impl Notification {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_to_cache(&self) {
|
||||
crate::database::channel::process_event(&self);
|
||||
crate::database::guild::process_event(&self);
|
||||
crate::database::user::process_event(&self);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,5 +3,6 @@ use serde::{Deserialize, Serialize};
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct FriendStatus {
|
||||
pub id: String,
|
||||
pub user: String,
|
||||
pub status: i32,
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ pub fn send_message<U: Into<Option<Vec<String>>>, G: Into<Option<String>>>(
|
||||
let users = users.into();
|
||||
let guild = guild.into();
|
||||
|
||||
data.push_to_cache();
|
||||
|
||||
if pubsub::send_message(users.clone(), guild.clone(), data.clone()) {
|
||||
state::send_message(users, guild, data.serialize());
|
||||
|
||||
|
||||
@@ -36,13 +36,23 @@ impl Handler for Server {
|
||||
|
||||
match state.try_authenticate(self.id.clone(), token.to_string()) {
|
||||
StateResult::Success(user_id) => {
|
||||
let user = crate::database::user::fetch_user(&user_id).unwrap().unwrap();
|
||||
self.user_id = Some(user_id);
|
||||
|
||||
self.sender.send(
|
||||
json!({
|
||||
"type": "authenticate",
|
||||
"success": true,
|
||||
})
|
||||
.to_string(),
|
||||
)?;
|
||||
|
||||
self.sender.send(
|
||||
json!({
|
||||
"type": "ready",
|
||||
"data": user.create_payload()
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
StateResult::DatabaseError => self.sender.send(
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use super::Response;
|
||||
use crate::database::{
|
||||
self, channel::Channel, get_relationship, get_relationship_internal, message::Message,
|
||||
Permission, PermissionCalculator, Relationship,
|
||||
Permission, PermissionCalculator, Relationship, user::User
|
||||
};
|
||||
use crate::guards::auth::UserRef;
|
||||
use crate::notifications::{
|
||||
self,
|
||||
events::{groups::*, guilds::ChannelDelete, message::*, Notification},
|
||||
@@ -53,7 +52,7 @@ pub struct CreateGroup {
|
||||
|
||||
/// create a new group
|
||||
#[post("/create", data = "<info>")]
|
||||
pub fn create_group(user: UserRef, info: Json<CreateGroup>) -> Response {
|
||||
pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
||||
let name: String = info.name.chars().take(32).collect();
|
||||
let nonce: String = info.nonce.chars().take(32).collect();
|
||||
|
||||
@@ -90,13 +89,12 @@ pub fn create_group(user: UserRef, info: Json<CreateGroup>) -> Response {
|
||||
return Response::BadRequest(json!({ "error": "Specified non-existant user(s)." }));
|
||||
}
|
||||
|
||||
let relationships = user.fetch_relationships();
|
||||
for item in set {
|
||||
if item == user.id {
|
||||
continue;
|
||||
}
|
||||
|
||||
if get_relationship_internal(&user.id, &item, &relationships) != Relationship::Friend {
|
||||
if get_relationship_internal(&user.id, &item, &user.relations) != Relationship::Friend {
|
||||
return Response::BadRequest(json!({ "error": "Not friends with user(s)." }));
|
||||
}
|
||||
}
|
||||
@@ -129,58 +127,14 @@ pub fn create_group(user: UserRef, info: Json<CreateGroup>) -> Response {
|
||||
|
||||
/// fetch channel information
|
||||
#[get("/<target>")]
|
||||
pub fn channel(user: UserRef, target: Channel) -> Option<Response> {
|
||||
pub fn channel(user: User, target: Channel) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
match target.channel_type {
|
||||
0 => Some(Response::Success(json!({
|
||||
"id": target.id,
|
||||
"type": target.channel_type,
|
||||
"last_message": target.last_message,
|
||||
"recipients": target.recipients,
|
||||
}))),
|
||||
1 => {
|
||||
/*if let Some(info) = target.fetch_data(doc! {
|
||||
"name": 1,
|
||||
"description": 1,
|
||||
"owner": 1,
|
||||
}) {*/
|
||||
Some(Response::Success(json!({
|
||||
"id": target.id,
|
||||
"type": target.channel_type,
|
||||
"last_message": target.last_message,
|
||||
"recipients": target.recipients,
|
||||
"name": target.name,
|
||||
"owner": target.owner,
|
||||
"description": target.description,
|
||||
})))
|
||||
/*} else {
|
||||
None
|
||||
}*/
|
||||
}
|
||||
2 => {
|
||||
/*if let Some(info) = target.fetch_data(doc! {
|
||||
"name": 1,
|
||||
"description": 1,
|
||||
}) {*/
|
||||
Some(Response::Success(json!({
|
||||
"id": target.id,
|
||||
"type": target.channel_type,
|
||||
"guild": target.guild,
|
||||
"name": target.name,
|
||||
"description": target.description,
|
||||
})))
|
||||
/*} else {
|
||||
None
|
||||
}*/
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
Some(Response::Success(target.serialise()))
|
||||
}
|
||||
|
||||
/// [groups] add user to channel
|
||||
#[put("/<target>/recipients/<member>")]
|
||||
pub fn add_member(user: UserRef, target: Channel, member: UserRef) -> Option<Response> {
|
||||
pub fn add_member(user: User, target: Channel, member: User) -> Option<Response> {
|
||||
if target.channel_type != 1 {
|
||||
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
||||
}
|
||||
@@ -254,7 +208,7 @@ pub fn add_member(user: UserRef, target: Channel, member: UserRef) -> Option<Res
|
||||
|
||||
/// [groups] remove user from channel
|
||||
#[delete("/<target>/recipients/<member>")]
|
||||
pub fn remove_member(user: UserRef, target: Channel, member: UserRef) -> Option<Response> {
|
||||
pub fn remove_member(user: User, target: Channel, member: User) -> Option<Response> {
|
||||
if target.channel_type != 1 {
|
||||
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
||||
}
|
||||
@@ -326,7 +280,7 @@ pub fn remove_member(user: UserRef, target: Channel, member: UserRef) -> Option<
|
||||
/// or leave group DM
|
||||
/// or close DM conversation
|
||||
#[delete("/<target>")]
|
||||
pub fn delete(user: UserRef, target: Channel) -> Option<Response> {
|
||||
pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
let permissions = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_manage_channels() {
|
||||
@@ -449,7 +403,8 @@ pub fn delete(user: UserRef, target: Channel) -> Option<Response> {
|
||||
"$pull": {
|
||||
"invites": {
|
||||
"channel": &target.id
|
||||
}
|
||||
},
|
||||
"channels": &target.id
|
||||
}
|
||||
},
|
||||
None,
|
||||
@@ -488,7 +443,7 @@ pub struct MessageFetchOptions {
|
||||
/// fetch channel messages
|
||||
#[get("/<target>/messages?<options..>")]
|
||||
pub fn messages(
|
||||
user: UserRef,
|
||||
user: User,
|
||||
target: Channel,
|
||||
options: Form<MessageFetchOptions>,
|
||||
) -> Option<Response> {
|
||||
@@ -552,7 +507,7 @@ pub struct SendMessage {
|
||||
/// send a message to a channel
|
||||
#[post("/<target>/messages", data = "<message>")]
|
||||
pub fn send_message(
|
||||
user: UserRef,
|
||||
user: User,
|
||||
target: Channel,
|
||||
message: Json<SendMessage>,
|
||||
) -> Option<Response> {
|
||||
@@ -608,7 +563,7 @@ pub fn send_message(
|
||||
|
||||
/// get a message
|
||||
#[get("/<target>/messages/<message>")]
|
||||
pub fn get_message(user: UserRef, target: Channel, message: Message) -> Option<Response> {
|
||||
pub fn get_message(user: User, target: Channel, message: Message) -> Option<Response> {
|
||||
let permissions = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_read_messages() {
|
||||
@@ -641,7 +596,7 @@ pub struct EditMessage {
|
||||
/// edit a message
|
||||
#[patch("/<target>/messages/<message>", data = "<edit>")]
|
||||
pub fn edit_message(
|
||||
user: UserRef,
|
||||
user: User,
|
||||
target: Channel,
|
||||
message: Message,
|
||||
edit: Json<EditMessage>,
|
||||
@@ -699,7 +654,7 @@ pub fn edit_message(
|
||||
|
||||
/// delete a message
|
||||
#[delete("/<target>/messages/<message>")]
|
||||
pub fn delete_message(user: UserRef, target: Channel, message: Message) -> Option<Response> {
|
||||
pub fn delete_message(user: User, target: Channel, message: Message) -> Option<Response> {
|
||||
let permissions = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_manage_messages() {
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
use super::channel::ChannelType;
|
||||
use super::Response;
|
||||
use crate::database::guild::{get_invite, get_member, Guild};
|
||||
use crate::database::guild::{fetch_member as get_member, get_invite, Guild, MemberKey};
|
||||
use crate::database::{
|
||||
self, channel::fetch_channel, channel::Channel, Permission, PermissionCalculator,
|
||||
self, channel::fetch_channel, guild::fetch_guilds, channel::Channel, Permission, PermissionCalculator, user::User
|
||||
};
|
||||
use crate::guards::auth::UserRef;
|
||||
use crate::notifications::{
|
||||
self,
|
||||
events::{guilds::*, Notification},
|
||||
};
|
||||
use crate::util::gen_token;
|
||||
|
||||
use mongodb::bson::{doc, from_bson, Bson};
|
||||
use mongodb::bson::{doc, Bson};
|
||||
use mongodb::options::{FindOneOptions, FindOptions};
|
||||
use rocket::request::Form;
|
||||
use rocket_contrib::json::Json;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ulid::Ulid;
|
||||
|
||||
// ! FIXME: GET RID OF THIS
|
||||
macro_rules! with_permissions {
|
||||
($user: expr, $target: expr) => {{
|
||||
let permissions = PermissionCalculator::new($user.clone())
|
||||
@@ -35,54 +35,35 @@ macro_rules! with_permissions {
|
||||
|
||||
/// fetch your guilds
|
||||
#[get("/@me")]
|
||||
pub fn my_guilds(user: UserRef) -> Response {
|
||||
if let Ok(result) = database::get_collection("members").find(
|
||||
doc! {
|
||||
"_id.user": &user.id
|
||||
},
|
||||
None,
|
||||
) {
|
||||
let mut guilds = vec![];
|
||||
for item in result {
|
||||
if let Ok(entry) = item {
|
||||
guilds.push(Bson::String(
|
||||
entry
|
||||
.get_document("_id")
|
||||
.unwrap()
|
||||
.get_str("guild")
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
pub fn my_guilds(user: User) -> Response {
|
||||
if let Ok(gids) = user.find_guilds() {
|
||||
if let Ok(guilds) = fetch_guilds(&gids) {
|
||||
let cids: Vec<String> = guilds
|
||||
.iter()
|
||||
.flat_map(|x| x.channels.clone())
|
||||
.collect();
|
||||
|
||||
if let Ok(result) = database::get_collection("guilds").find(
|
||||
doc! {
|
||||
"_id": {
|
||||
"$in": guilds
|
||||
}
|
||||
},
|
||||
FindOptions::builder()
|
||||
.projection(doc! {
|
||||
"_id": 1,
|
||||
"name": 1,
|
||||
"description": 1,
|
||||
"owner": 1,
|
||||
})
|
||||
.build(),
|
||||
) {
|
||||
let mut parsed = vec![];
|
||||
for item in result {
|
||||
let doc = item.unwrap();
|
||||
parsed.push(json!({
|
||||
"id": doc.get_str("_id").unwrap(),
|
||||
"name": doc.get_str("name").unwrap(),
|
||||
"description": doc.get_str("description").unwrap(),
|
||||
"owner": doc.get_str("owner").unwrap(),
|
||||
}));
|
||||
if let Ok(channels) = database::channel::fetch_channels(&cids) {
|
||||
let data: Vec<rocket_contrib::json::JsonValue> = guilds
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
let id = x.id.clone();
|
||||
let mut obj = x.serialise();
|
||||
obj.as_object_mut().unwrap().insert(
|
||||
"channels".to_string(),
|
||||
channels.iter()
|
||||
.filter(|x| x.guild.is_some() && x.guild.as_ref().unwrap() == &id)
|
||||
.map(|x| x.clone().serialise())
|
||||
.collect()
|
||||
);
|
||||
obj
|
||||
})
|
||||
.collect();
|
||||
|
||||
Response::Success(json!(data))
|
||||
} else {
|
||||
Response::InternalServerError(json!({ "error": "Failed to fetch channels." }))
|
||||
}
|
||||
|
||||
Response::Success(json!(parsed))
|
||||
} else {
|
||||
Response::InternalServerError(json!({ "error": "Failed to fetch guilds." }))
|
||||
}
|
||||
@@ -93,48 +74,19 @@ pub fn my_guilds(user: UserRef) -> Response {
|
||||
|
||||
/// fetch a guild
|
||||
#[get("/<target>")]
|
||||
pub fn guild(user: UserRef, target: Guild) -> Option<Response> {
|
||||
pub fn guild(user: User, target: Guild) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
let col = database::get_collection("channels");
|
||||
match col.find(
|
||||
doc! {
|
||||
"type": 2,
|
||||
"guild": &target.id,
|
||||
},
|
||||
None,
|
||||
) {
|
||||
Ok(results) => {
|
||||
let mut channels = vec![];
|
||||
for item in results {
|
||||
if let Ok(entry) = item {
|
||||
if let Ok(channel) = from_bson(Bson::Document(entry)) as Result<Channel, _> {
|
||||
channels.push(json!({
|
||||
"id": channel.id,
|
||||
"name": channel.name,
|
||||
"description": channel.description,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(Response::Success(json!({
|
||||
"id": target.id,
|
||||
"name": target.name,
|
||||
"description": target.description,
|
||||
"owner": target.owner,
|
||||
"channels": channels,
|
||||
})))
|
||||
}
|
||||
Err(_) => Some(Response::InternalServerError(
|
||||
json!({ "error": "Failed to fetch channels." }),
|
||||
)),
|
||||
|
||||
if let Ok(result) = target.seralise_with_channels() {
|
||||
Some(Response::Success(result))
|
||||
} else {
|
||||
Some(Response::InternalServerError(json!({ "error": "Failed to fetch channels!" })))
|
||||
}
|
||||
}
|
||||
|
||||
/// delete or leave a guild
|
||||
#[delete("/<target>")]
|
||||
pub fn remove_guild(user: UserRef, target: Guild) -> Option<Response> {
|
||||
pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
if user.id == target.owner {
|
||||
@@ -265,7 +217,7 @@ pub struct CreateChannel {
|
||||
|
||||
/// create a new channel
|
||||
#[post("/<target>/channels", data = "<info>")]
|
||||
pub fn create_channel(user: UserRef, target: Guild, info: Json<CreateChannel>) -> Option<Response> {
|
||||
pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> Option<Response> {
|
||||
let (permissions, _) = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_manage_channels() {
|
||||
@@ -306,20 +258,39 @@ pub fn create_channel(user: UserRef, target: Guild, info: Json<CreateChannel>) -
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
target.id.clone(),
|
||||
Notification::guild_channel_create(ChannelCreate {
|
||||
id: target.id.clone(),
|
||||
channel: id.clone(),
|
||||
name: name.clone(),
|
||||
description: description.clone(),
|
||||
}),
|
||||
);
|
||||
if database::get_collection("guilds")
|
||||
.update_one(
|
||||
doc! {
|
||||
"_id": &target.id
|
||||
},
|
||||
doc! {
|
||||
"$addToSet": {
|
||||
"channels": &id
|
||||
}
|
||||
},
|
||||
None
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
target.id.clone(),
|
||||
Notification::guild_channel_create(ChannelCreate {
|
||||
id: target.id.clone(),
|
||||
channel: id.clone(),
|
||||
name: name.clone(),
|
||||
description: description.clone(),
|
||||
}),
|
||||
);
|
||||
|
||||
Some(Response::Success(json!({ "id": &id })))
|
||||
Some(Response::Success(json!({ "id": &id })))
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Couldn't save channel list." }),
|
||||
))
|
||||
}
|
||||
} else {
|
||||
Some(Response::BadRequest(
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Couldn't create channel." }),
|
||||
))
|
||||
}
|
||||
@@ -338,7 +309,7 @@ pub struct InviteOptions {
|
||||
/// create a new invite
|
||||
#[post("/<target>/channels/<channel>/invite", data = "<_options>")]
|
||||
pub fn create_invite(
|
||||
user: UserRef,
|
||||
user: User,
|
||||
target: Guild,
|
||||
channel: Channel,
|
||||
_options: Json<InviteOptions>,
|
||||
@@ -376,7 +347,7 @@ pub fn create_invite(
|
||||
|
||||
/// remove an invite
|
||||
#[delete("/<target>/invites/<code>")]
|
||||
pub fn remove_invite(user: UserRef, target: Guild, code: String) -> Option<Response> {
|
||||
pub fn remove_invite(user: User, target: Guild, code: String) -> Option<Response> {
|
||||
let (permissions, _) = with_permissions!(user, target);
|
||||
|
||||
if let Some((guild_id, _, invite)) = get_invite(&code, None) {
|
||||
@@ -417,7 +388,7 @@ pub fn remove_invite(user: UserRef, target: Guild, code: String) -> Option<Respo
|
||||
|
||||
/// fetch all guild invites
|
||||
#[get("/<target>/invites")]
|
||||
pub fn fetch_invites(user: UserRef, target: Guild) -> Option<Response> {
|
||||
pub fn fetch_invites(user: User, target: Guild) -> Option<Response> {
|
||||
let (permissions, _) = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_manage_server() {
|
||||
@@ -429,7 +400,7 @@ pub fn fetch_invites(user: UserRef, target: Guild) -> Option<Response> {
|
||||
|
||||
/// view an invite before joining
|
||||
#[get("/join/<code>", rank = 1)]
|
||||
pub fn fetch_invite(user: UserRef, code: String) -> Response {
|
||||
pub fn fetch_invite(user: User, code: String) -> Response {
|
||||
if let Some((guild_id, name, invite)) = get_invite(&code, user.id) {
|
||||
match fetch_channel(&invite.channel) {
|
||||
Ok(result) => {
|
||||
@@ -457,7 +428,7 @@ pub fn fetch_invite(user: UserRef, code: String) -> Response {
|
||||
|
||||
/// join a guild using an invite
|
||||
#[post("/join/<code>", rank = 1)]
|
||||
pub fn use_invite(user: UserRef, code: String) -> Response {
|
||||
pub fn use_invite(user: User, code: String) -> Response {
|
||||
if let Some((guild_id, _, invite)) = get_invite(&code, Some(user.id.clone())) {
|
||||
if let Ok(result) = database::get_collection("members").find_one(
|
||||
doc! {
|
||||
@@ -521,8 +492,8 @@ pub struct CreateGuild {
|
||||
|
||||
/// create a new guild
|
||||
#[post("/create", data = "<info>")]
|
||||
pub fn create_guild(user: UserRef, info: Json<CreateGuild>) -> Response {
|
||||
if !user.email_verified {
|
||||
pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||
if !user.email_verification.verified {
|
||||
return Response::Unauthorized(json!({ "error": "Email not verified!" }));
|
||||
}
|
||||
|
||||
@@ -611,7 +582,7 @@ pub fn create_guild(user: UserRef, info: Json<CreateGuild>) -> Response {
|
||||
|
||||
/// fetch a guild's member
|
||||
#[get("/<target>/members")]
|
||||
pub fn fetch_members(user: UserRef, target: Guild) -> Option<Response> {
|
||||
pub fn fetch_members(user: User, target: Guild) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
if let Ok(result) =
|
||||
@@ -638,24 +609,30 @@ pub fn fetch_members(user: UserRef, target: Guild) -> Option<Response> {
|
||||
|
||||
/// fetch a guild member
|
||||
#[get("/<target>/members/<other>")]
|
||||
pub fn fetch_member(user: UserRef, target: Guild, other: String) -> Option<Response> {
|
||||
pub fn fetch_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
if let Some(member) = get_member(&target.id, &other) {
|
||||
Some(Response::Success(json!({
|
||||
"id": member.id.user,
|
||||
"nickname": member.nickname,
|
||||
})))
|
||||
if let Ok(result) = get_member(MemberKey(target.id, other)) {
|
||||
if let Some(member) = result {
|
||||
Some(Response::Success(json!({
|
||||
"id": member.id.user,
|
||||
"nickname": member.nickname,
|
||||
})))
|
||||
} else {
|
||||
Some(Response::NotFound(
|
||||
json!({ "error": "Member does not exist!" }),
|
||||
))
|
||||
}
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Failed to fetch member or user does not exist." }),
|
||||
json!({ "error": "Failed to fetch member." }),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// kick a guild member
|
||||
#[delete("/<target>/members/<other>")]
|
||||
pub fn kick_member(user: UserRef, target: Guild, other: String) -> Option<Response> {
|
||||
pub fn kick_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||
let (permissions, _) = with_permissions!(user, target);
|
||||
|
||||
if user.id == other {
|
||||
@@ -668,10 +645,14 @@ pub fn kick_member(user: UserRef, target: Guild, other: String) -> Option<Respon
|
||||
return Some(Response::LackingPermission(Permission::KickMembers));
|
||||
}
|
||||
|
||||
if get_member(&target.id, &other).is_none() {
|
||||
return Some(Response::BadRequest(
|
||||
json!({ "error": "User not part of guild." }),
|
||||
));
|
||||
if let Ok(result) = get_member(MemberKey( target.id.clone(), other.clone() )) {
|
||||
if result.is_none() {
|
||||
return Some(Response::BadRequest(
|
||||
json!({ "error": "User not part of guild." }),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
return Some(Response::InternalServerError(json!({ "error": "Failed to fetch member." })))
|
||||
}
|
||||
|
||||
if database::get_collection("members")
|
||||
@@ -710,7 +691,7 @@ pub struct BanOptions {
|
||||
/// ban a guild member
|
||||
#[put("/<target>/members/<other>/ban?<options..>")]
|
||||
pub fn ban_member(
|
||||
user: UserRef,
|
||||
user: User,
|
||||
target: Guild,
|
||||
other: String,
|
||||
options: Form<BanOptions>,
|
||||
@@ -734,10 +715,14 @@ pub fn ban_member(
|
||||
return Some(Response::LackingPermission(Permission::BanMembers));
|
||||
}
|
||||
|
||||
if get_member(&target.id, &other).is_none() {
|
||||
return Some(Response::BadRequest(
|
||||
json!({ "error": "User not part of guild." }),
|
||||
));
|
||||
if let Ok(result) = get_member(MemberKey( target.id.clone(), other.clone() )) {
|
||||
if result.is_none() {
|
||||
return Some(Response::BadRequest(
|
||||
json!({ "error": "User not part of guild." }),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
return Some(Response::InternalServerError(json!({ "error": "Failed to fetch member." })))
|
||||
}
|
||||
|
||||
if database::get_collection("guilds")
|
||||
@@ -790,7 +775,7 @@ pub fn ban_member(
|
||||
|
||||
/// unban a guild member
|
||||
#[delete("/<target>/members/<other>/ban")]
|
||||
pub fn unban_member(user: UserRef, target: Guild, other: String) -> Option<Response> {
|
||||
pub fn unban_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||
let (permissions, _) = with_permissions!(user, target);
|
||||
|
||||
if user.id == other {
|
||||
|
||||
@@ -6,7 +6,12 @@ use mongodb::bson::doc;
|
||||
#[get("/")]
|
||||
pub fn root() -> Response {
|
||||
Response::Success(json!({
|
||||
"revolt": "0.2.3"
|
||||
"revolt": "0.2.8",
|
||||
"version": {
|
||||
"major": 0,
|
||||
"minor": 2,
|
||||
"patch": 8
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use super::Response;
|
||||
use crate::database::{self, get_relationship, get_relationship_internal, mutual, Relationship};
|
||||
use crate::guards::auth::UserRef;
|
||||
use crate::database::{self, get_relationship, get_relationship_internal, mutual, Relationship, user::User};
|
||||
use crate::notifications::{
|
||||
self,
|
||||
events::{users::*, Notification},
|
||||
@@ -15,36 +14,19 @@ use ulid::Ulid;
|
||||
|
||||
/// retrieve your user information
|
||||
#[get("/@me")]
|
||||
pub fn me(user: UserRef) -> Response {
|
||||
if let Some(info) = user.fetch_data(doc! { "email": 1 }) {
|
||||
Response::Success(json!({
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"display_name": user.display_name,
|
||||
"email": info.get_str("email").unwrap(),
|
||||
"verified": user.email_verified,
|
||||
}))
|
||||
} else {
|
||||
Response::InternalServerError(
|
||||
json!({ "error": "Failed to fetch information from database." }),
|
||||
)
|
||||
}
|
||||
pub fn me(user: User) -> Response {
|
||||
Response::Success(
|
||||
user.serialise(Relationship::SELF as i32)
|
||||
)
|
||||
}
|
||||
|
||||
/// retrieve another user's information
|
||||
#[get("/<target>")]
|
||||
pub fn user(user: UserRef, target: UserRef) -> Response {
|
||||
Response::Success(json!({
|
||||
"id": target.id,
|
||||
"username": target.username,
|
||||
"display_name": target.display_name,
|
||||
"relationship": get_relationship(&user, &target) as i32,
|
||||
"mutual": {
|
||||
"guilds": mutual::find_mutual_guilds(&user.id, &target.id),
|
||||
"friends": mutual::find_mutual_friends(&user.id, &target.id),
|
||||
"groups": mutual::find_mutual_groups(&user.id, &target.id),
|
||||
}
|
||||
}))
|
||||
pub fn user(user: User, target: User) -> Response {
|
||||
let relationship = get_relationship(&user, &target) as i32;
|
||||
Response::Success(
|
||||
user.serialise(relationship)
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -54,8 +36,7 @@ pub struct UserQuery {
|
||||
|
||||
/// find a user by their username
|
||||
#[post("/query", data = "<query>")]
|
||||
pub fn query(user: UserRef, query: Json<UserQuery>) -> Response {
|
||||
let relationships = user.fetch_relationships();
|
||||
pub fn query(user: User, query: Json<UserQuery>) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
if let Ok(result) = col.find_one(
|
||||
@@ -70,7 +51,7 @@ pub fn query(user: UserRef, query: Json<UserQuery>) -> Response {
|
||||
"id": id,
|
||||
"username": doc.get_str("username").unwrap(),
|
||||
"display_name": doc.get_str("display_name").unwrap(),
|
||||
"relationship": get_relationship_internal(&user.id, &id, &relationships) as i32
|
||||
"relationship": get_relationship_internal(&user.id, &id, &user.relations) as i32
|
||||
}))
|
||||
} else {
|
||||
Response::NotFound(json!({
|
||||
@@ -90,7 +71,7 @@ pub struct LookupQuery {
|
||||
/// lookup a user on Revolt
|
||||
/// currently only supports exact username searches
|
||||
#[post("/lookup", data = "<query>")]
|
||||
pub fn lookup(user: UserRef, query: Json<LookupQuery>) -> Response {
|
||||
pub fn lookup(user: User, query: Json<LookupQuery>) -> Response {
|
||||
let relationships = user.fetch_relationships();
|
||||
let col = database::get_collection("users");
|
||||
|
||||
@@ -121,7 +102,7 @@ pub fn lookup(user: UserRef, query: Json<LookupQuery>) -> Response {
|
||||
|
||||
/// retrieve all of your DMs
|
||||
#[get("/@me/dms")]
|
||||
pub fn dms(user: UserRef) -> Response {
|
||||
pub fn dms(user: User) -> Response {
|
||||
let col = database::get_collection("channels");
|
||||
|
||||
if let Ok(results) = col.find(
|
||||
@@ -178,7 +159,7 @@ pub fn dms(user: UserRef) -> Response {
|
||||
|
||||
/// open a DM with a user
|
||||
#[get("/<target>/dm")]
|
||||
pub fn dm(user: UserRef, target: UserRef) -> Response {
|
||||
pub fn dm(user: User, target: User) -> Response {
|
||||
let col = database::get_collection("channels");
|
||||
|
||||
if let Ok(result) = col.find_one(
|
||||
@@ -211,11 +192,9 @@ pub fn dm(user: UserRef, target: UserRef) -> Response {
|
||||
|
||||
/// retrieve all of your friends
|
||||
#[get("/@me/friend")]
|
||||
pub fn get_friends(user: UserRef) -> Response {
|
||||
let relationships = user.fetch_relationships();
|
||||
|
||||
pub fn get_friends(user: User) -> Response {
|
||||
let mut results = Vec::new();
|
||||
if let Some(arr) = relationships {
|
||||
if let Some(arr) = user.relations {
|
||||
for item in arr {
|
||||
results.push(json!({
|
||||
"id": item.id,
|
||||
@@ -229,13 +208,13 @@ pub fn get_friends(user: UserRef) -> Response {
|
||||
|
||||
/// retrieve friend status with user
|
||||
#[get("/<target>/friend")]
|
||||
pub fn get_friend(user: UserRef, target: UserRef) -> Response {
|
||||
pub fn get_friend(user: User, target: User) -> Response {
|
||||
Response::Success(json!({ "status": get_relationship(&user, &target) as i32 }))
|
||||
}
|
||||
|
||||
/// create or accept a friend request
|
||||
#[put("/<target>/friend")]
|
||||
pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
||||
pub fn add_friend(user: User, target: User) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
match get_relationship(&user, &target) {
|
||||
@@ -278,7 +257,8 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
id: target.id.clone(),
|
||||
user: user.id.clone(),
|
||||
status: Relationship::Friend as i32,
|
||||
}),
|
||||
);
|
||||
@@ -287,7 +267,8 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
id: user.id.clone(),
|
||||
user: target.id.clone(),
|
||||
status: Relationship::Friend as i32,
|
||||
}),
|
||||
);
|
||||
@@ -349,7 +330,8 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
id: user.id.clone(),
|
||||
user: target.id.clone(),
|
||||
status: Relationship::Outgoing as i32,
|
||||
}),
|
||||
);
|
||||
@@ -358,7 +340,8 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
id: target.id.clone(),
|
||||
user: user.id.clone(),
|
||||
status: Relationship::Incoming as i32,
|
||||
}),
|
||||
);
|
||||
@@ -383,7 +366,7 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
||||
|
||||
/// remove a friend or deny a request
|
||||
#[delete("/<target>/friend")]
|
||||
pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
||||
pub fn remove_friend(user: User, target: User) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
match get_relationship(&user, &target) {
|
||||
@@ -424,7 +407,8 @@ pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
id: user.id.clone(),
|
||||
user: target.id.clone(),
|
||||
status: Relationship::NONE as i32,
|
||||
}),
|
||||
);
|
||||
@@ -433,7 +417,8 @@ pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
id: target.id.clone(),
|
||||
user: user.id.clone(),
|
||||
status: Relationship::NONE as i32,
|
||||
}),
|
||||
);
|
||||
@@ -459,7 +444,7 @@ pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
||||
|
||||
/// block a user
|
||||
#[put("/<target>/block")]
|
||||
pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
pub fn block_user(user: User, target: User) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
match get_relationship(&user, &target) {
|
||||
@@ -498,7 +483,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
id: user.id.clone(),
|
||||
user: target.id.clone(),
|
||||
status: Relationship::Blocked as i32,
|
||||
}),
|
||||
);
|
||||
@@ -507,7 +493,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
id: target.id.clone(),
|
||||
user: user.id.clone(),
|
||||
status: Relationship::BlockedOther as i32,
|
||||
}),
|
||||
);
|
||||
@@ -564,7 +551,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
id: user.id.clone(),
|
||||
user: target.id.clone(),
|
||||
status: Relationship::Blocked as i32,
|
||||
}),
|
||||
);
|
||||
@@ -573,7 +561,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
id: target.id.clone(),
|
||||
user: user.id.clone(),
|
||||
status: Relationship::BlockedOther as i32,
|
||||
}),
|
||||
);
|
||||
@@ -613,7 +602,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
id: user.id.clone(),
|
||||
user: target.id.clone(),
|
||||
status: Relationship::Blocked as i32,
|
||||
}),
|
||||
);
|
||||
@@ -631,7 +621,7 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
|
||||
/// unblock a user
|
||||
#[delete("/<target>/block")]
|
||||
pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
||||
pub fn unblock_user(user: User, target: User) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
match get_relationship(&user, &target) {
|
||||
@@ -656,7 +646,8 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
id: user.id.clone(),
|
||||
user: target.id.clone(),
|
||||
status: Relationship::BlockedOther as i32,
|
||||
}),
|
||||
);
|
||||
@@ -705,7 +696,8 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
id: user.id.clone(),
|
||||
user: target.id.clone(),
|
||||
status: Relationship::NONE as i32,
|
||||
}),
|
||||
);
|
||||
@@ -714,7 +706,8 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
id: target.id.clone(),
|
||||
user: user.id.clone(),
|
||||
status: Relationship::NONE as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user