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::{is_mod_or_admin, 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?;
176 if community.posting_restricted_to_mods {
177 is_mod_or_admin(context.pool(), creator.id, community.id).await?;
186 .and_then(|c| c.lines().next().map(ToString::to_string))
188 .ok_or_else(|| anyhow!("Object must have name or content"))?;
189 if name.chars().count() > MAX_TITLE_LENGTH {
190 name = name.chars().take(MAX_TITLE_LENGTH).collect();
193 let form = if !page.is_mod_action(context).await? {
194 let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
195 let url = if first_attachment.is_some() {
197 } else if page.kind == PageType::Video {
198 // we cant display videos directly, so insert a link to external video page
199 Some(page.id.inner().clone())
203 let (metadata_res, thumbnail_url) = if let Some(url) = &url {
204 fetch_site_data(context.client(), context.settings(), Some(url)).await
206 (None, page.image.map(|i| i.url.into()))
208 let (embed_title, embed_description, embed_video_url) = metadata_res
209 .map(|u| (u.title, u.description, u.embed_video_url))
210 .unwrap_or_default();
211 let local_site = LocalSite::read(context.pool()).await.ok();
212 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
214 let body_slurs_removed =
215 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
216 .map(|s| remove_slurs(&s, slur_regex));
217 let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
221 url: url.map(Into::into),
222 body: body_slurs_removed,
223 creator_id: creator.id,
224 community_id: community.id,
226 locked: page.comments_enabled.map(|e| !e),
227 published: page.published.map(|u| u.naive_local()),
228 updated: page.updated.map(|u| u.naive_local()),
229 deleted: Some(false),
230 nsfw: page.sensitive,
235 ap_id: Some(page.id.clone().into()),
238 featured_community: page.stickied,
239 featured_local: None,
242 // if is mod action, only update locked/stickied fields, nothing else
243 PostInsertForm::builder()
245 .creator_id(creator.id)
246 .community_id(community.id)
247 .ap_id(Some(page.id.clone().into()))
248 .locked(page.comments_enabled.map(|e| !e))
249 .featured_community(page.stickied)
250 .updated(page.updated.map(|u| u.naive_local()))
253 // read existing, local post if any (for generating mod log)
254 let old_post = ObjectId::<ApubPost>::new(page.id.clone())
255 .dereference_local(context)
258 let post = Post::create(context.pool(), &form).await?;
260 // write mod log entries for feature/lock
261 if Page::is_featured_changed(&old_post, &page.stickied) {
262 let form = ModFeaturePostForm {
263 mod_person_id: creator.id,
265 featured: post.featured_community,
266 is_featured_community: true,
268 ModFeaturePost::create(context.pool(), &form).await?;
270 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
271 let form = ModLockPostForm {
272 mod_person_id: creator.id,
274 locked: Some(post.locked),
276 ModLockPost::create(context.pool(), &form).await?;
288 community::tests::parse_lemmy_community,
289 person::tests::parse_lemmy_person,
293 protocol::tests::file_to_json_object,
295 use lemmy_db_schema::source::site::Site;
296 use serial_test::serial;
300 async fn test_parse_lemmy_post() {
301 let context = init_context().await;
302 let (person, site) = parse_lemmy_person(&context).await;
303 let community = parse_lemmy_community(&context).await;
305 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
306 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
307 let mut request_counter = 0;
308 ApubPost::verify(&json, &url, &context, &mut request_counter)
311 let post = ApubPost::from_apub(json, &context, &mut request_counter)
315 assert_eq!(post.ap_id, url.into());
316 assert_eq!(post.name, "Post title");
317 assert!(post.body.is_some());
318 assert_eq!(post.body.as_ref().unwrap().len(), 45);
319 assert!(!post.locked);
320 assert!(post.featured_community);
321 assert_eq!(request_counter, 0);
323 Post::delete(context.pool(), post.id).await.unwrap();
324 Person::delete(context.pool(), person.id).await.unwrap();
325 Community::delete(context.pool(), community.id)
328 Site::delete(context.pool(), site.id).await.unwrap();