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;
24 use chrono::NaiveDateTime;
25 use lemmy_api_common::{
26 context::LemmyContext,
27 request::fetch_site_data,
28 utils::local_site_opt_to_slur_regex,
30 use lemmy_db_schema::{
34 local_site::LocalSite,
35 moderator::{ModLockPost, ModLockPostForm, ModStickyPost, ModStickyPostForm},
37 post::{Post, PostInsertForm, PostUpdateForm},
43 utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
48 #[derive(Clone, Debug)]
49 pub struct ApubPost(pub(crate) Post);
51 impl Deref for ApubPost {
53 fn deref(&self) -> &Self::Target {
58 impl From<Post> for ApubPost {
59 fn from(p: Post) -> Self {
64 #[async_trait::async_trait(?Send)]
65 impl ApubObject for ApubPost {
66 type DataType = LemmyContext;
69 type Error = LemmyError;
71 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
75 #[tracing::instrument(skip_all)]
76 async fn read_from_apub_id(
78 context: &LemmyContext,
79 ) -> Result<Option<Self>, LemmyError> {
81 Post::read_from_apub_id(context.pool(), object_id)
87 #[tracing::instrument(skip_all)]
88 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
90 let form = PostUpdateForm::builder().deleted(Some(true)).build();
91 Post::update(context.pool(), self.id, &form).await?;
96 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
97 #[tracing::instrument(skip_all)]
98 async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
99 let creator_id = self.creator_id;
100 let creator = Person::read(context.pool(), creator_id).await?;
101 let community_id = self.community_id;
102 let community = Community::read(context.pool(), community_id).await?;
103 let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
106 kind: PageType::Page,
107 id: ObjectId::new(self.ap_id.clone()),
108 attributed_to: AttributedTo::Lemmy(ObjectId::new(creator.actor_id)),
109 to: vec![community.actor_id.clone().into(), public()],
111 name: self.name.clone(),
112 content: self.body.as_ref().map(|b| markdown_to_html(b)),
113 media_type: Some(MediaTypeMarkdownOrHtml::Html),
114 source: self.body.clone().map(Source::new),
115 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
116 image: self.thumbnail_url.clone().map(ImageObject::new),
117 comments_enabled: Some(!self.locked),
118 sensitive: Some(self.nsfw),
119 stickied: Some(self.stickied),
121 published: Some(convert_datetime(self.published)),
122 updated: self.updated.map(convert_datetime),
123 audience: Some(ObjectId::new(community.actor_id)),
128 #[tracing::instrument(skip_all)]
131 expected_domain: &Url,
132 context: &LemmyContext,
133 request_counter: &mut i32,
134 ) -> Result<(), LemmyError> {
135 // We can't verify the domain in case of mod action, because the mod may be on a different
136 // instance from the post author.
137 if !page.is_mod_action(context).await? {
138 verify_domains_match(page.id.inner(), expected_domain)?;
139 verify_is_remote_object(page.id.inner(), context.settings())?;
142 let local_site_data = fetch_local_site_data(context.pool()).await?;
144 let community = page.community(context, request_counter).await?;
145 check_apub_id_valid_with_strictness(
151 verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
153 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
154 check_slurs(&page.name, slur_regex)?;
156 verify_domains_match(page.creator()?.inner(), page.id.inner())?;
157 verify_is_public(&page.to, &page.cc)?;
161 #[tracing::instrument(skip_all)]
164 context: &LemmyContext,
165 request_counter: &mut i32,
166 ) -> Result<ApubPost, LemmyError> {
169 .dereference(context, local_instance(context).await, request_counter)
171 let community = page.community(context, request_counter).await?;
173 let form = if !page.is_mod_action(context).await? {
174 let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
175 let url = if first_attachment.is_some() {
177 } else if page.kind == PageType::Video {
178 // we cant display videos directly, so insert a link to external video page
179 Some(page.id.inner().clone())
183 let (metadata_res, thumbnail_url) = if let Some(url) = &url {
184 fetch_site_data(context.client(), context.settings(), Some(url)).await
186 (None, page.image.map(|i| i.url.into()))
188 let (embed_title, embed_description, embed_video_url) = metadata_res
189 .map(|u| (u.title, u.description, u.embed_video_url))
190 .unwrap_or_default();
191 let local_site = LocalSite::read(context.pool()).await.ok();
192 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
194 let body_slurs_removed =
195 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
196 .map(|s| remove_slurs(&s, slur_regex));
197 let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
200 name: page.name.clone(),
201 url: url.map(Into::into),
202 body: body_slurs_removed,
203 creator_id: creator.id,
204 community_id: community.id,
206 locked: page.comments_enabled.map(|e| !e),
207 published: page.published.map(|u| u.naive_local()),
208 updated: page.updated.map(|u| u.naive_local()),
209 deleted: Some(false),
210 nsfw: page.sensitive,
211 stickied: page.stickied,
216 ap_id: Some(page.id.clone().into()),
221 // if is mod action, only update locked/stickied fields, nothing else
222 PostInsertForm::builder()
223 .name(page.name.clone())
224 .creator_id(creator.id)
225 .community_id(community.id)
226 .ap_id(Some(page.id.clone().into()))
227 .locked(page.comments_enabled.map(|e| !e))
228 .stickied(page.stickied)
229 .updated(page.updated.map(|u| u.naive_local()))
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)
237 let post = Post::create(context.pool(), &form).await?;
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,
244 stickied: Some(post.stickied),
246 ModStickyPost::create(context.pool(), &form).await?;
248 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
249 let form = ModLockPostForm {
250 mod_person_id: creator.id,
252 locked: Some(post.locked),
254 ModLockPost::create(context.pool(), &form).await?;
266 community::tests::parse_lemmy_community,
267 person::tests::parse_lemmy_person,
271 protocol::tests::file_to_json_object,
273 use lemmy_db_schema::source::site::Site;
274 use serial_test::serial;
278 async fn test_parse_lemmy_post() {
279 let context = init_context().await;
280 let (person, site) = parse_lemmy_person(&context).await;
281 let community = parse_lemmy_community(&context).await;
283 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
284 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
285 let mut request_counter = 0;
286 ApubPost::verify(&json, &url, &context, &mut request_counter)
289 let post = ApubPost::from_apub(json, &context, &mut request_counter)
293 assert_eq!(post.ap_id, url.into());
294 assert_eq!(post.name, "Post title");
295 assert!(post.body.is_some());
296 assert_eq!(post.body.as_ref().unwrap().len(), 45);
297 assert!(!post.locked);
298 assert!(post.stickied);
299 assert_eq!(request_counter, 0);
301 Post::delete(context.pool(), post.id).await.unwrap();
302 Person::delete(context.pool(), person.id).await.unwrap();
303 Community::delete(context.pool(), community.id)
306 Site::delete(context.pool(), site.id).await.unwrap();