From 51ff6aa983c251c014e569554e368cecedcb79d4 Mon Sep 17 00:00:00 2001 From: Paul Makles <paulmakles@gmail.com> Date: Fri, 10 Apr 2020 16:31:14 +0100 Subject: [PATCH] Refractor some code. --- src/database/mutual.rs | 14 +-- src/guards/channel.rs | 2 +- src/routes/account.rs | 27 ++-- src/routes/channel.rs | 45 +++---- src/routes/guild.rs | 21 ++-- src/routes/user.rs | 275 +++++++++++++++++++++-------------------- 6 files changed, 198 insertions(+), 186 deletions(-) diff --git a/src/database/mutual.rs b/src/database/mutual.rs index b6a7726..9fd3ed1 100644 --- a/src/database/mutual.rs +++ b/src/database/mutual.rs @@ -1,7 +1,7 @@ use super::get_collection; use bson::doc; -use mongodb::options::{FindOptions, FindOneOptions}; +use mongodb::options::{FindOneOptions, FindOptions}; pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> { let col = get_collection("guilds"); @@ -12,9 +12,7 @@ pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> { { "members": { "$elemMatch": { "id": target_id } } }, ] }, - FindOptions::builder() - .projection(doc! { "_id": 1 }) - .build(), + FindOptions::builder().projection(doc! { "_id": 1 }).build(), ) { let mut results = vec![]; @@ -39,9 +37,7 @@ pub fn find_mutual_friends(user_id: &str, target_id: &str) -> Vec<String> { { "relations": { "$elemMatch": { "id": target_id, "status": 0 } } }, ] }, - FindOptions::builder() - .projection(doc! { "_id": 1 }) - .build(), + FindOptions::builder().projection(doc! { "_id": 1 }).build(), ) { let mut results = vec![]; @@ -67,9 +63,7 @@ pub fn find_mutual_groups(user_id: &str, target_id: &str) -> Vec<String> { { "recipients": target_id }, ] }, - FindOptions::builder() - .projection(doc! { "_id": 1 }) - .build(), + FindOptions::builder().projection(doc! { "_id": 1 }).build(), ) { let mut results = vec![]; diff --git a/src/guards/channel.rs b/src/guards/channel.rs index 97200d0..a05db4f 100644 --- a/src/guards/channel.rs +++ b/src/guards/channel.rs @@ -6,8 +6,8 @@ use serde::{Deserialize, Serialize}; use crate::database; -use database::message::Message; use database::channel::LastMessage; +use database::message::Message; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ChannelRef { diff --git a/src/routes/account.rs b/src/routes/account.rs index a5e16aa..c7a2e76 100644 --- a/src/routes/account.rs +++ b/src/routes/account.rs @@ -246,12 +246,14 @@ pub fn login(info: Json<Login>) -> Response { Some(t) => t.to_string(), None => { let token = gen_token(92); - col.update_one( + if col.update_one( doc! { "_id": &user.id }, doc! { "$set": { "access_token": token.clone() } }, None, - ) - .expect("Failed to update user object"); + ).is_err() { + return Response::InternalServerError(json!({ "error": "Failed database operation." })); + } + token } }; @@ -275,16 +277,21 @@ pub struct Token { pub fn token(info: Json<Token>) -> Response { let col = database::get_collection("users"); - if let Some(u) = col + if let Ok(result) = col .find_one(doc! { "access_token": info.token.clone() }, None) - .expect("Failed user lookup") { - Response::Success(json!({ - "id": u.get_str("_id").unwrap(), - })) + if let Some(user) = result { + Response::Success(json!({ + "id": user.get_str("_id").unwrap(), + })) + } else { + Response::Unauthorized(json!({ + "error": "Invalid token!", + })) + } } else { - Response::Unauthorized(json!({ - "error": "Invalid token!", + Response::InternalServerError(json!({ + "error": "Failed database query.", })) } } diff --git a/src/routes/channel.rs b/src/routes/channel.rs index f3d5906..2906399 100644 --- a/src/routes/channel.rs +++ b/src/routes/channel.rs @@ -446,7 +446,8 @@ pub fn send_message( // !! this stuff can be async if target.channel_type == ChannelType::DM as u8 - || target.channel_type == ChannelType::GROUPDM as u8 { + || target.channel_type == ChannelType::GROUPDM as u8 + { let mut update = doc! { "$set": { "last_message": { @@ -458,14 +459,16 @@ pub fn send_message( }; if target.channel_type == ChannelType::DM as u8 { - update.get_document_mut("$set").unwrap().insert("active", true); + update + .get_document_mut("$set") + .unwrap() + .insert("active", true); } - if col.update_one( - doc! { "_id": &target.id }, - update, - None, - ).is_ok() { + if col + .update_one(doc! { "_id": &target.id }, update, None) + .is_ok() + { Response::Success(json!({ "id": id })) } else { Response::InternalServerError(json!({ "error": "Failed to update channel." })) @@ -474,20 +477,20 @@ pub fn send_message( Response::Success(json!({ "id": id })) } - /*websocket::queue_message( - get_recipients(&target), - json!({ - "type": "message", - "data": { - "id": id.clone(), - "nonce": nonce, - "channel": target.id, - "author": user.id, - "content": content, - }, - }) - .to_string(), - );*/ + /*websocket::queue_message( + get_recipients(&target), + json!({ + "type": "message", + "data": { + "id": id.clone(), + "nonce": nonce, + "channel": target.id, + "author": user.id, + "content": content, + }, + }) + .to_string(), + );*/ } else { Response::InternalServerError(json!({ "error": "Failed database query." diff --git a/src/routes/guild.rs b/src/routes/guild.rs index 42a8d9f..edd92ed 100644 --- a/src/routes/guild.rs +++ b/src/routes/guild.rs @@ -76,15 +76,18 @@ pub fn guild(user: UserRef, target: GuildRef) -> Option<Response> { Ok(results) => { let mut channels = vec![]; for item in results { - let channel: Channel = from_bson(bson::Bson::Document(item.unwrap())) - .expect("Failed to unwrap channel."); - - channels.push(json!({ - "id": channel.id, - "last_message": channel.last_message, - "name": channel.name, - "description": channel.description, - })); + if let Ok(entry) = item { + if let Ok(channel) = + from_bson(bson::Bson::Document(entry)) as Result<Channel, _> + { + channels.push(json!({ + "id": channel.id, + "last_message": channel.last_message, + "name": channel.name, + "description": channel.description, + })); + } + } } Some(Response::Success(json!({ diff --git a/src/routes/user.rs b/src/routes/user.rs index 631ed21..6c4543a 100644 --- a/src/routes/user.rs +++ b/src/routes/user.rs @@ -1,5 +1,5 @@ use super::Response; -use crate::database::{self, get_relationship, get_relationship_internal, Relationship, mutual}; +use crate::database::{self, get_relationship, get_relationship_internal, mutual, Relationship}; use crate::guards::auth::UserRef; use crate::routes::channel; @@ -53,29 +53,29 @@ pub fn lookup(user: UserRef, query: Json<Query>) -> Response { let relationships = user.fetch_relationships(); let col = database::get_collection("users"); - let users = col - .find( - doc! { "username": query.username.clone() }, - FindOptions::builder() - .projection(doc! { "_id": 1, "username": 1 }) - .limit(10) - .build(), - ) - .expect("Failed user lookup"); - - let mut results = Vec::new(); - for item in users { - if let Ok(doc) = item { - let id = doc.get_str("id").unwrap(); - results.push(json!({ - "id": id, - "username": doc.get_str("username").unwrap(), - "relationship": get_relationship_internal(&user.id, &id, &relationships) as u8 - })); + if let Ok(users) = col.find( + doc! { "username": query.username.clone() }, + FindOptions::builder() + .projection(doc! { "_id": 1, "username": 1 }) + .limit(10) + .build(), + ) { + let mut results = Vec::new(); + for item in users { + if let Ok(doc) = item { + let id = doc.get_str("id").unwrap(); + results.push(json!({ + "id": id, + "username": doc.get_str("username").unwrap(), + "relationship": get_relationship_internal(&user.id, &id, &relationships) as u8 + })); + } } - } - Response::Success(json!(results)) + Response::Success(json!(results)) + } else { + Response::InternalServerError(json!({ "error": "Failed database query." })) + } } /// retrieve all of your DMs @@ -83,53 +83,53 @@ pub fn lookup(user: UserRef, query: Json<Query>) -> Response { pub fn dms(user: UserRef) -> Response { let col = database::get_collection("channels"); - let results = col - .find( - doc! { - "$or": [ - { - "type": channel::ChannelType::DM as i32 - }, - { - "type": channel::ChannelType::GROUPDM as i32 - } - ], - "recipients": user.id - }, - FindOptions::builder().projection(doc! {}).build(), - ) - .expect("Failed channel lookup"); - - let mut channels = Vec::new(); - for item in results { - if let Ok(doc) = item { - let id = doc.get_str("_id").unwrap(); - let recipients = doc.get_array("recipients").unwrap(); - - match doc.get_i32("type").unwrap() { - 0 => { - channels.push(json!({ - "id": id, - "type": 0, - "recipients": recipients, - })); + if let Ok(results) = col.find( + doc! { + "$or": [ + { + "type": channel::ChannelType::DM as i32 + }, + { + "type": channel::ChannelType::GROUPDM as i32 } - 1 => { - channels.push(json!({ - "id": id, - "type": 1, - "recipients": recipients, - "name": doc.get_str("name").unwrap(), - "owner": doc.get_str("owner").unwrap(), - "description": doc.get_str("description").unwrap_or(""), - })); + ], + "recipients": user.id + }, + FindOptions::builder().projection(doc! {}).build(), + ) { + let mut channels = Vec::new(); + for item in results { + if let Ok(doc) = item { + let id = doc.get_str("_id").unwrap(); + let recipients = doc.get_array("recipients").unwrap(); + + match doc.get_i32("type").unwrap() { + 0 => { + channels.push(json!({ + "id": id, + "type": 0, + "recipients": recipients, + })); + } + 1 => { + channels.push(json!({ + "id": id, + "type": 1, + "recipients": recipients, + "name": doc.get_str("name").unwrap(), + "owner": doc.get_str("owner").unwrap(), + "description": doc.get_str("description").unwrap_or(""), + })); + } + _ => unreachable!(), } - _ => unreachable!(), } } - } - Response::Success(json!(channels)) + Response::Success(json!(channels)) + } else { + Response::InternalServerError(json!({ "error": "Failed database query." })) + } } /// open a DM with a user @@ -137,16 +137,16 @@ pub fn dms(user: UserRef) -> Response { pub fn dm(user: UserRef, target: UserRef) -> Response { let col = database::get_collection("channels"); - match col.find_one( + if let Ok(result) = col.find_one( doc! { "type": channel::ChannelType::DM as i32, "recipients": { "$all": [ user.id.clone(), target.id.clone() ] } }, None - ).expect("Failed channel lookup") { - Some(channel) => - Response::Success( json!({ "id": channel.get_str("_id").unwrap() })), - None => { + ) { + if let Some(channel) = result { + Response::Success( json!({ "id": channel.get_str("_id").unwrap() })) + } else { let id = Ulid::new(); - col.insert_one( + if col.insert_one( doc! { "_id": id.to_string(), "type": channel::ChannelType::DM as i32, @@ -154,11 +154,15 @@ pub fn dm(user: UserRef, target: UserRef) -> Response { "active": false }, None - ).expect("Failed insert query."); - - Response::Success(json!({ "id": id.to_string() })) + ).is_ok() { + Response::Success(json!({ "id": id.to_string() })) + } else { + Response::InternalServerError(json!({ "error": "Failed to create new chanel." })) + } } - } + } else { + Response::InternalServerError(json!({ "error": "Failed server query." })) + } } /// retrieve all of your friends @@ -361,9 +365,7 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response { let col = database::get_collection("users"); match get_relationship(&user, &target) { - Relationship::Friend - | Relationship::Incoming - | Relationship::Outgoing => { + Relationship::Friend | Relationship::Incoming | Relationship::Outgoing => { if col .update_one( doc! { @@ -405,8 +407,10 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response { json!({ "error": "Failed to commit to database, try again." }), ) } - }, - Relationship::Blocked => Response::BadRequest(json!({ "error": "Already blocked this person." })), + } + Relationship::Blocked => { + Response::BadRequest(json!({ "error": "Already blocked this person." })) + } Relationship::BlockedOther => { if col .update_one( @@ -429,9 +433,10 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response { json!({ "error": "Failed to commit to database, try again." }), ) } - }, - Relationship::SELF - | Relationship::NONE => Response::BadRequest(json!({ "error": "This has no effect." })), + } + Relationship::SELF | Relationship::NONE => { + Response::BadRequest(json!({ "error": "This has no effect." })) + } } } @@ -441,41 +446,56 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response { let col = database::get_collection("users"); match get_relationship(&user, &target) { - Relationship::Blocked => { - match get_relationship(&target, &user) { - Relationship::Blocked => { - if col - .update_one( - doc! { - "_id": user.id.clone(), - "relations.id": target.id.clone() - }, - doc! { - "$set": { - "relations.$.status": Relationship::BlockedOther as i32 + Relationship::Blocked => match get_relationship(&target, &user) { + Relationship::Blocked => { + if col + .update_one( + doc! { + "_id": user.id.clone(), + "relations.id": target.id.clone() + }, + doc! { + "$set": { + "relations.$.status": Relationship::BlockedOther as i32 + } + }, + None, + ) + .is_ok() + { + Response::Success(json!({ "status": Relationship::BlockedOther as u8 })) + } else { + Response::InternalServerError( + json!({ "error": "Failed to commit to database, try again." }), + ) + } + } + Relationship::BlockedOther => { + if col + .update_one( + doc! { + "_id": user.id.clone() + }, + doc! { + "$pull": { + "relations": { + "id": target.id.clone() } - }, - None, - ) - .is_ok() - { - Response::Success(json!({ "status": Relationship::BlockedOther as u8 })) - } else { - Response::InternalServerError( - json!({ "error": "Failed to commit to database, try again." }), - ) - } - }, - Relationship::BlockedOther => { + } + }, + None, + ) + .is_ok() + { if col .update_one( doc! { - "_id": user.id.clone() + "_id": target.id }, doc! { "$pull": { "relations": { - "id": target.id.clone() + "id": user.id } } }, @@ -483,38 +503,23 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response { ) .is_ok() { - if col - .update_one( - doc! { - "_id": target.id - }, - doc! { - "$pull": { - "relations": { - "id": user.id - } - } - }, - None, - ) - .is_ok() - { - Response::Success(json!({ "status": Relationship::NONE as u8 })) - } else { - Response::InternalServerError( - json!({ "error": "Failed to commit! Target remains in same state." }), - ) - } + Response::Success(json!({ "status": Relationship::NONE as u8 })) } else { Response::InternalServerError( - json!({ "error": "Failed to commit to database, try again." }), + json!({ "error": "Failed to commit! Target remains in same state." }), ) } - }, - _ => unreachable!() + } else { + Response::InternalServerError( + json!({ "error": "Failed to commit to database, try again." }), + ) + } } + _ => unreachable!(), }, - Relationship::BlockedOther => Response::BadRequest(json!({ "error": "Cannot remove block by other user." })), + Relationship::BlockedOther => { + Response::BadRequest(json!({ "error": "Cannot remove block by other user." })) + } Relationship::Friend | Relationship::Incoming | Relationship::Outgoing -- GitLab