2 activities::{verify_is_public, verify_person_in_community},
3 context::lemmy_context,
4 fetcher::object_id::ObjectId,
6 community::ApubCommunity,
14 use activitystreams::{
16 chrono::NaiveDateTime,
17 object::kind::NoteType,
18 primitives::OneOrMany,
23 use chrono::{DateTime, FixedOffset};
24 use html2md::parse_html;
25 use lemmy_api_common::blocking;
28 values::{MediaTypeHtml, MediaTypeMarkdown},
29 verify::verify_domains_match,
31 use lemmy_db_schema::{
34 comment::{Comment, CommentForm},
42 utils::{convert_datetime, remove_slurs},
45 use lemmy_websocket::LemmyContext;
46 use serde::{Deserialize, Serialize};
47 use serde_with::skip_serializing_none;
51 #[skip_serializing_none]
52 #[derive(Clone, Debug, Deserialize, Serialize)]
53 #[serde(rename_all = "camelCase")]
55 /// Necessary to make this optional to make Pleroma Create/Note work.
56 /// TODO: change this so that context is not defined in the struct itself, but added in activity
57 /// queue and http handlers
58 #[serde(rename = "@context")]
59 context: Option<OneOrMany<AnyBase>>,
62 pub(crate) attributed_to: ObjectId<ApubPerson>,
63 /// Indicates that the object is publicly readable. Unlike [`Post.to`], this one doesn't contain
64 /// the community ID, as it would be incompatible with Pleroma (and we can get the community from
65 /// the post in [`in_reply_to`]).
68 media_type: Option<MediaTypeHtml>,
70 in_reply_to: ObjectId<PostOrComment>,
71 published: Option<DateTime<FixedOffset>>,
72 updated: Option<DateTime<FixedOffset>>,
77 /// Pleroma puts a raw string in the source, so we have to handle it here for deserialization to work
78 #[derive(Clone, Debug, Deserialize, Serialize)]
79 #[serde(rename_all = "camelCase")]
87 pub(crate) fn id_unchecked(&self) -> &Url {
90 pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
91 verify_domains_match(&self.id, expected_domain)?;
95 pub(crate) async fn get_parents(
97 context: &LemmyContext,
98 request_counter: &mut i32,
99 ) -> Result<(ApubPost, Option<CommentId>), LemmyError> {
100 // Fetch parent comment chain in a box, otherwise it can cause a stack overflow.
101 let parent = Box::pin(
104 .dereference(context, request_counter)
107 match parent.deref() {
108 PostOrComment::Post(p) => {
109 // Workaround because I cant figure out how to get the post out of the box (and we dont
110 // want to stackoverflow in a deep comment hierarchy).
112 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
113 Ok((post.into(), None))
115 PostOrComment::Comment(c) => {
116 let post_id = c.post_id;
117 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
118 Ok((post.into(), Some(c.id)))
123 pub(crate) async fn verify(
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: ApubCommunity = blocking(context.pool(), move |conn| {
131 Community::read(conn, community_id)
137 return Err(anyhow!("Post is locked").into());
139 verify_domains_match(self.attributed_to.inner(), &self.id)?;
140 verify_person_in_community(&self.attributed_to, &community, context, request_counter).await?;
141 verify_is_public(&self.to)?;
146 #[derive(Clone, Debug)]
147 pub struct ApubComment(Comment);
149 impl Deref for ApubComment {
150 type Target = Comment;
151 fn deref(&self) -> &Self::Target {
156 impl From<Comment> for ApubComment {
157 fn from(c: Comment) -> Self {
162 #[async_trait::async_trait(?Send)]
163 impl ApubObject for ApubComment {
164 type DataType = LemmyContext;
165 type ApubType = Note;
166 type TombstoneType = Tombstone;
168 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
172 async fn read_from_apub_id(
174 context: &LemmyContext,
175 ) -> Result<Option<Self>, LemmyError> {
177 blocking(context.pool(), move |conn| {
178 Comment::read_from_apub_id(conn, object_id)
185 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
186 blocking(context.pool(), move |conn| {
187 Comment::update_deleted(conn, self.id, true)
193 async fn to_apub(&self, context: &LemmyContext) -> Result<Note, LemmyError> {
194 let creator_id = self.creator_id;
195 let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
197 let post_id = self.post_id;
198 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
200 let in_reply_to = if let Some(comment_id) = self.parent_id {
202 blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??;
203 ObjectId::<PostOrComment>::new(parent_comment.ap_id.into_inner())
205 ObjectId::<PostOrComment>::new(post.ap_id.into_inner())
209 context: Some(lemmy_context()),
210 r#type: NoteType::Note,
211 id: self.ap_id.to_owned().into_inner(),
212 attributed_to: ObjectId::new(creator.actor_id),
214 content: self.content.clone(),
215 media_type: Some(MediaTypeHtml::Html),
216 source: SourceCompat::Lemmy(Source {
217 content: self.content.clone(),
218 media_type: MediaTypeMarkdown::Markdown,
221 published: Some(convert_datetime(self.published)),
222 updated: self.updated.map(convert_datetime),
223 unparsed: Default::default(),
229 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
232 self.updated.unwrap_or(self.published),
236 /// Converts a `Note` to `Comment`.
238 /// If the parent community, post and comment(s) are not known locally, these are also fetched.
241 context: &LemmyContext,
242 expected_domain: &Url,
243 request_counter: &mut i32,
244 ) -> Result<ApubComment, LemmyError> {
245 let ap_id = Some(note.id(expected_domain)?.clone().into());
248 .dereference(context, request_counter)
250 let (post, parent_comment_id) = note.get_parents(context, request_counter).await?;
251 let community_id = post.community_id;
252 let community = blocking(context.pool(), move |conn| {
253 Community::read(conn, community_id)
256 verify_person_in_community(
264 return Err(anyhow!("Post is locked").into());
267 let content = if let SourceCompat::Lemmy(source) = ¬e.source {
268 source.content.clone()
270 parse_html(¬e.content)
272 let content_slurs_removed = remove_slurs(&content, &context.settings().slur_regex());
274 let form = CommentForm {
275 creator_id: creator.id,
277 parent_id: parent_comment_id,
278 content: content_slurs_removed,
281 published: note.published.map(|u| u.to_owned().naive_local()),
282 updated: note.updated.map(|u| u.to_owned().naive_local()),
287 let comment = blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??;
293 pub(crate) mod tests {
295 use crate::objects::{
296 community::ApubCommunity,
297 tests::{file_to_json_object, init_context},
299 use assert_json_diff::assert_json_include;
300 use serial_test::serial;
302 pub(crate) async fn prepare_comment_test(
304 context: &LemmyContext,
305 ) -> (ApubPerson, ApubCommunity, ApubPost) {
306 let person_json = file_to_json_object("assets/lemmy-person.json");
307 let person = ApubPerson::from_apub(&person_json, context, url, &mut 0)
310 let community_json = file_to_json_object("assets/lemmy-community.json");
311 let community = ApubCommunity::from_apub(&community_json, context, url, &mut 0)
314 let post_json = file_to_json_object("assets/lemmy-post.json");
315 let post = ApubPost::from_apub(&post_json, context, url, &mut 0)
318 (person, community, post)
321 fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), context: &LemmyContext) {
322 Post::delete(&*context.pool().get().unwrap(), data.2.id).unwrap();
323 Community::delete(&*context.pool().get().unwrap(), data.1.id).unwrap();
324 Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap();
329 pub(crate) async fn test_parse_lemmy_comment() {
330 let context = init_context();
331 let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
332 let data = prepare_comment_test(&url, &context).await;
334 let json = file_to_json_object("assets/lemmy-comment.json");
335 let mut request_counter = 0;
336 let comment = ApubComment::from_apub(&json, &context, &url, &mut request_counter)
340 assert_eq!(comment.ap_id.clone().into_inner(), url);
341 assert_eq!(comment.content.len(), 14);
342 assert!(!comment.local);
343 assert_eq!(request_counter, 0);
345 let to_apub = comment.to_apub(&context).await.unwrap();
346 assert_json_include!(actual: json, expected: to_apub);
348 Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
349 cleanup(data, &context);
354 async fn test_parse_pleroma_comment() {
355 let context = init_context();
356 let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
357 let data = prepare_comment_test(&url, &context).await;
360 Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
362 let person_json = file_to_json_object("assets/pleroma-person.json");
363 ApubPerson::from_apub(&person_json, &context, &pleroma_url, &mut 0)
366 let json = file_to_json_object("assets/pleroma-comment.json");
367 let mut request_counter = 0;
368 let comment = ApubComment::from_apub(&json, &context, &pleroma_url, &mut request_counter)
372 assert_eq!(comment.ap_id.clone().into_inner(), pleroma_url);
373 assert_eq!(comment.content.len(), 64);
374 assert!(!comment.local);
375 assert_eq!(request_counter, 0);
377 Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
378 cleanup(data, &context);
383 async fn test_html_to_markdown_sanitize() {
384 let parsed = parse_html("<script></script><b>hello</b>");
385 assert_eq!(parsed, "**hello**");