forked from jmug/stoatchat
Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81111c5937 | ||
|
|
49044d7796 | ||
|
|
f44180a980 | ||
|
|
8ee867eec7 | ||
|
|
dde4224deb | ||
|
|
088490dfc3 | ||
|
|
7e7eb34f65 | ||
|
|
74b4238f04 | ||
|
|
a8eb403280 | ||
|
|
750f8c6738 | ||
|
|
83ee9253fe | ||
|
|
0b90145b31 | ||
|
|
8cb697dfcd |
43
Cargo.lock
generated
43
Cargo.lock
generated
@@ -509,6 +509,19 @@ dependencies = [
|
|||||||
"syn 1.0.37",
|
"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]]
|
[[package]]
|
||||||
name = "err-derive"
|
name = "err-derive"
|
||||||
version = "0.2.4"
|
version = "0.2.4"
|
||||||
@@ -888,6 +901,15 @@ version = "1.3.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9"
|
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]]
|
[[package]]
|
||||||
name = "hyper"
|
name = "hyper"
|
||||||
version = "0.10.16"
|
version = "0.10.16"
|
||||||
@@ -1885,14 +1907,16 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "revolt"
|
name = "revolt"
|
||||||
version = "0.2.5"
|
version = "0.2.9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bcrypt",
|
"bcrypt",
|
||||||
"bitfield",
|
"bitfield",
|
||||||
"chrono",
|
"chrono",
|
||||||
"dotenv",
|
"dotenv",
|
||||||
|
"env_logger",
|
||||||
"hashbrown 0.7.2",
|
"hashbrown 0.7.2",
|
||||||
"lazy_static",
|
"lazy_static",
|
||||||
|
"log 0.4.11",
|
||||||
"lru",
|
"lru",
|
||||||
"mongodb",
|
"mongodb",
|
||||||
"num_enum",
|
"num_enum",
|
||||||
@@ -2423,6 +2447,15 @@ dependencies = [
|
|||||||
"winapi 0.3.9",
|
"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]]
|
[[package]]
|
||||||
name = "thiserror"
|
name = "thiserror"
|
||||||
version = "1.0.20"
|
version = "1.0.20"
|
||||||
@@ -2586,9 +2619,9 @@ checksum = "e987b6bf443f4b5b3b6f38704195592cca41c5bb7aedd3c3693c7081f8289860"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tracing"
|
name = "tracing"
|
||||||
version = "0.1.18"
|
version = "0.1.19"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f0aae59226cf195d8e74d4b34beae1859257efb4e5fed3f147d2dc2c7d372178"
|
checksum = "6d79ca061b032d6ce30c660fded31189ca0b9922bf483cd70759f13a2d86786c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"log 0.4.11",
|
"log 0.4.11",
|
||||||
@@ -2597,9 +2630,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tracing-core"
|
name = "tracing-core"
|
||||||
version = "0.1.12"
|
version = "0.1.14"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b2734b5a028fa697686f16c6d18c2c6a3c7e41513f9a213abb6754c4acb3c8d7"
|
checksum = "db63662723c316b43ca36d833707cc93dff82a02ba3d7e354f342682cc8b3545"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"lazy_static",
|
"lazy_static",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt"
|
name = "revolt"
|
||||||
version = "0.2.5"
|
version = "0.2.9"
|
||||||
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
@@ -28,3 +28,5 @@ rocket_cors = "0.5.2"
|
|||||||
bitfield = "0.13.2"
|
bitfield = "0.13.2"
|
||||||
lru = "0.5.3"
|
lru = "0.5.3"
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
|
log = "0.4.11"
|
||||||
|
env_logger = "0.7.1"
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
use super::get_collection;
|
use super::get_collection;
|
||||||
|
|
||||||
use lru::LruCache;
|
use lru::LruCache;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
use mongodb::bson::{doc, from_bson, Bson};
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
use rocket::http::RawStr;
|
use rocket::http::RawStr;
|
||||||
use rocket::request::FromParam;
|
use rocket::request::FromParam;
|
||||||
|
use rocket_contrib::json::JsonValue;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct LastMessage {
|
pub struct LastMessage {
|
||||||
@@ -40,6 +41,40 @@ pub struct Channel {
|
|||||||
pub description: Option<String>,
|
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! {
|
lazy_static! {
|
||||||
static ref CACHE: Arc<Mutex<LruCache<String, Channel>>> =
|
static ref CACHE: Arc<Mutex<LruCache<String, Channel>>> =
|
||||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
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 missing = vec![];
|
||||||
let mut channels = vec![];
|
let mut channels = vec![];
|
||||||
|
|
||||||
{
|
{
|
||||||
if let Ok(mut cache) = CACHE.lock() {
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
for gid in ids {
|
for id in ids {
|
||||||
let existing = cache.get(gid);
|
let existing = cache.get(id);
|
||||||
|
|
||||||
if let Some(channel) = existing {
|
if let Some(channel) = existing {
|
||||||
channels.push((*channel).clone());
|
channels.push((*channel).clone());
|
||||||
} else {
|
} else {
|
||||||
missing.push(gid);
|
missing.push(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -98,7 +133,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
|
|||||||
}
|
}
|
||||||
|
|
||||||
if missing.len() == 0 {
|
if missing.len() == 0 {
|
||||||
return Ok(Some(channels));
|
return Ok(channels);
|
||||||
}
|
}
|
||||||
|
|
||||||
let col = get_collection("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 {
|
} else {
|
||||||
Err("Failed to fetch channel from database.".to_string())
|
Err("Failed to fetch channel from database.".to_string())
|
||||||
}
|
}
|
||||||
@@ -145,25 +180,17 @@ pub fn process_event(event: &Notification) {
|
|||||||
match event {
|
match event {
|
||||||
Notification::group_user_join(ev) => {
|
Notification::group_user_join(ev) => {
|
||||||
let mut cache = CACHE.lock().unwrap();
|
let mut cache = CACHE.lock().unwrap();
|
||||||
let entry = cache.pop(&ev.id);
|
if let Some(channel) = cache.peek_mut(&ev.id) {
|
||||||
|
|
||||||
if entry.is_some() {
|
|
||||||
let mut channel = entry.unwrap();
|
|
||||||
channel.recipients.as_mut().unwrap().push(ev.user.clone());
|
channel.recipients.as_mut().unwrap().push(ev.user.clone());
|
||||||
cache.put(ev.id.clone(), channel);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Notification::group_user_leave(ev) => {
|
Notification::group_user_leave(ev) => {
|
||||||
let mut cache = CACHE.lock().unwrap();
|
let mut cache = CACHE.lock().unwrap();
|
||||||
let entry = cache.pop(&ev.id);
|
if let Some(channel) = cache.peek_mut(&ev.id) {
|
||||||
|
|
||||||
if entry.is_some() {
|
|
||||||
let mut channel = entry.unwrap();
|
|
||||||
let recipients = channel.recipients.as_mut().unwrap();
|
let recipients = channel.recipients.as_mut().unwrap();
|
||||||
if let Some(pos) = recipients.iter().position(|x| *x == ev.user) {
|
if let Some(pos) = recipients.iter().position(|x| *x == ev.user) {
|
||||||
recipients.remove(pos);
|
recipients.remove(pos);
|
||||||
}
|
}
|
||||||
cache.put(ev.id.clone(), channel);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Notification::guild_channel_create(ev) => {
|
Notification::guild_channel_create(ev) => {
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
use super::get_collection;
|
use super::get_collection;
|
||||||
|
use super::channel::fetch_channels;
|
||||||
|
|
||||||
use lru::LruCache;
|
use lru::LruCache;
|
||||||
use mongodb::bson::{doc, from_bson, Bson};
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
use rocket::http::RawStr;
|
use rocket::http::RawStr;
|
||||||
use rocket::request::FromParam;
|
use rocket::request::FromParam;
|
||||||
|
use rocket_contrib::json::JsonValue;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
@@ -42,12 +44,39 @@ pub struct Guild {
|
|||||||
pub description: String,
|
pub description: String,
|
||||||
pub owner: String,
|
pub owner: String,
|
||||||
|
|
||||||
|
pub channels: Vec<String>,
|
||||||
pub invites: Vec<Invite>,
|
pub invites: Vec<Invite>,
|
||||||
pub bans: Vec<Ban>,
|
pub bans: Vec<Ban>,
|
||||||
|
|
||||||
pub default_permissions: u32,
|
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)]
|
#[derive(Hash, Eq, PartialEq)]
|
||||||
pub struct MemberKey(pub String, pub String);
|
pub struct MemberKey(pub String, pub String);
|
||||||
|
|
||||||
@@ -90,6 +119,77 @@ 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 serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue>, String> {
|
||||||
|
let guilds = fetch_guilds(&ids)?;
|
||||||
|
let cids: Vec<String> = guilds
|
||||||
|
.iter()
|
||||||
|
.flat_map(|x| x.channels.clone())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let channels = fetch_channels(&cids)?;
|
||||||
|
Ok(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())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
|
pub fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
|
||||||
{
|
{
|
||||||
if let Ok(mut cache) = MEMBER_CACHE.lock() {
|
if let Ok(mut cache) = MEMBER_CACHE.lock() {
|
||||||
@@ -206,8 +306,8 @@ use crate::notifications::events::Notification;
|
|||||||
|
|
||||||
pub fn process_event(event: &Notification) {
|
pub fn process_event(event: &Notification) {
|
||||||
match event {
|
match event {
|
||||||
Notification::guild_channel_create(ev) => {} // ? for later use
|
Notification::guild_channel_create(_ev) => {} // ? for later use
|
||||||
Notification::guild_channel_delete(ev) => {} // ? for later use
|
Notification::guild_channel_delete(_ev) => {} // ? for later use
|
||||||
Notification::guild_delete(ev) => {
|
Notification::guild_delete(ev) => {
|
||||||
let mut cache = CACHE.lock().unwrap();
|
let mut cache = CACHE.lock().unwrap();
|
||||||
cache.pop(&ev.id);
|
cache.pop(&ev.id);
|
||||||
|
|||||||
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 mongodb::sync::{Client, Collection, Database};
|
||||||
use std::env;
|
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!"))
|
Client::with_uri_str(&env::var("DB_URI").expect("DB_URI not in environment variables!"))
|
||||||
.expect("Failed to init db connection.");
|
.expect("Failed to init db connection.");
|
||||||
|
|
||||||
client
|
|
||||||
.database("revolt")
|
|
||||||
.collection("migrations")
|
|
||||||
.find(doc! {}, None)
|
|
||||||
.expect("Failed to get migration data from database.");
|
|
||||||
|
|
||||||
DBCONN.set(client).unwrap();
|
DBCONN.set(client).unwrap();
|
||||||
|
migrations::run_migrations();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_connection() -> &'static Client {
|
pub fn get_connection() -> &'static Client {
|
||||||
@@ -31,6 +25,8 @@ pub fn get_collection(collection: &str) -> Collection {
|
|||||||
get_db().collection(collection)
|
get_db().collection(collection)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub mod migrations;
|
||||||
|
|
||||||
pub mod channel;
|
pub mod channel;
|
||||||
pub mod guild;
|
pub mod guild;
|
||||||
pub mod message;
|
pub mod message;
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
use super::mutual::has_mutual_connection;
|
use super::mutual::has_mutual_connection;
|
||||||
use crate::database::channel::Channel;
|
use crate::database::channel::Channel;
|
||||||
use crate::database::guild::{fetch_guild, fetch_member, Guild, Member, MemberKey};
|
use crate::database::guild::{fetch_guild, fetch_member, Guild, Member, MemberKey};
|
||||||
use crate::database::user::UserRelationship;
|
use crate::database::user::{User, UserRelationship};
|
||||||
use crate::guards::auth::UserRef;
|
|
||||||
|
|
||||||
use num_enum::TryFromPrimitive;
|
use num_enum::TryFromPrimitive;
|
||||||
|
|
||||||
@@ -77,23 +76,23 @@ pub fn get_relationship_internal(
|
|||||||
Relationship::NONE
|
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 {
|
if a.id == b.id {
|
||||||
return Relationship::SELF;
|
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 struct PermissionCalculator {
|
||||||
pub user: UserRef,
|
pub user: User,
|
||||||
pub channel: Option<Channel>,
|
pub channel: Option<Channel>,
|
||||||
pub guild: Option<Guild>,
|
pub guild: Option<Guild>,
|
||||||
pub member: Option<Member>,
|
pub member: Option<Member>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PermissionCalculator {
|
impl PermissionCalculator {
|
||||||
pub fn new(user: UserRef) -> PermissionCalculator {
|
pub fn new(user: User) -> PermissionCalculator {
|
||||||
PermissionCalculator {
|
PermissionCalculator {
|
||||||
user,
|
user,
|
||||||
channel: None,
|
channel: None,
|
||||||
@@ -174,9 +173,8 @@ impl PermissionCalculator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(other) = other_user {
|
if let Some(other) = other_user {
|
||||||
let relationships = self.user.fetch_relationships();
|
|
||||||
let relationship =
|
let relationship =
|
||||||
get_relationship_internal(&self.user.id, &other, &relationships);
|
get_relationship_internal(&self.user.id, &other, &self.user.relations);
|
||||||
|
|
||||||
if relationship == Relationship::Friend {
|
if relationship == Relationship::Friend {
|
||||||
permissions = 1024 + 128 + 32 + 16 + 1;
|
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||||
|
|||||||
@@ -1,4 +1,15 @@
|
|||||||
use mongodb::bson::DateTime;
|
use super::get_collection;
|
||||||
|
use super::guild::{serialise_guilds_with_channels};
|
||||||
|
use super::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};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
@@ -28,3 +39,280 @@ pub struct User {
|
|||||||
pub email_verification: UserEmailVerification,
|
pub email_verification: UserEmailVerification,
|
||||||
pub relations: Option<Vec<UserRelationship>>,
|
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();
|
||||||
|
|
||||||
|
Ok(json!({
|
||||||
|
"users": users,
|
||||||
|
"channels": channels,
|
||||||
|
"guilds": serialise_guilds_with_channels(&self.find_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 +0,0 @@
|
|||||||
pub mod auth;
|
|
||||||
@@ -9,11 +9,10 @@ extern crate bitfield;
|
|||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate lazy_static;
|
extern crate lazy_static;
|
||||||
|
|
||||||
pub mod database;
|
|
||||||
pub mod email;
|
|
||||||
pub mod guards;
|
|
||||||
pub mod notifications;
|
pub mod notifications;
|
||||||
|
pub mod database;
|
||||||
pub mod routes;
|
pub mod routes;
|
||||||
|
pub mod email;
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
|
||||||
use dotenv;
|
use dotenv;
|
||||||
@@ -22,6 +21,7 @@ use std::thread;
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
dotenv::dotenv().ok();
|
dotenv::dotenv().ok();
|
||||||
|
env_logger::init();
|
||||||
database::connect();
|
database::connect();
|
||||||
notifications::start_worker();
|
notifications::start_worker();
|
||||||
|
|
||||||
|
|||||||
@@ -41,5 +41,7 @@ impl Notification {
|
|||||||
|
|
||||||
pub fn push_to_cache(&self) {
|
pub fn push_to_cache(&self) {
|
||||||
crate::database::channel::process_event(&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)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct FriendStatus {
|
pub struct FriendStatus {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
|
pub user: String,
|
||||||
pub status: i32,
|
pub status: i32,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,13 +36,23 @@ impl Handler for Server {
|
|||||||
|
|
||||||
match state.try_authenticate(self.id.clone(), token.to_string()) {
|
match state.try_authenticate(self.id.clone(), token.to_string()) {
|
||||||
StateResult::Success(user_id) => {
|
StateResult::Success(user_id) => {
|
||||||
|
let user = crate::database::user::fetch_user(&user_id).unwrap().unwrap();
|
||||||
self.user_id = Some(user_id);
|
self.user_id = Some(user_id);
|
||||||
|
|
||||||
self.sender.send(
|
self.sender.send(
|
||||||
json!({
|
json!({
|
||||||
"type": "authenticate",
|
"type": "authenticate",
|
||||||
"success": true,
|
"success": true,
|
||||||
})
|
})
|
||||||
.to_string(),
|
.to_string(),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
self.sender.send(
|
||||||
|
json!({
|
||||||
|
"type": "ready",
|
||||||
|
"data": user.create_payload()
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
StateResult::DatabaseError => self.sender.send(
|
StateResult::DatabaseError => self.sender.send(
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use super::Response;
|
|||||||
use crate::database;
|
use crate::database;
|
||||||
use crate::email;
|
use crate::email;
|
||||||
use crate::util::gen_token;
|
use crate::util::gen_token;
|
||||||
|
use crate::util::captcha;
|
||||||
|
|
||||||
use bcrypt::{hash, verify};
|
use bcrypt::{hash, verify};
|
||||||
use chrono::prelude::*;
|
use chrono::prelude::*;
|
||||||
@@ -17,6 +18,7 @@ pub struct Create {
|
|||||||
username: String,
|
username: String,
|
||||||
password: String,
|
password: String,
|
||||||
email: String,
|
email: String,
|
||||||
|
captcha: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// create a new Revolt account
|
/// create a new Revolt account
|
||||||
@@ -28,6 +30,18 @@ pub struct Create {
|
|||||||
/// (3) add user and send email verification
|
/// (3) add user and send email verification
|
||||||
#[post("/create", data = "<info>")]
|
#[post("/create", data = "<info>")]
|
||||||
pub fn create(info: Json<Create>) -> Response {
|
pub fn create(info: Json<Create>) -> Response {
|
||||||
|
if let Err(error) = captcha::verify(&info.captcha) {
|
||||||
|
return Response::BadRequest(
|
||||||
|
json!({ "error": error })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if true {
|
||||||
|
return Response::BadRequest(
|
||||||
|
json!({ "error": "Registration disabled." })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
if info.username.len() < 2 || info.username.len() > 32 {
|
if info.username.len() < 2 || info.username.len() > 32 {
|
||||||
@@ -150,6 +164,7 @@ pub fn verify_email(code: String) -> Response {
|
|||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct Resend {
|
pub struct Resend {
|
||||||
email: String,
|
email: String,
|
||||||
|
captcha: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// resend a verification email
|
/// resend a verification email
|
||||||
@@ -158,6 +173,12 @@ pub struct Resend {
|
|||||||
/// (3) resend the email
|
/// (3) resend the email
|
||||||
#[post("/resend", data = "<info>")]
|
#[post("/resend", data = "<info>")]
|
||||||
pub fn resend_email(info: Json<Resend>) -> Response {
|
pub fn resend_email(info: Json<Resend>) -> Response {
|
||||||
|
if let Err(error) = captcha::verify(&info.captcha) {
|
||||||
|
return Response::BadRequest(
|
||||||
|
json!({ "error": error })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
if let Some(u) = col
|
if let Some(u) = col
|
||||||
@@ -218,6 +239,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
pub struct Login {
|
pub struct Login {
|
||||||
email: String,
|
email: String,
|
||||||
password: String,
|
password: String,
|
||||||
|
captcha: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// login to a Revolt account
|
/// login to a Revolt account
|
||||||
@@ -226,6 +248,12 @@ pub struct Login {
|
|||||||
/// (3) return access token
|
/// (3) return access token
|
||||||
#[post("/login", data = "<info>")]
|
#[post("/login", data = "<info>")]
|
||||||
pub fn login(info: Json<Login>) -> Response {
|
pub fn login(info: Json<Login>) -> Response {
|
||||||
|
if let Err(error) = captcha::verify(&info.captcha) {
|
||||||
|
return Response::BadRequest(
|
||||||
|
json!({ "error": error })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
if let Some(u) = col
|
if let Some(u) = col
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::database::{
|
use crate::database::{
|
||||||
self, channel::Channel, get_relationship, get_relationship_internal, message::Message,
|
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::{
|
use crate::notifications::{
|
||||||
self,
|
self,
|
||||||
events::{groups::*, guilds::ChannelDelete, message::*, Notification},
|
events::{groups::*, guilds::ChannelDelete, message::*, Notification},
|
||||||
@@ -53,7 +52,7 @@ pub struct CreateGroup {
|
|||||||
|
|
||||||
/// create a new group
|
/// create a new group
|
||||||
#[post("/create", data = "<info>")]
|
#[post("/create", data = "<info>")]
|
||||||
pub fn create_group(user: 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 name: String = info.name.chars().take(32).collect();
|
||||||
let nonce: String = info.nonce.chars().take(32).collect();
|
let nonce: String = info.nonce.chars().take(32).collect();
|
||||||
|
|
||||||
@@ -90,13 +89,12 @@ pub fn create_group(user: UserRef, info: Json<CreateGroup>) -> Response {
|
|||||||
return Response::BadRequest(json!({ "error": "Specified non-existant user(s)." }));
|
return Response::BadRequest(json!({ "error": "Specified non-existant user(s)." }));
|
||||||
}
|
}
|
||||||
|
|
||||||
let relationships = user.fetch_relationships();
|
|
||||||
for item in set {
|
for item in set {
|
||||||
if item == user.id {
|
if item == user.id {
|
||||||
continue;
|
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)." }));
|
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
|
/// fetch channel information
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub fn channel(user: UserRef, target: Channel) -> Option<Response> {
|
pub fn channel(user: User, target: Channel) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
Some(Response::Success(target.serialise()))
|
||||||
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!(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [groups] add user to channel
|
/// [groups] add user to channel
|
||||||
#[put("/<target>/recipients/<member>")]
|
#[put("/<target>/recipients/<member>")]
|
||||||
pub fn add_member(user: UserRef, target: Channel, member: UserRef) -> Option<Response> {
|
pub fn add_member(user: User, target: Channel, member: User) -> Option<Response> {
|
||||||
if target.channel_type != 1 {
|
if target.channel_type != 1 {
|
||||||
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
||||||
}
|
}
|
||||||
@@ -254,7 +208,7 @@ pub fn add_member(user: UserRef, target: Channel, member: UserRef) -> Option<Res
|
|||||||
|
|
||||||
/// [groups] remove user from channel
|
/// [groups] remove user from channel
|
||||||
#[delete("/<target>/recipients/<member>")]
|
#[delete("/<target>/recipients/<member>")]
|
||||||
pub fn remove_member(user: UserRef, target: Channel, member: UserRef) -> Option<Response> {
|
pub fn remove_member(user: User, target: Channel, member: User) -> Option<Response> {
|
||||||
if target.channel_type != 1 {
|
if target.channel_type != 1 {
|
||||||
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
||||||
}
|
}
|
||||||
@@ -326,7 +280,7 @@ pub fn remove_member(user: UserRef, target: Channel, member: UserRef) -> Option<
|
|||||||
/// or leave group DM
|
/// or leave group DM
|
||||||
/// or close DM conversation
|
/// or close DM conversation
|
||||||
#[delete("/<target>")]
|
#[delete("/<target>")]
|
||||||
pub fn delete(user: UserRef, target: Channel) -> Option<Response> {
|
pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_manage_channels() {
|
if !permissions.get_manage_channels() {
|
||||||
@@ -449,7 +403,8 @@ pub fn delete(user: UserRef, target: Channel) -> Option<Response> {
|
|||||||
"$pull": {
|
"$pull": {
|
||||||
"invites": {
|
"invites": {
|
||||||
"channel": &target.id
|
"channel": &target.id
|
||||||
}
|
},
|
||||||
|
"channels": &target.id
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
@@ -488,7 +443,7 @@ pub struct MessageFetchOptions {
|
|||||||
/// fetch channel messages
|
/// fetch channel messages
|
||||||
#[get("/<target>/messages?<options..>")]
|
#[get("/<target>/messages?<options..>")]
|
||||||
pub fn messages(
|
pub fn messages(
|
||||||
user: UserRef,
|
user: User,
|
||||||
target: Channel,
|
target: Channel,
|
||||||
options: Form<MessageFetchOptions>,
|
options: Form<MessageFetchOptions>,
|
||||||
) -> Option<Response> {
|
) -> Option<Response> {
|
||||||
@@ -552,7 +507,7 @@ pub struct SendMessage {
|
|||||||
/// send a message to a channel
|
/// send a message to a channel
|
||||||
#[post("/<target>/messages", data = "<message>")]
|
#[post("/<target>/messages", data = "<message>")]
|
||||||
pub fn send_message(
|
pub fn send_message(
|
||||||
user: UserRef,
|
user: User,
|
||||||
target: Channel,
|
target: Channel,
|
||||||
message: Json<SendMessage>,
|
message: Json<SendMessage>,
|
||||||
) -> Option<Response> {
|
) -> Option<Response> {
|
||||||
@@ -608,7 +563,7 @@ pub fn send_message(
|
|||||||
|
|
||||||
/// get a message
|
/// get a message
|
||||||
#[get("/<target>/messages/<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);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_read_messages() {
|
if !permissions.get_read_messages() {
|
||||||
@@ -641,7 +596,7 @@ pub struct EditMessage {
|
|||||||
/// edit a message
|
/// edit a message
|
||||||
#[patch("/<target>/messages/<message>", data = "<edit>")]
|
#[patch("/<target>/messages/<message>", data = "<edit>")]
|
||||||
pub fn edit_message(
|
pub fn edit_message(
|
||||||
user: UserRef,
|
user: User,
|
||||||
target: Channel,
|
target: Channel,
|
||||||
message: Message,
|
message: Message,
|
||||||
edit: Json<EditMessage>,
|
edit: Json<EditMessage>,
|
||||||
@@ -699,7 +654,7 @@ pub fn edit_message(
|
|||||||
|
|
||||||
/// delete a message
|
/// delete a message
|
||||||
#[delete("/<target>/messages/<message>")]
|
#[delete("/<target>/messages/<message>")]
|
||||||
pub fn delete_message(user: UserRef, target: Channel, message: Message) -> Option<Response> {
|
pub fn delete_message(user: User, target: Channel, message: Message) -> Option<Response> {
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_manage_messages() {
|
if !permissions.get_manage_messages() {
|
||||||
|
|||||||
@@ -2,22 +2,22 @@ use super::channel::ChannelType;
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::database::guild::{fetch_member as get_member, get_invite, Guild, MemberKey};
|
use crate::database::guild::{fetch_member as get_member, get_invite, Guild, MemberKey};
|
||||||
use crate::database::{
|
use crate::database::{
|
||||||
self, channel::fetch_channel, channel::Channel, Permission, PermissionCalculator,
|
self, channel::fetch_channel, guild::serialise_guilds_with_channels, channel::Channel, Permission, PermissionCalculator, user::User
|
||||||
};
|
};
|
||||||
use crate::guards::auth::UserRef;
|
|
||||||
use crate::notifications::{
|
use crate::notifications::{
|
||||||
self,
|
self,
|
||||||
events::{guilds::*, Notification},
|
events::{guilds::*, Notification},
|
||||||
};
|
};
|
||||||
use crate::util::gen_token;
|
use crate::util::gen_token;
|
||||||
|
|
||||||
use mongodb::bson::{doc, from_bson, Bson};
|
use mongodb::bson::{doc, Bson};
|
||||||
use mongodb::options::{FindOneOptions, FindOptions};
|
use mongodb::options::{FindOneOptions, FindOptions};
|
||||||
use rocket::request::Form;
|
use rocket::request::Form;
|
||||||
use rocket_contrib::json::Json;
|
use rocket_contrib::json::Json;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
|
|
||||||
|
// ! FIXME: GET RID OF THIS
|
||||||
macro_rules! with_permissions {
|
macro_rules! with_permissions {
|
||||||
($user: expr, $target: expr) => {{
|
($user: expr, $target: expr) => {{
|
||||||
let permissions = PermissionCalculator::new($user.clone())
|
let permissions = PermissionCalculator::new($user.clone())
|
||||||
@@ -35,54 +35,10 @@ macro_rules! with_permissions {
|
|||||||
|
|
||||||
/// fetch your guilds
|
/// fetch your guilds
|
||||||
#[get("/@me")]
|
#[get("/@me")]
|
||||||
pub fn my_guilds(user: UserRef) -> Response {
|
pub fn my_guilds(user: User) -> Response {
|
||||||
if let Ok(result) = database::get_collection("members").find(
|
if let Ok(gids) = user.find_guilds() {
|
||||||
doc! {
|
if let Ok(data) = serialise_guilds_with_channels(&gids) {
|
||||||
"_id.user": &user.id
|
Response::Success(json!(data))
|
||||||
},
|
|
||||||
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(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(),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
Response::Success(json!(parsed))
|
|
||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(json!({ "error": "Failed to fetch guilds." }))
|
Response::InternalServerError(json!({ "error": "Failed to fetch guilds." }))
|
||||||
}
|
}
|
||||||
@@ -93,48 +49,19 @@ pub fn my_guilds(user: UserRef) -> Response {
|
|||||||
|
|
||||||
/// fetch a guild
|
/// fetch a guild
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub fn guild(user: UserRef, target: Guild) -> Option<Response> {
|
pub fn guild(user: User, target: Guild) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
let col = database::get_collection("channels");
|
if let Ok(result) = target.seralise_with_channels() {
|
||||||
match col.find(
|
Some(Response::Success(result))
|
||||||
doc! {
|
} else {
|
||||||
"type": 2,
|
Some(Response::InternalServerError(json!({ "error": "Failed to fetch channels!" })))
|
||||||
"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." }),
|
|
||||||
)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// delete or leave a guild
|
/// delete or leave a guild
|
||||||
#[delete("/<target>")]
|
#[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);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if user.id == target.owner {
|
if user.id == target.owner {
|
||||||
@@ -265,7 +192,7 @@ pub struct CreateChannel {
|
|||||||
|
|
||||||
/// create a new channel
|
/// create a new channel
|
||||||
#[post("/<target>/channels", data = "<info>")]
|
#[post("/<target>/channels", data = "<info>")]
|
||||||
pub fn create_channel(user: 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);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_manage_channels() {
|
if !permissions.get_manage_channels() {
|
||||||
@@ -306,20 +233,39 @@ pub fn create_channel(user: UserRef, target: Guild, info: Json<CreateChannel>) -
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
notifications::send_message_threaded(
|
if database::get_collection("guilds")
|
||||||
None,
|
.update_one(
|
||||||
target.id.clone(),
|
doc! {
|
||||||
Notification::guild_channel_create(ChannelCreate {
|
"_id": &target.id
|
||||||
id: target.id.clone(),
|
},
|
||||||
channel: id.clone(),
|
doc! {
|
||||||
name: name.clone(),
|
"$addToSet": {
|
||||||
description: description.clone(),
|
"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 {
|
} else {
|
||||||
Some(Response::BadRequest(
|
Some(Response::InternalServerError(
|
||||||
json!({ "error": "Couldn't create channel." }),
|
json!({ "error": "Couldn't create channel." }),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
@@ -338,7 +284,7 @@ pub struct InviteOptions {
|
|||||||
/// create a new invite
|
/// create a new invite
|
||||||
#[post("/<target>/channels/<channel>/invite", data = "<_options>")]
|
#[post("/<target>/channels/<channel>/invite", data = "<_options>")]
|
||||||
pub fn create_invite(
|
pub fn create_invite(
|
||||||
user: UserRef,
|
user: User,
|
||||||
target: Guild,
|
target: Guild,
|
||||||
channel: Channel,
|
channel: Channel,
|
||||||
_options: Json<InviteOptions>,
|
_options: Json<InviteOptions>,
|
||||||
@@ -376,7 +322,7 @@ pub fn create_invite(
|
|||||||
|
|
||||||
/// remove an invite
|
/// remove an invite
|
||||||
#[delete("/<target>/invites/<code>")]
|
#[delete("/<target>/invites/<code>")]
|
||||||
pub fn remove_invite(user: UserRef, target: Guild, code: String) -> Option<Response> {
|
pub fn remove_invite(user: User, target: Guild, code: String) -> Option<Response> {
|
||||||
let (permissions, _) = with_permissions!(user, target);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if let Some((guild_id, _, invite)) = get_invite(&code, None) {
|
if let Some((guild_id, _, invite)) = get_invite(&code, None) {
|
||||||
@@ -417,7 +363,7 @@ pub fn remove_invite(user: UserRef, target: Guild, code: String) -> Option<Respo
|
|||||||
|
|
||||||
/// fetch all guild invites
|
/// fetch all guild invites
|
||||||
#[get("/<target>/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);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_manage_server() {
|
if !permissions.get_manage_server() {
|
||||||
@@ -429,7 +375,7 @@ pub fn fetch_invites(user: UserRef, target: Guild) -> Option<Response> {
|
|||||||
|
|
||||||
/// view an invite before joining
|
/// view an invite before joining
|
||||||
#[get("/join/<code>", rank = 1)]
|
#[get("/join/<code>", rank = 1)]
|
||||||
pub fn fetch_invite(user: 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) {
|
if let Some((guild_id, name, invite)) = get_invite(&code, user.id) {
|
||||||
match fetch_channel(&invite.channel) {
|
match fetch_channel(&invite.channel) {
|
||||||
Ok(result) => {
|
Ok(result) => {
|
||||||
@@ -457,7 +403,7 @@ pub fn fetch_invite(user: UserRef, code: String) -> Response {
|
|||||||
|
|
||||||
/// join a guild using an invite
|
/// join a guild using an invite
|
||||||
#[post("/join/<code>", rank = 1)]
|
#[post("/join/<code>", rank = 1)]
|
||||||
pub fn use_invite(user: 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 Some((guild_id, _, invite)) = get_invite(&code, Some(user.id.clone())) {
|
||||||
if let Ok(result) = database::get_collection("members").find_one(
|
if let Ok(result) = database::get_collection("members").find_one(
|
||||||
doc! {
|
doc! {
|
||||||
@@ -521,8 +467,8 @@ pub struct CreateGuild {
|
|||||||
|
|
||||||
/// create a new guild
|
/// create a new guild
|
||||||
#[post("/create", data = "<info>")]
|
#[post("/create", data = "<info>")]
|
||||||
pub fn create_guild(user: UserRef, info: Json<CreateGuild>) -> Response {
|
pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||||
if !user.email_verified {
|
if !user.email_verification.verified {
|
||||||
return Response::Unauthorized(json!({ "error": "Email not verified!" }));
|
return Response::Unauthorized(json!({ "error": "Email not verified!" }));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -591,6 +537,7 @@ pub fn create_guild(user: UserRef, info: Json<CreateGuild>) -> Response {
|
|||||||
"name": name,
|
"name": name,
|
||||||
"description": description,
|
"description": description,
|
||||||
"owner": &user.id,
|
"owner": &user.id,
|
||||||
|
"channels": [ channel_id.clone() ],
|
||||||
"invites": [],
|
"invites": [],
|
||||||
"bans": [],
|
"bans": [],
|
||||||
"default_permissions": 51,
|
"default_permissions": 51,
|
||||||
@@ -611,7 +558,7 @@ pub fn create_guild(user: UserRef, info: Json<CreateGuild>) -> Response {
|
|||||||
|
|
||||||
/// fetch a guild's member
|
/// fetch a guild's member
|
||||||
#[get("/<target>/members")]
|
#[get("/<target>/members")]
|
||||||
pub fn fetch_members(user: UserRef, target: Guild) -> Option<Response> {
|
pub fn fetch_members(user: User, target: Guild) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if let Ok(result) =
|
if let Ok(result) =
|
||||||
@@ -638,10 +585,10 @@ pub fn fetch_members(user: UserRef, target: Guild) -> Option<Response> {
|
|||||||
|
|
||||||
/// fetch a guild member
|
/// fetch a guild member
|
||||||
#[get("/<target>/members/<other>")]
|
#[get("/<target>/members/<other>")]
|
||||||
pub fn fetch_member(user: UserRef, target: Guild, other: String) -> Option<Response> {
|
pub fn fetch_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if let Ok(result) = get_member(MemberKey(target.id, user.id)) {
|
if let Ok(result) = get_member(MemberKey(target.id, other)) {
|
||||||
if let Some(member) = result {
|
if let Some(member) = result {
|
||||||
Some(Response::Success(json!({
|
Some(Response::Success(json!({
|
||||||
"id": member.id.user,
|
"id": member.id.user,
|
||||||
@@ -654,14 +601,14 @@ pub fn fetch_member(user: UserRef, target: Guild, other: String) -> Option<Respo
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
json!({ "error": "Failed to fetch member or user does not exist." }),
|
json!({ "error": "Failed to fetch member." }),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// kick a guild member
|
/// kick a guild member
|
||||||
#[delete("/<target>/members/<other>")]
|
#[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);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if user.id == other {
|
if user.id == other {
|
||||||
@@ -720,7 +667,7 @@ pub struct BanOptions {
|
|||||||
/// ban a guild member
|
/// ban a guild member
|
||||||
#[put("/<target>/members/<other>/ban?<options..>")]
|
#[put("/<target>/members/<other>/ban?<options..>")]
|
||||||
pub fn ban_member(
|
pub fn ban_member(
|
||||||
user: UserRef,
|
user: User,
|
||||||
target: Guild,
|
target: Guild,
|
||||||
other: String,
|
other: String,
|
||||||
options: Form<BanOptions>,
|
options: Form<BanOptions>,
|
||||||
@@ -804,7 +751,7 @@ pub fn ban_member(
|
|||||||
|
|
||||||
/// unban a guild member
|
/// unban a guild member
|
||||||
#[delete("/<target>/members/<other>/ban")]
|
#[delete("/<target>/members/<other>/ban")]
|
||||||
pub fn unban_member(user: UserRef, target: Guild, other: String) -> Option<Response> {
|
pub fn unban_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||||
let (permissions, _) = with_permissions!(user, target);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if user.id == other {
|
if user.id == other {
|
||||||
|
|||||||
@@ -1,12 +1,21 @@
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
|
|
||||||
use mongodb::bson::doc;
|
use mongodb::bson::doc;
|
||||||
|
use std::env;
|
||||||
|
|
||||||
/// root
|
/// root
|
||||||
#[get("/")]
|
#[get("/")]
|
||||||
pub fn root() -> Response {
|
pub fn root() -> Response {
|
||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
"revolt": "0.2.5"
|
"revolt": "0.2.9",
|
||||||
|
"version": {
|
||||||
|
"major": 0,
|
||||||
|
"minor": 2,
|
||||||
|
"patch": 9
|
||||||
|
},
|
||||||
|
"features": {
|
||||||
|
"captcha": env::var("HCAPTCHA_KEY").is_ok()
|
||||||
|
}
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::database::{self, get_relationship, get_relationship_internal, mutual, Relationship};
|
use crate::database::{self, get_relationship, get_relationship_internal, mutual, Relationship, user::User};
|
||||||
use crate::guards::auth::UserRef;
|
|
||||||
use crate::notifications::{
|
use crate::notifications::{
|
||||||
self,
|
self,
|
||||||
events::{users::*, Notification},
|
events::{users::*, Notification},
|
||||||
@@ -15,36 +14,19 @@ use ulid::Ulid;
|
|||||||
|
|
||||||
/// retrieve your user information
|
/// retrieve your user information
|
||||||
#[get("/@me")]
|
#[get("/@me")]
|
||||||
pub fn me(user: UserRef) -> Response {
|
pub fn me(user: User) -> Response {
|
||||||
if let Some(info) = user.fetch_data(doc! { "email": 1 }) {
|
Response::Success(
|
||||||
Response::Success(json!({
|
user.serialise(Relationship::SELF as i32)
|
||||||
"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." }),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// retrieve another user's information
|
/// retrieve another user's information
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub fn user(user: UserRef, target: UserRef) -> Response {
|
pub fn user(user: User, target: User) -> Response {
|
||||||
Response::Success(json!({
|
let relationship = get_relationship(&user, &target) as i32;
|
||||||
"id": target.id,
|
Response::Success(
|
||||||
"username": target.username,
|
user.serialise(relationship)
|
||||||
"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),
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
@@ -54,8 +36,7 @@ pub struct UserQuery {
|
|||||||
|
|
||||||
/// find a user by their username
|
/// find a user by their username
|
||||||
#[post("/query", data = "<query>")]
|
#[post("/query", data = "<query>")]
|
||||||
pub fn query(user: UserRef, query: Json<UserQuery>) -> Response {
|
pub fn query(user: User, query: Json<UserQuery>) -> Response {
|
||||||
let relationships = user.fetch_relationships();
|
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
if let Ok(result) = col.find_one(
|
if let Ok(result) = col.find_one(
|
||||||
@@ -70,7 +51,7 @@ pub fn query(user: UserRef, query: Json<UserQuery>) -> Response {
|
|||||||
"id": id,
|
"id": id,
|
||||||
"username": doc.get_str("username").unwrap(),
|
"username": doc.get_str("username").unwrap(),
|
||||||
"display_name": doc.get_str("display_name").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 {
|
} else {
|
||||||
Response::NotFound(json!({
|
Response::NotFound(json!({
|
||||||
@@ -90,7 +71,7 @@ pub struct LookupQuery {
|
|||||||
/// lookup a user on Revolt
|
/// lookup a user on Revolt
|
||||||
/// currently only supports exact username searches
|
/// currently only supports exact username searches
|
||||||
#[post("/lookup", data = "<query>")]
|
#[post("/lookup", data = "<query>")]
|
||||||
pub fn lookup(user: UserRef, query: Json<LookupQuery>) -> Response {
|
pub fn lookup(user: User, query: Json<LookupQuery>) -> Response {
|
||||||
let relationships = user.fetch_relationships();
|
let relationships = user.fetch_relationships();
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
@@ -121,7 +102,7 @@ pub fn lookup(user: UserRef, query: Json<LookupQuery>) -> Response {
|
|||||||
|
|
||||||
/// retrieve all of your DMs
|
/// retrieve all of your DMs
|
||||||
#[get("/@me/dms")]
|
#[get("/@me/dms")]
|
||||||
pub fn dms(user: UserRef) -> Response {
|
pub fn dms(user: User) -> Response {
|
||||||
let col = database::get_collection("channels");
|
let col = database::get_collection("channels");
|
||||||
|
|
||||||
if let Ok(results) = col.find(
|
if let Ok(results) = col.find(
|
||||||
@@ -178,7 +159,7 @@ pub fn dms(user: UserRef) -> Response {
|
|||||||
|
|
||||||
/// open a DM with a user
|
/// open a DM with a user
|
||||||
#[get("/<target>/dm")]
|
#[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");
|
let col = database::get_collection("channels");
|
||||||
|
|
||||||
if let Ok(result) = col.find_one(
|
if let Ok(result) = col.find_one(
|
||||||
@@ -211,11 +192,9 @@ pub fn dm(user: UserRef, target: UserRef) -> Response {
|
|||||||
|
|
||||||
/// retrieve all of your friends
|
/// retrieve all of your friends
|
||||||
#[get("/@me/friend")]
|
#[get("/@me/friend")]
|
||||||
pub fn get_friends(user: UserRef) -> Response {
|
pub fn get_friends(user: User) -> Response {
|
||||||
let relationships = user.fetch_relationships();
|
|
||||||
|
|
||||||
let mut results = Vec::new();
|
let mut results = Vec::new();
|
||||||
if let Some(arr) = relationships {
|
if let Some(arr) = user.relations {
|
||||||
for item in arr {
|
for item in arr {
|
||||||
results.push(json!({
|
results.push(json!({
|
||||||
"id": item.id,
|
"id": item.id,
|
||||||
@@ -229,13 +208,13 @@ pub fn get_friends(user: UserRef) -> Response {
|
|||||||
|
|
||||||
/// retrieve friend status with user
|
/// retrieve friend status with user
|
||||||
#[get("/<target>/friend")]
|
#[get("/<target>/friend")]
|
||||||
pub fn get_friend(user: UserRef, target: UserRef) -> Response {
|
pub fn get_friend(user: User, target: User) -> Response {
|
||||||
Response::Success(json!({ "status": get_relationship(&user, &target) as i32 }))
|
Response::Success(json!({ "status": get_relationship(&user, &target) as i32 }))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// create or accept a friend request
|
/// create or accept a friend request
|
||||||
#[put("/<target>/friend")]
|
#[put("/<target>/friend")]
|
||||||
pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
pub fn add_friend(user: User, target: User) -> Response {
|
||||||
let col = database::get_collection("users");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
match get_relationship(&user, &target) {
|
match get_relationship(&user, &target) {
|
||||||
@@ -278,7 +257,8 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![target.id.clone()],
|
vec![target.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: user.id.clone(),
|
id: target.id.clone(),
|
||||||
|
user: user.id.clone(),
|
||||||
status: Relationship::Friend as i32,
|
status: Relationship::Friend as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -287,7 +267,8 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![user.id.clone()],
|
vec![user.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: target.id.clone(),
|
id: user.id.clone(),
|
||||||
|
user: target.id.clone(),
|
||||||
status: Relationship::Friend as i32,
|
status: Relationship::Friend as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -349,7 +330,8 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![user.id.clone()],
|
vec![user.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: target.id.clone(),
|
id: user.id.clone(),
|
||||||
|
user: target.id.clone(),
|
||||||
status: Relationship::Outgoing as i32,
|
status: Relationship::Outgoing as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -358,7 +340,8 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![target.id.clone()],
|
vec![target.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: user.id.clone(),
|
id: target.id.clone(),
|
||||||
|
user: user.id.clone(),
|
||||||
status: Relationship::Incoming as i32,
|
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
|
/// remove a friend or deny a request
|
||||||
#[delete("/<target>/friend")]
|
#[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");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
match get_relationship(&user, &target) {
|
match get_relationship(&user, &target) {
|
||||||
@@ -424,7 +407,8 @@ pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![user.id.clone()],
|
vec![user.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: target.id.clone(),
|
id: user.id.clone(),
|
||||||
|
user: target.id.clone(),
|
||||||
status: Relationship::NONE as i32,
|
status: Relationship::NONE as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -433,7 +417,8 @@ pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![target.id.clone()],
|
vec![target.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: user.id.clone(),
|
id: target.id.clone(),
|
||||||
|
user: user.id.clone(),
|
||||||
status: Relationship::NONE as i32,
|
status: Relationship::NONE as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -459,7 +444,7 @@ pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
|||||||
|
|
||||||
/// block a user
|
/// block a user
|
||||||
#[put("/<target>/block")]
|
#[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");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
match get_relationship(&user, &target) {
|
match get_relationship(&user, &target) {
|
||||||
@@ -498,7 +483,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![user.id.clone()],
|
vec![user.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: target.id.clone(),
|
id: user.id.clone(),
|
||||||
|
user: target.id.clone(),
|
||||||
status: Relationship::Blocked as i32,
|
status: Relationship::Blocked as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -507,7 +493,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![target.id.clone()],
|
vec![target.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: user.id.clone(),
|
id: target.id.clone(),
|
||||||
|
user: user.id.clone(),
|
||||||
status: Relationship::BlockedOther as i32,
|
status: Relationship::BlockedOther as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -564,7 +551,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![user.id.clone()],
|
vec![user.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: target.id.clone(),
|
id: user.id.clone(),
|
||||||
|
user: target.id.clone(),
|
||||||
status: Relationship::Blocked as i32,
|
status: Relationship::Blocked as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -573,7 +561,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![target.id.clone()],
|
vec![target.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: user.id.clone(),
|
id: target.id.clone(),
|
||||||
|
user: user.id.clone(),
|
||||||
status: Relationship::BlockedOther as i32,
|
status: Relationship::BlockedOther as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -613,7 +602,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![user.id.clone()],
|
vec![user.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: target.id.clone(),
|
id: user.id.clone(),
|
||||||
|
user: target.id.clone(),
|
||||||
status: Relationship::Blocked as i32,
|
status: Relationship::Blocked as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -631,7 +621,7 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
|
|
||||||
/// unblock a user
|
/// unblock a user
|
||||||
#[delete("/<target>/block")]
|
#[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");
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
match get_relationship(&user, &target) {
|
match get_relationship(&user, &target) {
|
||||||
@@ -656,7 +646,8 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![user.id.clone()],
|
vec![user.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: target.id.clone(),
|
id: user.id.clone(),
|
||||||
|
user: target.id.clone(),
|
||||||
status: Relationship::BlockedOther as i32,
|
status: Relationship::BlockedOther as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -705,7 +696,8 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![user.id.clone()],
|
vec![user.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: target.id.clone(),
|
id: user.id.clone(),
|
||||||
|
user: target.id.clone(),
|
||||||
status: Relationship::NONE as i32,
|
status: Relationship::NONE as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -714,7 +706,8 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
vec![target.id.clone()],
|
vec![target.id.clone()],
|
||||||
None,
|
None,
|
||||||
Notification::user_friend_status(FriendStatus {
|
Notification::user_friend_status(FriendStatus {
|
||||||
id: user.id.clone(),
|
id: target.id.clone(),
|
||||||
|
user: user.id.clone(),
|
||||||
status: Relationship::NONE as i32,
|
status: Relationship::NONE as i32,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
42
src/util/captcha.rs
Normal file
42
src/util/captcha.rs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
use serde::{Serialize, Deserialize};
|
||||||
|
use reqwest::blocking::Client;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct CaptchaResponse {
|
||||||
|
success: bool
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify(user_token: &Option<String>) -> Result<(), String> {
|
||||||
|
if let Ok(key) = env::var("HCAPTCHA_KEY") {
|
||||||
|
if let Some(token) = user_token {
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
map.insert("secret", key);
|
||||||
|
map.insert("response", token.to_string());
|
||||||
|
|
||||||
|
let client = Client::new();
|
||||||
|
if let Ok(response) = client
|
||||||
|
.post("https://hcaptcha.com/siteverify")
|
||||||
|
.form(&map)
|
||||||
|
.send()
|
||||||
|
{
|
||||||
|
let result: CaptchaResponse = response
|
||||||
|
.json()
|
||||||
|
.map_err(|_| "Failed to deserialise captcha result.".to_string())?;
|
||||||
|
|
||||||
|
if result.success {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err("Unsuccessful captcha verification".to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err("Failed to verify with hCaptcha".to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err("Missing hCaptcha token!".to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ use hashbrown::HashSet;
|
|||||||
use rand::{distributions::Alphanumeric, Rng};
|
use rand::{distributions::Alphanumeric, Rng};
|
||||||
use std::iter::FromIterator;
|
use std::iter::FromIterator;
|
||||||
|
|
||||||
|
pub mod captcha;
|
||||||
|
|
||||||
pub fn vec_to_set<T: Clone + Eq + std::hash::Hash>(data: &[T]) -> HashSet<T> {
|
pub fn vec_to_set<T: Clone + Eq + std::hash::Hash>(data: &[T]) -> HashSet<T> {
|
||||||
HashSet::from_iter(data.iter().cloned())
|
HashSet::from_iter(data.iter().cloned())
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user