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},
7 objects::page::{Attachment, AttributedTo, Page, PageType},
12 use activitypub_federation::{
13 core::object_id::ObjectId,
14 deser::values::MediaTypeMarkdownOrHtml,
16 utils::verify_domains_match,
18 use activitystreams_kinds::public;
19 use chrono::NaiveDateTime;
20 use lemmy_api_common::{request::fetch_site_data, utils::blocking};
21 use lemmy_db_schema::{
25 moderator::{ModLockPost, ModLockPostForm, ModStickyPost, ModStickyPostForm},
27 post::{Post, PostForm},
33 utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
35 use lemmy_websocket::LemmyContext;
39 #[derive(Clone, Debug)]
40 pub struct ApubPost(Post);
42 impl Deref for ApubPost {
44 fn deref(&self) -> &Self::Target {
49 impl From<Post> for ApubPost {
50 fn from(p: Post) -> Self {
55 #[async_trait::async_trait(?Send)]
56 impl ApubObject for ApubPost {
57 type DataType = LemmyContext;
60 type Error = LemmyError;
62 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
66 #[tracing::instrument(skip_all)]
67 async fn read_from_apub_id(
69 context: &LemmyContext,
70 ) -> Result<Option<Self>, LemmyError> {
72 blocking(context.pool(), move |conn| {
73 Post::read_from_apub_id(conn, object_id)
80 #[tracing::instrument(skip_all)]
81 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
83 blocking(context.pool(), move |conn| {
84 Post::update_deleted(conn, self.id, true)
91 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
92 #[tracing::instrument(skip_all)]
93 async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
94 let creator_id = self.creator_id;
95 let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
96 let community_id = self.community_id;
97 let community = blocking(context.pool(), move |conn| {
98 Community::read(conn, community_id)
103 kind: PageType::Page,
104 id: ObjectId::new(self.ap_id.clone()),
105 attributed_to: AttributedTo::Lemmy(ObjectId::new(creator.actor_id)),
106 to: vec![community.actor_id.into(), public()],
108 name: self.name.clone(),
109 content: self.body.as_ref().map(|b| markdown_to_html(b)),
110 media_type: Some(MediaTypeMarkdownOrHtml::Html),
111 source: self.body.clone().map(Source::new),
112 url: self.url.clone().map(|u| u.into()),
113 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
114 image: self.thumbnail_url.clone().map(ImageObject::new),
115 comments_enabled: Some(!self.locked),
116 sensitive: Some(self.nsfw),
117 stickied: Some(self.stickied),
118 published: Some(convert_datetime(self.published)),
119 updated: self.updated.map(convert_datetime),
124 #[tracing::instrument(skip_all)]
127 expected_domain: &Url,
128 context: &LemmyContext,
129 request_counter: &mut i32,
130 ) -> Result<(), LemmyError> {
131 // We can't verify the domain in case of mod action, because the mod may be on a different
132 // instance from the post author.
133 if !page.is_mod_action(context).await? {
134 verify_domains_match(page.id.inner(), expected_domain)?;
135 verify_is_remote_object(page.id.inner(), context.settings())?;
138 let community = page.extract_community(context, request_counter).await?;
139 check_apub_id_valid_with_strictness(page.id.inner(), community.local, context.settings())?;
140 verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
141 check_slurs(&page.name, &context.settings().slur_regex())?;
142 verify_domains_match(page.creator()?.inner(), page.id.inner())?;
143 verify_is_public(&page.to, &page.cc)?;
147 #[tracing::instrument(skip_all)]
150 context: &LemmyContext,
151 request_counter: &mut i32,
152 ) -> Result<ApubPost, LemmyError> {
155 .dereference(context, local_instance(context), request_counter)
157 let community = page.extract_community(context, request_counter).await?;
159 let form = if !page.is_mod_action(context).await? {
160 let url = if let Some(attachment) = page.attachment.first() {
161 // url as sent by Lemmy (new)
162 Some(attachment.href.clone())
163 } else if page.kind == PageType::Video {
164 // we cant display videos directly, so insert a link to external video page
165 Some(page.id.inner().clone())
167 // url sent by lemmy (old)
170 let (metadata_res, thumbnail_url) = if let Some(url) = &url {
171 fetch_site_data(context.client(), context.settings(), Some(url)).await
173 (None, page.image.map(|i| i.url.into()))
175 let (embed_title, embed_description, embed_video_url) = metadata_res
176 .map(|u| (Some(u.title), Some(u.description), Some(u.embed_video_url)))
177 .unwrap_or_default();
178 let body_slurs_removed =
179 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
180 .map(|s| Some(remove_slurs(&s, &context.settings().slur_regex())));
183 name: page.name.clone(),
184 url: Some(url.map(Into::into)),
185 body: body_slurs_removed,
186 creator_id: creator.id,
187 community_id: community.id,
189 locked: page.comments_enabled.map(|e| !e),
190 published: page.published.map(|u| u.naive_local()),
191 updated: page.updated.map(|u| u.naive_local()),
193 nsfw: page.sensitive,
194 stickied: page.stickied,
198 thumbnail_url: Some(thumbnail_url),
199 ap_id: Some(page.id.clone().into()),
203 // if is mod action, only update locked/stickied fields, nothing else
205 name: page.name.clone(),
206 creator_id: creator.id,
207 community_id: community.id,
208 locked: page.comments_enabled.map(|e| !e),
209 stickied: page.stickied,
210 updated: page.updated.map(|u| u.naive_local()),
211 ap_id: Some(page.id.clone().into()),
216 // read existing, local post if any (for generating mod log)
217 let old_post = ObjectId::<ApubPost>::new(page.id.clone())
218 .dereference_local(context)
221 let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
223 // write mod log entries for sticky/lock
224 if Page::is_stickied_changed(&old_post, &page.stickied) {
225 let form = ModStickyPostForm {
226 mod_person_id: creator.id,
228 stickied: Some(post.stickied),
230 blocking(context.pool(), move |conn| {
231 ModStickyPost::create(conn, &form)
235 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
236 let form = ModLockPostForm {
237 mod_person_id: creator.id,
239 locked: Some(post.locked),
241 blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??;
253 community::tests::parse_lemmy_community,
254 person::tests::parse_lemmy_person,
258 protocol::tests::file_to_json_object,
260 use lemmy_db_schema::source::site::Site;
261 use serial_test::serial;
265 async fn test_parse_lemmy_post() {
266 let context = init_context();
267 let (person, site) = parse_lemmy_person(&context).await;
268 let community = parse_lemmy_community(&context).await;
270 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
271 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
272 let mut request_counter = 0;
273 ApubPost::verify(&json, &url, &context, &mut request_counter)
276 let post = ApubPost::from_apub(json, &context, &mut request_counter)
280 assert_eq!(post.ap_id, url.into());
281 assert_eq!(post.name, "Post title");
282 assert!(post.body.is_some());
283 assert_eq!(post.body.as_ref().unwrap().len(), 45);
284 assert!(!post.locked);
285 assert!(post.stickied);
286 assert_eq!(request_counter, 0);
288 Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
289 Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
290 Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
291 Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();