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