2 activities::{verify_is_public, verify_person_in_community},
3 context::lemmy_context,
4 fetcher::object_id::ObjectId,
5 objects::{person::ApubPerson, post::ApubPost, tombstone::Tombstone, Source},
10 chrono::NaiveDateTime,
11 object::kind::NoteType,
12 primitives::OneOrMany,
17 use chrono::{DateTime, FixedOffset};
18 use html2md::parse_html;
19 use lemmy_api_common::blocking;
22 values::{MediaTypeHtml, MediaTypeMarkdown},
23 verify::verify_domains_match,
25 use lemmy_db_schema::{
28 comment::{Comment, CommentForm},
36 utils::{convert_datetime, remove_slurs},
39 use lemmy_websocket::LemmyContext;
40 use serde::{Deserialize, Serialize};
41 use serde_with::skip_serializing_none;
45 #[skip_serializing_none]
46 #[derive(Clone, Debug, Deserialize, Serialize)]
47 #[serde(rename_all = "camelCase")]
49 #[serde(rename = "@context")]
50 context: OneOrMany<AnyBase>,
53 pub(crate) attributed_to: ObjectId<ApubPerson>,
54 /// Indicates that the object is publicly readable. Unlike [`Post.to`], this one doesn't contain
55 /// the community ID, as it would be incompatible with Pleroma (and we can get the community from
56 /// the post in [`in_reply_to`]).
59 media_type: Option<MediaTypeHtml>,
61 in_reply_to: ObjectId<PostOrComment>,
62 published: Option<DateTime<FixedOffset>>,
63 updated: Option<DateTime<FixedOffset>>,
68 /// Pleroma puts a raw string in the source, so we have to handle it here for deserialization to work
69 #[derive(Clone, Debug, Deserialize, Serialize)]
70 #[serde(rename_all = "camelCase")]
78 pub(crate) fn id_unchecked(&self) -> &Url {
81 pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
82 verify_domains_match(&self.id, expected_domain)?;
86 pub(crate) async fn get_parents(
88 context: &LemmyContext,
89 request_counter: &mut i32,
90 ) -> Result<(ApubPost, Option<CommentId>), LemmyError> {
91 // Fetch parent comment chain in a box, otherwise it can cause a stack overflow.
92 let parent = Box::pin(
95 .dereference(context, request_counter)
98 match parent.deref() {
99 PostOrComment::Post(p) => {
100 // Workaround because I cant figure out how to get the post out of the box (and we dont
101 // want to stackoverflow in a deep comment hierarchy).
103 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
104 Ok((post.into(), None))
106 PostOrComment::Comment(c) => {
107 let post_id = c.post_id;
108 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
109 Ok((post.into(), Some(c.id)))
114 pub(crate) async fn verify(
116 context: &LemmyContext,
117 request_counter: &mut i32,
118 ) -> Result<(), LemmyError> {
119 let (post, _parent_comment_id) = self.get_parents(context, request_counter).await?;
120 let community_id = post.community_id;
121 let community = blocking(context.pool(), move |conn| {
122 Community::read(conn, community_id)
127 return Err(anyhow!("Post is locked").into());
129 verify_domains_match(self.attributed_to.inner(), &self.id)?;
130 verify_person_in_community(
132 &ObjectId::new(community.actor_id),
137 verify_is_public(&self.to)?;
142 #[derive(Clone, Debug)]
143 pub struct ApubComment(Comment);
145 impl Deref for ApubComment {
146 type Target = Comment;
147 fn deref(&self) -> &Self::Target {
152 impl From<Comment> for ApubComment {
153 fn from(c: Comment) -> Self {
158 #[async_trait::async_trait(?Send)]
159 impl ApubObject for ApubComment {
160 type DataType = LemmyContext;
161 type ApubType = Note;
162 type TombstoneType = Tombstone;
164 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
168 async fn read_from_apub_id(
170 context: &LemmyContext,
171 ) -> Result<Option<Self>, LemmyError> {
173 blocking(context.pool(), move |conn| {
174 Comment::read_from_apub_id(conn, object_id)
181 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
182 blocking(context.pool(), move |conn| {
183 Comment::update_deleted(conn, self.id, true)
189 async fn to_apub(&self, context: &LemmyContext) -> Result<Note, LemmyError> {
190 let creator_id = self.creator_id;
191 let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
193 let post_id = self.post_id;
194 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
196 let in_reply_to = if let Some(comment_id) = self.parent_id {
198 blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??;
199 ObjectId::<PostOrComment>::new(parent_comment.ap_id.into_inner())
201 ObjectId::<PostOrComment>::new(post.ap_id.into_inner())
205 context: lemmy_context(),
206 r#type: NoteType::Note,
207 id: self.ap_id.to_owned().into_inner(),
208 attributed_to: ObjectId::new(creator.actor_id),
210 content: self.content.clone(),
211 media_type: Some(MediaTypeHtml::Html),
212 source: SourceCompat::Lemmy(Source {
213 content: self.content.clone(),
214 media_type: MediaTypeMarkdown::Markdown,
217 published: Some(convert_datetime(self.published)),
218 updated: self.updated.map(convert_datetime),
219 unparsed: Default::default(),
225 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
228 self.updated.unwrap_or(self.published),
232 /// Converts a `Note` to `Comment`.
234 /// If the parent community, post and comment(s) are not known locally, these are also fetched.
237 context: &LemmyContext,
238 expected_domain: &Url,
239 request_counter: &mut i32,
240 ) -> Result<ApubComment, LemmyError> {
241 let ap_id = Some(note.id(expected_domain)?.clone().into());
244 .dereference(context, request_counter)
246 let (post, parent_comment_id) = note.get_parents(context, request_counter).await?;
248 return Err(anyhow!("Post is locked").into());
251 let content = if let SourceCompat::Lemmy(source) = ¬e.source {
252 source.content.clone()
254 parse_html(¬e.content)
256 let content_slurs_removed = remove_slurs(&content, &context.settings().slur_regex());
258 let form = CommentForm {
259 creator_id: creator.id,
261 parent_id: parent_comment_id,
262 content: content_slurs_removed,
265 published: note.published.map(|u| u.to_owned().naive_local()),
266 updated: note.updated.map(|u| u.to_owned().naive_local()),
271 let comment = blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??;
279 use crate::objects::{
280 community::ApubCommunity,
281 tests::{file_to_json_object, init_context},
283 use assert_json_diff::assert_json_include;
284 use serial_test::serial;
286 async fn prepare_comment_test(
288 context: &LemmyContext,
289 ) -> (ApubPerson, ApubCommunity, ApubPost) {
290 let person_json = file_to_json_object("assets/lemmy-person.json");
291 let person = ApubPerson::from_apub(&person_json, context, url, &mut 0)
294 let community_json = file_to_json_object("assets/lemmy-community.json");
295 let community = ApubCommunity::from_apub(&community_json, context, url, &mut 0)
298 let post_json = file_to_json_object("assets/lemmy-post.json");
299 let post = ApubPost::from_apub(&post_json, context, url, &mut 0)
302 (person, community, post)
305 fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), context: &LemmyContext) {
306 Post::delete(&*context.pool().get().unwrap(), data.2.id).unwrap();
307 Community::delete(&*context.pool().get().unwrap(), data.1.id).unwrap();
308 Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap();
313 async fn test_parse_lemmy_comment() {
314 // TODO: changed ObjectId::dereference() so that it always fetches if
315 // last_refreshed_at() == None. But post doesnt store that and expects to never be refetched
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**");