]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Merge pull request #1850 from LemmyNet/refactor-apub
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::{extract_community, 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: [Url; 2],
55   name: String,
56   content: Option<String>,
57   media_type: 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: 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     Ok(())
113   }
114 }
115
116 #[derive(Clone, Debug)]
117 pub struct ApubPost(Post);
118
119 impl Deref for ApubPost {
120   type Target = Post;
121   fn deref(&self) -> &Self::Target {
122     &self.0
123   }
124 }
125
126 impl From<Post> for ApubPost {
127   fn from(p: Post) -> Self {
128     ApubPost { 0: p }
129   }
130 }
131
132 #[async_trait::async_trait(?Send)]
133 impl ApubObject for ApubPost {
134   type DataType = LemmyContext;
135
136   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
137     None
138   }
139
140   async fn read_from_apub_id(
141     object_id: Url,
142     context: &LemmyContext,
143   ) -> Result<Option<Self>, LemmyError> {
144     Ok(
145       blocking(context.pool(), move |conn| {
146         Post::read_from_apub_id(conn, object_id)
147       })
148       .await??
149       .map(Into::into),
150     )
151   }
152
153   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
154     blocking(context.pool(), move |conn| {
155       Post::update_deleted(conn, self.id, true)
156     })
157     .await??;
158     Ok(())
159   }
160 }
161
162 #[async_trait::async_trait(?Send)]
163 impl ToApub for ApubPost {
164   type ApubType = Page;
165   type TombstoneType = Tombstone;
166   type DataType = DbPool;
167
168   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
169   async fn to_apub(&self, pool: &DbPool) -> Result<Page, LemmyError> {
170     let creator_id = self.creator_id;
171     let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
172     let community_id = self.community_id;
173     let community = blocking(pool, move |conn| Community::read(conn, community_id)).await??;
174
175     let source = self.body.clone().map(|body| Source {
176       content: body,
177       media_type: MediaTypeMarkdown::Markdown,
178     });
179     let image = self.thumbnail_url.clone().map(|thumb| ImageObject {
180       kind: ImageType::Image,
181       url: thumb.into(),
182     });
183
184     let page = Page {
185       context: lemmy_context(),
186       r#type: PageType::Page,
187       id: self.ap_id.clone().into(),
188       attributed_to: ObjectId::new(creator.actor_id),
189       to: [community.actor_id.into(), public()],
190       name: self.name.clone(),
191       content: self.body.as_ref().map(|b| markdown_to_html(b)),
192       media_type: MediaTypeHtml::Html,
193       source,
194       url: self.url.clone().map(|u| u.into()),
195       image,
196       comments_enabled: Some(!self.locked),
197       sensitive: Some(self.nsfw),
198       stickied: Some(self.stickied),
199       published: convert_datetime(self.published),
200       updated: self.updated.map(convert_datetime),
201       unparsed: Default::default(),
202     };
203     Ok(page)
204   }
205
206   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
207     create_tombstone(
208       self.deleted,
209       self.ap_id.to_owned().into(),
210       self.updated,
211       PageType::Page,
212     )
213   }
214 }
215
216 #[async_trait::async_trait(?Send)]
217 impl FromApub for ApubPost {
218   type ApubType = Page;
219   type DataType = LemmyContext;
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 = extract_community(&page.to, context, request_counter).await?;
240
241     let thumbnail_url: Option<Url> = page.image.clone().map(|i| i.url);
242     let (metadata_res, pictrs_thumbnail) = if let Some(url) = &page.url {
243       fetch_site_data(context.client(), &context.settings(), Some(url)).await
244     } else {
245       (None, thumbnail_url)
246     };
247     let (embed_title, embed_description, embed_html) = metadata_res
248       .map(|u| (u.title, u.description, u.html))
249       .unwrap_or((None, None, None));
250
251     let body_slurs_removed = page
252       .source
253       .as_ref()
254       .map(|s| remove_slurs(&s.content, &context.settings().slur_regex()));
255     let form = PostForm {
256       name: page.name.clone(),
257       url: page.url.clone().map(|u| u.into()),
258       body: body_slurs_removed,
259       creator_id: creator.id,
260       community_id: community.id,
261       removed: None,
262       locked: page.comments_enabled.map(|e| !e),
263       published: Some(page.published.naive_local()),
264       updated: page.updated.map(|u| u.naive_local()),
265       deleted: None,
266       nsfw: page.sensitive,
267       stickied: page.stickied,
268       embed_title,
269       embed_description,
270       embed_html,
271       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
272       ap_id,
273       local: Some(false),
274     };
275     let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
276     Ok(post.into())
277   }
278 }