From d95982fb5466b9cd1a30a1b0f2127a1a2b1ab1da Mon Sep 17 00:00:00 2001
From: Paul Makles <paulmakles@gmail.com>
Date: Tue, 4 Aug 2020 10:19:33 +0200
Subject: [PATCH] Run cargo fmt, add root preflight.

---
 src/database/channel.rs     | 21 ++++++++++----------
 src/database/guild.rs       | 13 +++++++------
 src/database/message.rs     | 12 ++++++------
 src/database/mod.rs         |  8 ++++++--
 src/database/permissions.rs |  2 +-
 src/guards/auth.rs          |  2 +-
 src/main.rs                 |  4 ++--
 src/notifications/state.rs  |  2 +-
 src/routes/account.rs       |  6 ++----
 src/routes/channel.rs       | 38 ++++++++++++++++++-------------------
 src/routes/guild.rs         | 18 +++++++-----------
 src/routes/mod.rs           |  2 +-
 src/routes/root.rs          |  5 +++++
 src/routes/user.rs          | 11 +++--------
 14 files changed, 72 insertions(+), 72 deletions(-)

diff --git a/src/database/channel.rs b/src/database/channel.rs
index 3f520b8..a94a01c 100644
--- a/src/database/channel.rs
+++ b/src/database/channel.rs
@@ -1,11 +1,11 @@
 use super::get_collection;
 
-use serde::{Deserialize, Serialize};
+use lru::LruCache;
+use mongodb::bson::{doc, from_bson, Bson};
+use rocket::http::RawStr;
 use rocket::request::FromParam;
+use serde::{Deserialize, Serialize};
 use std::sync::{Arc, Mutex};
