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 lemmy_api_common::{
27 context::LemmyContext,
28 request::fetch_site_data,
29 utils::local_site_opt_to_slur_regex,
31 use lemmy_db_schema::{
35 local_site::LocalSite,
36 moderator::{ModFeaturePost, ModFeaturePostForm, ModLockPost, ModLockPostForm},
38 post::{Post, PostInsertForm, PostUpdateForm},
44 utils::{check_slurs_opt, convert_datetime, markdown_to_html, remove_slurs},
49 const MAX_TITLE_LENGTH: usize = 100;
51 #[derive(Clone, Debug)]
52 pub struct ApubPost(pub(crate) Post);
54 impl Deref for ApubPost {
56 fn deref(&self) -> &Self::Target {
61 impl From<Post> for ApubPost {
62 fn from(p: Post) -> Self {
67 #[async_trait::async_trait(?Send)]
68 impl ApubObject for ApubPost {
69 type DataType = LemmyContext;
72 type Error = LemmyError;
74 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
78 #[tracing::instrument(skip_all)]
79 async fn read_from_apub_id(
81 context: &LemmyContext,
82 ) -> Result<Option<Self>, LemmyError> {
84 Post::read_from_apub_id(context.pool(), object_id)
90 #[tracing::instrument(skip_all)]
91 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
93 let form = PostUpdateForm::builder().deleted(Some(true)).build();
94 Post::update(context.pool(), self.id, &form).await?;
99 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
100 #[tracing::instrument(skip_all)]
101 async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
102 let creator_id = self.creator_id;
103 let creator = Person::read(context.pool(), creator_id).await?;
104 let community_id = self.community_id;
105 let community = Community::read(context.pool(), community_id).await?;
106 let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
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.clone().into(), public()],
114 name: Some(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 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
119 image: self.thumbnail_url.clone().map(ImageObject::new),
120 comments_enabled: Some(!self.locked),
121 sensitive: Some(self.nsfw),
122 stickied: Some(self.featured_community),
124 published: Some(convert_datetime(self.published)),
125 updated: self.updated.map(convert_datetime),
126 audience: Some(ObjectId::new(community.actor_id)),
132 #[tracing::instrument(skip_all)]
135 expected_domain: &Url,
136 context: &LemmyContext,
137 request_counter: &mut i32,
138 ) -> Result<(), LemmyError> {
139 // We can't verify the domain in case of mod action, because the mod may be on a different
140 // instance from the post author.
141 if !page.is_mod_action(context).await? {
142 verify_domains_match(page.id.inner(), expected_domain)?;
143 verify_is_remote_object(page.id.inner(), context.settings())?;
146 let local_site_data = fetch_local_site_data(context.pool()).await?;
148 let community = page.community(context, request_counter).await?;
149 check_apub_id_valid_with_strictness(
155 verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
157 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
158 check_slurs_opt(&page.name, slur_regex)?;
160 verify_domains_match(page.creator()?.inner(), page.id.inner())?;
161 verify_is_public(&page.to, &page.cc)?;
165 #[tracing::instrument(skip_all)]
168 context: &LemmyContext,
169 request_counter: &mut i32,
170 ) -> Result<ApubPost, LemmyError> {
173 .dereference(context, local_instance(context).await, request_counter)
175 let community = page.community(context, request_counter).await?;
183 .and_then(|c| c.lines().next().map(ToString::to_string))
185 .ok_or_else(|| anyhow!("Object must have name or content"))?;
186 if name.chars().count() > MAX_TITLE_LENGTH {
187 name = name.chars().take(MAX_TITLE_LENGTH).collect();
190 let form = if !page.is_mod_action(context).await? {
191 let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
192 let url = if first_attachment.is_some() {
194 } else if page.kind == PageType::Video {
195 // we cant display videos directly, so insert a link to external video page
196 Some(page.id.inner().clone())
200 let (metadata_res, thumbnail_url) = if let Some(url) = &url {
201 fetch_site_data(context.client(), context.settings(), Some(url)).await
203 (None, page.image.map(|i| i.url.into()))
205 let (embed_title, embed_description, embed_video_url) = metadata_res
206 .map(|u| (u.title, u.description, u.embed_video_url))
207 .unwrap_or_default();
208 let local_site = LocalSite::read(context.pool()).await.ok();
209 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
211 let body_slurs_removed =
212 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
213 .map(|s| remove_slurs(&s, slur_regex));
214 let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
218 url: url.map(Into::into),
219 body: body_slurs_removed,
220 creator_id: creator.id,
221 community_id: community.id,
223 locked: page.comments_enabled.map(|e| !e),
224 published: page.published.map(|u| u.naive_local()),
225 updated: page.updated.map(|u| u.naive_local()),
226 deleted: Some(false),
227 nsfw: page.sensitive,
232 ap_id: Some(page.id.clone().into()),
235 featured_community: page.stickied,
236 featured_local: None,
239 // if is mod action, only update locked/stickied fields, nothing else
240 PostInsertForm::builder()
242 .creator_id(creator.id)
243 .community_id(community.id)
244 .ap_id(Some(page.id.clone().into()))
245 .locked(page.comments_enabled.map(|e| !e))
246 .featured_community(page.stickied)
247 .updated(page.updated.map(|u| u.naive_local()))
250 // read existing, local post if any (for generating mod log)
251 let old_post = ObjectId::<ApubPost>::new(page.id.clone())
252 .dereference_local(context)
255 let post = Post::create(context.pool(), &form).await?;
257 // write mod log entries for feature/lock
258 if Page::is_featured_changed(&old_post, &page.stickied) {
259 let form = ModFeaturePostForm {
260 mod_person_id: creator.id,
262 featured: post.featured_community,
263 is_featured_community: true,
265 ModFeaturePost::create(context.pool(), &form).await?;
267 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
268 let form = ModLockPostForm {
269 mod_person_id: creator.id,
271 locked: Some(post.locked),
273 ModLockPost::create(context.pool(), &form).await?;
285 community::tests::parse_lemmy_community,
286 person::tests::parse_lemmy_person,
290 protocol::tests::file_to_json_object,
292 use lemmy_db_schema::source::site::Site;
293 use serial_test::serial;
297 async fn test_parse_lemmy_post() {
298 let context = init_context().await;
299 let (person, site) = parse_lemmy_person(&context).await;
300 let community = parse_lemmy_community(&context).await;
302 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
303 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
304 let mut request_counter = 0;
305 ApubPost::verify(&json, &url, &context, &mut request_counter)
308 let post = ApubPost::from_apub(json, &context, &mut request_counter)
312 assert_eq!(post.ap_id, url.into());
313 assert_eq!(post.name, "Post title");
314 assert!(post.body.is_some());
315 assert_eq!(post.body.as_ref().unwrap().len(), 45);
316 assert!(!post.locked);
317 assert!(post.featured_community);
318 assert_eq!(request_counter, 0);
320 Post::delete(context.pool(), post.id).await.unwrap();
321 Person::delete(context.pool(), person.id).await.unwrap();
322 Community::delete(context.pool(), community.id)
325 Site::delete(context.pool(), site.id).await.unwrap();