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