]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Refactoring apub code
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::verify_person_in_community,
3   check_is_apub_id_valid,
4   fetcher::object_id::ObjectId,
5   protocol::{
6     objects::{page::Page, tombstone::Tombstone},
7     ImageObject,
8     Source,
9   },
10 };
11 use activitystreams::{
12   object::kind::{ImageType, PageType},
13   public,
14 };
15 use chrono::NaiveDateTime;
16 use lemmy_api_common::blocking;
17 use lemmy_apub_lib::{
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::{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   async fn read_from_apub_id(
67     object_id: Url,
68     context: &LemmyContext,
69   ) -> Result<Option<Self>, LemmyError> {
70     Ok(
71       blocking(context.pool(), move |conn| {
72         Post::read_from_apub_id(conn, object_id)
73       })
74       .await??
75       .map(Into::into),
76     )
77   }
78
79   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
80     if !self.deleted {
81       blocking(context.pool(), move |conn| {
82         Post::update_deleted(conn, self.id, true)
83       })
84       .await??;
85     }
86     Ok(())
87   }
88
89   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
90   async fn to_apub(&self, context: &LemmyContext) -> Result<Page, LemmyError> {
91     let creator_id = self.creator_id;
92     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
93     let community_id = self.community_id;
94     let community = blocking(context.pool(), move |conn| {
95       Community::read(conn, community_id)
96     })
97     .await??;
98
99     let source = self.body.clone().map(|body| Source {
100       content: body,
101       media_type: MediaTypeMarkdown::Markdown,
102     });
103     let image = self.thumbnail_url.clone().map(|thumb| ImageObject {
104       kind: ImageType::Image,
105       url: thumb.into(),
106     });
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       name: self.name.clone(),
114       content: self.body.as_ref().map(|b| markdown_to_html(b)),
115       media_type: Some(MediaTypeHtml::Html),
116       source,
117       url: self.url.clone().map(|u| u.into()),
118       image,
119       comments_enabled: Some(!self.locked),
120       sensitive: Some(self.nsfw),
121       stickied: Some(self.stickied),
122       published: Some(convert_datetime(self.published)),
123       updated: self.updated.map(convert_datetime),
124       unparsed: Default::default(),
125     };
126     Ok(page)
127   }
128
129   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
130     Ok(Tombstone::new(
131       PageType::Page,
132       self.updated.unwrap_or(self.published),
133     ))
134   }
135
136   async fn from_apub(
137     page: &Page,
138     context: &LemmyContext,
139     expected_domain: &Url,
140     request_counter: &mut i32,
141   ) -> Result<ApubPost, LemmyError> {
142     // We can't verify the domain in case of mod action, because the mod may be on a different
143     // instance from the post author.
144     if !page.is_mod_action(context).await? {
145       verify_domains_match(page.id.inner(), expected_domain)?;
146     };
147     let ap_id = Some(page.id.clone().into());
148     let creator = page
149       .attributed_to
150       .dereference(context, request_counter)
151       .await?;
152     let community = page.extract_community(context, request_counter).await?;
153     check_is_apub_id_valid(page.id.inner(), community.local, &context.settings())?;
154     verify_person_in_community(&page.attributed_to, &community, context, request_counter).await?;
155
156     let thumbnail_url: Option<Url> = page.image.clone().map(|i| i.url);
157     let (metadata_res, pictrs_thumbnail) = if let Some(url) = &page.url {
158       fetch_site_data(context.client(), &context.settings(), Some(url)).await
159     } else {
160       (None, thumbnail_url)
161     };
162     let (embed_title, embed_description, embed_html) = metadata_res
163       .map(|u| (u.title, u.description, u.html))
164       .unwrap_or((None, None, None));
165
166     let body_slurs_removed = page
167       .source
168       .as_ref()
169       .map(|s| remove_slurs(&s.content, &context.settings().slur_regex()));
170     let form = PostForm {
171       name: page.name.clone(),
172       url: page.url.clone().map(|u| u.into()),
173       body: body_slurs_removed,
174       creator_id: creator.id,
175       community_id: community.id,
176       removed: None,
177       locked: page.comments_enabled.map(|e| !e),
178       published: page.published.map(|u| u.naive_local()),
179       updated: page.updated.map(|u| u.naive_local()),
180       deleted: None,
181       nsfw: page.sensitive,
182       stickied: page.stickied,
183       embed_title,
184       embed_description,
185       embed_html,
186       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
187       ap_id,
188       local: Some(false),
189     };
190     let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
191     Ok(post.into())
192   }
193 }
194
195 #[cfg(test)]
196 mod tests {
197   use super::*;
198   use crate::objects::{
199     community::tests::parse_lemmy_community,
200     person::tests::parse_lemmy_person,
201     post::ApubPost,
202     tests::{file_to_json_object, init_context},
203   };
204   use serial_test::serial;
205
206   #[actix_rt::test]
207   #[serial]
208   async fn test_parse_lemmy_post() {
209     let context = init_context();
210     let community = parse_lemmy_community(&context).await;
211     let person = parse_lemmy_person(&context).await;
212
213     let json = file_to_json_object("assets/lemmy/objects/page.json");
214     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
215     let mut request_counter = 0;
216     let post = ApubPost::from_apub(&json, &context, &url, &mut request_counter)
217       .await
218       .unwrap();
219
220     assert_eq!(post.ap_id.clone().into_inner(), url);
221     assert_eq!(post.name, "Post title");
222     assert!(post.body.is_some());
223     assert_eq!(post.body.as_ref().unwrap().len(), 45);
224     assert!(!post.locked);
225     assert!(post.stickied);
226     assert_eq!(request_counter, 0);
227
228     Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
229     Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
230     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
231   }
232 }