]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Pleroma federation2 (#1855)
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::{extract_community, verify_is_public, verify_person_in_community},
3   context::lemmy_context,
4   fetcher::object_id::ObjectId,
5   objects::{create_tombstone, person::ApubPerson, ImageObject, Source},
6 };
7 use activitystreams::{
8   base::AnyBase,
9   object::{
10     kind::{ImageType, PageType},
11     Tombstone,
12   },
13   primitives::OneOrMany,
14   public,
15   unparsed::Unparsed,
16 };
17 use chrono::{DateTime, FixedOffset, NaiveDateTime};
18 use lemmy_api_common::blocking;
19 use lemmy_apub_lib::{
20   traits::{ActorType, ApubObject, FromApub, ToApub},
21   values::{MediaTypeHtml, MediaTypeMarkdown},
22   verify::verify_domains_match,
23 };
24 use lemmy_db_schema::{
25   self,
26   source::{
27     community::Community,
28     person::Person,
29     post::{Post, PostForm},
30   },
31   traits::Crud,
32   DbPool,
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   #[serde(rename = "@context")]
50   context: OneOrMany<AnyBase>,
51   r#type: PageType,
52   id: Url,
53   pub(crate) attributed_to: ObjectId<ApubPerson>,
54   to: Vec<Url>,
55   name: String,
56   content: Option<String>,
57   media_type: Option<MediaTypeHtml>,
58   source: Option<Source>,
59   url: Option<Url>,
60   image: Option<ImageObject>,
61   pub(crate) comments_enabled: Option<bool>,
62   sensitive: Option<bool>,
63   pub(crate) stickied: Option<bool>,
64   published: Option<DateTime<FixedOffset>>,
65   updated: Option<DateTime<FixedOffset>>,
66   #[serde(flatten)]
67   unparsed: Unparsed,
68 }
69
70 impl Page {
71   pub(crate) fn id_unchecked(&self) -> &Url {
72     &self.id
73   }
74   pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
75     verify_domains_match(&self.id, expected_domain)?;
76     Ok(&self.id)
77   }
78
79   /// Only mods can change the post's stickied/locked status. So if either of these is changed from
80   /// the current value, it is a mod action and needs to be verified as such.
81   ///
82   /// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]].
83   pub(crate) async fn is_mod_action(&self, context: &LemmyContext) -> Result<bool, LemmyError> {
84     let old_post = ObjectId::<ApubPost>::new(self.id.clone())
85       .dereference_local(context)
86       .await;
87
88     let is_mod_action = if let Ok(old_post) = old_post {
89       self.stickied != Some(old_post.stickied) || self.comments_enabled != Some(!old_post.locked)
90     } else {
91       false
92     };
93     Ok(is_mod_action)
94   }
95
96   pub(crate) async fn verify(
97     &self,
98     context: &LemmyContext,
99     request_counter: &mut i32,
100   ) -> Result<(), LemmyError> {
101     let community = extract_community(&self.to, context, request_counter).await?;
102
103     check_slurs(&self.name, &context.settings().slur_regex())?;
104     verify_domains_match(self.attributed_to.inner(), &self.id.clone())?;
105     verify_person_in_community(
106       &self.attributed_to,
107       &ObjectId::new(community.actor_id()),
108       context,
109       request_counter,
110     )
111     .await?;
112     verify_is_public(&self.to.clone())?;
113     Ok(())
114   }
115 }
116
117 #[derive(Clone, Debug)]
118 pub struct ApubPost(Post);
119
120 impl Deref for ApubPost {
121   type Target = Post;
122   fn deref(&self) -> &Self::Target {
123     &self.0
124   }
125 }
126
127 impl From<Post> for ApubPost {
128   fn from(p: Post) -> Self {
129     ApubPost { 0: p }
130   }
131 }
132
133 #[async_trait::async_trait(?Send)]
134 impl ApubObject for ApubPost {
135   type DataType = LemmyContext;
136
137   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
138     None
139   }
140
141   async fn read_from_apub_id(
142     object_id: Url,
143     context: &LemmyContext,
144   ) -> Result<Option<Self>, LemmyError> {
145     Ok(
146       blocking(context.pool(), move |conn| {
147         Post::read_from_apub_id(conn, object_id)
148       })
149       .await??
150       .map(Into::into),
151     )
152   }
153
154   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
155     blocking(context.pool(), move |conn| {
156       Post::update_deleted(conn, self.id, true)
157     })
158     .await??;
159     Ok(())
160   }
161 }
162
163 #[async_trait::async_trait(?Send)]
164 impl ToApub for ApubPost {
165   type ApubType = Page;
166   type TombstoneType = Tombstone;
167   type DataType = DbPool;
168
169   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
170   async fn to_apub(&self, pool: &DbPool) -> Result<Page, LemmyError> {
171     let creator_id = self.creator_id;
172     let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
173     let community_id = self.community_id;
174     let community = blocking(pool, move |conn| Community::read(conn, community_id)).await??;
175
176     let source = self.body.clone().map(|body| Source {
177       content: body,
178       media_type: MediaTypeMarkdown::Markdown,
179     });
180     let image = self.thumbnail_url.clone().map(|thumb| ImageObject {
181       kind: ImageType::Image,
182       url: thumb.into(),
183     });
184
185     let page = Page {
186       context: lemmy_context(),
187       r#type: PageType::Page,
188       id: self.ap_id.clone().into(),
189       attributed_to: ObjectId::new(creator.actor_id),
190       to: vec![community.actor_id.into(), public()],
191       name: self.name.clone(),
192       content: self.body.as_ref().map(|b| markdown_to_html(b)),
193       media_type: Some(MediaTypeHtml::Html),
194       source,
195       url: self.url.clone().map(|u| u.into()),
196       image,
197       comments_enabled: Some(!self.locked),
198       sensitive: Some(self.nsfw),
199       stickied: Some(self.stickied),
200       published: Some(convert_datetime(self.published)),
201       updated: self.updated.map(convert_datetime),
202       unparsed: Default::default(),
203     };
204     Ok(page)
205   }
206
207   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
208     create_tombstone(
209       self.deleted,
210       self.ap_id.to_owned().into(),
211       self.updated,
212       PageType::Page,
213     )
214   }
215 }
216
217 #[async_trait::async_trait(?Send)]
218 impl FromApub for ApubPost {
219   type ApubType = Page;
220   type DataType = LemmyContext;
221
222   async fn from_apub(
223     page: &Page,
224     context: &LemmyContext,
225     expected_domain: &Url,
226     request_counter: &mut i32,
227   ) -> Result<ApubPost, LemmyError> {
228     // We can't verify the domain in case of mod action, because the mod may be on a different
229     // instance from the post author.
230     let ap_id = if page.is_mod_action(context).await? {
231       page.id_unchecked()
232     } else {
233       page.id(expected_domain)?
234     };
235     let ap_id = Some(ap_id.clone().into());
236     let creator = page
237       .attributed_to
238       .dereference(context, request_counter)
239       .await?;
240     let community = extract_community(&page.to, 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_fetch_lemmy_post() {
294     let context = init_context();
295     let url = Url::parse("https://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, "Statement on Politics of Lemmy.ml");
312     assert!(post.body.is_some());
313     assert_eq!(post.body.as_ref().unwrap().len(), 2144);
314     assert!(!post.locked);
315     assert!(post.stickied);
316     assert_eq!(request_counter, 0);
317
318     let to_apub = post.to_apub(context.pool()).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 }