]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Fix code to allow sticky/lock from remote moderators
[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::user::get_or_fetch_and_upsert_user,
5   objects::{
6     check_object_domain,
7     check_object_for_community_or_site_ban,
8     create_tombstone,
9     get_object_from_apub,
10     get_source_markdown_value,
11     get_to_community,
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_structs::blocking;
27 use lemmy_db_queries::{Crud, DbPool};
28 use lemmy_db_schema::{
29   self,
30   source::{
31     community::Community,
32     post::{Post, PostForm},
33     user::User_,
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| User_::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: Option<Url>,
120     request_counter: &mut i32,
121   ) -> Result<Post, LemmyError> {
122     let post: Post = get_object_from_apub(page, context, expected_domain, request_counter).await?;
123     check_object_for_community_or_site_ban(page, post.community_id, context, request_counter)
124       .await?;
125     Ok(post)
126   }
127 }
128
129 #[async_trait::async_trait(?Send)]
130 impl FromApubToForm<PageExt> for PostForm {
131   async fn from_apub(
132     page: &PageExt,
133     context: &LemmyContext,
134     expected_domain: Option<Url>,
135     request_counter: &mut i32,
136   ) -> Result<PostForm, LemmyError> {
137     let ap_id = match expected_domain {
138       Some(e) => check_object_domain(page, e)?,
139       None => {
140         let id = page.id_unchecked().context(location_info!())?;
141         check_is_apub_id_valid(id)?;
142         id.to_owned().into()
143       }
144     };
145     let ext = &page.ext_one;
146     let creator_actor_id = page
147       .inner
148       .attributed_to()
149       .as_ref()
150       .context(location_info!())?
151       .as_single_xsd_any_uri()
152       .context(location_info!())?;
153
154     let creator = get_or_fetch_and_upsert_user(creator_actor_id, context, request_counter).await?;
155
156     let community = get_to_community(page, context, request_counter).await?;
157
158     let thumbnail_url: Option<Url> = match &page.inner.image() {
159       Some(any_image) => Image::from_any_base(
160         any_image
161           .to_owned()
162           .as_one()
163           .context(location_info!())?
164           .to_owned(),
165       )?
166       .context(location_info!())?
167       .url()
168       .context(location_info!())?
169       .as_single_xsd_any_uri()
170       .map(|url| url.to_owned()),
171       None => None,
172     };
173     let url = page
174       .inner
175       .url()
176       .map(|u| u.as_single_xsd_any_uri())
177       .flatten()
178       .map(|u| u.to_owned());
179
180     let (iframely_title, iframely_description, iframely_html, pictrs_thumbnail) =
181       if let Some(url) = &url {
182         fetch_iframely_and_pictrs_data(context.client(), Some(url)).await
183       } else {
184         (None, None, None, thumbnail_url)
185       };
186
187     let name = page
188       .inner
189       .name()
190       // The following is for compatibility with lemmy v0.9.9 and older
191       // TODO: remove it after some time (along with the map above)
192       .or_else(|| page.inner.summary())
193       .context(location_info!())?
194       .as_single_xsd_string()
195       .context(location_info!())?
196       .to_string();
197     let body = get_source_markdown_value(page)?;
198
199     // TODO: expected_domain is wrong in this case, because it simply takes the domain of the actor
200     //       maybe we need to take id_unchecked() if the activity is from community to user?
201     //       why did this work before? -> i dont think it did?
202     //       -> try to make expected_domain optional and set it null if it is a mod action
203
204     check_slurs(&name)?;
205     let body_slurs_removed = body.map(|b| remove_slurs(&b));
206     Ok(PostForm {
207       name,
208       url: url.map(|u| u.into()),
209       body: body_slurs_removed,
210       creator_id: creator.id,
211       community_id: community.id,
212       removed: None,
213       locked: ext.comments_enabled.map(|e| !e),
214       published: page
215         .inner
216         .published()
217         .as_ref()
218         .map(|u| u.to_owned().naive_local()),
219       updated: page
220         .inner
221         .updated()
222         .as_ref()
223         .map(|u| u.to_owned().naive_local()),
224       deleted: None,
225       nsfw: ext.sensitive.unwrap_or(false),
226       stickied: ext.stickied.or(Some(false)),
227       embed_title: iframely_title,
228       embed_description: iframely_description,
229       embed_html: iframely_html,
230       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
231       ap_id: Some(ap_id),
232       local: false,
233     })
234   }
235 }