]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Rewrite fetcher (#1792)
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::{extract_community, verify_person_in_community},
3   extensions::context::lemmy_context,
4   fetcher::object_id::ObjectId,
5   objects::{create_tombstone, FromApub, ImageObject, Source, ToApub},
6   ActorType,
7 };
8 use activitystreams::{
9   base::AnyBase,
10   object::{
11     kind::{ImageType, PageType},
12     Tombstone,
13   },
14   primitives::OneOrMany,
15   public,
16   unparsed::Unparsed,
17 };
18 use chrono::{DateTime, FixedOffset};
19 use lemmy_api_common::blocking;
20 use lemmy_apub_lib::{
21   values::{MediaTypeHtml, MediaTypeMarkdown},
22   verify_domains_match,
23 };
24 use lemmy_db_queries::{source::post::Post_, ApubObject, 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, pool: &DbPool) -> Result<bool, LemmyError> {
82     let post_id = self.id.clone();
83     let old_post = blocking(pool, move |conn| {
84       Post::read_from_apub_id(conn, &post_id.into())
85     })
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)?;
104     verify_domains_match(self.attributed_to.inner(), &self.id)?;
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 #[async_trait::async_trait(?Send)]
117 impl ToApub for Post {
118   type ApubType = Page;
119
120   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
121   async fn to_apub(&self, pool: &DbPool) -> Result<Page, LemmyError> {
122     let creator_id = self.creator_id;
123     let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
124     let community_id = self.community_id;
125     let community = blocking(pool, move |conn| Community::read(conn, community_id)).await??;
126
127     let source = self.body.clone().map(|body| Source {
128       content: body,
129       media_type: MediaTypeMarkdown::Markdown,
130     });
131     let image = self.thumbnail_url.clone().map(|thumb| ImageObject {
132       kind: ImageType::Image,
133       url: thumb.into(),
134     });
135
136     let page = Page {
137       context: lemmy_context(),
138       r#type: PageType::Page,
139       id: self.ap_id.clone().into(),
140       attributed_to: ObjectId::new(creator.actor_id),
141       to: [community.actor_id.into(), public()],
142       name: self.name.clone(),
143       content: self.body.as_ref().map(|b| markdown_to_html(b)),
144       media_type: MediaTypeHtml::Html,
145       source,
146       url: self.url.clone().map(|u| u.into()),
147       image,
148       comments_enabled: Some(!self.locked),
149       sensitive: Some(self.nsfw),
150       stickied: Some(self.stickied),
151       published: convert_datetime(self.published),
152       updated: self.updated.map(convert_datetime),
153       unparsed: Default::default(),
154     };
155     Ok(page)
156   }
157
158   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
159     create_tombstone(
160       self.deleted,
161       self.ap_id.to_owned().into(),
162       self.updated,
163       PageType::Page,
164     )
165   }
166 }
167
168 #[async_trait::async_trait(?Send)]
169 impl FromApub for Post {
170   type ApubType = Page;
171
172   async fn from_apub(
173     page: &Page,
174     context: &LemmyContext,
175     expected_domain: &Url,
176     request_counter: &mut i32,
177   ) -> Result<Post, LemmyError> {
178     // We can't verify the domain in case of mod action, because the mod may be on a different
179     // instance from the post author.
180     let ap_id = if page.is_mod_action(context.pool()).await? {
181       page.id_unchecked()
182     } else {
183       page.id(expected_domain)?
184     };
185     let ap_id = Some(ap_id.clone().into());
186     let creator = page
187       .attributed_to
188       .dereference(context, request_counter)
189       .await?;
190     let community = extract_community(&page.to, context, request_counter).await?;
191
192     let thumbnail_url: Option<Url> = page.image.clone().map(|i| i.url);
193     let (metadata_res, pictrs_thumbnail) = if let Some(url) = &page.url {
194       fetch_site_data(context.client(), Some(url)).await
195     } else {
196       (None, thumbnail_url)
197     };
198     let (embed_title, embed_description, embed_html) = metadata_res
199       .map(|u| (u.title, u.description, u.html))
200       .unwrap_or((None, None, None));
201
202     let body_slurs_removed = page.source.as_ref().map(|s| remove_slurs(&s.content));
203     let form = PostForm {
204       name: page.name.clone(),
205       url: page.url.clone().map(|u| u.into()),
206       body: body_slurs_removed,
207       creator_id: creator.id,
208       community_id: community.id,
209       removed: None,
210       locked: page.comments_enabled.map(|e| !e),
211       published: Some(page.published.naive_local()),
212       updated: page.updated.map(|u| u.naive_local()),
213       deleted: None,
214       nsfw: page.sensitive,
215       stickied: page.stickied,
216       embed_title,
217       embed_description,
218       embed_html,
219       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
220       ap_id,
221       local: Some(false),
222     };
223     Ok(blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??)
224   }
225 }