From 1711eb98b4c091d6dd59ede8e91923d01fe3edd6 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Thu, 13 Aug 2020 11:46:31 -0400 Subject: [PATCH] Removing some unecessary unwrap. Fixes #639 (#1078) * Removing some unecessary unwrap. Fixes #639 * Changing some location_infos. Co-authored-by: Felix Ableitner --- server/src/api/claims.rs | 3 +- server/src/api/community.rs | 9 ++++-- server/src/api/site.rs | 5 ++-- server/src/api/user.rs | 15 ++++++---- server/src/routes/feeds.rs | 54 +++++++++++++++++++++------------- server/src/websocket/server.rs | 47 ++++++++++++++++++++--------- 6 files changed, 87 insertions(+), 46 deletions(-) diff --git a/server/src/api/claims.rs b/server/src/api/claims.rs index 0f0d05de8..f475f1dfe 100644 --- a/server/src/api/claims.rs +++ b/server/src/api/claims.rs @@ -24,7 +24,7 @@ impl Claims { ) } - pub fn jwt(user: User_, hostname: String) -> Jwt { + pub fn jwt(user: User_, hostname: String) -> Result { let my_claims = Claims { id: user.id, iss: hostname, @@ -34,6 +34,5 @@ impl Claims { &my_claims, &EncodingKey::from_secret(Settings::get().jwt_secret.as_ref()), ) - .unwrap() } } diff --git a/server/src/api/community.rs b/server/src/api/community.rs index 8418e612c..01c43ce11 100644 --- a/server/src/api/community.rs +++ b/server/src/api/community.rs @@ -11,6 +11,7 @@ use crate::{ DbPool, }; use actix_web::client::Client; +use anyhow::Context; use lemmy_db::{ diesel_option_overwrite, naive_now, @@ -23,6 +24,7 @@ use lemmy_db::{ use lemmy_utils::{ generate_actor_keypair, is_valid_community_name, + location_info, make_apub_endpoint, naive_from_unix, EndpointType, @@ -819,7 +821,10 @@ impl Perform for TransferCommunity { let mut admins = blocking(pool, move |conn| UserView::admins(conn)).await??; - let creator_index = admins.iter().position(|r| r.id == site_creator_id).unwrap(); + let creator_index = admins + .iter() + .position(|r| r.id == site_creator_id) + .context(location_info!())?; let creator_user = admins.remove(creator_index); admins.insert(0, creator_user); @@ -844,7 +849,7 @@ impl Perform for TransferCommunity { let creator_index = community_mods .iter() .position(|r| r.user_id == data.user_id) - .unwrap(); + .context(location_info!())?; let creator_user = community_mods.remove(creator_index); community_mods.insert(0, creator_user); diff --git a/server/src/api/site.rs b/server/src/api/site.rs index 7800b1b1b..12c59cca3 100644 --- a/server/src/api/site.rs +++ b/server/src/api/site.rs @@ -21,6 +21,7 @@ use crate::{ LemmyError, }; use actix_web::client::Client; +use anyhow::Context; use lemmy_db::{ category::*, comment_view::*, @@ -38,7 +39,7 @@ use lemmy_db::{ SearchType, SortType, }; -use lemmy_utils::settings::Settings; +use lemmy_utils::{location_info, settings::Settings}; use log::{debug, info}; use serde::{Deserialize, Serialize}; use std::str::FromStr; @@ -654,7 +655,7 @@ impl Perform for TransferSite { let creator_index = admins .iter() .position(|r| r.id == site_view.creator_id) - .unwrap(); + .context(location_info!())?; let creator_user = admins.remove(creator_index); admins.insert(0, creator_user); diff --git a/server/src/api/user.rs b/server/src/api/user.rs index 9bb03ba1a..d8c03b695 100644 --- a/server/src/api/user.rs +++ b/server/src/api/user.rs @@ -20,6 +20,7 @@ use crate::{ LemmyError, }; use actix_web::client::Client; +use anyhow::Context; use bcrypt::verify; use captcha::{gen, Difficulty}; use chrono::Duration; @@ -53,6 +54,7 @@ use lemmy_utils::{ generate_random_string, is_valid_preferred_username, is_valid_username, + location_info, make_apub_endpoint, naive_from_unix, remove_slurs, @@ -324,7 +326,7 @@ impl Perform for Login { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(user, Settings::get().hostname), + jwt: Claims::jwt(user, Settings::get().hostname)?, }) } } @@ -494,7 +496,7 @@ impl Perform for Register { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(inserted_user, Settings::get().hostname), + jwt: Claims::jwt(inserted_user, Settings::get().hostname)?, }) } } @@ -667,7 +669,7 @@ impl Perform for SaveUserSettings { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(updated_user, Settings::get().hostname), + jwt: Claims::jwt(updated_user, Settings::get().hostname)?, }) } } @@ -804,7 +806,10 @@ impl Perform for AddAdmin { blocking(pool, move |conn| Site::read(conn, 1).map(|s| s.creator_id)).await??; let mut admins = blocking(pool, move |conn| UserView::admins(conn)).await??; - let creator_index = admins.iter().position(|r| r.id == site_creator_id).unwrap(); + let creator_index = admins + .iter() + .position(|r| r.id == site_creator_id) + .context(location_info!())?; let creator_user = admins.remove(creator_index); admins.insert(0, creator_user); @@ -1183,7 +1188,7 @@ impl Perform for PasswordChange { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(updated_user, Settings::get().hostname), + jwt: Claims::jwt(updated_user, Settings::get().hostname)?, }) } } diff --git a/server/src/routes/feeds.rs b/server/src/routes/feeds.rs index 40e0ab658..e81d33b7f 100644 --- a/server/src/routes/feeds.rs +++ b/server/src/routes/feeds.rs @@ -62,7 +62,7 @@ fn get_feed_all_data(conn: &PgConnection, sort_type: &SortType) -> Result Result Result Result, mentions: Vec, -) -> Vec { +) -> Result, LemmyError> { let mut reply_items: Vec = replies .iter() .map(|r| { @@ -248,7 +248,7 @@ fn create_reply_and_mention_items( ); build_item(&r.creator_name, &r.published, &reply_url, &r.content) }) - .collect(); + .collect::, LemmyError>>()?; let mut mention_items: Vec = mentions .iter() @@ -261,13 +261,18 @@ fn create_reply_and_mention_items( ); build_item(&m.creator_name, &m.published, &mention_url, &m.content) }) - .collect(); + .collect::, LemmyError>>()?; reply_items.append(&mut mention_items); - reply_items + Ok(reply_items) } -fn build_item(creator_name: &str, published: &NaiveDateTime, url: &str, content: &str) -> Item { +fn build_item( + creator_name: &str, + published: &NaiveDateTime, + url: &str, + content: &str, +) -> Result { let mut i = ItemBuilder::default(); i.title(format!("Reply from {}", creator_name)); let author_url = format!("https://{}/u/{}", Settings::get().hostname, creator_name); @@ -278,16 +283,20 @@ fn build_item(creator_name: &str, published: &NaiveDateTime, url: &str, content: let dt = DateTime::::from_utc(*published, Utc); i.pub_date(dt.to_rfc2822()); i.comments(url.to_owned()); - let guid = GuidBuilder::default().permalink(true).value(url).build(); - i.guid(guid.unwrap()); + let guid = GuidBuilder::default() + .permalink(true) + .value(url) + .build() + .map_err(|e| anyhow!(e))?; + i.guid(guid); i.link(url.to_owned()); // TODO add images let html = markdown_to_html(&content.to_string()); i.description(html); - i.build().unwrap() + Ok(i.build().map_err(|e| anyhow!(e))?) } -fn create_post_items(posts: Vec) -> Vec { +fn create_post_items(posts: Vec) -> Result, LemmyError> { let mut items: Vec = Vec::new(); for p in posts { @@ -309,8 +318,9 @@ fn create_post_items(posts: Vec) -> Vec { let guid = GuidBuilder::default() .permalink(true) .value(&post_url) - .build(); - i.guid(guid.unwrap()); + .build() + .map_err(|e| anyhow!(e))?; + i.guid(guid); let community_url = format!( "https://{}/c/{}", @@ -324,8 +334,10 @@ fn create_post_items(posts: Vec) -> Vec { p.community_name, community_url )) .domain(Settings::get().hostname.to_owned()) - .build(); - i.categories(vec![category.unwrap()]); + .build() + .map_err(|e| anyhow!(e))?; + + i.categories(vec![category]); if let Some(url) = p.url { i.link(url); @@ -348,8 +360,8 @@ fn create_post_items(posts: Vec) -> Vec { i.description(description); - items.push(i.build().unwrap()); + items.push(i.build().map_err(|e| anyhow!(e))?); } - items + Ok(items) } diff --git a/server/src/websocket/server.rs b/server/src/websocket/server.rs index a6169fab9..a83e4d109 100644 --- a/server/src/websocket/server.rs +++ b/server/src/websocket/server.rs @@ -16,7 +16,9 @@ use crate::{ UserId, }; use actix_web::client::Client; +use anyhow::Context as acontext; use lemmy_db::naive_now; +use lemmy_utils::location_info; /// Chat server sends this messages to session #[derive(Message)] @@ -200,7 +202,11 @@ impl ChatServer { } } - pub fn join_community_room(&mut self, community_id: CommunityId, id: ConnectionId) { + pub fn join_community_room( + &mut self, + community_id: CommunityId, + id: ConnectionId, + ) -> Result<(), LemmyError> { // remove session from all rooms for sessions in self.community_rooms.values_mut() { sessions.remove(&id); @@ -220,11 +226,12 @@ impl ChatServer { self .community_rooms .get_mut(&community_id) - .unwrap() + .context(location_info!())? .insert(id); + Ok(()) } - pub fn join_post_room(&mut self, post_id: PostId, id: ConnectionId) { + pub fn join_post_room(&mut self, post_id: PostId, id: ConnectionId) -> Result<(), LemmyError> { // remove session from all rooms for sessions in self.post_rooms.values_mut() { sessions.remove(&id); @@ -244,10 +251,16 @@ impl ChatServer { self.post_rooms.insert(post_id, HashSet::new()); } - self.post_rooms.get_mut(&post_id).unwrap().insert(id); + self + .post_rooms + .get_mut(&post_id) + .context(location_info!())? + .insert(id); + + Ok(()) } - pub fn join_user_room(&mut self, user_id: UserId, id: ConnectionId) { + pub fn join_user_room(&mut self, user_id: UserId, id: ConnectionId) -> Result<(), LemmyError> { // remove session from all rooms for sessions in self.user_rooms.values_mut() { sessions.remove(&id); @@ -258,7 +271,13 @@ impl ChatServer { self.user_rooms.insert(user_id, HashSet::new()); } - self.user_rooms.get_mut(&user_id).unwrap().insert(id); + self + .user_rooms + .get_mut(&user_id) + .context(location_info!())? + .insert(id); + + Ok(()) } fn send_post_room_message( @@ -675,7 +694,7 @@ where fn handle(&mut self, msg: SendAllMessage, _: &mut Context) { self .send_all_message(&msg.op, &msg.response, msg.my_id) - .unwrap(); + .ok(); } } @@ -688,7 +707,7 @@ where fn handle(&mut self, msg: SendUserRoomMessage, _: &mut Context) { self .send_user_room_message(&msg.op, &msg.response, msg.recipient_id, msg.my_id) - .unwrap(); + .ok(); } } @@ -701,7 +720,7 @@ where fn handle(&mut self, msg: SendCommunityRoomMessage, _: &mut Context) { self .send_community_room_message(&msg.op, &msg.response, msg.community_id, msg.my_id) - .unwrap(); + .ok(); } } @@ -709,7 +728,7 @@ impl Handler for ChatServer { type Result = (); fn handle(&mut self, msg: SendPost, _: &mut Context) { - self.send_post(&msg.op, &msg.post, msg.my_id).unwrap(); + self.send_post(&msg.op, &msg.post, msg.my_id).ok(); } } @@ -717,7 +736,7 @@ impl Handler for ChatServer { type Result = (); fn handle(&mut self, msg: SendComment, _: &mut Context) { - self.send_comment(&msg.op, &msg.comment, msg.my_id).unwrap(); + self.send_comment(&msg.op, &msg.comment, msg.my_id).ok(); } } @@ -725,7 +744,7 @@ impl Handler for ChatServer { type Result = (); fn handle(&mut self, msg: JoinUserRoom, _: &mut Context) { - self.join_user_room(msg.user_id, msg.id); + self.join_user_room(msg.user_id, msg.id).ok(); } } @@ -733,7 +752,7 @@ impl Handler for ChatServer { type Result = (); fn handle(&mut self, msg: JoinCommunityRoom, _: &mut Context) { - self.join_community_room(msg.community_id, msg.id); + self.join_community_room(msg.community_id, msg.id).ok(); } } @@ -741,7 +760,7 @@ impl Handler for ChatServer { type Result = (); fn handle(&mut self, msg: JoinPostRoom, _: &mut Context) { - self.join_post_room(msg.post_id, msg.id); + self.join_post_room(msg.post_id, msg.id).ok(); } }