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