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