]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
7878fcf12215a22242021a7e1e658a1d28e7e18e
[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   objects::{read_from_string_or_source_opt, verify_is_remote_object},
6   protocol::{
7     objects::{
8       page::{Attachment, AttributedTo, Page, PageType},
9       LanguageTag,
10     },
11     ImageObject,
12     InCommunity,
13     Source,
14   },
15 };
16 use activitypub_federation::{
17   config::Data,
18   kinds::public,
19   protocol::{values::MediaTypeMarkdownOrHtml, verification::verify_domains_match},
20   traits::Object,
21 };
22 use anyhow::anyhow;
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},
29 };
30 use lemmy_db_schema::{
31   self,
32   source::{
33     community::Community,
34     local_site::LocalSite,
35     moderator::{ModLockPost, ModLockPostForm},
36     person::Person,
37     post::{Post, PostInsertForm, PostUpdateForm},
38   },
39   traits::Crud,
40 };
41 use lemmy_utils::{
42   error::LemmyError,
43   utils::{
44     markdown::markdown_to_html,
45     slurs::{check_slurs_opt, remove_slurs},
46     time::convert_datetime,
47   },
48 };
49 use std::ops::Deref;
50 use url::Url;
51
52 const MAX_TITLE_LENGTH: usize = 200;
53
54 #[derive(Clone, Debug)]
55 pub struct ApubPost(pub(crate) Post);
56
57 impl Deref for ApubPost {
58   type Target = Post;
59   fn deref(&self) -> &Self::Target {
60     &self.0
61   }
62 }
63
64 impl From<Post> for ApubPost {
65   fn from(p: Post) -> Self {
66     ApubPost(p)
67   }
68 }
69
70 #[async_trait::async_trait]
71 impl Object for ApubPost {
72   type DataType = LemmyContext;
73   type Kind = Page;
74   type Error = LemmyError;
75
76   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
77     None
78   }
79
80   #[tracing::instrument(skip_all)]
81   async fn read_from_id(
82     object_id: Url,
83     context: &Data<Self::DataType>,
84   ) -> Result<Option<Self>, LemmyError> {
85     Ok(
86       Post::read_from_apub_id(context.pool(), object_id)
87         .await?
88         .map(Into::into),
89     )
90   }
91
92   #[tracing::instrument(skip_all)]
93   async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
94     if !self.deleted {
95       let form = PostUpdateForm::builder().deleted(Some(true)).build();
96       Post::update(context.pool(), self.id, &form).await?;
97     }
98     Ok(())
99   }
100
101   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
102   #[tracing::instrument(skip_all)]
103   async fn into_json(self, context: &Data<Self::DataType>) -> Result<Page, LemmyError> {
104     let creator_id = self.creator_id;
105     let creator = Person::read(context.pool(), creator_id).await?;
106     let community_id = self.community_id;
107     let community = Community::read(context.pool(), community_id).await?;
108     let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
109
110     let page = Page {
111       kind: PageType::Page,
112       id: self.ap_id.clone().into(),
113       attributed_to: AttributedTo::Lemmy(creator.actor_id.into()),
114       to: vec![community.actor_id.clone().into(), public()],
115       cc: vec![],
116       name: Some(self.name.clone()),
117       content: self.body.as_ref().map(|b| markdown_to_html(b)),
118       media_type: Some(MediaTypeMarkdownOrHtml::Html),
119       source: self.body.clone().map(Source::new),
120       attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
121       image: self.thumbnail_url.clone().map(ImageObject::new),
122       comments_enabled: Some(!self.locked),
123       sensitive: Some(self.nsfw),
124       language,
125       published: Some(convert_datetime(self.published)),
126       updated: self.updated.map(convert_datetime),
127       audience: Some(community.actor_id.into()),
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: &Data<Self::DataType>,
138   ) -> Result<(), LemmyError> {
139     // We can't verify the domain in case of mod action, because the mod may be on a different
140     // instance from the post author.
141     if !page.is_mod_action(context).await? {
142       verify_domains_match(page.id.inner(), expected_domain)?;
143       verify_is_remote_object(page.id.inner(), context.settings())?;
144     };
145
146     let local_site_data = fetch_local_site_data(context.pool()).await?;
147
148     let community = page.community(context).await?;
149     check_apub_id_valid_with_strictness(
150       page.id.inner(),
151       community.local,
152       &local_site_data,
153       context.settings(),
154     )?;
155     verify_person_in_community(&page.creator()?, &community, context).await?;
156
157     let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
158     check_slurs_opt(&page.name, slur_regex)?;
159
160     verify_domains_match(page.creator()?.inner(), page.id.inner())?;
161     verify_is_public(&page.to, &page.cc)?;
162     Ok(())
163   }
164
165   #[tracing::instrument(skip_all)]
166   async fn from_json(page: Page, context: &Data<Self::DataType>) -> Result<ApubPost, LemmyError> {
167     let creator = page.creator()?.dereference(context).await?;
168     let community = page.community(context).await?;
169     if community.posting_restricted_to_mods {
170       is_mod_or_admin(context.pool(), creator.id, community.id).await?;
171     }
172     let mut name = page
173       .name
174       .clone()
175       .or_else(|| {
176         page
177           .content
178           .clone()
179           .as_ref()
180           .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
181       })
182       .ok_or_else(|| anyhow!("Object must have name or content"))?;
183     if name.chars().count() > MAX_TITLE_LENGTH {
184       name = name.chars().take(MAX_TITLE_LENGTH).collect();
185     }
186
187     // read existing, local post if any (for generating mod log)
188     let old_post = page.id.dereference_local(context).await;
189
190     let form = if !page.is_mod_action(context).await? {
191       let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
192       let url = if first_attachment.is_some() {
193         first_attachment
194       } else if page.kind == PageType::Video {
195         // we cant display videos directly, so insert a link to external video page
196         Some(page.id.inner().clone())
197       } else {
198         None
199       };
200
201       let local_site = LocalSite::read(context.pool()).await.ok();
202       let allow_sensitive = local_site_opt_to_sensitive(&local_site);
203       let page_is_sensitive = page.sensitive.unwrap_or(false);
204       let include_image = allow_sensitive || !page_is_sensitive;
205
206       // Only fetch metadata if the post has a url and was not seen previously. We dont want to
207       // waste resources by fetching metadata for the same post multiple times.
208       // Additionally, only fetch image if content is not sensitive or is allowed on local site.
209       let (metadata_res, thumbnail) = match &url {
210         Some(url) if old_post.is_err() => {
211           fetch_site_data(
212             context.client(),
213             context.settings(),
214             Some(url),
215             include_image,
216           )
217           .await
218         }
219         _ => (None, None),
220       };
221       // If no image was included with metadata, use post image instead when available.
222       let thumbnail_url = thumbnail.or_else(|| page.image.map(|i| i.url.into()));
223
224       let (embed_title, embed_description, embed_video_url) = metadata_res
225         .map(|u| (u.title, u.description, u.embed_video_url))
226         .unwrap_or_default();
227       let slur_regex = &local_site_opt_to_slur_regex(&local_site);
228
229       let body_slurs_removed =
230         read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
231           .map(|s| remove_slurs(&s, slur_regex));
232       let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
233
234       PostInsertForm {
235         name,
236         url: url.map(Into::into),
237         body: body_slurs_removed,
238         creator_id: creator.id,
239         community_id: community.id,
240         removed: None,
241         locked: page.comments_enabled.map(|e| !e),
242         published: page.published.map(|u| u.naive_local()),
243         updated: page.updated.map(|u| u.naive_local()),
244         deleted: Some(false),
245         nsfw: page.sensitive,
246         embed_title,
247         embed_description,
248         embed_video_url,
249         thumbnail_url,
250         ap_id: Some(page.id.clone().into()),
251         local: Some(false),
252         language_id,
253         featured_community: None,
254         featured_local: None,
255       }
256     } else {
257       // if is mod action, only update locked/stickied fields, nothing else
258       PostInsertForm::builder()
259         .name(name)
260         .creator_id(creator.id)
261         .community_id(community.id)
262         .ap_id(Some(page.id.clone().into()))
263         .locked(page.comments_enabled.map(|e| !e))
264         .updated(page.updated.map(|u| u.naive_local()))
265         .build()
266     };
267
268     let post = Post::create(context.pool(), &form).await?;
269
270     // write mod log entry for lock
271     if Page::is_locked_changed(&old_post, &page.comments_enabled) {
272       let form = ModLockPostForm {
273         mod_person_id: creator.id,
274         post_id: post.id,
275         locked: Some(post.locked),
276       };
277       ModLockPost::create(context.pool(), &form).await?;
278     }
279
280     Ok(post.into())
281   }
282 }
283
284 #[cfg(test)]
285 mod tests {
286   use super::*;
287   use crate::{
288     objects::{
289       community::tests::parse_lemmy_community,
290       person::tests::parse_lemmy_person,
291       post::ApubPost,
292       tests::init_context,
293     },
294     protocol::tests::file_to_json_object,
295   };
296   use lemmy_db_schema::source::site::Site;
297   use serial_test::serial;
298
299   #[tokio::test]
300   #[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;
305
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();
310
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);
318
319     Post::delete(context.pool(), post.id).await.unwrap();
320     Person::delete(context.pool(), person.id).await.unwrap();
321     Community::delete(context.pool(), community.id)
322       .await
323       .unwrap();
324     Site::delete(context.pool(), site.id).await.unwrap();
325   }
326 }