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