2 activities::{verify_is_public, verify_person_in_community},
3 fetcher::object_id::ObjectId,
5 community::ApubCommunity,
13 use activitystreams::{object::kind::NoteType, public, unparsed::Unparsed};
15 use chrono::{DateTime, FixedOffset, NaiveDateTime};
16 use html2md::parse_html;
17 use lemmy_api_common::blocking;
20 values::{MediaTypeHtml, MediaTypeMarkdown},
21 verify::verify_domains_match,
23 use lemmy_db_schema::{
26 comment::{Comment, CommentForm},
34 utils::{convert_datetime, remove_slurs},
37 use lemmy_websocket::LemmyContext;
38 use serde::{Deserialize, Serialize};
39 use serde_with::skip_serializing_none;
43 #[skip_serializing_none]
44 #[derive(Clone, Debug, Deserialize, Serialize)]
45 #[serde(rename_all = "camelCase")]
49 pub(crate) attributed_to: ObjectId<ApubPerson>,
50 /// Indicates that the object is publicly readable. Unlike [`Post.to`], this one doesn't contain
51 /// the community ID, as it would be incompatible with Pleroma (and we can get the community from
52 /// the post in [`in_reply_to`]).
55 media_type: Option<MediaTypeHtml>,
57 in_reply_to: ObjectId<PostOrComment>,
58 published: Option<DateTime<FixedOffset>>,
59 updated: Option<DateTime<FixedOffset>>,
64 /// Pleroma puts a raw string in the source, so we have to handle it here for deserialization to work
65 #[derive(Clone, Debug, Deserialize, Serialize)]
66 #[serde(rename_all = "camelCase")]
74 pub(crate) fn id_unchecked(&self) -> &Url {
77 pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
78 verify_domains_match(&self.id, expected_domain)?;
82 pub(crate) async fn get_parents(
84 context: &LemmyContext,
85 request_counter: &mut i32,
86 ) -> Result<(ApubPost, Option<CommentId>), LemmyError> {
87 // Fetch parent comment chain in a box, otherwise it can cause a stack overflow.
88 let parent = Box::pin(
91 .dereference(context, request_counter)
94 match parent.deref() {
95 PostOrComment::Post(p) => {
96 // Workaround because I cant figure out how to get the post out of the box (and we dont
97 // want to stackoverflow in a deep comment hierarchy).
99 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
100 Ok((post.into(), None))
102 PostOrComment::Comment(c) => {
103 let post_id = c.post_id;
104 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
105 Ok((post.into(), Some(c.id)))
110 pub(crate) async fn verify(
112 context: &LemmyContext,
113 request_counter: &mut i32,
114 ) -> Result<(), LemmyError> {
115 let (post, _parent_comment_id) = self.get_parents(context, request_counter).await?;
116 let community_id = post.community_id;
117 let community: ApubCommunity = blocking(context.pool(), move |conn| {
118 Community::read(conn, community_id)
124 return Err(anyhow!("Post is locked").into());
126 verify_domains_match(self.attributed_to.inner(), &self.id)?;
127 verify_person_in_community(&self.attributed_to, &community, context, request_counter).await?;
128 verify_is_public(&self.to)?;
133 #[derive(Clone, Debug)]
134 pub struct ApubComment(Comment);
136 impl Deref for ApubComment {
137 type Target = Comment;
138 fn deref(&self) -> &Self::Target {
143 impl From<Comment> for ApubComment {
144 fn from(c: Comment) -> Self {
149 #[async_trait::async_trait(?Send)]
150 impl ApubObject for ApubComment {
151 type DataType = LemmyContext;
152 type ApubType = Note;
153 type TombstoneType = Tombstone;
155 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
159 async fn read_from_apub_id(
161 context: &LemmyContext,
162 ) -> Result<Option<Self>, LemmyError> {
164 blocking(context.pool(), move |conn| {
165 Comment::read_from_apub_id(conn, object_id)
172 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
173 blocking(context.pool(), move |conn| {
174 Comment::update_deleted(conn, self.id, true)
180 async fn to_apub(&self, context: &LemmyContext) -> Result<Note, LemmyError> {
181 let creator_id = self.creator_id;
182 let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
184 let post_id = self.post_id;
185 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
187 let in_reply_to = if let Some(comment_id) = self.parent_id {
189 blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??;
190 ObjectId::<PostOrComment>::new(parent_comment.ap_id.into_inner())
192 ObjectId::<PostOrComment>::new(post.ap_id.into_inner())
196 r#type: NoteType::Note,
197 id: self.ap_id.to_owned().into_inner(),
198 attributed_to: ObjectId::new(creator.actor_id),
200 content: self.content.clone(),
201 media_type: Some(MediaTypeHtml::Html),
202 source: SourceCompat::Lemmy(Source {
203 content: self.content.clone(),
204 media_type: MediaTypeMarkdown::Markdown,
207 published: Some(convert_datetime(self.published)),
208 updated: self.updated.map(convert_datetime),
209 unparsed: Default::default(),
215 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
218 self.updated.unwrap_or(self.published),
222 /// Converts a `Note` to `Comment`.
224 /// If the parent community, post and comment(s) are not known locally, these are also fetched.
227 context: &LemmyContext,
228 expected_domain: &Url,
229 request_counter: &mut i32,
230 ) -> Result<ApubComment, LemmyError> {
231 let ap_id = Some(note.id(expected_domain)?.clone().into());
234 .dereference(context, request_counter)
236 let (post, parent_comment_id) = note.get_parents(context, request_counter).await?;
237 let community_id = post.community_id;
238 let community = blocking(context.pool(), move |conn| {
239 Community::read(conn, community_id)
242 verify_person_in_community(
250 return Err(anyhow!("Post is locked").into());
253 let content = if let SourceCompat::Lemmy(source) = ¬e.source {
254 source.content.clone()
256 parse_html(¬e.content)
258 let content_slurs_removed = remove_slurs(&content, &context.settings().slur_regex());
260 let form = CommentForm {
261 creator_id: creator.id,
263 parent_id: parent_comment_id,
264 content: content_slurs_removed,
267 published: note.published.map(|u| u.to_owned().naive_local()),
268 updated: note.updated.map(|u| u.to_owned().naive_local()),
273 let comment = blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??;
279 pub(crate) mod tests {
281 use crate::objects::{
282 community::ApubCommunity,
283 tests::{file_to_json_object, init_context},
285 use assert_json_diff::assert_json_include;
286 use serial_test::serial;
288 pub(crate) async fn prepare_comment_test(
290 context: &LemmyContext,
291 ) -> (ApubPerson, ApubCommunity, ApubPost) {
292 let person_json = file_to_json_object("assets/lemmy-person.json");
293 let person = ApubPerson::from_apub(&person_json, context, url, &mut 0)
296 let community_json = file_to_json_object("assets/lemmy-community.json");
297 let community = ApubCommunity::from_apub(&community_json, context, url, &mut 0)
300 let post_json = file_to_json_object("assets/lemmy-post.json");
301 let post = ApubPost::from_apub(&post_json, context, url, &mut 0)
304 (person, community, post)
307 fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), context: &LemmyContext) {
308 Post::delete(&*context.pool().get().unwrap(), data.2.id).unwrap();
309 Community::delete(&*context.pool().get().unwrap(), data.1.id).unwrap();
310 Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap();
315 pub(crate) async fn test_parse_lemmy_comment() {
316 let context = init_context();
317 let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
318 let data = prepare_comment_test(&url, &context).await;
320 let json = file_to_json_object("assets/lemmy-comment.json");
321 let mut request_counter = 0;
322 let comment = ApubComment::from_apub(&json, &context, &url, &mut request_counter)
326 assert_eq!(comment.ap_id.clone().into_inner(), url);
327 assert_eq!(comment.content.len(), 14);
328 assert!(!comment.local);
329 assert_eq!(request_counter, 0);
331 let to_apub = comment.to_apub(&context).await.unwrap();
332 assert_json_include!(actual: json, expected: to_apub);
334 Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
335 cleanup(data, &context);
340 async fn test_parse_pleroma_comment() {
341 let context = init_context();
342 let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
343 let data = prepare_comment_test(&url, &context).await;
346 Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
348 let person_json = file_to_json_object("assets/pleroma-person.json");
349 ApubPerson::from_apub(&person_json, &context, &pleroma_url, &mut 0)
352 let json = file_to_json_object("assets/pleroma-comment.json");
353 let mut request_counter = 0;
354 let comment = ApubComment::from_apub(&json, &context, &pleroma_url, &mut request_counter)
358 assert_eq!(comment.ap_id.clone().into_inner(), pleroma_url);
359 assert_eq!(comment.content.len(), 64);
360 assert!(!comment.local);
361 assert_eq!(request_counter, 0);
363 Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
364 cleanup(data, &context);
369 async fn test_html_to_markdown_sanitize() {
370 let parsed = parse_html("<script></script><b>hello</b>");
371 assert_eq!(parsed, "**hello**");