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,
28 utils::{is_mod_or_admin, local_site_opt_to_sensitive, local_site_opt_to_slur_regex},
30 use lemmy_db_schema::{
34 local_site::LocalSite,
35 moderator::{ModLockPost, ModLockPostForm},
37 post::{Post, PostInsertForm, PostUpdateForm},
44 markdown::markdown_to_html,
45 slurs::{check_slurs_opt, remove_slurs},
46 time::convert_datetime,
47 validation::check_url_scheme,
53 const MAX_TITLE_LENGTH: usize = 200;
55 #[derive(Clone, Debug)]
56 pub struct ApubPost(pub(crate) Post);
58 impl Deref for ApubPost {
60 fn deref(&self) -> &Self::Target {
65 impl From<Post> for ApubPost {
66 fn from(p: Post) -> Self {
71 #[async_trait::async_trait]
72 impl Object for ApubPost {
73 type DataType = LemmyContext;
75 type Error = LemmyError;
77 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
81 #[tracing::instrument(skip_all)]
82 async fn read_from_id(
84 context: &Data<Self::DataType>,
85 ) -> Result<Option<Self>, LemmyError> {
87 Post::read_from_apub_id(&mut context.pool(), object_id)
93 #[tracing::instrument(skip_all)]
94 async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
96 let form = PostUpdateForm::builder().deleted(Some(true)).build();
97 Post::update(&mut context.pool(), self.id, &form).await?;
102 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
103 #[tracing::instrument(skip_all)]
104 async fn into_json(self, context: &Data<Self::DataType>) -> Result<Page, LemmyError> {
105 let creator_id = self.creator_id;
106 let creator = Person::read(&mut context.pool(), creator_id).await?;
107 let community_id = self.community_id;
108 let community = Community::read(&mut context.pool(), community_id).await?;
109 let language = LanguageTag::new_single(self.language_id, &mut context.pool()).await?;
112 kind: PageType::Page,
113 id: self.ap_id.clone().into(),
114 attributed_to: AttributedTo::Lemmy(creator.actor_id.into()),
115 to: vec![community.actor_id.clone().into(), public()],
117 name: Some(self.name.clone()),
118 content: self.body.as_ref().map(|b| markdown_to_html(b)),
119 media_type: Some(MediaTypeMarkdownOrHtml::Html),
120 source: self.body.clone().map(Source::new),
121 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
122 image: self.thumbnail_url.clone().map(ImageObject::new),
123 comments_enabled: Some(!self.locked),
124 sensitive: Some(self.nsfw),
126 published: Some(convert_datetime(self.published)),
127 updated: self.updated.map(convert_datetime),
128 audience: Some(community.actor_id.into()),
134 #[tracing::instrument(skip_all)]
137 expected_domain: &Url,
138 context: &Data<Self::DataType>,
139 ) -> Result<(), LemmyError> {
140 // We can't verify the domain in case of mod action, because the mod may be on a different
141 // instance from the post author.
142 if !page.is_mod_action(context).await? {
143 verify_domains_match(page.id.inner(), expected_domain)?;
144 verify_is_remote_object(page.id.inner(), context.settings())?;
147 let community = page.community(context).await?;
148 check_apub_id_valid_with_strictness(page.id.inner(), community.local, context).await?;
149 verify_person_in_community(&page.creator()?, &community, context).await?;
151 let local_site_data = local_site_data_cached(&mut context.pool()).await?;
152 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
153 check_slurs_opt(&page.name, slur_regex)?;
155 verify_domains_match(page.creator()?.inner(), page.id.inner())?;
156 verify_is_public(&page.to, &page.cc)?;
160 #[tracing::instrument(skip_all)]
161 async fn from_json(page: Page, context: &Data<Self::DataType>) -> Result<ApubPost, LemmyError> {
162 let creator = page.creator()?.dereference(context).await?;
163 let community = page.community(context).await?;
164 if community.posting_restricted_to_mods {
165 is_mod_or_admin(&mut context.pool(), creator.id, community.id).await?;
175 .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
177 .ok_or_else(|| anyhow!("Object must have name or content"))?;
178 if name.chars().count() > MAX_TITLE_LENGTH {
179 name = name.chars().take(MAX_TITLE_LENGTH).collect();
182 // read existing, local post if any (for generating mod log)
183 let old_post = page.id.dereference_local(context).await;
185 let form = if !page.is_mod_action(context).await? {
186 let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
187 let url = if first_attachment.is_some() {
189 } else if page.kind == PageType::Video {
190 // we cant display videos directly, so insert a link to external video page
191 Some(page.id.inner().clone())
195 check_url_scheme(&url)?;
197 let local_site = LocalSite::read(&mut context.pool()).await.ok();
198 let allow_sensitive = local_site_opt_to_sensitive(&local_site);
199 let page_is_sensitive = page.sensitive.unwrap_or(false);
200 let include_image = allow_sensitive || !page_is_sensitive;
202 // Only fetch metadata if the post has a url and was not seen previously. We dont want to
203 // waste resources by fetching metadata for the same post multiple times.
204 // Additionally, only fetch image if content is not sensitive or is allowed on local site.
205 let (metadata_res, thumbnail) = match &url {
206 Some(url) if old_post.is_err() => {
217 // If no image was included with metadata, use post image instead when available.
218 let thumbnail_url = thumbnail.or_else(|| page.image.map(|i| i.url.into()));
220 let (embed_title, embed_description, embed_video_url) = metadata_res
221 .map(|u| (u.title, u.description, u.embed_video_url))
222 .unwrap_or_default();
223 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
225 let body_slurs_removed =
226 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
227 .map(|s| remove_slurs(&s, slur_regex));
229 LanguageTag::to_language_id_single(page.language, &mut context.pool()).await?;
233 url: url.map(Into::into),
234 body: body_slurs_removed,
235 creator_id: creator.id,
236 community_id: community.id,
238 locked: page.comments_enabled.map(|e| !e),
239 published: page.published.map(|u| u.naive_local()),
240 updated: page.updated.map(|u| u.naive_local()),
241 deleted: Some(false),
242 nsfw: page.sensitive,
247 ap_id: Some(page.id.clone().into()),
250 featured_community: None,
251 featured_local: None,
254 // if is mod action, only update locked/stickied fields, nothing else
255 PostInsertForm::builder()
257 .creator_id(creator.id)
258 .community_id(community.id)
259 .ap_id(Some(page.id.clone().into()))
260 .locked(page.comments_enabled.map(|e| !e))
261 .updated(page.updated.map(|u| u.naive_local()))
265 let post = Post::create(&mut context.pool(), &form).await?;
267 // write mod log entry for lock
268 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
269 let form = ModLockPostForm {
270 mod_person_id: creator.id,
272 locked: Some(post.locked),
274 ModLockPost::create(&mut context.pool(), &form).await?;
283 #![allow(clippy::unwrap_used)]
284 #![allow(clippy::indexing_slicing)]
289 community::tests::parse_lemmy_community,
290 person::tests::parse_lemmy_person,
294 protocol::tests::file_to_json_object,
296 use lemmy_db_schema::source::site::Site;
297 use serial_test::serial;
301 async fn test_parse_lemmy_post() {
302 let context = init_context().await;
303 let (person, site) = parse_lemmy_person(&context).await;
304 let community = parse_lemmy_community(&context).await;
306 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
307 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
308 ApubPost::verify(&json, &url, &context).await.unwrap();
309 let post = ApubPost::from_json(json, &context).await.unwrap();
311 assert_eq!(post.ap_id, url.into());
312 assert_eq!(post.name, "Post title");
313 assert!(post.body.is_some());
314 assert_eq!(post.body.as_ref().unwrap().len(), 45);
315 assert!(!post.locked);
316 assert!(!post.featured_community);
317 assert_eq!(context.request_count(), 0);
319 Post::delete(&mut context.pool(), post.id).await.unwrap();
320 Person::delete(&mut context.pool(), person.id)
323 Community::delete(&mut context.pool(), community.id)
326 Site::delete(&mut context.pool(), site.id).await.unwrap();