2 activities::{verify_is_public, verify_person_in_community},
3 check_apub_id_valid_with_strictness,
6 objects::{read_from_string_or_source_opt, verify_is_remote_object},
9 page::{Attachment, AttributedTo, Page, PageType},
17 use activitypub_federation::{
18 core::object_id::ObjectId,
19 deser::values::MediaTypeMarkdownOrHtml,
21 utils::verify_domains_match,
23 use activitystreams_kinds::public;
25 use chrono::NaiveDateTime;
26 use html2md::parse_html;
27 use lemmy_api_common::{
28 context::LemmyContext,
29 request::fetch_site_data,
30 utils::{is_mod_or_admin, local_site_opt_to_slur_regex},
32 use lemmy_db_schema::{
36 local_site::LocalSite,
37 moderator::{ModFeaturePost, ModFeaturePostForm, ModLockPost, ModLockPostForm},
39 post::{Post, PostInsertForm, PostUpdateForm},
46 markdown::markdown_to_html,
47 slurs::{check_slurs_opt, remove_slurs},
48 time::convert_datetime,
54 const MAX_TITLE_LENGTH: usize = 200;
56 #[derive(Clone, Debug)]
57 pub struct ApubPost(pub(crate) Post);
59 impl Deref for ApubPost {
61 fn deref(&self) -> &Self::Target {
66 impl From<Post> for ApubPost {
67 fn from(p: Post) -> Self {
72 #[async_trait::async_trait(?Send)]
73 impl ApubObject for ApubPost {
74 type DataType = LemmyContext;
77 type Error = LemmyError;
79 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
83 #[tracing::instrument(skip_all)]
84 async fn read_from_apub_id(
86 context: &LemmyContext,
87 ) -> Result<Option<Self>, LemmyError> {
89 Post::read_from_apub_id(context.pool(), object_id)
95 #[tracing::instrument(skip_all)]
96 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
98 let form = PostUpdateForm::builder().deleted(Some(true)).build();
99 Post::update(context.pool(), self.id, &form).await?;
104 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
105 #[tracing::instrument(skip_all)]
106 async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
107 let creator_id = self.creator_id;
108 let creator = Person::read(context.pool(), creator_id).await?;
109 let community_id = self.community_id;
110 let community = Community::read(context.pool(), community_id).await?;
111 let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
114 kind: PageType::Page,
115 id: ObjectId::new(self.ap_id.clone()),
116 attributed_to: AttributedTo::Lemmy(ObjectId::new(creator.actor_id)),
117 to: vec![community.actor_id.clone().into(), public()],
119 name: Some(self.name.clone()),
120 content: self.body.as_ref().map(|b| markdown_to_html(b)),
121 media_type: Some(MediaTypeMarkdownOrHtml::Html),
122 source: self.body.clone().map(Source::new),
123 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
124 image: self.thumbnail_url.clone().map(ImageObject::new),
125 comments_enabled: Some(!self.locked),
126 sensitive: Some(self.nsfw),
127 stickied: Some(self.featured_community),
129 published: Some(convert_datetime(self.published)),
130 updated: self.updated.map(convert_datetime),
131 audience: Some(ObjectId::new(community.actor_id)),
137 #[tracing::instrument(skip_all)]
140 expected_domain: &Url,
141 context: &LemmyContext,
142 request_counter: &mut i32,
143 ) -> Result<(), LemmyError> {
144 // We can't verify the domain in case of mod action, because the mod may be on a different
145 // instance from the post author.
146 if !page.is_mod_action(context).await? {
147 verify_domains_match(page.id.inner(), expected_domain)?;
148 verify_is_remote_object(page.id.inner(), context.settings())?;
151 let local_site_data = fetch_local_site_data(context.pool()).await?;
153 let community = page.community(context, request_counter).await?;
154 check_apub_id_valid_with_strictness(
160 verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
162 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
163 check_slurs_opt(&page.name, slur_regex)?;
165 verify_domains_match(page.creator()?.inner(), page.id.inner())?;
166 verify_is_public(&page.to, &page.cc)?;
170 #[tracing::instrument(skip_all)]
173 context: &LemmyContext,
174 request_counter: &mut i32,
175 ) -> Result<ApubPost, LemmyError> {
178 .dereference(context, local_instance(context).await, request_counter)
180 let community = page.community(context, request_counter).await?;
181 if community.posting_restricted_to_mods {
182 is_mod_or_admin(context.pool(), creator.id, community.id).await?;
192 .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
194 .ok_or_else(|| anyhow!("Object must have name or content"))?;
195 if name.chars().count() > MAX_TITLE_LENGTH {
196 name = name.chars().take(MAX_TITLE_LENGTH).collect();
199 let form = if !page.is_mod_action(context).await? {
200 let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
201 let url = if first_attachment.is_some() {
203 } else if page.kind == PageType::Video {
204 // we cant display videos directly, so insert a link to external video page
205 Some(page.id.inner().clone())
209 let (metadata_res, thumbnail_url) = if let Some(url) = &url {
210 fetch_site_data(context.client(), context.settings(), Some(url)).await
212 (None, page.image.map(|i| i.url.into()))
214 let (embed_title, embed_description, embed_video_url) = metadata_res
215 .map(|u| (u.title, u.description, u.embed_video_url))
216 .unwrap_or_default();
217 let local_site = LocalSite::read(context.pool()).await.ok();
218 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
220 let body_slurs_removed =
221 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
222 .map(|s| remove_slurs(&s, slur_regex));
223 let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
227 url: url.map(Into::into),
228 body: body_slurs_removed,
229 creator_id: creator.id,
230 community_id: community.id,
232 locked: page.comments_enabled.map(|e| !e),
233 published: page.published.map(|u| u.naive_local()),
234 updated: page.updated.map(|u| u.naive_local()),
235 deleted: Some(false),
236 nsfw: page.sensitive,
241 ap_id: Some(page.id.clone().into()),
244 featured_community: page.stickied,
245 featured_local: None,
248 // if is mod action, only update locked/stickied fields, nothing else
249 PostInsertForm::builder()
251 .creator_id(creator.id)
252 .community_id(community.id)
253 .ap_id(Some(page.id.clone().into()))
254 .locked(page.comments_enabled.map(|e| !e))
255 .featured_community(page.stickied)
256 .updated(page.updated.map(|u| u.naive_local()))
259 // read existing, local post if any (for generating mod log)
260 let old_post = ObjectId::<ApubPost>::new(page.id.clone())
261 .dereference_local(context)
264 let post = Post::create(context.pool(), &form).await?;
266 // write mod log entries for feature/lock
267 if Page::is_featured_changed(&old_post, &page.stickied) {
268 let form = ModFeaturePostForm {
269 mod_person_id: creator.id,
271 featured: post.featured_community,
272 is_featured_community: true,
274 ModFeaturePost::create(context.pool(), &form).await?;
276 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
277 let form = ModLockPostForm {
278 mod_person_id: creator.id,
280 locked: Some(post.locked),
282 ModLockPost::create(context.pool(), &form).await?;
294 community::tests::parse_lemmy_community,
295 person::tests::parse_lemmy_person,
299 protocol::tests::file_to_json_object,
301 use lemmy_db_schema::source::site::Site;
302 use serial_test::serial;
306 async fn test_parse_lemmy_post() {
307 let context = init_context().await;
308 let (person, site) = parse_lemmy_person(&context).await;
309 let community = parse_lemmy_community(&context).await;
311 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
312 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
313 let mut request_counter = 0;
314 ApubPost::verify(&json, &url, &context, &mut request_counter)
317 let post = ApubPost::from_apub(json, &context, &mut request_counter)
321 assert_eq!(post.ap_id, url.into());
322 assert_eq!(post.name, "Post title");
323 assert!(post.body.is_some());
324 assert_eq!(post.body.as_ref().unwrap().len(), 45);
325 assert!(!post.locked);
326 assert!(post.featured_community);
327 assert_eq!(request_counter, 0);
329 Post::delete(context.pool(), post.id).await.unwrap();
330 Person::delete(context.pool(), person.id).await.unwrap();
331 Community::delete(context.pool(), community.id)
334 Site::delete(context.pool(), site.id).await.unwrap();