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},
11 object::{kind::NoteType, Tombstone},
12 primitives::OneOrMany,
15 use anyhow::{anyhow, Context};
16 use chrono::{DateTime, FixedOffset};
17 use lemmy_api_common::blocking;
20 values::{MediaTypeHtml, MediaTypeMarkdown, PublicUrl},
21 verify::verify_domains_match,
23 use lemmy_db_queries::{source::comment::Comment_, Crud, DbPool};
24 use lemmy_db_schema::{
26 comment::{Comment, CommentForm},
35 utils::{convert_datetime, remove_slurs},
38 use lemmy_websocket::LemmyContext;
39 use serde::{Deserialize, Serialize};
40 use serde_with::skip_serializing_none;
44 #[skip_serializing_none]
45 #[derive(Clone, Debug, Deserialize, Serialize)]
46 #[serde(rename_all = "camelCase")]
48 #[serde(rename = "@context")]
49 context: OneOrMany<AnyBase>,
52 pub(crate) attributed_to: ObjectId<Person>,
53 /// Indicates that the object is publicly readable. Unlike [`Post.to`], this one doesn't contain
54 /// the community ID, as it would be incompatible with Pleroma (and we can get the community from
55 /// the post in [`in_reply_to`]).
58 media_type: MediaTypeHtml,
60 in_reply_to: CommentInReplyToMigration,
61 published: DateTime<FixedOffset>,
62 updated: Option<DateTime<FixedOffset>>,
68 pub(crate) fn id_unchecked(&self) -> &Url {
71 pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
72 verify_domains_match(&self.id, expected_domain)?;
76 pub(crate) async fn get_parents(
78 context: &LemmyContext,
79 request_counter: &mut i32,
80 ) -> Result<(Post, Option<CommentId>), LemmyError> {
81 match &self.in_reply_to {
82 CommentInReplyToMigration::Old(in_reply_to) => {
83 // This post, or the parent comment might not yet exist on this server yet, fetch them.
84 let post_id = in_reply_to.get(0).context(location_info!())?;
85 let post_id = ObjectId::new(post_id.clone());
86 let post = Box::pin(post_id.dereference(context, request_counter)).await?;
88 // The 2nd item, if it exists, is the parent comment apub_id
89 // Nested comments will automatically get fetched recursively
90 let parent_id: Option<CommentId> = match in_reply_to.get(1) {
92 let comment_id = ObjectId::<Comment>::new(comment_id.clone());
93 let parent_comment = Box::pin(comment_id.dereference(context, request_counter)).await?;
95 Some(parent_comment.id)
100 Ok((post, parent_id))
102 CommentInReplyToMigration::New(in_reply_to) => {
103 let parent = Box::pin(in_reply_to.dereference(context, request_counter).await?);
104 match parent.deref() {
105 PostOrComment::Post(p) => {
106 // Workaround because I cant figure ut how to get the post out of the box (and we dont
107 // want to stackoverflow in a deep comment hierarchy).
109 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
112 PostOrComment::Comment(c) => {
113 let post_id = c.post_id;
114 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
115 Ok((post, Some(c.id)))
122 pub(crate) async fn verify(
124 context: &LemmyContext,
125 request_counter: &mut i32,
126 ) -> Result<(), LemmyError> {
127 let (post, _parent_comment_id) = self.get_parents(context, request_counter).await?;
128 let community_id = post.community_id;
129 let community = blocking(context.pool(), move |conn| {
130 Community::read(conn, community_id)
135 return Err(anyhow!("Post is locked").into());
137 verify_domains_match(self.attributed_to.inner(), &self.id)?;
138 verify_person_in_community(
140 &ObjectId::new(community.actor_id()),
149 #[async_trait::async_trait(?Send)]
150 impl ToApub for Comment {
151 type ApubType = Note;
153 async fn to_apub(&self, pool: &DbPool) -> Result<Note, LemmyError> {
154 let creator_id = self.creator_id;
155 let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
157 let post_id = self.post_id;
158 let post = blocking(pool, move |conn| Post::read(conn, post_id)).await??;
160 // Add a vector containing some important info to the "in_reply_to" field
161 // [post_ap_id, Option(parent_comment_ap_id)]
162 let mut in_reply_to_vec = vec![post.ap_id.into_inner()];
164 if let Some(parent_id) = self.parent_id {
165 let parent_comment = blocking(pool, move |conn| Comment::read(conn, parent_id)).await??;
167 in_reply_to_vec.push(parent_comment.ap_id.into_inner());
171 context: lemmy_context(),
172 r#type: NoteType::Note,
173 id: self.ap_id.to_owned().into_inner(),
174 attributed_to: ObjectId::new(creator.actor_id),
175 to: PublicUrl::Public,
176 content: self.content.clone(),
177 media_type: MediaTypeHtml::Html,
179 content: self.content.clone(),
180 media_type: MediaTypeMarkdown::Markdown,
182 in_reply_to: CommentInReplyToMigration::Old(in_reply_to_vec),
183 published: convert_datetime(self.published),
184 updated: self.updated.map(convert_datetime),
185 unparsed: Default::default(),
191 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
194 self.ap_id.to_owned().into(),
201 #[async_trait::async_trait(?Send)]
202 impl FromApub for Comment {
203 type ApubType = Note;
205 /// Converts a `Note` to `Comment`.
207 /// If the parent community, post and comment(s) are not known locally, these are also fetched.
210 context: &LemmyContext,
211 expected_domain: &Url,
212 request_counter: &mut i32,
213 ) -> Result<Comment, LemmyError> {
214 let ap_id = Some(note.id(expected_domain)?.clone().into());
217 .dereference(context, request_counter)
219 let (post, parent_comment_id) = note.get_parents(context, request_counter).await?;
221 return Err(anyhow!("Post is locked").into());
224 let content = ¬e.source.content;
225 let content_slurs_removed = remove_slurs(content, &context.settings().slur_regex());
227 let form = CommentForm {
228 creator_id: creator.id,
230 parent_id: parent_comment_id,
231 content: content_slurs_removed,
234 published: Some(note.published.naive_local()),
235 updated: note.updated.map(|u| u.to_owned().naive_local()),
240 Ok(blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??)