]> Untitled Git - lemmy.git/blob - crates/api/src/post_report/create.rs
092f1cd8d8d10c05001d625b86a931727a97c11f
[lemmy.git] / crates / api / src / post_report / create.rs
1 use crate::{check_report_reason, Perform};
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   context::LemmyContext,
5   post::{CreatePostReport, PostReportResponse},
6   utils::{check_community_ban, local_user_view_from_jwt, send_new_report_email_to_admins},
7   websocket::UserOperation,
8 };
9 use lemmy_db_schema::{
10   source::{
11     local_site::LocalSite,
12     post_report::{PostReport, PostReportForm},
13   },
14   traits::Reportable,
15 };
16 use lemmy_db_views::structs::{PostReportView, PostView};
17 use lemmy_utils::{error::LemmyError, ConnectionId};
18
19 /// Creates a post report and notifies the moderators of the community
20 #[async_trait::async_trait(?Send)]
21 impl Perform for CreatePostReport {
22   type Response = PostReportResponse;
23
24   #[tracing::instrument(skip(context, websocket_id))]
25   async fn perform(
26     &self,
27     context: &Data<LemmyContext>,
28     websocket_id: Option<ConnectionId>,
29   ) -> Result<PostReportResponse, LemmyError> {
30     let data: &CreatePostReport = self;
31     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
32     let local_site = LocalSite::read(context.pool()).await?;
33
34     let reason = self.reason.trim();
35     check_report_reason(reason, &local_site)?;
36
37     let person_id = local_user_view.person.id;
38     let post_id = data.post_id;
39     let post_view = PostView::read(context.pool(), post_id, None, None).await?;
40
41     check_community_ban(person_id, post_view.community.id, context.pool()).await?;
42
43     let report_form = PostReportForm {
44       creator_id: person_id,
45       post_id,
46       original_post_name: post_view.post.name,
47       original_post_url: post_view.post.url,
48       original_post_body: post_view.post.body,
49       reason: reason.to_owned(),
50     };
51
52     let report = PostReport::report(context.pool(), &report_form)
53       .await
54       .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_report"))?;
55
56     let post_report_view = PostReportView::read(context.pool(), report.id, person_id).await?;
57
58     // Email the admins
59     if local_site.reports_email_admins {
60       send_new_report_email_to_admins(
61         &post_report_view.creator.name,
62         &post_report_view.post_creator.name,
63         context.pool(),
64         context.settings(),
65       )
66       .await?;
67     }
68
69     let res = PostReportResponse { post_report_view };
70
71     context.send_mod_ws_message(
72       &UserOperation::CreatePostReport,
73       &res,
74       post_view.community.id,
75       websocket_id,
76     )?;
77
78     Ok(res)
79   }
80 }