forked from jmug/stoatchat
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c95dc19f67 | ||
|
|
ab2a510bc6 | ||
|
|
7c374ec756 | ||
|
|
cbac802978 | ||
|
|
ff0e539c7b | ||
|
|
8bb1977025 | ||
|
|
000ffe6aaa | ||
|
|
81111c5937 | ||
|
|
49044d7796 | ||
|
|
f44180a980 | ||
|
|
8ee867eec7 | ||
|
|
dde4224deb | ||
|
|
088490dfc3 | ||
|
|
7e7eb34f65 | ||
|
|
74b4238f04 | ||
|
|
a8eb403280 | ||
|
|
750f8c6738 | ||
|
|
83ee9253fe | ||
|
|
0b90145b31 | ||
|
|
8cb697dfcd | ||
|
|
cd5c7ce02c | ||
|
|
6504f78518 | ||
|
|
11ce7c9e30 | ||
|
|
8956400e44 | ||
|
|
aba0db268a | ||
|
|
d95982fb54 | ||
|
|
17c9148556 | ||
|
|
6a1912c27b | ||
|
|
fa6ed75ed8 | ||
|
|
b0f8abef33 | ||
|
|
6f065b7575 | ||
|
|
5e59c553f3 | ||
|
|
c271054613 | ||
|
|
d99c87d6da | ||
|
|
211a8c8ec2 | ||
|
|
ef76ed25fa | ||
|
|
b687190105 | ||
|
|
fc03dd2cdb | ||
|
|
188fe30dbf | ||
|
|
2095a2982b | ||
|
|
3bca53c6a8 | ||
|
|
0bd711aa57 | ||
|
|
2851fbca25 | ||
|
|
d6c7b7465e | ||
|
|
33f3bac4b8 | ||
|
|
0a027b68e0 | ||
|
|
50ef5c43c7 |
@@ -0,0 +1,3 @@
|
|||||||
|
assets
|
||||||
|
target
|
||||||
|
.env
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
Rocket.toml
|
||||||
/target
|
/target
|
||||||
**/*.rs.bk
|
**/*.rs.bk
|
||||||
.env
|
.env
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
stages:
|
||||||
|
- build
|
||||||
|
|
||||||
|
# Rocket does not currently compile on stable Rust.
|
||||||
|
# Once it does, we can uncomment this, and instead
|
||||||
|
# put `allow-failure: true` on the nightly build.
|
||||||
|
#
|
||||||
|
# rust-latest:
|
||||||
|
# stage: build
|
||||||
|
# image: rust:latest
|
||||||
|
# script:
|
||||||
|
# - cargo build --verbose
|
||||||
|
# - cargo test --verbose
|
||||||
|
|
||||||
|
rust-nightly:
|
||||||
|
stage: build
|
||||||
|
image: rustlang/rust:nightly
|
||||||
|
script:
|
||||||
|
- cargo build --verbose
|
||||||
|
- cargo test --verbose
|
||||||
Generated
+1687
-1155
File diff suppressed because it is too large
Load Diff
+20
-16
@@ -1,29 +1,33 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt"
|
name = "revolt"
|
||||||
version = "0.2.0"
|
version = "0.2.10"
|
||||||
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
mongodb = "0.9.2"
|
mongodb = { version = "1.1.0", default-features = false, features = ["sync"] } # FIXME: rewrite database with async API
|
||||||
bson = "0.14.1"
|
rocket = { version = "0.4.5", default-features = false }
|
||||||
rocket = { version = "0.4.4", default-features = false }
|
once_cell = "1.4.1"
|
||||||
once_cell = "1.3.1"
|
|
||||||
dotenv = "0.15.0"
|
dotenv = "0.15.0"
|
||||||
ulid = "0.3.1"
|
ulid = "0.4.0"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0.115", features = ["derive"] }
|
||||||
rocket_contrib = "0.4.4"
|
rocket_contrib = "0.4.5"
|
||||||
validator = "0.10.0"
|
validator = "0.10.1"
|
||||||
bcrypt = "0.7.0"
|
bcrypt = "0.8.2"
|
||||||
chrono = "0.4.11"
|
chrono = "0.4.15"
|
||||||
rand = "0.7.3"
|
rand = "0.7.3"
|
||||||
time = "0.2.9"
|
time = "0.2.16"
|
||||||
reqwest = { version = "0.10.4", features = ["blocking", "json"] }
|
reqwest = { version = "0.10.8", features = ["blocking", "json"] }
|
||||||
num_enum = "0.4.3"
|
num_enum = "0.5.1"
|
||||||
ws = "0.9.1"
|
ws = "0.9.1"
|
||||||
hashbrown = "0.7.1"
|
hashbrown = "0.8.2"
|
||||||
serde_json = "1.0.51"
|
serde_json = "1.0.57"
|
||||||
rocket_cors = "0.5.2"
|
rocket_cors = "0.5.2"
|
||||||
bitfield = "0.13.2"
|
bitfield = "0.13.2"
|
||||||
|
lru = "0.6.0"
|
||||||
|
lazy_static = "1.4.0"
|
||||||
|
log = "0.4.11"
|
||||||
|
env_logger = "0.7.1"
|
||||||
|
lettre = "0.10.0-alpha.1"
|
||||||
|
|||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
# Build Stage
|
||||||
|
FROM ekidd/rust-musl-builder:nightly-2020-08-26 AS builder
|
||||||
|
WORKDIR /home/rust/src
|
||||||
|
|
||||||
|
RUN USER=root cargo new --bin revolt
|
||||||
|
WORKDIR ./revolt
|
||||||
|
COPY Cargo.toml Cargo.lock ./
|
||||||
|
COPY src ./src
|
||||||
|
RUN cargo build --release
|
||||||
|
|
||||||
|
# Bundle Stage
|
||||||
|
FROM scratch
|
||||||
|
COPY --from=builder /home/rust/src/revolt/target/x86_64-unknown-linux-musl/release/revolt ./
|
||||||
|
EXPOSE 8000
|
||||||
|
EXPOSE 9000
|
||||||
|
CMD ["./revolt"]
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|

