Compare commits

..
15 Commits
26 changed files with 572 additions and 158 deletions

No files matched your search

Generated
+5 -3
View File
@@ -1,5 +1,7 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3
[[package]] [[package]]
name = "addr2line" name = "addr2line"
version = "0.14.1" version = "0.14.1"
@@ -1065,9 +1067,9 @@ checksum = "644f9158b2f133fd50f5fb3242878846d9eb792e445c893805ff0e3824006e35"
[[package]] [[package]]
name = "hive_pubsub" name = "hive_pubsub"
version = "0.4.3" version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83760410241f6db418bb15e54b506a0887e7240286e29e5b0d2d88f5d1659b24" checksum = "2ac4635b1e9faf304ccb33c2f0edbc615030e40d249183281fc788ef20ef5c76"
dependencies = [ dependencies = [
"futures", "futures",
"many-to-many", "many-to-many",
@@ -2473,7 +2475,7 @@ dependencies = [
[[package]] [[package]]
name = "revolt" name = "revolt"
version = "0.3.3-alpha.7" version = "0.4.0-alpha.6"
dependencies = [ dependencies = [
"async-std", "async-std",
"async-tungstenite", "async-tungstenite",
+29 -34
View File
@@ -1,49 +1,44 @@
[package] [package]
name = "revolt" name = "revolt"
version = "0.3.3-alpha.7" version = "0.4.0-alpha.6"
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]
regex = "1"
md5 = "0.7.0"
log = "0.4.11"
ulid = "0.4.1"
rand = "0.7.3"
time = "0.2.16"
base64 = "0.13.0" base64 = "0.13.0"
dotenv = "0.15.0"
futures = "0.3.8" futures = "0.3.8"
chrono = "0.4.15"
num_enum = "0.5.1"
impl_ops = "0.1.1" impl_ops = "0.1.1"
web-push = "0.7.2" web-push = "0.7.2"
many-to-many = "0.1.2"
ctrlc = { version = "3.0", features = ["termination"] }
async-std = { version = "1.8.0", features = ["tokio02", "attributes"] }
async-tungstenite = { version = "0.10.0", features = ["async-std-runtime"] }
rauth = { git = "https://gitlab.insrt.uk/insert/rauth", rev = "c52758a5087cd035b0ed9c6eacc942ba5468d2ce" }
hive_pubsub = { version = "0.4.3", features = ["mongo"] }
rocket_cors = { git = "https://github.com/insertish/rocket_cors", branch = "master" }
rocket_prometheus = { git = "https://github.com/insertish/rocket_prometheus", rev = "3d825aedb42793246c306a81fe67c5b187948983" }
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket", rev = "031948c1daaa146128d8a435be116476f2adde00" }
rocket = { git = "https://github.com/SergioBenitez/Rocket", rev = "031948c1daaa146128d8a435be116476f2adde00", default-features = false }
mongodb = { version = "1.1.1", features = ["tokio-runtime"], default-features = false }
once_cell = "1.4.1" once_cell = "1.4.1"
dotenv = "0.15.0" bitfield = "0.13.2"
ulid = "0.4.1" env_logger = "0.7.1"
serde_json = "1.0.57"
lazy_static = "1.4.0"
urlencoding = "1.1.1"
many-to-many = "0.1.2"
lettre = "0.10.0-alpha.1"
snafu = { version = "0.6.9" }
reqwest = { version = "0.10.8", features = ["json"] }
serde = { version = "1.0.115", features = ["derive"] } serde = { version = "1.0.115", features = ["derive"] }
validator = { version = "0.11", features = ["derive"] } validator = { version = "0.11", features = ["derive"] }
snafu = { version = "0.6.9" } ctrlc = { version = "3.0", features = ["termination"] }
serde_json = "1.0.57" hive_pubsub = { version = "0.4.4", features = ["mongo"] }
bitfield = "0.13.2" async-std = { version = "1.8.0", features = ["tokio02", "attributes"] }
async-tungstenite = { version = "0.10.0", features = ["async-std-runtime"] }
reqwest = { version = "0.10.8", features = ["json"] } rocket_cors = { git = "https://github.com/insertish/rocket_cors", branch = "master" }
urlencoding = "1.1.1" mongodb = { version = "1.1.1", features = ["tokio-runtime"], default-features = false }
lazy_static = "1.4.0" rauth = { git = "https://gitlab.insrt.uk/insert/rauth", rev = "c52758a5087cd035b0ed9c6eacc942ba5468d2ce" }
num_enum = "0.5.1" rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket", rev = "031948c1daaa146128d8a435be116476f2adde00" }
chrono = "0.4.15" rocket_prometheus = { git = "https://github.com/insertish/rocket_prometheus", rev = "3d825aedb42793246c306a81fe67c5b187948983" }
time = "0.2.16" rocket = { git = "https://github.com/SergioBenitez/Rocket", rev = "031948c1daaa146128d8a435be116476f2adde00", default-features = false }
rand = "0.7.3"
md5 = "0.7.0"
regex = "1"
lettre = "0.10.0-alpha.1"
env_logger = "0.7.1"
log = "0.4.11"
+1
View File
@@ -1,5 +1,6 @@
# Build Stage # Build Stage
FROM ekidd/rust-musl-builder:nightly-2021-01-01 AS builder FROM ekidd/rust-musl-builder:nightly-2021-01-01 AS builder
USER 0:0
WORKDIR /home/rust/src WORKDIR /home/rust/src
RUN USER=root cargo new --bin revolt RUN USER=root cargo new --bin revolt
+94 -60
View File
@@ -17,6 +17,34 @@ use web_push::{
ContentEncoding, SubscriptionInfo, VapidSignatureBuilder, WebPushClient, WebPushMessageBuilder, ContentEncoding, SubscriptionInfo, VapidSignatureBuilder, WebPushClient, WebPushMessageBuilder,
}; };
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum MessageEmbed {
Dummy,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum SystemMessage {
#[serde(rename = "text")]
Text { content: String },
#[serde(rename = "user_added")]
UserAdded { id: String, by: String },
#[serde(rename = "user_remove")]
UserRemove { id: String, by: String },
#[serde(rename = "user_left")]
UserLeft { id: String },
#[serde(rename = "channel_renamed")]
ChannelRenamed { name: String, by: String },
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum Content {
Text(String),
SystemMessage(SystemMessage),
}
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Message { pub struct Message {
#[serde(rename = "_id")] #[serde(rename = "_id")]
@@ -26,15 +54,17 @@ pub struct Message {
pub channel: String, pub channel: String,
pub author: String, pub author: String,
pub content: String, pub content: Content,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub attachment: Option<File>, pub attachment: Option<File>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub edited: Option<DateTime>, pub edited: Option<DateTime>,
#[serde(skip_serializing_if = "Option::is_none")]
pub embeds: Option<MessageEmbed>,
} }
impl Message { impl Message {
pub fn create(author: String, channel: String, content: String) -> Message { pub fn create(author: String, channel: String, content: Content) -> Message {
Message { Message {
id: Ulid::new().to_string(), id: Ulid::new().to_string(),
nonce: None, nonce: None,
@@ -44,6 +74,7 @@ impl Message {
content, content,
attachment: None, attachment: None,
edited: None, edited: None,
embeds: None,
} }
} }
@@ -56,22 +87,28 @@ impl Message {
with: "message", with: "message",
})?; })?;
let mut set = if let Content::Text(text) = &self.content {
doc! {
"last_message": {
"_id": self.id.clone(),
"author": self.author.clone(),
"short": text.chars().take(24).collect::<String>()
}
}
} else {
doc! {}
};
// ! FIXME: temp code // ! FIXME: temp code
let channels = get_collection("channels"); let channels = get_collection("channels");
match &channel { match &channel {
Channel::DirectMessage { id, .. } => { Channel::DirectMessage { id, .. } => {
set.insert("active", true);
channels channels
.update_one( .update_one(
doc! { "_id": id }, doc! { "_id": id },
doc! { doc! {
"$set": { "$set": set
"active": true,
"last_message": {
"_id": self.id.clone(),
"author": self.author.clone(),
"short": self.content.chars().take(24).collect::<String>()
}
}
}, },
None, None,
) )
@@ -82,25 +119,21 @@ impl Message {
})?; })?;
} }
Channel::Group { id, .. } => { Channel::Group { id, .. } => {
channels if let Content::Text(_) = &self.content {
.update_one( channels
doc! { "_id": id }, .update_one(
doc! { doc! { "_id": id },
"$set": { doc! {
"last_message": { "$set": set
"_id": self.id.clone(), },
"author": self.author.clone(), None,
"short": self.content.chars().take(24).collect::<String>() )
} .await
} .map_err(|_| Error::DatabaseError {
}, operation: "update_one",
None, with: "channel",
) })?;
.await }
.map_err(|_| Error::DatabaseError {
operation: "update_one",
with: "channel",
})?;
} }
_ => {} _ => {}
} }
@@ -109,7 +142,7 @@ impl Message {
ClientboundNotification::Message(self) ClientboundNotification::Message(self)
.publish(channel.id().to_string()) .publish(channel.id().to_string())
.await .await
.ok(); .unwrap();
/* /*
Web Push Test Code Web Push Test Code
@@ -130,7 +163,7 @@ impl Message {
} }
// Fetch their corresponding sessions. // Fetch their corresponding sessions.
let mut cursor = get_collection("accounts") if let Ok(mut cursor) = get_collection("accounts")
.find( .find(
doc! { doc! {
"_id": { "_id": {
@@ -145,42 +178,43 @@ impl Message {
.build(), .build(),
) )
.await .await
.unwrap(); // !FIXME {
let mut subscriptions = vec![];
while let Some(result) = cursor.next().await {
if let Ok(doc) = result {
if let Ok(sessions) = doc.get_array("sessions") {
for session in sessions {
if let Some(doc) = session.as_document() {
if let Ok(sub) = doc.get_document("subscription") {
let endpoint = sub.get_str("endpoint").unwrap().to_string();
let p256dh = sub.get_str("p256dh").unwrap().to_string();
let auth = sub.get_str("auth").unwrap().to_string();
let mut subscriptions = vec![]; subscriptions
while let Some(result) = cursor.next().await { .push(SubscriptionInfo::new(endpoint, p256dh, auth));
if let Ok(doc) = result { }
if let Ok(sessions) = doc.get_array("sessions") {
for session in sessions {
if let Some(doc) = session.as_document() {
if let Ok(sub) = doc.get_document("subscription") {
let endpoint = sub.get_str("endpoint").unwrap().to_string();
let p256dh = sub.get_str("p256dh").unwrap().to_string();
let auth = sub.get_str("auth").unwrap().to_string();
subscriptions.push(SubscriptionInfo::new(endpoint, p256dh, auth));
} }
} }
} }
} }
} }
}
if subscriptions.len() > 0 { if subscriptions.len() > 0 {
let client = WebPushClient::new(); let client = WebPushClient::new();
let key = base64::decode_config(VAPID_PRIVATE_KEY.clone(), base64::URL_SAFE).unwrap(); let key =
base64::decode_config(VAPID_PRIVATE_KEY.clone(), base64::URL_SAFE).unwrap();
for subscription in subscriptions { for subscription in subscriptions {
let mut builder = WebPushMessageBuilder::new(&subscription).unwrap(); let mut builder = WebPushMessageBuilder::new(&subscription).unwrap();
let sig_builder = let sig_builder =
VapidSignatureBuilder::from_pem(std::io::Cursor::new(&key), &subscription) VapidSignatureBuilder::from_pem(std::io::Cursor::new(&key), &subscription)
.unwrap(); .unwrap();
let signature = sig_builder.build().unwrap(); let signature = sig_builder.build().unwrap();
builder.set_vapid_signature(signature); builder.set_vapid_signature(signature);
builder.set_payload(ContentEncoding::AesGcm, enc.as_bytes()); builder.set_payload(ContentEncoding::AesGcm, enc.as_bytes());
let m = builder.build().unwrap(); let m = builder.build().unwrap();
let response = client.send(m).await.unwrap(); client.send(m).await.ok();
dbg!(response); }
} }
} }
@@ -212,7 +246,7 @@ impl Message {
"deleted": true "deleted": true
} }
}, },
None None,
) )
.await .await
.map_err(|_| Error::DatabaseError { .map_err(|_| Error::DatabaseError {
+46 -6
View File
@@ -1,11 +1,12 @@
use mongodb::bson::doc; use mongodb::bson::doc;
use serde::{Deserialize, Serialize};
use mongodb::options::{Collation, FindOneOptions}; use mongodb::options::{Collation, FindOneOptions};
use serde::{Deserialize, Serialize};
use crate::database::*;
use crate::util::result::{Error, Result};
use crate::notifications::websocket::is_online;
use crate::database::permissions::user::UserPermissions; use crate::database::permissions::user::UserPermissions;
use crate::database::*;
use crate::notifications::websocket::is_online;
use crate::util::result::{Error, Result};
use validator::Validate;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum RelationshipStatus { pub enum RelationshipStatus {
@@ -25,6 +26,37 @@ pub struct Relationship {
pub status: RelationshipStatus, pub status: RelationshipStatus,
} }
/*
pub enum Badge {
Developer = 1,
Translator = 2,
}
*/
#[derive(Serialize, Deserialize, Debug)]
pub enum Presence {
Online,
Idle,
Busy,
Invisible
}
#[derive(Validate, Serialize, Deserialize, Debug)]
pub struct UserStatus {
#[validate(length(min = 1, max = 128))]
#[serde(skip_serializing_if = "Option::is_none")]
text: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
presence: Option<Presence>
}
#[derive(Validate, Serialize, Deserialize, Debug)]
pub struct UserProfile {
#[validate(length(min = 1, max = 2000))]
#[serde(skip_serializing_if = "Option::is_none")]
content: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct User { pub struct User {
#[serde(rename = "_id")] #[serde(rename = "_id")]
@@ -33,6 +65,13 @@ pub struct User {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub relations: Option<Vec<Relationship>>, pub relations: Option<Vec<Relationship>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub badges: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<UserStatus>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile: Option<UserProfile>,
// ? This should never be pushed to the collection. // ? This should never be pushed to the collection.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub relationship: Option<RelationshipStatus>, pub relationship: Option<RelationshipStatus>,
@@ -65,13 +104,14 @@ impl User {
self.online = Some(is_online(&self.id)); self.online = Some(is_online(&self.id));
} }
self.profile = None;
self self
} }
/// Utility function for checking claimed usernames. /// Utility function for checking claimed usernames.
pub async fn is_username_taken(username: &str) -> Result<bool> { pub async fn is_username_taken(username: &str) -> Result<bool> {
if username == "revolt" && username == "admin" { if username.to_lowercase() == "revolt" && username.to_lowercase() == "admin" {
return Ok(true) return Ok(true);
} }
if get_collection("users") if get_collection("users")
+12 -5
View File
@@ -12,6 +12,8 @@ pub enum ChannelPermission {
View = 1, View = 1,
SendMessage = 2, SendMessage = 2,
ManageMessages = 4, ManageMessages = 4,
ManageChannel = 8,
VoiceCall = 16,
} }
bitfield! { bitfield! {
@@ -20,6 +22,8 @@ bitfield! {
pub get_view, _: 31; pub get_view, _: 31;
pub get_send_message, _: 30; pub get_send_message, _: 30;
pub get_manage_messages, _: 29; pub get_manage_messages, _: 29;
pub get_manage_channel, _: 28;
pub get_voice_call, _: 27;
} }
impl_op_ex!(+ |a: &ChannelPermission, b: &ChannelPermission| -> u32 { *a as u32 | *b as u32 }); impl_op_ex!(+ |a: &ChannelPermission, b: &ChannelPermission| -> u32 { *a as u32 | *b as u32 });
@@ -36,9 +40,7 @@ impl<'a> PermissionCalculator<'a> {
match channel { match channel {
Channel::SavedMessages { user: owner, .. } => { Channel::SavedMessages { user: owner, .. } => {
if &self.perspective.id == owner { if &self.perspective.id == owner {
Ok(ChannelPermission::View Ok(u32::MAX)
+ ChannelPermission::SendMessage
+ ChannelPermission::ManageMessages)
} else { } else {
Ok(0) Ok(0)
} }
@@ -54,7 +56,9 @@ impl<'a> PermissionCalculator<'a> {
let perms = self.for_user(recipient).await?; let perms = self.for_user(recipient).await?;
if perms.get_send_message() { if perms.get_send_message() {
return Ok(ChannelPermission::View + ChannelPermission::SendMessage); return Ok(ChannelPermission::View
+ ChannelPermission::SendMessage
+ ChannelPermission::VoiceCall);
} }
return Ok(ChannelPermission::View as u32); return Ok(ChannelPermission::View as u32);
@@ -69,7 +73,10 @@ impl<'a> PermissionCalculator<'a> {
.find(|x| *x == &self.perspective.id) .find(|x| *x == &self.perspective.id)
.is_some() .is_some()
{ {
Ok(ChannelPermission::View + ChannelPermission::SendMessage) Ok(ChannelPermission::View
+ ChannelPermission::SendMessage
+ ChannelPermission::ManageChannel
+ ChannelPermission::VoiceCall)
} else { } else {
Ok(0) Ok(0)
} }
+3 -3
View File
@@ -11,7 +11,7 @@ pub struct PermissionCalculator<'a> {
user: Option<&'a User>, user: Option<&'a User>,
channel: Option<&'a Channel>, channel: Option<&'a Channel>,
has_mutual_conncetion: bool, has_mutual_connection: bool,
} }
impl<'a> PermissionCalculator<'a> { impl<'a> PermissionCalculator<'a> {
@@ -22,7 +22,7 @@ impl<'a> PermissionCalculator<'a> {
user: None, user: None,
channel: None, channel: None,
has_mutual_conncetion: false, has_mutual_connection: false,
} }
} }
@@ -42,7 +42,7 @@ impl<'a> PermissionCalculator<'a> {
pub fn with_mutual_connection(self) -> PermissionCalculator<'a> { pub fn with_mutual_connection(self) -> PermissionCalculator<'a> {
PermissionCalculator { PermissionCalculator {
has_mutual_conncetion: true, has_mutual_connection: true,
..self ..self
} }
} }
+9 -10
View File
@@ -64,18 +64,16 @@ impl<'a> PermissionCalculator<'a> {
_ => {} _ => {}
} }
if self.has_mutual_conncetion if self.has_mutual_connection
|| get_collection("channels") || get_collection("channels")
.find_one( .find_one(
doc! { doc! {
"$or": [ "channel_type": {
{ "type": "Group" }, "$in": ["Group", "DirectMessage"]
{ "type": "DirectMessage" }, },
], "recipients": {
"$and": [ "$all": [ &self.perspective.id, target ]
{ "recipients": &self.perspective.id }, }
{ "recipients": target }
]
}, },
None, None,
) )
@@ -86,7 +84,8 @@ impl<'a> PermissionCalculator<'a> {
})? })?
.is_some() .is_some()
{ {
return Ok(UserPermission::Access as u32); // ! FIXME: add privacy settings
return Ok(UserPermission::Access + UserPermission::ViewProfile);
} }
Ok(permissions) Ok(permissions)
+8 -8
View File
@@ -26,12 +26,8 @@ pub enum WebSocketError {
#[serde(tag = "type")] #[serde(tag = "type")]
pub enum ServerboundNotification { pub enum ServerboundNotification {
Authenticate(Session), Authenticate(Session),
BeginTyping { BeginTyping { channel: String },
channel: String EndTyping { channel: String },
},
EndTyping {
channel: String
}
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
@@ -71,13 +67,17 @@ pub enum ClientboundNotification {
}, },
ChannelStartTyping { ChannelStartTyping {
id: String, id: String,
user: String user: String,
}, },
ChannelStopTyping { ChannelStopTyping {
id: String, id: String,
user: String user: String,
}, },
UserUpdate {
id: String,
data: JsonValue,
},
UserRelationship { UserRelationship {
id: String, id: String,
user: String, user: String,
+1 -1
View File
@@ -77,7 +77,7 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
} }
}, },
FindOptions::builder() FindOptions::builder()
.projection(doc! { "_id": 1, "username": 1 }) .projection(doc! { "_id": 1, "username": 1, "badges": 1, "status": 1 })
.build(), .build(),
) )
.await .await
+2 -2
View File
@@ -171,7 +171,7 @@ async fn accept(stream: TcpStream) {
ClientboundNotification::ChannelStartTyping { ClientboundNotification::ChannelStartTyping {
id: channel.clone(), id: channel.clone(),
user user,
} }
.publish(channel) .publish(channel)
.await .await
@@ -194,7 +194,7 @@ async fn accept(stream: TcpStream) {
ClientboundNotification::ChannelStopTyping { ClientboundNotification::ChannelStopTyping {
id: channel.clone(), id: channel.clone(),
user user,
} }
.publish(channel) .publish(channel)
.await .await
+1 -2
View File
@@ -102,8 +102,7 @@ pub async fn req(user: User, target: Ref) -> Result<()> {
Message::create( Message::create(
"00000000000000000000000000".to_string(), "00000000000000000000000000".to_string(),
id.clone(), id.clone(),
// ! FIXME: make a schema for this Content::SystemMessage(SystemMessage::UserLeft { id: user.id }),
format!("{{\"type\":\"user_left\",\"id\":\"{}\"}}", user.id),
) )
.publish(&target) .publish(&target)
.await .await
+76
View File
@@ -0,0 +1,76 @@
use crate::database::*;
use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result};
use mongodb::bson::{doc, to_document};
use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize};
use validator::Validate;
#[derive(Validate, Serialize, Deserialize)]
pub struct Data {
#[validate(length(min = 1, max = 32))]
#[serde(skip_serializing_if = "Option::is_none")]
name: Option<String>,
#[validate(length(min = 0, max = 1024))]
#[serde(skip_serializing_if = "Option::is_none")]
description: Option<String>,
}
#[patch("/<target>", data = "<info>")]
pub async fn req(user: User, target: Ref, info: Json<Data>) -> Result<()> {
info.validate()
.map_err(|error| Error::FailedValidation { error })?;
if info.name.is_none() && info.description.is_none() {
return Ok(());
}
let target = target.fetch_channel().await?;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target)
.for_channel()
.await?;
if !perm.get_manage_channel() {
Err(Error::MissingPermission)?
}
match &target {
Channel::Group { id, .. } => {
get_collection("channels")
.update_one(
doc! { "_id": &id },
doc! { "$set": to_document(&info.0).map_err(|_| Error::DatabaseError { operation: "to_document", with: "data" })? },
None
)
.await
.map_err(|_| Error::DatabaseError { operation: "update_one", with: "channel" })?;
ClientboundNotification::ChannelUpdate {
id: id.clone(),
data: json!(info.0),
}
.publish(id.clone())
.await
.ok();
if let Some(name) = &info.name {
Message::create(
"00000000000000000000000000".to_string(),
id.clone(),
Content::SystemMessage(SystemMessage::ChannelRenamed {
name: name.clone(),
by: user.id,
}),
)
.publish(&target)
.await
.ok();
}
Ok(())
}
_ => Err(Error::InvalidOperation),
}
}
+4 -2
View File
@@ -59,8 +59,10 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
Message::create( Message::create(
"00000000000000000000000000".to_string(), "00000000000000000000000000".to_string(),
id.clone(), id.clone(),
// ! FIXME: make a schema for this Content::SystemMessage(SystemMessage::UserAdded {
format!("{{\"type\":\"user_added\",\"id\":\"{}\",\"by\":\"{}\"}}", member.id, user.id), id: member.id,
by: user.id,
}),
) )
.publish(&channel) .publish(&channel)
.await .await
+4 -2
View File
@@ -56,8 +56,10 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
Message::create( Message::create(
"00000000000000000000000000".to_string(), "00000000000000000000000000".to_string(),
id.clone(), id.clone(),
// ! FIXME: make a schema for this Content::SystemMessage(SystemMessage::UserRemove {
format!("{{\"type\":\"user_remove\",\"id\":\"{}\",\"by\":\"{}\"}}", member.id, user.id), id: member.id,
by: user.id,
}),
) )
.publish(&channel) .publish(&channel)
.await .await
+84
View File
@@ -0,0 +1,84 @@
use crate::database::*;
use crate::util::result::{Error, Result};
use crate::util::variables::{USE_VOSO, VOSO_MANAGE_TOKEN, VOSO_URL};
use rocket_contrib::json::JsonValue;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct CreateUserResponse {
token: String,
}
#[post("/<target>/join_call")]
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
if !*USE_VOSO {
return Err(Error::VosoUnavailable);
}
let target = target.fetch_channel().await?;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target)
.for_channel()
.await?;
if !perm.get_voice_call() {
return Err(Error::MissingPermission);
}
// To join a call:
// - Check if the room exists.
// - If not, create it.
let client = reqwest::Client::new();
let result = client
.get(&format!("{}/room/{}", *VOSO_URL, target.id()))
.header(
reqwest::header::AUTHORIZATION,
VOSO_MANAGE_TOKEN.to_string(),
)
.send()
.await;
match result {
Err(_) => return Err(Error::VosoUnavailable),
Ok(result) => match result.status() {
reqwest::StatusCode::OK => (),
reqwest::StatusCode::NOT_FOUND => {
if let Err(_) = client
.post(&format!("{}/room/{}", *VOSO_URL, target.id()))
.header(
reqwest::header::AUTHORIZATION,
VOSO_MANAGE_TOKEN.to_string(),
)
.send()
.await
{
return Err(Error::VosoUnavailable);
}
}
_ => return Err(Error::VosoUnavailable),
},
}
// Then create a user for the room.
if let Ok(response) = client
.post(&format!(
"{}/room/{}/user/{}",
*VOSO_URL,
target.id(),
user.id
))
.header(
reqwest::header::AUTHORIZATION,
VOSO_MANAGE_TOKEN.to_string(),
)
.send()
.await
{
let res: CreateUserResponse = response.json().await.map_err(|_| Error::InvalidOperation)?;
Ok(json!(res))
} else {
Err(Error::VosoUnavailable)
}
}
+3 -2
View File
@@ -32,11 +32,11 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
} }
let target = target.fetch_channel().await?; let target = target.fetch_channel().await?;
let perm = permissions::PermissionCalculator::new(&user) let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target) .with_channel(&target)
.for_channel() .for_channel()
.await?; .await?;
if !perm.get_send_message() { if !perm.get_send_message() {
Err(Error::MissingPermission)? Err(Error::MissingPermission)?
} }
@@ -115,10 +115,11 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
channel: target.id().to_string(), channel: target.id().to_string(),
author: user.id, author: user.id,
content: message.content.clone(), content: Content::Text(message.content.clone()),
attachment, attachment,
nonce: Some(message.nonce.clone()), nonce: Some(message.nonce.clone()),
edited: None, edited: None,
embeds: None,
}; };
msg.clone().publish(&target).await?; msg.clone().publish(&target).await?;
+5 -1
View File
@@ -1,10 +1,12 @@
use rocket::Route; use rocket::Route;
mod delete_channel; mod delete_channel;
mod edit_channel;
mod fetch_channel; mod fetch_channel;
mod group_add_member; mod group_add_member;
mod group_create; mod group_create;
mod group_remove_member; mod group_remove_member;
mod join_call;
mod message_delete; mod message_delete;
mod message_edit; mod message_edit;
mod message_fetch; mod message_fetch;
@@ -16,6 +18,7 @@ pub fn routes() -> Vec<Route> {
routes![ routes![
fetch_channel::req, fetch_channel::req,
delete_channel::req, delete_channel::req,
edit_channel::req,
message_send::req, message_send::req,
message_query::req, message_query::req,
message_query_stale::req, message_query_stale::req,
@@ -24,6 +27,7 @@ pub fn routes() -> Vec<Route> {
message_delete::req, message_delete::req,
group_create::req, group_create::req,
group_add_member::req, group_add_member::req,
group_remove_member::req group_remove_member::req,
join_call::req,
] ]
} }
+14 -13
View File
@@ -28,21 +28,22 @@ pub async fn req(session: Session, user: Option<User>, data: Json<Data>) -> Resu
.map_err(|error| Error::FailedValidation { error })?; .map_err(|error| Error::FailedValidation { error })?;
if User::is_username_taken(&data.username).await? { if User::is_username_taken(&data.username).await? {
return Err(Error::UsernameTaken) return Err(Error::UsernameTaken);
} }
get_collection("users").insert_one( get_collection("users")
doc! { .insert_one(
"_id": session.user_id, doc! {
"username": &data.username "_id": session.user_id,
}, "username": &data.username
None, },
) None,
.await )
.map_err(|_| Error::DatabaseError { .await
operation: "insert_one", .map_err(|_| Error::DatabaseError {
with: "user", operation: "insert_one",
})?; with: "user",
})?;
Ok(()) Ok(())
} }
+9 -3
View File
@@ -1,6 +1,6 @@
use crate::util::variables::{ use crate::util::variables::{
AUTUMN_URL, DISABLE_REGISTRATION, EXTERNAL_WS_URL, HCAPTCHA_SITEKEY, INVITE_ONLY, USE_AUTUMN, APP_URL, AUTUMN_URL, DISABLE_REGISTRATION, EXTERNAL_WS_URL, HCAPTCHA_SITEKEY, INVITE_ONLY,
USE_EMAIL, USE_HCAPTCHA, VAPID_PUBLIC_KEY, USE_AUTUMN, USE_EMAIL, USE_HCAPTCHA, USE_VOSO, VAPID_PUBLIC_KEY, VOSO_URL, VOSO_WS_HOST,
}; };
use mongodb::bson::doc; use mongodb::bson::doc;
@@ -9,7 +9,7 @@ use rocket_contrib::json::JsonValue;
#[get("/")] #[get("/")]
pub async fn root() -> JsonValue { pub async fn root() -> JsonValue {
json!({ json!({
"revolt": "0.3.3-alpha.7", "revolt": "0.4.0-alpha.6",
"features": { "features": {
"registration": !*DISABLE_REGISTRATION, "registration": !*DISABLE_REGISTRATION,
"captcha": { "captcha": {
@@ -21,9 +21,15 @@ pub async fn root() -> JsonValue {
"autumn": { "autumn": {
"enabled": *USE_AUTUMN, "enabled": *USE_AUTUMN,
"url": *AUTUMN_URL "url": *AUTUMN_URL
},
"voso": {
"enabled": *USE_VOSO,
"url": *VOSO_URL,
"ws": *VOSO_WS_HOST
} }
}, },
"ws": *EXTERNAL_WS_URL, "ws": *EXTERNAL_WS_URL,
"app": *APP_URL,
"vapid": *VAPID_PUBLIC_KEY "vapid": *VAPID_PUBLIC_KEY
}) })
} }
+67
View File
@@ -0,0 +1,67 @@
use crate::database::*;
use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result};
use mongodb::bson::doc;
use rauth::auth::{Auth, Session};
use regex::Regex;
use rocket::State;
use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize};
use validator::Validate;
// ! FIXME: should be global somewhere; maybe use config(?)
lazy_static! {
static ref RE_USERNAME: Regex = Regex::new(r"^[a-zA-Z0-9_.]+$").unwrap();
}
#[derive(Validate, Serialize, Deserialize)]
pub struct Data {
#[validate(length(min = 2, max = 32), regex = "RE_USERNAME")]
username: Option<String>,
#[validate(length(min = 8, max = 72))]
password: String,
}
#[patch("/<_ignore_id>/username", data = "<data>")]
pub async fn req(
auth: State<'_, Auth>,
session: Session,
user: User,
data: Json<Data>,
_ignore_id: String,
) -> Result<()> {
data.validate()
.map_err(|error| Error::FailedValidation { error })?;
auth.verify_password(&session, data.password.clone())
.await
.map_err(|_| Error::InvalidCredentials)?;
let mut set = doc! {};
if let Some(username) = &data.username {
if User::is_username_taken(&username).await? {
return Err(Error::UsernameTaken);
}
set.insert("username", username.clone());
}
get_collection("users")
.update_one(doc! { "_id": &user.id }, doc! { "$set": set }, None)
.await
.map_err(|_| Error::DatabaseError {
operation: "update_one",
with: "user",
})?;
ClientboundNotification::UserUpdate {
id: user.id.clone(),
data: json!(data.0),
}
.publish(user.id.clone())
.await
.ok();
Ok(())
}
+41
View File
@@ -0,0 +1,41 @@
use crate::database::*;
use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result};
use mongodb::bson::{doc, to_document};
use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize};
use validator::Validate;
#[derive(Validate, Serialize, Deserialize)]
pub struct Data {
#[serde(skip_serializing_if = "Option::is_none")]
status: Option<UserStatus>,
#[serde(skip_serializing_if = "Option::is_none")]
profile: Option<UserProfile>,
}
#[patch("/<_ignore_id>", data = "<data>")]
pub async fn req(user: User, data: Json<Data>, _ignore_id: String) -> Result<()> {
data.validate()
.map_err(|error| Error::FailedValidation { error })?;
get_collection("users")
.update_one(
doc! { "_id": &user.id },
doc! { "$set": to_document(&data.0).map_err(|_| Error::DatabaseError { operation: "to_document", with: "data" })? },
None
)
.await
.map_err(|_| Error::DatabaseError { operation: "update_one", with: "user" })?;
ClientboundNotification::UserUpdate {
id: user.id.clone(),
data: json!(data.0),
}
.publish(user.id.clone())
.await
.ok();
Ok(())
}
+24
View File
@@ -0,0 +1,24 @@
use crate::database::*;
use crate::util::result::{Error, Result};
use mongodb::bson::doc;
use rocket_contrib::json::JsonValue;
#[get("/<target>/profile")]
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
let target = target.fetch_user().await?;
let perm = permissions::PermissionCalculator::new(&user)
.with_user(&target)
.for_user_given()
.await?;
if !perm.get_view_profile() {
Err(Error::MissingPermission)?
}
if target.profile.is_some() {
Ok(json!(target.profile))
} else {
Ok(json!({}))
}
}
+6
View File
@@ -2,7 +2,10 @@ use rocket::Route;
mod add_friend; mod add_friend;
mod block_user; mod block_user;
mod change_username;
mod edit_user;
mod fetch_dms; mod fetch_dms;
mod fetch_profile;
mod fetch_relationship; mod fetch_relationship;
mod fetch_relationships; mod fetch_relationships;
mod fetch_user; mod fetch_user;
@@ -17,8 +20,11 @@ pub fn routes() -> Vec<Route> {
routes![ routes![
// User Information // User Information
fetch_user::req, fetch_user::req,
edit_user::req,
change_username::req,
get_default_avatar::req, get_default_avatar::req,
get_avatar::req, get_avatar::req,
fetch_profile::req,
// Direct Messaging // Direct Messaging
fetch_dms::req, fetch_dms::req,
open_dm::req, open_dm::req,
+6
View File
@@ -67,8 +67,12 @@ pub enum Error {
MissingPermission, MissingPermission,
#[snafu(display("Operation cannot be performed on this object."))] #[snafu(display("Operation cannot be performed on this object."))]
InvalidOperation, InvalidOperation,
#[snafu(display("Email or password is incorrect."))]
InvalidCredentials,
#[snafu(display("Already created an object with this nonce."))] #[snafu(display("Already created an object with this nonce."))]
DuplicateNonce, DuplicateNonce,
#[snafu(display("Voso is not enabled on this instance."))]
VosoUnavailable,
#[snafu(display("This request had no effect."))] #[snafu(display("This request had no effect."))]
NoEffect, NoEffect,
} }
@@ -106,7 +110,9 @@ impl<'r> Responder<'r, 'static> for Error {
Error::MissingPermission => Status::Forbidden, Error::MissingPermission => Status::Forbidden,
Error::InvalidOperation => Status::BadRequest, Error::InvalidOperation => Status::BadRequest,
Error::TooManyIds => Status::BadRequest, Error::TooManyIds => Status::BadRequest,
Error::InvalidCredentials => Status::Forbidden,
Error::DuplicateNonce => Status::Conflict, Error::DuplicateNonce => Status::Conflict,
Error::VosoUnavailable => Status::BadRequest,
Error::NoEffect => Status::Ok, Error::NoEffect => Status::Ok,
}; };
+18 -1
View File
@@ -12,11 +12,19 @@ lazy_static! {
pub static ref PUBLIC_URL: String = pub static ref PUBLIC_URL: String =
env::var("REVOLT_PUBLIC_URL").expect("Missing REVOLT_PUBLIC_URL environment variable."); env::var("REVOLT_PUBLIC_URL").expect("Missing REVOLT_PUBLIC_URL environment variable.");
pub static ref APP_URL: String = pub static ref APP_URL: String =
env::var("REVOLT_APP_URL").unwrap_or_else(|_| "https://app.revolt.chat".to_string()); env::var("REVOLT_APP_URL").expect("Missing REVOLT_APP_URL environment variable.");
pub static ref EXTERNAL_WS_URL: String = pub static ref EXTERNAL_WS_URL: String =
env::var("REVOLT_EXTERNAL_WS_URL").expect("Missing REVOLT_EXTERNAL_WS_URL environment variable."); env::var("REVOLT_EXTERNAL_WS_URL").expect("Missing REVOLT_EXTERNAL_WS_URL environment variable.");
pub static ref AUTUMN_URL: String = pub static ref AUTUMN_URL: String =
env::var("AUTUMN_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string()); env::var("AUTUMN_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string());
pub static ref VOSO_URL: String =
env::var("VOSO_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string());
pub static ref VOSO_WS_HOST: String =
env::var("VOSO_WS_HOST").unwrap_or_else(|_| "wss://example.com".to_string());
pub static ref VOSO_MANAGE_TOKEN: String =
env::var("VOSO_MANAGE_TOKEN").unwrap_or_else(|_| "0".to_string());
pub static ref HCAPTCHA_KEY: String = pub static ref HCAPTCHA_KEY: String =
env::var("REVOLT_HCAPTCHA_KEY").unwrap_or_else(|_| "0x0000000000000000000000000000000000000000".to_string()); env::var("REVOLT_HCAPTCHA_KEY").unwrap_or_else(|_| "0x0000000000000000000000000000000000000000".to_string());
pub static ref HCAPTCHA_SITEKEY: String = pub static ref HCAPTCHA_SITEKEY: String =
@@ -39,6 +47,7 @@ lazy_static! {
pub static ref USE_HCAPTCHA: bool = env::var("REVOLT_HCAPTCHA_KEY").is_ok(); pub static ref USE_HCAPTCHA: bool = env::var("REVOLT_HCAPTCHA_KEY").is_ok();
pub static ref USE_PROMETHEUS: bool = env::var("REVOLT_ENABLE_PROMETHEUS").map_or(false, |v| v == "1"); pub static ref USE_PROMETHEUS: bool = env::var("REVOLT_ENABLE_PROMETHEUS").map_or(false, |v| v == "1");
pub static ref USE_AUTUMN: bool = env::var("AUTUMN_PUBLIC_URL").is_ok(); pub static ref USE_AUTUMN: bool = env::var("AUTUMN_PUBLIC_URL").is_ok();
pub static ref USE_VOSO: bool = env::var("VOSO_PUBLIC_URL").is_ok() && env::var("VOSO_MANAGE_TOKEN").is_ok();
// SMTP Settings // SMTP Settings
pub static ref SMTP_HOST: String = pub static ref SMTP_HOST: String =
@@ -55,6 +64,14 @@ lazy_static! {
} }
pub fn preflight_checks() { pub fn preflight_checks() {
format!("{}", *APP_URL);
format!("{}", *MONGO_URI);
format!("{}", *PUBLIC_URL);
format!("{}", *EXTERNAL_WS_URL);
format!("{}", *VAPID_PRIVATE_KEY);
format!("{}", *VAPID_PUBLIC_KEY);
if *USE_EMAIL == false { if *USE_EMAIL == false {
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
if !env::var("REVOLT_UNSAFE_NO_EMAIL").map_or(false, |v| v == *"1") { if !env::var("REVOLT_UNSAFE_NO_EMAIL").map_or(false, |v| v == *"1") {