]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
c18647dd1518d670483b698a8c6856f76d572920
[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_queries::{source::post::Post_, Crud, DbPool};
25 use lemmy_db_schema::{
26   self,
27   source::{
28     community::Community,
29     person::Person,
30     post::{Post, PostForm},
31   },
32 };
33 use lemmy_utils::{
34   request::fetch_site_data,
35   utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
36   LemmyError,
37 };
38 use lemmy_websocket::LemmyContext;
39 use serde::{Deserialize, Serialize};
40 use serde_with::skip_serializing_none;
41 use url::Url;
42
43 #[skip_serializing_none]
44 #[derive(Clone, Debug, Deserialize, Serialize)]
45 #[serde(rename_all = "camelCase")]
46 pub struct Page {
47   #[serde(rename = "@context")]
48   context: OneOrMany<AnyBase>,
49   r#type: PageType,
50   id: Url,
51   pub(crate) attributed_to: ObjectId<Person>,
52   to: [Url; 2],
53   name: String,
54   content: Option<String>,
55   media_type: 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: 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::<Post>::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 = extract_community(&self.to, 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(
104       &self.attributed_to,
105       &ObjectId::new(community.actor_id()),
106       context,
107       request_counter,
108     )
109     .await?;
110     Ok(())
111   }
112 }
113
114 #[async_trait::async_trait(?Send)]
115 impl ToApub for Post {
116   type ApubType = Page;
117
118   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
119   async fn to_apub(&self, pool: &DbPool) -> Result<Page, LemmyError> {
120     let creator_id = self.creator_id;
121     let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
122     let community_id = self.community_id;
123     let community = blocking(pool, move |conn| Community::read(conn, community_id)).await??;
124
125     let source = self.body.clone().map(|body| Source {
126       content: body,
127       media_type: MediaTypeMarkdown::Markdown,
128     });
129     let image = self.thumbnail_url.clone().map(|thumb| ImageObject {
130       kind: ImageType::Image,
131       url: thumb.into(),
132     });
133
134     let page = Page {
135       context: lemmy_context(),
136       r#type: PageType::Page,
137       id: self.ap_id.clone().into(),
138       attributed_to: ObjectId::new(creator.actor_id),
139       to: [community.actor_id.into(), public()],
140       name: self.name.clone(),
141       content: self.body.as_ref().map(|b| markdown_to_html(b)),
142       media_type: MediaTypeHtml::Html,
143       source,
144       url: self.url.clone().map(|u| u.into()),
145       image,
146       comments_enabled: Some(!self.locked),
147       sensitive: Some(self.nsfw),
148       stickied: Some(self.stickied),
149       published: convert_datetime(self.published),
150       updated: self.updated.map(convert_datetime),
151       unparsed: Default::default(),
152     };
153     Ok(page)
154   }
155
156   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
157     create_tombstone(
158       self.deleted,
159       self.ap_id.to_owned().into(),
160       self.updated,
161       PageType::Page,
162     )
163   }
164 }
165
166 #[async_trait::async_trait(?Send)]
167 impl FromApub for Post {
168   type ApubType = Page;
169
170   async fn from_apub(
171     page: &Page,
172     context: &LemmyContext,
173     expected_domain: &Url,
174     request_counter: &mut i32,
175   ) -> Result<Post, LemmyError> {
176     // We can't verify the domain in case of mod action, because the mod may be on a different
177     // instance from the post author.
178     let ap_id = if page.is_mod_action(context).await? {
179       page.id_unchecked()
180     } else {
181       page.id(expected_domain)?
182     };
183     let ap_id = Some(ap_id.clone().into());
184     let creator = page
185       .attributed_to
186       .dereference(context, request_counter)
187       .await?;
188     let community = extract_community(&page.to, context, request_counter).await?;
189
190     let thumbnail_url: Option<Url> = page.image.clone().map(|i| i.url);
191     let (metadata_res, pictrs_thumbnail) = if let Some(url) = &page.url {
192       fetch_site_data(context.client(), &context.settings(), Some(url)).await
193     } else {
194       (None, thumbnail_url)
195     };
196     let (embed_title, embed_description, embed_html) = metadata_res
197       .map(|u| (u.title, u.description, u.html))
198       .unwrap_or((None, None, None));
199
200     let body_slurs_removed = page
201       .source
202       .as_ref()
203       .map(|s| remove_slurs(&s.content, &context.settings().slur_regex()));
204     let form = PostForm {
205       name: page.name.clone(),
206       url: page.url.clone().map(|u| u.into()),
207       body: body_slurs_removed,
208       creator_id: creator.id,
209       community_id: community.id,
210       removed: None,
211       locked: page.comments_enabled.map(|e| !e),
212       published: Some(page.published.naive_local()),
213       updated: page.updated.map(|u| u.naive_local()),
214       deleted: None,
215       nsfw: page.sensitive,
216       stickied: page.stickied,
217       embed_title,
218       embed_description,
219       embed_html,
220       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
221       ap_id,
222       local: Some(false),
223     };
224     Ok(blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??)
225   }
226 }