]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Merge branch 'main' into move_matrix_and_admin_to_person
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   extensions::{context::lemmy_context, page_extension::PageExtension},
3   fetcher::person::get_or_fetch_and_upsert_person,
4   objects::{
5     check_object_domain,
6     check_object_for_community_or_site_ban,
7     create_tombstone,
8     get_object_from_apub,
9     get_source_markdown_value,
10     get_to_community,
11     set_content_and_source,
12     FromApub,
13     FromApubToForm,
14     ToApub,
15   },
16   PageExt,
17 };
18 use activitystreams::{
19   object::{kind::PageType, ApObject, Image, Page, Tombstone},
20   prelude::*,
21   public,
22 };
23 use activitystreams_ext::Ext1;
24 use anyhow::Context;
25 use lemmy_api_structs::blocking;
26 use lemmy_db_queries::{Crud, DbPool};
27 use lemmy_db_schema::{
28   self,
29   source::{
30     community::Community,
31     person::Person,
32     post::{Post, PostForm},
33   },
34 };
35 use lemmy_utils::{
36   location_info,
37   request::fetch_iframely_and_pictrs_data,
38   utils::{check_slurs, convert_datetime, remove_slurs},
39   LemmyError,
40 };
41 use lemmy_websocket::LemmyContext;
42 use url::Url;
43
44 #[async_trait::async_trait(?Send)]
45 impl ToApub for Post {
46   type ApubType = PageExt;
47
48   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
49   async fn to_apub(&self, pool: &DbPool) -> Result<PageExt, LemmyError> {
50     let mut page = ApObject::new(Page::new());
51
52     let creator_id = self.creator_id;
53     let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
54
55     let community_id = self.community_id;
56     let community = blocking(pool, move |conn| Community::read(conn, community_id)).await??;
57
58     page
59       // Not needed when the Post is embedded in a collection (like for community outbox)
60       // TODO: need to set proper context defining sensitive/commentsEnabled fields
61       // https://git.asonix.dog/Aardwolf/activitystreams/issues/5
62       .set_many_contexts(lemmy_context()?)
63       .set_id(self.ap_id.to_owned().into_inner())
64       .set_name(self.name.to_owned())
65       // `summary` field for compatibility with lemmy v0.9.9 and older,
66       // TODO: remove this after some time
67       .set_summary(self.name.to_owned())
68       .set_published(convert_datetime(self.published))
69       .set_many_tos(vec![community.actor_id.into_inner(), public()])
70       .set_attributed_to(creator.actor_id.into_inner());
71
72     if let Some(body) = &self.body {
73       set_content_and_source(&mut page, &body)?;
74     }
75
76     if let Some(url) = &self.url {
77       page.set_url::<Url>(url.to_owned().into());
78     }
79
80     if let Some(thumbnail_url) = &self.thumbnail_url {
81       let mut image = Image::new();
82       image.set_url::<Url>(thumbnail_url.to_owned().into());
83       page.set_image(image.into_any_base()?);
84     }
85
86     if let Some(u) = self.updated {
87       page.set_updated(convert_datetime(u));
88     }
89
90     let ext = PageExtension {
91       comments_enabled: Some(!self.locked),
92       sensitive: Some(self.nsfw),
93       stickied: Some(self.stickied),
94     };
95     Ok(Ext1::new(page, ext))
96   }
97
98   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
99     create_tombstone(
100       self.deleted,
101       self.ap_id.to_owned().into(),
102       self.updated,
103       PageType::Page,
104     )
105   }
106 }
107
108 #[async_trait::async_trait(?Send)]
109 impl FromApub for Post {
110   type ApubType = PageExt;
111
112   /// Converts a `PageExt` to `PostForm`.
113   ///
114   /// If the post's community or creator are not known locally, these are also fetched.
115   async fn from_apub(
116     page: &PageExt,
117     context: &LemmyContext,
118     expected_domain: Url,
119     request_counter: &mut i32,
120   ) -> Result<Post, LemmyError> {
121     let post: Post = get_object_from_apub(page, context, expected_domain, request_counter).await?;
122     check_object_for_community_or_site_ban(page, post.community_id, context, request_counter)
123       .await?;
124     Ok(post)
125   }
126 }
127
128 #[async_trait::async_trait(?Send)]
129 impl FromApubToForm<PageExt> for PostForm {
130   async fn from_apub(
131     page: &PageExt,
132     context: &LemmyContext,
133     expected_domain: Url,
134     request_counter: &mut i32,
135   ) -> Result<PostForm, LemmyError> {
136     let ext = &page.ext_one;
137     let creator_actor_id = page
138       .inner
139       .attributed_to()
140       .as_ref()
141       .context(location_info!())?
142       .as_single_xsd_any_uri()
143       .context(location_info!())?;
144
145     let creator =
146       get_or_fetch_and_upsert_person(creator_actor_id, context, request_counter).await?;
147
148     let community = get_to_community(page, context, request_counter).await?;
149
150     let thumbnail_url: Option<Url> = match &page.inner.image() {
151       Some(any_image) => Image::from_any_base(
152         any_image
153           .to_owned()
154           .as_one()
155           .context(location_info!())?
156           .to_owned(),
157       )?
158       .context(location_info!())?
159       .url()
160       .context(location_info!())?
161       .as_single_xsd_any_uri()
162       .map(|url| url.to_owned()),
163       None => None,
164     };
165     let url = page
166       .inner
167       .url()
168       .map(|u| u.as_single_xsd_any_uri())
169       .flatten()
170       .map(|u| u.to_owned());
171
172     let (iframely_title, iframely_description, iframely_html, pictrs_thumbnail) =
173       if let Some(url) = &url {
174         fetch_iframely_and_pictrs_data(context.client(), Some(url)).await
175       } else {
176         (None, None, None, thumbnail_url)
177       };
178
179     let name = page
180       .inner
181       .name()
182       .map(|s| s.map(|s2| s2.to_owned()))
183       // The following is for compatibility with lemmy v0.9.9 and older
184       // TODO: remove it after some time (along with the map above)
185       .or_else(|| page.inner.summary().map(|s| s.to_owned()))
186       .context(location_info!())?
187       .as_single_xsd_string()
188       .context(location_info!())?
189       .to_string();
190     let body = get_source_markdown_value(page)?;
191
192     check_slurs(&name)?;
193     let body_slurs_removed = body.map(|b| remove_slurs(&b));
194     Ok(PostForm {
195       name,
196       url: url.map(|u| u.into()),
197       body: body_slurs_removed,
198       creator_id: creator.id,
199       community_id: community.id,
200       removed: None,
201       locked: ext.comments_enabled.map(|e| !e),
202       published: page
203         .inner
204         .published()
205         .as_ref()
206         .map(|u| u.to_owned().naive_local()),
207       updated: page
208         .inner
209         .updated()
210         .as_ref()
211         .map(|u| u.to_owned().naive_local()),
212       deleted: None,
213       nsfw: ext.sensitive.unwrap_or(false),
214       stickied: ext.stickied.or(Some(false)),
215       embed_title: iframely_title,
216       embed_description: iframely_description,
217       embed_html: iframely_html,
218       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
219       ap_id: Some(check_object_domain(page, expected_domain)?),
220       local: Some(false),
221     })
222   }
223 }