]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Merge pull request 'Use `name` field for post titles instead of `summary` (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       .set_name(self.name.to_owned())
62       // `summary` field for compatibility with lemmy v0.9.9 and older,
63       // TODO: remove this after some time
64       .set_summary(self.name.to_owned())
65       .set_published(convert_datetime(self.published))
66       .set_many_tos(vec![community.actor_id.into_inner(), public()])
67       .set_attributed_to(creator.actor_id.into_inner());
68
69     if let Some(body) = &self.body {
70       set_content_and_source(&mut page, &body)?;
71     }
72
73     // TODO: hacky code because we get self.url == Some("")
74     // https://github.com/LemmyNet/lemmy/issues/602
75     let url = self.url.as_ref().filter(|u| !u.is_empty());
76     if let Some(u) = url {
77       page.set_url(Url::parse(u)?);
78     }
79
80     if let Some(thumbnail_url) = &self.thumbnail_url {
81       let mut image = Image::new();
82       image.set_url(Url::parse(thumbnail_url)?);
83       page.set_image(image.into_any_base()?);
84     }
85
86     if let Some(u) = self.updated {
87       page.set_updated(convert_datetime(u));
88     }
89
90     let ext = PageExtension {
91       comments_enabled: Some(!self.locked),
92       sensitive: Some(self.nsfw),
93       stickied: Some(self.stickied),
94     };
95     Ok(Ext1::new(page, ext))
96   }
97
98   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
99     create_tombstone(
100       self.deleted,
101       self.ap_id.to_owned().into(),
102       self.updated,
103       PageType::Page,
104     )
105   }
106 }
107
108 #[async_trait::async_trait(?Send)]
109 impl FromApub for Post {
110   type ApubType = PageExt;
111
112   /// Converts a `PageExt` to `PostForm`.
113   ///
114   /// If the post's community or creator are not known locally, these are also fetched.
115   async fn from_apub(
116     page: &PageExt,
117     context: &LemmyContext,
118     expected_domain: Url,
119     request_counter: &mut i32,
120   ) -> Result<Post, LemmyError> {
121     check_object_for_community_or_site_ban(page, context, request_counter).await?;
122     get_object_from_apub(page, context, expected_domain, request_counter).await
123   }
124 }
125
126 #[async_trait::async_trait(?Send)]
127 impl FromApubToForm<PageExt> for PostForm {
128   async fn from_apub(
129     page: &PageExt,
130     context: &LemmyContext,
131     expected_domain: Url,
132     request_counter: &mut i32,
133   ) -> Result<PostForm, LemmyError> {
134     let ext = &page.ext_one;
135     let creator_actor_id = page
136       .inner
137       .attributed_to()
138       .as_ref()
139       .context(location_info!())?
140       .as_single_xsd_any_uri()
141       .context(location_info!())?;
142
143     let creator = get_or_fetch_and_upsert_user(creator_actor_id, context, request_counter).await?;
144
145     let community = get_to_community(page, context, request_counter).await?;
146
147     let thumbnail_url = match &page.inner.image() {
148       Some(any_image) => Image::from_any_base(
149         any_image
150           .to_owned()
151           .as_one()
152           .context(location_info!())?
153           .to_owned(),
154       )?
155       .context(location_info!())?
156       .url()
157       .context(location_info!())?
158       .as_single_xsd_any_uri()
159       .map(|u| u.to_string()),
160       None => None,
161     };
162     let url = page
163       .inner
164       .url()
165       .map(|u| u.as_single_xsd_any_uri())
166       .flatten()
167       .map(|s| s.to_string());
168
169     let (iframely_title, iframely_description, iframely_html, pictrs_thumbnail) =
170       if let Some(url) = &url {
171         fetch_iframely_and_pictrs_data(context.client(), Some(url.to_owned())).await
172       } else {
173         (None, None, None, thumbnail_url)
174       };
175
176     let name = page
177       .inner
178       .name()
179       .map(|s| s.map(|s2| s2.to_owned()))
180       // The following is for compatibility with lemmy v0.9.9 and older
181       // TODO: remove it after some time (along with the map above)
182       .or_else(|| page.inner.summary().map(|s| s.to_owned()))
183       .context(location_info!())?
184       .as_single_xsd_string()
185       .context(location_info!())?
186       .to_string();
187     let body = get_source_markdown_value(page)?;
188
189     check_slurs(&name)?;
190     let body_slurs_removed = body.map(|b| remove_slurs(&b));
191     Ok(PostForm {
192       name,
193       url,
194       body: body_slurs_removed,
195       creator_id: creator.id,
196       community_id: community.id,
197       removed: None,
198       locked: ext.comments_enabled.map(|e| !e),
199       published: page
200         .inner
201         .published()
202         .as_ref()
203         .map(|u| u.to_owned().naive_local()),
204       updated: page
205         .inner
206         .updated()
207         .as_ref()
208         .map(|u| u.to_owned().naive_local()),
209       deleted: None,
210       nsfw: ext.sensitive.unwrap_or(false),
211       stickied: ext.stickied.or(Some(false)),
212       embed_title: iframely_title,
213       embed_description: iframely_description,
214       embed_html: iframely_html,
215       thumbnail_url: pictrs_thumbnail,
216       ap_id: Some(check_object_domain(page, expected_domain)?),
217       local: false,
218     })
219   }
220 }