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},
16 use activitypub_federation::{
17 core::object_id::ObjectId,
18 deser::values::MediaTypeMarkdownOrHtml,
20 utils::verify_domains_match,
22 use activitystreams_kinds::public;
23 use chrono::NaiveDateTime;
24 use lemmy_api_common::{
25 request::fetch_site_data,
26 utils::{blocking, local_site_opt_to_slur_regex},
28 use lemmy_db_schema::{
32 local_site::LocalSite,
33 moderator::{ModLockPost, ModLockPostForm, ModStickyPost, ModStickyPostForm},
35 post::{Post, PostInsertForm, PostUpdateForm},
41 utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
43 use lemmy_websocket::LemmyContext;
47 #[derive(Clone, Debug)]
48 pub struct ApubPost(Post);
50 impl Deref for ApubPost {
52 fn deref(&self) -> &Self::Target {
57 impl From<Post> for ApubPost {
58 fn from(p: Post) -> Self {
63 #[async_trait::async_trait(?Send)]
64 impl ApubObject for ApubPost {
65 type DataType = LemmyContext;
68 type Error = LemmyError;
70 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
74 #[tracing::instrument(skip_all)]
75 async fn read_from_apub_id(
77 context: &LemmyContext,
78 ) -> Result<Option<Self>, LemmyError> {
80 blocking(context.pool(), move |conn| {
81 Post::read_from_apub_id(conn, object_id)
88 #[tracing::instrument(skip_all)]
89 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
91 blocking(context.pool(), move |conn| {
92 let form = PostUpdateForm::builder().deleted(Some(true)).build();
93 Post::update(conn, self.id, &form)
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 = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
105 let community_id = self.community_id;
106 let community = blocking(context.pool(), move |conn| {
107 Community::read(conn, community_id)
110 let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
113 kind: PageType::Page,
114 id: ObjectId::new(self.ap_id.clone()),
115 attributed_to: AttributedTo::Lemmy(ObjectId::new(creator.actor_id)),
116 to: vec![community.actor_id.into(), public()],
118 name: self.name.clone(),
119 content: self.body.as_ref().map(|b| markdown_to_html(b)),
120 media_type: Some(MediaTypeMarkdownOrHtml::Html),
121 source: self.body.clone().map(Source::new),
122 url: self.url.clone().map(|u| u.into()),
123 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
124 image: self.thumbnail_url.clone().map(ImageObject::new),
125 comments_enabled: Some(!self.locked),
126 sensitive: Some(self.nsfw),
127 stickied: Some(self.stickied),
129 published: Some(convert_datetime(self.published)),
130 updated: self.updated.map(convert_datetime),
135 #[tracing::instrument(skip_all)]
138 expected_domain: &Url,
139 context: &LemmyContext,
140 request_counter: &mut i32,
141 ) -> Result<(), LemmyError> {
142 // We can't verify the domain in case of mod action, because the mod may be on a different
143 // instance from the post author.
144 if !page.is_mod_action(context).await? {
145 verify_domains_match(page.id.inner(), expected_domain)?;
146 verify_is_remote_object(page.id.inner(), context.settings())?;
149 let local_site_data = blocking(context.pool(), fetch_local_site_data).await??;
151 let community = page.extract_community(context, request_counter).await?;
152 check_apub_id_valid_with_strictness(
158 verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
160 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
161 check_slurs(&page.name, slur_regex)?;
163 verify_domains_match(page.creator()?.inner(), page.id.inner())?;
164 verify_is_public(&page.to, &page.cc)?;
168 #[tracing::instrument(skip_all)]
171 context: &LemmyContext,
172 request_counter: &mut i32,
173 ) -> Result<ApubPost, LemmyError> {
176 .dereference(context, local_instance(context), request_counter)
178 let community = page.extract_community(context, request_counter).await?;
180 let form = if !page.is_mod_action(context).await? {
181 let url = if let Some(attachment) = page.attachment.first() {
182 Some(match attachment {
183 // url as sent by Lemmy (new)
184 Attachment::Link(link) => link.href.clone(),
185 Attachment::Image(image) => image.url.clone(),
187 } else if page.kind == PageType::Video {
188 // we cant display videos directly, so insert a link to external video page
189 Some(page.id.inner().clone())
191 // url sent by lemmy (old)
194 let (metadata_res, thumbnail_url) = if let Some(url) = &url {
195 fetch_site_data(context.client(), context.settings(), Some(url)).await
197 (None, page.image.map(|i| i.url.into()))
199 let (embed_title, embed_description, embed_video_url) = metadata_res
200 .map(|u| (u.title, u.description, u.embed_video_url))
201 .unwrap_or_default();
202 let local_site = blocking(context.pool(), LocalSite::read).await?.ok();
203 let slur_regex = &local_site_opt_to_slur_regex(&local_site);
205 let body_slurs_removed =
206 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
207 .map(|s| remove_slurs(&s, slur_regex));
208 let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
211 name: page.name.clone(),
212 url: url.map(Into::into),
213 body: body_slurs_removed,
214 creator_id: creator.id,
215 community_id: community.id,
217 locked: page.comments_enabled.map(|e| !e),
218 published: page.published.map(|u| u.naive_local()),
219 updated: page.updated.map(|u| u.naive_local()),
221 nsfw: page.sensitive,
222 stickied: page.stickied,
227 ap_id: Some(page.id.clone().into()),
232 // if is mod action, only update locked/stickied fields, nothing else
233 PostInsertForm::builder()
234 .name(page.name.clone())
235 .creator_id(creator.id)
236 .community_id(community.id)
237 .ap_id(Some(page.id.clone().into()))
238 .locked(page.comments_enabled.map(|e| !e))
239 .stickied(page.stickied)
240 .updated(page.updated.map(|u| u.naive_local()))
244 // read existing, local post if any (for generating mod log)
245 let old_post = ObjectId::<ApubPost>::new(page.id.clone())
246 .dereference_local(context)
249 let post = blocking(context.pool(), move |conn| Post::create(conn, &form)).await??;
251 // write mod log entries for sticky/lock
252 if Page::is_stickied_changed(&old_post, &page.stickied) {
253 let form = ModStickyPostForm {
254 mod_person_id: creator.id,
256 stickied: Some(post.stickied),
258 blocking(context.pool(), move |conn| {
259 ModStickyPost::create(conn, &form)
263 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
264 let form = ModLockPostForm {
265 mod_person_id: creator.id,
267 locked: Some(post.locked),
269 blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??;
281 community::tests::parse_lemmy_community,
282 person::tests::parse_lemmy_person,
286 protocol::tests::file_to_json_object,
288 use lemmy_db_schema::source::site::Site;
289 use serial_test::serial;
293 async fn test_parse_lemmy_post() {
294 let context = init_context();
295 let conn = &mut context.pool().get().unwrap();
296 let (person, site) = parse_lemmy_person(&context).await;
297 let community = parse_lemmy_community(&context).await;
299 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
300 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
301 let mut request_counter = 0;
302 ApubPost::verify(&json, &url, &context, &mut request_counter)
305 let post = ApubPost::from_apub(json, &context, &mut request_counter)
309 assert_eq!(post.ap_id, url.into());
310 assert_eq!(post.name, "Post title");
311 assert!(post.body.is_some());
312 assert_eq!(post.body.as_ref().unwrap().len(), 45);
313 assert!(!post.locked);
314 assert!(post.stickied);
315 assert_eq!(request_counter, 0);
317 Post::delete(conn, post.id).unwrap();
318 Person::delete(conn, person.id).unwrap();
319 Community::delete(conn, community.id).unwrap();
320 Site::delete(conn, site.id).unwrap();