]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
In apub post receive, check posting restricted to mods (ref #2702) (#2704)
[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::{is_mod_or_admin, 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     if community.posting_restricted_to_mods {
177       is_mod_or_admin(context.pool(), creator.id, community.id).await?;
178     }
179     let mut name = page
180       .name
181       .clone()
182       .or_else(|| {
183         page
184           .content
185           .clone()
186           .and_then(|c| c.lines().next().map(ToString::to_string))
187       })
188       .ok_or_else(|| anyhow!("Object must have name or content"))?;
189     if name.chars().count() > MAX_TITLE_LENGTH {
190       name = name.chars().take(MAX_TITLE_LENGTH).collect();
191     }
192
193     let form = if !page.is_mod_action(context).await? {
194       let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
195       let url = if first_attachment.is_some() {
196         first_attachment
197       } else if page.kind == PageType::Video {
198         // we cant display videos directly, so insert a link to external video page
199         Some(page.id.inner().clone())
200       } else {
201         None
202       };
203       let (metadata_res, thumbnail_url) = if let Some(url) = &url {
204         fetch_site_data(context.client(), context.settings(), Some(url)).await
205       } else {
206         (None, page.image.map(|i| i.url.into()))
207       };
208       let (embed_title, embed_description, embed_video_url) = metadata_res
209         .map(|u| (u.title, u.description, u.embed_video_url))
210         .unwrap_or_default();
211       let local_site = LocalSite::read(context.pool()).await.ok();
212       let slur_regex = &local_site_opt_to_slur_regex(&local_site);
213
214       let body_slurs_removed =
215         read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
216           .map(|s| remove_slurs(&s, slur_regex));
217       let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
218
219       PostInsertForm {
220         name,
221         url: url.map(Into::into),
222         body: body_slurs_removed,
223         creator_id: creator.id,
224         community_id: community.id,
225         removed: None,
226         locked: page.comments_enabled.map(|e| !e),
227         published: page.published.map(|u| u.naive_local()),
228         updated: page.updated.map(|u| u.naive_local()),
229         deleted: Some(false),
230         nsfw: page.sensitive,
231         embed_title,
232         embed_description,
233         embed_video_url,
234         thumbnail_url,
235         ap_id: Some(page.id.clone().into()),
236         local: Some(false),
237         language_id,
238         featured_community: page.stickied,
239         featured_local: None,
240       }
241     } else {
242       // if is mod action, only update locked/stickied fields, nothing else
243       PostInsertForm::builder()
244         .name(name)
245         .creator_id(creator.id)
246         .community_id(community.id)
247         .ap_id(Some(page.id.clone().into()))
248         .locked(page.comments_enabled.map(|e| !e))
249         .featured_community(page.stickied)
250         .updated(page.updated.map(|u| u.naive_local()))
251         .build()
252     };
253     // read existing, local post if any (for generating mod log)
254     let old_post = ObjectId::<ApubPost>::new(page.id.clone())
255       .dereference_local(context)
256       .await;
257
258     let post = Post::create(context.pool(), &form).await?;
259
260     // write mod log entries for feature/lock
261     if Page::is_featured_changed(&old_post, &page.stickied) {
262       let form = ModFeaturePostForm {
263         mod_person_id: creator.id,
264         post_id: post.id,
265         featured: post.featured_community,
266         is_featured_community: true,
267       };
268       ModFeaturePost::create(context.pool(), &form).await?;
269     }
270     if Page::is_locked_changed(&old_post, &page.comments_enabled) {
271       let form = ModLockPostForm {
272         mod_person_id: creator.id,
273         post_id: post.id,
274         locked: Some(post.locked),
275       };
276       ModLockPost::create(context.pool(), &form).await?;
277     }
278
279     Ok(post.into())
280   }
281 }
282
283 #[cfg(test)]
284 mod tests {
285   use super::*;
286   use crate::{
287     objects::{
288       community::tests::parse_lemmy_community,
289       person::tests::parse_lemmy_person,
290       post::ApubPost,
291       tests::init_context,
292     },
293     protocol::tests::file_to_json_object,
294   };
295   use lemmy_db_schema::source::site::Site;
296   use serial_test::serial;
297
298   #[actix_rt::test]
299   #[serial]
300   async fn test_parse_lemmy_post() {
301     let context = init_context().await;
302     let (person, site) = parse_lemmy_person(&context).await;
303     let community = parse_lemmy_community(&context).await;
304
305     let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
306     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
307     let mut request_counter = 0;
308     ApubPost::verify(&json, &url, &context, &mut request_counter)
309       .await
310       .unwrap();
311     let post = ApubPost::from_apub(json, &context, &mut request_counter)
312       .await
313       .unwrap();
314
315     assert_eq!(post.ap_id, url.into());
316     assert_eq!(post.name, "Post title");
317     assert!(post.body.is_some());
318     assert_eq!(post.body.as_ref().unwrap().len(), 45);
319     assert!(!post.locked);
320     assert!(post.featured_community);
321     assert_eq!(request_counter, 0);
322
323     Post::delete(context.pool(), post.id).await.unwrap();
324     Person::delete(context.pool(), person.id).await.unwrap();
325     Community::delete(context.pool(), community.id)
326       .await
327       .unwrap();
328     Site::delete(context.pool(), site.id).await.unwrap();
329   }
330 }