]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
add enable_federated_downvotes site option
[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::{
29     is_mod_or_admin,
30     local_site_opt_to_sensitive,
31     local_site_opt_to_slur_regex,
32     sanitize_html,
33     sanitize_html_opt,
34   },
35 };
36 use lemmy_db_schema::{
37   self,
38   source::{
39     community::Community,
40     local_site::LocalSite,
41     moderator::{ModLockPost, ModLockPostForm},
42     person::Person,
43     post::{Post, PostInsertForm, PostUpdateForm},
44   },
45   traits::Crud,
46 };
47 use lemmy_utils::{
48   error::LemmyError,
49   utils::{
50     markdown::markdown_to_html,
51     slurs::{check_slurs_opt, remove_slurs},
52     time::convert_datetime,
53     validation::check_url_scheme,
54   },
55 };
56 use std::ops::Deref;
57 use url::Url;
58
59 const MAX_TITLE_LENGTH: usize = 200;
60
61 #[derive(Clone, Debug)]
62 pub struct ApubPost(pub(crate) Post);
63
64 impl Deref for ApubPost {
65   type Target = Post;
66   fn deref(&self) -> &Self::Target {
67     &self.0
68   }
69 }
70
71 impl From<Post> for ApubPost {
72   fn from(p: Post) -> Self {
73     ApubPost(p)
74   }
75 }
76
77 #[async_trait::async_trait]
78 impl Object for ApubPost {
79   type DataType = LemmyContext;
80   type Kind = Page;
81   type Error = LemmyError;
82
83   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
84     None
85   }
86
87   #[tracing::instrument(skip_all)]
88   async fn read_from_id(
89     object_id: Url,
90     context: &Data<Self::DataType>,
91   ) -> Result<Option<Self>, LemmyError> {
92     Ok(
93       Post::read_from_apub_id(&mut context.pool(), object_id)
94         .await?
95         .map(Into::into),
96     )
97   }
98
99   #[tracing::instrument(skip_all)]
100   async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
101     if !self.deleted {
102       let form = PostUpdateForm {
103         deleted: Some(true),
104         ..Default::default()
105       };
106       Post::update(&mut context.pool(), self.id, &form).await?;
107     }
108     Ok(())
109   }
110
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?;
119
120     let page = Page {
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()],
125       cc: vec![],
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),
134       language,
135       published: Some(convert_datetime(self.published)),
136       updated: self.updated.map(convert_datetime),
137       audience: Some(community.actor_id.into()),
138       in_reply_to: None,
139     };
140     Ok(page)
141   }
142
143   #[tracing::instrument(skip_all)]
144   async fn verify(
145     page: &Page,
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())?;
154     };
155
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?;
159
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)?;
163
164     verify_domains_match(page.creator()?.inner(), page.id.inner())?;
165     verify_is_public(&page.to, &page.cc)?;
166     Ok(())
167   }
168
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?;
175     }
176     let mut name = page
177       .name
178       .clone()
179       .or_else(|| {
180         page
181           .content
182           .clone()
183           .as_ref()
184           .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
185       })
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();
189     }
190
191     // read existing, local post if any (for generating mod log)
192     let old_post = page.id.dereference_local(context).await;
193
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() {
197         first_attachment
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())
201       } else {
202         None
203       };
204       check_url_scheme(&url)?;
205
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;
210
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() => {
216           fetch_site_data(
217             context.client(),
218             context.settings(),
219             Some(url),
220             include_image,
221           )
222           .await
223         }
224         _ => (None, None),
225       };
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()));
228
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);
233
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));
237       let language_id =
238         LanguageTag::to_language_id_single(page.language, &mut context.pool()).await?;
239
240       let name = sanitize_html(&name);
241       let embed_title = sanitize_html_opt(&embed_title);
242       let embed_description = sanitize_html_opt(&embed_description);
243
244       PostInsertForm {
245         name,
246         url: url.map(Into::into),
247         body: body_slurs_removed,
248         creator_id: creator.id,
249         community_id: community.id,
250         removed: None,
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,
256         embed_title,
257         embed_description,
258         embed_video_url,
259         thumbnail_url,
260         ap_id: Some(page.id.clone().into()),
261         local: Some(false),
262         language_id,
263         featured_community: None,
264         featured_local: None,
265       }
266     } else {
267       // if is mod action, only update locked/stickied fields, nothing else
268       PostInsertForm::builder()
269         .name(name)
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()))
275         .build()
276     };
277
278     let post = Post::create(&mut context.pool(), &form).await?;
279
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,
284         post_id: post.id,
285         locked: Some(post.locked),
286       };
287       ModLockPost::create(&mut context.pool(), &form).await?;
288     }
289
290     Ok(post.into())
291   }
292 }
293
294 #[cfg(test)]
295 mod tests {
296   #![allow(clippy::unwrap_used)]
297   #![allow(clippy::indexing_slicing)]
298
299   use super::*;
300   use crate::{
301     objects::{
302       community::tests::parse_lemmy_community,
303       person::tests::parse_lemmy_person,
304       post::ApubPost,
305       tests::init_context,
306     },
307     protocol::tests::file_to_json_object,
308   };
309   use lemmy_db_schema::source::site::Site;
310   use serial_test::serial;
311
312   #[tokio::test]
313   #[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;
318
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();
323
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);
331
332     Post::delete(&mut context.pool(), post.id).await.unwrap();
333     Person::delete(&mut context.pool(), person.id)
334       .await
335       .unwrap();
336     Community::delete(&mut context.pool(), community.id)
337       .await
338       .unwrap();
339     Site::delete(&mut context.pool(), site.id).await.unwrap();
340   }
341 }