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