Skip to main content

azalea_auth/
game_profile.rs

1use std::{
2    io::{self, Write},
3    sync::Arc,
4};
5
6use azalea_buf::{AzBuf, AzBufLimited, AzBufVar, BufReadError, BufReadErrorRepr};
7use indexmap::IndexMap;
8use serde::{Deserialize, Serialize, Serializer};
9use uuid::Uuid;
10
11/// Information about the player that's usually stored on Mojang's servers.
12#[derive(AzBuf, Clone, Debug, Default, Eq, PartialEq)]
13pub struct GameProfile {
14    /// The UUID of the player.
15    ///
16    /// Typically a UUIDv4 for online-mode players and UUIDv3 for offline-mode
17    /// players.
18    pub uuid: Uuid,
19    /// The username of the player.
20    ///
21    /// Limited to 16 bytes.
22    pub name: String,
23    /// The properties of the player, including their in-game skin and cape.
24    ///
25    /// This is an `Arc` to make it cheaper to clone.
26    pub properties: Arc<GameProfileProperties>,
27}
28
29impl GameProfile {
30    pub fn new(uuid: Uuid, name: String) -> Self {
31        GameProfile {
32            uuid,
33            name,
34            properties: Arc::new(GameProfileProperties::default()),
35        }
36    }
37}
38
39impl From<SerializableGameProfile> for GameProfile {
40    fn from(value: SerializableGameProfile) -> Self {
41        Self {
42            uuid: value.id.unwrap_or_default(),
43            name: value.name.unwrap_or_default(),
44            properties: Arc::new(value.properties.into()),
45        }
46    }
47}
48#[cfg(feature = "azalea-codec")]
49azalea_codec::impl_codec_from!(GameProfile, SerializableGameProfile, struct IncompleteGameProfile);
50#[cfg(feature = "azalea-codec")]
51azalea_codec::impl_mapcodec_from!(GameProfile, SerializableGameProfile);
52
53/// The properties of the player, including their in-game skin and cape.
54#[derive(Clone, Debug, Default, Eq, PartialEq)]
55pub struct GameProfileProperties {
56    pub map: IndexMap<String, ProfilePropertyValue>,
57}
58impl AzBuf for GameProfileProperties {
59    fn azalea_read(
60        ctx: azalea_buf::Ctx,
61        buf: &mut io::Cursor<&[u8]>,
62    ) -> Result<Self, BufReadError> {
63        let mut properties = IndexMap::new();
64        let properties_len = u32::azalea_read_var(ctx, buf)?;
65        if properties_len > 16 {
66            return Err(BufReadErrorRepr::VecLengthTooLong {
67                length: properties_len,
68                max_length: 16,
69            }
70            .into());
71        }
72        for _ in 0..properties_len {
73            let key = String::azalea_read_limited(ctx, buf, 16)?;
74            let value = ProfilePropertyValue::azalea_read(ctx, buf)?;
75            properties.insert(key, value);
76        }
77        Ok(GameProfileProperties { map: properties })
78    }
79    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
80        (self.map.len() as u64).azalea_write_var(ctx, buf)?;
81        for (key, value) in &self.map {
82            key.azalea_write(ctx, buf)?;
83            value.azalea_write(ctx, buf)?;
84        }
85        Ok(())
86    }
87}
88
89#[cfg(feature = "azalea-codec")]
90azalea_codec::impl_codec_from!(GameProfileProperties, SerializableProfileProperties, struct IncompleteGameProfileProperties);
91#[cfg(feature = "azalea-codec")]
92azalea_codec::impl_defaultable!(GameProfileProperties);
93
94#[derive(Clone, Debug, Eq, PartialEq)]
95pub struct ProfilePropertyValue {
96    pub value: String,
97    pub signature: Option<String>,
98}
99impl AzBuf for ProfilePropertyValue {
100    fn azalea_read(
101        ctx: azalea_buf::Ctx,
102        buf: &mut io::Cursor<&[u8]>,
103    ) -> Result<Self, BufReadError> {
104        let value = String::azalea_read_limited(ctx, buf, 32767)?;
105        let signature = Option::<String>::azalea_read_limited(ctx, buf, 1024)?;
106        Ok(ProfilePropertyValue { value, signature })
107    }
108    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
109        self.value.azalea_write(ctx, buf)?;
110        self.signature.azalea_write(ctx, buf)?;
111        Ok(())
112    }
113}
114
115#[derive(Clone, Debug, Deserialize, Serialize)]
116#[cfg_attr(feature = "azalea-codec", derive(azalea_codec::Codec))]
117pub struct SerializableGameProfile {
118    #[serde(default)]
119    #[serde(skip_serializing_if = "Option::is_none")]
120    #[cfg_attr(feature = "azalea-codec", codec(optional))]
121    pub id: Option<Uuid>,
122    #[serde(default)]
123    #[serde(skip_serializing_if = "Option::is_none")]
124    #[cfg_attr(feature = "azalea-codec", codec(optional))]
125    pub name: Option<String>,
126    #[serde(default)]
127    #[serde(skip_serializing_if = "SerializableProfileProperties::is_empty")]
128    #[cfg_attr(feature = "azalea-codec", codec(optional))]
129    pub properties: SerializableProfileProperties,
130}
131
132impl From<GameProfile> for SerializableGameProfile {
133    fn from(value: GameProfile) -> Self {
134        Self {
135            id: Some(value.uuid),
136            name: Some(value.name),
137            properties: (*value.properties).clone().into(),
138        }
139    }
140}
141
142#[derive(Clone, Debug, Default, Deserialize, Serialize)]
143#[cfg_attr(feature = "azalea-codec", derive(azalea_codec::Codec))]
144#[serde(transparent)]
145pub struct SerializableProfileProperties {
146    pub list: Vec<SerializableProfilePropertyValue>,
147}
148impl SerializableProfileProperties {
149    pub fn is_empty(&self) -> bool {
150        self.list.is_empty()
151    }
152}
153#[cfg(feature = "azalea-codec")]
154azalea_codec::impl_defaultable!(SerializableProfileProperties, self, self.is_empty());
155
156#[derive(Clone, Debug, Deserialize, Serialize)]
157#[cfg_attr(feature = "azalea-codec", derive(azalea_codec::Codec))]
158pub struct SerializableProfilePropertyValue {
159    pub name: String,
160    pub value: String,
161    #[serde(default)]
162    #[serde(skip_serializing_if = "Option::is_none")]
163    #[cfg_attr(feature = "azalea-codec", codec(optional))]
164    pub signature: Option<String>,
165}
166
167impl From<GameProfileProperties> for SerializableProfileProperties {
168    fn from(value: GameProfileProperties) -> Self {
169        let mut list = Vec::new();
170        for (name, entry) in value.map {
171            list.push(SerializableProfilePropertyValue {
172                name,
173                value: entry.value,
174                signature: entry.signature,
175            });
176        }
177        Self { list }
178    }
179}
180impl From<SerializableProfileProperties> for GameProfileProperties {
181    fn from(value: SerializableProfileProperties) -> Self {
182        let mut map = IndexMap::new();
183        for entry in value.list {
184            map.insert(
185                entry.name,
186                ProfilePropertyValue {
187                    value: entry.value,
188                    signature: entry.signature,
189                },
190            );
191        }
192        Self { map }
193    }
194}
195impl Serialize for GameProfile {
196    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
197        let serializable = SerializableGameProfile::from(self.clone());
198        serializable.serialize(serializer)
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn test_deserialize_game_profile() {
208        let json = r#"{
209            "id": "f1a2b3c4-d5e6-f7a8-b9c0-d1e2f3a4b5c6",
210            "name": "Notch",
211            "properties": [
212                {
213                    "name": "qwer",
214                    "value": "asdf",
215                    "signature": "zxcv"
216                }
217            ]
218        }"#;
219        let profile =
220            GameProfile::from(serde_json::from_str::<SerializableGameProfile>(json).unwrap());
221        assert_eq!(
222            profile,
223            GameProfile {
224                uuid: Uuid::parse_str("f1a2b3c4-d5e6-f7a8-b9c0-d1e2f3a4b5c6").unwrap(),
225                name: "Notch".to_owned(),
226                properties: {
227                    let mut map = IndexMap::new();
228                    map.insert(
229                        "qwer".to_owned(),
230                        ProfilePropertyValue {
231                            value: "asdf".to_owned(),
232                            signature: Some("zxcv".to_owned()),
233                        },
234                    );
235                    GameProfileProperties { map }.into()
236                },
237            }
238        );
239    }
240}