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