forked from jmug/stoatchat
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e7eb34f65 | ||
|
|
74b4238f04 | ||
|
|
a8eb403280 | ||
|
|
750f8c6738 | ||
|
|
83ee9253fe |
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.6"
|
||||
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.6"
|
||||
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())
|
||||
}
|
||||
|
||||
@@ -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,12 +43,39 @@ 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);
|
||||
|
||||
@@ -90,6 +118,52 @@ 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() {
|
||||
|
||||
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,9 +1,13 @@
|
||||
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};
|
||||
@@ -36,6 +40,116 @@ pub struct User {
|
||||
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)));
|
||||
@@ -73,6 +187,52 @@ pub fn fetch_user(id: &str) -> Result<Option<User>, 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,
|
||||
|
||||
@@ -21,6 +21,7 @@ use std::thread;
|
||||
|
||||
fn main() {
|
||||
dotenv::dotenv().ok();
|
||||
env_logger::init();
|
||||
database::connect();
|
||||
notifications::start_worker();
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -129,51 +129,7 @@ pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
||||
#[get("/<target>")]
|
||||
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
|
||||
@@ -447,7 +403,8 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
"$pull": {
|
||||
"invites": {
|
||||
"channel": &target.id
|
||||
}
|
||||
},
|
||||
"channels": &target.id
|
||||
}
|
||||
},
|
||||
None,
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::channel::ChannelType;
|
||||
use super::Response;
|
||||
use crate::database::guild::{fetch_member as get_member, get_invite, Guild, MemberKey};
|
||||
use crate::database::{
|
||||
self, channel::fetch_channel, channel::Channel, Permission, PermissionCalculator, user::User
|
||||
self, channel::fetch_channel, guild::fetch_guilds, channel::Channel, Permission, PermissionCalculator, user::User
|
||||
};
|
||||
use crate::notifications::{
|
||||
self,
|
||||
@@ -10,13 +10,14 @@ use crate::notifications::{
|
||||
};
|
||||
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,53 +36,34 @@ macro_rules! with_permissions {
|
||||
/// fetch your guilds
|
||||
#[get("/@me")]
|
||||
pub fn my_guilds(user: User) -> 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(),
|
||||
));
|
||||
}
|
||||
}
|
||||
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." }))
|
||||
}
|
||||
@@ -94,40 +76,11 @@ pub fn my_guilds(user: User) -> Response {
|
||||
#[get("/<target>")]
|
||||
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!" })))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,20 +258,39 @@ pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> O
|
||||
)
|
||||
.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." }),
|
||||
))
|
||||
}
|
||||
@@ -640,7 +612,7 @@ pub fn fetch_members(user: User, target: Guild) -> Option<Response> {
|
||||
pub fn fetch_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
if let Ok(result) = get_member(MemberKey(target.id, user.id)) {
|
||||
if let Ok(result) = get_member(MemberKey(target.id, other)) {
|
||||
if let Some(member) = result {
|
||||
Some(Response::Success(json!({
|
||||
"id": member.id.user,
|
||||
@@ -653,7 +625,7 @@ pub fn fetch_member(user: User, target: Guild, other: String) -> Option<Response
|
||||
}
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Failed to fetch member or user does not exist." }),
|
||||
json!({ "error": "Failed to fetch member." }),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,12 @@ use mongodb::bson::doc;
|
||||
#[get("/")]
|
||||
pub fn root() -> Response {
|
||||
Response::Success(json!({
|
||||
"revolt": "0.2.6"
|
||||
"revolt": "0.2.8",
|
||||
"version": {
|
||||
"major": 0,
|
||||
"minor": 2,
|
||||
"patch": 8
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -15,29 +15,18 @@ use ulid::Ulid;
|
||||
/// retrieve your user information
|
||||
#[get("/@me")]
|
||||
pub fn me(user: User) -> Response {
|
||||
Response::Success(json!({
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"display_name": user.display_name,
|
||||
"email": user.email,
|
||||
"verified": user.email_verification.verified,
|
||||
}))
|
||||
Response::Success(
|
||||
user.serialise(Relationship::SELF as i32)
|
||||
)
|
||||
}
|
||||
|
||||
/// retrieve another user's information
|
||||
#[get("/<target>")]
|
||||
pub fn user(user: User, target: User) -> 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),
|
||||
}
|
||||
}))
|
||||
let relationship = get_relationship(&user, &target) as i32;
|
||||
Response::Success(
|
||||
user.serialise(relationship)
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
|
||||
Reference in New Issue
Block a user