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, LanguageTag, 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::{
26 moderator::{ModLockPost, ModLockPostForm, ModStickyPost, ModStickyPostForm},
28 post::{Post, PostForm},
34 utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
36 use lemmy_websocket::LemmyContext;
40 #[derive(Clone, Debug)]
41 pub struct ApubPost(Post);
43 impl Deref for ApubPost {
45 fn deref(&self) -> &Self::Target {
50 impl From<Post> for ApubPost {
51 fn from(p: Post) -> Self {
56 #[async_trait::async_trait(?Send)]
57 impl ApubObject for ApubPost {
58 type DataType = LemmyContext;
61 type Error = LemmyError;
63 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
67 #[tracing::instrument(skip_all)]
68 async fn read_from_apub_id(
70 context: &LemmyContext,
71 ) -> Result<Option<Self>, LemmyError> {
73 blocking(context.pool(), move |conn| {
74 Post::read_from_apub_id(conn, object_id)
81 #[tracing::instrument(skip_all)]
82 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
84 blocking(context.pool(), move |conn| {
85 Post::update_deleted(conn, self.id, true)
92 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
93 #[tracing::instrument(skip_all)]
94 async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
95 let creator_id = self.creator_id;
96 let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
97 let community_id = self.community_id;
98 let community = blocking(context.pool(), move |conn| {
99 Community::read(conn, community_id)
102 let language = self.language_id;
103 let language = blocking(context.pool(), move |conn| {
104 Language::read_from_id(conn, language)
109 kind: PageType::Page,
110 id: ObjectId::new(self.ap_id.clone()),
111 attributed_to: AttributedTo::Lemmy(ObjectId::new(creator.actor_id)),
112 to: vec![community.actor_id.into(), public()],
114 name: self.name.clone(),
115 content: self.body.as_ref().map(|b| markdown_to_html(b)),
116 media_type: Some(MediaTypeMarkdownOrHtml::Html),
117 source: self.body.clone().map(Source::new),
118 url: self.url.clone().map(|u| u.into()),
119 attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
120 image: self.thumbnail_url.clone().map(ImageObject::new),
121 comments_enabled: Some(!self.locked),
122 sensitive: Some(self.nsfw),
123 stickied: Some(self.stickied),
124 language: LanguageTag::new(language),
125 published: Some(convert_datetime(self.published)),
126 updated: self.updated.map(convert_datetime),
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(), context.settings())?;
145 let community = page.extract_community(context, request_counter).await?;
146 check_apub_id_valid_with_strictness(page.id.inner(), community.local, context.settings())?;
147 verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
148 check_slurs(&page.name, &context.settings().slur_regex())?;
149 verify_domains_match(page.creator()?.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, local_instance(context), 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(match attachment {
169 // url as sent by Lemmy (new)
170 Attachment::Link(link) => link.href.clone(),
171 Attachment::Image(image) => image.url.clone(),
173 } else if page.kind == PageType::Video {
174 // we cant display videos directly, so insert a link to external video page
175 Some(page.id.inner().clone())
177 // url sent by lemmy (old)
180 let (metadata_res, thumbnail_url) = if let Some(url) = &url {
181 fetch_site_data(context.client(), context.settings(), Some(url)).await
183 (None, page.image.map(|i| i.url.into()))
185 let (embed_title, embed_description, embed_video_url) = metadata_res
186 .map(|u| (Some(u.title), Some(u.description), Some(u.embed_video_url)))
187 .unwrap_or_default();
188 let body_slurs_removed =
189 read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
190 .map(|s| Some(remove_slurs(&s, &context.settings().slur_regex())));
191 let language = page.language.map(|l| l.identifier);
192 let language = blocking(context.pool(), move |conn| {
193 Language::read_id_from_code_opt(conn, language.as_deref())
198 name: page.name.clone(),
199 url: Some(url.map(Into::into)),
200 body: body_slurs_removed,
201 creator_id: creator.id,
202 community_id: community.id,
204 locked: page.comments_enabled.map(|e| !e),
205 published: page.published.map(|u| u.naive_local()),
206 updated: page.updated.map(|u| u.naive_local()),
208 nsfw: page.sensitive,
209 stickied: page.stickied,
213 thumbnail_url: Some(thumbnail_url),
214 ap_id: Some(page.id.clone().into()),
216 language_id: language,
219 // if is mod action, only update locked/stickied fields, nothing else
221 name: page.name.clone(),
222 creator_id: creator.id,
223 community_id: community.id,
224 locked: page.comments_enabled.map(|e| !e),
225 stickied: page.stickied,
226 updated: page.updated.map(|u| u.naive_local()),
227 ap_id: Some(page.id.clone().into()),
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 = blocking(context.pool(), move |conn| Post::upsert(conn, &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 blocking(context.pool(), move |conn| {
247 ModStickyPost::create(conn, &form)
251 if Page::is_locked_changed(&old_post, &page.comments_enabled) {
252 let form = ModLockPostForm {
253 mod_person_id: creator.id,
255 locked: Some(post.locked),
257 blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??;
269 community::tests::parse_lemmy_community,
270 person::tests::parse_lemmy_person,
274 protocol::tests::file_to_json_object,
276 use lemmy_db_schema::source::site::Site;
277 use serial_test::serial;
281 async fn test_parse_lemmy_post() {
282 let context = init_context();
283 let (person, site) = parse_lemmy_person(&context).await;
284 let community = parse_lemmy_community(&context).await;
286 let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
287 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
288 let mut request_counter = 0;
289 ApubPost::verify(&json, &url, &context, &mut request_counter)
292 let post = ApubPost::from_apub(json, &context, &mut request_counter)
296 assert_eq!(post.ap_id, url.into());
297 assert_eq!(post.name, "Post title");
298 assert!(post.body.is_some());
299 assert_eq!(post.body.as_ref().unwrap().len(), 45);
300 assert!(!post.locked);
301 assert!(post.stickied);
302 assert_eq!(request_counter, 0);
304 Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
305 Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
306 Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
307 Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();