]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/mod.rs
Fix code to allow sticky/lock from remote moderators
[lemmy.git] / crates / apub / src / objects / mod.rs
1 use crate::{
2   check_is_apub_id_valid,
3   fetcher::{community::get_or_fetch_and_upsert_community, user::get_or_fetch_and_upsert_user},
4   inbox::community_inbox::check_community_or_site_ban,
5 };
6 use activitystreams::{
7   base::{AsBase, BaseExt, ExtendsExt},
8   markers::Base,
9   mime::{FromStrError, Mime},
10   object::{ApObjectExt, Object, ObjectExt, Tombstone, TombstoneExt},
11 };
12 use anyhow::{anyhow, Context};
13 use chrono::NaiveDateTime;
14 use diesel::result::Error::NotFound;
15 use lemmy_api_structs::blocking;
16 use lemmy_db_queries::{ApubObject, Crud, DbPool};
17 use lemmy_db_schema::{source::community::Community, DbUrl};
18 use lemmy_utils::{
19   location_info,
20   settings::structs::Settings,
21   utils::{convert_datetime, markdown_to_html},
22   LemmyError,
23 };
24 use lemmy_websocket::LemmyContext;
25 use url::Url;
26
27 pub(crate) mod comment;
28 pub(crate) mod community;
29 pub(crate) mod post;
30 pub(crate) mod private_message;
31 pub(crate) mod user;
32
33 /// Trait for converting an object or actor into the respective ActivityPub type.
34 #[async_trait::async_trait(?Send)]
35 pub(crate) trait ToApub {
36   type ApubType;
37   async fn to_apub(&self, pool: &DbPool) -> Result<Self::ApubType, LemmyError>;
38   fn to_tombstone(&self) -> Result<Tombstone, LemmyError>;
39 }
40
41 #[async_trait::async_trait(?Send)]
42 pub(crate) trait FromApub {
43   type ApubType;
44   /// Converts an object from ActivityPub type to Lemmy internal type.
45   ///
46   /// * `apub` The object to read from
47   /// * `context` LemmyContext which holds DB pool, HTTP client etc
48   /// * `expected_domain` Domain where the object was received from. None in case of mod action.
49   async fn from_apub(
50     apub: &Self::ApubType,
51     context: &LemmyContext,
52     expected_domain: Option<Url>,
53     request_counter: &mut i32,
54   ) -> Result<Self, LemmyError>
55   where
56     Self: Sized;
57 }
58
59 #[async_trait::async_trait(?Send)]
60 pub(in crate::objects) trait FromApubToForm<ApubType> {
61   async fn from_apub(
62     apub: &ApubType,
63     context: &LemmyContext,
64     expected_domain: Option<Url>,
65     request_counter: &mut i32,
66   ) -> Result<Self, LemmyError>
67   where
68     Self: Sized;
69 }
70
71 /// Updated is actually the deletion time
72 fn create_tombstone<T>(
73   deleted: bool,
74   object_id: Url,
75   updated: Option<NaiveDateTime>,
76   former_type: T,
77 ) -> Result<Tombstone, LemmyError>
78 where
79   T: ToString,
80 {
81   if deleted {
82     if let Some(updated) = updated {
83       let mut tombstone = Tombstone::new();
84       tombstone.set_id(object_id);
85       tombstone.set_former_type(former_type.to_string());
86       tombstone.set_deleted(convert_datetime(updated));
87       Ok(tombstone)
88     } else {
89       Err(anyhow!("Cant convert to tombstone because updated time was None.").into())
90     }
91   } else {
92     Err(anyhow!("Cant convert object to tombstone if it wasnt deleted").into())
93   }
94 }
95
96 pub(in crate::objects) fn check_object_domain<T, Kind>(
97   apub: &T,
98   expected_domain: Url,
99 ) -> Result<DbUrl, LemmyError>
100 where
101   T: Base + AsBase<Kind>,
102 {
103   let domain = expected_domain.domain().context(location_info!())?;
104   let object_id = apub.id(domain)?.context(location_info!())?;
105   check_is_apub_id_valid(object_id)?;
106   Ok(object_id.to_owned().into())
107 }
108
109 pub(in crate::objects) fn set_content_and_source<T, Kind1, Kind2>(
110   object: &mut T,
111   markdown_text: &str,
112 ) -> Result<(), LemmyError>
113 where
114   T: ApObjectExt<Kind1> + ObjectExt<Kind2> + AsBase<Kind2>,
115 {
116   let mut source = Object::<()>::new_none_type();
117   source
118     .set_content(markdown_text)
119     .set_media_type(mime_markdown()?);
120   object.set_source(source.into_any_base()?);
121
122   object.set_content(markdown_to_html(markdown_text));
123   object.set_media_type(mime_html()?);
124   Ok(())
125 }
126
127 pub(in crate::objects) fn get_source_markdown_value<T, Kind1, Kind2>(
128   object: &T,
129 ) -> Result<Option<String>, LemmyError>
130 where
131   T: ApObjectExt<Kind1> + ObjectExt<Kind2> + AsBase<Kind2>,
132 {
133   let content = object
134     .content()
135     .map(|s| s.as_single_xsd_string().map(|s2| s2.to_string()))
136     .flatten();
137   if content.is_some() {
138     let source = object.source().context(location_info!())?;
139     let source = Object::<()>::from_any_base(source.to_owned())?.context(location_info!())?;
140     check_is_markdown(source.media_type())?;
141     let source_content = source
142       .content()
143       .map(|s| s.as_single_xsd_string().map(|s2| s2.to_string()))
144       .flatten()
145       .context(location_info!())?;
146     return Ok(Some(source_content));
147   }
148   Ok(None)
149 }
150
151 fn mime_markdown() -> Result<Mime, FromStrError> {
152   "text/markdown".parse()
153 }
154
155 fn mime_html() -> Result<Mime, FromStrError> {
156   "text/html".parse()
157 }
158
159 pub(in crate::objects) fn check_is_markdown(mime: Option<&Mime>) -> Result<(), LemmyError> {
160   let mime = mime.context(location_info!())?;
161   if !mime.eq(&mime_markdown()?) {
162     Err(LemmyError::from(anyhow!(
163       "Lemmy only supports markdown content"
164     )))
165   } else {
166     Ok(())
167   }
168 }
169
170 /// Converts an ActivityPub object (eg `Note`) to a database object (eg `Comment`). If an object
171 /// with the same ActivityPub ID already exists in the database, it is returned directly. Otherwise
172 /// the apub object is parsed, inserted and returned.
173 pub(in crate::objects) async fn get_object_from_apub<From, Kind, To, ToForm>(
174   from: &From,
175   context: &LemmyContext,
176   expected_domain: Option<Url>,
177   request_counter: &mut i32,
178 ) -> Result<To, LemmyError>
179 where
180   From: BaseExt<Kind>,
181   To: ApubObject<ToForm> + Crud<ToForm> + Send + 'static,
182   ToForm: FromApubToForm<From> + Send + 'static,
183 {
184   let object_id = from.id_unchecked().context(location_info!())?.to_owned();
185   let domain = object_id.domain().context(location_info!())?;
186
187   // if its a local object, return it directly from the database
188   if Settings::get().hostname() == domain {
189     let object = blocking(context.pool(), move |conn| {
190       To::read_from_apub_id(conn, &object_id.into())
191     })
192     .await??;
193     Ok(object)
194   }
195   // otherwise parse and insert, assuring that it comes from the right domain
196   else {
197     let to_form = ToForm::from_apub(&from, context, expected_domain, request_counter).await?;
198
199     let to = blocking(context.pool(), move |conn| To::upsert(conn, &to_form)).await??;
200     Ok(to)
201   }
202 }
203
204 pub(in crate::objects) async fn check_object_for_community_or_site_ban<T, Kind>(
205   object: &T,
206   community_id: i32,
207   context: &LemmyContext,
208   request_counter: &mut i32,
209 ) -> Result<(), LemmyError>
210 where
211   T: ObjectExt<Kind>,
212 {
213   let user_id = object
214     .attributed_to()
215     .context(location_info!())?
216     .as_single_xsd_any_uri()
217     .context(location_info!())?;
218   let user = get_or_fetch_and_upsert_user(user_id, context, request_counter).await?;
219   check_community_or_site_ban(&user, community_id, context.pool()).await
220 }
221
222 pub(in crate::objects) async fn get_to_community<T, Kind>(
223   object: &T,
224   context: &LemmyContext,
225   request_counter: &mut i32,
226 ) -> Result<Community, LemmyError>
227 where
228   T: ObjectExt<Kind>,
229 {
230   let community_ids = object
231     .to()
232     .context(location_info!())?
233     .as_many()
234     .context(location_info!())?
235     .iter()
236     .map(|a| a.as_xsd_any_uri().context(location_info!()))
237     .collect::<Result<Vec<&Url>, anyhow::Error>>()?;
238   for cid in community_ids {
239     let community = get_or_fetch_and_upsert_community(&cid, context, request_counter).await;
240     if community.is_ok() {
241       return community;
242     }
243   }
244   Err(NotFound.into())
245 }