aboutsummaryrefslogtreecommitdiff
path: root/azalea-auth/src/game_profile.rs
blob: ff456bc9593d419d0f232df0f0c50dbd6e80f90a (plain)
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
use std::{
    io::{self, Write},
    sync::Arc,
};

use azalea_buf::{AzBuf, AzBufLimited, AzBufVar, BufReadError};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize, Serializer};
use uuid::Uuid;

/// Information about the player that's usually stored on Mojang's servers.
#[derive(AzBuf, Clone, Debug, Default, Eq, PartialEq)]
pub struct GameProfile {
    /// The UUID of the player.
    ///
    /// Typically a UUIDv4 for online-mode players and UUIDv3 for offline-mode
    /// players.
    pub uuid: Uuid,
    /// The username of the player.
    ///
    /// Limited to 16 bytes.
    pub name: String,
    /// The properties of the player, including their in-game skin and cape.
    ///
    /// This is an `Arc` to make it cheaper to clone.
    pub properties: Arc<GameProfileProperties>,
}

impl GameProfile {
    pub fn new(uuid: Uuid, name: String) -> Self {
        GameProfile {
            uuid,
            name,
            properties: Arc::new(GameProfileProperties::default()),
        }
    }
}

impl From<SerializableGameProfile> for GameProfile {
    fn from(value: SerializableGameProfile) -> Self {
        Self {
            uuid: value.id.unwrap_or_default(),
            name: value.name.unwrap_or_default(),
            properties: Arc::new(value.properties.into()),
        }
    }
}

/// The properties of the player, including their in-game skin and cape.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct GameProfileProperties {
    pub map: IndexMap<String, ProfilePropertyValue>,
}
impl AzBuf for GameProfileProperties {
    fn azalea_read(buf: &mut io::Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let mut properties = IndexMap::new();
        let properties_len = u32::azalea_read_var(buf)?;
        if properties_len > 16 {
            return Err(BufReadError::VecLengthTooLong {
                length: properties_len,
                max_length: 16,
            });
        }
        for _ in 0..properties_len {
            let key = String::azalea_read_limited(buf, 16)?;
            let value = ProfilePropertyValue::azalea_read(buf)?;
            properties.insert(key, value);
        }
        Ok(GameProfileProperties { map: properties })
    }
    fn azalea_write(&self, buf: &mut impl Write) -> io::Result<()> {
        (self.map.len() as u64).azalea_write_var(buf)?;
        for (key, value) in &self.map {
            key.azalea_write(buf)?;
            value.azalea_write(buf)?;
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProfilePropertyValue {
    pub value: String,
    pub signature: Option<String>,
}
impl AzBuf for ProfilePropertyValue {
    fn azalea_read(buf: &mut io::Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let value = String::azalea_read_limited(buf, 32767)?;
        let signature = Option::<String>::azalea_read_limited(buf, 1024)?;
        Ok(ProfilePropertyValue { value, signature })
    }
    fn azalea_write(&self, buf: &mut impl Write) -> io::Result<()> {
        self.value.azalea_write(buf)?;
        self.signature.azalea_write(buf)?;
        Ok(())
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SerializableGameProfile {
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Uuid>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default)]
    #[serde(skip_serializing_if = "SerializableProfileProperties::is_empty")]
    pub properties: SerializableProfileProperties,
}

impl From<GameProfile> for SerializableGameProfile {
    fn from(value: GameProfile) -> Self {
        Self {
            id: Some(value.uuid),
            name: Some(value.name),
            properties: (*value.properties).clone().into(),
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(transparent)]
pub struct SerializableProfileProperties {
    pub list: Vec<SerializableProfilePropertyValue>,
}
impl SerializableProfileProperties {
    pub fn is_empty(&self) -> bool {
        self.list.is_empty()
    }
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SerializableProfilePropertyValue {
    pub name: String,
    pub value: String,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

impl From<GameProfileProperties> for SerializableProfileProperties {
    fn from(value: GameProfileProperties) -> Self {
        let mut list = Vec::new();
        for (name, entry) in value.map {
            list.push(SerializableProfilePropertyValue {
                name,
                value: entry.value,
                signature: entry.signature,
            });
        }
        Self { list }
    }
}
impl From<SerializableProfileProperties> for GameProfileProperties {
    fn from(value: SerializableProfileProperties) -> Self {
        let mut map = IndexMap::new();
        for entry in value.list {
            map.insert(
                entry.name,
                ProfilePropertyValue {
                    value: entry.value,
                    signature: entry.signature,
                },
            );
        }
        Self { map }
    }
}
impl Serialize for GameProfile {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let serializable = SerializableGameProfile::from(self.clone());
        serializable.serialize(serializer)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_deserialize_game_profile() {
        let json = r#"{
            "id": "f1a2b3c4-d5e6-f7a8-b9c0-d1e2f3a4b5c6",
            "name": "Notch",
            "properties": [
                {
                    "name": "qwer",
                    "value": "asdf",
                    "signature": "zxcv"
                }
            ]
        }"#;
        let profile =
            GameProfile::from(serde_json::from_str::<SerializableGameProfile>(json).unwrap());
        assert_eq!(
            profile,
            GameProfile {
                uuid: Uuid::parse_str("f1a2b3c4-d5e6-f7a8-b9c0-d1e2f3a4b5c6").unwrap(),
                name: "Notch".to_owned(),
                properties: {
                    let mut map = IndexMap::new();
                    map.insert(
                        "qwer".to_owned(),
                        ProfilePropertyValue {
                            value: "asdf".to_owned(),
                            signature: Some("zxcv".to_owned()),
                        },
                    );
                    GameProfileProperties { map }.into()
                },
            }
        );
    }
}