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