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