From a1a921bbcb09d708894e9b7181500aae4575096a Mon Sep 17 00:00:00 2001 From: Paul Makles <paulmakles@gmail.com> Date: Mon, 18 Jan 2021 20:26:26 +0000 Subject: [PATCH] Run cargo fmt. --- src/database/entities/channel.rs | 2 +- src/database/entities/message.rs | 20 ++++++----- src/database/guards/reference.rs | 16 ++++----- src/database/guards/user.rs | 2 +- src/database/migrations/scripts.rs | 2 +- src/database/permissions/channel.rs | 20 +++++------ src/database/permissions/mod.rs | 2 +- src/database/permissions/user.rs | 14 ++++---- src/notifications/events.rs | 7 ++-- src/notifications/payload.rs | 29 ++++++++------- src/notifications/subscriptions.rs | 10 +++--- src/notifications/websocket.rs | 37 +++++++++---------- src/routes/channels/delete_channel.rs | 13 ++++--- src/routes/channels/message_fetch.rs | 25 ++++++++----- src/routes/channels/message_send.rs | 19 ++++++---- src/routes/channels/mod.rs | 4 +-- src/routes/users/add_friend.rs | 5 +-- src/routes/users/fetch_user.rs | 2 +- src/routes/users/get_avatar.rs | 52 ++++++++++----------------- 19 files changed, 140 insertions(+), 141 deletions(-) diff --git a/src/database/entities/channel.rs b/src/database/entities/channel.rs index 30e24b7..edf5cbf 100644 --- a/src/database/entities/channel.rs +++ b/src/database/entities/channel.rs @@ -1,7 +1,7 @@ use crate::database::*; +use crate::util::result::{Error, Result}; use mongodb::bson::to_document; use serde::{Deserialize, Serialize}; -use crate::util::result::{Error, Result}; #[derive(Serialize, Deserialize, Debug)] #[serde(tag = "type")] diff --git a/src/database/entities/message.rs b/src/database/entities/message.rs index 8b07194..8cec6ce 100644 --- a/src/database/entities/message.rs +++ b/src/database/entities/message.rs @@ -1,5 +1,9 @@ -use crate::{database::*, notifications::events::ClientboundNotification, util::result::{Error, Result}}; -use mongodb::bson::{DateTime, to_bson}; +use crate::{ + database::*, + notifications::events::ClientboundNotification, + util::result::{Error, Result}, +}; +use mongodb::bson::{to_bson, DateTime}; use serde::{Deserialize, Serialize}; /*#[derive(Serialize, Deserialize, Debug)] @@ -39,13 +43,13 @@ pub struct Message { impl Message { pub async fn send(self) -> Result<()> { 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) .await - .map_err(|_| Error::DatabaseError { operation: "insert_one", with: "messages" })?; - + .map_err(|_| Error::DatabaseError { + operation: "insert_one", + with: "messages", + })?; + let channel = self.channel.clone(); ClientboundNotification::Message(self) .publish(channel) diff --git a/src/database/guards/reference.rs b/src/database/guards/reference.rs index 7f7a651..a90a293 100644 --- a/src/database/guards/reference.rs +++ b/src/database/guards/reference.rs @@ -1,11 +1,11 @@ use crate::database::*; use crate::util::result::{Error, Result}; -use validator::Validate; +use mongodb::bson::{doc, from_bson, from_document, Bson}; use rocket::http::RawStr; use rocket::request::FromParam; -use mongodb::bson::{Bson, doc, from_bson, from_document}; -use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use validator::Validate; #[derive(Validate, Serialize, Deserialize)] pub struct Ref { @@ -33,12 +33,10 @@ impl Ref { })? .ok_or_else(|| Error::UnknownUser)?; - Ok( - from_document::<T>(doc).map_err(|_| Error::DatabaseError { - operation: "from_document", - with: &collection, - })?, - ) + Ok(from_document::<T>(doc).map_err(|_| Error::DatabaseError { + operation: "from_document", + with: &collection, + })?) } pub async fn fetch_user(&self) -> Result<User> { diff --git a/src/database/guards/user.rs b/src/database/guards/user.rs index dc3d7ee..c7363d1 100644 --- a/src/database/guards/user.rs +++ b/src/database/guards/user.rs @@ -1,6 +1,6 @@ use crate::database::*; -use mongodb::bson::{Bson, doc, from_bson, from_document}; +use mongodb::bson::{doc, from_bson, from_document, Bson}; use rauth::auth::Session; use rocket::http::Status; use rocket::request::{self, FromRequest, Outcome, Request}; diff --git a/src/database/migrations/scripts.rs b/src/database/migrations/scripts.rs index b5f411b..64866c0 100644 --- a/src/database/migrations/scripts.rs +++ b/src/database/migrations/scripts.rs @@ -2,7 +2,7 @@ use super::super::{get_collection, get_db}; use crate::rocket::futures::StreamExt; use log::info; -use mongodb::bson::{Bson, doc, from_bson, from_document}; +use mongodb::bson::{doc, from_bson, from_document, Bson}; use mongodb::options::FindOptions; use serde::{Deserialize, Serialize}; diff --git a/src/database/permissions/channel.rs b/src/database/permissions/channel.rs index 37ff81e..7164b3f 100644 --- a/src/database/permissions/channel.rs +++ b/src/database/permissions/channel.rs @@ -23,28 +23,28 @@ pub async fn calculate(user: &User, target: &Channel) -> ChannelPermissions<[u32 match target { Channel::SavedMessages { user: owner, .. } => { if &user.id == owner { - ChannelPermissions([ ChannelPermission::View + ChannelPermission::SendMessage ]) + ChannelPermissions([ChannelPermission::View + ChannelPermission::SendMessage]) } else { - ChannelPermissions([ 0 ]) + ChannelPermissions([0]) } } Channel::DirectMessage { recipients, .. } => { if recipients.iter().find(|x| *x == &user.id).is_some() { - if let Some(recipient) = recipients - .iter() - .find(|x| *x != &user.id) { + if let Some(recipient) = recipients.iter().find(|x| *x != &user.id) { let perms = super::user::calculate(&user, recipient).await; if perms.get_send_message() { - return ChannelPermissions([ ChannelPermission::View + ChannelPermission::SendMessage ]); + return ChannelPermissions([ + ChannelPermission::View + ChannelPermission::SendMessage + ]); } - - return ChannelPermissions([ ChannelPermission::View as u32 ]); + + return ChannelPermissions([ChannelPermission::View as u32]); } } - ChannelPermissions([ 0 ]) + ChannelPermissions([0]) } - _ => unreachable!() + _ => unreachable!(), } } diff --git a/src/database/permissions/mod.rs b/src/database/permissions/mod.rs index 0240b8b..0aea919 100644 --- a/src/database/permissions/mod.rs +++ b/src/database/permissions/mod.rs @@ -1,4 +1,4 @@ -pub mod user; pub mod channel; +pub mod user; pub use user::get_relationship; diff --git a/src/database/permissions/user.rs b/src/database/permissions/user.rs index 54c8dc8..951afe5 100644 --- a/src/database/permissions/user.rs +++ b/src/database/permissions/user.rs @@ -31,20 +31,20 @@ pub async fn calculate(user: &User, target: &str) -> UserPermissions<[u32; 1]> { let mut permissions: u32 = 0; match get_relationship(&user, &target) { RelationshipStatus::Friend => { - return UserPermissions([ UserPermission::Access + UserPermission::SendMessage + UserPermission::Invite ]) + return UserPermissions([UserPermission::Access + + UserPermission::SendMessage + + UserPermission::Invite]) } - RelationshipStatus::Blocked | - RelationshipStatus::BlockedOther => { - return UserPermissions([ UserPermission::Access as u32 ]) + RelationshipStatus::Blocked | RelationshipStatus::BlockedOther => { + return UserPermissions([UserPermission::Access as u32]) } - RelationshipStatus::Incoming | - RelationshipStatus::Outgoing => { + RelationshipStatus::Incoming | RelationshipStatus::Outgoing => { permissions = UserPermission::Access as u32; } _ => {} } - UserPermissions([ permissions ]) + UserPermissions([permissions]) } pub fn get_relationship(a: &User, b: &str) -> RelationshipStatus { diff --git a/src/notifications/events.rs b/src/notifications/events.rs index cf4f0e4..eeb03a9 100644 --- a/src/notifications/events.rs +++ b/src/notifications/events.rs @@ -33,7 +33,7 @@ pub enum ClientboundNotification { Authenticated, Ready { users: Vec<User>, - channels: Vec<Channel> + channels: Vec<Channel>, }, Message(Message), @@ -93,7 +93,6 @@ pub enum ClientboundNotification { GuildDelete { id: String, },*/ - UserRelationship { id: String, user: String, @@ -102,8 +101,8 @@ pub enum ClientboundNotification { UserPresence { id: String, - online: bool - } + online: bool, + }, } impl ClientboundNotification { diff --git a/src/notifications/payload.rs b/src/notifications/payload.rs index 7ec7629..c3b2559 100644 --- a/src/notifications/payload.rs +++ b/src/notifications/payload.rs @@ -4,7 +4,10 @@ use crate::{ util::result::{Error, Result}, }; use futures::StreamExt; -use mongodb::{bson::{Bson, doc, from_bson, from_document}, options::FindOptions}; +use mongodb::{ + bson::{doc, from_bson, from_document, Bson}, + options::FindOptions, +}; use super::websocket::is_online; @@ -36,11 +39,10 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> { while let Some(result) = cursor.next().await { if let Ok(doc) = result { - let mut user: User = - from_document(doc).map_err(|_| Error::DatabaseError { - operation: "from_document", - with: "user", - })?; + let mut user: User = from_document(doc).map_err(|_| Error::DatabaseError { + operation: "from_document", + with: "user", + })?; user.relationship = Some( relationships @@ -77,24 +79,21 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> { } ] }, - None + None, ) .await .map_err(|_| Error::DatabaseError { operation: "find", with: "channels", })?; - + let mut channels = vec![]; while let Some(result) = cursor.next().await { if let Ok(doc) = result { - channels.push( - from_document(doc) - .map_err(|_| Error::DatabaseError { - operation: "from_document", - with: "channel", - })? - ); + channels.push(from_document(doc).map_err(|_| Error::DatabaseError { + operation: "from_document", + with: "channel", + })?); } } diff --git a/src/notifications/subscriptions.rs b/src/notifications/subscriptions.rs index 0c9105c..345f370 100644 --- a/src/notifications/subscriptions.rs +++ b/src/notifications/subscriptions.rs @@ -1,9 +1,9 @@ use crate::database::*; +use super::hive::get_hive; use futures::StreamExt; -use mongodb::bson::doc; use hive_pubsub::PubSub; -use super::hive::get_hive; +use mongodb::bson::doc; use mongodb::options::FindOptions; pub async fn generate_subscriptions(user: &User) -> Result<(), String> { @@ -35,13 +35,11 @@ pub async fn generate_subscriptions(user: &User) -> Result<(), String> { } ] }, - FindOptions::builder() - .projection(doc! { "_id": 1 }) - .build() + FindOptions::builder().projection(doc! { "_id": 1 }).build(), ) .await .map_err(|_| "Failed to fetch channels.".to_string())?; - + while let Some(result) = cursor.next().await { if let Ok(doc) = result { hive.subscribe(user.id.clone(), doc.get_str("_id").unwrap().to_string())?; diff --git a/src/notifications/websocket.rs b/src/notifications/websocket.rs index e218323..a9651b6 100644 --- a/src/notifications/websocket.rs +++ b/src/notifications/websocket.rs @@ -64,7 +64,7 @@ async fn accept(stream: TcpStream) { }; let session: Arc<Mutex<Option<Session>>> = Arc::new(Mutex::new(None)); - let mutex_generator = || { session.clone() }; + let mutex_generator = || session.clone(); let fwd = rx.map(Ok).forward(write); let incoming = read.try_for_each(async move |msg| { let mutex = mutex_generator(); @@ -79,22 +79,17 @@ async fn accept(stream: TcpStream) { send(ClientboundNotification::Error( WebSocketError::AlreadyAuthenticated, )); - - return Ok(()) + + return Ok(()); } } if let Ok(validated_session) = Auth::new(get_collection("accounts")) .verify_session(new_session) - .await { + .await + { let id = validated_session.user_id.clone(); - if let Ok(user) = ( - Ref { - id: id.clone() - } - ) - .fetch_user() - .await { + if let Ok(user) = (Ref { id: id.clone() }).fetch_user().await { let was_online = is_online(&id); { match USERS.write() { @@ -103,10 +98,12 @@ async fn accept(stream: TcpStream) { } Err(_) => { send(ClientboundNotification::Error( - WebSocketError::InternalError { at: "Writing users map.".to_string() }, + WebSocketError::InternalError { + at: "Writing users map.".to_string(), + }, )); - return Ok(()) + return Ok(()); } } } @@ -115,10 +112,12 @@ async fn accept(stream: TcpStream) { if let Err(_) = subscriptions::generate_subscriptions(&user).await { send(ClientboundNotification::Error( - WebSocketError::InternalError { at: "Generating subscriptions.".to_string() }, + WebSocketError::InternalError { + at: "Generating subscriptions.".to_string(), + }, )); - return Ok(()) + return Ok(()); } send(ClientboundNotification::Authenticated); @@ -130,7 +129,7 @@ async fn accept(stream: TcpStream) { if !was_online { ClientboundNotification::UserPresence { id: id.clone(), - online: true + online: true, } .publish(id) .await @@ -139,10 +138,12 @@ async fn accept(stream: TcpStream) { } Err(_) => { send(ClientboundNotification::Error( - WebSocketError::InternalError { at: "Generating payload.".to_string() }, + WebSocketError::InternalError { + at: "Generating payload.".to_string(), + }, )); - return Ok(()) + return Ok(()); } } } else { diff --git a/src/routes/channels/delete_channel.rs b/src/routes/channels/delete_channel.rs index 8704d81..aea5071 100644 --- a/src/routes/channels/delete_channel.rs +++ b/src/routes/channels/delete_channel.rs @@ -25,13 +25,16 @@ pub async fn req(user: User, target: Ref) -> Result<()> { "active": false } }, - None + None, ) .await - .map_err(|_| Error::DatabaseError { operation: "update_one", with: "channel" })?; - + .map_err(|_| Error::DatabaseError { + operation: "update_one", + with: "channel", + })?; + Ok(()) - }, - _ => unimplemented!() + } + _ => unimplemented!(), } } diff --git a/src/routes/channels/message_fetch.rs b/src/routes/channels/message_fetch.rs index 2c005fd..0bb1284 100644 --- a/src/routes/channels/message_fetch.rs +++ b/src/routes/channels/message_fetch.rs @@ -2,11 +2,14 @@ use crate::database::*; use crate::util::result::{Error, Result}; use futures::StreamExt; -use validator::Validate; +use mongodb::{ + bson::{doc, from_document}, + options::FindOptions, +}; use rocket::request::Form; -use serde::{Serialize, Deserialize}; use rocket_contrib::json::JsonValue; -use mongodb::{bson::{doc, from_document}, options::FindOptions}; +use serde::{Deserialize, Serialize}; +use validator::Validate; #[derive(Validate, Serialize, Deserialize, FromForm)] pub struct Options { @@ -20,7 +23,8 @@ pub struct Options { #[get("/<target>/messages?<options..>")] pub async fn req(user: User, target: Ref, options: Form<Options>) -> Result<JsonValue> { - options.validate() + options + .validate() .map_err(|error| Error::FailedValidation { error })?; let target = target.fetch_channel().await?; @@ -51,14 +55,19 @@ pub async fn req(user: User, target: Ref, options: Form<Options>) -> Result<Json .build(), ) .await - .map_err(|_| Error::DatabaseError { operation: "find", with: "messages" })?; - + .map_err(|_| Error::DatabaseError { + operation: "find", + with: "messages", + })?; + let mut messages = vec![]; while let Some(result) = cursor.next().await { if let Ok(doc) = result { messages.push( - from_document::<Message>(doc) - .map_err(|_| Error::DatabaseError { operation: "from_document", with: "message" })? + from_document::<Message>(doc).map_err(|_| Error::DatabaseError { + operation: "from_document", + with: "message", + })?, ); } } diff --git a/src/routes/channels/message_send.rs b/src/routes/channels/message_send.rs index 472112d..6fbb340 100644 --- a/src/routes/channels/message_send.rs +++ b/src/routes/channels/message_send.rs @@ -1,11 +1,11 @@ use crate::database::*; use crate::util::result::{Error, Result}; -use serde::{Serialize, Deserialize}; -use rocket_contrib::json::Json; -use validator::Validate; use mongodb::bson::doc; +use rocket_contrib::json::Json; +use serde::{Deserialize, Serialize}; use ulid::Ulid; +use validator::Validate; #[derive(Validate, Serialize, Deserialize)] pub struct Data { @@ -18,7 +18,8 @@ pub struct Data { #[post("/<target>/messages", data = "<message>")] pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<()> { - message.validate() + message + .validate() .map_err(|error| Error::FailedValidation { error })?; let target = target.fetch_channel().await?; @@ -33,11 +34,15 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<()> { doc! { "nonce": &message.nonce }, - None + None, ) .await - .map_err(|_| Error::DatabaseError { operation: "find_one", with: "message" })? - .is_some() { + .map_err(|_| Error::DatabaseError { + operation: "find_one", + with: "message", + })? + .is_some() + { Err(Error::AlreadySentMessage)? } diff --git a/src/routes/channels/mod.rs b/src/routes/channels/mod.rs index 3942505..bceb115 100644 --- a/src/routes/channels/mod.rs +++ b/src/routes/channels/mod.rs @@ -1,9 +1,9 @@ use rocket::Route; -mod fetch_channel; mod delete_channel; -mod message_send; +mod fetch_channel; mod message_fetch; +mod message_send; pub fn routes() -> Vec<Route> { routes![ diff --git a/src/routes/users/add_friend.rs b/src/routes/users/add_friend.rs index 1af0a85..dfbae93 100644 --- a/src/routes/users/add_friend.rs +++ b/src/routes/users/add_friend.rs @@ -31,10 +31,7 @@ pub async fn req(user: User, username: String) -> Result<JsonValue> { with: "user", })?; - match get_relationship( - &user, - &target_id, - ) { + match get_relationship(&user, &target_id) { RelationshipStatus::User => return Err(Error::NoEffect), RelationshipStatus::Friend => return Err(Error::AlreadyFriends), RelationshipStatus::Outgoing => return Err(Error::AlreadySentRequest), diff --git a/src/routes/users/fetch_user.rs b/src/routes/users/fetch_user.rs index 4ae40aa..8c4b91c 100644 --- a/src/routes/users/fetch_user.rs +++ b/src/routes/users/fetch_user.rs @@ -1,5 +1,5 @@ -use crate::{database::*, notifications::websocket::is_online}; use crate::util::result::{Error, Result}; +use crate::{database::*, notifications::websocket::is_online}; use rocket_contrib::json::JsonValue; diff --git a/src/routes/users/get_avatar.rs b/src/routes/users/get_avatar.rs index c9666c6..4e5859f 100644 --- a/src/routes/users/get_avatar.rs +++ b/src/routes/users/get_avatar.rs @@ -6,38 +6,24 @@ use crate::database::Ref; #[get("/<target>/avatar")] pub async fn req(target: Ref) -> Option<NamedFile> { match target.id.chars().nth(25).unwrap() { - '0' | - '1' | - '2' | - '3' | - '4' | - '5' | - '6' | - '7' => NamedFile::open(Path::new("assets/user_red.png")).await.ok(), - '8' | - '9' | - 'A' | - 'C' | - 'B' | - 'D' | - 'E' | - 'F' => NamedFile::open(Path::new("assets/user_green.png")).await.ok(), - 'G' | - 'H' | - 'J' | - 'K' | - 'M' | - 'N' | - 'P' | - 'Q' => NamedFile::open(Path::new("assets/user_blue.png")).await.ok(), - 'R' | - 'S' | - 'T' | - 'V' | - 'W' | - 'X' | - 'Y' | - 'Z' => NamedFile::open(Path::new("assets/user_yellow.png")).await.ok(), - _ => unreachable!() + '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' => { + NamedFile::open(Path::new("assets/user_red.png")).await.ok() + } + '8' | '9' | 'A' | 'C' | 'B' | 'D' | 'E' | 'F' => { + NamedFile::open(Path::new("assets/user_green.png")) + .await + .ok() + } + 'G' | 'H' | 'J' | 'K' | 'M' | 'N' | 'P' | 'Q' => { + NamedFile::open(Path::new("assets/user_blue.png")) + .await + .ok() + } + 'R' | 'S' | 'T' | 'V' | 'W' | 'X' | 'Y' | 'Z' => { + NamedFile::open(Path::new("assets/user_yellow.png")) + .await + .ok() + } + _ => unreachable!(), } } -- GitLab