]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Explicitly mark posts and comments as public (ref #1220)
[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_db_queries::{Crud, DbPool};
26 use lemmy_db_schema::source::{
27   community::Community,
28   post::{Post, PostForm},
29   user::User_,
30 };
31 use lemmy_structs::blocking;
32 use lemmy_utils::{
33   location_info,
34   request::fetch_iframely_and_pictrs_data,
35   utils::{check_slurs, convert_datetime, remove_slurs},
36   LemmyError,
37 };
38 use lemmy_websocket::LemmyContext;
39 use url::Url;
40
41 #[async_trait::async_trait(?Send)]
42 impl ToApub for Post {
43   type ApubType = PageExt;
44
45   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
46   async fn to_apub(&self, pool: &DbPool) -> Result<PageExt, LemmyError> {
47     let mut page = ApObject::new(Page::new());
48
49     let creator_id = self.creator_id;
50     let creator = blocking(pool, move |conn| User_::read(conn, creator_id)).await??;
51
52     let community_id = self.community_id;
53     let community = blocking(pool, move |conn| Community::read(conn, community_id)).await??;
54
55     page
56       // Not needed when the Post is embedded in a collection (like for community outbox)
57       // TODO: need to set proper context defining sensitive/commentsEnabled fields
58       // https://git.asonix.dog/Aardwolf/activitystreams/issues/5
59       .set_many_contexts(lemmy_context()?)
60       .set_id(self.ap_id.to_owned().into_inner())
61       // Use summary field to be consistent with mastodon content warning.
62       // https://mastodon.xyz/@Louisa/103987265222901387.json
63       .set_summary(self.name.to_owned())
64       .set_published(convert_datetime(self.published))
65       .set_many_tos(vec![community.actor_id.into_inner(), public()])
66       .set_attributed_to(creator.actor_id.into_inner());
67
68     if let Some(body) = &self.body {
69       set_content_and_source(&mut page, &body)?;
70     }
71
72     // TODO: hacky code because we get self.url == Some("")
73     // https://github.com/LemmyNet/lemmy/issues/602
74     let url = self.url.as_ref().filter(|u| !u.is_empty());
75     if let Some(u) = url {
76       page.set_url(Url::parse(u)?);
77     }
78
79     if let Some(thumbnail_url) = &self.thumbnail_url {
80       let mut image = Image::new();
81       image.set_url(Url::parse(thumbnail_url)?);
82       page.set_image(image.into_any_base()?);
83     }
84
85     if let Some(u) = self.updated {
86       page.set_updated(convert_datetime(u));
87     }
88
89     let ext = PageExtension {
90       comments_enabled: Some(!self.locked),
91       sensitive: Some(self.nsfw),
92       stickied: Some(self.stickied),
93     };
94     Ok(Ext1::new(page, ext))
95   }
96
97   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
98     create_tombstone(
99       self.deleted,
100       self.ap_id.to_owned().into(),
101       self.updated,
102       PageType::Page,
103     )
104   }
105 }
106
107 #[async_trait::async_trait(?Send)]
108 impl FromApub for Post {
109   type ApubType = PageExt;
110
111   /// Converts a `PageExt` to `PostForm`.
112   ///
113   /// If the post's community or creator are not known locally, these are also fetched.
114   async fn from_apub(
115     page: &PageExt,
116     context: &LemmyContext,
117     expected_domain: Url,
118     request_counter: &mut i32,
119   ) -> Result<Post, LemmyError> {
120     check_object_for_community_or_site_ban(page, context, request_counter).await?;
121     get_object_from_apub(page, context, expected_domain, request_counter).await
122   }
123 }
124
125 #[async_trait::async_trait(?Send)]
126 impl FromApubToForm<PageExt> for PostForm {
127   async fn from_apub(
128     page: &PageExt,
129     context: &LemmyContext,
130     expected_domain: Url,
131     request_counter: &mut i32,
132   ) -> Result<PostForm, LemmyError> {
133     let ext = &page.ext_one;
134     let creator_actor_id = page
135       .inner
136       .attributed_to()
137       .as_ref()
138       .context(location_info!())?
139       .as_single_xsd_any_uri()
140       .context(location_info!())?;
141
142     let creator = get_or_fetch_and_upsert_user(creator_actor_id, context, request_counter).await?;
143
144     let community = get_to_community(page, context, request_counter).await?;
145
146     let thumbnail_url = match &page.inner.image() {
147       Some(any_image) => Image::from_any_base(
148         any_image
149           .to_owned()
150           .as_one()
151           .context(location_info!())?
152           .to_owned(),
153       )?
154       .context(location_info!())?
155       .url()
156       .context(location_info!())?
157       .as_single_xsd_any_uri()
158       .map(|u| u.to_string()),
159       None => None,
160     };
161     let url = page
162       .inner
163       .url()
164       .map(|u| u.as_single_xsd_any_uri())
165       .flatten()
166       .map(|s| s.to_string());
167
168     let (iframely_title, iframely_description, iframely_html, pictrs_thumbnail) =
169       if let Some(url) = &url {
170         fetch_iframely_and_pictrs_data(context.client(), Some(url.to_owned())).await
171       } else {
172         (None, None, None, thumbnail_url)
173       };
174
175     let name = page
176       .inner
177       .summary()
178       .as_ref()
179       .context(location_info!())?
180       .as_single_xsd_string()
181       .context(location_info!())?
182       .to_string();
183     let body = get_source_markdown_value(page)?;
184
185     check_slurs(&name)?;
186     let body_slurs_removed = body.map(|b| remove_slurs(&b));
187     Ok(PostForm {
188       name,
189       url,
190       body: body_slurs_removed,
191       creator_id: creator.id,
192       community_id: community.id,
193       removed: None,
194       locked: ext.comments_enabled.map(|e| !e),
195       published: page
196         .inner
197         .published()
198         .as_ref()
199         .map(|u| u.to_owned().naive_local()),
200       updated: page
201         .inner
202         .updated()
203         .as_ref()
204         .map(|u| u.to_owned().naive_local()),
205       deleted: None,
206       nsfw: ext.sensitive.unwrap_or(false),
207       stickied: ext.stickied.or(Some(false)),
208       embed_title: iframely_title,
209       embed_description: iframely_description,
210       embed_html: iframely_html,
211       thumbnail_url: pictrs_thumbnail,
212       ap_id: Some(check_object_domain(page, expected_domain)?),
213       local: false,
214     })
215   }
216 }