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 {
106 Post::update(&mut context.pool(), self.id, &form).await?;
111 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
112 #[tracing::instrument(skip_all)]
113 async fn into_json(self, context: &Data<Self::DataType>) -> Result<Page, LemmyError> {
114 let creator_id = self.creator_id;
115 let creator = Person::read(&mut context.pool(), creator_id).await?;
116 let community_id = self.community_id;
117 let community = Community::read(&mut context.pool(), community_id).await?;
118 let language = LanguageTag::new_single(self.language_id, &mut context.pool()).await?;
121 kind: PageType::Page,
122 id: self.ap_id.clone().into(),
123 attributed_to: AttributedTo::Lemmy(creator.actor_id.into()),
124 to: vec![community.actor_id.clone().into(), public()],
126 name: Some(self.name.clone()),
127 content: self.body.as_ref().map(|b| markdown_to_html(b)),
128 media_type: Some(MediaTypeMarkdownOrHtml::Html),
129 source: self.body.clone().map(Source::new),
130 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
131 image: self.thumbnail_url.clone().map(ImageObject::new),
132 comments_enabled: Some(!self.locked),
133 sensitive: Some(self.nsfw),
135 published: Some(convert_datetime(self.published)),
136 updated: self.updated.map(convert_datetime),
137 audience: Some(community.actor_id.into()),
143 #[tracing::instrument(skip_all)]
146 expected_domain: &Url,
147 context: &Data<Self::DataType>,
148 ) -> Result<(), LemmyError> {
149 // We can't verify the domain in case of mod action, because the mod may be on a different
150 // instance from the post author.
151 if !page.is_mod_action(context).await? {
152 verify_domains_match(page.id.inner(), expected_domain)?;
153 verify_is_remote_object(page.id.inner(), context.settings())?;
156 let community = page.community(context).await?;
157 check_apub_id_valid_with_strictness(page.id.inner(), community.local, context).await?;
158 verify_person_in_community(&page.creator()?, &community, context).await?;
160 let local_site_data = local_site_data_cached(&mut context.pool()).await?;
161 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
162 check_slurs_opt(&page.name, slur_regex)?;
164 verify_domains_match(page.creator()?.inner(), page.id.inner())?;
165 verify_is_public(&page.to, &page.cc)?;
169 #[tracing::instrument(skip_all)]
170 async fn from_json(page: Page, context: &Data<Self::DataType>) -> Result<ApubPost, LemmyError> {
171 let creator = page.creator()?.dereference(context).await?;
172 let community = page.community(context).await?;
173 if community.posting_restricted_to_mods {
174 is_mod_or_admin(&mut context.pool(), creator.id, community.id).await?;
184 .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
186 .ok_or_else(|| anyhow!("Object must have name or content"))?;
187 if name.chars().count() > MAX_TITLE_LENGTH {
188 name = name.chars().take(MAX_TITLE_LENGTH).collect();
191 // read existing, local post if any (for generating mod log)
192 let old_post = page.id.dereference_local(context).await;
194 let form = if !page.is_mod_action(context).await? {
195 let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
196 let url = if first_attachment.is_some() {
198 } else if page.kind == PageType::Video {
199 // we cant display videos directly, so insert a link to external video page
200 Some(page.id.inner().clone())
204 check_url_scheme(&url)?;
206 let local_site = LocalSite::read(&mut context.pool()).await.ok();
207 let allow_sensitive = local_site_opt_to_sensitive(&local_site);
208 let page_is_sensitive = page.sensitive.unwrap_or(false);
209 let include_image = allow_sensitive || !page_is_sensitive;
211 // Only fetch metadata if the post has a url and was not seen previously. We dont want to
212 // waste resources by fetching metadata for the same post multiple times.
213 // Additionally, only fetch image if content is not sensitive or is allowed on local site.
214 let (metadata_res, thumbnail) = match &url {
215 Some(url) if old_post.is_err() => {
226 // If no image was included with metadata, use post image instead when available.
227 let thumbnail_url = thumbnail.or_else(|| page.image.map(|i| i.url.into()));
229 let (embed_title, embed_description, embed_video_url) = metadata_res
230 .map(|u| (u.title, u.description, u.embed_video_url))
231 .unwrap_or_default();
232 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
234 let body_slurs_removed =
235 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
236 .map(|s| remove_slurs(&s, slur_regex));
238 LanguageTag::to_language_id_single(page.language, &mut context.pool()).await?;
240 let name = sanitize_html(&name);
241 let embed_title = sanitize_html_opt(&embed_title);
242 let embed_description = sanitize_html_opt(&embed_description);
246 url: url.map(Into::into),
247 body: body_slurs_removed,
248 creator_id: creator.id,
249 community_id: community.id,
251 locked: page.comments_enabled.map(|e| !e),
252 published: page.published.map(|u| u.naive_local()),
253 updated: page.updated.map(|u| u.naive_local()),
254 deleted: Some(false),
255 nsfw: page.sensitive,
260 ap_id: Some(page.id.clone().into()),
263 featured_community: None,
264 featured_local: None,
267 // if is mod action, only update locked/stickied fields, nothing else
268 PostInsertForm::builder()
270 .creator_id(creator.id)
271 .community_id(community.id)
272 .ap_id(Some(page.id.clone().into()))
273 .locked(page.comments_enabled.map(|e| !e))
274 .updated(page.updated.map(|u| u.naive_local()))
278 let post = Post::create(&mut context.pool(), &form).await?;
280 // write mod log entry for lock
281 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
282 let form = ModLockPostForm {
283 mod_person_id: creator.id,
285 locked: Some(post.locked),
287 ModLockPost::create(&mut context.pool(), &form).await?;
296 #![allow(clippy::unwrap_used)]
297 #![allow(clippy::indexing_slicing)]
302 community::tests::parse_lemmy_community,
303 person::tests::parse_lemmy_person,
307 protocol::tests::file_to_json_object,
309 use lemmy_db_schema::source::site::Site;
310 use serial_test::serial;
314 async fn test_parse_lemmy_post() {
315 let context = init_context().await;
316 let (person, site) = parse_lemmy_person(&context).await;
317 let community = parse_lemmy_community(&context).await;
319 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
320 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
321 ApubPost::verify(&json, &url, &context).await.unwrap();
322 let post = ApubPost::from_json(json, &context).await.unwrap();
324 assert_eq!(post.ap_id, url.into());
325 assert_eq!(post.name, "Post title");
326 assert!(post.body.is_some());
327 assert_eq!(post.body.as_ref().unwrap().len(), 45);
328 assert!(!post.locked);
329 assert!(!post.featured_community);
330 assert_eq!(context.request_count(), 0);
332 Post::delete(&mut context.pool(), post.id).await.unwrap();
333 Person::delete(&mut context.pool(), person.id)
336 Community::delete(&mut context.pool(), community.id)
339 Site::delete(&mut context.pool(), site.id).await.unwrap();