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