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