|
||||||
|
|
||||||
|
Delta is a **blazing fast API server** built with Rust for the REVOLT platform.
|
||||||
|
|
||||||
|
Features:
|
||||||
|
- Robust and efficient API routes for running a chat platform.
|
||||||
|
- Distributed notification system, allowing any node to be seamlessly connected.
|
||||||
|
- Simple deployment, based mostly on pure Rust code and libraries.
|
||||||
|
- Hooks up to a MongoDB deployment, provide URI and no extra work needed.
|
||||||
|
|
||||||
|
## Docker Helper Scripts
|
||||||
|
|
||||||
|
If you have Docker installed, you can use the helper scripts to deploy Revolt in your development environment.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./build.sh # build Docker image
|
||||||
|
./run.sh # run Docker container
|
||||||
|
./monitor.sh # view container logs
|
||||||
|
./remove.sh # kill and remove container
|
||||||
|
```
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
[development]
|
|
||||||
address = "192.168.0.10"
|
|
||||||
port = 5500
|
|
||||||
|
|
||||||
[production]
|
|
||||||
address = "192.168.0.10"
|
|
||||||
port = 3000
|
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 3.9 KiB |
@@ -0,0 +1,2 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
docker logs -f revolt
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
echo "Removing Revolt container."
|
||||||
|
docker kill revolt
|
||||||
|
docker rm revolt
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Split at \n instead of space.
|
||||||
|
# https://unix.stackexchange.com/a/39482
|
||||||
|
set -f
|
||||||
|
IFS='
|
||||||
|
'
|
||||||
|
|
||||||
|
input=($(egrep -v '^#' .env))
|
||||||
|
prepended=(${input[@]/#/-e\"})
|
||||||
|
variables=${prepended[@]/%/\"}
|
||||||
|
|
||||||
|
unset IFS
|
||||||
|
set +f
|
||||||
|
|
||||||
|
echo "Running Revolt in detached mode."
|
||||||
|
docker run \
|
||||||
|
-d \
|
||||||
|
--name revolt \
|
||||||
|
-p 8000:8000 \
|
||||||
|
-p 9000:9000 \
|
||||||
|
$variables \
|
||||||
|
revolt
|
||||||
+192
-10
@@ -1,33 +1,215 @@
|
|||||||
|
use super::get_collection;
|
||||||
|
|
||||||
|
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 serde::{Deserialize, Serialize};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct LastMessage {
|
pub struct LastMessage {
|
||||||
|
// message id
|
||||||
id: String,
|
id: String,
|
||||||
|
// author's id
|
||||||
user_id: String,
|
user_id: String,
|
||||||
|
// truncated content with author's name prepended (for GDM / GUILD)
|
||||||
short_content: String,
|
short_content: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct Channel {
|
pub struct Channel {
|
||||||
#[serde(rename = "_id")]
|
#[serde(rename = "_id")]
|
||||||
pub id: String,
|
pub id: String,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type")]
|
||||||
pub channel_type: u8,
|
pub channel_type: u8,
|
||||||
|
|
||||||
// for Direct Messages
|
// DM: whether the DM is active
|
||||||
pub active: Option<bool>,
|
pub active: Option<bool>,
|
||||||
|
// DM + GDM: last message in channel
|
||||||
// for DMs / GDMs
|
|
||||||
pub last_message: Option<LastMessage>,
|
pub last_message: Option<LastMessage>,
|
||||||
|
// DM + GDM: recipients for channel
|
||||||
pub recipients: Option<Vec<String>>,
|
pub recipients: Option<Vec<String>>,
|
||||||
|
// GDM: owner of group
|
||||||
// for GDMs
|
|
||||||
pub owner: Option<String>,
|
pub owner: Option<String>,
|
||||||
|
// GUILD: channel parent
|
||||||
// for Guilds
|
|
||||||
pub guild: Option<String>,
|
pub guild: Option<String>,
|
||||||
|
// GUILD + GDM: channel name
|
||||||
// for Guilds and Group DMs
|
|
||||||
pub name: Option<String>,
|
pub name: Option<String>,
|
||||||
|
// GUILD + GDM: channel description
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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)));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
||||||
|
{
|
||||||
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
|
let existing = cache.get(&id.to_string());
|
||||||
|
|
||||||
|
if let Some(channel) = existing {
|
||||||
|
return Ok(Some((*channel).clone()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err("Failed to lock cache.".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let col = get_collection("channels");
|
||||||
|
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
if let Ok(channel) = from_bson(Bson::Document(doc)) as Result<Channel, _> {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
cache.put(id.to_string(), channel.clone());
|
||||||
|
|
||||||
|
Ok(Some(channel))
|
||||||
|
} else {
|
||||||
|
Err("Failed to deserialize channel!".to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err("Failed to fetch channel from database.".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
|
||||||
|
let mut missing = vec![];
|
||||||
|
let mut channels = vec![];
|
||||||
|
|
||||||
|
{
|
||||||
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
|
for id in ids {
|
||||||
|
let existing = cache.get(id);
|
||||||
|
|
||||||
|
if let Some(channel) = existing {
|
||||||
|
channels.push((*channel).clone());
|
||||||
|
} else {
|
||||||
|
missing.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err("Failed to lock cache.".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if missing.len() == 0 {
|
||||||
|
return Ok(channels);
|
||||||
|
}
|
||||||
|
|
||||||
|
let col = get_collection("channels");
|
||||||
|
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
||||||
|
for item in result {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
if let Ok(doc) = item {
|
||||||
|
if let Ok(channel) = from_bson(Bson::Document(doc)) as Result<Channel, _> {
|
||||||
|
cache.put(channel.id.clone(), channel.clone());
|
||||||
|
channels.push(channel);
|
||||||
|
} else {
|
||||||
|
return Err("Failed to deserialize channel!".to_string());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err("Failed to fetch channel.".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(channels)
|
||||||
|
} else {
|
||||||
|
Err("Failed to fetch channel from database.".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'r> FromParam<'r> for Channel {
|
||||||
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
|
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||||
|
if let Ok(result) = fetch_channel(param) {
|
||||||
|
if let Some(channel) = result {
|
||||||
|
Ok(channel)
|
||||||
|
} else {
|
||||||
|
Err(param)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err(param)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use crate::notifications::events::Notification;
|
||||||
|
|
||||||
|
pub fn process_event(event: &Notification) {
|
||||||
|
match event {
|
||||||
|
Notification::group_user_join(ev) => {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
if let Some(channel) = cache.peek_mut(&ev.id) {
|
||||||
|
channel.recipients.as_mut().unwrap().push(ev.user.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Notification::group_user_leave(ev) => {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
if let Some(channel) = cache.peek_mut(&ev.id) {
|
||||||
|
let recipients = channel.recipients.as_mut().unwrap();
|
||||||
|
if let Some(pos) = recipients.iter().position(|x| *x == ev.user) {
|
||||||
|
recipients.remove(pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Notification::guild_channel_create(ev) => {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
cache.put(
|
||||||
|
ev.id.clone(),
|
||||||
|
Channel {
|
||||||
|
id: ev.channel.clone(),
|
||||||
|
channel_type: 2,
|
||||||
|
active: None,
|
||||||
|
last_message: None,
|
||||||
|
recipients: None,
|
||||||
|
owner: None,
|
||||||
|
guild: Some(ev.id.clone()),
|
||||||
|
name: Some(ev.name.clone()),
|
||||||
|
description: Some(ev.description.clone()),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Notification::guild_channel_delete(ev) => {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
cache.pop(&ev.channel);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+299
-6
@@ -1,20 +1,28 @@
|
|||||||
use bson::doc;
|
use super::channel::fetch_channels;
|
||||||
use serde::{Deserialize, Serialize};
|
use super::get_collection;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
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};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct MemberRef {
|
pub struct MemberRef {
|
||||||
pub guild: String,
|
pub guild: String,
|
||||||
pub user: String,
|
pub user: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct Member {
|
pub struct Member {
|
||||||
#[serde(rename = "_id")]
|
#[serde(rename = "_id")]
|
||||||
pub id: MemberRef,
|
pub id: MemberRef,
|
||||||
pub nickname: Option<String>,
|
pub nickname: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct Invite {
|
pub struct Invite {
|
||||||
pub code: String,
|
pub code: String,
|
||||||
pub creator: String,
|
pub creator: String,
|
||||||
@@ -27,7 +35,7 @@ pub struct Ban {
|
|||||||
pub reason: String,
|
pub reason: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct Guild {
|
pub struct Guild {
|
||||||
#[serde(rename = "_id")]
|
#[serde(rename = "_id")]
|
||||||
pub id: String,
|
pub id: String,
|
||||||
@@ -36,8 +44,293 @@ 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)]
|
||||||
|
pub struct MemberKey(pub String, pub String);
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
static ref CACHE: Arc<Mutex<LruCache<String, Guild>>> =
|
||||||
|
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||||
|
static ref MEMBER_CACHE: Arc<Mutex<LruCache<MemberKey, Member>>> =
|
||||||
|
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
||||||
|
{
|
||||||
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
|
let existing = cache.get(&id.to_string());
|
||||||
|
|
||||||
|
if let Some(guild) = existing {
|
||||||
|
return Ok(Some((*guild).clone()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err("Failed to lock cache.".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let col = get_collection("guilds");
|
||||||
|
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
if let Ok(guild) = from_bson(Bson::Document(doc)) as Result<Guild, _> {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
cache.put(id.to_string(), guild.clone());
|
||||||
|
|
||||||
|
Ok(Some(guild))
|
||||||
|
} else {
|
||||||
|
Err("Failed to deserialize guild!".to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err("Failed to fetch guild from database.".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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> {
|
||||||
|
{
|
||||||
|
if let Ok(mut cache) = MEMBER_CACHE.lock() {
|
||||||
|
let existing = cache.get(&key);
|
||||||
|
|
||||||
|
if let Some(member) = existing {
|
||||||
|
return Ok(Some((*member).clone()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err("Failed to lock cache.".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let col = get_collection("members");
|
||||||
|
if let Ok(result) = col.find_one(
|
||||||
|
doc! {
|
||||||
|
"_id.guild": &key.0,
|
||||||
|
"_id.user": &key.1,
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
) {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
if let Ok(member) = from_bson(Bson::Document(doc)) as Result<Member, _> {
|
||||||
|
let mut cache = MEMBER_CACHE.lock().unwrap();
|
||||||
|
cache.put(key, member.clone());
|
||||||
|
|
||||||
|
Ok(Some(member))
|
||||||
|
} else {
|
||||||
|
Err("Failed to deserialize member!".to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err("Failed to fetch member from database.".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'r> FromParam<'r> for Guild {
|
||||||
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
|
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||||
|
if let Ok(result) = fetch_guild(param) {
|
||||||
|
if let Some(channel) = result {
|
||||||
|
Ok(channel)
|
||||||
|
} else {
|
||||||
|
Err(param)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err(param)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_invite<U: Into<Option<String>>>(
|
||||||
|
code: &String,
|
||||||
|
user: U,
|
||||||
|
) -> Option<(String, String, Invite)> {
|
||||||
|
let mut doc = doc! {
|
||||||
|
"invites": {
|
||||||
|
"$elemMatch": {
|
||||||
|
"code": &code
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(user_id) = user.into() {
|
||||||
|
doc.insert(
|
||||||
|
"bans",
|
||||||
|
doc! {
|
||||||
|
"$not": {
|
||||||
|
"$elemMatch": {
|
||||||
|
"id": user_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(result) = get_collection("guilds").find_one(
|
||||||
|
doc,
|
||||||
|
mongodb::options::FindOneOptions::builder()
|
||||||
|
.projection(doc! {
|
||||||
|
"_id": 1,
|
||||||
|
"name": 1,
|
||||||
|
"invites.$": 1,
|
||||||
|
})
|
||||||
|
.build(),
|
||||||
|
) {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
let invite = doc
|
||||||
|
.get_array("invites")
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.as_document()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
Some((
|
||||||
|
doc.get_str("_id").unwrap().to_string(),
|
||||||
|
doc.get_str("name").unwrap().to_string(),
|
||||||
|
from_bson(Bson::Document(invite.clone())).unwrap(),
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use crate::notifications::events::Notification;
|
||||||
|
|
||||||
|
pub fn process_event(event: &Notification) {
|
||||||
|
match event {
|
||||||
|
Notification::guild_channel_create(_ev) => {} // ? for later use
|
||||||
|
Notification::guild_channel_delete(_ev) => {} // ? for later use
|
||||||
|
Notification::guild_delete(ev) => {
|
||||||
|
let mut cache = CACHE.lock().unwrap();
|
||||||
|
cache.pop(&ev.id);
|
||||||
|
}
|
||||||
|
Notification::guild_user_join(ev) => {
|
||||||
|
let mut cache = MEMBER_CACHE.lock().unwrap();
|
||||||
|
cache.put(
|
||||||
|
MemberKey(ev.id.clone(), ev.user.clone()),
|
||||||
|
Member {
|
||||||
|
id: MemberRef {
|
||||||
|
guild: ev.id.clone(),
|
||||||
|
user: ev.user.clone(),
|
||||||
|
},
|
||||||
|
nickname: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Notification::guild_user_leave(ev) => {
|
||||||
|
let mut cache = MEMBER_CACHE.lock().unwrap();
|
||||||
|
cache.pop(&MemberKey(ev.id.clone(), ev.user.clone()));
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+25
-5
@@ -1,17 +1,20 @@
|
|||||||
use super::get_collection;
|
use super::get_collection;
|
||||||
use crate::guards::channel::ChannelRef;
|
use crate::database::channel::Channel;
|
||||||
use crate::notifications;
|
use crate::notifications;
|
||||||
use crate::notifications::events::message::Create;
|
use crate::notifications::events::message::Create;
|
||||||
use crate::notifications::events::Notification;
|
use crate::notifications::events::Notification;
|
||||||
use crate::routes::channel::ChannelType;
|
use crate::routes::channel::ChannelType;
|
||||||
|
|
||||||
use bson::{doc, to_bson, UtcDateTime};
|
use mongodb::bson::from_bson;
|
||||||
|
use mongodb::bson::{doc, to_bson, Bson, DateTime};
|
||||||
|
use rocket::http::RawStr;
|
||||||
|
use rocket::request::FromParam;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct PreviousEntry {
|
pub struct PreviousEntry {
|
||||||
pub content: String,
|
pub content: String,
|
||||||
pub time: UtcDateTime,
|
pub time: DateTime,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
@@ -23,7 +26,7 @@ pub struct Message {
|
|||||||
pub author: String,
|
pub author: String,
|
||||||
|
|
||||||
pub content: String,
|
pub content: String,
|
||||||
pub edited: Option<UtcDateTime>,
|
pub edited: Option<DateTime>,
|
||||||
|
|
||||||
pub previous_content: Vec<PreviousEntry>,
|
pub previous_content: Vec<PreviousEntry>,
|
||||||
}
|
}
|
||||||
@@ -32,7 +35,7 @@ pub struct Message {
|
|||||||
// ? pub fn send_message();
|
// ? pub fn send_message();
|
||||||
// ? handle websockets?
|
// ? handle websockets?
|
||||||
impl Message {
|
impl Message {
|
||||||
pub fn send(&self, target: &ChannelRef) -> bool {
|
pub fn send(&self, target: &Channel) -> bool {
|
||||||
if get_collection("messages")
|
if get_collection("messages")
|
||||||
.insert_one(to_bson(&self).unwrap().as_document().unwrap().clone(), None)
|
.insert_one(to_bson(&self).unwrap().as_document().unwrap().clone(), None)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
@@ -87,3 +90,20 @@ impl Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'r> FromParam<'r> for Message {
|
||||||
|
type Error = &'r RawStr;
|
||||||
|
|
||||||
|
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||||
|
let col = get_collection("messages");
|
||||||
|
let result = col
|
||||||
|
.find_one(doc! { "_id": param.to_string() }, None)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
if let Some(message) = result {
|
||||||
|
Ok(from_bson(Bson::Document(message)).expect("Failed to unwrap message."))
|
||||||
|
} else {
|
||||||
|
Err(param)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
use super::super::get_db;
|
||||||
|
use super::scripts::LATEST_REVISION;
|
||||||
|
|
||||||
|
use log::info;
|
||||||
|
use mongodb::bson::doc;
|
||||||
|
use mongodb::options::CreateCollectionOptions;
|
||||||
|
|
||||||
|
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.");
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
use super::super::get_collection;
|
||||||
|
|
||||||
|
use log::info;
|
||||||
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
|
use mongodb::options::FindOptions;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[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
|
||||||
|
}
|
||||||
+7
-5
@@ -1,15 +1,15 @@
|
|||||||
use mongodb::{Client, Collection, Database};
|
use crate::util::variables::MONGO_URI;
|
||||||
use std::env;
|
|
||||||
|
|
||||||
|
use mongodb::sync::{Client, Collection, Database};
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
|
|
||||||
static DBCONN: OnceCell<Client> = OnceCell::new();
|
static DBCONN: OnceCell<Client> = OnceCell::new();
|
||||||
|
|
||||||
pub fn connect() {
|
pub fn connect() {
|
||||||
let client =
|
let client = Client::with_uri_str(&MONGO_URI).expect("Failed to init db connection.");
|
||||||
Client::with_uri_str(&env::var("DB_URI").expect("DB_URI not in environment variables!"))
|
|
||||||
.expect("Failed to init db connection.");
|
|
||||||
|
|
||||||
DBCONN.set(client).unwrap();
|
DBCONN.set(client).unwrap();
|
||||||
|
migrations::run_migrations();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_connection() -> &'static Client {
|
pub fn get_connection() -> &'static Client {
|
||||||
@@ -24,6 +24,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,6 +1,6 @@
|
|||||||
use super::{get_collection, MemberPermissions};
|
use super::{get_collection, MemberPermissions};
|
||||||
|
|
||||||
use bson::doc;
|
use mongodb::bson::doc;
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::FindOptions;
|
||||||
|
|
||||||
pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
||||||
@@ -118,12 +118,10 @@ pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bo
|
|||||||
}
|
}
|
||||||
|
|
||||||
false
|
false
|
||||||
|
} else if result.count() > 0 {
|
||||||
|
true
|
||||||
} else {
|
} else {
|
||||||
if result.count() > 0 {
|
false
|
||||||
true
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
false
|
false
|
||||||
|
|||||||
+40
-29
@@ -1,9 +1,7 @@
|
|||||||
use super::mutual::has_mutual_connection;
|
use super::mutual::has_mutual_connection;
|
||||||
use crate::database::guild::Member;
|
use crate::database::channel::Channel;
|
||||||
use crate::database::user::UserRelationship;
|
use crate::database::guild::{fetch_guild, fetch_member, Guild, Member, MemberKey};
|
||||||
use crate::guards::auth::UserRef;
|
use crate::database::user::{User, UserRelationship};
|
||||||
use crate::guards::channel::ChannelRef;
|
|
||||||
use crate::guards::guild::{get_member, GuildRef};
|
|
||||||
|
|
||||||
use num_enum::TryFromPrimitive;
|
use num_enum::TryFromPrimitive;
|
||||||
|
|
||||||
@@ -78,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<ChannelRef>,
|
pub channel: Option<Channel>,
|
||||||
pub guild: Option<GuildRef>,
|
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,
|
||||||
@@ -103,14 +101,14 @@ impl PermissionCalculator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn channel(self, channel: ChannelRef) -> PermissionCalculator {
|
pub fn channel(self, channel: Channel) -> PermissionCalculator {
|
||||||
PermissionCalculator {
|
PermissionCalculator {
|
||||||
channel: Some(channel),
|
channel: Some(channel),
|
||||||
..self
|
..self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn guild(self, guild: GuildRef) -> PermissionCalculator {
|
pub fn guild(self, guild: Guild) -> PermissionCalculator {
|
||||||
PermissionCalculator {
|
PermissionCalculator {
|
||||||
guild: Some(guild),
|
guild: Some(guild),
|
||||||
..self
|
..self
|
||||||
@@ -125,7 +123,11 @@ impl PermissionCalculator {
|
|||||||
0..=1 => None,
|
0..=1 => None,
|
||||||
2 => {
|
2 => {
|
||||||
if let Some(id) = &channel.guild {
|
if let Some(id) = &channel.guild {
|
||||||
GuildRef::from(id.clone())
|
if let Ok(result) = fetch_guild(id) {
|
||||||
|
result
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -137,7 +139,9 @@ impl PermissionCalculator {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(guild) = &guild {
|
if let Some(guild) = &guild {
|
||||||
self.member = get_member(&guild.id, &self.user.id);
|
if let Ok(result) = fetch_member(MemberKey(guild.id.clone(), self.user.id.clone())) {
|
||||||
|
self.member = result;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.guild = guild;
|
self.guild = guild;
|
||||||
@@ -161,27 +165,34 @@ impl PermissionCalculator {
|
|||||||
match channel.channel_type {
|
match channel.channel_type {
|
||||||
0 => {
|
0 => {
|
||||||
if let Some(arr) = &channel.recipients {
|
if let Some(arr) = &channel.recipients {
|
||||||
let mut other_user = "";
|
let mut other_user = None;
|
||||||
for item in arr {
|
for item in arr {
|
||||||
if item != &self.user.id {
|
if item != &self.user.id {
|
||||||
other_user = item;
|
other_user = Some(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let relationships = self.user.fetch_relationships();
|
if let Some(other) = other_user {
|
||||||
let relationship =
|
let relationship = get_relationship_internal(
|
||||||
get_relationship_internal(&self.user.id, &other_user, &relationships);
|
&self.user.id,
|
||||||
|
&other,
|
||||||
|
&self.user.relations,
|
||||||
|
);
|
||||||
|
|
||||||
if relationship == Relationship::Friend {
|
if relationship == Relationship::Friend {
|
||||||
permissions = 177;
|
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||||
} else if relationship == Relationship::Blocked
|
} else if relationship == Relationship::Blocked
|
||||||
|| relationship == Relationship::BlockedOther
|
|| relationship == Relationship::BlockedOther
|
||||||
{
|
{
|
||||||
permissions = 1;
|
permissions = 1;
|
||||||
} else if has_mutual_connection(&self.user.id, other_user, true) {
|
} else if has_mutual_connection(&self.user.id, other, true) {
|
||||||
permissions = 177;
|
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||||
|
} else {
|
||||||
|
permissions = 1;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
permissions = 1;
|
// ? In this case, it is a "self DM".
|
||||||
|
return 1024 + 128 + 32 + 16 + 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+274
-3
@@ -1,12 +1,23 @@
|
|||||||
use bson::UtcDateTime;
|
use super::channel::fetch_channels;
|
||||||
|
use super::get_collection;
|
||||||
|
use super::guild::serialise_guilds_with_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::Outcome;
|
||||||
|
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 UserEmailVerification {
|
pub struct UserEmailVerification {
|
||||||
pub verified: bool,
|
pub verified: bool,
|
||||||
pub target: Option<String>,
|
pub target: Option<String>,
|
||||||
pub expiry: Option<UtcDateTime>,
|
pub expiry: Option<DateTime>,
|
||||||
pub rate_limit: Option<UtcDateTime>,
|
pub rate_limit: Option<DateTime>,
|
||||||
pub code: Option<String>,
|
pub code: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +34,267 @@ pub struct User {
|
|||||||
pub email: String,
|
pub email: String,
|
||||||
pub username: String,
|
pub username: String,
|
||||||
pub password: String,
|
pub password: String,
|
||||||
|
pub display_name: String,
|
||||||
pub access_token: Option<String>,
|
pub access_token: Option<String>,
|
||||||
pub email_verification: UserEmailVerification,
|
pub email_verification: UserEmailVerification,
|
||||||
pub relations: Option<Vec<UserRelationship>>,
|
pub relations: Option<Vec<UserRelationship>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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,50 +0,0 @@
|
|||||||
use reqwest::blocking::Client;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::env;
|
|
||||||
|
|
||||||
pub fn send_email(target: String, subject: String, body: String, html: String) -> Result<(), ()> {
|
|
||||||
let mut map = HashMap::new();
|
|
||||||
map.insert("target", target.clone());
|
|
||||||
map.insert("subject", subject);
|
|
||||||
map.insert("body", body);
|
|
||||||
map.insert("html", html);
|
|
||||||
|
|
||||||
let client = Client::new();
|
|
||||||
match client
|
|
||||||
.post("http://192.168.0.26:3838/send")
|
|
||||||
.json(&map)
|
|
||||||
.send()
|
|
||||||
{
|
|
||||||
Ok(_) => Ok(()),
|
|
||||||
Err(_) => Err(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn public_uri() -> String {
|
|
||||||
env::var("PUBLIC_URI").expect("PUBLIC_URI not in environment variables!")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn send_verification_email(email: String, code: String) -> bool {
|
|
||||||
let url = format!("{}/api/account/verify/{}", public_uri(), code);
|
|
||||||
send_email(
|
|
||||||
email,
|
|
||||||
"Verify your email!".to_string(),
|
|
||||||
format!("Verify your email here: {}", url),
|
|
||||||
format!("<a href=\"{}\">Click to verify your email!</a>", url),
|
|
||||||
)
|
|
||||||
.is_ok()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn send_welcome_email(email: String, username: String) -> bool {
|
|
||||||
send_email(
|
|
||||||
email,
|
|
||||||
"Welcome to REVOLT!".to_string(),
|
|
||||||
format!("Welcome, {}! You can now use REVOLT.", username.clone()),
|
|
||||||
format!(
|
|
||||||
"<b>Welcome, {}!</b><br/>You can now use REVOLT.<br/><a href=\"{}\">Go to REVOLT</a>",
|
|
||||||
username.clone(),
|
|
||||||
public_uri()
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.is_ok()
|
|
||||||
}
|
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
use bson::{doc, from_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 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,
|
|
||||||
"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(),
|
|
||||||
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,
|
|
||||||
"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(),
|
|
||||||
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::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,91 +0,0 @@
|
|||||||
use bson::{doc, from_bson, Document};
|
|
||||||
use mongodb::options::FindOneOptions;
|
|
||||||
use rocket::http::RawStr;
|
|
||||||
use rocket::request::FromParam;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::database;
|
|
||||||
|
|
||||||
use database::channel::LastMessage;
|
|
||||||
use database::message::Message;
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
|
||||||
pub struct ChannelRef {
|
|
||||||
#[serde(rename = "_id")]
|
|
||||||
pub id: String,
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
pub channel_type: u8,
|
|
||||||
|
|
||||||
pub name: Option<String>,
|
|
||||||
pub last_message: Option<LastMessage>,
|
|
||||||
|
|
||||||
// information required for permission calculations
|
|
||||||
pub recipients: Option<Vec<String>>,
|
|
||||||
pub guild: Option<String>,
|
|
||||||
pub owner: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ChannelRef {
|
|
||||||
pub fn from(id: String) -> Option<ChannelRef> {
|
|
||||||
match database::get_collection("channels").find_one(
|
|
||||||
doc! { "_id": id },
|
|
||||||
FindOneOptions::builder()
|
|
||||||
.projection(doc! {
|
|
||||||
"_id": 1,
|
|
||||||
"type": 1,
|
|
||||||
"name": 1,
|
|
||||||
"last_message": 1,
|
|
||||||
"recipients": 1,
|
|
||||||
"guild": 1,
|
|
||||||
"owner": 1,
|
|
||||||
})
|
|
||||||
.build(),
|
|
||||||
) {
|
|
||||||
Ok(result) => match result {
|
|
||||||
Some(doc) => {
|
|
||||||
Some(from_bson(bson::Bson::Document(doc)).expect("Failed to unwrap channel."))
|
|
||||||
}
|
|
||||||
None => None,
|
|
||||||
},
|
|
||||||
Err(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn fetch_data(&self, projection: Document) -> Option<Document> {
|
|
||||||
database::get_collection("channels")
|
|
||||||
.find_one(
|
|
||||||
doc! { "_id": &self.id },
|
|
||||||
FindOneOptions::builder().projection(projection).build(),
|
|
||||||
)
|
|
||||||
.expect("Failed to fetch channel from database.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'r> FromParam<'r> for ChannelRef {
|
|
||||||
type Error = &'r RawStr;
|
|
||||||
|
|
||||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
|
||||||
if let Some(channel) = ChannelRef::from(param.to_string()) {
|
|
||||||
Ok(channel)
|
|
||||||
} else {
|
|
||||||
Err(param)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'r> FromParam<'r> for Message {
|
|
||||||
type Error = &'r RawStr;
|
|
||||||
|
|
||||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
|
||||||
let col = database::get_collection("messages");
|
|
||||||
let result = col
|
|
||||||
.find_one(doc! { "_id": param.to_string() }, None)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
if let Some(message) = result {
|
|
||||||
Ok(from_bson(bson::Bson::Document(message)).expect("Failed to unwrap message."))
|
|
||||||
} else {
|
|
||||||
Err(param)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,153 +0,0 @@
|
|||||||
use bson::{doc, from_bson, Bson, Document};
|
|
||||||
use mongodb::options::FindOneOptions;
|
|
||||||
use rocket::http::RawStr;
|
|
||||||
use rocket::request::FromParam;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::database;
|
|
||||||
use crate::database::guild::{Ban, Invite, Member};
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
|
||||||
pub struct GuildRef {
|
|
||||||
#[serde(rename = "_id")]
|
|
||||||
pub id: String,
|
|
||||||
pub name: String,
|
|
||||||
pub description: String,
|
|
||||||
pub owner: String,
|
|
||||||
|
|
||||||
pub bans: Vec<Ban>,
|
|
||||||
|
|
||||||
pub default_permissions: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GuildRef {
|
|
||||||
pub fn from(id: String) -> Option<GuildRef> {
|
|
||||||
match database::get_collection("guilds").find_one(
|
|
||||||
doc! { "_id": id },
|
|
||||||
FindOneOptions::builder()
|
|
||||||
.projection(doc! {
|
|
||||||
"name": 1,
|
|
||||||
"description": 1,
|
|
||||||
"owner": 1,
|
|
||||||
"bans": 1,
|
|
||||||
"default_permissions": 1
|
|
||||||
})
|
|
||||||
.build(),
|
|
||||||
) {
|
|
||||||
Ok(result) => match result {
|
|
||||||
Some(doc) => {
|
|
||||||
Some(from_bson(bson::Bson::Document(doc)).expect("Failed to unwrap guild."))
|
|
||||||
}
|
|
||||||
None => None,
|
|
||||||
},
|
|
||||||
Err(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn fetch_data(&self, projection: Document) -> Option<Document> {
|
|
||||||
database::get_collection("guilds")
|
|
||||||
.find_one(
|
|
||||||
doc! { "_id": &self.id },
|
|
||||||
FindOneOptions::builder().projection(projection).build(),
|
|
||||||
)
|
|
||||||
.expect("Failed to fetch guild from database.")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn fetch_data_given(&self, mut filter: Document, projection: Document) -> Option<Document> {
|
|
||||||
filter.insert("_id", self.id.clone());
|
|
||||||
database::get_collection("guilds")
|
|
||||||
.find_one(
|
|
||||||
filter,
|
|
||||||
FindOneOptions::builder().projection(projection).build(),
|
|
||||||
)
|
|
||||||
.expect("Failed to fetch guild from database.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'r> FromParam<'r> for GuildRef {
|
|
||||||
type Error = &'r RawStr;
|
|
||||||
|
|
||||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
|
||||||
if let Some(guild) = GuildRef::from(param.to_string()) {
|
|
||||||
Ok(guild)
|
|
||||||
} else {
|
|
||||||
Err(param)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_member(guild_id: &String, member: &String) -> Option<Member> {
|
|
||||||
if let Ok(result) = database::get_collection("members").find_one(
|
|
||||||
doc! {
|
|
||||||
"_id.guild": &guild_id,
|
|
||||||
"_id.user": &member,
|
|
||||||
},
|
|
||||||
None,
|
|
||||||
) {
|
|
||||||
if let Some(doc) = result {
|
|
||||||
Some(from_bson(Bson::Document(doc)).expect("Failed to unwrap member."))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_invite<U: Into<Option<String>>>(
|
|
||||||
code: &String,
|
|
||||||
user: U,
|
|
||||||
) -> Option<(String, String, Invite)> {
|
|
||||||
let mut doc = doc! {
|
|
||||||
"invites": {
|
|
||||||
"$elemMatch": {
|
|
||||||
"code": &code
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(user_id) = user.into() {
|
|
||||||
doc.insert(
|
|
||||||
"bans",
|
|
||||||
doc! {
|
|
||||||
"$not": {
|
|
||||||
"$elemMatch": {
|
|
||||||
"id": user_id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(result) = database::get_collection("guilds").find_one(
|
|
||||||
doc,
|
|
||||||
FindOneOptions::builder()
|
|
||||||
.projection(doc! {
|
|
||||||
"_id": 1,
|
|
||||||
"name": 1,
|
|
||||||
"invites.$": 1,
|
|
||||||
})
|
|
||||||
.build(),
|
|
||||||
) {
|
|
||||||
if let Some(doc) = result {
|
|
||||||
let invite = doc
|
|
||||||
.get_array("invites")
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.next()
|
|
||||||
.unwrap()
|
|
||||||
.as_document()
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
Some((
|
|
||||||
doc.get_str("_id").unwrap().to_string(),
|
|
||||||
doc.get_str("name").unwrap().to_string(),
|
|
||||||
from_bson(Bson::Document(invite.clone())).unwrap(),
|
|
||||||
))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
pub mod auth;
|
|
||||||
pub mod channel;
|
|
||||||
pub mod guild;
|
|
||||||
+12
-3
@@ -1,24 +1,33 @@
|
|||||||
#![feature(proc_macro_hygiene, decl_macro)]
|
#![feature(proc_macro_hygiene, decl_macro)]
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate rocket;
|
extern crate rocket;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate rocket_contrib;
|
extern crate rocket_contrib;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate bitfield;
|
extern crate bitfield;
|
||||||
|
#[macro_use]
|
||||||
|
extern crate lazy_static;
|
||||||
|
|
||||||
pub mod database;
|
pub mod database;
|
||||||
pub mod email;
|
|
||||||
pub mod guards;
|
|
||||||
pub mod notifications;
|
pub mod notifications;
|
||||||
pub mod routes;
|
pub mod routes;
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
|
||||||
use dotenv;
|
|
||||||
use rocket_cors::AllowedOrigins;
|
use rocket_cors::AllowedOrigins;
|
||||||
use std::thread;
|
use std::thread;
|
||||||
|
use log::info;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
dotenv::dotenv().ok();
|
dotenv::dotenv().ok();
|
||||||
|
env_logger::init_from_env(
|
||||||
|
env_logger::Env::default()
|
||||||
|
.filter_or("RUST_LOG", "info")
|
||||||
|
);
|
||||||
|
|
||||||
|
info!("Starting REVOLT server.");
|
||||||
|
|
||||||
|
util::variables::preflight_checks();
|
||||||
database::connect();
|
database::connect();
|
||||||
notifications::start_worker();
|
notifications::start_worker();
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ pub struct Create {
|
|||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct Edit {
|
pub struct Edit {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
|
pub channel: String,
|
||||||
|
pub author: String,
|
||||||
pub content: String,
|
pub content: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,4 +38,10 @@ impl Notification {
|
|||||||
unreachable!()
|
unreachable!()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn push_to_cache(&self) {
|
||||||
|
crate::database::channel::process_event(&self);
|
||||||
|
crate::database::guild::process_event(&self);
|
||||||
|
crate::database::user::process_event(&self);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,5 +3,6 @@ use serde::{Deserialize, Serialize};
|
|||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[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,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::guards::channel::ChannelRef;
|
use crate::database::channel::Channel;
|
||||||
|
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
use std::sync::mpsc::{channel, Sender};
|
use std::sync::mpsc::{channel, Sender};
|
||||||
@@ -17,6 +17,8 @@ pub fn send_message<U: Into<Option<Vec<String>>>, G: Into<Option<String>>>(
|
|||||||
let users = users.into();
|
let users = users.into();
|
||||||
let guild = guild.into();
|
let guild = guild.into();
|
||||||
|
|
||||||
|
data.push_to_cache();
|
||||||
|
|
||||||
if pubsub::send_message(users.clone(), guild.clone(), data.clone()) {
|
if pubsub::send_message(users.clone(), guild.clone(), data.clone()) {
|
||||||
state::send_message(users, guild, data.serialize());
|
state::send_message(users, guild, data.serialize());
|
||||||
|
|
||||||
@@ -65,7 +67,7 @@ pub fn send_message_threaded<U: Into<Option<Vec<String>>>, G: Into<Option<String
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn send_message_given_channel(data: events::Notification, channel: &ChannelRef) {
|
pub fn send_message_given_channel(data: events::Notification, channel: &Channel) {
|
||||||
match channel.channel_type {
|
match channel.channel_type {
|
||||||
0..=1 => send_message_threaded(channel.recipients.clone(), None, data),
|
0..=1 => send_message_threaded(channel.recipients.clone(), None, data),
|
||||||
2 => send_message_threaded(None, channel.guild.clone(), data),
|
2 => send_message_threaded(None, channel.guild.clone(), data),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use super::events::Notification;
|
use super::events::Notification;
|
||||||
use crate::database::get_collection;
|
use crate::database::get_collection;
|
||||||
|
|
||||||
use bson::{doc, from_bson, to_bson, Bson};
|
use mongodb::bson::{doc, from_bson, to_bson, Bson};
|
||||||
use mongodb::options::{CursorType, FindOneOptions, FindOptions};
|
use mongodb::options::{CursorType, FindOneOptions, FindOptions};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use crate::database;
|
use crate::database;
|
||||||
use crate::util::vec_to_set;
|
use crate::util::vec_to_set;
|
||||||
|
|
||||||
use bson::doc;
|
|
||||||
use hashbrown::{HashMap, HashSet};
|
use hashbrown::{HashMap, HashSet};
|
||||||
|
use mongodb::bson::doc;
|
||||||
use mongodb::options::FindOneOptions;
|
use mongodb::options::FindOneOptions;
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
use std::sync::RwLock;
|
use std::sync::RwLock;
|
||||||
|
|||||||
+26
-10
@@ -1,7 +1,7 @@
|
|||||||
use super::state::{self, StateResult};
|
use super::state::{self, StateResult};
|
||||||
|
use crate::util::variables::WS_HOST;
|
||||||
|
|
||||||
use serde_json::{from_str, json, Value};
|
use serde_json::{from_str, json, Value};
|
||||||
use std::env;
|
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
use ws::{listen, CloseCode, Error, Handler, Handshake, Message, Result, Sender};
|
use ws::{listen, CloseCode, Error, Handler, Handshake, Message, Result, Sender};
|
||||||
|
|
||||||
@@ -36,14 +36,33 @@ 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(),
|
||||||
)
|
)?;
|
||||||
|
|
||||||
|
if let Ok(payload) = user.create_payload() {
|
||||||
|
self.sender.send(
|
||||||
|
json!({
|
||||||
|
"type": "ready",
|
||||||
|
"data": payload
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// ! TODO: FIXME: ALL THE NOTIFICATIONS CODE NEEDS TO BE
|
||||||
|
// ! RESTRUCTURED, IT IS UTTER GARBAGE. :)))))
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
StateResult::DatabaseError => self.sender.send(
|
StateResult::DatabaseError => self.sender.send(
|
||||||
json!({
|
json!({
|
||||||
@@ -107,13 +126,10 @@ impl Handler for Server {
|
|||||||
pub fn launch_server() {
|
pub fn launch_server() {
|
||||||
state::init();
|
state::init();
|
||||||
|
|
||||||
listen(
|
listen(WS_HOST.to_string(), |sender| Server {
|
||||||
env::var("WS_HOST").unwrap_or("0.0.0.0:9999".to_string()),
|
sender,
|
||||||
|sender| Server {
|
user_id: None,
|
||||||
sender,
|
id: Ulid::new().to_string(),
|
||||||
user_id: None,
|
})
|
||||||
id: Ulid::new().to_string(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|||||||
+97
-35
@@ -1,12 +1,13 @@
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::database;
|
use crate::database;
|
||||||
use crate::email;
|
use crate::util::{captcha, email, gen_token};
|
||||||
use crate::util::gen_token;
|
use crate::util::variables::{DISABLE_REGISTRATION, USE_EMAIL};
|
||||||
|
|
||||||
use bcrypt::{hash, verify};
|
use bcrypt::{hash, verify};
|
||||||
use bson::{doc, from_bson, Bson::UtcDatetime};
|
|
||||||
use chrono::prelude::*;
|
use chrono::prelude::*;
|
||||||
use database::user::User;
|
use database::user::User;
|
||||||
|
use log::error;
|
||||||
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
use rocket_contrib::json::Json;
|
use rocket_contrib::json::Json;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
@@ -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,14 @@ 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 *DISABLE_REGISTRATION {
|
||||||
|
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 {
|
||||||
@@ -53,34 +63,56 @@ pub fn create(info: Json<Create>) -> Response {
|
|||||||
return Response::Conflict(json!({ "error": "Email already in use!" }));
|
return Response::Conflict(json!({ "error": "Email already in use!" }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(_) = col
|
||||||
|
.find_one(doc! { "username": info.username.clone() }, None)
|
||||||
|
.expect("Failed user lookup")
|
||||||
|
{
|
||||||
|
return Response::Conflict(json!({ "error": "Username already in use!" }));
|
||||||
|
}
|
||||||
|
|
||||||
if let Ok(hashed) = hash(info.password.clone(), 10) {
|
if let Ok(hashed) = hash(info.password.clone(), 10) {
|
||||||
let access_token = gen_token(92);
|
let access_token = gen_token(92);
|
||||||
let code = gen_token(48);
|
let code = gen_token(48);
|
||||||
|
|
||||||
|
let email_verification = match *USE_EMAIL {
|
||||||
|
true => doc! {
|
||||||
|
"verified": false,
|
||||||
|
"target": info.email.clone(),
|
||||||
|
"expiry": Bson::DateTime(Utc::now() + chrono::Duration::days(1)),
|
||||||
|
"rate_limit": Bson::DateTime(Utc::now() + chrono::Duration::minutes(1)),
|
||||||
|
"code": code.clone(),
|
||||||
|
},
|
||||||
|
false => doc! {
|
||||||
|
"verified": true
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let id = Ulid::new().to_string();
|
||||||
match col.insert_one(
|
match col.insert_one(
|
||||||
doc! {
|
doc! {
|
||||||
"_id": Ulid::new().to_string(),
|
"_id": &id,
|
||||||
"email": info.email.clone(),
|
"email": info.email.clone(),
|
||||||
"username": info.username.clone(),
|
"username": info.username.clone(),
|
||||||
|
"display_name": info.username.clone(),
|
||||||
"password": hashed,
|
"password": hashed,
|
||||||
"access_token": access_token,
|
"access_token": &access_token,
|
||||||
"email_verification": {
|
"email_verification": email_verification
|
||||||
"verified": false,
|
|
||||||
"target": info.email.clone(),
|
|
||||||
"expiry": UtcDatetime(Utc::now() + chrono::Duration::days(1)),
|
|
||||||
"rate_limit": UtcDatetime(Utc::now() + chrono::Duration::minutes(1)),
|
|
||||||
"code": code.clone(),
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
) {
|
) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
let sent = email::send_verification_email(info.email.clone(), code);
|
if *USE_EMAIL {
|
||||||
|
let sent = email::send_verification_email(info.email.clone(), code);
|
||||||
|
|
||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
"success": true,
|
"email_sent": sent,
|
||||||
"email_sent": sent,
|
}))
|
||||||
}))
|
} else {
|
||||||
|
Response::Success(json!({
|
||||||
|
"id": id,
|
||||||
|
"access_token": access_token
|
||||||
|
}))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
Response::InternalServerError(json!({ "error": "Failed to create account." }))
|
Response::InternalServerError(json!({ "error": "Failed to create account." }))
|
||||||
@@ -103,7 +135,7 @@ pub fn verify_email(code: String) -> Response {
|
|||||||
.find_one(doc! { "email_verification.code": code.clone() }, None)
|
.find_one(doc! { "email_verification.code": code.clone() }, None)
|
||||||
.expect("Failed user lookup")
|
.expect("Failed user lookup")
|
||||||
{
|
{
|
||||||
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
|
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||||
let ev = user.email_verification;
|
let ev = user.email_verification;
|
||||||
|
|
||||||
if Utc::now() > *ev.expiry.unwrap() {
|
if Utc::now() > *ev.expiry.unwrap() {
|
||||||
@@ -131,11 +163,13 @@ pub fn verify_email(code: String) -> Response {
|
|||||||
)
|
)
|
||||||
.expect("Failed to update user!");
|
.expect("Failed to update user!");
|
||||||
|
|
||||||
email::send_welcome_email(target.to_string(), user.username);
|
if *USE_EMAIL {
|
||||||
|
if let Err(err) = email::send_welcome_email(target.to_string(), user.username) {
|
||||||
|
error!("Failed to send welcome email! {}", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Response::Redirect(
|
Response::Redirect(super::Redirect::to("https://app.revolt.chat"))
|
||||||
super::Redirect::to("https://example.com"), // ! FIXME; redirect to landing page
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Response::BadRequest(json!({ "error": "Invalid code." }))
|
Response::BadRequest(json!({ "error": "Invalid code." }))
|
||||||
@@ -145,6 +179,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
|
||||||
@@ -153,6 +188,10 @@ 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
|
||||||
@@ -162,7 +201,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
)
|
)
|
||||||
.expect("Failed user lookup.")
|
.expect("Failed user lookup.")
|
||||||
{
|
{
|
||||||
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
|
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||||
let ev = user.email_verification;
|
let ev = user.email_verification;
|
||||||
|
|
||||||
let expiry = ev.expiry.unwrap();
|
let expiry = ev.expiry.unwrap();
|
||||||
@@ -173,7 +212,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
json!({ "error": "You are being rate limited, please try again in a while." }),
|
json!({ "error": "You are being rate limited, please try again in a while." }),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
let mut new_expiry = UtcDatetime(Utc::now() + chrono::Duration::days(1));
|
let mut new_expiry = Bson::DateTime(Utc::now() + chrono::Duration::days(1));
|
||||||
if info.email.clone() != user.email {
|
if info.email.clone() != user.email {
|
||||||
if Utc::now() > *expiry {
|
if Utc::now() > *expiry {
|
||||||
return Response::Gone(
|
return Response::Gone(
|
||||||
@@ -181,7 +220,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
new_expiry = UtcDatetime(*expiry);
|
new_expiry = Bson::DateTime(*expiry);
|
||||||
}
|
}
|
||||||
|
|
||||||
let code = gen_token(48);
|
let code = gen_token(48);
|
||||||
@@ -191,23 +230,20 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
|||||||
"$set": {
|
"$set": {
|
||||||
"email_verification.code": code.clone(),
|
"email_verification.code": code.clone(),
|
||||||
"email_verification.expiry": new_expiry,
|
"email_verification.expiry": new_expiry,
|
||||||
"email_verification.rate_limit": UtcDatetime(Utc::now() + chrono::Duration::minutes(1)),
|
"email_verification.rate_limit": Bson::DateTime(Utc::now() + chrono::Duration::minutes(1)),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
).expect("Failed to update user!");
|
).expect("Failed to update user!");
|
||||||
|
|
||||||
match email::send_verification_email(info.email.to_string(), code) {
|
if let Err(err) = email::send_verification_email(info.email.clone(), code) {
|
||||||
true => Response::Result(super::Status::Ok),
|
return Response::InternalServerError(json!({ "error": err }));
|
||||||
false => Response::InternalServerError(
|
|
||||||
json!({ "success": false, "error": "Failed to send email! Likely an issue with the backend API." }),
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Response::NotFound(
|
Response::NotFound(json!({ "error": "Email not found or pending verification!" }))
|
||||||
json!({ "success": false, "error": "Email not found or pending verification!" }),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -215,6 +251,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
|
||||||
@@ -223,13 +260,17 @@ 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
|
||||||
.find_one(doc! { "email": info.email.clone() }, None)
|
.find_one(doc! { "email": info.email.clone() }, None)
|
||||||
.expect("Failed user lookup")
|
.expect("Failed user lookup")
|
||||||
{
|
{
|
||||||
let user: User = from_bson(bson::Bson::Document(u)).expect("Failed to unwrap user.");
|
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||||
|
|
||||||
match verify(info.password.clone(), &user.password)
|
match verify(info.password.clone(), &user.password)
|
||||||
.expect("Failed to check hash of password.")
|
.expect("Failed to check hash of password.")
|
||||||
@@ -291,3 +332,24 @@ pub fn token(info: Json<Token>) -> Response {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[options("/create")]
|
||||||
|
pub fn create_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/verify/<_code>")]
|
||||||
|
pub fn verify_email_preflight(_code: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/resend")]
|
||||||
|
pub fn resend_email_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/login")]
|
||||||
|
pub fn login_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/token")]
|
||||||
|
pub fn token_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
|||||||
+94
-78
@@ -1,20 +1,19 @@
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::database::{
|
use crate::database::{
|
||||||
self, get_relationship, get_relationship_internal, message::Message, Permission,
|
self, channel::Channel, get_relationship, get_relationship_internal, message::Message,
|
||||||
PermissionCalculator, Relationship,
|
user::User, Permission, PermissionCalculator, Relationship,
|
||||||
};
|
};
|
||||||
use crate::guards::auth::UserRef;
|
|
||||||
use crate::guards::channel::ChannelRef;
|
|
||||||
use crate::notifications::{
|
use crate::notifications::{
|
||||||
self,
|
self,
|
||||||
events::{groups::*, guilds::ChannelDelete, message::*, Notification},
|
events::{groups::*, guilds::ChannelDelete, message::*, Notification},
|
||||||
};
|
};
|
||||||
use crate::util::vec_to_set;
|
use crate::util::vec_to_set;
|
||||||
|
|
||||||
use bson::{doc, from_bson, Bson, Bson::UtcDatetime};
|
|
||||||
use chrono::prelude::*;
|
use chrono::prelude::*;
|
||||||
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::FindOptions;
|
||||||
use num_enum::TryFromPrimitive;
|
use num_enum::TryFromPrimitive;
|
||||||
|
use rocket::request::Form;
|
||||||
use rocket_contrib::json::Json;
|
use rocket_contrib::json::Json;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
@@ -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: ChannelRef) -> 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": info.get_str("name").unwrap(),
|
|
||||||
"owner": info.get_str("owner").unwrap(),
|
|
||||||
"description": info.get_str("description").unwrap_or(""),
|
|
||||||
})))
|
|
||||||
} 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": info.get_str("name").unwrap(),
|
|
||||||
"description": info.get_str("description").unwrap_or(""),
|
|
||||||
})))
|
|
||||||
} 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: ChannelRef, 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: ChannelRef, member: UserRef) -> Option<
|
|||||||
|
|
||||||
/// [groups] remove user from channel
|
/// [groups] remove user from channel
|
||||||
#[delete("/<target>/recipients/<member>")]
|
#[delete("/<target>/recipients/<member>")]
|
||||||
pub fn remove_member(user: UserRef, target: ChannelRef, member: UserRef) -> Option<Response> {
|
pub fn remove_member(user: 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: ChannelRef, member: UserRef) -> Opti
|
|||||||
/// or leave group DM
|
/// or leave group DM
|
||||||
/// or close DM conversation
|
/// or close DM conversation
|
||||||
#[delete("/<target>")]
|
#[delete("/<target>")]
|
||||||
pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
pub fn delete(user: 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: ChannelRef) -> Option<Response> {
|
|||||||
"$pull": {
|
"$pull": {
|
||||||
"invites": {
|
"invites": {
|
||||||
"channel": &target.id
|
"channel": &target.id
|
||||||
}
|
},
|
||||||
|
"channels": &target.id
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
@@ -478,22 +433,60 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, FromForm)]
|
||||||
|
pub struct MessageFetchOptions {
|
||||||
|
limit: Option<i64>,
|
||||||
|
before: Option<String>,
|
||||||
|
after: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
/// fetch channel messages
|
/// fetch channel messages
|
||||||
#[get("/<target>/messages")]
|
#[get("/<target>/messages?<options..>")]
|
||||||
pub fn messages(user: UserRef, target: ChannelRef) -> Option<Response> {
|
pub fn messages(
|
||||||
|
user: User,
|
||||||
|
target: Channel,
|
||||||
|
options: Form<MessageFetchOptions>,
|
||||||
|
) -> Option<Response> {
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_read_messages() {
|
if !permissions.get_read_messages() {
|
||||||
return Some(Response::LackingPermission(Permission::ReadMessages));
|
return Some(Response::LackingPermission(Permission::ReadMessages));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ! FIXME: update wiki to reflect changes
|
||||||
|
let mut query = doc! { "channel": target.id };
|
||||||
|
|
||||||
|
if let Some(before) = &options.before {
|
||||||
|
query.insert("_id", doc! { "$lt": before });
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(after) = &options.after {
|
||||||
|
query.insert("_id", doc! { "$gt": after });
|
||||||
|
}
|
||||||
|
|
||||||
|
let limit = if let Some(limit) = options.limit {
|
||||||
|
limit.min(100).max(0)
|
||||||
|
} else {
|
||||||
|
50
|
||||||
|
};
|
||||||
|
|
||||||
let col = database::get_collection("messages");
|
let col = database::get_collection("messages");
|
||||||
let result = col.find(doc! { "channel": target.id }, None).unwrap();
|
let result = col
|
||||||
|
.find(
|
||||||
|
query,
|
||||||
|
FindOptions::builder()
|
||||||
|
.limit(limit)
|
||||||
|
.sort(doc! {
|
||||||
|
"_id": -1
|
||||||
|
})
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let mut messages = Vec::new();
|
let mut messages = Vec::new();
|
||||||
for item in result {
|
for item in result {
|
||||||
let message: Message =
|
let message: Message =
|
||||||
from_bson(bson::Bson::Document(item.unwrap())).expect("Failed to unwrap message.");
|
from_bson(Bson::Document(item.unwrap())).expect("Failed to unwrap message.");
|
||||||
messages.push(json!({
|
messages.push(json!({
|
||||||
"id": message.id,
|
"id": message.id,
|
||||||
"author": message.author,
|
"author": message.author,
|
||||||
@@ -513,11 +506,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: User, target: Channel, message: Json<SendMessage>) -> Option<Response> {
|
||||||
user: UserRef,
|
|
||||||
target: ChannelRef,
|
|
||||||
message: Json<SendMessage>,
|
|
||||||
) -> Option<Response> {
|
|
||||||
let permissions = with_permissions!(user, target);
|
let permissions = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_send_messages() {
|
if !permissions.get_send_messages() {
|
||||||
@@ -531,6 +520,12 @@ pub fn send_message(
|
|||||||
let content: String = message.content.chars().take(2000).collect();
|
let content: String = message.content.chars().take(2000).collect();
|
||||||
let nonce: String = message.nonce.chars().take(32).collect();
|
let nonce: String = message.nonce.chars().take(32).collect();
|
||||||
|
|
||||||
|
if content.len() == 0 {
|
||||||
|
return Some(Response::NotAcceptable(
|
||||||
|
json!({ "error": "No message content!" }),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
let col = database::get_collection("messages");
|
let col = database::get_collection("messages");
|
||||||
if col
|
if col
|
||||||
.find_one(doc! { "nonce": nonce.clone() }, None)
|
.find_one(doc! { "nonce": nonce.clone() }, None)
|
||||||
@@ -564,7 +559,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: ChannelRef, 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() {
|
||||||
@@ -597,8 +592,8 @@ 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: ChannelRef,
|
target: Channel,
|
||||||
message: Message,
|
message: Message,
|
||||||
edit: Json<EditMessage>,
|
edit: Json<EditMessage>,
|
||||||
) -> Option<Response> {
|
) -> Option<Response> {
|
||||||
@@ -622,8 +617,8 @@ pub fn edit_message(
|
|||||||
doc! { "_id": message.id.clone() },
|
doc! { "_id": message.id.clone() },
|
||||||
doc! {
|
doc! {
|
||||||
"$set": {
|
"$set": {
|
||||||
"content": edit.content.clone(),
|
"content": &edit.content,
|
||||||
"edited": UtcDatetime(edited)
|
"edited": Bson::DateTime(edited)
|
||||||
},
|
},
|
||||||
"$push": {
|
"$push": {
|
||||||
"previous_content": {
|
"previous_content": {
|
||||||
@@ -638,7 +633,9 @@ pub fn edit_message(
|
|||||||
notifications::send_message_given_channel(
|
notifications::send_message_given_channel(
|
||||||
Notification::message_edit(Edit {
|
Notification::message_edit(Edit {
|
||||||
id: message.id.clone(),
|
id: message.id.clone(),
|
||||||
content: message.content,
|
channel: target.id.clone(),
|
||||||
|
author: message.author.clone(),
|
||||||
|
content: edit.content.clone(),
|
||||||
}),
|
}),
|
||||||
&target,
|
&target,
|
||||||
);
|
);
|
||||||
@@ -653,13 +650,11 @@ pub fn edit_message(
|
|||||||
|
|
||||||
/// delete a message
|
/// delete a message
|
||||||
#[delete("/<target>/messages/<message>")]
|
#[delete("/<target>/messages/<message>")]
|
||||||
pub fn delete_message(user: UserRef, target: ChannelRef, message: Message) -> Option<Response> {
|
pub fn delete_message(user: 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() && message.author != user.id {
|
||||||
if message.author != user.id {
|
return Some(Response::LackingPermission(Permission::ManageMessages));
|
||||||
return Some(Response::LackingPermission(Permission::ManageMessages));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let col = database::get_collection("messages");
|
let col = database::get_collection("messages");
|
||||||
@@ -680,3 +675,24 @@ pub fn delete_message(user: UserRef, target: ChannelRef, message: Message) -> Op
|
|||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[options("/create")]
|
||||||
|
pub fn create_group_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>")]
|
||||||
|
pub fn channel_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/recipients/<_member>")]
|
||||||
|
pub fn member_preflight(_target: String, _member: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/messages")]
|
||||||
|
pub fn messages_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/messages/<_message>")]
|
||||||
|
pub fn message_preflight(_target: String, _message: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
|||||||
+209
-210
@@ -1,22 +1,24 @@
|
|||||||
use super::channel::ChannelType;
|
use super::channel::ChannelType;
|
||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::database::{self, channel::Channel, Permission, PermissionCalculator};
|
use crate::database::guild::{fetch_member as get_member, get_invite, Guild, MemberKey};
|
||||||
use crate::guards::auth::UserRef;
|
use crate::database::{
|
||||||
use crate::guards::channel::ChannelRef;
|
self, channel::fetch_channel, channel::Channel, guild::serialise_guilds_with_channels,
|
||||||
use crate::guards::guild::{get_invite, get_member, GuildRef};
|
user::User, Permission, PermissionCalculator,
|
||||||
|
};
|
||||||
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 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())
|
||||||
@@ -34,54 +36,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." }))
|
||||||
}
|
}
|
||||||
@@ -92,50 +50,21 @@ pub fn my_guilds(user: UserRef) -> Response {
|
|||||||
|
|
||||||
/// fetch a guild
|
/// fetch a guild
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub fn guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
pub fn guild(user: 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(
|
||||||
"guild": &target.id,
|
json!({ "error": "Failed to fetch channels!" }),
|
||||||
},
|
))
|
||||||
None,
|
|
||||||
) {
|
|
||||||
Ok(results) => {
|
|
||||||
let mut channels = vec![];
|
|
||||||
for item in results {
|
|
||||||
if let Ok(entry) = item {
|
|
||||||
if let Ok(channel) =
|
|
||||||
from_bson(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: GuildRef) -> 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 {
|
||||||
@@ -175,27 +104,41 @@ pub fn remove_guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
|||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
if database::get_collection("guilds")
|
if database::get_collection("members")
|
||||||
.delete_one(
|
.delete_many(
|
||||||
doc! {
|
doc! {
|
||||||
"_id": &target.id
|
"_id.guild": &target.id,
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
notifications::send_message_threaded(
|
if database::get_collection("guilds")
|
||||||
None,
|
.delete_one(
|
||||||
target.id.clone(),
|
doc! {
|
||||||
Notification::guild_delete(Delete {
|
"_id": &target.id
|
||||||
id: target.id.clone(),
|
},
|
||||||
}),
|
None,
|
||||||
);
|
)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
notifications::send_message_threaded(
|
||||||
|
None,
|
||||||
|
target.id.clone(),
|
||||||
|
Notification::guild_delete(Delete {
|
||||||
|
id: target.id.clone(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
|
} else {
|
||||||
|
Some(Response::InternalServerError(
|
||||||
|
json!({ "error": "Failed to delete guild." }),
|
||||||
|
))
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
json!({ "error": "Failed to delete guild." }),
|
json!({ "error": "Failed to delete guild members." }),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -213,33 +156,31 @@ pub fn remove_guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
|||||||
json!({ "error": "Could not fetch channels." }),
|
json!({ "error": "Could not fetch channels." }),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
} else {
|
} else if database::get_collection("members")
|
||||||
if database::get_collection("members")
|
.delete_one(
|
||||||
.delete_one(
|
doc! {
|
||||||
doc! {
|
"_id.guild": &target.id,
|
||||||
"_id.guild": &target.id,
|
"_id.user": &user.id,
|
||||||
"_id.user": &user.id,
|
},
|
||||||
},
|
None,
|
||||||
None,
|
)
|
||||||
)
|
.is_ok()
|
||||||
.is_ok()
|
{
|
||||||
{
|
notifications::send_message_threaded(
|
||||||
notifications::send_message_threaded(
|
None,
|
||||||
None,
|
target.id.clone(),
|
||||||
target.id.clone(),
|
Notification::guild_user_leave(UserLeave {
|
||||||
Notification::guild_user_leave(UserLeave {
|
id: target.id.clone(),
|
||||||
id: target.id.clone(),
|
user: user.id.clone(),
|
||||||
user: user.id.clone(),
|
banned: false,
|
||||||
banned: false,
|
}),
|
||||||
}),
|
);
|
||||||
);
|
|
||||||
|
|
||||||
Some(Response::Result(super::Status::Ok))
|
Some(Response::Result(super::Status::Ok))
|
||||||
} else {
|
} else {
|
||||||
Some(Response::InternalServerError(
|
Some(Response::InternalServerError(
|
||||||
json!({ "error": "Failed to remove you from the guild." }),
|
json!({ "error": "Failed to remove you from the guild." }),
|
||||||
))
|
))
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,11 +193,7 @@ pub struct CreateChannel {
|
|||||||
|
|
||||||
/// create a new channel
|
/// create a new channel
|
||||||
#[post("/<target>/channels", data = "<info>")]
|
#[post("/<target>/channels", data = "<info>")]
|
||||||
pub fn create_channel(
|
pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> Option<Response> {
|
||||||
user: UserRef,
|
|
||||||
target: GuildRef,
|
|
||||||
info: Json<CreateChannel>,
|
|
||||||
) -> Option<Response> {
|
|
||||||
let (permissions, _) = with_permissions!(user, target);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
|
|
||||||
if !permissions.get_manage_channels() {
|
if !permissions.get_manage_channels() {
|
||||||
@@ -297,20 +234,39 @@ pub fn create_channel(
|
|||||||
)
|
)
|
||||||
.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." }),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
@@ -329,9 +285,9 @@ 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: GuildRef,
|
target: Guild,
|
||||||
channel: ChannelRef,
|
channel: Channel,
|
||||||
_options: Json<InviteOptions>,
|
_options: Json<InviteOptions>,
|
||||||
) -> Option<Response> {
|
) -> Option<Response> {
|
||||||
let (permissions, _) = with_permissions!(user, target);
|
let (permissions, _) = with_permissions!(user, target);
|
||||||
@@ -367,14 +323,12 @@ pub fn create_invite(
|
|||||||
|
|
||||||
/// remove an invite
|
/// remove an invite
|
||||||
#[delete("/<target>/invites/<code>")]
|
#[delete("/<target>/invites/<code>")]
|
||||||
pub fn remove_invite(user: UserRef, target: GuildRef, code: String) -> Option<Response> {
|
pub fn remove_invite(user: 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) {
|
||||||
if invite.creator != user.id {
|
if invite.creator != user.id && !permissions.get_manage_server() {
|
||||||
if !permissions.get_manage_server() {
|
return Some(Response::LackingPermission(Permission::ManageServer));
|
||||||
return Some(Response::LackingPermission(Permission::ManageServer));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if database::get_collection("guilds")
|
if database::get_collection("guilds")
|
||||||
@@ -408,41 +362,38 @@ pub fn remove_invite(user: UserRef, target: GuildRef, code: String) -> Option<Re
|
|||||||
|
|
||||||
/// fetch all guild invites
|
/// fetch all guild invites
|
||||||
#[get("/<target>/invites")]
|
#[get("/<target>/invites")]
|
||||||
pub fn fetch_invites(user: UserRef, target: GuildRef) -> Option<Response> {
|
pub fn fetch_invites(user: 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() {
|
||||||
return Some(Response::LackingPermission(Permission::ManageServer));
|
return Some(Response::LackingPermission(Permission::ManageServer));
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(doc) = target.fetch_data(doc! {
|
Some(Response::Success(json!(target.invites)))
|
||||||
"invites": 1,
|
|
||||||
}) {
|
|
||||||
Some(Response::Success(json!(doc.get_array("invites").unwrap())))
|
|
||||||
} else {
|
|
||||||
Some(Response::InternalServerError(
|
|
||||||
json!({ "error": "Failed to fetch invites." }),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// view an invite before joining
|
/// view an invite before joining
|
||||||
#[get("/join/<code>", rank = 1)]
|
#[get("/join/<code>", rank = 1)]
|
||||||
pub fn fetch_invite(user: UserRef, code: String) -> Response {
|
pub fn fetch_invite(user: 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) {
|
||||||
if let Some(channel) = ChannelRef::from(invite.channel) {
|
match fetch_channel(&invite.channel) {
|
||||||
Response::Success(json!({
|
Ok(result) => {
|
||||||
"guild": {
|
if let Some(channel) = result {
|
||||||
"id": guild_id,
|
Response::Success(json!({
|
||||||
"name": name,
|
"guild": {
|
||||||
},
|
"id": guild_id,
|
||||||
"channel": {
|
"name": name,
|
||||||
"id": channel.id,
|
},
|
||||||
"name": channel.name,
|
"channel": {
|
||||||
|
"id": channel.id,
|
||||||
|
"name": channel.name,
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
} else {
|
||||||
|
Response::NotFound(json!({ "error": "Channel does not exist." }))
|
||||||
}
|
}
|
||||||
}))
|
}
|
||||||
} else {
|
Err(err) => Response::InternalServerError(json!({ "error": err })),
|
||||||
Response::BadRequest(json!({ "error": "Failed to fetch channel." }))
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Response::NotFound(json!({ "error": "Failed to fetch invite or code is invalid." }))
|
Response::NotFound(json!({ "error": "Failed to fetch invite or code is invalid." }))
|
||||||
@@ -451,7 +402,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! {
|
||||||
@@ -515,8 +466,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!" }));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -585,6 +536,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,
|
||||||
@@ -605,7 +557,7 @@ pub fn create_guild(user: UserRef, info: Json<CreateGuild>) -> Response {
|
|||||||
|
|
||||||
/// fetch a guild's member
|
/// fetch a guild's member
|
||||||
#[get("/<target>/members")]
|
#[get("/<target>/members")]
|
||||||
pub fn fetch_members(user: UserRef, target: GuildRef) -> Option<Response> {
|
pub fn fetch_members(user: User, target: Guild) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if let Ok(result) =
|
if let Ok(result) =
|
||||||
@@ -632,24 +584,30 @@ pub fn fetch_members(user: UserRef, target: GuildRef) -> Option<Response> {
|
|||||||
|
|
||||||
/// fetch a guild member
|
/// fetch a guild member
|
||||||
#[get("/<target>/members/<other>")]
|
#[get("/<target>/members/<other>")]
|
||||||
pub fn fetch_member(user: UserRef, target: GuildRef, other: String) -> Option<Response> {
|
pub fn fetch_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||||
with_permissions!(user, target);
|
with_permissions!(user, target);
|
||||||
|
|
||||||
if let Some(member) = get_member(&target.id, &other) {
|
if let Ok(result) = get_member(MemberKey(target.id, other)) {
|
||||||
Some(Response::Success(json!({
|
if let Some(member) = result {
|
||||||
"id": member.id.user,
|
Some(Response::Success(json!({
|
||||||
"nickname": member.nickname,
|
"id": member.id.user,
|
||||||
})))
|
"nickname": member.nickname,
|
||||||
|
})))
|
||||||
|
} else {
|
||||||
|
Some(Response::NotFound(
|
||||||
|
json!({ "error": "Member does not exist!" }),
|
||||||
|
))
|
||||||
|
}
|
||||||
} 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: GuildRef, 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 {
|
||||||
@@ -662,9 +620,15 @@ pub fn kick_member(user: UserRef, target: GuildRef, other: String) -> Option<Res
|
|||||||
return Some(Response::LackingPermission(Permission::KickMembers));
|
return Some(Response::LackingPermission(Permission::KickMembers));
|
||||||
}
|
}
|
||||||
|
|
||||||
if get_member(&target.id, &other).is_none() {
|
if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())) {
|
||||||
return Some(Response::BadRequest(
|
if result.is_none() {
|
||||||
json!({ "error": "User not part of guild." }),
|
return Some(Response::BadRequest(
|
||||||
|
json!({ "error": "User not part of guild." }),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Some(Response::InternalServerError(
|
||||||
|
json!({ "error": "Failed to fetch member." }),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -704,8 +668,8 @@ 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: GuildRef,
|
target: Guild,
|
||||||
other: String,
|
other: String,
|
||||||
options: Form<BanOptions>,
|
options: Form<BanOptions>,
|
||||||
) -> Option<Response> {
|
) -> Option<Response> {
|
||||||
@@ -728,9 +692,15 @@ pub fn ban_member(
|
|||||||
return Some(Response::LackingPermission(Permission::BanMembers));
|
return Some(Response::LackingPermission(Permission::BanMembers));
|
||||||
}
|
}
|
||||||
|
|
||||||
if get_member(&target.id, &other).is_none() {
|
if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())) {
|
||||||
return Some(Response::BadRequest(
|
if result.is_none() {
|
||||||
json!({ "error": "User not part of guild." }),
|
return Some(Response::BadRequest(
|
||||||
|
json!({ "error": "User not part of guild." }),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Some(Response::InternalServerError(
|
||||||
|
json!({ "error": "Failed to fetch member." }),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -784,7 +754,7 @@ pub fn ban_member(
|
|||||||
|
|
||||||
/// unban a guild member
|
/// unban a guild member
|
||||||
#[delete("/<target>/members/<other>/ban")]
|
#[delete("/<target>/members/<other>/ban")]
|
||||||
pub fn unban_member(user: UserRef, target: GuildRef, other: String) -> Option<Response> {
|
pub fn unban_member(user: 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 {
|
||||||
@@ -797,19 +767,7 @@ pub fn unban_member(user: UserRef, target: GuildRef, other: String) -> Option<Re
|
|||||||
return Some(Response::LackingPermission(Permission::BanMembers));
|
return Some(Response::LackingPermission(Permission::BanMembers));
|
||||||
}
|
}
|
||||||
|
|
||||||
if target
|
if target.bans.iter().any(|v| v.id == other) {
|
||||||
.fetch_data_given(
|
|
||||||
doc! {
|
|
||||||
"bans": {
|
|
||||||
"$elemMatch": {
|
|
||||||
"id": &other
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
doc! {},
|
|
||||||
)
|
|
||||||
.is_none()
|
|
||||||
{
|
|
||||||
return Some(Response::BadRequest(json!({ "error": "User not banned." })));
|
return Some(Response::BadRequest(json!({ "error": "User not banned." })));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -838,3 +796,44 @@ pub fn unban_member(user: UserRef, target: GuildRef, other: String) -> Option<Re
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[options("/<_target>")]
|
||||||
|
pub fn guild_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/channels")]
|
||||||
|
pub fn create_channel_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/channels/<_channel>/invite")]
|
||||||
|
pub fn create_invite_preflight(_target: String, _channel: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/invites/<_code>")]
|
||||||
|
pub fn remove_invite_preflight(_target: String, _code: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/invites")]
|
||||||
|
pub fn fetch_invites_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/join/<_code>", rank = 1)]
|
||||||
|
pub fn invite_preflight(_code: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/create")]
|
||||||
|
pub fn create_guild_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/members")]
|
||||||
|
pub fn fetch_members_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/members/<_other>")]
|
||||||
|
pub fn fetch_member_preflight(_target: String, _other: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/members/<_other>/ban")]
|
||||||
|
pub fn ban_member_preflight(_target: String, _other: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
|||||||
+38
-10
@@ -35,6 +35,8 @@ pub enum Response {
|
|||||||
Conflict(JsonValue),
|
Conflict(JsonValue),
|
||||||
#[response(status = 410)]
|
#[response(status = 410)]
|
||||||
Gone(JsonValue),
|
Gone(JsonValue),
|
||||||
|
#[response(status = 418)]
|
||||||
|
Teapot(JsonValue),
|
||||||
#[response(status = 422)]
|
#[response(status = 422)]
|
||||||
UnprocessableEntity(JsonValue),
|
UnprocessableEntity(JsonValue),
|
||||||
#[response(status = 429)]
|
#[response(status = 429)]
|
||||||
@@ -61,23 +63,28 @@ impl<'a> rocket::response::Responder<'a> for Permission {
|
|||||||
|
|
||||||
pub fn mount(rocket: Rocket) -> Rocket {
|
pub fn mount(rocket: Rocket) -> Rocket {
|
||||||
rocket
|
rocket
|
||||||
.mount("/api", routes![root::root])
|
.mount("/", routes![root::root, root::root_preflight, root::teapot])
|
||||||
.mount(
|
.mount(
|
||||||
"/api/account",
|
"/account",
|
||||||
routes![
|
routes![
|
||||||
account::create,
|
account::create,
|
||||||
account::verify_email,
|
account::verify_email,
|
||||||
account::resend_email,
|
account::resend_email,
|
||||||
account::login,
|
account::login,
|
||||||
account::token
|
account::token,
|
||||||
|
account::create_preflight,
|
||||||
|
account::verify_email_preflight,
|
||||||
|
account::resend_email_preflight,
|
||||||
|
account::login_preflight,
|
||||||
|
account::token_preflight,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
.mount(
|
.mount(
|
||||||
"/api/users",
|
"/users",
|
||||||
routes![
|
routes![
|
||||||
user::me,
|
user::me,
|
||||||
user::user,
|
user::user,
|
||||||
user::lookup,
|
user::query,
|
||||||
user::dms,
|
user::dms,
|
||||||
user::dm,
|
user::dm,
|
||||||
user::get_friends,
|
user::get_friends,
|
||||||
@@ -85,11 +92,17 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
user::add_friend,
|
user::add_friend,
|
||||||
user::remove_friend,
|
user::remove_friend,
|
||||||
user::block_user,
|
user::block_user,
|
||||||
user::unblock_user
|
user::unblock_user,
|
||||||
|
user::user_preflight,
|
||||||
|
user::query_preflight,
|
||||||
|
user::dms_preflight,
|
||||||
|
user::dm_preflight,
|
||||||
|
user::friend_preflight,
|
||||||
|
user::block_user_preflight,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
.mount(
|
.mount(
|
||||||
"/api/channels",
|
"/channels",
|
||||||
routes![
|
routes![
|
||||||
channel::create_group,
|
channel::create_group,
|
||||||
channel::channel,
|
channel::channel,
|
||||||
@@ -100,11 +113,16 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
channel::get_message,
|
channel::get_message,
|
||||||
channel::send_message,
|
channel::send_message,
|
||||||
channel::edit_message,
|
channel::edit_message,
|
||||||
channel::delete_message
|
channel::delete_message,
|
||||||
|
channel::create_group_preflight,
|
||||||
|
channel::channel_preflight,
|
||||||
|
channel::member_preflight,
|
||||||
|
channel::messages_preflight,
|
||||||
|
channel::message_preflight,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
.mount(
|
.mount(
|
||||||
"/api/guild",
|
"/guild",
|
||||||
routes![
|
routes![
|
||||||
guild::my_guilds,
|
guild::my_guilds,
|
||||||
guild::guild,
|
guild::guild,
|
||||||
@@ -120,7 +138,17 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
guild::fetch_member,
|
guild::fetch_member,
|
||||||
guild::kick_member,
|
guild::kick_member,
|
||||||
guild::ban_member,
|
guild::ban_member,
|
||||||
guild::unban_member
|
guild::unban_member,
|
||||||
|
guild::guild_preflight,
|
||||||
|
guild::create_channel_preflight,
|
||||||
|
guild::create_invite_preflight,
|
||||||
|
guild::remove_invite_preflight,
|
||||||
|
guild::fetch_invites_preflight,
|
||||||
|
guild::invite_preflight,
|
||||||
|
guild::create_guild_preflight,
|
||||||
|
guild::fetch_members_preflight,
|
||||||
|
guild::fetch_member_preflight,
|
||||||
|
guild::ban_member_preflight,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-2
@@ -1,11 +1,36 @@
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
|
use crate::util::variables::{USE_EMAIL, DISABLE_REGISTRATION, USE_HCAPTCHA};
|
||||||
|
|
||||||
use bson::doc;
|
use mongodb::bson::doc;
|
||||||
|
|
||||||
/// root
|
/// root
|
||||||
#[get("/")]
|
#[get("/")]
|
||||||
pub fn root() -> Response {
|
pub fn root() -> Response {
|
||||||
Response::Success(json!({
|
Response::Success(json!({
|
||||||
"revolt": "0.1.0"
|
"revolt": "0.2.10",
|
||||||
|
"version": {
|
||||||
|
"major": 0,
|
||||||
|
"minor": 2,
|
||||||
|
"patch": 10
|
||||||
|
},
|
||||||
|
"features": {
|
||||||
|
"registration": !*DISABLE_REGISTRATION,
|
||||||
|
"captcha": *USE_HCAPTCHA,
|
||||||
|
"email": *USE_EMAIL,
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[options("/")]
|
||||||
|
pub fn root_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// I'm a teapot.
|
||||||
|
#[delete("/")]
|
||||||
|
pub fn teapot() -> Response {
|
||||||
|
Response::Teapot(json!({
|
||||||
|
"teapot": true,
|
||||||
|
"can_delete": false
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|||||||
+113
-59
@@ -1,51 +1,67 @@
|
|||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::database::{self, get_relationship, get_relationship_internal, mutual, Relationship};
|
use crate::database::{
|
||||||
use crate::guards::auth::UserRef;
|
self, get_relationship, get_relationship_internal, user::User, Relationship,
|
||||||
|
};
|
||||||
use crate::notifications::{
|
use crate::notifications::{
|
||||||
self,
|
self,
|
||||||
events::{users::*, Notification},
|
events::{users::*, Notification},
|
||||||
};
|
};
|
||||||
use crate::routes::channel;
|
use crate::routes::channel;
|
||||||
|
|
||||||
use bson::doc;
|
use mongodb::bson::doc;
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::{Collation, FindOneOptions, FindOptions};
|
||||||
use rocket_contrib::json::Json;
|
use rocket_contrib::json::Json;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
|
|
||||||
/// 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(user.serialise(Relationship::SELF as i32))
|
||||||
Response::Success(json!({
|
|
||||||
"id": user.id,
|
|
||||||
"username": user.username,
|
|
||||||
"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(user.serialise(relationship))
|
||||||
"username": target.username,
|
|
||||||
"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)]
|
||||||
|
pub struct UserQuery {
|
||||||
|
username: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// find a user by their username
|
||||||
|
#[post("/query", data = "<query>")]
|
||||||
|
pub fn query(user: User, query: Json<UserQuery>) -> Response {
|
||||||
|
let col = database::get_collection("users");
|
||||||
|
|
||||||
|
if let Ok(result) = col.find_one(
|
||||||
|
doc! { "username": query.username.clone() },
|
||||||
|
FindOneOptions::builder()
|
||||||
|
.collation(Collation::builder().locale("en").strength(2).build())
|
||||||
|
.build(),
|
||||||
|
) {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
let id = doc.get_str("_id").unwrap();
|
||||||
|
Response::Success(json!({
|
||||||
|
"id": id,
|
||||||
|
"username": doc.get_str("username").unwrap(),
|
||||||
|
"display_name": doc.get_str("display_name").unwrap(),
|
||||||
|
"relationship": get_relationship_internal(&user.id, &id, &user.relations) as i32
|
||||||
|
}))
|
||||||
|
} else {
|
||||||
|
Response::NotFound(json!({
|
||||||
|
"error": "User not found!"
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Response::InternalServerError(json!({ "error": "Failed database query." }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*#[derive(Serialize, Deserialize)]
|
||||||
pub struct LookupQuery {
|
pub struct LookupQuery {
|
||||||
username: String,
|
username: String,
|
||||||
}
|
}
|
||||||
@@ -53,7 +69,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");
|
||||||
|
|
||||||
@@ -80,18 +96,19 @@ pub fn lookup(user: UserRef, query: Json<LookupQuery>) -> Response {
|
|||||||
} else {
|
} else {
|
||||||
Response::InternalServerError(json!({ "error": "Failed database query." }))
|
Response::InternalServerError(json!({ "error": "Failed database query." }))
|
||||||
}
|
}
|
||||||
}
|
}*/
|
||||||
|
|
||||||
/// retrieve all of your DMs
|
/// retrieve all of your DMs
|
||||||
#[get("/@me/dms")]
|
#[get("/@me/dms")]
|
||||||
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(
|
||||||
doc! {
|
doc! {
|
||||||
"$or": [
|
"$or": [
|
||||||
{
|
{
|
||||||
"type": channel::ChannelType::DM as i32
|
"type": channel::ChannelType::DM as i32,
|
||||||
|
"active": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": channel::ChannelType::GROUPDM as i32
|
"type": channel::ChannelType::GROUPDM as i32
|
||||||
@@ -105,6 +122,7 @@ pub fn dms(user: UserRef) -> Response {
|
|||||||
for item in results {
|
for item in results {
|
||||||
if let Ok(doc) = item {
|
if let Ok(doc) = item {
|
||||||
let id = doc.get_str("_id").unwrap();
|
let id = doc.get_str("_id").unwrap();
|
||||||
|
let last_message = doc.get_document("last_message").unwrap();
|
||||||
let recipients = doc.get_array("recipients").unwrap();
|
let recipients = doc.get_array("recipients").unwrap();
|
||||||
|
|
||||||
match doc.get_i32("type").unwrap() {
|
match doc.get_i32("type").unwrap() {
|
||||||
@@ -112,6 +130,7 @@ pub fn dms(user: UserRef) -> Response {
|
|||||||
channels.push(json!({
|
channels.push(json!({
|
||||||
"id": id,
|
"id": id,
|
||||||
"type": 0,
|
"type": 0,
|
||||||
|
"last_message": last_message,
|
||||||
"recipients": recipients,
|
"recipients": recipients,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -138,7 +157,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(
|
||||||
@@ -171,11 +190,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,
|
||||||
@@ -189,13 +206,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) {
|
||||||
@@ -238,7 +255,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -247,7 +265,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -309,7 +328,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -318,7 +338,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -343,7 +364,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) {
|
||||||
@@ -384,7 +405,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -393,7 +415,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -419,13 +442,11 @@ 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) {
|
||||||
Relationship::Friend
|
Relationship::Friend | Relationship::Incoming | Relationship::Outgoing => {
|
||||||
| Relationship::Incoming
|
|
||||||
| Relationship::Outgoing => {
|
|
||||||
if col
|
if col
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! {
|
doc! {
|
||||||
@@ -460,7 +481,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -469,7 +491,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -526,7 +549,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -535,7 +559,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -575,7 +600,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -593,7 +619,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) {
|
||||||
@@ -618,7 +644,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -667,7 +694,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -676,7 +704,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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -705,3 +734,28 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
|||||||
| Relationship::NONE => Response::BadRequest(json!({ "error": "This has no effect." })),
|
| Relationship::NONE => Response::BadRequest(json!({ "error": "This has no effect." })),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[options("/<_target>")]
|
||||||
|
pub fn user_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/query")]
|
||||||
|
pub fn query_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/@me/dms")]
|
||||||
|
pub fn dms_preflight() -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/dm")]
|
||||||
|
pub fn dm_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/friend")]
|
||||||
|
pub fn friend_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
#[options("/<_target>/block")]
|
||||||
|
pub fn block_user_preflight(_target: String) -> Response {
|
||||||
|
Response::Result(super::Status::Ok)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
use crate::util::variables::{HCAPTCHA_KEY, USE_HCAPTCHA};
|
||||||
|
|
||||||
|
use reqwest::blocking::Client;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct CaptchaResponse {
|
||||||
|
success: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify(user_token: &Option<String>) -> Result<(), String> {
|
||||||
|
if *USE_HCAPTCHA {
|
||||||
|
if let Some(token) = user_token {
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
map.insert("secret", HCAPTCHA_KEY.to_string());
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
use lettre::message::{header, MultiPart, SinglePart};
|
||||||
|
use lettre::transport::smtp::authentication::Credentials;
|
||||||
|
use lettre::{Message, SmtpTransport, Transport};
|
||||||
|
|
||||||
|
use super::variables::{PUBLIC_URL, SMTP_FROM, SMTP_HOST, SMTP_PASSWORD, SMTP_USERNAME};
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
static ref MAILER: lettre::transport::smtp::SmtpTransport =
|
||||||
|
SmtpTransport::relay(SMTP_HOST.as_ref())
|
||||||
|
.unwrap()
|
||||||
|
.credentials(Credentials::new(
|
||||||
|
SMTP_USERNAME.to_string(),
|
||||||
|
SMTP_PASSWORD.to_string()
|
||||||
|
))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(message: Message) -> Result<(), String> {
|
||||||
|
MAILER
|
||||||
|
.send(&message)
|
||||||
|
.map_err(|err| format!("Failed to send email! {}", err.to_string()))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_multipart(text: &str, html: &str) -> MultiPart {
|
||||||
|
MultiPart::mixed().multipart(
|
||||||
|
MultiPart::alternative()
|
||||||
|
.singlepart(
|
||||||
|
SinglePart::quoted_printable()
|
||||||
|
.header(header::ContentType(
|
||||||
|
"text/plain; charset=utf8".parse().unwrap(),
|
||||||
|
))
|
||||||
|
.body(text),
|
||||||
|
)
|
||||||
|
.multipart(
|
||||||
|
MultiPart::related().singlepart(
|
||||||
|
SinglePart::eight_bit()
|
||||||
|
.header(header::ContentType(
|
||||||
|
"text/html; charset=utf8".parse().unwrap(),
|
||||||
|
))
|
||||||
|
.body(html),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_verification_email(email: String, code: String) -> Result<(), String> {
|
||||||
|
let url = format!("{}/api/account/verify/{}", PUBLIC_URL.to_string(), code);
|
||||||
|
let email = Message::builder()
|
||||||
|
.from(SMTP_FROM.to_string().parse().unwrap())
|
||||||
|
.to(email.parse().unwrap())
|
||||||
|
.subject("Verify your email!")
|
||||||
|
.multipart(generate_multipart(
|
||||||
|
&format!("Verify your email here: {}", url),
|
||||||
|
&format!("<a href=\"{}\">Click to verify your email!</a>", url),
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
send(email)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_password_reset(email: String, code: String) -> Result<(), String> {
|
||||||
|
let url = format!("{}/api/account/reset/{}", PUBLIC_URL.to_string(), code);
|
||||||
|
let email = Message::builder()
|
||||||
|
.from(SMTP_FROM.to_string().parse().unwrap())
|
||||||
|
.to(email.parse().unwrap())
|
||||||
|
.subject("Reset your password.")
|
||||||
|
.multipart(generate_multipart(
|
||||||
|
&format!("Reset your password here: {}", url),
|
||||||
|
&format!("<a href=\"{}\">Click to reset your password!</a>", url),
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
send(email)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_welcome_email(email: String, username: String) -> Result<(), String> {
|
||||||
|
let email = Message::builder()
|
||||||
|
.from(SMTP_FROM.to_string().parse().unwrap())
|
||||||
|
.to(email.parse().unwrap())
|
||||||
|
.subject("Welcome to REVOLT!")
|
||||||
|
.multipart(
|
||||||
|
generate_multipart(
|
||||||
|
&format!("Welcome, {}! You can now use REVOLT.", username),
|
||||||
|
&format!(
|
||||||
|
"<b>Welcome, {}!</b><br/>You can now use REVOLT.<br/><a href=\"{}\">Go to REVOLT</a>",
|
||||||
|
username,
|
||||||
|
PUBLIC_URL.to_string()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
send(email)
|
||||||
|
}
|
||||||
@@ -2,6 +2,10 @@ 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 mod email;
|
||||||
|
pub mod variables;
|
||||||
|
|
||||||
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())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use std::env;
|
||||||
|
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
use log::warn;
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
// Application Settings
|
||||||
|
pub static ref MONGO_URI: String =
|
||||||
|
env::var("REVOLT_MONGO_URI").expect("Missing REVOLT_MONGO_URI environment variable.");
|
||||||
|
pub static ref PUBLIC_URL: String =
|
||||||
|
env::var("REVOLT_PUBLIC_URL").expect("Missing REVOLT_PUBLIC_URL environment variable.");
|
||||||
|
pub static ref HCAPTCHA_KEY: String =
|
||||||
|
env::var("REVOLT_HCAPTCHA_KEY").unwrap_or_else(|_| "".to_string());
|
||||||
|
pub static ref WS_HOST: String =
|
||||||
|
env::var("REVOLT_WS_HOST").unwrap_or_else(|_| "0.0.0.0:9999".to_string());
|
||||||
|
|
||||||
|
// Application Flags
|
||||||
|
pub static ref DISABLE_REGISTRATION: bool = env::var("REVOLT_DISABLE_REGISTRATION").map_or(false, |v| v == "*1");
|
||||||
|
pub static ref USE_EMAIL: bool = env::var("REVOLT_USE_EMAIL_VERIFICATION").map_or(
|
||||||
|
env::var("REVOLT_SMTP_HOST").is_ok()
|
||||||
|
&& env::var("REVOLT_SMTP_USERNAME").is_ok()
|
||||||
|
&& env::var("REVOLT_SMTP_PASSWORD").is_ok()
|
||||||
|
&& env::var("REVOLT_SMTP_FROM").is_ok(),
|
||||||
|
|v| v == *"1"
|
||||||
|
);
|
||||||
|
pub static ref USE_HCAPTCHA: bool = env::var("REVOLT_HCAPTCHA_KEY").is_ok();
|
||||||
|
|
||||||
|
// SMTP Settings
|
||||||
|
pub static ref SMTP_HOST: String =
|
||||||
|
env::var("REVOLT_SMTP_HOST").unwrap_or_else(|_| "".to_string());
|
||||||
|
pub static ref SMTP_USERNAME: String =
|
||||||
|
env::var("SMTP_USERNAME").unwrap_or_else(|_| "".to_string());
|
||||||
|
pub static ref SMTP_PASSWORD: String =
|
||||||
|
env::var("SMTP_PASSWORD").unwrap_or_else(|_| "".to_string());
|
||||||
|
pub static ref SMTP_FROM: String = env::var("SMTP_FROM").unwrap_or_else(|_| "".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn preflight_checks() {
|
||||||
|
if *USE_EMAIL == false {
|
||||||
|
#[cfg(not(debug_assertions))]
|
||||||
|
{
|
||||||
|
if !env::var("REVOLT_UNSAFE_NO_EMAIL")
|
||||||
|
.map_or(false, |v| v == *"1") {
|
||||||
|
panic!(
|
||||||
|
"Not letting you run this in production, set REVOLT_UNSAFE_NO_EMAIL=1 to run."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
warn!("No SMTP settings specified! Remember to configure email.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if *USE_HCAPTCHA == false {
|
||||||
|
#[cfg(not(debug_assertions))]
|
||||||
|
{
|
||||||
|
if !env::var("REVOLT_UNSAFE_NO_CAPTCHA")
|
||||||
|
.map_or(false, |v| v == *"1") {
|
||||||
|
panic!("Not letting you run this in production, set REVOLT_UNSAFE_NO_CAPTCHA=1 to run.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
warn!("No Captcha key specified! Remember to add hCaptcha key.");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user