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