Format code.

This commit is contained in:
Paul
2021-04-03 14:44:01 +01:00
parent 9492e145f9
commit 7f5d6f2312
17 changed files with 170 additions and 154 deletions

View File

@@ -20,42 +20,29 @@ use web_push::{
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")] #[serde(tag = "type")]
pub enum MessageEmbed { pub enum MessageEmbed {
Dummy Dummy,
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")] #[serde(tag = "type")]
pub enum SystemMessage { pub enum SystemMessage {
#[serde(rename = "text")] #[serde(rename = "text")]
Text { Text { content: String },
content: String
},
#[serde(rename = "user_added")] #[serde(rename = "user_added")]
UserAdded { UserAdded { id: String, by: String },
id: String,
by: String
},
#[serde(rename = "user_remove")] #[serde(rename = "user_remove")]
UserRemove { UserRemove { id: String, by: String },
id: String,
by: String
},
#[serde(rename = "user_left")] #[serde(rename = "user_left")]
UserLeft { UserLeft { id: String },
id: String
},
#[serde(rename = "channel_renamed")] #[serde(rename = "channel_renamed")]
ChannelRenamed { ChannelRenamed { name: String, by: String },
name: String,
by: String
},
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)] #[serde(untagged)]
pub enum Content { pub enum Content {
Text(String), Text(String),
SystemMessage(SystemMessage) SystemMessage(SystemMessage),
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
@@ -87,7 +74,7 @@ impl Message {
content, content,
attachment: None, attachment: None,
edited: None, edited: None,
embeds: None embeds: None,
} }
} }
@@ -174,7 +161,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": {
@@ -189,8 +176,7 @@ impl Message {
.build(), .build(),
) )
.await .await
.unwrap(); // !FIXME {
let mut subscriptions = vec![]; let mut subscriptions = vec![];
while let Some(result) = cursor.next().await { while let Some(result) = cursor.next().await {
if let Ok(doc) = result { if let Ok(doc) = result {
@@ -202,7 +188,8 @@ impl Message {
let p256dh = sub.get_str("p256dh").unwrap().to_string(); let p256dh = sub.get_str("p256dh").unwrap().to_string();
let auth = sub.get_str("auth").unwrap().to_string(); let auth = sub.get_str("auth").unwrap().to_string();
subscriptions.push(SubscriptionInfo::new(endpoint, p256dh, auth)); subscriptions
.push(SubscriptionInfo::new(endpoint, p256dh, auth));
} }
} }
} }
@@ -212,7 +199,8 @@ impl Message {
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();
@@ -226,6 +214,7 @@ impl Message {
client.send(m).await.ok(); client.send(m).await.ok();
} }
} }
}
Ok(()) Ok(())
} }
@@ -255,7 +244,7 @@ impl Message {
"deleted": true "deleted": true
} }
}, },
None None,
) )
.await .await
.map_err(|_| Error::DatabaseError { .map_err(|_| Error::DatabaseError {

View File

@@ -1,12 +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 validator::Validate;
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 {
@@ -37,14 +37,14 @@ pub enum Badge {
pub struct UserStatus { pub struct UserStatus {
#[validate(length(min = 1, max = 128))] #[validate(length(min = 1, max = 128))]
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
text: Option<String> text: Option<String>,
} }
#[derive(Validate, Serialize, Deserialize, Debug)] #[derive(Validate, Serialize, Deserialize, Debug)]
pub struct UserProfile { pub struct UserProfile {
#[validate(length(min = 1, max = 2000))] #[validate(length(min = 1, max = 2000))]
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
content: Option<String> content: Option<String>,
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
@@ -101,7 +101,7 @@ impl User {
/// 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 == "revolt" && username == "admin" {
return Ok(true) return Ok(true);
} }
if get_collection("users") if get_collection("users")

View File

@@ -56,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 + ChannelPermission::VoiceCall); return Ok(ChannelPermission::View
+ ChannelPermission::SendMessage
+ ChannelPermission::VoiceCall);
} }
return Ok(ChannelPermission::View as u32); return Ok(ChannelPermission::View as u32);
@@ -71,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 + ChannelPermission::ManageChannel + ChannelPermission::VoiceCall) Ok(ChannelPermission::View
+ ChannelPermission::SendMessage
+ ChannelPermission::ManageChannel
+ ChannelPermission::VoiceCall)
} else { } else {
Ok(0) Ok(0)
} }

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,11 +67,11 @@ pub enum ClientboundNotification {
}, },
ChannelStartTyping { ChannelStartTyping {
id: String, id: String,
user: String user: String,
}, },
ChannelStopTyping { ChannelStopTyping {
id: String, id: String,
user: String user: String,
}, },
UserUpdate { UserUpdate {

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

View File

@@ -102,7 +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(),
Content::SystemMessage(SystemMessage::UserLeft { id: user.id }) Content::SystemMessage(SystemMessage::UserLeft { id: user.id }),
) )
.publish(&target) .publish(&target)
.await .await

