]> Untitled Git - lemmy.git/blob - crates/apub/src/protocol/objects/page.rs
9bf8dbe59eafc857d44e5bfbd062ffb66402f10a
[lemmy.git] / crates / apub / src / protocol / objects / page.rs
1 use crate::{
2   activities::verify_community_matches,
3   fetcher::user_or_community::{PersonOrGroupType, UserOrCommunity},
4   objects::{community::ApubCommunity, person::ApubPerson, post::ApubPost},
5   protocol::{objects::LanguageTag, ImageObject, InCommunity, Source},
6 };
7 use activitypub_federation::{
8   config::Data,
9   fetch::object_id::ObjectId,
10   kinds::{
11     link::LinkType,
12     object::{DocumentType, ImageType},
13   },
14   protocol::{
15     helpers::{deserialize_one_or_many, deserialize_skip_error},
16     values::MediaTypeMarkdownOrHtml,
17   },
18   traits::{ActivityHandler, Object},
19 };
20 use chrono::{DateTime, FixedOffset};
21 use itertools::Itertools;
22 use lemmy_api_common::context::LemmyContext;
23 use lemmy_db_schema::newtypes::DbUrl;
24 use lemmy_utils::error::LemmyError;
25 use serde::{de::Error, Deserialize, Deserializer, Serialize};
26 use serde_with::skip_serializing_none;
27 use url::Url;
28
29 #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
30 pub enum PageType {
31   Page,
32   Article,
33   Note,
34   Video,
35   Event,
36 }
37
38 #[skip_serializing_none]
39 #[derive(Clone, Debug, Deserialize, Serialize)]
40 #[serde(rename_all = "camelCase")]
41 pub struct Page {
42   #[serde(rename = "type")]
43   pub(crate) kind: PageType,
44   pub(crate) id: ObjectId<ApubPost>,
45   pub(crate) attributed_to: AttributedTo,
46   #[serde(deserialize_with = "deserialize_one_or_many")]
47   pub(crate) to: Vec<Url>,
48   // If there is inReplyTo field this is actually a comment and must not be parsed
49   #[serde(deserialize_with = "deserialize_not_present", default)]
50   pub(crate) in_reply_to: Option<String>,
51
52   pub(crate) name: Option<String>,
53   #[serde(deserialize_with = "deserialize_one_or_many", default)]
54   pub(crate) cc: Vec<Url>,
55   pub(crate) content: Option<String>,
56   pub(crate) media_type: Option<MediaTypeMarkdownOrHtml>,
57   #[serde(deserialize_with = "deserialize_skip_error", default)]
58   pub(crate) source: Option<Source>,
59   /// most software uses array type for attachment field, so we do the same. nevertheless, we only
60   /// use the first item
61   #[serde(default)]
62   pub(crate) attachment: Vec<Attachment>,
63   pub(crate) image: Option<ImageObject>,
64   pub(crate) comments_enabled: Option<bool>,
65   pub(crate) sensitive: Option<bool>,
66   /// Deprecated, for compatibility with Lemmy 0.17
67   pub(crate) stickied: Option<bool>,
68   pub(crate) published: Option<DateTime<FixedOffset>>,
69   pub(crate) updated: Option<DateTime<FixedOffset>>,
70   pub(crate) language: Option<LanguageTag>,
71   pub(crate) audience: Option<ObjectId<ApubCommunity>>,
72 }
73
74 #[derive(Clone, Debug, Deserialize, Serialize)]
75 #[serde(rename_all = "camelCase")]
76 pub(crate) struct Link {
77   pub(crate) href: Url,
78   pub(crate) r#type: LinkType,
79 }
80
81 #[derive(Clone, Debug, Deserialize, Serialize)]
82 #[serde(rename_all = "camelCase")]
83 pub(crate) struct Image {
84   #[serde(rename = "type")]
85   pub(crate) kind: ImageType,
86   pub(crate) url: Url,
87 }
88
89 #[derive(Clone, Debug, Deserialize, Serialize)]
90 #[serde(rename_all = "camelCase")]
91 pub(crate) struct Document {
92   #[serde(rename = "type")]
93   pub(crate) kind: DocumentType,
94   pub(crate) url: Url,
95 }
96
97 #[derive(Clone, Debug, Deserialize, Serialize)]
98 #[serde(untagged)]
99 pub(crate) enum Attachment {
100   Link(Link),
101   Image(Image),
102   Document(Document),
103 }
104
105 impl Attachment {
106   pub(crate) fn url(self) -> Url {
107     match self {
108       // url as sent by Lemmy (new)
109       Attachment::Link(l) => l.href,
110       // image sent by lotide
111       Attachment::Image(i) => i.url,
112       // sent by mobilizon
113       Attachment::Document(d) => d.url,
114     }
115   }
116 }
117
118 #[derive(Clone, Debug, Deserialize, Serialize)]
119 #[serde(untagged)]
120 pub(crate) enum AttributedTo {
121   Lemmy(ObjectId<ApubPerson>),
122   Peertube([AttributedToPeertube; 2]),
123 }
124
125 #[derive(Clone, Debug, Deserialize, Serialize)]
126 #[serde(rename_all = "camelCase")]
127 pub(crate) struct AttributedToPeertube {
128   #[serde(rename = "type")]
129   pub kind: PersonOrGroupType,
130   pub id: ObjectId<UserOrCommunity>,
131 }
132
133 impl Page {
134   /// Only mods can change the post's stickied/locked status. So if either of these is changed from
135   /// the current value, it is a mod action and needs to be verified as such.
136   ///
137   /// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]].
138   pub(crate) async fn is_mod_action(
139     &self,
140     context: &Data<LemmyContext>,
141   ) -> Result<bool, LemmyError> {
142     let old_post = self.id.clone().dereference_local(context).await;
143
144     let featured_changed = Page::is_featured_changed(&old_post, &self.stickied);
145     let locked_changed = Page::is_locked_changed(&old_post, &self.comments_enabled);
146     Ok(featured_changed || locked_changed)
147   }
148
149   pub(crate) fn is_featured_changed<E>(
150     old_post: &Result<ApubPost, E>,
151     new_featured_community: &Option<bool>,
152   ) -> bool {
153     if let Some(new_featured_community) = new_featured_community {
154       if let Ok(old_post) = old_post {
155         return new_featured_community != &old_post.featured_community;
156       }
157     }
158
159     false
160   }
161
162   pub(crate) fn is_locked_changed<E>(
163     old_post: &Result<ApubPost, E>,
164     new_comments_enabled: &Option<bool>,
165   ) -> bool {
166     if let Some(new_comments_enabled) = new_comments_enabled {
167       if let Ok(old_post) = old_post {
168         return new_comments_enabled != &!old_post.locked;
169       }
170     }
171
172     false
173   }
174
175   pub(crate) fn creator(&self) -> Result<ObjectId<ApubPerson>, LemmyError> {
176     match &self.attributed_to {
177       AttributedTo::Lemmy(l) => Ok(l.clone()),
178       AttributedTo::Peertube(p) => p
179         .iter()
180         .find(|a| a.kind == PersonOrGroupType::Person)
181         .map(|a| ObjectId::<ApubPerson>::from(a.id.clone().into_inner()))
182         .ok_or_else(|| LemmyError::from_message("page does not specify creator person")),
183     }
184   }
185 }
186
187 impl Attachment {
188   pub(crate) fn new(url: DbUrl) -> Attachment {
189     Attachment::Link(Link {
190       href: url.into(),
191       r#type: Default::default(),
192     })
193   }
194 }
195
196 // Used for community outbox, so that it can be compatible with Pleroma/Mastodon.
197 #[async_trait::async_trait]
198 impl ActivityHandler for Page {
199   type DataType = LemmyContext;
200   type Error = LemmyError;
201   fn id(&self) -> &Url {
202     unimplemented!()
203   }
204   fn actor(&self) -> &Url {
205     unimplemented!()
206   }
207   async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), LemmyError> {
208     ApubPost::verify(self, self.id.inner(), data).await
209   }
210   async fn receive(self, data: &Data<Self::DataType>) -> Result<(), LemmyError> {
211     ApubPost::from_json(self, data).await?;
212     Ok(())
213   }
214 }
215
216 #[async_trait::async_trait]
217 impl InCommunity for Page {
218   async fn community(&self, context: &Data<LemmyContext>) -> Result<ApubCommunity, LemmyError> {
219     let community = match &self.attributed_to {
220       AttributedTo::Lemmy(_) => {
221         let mut iter = self.to.iter().merge(self.cc.iter());
222         loop {
223           if let Some(cid) = iter.next() {
224             let cid = ObjectId::from(cid.clone());
225             if let Ok(c) = cid.dereference(context).await {
226               break c;
227             }
228           } else {
229             return Err(LemmyError::from_message("No community found in cc"));
230           }
231         }
232       }
233       AttributedTo::Peertube(p) => {
234         p.iter()
235           .find(|a| a.kind == PersonOrGroupType::Group)
236           .map(|a| ObjectId::<ApubCommunity>::from(a.id.clone().into_inner()))
237           .ok_or_else(|| LemmyError::from_message("page does not specify group"))?
238           .dereference(context)
239           .await?
240       }
241     };
242     if let Some(audience) = &self.audience {
243       verify_community_matches(audience, community.actor_id.clone())?;
244     }
245     Ok(community)
246   }
247 }
248
249 /// Only allows deserialization if the field is missing or null. If it is present, throws an error.
250 pub fn deserialize_not_present<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
251 where
252   D: Deserializer<'de>,
253 {
254   let result: Option<String> = Deserialize::deserialize(deserializer)?;
255   match result {
256     None => Ok(None),
257     Some(_) => Err(D::Error::custom("Post must not have inReplyTo property")),
258   }
259 }
260
261 #[cfg(test)]
262 mod tests {
263   use crate::protocol::{objects::page::Page, tests::test_parse_lemmy_item};
264
265   #[test]
266   fn test_not_parsing_note_as_page() {
267     assert!(test_parse_lemmy_item::<Page>("assets/lemmy/objects/note.json").is_err());
268   }
269 }