2 activities::{verify_is_public, verify_person_in_community},
3 check_apub_id_valid_with_strictness,
4 mentions::collect_non_local_mentions,
5 objects::{read_from_string_or_source, verify_is_remote_object},
7 objects::{note::Note, LanguageTag},
12 use activitypub_federation::{
14 kinds::{object::NoteType, public},
15 protocol::{values::MediaTypeMarkdownOrHtml, verification::verify_domains_match},
18 use chrono::NaiveDateTime;
19 use lemmy_api_common::{
20 context::LemmyContext,
21 utils::{local_site_opt_to_slur_regex, sanitize_html},
23 use lemmy_db_schema::{
25 comment::{Comment, CommentInsertForm, CommentUpdateForm},
27 local_site::LocalSite,
34 error::{LemmyError, LemmyErrorType},
35 utils::{markdown::markdown_to_html, slurs::remove_slurs, time::convert_datetime},
40 #[derive(Clone, Debug)]
41 pub struct ApubComment(pub(crate) Comment);
43 impl Deref for ApubComment {
44 type Target = Comment;
45 fn deref(&self) -> &Self::Target {
50 impl From<Comment> for ApubComment {
51 fn from(c: Comment) -> Self {
56 #[async_trait::async_trait]
57 impl Object for ApubComment {
58 type DataType = LemmyContext;
60 type Error = LemmyError;
62 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
66 #[tracing::instrument(skip_all)]
67 async fn read_from_id(
69 context: &Data<Self::DataType>,
70 ) -> Result<Option<Self>, LemmyError> {
72 Comment::read_from_apub_id(&mut context.pool(), object_id)
78 #[tracing::instrument(skip_all)]
79 async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
81 let form = CommentUpdateForm::builder().deleted(Some(true)).build();
82 Comment::update(&mut context.pool(), self.id, &form).await?;
87 #[tracing::instrument(skip_all)]
88 async fn into_json(self, context: &Data<Self::DataType>) -> Result<Note, LemmyError> {
89 let creator_id = self.creator_id;
90 let creator = Person::read(&mut context.pool(), creator_id).await?;
92 let post_id = self.post_id;
93 let post = Post::read(&mut context.pool(), post_id).await?;
94 let community_id = post.community_id;
95 let community = Community::read(&mut context.pool(), community_id).await?;
97 let in_reply_to = if let Some(comment_id) = self.parent_comment_id() {
98 let parent_comment = Comment::read(&mut context.pool(), comment_id).await?;
99 parent_comment.ap_id.into()
103 let language = LanguageTag::new_single(self.language_id, &mut context.pool()).await?;
104 let maa = collect_non_local_mentions(&self, community.actor_id.clone().into(), context).await?;
107 r#type: NoteType::Note,
108 id: self.ap_id.clone().into(),
109 attributed_to: creator.actor_id.into(),
112 content: markdown_to_html(&self.content),
113 media_type: Some(MediaTypeMarkdownOrHtml::Html),
114 source: Some(Source::new(self.content.clone())),
116 published: Some(convert_datetime(self.published)),
117 updated: self.updated.map(convert_datetime),
119 distinguished: Some(self.distinguished),
121 audience: Some(community.actor_id.into()),
127 #[tracing::instrument(skip_all)]
130 expected_domain: &Url,
131 context: &Data<LemmyContext>,
132 ) -> Result<(), LemmyError> {
133 verify_domains_match(note.id.inner(), expected_domain)?;
134 verify_domains_match(note.attributed_to.inner(), note.id.inner())?;
135 verify_is_public(¬e.to, ¬e.cc)?;
136 let community = note.community(context).await?;
138 check_apub_id_valid_with_strictness(note.id.inner(), community.local, context).await?;
139 verify_is_remote_object(note.id.inner(), context.settings())?;
140 verify_person_in_community(¬e.attributed_to, &community, context).await?;
141 let (post, _) = note.get_parents(context).await?;
143 return Err(LemmyErrorType::PostIsLocked)?;
148 /// Converts a `Note` to `Comment`.
150 /// If the parent community, post and comment(s) are not known locally, these are also fetched.
151 #[tracing::instrument(skip_all)]
152 async fn from_json(note: Note, context: &Data<LemmyContext>) -> Result<ApubComment, LemmyError> {
153 let creator = note.attributed_to.dereference(context).await?;
154 let (post, parent_comment) = note.get_parents(context).await?;
156 let content = read_from_string_or_source(¬e.content, ¬e.media_type, ¬e.source);
158 let local_site = LocalSite::read(&mut context.pool()).await.ok();
159 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
160 let content = remove_slurs(&content, slur_regex);
161 let content = sanitize_html(&content);
163 LanguageTag::to_language_id_single(note.language, &mut context.pool()).await?;
165 let form = CommentInsertForm {
166 creator_id: creator.id,
170 published: note.published.map(|u| u.naive_local()),
171 updated: note.updated.map(|u| u.naive_local()),
172 deleted: Some(false),
173 ap_id: Some(note.id.into()),
174 distinguished: note.distinguished,
178 let parent_comment_path = parent_comment.map(|t| t.0.path);
179 let comment = Comment::create(&mut context.pool(), &form, parent_comment_path.as_ref()).await?;
185 pub(crate) mod tests {
186 #![allow(clippy::unwrap_used)]
187 #![allow(clippy::indexing_slicing)]
192 community::{tests::parse_lemmy_community, ApubCommunity},
194 person::{tests::parse_lemmy_person, ApubPerson},
198 protocol::tests::file_to_json_object,
200 use assert_json_diff::assert_json_include;
201 use html2md::parse_html;
202 use lemmy_db_schema::source::site::Site;
203 use serial_test::serial;
205 async fn prepare_comment_test(
207 context: &Data<LemmyContext>,
208 ) -> (ApubPerson, ApubCommunity, ApubPost, ApubSite) {
209 // use separate counter so this doesnt affect tests
210 let context2 = context.reset_request_count();
211 let (person, site) = parse_lemmy_person(&context2).await;
212 let community = parse_lemmy_community(&context2).await;
213 let post_json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
214 ApubPost::verify(&post_json, url, &context2).await.unwrap();
215 let post = ApubPost::from_json(post_json, &context2).await.unwrap();
216 (person, community, post, site)
219 async fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost, ApubSite), context: &LemmyContext) {
220 Post::delete(&mut context.pool(), data.2.id).await.unwrap();
221 Community::delete(&mut context.pool(), data.1.id)
224 Person::delete(&mut context.pool(), data.0.id)
227 Site::delete(&mut context.pool(), data.3.id).await.unwrap();
228 LocalSite::delete(&mut context.pool()).await.unwrap();
233 pub(crate) async fn test_parse_lemmy_comment() {
234 let context = init_context().await;
235 let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
236 let data = prepare_comment_test(&url, &context).await;
238 let json: Note = file_to_json_object("assets/lemmy/objects/note.json").unwrap();
239 ApubComment::verify(&json, &url, &context).await.unwrap();
240 let comment = ApubComment::from_json(json.clone(), &context)
244 assert_eq!(comment.ap_id, url.into());
245 assert_eq!(comment.content.len(), 14);
246 assert!(!comment.local);
247 assert_eq!(context.request_count(), 0);
249 let comment_id = comment.id;
250 let to_apub = comment.into_json(&context).await.unwrap();
251 assert_json_include!(actual: json, expected: to_apub);
253 Comment::delete(&mut context.pool(), comment_id)
256 cleanup(data, &context).await;
261 async fn test_parse_pleroma_comment() {
262 let context = init_context().await;
263 let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
264 let data = prepare_comment_test(&url, &context).await;
267 Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
269 let person_json = file_to_json_object("assets/pleroma/objects/person.json").unwrap();
270 ApubPerson::verify(&person_json, &pleroma_url, &context)
273 ApubPerson::from_json(person_json, &context).await.unwrap();
274 let json = file_to_json_object("assets/pleroma/objects/note.json").unwrap();
275 ApubComment::verify(&json, &pleroma_url, &context)
278 let comment = ApubComment::from_json(json, &context).await.unwrap();
280 assert_eq!(comment.ap_id, pleroma_url.into());
281 assert_eq!(comment.content.len(), 64);
282 assert!(!comment.local);
283 assert_eq!(context.request_count(), 1);
285 Comment::delete(&mut context.pool(), comment.id)
288 cleanup(data, &context).await;
293 async fn test_html_to_markdown_sanitize() {
294 let parsed = parse_html("<script></script><b>hello</b>");
295 assert_eq!(parsed, "**hello**");