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
//! Helper module for the Serialize / Deserialize impl's for the UserIdentifier struct
//! in the parent module.

use ruma_common::{serde::from_raw_json_value, thirdparty::Medium};
use serde::{de, ser::SerializeStruct, Deserialize, Deserializer, Serialize};
use serde_json::value::RawValue as RawJsonValue;

use super::{CustomThirdPartyId, UserIdentifier};

impl Serialize for UserIdentifier {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut id;
        match self {
            Self::UserIdOrLocalpart(user) => {
                id = serializer.serialize_struct("UserIdentifier", 2)?;
                id.serialize_field("type", "m.id.user")?;
                id.serialize_field("user", user)?;
            }
            Self::PhoneNumber { country, phone } => {
                id = serializer.serialize_struct("UserIdentifier", 3)?;
                id.serialize_field("type", "m.id.phone")?;
                id.serialize_field("country", country)?;
                id.serialize_field("phone", phone)?;
            }
            Self::Email { address } => {
                id = serializer.serialize_struct("UserIdentifier", 3)?;
                id.serialize_field("type", "m.id.thirdparty")?;
                id.serialize_field("medium", &Medium::Email)?;
                id.serialize_field("address", address)?;
            }
            Self::Msisdn { number } => {
                id = serializer.serialize_struct("UserIdentifier", 3)?;
                id.serialize_field("type", "m.id.thirdparty")?;
                id.serialize_field("medium", &Medium::Msisdn)?;
                id.serialize_field("address", number)?;
            }
            Self::_CustomThirdParty(CustomThirdPartyId { medium, address }) => {
                id = serializer.serialize_struct("UserIdentifier", 3)?;
                id.serialize_field("type", "m.id.thirdparty")?;
                id.serialize_field("medium", &medium)?;
                id.serialize_field("address", address)?;
            }
        }
        id.end()
    }
}

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

        #[derive(Deserialize)]
        #[serde(tag = "type")]
        enum ExtractType {
            #[serde(rename = "m.id.user")]
            User,
            #[serde(rename = "m.id.phone")]
            Phone,
            #[serde(rename = "m.id.thirdparty")]
            ThirdParty,
        }

        #[derive(Deserialize)]
        struct UserIdOrLocalpart {
            user: String,
        }

        #[derive(Deserialize)]
        struct ThirdPartyId {
            medium: Medium,
            address: String,
        }

        #[derive(Deserialize)]
        struct PhoneNumber {
            country: String,
            phone: String,
        }

        let id_type = serde_json::from_str::<ExtractType>(json.get()).map_err(de::Error::custom)?;

        match id_type {
            ExtractType::User => from_raw_json_value(&json)
                .map(|user_id: UserIdOrLocalpart| Self::UserIdOrLocalpart(user_id.user)),
            ExtractType::Phone => from_raw_json_value(&json)
                .map(|nb: PhoneNumber| Self::PhoneNumber { country: nb.country, phone: nb.phone }),
            ExtractType::ThirdParty => {
                let ThirdPartyId { medium, address } = from_raw_json_value(&json)?;
                match medium {
                    Medium::Email => Ok(Self::Email { address }),
                    Medium::Msisdn => Ok(Self::Msisdn { number: address }),
                    _ => Ok(Self::_CustomThirdParty(CustomThirdPartyId { medium, address })),
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use assert_matches2::assert_matches;
    use serde_json::{from_value as from_json_value, json, to_value as to_json_value};

    use crate::uiaa::UserIdentifier;

    #[test]
    fn serialize() {
        assert_eq!(
            to_json_value(UserIdentifier::UserIdOrLocalpart("@user:notareal.hs".to_owned()))
                .unwrap(),
            json!({
                "type": "m.id.user",
                "user": "@user:notareal.hs",
            })
        );

        assert_eq!(
            to_json_value(UserIdentifier::PhoneNumber {
                country: "33".to_owned(),
                phone: "0102030405".to_owned()
            })
            .unwrap(),
            json!({
                "type": "m.id.phone",
                "country": "33",
                "phone": "0102030405",
            })
        );

        assert_eq!(
            to_json_value(UserIdentifier::Email { address: "me@myprovider.net".to_owned() })
                .unwrap(),
            json!({
                "type": "m.id.thirdparty",
                "medium": "email",
                "address": "me@myprovider.net",
            })
        );

        assert_eq!(
            to_json_value(UserIdentifier::Msisdn { number: "330102030405".to_owned() }).unwrap(),
            json!({
                "type": "m.id.thirdparty",
                "medium": "msisdn",
                "address": "330102030405",
            })
        );

        assert_eq!(
            to_json_value(UserIdentifier::third_party_id("robot".into(), "01001110".to_owned()))
                .unwrap(),
            json!({
                "type": "m.id.thirdparty",
                "medium": "robot",
                "address": "01001110",
            })
        );
    }

    #[test]
    fn deserialize() {
        let json = json!({
            "type": "m.id.user",
            "user": "@user:notareal.hs",
        });
        assert_matches!(from_json_value(json), Ok(UserIdentifier::UserIdOrLocalpart(user)));
        assert_eq!(user, "@user:notareal.hs");

        let json = json!({
            "type": "m.id.phone",
            "country": "33",
            "phone": "0102030405",
        });
        assert_matches!(from_json_value(json), Ok(UserIdentifier::PhoneNumber { country, phone }));
        assert_eq!(country, "33");
        assert_eq!(phone, "0102030405");

        let json = json!({
            "type": "m.id.thirdparty",
            "medium": "email",
            "address": "me@myprovider.net",
        });
        assert_matches!(from_json_value(json), Ok(UserIdentifier::Email { address }));
        assert_eq!(address, "me@myprovider.net");

        let json = json!({
            "type": "m.id.thirdparty",
            "medium": "msisdn",
            "address": "330102030405",
        });
        assert_matches!(from_json_value(json), Ok(UserIdentifier::Msisdn { number }));
        assert_eq!(number, "330102030405");

        let json = json!({
            "type": "m.id.thirdparty",
            "medium": "robot",
            "address": "01110010",
        });
        let id = from_json_value::<UserIdentifier>(json).unwrap();
        let (medium, address) = id.as_third_party_id().unwrap();
        assert_eq!(medium.as_str(), "robot");
        assert_eq!(address, "01110010");
    }
}