Skip to main content

djs_model/
application_identity_profile.rs

1//! [Application identity profiles](https://docs.discord.com/developers/resources/application-identity-profile):
2//! game stats an app stores on a user's identity in its game, shown in Game Stats Widgets on
3//! Discord profiles (D-072).
4//!
5//! An identity is keyed by the provider type, an optional provider ID and the user's ID in the
6//! external system ([`ApplicationIdentity`]); its [`ApplicationIdentityProfile`] holds the
7//! stats.
8
9use std::collections::BTreeMap;
10
11use compact_str::CompactString;
12use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as DeError};
13
14use crate::{
15    id::UserId,
16    macros::int_enum,
17    util::{JsonValue, JsonValueError},
18};
19
20/// An [application identity](https://docs.discord.com/developers/resources/application-identity-profile#application-identity-object):
21/// a user's account in the app's external system.
22///
23/// discord.js counterpart: `APIApplicationIdentity` (discord-api-types).
24#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
25#[non_exhaustive]
26pub struct ApplicationIdentity {
27    /// The Discord user (included in the identity lists the API returns).
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub user_id: Option<UserId>,
30    /// The external account provider type (`NONE` for identities created by a profile write).
31    pub provider_type: CompactString,
32    /// A provider-specific ID that disambiguates identities (absent when empty).
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub provider_id: Option<CompactString>,
35    /// The user's ID in the external system.
36    pub provider_issued_user_id: CompactString,
37}
38
39/// The [profile of an application identity](https://docs.discord.com/developers/resources/application-identity-profile#application-identity-profile-object):
40/// the user's game stats.
41///
42/// Contains floats, so it is `PartialEq` but not `Eq` (D-064).
43///
44/// discord.js counterpart: `APIApplicationIdentityProfile` (discord-api-types).
45#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
46#[non_exhaustive]
47pub struct ApplicationIdentityProfile {
48    /// The user's username in the external system.
49    pub username: Option<CompactString>,
50    /// Arbitrary game-defined data, stored for the app's own use (D-072).
51    pub metadata: Option<BTreeMap<CompactString, JsonValue>>,
52    /// The game stats.
53    pub data: Option<ProfileData>,
54}
55
56/// The [game stats](https://docs.discord.com/developers/resources/application-identity-profile#profile-data-object)
57/// of a profile: preconfigured fields and custom ones.
58///
59/// Also the `data` sent to update a profile (max 10 KB serialized, up to 30 dynamic fields).
60///
61/// discord.js counterpart: `APIApplicationIdentityProfileData` (discord-api-types).
62#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
63#[non_exhaustive]
64pub struct ProfileData {
65    /// The preconfigured stat fields.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub primary: Option<Box<PrimaryProfileData>>,
68    /// Custom stat fields.
69    #[serde(default, skip_serializing_if = "Vec::is_empty")]
70    pub dynamic: Vec<DynamicField>,
71}
72
73/// The [preconfigured stat fields](https://docs.discord.com/developers/resources/application-identity-profile#primary-profile-data-object)
74/// of a profile (text values: max 100 characters).
75///
76/// discord.js counterpart: `APIApplicationIdentityProfilePrimaryData` (discord-api-types).
77#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
78#[non_exhaustive]
79pub struct PrimaryProfileData {
80    /// The current season's name (e.g. "Season 3").
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub season: Option<CompactString>,
83    /// The current rank's name (e.g. "Silver").
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub rank_name: Option<CompactString>,
86    /// An image of the current rank.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub rank_image: Option<ProfileMedia>,
89    /// The highest rank achieved.
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub highest_rank: Option<CompactString>,
92    /// An image of the highest rank achieved.
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    pub highest_rank_image: Option<ProfileMedia>,
95    /// The featured played character's name.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub featured_played_character: Option<CompactString>,
98    /// An image of the featured played character.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub featured_played_character_image: Option<ProfileMedia>,
101    /// The total playtime in hours (fractions allowed, e.g. `69.41`).
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub playtime_hours: Option<f64>,
104    /// The total number of wins.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub total_wins: Option<u64>,
107    /// The wins in the current period (e.g. season).
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub current_period_wins: Option<u64>,
110    /// The total number of games played.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub total_games: Option<u64>,
113    /// The games played in the current period.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub current_period_games: Option<u64>,
116    /// The total number of kills.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub total_kills: Option<u64>,
119    /// The kills in the current period.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub current_period_kills: Option<u64>,
122    /// The total number of assists.
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub total_assists: Option<u64>,
125    /// The assists in the current period.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub current_period_assists: Option<u64>,
128    /// The total number of deaths.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub total_deaths: Option<u64>,
131    /// The deaths in the current period.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub current_period_deaths: Option<u64>,
134}
135
136/// An image in profile data ([media object](https://docs.discord.com/developers/resources/application-identity-profile#media-object)).
137///
138/// discord.js counterpart: `APIApplicationIdentityProfileMedia` (discord-api-types).
139#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
140#[non_exhaustive]
141pub struct ProfileMedia {
142    /// The image's URL.
143    pub url: CompactString,
144}
145
146impl ProfileMedia {
147    /// Creates a media object.
148    ///
149    /// discord.js counterpart: `APIApplicationIdentityProfileMedia` (discord-api-types).
150    #[must_use]
151    pub fn new(url: impl Into<CompactString>) -> Self {
152        Self { url: url.into() }
153    }
154}
155
156/// A [custom stat field](https://docs.discord.com/developers/resources/application-identity-profile#dynamic-field-object):
157/// a name and a typed value.
158///
159/// discord.js counterpart: `APIApplicationIdentityProfileDynamicField` (discord-api-types).
160#[derive(Clone, Debug, PartialEq)]
161#[non_exhaustive]
162pub struct DynamicField {
163    /// The field's name (max 100 characters).
164    pub name: CompactString,
165    /// The field's value.
166    pub value: DynamicFieldValue,
167}
168
169impl DynamicField {
170    /// Creates a field.
171    ///
172    /// discord.js counterpart: `APIApplicationIdentityProfileDynamicField` (discord-api-types).
173    #[must_use]
174    pub fn new(name: impl Into<CompactString>, value: DynamicFieldValue) -> Self {
175        Self {
176            name: name.into(),
177            value,
178        }
179    }
180}
181
182/// The value of a [`DynamicField`], by [field type](DynamicFieldType).
183///
184/// discord.js counterpart: none (the `value` of an `APIApplicationIdentityProfileDynamicField`, typed by its type).
185#[derive(Clone, Debug, PartialEq)]
186#[non_exhaustive]
187pub enum DynamicFieldValue {
188    /// Text.
189    String(CompactString),
190    /// A number.
191    Number(f64),
192    /// An image.
193    Media(ProfileMedia),
194    /// A field type this version does not know; its value is not kept.
195    Unknown(DynamicFieldType),
196}
197
198impl DynamicFieldValue {
199    /// Returns the field type.
200    ///
201    /// discord.js counterpart: `ApplicationIdentityProfileDynamicFieldType` (discord-api-types).
202    #[must_use]
203    pub const fn kind(&self) -> DynamicFieldType {
204        match self {
205            Self::String(_) => DynamicFieldType::String,
206            Self::Number(_) => DynamicFieldType::Number,
207            Self::Media(_) => DynamicFieldType::Media,
208            Self::Unknown(kind) => *kind,
209        }
210    }
211}
212
213int_enum! {
214    /// The [type of a dynamic field](https://docs.discord.com/developers/resources/application-identity-profile#dynamic-field-object-dynamic-field-types).
215    ///
216    /// discord.js counterpart: `ApplicationIdentityProfileDynamicFieldType` (discord-api-types).
217    pub enum DynamicFieldType: u8 {
218        /// [`DynamicFieldValue::String`].
219        String = 1,
220        /// [`DynamicFieldValue::Number`].
221        Number = 2,
222        /// [`DynamicFieldValue::Media`].
223        Media = 3,
224    }
225}
226
227#[derive(Deserialize)]
228struct RawDynamicField {
229    #[serde(rename = "type")]
230    kind: DynamicFieldType,
231    name: CompactString,
232    #[serde(default)]
233    value: Option<JsonValue>,
234}
235
236impl<'de> Deserialize<'de> for DynamicField {
237    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
238        let raw = RawDynamicField::deserialize(deserializer)?;
239        let convert = |error: JsonValueError| D::Error::custom(format_args!("value: {error}"));
240        let value = match raw.kind {
241            DynamicFieldType::Unknown(_) => DynamicFieldValue::Unknown(raw.kind),
242            kind => {
243                let value = raw.value.ok_or_else(|| D::Error::missing_field("value"))?;
244                match kind {
245                    DynamicFieldType::String => {
246                        DynamicFieldValue::String(value.to_type().map_err(convert)?)
247                    }
248                    DynamicFieldType::Number => {
249                        DynamicFieldValue::Number(value.to_type().map_err(convert)?)
250                    }
251                    _ => DynamicFieldValue::Media(value.to_type().map_err(convert)?),
252                }
253            }
254        };
255        Ok(Self {
256            name: raw.name,
257            value,
258        })
259    }
260}
261
262impl Serialize for DynamicField {
263    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
264        #[derive(Serialize)]
265        #[serde(untagged)]
266        enum Value<'a> {
267            String(&'a str),
268            Number(f64),
269            Media(&'a ProfileMedia),
270        }
271
272        #[derive(Serialize)]
273        struct Flat<'a> {
274            #[serde(rename = "type")]
275            kind: DynamicFieldType,
276            name: &'a str,
277            #[serde(skip_serializing_if = "Option::is_none")]
278            value: Option<Value<'a>>,
279        }
280
281        Flat {
282            kind: self.value.kind(),
283            name: &self.name,
284            value: match &self.value {
285                DynamicFieldValue::String(value) => Some(Value::String(value)),
286                DynamicFieldValue::Number(value) => Some(Value::Number(*value)),
287                DynamicFieldValue::Media(value) => Some(Value::Media(value)),
288                DynamicFieldValue::Unknown(_) => None,
289            },
290        }
291        .serialize(serializer)
292    }
293}