Run cargo fmt, add root preflight.

This commit is contained in:
Paul Makles
2020-08-04 10:19:33 +02:00
parent 17c9148556
commit d95982fb54
14 changed files with 75 additions and 75 deletions

View File

@@ -1,11 +1,11 @@
use super::get_collection; use super::get_collection;
use serde::{Deserialize, Serialize};
use rocket::request::FromParam;
use std::sync::{Arc, Mutex};
use mongodb::bson::{Bson, doc, from_bson};
use rocket::http::RawStr;
use lru::LruCache; 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};
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LastMessage { pub struct LastMessage {
@@ -41,7 +41,8 @@ pub struct Channel {
} }
lazy_static! { 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> { pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
@@ -97,7 +98,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
} }
if missing.len() == 0 { if missing.len() == 0 {
return Ok(Some(channels)) return Ok(Some(channels));
} }
let col = get_collection("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()); cache.put(channel.id.clone(), channel.clone());
channels.push(channel); channels.push(channel);
} else { } else {
return Err("Failed to deserialize channel!".to_string()) return Err("Failed to deserialize channel!".to_string());
} }
} else { } else {
return Err("Failed to fetch channel.".to_string()); return Err("Failed to fetch channel.".to_string());

View File

@@ -1,11 +1,11 @@
use super::get_collection; use super::get_collection;
use serde::{Deserialize, Serialize};
use rocket::request::FromParam;
use std::sync::{Arc, Mutex};
use mongodb::bson::{Bson, doc, from_bson};
use rocket::http::RawStr;
use lru::LruCache; 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};
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct MemberRef { pub struct MemberRef {
@@ -49,7 +49,8 @@ pub struct Guild {
} }
lazy_static! { 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> { pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {

View File

@@ -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::message::Create;
use crate::notifications::events::Notification; use crate::notifications::events::Notification;
use crate::routes::channel::ChannelType; 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::from_bson;
use mongodb::bson::{doc, to_bson, Bson, DateTime};
use rocket::http::RawStr; use rocket::http::RawStr;
use rocket::request::FromParam;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct PreviousEntry { pub struct PreviousEntry {

View File

@@ -1,5 +1,5 @@
use mongodb::sync::{Client, Collection, Database};
use mongodb::bson::doc; use mongodb::bson::doc;
use mongodb::sync::{Client, Collection, Database};
use std::env; use std::env;
use once_cell::sync::OnceCell; 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!")) Client::with_uri_str(&env::var("DB_URI").expect("DB_URI not in environment variables!"))
.expect("Failed to init db connection."); .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(); DBCONN.set(client).unwrap();
} }

View File

@@ -1,6 +1,6 @@
use super::mutual::has_mutual_connection; use super::mutual::has_mutual_connection;
use crate::database::channel::Channel; 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::database::user::UserRelationship;
use crate::guards::auth::UserRef; use crate::guards::auth::UserRef;

View File

@@ -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 mongodb::options::FindOneOptions;
use rocket::http::{RawStr, Status}; use rocket::http::{RawStr, Status};
use rocket::request::{self, FromParam, FromRequest, Request}; use rocket::request::{self, FromParam, FromRequest, Request};

View File

@@ -9,11 +9,11 @@ extern crate bitfield;
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
pub mod notifications;
pub mod database; pub mod database;
pub mod guards;
pub mod routes;
pub mod email; pub mod email;
pub mod guards;
pub mod notifications;
pub mod routes;
pub mod util; pub mod util;
use dotenv; use dotenv;

View File

@@ -1,8 +1,8 @@
use crate::database; use crate::database;
use crate::util::vec_to_set; use crate::util::vec_to_set;
use mongodb::bson::doc;
use hashbrown::{HashMap, HashSet}; use hashbrown::{HashMap, HashSet};
use mongodb::bson::doc;
use mongodb::options::FindOneOptions; use mongodb::options::FindOneOptions;
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
use std::sync::RwLock; use std::sync::RwLock;

View File

@@ -4,9 +4,9 @@ use crate::email;
use crate::util::gen_token; use crate::util::gen_token;
use bcrypt::{hash, verify}; use bcrypt::{hash, verify};
use mongodb::bson::{doc, from_bson, Bson};
use chrono::prelude::*; use chrono::prelude::*;
use database::user::User; use database::user::User;
use mongodb::bson::{doc, from_bson, Bson};
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use ulid::Ulid; use ulid::Ulid;
@@ -140,9 +140,7 @@ pub fn verify_email(code: String) -> Response {
email::send_welcome_email(target.to_string(), user.username); email::send_welcome_email(target.to_string(), user.username);
Response::Redirect( Response::Redirect(super::Redirect::to("https://app.revolt.chat"))
super::Redirect::to("https://app.revolt.chat"),
)
} }
} else { } else {
Response::BadRequest(json!({ "error": "Invalid code." })) Response::BadRequest(json!({ "error": "Invalid code." }))

View File

@@ -1,7 +1,7 @@
use super::Response; use super::Response;
use crate::database::{ use crate::database::{
self, get_relationship, get_relationship_internal, message::Message, Permission, self, channel::Channel, get_relationship, get_relationship_internal, message::Message,
PermissionCalculator, Relationship, channel::Channel Permission, PermissionCalculator, Relationship,
}; };
use crate::guards::auth::UserRef; use crate::guards::auth::UserRef;
use crate::notifications::{ use crate::notifications::{
@@ -10,8 +10,8 @@ use crate::notifications::{
}; };
use crate::util::vec_to_set; use crate::util::vec_to_set;
use mongodb::bson::{doc, from_bson, Bson};
use chrono::prelude::*; use chrono::prelude::*;
use mongodb::bson::{doc, from_bson, Bson};
use mongodb::options::FindOptions; use mongodb::options::FindOptions;
use num_enum::TryFromPrimitive; use num_enum::TryFromPrimitive;
use rocket::request::Form; use rocket::request::Form;
@@ -145,15 +145,15 @@ pub fn channel(user: UserRef, target: Channel) -> Option<Response> {
"description": 1, "description": 1,
"owner": 1, "owner": 1,
}) {*/ }) {*/
Some(Response::Success(json!({ Some(Response::Success(json!({
"id": target.id, "id": target.id,
"type": target.channel_type, "type": target.channel_type,
"last_message": target.last_message, "last_message": target.last_message,
"recipients": target.recipients, "recipients": target.recipients,
"name": target.name, "name": target.name,
"owner": target.owner, "owner": target.owner,
"description": target.description, "description": target.description,
}))) })))
/*} else { /*} else {
None None
}*/ }*/
@@ -163,13 +163,13 @@ pub fn channel(user: UserRef, target: Channel) -> Option<Response> {
"name": 1, "name": 1,
"description": 1, "description": 1,
}) {*/ }) {*/
Some(Response::Success(json!({ Some(Response::Success(json!({
"id": target.id, "id": target.id,
"type": target.channel_type, "type": target.channel_type,
"guild": target.guild, "guild": target.guild,
"name": target.name, "name": target.name,
"description": target.description, "description": target.description,
}))) })))
/*} else { /*} else {
None None
}*/ }*/

