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