]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Move @context out of object/activity definitions
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::{verify_is_public, verify_person_in_community},
3   fetcher::object_id::ObjectId,
4   objects::{
5     community::ApubCommunity,
6     person::ApubPerson,
7     tombstone::Tombstone,
8     ImageObject,
9     Source,
10   },
11 };
12 use activitystreams::{
13   object::kind::{ImageType, PageType},
14   public,
15   unparsed::Unparsed,
16 };
17 use anyhow::anyhow;
18 use chrono::{DateTime, FixedOffset, NaiveDateTime};
19 use lemmy_api_common::blocking;
20 use lemmy_apub_lib::{
21   traits::ApubObject,
22   values::{MediaTypeHtml, MediaTypeMarkdown},
23   verify::verify_domains_match,
24 };
25 use lemmy_db_schema::{
26   self,
27   source::{
28     community::Community,
29     person::Person,
30     post::{Post, PostForm},
31   },
32   traits::Crud,
33 };
34 use lemmy_utils::{
35   request::fetch_site_data,
36   utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
37   LemmyError,
38 };
39 use lemmy_websocket::LemmyContext;
40 use serde::{Deserialize, Serialize};
41 use serde_with::skip_serializing_none;
42 use std::ops::Deref;
43 use url::Url;
44
45 #[skip_serializing_none]
46 #[derive(Clone, Debug, Deserialize, Serialize)]
47 #[serde(rename_all = "camelCase")]
48 pub struct Page {
49   r#type: PageType,
50   id: Url,
51   pub(crate) attributed_to: ObjectId<ApubPerson>,
52   to: Vec<Url>,
53   name: String,
54   content: Option<String>,
55   media_type: Option<MediaTypeHtml>,
56   source: Option<Source>,
57   url: Option<Url>,
58   image: Option<ImageObject>,
59   pub(crate) comments_enabled: Option<bool>,
60   sensitive: Option<bool>,
61   pub(crate) stickied: Option<bool>,
62   published: Option<DateTime<FixedOffset>>,
63   updated: Option<DateTime<FixedOffset>>,
64   #[serde(flatten)]
65   unparsed: Unparsed,
66 }
67
68 impl Page {
69   pub(crate) fn id_unchecked(&self) -> &Url {
70     &self.id
71   }
72   pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
73     verify_domains_match(&self.id, expected_domain)?;
74     Ok(&self.id)
75   }
76
77   /// Only mods can change the post's stickied/locked status. So if either of these is changed from
78   /// the current value, it is a mod action and needs to be verified as such.
79   ///
80   /// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]].
81   pub(crate) async fn is_mod_action(&self, context: &LemmyContext) -> Result<bool, LemmyError> {
82     let old_post = ObjectId::<ApubPost>::new(self.id.clone())
83       .dereference_local(context)
84       .await;
85
86     let is_mod_action = if let Ok(old_post) = old_post {
87       self.stickied != Some(old_post.stickied) || self.comments_enabled != Some(!old_post.locked)
88     } else {
89       false
90     };
91     Ok(is_mod_action)
92   }
93
94   pub(crate) async fn verify(
95     &self,
96     context: &LemmyContext,
97     request_counter: &mut i32,
98   ) -> Result<(), LemmyError> {
99     let community = self.extract_community(context, request_counter).await?;
100
101     check_slurs(&self.name, &context.settings().slur_regex())?;
102     verify_domains_match(self.attributed_to.inner(), &self.id.clone())?;
103     verify_person_in_community(&self.attributed_to, &community, context, request_counter).await?;
104     verify_is_public(&self.to.clone())?;
105     Ok(())
106   }
107
108   pub(crate) async fn extract_community(
109     &self,
110     context: &LemmyContext,
111     request_counter: &mut i32,
112   ) -> Result<ApubCommunity, LemmyError> {
113     let mut to_iter = self.to.iter();
114     loop {
115       if let Some(cid) = to_iter.next() {
116         let cid = ObjectId::new(cid.clone());
117         if let Ok(c) = cid.dereference(context, request_counter).await {
118           break Ok(c);
119         }
120       } else {
121         return Err(anyhow!("No community found in cc").into());
122       }
123     }
124   }
125 }
126
127 #[derive(Clone, Debug)]
128 pub struct ApubPost(Post);
129
130 impl Deref for ApubPost {
131   type Target = Post;
132   fn deref(&self) -> &Self::Target {
133     &self.0
134   }
135 }
136
137 impl From<Post> for ApubPost {
138   fn from(p: Post) -> Self {
139     ApubPost { 0: p }
140   }
141 }
142
143 #[async_trait::async_trait(?Send)]
144 impl ApubObject for ApubPost {
145   type DataType = LemmyContext;
146   type ApubType = Page;
147   type TombstoneType = Tombstone;
148
149   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
150     None
151   }
152
153   async fn read_from_apub_id(
154     object_id: Url,
155     context: &LemmyContext,
156   ) -> Result<Option<Self>, LemmyError> {
157     Ok(
158       blocking(context.pool(), move |conn| {
159         Post::read_from_apub_id(conn, object_id)
160       })
161       .await??
162       .map(Into::into),
163     )
164   }
165
166   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
167     blocking(context.pool(), move |conn| {
168       Post::update_deleted(conn, self.id, true)
169     })
170     .await??;
171     Ok(())
172   }
173
174   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
175   async fn to_apub(&self, context: &LemmyContext) -> Result<Page, LemmyError> {
176     let creator_id = self.creator_id;
177     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
178     let community_id = self.community_id;
179     let community = blocking(context.pool(), move |conn| {
180       Community::read(conn, community_id)
181     })
182     .await??;
183
184     let source = self.body.clone().map(|body| Source {
185       content: body,
186       media_type: MediaTypeMarkdown::Markdown,
187     });
188     let image = self.thumbnail_url.clone().map(|thumb| ImageObject {
189       kind: ImageType::Image,
190       url: thumb.into(),
191     });
192
193     let page = Page {
194       r#type: PageType::Page,
195       id: self.ap_id.clone().into(),
196       attributed_to: ObjectId::new(creator.actor_id),
197       to: vec![community.actor_id.into(), public()],
198       name: self.name.clone(),
199       content: self.body.as_ref().map(|b| markdown_to_html(b)),
200       media_type: Some(MediaTypeHtml::Html),
201       source,
202       url: self.url.clone().map(|u| u.into()),
203       image,
204       comments_enabled: Some(!self.locked),
205       sensitive: Some(self.nsfw),
206       stickied: Some(self.stickied),
207       published: Some(convert_datetime(self.published)),
208       updated: self.updated.map(convert_datetime),
209       unparsed: Default::default(),
210     };
211     Ok(page)
212   }
213
214   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
215     Ok(Tombstone::new(
216       PageType::Page,
217       self.updated.unwrap_or(self.published),
218     ))
219   }
220
221   async fn from_apub(
222     page: &Page,
223     context: &LemmyContext,
224     expected_domain: &Url,
225     request_counter: &mut i32,
226   ) -> Result<ApubPost, LemmyError> {
227     // We can't verify the domain in case of mod action, because the mod may be on a different
228     // instance from the post author.
229     let ap_id = if page.is_mod_action(context).await? {
230       page.id_unchecked()
231     } else {
232       page.id(expected_domain)?
233     };
234     let ap_id = Some(ap_id.clone().into());
235     let creator = page
236       .attributed_to
237       .dereference(context, request_counter)
238       .await?;
239     let community = page.extract_community(context, request_counter).await?;
240     verify_person_in_community(&page.attributed_to, &community, context, request_counter).await?;
241
242     let thumbnail_url: Option<Url> = page.image.clone().map(|i| i.url);
243     let (metadata_res, pictrs_thumbnail) = if let Some(url) = &page.url {
244       fetch_site_data(context.client(), &context.settings(), Some(url)).await
245     } else {
246       (None, thumbnail_url)
247     };
248     let (embed_title, embed_description, embed_html) = metadata_res
249       .map(|u| (u.title, u.description, u.html))
250       .unwrap_or((None, None, None));
251
252     let body_slurs_removed = page
253       .source
254       .as_ref()
255       .map(|s| remove_slurs(&s.content, &context.settings().slur_regex()));
256     let form = PostForm {
257       name: page.name.clone(),
258       url: page.url.clone().map(|u| u.into()),
259       body: body_slurs_removed,
260       creator_id: creator.id,
261       community_id: community.id,
262       removed: None,
263       locked: page.comments_enabled.map(|e| !e),
264       published: page.published.map(|u| u.naive_local()),
265       updated: page.updated.map(|u| u.naive_local()),
266       deleted: None,
267       nsfw: page.sensitive,
268       stickied: page.stickied,
269       embed_title,
270       embed_description,
271       embed_html,
272       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
273       ap_id,
274       local: Some(false),
275     };
276     let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
277     Ok(post.into())
278   }
279 }
280
281 #[cfg(test)]
282 mod tests {
283   use super::*;
284   use crate::objects::{
285     community::ApubCommunity,
286     tests::{file_to_json_object, init_context},
287   };
288   use assert_json_diff::assert_json_include;
289   use serial_test::serial;
290
291   #[actix_rt::test]
292   #[serial]
293   async fn test_parse_lemmy_post() {
294     let context = init_context();
295     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
296     let community_json = file_to_json_object("assets/lemmy-community.json");
297     let community = ApubCommunity::from_apub(&community_json, &context, &url, &mut 0)
298       .await
299       .unwrap();
300     let person_json = file_to_json_object("assets/lemmy-person.json");
301     let person = ApubPerson::from_apub(&person_json, &context, &url, &mut 0)
302       .await
303       .unwrap();
304     let json = file_to_json_object("assets/lemmy-post.json");
305     let mut request_counter = 0;
306     let post = ApubPost::from_apub(&json, &context, &url, &mut request_counter)
307       .await
308       .unwrap();
309
310     assert_eq!(post.ap_id.clone().into_inner(), url);
311     assert_eq!(post.name, "Post title");
312     assert!(post.body.is_some());
313     assert_eq!(post.body.as_ref().unwrap().len(), 45);
314     assert!(!post.locked);
315     assert!(post.stickied);
316     assert_eq!(request_counter, 0);
317
318     let to_apub = post.to_apub(&context).await.unwrap();
319     assert_json_include!(actual: json, expected: to_apub);
320
321     Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
322     Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
323     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
324   }
325 }