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