]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
background-jobs 0.11 (#1943)
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::{verify_is_public, verify_person_in_community},
3   check_is_apub_id_valid,
4   protocol::{
5     objects::{page::Page, tombstone::Tombstone},
6     ImageObject,
7     Source,
8   },
9 };
10 use activitystreams_kinds::{object::PageType, public};
11 use chrono::NaiveDateTime;
12 use lemmy_api_common::blocking;
13 use lemmy_apub_lib::{
14   object_id::ObjectId,
15   traits::ApubObject,
16   values::{MediaTypeHtml, MediaTypeMarkdown},
17   verify::verify_domains_match,
18 };
19 use lemmy_db_schema::{
20   self,
21   source::{
22     community::Community,
23     person::Person,
24     post::{Post, PostForm},
25   },
26   traits::Crud,
27 };
28 use lemmy_utils::{
29   request::fetch_site_data,
30   utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
31   LemmyError,
32 };
33 use lemmy_websocket::LemmyContext;
34 use std::ops::Deref;
35 use url::Url;
36
37 #[derive(Clone, Debug)]
38 pub struct ApubPost(Post);
39
40 impl Deref for ApubPost {
41   type Target = Post;
42   fn deref(&self) -> &Self::Target {
43     &self.0
44   }
45 }
46
47 impl From<Post> for ApubPost {
48   fn from(p: Post) -> Self {
49     ApubPost { 0: p }
50   }
51 }
52
53 #[async_trait::async_trait(?Send)]
54 impl ApubObject for ApubPost {
55   type DataType = LemmyContext;
56   type ApubType = Page;
57   type TombstoneType = Tombstone;
58
59   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
60     None
61   }
62
63   async fn read_from_apub_id(
64     object_id: Url,
65     context: &LemmyContext,
66   ) -> Result<Option<Self>, LemmyError> {
67     Ok(
68       blocking(context.pool(), move |conn| {
69         Post::read_from_apub_id(conn, object_id)
70       })
71       .await??
72       .map(Into::into),
73     )
74   }
75
76   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
77     if !self.deleted {
78       blocking(context.pool(), move |conn| {
79         Post::update_deleted(conn, self.id, true)
80       })
81       .await??;
82     }
83     Ok(())
84   }
85
86   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
87   async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
88     let creator_id = self.creator_id;
89     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
90     let community_id = self.community_id;
91     let community = blocking(context.pool(), move |conn| {
92       Community::read(conn, community_id)
93     })
94     .await??;
95
96     let source = self.body.clone().map(|body| Source {
97       content: body,
98       media_type: MediaTypeMarkdown::Markdown,
99     });
100     let image = self.thumbnail_url.clone().map(ImageObject::new);
101
102     let page = Page {
103       r#type: PageType::Page,
104       id: ObjectId::new(self.ap_id.clone()),
105       attributed_to: ObjectId::new(creator.actor_id),
106       to: vec![community.actor_id.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(MediaTypeHtml::Html),
111       source,
112       url: self.url.clone().map(|u| u.into()),
113       image,
114       comments_enabled: Some(!self.locked),
115       sensitive: Some(self.nsfw),
116       stickied: Some(self.stickied),
117       published: Some(convert_datetime(self.published)),
118       updated: self.updated.map(convert_datetime),
119       unparsed: Default::default(),
120     };
121     Ok(page)
122   }
123
124   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
125     Ok(Tombstone::new(self.ap_id.clone().into()))
126   }
127
128   async fn verify(
129     page: &Page,
130     expected_domain: &Url,
131     context: &LemmyContext,
132     request_counter: &mut i32,
133   ) -> Result<(), LemmyError> {
134     // We can't verify the domain in case of mod action, because the mod may be on a different
135     // instance from the post author.
136     if !page.is_mod_action(context).await? {
137       verify_domains_match(page.id.inner(), expected_domain)?;
138     };
139
140     let community = page.extract_community(context, request_counter).await?;
141     check_is_apub_id_valid(page.id.inner(), community.local, &context.settings())?;
142     verify_person_in_community(&page.attributed_to, &community, context, request_counter).await?;
143     check_slurs(&page.name, &context.settings().slur_regex())?;
144     verify_domains_match(page.attributed_to.inner(), page.id.inner())?;
145     verify_is_public(&page.to, &page.cc)?;
146     Ok(())
147   }
148
149   async fn from_apub(
150     page: Page,
151     context: &LemmyContext,
152     request_counter: &mut i32,
153   ) -> Result<ApubPost, LemmyError> {
154     let creator = page
155       .attributed_to
156       .dereference(context, request_counter)
157       .await?;
158     let community = page.extract_community(context, request_counter).await?;
159
160     let thumbnail_url: Option<Url> = page.image.map(|i| i.url);
161     let (metadata_res, pictrs_thumbnail) = if let Some(url) = &page.url {
162       fetch_site_data(context.client(), &context.settings(), Some(url)).await
163     } else {
164       (None, thumbnail_url)
165     };
166     let (embed_title, embed_description, embed_html) = metadata_res
167       .map(|u| (u.title, u.description, u.html))
168       .unwrap_or((None, None, None));
169
170     let body_slurs_removed = page
171       .source
172       .as_ref()
173       .map(|s| remove_slurs(&s.content, &context.settings().slur_regex()));
174     let form = PostForm {
175       name: page.name,
176       url: page.url.map(|u| u.into()),
177       body: body_slurs_removed,
178       creator_id: creator.id,
179       community_id: community.id,
180       removed: None,
181       locked: page.comments_enabled.map(|e| !e),
182       published: page.published.map(|u| u.naive_local()),
183       updated: page.updated.map(|u| u.naive_local()),
184       deleted: None,
185       nsfw: page.sensitive,
186       stickied: page.stickied,
187       embed_title,
188       embed_description,
189       embed_html,
190       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
191       ap_id: Some(page.id.into()),
192       local: Some(false),
193     };
194     let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
195     Ok(post.into())
196   }
197 }
198
199 #[cfg(test)]
200 mod tests {
201   use super::*;
202   use crate::objects::{
203     community::tests::parse_lemmy_community,
204     person::tests::parse_lemmy_person,
205     post::ApubPost,
206     tests::{file_to_json_object, init_context},
207   };
208   use lemmy_apub_lib::activity_queue::create_activity_queue;
209   use serial_test::serial;
210
211   #[actix_rt::test]
212   #[serial]
213   async fn test_parse_lemmy_post() {
214     let manager = create_activity_queue();
215     let context = init_context(manager.queue_handle().clone());
216     let community = parse_lemmy_community(&context).await;
217     let person = parse_lemmy_person(&context).await;
218
219     let json = file_to_json_object("assets/lemmy/objects/page.json");
220     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
221     let mut request_counter = 0;
222     ApubPost::verify(&json, &url, &context, &mut request_counter)
223       .await
224       .unwrap();
225     let post = ApubPost::from_apub(json, &context, &mut request_counter)
226       .await
227       .unwrap();
228
229     assert_eq!(post.ap_id, url.into());
230     assert_eq!(post.name, "Post title");
231     assert!(post.body.is_some());
232     assert_eq!(post.body.as_ref().unwrap().len(), 45);
233     assert!(!post.locked);
234     assert!(post.stickied);
235     assert_eq!(request_counter, 0);
236
237     Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
238     Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
239     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
240   }
241 }