2 activities::{verify_is_public, verify_person_in_community},
3 context::lemmy_context,
4 fetcher::object_id::ObjectId,
6 community::ApubCommunity,
13 use activitystreams::{
15 object::kind::{ImageType, PageType},
16 primitives::OneOrMany,
21 use chrono::{DateTime, FixedOffset, NaiveDateTime};
22 use lemmy_api_common::blocking;
25 values::{MediaTypeHtml, MediaTypeMarkdown},
26 verify::verify_domains_match,
28 use lemmy_db_schema::{
33 post::{Post, PostForm},
38 request::fetch_site_data,
39 utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
42 use lemmy_websocket::LemmyContext;
43 use serde::{Deserialize, Serialize};
44 use serde_with::skip_serializing_none;
48 #[skip_serializing_none]
49 #[derive(Clone, Debug, Deserialize, Serialize)]
50 #[serde(rename_all = "camelCase")]
52 #[serde(rename = "@context")]
53 context: OneOrMany<AnyBase>,
56 pub(crate) attributed_to: ObjectId<ApubPerson>,
59 content: Option<String>,
60 media_type: Option<MediaTypeHtml>,
61 source: Option<Source>,
63 image: Option<ImageObject>,
64 pub(crate) comments_enabled: Option<bool>,
65 sensitive: Option<bool>,
66 pub(crate) stickied: Option<bool>,
67 published: Option<DateTime<FixedOffset>>,
68 updated: Option<DateTime<FixedOffset>>,
74 pub(crate) fn id_unchecked(&self) -> &Url {
77 pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
78 verify_domains_match(&self.id, expected_domain)?;
82 /// Only mods can change the post's stickied/locked status. So if either of these is changed from
83 /// the current value, it is a mod action and needs to be verified as such.
85 /// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]].
86 pub(crate) async fn is_mod_action(&self, context: &LemmyContext) -> Result<bool, LemmyError> {
87 let old_post = ObjectId::<ApubPost>::new(self.id.clone())
88 .dereference_local(context)
91 let is_mod_action = if let Ok(old_post) = old_post {
92 self.stickied != Some(old_post.stickied) || self.comments_enabled != Some(!old_post.locked)
99 pub(crate) async fn verify(
101 context: &LemmyContext,
102 request_counter: &mut i32,
103 ) -> Result<(), LemmyError> {
104 let community = self.extract_community(context, request_counter).await?;
106 check_slurs(&self.name, &context.settings().slur_regex())?;
107 verify_domains_match(self.attributed_to.inner(), &self.id.clone())?;
108 verify_person_in_community(&self.attributed_to, &community, context, request_counter).await?;
109 verify_is_public(&self.to.clone())?;
113 pub(crate) async fn extract_community(
115 context: &LemmyContext,
116 request_counter: &mut i32,
117 ) -> Result<ApubCommunity, LemmyError> {
118 let mut to_iter = self.to.iter();
120 if let Some(cid) = to_iter.next() {
121 let cid = ObjectId::new(cid.clone());
122 if let Ok(c) = cid.dereference(context, request_counter).await {
126 return Err(anyhow!("No community found in cc").into());
132 #[derive(Clone, Debug)]
133 pub struct ApubPost(Post);
135 impl Deref for ApubPost {
137 fn deref(&self) -> &Self::Target {
142 impl From<Post> for ApubPost {
143 fn from(p: Post) -> Self {
148 #[async_trait::async_trait(?Send)]
149 impl ApubObject for ApubPost {
150 type DataType = LemmyContext;
151 type ApubType = Page;
152 type TombstoneType = Tombstone;
154 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
158 async fn read_from_apub_id(
160 context: &LemmyContext,
161 ) -> Result<Option<Self>, LemmyError> {
163 blocking(context.pool(), move |conn| {
164 Post::read_from_apub_id(conn, object_id)
171 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
172 blocking(context.pool(), move |conn| {
173 Post::update_deleted(conn, self.id, true)
179 // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
180 async fn to_apub(&self, context: &LemmyContext) -> Result<Page, LemmyError> {
181 let creator_id = self.creator_id;
182 let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
183 let community_id = self.community_id;
184 let community = blocking(context.pool(), move |conn| {
185 Community::read(conn, community_id)
189 let source = self.body.clone().map(|body| Source {
191 media_type: MediaTypeMarkdown::Markdown,
193 let image = self.thumbnail_url.clone().map(|thumb| ImageObject {
194 kind: ImageType::Image,
199 context: lemmy_context(),
200 r#type: PageType::Page,
201 id: self.ap_id.clone().into(),
202 attributed_to: ObjectId::new(creator.actor_id),
203 to: vec![community.actor_id.into(), public()],
204 name: self.name.clone(),
205 content: self.body.as_ref().map(|b| markdown_to_html(b)),
206 media_type: Some(MediaTypeHtml::Html),
208 url: self.url.clone().map(|u| u.into()),
210 comments_enabled: Some(!self.locked),
211 sensitive: Some(self.nsfw),
212 stickied: Some(self.stickied),
213 published: Some(convert_datetime(self.published)),
214 updated: self.updated.map(convert_datetime),
215 unparsed: Default::default(),
220 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
223 self.updated.unwrap_or(self.published),
229 context: &LemmyContext,
230 expected_domain: &Url,
231 request_counter: &mut i32,
232 ) -> Result<ApubPost, LemmyError> {
233 // We can't verify the domain in case of mod action, because the mod may be on a different
234 // instance from the post author.
235 let ap_id = if page.is_mod_action(context).await? {
238 page.id(expected_domain)?
240 let ap_id = Some(ap_id.clone().into());
243 .dereference(context, request_counter)
245 let community = page.extract_community(context, request_counter).await?;
246 verify_person_in_community(&page.attributed_to, &community, context, request_counter).await?;
248 let thumbnail_url: Option<Url> = page.image.clone().map(|i| i.url);
249 let (metadata_res, pictrs_thumbnail) = if let Some(url) = &page.url {
250 fetch_site_data(context.client(), &context.settings(), Some(url)).await
252 (None, thumbnail_url)
254 let (embed_title, embed_description, embed_html) = metadata_res
255 .map(|u| (u.title, u.description, u.html))
256 .unwrap_or((None, None, None));
258 let body_slurs_removed = page
261 .map(|s| remove_slurs(&s.content, &context.settings().slur_regex()));
262 let form = PostForm {
263 name: page.name.clone(),
264 url: page.url.clone().map(|u| u.into()),
265 body: body_slurs_removed,
266 creator_id: creator.id,
267 community_id: community.id,
269 locked: page.comments_enabled.map(|e| !e),
270 published: page.published.map(|u| u.naive_local()),
271 updated: page.updated.map(|u| u.naive_local()),
273 nsfw: page.sensitive,
274 stickied: page.stickied,
278 thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
282 let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
290 use crate::objects::{
291 community::ApubCommunity,
292 tests::{file_to_json_object, init_context},
294 use assert_json_diff::assert_json_include;
295 use serial_test::serial;
299 async fn test_parse_lemmy_post() {
300 let context = init_context();
301 let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
302 let community_json = file_to_json_object("assets/lemmy-community.json");
303 let community = ApubCommunity::from_apub(&community_json, &context, &url, &mut 0)
306 let person_json = file_to_json_object("assets/lemmy-person.json");
307 let person = ApubPerson::from_apub(&person_json, &context, &url, &mut 0)
310 let json = file_to_json_object("assets/lemmy-post.json");
311 let mut request_counter = 0;
312 let post = ApubPost::from_apub(&json, &context, &url, &mut request_counter)
316 assert_eq!(post.ap_id.clone().into_inner(), url);
317 assert_eq!(post.name, "Post title");
318 assert!(post.body.is_some());
319 assert_eq!(post.body.as_ref().unwrap().len(), 45);
320 assert!(!post.locked);
321 assert!(post.stickied);
322 assert_eq!(request_counter, 0);
324 let to_apub = post.to_apub(&context).await.unwrap();
325 assert_json_include!(actual: json, expected: to_apub);
327 Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
328 Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
329 Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();