2 activities::{verify_is_public, verify_person_in_community},
3 check_is_apub_id_valid,
4 objects::{read_from_string_or_source_opt, verify_is_remote_object},
7 page::{Attachment, Page, PageType},
14 use activitystreams_kinds::public;
15 use chrono::NaiveDateTime;
16 use lemmy_api_common::blocking;
20 values::MediaTypeHtml,
21 verify::verify_domains_match,
23 use lemmy_db_schema::{
27 moderator::{ModLockPost, ModLockPostForm, ModStickyPost, ModStickyPostForm},
29 post::{Post, PostForm},
34 request::fetch_site_data,
35 utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
38 use lemmy_websocket::LemmyContext;
42 #[derive(Clone, Debug)]
43 pub struct ApubPost(Post);
45 impl Deref for ApubPost {
47 fn deref(&self) -> &Self::Target {
52 impl From<Post> for ApubPost {
53 fn from(p: Post) -> Self {
58 #[async_trait::async_trait(?Send)]
59 impl ApubObject for ApubPost {
60 type DataType = LemmyContext;
63 type TombstoneType = Tombstone;
65 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
69 #[tracing::instrument(skip_all)]
70 async fn read_from_apub_id(
72 context: &LemmyContext,
73 ) -> Result<Option<Self>, LemmyError> {
75 blocking(context.pool(), move |conn| {
76 Post::read_from_apub_id(conn, object_id)
83 #[tracing::instrument(skip_all)]
84 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
86 blocking(context.pool(), move |conn| {
87 Post::update_deleted(conn, self.id, true)
94 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
95 #[tracing::instrument(skip_all)]
96 async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
97 let creator_id = self.creator_id;
98 let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
99 let community_id = self.community_id;
100 let community = blocking(context.pool(), move |conn| {
101 Community::read(conn, community_id)
106 r#type: PageType::Page,
107 id: ObjectId::new(self.ap_id.clone()),
108 attributed_to: ObjectId::new(creator.actor_id),
109 to: vec![community.actor_id.into(), public()],
111 name: self.name.clone(),
112 content: self.body.as_ref().map(|b| markdown_to_html(b)),
113 media_type: Some(MediaTypeHtml::Html),
114 source: self.body.clone().map(Source::new),
115 url: self.url.clone().map(|u| u.into()),
116 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
117 image: self.thumbnail_url.clone().map(ImageObject::new),
118 comments_enabled: Some(!self.locked),
119 sensitive: Some(self.nsfw),
120 stickied: Some(self.stickied),
121 published: Some(convert_datetime(self.published)),
122 updated: self.updated.map(convert_datetime),
127 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
128 Ok(Tombstone::new(self.ap_id.clone().into()))
131 #[tracing::instrument(skip_all)]
134 expected_domain: &Url,
135 context: &LemmyContext,
136 request_counter: &mut i32,
137 ) -> Result<(), LemmyError> {
138 // We can't verify the domain in case of mod action, because the mod may be on a different
139 // instance from the post author.
140 if !page.is_mod_action(context).await? {
141 verify_domains_match(page.id.inner(), expected_domain)?;
142 verify_is_remote_object(page.id.inner())?;
145 let community = page.extract_community(context, request_counter).await?;
146 check_is_apub_id_valid(page.id.inner(), community.local, &context.settings())?;
147 verify_person_in_community(&page.attributed_to, &community, context, request_counter).await?;
148 check_slurs(&page.name, &context.settings().slur_regex())?;
149 verify_domains_match(page.attributed_to.inner(), page.id.inner())?;
150 verify_is_public(&page.to, &page.cc)?;
154 #[tracing::instrument(skip_all)]
157 context: &LemmyContext,
158 request_counter: &mut i32,
159 ) -> Result<ApubPost, LemmyError> {
162 .dereference(context, context.client(), request_counter)
164 let community = page.extract_community(context, request_counter).await?;
166 let form = if !page.is_mod_action(context).await? {
167 let url = if let Some(attachment) = page.attachment.first() {
168 Some(attachment.href.clone())
172 let thumbnail_url: Option<Url> = page.image.map(|i| i.url);
173 let (metadata_res, pictrs_thumbnail) = if let Some(url) = &url {
174 fetch_site_data(context.client(), &context.settings(), Some(url)).await
176 (None, thumbnail_url)
178 let (embed_title, embed_description, embed_html) = metadata_res
179 .map(|u| (u.title, u.description, u.html))
180 .unwrap_or((None, None, None));
181 let body_slurs_removed = read_from_string_or_source_opt(&page.content, &page.source)
182 .map(|s| remove_slurs(&s, &context.settings().slur_regex()));
185 name: page.name.clone(),
186 url: url.map(Into::into),
187 body: body_slurs_removed,
188 creator_id: creator.id,
189 community_id: community.id,
191 locked: page.comments_enabled.map(|e| !e),
192 published: page.published.map(|u| u.naive_local()),
193 updated: page.updated.map(|u| u.naive_local()),
195 nsfw: page.sensitive,
196 stickied: page.stickied,
200 thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
201 ap_id: Some(page.id.clone().into()),
205 // if is mod action, only update locked/stickied fields, nothing else
207 name: page.name.clone(),
208 creator_id: creator.id,
209 community_id: community.id,
210 locked: page.comments_enabled.map(|e| !e),
211 stickied: page.stickied,
212 updated: page.updated.map(|u| u.naive_local()),
213 ap_id: Some(page.id.clone().into()),
218 // read existing, local post if any (for generating mod log)
219 let old_post = ObjectId::<ApubPost>::new(page.id.clone())
220 .dereference_local(context)
223 let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
225 // write mod log entries for sticky/lock
226 if Page::is_stickied_changed(&old_post, &page.stickied) {
227 let form = ModStickyPostForm {
228 mod_person_id: creator.id,
230 stickied: Some(post.stickied),
232 blocking(context.pool(), move |conn| {
233 ModStickyPost::create(conn, &form)
237 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
238 let form = ModLockPostForm {
239 mod_person_id: creator.id,
241 locked: Some(post.locked),
243 blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??;
255 community::tests::parse_lemmy_community,
256 person::tests::parse_lemmy_person,
260 protocol::tests::file_to_json_object,
262 use lemmy_db_schema::source::site::Site;
263 use serial_test::serial;
267 async fn test_parse_lemmy_post() {
268 let context = init_context();
269 let (person, site) = parse_lemmy_person(&context).await;
270 let community = parse_lemmy_community(&context).await;
272 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
273 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
274 let mut request_counter = 0;
275 ApubPost::verify(&json, &url, &context, &mut request_counter)
278 let post = ApubPost::from_apub(json, &context, &mut request_counter)
282 assert_eq!(post.ap_id, url.into());
283 assert_eq!(post.name, "Post title");
284 assert!(post.body.is_some());
285 assert_eq!(post.body.as_ref().unwrap().len(), 45);
286 assert!(!post.locked);
287 assert!(post.stickied);
288 assert_eq!(request_counter, 0);
290 Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
291 Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
292 Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
293 Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();