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