2 activities::{verify_is_public, verify_person_in_community},
3 check_apub_id_valid_with_strictness,
6 objects::{read_from_string_or_source_opt, verify_is_remote_object},
9 page::{Attachment, AttributedTo, Page, PageType},
17 use activitypub_federation::{
18 core::object_id::ObjectId,
19 deser::values::MediaTypeMarkdownOrHtml,
21 utils::verify_domains_match,
23 use activitystreams_kinds::public;
25 use chrono::NaiveDateTime;
26 use html2md::parse_html;
27 use lemmy_api_common::{
28 context::LemmyContext,
29 request::fetch_site_data,
30 utils::{is_mod_or_admin, local_site_opt_to_slur_regex},
32 use lemmy_db_schema::{
36 local_site::LocalSite,
37 moderator::{ModFeaturePost, ModFeaturePostForm, ModLockPost, ModLockPostForm},
39 post::{Post, PostInsertForm, PostUpdateForm},
45 utils::{check_slurs_opt, convert_datetime, markdown_to_html, remove_slurs},
50 const MAX_TITLE_LENGTH: usize = 100;
52 #[derive(Clone, Debug)]
53 pub struct ApubPost(pub(crate) Post);
55 impl Deref for ApubPost {
57 fn deref(&self) -> &Self::Target {
62 impl From<Post> for ApubPost {
63 fn from(p: Post) -> Self {
68 #[async_trait::async_trait(?Send)]
69 impl ApubObject for ApubPost {
70 type DataType = LemmyContext;
73 type Error = LemmyError;
75 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
79 #[tracing::instrument(skip_all)]
80 async fn read_from_apub_id(
82 context: &LemmyContext,
83 ) -> Result<Option<Self>, LemmyError> {
85 Post::read_from_apub_id(context.pool(), object_id)
91 #[tracing::instrument(skip_all)]
92 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
94 let form = PostUpdateForm::builder().deleted(Some(true)).build();
95 Post::update(context.pool(), self.id, &form).await?;
100 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
101 #[tracing::instrument(skip_all)]
102 async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
103 let creator_id = self.creator_id;
104 let creator = Person::read(context.pool(), creator_id).await?;
105 let community_id = self.community_id;
106 let community = Community::read(context.pool(), community_id).await?;
107 let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
110 kind: PageType::Page,
111 id: ObjectId::new(self.ap_id.clone()),
112 attributed_to: AttributedTo::Lemmy(ObjectId::new(creator.actor_id)),
113 to: vec![community.actor_id.clone().into(), public()],
115 name: Some(self.name.clone()),
116 content: self.body.as_ref().map(|b| markdown_to_html(b)),
117 media_type: Some(MediaTypeMarkdownOrHtml::Html),
118 source: self.body.clone().map(Source::new),
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.featured_community),
125 published: Some(convert_datetime(self.published)),
126 updated: self.updated.map(convert_datetime),
127 audience: Some(ObjectId::new(community.actor_id)),
133 #[tracing::instrument(skip_all)]
136 expected_domain: &Url,
137 context: &LemmyContext,
138 request_counter: &mut i32,
139 ) -> Result<(), LemmyError> {
140 // We can't verify the domain in case of mod action, because the mod may be on a different
141 // instance from the post author.
142 if !page.is_mod_action(context).await? {
143 verify_domains_match(page.id.inner(), expected_domain)?;
144 verify_is_remote_object(page.id.inner(), context.settings())?;
147 let local_site_data = fetch_local_site_data(context.pool()).await?;
149 let community = page.community(context, request_counter).await?;
150 check_apub_id_valid_with_strictness(
156 verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
158 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
159 check_slurs_opt(&page.name, slur_regex)?;
161 verify_domains_match(page.creator()?.inner(), page.id.inner())?;
162 verify_is_public(&page.to, &page.cc)?;
166 #[tracing::instrument(skip_all)]
169 context: &LemmyContext,
170 request_counter: &mut i32,
171 ) -> Result<ApubPost, LemmyError> {
174 .dereference(context, local_instance(context).await, request_counter)
176 let community = page.community(context, request_counter).await?;
177 if community.posting_restricted_to_mods {
178 is_mod_or_admin(context.pool(), creator.id, community.id).await?;
188 .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
190 .ok_or_else(|| anyhow!("Object must have name or content"))?;
191 if name.chars().count() > MAX_TITLE_LENGTH {
192 name = name.chars().take(MAX_TITLE_LENGTH).collect();
195 let form = if !page.is_mod_action(context).await? {
196 let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
197 let url = if first_attachment.is_some() {
199 } else if page.kind == PageType::Video {
200 // we cant display videos directly, so insert a link to external video page
201 Some(page.id.inner().clone())
205 let (metadata_res, thumbnail_url) = if let Some(url) = &url {
206 fetch_site_data(context.client(), context.settings(), Some(url)).await
208 (None, page.image.map(|i| i.url.into()))
210 let (embed_title, embed_description, embed_video_url) = metadata_res
211 .map(|u| (u.title, u.description, u.embed_video_url))
212 .unwrap_or_default();
213 let local_site = LocalSite::read(context.pool()).await.ok();
214 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
216 let body_slurs_removed =
217 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
218 .map(|s| remove_slurs(&s, slur_regex));
219 let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
223 url: url.map(Into::into),
224 body: body_slurs_removed,
225 creator_id: creator.id,
226 community_id: community.id,
228 locked: page.comments_enabled.map(|e| !e),
229 published: page.published.map(|u| u.naive_local()),
230 updated: page.updated.map(|u| u.naive_local()),
231 deleted: Some(false),
232 nsfw: page.sensitive,
237 ap_id: Some(page.id.clone().into()),
240 featured_community: page.stickied,
241 featured_local: None,
244 // if is mod action, only update locked/stickied fields, nothing else
245 PostInsertForm::builder()
247 .creator_id(creator.id)
248 .community_id(community.id)
249 .ap_id(Some(page.id.clone().into()))
250 .locked(page.comments_enabled.map(|e| !e))
251 .featured_community(page.stickied)
252 .updated(page.updated.map(|u| u.naive_local()))
255 // read existing, local post if any (for generating mod log)
256 let old_post = ObjectId::<ApubPost>::new(page.id.clone())
257 .dereference_local(context)
260 let post = Post::create(context.pool(), &form).await?;
262 // write mod log entries for feature/lock
263 if Page::is_featured_changed(&old_post, &page.stickied) {
264 let form = ModFeaturePostForm {
265 mod_person_id: creator.id,
267 featured: post.featured_community,
268 is_featured_community: true,
270 ModFeaturePost::create(context.pool(), &form).await?;
272 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
273 let form = ModLockPostForm {
274 mod_person_id: creator.id,
276 locked: Some(post.locked),
278 ModLockPost::create(context.pool(), &form).await?;
290 community::tests::parse_lemmy_community,
291 person::tests::parse_lemmy_person,
295 protocol::tests::file_to_json_object,
297 use lemmy_db_schema::source::site::Site;
298 use serial_test::serial;
302 async fn test_parse_lemmy_post() {
303 let context = init_context().await;
304 let (person, site) = parse_lemmy_person(&context).await;
305 let community = parse_lemmy_community(&context).await;
307 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
308 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
309 let mut request_counter = 0;
310 ApubPost::verify(&json, &url, &context, &mut request_counter)
313 let post = ApubPost::from_apub(json, &context, &mut request_counter)
317 assert_eq!(post.ap_id, url.into());
318 assert_eq!(post.name, "Post title");
319 assert!(post.body.is_some());
320 assert_eq!(post.body.as_ref().unwrap().len(), 45);
321 assert!(!post.locked);
322 assert!(post.featured_community);
323 assert_eq!(request_counter, 0);
325 Post::delete(context.pool(), post.id).await.unwrap();
326 Person::delete(context.pool(), person.id).await.unwrap();
327 Community::delete(context.pool(), community.id)
330 Site::delete(context.pool(), site.id).await.unwrap();