]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Move most code into crates/ subfolder
[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.parse::<Url>()?)
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)
64       .set_attributed_to(creator.actor_id);
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: !self.locked,
89       sensitive: self.nsfw,
90       stickied: self.stickied,
91     };
92     Ok(Ext1::new(page, ext))
93   }
94
95   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
96     create_tombstone(self.deleted, &self.ap_id, self.updated, PageType::Page)
97   }
98 }
99
100 #[async_trait::async_trait(?Send)]
101 impl FromApub for Post {
102   type ApubType = PageExt;
103
104   /// Converts a `PageExt` to `PostForm`.
105   ///
106   /// If the post's community or creator are not known locally, these are also fetched.
107   async fn from_apub(
108     page: &PageExt,
109     context: &LemmyContext,
110     expected_domain: Url,
111     request_counter: &mut i32,
112   ) -> Result<Post, LemmyError> {
113     check_object_for_community_or_site_ban(page, context, request_counter).await?;
114     get_object_from_apub(page, context, expected_domain, request_counter).await
115   }
116 }
117
118 #[async_trait::async_trait(?Send)]
119 impl FromApubToForm<PageExt> for PostForm {
120   async fn from_apub(
121     page: &PageExt,
122     context: &LemmyContext,
123     expected_domain: Url,
124     request_counter: &mut i32,
125   ) -> Result<PostForm, LemmyError> {
126     let ext = &page.ext_one;
127     let creator_actor_id = page
128       .inner
129       .attributed_to()
130       .as_ref()
131       .context(location_info!())?
132       .as_single_xsd_any_uri()
133       .context(location_info!())?;
134
135     let creator = get_or_fetch_and_upsert_user(creator_actor_id, context, request_counter).await?;
136
137     let community_actor_id = page
138       .inner
139       .to()
140       .as_ref()
141       .context(location_info!())?
142       .as_single_xsd_any_uri()
143       .context(location_info!())?;
144
145     let community =
146       get_or_fetch_and_upsert_community(community_actor_id, context, request_counter).await?;
147
148     let thumbnail_url = match &page.inner.image() {
149       Some(any_image) => Image::from_any_base(
150         any_image
151           .to_owned()
152           .as_one()
153           .context(location_info!())?
154           .to_owned(),
155       )?
156       .context(location_info!())?
157       .url()
158       .context(location_info!())?
159       .as_single_xsd_any_uri()
160       .map(|u| u.to_string()),
161       None => None,
162     };
163     let url = page
164       .inner
165       .url()
166       .map(|u| u.as_single_xsd_any_uri())
167       .flatten()
168       .map(|s| s.to_string());
169
170     let (iframely_title, iframely_description, iframely_html, pictrs_thumbnail) =
171       if let Some(url) = &url {
172         fetch_iframely_and_pictrs_data(context.client(), Some(url.to_owned())).await
173       } else {
174         (None, None, None, thumbnail_url)
175       };
176
177     let name = page
178       .inner
179       .summary()
180       .as_ref()
181       .context(location_info!())?
182       .as_single_xsd_string()
183       .context(location_info!())?
184       .to_string();
185     let body = get_source_markdown_value(page)?;
186
187     check_slurs(&name)?;
188     let body_slurs_removed = body.map(|b| remove_slurs(&b));
189     Ok(PostForm {
190       name,
191       url,
192       body: body_slurs_removed,
193       creator_id: creator.id,
194       community_id: community.id,
195       removed: None,
196       locked: Some(!ext.comments_enabled),
197       published: page
198         .inner
199         .published()
200         .as_ref()
201         .map(|u| u.to_owned().naive_local()),
202       updated: page
203         .inner
204         .updated()
205         .as_ref()
206         .map(|u| u.to_owned().naive_local()),
207       deleted: None,
208       nsfw: ext.sensitive,
209       stickied: Some(ext.stickied),
210       embed_title: iframely_title,
211       embed_description: iframely_description,
212       embed_html: iframely_html,
213       thumbnail_url: pictrs_thumbnail,
214       ap_id: Some(check_object_domain(page, expected_domain)?),
215       local: false,
216     })
217   }
218 }