]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/comment.rs
Rewrite activitypub following, person, community, pm (#1692)
[lemmy.git] / crates / apub / src / objects / comment.rs
1 use crate::{
2   activities::verify_person_in_community,
3   extensions::context::lemmy_context,
4   fetcher::objects::{
5     get_or_fetch_and_insert_comment,
6     get_or_fetch_and_insert_post,
7     get_or_fetch_and_insert_post_or_comment,
8   },
9   migrations::CommentInReplyToMigration,
10   objects::{create_tombstone, get_or_fetch_and_upsert_person, FromApub, Source, ToApub},
11   ActorType,
12   PostOrComment,
13 };
14 use activitystreams::{
15   base::AnyBase,
16   object::{kind::NoteType, Tombstone},
17   primitives::OneOrMany,
18   unparsed::Unparsed,
19 };
20 use anyhow::{anyhow, Context};
21 use chrono::{DateTime, FixedOffset};
22 use lemmy_api_common::blocking;
23 use lemmy_apub_lib::{
24   values::{MediaTypeHtml, MediaTypeMarkdown, PublicUrl},
25   verify_domains_match,
26 };
27 use lemmy_db_queries::{ApubObject, Crud, DbPool};
28 use lemmy_db_schema::{
29   source::{
30     comment::{Comment, CommentForm},
31     community::Community,
32     person::Person,
33     post::Post,
34   },
35   CommentId,
36 };
37 use lemmy_utils::{
38   location_info,
39   utils::{convert_datetime, remove_slurs},
40   LemmyError,
41 };
42 use lemmy_websocket::LemmyContext;
43 use serde::{Deserialize, Serialize};
44 use serde_with::skip_serializing_none;
45 use std::ops::Deref;
46 use url::Url;
47
48 #[skip_serializing_none]
49 #[derive(Clone, Debug, Deserialize, Serialize)]
50 #[serde(rename_all = "camelCase")]
51 pub struct Note {
52   #[serde(rename = "@context")]
53   context: OneOrMany<AnyBase>,
54   r#type: NoteType,
55   id: Url,
56   pub(crate) attributed_to: Url,
57   /// Indicates that the object is publicly readable. Unlike [`Post.to`], this one doesn't contain
58   /// the community ID, as it would be incompatible with Pleroma (and we can get the community from
59   /// the post in [`in_reply_to`]).
60   to: PublicUrl,
61   content: String,
62   media_type: MediaTypeHtml,
63   source: Source,
64   in_reply_to: CommentInReplyToMigration,
65   published: DateTime<FixedOffset>,
66   updated: Option<DateTime<FixedOffset>>,
67   #[serde(flatten)]
68   unparsed: Unparsed,
69 }
70
71 impl Note {
72   pub(crate) fn id_unchecked(&self) -> &Url {
73     &self.id
74   }
75   pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
76     verify_domains_match(&self.id, expected_domain)?;
77     Ok(&self.id)
78   }
79
80   async fn get_parents(
81     &self,
82     context: &LemmyContext,
83     request_counter: &mut i32,
84   ) -> Result<(Post, Option<CommentId>), LemmyError> {
85     match &self.in_reply_to {
86       CommentInReplyToMigration::Old(in_reply_to) => {
87         // This post, or the parent comment might not yet exist on this server yet, fetch them.
88         let post_id = in_reply_to.get(0).context(location_info!())?;
89         let post = Box::pin(get_or_fetch_and_insert_post(
90           post_id,
91           context,
92           request_counter,
93         ))
94         .await?;
95
96         // The 2nd item, if it exists, is the parent comment apub_id
97         // Nested comments will automatically get fetched recursively
98         let parent_id: Option<CommentId> = match in_reply_to.get(1) {
99           Some(parent_comment_uri) => {
100             let parent_comment = Box::pin(get_or_fetch_and_insert_comment(
101               parent_comment_uri,
102               context,
103               request_counter,
104             ))
105             .await?;
106
107             Some(parent_comment.id)
108           }
109           None => None,
110         };
111
112         Ok((post, parent_id))
113       }
114       CommentInReplyToMigration::New(in_reply_to) => {
115         let parent = Box::pin(
116           get_or_fetch_and_insert_post_or_comment(in_reply_to, context, request_counter).await?,
117         );
118         match parent.deref() {
119           PostOrComment::Post(p) => {
120             // Workaround because I cant figure ut how to get the post out of the box (and we dont
121             // want to stackoverflow in a deep comment hierarchy).
122             let post_id = p.id;
123             let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
124             Ok((post, None))
125           }
126           PostOrComment::Comment(c) => {
127             let post_id = c.post_id;
128             let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
129             Ok((post, Some(c.id)))
130           }
131         }
132       }
133     }
134   }
135
136   pub(crate) async fn verify(
137     &self,
138     context: &LemmyContext,
139     request_counter: &mut i32,
140   ) -> Result<(), LemmyError> {
141     let (post, _parent_comment_id) = self.get_parents(context, request_counter).await?;
142     let community_id = post.community_id;
143     let community = blocking(context.pool(), move |conn| {
144       Community::read(conn, community_id)
145     })
146     .await??;
147
148     if post.locked {
149       return Err(anyhow!("Post is locked").into());
150     }
151     verify_domains_match(&self.attributed_to, &self.id)?;
152     verify_person_in_community(
153       &self.attributed_to,
154       &community.actor_id(),
155       context,
156       request_counter,
157     )
158     .await?;
159     Ok(())
160   }
161 }
162
163 #[async_trait::async_trait(?Send)]
164 impl ToApub for Comment {
165   type ApubType = Note;
166
167   async fn to_apub(&self, pool: &DbPool) -> Result<Note, LemmyError> {
168     let creator_id = self.creator_id;
169     let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
170
171     let post_id = self.post_id;
172     let post = blocking(pool, move |conn| Post::read(conn, post_id)).await??;
173
174     // Add a vector containing some important info to the "in_reply_to" field
175     // [post_ap_id, Option(parent_comment_ap_id)]
176     let mut in_reply_to_vec = vec![post.ap_id.into_inner()];
177
178     if let Some(parent_id) = self.parent_id {
179       let parent_comment = blocking(pool, move |conn| Comment::read(conn, parent_id)).await??;
180
181       in_reply_to_vec.push(parent_comment.ap_id.into_inner());
182     }
183
184     let note = Note {
185       context: lemmy_context(),
186       r#type: NoteType::Note,
187       id: self.ap_id.to_owned().into_inner(),
188       attributed_to: creator.actor_id.into_inner(),
189       to: PublicUrl::Public,
190       content: self.content.clone(),
191       media_type: MediaTypeHtml::Html,
192       source: Source {
193         content: self.content.clone(),
194         media_type: MediaTypeMarkdown::Markdown,
195       },
196       in_reply_to: CommentInReplyToMigration::Old(in_reply_to_vec),
197       published: convert_datetime(self.published),
198       updated: self.updated.map(convert_datetime),
199       unparsed: Default::default(),
200     };
201
202     Ok(note)
203   }
204
205   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
206     create_tombstone(
207       self.deleted,
208       self.ap_id.to_owned().into(),
209       self.updated,
210       NoteType::Note,
211     )
212   }
213 }
214
215 #[async_trait::async_trait(?Send)]
216 impl FromApub for Comment {
217   type ApubType = Note;
218
219   /// Converts a `Note` to `Comment`.
220   ///
221   /// If the parent community, post and comment(s) are not known locally, these are also fetched.
222   async fn from_apub(
223     note: &Note,
224     context: &LemmyContext,
225     expected_domain: &Url,
226     request_counter: &mut i32,
227   ) -> Result<Comment, LemmyError> {
228     let ap_id = Some(note.id(expected_domain)?.clone().into());
229     let creator =
230       get_or_fetch_and_upsert_person(&note.attributed_to, context, request_counter).await?;
231     let (post, parent_comment_id) = note.get_parents(context, request_counter).await?;
232
233     let content = &note.source.content;
234     let content_slurs_removed = remove_slurs(content);
235
236     let form = CommentForm {
237       creator_id: creator.id,
238       post_id: post.id,
239       parent_id: parent_comment_id,
240       content: content_slurs_removed,
241       removed: None,
242       read: None,
243       published: Some(note.published.naive_local()),
244       updated: note.updated.map(|u| u.to_owned().naive_local()),
245       deleted: None,
246       ap_id,
247       local: Some(false),
248     };
249     Ok(blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??)
250   }
251 }