]> Untitled Git - lemmy.git/blob - crates/api_crud/src/comment/create.rs
Split api crate into api_structs and api
[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   blocking,
5   check_community_ban,
6   comment::*,
7   get_local_user_view_from_jwt,
8   get_post,
9   send_local_notifs,
10 };
11 use lemmy_apub::{generate_apub_endpoint, ApubLikeableType, ApubObjectType, EndpointType};
12 use lemmy_db_queries::{source::comment::Comment_, Crud, Likeable};
13 use lemmy_db_schema::source::comment::*;
14 use lemmy_db_views::comment_view::CommentView;
15 use lemmy_utils::{
16   utils::{remove_slurs, scrape_text_for_mentions},
17   ApiError,
18   ConnectionId,
19   LemmyError,
20 };
21 use lemmy_websocket::{messages::SendComment, LemmyContext, UserOperation};
22
23 #[async_trait::async_trait(?Send)]
24 impl PerformCrud for CreateComment {
25   type Response = CommentResponse;
26
27   async fn perform(
28     &self,
29     context: &Data<LemmyContext>,
30     websocket_id: Option<ConnectionId>,
31   ) -> Result<CommentResponse, LemmyError> {
32     let data: &CreateComment = &self;
33     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
34
35     let content_slurs_removed = remove_slurs(&data.content.to_owned());
36
37     // Check for a community ban
38     let post_id = data.post_id;
39     let post = get_post(post_id, context.pool()).await?;
40
41     check_community_ban(local_user_view.person.id, post.community_id, context.pool()).await?;
42
43     // Check if post is locked, no new comments
44     if post.locked {
45       return Err(ApiError::err("locked").into());
46     }
47
48     // If there's a parent_id, check to make sure that comment is in that post
49     if let Some(parent_id) = data.parent_id {
50       // Make sure the parent comment exists
51       let parent =
52         match blocking(context.pool(), move |conn| Comment::read(&conn, parent_id)).await? {
53           Ok(comment) => comment,
54           Err(_e) => return Err(ApiError::err("couldnt_create_comment").into()),
55         };
56       if parent.post_id != post_id {
57         return Err(ApiError::err("couldnt_create_comment").into());
58       }
59     }
60
61     let comment_form = CommentForm {
62       content: content_slurs_removed,
63       parent_id: data.parent_id.to_owned(),
64       post_id: data.post_id,
65       creator_id: local_user_view.person.id,
66       removed: None,
67       deleted: None,
68       read: None,
69       published: None,
70       updated: None,
71       ap_id: None,
72       local: true,
73     };
74
75     // Create the comment
76     let comment_form2 = comment_form.clone();
77     let inserted_comment = match blocking(context.pool(), move |conn| {
78       Comment::create(&conn, &comment_form2)
79     })
80     .await?
81     {
82       Ok(comment) => comment,
83       Err(_e) => return Err(ApiError::err("couldnt_create_comment").into()),
84     };
85
86     // Necessary to update the ap_id
87     let inserted_comment_id = inserted_comment.id;
88     let updated_comment: Comment =
89       match blocking(context.pool(), move |conn| -> Result<Comment, LemmyError> {
90         let apub_id =
91           generate_apub_endpoint(EndpointType::Comment, &inserted_comment_id.to_string())?;
92         Ok(Comment::update_ap_id(&conn, inserted_comment_id, apub_id)?)
93       })
94       .await?
95       {
96         Ok(comment) => comment,
97         Err(_e) => return Err(ApiError::err("couldnt_create_comment").into()),
98       };
99
100     updated_comment
101       .send_create(&local_user_view.person, context)
102       .await?;
103
104     // Scan the comment for user mentions, add those rows
105     let post_id = post.id;
106     let mentions = scrape_text_for_mentions(&comment_form.content);
107     let recipient_ids = send_local_notifs(
108       mentions,
109       updated_comment.clone(),
110       local_user_view.person.clone(),
111       post,
112       context.pool(),
113       true,
114     )
115     .await?;
116
117     // You like your own comment by default
118     let like_form = CommentLikeForm {
119       comment_id: inserted_comment.id,
120       post_id,
121       person_id: local_user_view.person.id,
122       score: 1,
123     };
124
125     let like = move |conn: &'_ _| CommentLike::like(&conn, &like_form);
126     if blocking(context.pool(), like).await?.is_err() {
127       return Err(ApiError::err("couldnt_like_comment").into());
128     }
129
130     updated_comment
131       .send_like(&local_user_view.person, context)
132       .await?;
133
134     let person_id = local_user_view.person.id;
135     let mut comment_view = blocking(context.pool(), move |conn| {
136       CommentView::read(&conn, inserted_comment.id, Some(person_id))
137     })
138     .await??;
139
140     // If its a comment to yourself, mark it as read
141     let comment_id = comment_view.comment.id;
142     if local_user_view.person.id == comment_view.get_recipient_id() {
143       match blocking(context.pool(), move |conn| {
144         Comment::update_read(conn, comment_id, true)
145       })
146       .await?
147       {
148         Ok(comment) => comment,
149         Err(_e) => return Err(ApiError::err("couldnt_update_comment").into()),
150       };
151       comment_view.comment.read = true;
152     }
153
154     let mut res = CommentResponse {
155       comment_view,
156       recipient_ids,
157       form_id: data.form_id.to_owned(),
158     };
159
160     context.chat_server().do_send(SendComment {
161       op: UserOperation::CreateComment,
162       comment: res.clone(),
163       websocket_id,
164     });
165
166     res.recipient_ids = Vec::new(); // Necessary to avoid doubles
167
168     Ok(res)
169   }
170 }