1 use crate::{check_is_apub_id_valid, fetcher::person::get_or_fetch_and_upsert_person};
3 base::{AsBase, BaseExt, ExtendsExt},
5 mime::{FromStrError, Mime},
6 object::{ApObjectExt, Object, ObjectExt, Tombstone, TombstoneExt},
8 use anyhow::{anyhow, Context};
9 use chrono::NaiveDateTime;
10 use lemmy_api_common::blocking;
11 use lemmy_apub_lib::values::MediaTypeMarkdown;
12 use lemmy_db_queries::{ApubObject, Crud, DbPool};
13 use lemmy_db_schema::DbUrl;
16 settings::structs::Settings,
17 utils::{convert_datetime, markdown_to_html},
20 use lemmy_websocket::LemmyContext;
23 pub(crate) mod comment;
24 pub(crate) mod community;
25 pub(crate) mod person;
27 pub(crate) mod private_message;
29 /// Trait for converting an object or actor into the respective ActivityPub type.
30 #[async_trait::async_trait(?Send)]
33 async fn to_apub(&self, pool: &DbPool) -> Result<Self::ApubType, LemmyError>;
34 fn to_tombstone(&self) -> Result<Tombstone, LemmyError>;
37 #[async_trait::async_trait(?Send)]
40 /// Converts an object from ActivityPub type to Lemmy internal type.
42 /// * `apub` The object to read from
43 /// * `context` LemmyContext which holds DB pool, HTTP client etc
44 /// * `expected_domain` Domain where the object was received from. None in case of mod action.
45 /// * `mod_action_allowed` True if the object can be a mod activity, ignore `expected_domain` in this case
47 apub: &Self::ApubType,
48 context: &LemmyContext,
50 request_counter: &mut i32,
51 mod_action_allowed: bool,
52 ) -> Result<Self, LemmyError>
57 #[async_trait::async_trait(?Send)]
58 pub trait FromApubToForm<ApubType> {
61 context: &LemmyContext,
63 request_counter: &mut i32,
64 mod_action_allowed: bool,
65 ) -> Result<Self, LemmyError>
70 #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
71 #[serde(rename_all = "camelCase")]
74 media_type: MediaTypeMarkdown,
77 /// Updated is actually the deletion time
78 fn create_tombstone<T>(
81 updated: Option<NaiveDateTime>,
83 ) -> Result<Tombstone, LemmyError>
88 if let Some(updated) = updated {
89 let mut tombstone = Tombstone::new();
90 tombstone.set_id(object_id);
91 tombstone.set_former_type(former_type.to_string());
92 tombstone.set_deleted(convert_datetime(updated));
95 Err(anyhow!("Cant convert to tombstone because updated time was None.").into())
98 Err(anyhow!("Cant convert object to tombstone if it wasnt deleted").into())
102 pub(in crate::objects) fn check_object_domain<T, Kind>(
104 expected_domain: Url,
105 use_strict_allowlist: bool,
106 ) -> Result<DbUrl, LemmyError>
108 T: Base + AsBase<Kind>,
110 let domain = expected_domain.domain().context(location_info!())?;
111 let object_id = apub.id(domain)?.context(location_info!())?;
112 check_is_apub_id_valid(object_id, use_strict_allowlist)?;
113 Ok(object_id.to_owned().into())
116 pub(in crate::objects) fn set_content_and_source<T, Kind1, Kind2>(
119 ) -> Result<(), LemmyError>
121 T: ApObjectExt<Kind1> + ObjectExt<Kind2> + AsBase<Kind2>,
123 let mut source = Object::<()>::new_none_type();
125 .set_content(markdown_text)
126 .set_media_type(mime_markdown()?);
127 object.set_source(source.into_any_base()?);
129 object.set_content(markdown_to_html(markdown_text));
130 object.set_media_type(mime_html()?);
134 pub(in crate::objects) fn get_source_markdown_value<T, Kind1, Kind2>(
136 ) -> Result<Option<String>, LemmyError>
138 T: ApObjectExt<Kind1> + ObjectExt<Kind2> + AsBase<Kind2>,
142 .map(|s| s.as_single_xsd_string().map(|s2| s2.to_string()))
144 if content.is_some() {
145 let source = object.source().context(location_info!())?;
146 let source = Object::<()>::from_any_base(source.to_owned())?.context(location_info!())?;
147 check_is_markdown(source.media_type())?;
148 let source_content = source
150 .map(|s| s.as_single_xsd_string().map(|s2| s2.to_string()))
152 .context(location_info!())?;
153 return Ok(Some(source_content));
158 fn mime_markdown() -> Result<Mime, FromStrError> {
159 "text/markdown".parse()
162 fn mime_html() -> Result<Mime, FromStrError> {
166 pub(in crate::objects) fn check_is_markdown(mime: Option<&Mime>) -> Result<(), LemmyError> {
167 let mime = mime.context(location_info!())?;
168 if !mime.eq(&mime_markdown()?) {
169 Err(LemmyError::from(anyhow!(
170 "Lemmy only supports markdown content"
177 /// Converts an ActivityPub object (eg `Note`) to a database object (eg `Comment`). If an object
178 /// with the same ActivityPub ID already exists in the database, it is returned directly. Otherwise
179 /// the apub object is parsed, inserted and returned.
180 pub async fn get_object_from_apub<From, Kind, To, ToForm, IdType>(
182 context: &LemmyContext,
183 expected_domain: Url,
184 request_counter: &mut i32,
186 ) -> Result<To, LemmyError>
189 To: ApubObject<ToForm> + Crud<ToForm, IdType> + Send + 'static,
190 ToForm: FromApubToForm<From> + Send + 'static,
192 let object_id = from.id_unchecked().context(location_info!())?.to_owned();
193 let domain = object_id.domain().context(location_info!())?;
195 // if its a local object, return it directly from the database
196 if Settings::get().hostname() == domain {
197 let object = blocking(context.pool(), move |conn| {
198 To::read_from_apub_id(conn, &object_id.into())
203 // otherwise parse and insert, assuring that it comes from the right domain
205 let to_form = ToForm::from_apub(
214 let to = blocking(context.pool(), move |conn| To::upsert(conn, &to_form)).await??;