Refractor some code.

This commit is contained in:
Paul Makles
2020-04-10 16:31:14 +01:00
parent 95aad8092b
commit 51ff6aa983
6 changed files with 198 additions and 186 deletions

View File

@@ -1,7 +1,7 @@
use super::get_collection; use super::get_collection;
use bson::doc; 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> { pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
let col = get_collection("guilds"); 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 } } }, { "members": { "$elemMatch": { "id": target_id } } },
] ]
}, },
FindOptions::builder() FindOptions::builder().projection(doc! { "_id": 1 }).build(),
.projection(doc! { "_id": 1 })
.build(),
) { ) {
let mut results = vec![]; 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 } } }, { "relations": { "$elemMatch": { "id": target_id, "status": 0 } } },
] ]
}, },
FindOptions::builder() FindOptions::builder().projection(doc! { "_id": 1 }).build(),
.projection(doc! { "_id": 1 })
.build(),
) { ) {
let mut results = vec![]; let mut results = vec![];
@@ -67,9 +63,7 @@ pub fn find_mutual_groups(user_id: &str, target_id: &str) -> Vec<String> {
{ "recipients": target_id }, { "recipients": target_id },
] ]
}, },
FindOptions::builder() FindOptions::builder().projection(doc! { "_id": 1 }).build(),
.projection(doc! { "_id": 1 })
.build(),
) { ) {
let mut results = vec![]; let mut results = vec![];

View File

@@ -6,8 +6,8 @@ use serde::{Deserialize, Serialize};
use crate::database; use crate::database;
use database::message::Message;
use database::channel::LastMessage; use database::channel::LastMessage;
use database::message::Message;
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ChannelRef { pub struct ChannelRef {

View File

@@ -246,12 +246,14 @@ pub fn login(info: Json<Login>) -> Response {
Some(t) => t.to_string(), Some(t) => t.to_string(),
None => { None => {
let token = gen_token(92); let token = gen_token(92);
col.update_one( if col.update_one(
doc! { "_id": &user.id }, doc! { "_id": &user.id },
doc! { "$set": { "access_token": token.clone() } }, doc! { "$set": { "access_token": token.clone() } },
None, None,
) ).is_err() {
.expect("Failed to update user object"); return Response::InternalServerError(json!({ "error": "Failed database operation." }));
}
token token
} }
}; };
@@ -275,16 +277,21 @@ pub struct Token {
pub fn token(info: Json<Token>) -> Response { pub fn token(info: Json<Token>) -> Response {
let col = database::get_collection("users"); 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) .find_one(doc! { "access_token": info.token.clone() }, None)
.expect("Failed user lookup")
{ {
Response::Success(json!({ if let Some(user) = result {
"id": u.get_str("_id").unwrap(), Response::Success(json!({
})) "id": user.get_str("_id").unwrap(),
}))
} else {
Response::Unauthorized(json!({
"error": "Invalid token!",
}))
}
} else { } else {
Response::Unauthorized(json!({ Response::InternalServerError(json!({
"error": "Invalid token!", "error": "Failed database query.",
})) }))
} }
} }

View File

@@ -446,7 +446,8 @@ pub fn send_message(
// !! this stuff can be async // !! this stuff can be async
if target.channel_type == ChannelType::DM as u8 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! { let mut update = doc! {
"$set": { "$set": {
"last_message": { "last_message": {
@@ -458,14 +459,16 @@ pub fn send_message(
}; };
if target.channel_type == ChannelType::DM as u8 { 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( if col
doc! { "_id": &target.id }, .update_one(doc! { "_id": &target.id }, update, None)
update, .is_ok()
None, {
).is_ok() {
Response::Success(json!({ "id": id })) Response::Success(json!({ "id": id }))
} else { } else {
Response::InternalServerError(json!({ "error": "Failed to update channel." })) Response::InternalServerError(json!({ "error": "Failed to update channel." }))
@@ -474,20 +477,20 @@ pub fn send_message(
Response::Success(json!({ "id": id })) Response::Success(json!({ "id": id }))
} }
/*websocket::queue_message( /*websocket::queue_message(
get_recipients(&target), get_recipients(&target),
json!({ json!({
"type": "message", "type": "message",
"data": { "data": {
"id": id.clone(), "id": id.clone(),
"nonce": nonce, "nonce": nonce,
"channel": target.id, "channel": target.id,
"author": user.id, "author": user.id,
"content": content, "content": content,
}, },
}) })
.to_string(), .to_string(),
);*/ );*/
} else { } else {
Response::InternalServerError(json!({ Response::InternalServerError(json!({
"error": "Failed database query." "error": "Failed database query."

View File

@@ -76,15 +76,18 @@ pub fn guild(user: UserRef, target: GuildRef) -> Option<Response> {
Ok(results) => { Ok(results) => {
let mut channels = vec![]; let mut channels = vec![];
for item in results { for item in results {
let channel: Channel = from_bson(bson::Bson::Document(item.unwrap())) if let Ok(entry) = item {
.expect("Failed to unwrap channel."); if let Ok(channel) =
from_bson(bson::Bson::Document(entry)) as Result<Channel, _>
channels.push(json!({ {
"id": channel.id, channels.push(json!({
"last_message": channel.last_message, "id": channel.id,
"name": channel.name, "last_message": channel.last_message,
"description": channel.description, "name": channel.name,
})); "description": channel.description,
}));
}
}
} }
Some(Response::Success(json!({ Some(Response::Success(json!({

View File

@@ -1,5 +1,5 @@
use super::Response; 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::guards::auth::UserRef;
use crate::routes::channel; use crate::routes::channel;
@@ -53,29 +53,29 @@ pub fn lookup(user: UserRef, query: Json<Query>) -> Response {
let relationships = user.fetch_relationships(); let relationships = user.fetch_relationships();
let col = database::get_collection("users"); let col = database::get_collection("users");
let users = col if let Ok(users) = col.find(
.find( doc! { "username": query.username.clone() },
doc! { "username": query.username.clone() }, FindOptions::builder()
FindOptions::builder() .projection(doc! { "_id": 1, "username": 1 })
.projection(doc! { "_id": 1, "username": 1 }) .limit(10)
.limit(10) .build(),
.build(), ) {
) let mut results = Vec::new();
.expect("Failed user lookup"); for item in users {
if let Ok(doc) = item {
let mut results = Vec::new(); let id = doc.get_str("id").unwrap();
for item in users { results.push(json!({
if let Ok(doc) = item { "id": id,
let id = doc.get_str("id").unwrap(); "username": doc.get_str("username").unwrap(),
results.push(json!({ "relationship": get_relationship_internal(&user.id, &id, &relationships) as u8
"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 /// retrieve all of your DMs
@@ -83,53 +83,53 @@ pub fn lookup(user: UserRef, query: Json<Query>) -> Response {
pub fn dms(user: UserRef) -> Response { pub fn dms(user: UserRef) -> Response {
let col = database::get_collection("channels"); let col = database::get_collection("channels");
let results = col if let Ok(results) = col.find(
.find( doc! {
doc! { "$or": [
"$or": [ {
{ "type": channel::ChannelType::DM as i32
"type": channel::ChannelType::DM as i32 },
}, {
{ "type": channel::ChannelType::GROUPDM as i32
"type": channel::ChannelType::GROUPDM as i32 }
],
"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 => {
"recipients": user.id channels.push(json!({
}, "id": id,
FindOptions::builder().projection(doc! {}).build(), "type": 1,
) "recipients": recipients,
.expect("Failed channel lookup"); "name": doc.get_str("name").unwrap(),
"owner": doc.get_str("owner").unwrap(),
let mut channels = Vec::new(); "description": doc.get_str("description").unwrap_or(""),
for item in results { }));
if let Ok(doc) = item { }
let id = doc.get_str("_id").unwrap(); _ => unreachable!(),
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!(),
} }
} }
}
Response::Success(json!(channels)) Response::Success(json!(channels))
} else {
Response::InternalServerError(json!({ "error": "Failed database query." }))
}
} }
/// open a DM with a user /// open a DM with a user
@@ -137,16 +137,16 @@ pub fn dms(user: UserRef) -> Response {
pub fn dm(user: UserRef, target: UserRef) -> Response { pub fn dm(user: UserRef, target: UserRef) -> Response {
let col = database::get_collection("channels"); 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() ] } }, doc! { "type": channel::ChannelType::DM as i32, "recipients": { "$all": [ user.id.clone(), target.id.clone() ] } },
None None
).expect("Failed channel lookup") { ) {
Some(channel) => if let Some(channel) = result {
Response::Success( json!({ "id": channel.get_str("_id").unwrap() })), Response::Success( json!({ "id": channel.get_str("_id").unwrap() }))
None => { } else {
let id = Ulid::new(); let id = Ulid::new();
col.insert_one( if col.insert_one(
doc! { doc! {
"_id": id.to_string(), "_id": id.to_string(),
"type": channel::ChannelType::DM as i32, "type": channel::ChannelType::DM as i32,
@@ -154,11 +154,15 @@ pub fn dm(user: UserRef, target: UserRef) -> Response {
"active": false "active": false
}, },
None None
).expect("Failed insert query."); ).is_ok() {
Response::Success(json!({ "id": id.to_string() }))
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 /// retrieve all of your friends
@@ -361,9 +365,7 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
let col = database::get_collection("users"); let col = database::get_collection("users");
match get_relationship(&user, &target) { match get_relationship(&user, &target) {
Relationship::Friend Relationship::Friend | Relationship::Incoming | Relationship::Outgoing => {
| Relationship::Incoming
| Relationship::Outgoing => {
if col if col
.update_one( .update_one(
doc! { doc! {
@@ -405,8 +407,10 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
json!({ "error": "Failed to commit to database, try again." }), 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 => { Relationship::BlockedOther => {
if col if col
.update_one( .update_one(
@@ -429,9 +433,10 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
json!({ "error": "Failed to commit to database, try again." }), json!({ "error": "Failed to commit to database, try again." }),
) )
} }
}, }
Relationship::SELF Relationship::SELF | Relationship::NONE => {
| Relationship::NONE => Response::BadRequest(json!({ "error": "This has no effect." })), 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"); let col = database::get_collection("users");
match get_relationship(&user, &target) { match get_relationship(&user, &target) {
Relationship::Blocked => { Relationship::Blocked => match get_relationship(&target, &user) {
match get_relationship(&target, &user) { Relationship::Blocked => {
Relationship::Blocked => { if col
if col .update_one(
.update_one( doc! {
doc! { "_id": user.id.clone(),
"_id": user.id.clone(), "relations.id": target.id.clone()
"relations.id": target.id.clone() },
}, doc! {
doc! { "$set": {
"$set": { "relations.$.status": Relationship::BlockedOther as i32
"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, },
) None,
.is_ok() )
{ .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 if col
.update_one( .update_one(
doc! { doc! {
"_id": user.id.clone() "_id": target.id
}, },
doc! { doc! {
"$pull": { "$pull": {
"relations": { "relations": {
"id": target.id.clone() "id": user.id
} }
} }
}, },
@@ -483,38 +503,23 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
) )
.is_ok() .is_ok()
{ {
if col Response::Success(json!({ "status": Relationship::NONE as u8 }))
.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." }),
)
}
} else { } else {
Response::InternalServerError( Response::InternalServerError(
json!({ "error": "Failed to commit to database, try again." }), json!({ "error": "Failed to commit! Target remains in same state." }),
) )
} }
}, } else {
_ => unreachable!() 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::Friend
| Relationship::Incoming | Relationship::Incoming
| Relationship::Outgoing | Relationship::Outgoing