Merge pull request 'Fix clippy error upper_case_acronyms' (#172) from fix-clippy into main

Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/172
This commit is contained in:
dessalines 2021-02-22 20:34:22 +00:00
commit 7dc3ff4544
12 changed files with 162 additions and 162 deletions

View file

@ -27,7 +27,7 @@ use lemmy_db_views::{
use lemmy_structs::{blocking, comment::*, send_local_notifs}; use lemmy_structs::{blocking, comment::*, send_local_notifs};
use lemmy_utils::{ use lemmy_utils::{
utils::{remove_slurs, scrape_text_for_mentions}, utils::{remove_slurs, scrape_text_for_mentions},
APIError, ApiError,
ConnectionId, ConnectionId,
LemmyError, LemmyError,
}; };
@ -60,7 +60,7 @@ impl Perform for CreateComment {
// Check if post is locked, no new comments // Check if post is locked, no new comments
if post.locked { if post.locked {
return Err(APIError::err("locked").into()); return Err(ApiError::err("locked").into());
} }
// If there's a parent_id, check to make sure that comment is in that post // If there's a parent_id, check to make sure that comment is in that post
@ -69,10 +69,10 @@ impl Perform for CreateComment {
let parent = let parent =
match blocking(context.pool(), move |conn| Comment::read(&conn, parent_id)).await? { match blocking(context.pool(), move |conn| Comment::read(&conn, parent_id)).await? {
Ok(comment) => comment, Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_create_comment").into()), Err(_e) => return Err(ApiError::err("couldnt_create_comment").into()),
}; };
if parent.post_id != post_id { if parent.post_id != post_id {
return Err(APIError::err("couldnt_create_comment").into()); return Err(ApiError::err("couldnt_create_comment").into());
} }
} }
@ -98,7 +98,7 @@ impl Perform for CreateComment {
.await? .await?
{ {
Ok(comment) => comment, Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_create_comment").into()), Err(_e) => return Err(ApiError::err("couldnt_create_comment").into()),
}; };
// Necessary to update the ap_id // Necessary to update the ap_id
@ -112,7 +112,7 @@ impl Perform for CreateComment {
.await? .await?
{ {
Ok(comment) => comment, Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_create_comment").into()), Err(_e) => return Err(ApiError::err("couldnt_create_comment").into()),
}; };
updated_comment.send_create(&user, context).await?; updated_comment.send_create(&user, context).await?;
@ -140,7 +140,7 @@ impl Perform for CreateComment {
let like = move |conn: &'_ _| CommentLike::like(&conn, &like_form); let like = move |conn: &'_ _| CommentLike::like(&conn, &like_form);
if blocking(context.pool(), like).await?.is_err() { if blocking(context.pool(), like).await?.is_err() {
return Err(APIError::err("couldnt_like_comment").into()); return Err(ApiError::err("couldnt_like_comment").into());
} }
updated_comment.send_like(&user, context).await?; updated_comment.send_like(&user, context).await?;
@ -160,7 +160,7 @@ impl Perform for CreateComment {
.await? .await?
{ {
Ok(comment) => comment, Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_update_comment").into()), Err(_e) => return Err(ApiError::err("couldnt_update_comment").into()),
}; };
comment_view.comment.read = true; comment_view.comment.read = true;
} }
@ -205,7 +205,7 @@ impl Perform for EditComment {
// Verify that only the creator can edit // Verify that only the creator can edit
if user.id != orig_comment.creator.id { if user.id != orig_comment.creator.id {
return Err(APIError::err("no_comment_edit_allowed").into()); return Err(ApiError::err("no_comment_edit_allowed").into());
} }
// Do the update // Do the update
@ -217,7 +217,7 @@ impl Perform for EditComment {
.await? .await?
{ {
Ok(comment) => comment, Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_update_comment").into()), Err(_e) => return Err(ApiError::err("couldnt_update_comment").into()),
}; };
// Send the apub update // Send the apub update
@ -281,7 +281,7 @@ impl Perform for DeleteComment {
// Verify that only the creator can delete // Verify that only the creator can delete
if user.id != orig_comment.creator.id { if user.id != orig_comment.creator.id {
return Err(APIError::err("no_comment_edit_allowed").into()); return Err(ApiError::err("no_comment_edit_allowed").into());
} }
// Do the delete // Do the delete
@ -292,7 +292,7 @@ impl Perform for DeleteComment {
.await? .await?
{ {
Ok(comment) => comment, Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_update_comment").into()), Err(_e) => return Err(ApiError::err("couldnt_update_comment").into()),
}; };
// Send the apub message // Send the apub message
@ -370,7 +370,7 @@ impl Perform for RemoveComment {
.await? .await?
{ {
Ok(comment) => comment, Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_update_comment").into()), Err(_e) => return Err(ApiError::err("couldnt_update_comment").into()),
}; };
// Mod tables // Mod tables
@ -452,7 +452,7 @@ impl Perform for MarkCommentAsRead {
// Verify that only the recipient can mark as read // Verify that only the recipient can mark as read
if user.id != orig_comment.get_recipient_id() { if user.id != orig_comment.get_recipient_id() {
return Err(APIError::err("no_comment_edit_allowed").into()); return Err(ApiError::err("no_comment_edit_allowed").into());
} }
// Do the mark as read // Do the mark as read
@ -463,7 +463,7 @@ impl Perform for MarkCommentAsRead {
.await? .await?
{ {
Ok(comment) => comment, Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_update_comment").into()), Err(_e) => return Err(ApiError::err("couldnt_update_comment").into()),
}; };
// Refetch it // Refetch it
@ -504,12 +504,12 @@ impl Perform for SaveComment {
if data.save { if data.save {
let save_comment = move |conn: &'_ _| CommentSaved::save(conn, &comment_saved_form); let save_comment = move |conn: &'_ _| CommentSaved::save(conn, &comment_saved_form);
if blocking(context.pool(), save_comment).await?.is_err() { if blocking(context.pool(), save_comment).await?.is_err() {
return Err(APIError::err("couldnt_save_comment").into()); return Err(ApiError::err("couldnt_save_comment").into());
} }
} else { } else {
let unsave_comment = move |conn: &'_ _| CommentSaved::unsave(conn, &comment_saved_form); let unsave_comment = move |conn: &'_ _| CommentSaved::unsave(conn, &comment_saved_form);
if blocking(context.pool(), unsave_comment).await?.is_err() { if blocking(context.pool(), unsave_comment).await?.is_err() {
return Err(APIError::err("couldnt_save_comment").into()); return Err(ApiError::err("couldnt_save_comment").into());
} }
} }
@ -577,7 +577,7 @@ impl Perform for CreateCommentLike {
let like_form2 = like_form.clone(); let like_form2 = like_form.clone();
let like = move |conn: &'_ _| CommentLike::like(conn, &like_form2); let like = move |conn: &'_ _| CommentLike::like(conn, &like_form2);
if blocking(context.pool(), like).await?.is_err() { if blocking(context.pool(), like).await?.is_err() {
return Err(APIError::err("couldnt_like_comment").into()); return Err(ApiError::err("couldnt_like_comment").into());
} }
if like_form.score == 1 { if like_form.score == 1 {
@ -647,7 +647,7 @@ impl Perform for GetComments {
.await?; .await?;
let comments = match comments { let comments = match comments {
Ok(comments) => comments, Ok(comments) => comments,
Err(_) => return Err(APIError::err("couldnt_get_comments").into()), Err(_) => return Err(ApiError::err("couldnt_get_comments").into()),
}; };
Ok(GetCommentsResponse { comments }) Ok(GetCommentsResponse { comments })
@ -670,10 +670,10 @@ impl Perform for CreateCommentReport {
// check size of report and check for whitespace // check size of report and check for whitespace
let reason = data.reason.trim(); let reason = data.reason.trim();
if reason.is_empty() { if reason.is_empty() {
return Err(APIError::err("report_reason_required").into()); return Err(ApiError::err("report_reason_required").into());
} }
if reason.chars().count() > 1000 { if reason.chars().count() > 1000 {
return Err(APIError::err("report_too_long").into()); return Err(ApiError::err("report_too_long").into());
} }
let user_id = user.id; let user_id = user.id;
@ -698,7 +698,7 @@ impl Perform for CreateCommentReport {
.await? .await?
{ {
Ok(report) => report, Ok(report) => report,
Err(_e) => return Err(APIError::err("couldnt_create_report").into()), Err(_e) => return Err(ApiError::err("couldnt_create_report").into()),
}; };
let res = CreateCommentReportResponse { success: true }; let res = CreateCommentReportResponse { success: true };
@ -753,7 +753,7 @@ impl Perform for ResolveCommentReport {
}; };
if blocking(context.pool(), resolve_fun).await?.is_err() { if blocking(context.pool(), resolve_fun).await?.is_err() {
return Err(APIError::err("couldnt_resolve_report").into()); return Err(ApiError::err("couldnt_resolve_report").into());
}; };
let report_id = data.report_id; let report_id = data.report_id;

View file

@ -48,7 +48,7 @@ use lemmy_utils::{
apub::generate_actor_keypair, apub::generate_actor_keypair,
location_info, location_info,
utils::{check_slurs, check_slurs_opt, is_valid_community_name, naive_from_unix}, utils::{check_slurs, check_slurs_opt, is_valid_community_name, naive_from_unix},
APIError, ApiError,
ConnectionId, ConnectionId,
LemmyError, LemmyError,
}; };
@ -82,7 +82,7 @@ impl Perform for GetCommunity {
.await? .await?
{ {
Ok(community) => community, Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()), Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
} }
.id .id
} }
@ -94,7 +94,7 @@ impl Perform for GetCommunity {
.await? .await?
{ {
Ok(community) => community, Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()), Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
}; };
let moderators: Vec<CommunityModeratorView> = match blocking(context.pool(), move |conn| { let moderators: Vec<CommunityModeratorView> = match blocking(context.pool(), move |conn| {
@ -103,7 +103,7 @@ impl Perform for GetCommunity {
.await? .await?
{ {
Ok(moderators) => moderators, Ok(moderators) => moderators,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()), Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
}; };
let online = context let online = context
@ -140,7 +140,7 @@ impl Perform for CreateCommunity {
check_slurs_opt(&data.description)?; check_slurs_opt(&data.description)?;
if !is_valid_community_name(&data.name) { if !is_valid_community_name(&data.name) {
return Err(APIError::err("invalid_community_name").into()); return Err(ApiError::err("invalid_community_name").into());
} }
// Double check for duplicate community actor_ids // Double check for duplicate community actor_ids
@ -151,7 +151,7 @@ impl Perform for CreateCommunity {
}) })
.await?; .await?;
if community_dupe.is_ok() { if community_dupe.is_ok() {
return Err(APIError::err("community_already_exists").into()); return Err(ApiError::err("community_already_exists").into());
} }
// Check to make sure the icon and banners are urls // Check to make sure the icon and banners are urls
@ -193,7 +193,7 @@ impl Perform for CreateCommunity {
.await? .await?
{ {
Ok(community) => community, Ok(community) => community,
Err(_e) => return Err(APIError::err("community_already_exists").into()), Err(_e) => return Err(ApiError::err("community_already_exists").into()),
}; };
// The community creator becomes a moderator // The community creator becomes a moderator
@ -204,7 +204,7 @@ impl Perform for CreateCommunity {
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() { if blocking(context.pool(), join).await?.is_err() {
return Err(APIError::err("community_moderator_already_exists").into()); return Err(ApiError::err("community_moderator_already_exists").into());
} }
// Follow your own community // Follow your own community
@ -216,7 +216,7 @@ impl Perform for CreateCommunity {
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
if blocking(context.pool(), follow).await?.is_err() { if blocking(context.pool(), follow).await?.is_err() {
return Err(APIError::err("community_follower_already_exists").into()); return Err(ApiError::err("community_follower_already_exists").into());
} }
let user_id = user.id; let user_id = user.id;
@ -252,7 +252,7 @@ impl Perform for EditCommunity {
}) })
.await??; .await??;
if !mods.contains(&user.id) { if !mods.contains(&user.id) {
return Err(APIError::err("not_a_moderator").into()); return Err(ApiError::err("not_a_moderator").into());
} }
let community_id = data.community_id; let community_id = data.community_id;
@ -297,7 +297,7 @@ impl Perform for EditCommunity {
.await? .await?
{ {
Ok(community) => community, Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_update_community").into()), Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
}; };
// TODO there needs to be some kind of an apub update // TODO there needs to be some kind of an apub update
@ -337,7 +337,7 @@ impl Perform for DeleteCommunity {
}) })
.await??; .await??;
if read_community.creator_id != user.id { if read_community.creator_id != user.id {
return Err(APIError::err("no_community_edit_allowed").into()); return Err(ApiError::err("no_community_edit_allowed").into());
} }
// Do the delete // Do the delete
@ -349,7 +349,7 @@ impl Perform for DeleteCommunity {
.await? .await?
{ {
Ok(community) => community, Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_update_community").into()), Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
}; };
// Send apub messages // Send apub messages
@ -398,7 +398,7 @@ impl Perform for RemoveCommunity {
.await? .await?
{ {
Ok(community) => community, Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_update_community").into()), Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
}; };
// Mod tables // Mod tables
@ -513,13 +513,13 @@ impl Perform for FollowCommunity {
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
if blocking(context.pool(), follow).await?.is_err() { if blocking(context.pool(), follow).await?.is_err() {
return Err(APIError::err("community_follower_already_exists").into()); return Err(ApiError::err("community_follower_already_exists").into());
} }
} else { } else {
let unfollow = let unfollow =
move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
if blocking(context.pool(), unfollow).await?.is_err() { if blocking(context.pool(), unfollow).await?.is_err() {
return Err(APIError::err("community_follower_already_exists").into()); return Err(ApiError::err("community_follower_already_exists").into());
} }
} }
} else if data.follow { } else if data.follow {
@ -530,7 +530,7 @@ impl Perform for FollowCommunity {
user.send_unfollow(&community.actor_id(), context).await?; user.send_unfollow(&community.actor_id(), context).await?;
let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
if blocking(context.pool(), unfollow).await?.is_err() { if blocking(context.pool(), unfollow).await?.is_err() {
return Err(APIError::err("community_follower_already_exists").into()); return Err(ApiError::err("community_follower_already_exists").into());
} }
} }
@ -571,7 +571,7 @@ impl Perform for GetFollowedCommunities {
.await? .await?
{ {
Ok(communities) => communities, Ok(communities) => communities,
_ => return Err(APIError::err("system_err_login").into()), _ => return Err(ApiError::err("system_err_login").into()),
}; };
// Return the jwt // Return the jwt
@ -605,7 +605,7 @@ impl Perform for BanFromCommunity {
if data.ban { if data.ban {
let ban = move |conn: &'_ _| CommunityUserBan::ban(conn, &community_user_ban_form); let ban = move |conn: &'_ _| CommunityUserBan::ban(conn, &community_user_ban_form);
if blocking(context.pool(), ban).await?.is_err() { if blocking(context.pool(), ban).await?.is_err() {
return Err(APIError::err("community_user_already_banned").into()); return Err(ApiError::err("community_user_already_banned").into());
} }
// Also unsubscribe them from the community, if they are subscribed // Also unsubscribe them from the community, if they are subscribed
@ -622,7 +622,7 @@ impl Perform for BanFromCommunity {
} else { } else {
let unban = move |conn: &'_ _| CommunityUserBan::unban(conn, &community_user_ban_form); let unban = move |conn: &'_ _| CommunityUserBan::unban(conn, &community_user_ban_form);
if blocking(context.pool(), unban).await?.is_err() { if blocking(context.pool(), unban).await?.is_err() {
return Err(APIError::err("community_user_already_banned").into()); return Err(ApiError::err("community_user_already_banned").into());
} }
} }
@ -721,12 +721,12 @@ impl Perform for AddModToCommunity {
if data.added { if data.added {
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() { if blocking(context.pool(), join).await?.is_err() {
return Err(APIError::err("community_moderator_already_exists").into()); return Err(ApiError::err("community_moderator_already_exists").into());
} }
} else { } else {
let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form); let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form);
if blocking(context.pool(), leave).await?.is_err() { if blocking(context.pool(), leave).await?.is_err() {
return Err(APIError::err("community_moderator_already_exists").into()); return Err(ApiError::err("community_moderator_already_exists").into());
} }
} }
@ -798,14 +798,14 @@ impl Perform for TransferCommunity {
if user.id != read_community.creator_id if user.id != read_community.creator_id
&& !admins.iter().map(|a| a.user.id).any(|x| x == user.id) && !admins.iter().map(|a| a.user.id).any(|x| x == user.id)
{ {
return Err(APIError::err("not_an_admin").into()); return Err(ApiError::err("not_an_admin").into());
} }
let community_id = data.community_id; let community_id = data.community_id;
let new_creator = data.user_id; let new_creator = data.user_id;
let update = move |conn: &'_ _| Community::update_creator(conn, community_id, new_creator); let update = move |conn: &'_ _| Community::update_creator(conn, community_id, new_creator);
if blocking(context.pool(), update).await?.is_err() { if blocking(context.pool(), update).await?.is_err() {
return Err(APIError::err("couldnt_update_community").into()); return Err(ApiError::err("couldnt_update_community").into());
}; };
// You also have to re-do the community_moderator table, reordering it. // You also have to re-do the community_moderator table, reordering it.
@ -836,7 +836,7 @@ impl Perform for TransferCommunity {
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() { if blocking(context.pool(), join).await?.is_err() {
return Err(APIError::err("community_moderator_already_exists").into()); return Err(ApiError::err("community_moderator_already_exists").into());
} }
} }
@ -860,7 +860,7 @@ impl Perform for TransferCommunity {
.await? .await?
{ {
Ok(community) => community, Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()), Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
}; };
let community_id = data.community_id; let community_id = data.community_id;
@ -870,7 +870,7 @@ impl Perform for TransferCommunity {
.await? .await?
{ {
Ok(moderators) => moderators, Ok(moderators) => moderators,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()), Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
}; };
// Return the jwt // Return the jwt

View file

@ -19,7 +19,7 @@ use lemmy_db_views_actor::{
community_view::CommunityView, community_view::CommunityView,
}; };
use lemmy_structs::{blocking, comment::*, community::*, post::*, site::*, user::*, websocket::*}; use lemmy_structs::{blocking, comment::*, community::*, post::*, site::*, user::*, websocket::*};
use lemmy_utils::{claims::Claims, settings::Settings, APIError, ConnectionId, LemmyError}; use lemmy_utils::{claims::Claims, settings::Settings, ApiError, ConnectionId, LemmyError};
use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperation}; use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperation};
use serde::Deserialize; use serde::Deserialize;
use std::process::Command; use std::process::Command;
@ -54,14 +54,14 @@ pub(crate) async fn is_mod_or_admin(
}) })
.await?; .await?;
if !is_mod_or_admin { if !is_mod_or_admin {
return Err(APIError::err("not_a_mod_or_admin").into()); return Err(ApiError::err("not_a_mod_or_admin").into());
} }
Ok(()) Ok(())
} }
pub async fn is_admin(pool: &DbPool, user_id: i32) -> Result<(), LemmyError> { pub async fn is_admin(pool: &DbPool, user_id: i32) -> Result<(), LemmyError> {
let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??; let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
if !user.admin { if !user.admin {
return Err(APIError::err("not_an_admin").into()); return Err(ApiError::err("not_an_admin").into());
} }
Ok(()) Ok(())
} }
@ -69,20 +69,20 @@ pub async fn is_admin(pool: &DbPool, user_id: i32) -> Result<(), LemmyError> {
pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result<Post, LemmyError> { pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result<Post, LemmyError> {
match blocking(pool, move |conn| Post::read(conn, post_id)).await? { match blocking(pool, move |conn| Post::read(conn, post_id)).await? {
Ok(post) => Ok(post), Ok(post) => Ok(post),
Err(_e) => Err(APIError::err("couldnt_find_post").into()), Err(_e) => Err(ApiError::err("couldnt_find_post").into()),
} }
} }
pub(crate) async fn get_user_from_jwt(jwt: &str, pool: &DbPool) -> Result<User_, LemmyError> { pub(crate) async fn get_user_from_jwt(jwt: &str, pool: &DbPool) -> Result<User_, LemmyError> {
let claims = match Claims::decode(&jwt) { let claims = match Claims::decode(&jwt) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
Err(_e) => return Err(APIError::err("not_logged_in").into()), Err(_e) => return Err(ApiError::err("not_logged_in").into()),
}; };
let user_id = claims.id; let user_id = claims.id;
let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??; let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
// Check for a site ban // Check for a site ban
if user.banned { if user.banned {
return Err(APIError::err("site_ban").into()); return Err(ApiError::err("site_ban").into());
} }
Ok(user) Ok(user)
} }
@ -103,13 +103,13 @@ pub(crate) async fn get_user_safe_settings_from_jwt(
) -> Result<UserSafeSettings, LemmyError> { ) -> Result<UserSafeSettings, LemmyError> {
let claims = match Claims::decode(&jwt) { let claims = match Claims::decode(&jwt) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
Err(_e) => return Err(APIError::err("not_logged_in").into()), Err(_e) => return Err(ApiError::err("not_logged_in").into()),
}; };
let user_id = claims.id; let user_id = claims.id;
let user = blocking(pool, move |conn| UserSafeSettings::read(conn, user_id)).await??; let user = blocking(pool, move |conn| UserSafeSettings::read(conn, user_id)).await??;
// Check for a site ban // Check for a site ban
if user.banned { if user.banned {
return Err(APIError::err("site_ban").into()); return Err(ApiError::err("site_ban").into());
} }
Ok(user) Ok(user)
} }
@ -131,7 +131,7 @@ pub(crate) async fn check_community_ban(
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let is_banned = move |conn: &'_ _| CommunityUserBanView::get(conn, user_id, community_id).is_ok(); let is_banned = move |conn: &'_ _| CommunityUserBanView::get(conn, user_id, community_id).is_ok();
if blocking(pool, is_banned).await? { if blocking(pool, is_banned).await? {
Err(APIError::err("community_ban").into()) Err(ApiError::err("community_ban").into())
} else { } else {
Ok(()) Ok(())
} }
@ -141,7 +141,7 @@ pub(crate) async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result
if score == -1 { if score == -1 {
let site = blocking(pool, move |conn| Site::read_simple(conn)).await??; let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
if !site.enable_downvotes { if !site.enable_downvotes {
return Err(APIError::err("downvotes_disabled").into()); return Err(ApiError::err("downvotes_disabled").into());
} }
} }
Ok(()) Ok(())
@ -175,7 +175,7 @@ pub(crate) async fn collect_moderated_communities(
pub(crate) fn check_optional_url(item: &Option<Option<String>>) -> Result<(), LemmyError> { pub(crate) fn check_optional_url(item: &Option<Option<String>>) -> Result<(), LemmyError> {
if let Some(Some(item)) = &item { if let Some(Some(item)) = &item {
if Url::parse(item).is_err() { if Url::parse(item).is_err() {
return Err(APIError::err("invalid_url").into()); return Err(ApiError::err("invalid_url").into());
} }
} }
Ok(()) Ok(())

View file

@ -40,7 +40,7 @@ use lemmy_structs::{blocking, post::*};
use lemmy_utils::{ use lemmy_utils::{
request::fetch_iframely_and_pictrs_data, request::fetch_iframely_and_pictrs_data,
utils::{check_slurs, check_slurs_opt, is_valid_post_title}, utils::{check_slurs, check_slurs_opt, is_valid_post_title},
APIError, ApiError,
ConnectionId, ConnectionId,
LemmyError, LemmyError,
}; };
@ -67,7 +67,7 @@ impl Perform for CreatePost {
check_slurs_opt(&data.body)?; check_slurs_opt(&data.body)?;
if !is_valid_post_title(&data.name) { if !is_valid_post_title(&data.name) {
return Err(APIError::err("invalid_post_title").into()); return Err(ApiError::err("invalid_post_title").into());
} }
check_community_ban(user.id, data.community_id, context.pool()).await?; check_community_ban(user.id, data.community_id, context.pool()).await?;
@ -109,7 +109,7 @@ impl Perform for CreatePost {
"couldnt_create_post" "couldnt_create_post"
}; };
return Err(APIError::err(err_type).into()); return Err(ApiError::err(err_type).into());
} }
}; };
@ -121,7 +121,7 @@ impl Perform for CreatePost {
.await? .await?
{ {
Ok(post) => post, Ok(post) => post,
Err(_e) => return Err(APIError::err("couldnt_create_post").into()), Err(_e) => return Err(ApiError::err("couldnt_create_post").into()),
}; };
updated_post.send_create(&user, context).await?; updated_post.send_create(&user, context).await?;
@ -135,7 +135,7 @@ impl Perform for CreatePost {
let like = move |conn: &'_ _| PostLike::like(conn, &like_form); let like = move |conn: &'_ _| PostLike::like(conn, &like_form);
if blocking(context.pool(), like).await?.is_err() { if blocking(context.pool(), like).await?.is_err() {
return Err(APIError::err("couldnt_like_post").into()); return Err(ApiError::err("couldnt_like_post").into());
} }
updated_post.send_like(&user, context).await?; updated_post.send_like(&user, context).await?;
@ -148,7 +148,7 @@ impl Perform for CreatePost {
.await? .await?
{ {
Ok(post) => post, Ok(post) => post,
Err(_e) => return Err(APIError::err("couldnt_find_post").into()), Err(_e) => return Err(ApiError::err("couldnt_find_post").into()),
}; };
let res = PostResponse { post_view }; let res = PostResponse { post_view };
@ -183,7 +183,7 @@ impl Perform for GetPost {
.await? .await?
{ {
Ok(post) => post, Ok(post) => post,
Err(_e) => return Err(APIError::err("couldnt_find_post").into()), Err(_e) => return Err(ApiError::err("couldnt_find_post").into()),
}; };
let id = data.id; let id = data.id;
@ -209,7 +209,7 @@ impl Perform for GetPost {
.await? .await?
{ {
Ok(community) => community, Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()), Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
}; };
let online = context let online = context
@ -273,7 +273,7 @@ impl Perform for GetPosts {
.await? .await?
{ {
Ok(posts) => posts, Ok(posts) => posts,
Err(_e) => return Err(APIError::err("couldnt_get_posts").into()), Err(_e) => return Err(ApiError::err("couldnt_get_posts").into()),
}; };
Ok(GetPostsResponse { posts }) Ok(GetPostsResponse { posts })
@ -320,7 +320,7 @@ impl Perform for CreatePostLike {
let like_form2 = like_form.clone(); let like_form2 = like_form.clone();
let like = move |conn: &'_ _| PostLike::like(conn, &like_form2); let like = move |conn: &'_ _| PostLike::like(conn, &like_form2);
if blocking(context.pool(), like).await?.is_err() { if blocking(context.pool(), like).await?.is_err() {
return Err(APIError::err("couldnt_like_post").into()); return Err(ApiError::err("couldnt_like_post").into());
} }
if like_form.score == 1 { if like_form.score == 1 {
@ -340,7 +340,7 @@ impl Perform for CreatePostLike {
.await? .await?
{ {
Ok(post) => post, Ok(post) => post,
Err(_e) => return Err(APIError::err("couldnt_find_post").into()), Err(_e) => return Err(ApiError::err("couldnt_find_post").into()),
}; };
let res = PostResponse { post_view }; let res = PostResponse { post_view };
@ -371,7 +371,7 @@ impl Perform for EditPost {
check_slurs_opt(&data.body)?; check_slurs_opt(&data.body)?;
if !is_valid_post_title(&data.name) { if !is_valid_post_title(&data.name) {
return Err(APIError::err("invalid_post_title").into()); return Err(ApiError::err("invalid_post_title").into());
} }
let post_id = data.post_id; let post_id = data.post_id;
@ -381,7 +381,7 @@ impl Perform for EditPost {
// Verify that only the creator can edit // Verify that only the creator can edit
if !Post::is_post_creator(user.id, orig_post.creator_id) { if !Post::is_post_creator(user.id, orig_post.creator_id) {
return Err(APIError::err("no_post_edit_allowed").into()); return Err(ApiError::err("no_post_edit_allowed").into());
} }
// Fetch Iframely and Pictrs cached image // Fetch Iframely and Pictrs cached image
@ -423,7 +423,7 @@ impl Perform for EditPost {
"couldnt_update_post" "couldnt_update_post"
}; };
return Err(APIError::err(err_type).into()); return Err(ApiError::err(err_type).into());
} }
}; };
@ -467,7 +467,7 @@ impl Perform for DeletePost {
// Verify that only the creator can delete // Verify that only the creator can delete
if !Post::is_post_creator(user.id, orig_post.creator_id) { if !Post::is_post_creator(user.id, orig_post.creator_id) {
return Err(APIError::err("no_post_edit_allowed").into()); return Err(ApiError::err("no_post_edit_allowed").into());
} }
// Update the post // Update the post
@ -711,12 +711,12 @@ impl Perform for SavePost {
if data.save { if data.save {
let save = move |conn: &'_ _| PostSaved::save(conn, &post_saved_form); let save = move |conn: &'_ _| PostSaved::save(conn, &post_saved_form);
if blocking(context.pool(), save).await?.is_err() { if blocking(context.pool(), save).await?.is_err() {
return Err(APIError::err("couldnt_save_post").into()); return Err(ApiError::err("couldnt_save_post").into());
} }
} else { } else {
let unsave = move |conn: &'_ _| PostSaved::unsave(conn, &post_saved_form); let unsave = move |conn: &'_ _| PostSaved::unsave(conn, &post_saved_form);
if blocking(context.pool(), unsave).await?.is_err() { if blocking(context.pool(), unsave).await?.is_err() {
return Err(APIError::err("couldnt_save_post").into()); return Err(ApiError::err("couldnt_save_post").into());
} }
} }
@ -747,10 +747,10 @@ impl Perform for CreatePostReport {
// check size of report and check for whitespace // check size of report and check for whitespace
let reason = data.reason.trim(); let reason = data.reason.trim();
if reason.is_empty() { if reason.is_empty() {
return Err(APIError::err("report_reason_required").into()); return Err(ApiError::err("report_reason_required").into());
} }
if reason.chars().count() > 1000 { if reason.chars().count() > 1000 {
return Err(APIError::err("report_too_long").into()); return Err(ApiError::err("report_too_long").into());
} }
let user_id = user.id; let user_id = user.id;
@ -777,7 +777,7 @@ impl Perform for CreatePostReport {
.await? .await?
{ {
Ok(report) => report, Ok(report) => report,
Err(_e) => return Err(APIError::err("couldnt_create_report").into()), Err(_e) => return Err(ApiError::err("couldnt_create_report").into()),
}; };
let res = CreatePostReportResponse { success: true }; let res = CreatePostReportResponse { success: true };
@ -837,7 +837,7 @@ impl Perform for ResolvePostReport {
}; };
if blocking(context.pool(), resolve_fun).await?.is_err() { if blocking(context.pool(), resolve_fun).await?.is_err() {
return Err(APIError::err("couldnt_resolve_report").into()); return Err(ApiError::err("couldnt_resolve_report").into());
}; };
context.chat_server().do_send(SendModRoomMessage { context.chat_server().do_send(SendModRoomMessage {

View file

@ -51,7 +51,7 @@ use lemmy_utils::{
settings::Settings, settings::Settings,
utils::{check_slurs, check_slurs_opt}, utils::{check_slurs, check_slurs_opt},
version, version,
APIError, ApiError,
ConnectionId, ConnectionId,
LemmyError, LemmyError,
}; };
@ -168,7 +168,7 @@ impl Perform for CreateSite {
let read_site = move |conn: &'_ _| Site::read_simple(conn); let read_site = move |conn: &'_ _| Site::read_simple(conn);
if blocking(context.pool(), read_site).await?.is_ok() { if blocking(context.pool(), read_site).await?.is_ok() {
return Err(APIError::err("site_already_exists").into()); return Err(ApiError::err("site_already_exists").into());
}; };
let user = get_user_from_jwt(&data.auth, context.pool()).await?; let user = get_user_from_jwt(&data.auth, context.pool()).await?;
@ -193,7 +193,7 @@ impl Perform for CreateSite {
let create_site = move |conn: &'_ _| Site::create(conn, &site_form); let create_site = move |conn: &'_ _| Site::create(conn, &site_form);
if blocking(context.pool(), create_site).await?.is_err() { if blocking(context.pool(), create_site).await?.is_err() {
return Err(APIError::err("site_already_exists").into()); return Err(ApiError::err("site_already_exists").into());
} }
let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
@ -238,7 +238,7 @@ impl Perform for EditSite {
let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form); let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form);
if blocking(context.pool(), update_site).await?.is_err() { if blocking(context.pool(), update_site).await?.is_err() {
return Err(APIError::err("couldnt_update_site").into()); return Err(ApiError::err("couldnt_update_site").into());
} }
let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
@ -525,13 +525,13 @@ impl Perform for TransferSite {
// Make sure user is the creator // Make sure user is the creator
if read_site.creator_id != user.id { if read_site.creator_id != user.id {
return Err(APIError::err("not_an_admin").into()); return Err(ApiError::err("not_an_admin").into());
} }
let new_creator_id = data.user_id; let new_creator_id = data.user_id;
let transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id); let transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id);
if blocking(context.pool(), transfer_site).await?.is_err() { if blocking(context.pool(), transfer_site).await?.is_err() {
return Err(APIError::err("couldnt_update_site").into()); return Err(ApiError::err("couldnt_update_site").into());
}; };
// Mod tables // Mod tables
@ -608,7 +608,7 @@ impl Perform for SaveSiteConfig {
// Make sure docker doesn't have :ro at the end of the volume, so its not a read-only filesystem // Make sure docker doesn't have :ro at the end of the volume, so its not a read-only filesystem
let config_hjson = match Settings::save_config_file(&data.config_hjson) { let config_hjson = match Settings::save_config_file(&data.config_hjson) {
Ok(config_hjson) => config_hjson, Ok(config_hjson) => config_hjson,
Err(_e) => return Err(APIError::err("couldnt_update_site").into()), Err(_e) => return Err(ApiError::err("couldnt_update_site").into()),
}; };
Ok(GetSiteConfigResponse { config_hjson }) Ok(GetSiteConfigResponse { config_hjson })

View file

@ -80,7 +80,7 @@ use lemmy_utils::{
naive_from_unix, naive_from_unix,
remove_slurs, remove_slurs,
}, },
APIError, ApiError,
ConnectionId, ConnectionId,
LemmyError, LemmyError,
}; };
@ -110,13 +110,13 @@ impl Perform for Login {
.await? .await?
{ {
Ok(user) => user, Ok(user) => user,
Err(_e) => return Err(APIError::err("couldnt_find_that_username_or_email").into()), Err(_e) => return Err(ApiError::err("couldnt_find_that_username_or_email").into()),
}; };
// Verify the password // Verify the password
let valid: bool = verify(&data.password, &user.password_encrypted).unwrap_or(false); let valid: bool = verify(&data.password, &user.password_encrypted).unwrap_or(false);
if !valid { if !valid {
return Err(APIError::err("password_incorrect").into()); return Err(ApiError::err("password_incorrect").into());
} }
// Return the jwt // Return the jwt
@ -140,18 +140,18 @@ impl Perform for Register {
// Make sure site has open registration // Make sure site has open registration
if let Ok(site) = blocking(context.pool(), move |conn| Site::read_simple(conn)).await? { if let Ok(site) = blocking(context.pool(), move |conn| Site::read_simple(conn)).await? {
if !site.open_registration { if !site.open_registration {
return Err(APIError::err("registration_closed").into()); return Err(ApiError::err("registration_closed").into());
} }
} }
// Password length check // Password length check
if data.password.len() > 60 { if data.password.len() > 60 {
return Err(APIError::err("invalid_password").into()); return Err(ApiError::err("invalid_password").into());
} }
// Make sure passwords match // Make sure passwords match
if data.password != data.password_verify { if data.password != data.password_verify {
return Err(APIError::err("passwords_dont_match").into()); return Err(ApiError::err("passwords_dont_match").into());
} }
// Check if there are admins. False if admins exist // Check if there are admins. False if admins exist
@ -176,7 +176,7 @@ impl Perform for Register {
}) })
.await?; .await?;
if !check { if !check {
return Err(APIError::err("captcha_incorrect").into()); return Err(ApiError::err("captcha_incorrect").into());
} }
} }
@ -184,7 +184,7 @@ impl Perform for Register {
let user_keypair = generate_actor_keypair()?; let user_keypair = generate_actor_keypair()?;
if !is_valid_username(&data.username) { if !is_valid_username(&data.username) {
return Err(APIError::err("invalid_username").into()); return Err(ApiError::err("invalid_username").into());
} }
let user_actor_id = generate_apub_endpoint(EndpointType::User, &data.username)?; let user_actor_id = generate_apub_endpoint(EndpointType::User, &data.username)?;
@ -234,7 +234,7 @@ impl Perform for Register {
"user_already_exists" "user_already_exists"
}; };
return Err(APIError::err(err_type).into()); return Err(ApiError::err(err_type).into());
} }
}; };
@ -285,7 +285,7 @@ impl Perform for Register {
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
if blocking(context.pool(), follow).await?.is_err() { if blocking(context.pool(), follow).await?.is_err() {
return Err(APIError::err("community_follower_already_exists").into()); return Err(ApiError::err("community_follower_already_exists").into());
}; };
// If its an admin, add them as a mod and follower to main // If its an admin, add them as a mod and follower to main
@ -297,7 +297,7 @@ impl Perform for Register {
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() { if blocking(context.pool(), join).await?.is_err() {
return Err(APIError::err("community_moderator_already_exists").into()); return Err(ApiError::err("community_moderator_already_exists").into());
} }
} }
@ -380,13 +380,13 @@ impl Perform for SaveUserSettings {
if let Some(Some(bio)) = &bio { if let Some(Some(bio)) = &bio {
if bio.chars().count() > 300 { if bio.chars().count() > 300 {
return Err(APIError::err("bio_length_overflow").into()); return Err(ApiError::err("bio_length_overflow").into());
} }
} }
if let Some(Some(preferred_username)) = &preferred_username { if let Some(Some(preferred_username)) = &preferred_username {
if !is_valid_preferred_username(preferred_username.trim()) { if !is_valid_preferred_username(preferred_username.trim()) {
return Err(APIError::err("invalid_username").into()); return Err(ApiError::err("invalid_username").into());
} }
} }
@ -397,7 +397,7 @@ impl Perform for SaveUserSettings {
Some(new_password_verify) => { Some(new_password_verify) => {
// Make sure passwords match // Make sure passwords match
if new_password != new_password_verify { if new_password != new_password_verify {
return Err(APIError::err("passwords_dont_match").into()); return Err(ApiError::err("passwords_dont_match").into());
} }
// Check the old password // Check the old password
@ -405,7 +405,7 @@ impl Perform for SaveUserSettings {
Some(old_password) => { Some(old_password) => {
let valid: bool = verify(old_password, &user.password_encrypted).unwrap_or(false); let valid: bool = verify(old_password, &user.password_encrypted).unwrap_or(false);
if !valid { if !valid {
return Err(APIError::err("password_incorrect").into()); return Err(ApiError::err("password_incorrect").into());
} }
let new_password = new_password.to_owned(); let new_password = new_password.to_owned();
let user = blocking(context.pool(), move |conn| { let user = blocking(context.pool(), move |conn| {
@ -414,10 +414,10 @@ impl Perform for SaveUserSettings {
.await??; .await??;
user.password_encrypted user.password_encrypted
} }
None => return Err(APIError::err("password_incorrect").into()), None => return Err(ApiError::err("password_incorrect").into()),
} }
} }
None => return Err(APIError::err("passwords_dont_match").into()), None => return Err(ApiError::err("passwords_dont_match").into()),
} }
} }
None => user.password_encrypted, None => user.password_encrypted,
@ -470,7 +470,7 @@ impl Perform for SaveUserSettings {
"user_already_exists" "user_already_exists"
}; };
return Err(APIError::err(err_type).into()); return Err(ApiError::err(err_type).into());
} }
}; };
@ -513,7 +513,7 @@ impl Perform for GetUserDetails {
.await?; .await?;
match user { match user {
Ok(user) => user.id, Ok(user) => user.id,
Err(_e) => return Err(APIError::err("couldnt_find_that_username_or_email").into()), Err(_e) => return Err(ApiError::err("couldnt_find_that_username_or_email").into()),
} }
} }
}; };
@ -607,7 +607,7 @@ impl Perform for AddAdmin {
let added_user_id = data.user_id; let added_user_id = data.user_id;
let add_admin = move |conn: &'_ _| User_::add_admin(conn, added_user_id, added); let add_admin = move |conn: &'_ _| User_::add_admin(conn, added_user_id, added);
if blocking(context.pool(), add_admin).await?.is_err() { if blocking(context.pool(), add_admin).await?.is_err() {
return Err(APIError::err("couldnt_update_user").into()); return Err(ApiError::err("couldnt_update_user").into());
} }
// Mod tables // Mod tables
@ -663,7 +663,7 @@ impl Perform for BanUser {
let banned_user_id = data.user_id; let banned_user_id = data.user_id;
let ban_user = move |conn: &'_ _| User_::ban_user(conn, banned_user_id, ban); let ban_user = move |conn: &'_ _| User_::ban_user(conn, banned_user_id, ban);
if blocking(context.pool(), ban_user).await?.is_err() { if blocking(context.pool(), ban_user).await?.is_err() {
return Err(APIError::err("couldnt_update_user").into()); return Err(ApiError::err("couldnt_update_user").into());
} }
// Remove their data if that's desired // Remove their data if that's desired
@ -811,14 +811,14 @@ impl Perform for MarkUserMentionAsRead {
.await??; .await??;
if user.id != read_user_mention.recipient_id { if user.id != read_user_mention.recipient_id {
return Err(APIError::err("couldnt_update_comment").into()); return Err(ApiError::err("couldnt_update_comment").into());
} }
let user_mention_id = read_user_mention.id; let user_mention_id = read_user_mention.id;
let read = data.read; let read = data.read;
let update_mention = move |conn: &'_ _| UserMention::update_read(conn, user_mention_id, read); let update_mention = move |conn: &'_ _| UserMention::update_read(conn, user_mention_id, read);
if blocking(context.pool(), update_mention).await?.is_err() { if blocking(context.pool(), update_mention).await?.is_err() {
return Err(APIError::err("couldnt_update_comment").into()); return Err(ApiError::err("couldnt_update_comment").into());
}; };
let user_mention_id = read_user_mention.id; let user_mention_id = read_user_mention.id;
@ -863,7 +863,7 @@ impl Perform for MarkAllAsRead {
let reply_id = comment_view.comment.id; let reply_id = comment_view.comment.id;
let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true); let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true);
if blocking(context.pool(), mark_as_read).await?.is_err() { if blocking(context.pool(), mark_as_read).await?.is_err() {
return Err(APIError::err("couldnt_update_comment").into()); return Err(ApiError::err("couldnt_update_comment").into());
} }
} }
@ -873,13 +873,13 @@ impl Perform for MarkAllAsRead {
.await? .await?
.is_err() .is_err()
{ {
return Err(APIError::err("couldnt_update_comment").into()); return Err(ApiError::err("couldnt_update_comment").into());
} }
// Mark all private_messages as read // Mark all private_messages as read
let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, user_id); let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, user_id);
if blocking(context.pool(), update_pm).await?.is_err() { if blocking(context.pool(), update_pm).await?.is_err() {
return Err(APIError::err("couldnt_update_private_message").into()); return Err(ApiError::err("couldnt_update_private_message").into());
} }
Ok(GetRepliesResponse { replies: vec![] }) Ok(GetRepliesResponse { replies: vec![] })
@ -901,20 +901,20 @@ impl Perform for DeleteAccount {
// Verify the password // Verify the password
let valid: bool = verify(&data.password, &user.password_encrypted).unwrap_or(false); let valid: bool = verify(&data.password, &user.password_encrypted).unwrap_or(false);
if !valid { if !valid {
return Err(APIError::err("password_incorrect").into()); return Err(ApiError::err("password_incorrect").into());
} }
// Comments // Comments
let user_id = user.id; let user_id = user.id;
let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, user_id); let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, user_id);
if blocking(context.pool(), permadelete).await?.is_err() { if blocking(context.pool(), permadelete).await?.is_err() {
return Err(APIError::err("couldnt_update_comment").into()); return Err(ApiError::err("couldnt_update_comment").into());
} }
// Posts // Posts
let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, user_id); let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, user_id);
if blocking(context.pool(), permadelete).await?.is_err() { if blocking(context.pool(), permadelete).await?.is_err() {
return Err(APIError::err("couldnt_update_post").into()); return Err(ApiError::err("couldnt_update_post").into());
} }
blocking(context.pool(), move |conn| { blocking(context.pool(), move |conn| {
@ -947,7 +947,7 @@ impl Perform for PasswordReset {
.await? .await?
{ {
Ok(user) => user, Ok(user) => user,
Err(_e) => return Err(APIError::err("couldnt_find_that_username_or_email").into()), Err(_e) => return Err(ApiError::err("couldnt_find_that_username_or_email").into()),
}; };
// Generate a random token // Generate a random token
@ -969,7 +969,7 @@ impl Perform for PasswordReset {
let html = &format!("<h1>Password Reset Request for {}</h1><br><a href={}/password_change/{}>Click here to reset your password</a>", user.name, hostname, &token); let html = &format!("<h1>Password Reset Request for {}</h1><br><a href={}/password_change/{}>Click here to reset your password</a>", user.name, hostname, &token);
match send_email(subject, user_email, &user.name, html) { match send_email(subject, user_email, &user.name, html) {
Ok(_o) => _o, Ok(_o) => _o,
Err(_e) => return Err(APIError::err(&_e).into()), Err(_e) => return Err(ApiError::err(&_e).into()),
}; };
Ok(PasswordResetResponse {}) Ok(PasswordResetResponse {})
@ -996,7 +996,7 @@ impl Perform for PasswordChange {
// Make sure passwords match // Make sure passwords match
if data.password != data.password_verify { if data.password != data.password_verify {
return Err(APIError::err("passwords_dont_match").into()); return Err(ApiError::err("passwords_dont_match").into());
} }
// Update the user with the new password // Update the user with the new password
@ -1007,7 +1007,7 @@ impl Perform for PasswordChange {
.await? .await?
{ {
Ok(user) => user, Ok(user) => user,
Err(_e) => return Err(APIError::err("couldnt_update_user").into()), Err(_e) => return Err(ApiError::err("couldnt_update_user").into()),
}; };
// Return the jwt // Return the jwt
@ -1050,7 +1050,7 @@ impl Perform for CreatePrivateMessage {
{ {
Ok(private_message) => private_message, Ok(private_message) => private_message,
Err(_e) => { Err(_e) => {
return Err(APIError::err("couldnt_create_private_message").into()); return Err(ApiError::err("couldnt_create_private_message").into());
} }
}; };
@ -1072,7 +1072,7 @@ impl Perform for CreatePrivateMessage {
.await? .await?
{ {
Ok(private_message) => private_message, Ok(private_message) => private_message,
Err(_e) => return Err(APIError::err("couldnt_create_private_message").into()), Err(_e) => return Err(ApiError::err("couldnt_create_private_message").into()),
}; };
updated_private_message.send_create(&user, context).await?; updated_private_message.send_create(&user, context).await?;
@ -1129,7 +1129,7 @@ impl Perform for EditPrivateMessage {
}) })
.await??; .await??;
if user.id != orig_private_message.creator_id { if user.id != orig_private_message.creator_id {
return Err(APIError::err("no_private_message_edit_allowed").into()); return Err(ApiError::err("no_private_message_edit_allowed").into());
} }
// Doing the update // Doing the update
@ -1141,7 +1141,7 @@ impl Perform for EditPrivateMessage {
.await? .await?
{ {
Ok(private_message) => private_message, Ok(private_message) => private_message,
Err(_e) => return Err(APIError::err("couldnt_update_private_message").into()), Err(_e) => return Err(ApiError::err("couldnt_update_private_message").into()),
}; };
// Send the apub update // Send the apub update
@ -1188,7 +1188,7 @@ impl Perform for DeletePrivateMessage {
}) })
.await??; .await??;
if user.id != orig_private_message.creator_id { if user.id != orig_private_message.creator_id {
return Err(APIError::err("no_private_message_edit_allowed").into()); return Err(ApiError::err("no_private_message_edit_allowed").into());
} }
// Doing the update // Doing the update
@ -1200,7 +1200,7 @@ impl Perform for DeletePrivateMessage {
.await? .await?
{ {
Ok(private_message) => private_message, Ok(private_message) => private_message,
Err(_e) => return Err(APIError::err("couldnt_update_private_message").into()), Err(_e) => return Err(ApiError::err("couldnt_update_private_message").into()),
}; };
// Send the apub update // Send the apub update
@ -1253,7 +1253,7 @@ impl Perform for MarkPrivateMessageAsRead {
}) })
.await??; .await??;
if user.id != orig_private_message.recipient_id { if user.id != orig_private_message.recipient_id {
return Err(APIError::err("couldnt_update_private_message").into()); return Err(ApiError::err("couldnt_update_private_message").into());
} }
// Doing the update // Doing the update
@ -1265,7 +1265,7 @@ impl Perform for MarkPrivateMessageAsRead {
.await? .await?
{ {
Ok(private_message) => private_message, Ok(private_message) => private_message,
Err(_e) => return Err(APIError::err("couldnt_update_private_message").into()), Err(_e) => return Err(ApiError::err("couldnt_update_private_message").into()),
}; };
// No need to send an apub update // No need to send an apub update

View file

@ -23,7 +23,7 @@ pub type ConnectionId = usize;
pub type PostId = i32; pub type PostId = i32;
pub type CommunityId = i32; pub type CommunityId = i32;
pub type UserId = i32; pub type UserId = i32;
pub type IPAddr = String; pub type IpAddr = String;
#[macro_export] #[macro_export]
macro_rules! location_info { macro_rules! location_info {
@ -39,13 +39,13 @@ macro_rules! location_info {
#[derive(Debug, Error)] #[derive(Debug, Error)]
#[error("{{\"error\":\"{message}\"}}")] #[error("{{\"error\":\"{message}\"}}")]
pub struct APIError { pub struct ApiError {
pub message: String, pub message: String,
} }
impl APIError { impl ApiError {
pub fn err(msg: &str) -> Self { pub fn err(msg: &str) -> Self {
APIError { ApiError {
message: msg.to_string(), message: msg.to_string(),
} }
} }

View file

@ -1,4 +1,4 @@
use crate::{APIError, IPAddr, LemmyError}; use crate::{ApiError, IpAddr, LemmyError};
use log::debug; use log::debug;
use std::{collections::HashMap, time::SystemTime}; use std::{collections::HashMap, time::SystemTime};
use strum::IntoEnumIterator; use strum::IntoEnumIterator;
@ -20,13 +20,13 @@ pub(crate) enum RateLimitType {
/// Rate limiting based on rate type and IP addr /// Rate limiting based on rate type and IP addr
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RateLimiter { pub struct RateLimiter {
buckets: HashMap<RateLimitType, HashMap<IPAddr, RateLimitBucket>>, buckets: HashMap<RateLimitType, HashMap<IpAddr, RateLimitBucket>>,
} }
impl Default for RateLimiter { impl Default for RateLimiter {
fn default() -> Self { fn default() -> Self {
Self { Self {
buckets: HashMap::<RateLimitType, HashMap<IPAddr, RateLimitBucket>>::new(), buckets: HashMap::<RateLimitType, HashMap<IpAddr, RateLimitBucket>>::new(),
} }
} }
} }
@ -87,7 +87,7 @@ impl RateLimiter {
rate_limit.allowance rate_limit.allowance
); );
Err( Err(
APIError { ApiError {
message: format!( message: format!(
"Too many requests. type: {}, IP: {}, {} per {} seconds", "Too many requests. type: {}, IP: {}, {} per {} seconds",
type_.as_ref(), type_.as_ref(),

View file

@ -1,4 +1,4 @@
use crate::{settings::Settings, APIError}; use crate::{settings::Settings, ApiError};
use actix_web::dev::ConnectionInfo; use actix_web::dev::ConnectionInfo;
use chrono::{DateTime, FixedOffset, NaiveDateTime}; use chrono::{DateTime, FixedOffset, NaiveDateTime};
use itertools::Itertools; use itertools::Itertools;
@ -43,15 +43,15 @@ pub(crate) fn slur_check(test: &str) -> Result<(), Vec<&str>> {
} }
} }
pub fn check_slurs(text: &str) -> Result<(), APIError> { pub fn check_slurs(text: &str) -> Result<(), ApiError> {
if let Err(slurs) = slur_check(text) { if let Err(slurs) = slur_check(text) {
Err(APIError::err(&slurs_vec_to_str(slurs))) Err(ApiError::err(&slurs_vec_to_str(slurs)))
} else { } else {
Ok(()) Ok(())
} }
} }
pub fn check_slurs_opt(text: &Option<String>) -> Result<(), APIError> { pub fn check_slurs_opt(text: &Option<String>) -> Result<(), ApiError> {
match text { match text {
Some(t) => check_slurs(t), Some(t) => check_slurs(t),
None => Ok(()), None => Ok(()),

View file

@ -10,10 +10,10 @@ use lemmy_structs::{comment::*, post::*};
use lemmy_utils::{ use lemmy_utils::{
location_info, location_info,
rate_limit::RateLimit, rate_limit::RateLimit,
APIError, ApiError,
CommunityId, CommunityId,
ConnectionId, ConnectionId,
IPAddr, IpAddr,
LemmyError, LemmyError,
PostId, PostId,
UserId, UserId,
@ -73,8 +73,8 @@ pub struct ChatServer {
} }
pub struct SessionInfo { pub struct SessionInfo {
pub addr: Recipient<WSMessage>, pub addr: Recipient<WsMessage>,
pub ip: IPAddr, pub ip: IpAddr,
} }
/// `ChatServer` is an actor. It maintains list of connection client session. /// `ChatServer` is an actor. It maintains list of connection client session.
@ -395,7 +395,7 @@ impl ChatServer {
fn sendit(&self, message: &str, id: ConnectionId) { fn sendit(&self, message: &str, id: ConnectionId) {
if let Some(info) = self.sessions.get(&id) { if let Some(info) = self.sessions.get(&id) {
let _ = info.addr.do_send(WSMessage(message.to_owned())); let _ = info.addr.do_send(WsMessage(message.to_owned()));
} }
} }
@ -406,7 +406,7 @@ impl ChatServer {
) -> impl Future<Output = Result<String, LemmyError>> { ) -> impl Future<Output = Result<String, LemmyError>> {
let rate_limiter = self.rate_limiter.clone(); let rate_limiter = self.rate_limiter.clone();
let ip: IPAddr = match self.sessions.get(&msg.id) { let ip: IpAddr = match self.sessions.get(&msg.id) {
Some(info) => info.ip.to_owned(), Some(info) => info.ip.to_owned(),
None => "blank_ip".to_string(), None => "blank_ip".to_string(),
}; };
@ -421,7 +421,7 @@ impl ChatServer {
async move { async move {
let json: Value = serde_json::from_str(&msg.msg)?; let json: Value = serde_json::from_str(&msg.msg)?;
let data = &json["data"].to_string(); let data = &json["data"].to_string();
let op = &json["op"].as_str().ok_or(APIError { let op = &json["op"].as_str().ok_or(ApiError {
message: "Unknown op type".to_string(), message: "Unknown op type".to_string(),
})?; })?;

View file

@ -1,13 +1,13 @@
use crate::UserOperation; use crate::UserOperation;
use actix::{prelude::*, Recipient}; use actix::{prelude::*, Recipient};
use lemmy_structs::{comment::CommentResponse, post::PostResponse}; use lemmy_structs::{comment::CommentResponse, post::PostResponse};
use lemmy_utils::{CommunityId, ConnectionId, IPAddr, PostId, UserId}; use lemmy_utils::{CommunityId, ConnectionId, IpAddr, PostId, UserId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// Chat server sends this messages to session /// Chat server sends this messages to session
#[derive(Message)] #[derive(Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
pub struct WSMessage(pub String); pub struct WsMessage(pub String);
/// Message for chat server communications /// Message for chat server communications
@ -15,8 +15,8 @@ pub struct WSMessage(pub String);
#[derive(Message)] #[derive(Message)]
#[rtype(usize)] #[rtype(usize)]
pub struct Connect { pub struct Connect {
pub addr: Recipient<WSMessage>, pub addr: Recipient<WsMessage>,
pub ip: IPAddr, pub ip: IpAddr,
} }
/// Session is disconnected /// Session is disconnected
@ -24,7 +24,7 @@ pub struct Connect {
#[rtype(result = "()")] #[rtype(result = "()")]
pub struct Disconnect { pub struct Disconnect {
pub id: ConnectionId, pub id: ConnectionId,
pub ip: IPAddr, pub ip: IpAddr,
} }
/// The messages sent to websocket clients /// The messages sent to websocket clients

View file

@ -1,6 +1,6 @@
use crate::{ use crate::{
chat_server::ChatServer, chat_server::ChatServer,
messages::{Connect, Disconnect, StandardMessage, WSMessage}, messages::{Connect, Disconnect, StandardMessage, WsMessage},
LemmyContext, LemmyContext,
}; };
use actix::prelude::*; use actix::prelude::*;
@ -22,7 +22,7 @@ pub async fn chat_route(
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
ws::start( ws::start(
WSSession { WsSession {
cs_addr: context.chat_server().to_owned(), cs_addr: context.chat_server().to_owned(),
id: 0, id: 0,
hb: Instant::now(), hb: Instant::now(),
@ -33,7 +33,7 @@ pub async fn chat_route(
) )
} }
struct WSSession { struct WsSession {
cs_addr: Addr<ChatServer>, cs_addr: Addr<ChatServer>,
/// unique session id /// unique session id
id: usize, id: usize,
@ -43,7 +43,7 @@ struct WSSession {
hb: Instant, hb: Instant,
} }
impl Actor for WSSession { impl Actor for WsSession {
type Context = ws::WebsocketContext<Self>; type Context = ws::WebsocketContext<Self>;
/// Method is called on actor start. /// Method is called on actor start.
@ -87,16 +87,16 @@ impl Actor for WSSession {
/// Handle messages from chat server, we simply send it to peer websocket /// Handle messages from chat server, we simply send it to peer websocket
/// These are room messages, IE sent to others in the room /// These are room messages, IE sent to others in the room
impl Handler<WSMessage> for WSSession { impl Handler<WsMessage> for WsSession {
type Result = (); type Result = ();
fn handle(&mut self, msg: WSMessage, ctx: &mut Self::Context) { fn handle(&mut self, msg: WsMessage, ctx: &mut Self::Context) {
ctx.text(msg.0); ctx.text(msg.0);
} }
} }
/// WebSocket message handler /// WebSocket message handler
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WSSession { impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsSession {
fn handle(&mut self, result: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) { fn handle(&mut self, result: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
let message = match result { let message = match result {
Ok(m) => m, Ok(m) => m,
@ -143,7 +143,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WSSession {
} }
} }
impl WSSession { impl WsSession {
/// helper method that sends ping to client every second. /// helper method that sends ping to client every second.
/// ///
/// also this method checks heartbeats from client /// also this method checks heartbeats from client