]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/comment.rs
Running clippy --fix (#1647)
[lemmy.git] / crates / apub / src / objects / comment.rs
1 use crate::{
2   extensions::context::lemmy_context,
3   fetcher::objects::{get_or_fetch_and_insert_comment, get_or_fetch_and_insert_post},
4   get_community_from_to_or_cc,
5   objects::{
6     check_object_domain,
7     check_object_for_community_or_site_ban,
8     create_tombstone,
9     get_object_from_apub,
10     get_or_fetch_and_upsert_person,
11     get_source_markdown_value,
12     set_content_and_source,
13     FromApub,
14     FromApubToForm,
15     ToApub,
16   },
17   NoteExt,
18 };
19 use activitystreams::{
20   object::{kind::NoteType, ApObject, Note, Tombstone},
21   prelude::*,
22   public,
23 };
24 use anyhow::{anyhow, Context};
25 use lemmy_api_common::blocking;
26 use lemmy_db_queries::{Crud, DbPool};
27 use lemmy_db_schema::{
28   source::{
29     comment::{Comment, CommentForm},
30     community::Community,
31     person::Person,
32     post::Post,
33   },
34   CommentId,
35 };
36 use lemmy_utils::{
37   location_info,
38   utils::{convert_datetime, remove_slurs},
39   LemmyError,
40 };
41 use lemmy_websocket::LemmyContext;
42 use url::Url;
43
44 #[async_trait::async_trait(?Send)]
45 impl ToApub for Comment {
46   type ApubType = NoteExt;
47
48   async fn to_apub(&self, pool: &DbPool) -> Result<NoteExt, LemmyError> {
49     let mut comment = ApObject::new(Note::new());
50
51     let creator_id = self.creator_id;
52     let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
53
54     let post_id = self.post_id;
55     let post = blocking(pool, move |conn| Post::read(conn, post_id)).await??;
56
57     let community_id = post.community_id;
58     let community = blocking(pool, move |conn| Community::read(conn, community_id)).await??;
59
60     // Add a vector containing some important info to the "in_reply_to" field
61     // [post_ap_id, Option(parent_comment_ap_id)]
62     let mut in_reply_to_vec = vec![post.ap_id.into_inner()];
63
64     if let Some(parent_id) = self.parent_id {
65       let parent_comment = blocking(pool, move |conn| Comment::read(conn, parent_id)).await??;
66
67       in_reply_to_vec.push(parent_comment.ap_id.into_inner());
68     }
69
70     comment
71       // Not needed when the Post is embedded in a collection (like for community outbox)
72       .set_many_contexts(lemmy_context()?)
73       .set_id(self.ap_id.to_owned().into_inner())
74       .set_published(convert_datetime(self.published))
75       // NOTE: included community id for compatibility with lemmy v0.9.9
76       .set_many_tos(vec![community.actor_id.into_inner(), public()])
77       .set_many_in_reply_tos(in_reply_to_vec)
78       .set_attributed_to(creator.actor_id.into_inner());
79
80     set_content_and_source(&mut comment, &self.content)?;
81
82     if let Some(u) = self.updated {
83       comment.set_updated(convert_datetime(u));
84     }
85
86     Ok(comment)
87   }
88
89   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
90     create_tombstone(
91       self.deleted,
92       self.ap_id.to_owned().into(),
93       self.updated,
94       NoteType::Note,
95     )
96   }
97 }
98
99 #[async_trait::async_trait(?Send)]
100 impl FromApub for Comment {
101   type ApubType = NoteExt;
102
103   /// Converts a `Note` to `Comment`.
104   ///
105   /// If the parent community, post and comment(s) are not known locally, these are also fetched.
106   async fn from_apub(
107     note: &NoteExt,
108     context: &LemmyContext,
109     expected_domain: Url,
110     request_counter: &mut i32,
111     mod_action_allowed: bool,
112   ) -> Result<Comment, LemmyError> {
113     let comment: Comment = get_object_from_apub(
114       note,
115       context,
116       expected_domain,
117       request_counter,
118       mod_action_allowed,
119     )
120     .await?;
121
122     let post_id = comment.post_id;
123     let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
124     check_object_for_community_or_site_ban(note, post.community_id, context, request_counter)
125       .await?;
126     if post.locked {
127       // This is not very efficient because a comment gets inserted just to be deleted right
128       // afterwards, but it seems to be the easiest way to implement it.
129       blocking(context.pool(), move |conn| {
130         Comment::delete(conn, comment.id)
131       })
132       .await??;
133       Err(anyhow!("Post is locked").into())
134     } else {
135       Ok(comment)
136     }
137   }
138 }
139
140 #[async_trait::async_trait(?Send)]
141 impl FromApubToForm<NoteExt> for CommentForm {
142   async fn from_apub(
143     note: &NoteExt,
144     context: &LemmyContext,
145     expected_domain: Url,
146     request_counter: &mut i32,
147     _mod_action_allowed: bool,
148   ) -> Result<CommentForm, LemmyError> {
149     let community = get_community_from_to_or_cc(note, context, request_counter).await?;
150     let ap_id = Some(check_object_domain(note, expected_domain, community.local)?);
151     let creator_actor_id = &note
152       .attributed_to()
153       .context(location_info!())?
154       .as_single_xsd_any_uri()
155       .context(location_info!())?;
156
157     let creator =
158       get_or_fetch_and_upsert_person(creator_actor_id, context, request_counter).await?;
159
160     let mut in_reply_tos = note
161       .in_reply_to()
162       .as_ref()
163       .context(location_info!())?
164       .as_many()
165       .context(location_info!())?
166       .iter()
167       .map(|i| i.as_xsd_any_uri().context(""));
168     let post_ap_id = in_reply_tos.next().context(location_info!())??;
169
170     // This post, or the parent comment might not yet exist on this server yet, fetch them.
171     let post = Box::pin(get_or_fetch_and_insert_post(
172       post_ap_id,
173       context,
174       request_counter,
175     ))
176     .await?;
177
178     // The 2nd item, if it exists, is the parent comment apub_id
179     // For deeply nested comments, FromApub automatically gets called recursively
180     let parent_id: Option<CommentId> = match in_reply_tos.next() {
181       Some(parent_comment_uri) => {
182         let parent_comment_ap_id = &parent_comment_uri?;
183         let parent_comment = Box::pin(get_or_fetch_and_insert_comment(
184           parent_comment_ap_id,
185           context,
186           request_counter,
187         ))
188         .await?;
189
190         Some(parent_comment.id)
191       }
192       None => None,
193     };
194
195     let content = get_source_markdown_value(note)?.context(location_info!())?;
196     let content_slurs_removed = remove_slurs(&content);
197
198     Ok(CommentForm {
199       creator_id: creator.id,
200       post_id: post.id,
201       parent_id,
202       content: content_slurs_removed,
203       removed: None,
204       read: None,
205       published: note.published().map(|u| u.to_owned().naive_local()),
206       updated: note.updated().map(|u| u.to_owned().naive_local()),
207       deleted: None,
208       ap_id,
209       local: Some(false),
210     })
211   }
212 }