]> Untitled Git - lemmy.git/blob - crates/apub/src/protocol/mod.rs
Migrate towards using page.attachment field for url (ref #2144) (#2182)
[lemmy.git] / crates / apub / src / protocol / mod.rs
1 use activitystreams_kinds::object::ImageType;
2 use lemmy_apub_lib::values::MediaTypeMarkdown;
3 use lemmy_db_schema::newtypes::DbUrl;
4 use serde::{Deserialize, Serialize};
5 use std::collections::HashMap;
6 use url::Url;
7
8 pub mod activities;
9 pub(crate) mod collections;
10 pub(crate) mod objects;
11
12 #[derive(Clone, Debug, Deserialize, Serialize)]
13 #[serde(rename_all = "camelCase")]
14 pub struct Source {
15   pub(crate) content: String,
16   pub(crate) media_type: MediaTypeMarkdown,
17 }
18
19 impl Source {
20   pub(crate) fn new(content: String) -> Self {
21     Source {
22       content,
23       media_type: MediaTypeMarkdown::Markdown,
24     }
25   }
26 }
27
28 #[derive(Clone, Debug, Deserialize, Serialize)]
29 #[serde(rename_all = "camelCase")]
30 pub struct ImageObject {
31   #[serde(rename = "type")]
32   kind: ImageType,
33   pub(crate) url: Url,
34 }
35
36 impl ImageObject {
37   pub(crate) fn new(url: DbUrl) -> Self {
38     ImageObject {
39       kind: ImageType::Image,
40       url: url.into(),
41     }
42   }
43 }
44
45 #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
46 #[serde(transparent)]
47 pub struct Unparsed(HashMap<String, serde_json::Value>);
48
49 #[cfg(test)]
50 pub(crate) mod tests {
51   use crate::context::WithContext;
52   use assert_json_diff::assert_json_include;
53   use lemmy_utils::LemmyError;
54   use serde::{de::DeserializeOwned, Serialize};
55   use std::{collections::HashMap, fs::File, io::BufReader};
56
57   pub(crate) fn file_to_json_object<T: DeserializeOwned>(path: &str) -> Result<T, LemmyError> {
58     let file = File::open(path)?;
59     let reader = BufReader::new(file);
60     Ok(serde_json::from_reader(reader)?)
61   }
62
63   pub(crate) fn test_json<T: DeserializeOwned>(path: &str) -> Result<WithContext<T>, LemmyError> {
64     file_to_json_object::<WithContext<T>>(path)
65   }
66
67   /// Check that json deserialize -> serialize -> deserialize gives identical file as initial one.
68   /// Ensures that there are no breaking changes in sent data.
69   pub(crate) fn test_parse_lemmy_item<T: Serialize + DeserializeOwned + std::fmt::Debug>(
70     path: &str,
71   ) -> Result<T, LemmyError> {
72     // parse file as T
73     let parsed = file_to_json_object::<T>(path)?;
74
75     // parse file into hashmap, which ensures that every field is included
76     let raw = file_to_json_object::<HashMap<String, serde_json::Value>>(path)?;
77     // assert that all fields are identical, otherwise print diff
78     assert_json_include!(actual: &parsed, expected: raw);
79     Ok(parsed)
80   }
81 }