2 activities::{verify_is_public, verify_person_in_community},
3 check_apub_id_valid_with_strictness,
4 local_site_data_cached,
5 objects::{read_from_string_or_source_opt, verify_is_remote_object},
8 page::{Attachment, AttributedTo, Page, PageType},
16 use activitypub_federation::{
19 protocol::{values::MediaTypeMarkdownOrHtml, verification::verify_domains_match},
23 use chrono::NaiveDateTime;
24 use html2md::parse_html;
25 use lemmy_api_common::{
26 context::LemmyContext,
27 request::fetch_site_data,
30 local_site_opt_to_sensitive,
31 local_site_opt_to_slur_regex,
36 use lemmy_db_schema::{
40 local_site::LocalSite,
41 moderator::{ModLockPost, ModLockPostForm},
43 post::{Post, PostInsertForm, PostUpdateForm},
50 markdown::markdown_to_html,
51 slurs::{check_slurs_opt, remove_slurs},
52 time::convert_datetime,
53 validation::check_url_scheme,
59 const MAX_TITLE_LENGTH: usize = 200;
61 #[derive(Clone, Debug)]
62 pub struct ApubPost(pub(crate) Post);
64 impl Deref for ApubPost {
66 fn deref(&self) -> &Self::Target {
71 impl From<Post> for ApubPost {
72 fn from(p: Post) -> Self {
77 #[async_trait::async_trait]
78 impl Object for ApubPost {
79 type DataType = LemmyContext;
81 type Error = LemmyError;
83 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
87 #[tracing::instrument(skip_all)]
88 async fn read_from_id(
90 context: &Data<Self::DataType>,
91 ) -> Result<Option<Self>, LemmyError> {
93 Post::read_from_apub_id(&mut context.pool(), object_id)
99 #[tracing::instrument(skip_all)]
100 async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
102 let form = PostUpdateForm::builder().deleted(Some(true)).build();
103 Post::update(&mut context.pool(), self.id, &form).await?;
108 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
109 #[tracing::instrument(skip_all)]
110 async fn into_json(self, context: &Data<Self::DataType>) -> Result<Page, LemmyError> {
111 let creator_id = self.creator_id;
112 let creator = Person::read(&mut context.pool(), creator_id).await?;
113 let community_id = self.community_id;
114 let community = Community::read(&mut context.pool(), community_id).await?;
115 let language = LanguageTag::new_single(self.language_id, &mut context.pool()).await?;
118 kind: PageType::Page,
119 id: self.ap_id.clone().into(),
120 attributed_to: AttributedTo::Lemmy(creator.actor_id.into()),
121 to: vec![community.actor_id.clone().into(), public()],
123 name: Some(self.name.clone()),
124 content: self.body.as_ref().map(|b| markdown_to_html(b)),
125 media_type: Some(MediaTypeMarkdownOrHtml::Html),
126 source: self.body.clone().map(Source::new),
127 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
128 image: self.thumbnail_url.clone().map(ImageObject::new),
129 comments_enabled: Some(!self.locked),
130 sensitive: Some(self.nsfw),
132 published: Some(convert_datetime(self.published)),
133 updated: self.updated.map(convert_datetime),
134 audience: Some(community.actor_id.into()),
140 #[tracing::instrument(skip_all)]
143 expected_domain: &Url,
144 context: &Data<Self::DataType>,
145 ) -> Result<(), LemmyError> {
146 // We can't verify the domain in case of mod action, because the mod may be on a different
147 // instance from the post author.
148 if !page.is_mod_action(context).await? {
149 verify_domains_match(page.id.inner(), expected_domain)?;
150 verify_is_remote_object(page.id.inner(), context.settings())?;
153 let community = page.community(context).await?;
154 check_apub_id_valid_with_strictness(page.id.inner(), community.local, context).await?;
155 verify_person_in_community(&page.creator()?, &community, context).await?;
157 let local_site_data = local_site_data_cached(&mut context.pool()).await?;
158 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
159 check_slurs_opt(&page.name, slur_regex)?;
161 verify_domains_match(page.creator()?.inner(), page.id.inner())?;
162 verify_is_public(&page.to, &page.cc)?;
166 #[tracing::instrument(skip_all)]
167 async fn from_json(page: Page, context: &Data<Self::DataType>) -> Result<ApubPost, LemmyError> {
168 let creator = page.creator()?.dereference(context).await?;
169 let community = page.community(context).await?;
170 if community.posting_restricted_to_mods {
171 is_mod_or_admin(&mut context.pool(), creator.id, community.id).await?;
181 .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
183 .ok_or_else(|| anyhow!("Object must have name or content"))?;
184 if name.chars().count() > MAX_TITLE_LENGTH {
185 name = name.chars().take(MAX_TITLE_LENGTH).collect();
188 // read existing, local post if any (for generating mod log)
189 let old_post = page.id.dereference_local(context).await;
191 let form = if !page.is_mod_action(context).await? {
192 let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
193 let url = if first_attachment.is_some() {
195 } else if page.kind == PageType::Video {
196 // we cant display videos directly, so insert a link to external video page
197 Some(page.id.inner().clone())
201 check_url_scheme(&url)?;
203 let local_site = LocalSite::read(&mut context.pool()).await.ok();
204 let allow_sensitive = local_site_opt_to_sensitive(&local_site);
205 let page_is_sensitive = page.sensitive.unwrap_or(false);
206 let include_image = allow_sensitive || !page_is_sensitive;
208 // Only fetch metadata if the post has a url and was not seen previously. We dont want to
209 // waste resources by fetching metadata for the same post multiple times.
210 // Additionally, only fetch image if content is not sensitive or is allowed on local site.
211 let (metadata_res, thumbnail) = match &url {
212 Some(url) if old_post.is_err() => {
223 // If no image was included with metadata, use post image instead when available.
224 let thumbnail_url = thumbnail.or_else(|| page.image.map(|i| i.url.into()));
226 let (embed_title, embed_description, embed_video_url) = metadata_res
227 .map(|u| (u.title, u.description, u.embed_video_url))
228 .unwrap_or_default();
229 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
231 let body_slurs_removed =
232 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
233 .map(|s| remove_slurs(&s, slur_regex));
235 LanguageTag::to_language_id_single(page.language, &mut context.pool()).await?;
237 let name = sanitize_html(&name);
238 let embed_title = sanitize_html_opt(&embed_title);
239 let embed_description = sanitize_html_opt(&embed_description);
243 url: url.map(Into::into),
244 body: body_slurs_removed,
245 creator_id: creator.id,
246 community_id: community.id,
248 locked: page.comments_enabled.map(|e| !e),
249 published: page.published.map(|u| u.naive_local()),
250 updated: page.updated.map(|u| u.naive_local()),
251 deleted: Some(false),
252 nsfw: page.sensitive,
257 ap_id: Some(page.id.clone().into()),
260 featured_community: None,
261 featured_local: None,
264 // if is mod action, only update locked/stickied fields, nothing else
265 PostInsertForm::builder()
267 .creator_id(creator.id)
268 .community_id(community.id)
269 .ap_id(Some(page.id.clone().into()))
270 .locked(page.comments_enabled.map(|e| !e))
271 .updated(page.updated.map(|u| u.naive_local()))
275 let post = Post::create(&mut context.pool(), &form).await?;
277 // write mod log entry for lock
278 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
279 let form = ModLockPostForm {
280 mod_person_id: creator.id,
282 locked: Some(post.locked),
284 ModLockPost::create(&mut context.pool(), &form).await?;
293 #![allow(clippy::unwrap_used)]
294 #![allow(clippy::indexing_slicing)]
299 community::tests::parse_lemmy_community,
300 person::tests::parse_lemmy_person,
304 protocol::tests::file_to_json_object,
306 use lemmy_db_schema::source::site::Site;
307 use serial_test::serial;
311 async fn test_parse_lemmy_post() {
312 let context = init_context().await;
313 let (person, site) = parse_lemmy_person(&context).await;
314 let community = parse_lemmy_community(&context).await;
316 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
317 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
318 ApubPost::verify(&json, &url, &context).await.unwrap();
319 let post = ApubPost::from_json(json, &context).await.unwrap();
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!(context.request_count(), 0);
329 Post::delete(&mut context.pool(), post.id).await.unwrap();
330 Person::delete(&mut context.pool(), person.id)
333 Community::delete(&mut context.pool(), community.id)
336 Site::delete(&mut context.pool(), site.id).await.unwrap();