View File

@@ -1,11 +1,11 @@
use crate::database::*; use crate::database::*;
use crate::util::result::{Error, Result};
use crate::notifications::events::ClientboundNotification; use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result};
use mongodb::bson::{doc, to_document}; use mongodb::bson::{doc, to_document};
use validator::Validate;
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
use validator::Validate;
#[derive(Validate, Serialize, Deserialize)] #[derive(Validate, Serialize, Deserialize)]
pub struct Data { pub struct Data {
@@ -23,7 +23,7 @@ pub async fn req(user: User, target: Ref, info: Json<Data>) -> Result<()> {
.map_err(|error| Error::FailedValidation { error })?; .map_err(|error| Error::FailedValidation { error })?;
if info.name.is_none() && info.description.is_none() { if info.name.is_none() && info.description.is_none() {
return Ok(()) return Ok(());
} }
let target = target.fetch_channel().await?; let target = target.fetch_channel().await?;
@@ -49,7 +49,7 @@ pub async fn req(user: User, target: Ref, info: Json<Data>) -> Result<()> {
ClientboundNotification::ChannelUpdate { ClientboundNotification::ChannelUpdate {
id: id.clone(), id: id.clone(),
data: json!(info.0) data: json!(info.0),
} }
.publish(id.clone()) .publish(id.clone())
.await .await
@@ -59,7 +59,10 @@ pub async fn req(user: User, target: Ref, info: Json<Data>) -> Result<()> {
Message::create( Message::create(
"00000000000000000000000000".to_string(), "00000000000000000000000000".to_string(),
id.clone(), id.clone(),
Content::SystemMessage(SystemMessage::ChannelRenamed { name: name.clone(), by: user.id }) Content::SystemMessage(SystemMessage::ChannelRenamed {
name: name.clone(),
by: user.id,
}),
) )
.publish(&target) .publish(&target)
.await .await
@@ -68,6 +71,6 @@ pub async fn req(user: User, target: Ref, info: Json<Data>) -> Result<()> {
Ok(()) Ok(())
} }
_ => Err(Error::InvalidOperation) _ => Err(Error::InvalidOperation),
} }
} }

View File

@@ -59,7 +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(),
Content::SystemMessage(SystemMessage::UserAdded { id: member.id, by: user.id }) Content::SystemMessage(SystemMessage::UserAdded {
id: member.id,
by: user.id,
}),
) )
.publish(&channel) .publish(&channel)
.await .await

View File

@@ -56,7 +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(),
Content::SystemMessage(SystemMessage::UserRemove { id: member.id, by: user.id }) Content::SystemMessage(SystemMessage::UserRemove {
id: member.id,
by: user.id,
}),
) )
.publish(&channel) .publish(&channel)
.await .await

View File

