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