]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/mod.rs
b05a944cd9f392e38e1170ad5f4ae95426558b39
[lemmy.git] / crates / apub / src / objects / mod.rs
1 use activitystreams::{
2   base::BaseExt,
3   object::{kind::ImageType, Tombstone, TombstoneExt},
4 };
5 use anyhow::anyhow;
6 use chrono::NaiveDateTime;
7 use lemmy_apub_lib::values::MediaTypeMarkdown;
8 use lemmy_db_queries::DbPool;
9 use lemmy_utils::{utils::convert_datetime, LemmyError};
10 use lemmy_websocket::LemmyContext;
11 use url::Url;
12
13 pub(crate) mod comment;
14 pub(crate) mod community;
15 pub(crate) mod person;
16 pub(crate) mod post;
17 pub(crate) mod private_message;
18
19 /// Trait for converting an object or actor into the respective ActivityPub type.
20 #[async_trait::async_trait(?Send)]
21 pub(crate) trait ToApub {
22   type ApubType;
23   async fn to_apub(&self, pool: &DbPool) -> Result<Self::ApubType, LemmyError>;
24   fn to_tombstone(&self) -> Result<Tombstone, LemmyError>;
25 }
26
27 #[async_trait::async_trait(?Send)]
28 pub trait FromApub {
29   type ApubType;
30   /// Converts an object from ActivityPub type to Lemmy internal type.
31   ///
32   /// * `apub` The object to read from
33   /// * `context` LemmyContext which holds DB pool, HTTP client etc
34   /// * `expected_domain` Domain where the object was received from. None in case of mod action.
35   /// * `mod_action_allowed` True if the object can be a mod activity, ignore `expected_domain` in this case
36   async fn from_apub(
37     apub: &Self::ApubType,
38     context: &LemmyContext,
39     expected_domain: &Url,
40     request_counter: &mut i32,
41   ) -> Result<Self, LemmyError>
42   where
43     Self: Sized;
44 }
45
46 #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
47 #[serde(rename_all = "camelCase")]
48 pub struct Source {
49   content: String,
50   media_type: MediaTypeMarkdown,
51 }
52
53 #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
54 #[serde(rename_all = "camelCase")]
55 pub struct ImageObject {
56   #[serde(rename = "type")]
57   kind: ImageType,
58   url: Url,
59 }
60
61 /// Updated is actually the deletion time
62 fn create_tombstone<T>(
63   deleted: bool,
64   object_id: Url,
65   updated: Option<NaiveDateTime>,
66   former_type: T,
67 ) -> Result<Tombstone, LemmyError>
68 where
69   T: ToString,
70 {
71   if deleted {
72     if let Some(updated) = updated {
73       let mut tombstone = Tombstone::new();
74       tombstone.set_id(object_id);
75       tombstone.set_former_type(former_type.to_string());
76       tombstone.set_deleted(convert_datetime(updated));
77       Ok(tombstone)
78     } else {
79       Err(anyhow!("Cant convert to tombstone because updated time was None.").into())
80     }
81   } else {
82     Err(anyhow!("Cant convert object to tombstone if it wasnt deleted").into())
83   }
84 }