]> Untitled Git - lemmy.git/blob - crates/api_crud/src/comment/delete.rs
Making the chat server an actor. (#2793)
[lemmy.git] / crates / api_crud / src / comment / delete.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   comment::{CommentResponse, DeleteComment},
5   context::LemmyContext,
6   utils::{check_community_ban, get_local_user_view_from_jwt},
7   websocket::UserOperationCrud,
8 };
9 use lemmy_db_schema::{
10   source::{
11     comment::{Comment, CommentUpdateForm},
12     post::Post,
13   },
14   traits::Crud,
15 };
16 use lemmy_db_views::structs::CommentView;
17 use lemmy_utils::{error::LemmyError, ConnectionId};
18
19 #[async_trait::async_trait(?Send)]
20 impl PerformCrud for DeleteComment {
21   type Response = CommentResponse;
22
23   #[tracing::instrument(skip(context, websocket_id))]
24   async fn perform(
25     &self,
26     context: &Data<LemmyContext>,
27     websocket_id: Option<ConnectionId>,
28   ) -> Result<CommentResponse, LemmyError> {
29     let data: &DeleteComment = self;
30     let local_user_view =
31       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
32
33     let comment_id = data.comment_id;
34     let orig_comment = CommentView::read(context.pool(), comment_id, None).await?;
35
36     // Dont delete it if its already been deleted.
37     if orig_comment.comment.deleted == data.deleted {
38       return Err(LemmyError::from_message("couldnt_update_comment"));
39     }
40
41     check_community_ban(
42       local_user_view.person.id,
43       orig_comment.community.id,
44       context.pool(),
45     )
46     .await?;
47
48     // Verify that only the creator can delete
49     if local_user_view.person.id != orig_comment.creator.id {
50       return Err(LemmyError::from_message("no_comment_edit_allowed"));
51     }
52
53     // Do the delete
54     let deleted = data.deleted;
55     let updated_comment = Comment::update(
56       context.pool(),
57       comment_id,
58       &CommentUpdateForm::builder().deleted(Some(deleted)).build(),
59     )
60     .await
61     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
62
63     let post_id = updated_comment.post_id;
64     let post = Post::read(context.pool(), post_id).await?;
65     let recipient_ids = context
66       .send_local_notifs(
67         vec![],
68         &updated_comment,
69         &local_user_view.person,
70         &post,
71         false,
72       )
73       .await?;
74
75     let res = context
76       .send_comment_ws_message(
77         &UserOperationCrud::DeleteComment,
78         data.comment_id,
79         websocket_id,
80         None,
81         Some(local_user_view.person.id),
82         recipient_ids,
83       )
84       .await?;
85
86     Ok(res)
87   }
88 }