]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
d252a8ea745c76e272042d1b44239c2606c8affe
[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   local_site_data_cached,
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     validation::check_url_scheme,
48   },
49 };
50 use std::ops::Deref;
51 use url::Url;
52
53 const MAX_TITLE_LENGTH: usize = 200;
54
55 #[derive(Clone, Debug)]
56 pub struct ApubPost(pub(crate) Post);
57
58 impl Deref for ApubPost {
59   type Target = Post;
60   fn deref(&self) -> &Self::Target {
61     &self.0
62   }
63 }
64
65 impl From<Post> for ApubPost {
66   fn from(p: Post) -> Self {
67     ApubPost(p)
68   }
69 }
70
71 #[async_trait::async_trait]
72 impl Object for ApubPost {
73   type DataType = LemmyContext;
74   type Kind = Page;
75   type Error = LemmyError;
76
77   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
78     None
79   }
80
81   #[tracing::instrument(skip_all)]
82   async fn read_from_id(
83     object_id: Url,
84     context: &Data<Self::DataType>,
85   ) -> Result<Option<Self>, LemmyError> {
86     Ok(
87       Post::read_from_apub_id(&mut context.pool(), object_id)
88         .await?
89         .map(Into::into),
90     )
91   }
92
93   #[tracing::instrument(skip_all)]
94   async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
95     if !self.deleted {
96       let form = PostUpdateForm::builder().deleted(Some(true)).build();
97       Post::update(&mut context.pool(), self.id, &form).await?;
98     }
99     Ok(())
100   }
101
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?;
110
111     let page = Page {
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()],
116       cc: vec![],
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),
125       language,
126       published: Some(convert_datetime(self.published)),
127       updated: self.updated.map(convert_datetime),
128       audience: Some(community.actor_id.into()),
129       in_reply_to: None,
130     };
131     Ok(page)
132   }
133
134   #[tracing::instrument(skip_all)]
135   async fn verify(
136     page: &Page,
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())?;
145     };
146
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?;
150
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)?;
154
155     verify_domains_match(page.creator()?.inner(), page.id.inner())?;
156     verify_is_public(&page.to, &page.cc)?;
157     Ok(())
158   }
159
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?;
166     }
167     let mut name = page
168       .name
169       .clone()
170       .or_else(|| {
171         page
172           .content
173           .clone()
174           .as_ref()
175           .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
176       })
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();
180     }
181
182     // read existing, local post if any (for generating mod log)
183     let old_post = page.id.dereference_local(context).await;
184
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() {
188         first_attachment
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())
192       } else {
193         None
194       };
195       check_url_scheme(&url)?;
196
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;
201
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() => {
207           fetch_site_data(
208             context.client(),
209             context.settings(),
210             Some(url),
211             include_image,
212           )
213           .await
214         }
215         _ => (None, None),
216       };
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()));
219
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);
224
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));
228       let language_id =
229         LanguageTag::to_language_id_single(page.language, &mut context.pool()).await?;
230
231       PostInsertForm {
232         name,
233         url: url.map(Into::into),
234         body: body_slurs_removed,
235         creator_id: creator.id,
236         community_id: community.id,
237         removed: None,
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,
243         embed_title,
244         embed_description,
245         embed_video_url,
246         thumbnail_url,
247         ap_id: Some(page.id.clone().into()),
248         local: Some(false),
249         language_id,
250         featured_community: None,
251         featured_local: None,
252       }
253     } else {
254       // if is mod action, only update locked/stickied fields, nothing else
255       PostInsertForm::builder()
256         .name(name)
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()))
262         .build()
263     };
264
265     let post = Post::create(&mut context.pool(), &form).await?;
266
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,
271         post_id: post.id,
272         locked: Some(post.locked),
273       };
274       ModLockPost::create(&mut context.pool(), &form).await?;
275     }
276
277     Ok(post.into())
278   }
279 }
280
281 #[cfg(test)]
282 mod tests {
283   use super::*;
284   use crate::{
285     objects::{
286       community::tests::parse_lemmy_community,
287       person::tests::parse_lemmy_person,
288       post::ApubPost,
289       tests::init_context,
290     },
291     protocol::tests::file_to_json_object,
292   };
293   use lemmy_db_schema::source::site::Site;
294   use serial_test::serial;
295
296   #[tokio::test]
297   #[serial]
298   async fn test_parse_lemmy_post() {
299     let context = init_context().await;
300     let (person, site) = parse_lemmy_person(&context).await;
301     let community = parse_lemmy_community(&context).await;
302
303     let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
304     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
305     ApubPost::verify(&json, &url, &context).await.unwrap();
306     let post = ApubPost::from_json(json, &context).await.unwrap();
307
308     assert_eq!(post.ap_id, url.into());
309     assert_eq!(post.name, "Post title");
310     assert!(post.body.is_some());
311     assert_eq!(post.body.as_ref().unwrap().len(), 45);
312     assert!(!post.locked);
313     assert!(!post.featured_community);
314     assert_eq!(context.request_count(), 0);
315
316     Post::delete(&mut context.pool(), post.id).await.unwrap();
317     Person::delete(&mut context.pool(), person.id)
318       .await
319       .unwrap();
320     Community::delete(&mut context.pool(), community.id)
321       .await
322       .unwrap();
323     Site::delete(&mut context.pool(), site.id).await.unwrap();
324   }
325 }