]> Untitled Git - lemmy.git/blob - crates/apub/src/protocol/objects/note.rs
First pass at adding comment trees. (#2362)
[lemmy.git] / crates / apub / src / protocol / objects / note.rs
1 use crate::{
2   fetcher::post_or_comment::PostOrComment,
3   local_instance,
4   mentions::MentionOrValue,
5   objects::{comment::ApubComment, person::ApubPerson, post::ApubPost},
6   protocol::Source,
7 };
8 use activitypub_federation::{
9   core::object_id::ObjectId,
10   deser::{
11     helpers::{deserialize_one_or_many, deserialize_skip_error},
12     values::MediaTypeMarkdownOrHtml,
13   },
14 };
15 use activitystreams_kinds::object::NoteType;
16 use chrono::{DateTime, FixedOffset};
17 use lemmy_api_common::utils::blocking;
18 use lemmy_db_schema::{source::post::Post, traits::Crud};
19 use lemmy_utils::error::LemmyError;
20 use lemmy_websocket::LemmyContext;
21 use serde::{Deserialize, Serialize};
22 use serde_with::skip_serializing_none;
23 use std::ops::Deref;
24 use url::Url;
25
26 #[skip_serializing_none]
27 #[derive(Clone, Debug, Deserialize, Serialize)]
28 #[serde(rename_all = "camelCase")]
29 pub struct Note {
30   pub(crate) r#type: NoteType,
31   pub(crate) id: ObjectId<ApubComment>,
32   pub(crate) attributed_to: ObjectId<ApubPerson>,
33   #[serde(deserialize_with = "deserialize_one_or_many")]
34   pub(crate) to: Vec<Url>,
35   #[serde(deserialize_with = "deserialize_one_or_many", default)]
36   pub(crate) cc: Vec<Url>,
37   pub(crate) content: String,
38   pub(crate) in_reply_to: ObjectId<PostOrComment>,
39
40   pub(crate) media_type: Option<MediaTypeMarkdownOrHtml>,
41   #[serde(deserialize_with = "deserialize_skip_error", default)]
42   pub(crate) source: Option<Source>,
43   pub(crate) published: Option<DateTime<FixedOffset>>,
44   pub(crate) updated: Option<DateTime<FixedOffset>>,
45   #[serde(default)]
46   pub(crate) tag: Vec<MentionOrValue>,
47 }
48
49 impl Note {
50   pub(crate) async fn get_parents(
51     &self,
52     context: &LemmyContext,
53     request_counter: &mut i32,
54   ) -> Result<(ApubPost, Option<ApubComment>), LemmyError> {
55     // Fetch parent comment chain in a box, otherwise it can cause a stack overflow.
56     let parent = Box::pin(
57       self
58         .in_reply_to
59         .dereference(context, local_instance(context), request_counter)
60         .await?,
61     );
62     match parent.deref() {
63       PostOrComment::Post(p) => {
64         let post = p.deref().to_owned();
65         Ok((post, None))
66       }
67       PostOrComment::Comment(c) => {
68         let post_id = c.post_id;
69         let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
70         let comment = c.deref().to_owned();
71         Ok((post.into(), Some(comment)))
72       }
73     }
74   }
75 }