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