]> Untitled Git - lemmy.git/blob - crates/apub/src/protocol/objects/page.rs
Add SendActivity trait so that api crates compile in parallel with lemmy_apub
[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::{Deserialize, 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   pub(crate) name: String,
50
51   #[serde(deserialize_with = "deserialize_one_or_many", default)]
52   pub(crate) cc: Vec<Url>,
53   pub(crate) content: Option<String>,
54   pub(crate) media_type: Option<MediaTypeMarkdownOrHtml>,
55   #[serde(deserialize_with = "deserialize_skip_error", default)]
56   pub(crate) source: Option<Source>,
57   /// deprecated, use attachment field
58   #[serde(deserialize_with = "deserialize_skip_error", default)]
59   pub(crate) url: Option<Url>,
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   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(&self, context: &LemmyContext) -> Result<bool, LemmyError> {
139     let old_post = ObjectId::<ApubPost>::new(self.id.clone())
140       .dereference_local(context)
141       .await;
142
143     let stickied_changed = Page::is_stickied_changed(&old_post, &self.stickied);
144     let locked_changed = Page::is_locked_changed(&old_post, &self.comments_enabled);
145     Ok(stickied_changed || locked_changed)
146   }
147
148   pub(crate) fn is_stickied_changed<E>(
149     old_post: &Result<ApubPost, E>,
150     new_stickied: &Option<bool>,
151   ) -> bool {
152     if let Some(new_stickied) = new_stickied {
153       if let Ok(old_post) = old_post {
154         return new_stickied != &old_post.stickied;
155       }
156     }
157
158     false
159   }
160
161   pub(crate) fn is_locked_changed<E>(
162     old_post: &Result<ApubPost, E>,
163     new_comments_enabled: &Option<bool>,
164   ) -> bool {
165     if let Some(new_comments_enabled) = new_comments_enabled {
166       if let Ok(old_post) = old_post {
167         return new_comments_enabled != &!old_post.locked;
168       }
169     }
170
171     false
172   }
173
174   pub(crate) fn creator(&self) -> Result<ObjectId<ApubPerson>, LemmyError> {
175     match &self.attributed_to {
176       AttributedTo::Lemmy(l) => Ok(l.clone()),
177       AttributedTo::Peertube(p) => p
178         .iter()
179         .find(|a| a.kind == PersonOrGroupType::Person)
180         .map(|a| ObjectId::<ApubPerson>::new(a.id.clone().into_inner()))
181         .ok_or_else(|| LemmyError::from_message("page does not specify creator person")),
182     }
183   }
184 }
185
186 impl Attachment {
187   pub(crate) fn new(url: DbUrl) -> Attachment {
188     Attachment::Link(Link {
189       href: url.into(),
190       r#type: Default::default(),
191     })
192   }
193 }
194
195 // Used for community outbox, so that it can be compatible with Pleroma/Mastodon.
196 #[async_trait::async_trait(?Send)]
197 impl ActivityHandler for Page {
198   type DataType = LemmyContext;
199   type Error = LemmyError;
200   fn id(&self) -> &Url {
201     unimplemented!()
202   }
203   fn actor(&self) -> &Url {
204     unimplemented!()
205   }
206   async fn verify(
207     &self,
208     data: &Data<Self::DataType>,
209     request_counter: &mut i32,
210   ) -> Result<(), LemmyError> {
211     ApubPost::verify(self, self.id.inner(), data, request_counter).await
212   }
213   async fn receive(
214     self,
215     data: &Data<Self::DataType>,
216     request_counter: &mut i32,
217   ) -> Result<(), LemmyError> {
218     ApubPost::from_apub(self, data, request_counter).await?;
219     Ok(())
220   }
221 }
222
223 #[async_trait::async_trait(?Send)]
224 impl InCommunity for Page {
225   async fn community(
226     &self,
227     context: &LemmyContext,
228     request_counter: &mut i32,
229   ) -> Result<ApubCommunity, LemmyError> {
230     let instance = local_instance(context).await;
231     let community = match &self.attributed_to {
232       AttributedTo::Lemmy(_) => {
233         let mut iter = self.to.iter().merge(self.cc.iter());
234         loop {
235           if let Some(cid) = iter.next() {
236             let cid = ObjectId::new(cid.clone());
237             if let Ok(c) = cid.dereference(context, instance, request_counter).await {
238               break c;
239             }
240           } else {
241             return Err(LemmyError::from_message("No community found in cc"));
242           }
243         }
244       }
245       AttributedTo::Peertube(p) => {
246         p.iter()
247           .find(|a| a.kind == PersonOrGroupType::Group)
248           .map(|a| ObjectId::<ApubCommunity>::new(a.id.clone().into_inner()))
249           .ok_or_else(|| LemmyError::from_message("page does not specify group"))?
250           .dereference(context, instance, request_counter)
251           .await?
252       }
253     };
254     if let Some(audience) = &self.audience {
255       let audience = audience
256         .dereference(context, instance, request_counter)
257         .await?;
258       verify_community_matches(&audience, community.id)?;
259       Ok(audience)
260     } else {
261       Ok(community)
262     }
263   }
264 }