1 use activitystreams_kinds::object::ImageType;
2 use lemmy_apub_lib::{utils::fetch_object_http, values::MediaTypeMarkdown};
3 use lemmy_db_schema::newtypes::DbUrl;
4 use lemmy_utils::LemmyError;
5 use lemmy_websocket::LemmyContext;
6 use serde::{de::DeserializeOwned, Deserialize, Serialize};
7 use std::collections::HashMap;
11 pub(crate) mod collections;
12 pub(crate) mod objects;
14 #[derive(Clone, Debug, Deserialize, Serialize)]
15 #[serde(rename_all = "camelCase")]
17 pub(crate) content: String,
18 pub(crate) media_type: MediaTypeMarkdown,
22 pub(crate) fn new(content: String) -> Self {
25 media_type: MediaTypeMarkdown::Markdown,
30 #[derive(Clone, Debug, Deserialize, Serialize)]
31 #[serde(rename_all = "camelCase")]
32 pub struct ImageObject {
33 #[serde(rename = "type")]
39 pub(crate) fn new(url: DbUrl) -> Self {
41 kind: ImageType::Image,
47 #[derive(Clone, Debug, Default, Deserialize, Serialize)]
49 pub struct Unparsed(HashMap<String, serde_json::Value>);
55 #[derive(Clone, Debug, Deserialize, Serialize)]
57 pub(crate) enum IdOrNestedObject<Kind: Id> {
62 impl<Kind: Id + DeserializeOwned> IdOrNestedObject<Kind> {
63 pub(crate) fn id(&self) -> &Url {
65 IdOrNestedObject::Id(i) => i,
66 IdOrNestedObject::NestedObject(n) => n.id(),
69 pub(crate) async fn object(
71 context: &LemmyContext,
72 request_counter: &mut i32,
73 ) -> Result<Kind, LemmyError> {
75 IdOrNestedObject::Id(i) => fetch_object_http(&i, context.client(), request_counter).await,
76 IdOrNestedObject::NestedObject(o) => Ok(o),
82 pub(crate) mod tests {
83 use crate::context::WithContext;
84 use assert_json_diff::assert_json_include;
85 use lemmy_utils::LemmyError;
86 use serde::{de::DeserializeOwned, Serialize};
87 use std::{collections::HashMap, fs::File, io::BufReader};
89 pub(crate) fn file_to_json_object<T: DeserializeOwned>(path: &str) -> Result<T, LemmyError> {
90 let file = File::open(path)?;
91 let reader = BufReader::new(file);
92 Ok(serde_json::from_reader(reader)?)
95 pub(crate) fn test_json<T: DeserializeOwned>(path: &str) -> Result<WithContext<T>, LemmyError> {
96 file_to_json_object::<WithContext<T>>(path)
99 /// Check that json deserialize -> serialize -> deserialize gives identical file as initial one.
100 /// Ensures that there are no breaking changes in sent data.
101 pub(crate) fn test_parse_lemmy_item<T: Serialize + DeserializeOwned + std::fmt::Debug>(
103 ) -> Result<T, LemmyError> {
105 let parsed = file_to_json_object::<T>(path)?;
107 // parse file into hashmap, which ensures that every field is included
108 let raw = file_to_json_object::<HashMap<String, serde_json::Value>>(path)?;
109 // assert that all fields are identical, otherwise print diff
110 assert_json_include!(actual: &parsed, expected: raw);