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 {
85 Comment::update(&mut context.pool(), self.id, &form).await?;
90 #[tracing::instrument(skip_all)]
91 async fn into_json(self, context: &Data<Self::DataType>) -> Result<Note, LemmyError> {
92 let creator_id = self.creator_id;
93 let creator = Person::read(&mut context.pool(), creator_id).await?;
95 let post_id = self.post_id;
96 let post = Post::read(&mut context.pool(), post_id).await?;
97 let community_id = post.community_id;
98 let community = Community::read(&mut context.pool(), community_id).await?;
100 let in_reply_to = if let Some(comment_id) = self.parent_comment_id() {
101 let parent_comment = Comment::read(&mut context.pool(), comment_id).await?;
102 parent_comment.ap_id.into()
106 let language = LanguageTag::new_single(self.language_id, &mut context.pool()).await?;
107 let maa = collect_non_local_mentions(&self, community.actor_id.clone().into(), context).await?;
110 r#type: NoteType::Note,
111 id: self.ap_id.clone().into(),
112 attributed_to: creator.actor_id.into(),
115 content: markdown_to_html(&self.content),
116 media_type: Some(MediaTypeMarkdownOrHtml::Html),
117 source: Some(Source::new(self.content.clone())),
119 published: Some(convert_datetime(self.published)),
120 updated: self.updated.map(convert_datetime),
122 distinguished: Some(self.distinguished),
124 audience: Some(community.actor_id.into()),
130 #[tracing::instrument(skip_all)]
133 expected_domain: &Url,
134 context: &Data<LemmyContext>,
135 ) -> Result<(), LemmyError> {
136 verify_domains_match(note.id.inner(), expected_domain)?;
137 verify_domains_match(note.attributed_to.inner(), note.id.inner())?;
138 verify_is_public(¬e.to, ¬e.cc)?;
139 let community = note.community(context).await?;
141 check_apub_id_valid_with_strictness(note.id.inner(), community.local, context).await?;
142 verify_is_remote_object(note.id.inner(), context.settings())?;
143 verify_person_in_community(¬e.attributed_to, &community, context).await?;
144 let (post, _) = note.get_parents(context).await?;
146 return Err(LemmyErrorType::PostIsLocked)?;
151 /// Converts a `Note` to `Comment`.
153 /// If the parent community, post and comment(s) are not known locally, these are also fetched.
154 #[tracing::instrument(skip_all)]
155 async fn from_json(note: Note, context: &Data<LemmyContext>) -> Result<ApubComment, LemmyError> {
156 let creator = note.attributed_to.dereference(context).await?;
157 let (post, parent_comment) = note.get_parents(context).await?;
159 let content = read_from_string_or_source(¬e.content, ¬e.media_type, ¬e.source);
161 let local_site = LocalSite::read(&mut context.pool()).await.ok();
162 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
163 let content = remove_slurs(&content, slur_regex);
164 let content = sanitize_html(&content);
166 LanguageTag::to_language_id_single(note.language, &mut context.pool()).await?;
168 let form = CommentInsertForm {
169 creator_id: creator.id,
173 published: note.published.map(|u| u.naive_local()),
174 updated: note.updated.map(|u| u.naive_local()),
175 deleted: Some(false),
176 ap_id: Some(note.id.into()),
177 distinguished: note.distinguished,
181 let parent_comment_path = parent_comment.map(|t| t.0.path);
182 let comment = Comment::create(&mut context.pool(), &form, parent_comment_path.as_ref()).await?;
188 pub(crate) mod tests {
189 #![allow(clippy::unwrap_used)]
190 #![allow(clippy::indexing_slicing)]
195 community::{tests::parse_lemmy_community, ApubCommunity},
197 person::{tests::parse_lemmy_person, ApubPerson},
201 protocol::tests::file_to_json_object,
203 use assert_json_diff::assert_json_include;
204 use html2md::parse_html;
205 use lemmy_db_schema::source::site::Site;
206 use serial_test::serial;
208 async fn prepare_comment_test(
210 context: &Data<LemmyContext>,
211 ) -> (ApubPerson, ApubCommunity, ApubPost, ApubSite) {
212 // use separate counter so this doesnt affect tests
213 let context2 = context.reset_request_count();
214 let (person, site) = parse_lemmy_person(&context2).await;
215 let community = parse_lemmy_community(&context2).await;
216 let post_json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
217 ApubPost::verify(&post_json, url, &context2).await.unwrap();
218 let post = ApubPost::from_json(post_json, &context2).await.unwrap();
219 (person, community, post, site)
222 async fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost, ApubSite), context: &LemmyContext) {
223 Post::delete(&mut context.pool(), data.2.id).await.unwrap();
224 Community::delete(&mut context.pool(), data.1.id)
227 Person::delete(&mut context.pool(), data.0.id)
230 Site::delete(&mut context.pool(), data.3.id).await.unwrap();
231 LocalSite::delete(&mut context.pool()).await.unwrap();
236 pub(crate) async fn test_parse_lemmy_comment() {
237 let context = init_context().await;
238 let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
239 let data = prepare_comment_test(&url, &context).await;
241 let json: Note = file_to_json_object("assets/lemmy/objects/note.json").unwrap();
242 ApubComment::verify(&json, &url, &context).await.unwrap();
243 let comment = ApubComment::from_json(json.clone(), &context)
247 assert_eq!(comment.ap_id, url.into());
248 assert_eq!(comment.content.len(), 14);
249 assert!(!comment.local);
250 assert_eq!(context.request_count(), 0);
252 let comment_id = comment.id;
253 let to_apub = comment.into_json(&context).await.unwrap();
254 assert_json_include!(actual: json, expected: to_apub);
256 Comment::delete(&mut context.pool(), comment_id)
259 cleanup(data, &context).await;
264 async fn test_parse_pleroma_comment() {
265 let context = init_context().await;
266 let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
267 let data = prepare_comment_test(&url, &context).await;
270 Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
272 let person_json = file_to_json_object("assets/pleroma/objects/person.json").unwrap();
273 ApubPerson::verify(&person_json, &pleroma_url, &context)
276 ApubPerson::from_json(person_json, &context).await.unwrap();
277 let json = file_to_json_object("assets/pleroma/objects/note.json").unwrap();
278 ApubComment::verify(&json, &pleroma_url, &context)
281 let comment = ApubComment::from_json(json, &context).await.unwrap();
283 assert_eq!(comment.ap_id, pleroma_url.into());
284 assert_eq!(comment.content.len(), 64);
285 assert!(!comment.local);
286 assert_eq!(context.request_count(), 1);
288 Comment::delete(&mut context.pool(), comment.id)
291 cleanup(data, &context).await;
296 async fn test_html_to_markdown_sanitize() {
297 let parsed = parse_html("<script></script><b>hello</b>");
298 assert_eq!(parsed, "**hello**");