1 use crate::local_instance;
2 use activitypub_federation::{deser::values::MediaTypeMarkdown, utils::fetch_object_http};
3 use activitystreams_kinds::object::ImageType;
4 use lemmy_db_schema::newtypes::DbUrl;
5 use lemmy_utils::error::LemmyError;
6 use lemmy_websocket::LemmyContext;
7 use serde::{de::DeserializeOwned, Deserialize, Serialize};
8 use std::collections::HashMap;
12 pub(crate) mod collections;
13 pub(crate) mod objects;
15 #[derive(Clone, Debug, Deserialize, Serialize)]
16 #[serde(rename_all = "camelCase")]
18 pub(crate) content: String,
19 pub(crate) media_type: MediaTypeMarkdown,
23 pub(crate) fn new(content: String) -> Self {
26 media_type: MediaTypeMarkdown::Markdown,
31 #[derive(Clone, Debug, Deserialize, Serialize)]
32 #[serde(rename_all = "camelCase")]
33 pub struct ImageObject {
34 #[serde(rename = "type")]
40 pub(crate) fn new(url: DbUrl) -> Self {
42 kind: ImageType::Image,
48 #[derive(Clone, Debug, Default, Deserialize, Serialize)]
50 pub struct Unparsed(HashMap<String, serde_json::Value>);
53 fn object_id(&self) -> &Url;
56 #[derive(Clone, Debug, Deserialize, Serialize)]
58 pub(crate) enum IdOrNestedObject<Kind: Id> {
63 impl<Kind: Id + DeserializeOwned> IdOrNestedObject<Kind> {
64 pub(crate) fn id(&self) -> &Url {
66 IdOrNestedObject::Id(i) => i,
67 IdOrNestedObject::NestedObject(n) => n.object_id(),
70 pub(crate) async fn object(
72 context: &LemmyContext,
73 request_counter: &mut i32,
74 ) -> Result<Kind, LemmyError> {
76 IdOrNestedObject::Id(i) => {
77 Ok(fetch_object_http(&i, local_instance(context), request_counter).await?)
79 IdOrNestedObject::NestedObject(o) => Ok(o),
85 pub(crate) mod tests {
86 use activitypub_federation::deser::context::WithContext;
87 use assert_json_diff::assert_json_include;
88 use lemmy_utils::error::LemmyError;
89 use serde::{de::DeserializeOwned, Serialize};
90 use std::{collections::HashMap, fs::File, io::BufReader};
92 pub(crate) fn file_to_json_object<T: DeserializeOwned>(path: &str) -> Result<T, LemmyError> {
93 let file = File::open(path)?;
94 let reader = BufReader::new(file);
95 Ok(serde_json::from_reader(reader)?)
98 pub(crate) fn test_json<T: DeserializeOwned>(path: &str) -> Result<WithContext<T>, LemmyError> {
99 file_to_json_object::<WithContext<T>>(path)
102 /// Check that json deserialize -> serialize -> deserialize gives identical file as initial one.
103 /// Ensures that there are no breaking changes in sent data.
104 pub(crate) fn test_parse_lemmy_item<T: Serialize + DeserializeOwned + std::fmt::Debug>(
106 ) -> Result<T, LemmyError> {
108 let parsed = file_to_json_object::<T>(path)?;
110 // parse file into hashmap, which ensures that every field is included
111 let raw = file_to_json_object::<HashMap<String, serde_json::Value>>(path)?;
112 // assert that all fields are identical, otherwise print diff
113 assert_json_include!(actual: &parsed, expected: raw);