Removing some unecessary unwrap. Fixes #639 (#1078)

* Removing some unecessary unwrap. Fixes #639

* Changing some location_infos.

Co-authored-by: Felix Ableitner <me@nutomic.com>
This commit is contained in:
Dessalines 2020-08-13 11:46:31 -04:00 committed by GitHub
parent 91926b2b1c
commit 1711eb98b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 87 additions and 46 deletions

View File

@ -24,7 +24,7 @@ impl Claims {
) )
} }
pub fn jwt(user: User_, hostname: String) -> Jwt { pub fn jwt(user: User_, hostname: String) -> Result<Jwt, jsonwebtoken::errors::Error> {
let my_claims = Claims { let my_claims = Claims {
id: user.id, id: user.id,
iss: hostname, iss: hostname,
@ -34,6 +34,5 @@ impl Claims {
&my_claims, &my_claims,
&EncodingKey::from_secret(Settings::get().jwt_secret.as_ref()), &EncodingKey::from_secret(Settings::get().jwt_secret.as_ref()),
) )
.unwrap()
} }
} }

View File

@ -11,6 +11,7 @@ use crate::{
DbPool, DbPool,
}; };
use actix_web::client::Client; use actix_web::client::Client;
use anyhow::Context;
use lemmy_db::{ use lemmy_db::{
diesel_option_overwrite, diesel_option_overwrite,
naive_now, naive_now,
@ -23,6 +24,7 @@ use lemmy_db::{
use lemmy_utils::{ use lemmy_utils::{
generate_actor_keypair, generate_actor_keypair,
is_valid_community_name, is_valid_community_name,
location_info,
make_apub_endpoint, make_apub_endpoint,
naive_from_unix, naive_from_unix,
EndpointType, EndpointType,
@ -819,7 +821,10 @@ impl Perform for TransferCommunity {
let mut admins = blocking(pool, move |conn| UserView::admins(conn)).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); let creator_user = admins.remove(creator_index);
admins.insert(0, creator_user); admins.insert(0, creator_user);
@ -844,7 +849,7 @@ impl Perform for TransferCommunity {
let creator_index = community_mods let creator_index = community_mods
.iter() .iter()
.position(|r| r.user_id == data.user_id) .position(|r| r.user_id == data.user_id)
.unwrap(); .context(location_info!())?;
let creator_user = community_mods.remove(creator_index); let creator_user = community_mods.remove(creator_index);
community_mods.insert(0, creator_user); community_mods.insert(0, creator_user);

View File

@ -21,6 +21,7 @@ use crate::{
LemmyError, LemmyError,
}; };
use actix_web::client::Client; use actix_web::client::Client;
use anyhow::Context;
use lemmy_db::{ use lemmy_db::{
category::*, category::*,
comment_view::*, comment_view::*,
@ -38,7 +39,7 @@ use lemmy_db::{
SearchType, SearchType,
SortType, SortType,
}; };
use lemmy_utils::settings::Settings; use lemmy_utils::{location_info, settings::Settings};
use log::{debug, info}; use log::{debug, info};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::str::FromStr; use std::str::FromStr;
@ -654,7 +655,7 @@ impl Perform for TransferSite {
let creator_index = admins let creator_index = admins
.iter() .iter()
.position(|r| r.id == site_view.creator_id) .position(|r| r.id == site_view.creator_id)
.unwrap(); .context(location_info!())?;
let creator_user = admins.remove(creator_index); let creator_user = admins.remove(creator_index);
admins.insert(0, creator_user); admins.insert(0, creator_user);

View File

@ -20,6 +20,7 @@ use crate::{
LemmyError, LemmyError,
}; };
use actix_web::client::Client; use actix_web::client::Client;
use anyhow::Context;
use bcrypt::verify; use bcrypt::verify;
use captcha::{gen, Difficulty}; use captcha::{gen, Difficulty};
use chrono::Duration; use chrono::Duration;
@ -53,6 +54,7 @@ use lemmy_utils::{
generate_random_string, generate_random_string,
is_valid_preferred_username, is_valid_preferred_username,
is_valid_username, is_valid_username,
location_info,
make_apub_endpoint, make_apub_endpoint,
naive_from_unix, naive_from_unix,
remove_slurs, remove_slurs,
@ -324,7 +326,7 @@ impl Perform for Login {
// Return the jwt // Return the jwt
Ok(LoginResponse { 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 // Return the jwt
Ok(LoginResponse { 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 // Return the jwt
Ok(LoginResponse { 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??; 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 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); let creator_user = admins.remove(creator_index);
admins.insert(0, creator_user); admins.insert(0, creator_user);
@ -1183,7 +1188,7 @@ impl Perform for PasswordChange {
// Return the jwt // Return the jwt
Ok(LoginResponse { Ok(LoginResponse {
jwt: Claims::jwt(updated_user, Settings::get().hostname), jwt: Claims::jwt(updated_user, Settings::get().hostname)?,
}) })
} }
} }

View File

@ -62,7 +62,7 @@ fn get_feed_all_data(conn: &PgConnection, sort_type: &SortType) -> Result<String
.sort(sort_type) .sort(sort_type)
.list()?; .list()?;
let items = create_post_items(posts); let items = create_post_items(posts)?;
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
@ -74,7 +74,7 @@ fn get_feed_all_data(conn: &PgConnection, sort_type: &SortType) -> Result<String
channel_builder.description(&site_desc); channel_builder.description(&site_desc);
} }
Ok(channel_builder.build().unwrap().to_string()) Ok(channel_builder.build().map_err(|e| anyhow!(e))?.to_string())
} }
async fn get_feed( async fn get_feed(
@ -135,7 +135,7 @@ fn get_feed_user(
.for_creator_id(user.id) .for_creator_id(user.id)
.list()?; .list()?;
let items = create_post_items(posts); let items = create_post_items(posts)?;
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
@ -160,7 +160,7 @@ fn get_feed_community(
.for_community_id(community.id) .for_community_id(community.id)
.list()?; .list()?;
let items = create_post_items(posts); let items = create_post_items(posts)?;
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
@ -189,7 +189,7 @@ fn get_feed_front(
.my_user_id(user_id) .my_user_id(user_id)
.list()?; .list()?;
let items = create_post_items(posts); let items = create_post_items(posts)?;
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
@ -218,7 +218,7 @@ fn get_feed_inbox(conn: &PgConnection, jwt: String) -> Result<ChannelBuilder, Le
.sort(&sort) .sort(&sort)
.list()?; .list()?;
let items = create_reply_and_mention_items(replies, mentions); let items = create_reply_and_mention_items(replies, mentions)?;
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
@ -236,7 +236,7 @@ fn get_feed_inbox(conn: &PgConnection, jwt: String) -> Result<ChannelBuilder, Le
fn create_reply_and_mention_items( fn create_reply_and_mention_items(
replies: Vec<ReplyView>, replies: Vec<ReplyView>,
mentions: Vec<UserMentionView>, mentions: Vec<UserMentionView>,
) -> Vec<Item> { ) -> Result<Vec<Item>, LemmyError> {
let mut reply_items: Vec<Item> = replies let mut reply_items: Vec<Item> = replies
.iter() .iter()
.map(|r| { .map(|r| {
@ -248,7 +248,7 @@ fn create_reply_and_mention_items(
); );
build_item(&r.creator_name, &r.published, &reply_url, &r.content) build_item(&r.creator_name, &r.published, &reply_url, &r.content)
}) })
.collect(); .collect::<Result<Vec<Item>, LemmyError>>()?;
let mut mention_items: Vec<Item> = mentions let mut mention_items: Vec<Item> = mentions
.iter() .iter()
@ -261,13 +261,18 @@ fn create_reply_and_mention_items(
); );
build_item(&m.creator_name, &m.published, &mention_url, &m.content) build_item(&m.creator_name, &m.published, &mention_url, &m.content)
}) })
.collect(); .collect::<Result<Vec<Item>, LemmyError>>()?;
reply_items.append(&mut mention_items); 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<Item, LemmyError> {
let mut i = ItemBuilder::default(); let mut i = ItemBuilder::default();
i.title(format!("Reply from {}", creator_name)); i.title(format!("Reply from {}", creator_name));
let author_url = format!("https://{}/u/{}", Settings::get().hostname, 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::<Utc>::from_utc(*published, Utc); let dt = DateTime::<Utc>::from_utc(*published, Utc);
i.pub_date(dt.to_rfc2822()); i.pub_date(dt.to_rfc2822());
i.comments(url.to_owned()); i.comments(url.to_owned());
let guid = GuidBuilder::default().permalink(true).value(url).build(); let guid = GuidBuilder::default()
i.guid(guid.unwrap()); .permalink(true)
.value(url)
.build()
.map_err(|e| anyhow!(e))?;
i.guid(guid);
i.link(url.to_owned()); i.link(url.to_owned());
// TODO add images // TODO add images
let html = markdown_to_html(&content.to_string()); let html = markdown_to_html(&content.to_string());
i.description(html); i.description(html);
i.build().unwrap() Ok(i.build().map_err(|e| anyhow!(e))?)
} }
fn create_post_items(posts: Vec<PostView>) -> Vec<Item> { fn create_post_items(posts: Vec<PostView>) -> Result<Vec<Item>, LemmyError> {
let mut items: Vec<Item> = Vec::new(); let mut items: Vec<Item> = Vec::new();
for p in posts { for p in posts {
@ -309,8 +318,9 @@ fn create_post_items(posts: Vec<PostView>) -> Vec<Item> {
let guid = GuidBuilder::default() let guid = GuidBuilder::default()
.permalink(true) .permalink(true)
.value(&post_url) .value(&post_url)
.build(); .build()
i.guid(guid.unwrap()); .map_err(|e| anyhow!(e))?;
i.guid(guid);
let community_url = format!( let community_url = format!(
"https://{}/c/{}", "https://{}/c/{}",
@ -324,8 +334,10 @@ fn create_post_items(posts: Vec<PostView>) -> Vec<Item> {
p.community_name, community_url p.community_name, community_url
)) ))
.domain(Settings::get().hostname.to_owned()) .domain(Settings::get().hostname.to_owned())
.build(); .build()
i.categories(vec![category.unwrap()]); .map_err(|e| anyhow!(e))?;
i.categories(vec![category]);
if let Some(url) = p.url { if let Some(url) = p.url {
i.link(url); i.link(url);
@ -348,8 +360,8 @@ fn create_post_items(posts: Vec<PostView>) -> Vec<Item> {
i.description(description); i.description(description);
items.push(i.build().unwrap()); items.push(i.build().map_err(|e| anyhow!(e))?);
} }
items Ok(items)
} }

View File

@ -16,7 +16,9 @@ use crate::{
UserId, UserId,
}; };
use actix_web::client::Client; use actix_web::client::Client;
use anyhow::Context as acontext;
use lemmy_db::naive_now; use lemmy_db::naive_now;
use lemmy_utils::location_info;
/// Chat server sends this messages to session /// Chat server sends this messages to session
#[derive(Message)] #[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 // remove session from all rooms
for sessions in self.community_rooms.values_mut() { for sessions in self.community_rooms.values_mut() {
sessions.remove(&id); sessions.remove(&id);
@ -220,11 +226,12 @@ impl ChatServer {
self self
.community_rooms .community_rooms
.get_mut(&community_id) .get_mut(&community_id)
.unwrap() .context(location_info!())?
.insert(id); .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 // remove session from all rooms
for sessions in self.post_rooms.values_mut() { for sessions in self.post_rooms.values_mut() {
sessions.remove(&id); sessions.remove(&id);
@ -244,10 +251,16 @@ impl ChatServer {
self.post_rooms.insert(post_id, HashSet::new()); 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 // remove session from all rooms
for sessions in self.user_rooms.values_mut() { for sessions in self.user_rooms.values_mut() {
sessions.remove(&id); sessions.remove(&id);
@ -258,7 +271,13 @@ impl ChatServer {
self.user_rooms.insert(user_id, HashSet::new()); 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<Response>( fn send_post_room_message<Response>(
@ -675,7 +694,7 @@ where
fn handle(&mut self, msg: SendAllMessage<Response>, _: &mut Context<Self>) { fn handle(&mut self, msg: SendAllMessage<Response>, _: &mut Context<Self>) {
self self
.send_all_message(&msg.op, &msg.response, msg.my_id) .send_all_message(&msg.op, &msg.response, msg.my_id)
.unwrap(); .ok();
} }
} }
@ -688,7 +707,7 @@ where
fn handle(&mut self, msg: SendUserRoomMessage<Response>, _: &mut Context<Self>) { fn handle(&mut self, msg: SendUserRoomMessage<Response>, _: &mut Context<Self>) {
self self
.send_user_room_message(&msg.op, &msg.response, msg.recipient_id, msg.my_id) .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<Response>, _: &mut Context<Self>) { fn handle(&mut self, msg: SendCommunityRoomMessage<Response>, _: &mut Context<Self>) {
self self
.send_community_room_message(&msg.op, &msg.response, msg.community_id, msg.my_id) .send_community_room_message(&msg.op, &msg.response, msg.community_id, msg.my_id)
.unwrap(); .ok();
} }
} }
@ -709,7 +728,7 @@ impl Handler<SendPost> for ChatServer {
type Result = (); type Result = ();
fn handle(&mut self, msg: SendPost, _: &mut Context<Self>) { fn handle(&mut self, msg: SendPost, _: &mut Context<Self>) {
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<SendComment> for ChatServer {
type Result = (); type Result = ();
fn handle(&mut self, msg: SendComment, _: &mut Context<Self>) { fn handle(&mut self, msg: SendComment, _: &mut Context<Self>) {
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<JoinUserRoom> for ChatServer {
type Result = (); type Result = ();
fn handle(&mut self, msg: JoinUserRoom, _: &mut Context<Self>) { fn handle(&mut self, msg: JoinUserRoom, _: &mut Context<Self>) {
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<JoinCommunityRoom> for ChatServer {
type Result = (); type Result = ();
fn handle(&mut self, msg: JoinCommunityRoom, _: &mut Context<Self>) { fn handle(&mut self, msg: JoinCommunityRoom, _: &mut Context<Self>) {
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<JoinPostRoom> for ChatServer {
type Result = (); type Result = ();
fn handle(&mut self, msg: JoinPostRoom, _: &mut Context<Self>) { fn handle(&mut self, msg: JoinPostRoom, _: &mut Context<Self>) {
self.join_post_room(msg.post_id, msg.id); self.join_post_room(msg.post_id, msg.id).ok();
} }
} }