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