]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Tag posts and comments with language (fixes #440) (#2269)
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::{verify_is_public, verify_person_in_community},
3   check_apub_id_valid_with_strictness,
4   local_instance,
5   objects::{read_from_string_or_source_opt, verify_is_remote_object},
6   protocol::{
7     objects::page::{Attachment, AttributedTo, LanguageTag, Page, PageType},
8     ImageObject,
9     Source,
10   },
11 };
12 use activitypub_federation::{
13   core::object_id::ObjectId,
14   deser::values::MediaTypeMarkdownOrHtml,
15   traits::ApubObject,
16   utils::verify_domains_match,
17 };
18 use activitystreams_kinds::public;
19 use chrono::NaiveDateTime;
20 use lemmy_api_common::{request::fetch_site_data, utils::blocking};
21 use lemmy_db_schema::{
22   self,
23   source::{
24     community::Community,
25     language::Language,
26     moderator::{ModLockPost, ModLockPostForm, ModStickyPost, ModStickyPostForm},
27     person::Person,
28     post::{Post, PostForm},
29   },
30   traits::Crud,
31 };
32 use lemmy_utils::{
33   error::LemmyError,
34   utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
35 };
36 use lemmy_websocket::LemmyContext;
37 use std::ops::Deref;
38 use url::Url;
39
40 #[derive(Clone, Debug)]
41 pub struct ApubPost(Post);
42
43 impl Deref for ApubPost {
44   type Target = Post;
45   fn deref(&self) -> &Self::Target {
46     &self.0
47   }
48 }
49
50 impl From<Post> for ApubPost {
51   fn from(p: Post) -> Self {
52     ApubPost(p)
53   }
54 }
55
56 #[async_trait::async_trait(?Send)]
57 impl ApubObject for ApubPost {
58   type DataType = LemmyContext;
59   type ApubType = Page;
60   type DbType = Post;
61   type Error = LemmyError;
62
63   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
64     None
65   }
66
67   #[tracing::instrument(skip_all)]
68   async fn read_from_apub_id(
69     object_id: Url,
70     context: &LemmyContext,
71   ) -> Result<Option<Self>, LemmyError> {
72     Ok(
73       blocking(context.pool(), move |conn| {
74         Post::read_from_apub_id(conn, object_id)
75       })
76       .await??
77       .map(Into::into),
78     )
79   }
80
81   #[tracing::instrument(skip_all)]
82   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
83     if !self.deleted {
84       blocking(context.pool(), move |conn| {
85         Post::update_deleted(conn, self.id, true)
86       })
87       .await??;
88     }
89     Ok(())
90   }
91
92   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
93   #[tracing::instrument(skip_all)]
94   async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
95     let creator_id = self.creator_id;
96     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
97     let community_id = self.community_id;
98     let community = blocking(context.pool(), move |conn| {
99       Community::read(conn, community_id)
100     })
101     .await??;
102     let language = self.language_id;
103     let language = blocking(context.pool(), move |conn| {
104       Language::read_from_id(conn, language)
105     })
106     .await??;
107
108     let page = Page {
109       kind: PageType::Page,
110       id: ObjectId::new(self.ap_id.clone()),
111       attributed_to: AttributedTo::Lemmy(ObjectId::new(creator.actor_id)),
112       to: vec![community.actor_id.into(), public()],
113       cc: vec![],
114       name: self.name.clone(),
115       content: self.body.as_ref().map(|b| markdown_to_html(b)),
116       media_type: Some(MediaTypeMarkdownOrHtml::Html),
117       source: self.body.clone().map(Source::new),
118       url: self.url.clone().map(|u| u.into()),
119       attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
120       image: self.thumbnail_url.clone().map(ImageObject::new),
121       comments_enabled: Some(!self.locked),
122       sensitive: Some(self.nsfw),
123       stickied: Some(self.stickied),
124       language: LanguageTag::new(language),
125       published: Some(convert_datetime(self.published)),
126       updated: self.updated.map(convert_datetime),
127     };
128     Ok(page)
129   }
130
131   #[tracing::instrument(skip_all)]
132   async fn verify(
133     page: &Page,
134     expected_domain: &Url,
135     context: &LemmyContext,
136     request_counter: &mut i32,
137   ) -> Result<(), LemmyError> {
138     // We can't verify the domain in case of mod action, because the mod may be on a different
139     // instance from the post author.
140     if !page.is_mod_action(context).await? {
141       verify_domains_match(page.id.inner(), expected_domain)?;
142       verify_is_remote_object(page.id.inner(), context.settings())?;
143     };
144
145     let community = page.extract_community(context, request_counter).await?;
146     check_apub_id_valid_with_strictness(page.id.inner(), community.local, context.settings())?;
147     verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
148     check_slurs(&page.name, &context.settings().slur_regex())?;
149     verify_domains_match(page.creator()?.inner(), page.id.inner())?;
150     verify_is_public(&page.to, &page.cc)?;
151     Ok(())
152   }
153
154   #[tracing::instrument(skip_all)]
155   async fn from_apub(
156     page: Page,
157     context: &LemmyContext,
158     request_counter: &mut i32,
159   ) -> Result<ApubPost, LemmyError> {
160     let creator = page
161       .creator()?
162       .dereference(context, local_instance(context), request_counter)
163       .await?;
164     let community = page.extract_community(context, request_counter).await?;
165
166     let form = if !page.is_mod_action(context).await? {
167       let url = if let Some(attachment) = page.attachment.first() {
168         Some(match attachment {
169           // url as sent by Lemmy (new)
170           Attachment::Link(link) => link.href.clone(),
171           Attachment::Image(image) => image.url.clone(),
172         })
173       } else if page.kind == PageType::Video {
174         // we cant display videos directly, so insert a link to external video page
175         Some(page.id.inner().clone())
176       } else {
177         // url sent by lemmy (old)
178         page.url
179       };
180       let (metadata_res, thumbnail_url) = if let Some(url) = &url {
181         fetch_site_data(context.client(), context.settings(), Some(url)).await
182       } else {
183         (None, page.image.map(|i| i.url.into()))
184       };
185       let (embed_title, embed_description, embed_video_url) = metadata_res
186         .map(|u| (Some(u.title), Some(u.description), Some(u.embed_video_url)))
187         .unwrap_or_default();
188       let body_slurs_removed =
189         read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
190           .map(|s| Some(remove_slurs(&s, &context.settings().slur_regex())));
191       let language = page.language.map(|l| l.identifier);
192       let language = blocking(context.pool(), move |conn| {
193         Language::read_id_from_code_opt(conn, language.as_deref())
194       })
195       .await??;
196
197       PostForm {
198         name: page.name.clone(),
199         url: Some(url.map(Into::into)),
200         body: body_slurs_removed,
201         creator_id: creator.id,
202         community_id: community.id,
203         removed: None,
204         locked: page.comments_enabled.map(|e| !e),
205         published: page.published.map(|u| u.naive_local()),
206         updated: page.updated.map(|u| u.naive_local()),
207         deleted: None,
208         nsfw: page.sensitive,
209         stickied: page.stickied,
210         embed_title,
211         embed_description,
212         embed_video_url,
213         thumbnail_url: Some(thumbnail_url),
214         ap_id: Some(page.id.clone().into()),
215         local: Some(false),
216         language_id: language,
217       }
218     } else {
219       // if is mod action, only update locked/stickied fields, nothing else
220       PostForm {
221         name: page.name.clone(),
222         creator_id: creator.id,
223         community_id: community.id,
224         locked: page.comments_enabled.map(|e| !e),
225         stickied: page.stickied,
226         updated: page.updated.map(|u| u.naive_local()),
227         ap_id: Some(page.id.clone().into()),
228         ..Default::default()
229       }
230     };
231
232     // read existing, local post if any (for generating mod log)
233     let old_post = ObjectId::<ApubPost>::new(page.id.clone())
234       .dereference_local(context)
235       .await;
236
237     let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
238
239     // write mod log entries for sticky/lock
240     if Page::is_stickied_changed(&old_post, &page.stickied) {
241       let form = ModStickyPostForm {
242         mod_person_id: creator.id,
243         post_id: post.id,
244         stickied: Some(post.stickied),
245       };
246       blocking(context.pool(), move |conn| {
247         ModStickyPost::create(conn, &form)
248       })
249       .await??;
250     }
251     if Page::is_locked_changed(&old_post, &page.comments_enabled) {
252       let form = ModLockPostForm {
253         mod_person_id: creator.id,
254         post_id: post.id,
255         locked: Some(post.locked),
256       };
257       blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??;
258     }
259
260     Ok(post.into())
261   }
262 }
263
264 #[cfg(test)]
265 mod tests {
266   use super::*;
267   use crate::{
268     objects::{
269       community::tests::parse_lemmy_community,
270       person::tests::parse_lemmy_person,
271       post::ApubPost,
272       tests::init_context,
273     },
274     protocol::tests::file_to_json_object,
275   };
276   use lemmy_db_schema::source::site::Site;
277   use serial_test::serial;
278
279   #[actix_rt::test]
280   #[serial]
281   async fn test_parse_lemmy_post() {
282     let context = init_context();
283     let (person, site) = parse_lemmy_person(&context).await;
284     let community = parse_lemmy_community(&context).await;
285
286     let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
287     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
288     let mut request_counter = 0;
289     ApubPost::verify(&json, &url, &context, &mut request_counter)
290       .await
291       .unwrap();
292     let post = ApubPost::from_apub(json, &context, &mut request_counter)
293       .await
294       .unwrap();
295
296     assert_eq!(post.ap_id, url.into());
297     assert_eq!(post.name, "Post title");
298     assert!(post.body.is_some());
299     assert_eq!(post.body.as_ref().unwrap().len(), 45);
300     assert!(!post.locked);
301     assert!(post.stickied);
302     assert_eq!(request_counter, 0);
303
304     Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
305     Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
306     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
307     Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();
308   }
309 }