]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Convert HTML from titles into markdown (#2709)
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::{verify_is_public, verify_person_in_community},
3   check_apub_id_valid_with_strictness,
4   fetch_local_site_data,
5   local_instance,
6   objects::{read_from_string_or_source_opt, verify_is_remote_object},
7   protocol::{
8     objects::{
9       page::{Attachment, AttributedTo, Page, PageType},
10       LanguageTag,
11     },
12     ImageObject,
13     InCommunity,
14     Source,
15   },
16 };
17 use activitypub_federation::{
18   core::object_id::ObjectId,
19   deser::values::MediaTypeMarkdownOrHtml,
20   traits::ApubObject,
21   utils::verify_domains_match,
22 };
23 use activitystreams_kinds::public;
24 use anyhow::anyhow;
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},
31 };
32 use lemmy_db_schema::{
33   self,
34   source::{
35     community::Community,
36     local_site::LocalSite,
37     moderator::{ModFeaturePost, ModFeaturePostForm, ModLockPost, ModLockPostForm},
38     person::Person,
39     post::{Post, PostInsertForm, PostUpdateForm},
40   },
41   traits::Crud,
42 };
43 use lemmy_utils::{
44   error::LemmyError,
45   utils::{check_slurs_opt, convert_datetime, markdown_to_html, remove_slurs},
46 };
47 use std::ops::Deref;
48 use url::Url;
49
50 const MAX_TITLE_LENGTH: usize = 100;
51
52 #[derive(Clone, Debug)]
53 pub struct ApubPost(pub(crate) Post);
54
55 impl Deref for ApubPost {
56   type Target = Post;
57   fn deref(&self) -> &Self::Target {
58     &self.0
59   }
60 }
61
62 impl From<Post> for ApubPost {
63   fn from(p: Post) -> Self {
64     ApubPost(p)
65   }
66 }
67
68 #[async_trait::async_trait(?Send)]
69 impl ApubObject for ApubPost {
70   type DataType = LemmyContext;
71   type ApubType = Page;
72   type DbType = Post;
73   type Error = LemmyError;
74
75   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
76     None
77   }
78
79   #[tracing::instrument(skip_all)]
80   async fn read_from_apub_id(
81     object_id: Url,
82     context: &LemmyContext,
83   ) -> Result<Option<Self>, LemmyError> {
84     Ok(
85       Post::read_from_apub_id(context.pool(), object_id)
86         .await?
87         .map(Into::into),
88     )
89   }
90
91   #[tracing::instrument(skip_all)]
92   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
93     if !self.deleted {
94       let form = PostUpdateForm::builder().deleted(Some(true)).build();
95       Post::update(context.pool(), self.id, &form).await?;
96     }
97     Ok(())
98   }
99
100   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
101   #[tracing::instrument(skip_all)]
102   async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
103     let creator_id = self.creator_id;
104     let creator = Person::read(context.pool(), creator_id).await?;
105     let community_id = self.community_id;
106     let community = Community::read(context.pool(), community_id).await?;
107     let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
108
109     let page = Page {
110       kind: PageType::Page,
111       id: ObjectId::new(self.ap_id.clone()),
112       attributed_to: AttributedTo::Lemmy(ObjectId::new(creator.actor_id)),
113       to: vec![community.actor_id.clone().into(), public()],
114       cc: vec![],
115       name: Some(self.name.clone()),
116       content: self.body.as_ref().map(|b| markdown_to_html(b)),
117       media_type: Some(MediaTypeMarkdownOrHtml::Html),
118       source: self.body.clone().map(Source::new),
119       attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
120       image: self.thumbnail_url.clone().map(ImageObject::new),
121       comments_enabled: Some(!self.locked),
122       sensitive: Some(self.nsfw),
123       stickied: Some(self.featured_community),
124       language,
125       published: Some(convert_datetime(self.published)),
126       updated: self.updated.map(convert_datetime),
127       audience: Some(ObjectId::new(community.actor_id)),
128       in_reply_to: None,
129     };
130     Ok(page)
131   }
132
133   #[tracing::instrument(skip_all)]
134   async fn verify(
135     page: &Page,
136     expected_domain: &Url,
137     context: &LemmyContext,
138     request_counter: &mut i32,
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())?;
145     };
146
147     let local_site_data = fetch_local_site_data(context.pool()).await?;
148
149     let community = page.community(context, request_counter).await?;
150     check_apub_id_valid_with_strictness(
151       page.id.inner(),
152       community.local,
153       &local_site_data,
154       context.settings(),
155     )?;
156     verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
157
158     let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
159     check_slurs_opt(&page.name, slur_regex)?;
160
161     verify_domains_match(page.creator()?.inner(), page.id.inner())?;
162     verify_is_public(&page.to, &page.cc)?;
163     Ok(())
164   }
165
166   #[tracing::instrument(skip_all)]
167   async fn from_apub(
168     page: Page,
169     context: &LemmyContext,
170     request_counter: &mut i32,
171   ) -> Result<ApubPost, LemmyError> {
172     let creator = page
173       .creator()?
174       .dereference(context, local_instance(context).await, request_counter)
175       .await?;
176     let community = page.community(context, request_counter).await?;
177     if community.posting_restricted_to_mods {
178       is_mod_or_admin(context.pool(), creator.id, community.id).await?;
179     }
180     let mut name = page
181       .name
182       .clone()
183       .or_else(|| {
184         page
185           .content
186           .clone()
187           .as_ref()
188           .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
189       })
190       .ok_or_else(|| anyhow!("Object must have name or content"))?;
191     if name.chars().count() > MAX_TITLE_LENGTH {
192       name = name.chars().take(MAX_TITLE_LENGTH).collect();
193     }
194
195     let form = if !page.is_mod_action(context).await? {
196       let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
197       let url = if first_attachment.is_some() {
198         first_attachment
199       } else if page.kind == PageType::Video {
200         // we cant display videos directly, so insert a link to external video page
201         Some(page.id.inner().clone())
202       } else {
203         None
204       };
205       let (metadata_res, thumbnail_url) = if let Some(url) = &url {
206         fetch_site_data(context.client(), context.settings(), Some(url)).await
207       } else {
208         (None, page.image.map(|i| i.url.into()))
209       };
210       let (embed_title, embed_description, embed_video_url) = metadata_res
211         .map(|u| (u.title, u.description, u.embed_video_url))
212         .unwrap_or_default();
213       let local_site = LocalSite::read(context.pool()).await.ok();
214       let slur_regex = &local_site_opt_to_slur_regex(&local_site);
215
216       let body_slurs_removed =
217         read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
218           .map(|s| remove_slurs(&s, slur_regex));
219       let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
220
221       PostInsertForm {
222         name,
223         url: url.map(Into::into),
224         body: body_slurs_removed,
225         creator_id: creator.id,
226         community_id: community.id,
227         removed: None,
228         locked: page.comments_enabled.map(|e| !e),
229         published: page.published.map(|u| u.naive_local()),
230         updated: page.updated.map(|u| u.naive_local()),
231         deleted: Some(false),
232         nsfw: page.sensitive,
233         embed_title,
234         embed_description,
235         embed_video_url,
236         thumbnail_url,
237         ap_id: Some(page.id.clone().into()),
238         local: Some(false),
239         language_id,
240         featured_community: page.stickied,
241         featured_local: None,
242       }
243     } else {
244       // if is mod action, only update locked/stickied fields, nothing else
245       PostInsertForm::builder()
246         .name(name)
247         .creator_id(creator.id)
248         .community_id(community.id)
249         .ap_id(Some(page.id.clone().into()))
250         .locked(page.comments_enabled.map(|e| !e))
251         .featured_community(page.stickied)
252         .updated(page.updated.map(|u| u.naive_local()))
253         .build()
254     };
255     // read existing, local post if any (for generating mod log)
256     let old_post = ObjectId::<ApubPost>::new(page.id.clone())
257       .dereference_local(context)
258       .await;
259
260     let post = Post::create(context.pool(), &form).await?;
261
262     // write mod log entries for feature/lock
263     if Page::is_featured_changed(&old_post, &page.stickied) {
264       let form = ModFeaturePostForm {
265         mod_person_id: creator.id,
266         post_id: post.id,
267         featured: post.featured_community,
268         is_featured_community: true,
269       };
270       ModFeaturePost::create(context.pool(), &form).await?;
271     }
272     if Page::is_locked_changed(&old_post, &page.comments_enabled) {
273       let form = ModLockPostForm {
274         mod_person_id: creator.id,
275         post_id: post.id,
276         locked: Some(post.locked),
277       };
278       ModLockPost::create(context.pool(), &form).await?;
279     }
280
281     Ok(post.into())
282   }
283 }
284
285 #[cfg(test)]
286 mod tests {
287   use super::*;
288   use crate::{
289     objects::{
290       community::tests::parse_lemmy_community,
291       person::tests::parse_lemmy_person,
292       post::ApubPost,
293       tests::init_context,
294     },
295     protocol::tests::file_to_json_object,
296   };
297   use lemmy_db_schema::source::site::Site;
298   use serial_test::serial;
299
300   #[actix_rt::test]
301   #[serial]
302   async fn test_parse_lemmy_post() {
303     let context = init_context().await;
304     let (person, site) = parse_lemmy_person(&context).await;
305     let community = parse_lemmy_community(&context).await;
306
307     let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
308     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
309     let mut request_counter = 0;
310     ApubPost::verify(&json, &url, &context, &mut request_counter)
311       .await
312       .unwrap();
313     let post = ApubPost::from_apub(json, &context, &mut request_counter)
314       .await
315       .unwrap();
316
317     assert_eq!(post.ap_id, url.into());
318     assert_eq!(post.name, "Post title");
319     assert!(post.body.is_some());
320     assert_eq!(post.body.as_ref().unwrap().len(), 45);
321     assert!(!post.locked);
322     assert!(post.featured_community);
323     assert_eq!(request_counter, 0);
324
325     Post::delete(context.pool(), post.id).await.unwrap();
326     Person::delete(context.pool(), person.id).await.unwrap();
327     Community::delete(context.pool(), community.id)
328       .await
329       .unwrap();
330     Site::delete(context.pool(), site.id).await.unwrap();
331   }
332 }