]> Untitled Git - lemmy.git/blob - crates/apub/src/protocol/objects/page.rs
89fb11415c425afb03d319b5f427706884277b87
[lemmy.git] / crates / apub / src / protocol / objects / page.rs
1 use crate::{
2   objects::{community::ApubCommunity, person::ApubPerson, post::ApubPost},
3   protocol::{ImageObject, Source},
4 };
5 use activitystreams::{object::kind::PageType, unparsed::Unparsed};
6 use anyhow::anyhow;
7 use chrono::{DateTime, FixedOffset};
8 use lemmy_apub_lib::{object_id::ObjectId, values::MediaTypeHtml};
9 use lemmy_utils::LemmyError;
10 use lemmy_websocket::LemmyContext;
11 use serde::{Deserialize, Serialize};
12 use serde_with::skip_serializing_none;
13 use url::Url;
14
15 #[skip_serializing_none]
16 #[derive(Clone, Debug, Deserialize, Serialize)]
17 #[serde(rename_all = "camelCase")]
18 pub struct Page {
19   pub(crate) r#type: PageType,
20   pub(crate) id: ObjectId<ApubPost>,
21   pub(crate) attributed_to: ObjectId<ApubPerson>,
22   pub(crate) to: Vec<Url>,
23   #[serde(default)]
24   pub(crate) cc: Vec<Url>,
25   pub(crate) name: String,
26   pub(crate) content: Option<String>,
27   pub(crate) media_type: Option<MediaTypeHtml>,
28   pub(crate) source: Option<Source>,
29   pub(crate) url: Option<Url>,
30   pub(crate) image: Option<ImageObject>,
31   pub(crate) comments_enabled: Option<bool>,
32   pub(crate) sensitive: Option<bool>,
33   pub(crate) stickied: Option<bool>,
34   pub(crate) published: Option<DateTime<FixedOffset>>,
35   pub(crate) updated: Option<DateTime<FixedOffset>>,
36   #[serde(flatten)]
37   pub(crate) unparsed: Unparsed,
38 }
39
40 impl Page {
41   /// Only mods can change the post's stickied/locked status. So if either of these is changed from
42   /// the current value, it is a mod action and needs to be verified as such.
43   ///
44   /// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]].
45   pub(crate) async fn is_mod_action(&self, context: &LemmyContext) -> Result<bool, LemmyError> {
46     let old_post = ObjectId::<ApubPost>::new(self.id.clone())
47       .dereference_local(context)
48       .await;
49
50     let is_mod_action = if let Ok(old_post) = old_post {
51       self.stickied != Some(old_post.stickied) || self.comments_enabled != Some(!old_post.locked)
52     } else {
53       false
54     };
55     Ok(is_mod_action)
56   }
57
58   pub(crate) async fn extract_community(
59     &self,
60     context: &LemmyContext,
61     request_counter: &mut i32,
62   ) -> Result<ApubCommunity, LemmyError> {
63     let mut to_iter = self.to.iter();
64     loop {
65       if let Some(cid) = to_iter.next() {
66         let cid = ObjectId::new(cid.clone());
67         if let Ok(c) = cid.dereference(context, request_counter).await {
68           break Ok(c);
69         }
70       } else {
71         return Err(anyhow!("No community found in cc").into());
72       }
73     }
74   }
75 }