]> Untitled Git - lemmy.git/blob - crates/apub/src/protocol/objects/page.rs
Implement separate mod activities for feature, lock post (#2716)
[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   local_instance,
5   objects::{community::ApubCommunity, person::ApubPerson, post::ApubPost},
6   protocol::{objects::LanguageTag, ImageObject, InCommunity, Source},
7 };
8 use activitypub_federation::{
9   core::object_id::ObjectId,
10   data::Data,
11   deser::{
12     helpers::{deserialize_one_or_many, deserialize_skip_error},
13     values::MediaTypeMarkdownOrHtml,
14   },
15   traits::{ActivityHandler, ApubObject},
16 };
17 use activitystreams_kinds::{
18   link::LinkType,
19   object::{DocumentType, ImageType},
20 };
21 use chrono::{DateTime, FixedOffset};
22 use itertools::Itertools;
23 use lemmy_api_common::context::LemmyContext;
24 use lemmy_db_schema::newtypes::DbUrl;
25 use lemmy_utils::error::LemmyError;
26 use serde::{de::Error, Deserialize, Deserializer, Serialize};
27 use serde_with::skip_serializing_none;
28 use url::Url;
29
30 #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
31 pub enum PageType {
32   Page,
33   Article,
34   Note,
35   Video,
36   Event,
37 }
38
39 #[skip_serializing_none]
40 #[derive(Clone, Debug, Deserialize, Serialize)]
41 #[serde(rename_all = "camelCase")]
42 pub struct Page {
43   #[serde(rename = "type")]
44   pub(crate) kind: PageType,
45   pub(crate) id: ObjectId<ApubPost>,
46   pub(crate) attributed_to: AttributedTo,
47   #[serde(deserialize_with = "deserialize_one_or_many")]
48   pub(crate) to: Vec<Url>,
49   // If there is inReplyTo field this is actually a comment and must not be parsed
50   #[serde(deserialize_with = "deserialize_not_present", default)]
51   pub(crate) in_reply_to: Option<String>,
52
53   pub(crate) name: Option<String>,
54   #[serde(deserialize_with = "deserialize_one_or_many", default)]
55   pub(crate) cc: Vec<Url>,
56   pub(crate) content: Option<String>,
57   pub(crate) media_type: Option<MediaTypeMarkdownOrHtml>,
58   #[serde(deserialize_with = "deserialize_skip_error", default)]
59   pub(crate) source: Option<Source>,
60   /// most software uses array type for attachment field, so we do the same. nevertheless, we only
61   /// use the first item
62   #[serde(default)]
63   pub(crate) attachment: Vec<Attachment>,
64   pub(crate) image: Option<ImageObject>,
65   pub(crate) comments_enabled: Option<bool>,
66   pub(crate) sensitive: Option<bool>,
67   /// Deprecated, for compatibility with Lemmy 0.17
68   pub(crate) stickied: Option<bool>,
69   pub(crate) published: Option<DateTime<FixedOffset>>,
70   pub(crate) updated: Option<DateTime<FixedOffset>>,
71   pub(crate) language: Option<LanguageTag>,
72   pub(crate) audience: Option<ObjectId<ApubCommunity>>,
73 }
74
75 #[derive(Clone, Debug, Deserialize, Serialize)]
76 #[serde(rename_all = "camelCase")]
77 pub(crate) struct Link {
78   pub(crate) href: Url,
79   pub(crate) r#type: LinkType,
80 }
81
82 #[derive(Clone, Debug, Deserialize, Serialize)]
83 #[serde(rename_all = "camelCase")]
84 pub(crate) struct Image {
85   #[serde(rename = "type")]
86   pub(crate) kind: ImageType,
87   pub(crate) url: Url,
88 }
89
90 #[derive(Clone, Debug, Deserialize, Serialize)]
91 #[serde(rename_all = "camelCase")]
92 pub(crate) struct Document {
93   #[serde(rename = "type")]
94   pub(crate) kind: DocumentType,
95   pub(crate) url: Url,
96 }
97
98 #[derive(Clone, Debug, Deserialize, Serialize)]
99 #[serde(untagged)]
100 pub(crate) enum Attachment {
101   Link(Link),
102   Image(Image),
103   Document(Document),
104 }
105
106 impl Attachment {
107   pub(crate) fn url(self) -> Url {
108     match self {
109       // url as sent by Lemmy (new)
110       Attachment::Link(l) => l.href,
111       // image sent by lotide
112       Attachment::Image(i) => i.url,
113       // sent by mobilizon
114       Attachment::Document(d) => d.url,
115     }
116   }
117 }
118
119 #[derive(Clone, Debug, Deserialize, Serialize)]
120 #[serde(untagged)]
121 pub(crate) enum AttributedTo {
122   Lemmy(ObjectId<ApubPerson>),
123   Peertube([AttributedToPeertube; 2]),
124 }
125
126 #[derive(Clone, Debug, Deserialize, Serialize)]
127 #[serde(rename_all = "camelCase")]
128 pub(crate) struct AttributedToPeertube {
129   #[serde(rename = "type")]
130   pub kind: PersonOrGroupType,
131   pub id: ObjectId<UserOrCommunity>,
132 }
133
134 impl Page {
135   /// Only mods can change the post's stickied/locked status. So if either of these is changed from
136   /// the current value, it is a mod action and needs to be verified as such.
137   ///
138   /// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]].
139   pub(crate) async fn is_mod_action(&self, context: &LemmyContext) -> Result<bool, LemmyError> {
140     let old_post = ObjectId::<ApubPost>::new(self.id.clone())
141       .dereference_local(context)
142       .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>::new(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(?Send)]
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(
208     &self,
209     data: &Data<Self::DataType>,
210     request_counter: &mut i32,
211   ) -> Result<(), LemmyError> {
212     ApubPost::verify(self, self.id.inner(), data, request_counter).await
213   }
214   async fn receive(
215     self,
216     data: &Data<Self::DataType>,
217     request_counter: &mut i32,
218   ) -> Result<(), LemmyError> {
219     ApubPost::from_apub(self, data, request_counter).await?;
220     Ok(())
221   }
222 }
223
224 #[async_trait::async_trait(?Send)]
225 impl InCommunity for Page {
226   async fn community(
227     &self,
228     context: &LemmyContext,
229     request_counter: &mut i32,
230   ) -> Result<ApubCommunity, LemmyError> {
231     let instance = local_instance(context).await;
232     let community = match &self.attributed_to {
233       AttributedTo::Lemmy(_) => {
234         let mut iter = self.to.iter().merge(self.cc.iter());
235         loop {
236           if let Some(cid) = iter.next() {
237             let cid = ObjectId::new(cid.clone());
238             if let Ok(c) = cid.dereference(context, instance, request_counter).await {
239               break c;
240             }
241           } else {
242             return Err(LemmyError::from_message("No community found in cc"));
243           }
244         }
245       }
246       AttributedTo::Peertube(p) => {
247         p.iter()
248           .find(|a| a.kind == PersonOrGroupType::Group)
249           .map(|a| ObjectId::<ApubCommunity>::new(a.id.clone().into_inner()))
250           .ok_or_else(|| LemmyError::from_message("page does not specify group"))?
251           .dereference(context, instance, request_counter)
252           .await?
253       }
254     };
255     if let Some(audience) = &self.audience {
256       verify_community_matches(audience, community.actor_id.clone())?;
257     }
258     Ok(community)
259   }
260 }
261
262 /// Only allows deserialization if the field is missing or null. If it is present, throws an error.
263 pub fn deserialize_not_present<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
264 where
265   D: Deserializer<'de>,
266 {
267   let result: Option<String> = Deserialize::deserialize(deserializer)?;
268   match result {
269     None => Ok(None),
270     Some(_) => Err(D::Error::custom("Post must not have inReplyTo property")),
271   }
272 }
273
274 #[cfg(test)]
275 mod tests {
276   use crate::protocol::{objects::page::Page, tests::test_parse_lemmy_item};
277
278   #[test]
279   fn test_not_parsing_note_as_page() {
280     assert!(test_parse_lemmy_item::<Page>("assets/lemmy/objects/note.json").is_err());
281   }
282 }