]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
bb301038072deec592e263b1635341f778aba150
[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, FromApub, ImageObject, Source, ToApub},
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};
18 use lemmy_api_common::blocking;
19 use lemmy_apub_lib::{
20   traits::ActorType,
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 url::Url;
43
44 #[skip_serializing_none]
45 #[derive(Clone, Debug, Deserialize, Serialize)]
46 #[serde(rename_all = "camelCase")]
47 pub struct Page {
48   #[serde(rename = "@context")]
49   context: OneOrMany<AnyBase>,
50   r#type: PageType,
51   id: Url,
52   pub(crate) attributed_to: ObjectId<Person>,
53   to: [Url; 2],
54   name: String,
55   content: Option<String>,
56   media_type: MediaTypeHtml,
57   source: Option<Source>,
58   url: Option<Url>,
59   image: Option<ImageObject>,
60   pub(crate) comments_enabled: Option<bool>,
61   sensitive: Option<bool>,
62   pub(crate) stickied: Option<bool>,
63   published: DateTime<FixedOffset>,
64   updated: Option<DateTime<FixedOffset>>,
65   #[serde(flatten)]
66   unparsed: Unparsed,
67 }
68
69 impl Page {
70   pub(crate) fn id_unchecked(&self) -> &Url {
71     &self.id
72   }
73   pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
74     verify_domains_match(&self.id, expected_domain)?;
75     Ok(&self.id)
76   }
77
78   /// Only mods can change the post's stickied/locked status. So if either of these is changed from
79   /// the current value, it is a mod action and needs to be verified as such.
80   ///
81   /// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]].
82   pub(crate) async fn is_mod_action(&self, context: &LemmyContext) -> Result<bool, LemmyError> {
83     let old_post = ObjectId::<Post>::new(self.id.clone())
84       .dereference_local(context)
85       .await;
86
87     let is_mod_action = if let Ok(old_post) = old_post {
88       self.stickied != Some(old_post.stickied) || self.comments_enabled != Some(!old_post.locked)
89     } else {
90       false
91     };
92     Ok(is_mod_action)
93   }
94
95   pub(crate) async fn verify(
96     &self,
97     context: &LemmyContext,
98     request_counter: &mut i32,
99   ) -> Result<(), LemmyError> {
100     let community = extract_community(&self.to, context, request_counter).await?;
101
102     check_slurs(&self.name, &context.settings().slur_regex())?;
103     verify_domains_match(self.attributed_to.inner(), &self.id.clone())?;
104     verify_person_in_community(
105       &self.attributed_to,
106       &ObjectId::new(community.actor_id()),
107       context,
108       request_counter,
109     )
110     .await?;
111     Ok(())
112   }
113 }
114
115 #[async_trait::async_trait(?Send)]
116 impl ToApub for Post {
117   type ApubType = Page;
118
119   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
120   async fn to_apub(&self, pool: &DbPool) -> Result<Page, LemmyError> {
121     let creator_id = self.creator_id;
122     let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
123     let community_id = self.community_id;
124     let community = blocking(pool, move |conn| Community::read(conn, community_id)).await??;
125
126     let source = self.body.clone().map(|body| Source {
127       content: body,
128       media_type: MediaTypeMarkdown::Markdown,
129     });
130     let image = self.thumbnail_url.clone().map(|thumb| ImageObject {
131       kind: ImageType::Image,
132       url: thumb.into(),
133     });
134
135     let page = Page {
136       context: lemmy_context(),
137       r#type: PageType::Page,
138       id: self.ap_id.clone().into(),
139       attributed_to: ObjectId::new(creator.actor_id),
140       to: [community.actor_id.into(), public()],
141       name: self.name.clone(),
142       content: self.body.as_ref().map(|b| markdown_to_html(b)),
143       media_type: MediaTypeHtml::Html,
144       source,
145       url: self.url.clone().map(|u| u.into()),
146       image,
147       comments_enabled: Some(!self.locked),
148       sensitive: Some(self.nsfw),
149       stickied: Some(self.stickied),
150       published: convert_datetime(self.published),
151       updated: self.updated.map(convert_datetime),
152       unparsed: Default::default(),
153     };
154     Ok(page)
155   }
156
157   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
158     create_tombstone(
159       self.deleted,
160       self.ap_id.to_owned().into(),
161       self.updated,
162       PageType::Page,
163     )
164   }
165 }
166
167 #[async_trait::async_trait(?Send)]
168 impl FromApub for Post {
169   type ApubType = Page;
170
171   async fn from_apub(
172     page: &Page,
173     context: &LemmyContext,
174     expected_domain: &Url,
175     request_counter: &mut i32,
176   ) -> Result<Post, LemmyError> {
177     // We can't verify the domain in case of mod action, because the mod may be on a different
178     // instance from the post author.
179     let ap_id = if page.is_mod_action(context).await? {
180       page.id_unchecked()
181     } else {
182       page.id(expected_domain)?
183     };
184     let ap_id = Some(ap_id.clone().into());
185     let creator = page
186       .attributed_to
187       .dereference(context, request_counter)
188       .await?;
189     let community = extract_community(&page.to, context, request_counter).await?;
190
191     let thumbnail_url: Option<Url> = page.image.clone().map(|i| i.url);
192     let (metadata_res, pictrs_thumbnail) = if let Some(url) = &page.url {
193       fetch_site_data(context.client(), &context.settings(), Some(url)).await
194     } else {
195       (None, thumbnail_url)
196     };
197     let (embed_title, embed_description, embed_html) = metadata_res
198       .map(|u| (u.title, u.description, u.html))
199       .unwrap_or((None, None, None));
200
201     let body_slurs_removed = page
202       .source
203       .as_ref()
204       .map(|s| remove_slurs(&s.content, &context.settings().slur_regex()));
205     let form = PostForm {
206       name: page.name.clone(),
207       url: page.url.clone().map(|u| u.into()),
208       body: body_slurs_removed,
209       creator_id: creator.id,
210       community_id: community.id,
211       removed: None,
212       locked: page.comments_enabled.map(|e| !e),
213       published: Some(page.published.naive_local()),
214       updated: page.updated.map(|u| u.naive_local()),
215       deleted: None,
216       nsfw: page.sensitive,
217       stickied: page.stickied,
218       embed_title,
219       embed_description,
220       embed_html,
221       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
222       ap_id,
223       local: Some(false),
224     };
225     Ok(blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??)
226   }
227 }