diff options
| author | Zeyla Hellyer <[email protected]> | 2017-04-11 08:15:37 -0700 |
|---|---|---|
| committer | Zeyla Hellyer <[email protected]> | 2017-04-11 10:52:43 -0700 |
| commit | f6b27eb39c042e6779edc2d5d4b6e6c27d133eaf (patch) | |
| tree | a6169fee3bf9ea75391101577dcb2982e3daa388 /src/model/guild | |
| parent | Clippy lints + permission byte literals (diff) | |
| download | serenity-f6b27eb39c042e6779edc2d5d4b6e6c27d133eaf.tar.xz serenity-f6b27eb39c042e6779edc2d5d4b6e6c27d133eaf.zip | |
Switch to using serde for deserialization
The current build system is rudimentary, incomplete, and rigid, offering
little in the way of customizing decoding options.
To solve this, switch to using serde-derive with custom Deserialization
implementations. This allows very simple deserialization when special
logic does not need to be applied, yet allows us to implement our own
deserialization logic when required.
The problem with the build system was that it built enums and structs
from YAML files. This is not so good, because it requires creating a
custom build system (which was rudimentary), creating "special struct
configs" when logic needed to be ever so slightly extended (rigid), and
if special logic needed to be applied, a custom deserialization method
would have been needed to be made anyway (incomplete).
To solve this, switch to serde-derive and implementing Deserialize
ourselves where required. This reduces YAML definitions that might
look like:
```yaml
---
name: Group
description: >
A group channel, potentially including other users, separate from a [`Guild`].
[`Guild`]: struct.Guild.html
fields:
- name: channel_id
description: The Id of the group channel.
from: id
type: ChannelId
- name: icon
description: The optional icon of the group channel.
optional: true
type: string
- name: last_message_id
description: The Id of the last message sent.
optional: true
type: MessageId
- name: last_pin_timestamp
description: Timestamp of the latest pinned message.
optional: true
type: string
- name: name
description: The name of the group channel.
optional: true
type: string
- name: owner_id
description: The Id of the group channel creator.
type: UserId
- name: recipients
description: Group channel's members.
custom: decode_users
t: UserId, Arc<RwLock<User>>
type: hashmap
```
to:
```rs
/// A group channel - potentially including other [`User`]s - separate from a
/// [`Guild`].
///
/// [`Guild`]: struct.Guild.html
/// [`User`]: struct.User.html
pub struct Group {
/// The Id of the group channel.
#[serde(rename="id")]
pub channel_id: ChannelId,
/// The optional icon of the group channel.
pub icon: Option<String>,
/// The Id of the last message sent.
pub last_message_id: Option<MessageId>,
/// Timestamp of the latest pinned message.
pub last_pin_timestamp: Option<String>,
/// The name of the group channel.
pub name: Option<String>,
/// The Id of the group owner.
pub owner_id: UserId,
/// A map of the group's recipients.
#[serde(deserialize_with="deserialize_users")]
pub recipients: HashMap<UserId, Arc<RwLock<User>>>,
}
```
This is much simpler and does not have as much boilerplate.
There should not be any backwards incompatible changes other than the
old, public - yet undocumented (and hidden from documentation) - decode
methods being removed. Due to the nature of this commit, field names may
be incorrect, and will need to be corrected as deserialization errors
are found.
Diffstat (limited to 'src/model/guild')
| -rw-r--r-- | src/model/guild/emoji.rs | 34 | ||||
| -rw-r--r-- | src/model/guild/feature.rs | 25 | ||||
| -rw-r--r-- | src/model/guild/guild_id.rs | 50 | ||||
| -rw-r--r-- | src/model/guild/integration.rs | 26 | ||||
| -rw-r--r-- | src/model/guild/member.rs | 41 | ||||
| -rw-r--r-- | src/model/guild/mod.rs | 408 | ||||
| -rw-r--r-- | src/model/guild/partial_guild.rs | 24 | ||||
| -rw-r--r-- | src/model/guild/role.rs | 46 |
8 files changed, 528 insertions, 126 deletions
diff --git a/src/model/guild/emoji.rs b/src/model/guild/emoji.rs index 0bb0f40..54a70d3 100644 --- a/src/model/guild/emoji.rs +++ b/src/model/guild/emoji.rs @@ -1,9 +1,7 @@ use std::fmt::{Display, Formatter, Result as FmtResult, Write as FmtWrite}; -use ::model::{Emoji, EmojiId}; +use ::model::{EmojiId, RoleId}; #[cfg(feature="cache")] -use serde_json::builder::ObjectBuilder; -#[cfg(feature="cache")] use std::mem; #[cfg(feature="cache")] use ::client::{CACHE, rest}; @@ -12,6 +10,30 @@ use ::internal::prelude::*; #[cfg(feature="cache")] use ::model::GuildId; +/// Represents a custom guild emoji, which can either be created using the API, +/// or via an integration. Emojis created using the API only work within the +/// guild it was created in. +#[derive(Clone, Debug, Deserialize)] +pub struct Emoji { + /// The Id of the emoji. + pub id: EmojiId, + /// The name of the emoji. It must be at least 2 characters long and can + /// only contain alphanumeric characters and underscores. + pub name: String, + /// Whether the emoji is managed via an [`Integration`] service. + /// + /// [`Integration`]: struct.Integration.html + pub managed: bool, + /// Whether the emoji name needs to be surrounded by colons in order to be + /// used by the client. + pub require_colons: bool, + /// A list of [`Role`]s that are allowed to use the emoji. If there are no + /// roles specified, then usage is unrestricted. + /// + /// [`Role`]: struct.Role.html + pub roles: Vec<RoleId>, +} + impl Emoji { /// Deletes the emoji. /// @@ -39,9 +61,9 @@ impl Emoji { pub fn edit(&mut self, name: &str) -> Result<()> { match self.find_guild_id() { Some(guild_id) => { - let map = ObjectBuilder::new() - .insert("name", name) - .build(); + let map = json!({ + "name": name, + }); match rest::edit_emoji(guild_id.0, self.id.0, &map) { Ok(emoji) => { diff --git a/src/model/guild/feature.rs b/src/model/guild/feature.rs new file mode 100644 index 0000000..cfbcabc --- /dev/null +++ b/src/model/guild/feature.rs @@ -0,0 +1,25 @@ +/// A special feature, such as for VIP guilds, that a [`Guild`] has had granted +/// to them. +/// +/// [`Guild`]: struct.Guild.html +#[derive(Copy, Clone, Debug, Deserialize, Hash, Eq, PartialEq)] +pub enum Feature { + /// The [`Guild`] can set a custom [`splash`][`Guild::splash`] image on + /// invite URLs. + /// + /// [`Guild`]: struct.Guild.html + /// [`Guild::splash`]: struct.Guild.html#structfield.splash + #[serde(rename="INVITE_SPLASH")] + InviteSplash, + /// The [`Guild`] can set a Vanity URL, which is a custom-named permanent + /// invite code. + /// + /// [`Guild`]: struct.Guild.html + #[serde(rename="VANITY_URL")] + VanityUrl, + /// The [`Guild`] has access to VIP voice channel regions. + /// + /// [`Guild`]: struct.Guild.html + #[serde(rename="VIP_REGIONS")] + VipRegions, +} diff --git a/src/model/guild/guild_id.rs b/src/model/guild/guild_id.rs index d568360..1ef9a32 100644 --- a/src/model/guild/guild_id.rs +++ b/src/model/guild/guild_id.rs @@ -1,4 +1,3 @@ -use serde_json::builder::ObjectBuilder; use std::fmt::{Display, Formatter, Result as FmtResult}; use ::client::rest; use ::internal::prelude::*; @@ -71,10 +70,10 @@ impl GuildId { /// [`rest::create_channel`]: ../client/rest/fn.create_channel.html /// [Manage Channels]: permissions/constant.MANAGE_CHANNELS.html pub fn create_channel(&self, name: &str, kind: ChannelType) -> Result<GuildChannel> { - let map = ObjectBuilder::new() - .insert("name", name) - .insert("type", kind.name()) - .build(); + let map = json!({ + "name": name, + "type": kind.name(), + }); rest::create_channel(self.0, &map) } @@ -97,10 +96,10 @@ impl GuildId { /// [`utils::read_image`]: ../utils/fn.read_image.html /// [Manage Emojis]: permissions/constant.MANAGE_EMOJIS.html pub fn create_emoji(&self, name: &str, image: &str) -> Result<Emoji> { - let map = ObjectBuilder::new() - .insert("name", name) - .insert("image", image) - .build(); + let map = json!({ + "name": name, + "image": image, + }); rest::create_emoji(self.0, &map) } @@ -113,10 +112,10 @@ impl GuildId { pub fn create_integration<I>(&self, integration_id: I, kind: &str) -> Result<()> where I: Into<IntegrationId> { let integration_id = integration_id.into(); - let map = ObjectBuilder::new() - .insert("id", integration_id.0) - .insert("type", kind) - .build(); + let map = json!({ + "id": integration_id.0, + "type": kind, + }); rest::create_guild_integration(self.0, integration_id.0, &map) } @@ -131,7 +130,7 @@ impl GuildId { /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html #[inline] pub fn create_role<F: FnOnce(EditRole) -> EditRole>(&self, f: F) -> Result<Role> { - rest::create_role(self.0, &f(EditRole::default()).0.build()) + rest::create_role(self.0, &f(EditRole::default()).0) } /// Deletes the current guild if the current account is the owner of the @@ -194,7 +193,7 @@ impl GuildId { /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] pub fn edit<F: FnOnce(EditGuild) -> EditGuild>(&mut self, f: F) -> Result<PartialGuild> { - rest::edit_guild(self.0, &f(EditGuild::default()).0.build()) + rest::edit_guild(self.0, &f(EditGuild::default()).0) } /// Edits an [`Emoji`]'s name in the guild. @@ -208,7 +207,9 @@ impl GuildId { /// [`Emoji::edit`]: struct.Emoji.html#method.edit /// [Manage Emojis]: permissions/constant.MANAGE_EMOJIS.html pub fn edit_emoji<E: Into<EmojiId>>(&self, emoji_id: E, name: &str) -> Result<Emoji> { - let map = ObjectBuilder::new().insert("name", name).build(); + let map = json!({ + "name": name, + }); rest::edit_emoji(self.0, emoji_id.into().0, &map) } @@ -229,7 +230,7 @@ impl GuildId { #[inline] pub fn edit_member<F, U>(&self, user_id: U, f: F) -> Result<()> where F: FnOnce(EditMember) -> EditMember, U: Into<UserId> { - rest::edit_member(self.0, user_id.into().0, &f(EditMember::default()).0.build()) + rest::edit_member(self.0, user_id.into().0, &f(EditMember::default()).0) } /// Edits the current user's nickname for the guild. @@ -263,7 +264,7 @@ impl GuildId { #[inline] pub fn edit_role<F, R>(&self, role_id: R, f: F) -> Result<Role> where F: FnOnce(EditRole) -> EditRole, R: Into<RoleId> { - rest::edit_role(self.0, role_id.into().0, &f(EditRole::default()).0.build()) + rest::edit_role(self.0, role_id.into().0, &f(EditRole::default()).0) } /// Search the cache for the guild. @@ -372,7 +373,9 @@ impl GuildId { /// [`Member`]: struct.Member.html /// [Kick Members]: permissions/constant.KICK_MEMBERS.html pub fn get_prune_count(&self, days: u16) -> Result<GuildPrune> { - let map = ObjectBuilder::new().insert("days", days).build(); + let map = json!({ + "days": days, + }); rest::get_guild_prune_count(self.0, &map) } @@ -411,7 +414,8 @@ impl GuildId { /// [Move Members]: permissions/constant.MOVE_MEMBERS.html pub fn move_member<C, U>(&self, user_id: U, channel_id: C) -> Result<()> where C: Into<ChannelId>, U: Into<UserId> { - let map = ObjectBuilder::new().insert("channel_id", channel_id.into().0).build(); + let mut map = Map::new(); + map.insert("channel_id".to_owned(), Value::Number(Number::from(channel_id.into().0))); rest::edit_member(self.0, user_id.into().0, &map) } @@ -437,7 +441,11 @@ impl GuildId { /// [Kick Members]: permissions/constant.KICK_MEMBERS.html #[inline] pub fn start_prune(&self, days: u16) -> Result<GuildPrune> { - rest::start_guild_prune(self.0, &ObjectBuilder::new().insert("days", days).build()) + let map = json!({ + "days": days, + }); + + rest::start_guild_prune(self.0, &map) } /// Unbans a [`User`] from the guild. diff --git a/src/model/guild/integration.rs b/src/model/guild/integration.rs index d7f9967..b276bc3 100644 --- a/src/model/guild/integration.rs +++ b/src/model/guild/integration.rs @@ -1,4 +1,21 @@ -use ::model::{Integration, IntegrationId}; +use super::*; + +/// Various information about integrations. +#[derive(Clone, Debug, Deserialize)] +pub struct Integration { + pub id: IntegrationId, + pub account: IntegrationAccount, + pub enabled: bool, + #[serde(rename="expire_behaviour")] + pub expire_behaviour: u64, + pub expire_grace_period: u64, + pub kind: String, + pub name: String, + pub role_id: RoleId, + pub synced_at: u64, + pub syncing: bool, + pub user: User, +} impl From<Integration> for IntegrationId { /// Gets the Id of integration. @@ -6,3 +23,10 @@ impl From<Integration> for IntegrationId { integration.id } } + +/// Integration account object. +#[derive(Clone, Debug, Deserialize)] +pub struct IntegrationAccount { + pub id: String, + pub name: String, +} diff --git a/src/model/guild/member.rs b/src/model/guild/member.rs index 8fc53e1..630610f 100644 --- a/src/model/guild/member.rs +++ b/src/model/guild/member.rs @@ -1,15 +1,39 @@ use std::borrow::Cow; use std::fmt::{Display, Formatter, Result as FmtResult}; -use ::internal::prelude::*; +use super::deserialize_sync_user; use ::model::*; #[cfg(feature="cache")] use ::client::{CACHE, rest}; #[cfg(feature="cache")] +use ::internal::prelude::*; +#[cfg(feature="cache")] use ::utils::builder::EditMember; #[cfg(feature="cache")] use ::utils::Colour; +/// Information about a member of a guild. +#[derive(Clone, Debug, Deserialize)] +pub struct Member { + /// Indicator of whether the member can hear in voice channels. + pub deaf: bool, + /// The unique Id of the guild that the member is a part of. + pub guild_id: Option<GuildId>, + /// Timestamp representing the date when the member joined. + pub joined_at: String, + /// Indicator of whether the member can speak in voice channels. + pub mute: bool, + /// The member's nickname, if present. + /// + /// Can't be longer than 32 characters. + pub nick: Option<String>, + /// Vector of Ids of [`Role`]s given to the member. + pub roles: Vec<RoleId>, + /// Attached User struct. + #[serde(deserialize_with="deserialize_sync_user")] + pub user: Arc<RwLock<User>>, +} + impl Member { /// Adds a [`Role`] to the member, editing its roles in-place if the request /// was successful. @@ -50,7 +74,7 @@ impl Member { let guild_id = self.find_guild()?; self.roles.extend_from_slice(role_ids); - let map = EditMember::default().roles(&self.roles).0.build(); + let map = EditMember::default().roles(&self.roles).0; match rest::edit_member(guild_id.0, self.user.read().unwrap().id.0, &map) { Ok(()) => Ok(()), @@ -105,15 +129,6 @@ impl Member { roles.iter().find(|r| r.colour.0 != default.0).map(|r| r.colour) } - #[doc(hidden)] - pub fn decode_guild(guild_id: GuildId, mut value: Value) -> Result<Member> { - if let Some(v) = value.as_object_mut() { - v.insert("guild_id".to_owned(), Value::U64(guild_id.0)); - } - - Self::decode(value) - } - /// Calculates the member's display name. /// /// The nickname takes priority over the member's username if it exists. @@ -141,7 +156,7 @@ impl Member { #[cfg(feature="cache")] pub fn edit<F: FnOnce(EditMember) -> EditMember>(&self, f: F) -> Result<()> { let guild_id = self.find_guild()?; - let map = f(EditMember::default()).0.build(); + let map = f(EditMember::default()).0; rest::edit_member(guild_id.0, self.user.read().unwrap().id.0, &map) } @@ -210,7 +225,7 @@ impl Member { let guild_id = self.find_guild()?; self.roles.retain(|r| !role_ids.contains(r)); - let map = EditMember::default().roles(&self.roles).0.build(); + let map = EditMember::default().roles(&self.roles).0; match rest::edit_member(guild_id.0, self.user.read().unwrap().id.0, &map) { Ok(()) => Ok(()), diff --git a/src/model/guild/mod.rs b/src/model/guild/mod.rs index 8b21ac7..7299f84 100644 --- a/src/model/guild/mod.rs +++ b/src/model/guild/mod.rs @@ -1,13 +1,5 @@ -use serde_json::builder::ObjectBuilder; -use ::client::rest; -use ::constants::LARGE_THRESHOLD; -use ::model::*; -use ::utils::builder::{EditGuild, EditMember, EditRole}; - -#[cfg(feature="cache")] -use ::client::CACHE; - mod emoji; +mod feature; mod guild_id; mod integration; mod member; @@ -15,12 +7,117 @@ mod partial_guild; mod role; pub use self::emoji::*; +pub use self::feature::*; pub use self::guild_id::*; pub use self::integration::*; pub use self::member::*; pub use self::partial_guild::*; pub use self::role::*; +use serde::de::Error as DeError; +use serde_json; +use super::utils::*; +use ::client::rest; +use ::constants::LARGE_THRESHOLD; +use ::model::*; +use ::utils::builder::{EditGuild, EditMember, EditRole}; + +#[cfg(feature="cache")] +use ::client::CACHE; + +/// A representation of a banning of a user. +#[derive(Clone, Debug, Deserialize)] +pub struct Ban { + /// The reason given for this ban. + /// + /// **Note**: Until the Audit Log feature is completed by Discord, this will + /// always be `None`. + pub reason: Option<String>, + /// The user that was banned. + pub user: User, +} + +/// Information about a Discord guild, such as channels, emojis, etc. +#[derive(Clone, Debug)] +pub struct Guild { + /// Id of a voice channel that's considered the AFK channel. + pub afk_channel_id: Option<ChannelId>, + /// The amount of seconds a user can not show any activity in a voice + /// channel before being moved to an AFK channel -- if one exists. + pub afk_timeout: u64, + /// All voice and text channels contained within a guild. + /// + /// This contains all channels regardless of permissions (i.e. the ability + /// of the bot to read from or connect to them). + pub channels: HashMap<ChannelId, Arc<RwLock<GuildChannel>>>, + /// Indicator of whether notifications for all messages are enabled by + /// default in the guild. + pub default_message_notifications: u64, + /// All of the guild's custom emojis. + pub emojis: HashMap<EmojiId, Emoji>, + /// VIP features enabled for the guild. Can be obtained through the + /// [Discord Partnership] website. + /// + /// [Discord Partnership]: https://discordapp.com/partners + pub features: Vec<Feature>, + /// The hash of the icon used by the guild. + /// + /// In the client, this appears on the guild list on the left-hand side. + pub icon: Option<String>, + /// The unique Id identifying the guild. + /// + /// This is equivilant to the Id of the default role (`@everyone`) and also + /// that of the default channel (typically `#general`). + pub id: GuildId, + /// The date that the current user joined the guild. + pub joined_at: String, + /// Indicator of whether the guild is considered "large" by Discord. + pub large: bool, + /// The number of members in the guild. + pub member_count: u64, + /// Users who are members of the guild. + /// + /// Members might not all be available when the [`ReadyEvent`] is received + /// if the [`member_count`] is greater than the `LARGE_THRESHOLD` set by + /// the library. + /// + /// [`ReadyEvent`]: events/struct.ReadyEvent.html + pub members: HashMap<UserId, Member>, + /// Indicator of whether the guild requires multi-factor authentication for + /// [`Role`]s or [`User`]s with moderation permissions. + /// + /// [`Role`]: struct.Role.html + /// [`User`]: struct.User.html + pub mfa_level: u64, + /// The name of the guild. + pub name: String, + /// The Id of the [`User`] who owns the guild. + /// + /// [`User`]: struct.User.html + pub owner_id: UserId, + /// A mapping of [`User`]s' Ids to their current presences. + /// + /// [`User`]: struct.User.html + pub presences: HashMap<UserId, Presence>, + /// The region that the voice servers that the guild uses are located in. + pub region: String, + /// A mapping of the guild's roles. + pub roles: HashMap<RoleId, Role>, + /// An identifying hash of the guild's splash icon. + /// + /// If the [`InviteSplash`] feature is enabled, this can be used to generate + /// a URL to a splash image. + /// + /// [`InviteSplash`]: enum.Feature.html#variant.InviteSplash + pub splash: Option<String>, + /// Indicator of the current verification level of the guild. + pub verification_level: VerificationLevel, + /// A mapping of of [`User`]s to their current voice state. + /// + /// [`User`]: struct.User.html + pub voice_states: HashMap<UserId, VoiceState>, +} + impl Guild { #[cfg(feature="cache")] fn has_perms(&self, mut permissions: Permissions) -> Result<bool> { @@ -133,11 +230,11 @@ impl Guild { /// [US West region]: enum.Region.html#variant.UsWest /// [whitelist]: https://discordapp.com/developers/docs/resources/guild#create-guild pub fn create(name: &str, region: Region, icon: Option<&str>) -> Result<PartialGuild> { - let map = ObjectBuilder::new() - .insert("icon", icon) - .insert("name", name) - .insert("region", region.name()) - .build(); + let map = json!({ + "icon": icon, + "name": name, + "region": region.name(), + }); rest::create_guild(&map) } @@ -249,50 +346,6 @@ impl Guild { self.id.create_role(f) } - #[doc(hidden)] - pub fn decode(value: Value) -> Result<Guild> { - let mut map = into_map(value)?; - - let id = remove(&mut map, "id").and_then(GuildId::decode)?; - - let channels = { - let mut channels = HashMap::new(); - - let vals = decode_array(remove(&mut map, "channels")?, - |v| GuildChannel::decode_guild(v, id))?; - - for channel in vals { - channels.insert(channel.id, Arc::new(RwLock::new(channel))); - } - - channels - }; - - Ok(Guild { - afk_channel_id: opt(&mut map, "afk_channel_id", ChannelId::decode)?, - afk_timeout: req!(remove(&mut map, "afk_timeout")?.as_u64()), - channels: channels, - default_message_notifications: req!(remove(&mut map, "default_message_notifications")?.as_u64()), - emojis: remove(&mut map, "emojis").and_then(decode_emojis)?, - features: remove(&mut map, "features").and_then(|v| decode_array(v, Feature::decode_str))?, - icon: opt(&mut map, "icon", into_string)?, - id: id, - joined_at: remove(&mut map, "joined_at").and_then(into_string)?, - large: req!(remove(&mut map, "large")?.as_bool()), - member_count: req!(remove(&mut map, "member_count")?.as_u64()), - members: remove(&mut map, "members").and_then(decode_members)?, - mfa_level: req!(remove(&mut map, "mfa_level")?.as_u64()), - name: remove(&mut map, "name").and_then(into_string)?, - owner_id: remove(&mut map, "owner_id").and_then(UserId::decode)?, - presences: remove(&mut map, "presences").and_then(decode_presences)?, - region: remove(&mut map, "region").and_then(into_string)?, - roles: remove(&mut map, "roles").and_then(decode_roles)?, - splash: opt(&mut map, "splash", into_string)?, - verification_level: remove(&mut map, "verification_level").and_then(VerificationLevel::decode)?, - voice_states: remove(&mut map, "voice_states").and_then(decode_voice_states)?, - }) - } - /// Deletes the current guild if the current user is the owner of the /// guild. /// @@ -904,6 +957,172 @@ impl Guild { } } +impl Deserialize for Guild { + fn deserialize<D: Deserializer>(deserializer: D) -> StdResult<Self, D::Error> { + let mut map = JsonMap::deserialize(deserializer)?; + + let id = map.get("id") + .and_then(|x| x.as_str()) + .and_then(|x| x.parse::<u64>().ok()); + + if let Some(guild_id) = id { + if let Some(array) = map.get_mut("channels").and_then(|x| x.as_array_mut()) { + + for value in array { + if let Some(channel) = value.as_object_mut() { + channel.insert("guild_id".to_owned(), Value::Number(Number::from(guild_id))); + } + } + } + } + + let afk_channel_id = match map.remove("afk_channel_id") { + Some(v) => serde_json::from_value::<Option<ChannelId>>(v).map_err(DeError::custom)?, + None => None, + }; + let afk_timeout = map.remove("afk_timeout") + .ok_or_else(|| DeError::custom("expected guild afk_timeout")) + .and_then(u64::deserialize) + .map_err(DeError::custom)?; + let channels = map.remove("channels") + .ok_or_else(|| DeError::custom("expected guild channels")) + .and_then(deserialize_guild_channels) + .map_err(DeError::custom)?; + let default_message_notifications = map.remove("default_message_notifications") + .ok_or_else(|| DeError::custom("expected guild default_message_notifications")) + .and_then(u64::deserialize) + .map_err(DeError::custom)?; + let emojis = map.remove("emojis") + .ok_or_else(|| DeError::custom("expected guild emojis")) + .and_then(deserialize_emojis) + .map_err(DeError::custom)?; + let features = map.remove("features") + .ok_or_else(|| DeError::custom("expected guild features")) + .and_then(serde_json::from_value::<Vec<Feature>>) + .map_err(DeError::custom)?; + let icon = match map.remove("icon") { + Some(v) => Option::<String>::deserialize(v).map_err(DeError::custom)?, + None => None, + }; + let id = map.remove("id") + .ok_or_else(|| DeError::custom("expected guild id")) + .and_then(GuildId::deserialize) + .map_err(DeError::custom)?; + let joined_at = map.remove("joined_at") + .ok_or_else(|| DeError::custom("expected guild joined_at")) + .and_then(String::deserialize) + .map_err(DeError::custom)?; + let large = map.remove("large") + .ok_or_else(|| DeError::custom("expected guild large")) + .and_then(bool::deserialize) + .map_err(DeError::custom)?; + let member_count = map.remove("member_count") + .ok_or_else(|| DeError::custom("expected guild member_count")) + .and_then(u64::deserialize) + .map_err(DeError::custom)?; + let members = map.remove("members") + .ok_or_else(|| DeError::custom("expected guild members")) + .and_then(deserialize_members) + .map_err(DeError::custom)?; + let mfa_level = map.remove("mfa_level") + .ok_or_else(|| DeError::custom("expected guild mfa_level")) + .and_then(u64::deserialize) + .map_err(DeError::custom)?; + let name = map.remove("name") + .ok_or_else(|| DeError::custom("expected guild name")) + .and_then(String::deserialize) + .map_err(DeError::custom)?; + let owner_id = map.remove("owner_id") + .ok_or_else(|| DeError::custom("expected guild owner_id")) + .and_then(UserId::deserialize) + .map_err(DeError::custom)?; + let presences = map.remove("presences") + .ok_or_else(|| DeError::custom("expected guild presences")) + .and_then(deserialize_presences) + .map_err(DeError::custom)?; + let region = map.remove("region") + .ok_or_else(|| DeError::custom("expected guild region")) + .and_then(String::deserialize) + .map_err(DeError::custom)?; + let roles = map.remove("roles") + .ok_or_else(|| DeError::custom("expected guild roles")) + .and_then(deserialize_roles) + .map_err(DeError::custom)?; + let splash = match map.remove("splash") { + Some(v) => Option::<String>::deserialize(v).map_err(DeError::custom)?, + None => None, + }; + let verification_level = map.remove("verification_level") + .ok_or_else(|| DeError::custom("expected guild verification_level")) + .and_then(VerificationLevel::deserialize) + .map_err(DeError::custom)?; + let voice_states = map.remove("voice_states") + .ok_or_else(|| DeError::custom("expected guild voice_states")) + .and_then(deserialize_voice_states) + .map_err(DeError::custom)?; + + Ok(Self { + afk_channel_id: afk_channel_id, + afk_timeout: afk_timeout, + channels: channels, + default_message_notifications: default_message_notifications, + emojis: emojis, + features: features, + icon: icon, + id: id, + joined_at: joined_at, + large: large, + member_count: member_count, + members: members, + mfa_level: mfa_level, + name: name, + owner_id: owner_id, + presences: presences, + region: region, + roles: roles, + splash: splash, + verification_level: verification_level, + voice_states: voice_states, + }) + } +} + +/// Information relating to a guild's widget embed. +#[derive(Clone, Debug, Deserialize)] +pub struct GuildEmbed { + /// The Id of the channel to show the embed for. + pub channel_id: ChannelId, + /// Whether the widget embed is enabled. + pub enabled: bool, +} + +/// Representation of the number of members that would be pruned by a guild +/// prune operation. +#[derive(Clone, Copy, Debug, Deserialize)] +pub struct GuildPrune { + /// The number of members that would be pruned by the operation. + pub pruned: u64, +} + +/// Basic information about a guild. +#[derive(Clone, Debug, Deserialize)] +pub struct GuildInfo { + /// The unique Id of the guild. + /// + /// Can be used to calculate creation date. + pub id: GuildId, + /// The hash of the icon of the guild. + /// + /// This can be used to generate a URL to the guild's icon image. + pub icon: Option<String>, + /// The name of the guild. + pub name: String, + /// Indicator of whether the current user is the owner. + pub owner: bool, + /// The permissions that the current user has. + pub permissions: Permissions, +} + impl GuildInfo { /// Returns the formatted URL of the guild's icon, if the guild has an icon. pub fn icon_url(&self) -> Option<String> { @@ -938,46 +1157,65 @@ impl InviteGuild { } } -impl PossibleGuild<Guild> { - #[doc(hidden)] - pub fn decode(value: Value) -> Result<Self> { - let mut value = into_map(value)?; - if remove(&mut value, "unavailable").ok().and_then(|v| v.as_bool()).unwrap_or(false) { - remove(&mut value, "id").and_then(GuildId::decode).map(PossibleGuild::Offline) - } else { - Guild::decode(Value::Object(value)).map(PossibleGuild::Online) - } - } +/// Data for an unavailable guild. +#[derive(Clone, Copy, Debug, Deserialize)] +pub struct GuildUnavailable { + /// The Id of the [`Guild`] that is unavailable. + /// + /// [`Guild`]: struct.Guild.html + pub id: GuildId, + /// Indicator of whether the guild is unavailable. + /// + /// This should always be `true`. + pub unavailable: bool, +} +#[allow(large_enum_variant)] +#[derive(Clone, Debug, Deserialize)] +#[serde(untagged)] +pub enum GuildStatus { + OnlinePartialGuild(PartialGuild), + OnlineGuild(Guild), + Offline(GuildUnavailable), +} + +impl GuildStatus { /// Retrieves the Id of the inner [`Guild`]. /// /// [`Guild`]: struct.Guild.html pub fn id(&self) -> GuildId { match *self { - PossibleGuild::Offline(guild_id) => guild_id, - PossibleGuild::Online(ref live_guild) => live_guild.id, + GuildStatus::Offline(offline) => offline.id, + GuildStatus::OnlineGuild(ref guild) => guild.id, + GuildStatus::OnlinePartialGuild(ref partial_guild) => partial_guild.id, } } } -impl PossibleGuild<PartialGuild> { - #[doc(hidden)] - pub fn decode(value: Value) -> Result<Self> { - let mut value = into_map(value)?; - if remove(&mut value, "unavailable").ok().and_then(|v| v.as_bool()).unwrap_or(false) { - remove(&mut value, "id").and_then(GuildId::decode).map(PossibleGuild::Offline) - } else { - PartialGuild::decode(Value::Object(value)).map(PossibleGuild::Online) - } +enum_number!( + #[doc="The level to set as criteria prior to a user being able to send + messages in a [`Guild`]. + + [`Guild`]: struct.Guild.html"] + VerificationLevel { + /// Does not require any verification. + None = 0, + /// Low verification level. + Low = 1, + /// Medium verification level. + Medium = 2, + /// High verification level. + High = 3, } +); - /// Retrieves the Id of the inner [`Guild`]. - /// - /// [`Guild`]: struct.Guild.html - pub fn id(&self) -> GuildId { +impl VerificationLevel { + pub fn num(&self) -> u64 { match *self { - PossibleGuild::Offline(id) => id, - PossibleGuild::Online(ref live_guild) => live_guild.id, + VerificationLevel::None => 0, + VerificationLevel::Low => 1, + VerificationLevel::Medium => 2, + VerificationLevel::High => 3, } } } diff --git a/src/model/guild/partial_guild.rs b/src/model/guild/partial_guild.rs index f5ab502..947de50 100644 --- a/src/model/guild/partial_guild.rs +++ b/src/model/guild/partial_guild.rs @@ -1,6 +1,30 @@ use ::model::*; use ::utils::builder::{EditGuild, EditMember, EditRole}; +/// Partial information about a [`Guild`]. This does not include information +/// like member data. +/// +/// [`Guild`]: struct.Guild.html +#[derive(Clone, Debug, Deserialize)] +pub struct PartialGuild { + pub id: GuildId, + pub afk_channel_id: Option<ChannelId>, + pub afk_timeout: u64, + pub default_message_notifications: u64, + pub embed_channel_id: Option<ChannelId>, + pub embed_enabled: bool, + pub emojis: HashMap<EmojiId, Emoji>, + pub features: Vec<Feature>, + pub icon: Option<String>, + pub mfa_level: u64, + pub name: String, + pub owner_id: UserId, + pub region: String, + pub roles: HashMap<RoleId, Role>, + pub splash: Option<String>, + pub verification_level: VerificationLevel, +} + impl PartialGuild { /// Ban a [`User`] from the guild. All messages by the /// user within the last given number of days given will be deleted. This diff --git a/src/model/guild/role.rs b/src/model/guild/role.rs index 77d84e1..d4e1da8 100644 --- a/src/model/guild/role.rs +++ b/src/model/guild/role.rs @@ -9,6 +9,52 @@ use ::internal::prelude::*; #[cfg(feature="cache")] use ::utils::builder::EditRole; +/// Information about a role within a guild. A role represents a set of +/// permissions, and can be attached to one or multiple users. A role has +/// various miscellaneous configurations, such as being assigned a colour. Roles +/// are unique per guild and do not cross over to other guilds in any way, and +/// can have channel-specific permission overrides in addition to guild-level +/// permissions. +#[derive(Clone, Debug, Deserialize)] +pub struct Role { + /// The Id of the role. Can be used to calculate the role's creation date. + pub id: RoleId, + /// The colour of the role. This is an ergonomic representation of the inner + /// value. + #[serde(rename="color")] + pub colour: Colour, + /// Indicator of whether the role is pinned above lesser roles. + /// + /// In the client, this causes [`Member`]s in the role to be seen above + /// those in roles with a lower [`position`]. + /// + /// [`Member`]: struct.Member.html + /// [`position`]: #structfield.position + pub hoist: bool, + /// Indicator of whether the role is managed by an integration service. + pub managed: bool, + /// Indicator of whether the role can be mentioned, similar to mentioning a + /// specific member or `@everyone`. + /// + /// Only members of the role will be notified if a role is mentioned with + /// this set to `true`. + #[serde(default)] + pub mentionable: bool, + /// The name of the role. + pub name: String, + /// A set of permissions that the role has been assigned. + /// + /// See the [`permissions`] module for more information. + /// + /// [`permissions`]: permissions/index.html + pub permissions: Permissions, + /// The role's position in the position list. Roles are considered higher in + /// hierarchy if their position is higher. + /// + /// The `@everyone` role is usually either `-1` or `0`. + pub position: i64, +} + impl Role { /// Deletes the role. /// |