2 activities::{verify_is_public, verify_person_in_community},
3 check_apub_id_valid_with_strictness,
5 objects::{read_from_string_or_source_opt, verify_is_remote_object},
8 page::{Attachment, AttributedTo, Page, PageType},
16 use activitypub_federation::{
19 protocol::{values::MediaTypeMarkdownOrHtml, verification::verify_domains_match},
23 use chrono::NaiveDateTime;
24 use html2md::parse_html;
25 use lemmy_api_common::{
26 context::LemmyContext,
27 request::fetch_site_data,
28 utils::{is_mod_or_admin, local_site_opt_to_slur_regex},
30 use lemmy_db_schema::{
34 local_site::LocalSite,
35 moderator::{ModFeaturePost, ModFeaturePostForm, ModLockPost, ModLockPostForm},
37 post::{Post, PostInsertForm, PostUpdateForm},
44 markdown::markdown_to_html,
45 slurs::{check_slurs_opt, remove_slurs},
46 time::convert_datetime,
52 const MAX_TITLE_LENGTH: usize = 200;
54 #[derive(Clone, Debug)]
55 pub struct ApubPost(pub(crate) Post);
57 impl Deref for ApubPost {
59 fn deref(&self) -> &Self::Target {
64 impl From<Post> for ApubPost {
65 fn from(p: Post) -> Self {
70 #[async_trait::async_trait]
71 impl Object for ApubPost {
72 type DataType = LemmyContext;
74 type Error = LemmyError;
76 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
80 #[tracing::instrument(skip_all)]
81 async fn read_from_id(
83 context: &Data<Self::DataType>,
84 ) -> Result<Option<Self>, LemmyError> {
86 Post::read_from_apub_id(context.pool(), object_id)
92 #[tracing::instrument(skip_all)]
93 async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
95 let form = PostUpdateForm::builder().deleted(Some(true)).build();
96 Post::update(context.pool(), self.id, &form).await?;
101 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
102 #[tracing::instrument(skip_all)]
103 async fn into_json(self, context: &Data<Self::DataType>) -> Result<Page, LemmyError> {
104 let creator_id = self.creator_id;
105 let creator = Person::read(context.pool(), creator_id).await?;
106 let community_id = self.community_id;
107 let community = Community::read(context.pool(), community_id).await?;
108 let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
111 kind: PageType::Page,
112 id: self.ap_id.clone().into(),
113 attributed_to: AttributedTo::Lemmy(creator.actor_id.into()),
114 to: vec![community.actor_id.clone().into(), public()],
116 name: Some(self.name.clone()),
117 content: self.body.as_ref().map(|b| markdown_to_html(b)),
118 media_type: Some(MediaTypeMarkdownOrHtml::Html),
119 source: self.body.clone().map(Source::new),
120 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
121 image: self.thumbnail_url.clone().map(ImageObject::new),
122 comments_enabled: Some(!self.locked),
123 sensitive: Some(self.nsfw),
124 stickied: Some(self.featured_community),
126 published: Some(convert_datetime(self.published)),
127 updated: self.updated.map(convert_datetime),
128 audience: Some(community.actor_id.into()),
134 #[tracing::instrument(skip_all)]
137 expected_domain: &Url,
138 context: &Data<Self::DataType>,
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).await?;
150 check_apub_id_valid_with_strictness(
156 verify_person_in_community(&page.creator()?, &community, context).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)]
167 async fn from_json(page: Page, context: &Data<Self::DataType>) -> Result<ApubPost, LemmyError> {
168 let creator = page.creator()?.dereference(context).await?;
169 let community = page.community(context).await?;
170 if community.posting_restricted_to_mods {
171 is_mod_or_admin(context.pool(), creator.id, community.id).await?;
181 .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
183 .ok_or_else(|| anyhow!("Object must have name or content"))?;
184 if name.chars().count() > MAX_TITLE_LENGTH {
185 name = name.chars().take(MAX_TITLE_LENGTH).collect();
188 // read existing, local post if any (for generating mod log)
189 let old_post = page.id.dereference_local(context).await;
191 let form = if !page.is_mod_action(context).await? {
192 let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
193 let url = if first_attachment.is_some() {
195 } else if page.kind == PageType::Video {
196 // we cant display videos directly, so insert a link to external video page
197 Some(page.id.inner().clone())
201 // Only fetch metadata if the post has a url and was not seen previously. We dont want to
202 // waste resources by fetching metadata for the same post multiple times.
203 let (metadata_res, thumbnail_url) = match &url {
204 Some(url) if old_post.is_err() => {
205 fetch_site_data(context.client(), context.settings(), Some(url)).await
207 _ => (None, page.image.map(|i| i.url.into())),
209 let (embed_title, embed_description, embed_video_url) = metadata_res
210 .map(|u| (u.title, u.description, u.embed_video_url))
211 .unwrap_or_default();
212 let local_site = LocalSite::read(context.pool()).await.ok();
213 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
215 let body_slurs_removed =
216 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
217 .map(|s| remove_slurs(&s, slur_regex));
218 let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
222 url: url.map(Into::into),
223 body: body_slurs_removed,
224 creator_id: creator.id,
225 community_id: community.id,
227 locked: page.comments_enabled.map(|e| !e),
228 published: page.published.map(|u| u.naive_local()),
229 updated: page.updated.map(|u| u.naive_local()),
230 deleted: Some(false),
231 nsfw: page.sensitive,
236 ap_id: Some(page.id.clone().into()),
239 featured_community: page.stickied,
240 featured_local: None,
243 // if is mod action, only update locked/stickied fields, nothing else
244 PostInsertForm::builder()
246 .creator_id(creator.id)
247 .community_id(community.id)
248 .ap_id(Some(page.id.clone().into()))
249 .locked(page.comments_enabled.map(|e| !e))
250 .featured_community(page.stickied)
251 .updated(page.updated.map(|u| u.naive_local()))
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 ApubPost::verify(&json, &url, &context).await.unwrap();
305 let post = ApubPost::from_json(json, &context).await.unwrap();
307 assert_eq!(post.ap_id, url.into());
308 assert_eq!(post.name, "Post title");
309 assert!(post.body.is_some());
310 assert_eq!(post.body.as_ref().unwrap().len(), 45);
311 assert!(!post.locked);
312 assert!(post.featured_community);
313 assert_eq!(context.request_count(), 0);
315 Post::delete(context.pool(), post.id).await.unwrap();
316 Person::delete(context.pool(), person.id).await.unwrap();
317 Community::delete(context.pool(), community.id)
320 Site::delete(context.pool(), site.id).await.unwrap();