]> Untitled Git - lemmy.git/blob - crates/api_crud/src/comment/remove.rs
cfc3ccff76a4f77c7612a32c17edfb8e6f83da00
[lemmy.git] / crates / api_crud / src / comment / remove.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   build_response::{build_comment_response, send_local_notifs},
5   comment::{CommentResponse, RemoveComment},
6   context::LemmyContext,
7   utils::{check_community_ban, is_mod_or_admin, local_user_view_from_jwt},
8 };
9 use lemmy_db_schema::{
10   source::{
11     comment::{Comment, CommentUpdateForm},
12     moderator::{ModRemoveComment, ModRemoveCommentForm},
13     post::Post,
14   },
15   traits::Crud,
16 };
17 use lemmy_db_views::structs::CommentView;
18 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
19 use std::ops::Deref;
20
21 #[async_trait::async_trait(?Send)]
22 impl PerformCrud for RemoveComment {
23   type Response = CommentResponse;
24
25   #[tracing::instrument(skip(context))]
26   async fn perform(&self, context: &Data<LemmyContext>) -> Result<CommentResponse, LemmyError> {
27     let data: &RemoveComment = self;
28     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
29
30     let comment_id = data.comment_id;
31     let orig_comment = CommentView::read(&mut context.pool(), comment_id, None).await?;
32
33     check_community_ban(
34       local_user_view.person.id,
35       orig_comment.community.id,
36       &mut context.pool(),
37     )
38     .await?;
39
40     // Verify that only a mod or admin can remove
41     is_mod_or_admin(
42       &mut context.pool(),
43       local_user_view.person.id,
44       orig_comment.community.id,
45     )
46     .await?;
47
48     // Do the remove
49     let removed = data.removed;
50     let updated_comment = Comment::update(
51       &mut context.pool(),
52       comment_id,
53       &CommentUpdateForm::builder().removed(Some(removed)).build(),
54     )
55     .await
56     .with_lemmy_type(LemmyErrorType::CouldntUpdateComment)?;
57
58     // Mod tables
59     let form = ModRemoveCommentForm {
60       mod_person_id: local_user_view.person.id,
61       comment_id: data.comment_id,
62       removed: Some(removed),
63       reason: data.reason.clone(),
64     };
65     ModRemoveComment::create(&mut context.pool(), &form).await?;
66
67     let post_id = updated_comment.post_id;
68     let post = Post::read(&mut context.pool(), post_id).await?;
69     let recipient_ids = send_local_notifs(
70       vec![],
71       &updated_comment,
72       &local_user_view.person.clone(),
73       &post,
74       false,
75       context,
76     )
77     .await?;
78
79     build_comment_response(
80       context.deref(),
81       updated_comment.id,
82       Some(local_user_view),
83       None,
84       recipient_ids,
85     )
86     .await
87   }
88 }