]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Update activitystreams to 0.7.0-alpha.11
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   extensions::{context::lemmy_context, page_extension::PageExtension},
3   fetcher::user::get_or_fetch_and_upsert_user,
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     post::{Post, PostForm},
32     user::User_,
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| User_::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 = get_or_fetch_and_upsert_user(creator_actor_id, context, request_counter).await?;
146
147     let community = get_to_community(page, context, request_counter).await?;
148
149     let thumbnail_url: Option<Url> = match &page.inner.image() {
150       Some(any_image) => Image::from_any_base(
151         any_image
152           .to_owned()
153           .as_one()
154           .context(location_info!())?
155           .to_owned(),
156       )?
157       .context(location_info!())?
158       .url()
159       .context(location_info!())?
160       .as_single_xsd_any_uri()
161       .map(|url| url.to_owned()),
162       None => None,
163     };
164     let url = page
165       .inner
166       .url()
167       .map(|u| u.as_single_xsd_any_uri())
168       .flatten()
169       .map(|u| u.to_owned());
170
171     let (iframely_title, iframely_description, iframely_html, pictrs_thumbnail) =
172       if let Some(url) = &url {
173         fetch_iframely_and_pictrs_data(context.client(), Some(url)).await
174       } else {
175         (None, None, None, thumbnail_url)
176       };
177
178     let name = page
179       .inner
180       .name()
181       // The following is for compatibility with lemmy v0.9.9 and older
182       // TODO: remove it after some time (along with the map above)
183       .or_else(|| page.inner.summary())
184       .context(location_info!())?
185       .as_single_xsd_string()
186       .context(location_info!())?
187       .to_string();
188     let body = get_source_markdown_value(page)?;
189
190     check_slurs(&name)?;
191     let body_slurs_removed = body.map(|b| remove_slurs(&b));
192     Ok(PostForm {
193       name,
194       url: url.map(|u| u.into()),
195       body: body_slurs_removed,
196       creator_id: creator.id,
197       community_id: community.id,
198       removed: None,
199       locked: ext.comments_enabled.map(|e| !e),
200       published: page
201         .inner
202         .published()
203         .as_ref()
204         .map(|u| u.to_owned().naive_local()),
205       updated: page
206         .inner
207         .updated()
208         .as_ref()
209         .map(|u| u.to_owned().naive_local()),
210       deleted: None,
211       nsfw: ext.sensitive.unwrap_or(false),
212       stickied: ext.stickied.or(Some(false)),
213       embed_title: iframely_title,
214       embed_description: iframely_description,
215       embed_html: iframely_html,
216       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
217       ap_id: Some(check_object_domain(page, expected_domain)?),
218       local: false,
219     })
220   }
221 }