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