ruma_client_api/push/
pusher_serde.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use ruma_common::serde::from_raw_json_value;
use serde::{de, ser::SerializeStruct, Deserialize, Serialize};
use serde_json::value::RawValue as RawJsonValue;

use super::{Pusher, PusherIds, PusherKind};

#[derive(Debug, Deserialize)]
struct PusherDeHelper {
    #[serde(flatten)]
    ids: PusherIds,
    app_display_name: String,
    device_display_name: String,
    profile_tag: Option<String>,
    lang: String,
}

impl<'de> Deserialize<'de> for Pusher {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        let json = Box::<RawJsonValue>::deserialize(deserializer)?;

        let PusherDeHelper { ids, app_display_name, device_display_name, profile_tag, lang } =
            from_raw_json_value(&json)?;
        let kind = from_raw_json_value(&json)?;

        Ok(Self { ids, kind, app_display_name, device_display_name, profile_tag, lang })
    }
}

impl Serialize for PusherKind {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut st = serializer.serialize_struct("PusherAction", 3)?;

        match self {
            PusherKind::Http(data) => {
                st.serialize_field("kind", &"http")?;
                st.serialize_field("data", data)?;
            }
            PusherKind::Email(data) => {
                st.serialize_field("kind", &"email")?;
                st.serialize_field("data", data)?;
            }
            PusherKind::_Custom(custom) => {
                st.serialize_field("kind", &custom.kind)?;
                st.serialize_field("data", &custom.data)?;
            }
        }

        st.end()
    }
}

#[derive(Debug, Deserialize)]
struct PusherKindDeHelper {
    kind: String,
    data: Box<RawJsonValue>,
}

impl<'de> Deserialize<'de> for PusherKind {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        let json = Box::<RawJsonValue>::deserialize(deserializer)?;
        let PusherKindDeHelper { kind, data } = from_raw_json_value(&json)?;

        match kind.as_ref() {
            "http" => from_raw_json_value(&data).map(Self::Http),
            "email" => from_raw_json_value(&data).map(Self::Email),
            _ => from_raw_json_value(&json).map(Self::_Custom),
        }
    }
}

#[cfg(test)]
mod tests {
    use assert_matches2::assert_matches;
    use ruma_common::{push::HttpPusherData, serde::JsonObject};
    use serde_json::{
        from_value as from_json_value, json, to_value as to_json_value, Value as JsonValue,
    };

    use crate::push::{CustomPusherData, EmailPusherData, PusherKind};

    #[test]
    fn serialize_email() {
        // With default data fields.
        let mut data = EmailPusherData::new();
        let action = PusherKind::Email(data.clone());

        assert_eq!(
            to_json_value(action).unwrap(),
            json!({
                "kind": "email",
                "data": {},
            })
        );

        // With custom data fields.
        data.data.insert("custom_key".to_owned(), "value".into());
        let action = PusherKind::Email(data);

        assert_eq!(
            to_json_value(action).unwrap(),
            json!({
                "kind": "email",
                "data": {
                    "custom_key": "value",
                },
            })
        );
    }

    #[test]
    fn serialize_http() {
        // With default data fields.
        let mut data = HttpPusherData::new("http://localhost".to_owned());
        let action = PusherKind::Http(data.clone());

        assert_eq!(
            to_json_value(action).unwrap(),
            json!({
                "kind": "http",
                "data": {
                    "url": "http://localhost",
                },
            })
        );

        // With custom data fields.
        data.data.insert("custom_key".to_owned(), "value".into());
        let action = PusherKind::Http(data);

        assert_eq!(
            to_json_value(action).unwrap(),
            json!({
                "kind": "http",
                "data": {
                    "url": "http://localhost",
                    "custom_key": "value",
                },
            })
        );
    }

    #[test]
    fn serialize_custom() {
        let action = PusherKind::_Custom(CustomPusherData {
            kind: "my.custom.kind".to_owned(),
            data: JsonObject::new(),
        });

        assert_eq!(
            to_json_value(action).unwrap(),
            json!({
                "kind": "my.custom.kind",
                "data": {}
            })
        );
    }

    #[test]
    fn deserialize_email() {
        // With default data fields.
        let json = json!({
            "kind": "email",
            "data": {},
        });

        assert_matches!(from_json_value(json).unwrap(), PusherKind::Email(data));
        assert!(data.data.is_empty());

        // With custom data fields.
        let json = json!({
            "kind": "email",
            "data": {
                "custom_key": "value",
            },
        });

        assert_matches!(from_json_value(json).unwrap(), PusherKind::Email(data));
        assert_eq!(data.data.len(), 1);
        assert_matches!(data.data.get("custom_key"), Some(JsonValue::String(custom_value)));
        assert_eq!(custom_value, "value");
    }

    #[test]
    fn deserialize_http() {
        // With default data fields.
        let json = json!({
            "kind": "http",
            "data": {
                "url": "http://localhost",
            },
        });

        assert_matches!(from_json_value(json).unwrap(), PusherKind::Http(data));
        assert_eq!(data.url, "http://localhost");
        assert_eq!(data.format, None);
        assert!(data.data.is_empty());

        // With custom data fields.
        let json = json!({
            "kind": "http",
            "data": {
                "url": "http://localhost",
                "custom_key": "value",
            },
        });

        assert_matches!(from_json_value(json).unwrap(), PusherKind::Http(data));
        assert_eq!(data.data.len(), 1);
        assert_matches!(data.data.get("custom_key"), Some(JsonValue::String(custom_value)));
        assert_eq!(custom_value, "value");
    }

    #[test]
    fn deserialize_custom() {
        let json = json!({
            "kind": "my.custom.kind",
            "data": {}
        });

        assert_matches!(from_json_value(json).unwrap(), PusherKind::_Custom(custom));
        assert_eq!(custom.kind, "my.custom.kind");
        assert!(custom.data.is_empty());
    }
}