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