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