View File

@@ -1,7 +1,9 @@
use super::channel::ChannelType; use super::channel::ChannelType;
use super::Response; 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::guild::{get_invite, get_member, Guild};
use crate::database::{
self, channel::fetch_channel, channel::Channel, Permission, PermissionCalculator,
};
use crate::guards::auth::UserRef; use crate::guards::auth::UserRef;
use crate::notifications::{ use crate::notifications::{
self, self,
@@ -106,9 +108,7 @@ pub fn guild(user: UserRef, target: Guild) -> Option<Response> {
let mut channels = vec![]; let mut channels = vec![];
for item in results { for item in results {
if let Ok(entry) = item { if let Ok(entry) = item {
if let Ok(channel) = if let Ok(channel) = from_bson(Bson::Document(entry)) as Result<Channel, _> {
from_bson(Bson::Document(entry)) as Result<Channel, _>
{
channels.push(json!({ channels.push(json!({
"id": channel.id, "id": channel.id,
"name": channel.name, "name": channel.name,
@@ -265,11 +265,7 @@ pub struct CreateChannel {
/// create a new channel /// create a new channel
#[post("/<target>/channels", data = "<info>")] #[post("/<target>/channels", data = "<info>")]
pub fn create_channel( pub fn create_channel(user: UserRef, target: Guild, info: Json<CreateChannel>) -> Option<Response> {
user: UserRef,
target: Guild,
info: Json<CreateChannel>,
) -> Option<Response> {
let (permissions, _) = with_permissions!(user, target); let (permissions, _) = with_permissions!(user, target);
if !permissions.get_manage_channels() { if !permissions.get_manage_channels() {
@@ -451,8 +447,8 @@ pub fn fetch_invite(user: UserRef, code: String) -> Response {
} else { } else {
Response::NotFound(json!({ "error": "Channel does not exist." })) Response::NotFound(json!({ "error": "Channel does not exist." }))
} }
}, }
Err(err) => Response::InternalServerError(json!({ "error": err })) Err(err) => Response::InternalServerError(json!({ "error": err })),
} }
} else { } else {
Response::NotFound(json!({ "error": "Failed to fetch invite or code is invalid." })) Response::NotFound(json!({ "error": "Failed to fetch invite or code is invalid." }))

View File

@@ -63,7 +63,7 @@ impl<'a> rocket::response::Responder<'a> for Permission {
pub fn mount(rocket: Rocket) -> Rocket { pub fn mount(rocket: Rocket) -> Rocket {
rocket rocket
.mount("/", routes![root::root, root::teapot]) .mount("/", routes![root::root, root::root_preflight, root::teapot])
.mount( .mount(
"/account", "/account",
routes![ routes![

View File

@@ -10,6 +10,11 @@ pub fn root() -> Response {
})) }))
} }
#[options("/")]
pub fn root_preflight() -> Response {
Response::Result(super::Status::Ok)
}
/// I'm a teapot. /// I'm a teapot.
#[delete("/")] #[delete("/")]
pub fn teapot() -> Response { pub fn teapot() -> Response {

View File

@@ -8,7 +8,7 @@ use crate::notifications::{
use crate::routes::channel; use crate::routes::channel;
use mongodb::bson::doc; use mongodb::bson::doc;
use mongodb::options::{Collation, FindOptions, FindOneOptions}; use mongodb::options::{Collation, FindOneOptions, FindOptions};
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use ulid::Ulid; use ulid::Ulid;
@@ -61,13 +61,8 @@ pub fn query(user: UserRef, query: Json<UserQuery>) -> Response {
if let Ok(result) = col.find_one( if let Ok(result) = col.find_one(
doc! { "username": query.username.clone() }, doc! { "username": query.username.clone() },
FindOneOptions::builder() FindOneOptions::builder()
.collation( .collation(Collation::builder().locale("en").strength(2).build())
Collation::builder() .build(),
.locale("en")
.strength(2)
.build()
)
.build()
) { ) {
if let Some(doc) = result { if let Some(doc) = result {
let id = doc.get_str("_id").unwrap(); let id = doc.get_str("_id").unwrap();