]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Making more fields optional in the 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   get_community_from_to_or_cc,
6   objects::{
7     check_object_domain,
8     check_object_for_community_or_site_ban,
9     create_tombstone,
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 community = get_community_from_to_or_cc(page, context, request_counter).await?;
147     let ap_id = if mod_action_allowed {
148       let id = page.id_unchecked().context(location_info!())?;
149       check_is_apub_id_valid(id, community.local)?;
150       id.to_owned().into()
151     } else {
152       check_object_domain(page, expected_domain, community.local)?
153     };
154     let ext = &page.ext_one;
155     let creator_actor_id = page
156       .inner
157       .attributed_to()
158       .as_ref()
159       .context(location_info!())?
160       .as_single_xsd_any_uri()
161       .context(location_info!())?;
162
163     let creator =
164       get_or_fetch_and_upsert_person(creator_actor_id, context, request_counter).await?;
165
166     let thumbnail_url: Option<Url> = match &page.inner.image() {
167       Some(any_image) => Image::from_any_base(
168         any_image
169           .to_owned()
170           .as_one()
171           .context(location_info!())?
172           .to_owned(),
173       )?
174       .context(location_info!())?
175       .url()
176       .context(location_info!())?
177       .as_single_xsd_any_uri()
178       .map(|url| url.to_owned()),
179       None => None,
180     };
181     let url = page
182       .inner
183       .url()
184       .map(|u| u.as_single_xsd_any_uri())
185       .flatten()
186       .map(|u| u.to_owned());
187
188     let (iframely_title, iframely_description, iframely_html, pictrs_thumbnail) =
189       if let Some(url) = &url {
190         fetch_iframely_and_pictrs_data(context.client(), Some(url)).await
191       } else {
192         (None, None, None, thumbnail_url)
193       };
194
195     let name = page
196       .inner
197       .name()
198       // The following is for compatibility with lemmy v0.9.9 and older
199       // TODO: remove it after some time (along with the map above)
200       .or_else(|| page.inner.summary())
201       .context(location_info!())?
202       .as_single_xsd_string()
203       .context(location_info!())?
204       .to_string();
205     let body = get_source_markdown_value(page)?;
206
207     // TODO: expected_domain is wrong in this case, because it simply takes the domain of the actor
208     //       maybe we need to take id_unchecked() if the activity is from community to user?
209     //       why did this work before? -> i dont think it did?
210     //       -> try to make expected_domain optional and set it null if it is a mod action
211
212     check_slurs(&name)?;
213     let body_slurs_removed = body.map(|b| remove_slurs(&b));
214     Ok(PostForm {
215       name,
216       url: url.map(|u| u.into()),
217       body: body_slurs_removed,
218       creator_id: creator.id,
219       community_id: community.id,
220       removed: None,
221       locked: ext.comments_enabled.map(|e| !e),
222       published: page
223         .inner
224         .published()
225         .as_ref()
226         .map(|u| u.to_owned().naive_local()),
227       updated: page
228         .inner
229         .updated()
230         .as_ref()
231         .map(|u| u.to_owned().naive_local()),
232       deleted: None,
233       nsfw: ext.sensitive,
234       stickied: ext.stickied,
235       embed_title: iframely_title,
236       embed_description: iframely_description,
237       embed_html: iframely_html,
238       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
239       ap_id: Some(ap_id),
240       local: Some(false),
241     })
242   }
243 }