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},
15 use activitypub_federation::{
16 core::object_id::ObjectId,
17 deser::values::MediaTypeMarkdownOrHtml,
19 utils::verify_domains_match,
21 use activitystreams_kinds::public;
22 use chrono::NaiveDateTime;
23 use lemmy_api_common::{request::fetch_site_data, utils::blocking};
24 use lemmy_db_schema::{
28 moderator::{ModLockPost, ModLockPostForm, ModStickyPost, ModStickyPostForm},
30 post::{Post, PostForm},
36 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 Error = LemmyError;
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)
104 let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
107 kind: PageType::Page,
108 id: ObjectId::new(self.ap_id.clone()),
109 attributed_to: AttributedTo::Lemmy(ObjectId::new(creator.actor_id)),
110 to: vec![community.actor_id.into(), public()],
112 name: self.name.clone(),
113 content: self.body.as_ref().map(|b| markdown_to_html(b)),
114 media_type: Some(MediaTypeMarkdownOrHtml::Html),
115 source: self.body.clone().map(Source::new),
116 url: self.url.clone().map(|u| u.into()),
117 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
118 image: self.thumbnail_url.clone().map(ImageObject::new),
119 comments_enabled: Some(!self.locked),
120 sensitive: Some(self.nsfw),
121 stickied: Some(self.stickied),
123 published: Some(convert_datetime(self.published)),
124 updated: self.updated.map(convert_datetime),
129 #[tracing::instrument(skip_all)]
132 expected_domain: &Url,
133 context: &LemmyContext,
134 request_counter: &mut i32,
135 ) -> Result<(), LemmyError> {
136 // We can't verify the domain in case of mod action, because the mod may be on a different
137 // instance from the post author.
138 if !page.is_mod_action(context).await? {
139 verify_domains_match(page.id.inner(), expected_domain)?;
140 verify_is_remote_object(page.id.inner(), context.settings())?;
143 let community = page.extract_community(context, request_counter).await?;
144 check_apub_id_valid_with_strictness(page.id.inner(), community.local, context.settings())?;
145 verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
146 check_slurs(&page.name, &context.settings().slur_regex())?;
147 verify_domains_match(page.creator()?.inner(), page.id.inner())?;
148 verify_is_public(&page.to, &page.cc)?;
152 #[tracing::instrument(skip_all)]
155 context: &LemmyContext,
156 request_counter: &mut i32,
157 ) -> Result<ApubPost, LemmyError> {
160 .dereference(context, local_instance(context), request_counter)
162 let community = page.extract_community(context, request_counter).await?;
164 let form = if !page.is_mod_action(context).await? {
165 let url = if let Some(attachment) = page.attachment.first() {
166 Some(match attachment {
167 // url as sent by Lemmy (new)
168 Attachment::Link(link) => link.href.clone(),
169 Attachment::Image(image) => image.url.clone(),
171 } else if page.kind == PageType::Video {
172 // we cant display videos directly, so insert a link to external video page
173 Some(page.id.inner().clone())
175 // url sent by lemmy (old)
178 let (metadata_res, thumbnail_url) = if let Some(url) = &url {
179 fetch_site_data(context.client(), context.settings(), Some(url)).await
181 (None, page.image.map(|i| i.url.into()))
183 let (embed_title, embed_description, embed_video_url) = metadata_res
184 .map(|u| (Some(u.title), Some(u.description), Some(u.embed_video_url)))
185 .unwrap_or_default();
186 let body_slurs_removed =
187 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
188 .map(|s| Some(remove_slurs(&s, &context.settings().slur_regex())));
189 let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
192 name: page.name.clone(),
193 url: Some(url.map(Into::into)),
194 body: body_slurs_removed,
195 creator_id: creator.id,
196 community_id: community.id,
198 locked: page.comments_enabled.map(|e| !e),
199 published: page.published.map(|u| u.naive_local()),
200 updated: page.updated.map(|u| u.naive_local()),
202 nsfw: page.sensitive,
203 stickied: page.stickied,
207 thumbnail_url: Some(thumbnail_url),
208 ap_id: Some(page.id.clone().into()),
213 // if is mod action, only update locked/stickied fields, nothing else
215 name: page.name.clone(),
216 creator_id: creator.id,
217 community_id: community.id,
218 locked: page.comments_enabled.map(|e| !e),
219 stickied: page.stickied,
220 updated: page.updated.map(|u| u.naive_local()),
221 ap_id: Some(page.id.clone().into()),
226 // read existing, local post if any (for generating mod log)
227 let old_post = ObjectId::<ApubPost>::new(page.id.clone())
228 .dereference_local(context)
231 let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
233 // write mod log entries for sticky/lock
234 if Page::is_stickied_changed(&old_post, &page.stickied) {
235 let form = ModStickyPostForm {
236 mod_person_id: creator.id,
238 stickied: Some(post.stickied),
240 blocking(context.pool(), move |conn| {
241 ModStickyPost::create(conn, &form)
245 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
246 let form = ModLockPostForm {
247 mod_person_id: creator.id,
249 locked: Some(post.locked),
251 blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??;
263 community::tests::parse_lemmy_community,
264 person::tests::parse_lemmy_person,
268 protocol::tests::file_to_json_object,
270 use lemmy_db_schema::source::site::Site;
271 use serial_test::serial;
275 async fn test_parse_lemmy_post() {
276 let context = init_context();
277 let conn = &mut context.pool().get().unwrap();
278 let (person, site) = parse_lemmy_person(&context).await;
279 let community = parse_lemmy_community(&context).await;
281 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
282 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
283 let mut request_counter = 0;
284 ApubPost::verify(&json, &url, &context, &mut request_counter)
287 let post = ApubPost::from_apub(json, &context, &mut request_counter)
291 assert_eq!(post.ap_id, url.into());
292 assert_eq!(post.name, "Post title");
293 assert!(post.body.is_some());
294 assert_eq!(post.body.as_ref().unwrap().len(), 45);
295 assert!(!post.locked);
296 assert!(post.stickied);
297 assert_eq!(request_counter, 0);
299 Post::delete(conn, post.id).unwrap();
300 Person::delete(conn, person.id).unwrap();
301 Community::delete(conn, community.id).unwrap();
302 Site::delete(conn, site.id).unwrap();