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