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