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