]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Don't drop error context when adding a message to errors (#1958)
[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   #[tracing::instrument(skip_all)]
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   #[tracing::instrument(skip_all)]
78   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
79     if !self.deleted {
80       blocking(context.pool(), move |conn| {
81         Post::update_deleted(conn, self.id, true)
82       })
83       .await??;
84     }
85     Ok(())
86   }
87
88   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
89   #[tracing::instrument(skip_all)]
90   async fn into_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(ImageObject::new);
104
105     let page = Page {
106       r#type: PageType::Page,
107       id: ObjectId::new(self.ap_id.clone()),
108       attributed_to: ObjectId::new(creator.actor_id),
109       to: vec![community.actor_id.into(), public()],
110       cc: vec![],
111       name: self.name.clone(),
112       content: self.body.as_ref().map(|b| markdown_to_html(b)),
113       media_type: Some(MediaTypeHtml::Html),
114       source,
115       url: self.url.clone().map(|u| u.into()),
116       image,
117       comments_enabled: Some(!self.locked),
118       sensitive: Some(self.nsfw),
119       stickied: Some(self.stickied),
120       published: Some(convert_datetime(self.published)),
121       updated: self.updated.map(convert_datetime),
122       unparsed: Default::default(),
123     };
124     Ok(page)
125   }
126
127   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
128     Ok(Tombstone::new(self.ap_id.clone().into()))
129   }
130
131   #[tracing::instrument(skip_all)]
132   async fn verify(
133     page: &Page,
134     expected_domain: &Url,
135     context: &LemmyContext,
136     request_counter: &mut i32,
137   ) -> Result<(), 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     if !page.is_mod_action(context).await? {
141       verify_domains_match(page.id.inner(), expected_domain)?;
142     };
143
144     let community = page.extract_community(context, request_counter).await?;
145     check_is_apub_id_valid(page.id.inner(), community.local, &context.settings())?;
146     verify_person_in_community(&page.attributed_to, &community, context, request_counter).await?;
147     check_slurs(&page.name, &context.settings().slur_regex())?;
148     verify_domains_match(page.attributed_to.inner(), page.id.inner())?;
149     verify_is_public(&page.to, &page.cc)?;
150     Ok(())
151   }
152
153   #[tracing::instrument(skip_all)]
154   async fn from_apub(
155     page: Page,
156     context: &LemmyContext,
157     request_counter: &mut i32,
158   ) -> Result<ApubPost, LemmyError> {
159     let creator = page
160       .attributed_to
161       .dereference(context, request_counter)
162       .await?;
163     let community = page.extract_community(context, request_counter).await?;
164
165     let thumbnail_url: Option<Url> = page.image.map(|i| i.url);
166     let (metadata_res, pictrs_thumbnail) = if let Some(url) = &page.url {
167       fetch_site_data(context.client(), &context.settings(), Some(url)).await
168     } else {
169       (None, thumbnail_url)
170     };
171     let (embed_title, embed_description, embed_html) = metadata_res
172       .map(|u| (u.title, u.description, u.html))
173       .unwrap_or((None, None, None));
174
175     let body_slurs_removed = page
176       .source
177       .as_ref()
178       .map(|s| remove_slurs(&s.content, &context.settings().slur_regex()));
179     let form = PostForm {
180       name: page.name,
181       url: page.url.map(|u| u.into()),
182       body: body_slurs_removed,
183       creator_id: creator.id,
184       community_id: community.id,
185       removed: None,
186       locked: page.comments_enabled.map(|e| !e),
187       published: page.published.map(|u| u.naive_local()),
188       updated: page.updated.map(|u| u.naive_local()),
189       deleted: None,
190       nsfw: page.sensitive,
191       stickied: page.stickied,
192       embed_title,
193       embed_description,
194       embed_html,
195       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
196       ap_id: Some(page.id.into()),
197       local: Some(false),
198     };
199     let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
200     Ok(post.into())
201   }
202 }
203
204 #[cfg(test)]
205 mod tests {
206   use super::*;
207   use crate::objects::{
208     community::tests::parse_lemmy_community,
209     person::tests::parse_lemmy_person,
210     post::ApubPost,
211     tests::{file_to_json_object, init_context},
212   };
213   use lemmy_apub_lib::activity_queue::create_activity_queue;
214   use serial_test::serial;
215
216   #[actix_rt::test]
217   #[serial]
218   async fn test_parse_lemmy_post() {
219     let manager = create_activity_queue();
220     let context = init_context(manager.queue_handle().clone());
221     let community = parse_lemmy_community(&context).await;
222     let person = parse_lemmy_person(&context).await;
223
224     let json = file_to_json_object("assets/lemmy/objects/page.json");
225     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
226     let mut request_counter = 0;
227     ApubPost::verify(&json, &url, &context, &mut request_counter)
228       .await
229       .unwrap();
230     let post = ApubPost::from_apub(json, &context, &mut request_counter)
231       .await
232       .unwrap();
233
234     assert_eq!(post.ap_id, url.into());
235     assert_eq!(post.name, "Post title");
236     assert!(post.body.is_some());
237     assert_eq!(post.body.as_ref().unwrap().len(), 45);
238     assert!(!post.locked);
239     assert!(post.stickied);
240     assert_eq!(request_counter, 0);
241
242     Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
243     Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
244     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
245   }
246 }