]> Untitled Git - lemmy.git/blob - crates/api/src/comment_report/create.rs
3a89e1014b977aef488c93262f2cfdcdc8c68800
[lemmy.git] / crates / api / src / comment_report / create.rs
1 use crate::{check_report_reason, Perform};
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   comment::{CommentReportResponse, CreateCommentReport},
5   context::LemmyContext,
6   utils::{check_community_ban, local_user_view_from_jwt, send_new_report_email_to_admins},
7 };
8 use lemmy_db_schema::{
9   source::{
10     comment_report::{CommentReport, CommentReportForm},
11     local_site::LocalSite,
12   },
13   traits::Reportable,
14 };
15 use lemmy_db_views::structs::{CommentReportView, CommentView};
16 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
17
18 /// Creates a comment report and notifies the moderators of the community
19 #[async_trait::async_trait(?Send)]
20 impl Perform for CreateCommentReport {
21   type Response = CommentReportResponse;
22
23   #[tracing::instrument(skip(context))]
24   async fn perform(
25     &self,
26     context: &Data<LemmyContext>,
27   ) -> Result<CommentReportResponse, LemmyError> {
28     let data: &CreateCommentReport = self;
29     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
30     let local_site = LocalSite::read(&mut context.pool()).await?;
31
32     let reason = self.reason.trim();
33     check_report_reason(reason, &local_site)?;
34
35     let person_id = local_user_view.person.id;
36     let comment_id = data.comment_id;
37     let comment_view = CommentView::read(&mut context.pool(), comment_id, None).await?;
38
39     check_community_ban(person_id, comment_view.community.id, &mut context.pool()).await?;
40
41     let report_form = CommentReportForm {
42       creator_id: person_id,
43       comment_id,
44       original_comment_text: comment_view.comment.content,
45       reason: reason.to_owned(),
46     };
47
48     let report = CommentReport::report(&mut context.pool(), &report_form)
49       .await
50       .with_lemmy_type(LemmyErrorType::CouldntCreateReport)?;
51
52     let comment_report_view =
53       CommentReportView::read(&mut context.pool(), report.id, person_id).await?;
54
55     // Email the admins
56     if local_site.reports_email_admins {
57       send_new_report_email_to_admins(
58         &comment_report_view.creator.name,
59         &comment_report_view.comment_creator.name,
60         &mut context.pool(),
61         context.settings(),
62       )
63       .await?;
64     }
65
66     Ok(CommentReportResponse {
67       comment_report_view,
68     })
69   }
70 }