@@ -1,19 +1,19 @@
use crate::database::*; use crate::database::*;
use crate::util::result::{Error, Result}; use crate::util::result::{Error, Result};
use crate::util::variables::{USE_VOSO, VOSO_URL, VOSO_MANAGE_TOKEN}; use crate::util::variables::{USE_VOSO, VOSO_MANAGE_TOKEN, VOSO_URL};
use serde::{Serialize, Deserialize};
use rocket_contrib::json::JsonValue; use rocket_contrib::json::JsonValue;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct CreateUserResponse { struct CreateUserResponse {
token: String token: String,
} }
#[post("/<target>/join_call")] #[post("/<target>/join_call")]
pub async fn req(user: User, target: Ref) -> Result<JsonValue> { pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
if !*USE_VOSO { if !*USE_VOSO {
return Err(Error::VosoUnavailable) return Err(Error::VosoUnavailable);
} }
let target = target.fetch_channel().await?; let target = target.fetch_channel().await?;
@@ -23,7 +23,7 @@ pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
.await?; .await?;
if !perm.get_voice_call() { if !perm.get_voice_call() {
return Err(Error::MissingPermission) return Err(Error::MissingPermission);
} }
// To join a call: // To join a call:
@@ -32,38 +32,50 @@ pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let result = client let result = client
.get(&format!("{}/room/{}", *VOSO_URL, target.id())) .get(&format!("{}/room/{}", *VOSO_URL, target.id()))
.header(reqwest::header::AUTHORIZATION, VOSO_MANAGE_TOKEN.to_string()) .header(
reqwest::header::AUTHORIZATION,
VOSO_MANAGE_TOKEN.to_string(),
)
.send() .send()
.await; .await;
match result { match result {
Err(_) => return Err(Error::VosoUnavailable), Err(_) => return Err(Error::VosoUnavailable),
Ok(result) => { Ok(result) => match result.status() {
match result.status() {
reqwest::StatusCode::OK => (), reqwest::StatusCode::OK => (),
reqwest::StatusCode::NOT_FOUND => { reqwest::StatusCode::NOT_FOUND => {
if let Err(_) = client if let Err(_) = client
.post(&format!("{}/room/{}", *VOSO_URL, target.id())) .post(&format!("{}/room/{}", *VOSO_URL, target.id()))
.header(reqwest::header::AUTHORIZATION, VOSO_MANAGE_TOKEN.to_string()) .header(
reqwest::header::AUTHORIZATION,
VOSO_MANAGE_TOKEN.to_string(),
)
.send() .send()
.await { .await
return Err(Error::VosoUnavailable) {
return Err(Error::VosoUnavailable);
} }
}
_ => return Err(Error::VosoUnavailable),
}, },
_ => return Err(Error::VosoUnavailable)
}
}
} }
// Then create a user for the room. // Then create a user for the room.
if let Ok(response) = client if let Ok(response) = client
.post(&format!("{}/room/{}/user/{}", *VOSO_URL, target.id(), user.id)) .post(&format!(
.header(reqwest::header::AUTHORIZATION, VOSO_MANAGE_TOKEN.to_string()) "{}/room/{}/user/{}",
*VOSO_URL,
target.id(),
user.id
))
.header(
reqwest::header::AUTHORIZATION,
VOSO_MANAGE_TOKEN.to_string(),
)
.send() .send()
.await {
let res: CreateUserResponse = response.json()
.await .await
.map_err(|_| Error::InvalidOperation)?; {
let res: CreateUserResponse = response.json().await.map_err(|_| Error::InvalidOperation)?;
Ok(json!(res)) Ok(json!(res))
} else { } else {

View File

@@ -119,7 +119,7 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
attachment, attachment,
nonce: Some(message.nonce.clone()), nonce: Some(message.nonce.clone()),
edited: None, edited: None,
embeds: None embeds: None,
}; };
msg.clone().publish(&target).await?; msg.clone().publish(&target).await?;

View File

@@ -28,10 +28,11 @@ 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")
.insert_one(
doc! { doc! {
"_id": session.user_id, "_id": session.user_id,
"username": &data.username "username": &data.username

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, APP_URL, AUTUMN_URL, DISABLE_REGISTRATION, EXTERNAL_WS_URL, HCAPTCHA_SITEKEY, INVITE_ONLY,
USE_EMAIL, USE_HCAPTCHA, VAPID_PUBLIC_KEY, USE_VOSO, VOSO_URL, VOSO_WS_HOST USE_AUTUMN, USE_EMAIL, USE_HCAPTCHA, USE_VOSO, VAPID_PUBLIC_KEY, VOSO_URL, VOSO_WS_HOST,
}; };
use mongodb::bson::doc; use mongodb::bson::doc;

View File

@@ -1,14 +1,14 @@
use crate::database::*; use crate::database::*;
use crate::util::result::{Error, Result};
use crate::notifications::events::ClientboundNotification; use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result};
use mongodb::bson::doc;
use rauth::auth::{Auth, Session}; use rauth::auth::{Auth, Session};
use regex::Regex; use regex::Regex;
use mongodb::bson::doc;
use rocket::State; use rocket::State;
use validator::Validate;
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
use validator::Validate;
// ! FIXME: should be global somewhere; maybe use config(?) // ! FIXME: should be global somewhere; maybe use config(?)
lazy_static! { lazy_static! {
@@ -24,7 +24,12 @@ pub struct Data {
} }
#[patch("/username", data = "<data>")] #[patch("/username", data = "<data>")]
pub async fn req(auth: State<'_, Auth>, session: Session, user: User, data: Json<Data>) -> Result<()> { pub async fn req(
auth: State<'_, Auth>,
session: Session,
user: User,
data: Json<Data>,
) -> Result<()> {
data.validate() data.validate()
.map_err(|error| Error::FailedValidation { error })?; .map_err(|error| Error::FailedValidation { error })?;
@@ -35,24 +40,23 @@ pub async fn req(auth: State<'_, Auth>, session: Session, user: User, data: Json
let mut set = doc! {}; let mut set = doc! {};
if let Some(username) = &data.username { if let Some(username) = &data.username {
if User::is_username_taken(&username).await? { if User::is_username_taken(&username).await? {
return Err(Error::UsernameTaken) return Err(Error::UsernameTaken);
} }
set.insert("username", username.clone()); set.insert("username", username.clone());
} }
get_collection("users") get_collection("users")
.update_one( .update_one(doc! { "_id": &user.id }, doc! { "$set": set }, None)
doc! { "_id": &user.id },
doc! { "$set": set },
None
)
.await .await
.map_err(|_| Error::DatabaseError { operation: "update_one", with: "user" })?; .map_err(|_| Error::DatabaseError {
operation: "update_one",
with: "user",
})?;
ClientboundNotification::UserUpdate { ClientboundNotification::UserUpdate {
id: user.id.clone(), id: user.id.clone(),
data: json!(data.0) data: json!(data.0),
} }
.publish(user.id.clone()) .publish(user.id.clone())
.await .await

View File

@@ -1,18 +1,18 @@
use crate::database::*; use crate::database::*;
use crate::util::result::{Error, Result};
use crate::notifications::events::ClientboundNotification; use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result};
use mongodb::bson::{doc, to_document}; use mongodb::bson::{doc, to_document};
use validator::Validate;
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
use validator::Validate;
#[derive(Validate, Serialize, Deserialize)] #[derive(Validate, Serialize, Deserialize)]
pub struct Data { pub struct Data {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
status: Option<UserStatus>, status: Option<UserStatus>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
profile: Option<UserProfile> profile: Option<UserProfile>,
} }
#[patch("/", data = "<data>")] #[patch("/", data = "<data>")]
@@ -31,7 +31,7 @@ pub async fn req(user: User, data: Json<Data>) -> Result<()> {
ClientboundNotification::UserUpdate { ClientboundNotification::UserUpdate {
id: user.id.clone(), id: user.id.clone(),
data: json!(data.0) data: json!(data.0),
} }
.publish(user.id.clone()) .publish(user.id.clone())
.await .await