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