-use mongodb::bson::{Bson, doc, from_bson};
-use rocket::http::RawStr;
-use lru::LruCache;
 
 #[derive(Serialize, Deserialize, Debug, Clone)]
 pub struct LastMessage {
@@ -41,7 +41,8 @@ pub struct Channel {
 }
 
 lazy_static! {
-    static ref CACHE: Arc<Mutex<LruCache<String, Channel>>> = Arc::new(Mutex::new(LruCache::new(4_000_000)));
+    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> {
@@ -63,7 +64,7 @@ pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
             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())
@@ -84,7 +85,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
         if let Ok(mut cache) = CACHE.lock() {
             for gid in ids {
                 let existing = cache.get(gid);
-    
+
                 if let Some(channel) = existing {
                     channels.push((*channel).clone());
                 } else {
@@ -97,7 +98,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
     }
 
     if missing.len() == 0 {
-        return Ok(Some(channels))
+        return Ok(Some(channels));
     }
 
     let col = get_collection("channels");
@@ -109,7 +110,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
                     cache.put(channel.id.clone(), channel.clone());
                     channels.push(channel);
                 } else {
-                    return Err("Failed to deserialize channel!".to_string())
+                    return Err("Failed to deserialize channel!".to_string());
                 }
             } else {
                 return Err("Failed to fetch channel.".to_string());
@@ -148,7 +149,7 @@ impl<'r> FromParam<'r> for Channel {
         let c = Channel {
             id: "potato".to_string(),
             channel_type: 0,
-    
+
             active: None,
             last_message: None,
             description: None,
diff --git a/src/database/guild.rs b/src/database/guild.rs
index 329cbf9..b5968ad 100644
--- a/src/database/guild.rs
+++ b/src/database/guild.rs
@@ -1,11 +1,11 @@
 use super::get_collection;
 
-use serde::{Deserialize, Serialize};
+use lru::LruCache;
+use mongodb::bson::{doc, from_bson, Bson};
+use rocket::http::RawStr;
 use rocket::request::FromParam;
+use serde::{Deserialize, Serialize};
 use std::sync::{Arc, Mutex};
-use mongodb::bson::{Bson, doc, from_bson};
-use rocket::http::RawStr;
-use lru::LruCache;
 
 #[derive(Serialize, Deserialize, Debug, Clone)]
 pub struct MemberRef {
@@ -49,7 +49,8 @@ pub struct Guild {
 }
 
 lazy_static! {
-    static ref CACHE: Arc<Mutex<LruCache<String, Guild>>> = Arc::new(Mutex::new(LruCache::new(4_000_000)));
+    static ref CACHE: Arc<Mutex<LruCache<String, Guild>>> =
+        Arc::new(Mutex::new(LruCache::new(4_000_000)));
 }
 
 pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
@@ -71,7 +72,7 @@ pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
             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())
diff --git a/src/database/message.rs b/src/database/message.rs
index eeac16a..f20d061 100644
--- a/src/database/message.rs
+++ b/src/database/message.rs
@@ -1,15 +1,15 @@
+use super::get_collection;
+use crate::database::channel::Channel;
+use crate::notifications;
 use crate::notifications::events::message::Create;
 use crate::notifications::events::Notification;
 use crate::routes::channel::ChannelType;
-use crate::database::channel::Channel;
-use super::get_collection;
-use crate::notifications;
 
-use mongodb::bson::{doc, to_bson, Bson, DateTime};
-use serde::{Deserialize, Serialize};
-use rocket::request::FromParam;
 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};
 
 #[derive(Serialize, Deserialize, Debug)]
 pub struct PreviousEntry {
diff --git a/src/database/mod.rs b/src/database/mod.rs
index 34e985f..49d688b 100644
--- a/src/database/mod.rs
+++ b/src/database/mod.rs
@@ -1,5 +1,5 @@
-use mongodb::sync::{Client, Collection, Database};
 use mongodb::bson::doc;
+use mongodb::sync::{Client, Collection, Database};
 use std::env;
 
 use once_cell::sync::OnceCell;
@@ -10,7 +10,11 @@ pub fn connect() {
         Client::with_uri_str(&env::var("DB_URI").expect("DB_URI not in environment variables!"))
             .expect("Failed to init db connection.");
 
-    client.database("revolt").collection("migrations").find(doc! { }, None).expect("Failed to get migration data from database.");
+    client
+        .database("revolt")
+        .collection("migrations")
+        .find(doc! {}, None)
+        .expect("Failed to get migration data from database.");
 
     DBCONN.set(client).unwrap();
 }
diff --git a/src/database/permissions.rs b/src/database/permissions.rs
index 52dce26..7c553e0 100644
--- a/src/database/permissions.rs
+++ b/src/database/permissions.rs
@@ -1,6 +1,6 @@
 use super::mutual::has_mutual_connection;
 use crate::database::channel::Channel;
-use crate::database::guild::{Guild, Member, get_member, fetch_guild};
+use crate::database::guild::{fetch_guild, get_member, Guild, Member};
 use crate::database::user::UserRelationship;
 use crate::guards::auth::UserRef;
 
diff --git a/src/guards/auth.rs b/src/guards/auth.rs
index 64a473b..35e9e7a 100644
--- a/src/guards/auth.rs
+++ b/src/guards/auth.rs
@@ -1,4 +1,4 @@
-use mongodb::bson::{Bson, doc, from_bson, Document};
+use mongodb::bson::{doc, from_bson, Bson, Document};
 use mongodb::options::FindOneOptions;
 use rocket::http::{RawStr, Status};
 use rocket::request::{self, FromParam, FromRequest, Request};
diff --git a/src/main.rs b/src/main.rs
index 2170332..0acea35 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -9,11 +9,11 @@ extern crate bitfield;
 #[macro_use]
 extern crate lazy_static;
 
-pub mod notifications;
 pub mod database;
+pub mod email;
 pub mod guards;
+pub mod notifications;
 pub mod routes;
-pub mod email;
 pub mod util;
 
 use dotenv;
diff --git a/src/notifications/state.rs b/src/notifications/state.rs
index 2c5399a..9b063ec 100644
--- a/src/notifications/state.rs
+++ b/src/notifications/state.rs
@@ -1,8 +1,8 @@
 use crate::database;
 use crate::util::vec_to_set;
 
-use mongodb::bson::doc;
 use hashbrown::{HashMap, HashSet};
+use mongodb::bson::doc;
 use mongodb::options::FindOneOptions;
 use once_cell::sync::OnceCell;
 use std::sync::RwLock;
diff --git a/src/routes/account.rs b/src/routes/account.rs
index b8af4a7..124dc5b 100644
--- a/src/routes/account.rs
+++ b/src/routes/account.rs
@@ -4,9 +4,9 @@ use crate::email;
 use crate::util::gen_token;
 
 use bcrypt::{hash, verify};
-use mongodb::bson::{doc, from_bson, Bson};
 use chrono::prelude::*;
 use database::user::User;
+use mongodb::bson::{doc, from_bson, Bson};
 use rocket_contrib::json::Json;
 use serde::{Deserialize, Serialize};
 use ulid::Ulid;
@@ -140,9 +140,7 @@ pub fn verify_email(code: String) -> Response {
 
             email::send_welcome_email(target.to_string(), user.username);
 
-            Response::Redirect(
-                super::Redirect::to("https://app.revolt.chat"),
-            )
+            Response::Redirect(super::Redirect::to("https://app.revolt.chat"))
         }
     } else {
         Response::BadRequest(json!({ "error": "Invalid code." }))
diff --git a/src/routes/channel.rs b/src/routes/channel.rs
index 7dd74cd..5a0a721 100644
--- a/src/routes/channel.rs
+++ b/src/routes/channel.rs
@@ -1,7 +1,7 @@
 use super::Response;
 use crate::database::{
-    self, get_relationship, get_relationship_internal, message::Message, Permission,
-    PermissionCalculator, Relationship, channel::Channel
+    self, channel::Channel, get_relationship, get_relationship_internal, message::Message,
+    Permission, PermissionCalculator, Relationship,
 };
 use crate::guards::auth::UserRef;
 use crate::notifications::{
@@ -10,8 +10,8 @@ use crate::notifications::{
 };
 use crate::util::vec_to_set;
 
-use mongodb::bson::{doc, from_bson, Bson};
 use chrono::prelude::*;
+use mongodb::bson::{doc, from_bson, Bson};
 use mongodb::options::FindOptions;
 use num_enum::TryFromPrimitive;
 use rocket::request::Form;
@@ -145,15 +145,15 @@ pub fn channel(user: UserRef, target: Channel) -> Option<Response> {
                 "description": 1,
                 "owner": 1,
             }) {*/
-                Some(Response::Success(json!({
-                    "id": target.id,
-                    "type": target.channel_type,
-                    "last_message": target.last_message,
-                    "recipients": target.recipients,
-                    "name": target.name,
-                    "owner": target.owner,
-                    "description": target.description,
-                })))
+            Some(Response::Success(json!({
+                "id": target.id,
+                "type": target.channel_type,
+                "last_message": target.last_message,
+                "recipients": target.recipients,
+                "name": target.name,
+                "owner": target.owner,
+                "description": target.description,
+            })))
             /*} else {
                 None
             }*/
@@ -163,13 +163,13 @@ pub fn channel(user: UserRef, target: Channel) -> Option<Response> {
                 "name": 1,
                 "description": 1,
             }) {*/
-                Some(Response::Success(json!({
-                    "id": target.id,
-                    "type": target.channel_type,
-                    "guild": target.guild,
-                    "name": target.name,
-                    "description": target.description,
-                })))
+            Some(Response::Success(json!({
+                "id": target.id,
+                "type": target.channel_type,
+                "guild": target.guild,
+                "name": target.name,
+                "description": target.description,
+            })))
             /*} else {
                 None
             }*/
diff --git a/src/routes/guild.rs b/src/routes/guild.rs
index f39fe80..52f5b4a 100644
--- a/src/routes/guild.rs
+++ b/src/routes/guild.rs
@@ -1,7 +1,9 @@
 use super::channel::ChannelType;
 use super::Response;
-use crate::database::{self, channel::Channel, channel::fetch_channel, Permission, PermissionCalculator};
 use crate::database::guild::{get_invite, get_member, Guild};
+use crate::database::{
+    self, channel::fetch_channel, channel::Channel, Permission, PermissionCalculator,
+};
 use crate::guards::auth::UserRef;
 use crate::notifications::{
     self,
@@ -106,9 +108,7 @@ pub fn guild(user: UserRef, target: Guild) -> Option<Response> {
             let mut channels = vec![];
             for item in results {
                 if let Ok(entry) = item {
-                    if let Ok(channel) =
-                        from_bson(Bson::Document(entry)) as Result<Channel, _>
-                    {
+                    if let Ok(channel) = from_bson(Bson::Document(entry)) as Result<Channel, _> {
                         channels.push(json!({
                             "id": channel.id,
                             "name": channel.name,
@@ -265,11 +265,7 @@ pub struct CreateChannel {
 
 /// create a new channel
 #[post("/<target>/channels", data = "<info>")]
-pub fn create_channel(
-    user: UserRef,
-    target: Guild,
-    info: Json<CreateChannel>,
-) -> Option<Response> {
+pub fn create_channel(user: UserRef, target: Guild, info: Json<CreateChannel>) -> Option<Response> {
     let (permissions, _) = with_permissions!(user, target);
 
     if !permissions.get_manage_channels() {
@@ -451,8 +447,8 @@ pub fn fetch_invite(user: UserRef, code: String) -> Response {
                 } else {
                     Response::NotFound(json!({ "error": "Channel does not exist." }))
                 }
-            },
-            Err(err) => Response::InternalServerError(json!({ "error": err }))
+            }
+            Err(err) => Response::InternalServerError(json!({ "error": err })),
         }
     } else {
         Response::NotFound(json!({ "error": "Failed to fetch invite or code is invalid." }))
diff --git a/src/routes/mod.rs b/src/routes/mod.rs
index c8a8119..499fd89 100644
--- a/src/routes/mod.rs
+++ b/src/routes/mod.rs
@@ -63,7 +63,7 @@ impl<'a> rocket::response::Responder<'a> for Permission {
 
 pub fn mount(rocket: Rocket) -> Rocket {
     rocket
-        .mount("/", routes![root::root, root::teapot])
+        .mount("/", routes![root::root, root::root_preflight, root::teapot])
         .mount(
             "/account",
             routes![
diff --git a/src/routes/root.rs b/src/routes/root.rs
index 3ab67b8..d1ea0f3 100644
--- a/src/routes/root.rs
+++ b/src/routes/root.rs
@@ -10,6 +10,11 @@ pub fn root() -> Response {
     }))
 }
 
+#[options("/")]
+pub fn root_preflight() -> Response {
+    Response::Result(super::Status::Ok)
+}
+
 /// I'm a teapot.
 #[delete("/")]
 pub fn teapot() -> Response {
diff --git a/src/routes/user.rs b/src/routes/user.rs
index 0a49af8..c9a3663 100644
--- a/src/routes/user.rs
+++ b/src/routes/user.rs
@@ -8,7 +8,7 @@ use crate::notifications::{
 use crate::routes::channel;
 
 use mongodb::bson::doc;
-use mongodb::options::{Collation, FindOptions, FindOneOptions};
+use mongodb::options::{Collation, FindOneOptions, FindOptions};
 use rocket_contrib::json::Json;
 use serde::{Deserialize, Serialize};
 use ulid::Ulid;
@@ -61,13 +61,8 @@ pub fn query(user: UserRef, query: Json<UserQuery>) -> Response {
     if let Ok(result) = col.find_one(
         doc! { "username": query.username.clone() },
         FindOneOptions::builder()
-            .collation(
-                Collation::builder()
-                    .locale("en")
-                    .strength(2)
-                    .build()
-            )
-            .build()
+            .collation(Collation::builder().locale("en").strength(2).build())
+            .build(),
     ) {
         if let Some(doc) = result {
             let id = doc.get_str("_id").unwrap();
-- 
GitLab