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