Removing some unecessary unwrap. Fixes #639

This commit is contained in:
Dessalines 2020-08-12 10:31:07 -04:00
parent bb4da4da02
commit a43797e523
7 changed files with 94 additions and 46 deletions

View file

@ -160,7 +160,9 @@ pub fn is_valid_username(name: &str) -> bool {
// Can't do a regex here, reverse lookarounds not supported // Can't do a regex here, reverse lookarounds not supported
pub fn is_valid_preferred_username(preferred_username: &str) -> bool { pub fn is_valid_preferred_username(preferred_username: &str) -> bool {
!preferred_username.starts_with("@") && preferred_username.len() >=3 && preferred_username.len() <= 20 !preferred_username.starts_with("@")
&& preferred_username.len() >= 3
&& preferred_username.len() <= 20
} }
pub fn is_valid_community_name(name: &str) -> bool { pub fn is_valid_community_name(name: &str) -> bool {
@ -176,8 +178,8 @@ mod tests {
use crate::{ use crate::{
is_valid_community_name, is_valid_community_name,
is_valid_post_title, is_valid_post_title,
is_valid_username,
is_valid_preferred_username, is_valid_preferred_username,
is_valid_username,
remove_slurs, remove_slurs,
scrape_text_for_mentions, scrape_text_for_mentions,
slur_check, slur_check,

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,
@ -822,7 +823,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("missing creator")?;
let creator_user = admins.remove(creator_index); let creator_user = admins.remove(creator_index);
admins.insert(0, creator_user); admins.insert(0, creator_user);
@ -847,7 +851,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("missing creator")?;
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

@ -17,6 +17,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::*,
@ -655,7 +656,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("missing creator")?;
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;
@ -324,7 +325,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 +495,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 +668,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 +805,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("missing creator")?;
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 +1187,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

@ -16,7 +16,7 @@ use lemmy_db::{
ListingType, ListingType,
SortType, SortType,
}; };
use lemmy_utils::{markdown_to_html, settings::Settings}; use lemmy_utils::{location_info, markdown_to_html, settings::Settings};
use rss::{CategoryBuilder, ChannelBuilder, GuidBuilder, Item, ItemBuilder}; use rss::{CategoryBuilder, ChannelBuilder, GuidBuilder, Item, ItemBuilder};
use serde::Deserialize; use serde::Deserialize;
use std::str::FromStr; use std::str::FromStr;
@ -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,12 @@ 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(|_| anyhow!(location_info!()))?
.to_string(),
)
} }
async fn get_feed( async fn get_feed(
@ -135,7 +140,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 +165,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 +194,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 +223,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 +241,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| {
@ -247,6 +252,7 @@ fn create_reply_and_mention_items(
r.id r.id
); );
build_item(&r.creator_name, &r.published, &reply_url, &r.content) build_item(&r.creator_name, &r.published, &reply_url, &r.content)
.unwrap_or_else(|_| panic!(location_info!()))
}) })
.collect(); .collect();
@ -260,14 +266,20 @@ fn create_reply_and_mention_items(
m.id m.id
); );
build_item(&m.creator_name, &m.published, &mention_url, &m.content) build_item(&m.creator_name, &m.published, &mention_url, &m.content)
.unwrap_or_else(|_| panic!(location_info!()))
}) })
.collect(); .collect();
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 +290,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(|_| anyhow!(location_info!()))?;
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(|_| anyhow!(location_info!()))?)
} }
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 +325,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(|_| anyhow!(location_info!()))?;
i.guid(guid);
let community_url = format!( let community_url = format!(
"https://{}/c/{}", "https://{}/c/{}",
@ -324,8 +341,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(|_| anyhow!(location_info!()))?;
i.categories(vec![category]);
if let Some(url) = p.url { if let Some(url) = p.url {
i.link(url); i.link(url);
@ -348,8 +367,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(|_| anyhow!(location_info!()))?);
} }
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();
} }
} }