]> Untitled Git - lemmy.git/blob - crates/apub/src/protocol/mod.rs
bfc9df772a25d532b7cd9ead706de4a777157f8c
[lemmy.git] / crates / apub / src / protocol / mod.rs
1 use crate::objects::community::ApubCommunity;
2 use activitypub_federation::{
3   config::Data,
4   fetch::fetch_object_http,
5   kinds::object::ImageType,
6   protocol::values::MediaTypeMarkdown,
7 };
8 use lemmy_api_common::context::LemmyContext;
9 use lemmy_db_schema::newtypes::DbUrl;
10 use lemmy_utils::error::LemmyError;
11 use serde::{de::DeserializeOwned, Deserialize, Serialize};
12 use std::collections::HashMap;
13 use url::Url;
14
15 pub mod activities;
16 pub(crate) mod collections;
17 pub(crate) mod objects;
18
19 #[derive(Clone, Debug, Deserialize, Serialize)]
20 #[serde(rename_all = "camelCase")]
21 pub struct Source {
22   pub(crate) content: String,
23   pub(crate) media_type: MediaTypeMarkdown,
24 }
25
26 impl Source {
27   pub(crate) fn new(content: String) -> Self {
28     Source {
29       content,
30       media_type: MediaTypeMarkdown::Markdown,
31     }
32   }
33 }
34
35 #[derive(Clone, Debug, Deserialize, Serialize)]
36 #[serde(rename_all = "camelCase")]
37 pub struct ImageObject {
38   #[serde(rename = "type")]
39   kind: ImageType,
40   pub(crate) url: Url,
41 }
42
43 impl ImageObject {
44   pub(crate) fn new(url: DbUrl) -> Self {
45     ImageObject {
46       kind: ImageType::Image,
47       url: url.into(),
48     }
49   }
50 }
51
52 #[derive(Clone, Debug, Default, Deserialize, Serialize)]
53 #[serde(transparent)]
54 pub struct Unparsed(HashMap<String, serde_json::Value>);
55
56 pub(crate) trait Id {
57   fn object_id(&self) -> &Url;
58 }
59
60 #[derive(Clone, Debug, Deserialize, Serialize)]
61 #[serde(untagged)]
62 pub(crate) enum IdOrNestedObject<Kind: Id> {
63   Id(Url),
64   NestedObject(Kind),
65 }
66
67 impl<Kind: Id + DeserializeOwned + Send> IdOrNestedObject<Kind> {
68   pub(crate) fn id(&self) -> &Url {
69     match self {
70       IdOrNestedObject::Id(i) => i,
71       IdOrNestedObject::NestedObject(n) => n.object_id(),
72     }
73   }
74   pub(crate) async fn object(self, context: &Data<LemmyContext>) -> Result<Kind, LemmyError> {
75     match self {
76       // TODO: move IdOrNestedObject struct to library and make fetch_object_http private
77       IdOrNestedObject::Id(i) => Ok(fetch_object_http(&i, context).await?),
78       IdOrNestedObject::NestedObject(o) => Ok(o),
79     }
80   }
81 }
82
83 #[async_trait::async_trait]
84 pub trait InCommunity {
85   // TODO: after we use audience field and remove backwards compat, it should be possible to change
86   //       this to simply `fn community(&self)  -> Result<ObjectId<ApubCommunity>, LemmyError>`
87   async fn community(&self, context: &Data<LemmyContext>) -> Result<ApubCommunity, LemmyError>;
88 }
89
90 #[cfg(test)]
91 pub(crate) mod tests {
92   use activitypub_federation::protocol::context::WithContext;
93   use assert_json_diff::assert_json_include;
94   use lemmy_utils::error::LemmyError;
95   use serde::{de::DeserializeOwned, Serialize};
96   use std::{collections::HashMap, fs::File, io::BufReader};
97
98   pub(crate) fn file_to_json_object<T: DeserializeOwned>(path: &str) -> Result<T, LemmyError> {
99     let file = File::open(path)?;
100     let reader = BufReader::new(file);
101     Ok(serde_json::from_reader(reader)?)
102   }
103
104   pub(crate) fn test_json<T: DeserializeOwned>(path: &str) -> Result<WithContext<T>, LemmyError> {
105     file_to_json_object::<WithContext<T>>(path)
106   }
107
108   /// Check that json deserialize -> serialize -> deserialize gives identical file as initial one.
109   /// Ensures that there are no breaking changes in sent data.
110   pub(crate) fn test_parse_lemmy_item<T: Serialize + DeserializeOwned + std::fmt::Debug>(
111     path: &str,
112   ) -> Result<T, LemmyError> {
113     // parse file as T
114     let parsed = file_to_json_object::<T>(path)?;
115
116     // parse file into hashmap, which ensures that every field is included
117     let raw = file_to_json_object::<HashMap<String, serde_json::Value>>(path)?;
118     // assert that all fields are identical, otherwise print diff
119     assert_json_include!(actual: &parsed, expected: raw);
120     Ok(parsed)
121   }
122 }