]> Untitled Git - lemmy.git/blob - crates/api_crud/src/comment/create.rs
Moving settings to Database. (#2492)
[lemmy.git] / crates / api_crud / src / comment / create.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   comment::{CommentResponse, CreateComment},
5   utils::{
6     blocking,
7     check_community_ban,
8     check_community_deleted_or_removed,
9     check_post_deleted_or_removed,
10     get_local_user_view_from_jwt,
11     get_post,
12     local_site_to_slur_regex,
13   },
14 };
15 use lemmy_apub::{
16   generate_local_apub_endpoint,
17   objects::comment::ApubComment,
18   protocol::activities::{create_or_update::comment::CreateOrUpdateComment, CreateOrUpdateType},
19   EndpointType,
20 };
21 use lemmy_db_schema::{
22   source::{
23     actor_language::CommunityLanguage,
24     comment::{Comment, CommentInsertForm, CommentLike, CommentLikeForm, CommentUpdateForm},
25     comment_reply::{CommentReply, CommentReplyUpdateForm},
26     local_site::LocalSite,
27     person_mention::{PersonMention, PersonMentionUpdateForm},
28   },
29   traits::{Crud, Likeable},
30 };
31 use lemmy_utils::{
32   error::LemmyError,
33   utils::{remove_slurs, scrape_text_for_mentions},
34   ConnectionId,
35 };
36 use lemmy_websocket::{
37   send::{send_comment_ws_message, send_local_notifs},
38   LemmyContext,
39   UserOperationCrud,
40 };
41
42 #[async_trait::async_trait(?Send)]
43 impl PerformCrud for CreateComment {
44   type Response = CommentResponse;
45
46   #[tracing::instrument(skip(context, websocket_id))]
47   async fn perform(
48     &self,
49     context: &Data<LemmyContext>,
50     websocket_id: Option<ConnectionId>,
51   ) -> Result<CommentResponse, LemmyError> {
52     let data: &CreateComment = self;
53     let local_user_view =
54       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
55     let local_site = blocking(context.pool(), LocalSite::read).await??;
56
57     let content_slurs_removed = remove_slurs(
58       &data.content.to_owned(),
59       &local_site_to_slur_regex(&local_site),
60     );
61
62     // Check for a community ban
63     let post_id = data.post_id;
64     let post = get_post(post_id, context.pool()).await?;
65     let community_id = post.community_id;
66
67     check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
68     check_community_deleted_or_removed(community_id, context.pool()).await?;
69     check_post_deleted_or_removed(&post)?;
70
71     // Check if post is locked, no new comments
72     if post.locked {
73       return Err(LemmyError::from_message("locked"));
74     }
75
76     // Fetch the parent, if it exists
77     let parent_opt = if let Some(parent_id) = data.parent_id {
78       blocking(context.pool(), move |conn| Comment::read(conn, parent_id))
79         .await?
80         .ok()
81     } else {
82       None
83     };
84
85     // If there's a parent_id, check to make sure that comment is in that post
86     // Strange issue where sometimes the post ID of the parent comment is incorrect
87     if let Some(parent) = parent_opt.as_ref() {
88       if parent.post_id != post_id {
89         return Err(LemmyError::from_message("couldnt_create_comment"));
90       }
91     }
92
93     // if no language is set, copy language from parent post/comment
94     let parent_language = parent_opt
95       .as_ref()
96       .map(|p| p.language_id)
97       .unwrap_or(post.language_id);
98     let language_id = data.language_id.unwrap_or(parent_language);
99
100     blocking(context.pool(), move |conn| {
101       CommunityLanguage::is_allowed_community_language(conn, Some(language_id), community_id)
102     })
103     .await??;
104
105     let comment_form = CommentInsertForm::builder()
106       .content(content_slurs_removed.to_owned())
107       .post_id(data.post_id)
108       .creator_id(local_user_view.person.id)
109       .language_id(Some(language_id))
110       .build();
111
112     // Create the comment
113     let comment_form2 = comment_form.clone();
114     let parent_path = parent_opt.to_owned().map(|t| t.path);
115     let inserted_comment = blocking(context.pool(), move |conn| {
116       Comment::create(conn, &comment_form2, parent_path.as_ref())
117     })
118     .await?
119     .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?;
120
121     // Necessary to update the ap_id
122     let inserted_comment_id = inserted_comment.id;
123     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
124
125     let updated_comment: Comment =
126       blocking(context.pool(), move |conn| -> Result<Comment, LemmyError> {
127         let apub_id = generate_local_apub_endpoint(
128           EndpointType::Comment,
129           &inserted_comment_id.to_string(),
130           &protocol_and_hostname,
131         )?;
132         Ok(Comment::update(
133           conn,
134           inserted_comment_id,
135           &CommentUpdateForm::builder().ap_id(Some(apub_id)).build(),
136         )?)
137       })
138       .await?
139       .map_err(|e| e.with_message("couldnt_create_comment"))?;
140
141     // Scan the comment for user mentions, add those rows
142     let post_id = post.id;
143     let mentions = scrape_text_for_mentions(&content_slurs_removed);
144     let recipient_ids = send_local_notifs(
145       mentions,
146       &updated_comment,
147       &local_user_view.person,
148       &post,
149       true,
150       context,
151     )
152     .await?;
153
154     // You like your own comment by default
155     let like_form = CommentLikeForm {
156       comment_id: inserted_comment.id,
157       post_id,
158       person_id: local_user_view.person.id,
159       score: 1,
160     };
161
162     let like = move |conn: &mut _| CommentLike::like(conn, &like_form);
163     blocking(context.pool(), like)
164       .await?
165       .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_comment"))?;
166
167     let apub_comment: ApubComment = updated_comment.into();
168     CreateOrUpdateComment::send(
169       apub_comment.clone(),
170       &local_user_view.person.clone().into(),
171       CreateOrUpdateType::Create,
172       context,
173       &mut 0,
174     )
175     .await?;
176
177     // If its a reply, mark the parent as read
178     if let Some(parent) = parent_opt {
179       let parent_id = parent.id;
180       let comment_reply = blocking(context.pool(), move |conn| {
181         CommentReply::read_by_comment(conn, parent_id)
182       })
183       .await?;
184       if let Ok(reply) = comment_reply {
185         blocking(context.pool(), move |conn| {
186           CommentReply::update(conn, reply.id, &CommentReplyUpdateForm { read: Some(true) })
187         })
188         .await?
189         .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_replies"))?;
190       }
191
192       // If the parent has PersonMentions mark them as read too
193       let person_id = local_user_view.person.id;
194       let person_mention = blocking(context.pool(), move |conn| {
195         PersonMention::read_by_comment_and_person(conn, parent_id, person_id)
196       })
197       .await?;
198       if let Ok(mention) = person_mention {
199         blocking(context.pool(), move |conn| {
200           PersonMention::update(
201             conn,
202             mention.id,
203             &PersonMentionUpdateForm { read: Some(true) },
204           )
205         })
206         .await?
207         .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_person_mentions"))?;
208       }
209     }
210
211     send_comment_ws_message(
212       inserted_comment.id,
213       UserOperationCrud::CreateComment,
214       websocket_id,
215       data.form_id.to_owned(),
216       Some(local_user_view.person.id),
217       recipient_ids,
218       context,
219     )
220     .await
221   }
222 }