diff options
| author | acdenisSK <[email protected]> | 2017-07-27 06:42:48 +0200 |
|---|---|---|
| committer | acdenisSK <[email protected]> | 2017-07-27 07:30:23 +0200 |
| commit | 550030264952f0e0043b63f4582bb817ef8bbf37 (patch) | |
| tree | b921e2f78fd603a5ca671623083a32806fd16090 /src | |
| parent | Use a consistent indentation style (diff) | |
| download | serenity-550030264952f0e0043b63f4582bb817ef8bbf37.tar.xz serenity-550030264952f0e0043b63f4582bb817ef8bbf37.zip | |
rustfmt
Diffstat (limited to 'src')
78 files changed, 2674 insertions, 2701 deletions
diff --git a/src/builder/create_embed.rs b/src/builder/create_embed.rs index da196ec..c0dead6 100644 --- a/src/builder/create_embed.rs +++ b/src/builder/create_embed.rs @@ -19,11 +19,11 @@ use chrono::{DateTime, TimeZone}; use serde_json::Value; use std::default::Default; use std::fmt::Display; -use ::internal::prelude::*; -use ::model::Embed; +use internal::prelude::*; +use model::Embed; -#[cfg(feature="utils")] -use ::utils::Colour; +#[cfg(feature = "utils")] +use utils::Colour; /// A builder to create a fake [`Embed`] object, for use with the /// [`ChannelId::send_message`] and [`ExecuteWebhook::embeds`] methods. @@ -47,7 +47,8 @@ impl CreateEmbed { /// /// [`CreateEmbedAuthor`]: struct.CreateEmbedAuthor.html pub fn author<F>(mut self, f: F) -> Self - where F: FnOnce(CreateEmbedAuthor) -> CreateEmbedAuthor { + where + F: FnOnce(CreateEmbedAuthor) -> CreateEmbedAuthor, { let author = f(CreateEmbedAuthor::default()).0; self.0.insert("author".to_owned(), Value::Object(author)); @@ -60,16 +61,15 @@ impl CreateEmbed { /// This is an alias of [`colour`]. /// /// [`colour`]: #method.colour - #[cfg(feature="utils")] + #[cfg(feature = "utils")] #[inline] - pub fn color<C: Into<Colour>>(self, colour: C) -> Self { - self.colour(colour.into()) - } + pub fn color<C: Into<Colour>>(self, colour: C) -> Self { self.colour(colour.into()) } /// Set the colour of the left-hand side of the embed. - #[cfg(feature="utils")] + #[cfg(feature = "utils")] pub fn colour<C: Into<Colour>>(mut self, colour: C) -> Self { - self.0.insert("color".to_owned(), Value::Number(Number::from(colour.into().0 as u64))); + self.0.insert("color".to_owned(), + Value::Number(Number::from(colour.into().0 as u64))); CreateEmbed(self.0) } @@ -79,16 +79,15 @@ impl CreateEmbed { /// This is an alias of [`colour`]. /// /// [`colour`]: #method.colour - #[cfg(not(feature="utils"))] + #[cfg(not(feature = "utils"))] #[inline] - pub fn color(self, colour: u32) -> Self { - self.colour(colour) - } + pub fn color(self, colour: u32) -> Self { self.colour(colour) } /// Set the colour of the left-hand side of the embed. - #[cfg(not(feature="utils"))] + #[cfg(not(feature = "utils"))] pub fn colour(mut self, colour: u32) -> Self { - self.0.insert("color".to_owned(), Value::Number(Number::from(colour))); + self.0 + .insert("color".to_owned(), Value::Number(Number::from(colour))); CreateEmbed(self.0) } @@ -97,7 +96,8 @@ impl CreateEmbed { /// /// **Note**: This can't be longer than 2048 characters. pub fn description(mut self, description: &str) -> Self { - self.0.insert("description".to_owned(), Value::String(description.to_owned())); + self.0.insert("description".to_owned(), + Value::String(description.to_owned())); CreateEmbed(self.0) } @@ -113,7 +113,8 @@ impl CreateEmbed { /// /// [`CreateEmbedField`]: struct.CreateEmbedField.html pub fn field<F>(mut self, f: F) -> Self - where F: FnOnce(CreateEmbedField) -> CreateEmbedField { + where + F: FnOnce(CreateEmbedField) -> CreateEmbedField, { let field = f(CreateEmbedField::default()).0; { @@ -141,9 +142,12 @@ impl CreateEmbed { /// Adds multiple fields at once. pub fn fields(mut self, fields: Vec<CreateEmbedField>) -> Self { - let fields = fields.into_iter().map(|m| Value::Object(m.0)).collect::<Vec<Value>>(); - - { + let fields = fields + .into_iter() + .map(|m| Value::Object(m.0)) + .collect::<Vec<Value>>(); + + { let key = "fields".to_owned(); let entry = self.0.remove(&key).unwrap_or_else(|| Value::Array(vec![])); @@ -166,7 +170,8 @@ impl CreateEmbed { /// /// [`CreateEmbedFooter`]: struct.CreateEmbedFooter.html pub fn footer<F>(mut self, f: F) -> Self - where F: FnOnce(CreateEmbedFooter) -> CreateEmbedFooter { + where + F: FnOnce(CreateEmbedFooter) -> CreateEmbedFooter, { let footer = f(CreateEmbedFooter::default()).0; self.0.insert("footer".to_owned(), Value::Object(footer)); @@ -215,7 +220,7 @@ impl CreateEmbed { /// ```rust,no_run /// # use serenity::prelude::*; /// # use serenity::model::*; - /// # + /// # /// struct Handler; /// impl EventHandler for Handler { /// fn on_message(&self, _: Context, msg: Message) { @@ -276,27 +281,30 @@ impl CreateEmbed { /// let mut client = Client::new("token", Handler); client.start().unwrap(); /// ``` pub fn timestamp<T: Into<Timestamp>>(mut self, timestamp: T) -> Self { - self.0.insert("timestamp".to_owned(), Value::String(timestamp.into().ts)); + self.0 + .insert("timestamp".to_owned(), Value::String(timestamp.into().ts)); CreateEmbed(self.0) } /// Set the title of the embed. pub fn title(mut self, title: &str) -> Self { - self.0.insert("title".to_owned(), Value::String(title.to_owned())); + self.0 + .insert("title".to_owned(), Value::String(title.to_owned())); CreateEmbed(self.0) } /// Set the URL to direct to when clicking on the title. pub fn url(mut self, url: &str) -> Self { - self.0.insert("url".to_owned(), Value::String(url.to_owned())); + self.0 + .insert("url".to_owned(), Value::String(url.to_owned())); CreateEmbed(self.0) } /// Same as calling [`image`] with "attachment://filename.(jpg, png)". - /// + /// /// Note however, you have to be sure you set an attachment (with [`ChannelId::send_files`]) /// with the provided filename. Or else this won't work. /// @@ -321,8 +329,7 @@ impl From<Embed> for CreateEmbed { /// /// Some values - such as Proxy URLs - are not preserved. fn from(embed: Embed) -> CreateEmbed { - let mut b = CreateEmbed::default() - .colour(embed.colour); + let mut b = CreateEmbed::default().colour(embed.colour); if let Some(author) = embed.author { b = b.author(move |mut a| { @@ -345,10 +352,7 @@ impl From<Embed> for CreateEmbed { } for field in embed.fields { - b = b.field(move |f| f - .inline(field.inline) - .name(&field.name) - .value(&field.value)); + b = b.field(move |f| f.inline(field.inline).name(&field.name).value(&field.value)); } if let Some(image) = embed.image { @@ -389,21 +393,24 @@ pub struct CreateEmbedAuthor(pub Map<String, Value>); impl CreateEmbedAuthor { /// Set the URL of the author's icon. pub fn icon_url(mut self, icon_url: &str) -> Self { - self.0.insert("icon_url".to_owned(), Value::String(icon_url.to_owned())); + self.0 + .insert("icon_url".to_owned(), Value::String(icon_url.to_owned())); self } /// Set the author's name. pub fn name(mut self, name: &str) -> Self { - self.0.insert("name".to_owned(), Value::String(name.to_owned())); + self.0 + .insert("name".to_owned(), Value::String(name.to_owned())); self } /// Set the author's URL. pub fn url(mut self, url: &str) -> Self { - self.0.insert("url".to_owned(), Value::String(url.to_owned())); + self.0 + .insert("url".to_owned(), Value::String(url.to_owned())); self } @@ -430,14 +437,16 @@ impl CreateEmbedField { /// Set the field's name. It can't be longer than 256 characters. pub fn name(mut self, name: &str) -> Self { - self.0.insert("name".to_owned(), Value::String(name.to_owned())); + self.0 + .insert("name".to_owned(), Value::String(name.to_owned())); self } /// Set the field's value. It can't be longer than 1024 characters. pub fn value(mut self, value: &str) -> Self { - self.0.insert("value".to_owned(), Value::String(value.to_owned())); + self.0 + .insert("value".to_owned(), Value::String(value.to_owned())); self } @@ -467,14 +476,16 @@ pub struct CreateEmbedFooter(pub Map<String, Value>); impl CreateEmbedFooter { /// Set the icon URL's value. This only supports HTTP(S). pub fn icon_url(mut self, icon_url: &str) -> Self { - self.0.insert("icon_url".to_owned(), Value::String(icon_url.to_owned())); + self.0 + .insert("icon_url".to_owned(), Value::String(icon_url.to_owned())); self } /// Set the footer's text. pub fn text(mut self, text: &str) -> Self { - self.0.insert("text".to_owned(), Value::String(text.to_owned())); + self.0 + .insert("text".to_owned(), Value::String(text.to_owned())); self } @@ -501,7 +512,9 @@ impl<'a> From<&'a str> for Timestamp { } } -impl<'a, Tz: TimeZone> From<&'a DateTime<Tz>> for Timestamp where Tz::Offset: Display { +impl<'a, Tz: TimeZone> From<&'a DateTime<Tz>> for Timestamp +where + Tz::Offset: Display, { fn from(dt: &'a DateTime<Tz>) -> Self { Timestamp { ts: dt.to_rfc3339(), diff --git a/src/builder/create_invite.rs b/src/builder/create_invite.rs index 8253205..58893fc 100644 --- a/src/builder/create_invite.rs +++ b/src/builder/create_invite.rs @@ -1,6 +1,6 @@ use serde_json::Value; use std::default::Default; -use ::internal::prelude::*; +use internal::prelude::*; /// A builder to create a [`RichInvite`] for use via [`GuildChannel::create_invite`]. /// @@ -14,9 +14,9 @@ use ::internal::prelude::*; /// ```rust,no_run /// # use serenity::prelude::*; /// # use serenity::model::*; -/// +/// /// struct Handler; -/// +/// /// impl EventHandler for Handler { /// fn on_message(&self, _: Context, msg: Message) { /// use serenity::client::CACHE; @@ -49,8 +49,8 @@ use ::internal::prelude::*; /// /// let content = format!("Here's your invite: {}", invite.url()); /// let _ = msg.channel_id.say(&content); -/// } -/// } +/// } +/// } /// } /// let mut client = Client::new("token", Handler); client.start().unwrap(); /// ``` @@ -89,7 +89,8 @@ impl CreateInvite { /// # } /// ``` pub fn max_age(mut self, max_age: u64) -> Self { - self.0.insert("max_age".to_owned(), Value::Number(Number::from(max_age))); + self.0 + .insert("max_age".to_owned(), Value::Number(Number::from(max_age))); self } @@ -122,7 +123,8 @@ impl CreateInvite { /// # } /// ``` pub fn max_uses(mut self, max_uses: u64) -> Self { - self.0.insert("max_uses".to_owned(), Value::Number(Number::from(max_uses))); + self.0 + .insert("max_uses".to_owned(), Value::Number(Number::from(max_uses))); self } @@ -153,7 +155,8 @@ impl CreateInvite { /// # } /// ``` pub fn temporary(mut self, temporary: bool) -> Self { - self.0.insert("temporary".to_owned(), Value::Bool(temporary)); + self.0 + .insert("temporary".to_owned(), Value::Bool(temporary)); self } diff --git a/src/builder/create_message.rs b/src/builder/create_message.rs index e9e8bf5..c5a3cc3 100644 --- a/src/builder/create_message.rs +++ b/src/builder/create_message.rs @@ -1,6 +1,6 @@ use super::CreateEmbed; -use ::model::ReactionType; -use ::internal::prelude::*; +use model::ReactionType; +use internal::prelude::*; /// A builder to specify the contents of an [`http::send_message`] request, /// primarily meant for use through [`ChannelId::send_message`]. @@ -45,14 +45,16 @@ impl CreateMessage { /// /// **Note**: Message contents must be under 2000 unicode code points. pub fn content(mut self, content: &str) -> Self { - self.0.insert("content".to_owned(), Value::String(content.to_owned())); + self.0 + .insert("content".to_owned(), Value::String(content.to_owned())); CreateMessage(self.0, self.1) } /// Set an embed for the message. pub fn embed<F>(mut self, f: F) -> Self - where F: FnOnce(CreateEmbed) -> CreateEmbed { + where + F: FnOnce(CreateEmbed) -> CreateEmbed, { let embed = Value::Object(f(CreateEmbed::default()).0); self.0.insert("embed".to_owned(), embed); diff --git a/src/builder/edit_channel.rs b/src/builder/edit_channel.rs index 9d859c7..5537b48 100644 --- a/src/builder/edit_channel.rs +++ b/src/builder/edit_channel.rs @@ -1,4 +1,4 @@ -use ::internal::prelude::*; +use internal::prelude::*; /// A builder to edit a [`GuildChannel`] for use via [`GuildChannel::edit`] /// @@ -27,7 +27,8 @@ impl EditChannel { /// /// [voice]: ../model/enum.ChannelType.html#variant.Voice pub fn bitrate(mut self, bitrate: u64) -> Self { - self.0.insert("bitrate".to_owned(), Value::Number(Number::from(bitrate))); + self.0 + .insert("bitrate".to_owned(), Value::Number(Number::from(bitrate))); self } @@ -36,14 +37,16 @@ impl EditChannel { /// /// Must be between 2 and 100 characters long. pub fn name(mut self, name: &str) -> Self { - self.0.insert("name".to_owned(), Value::String(name.to_owned())); + self.0 + .insert("name".to_owned(), Value::String(name.to_owned())); self } /// The position of the channel in the channel list. pub fn position(mut self, position: u64) -> Self { - self.0.insert("position".to_owned(), Value::Number(Number::from(position))); + self.0 + .insert("position".to_owned(), Value::Number(Number::from(position))); self } @@ -56,7 +59,8 @@ impl EditChannel { /// /// [text]: ../model/enum.ChannelType.html#variant.Text pub fn topic(mut self, topic: &str) -> Self { - self.0.insert("topic".to_owned(), Value::String(topic.to_owned())); + self.0 + .insert("topic".to_owned(), Value::String(topic.to_owned())); self } @@ -67,7 +71,8 @@ impl EditChannel { /// /// [voice]: ../model/enum.ChannelType.html#variant.Voice pub fn user_limit(mut self, user_limit: u64) -> Self { - self.0.insert("user_limit".to_owned(), Value::Number(Number::from(user_limit))); + self.0.insert("user_limit".to_owned(), + Value::Number(Number::from(user_limit))); self } diff --git a/src/builder/edit_guild.rs b/src/builder/edit_guild.rs index e74e54e..67b0003 100644 --- a/src/builder/edit_guild.rs +++ b/src/builder/edit_guild.rs @@ -1,5 +1,5 @@ -use ::internal::prelude::*; -use ::model::{ChannelId, Region, UserId, VerificationLevel}; +use internal::prelude::*; +use model::{ChannelId, Region, UserId, VerificationLevel}; /// A builder to optionally edit certain fields of a [`Guild`]. This is meant /// for usage with [`Guild::edit`]. @@ -36,7 +36,8 @@ impl EditGuild { /// /// [`afk_channel`]: #method.afk_channel pub fn afk_timeout(mut self, timeout: u64) -> Self { - self.0.insert("afk_timeout".to_owned(), Value::Number(Number::from(timeout))); + self.0.insert("afk_timeout".to_owned(), + Value::Number(Number::from(timeout))); self } @@ -71,7 +72,8 @@ impl EditGuild { /// /// [`utils::read_image`]: ../utils/fn.read_image.html pub fn icon(mut self, icon: Option<&str>) -> Self { - self.0.insert("icon".to_owned(), icon.map_or_else(|| Value::Null, |x| Value::String(x.to_owned()))); + self.0.insert("icon".to_owned(), + icon.map_or_else(|| Value::Null, |x| Value::String(x.to_owned()))); self } @@ -80,7 +82,8 @@ impl EditGuild { /// /// **Note**: Must be between (and including) 2-100 chracters. pub fn name(mut self, name: &str) -> Self { - self.0.insert("name".to_owned(), Value::String(name.to_owned())); + self.0 + .insert("name".to_owned(), Value::String(name.to_owned())); self } @@ -89,7 +92,8 @@ impl EditGuild { /// /// **Note**: The current user must be the owner of the guild. pub fn owner<U: Into<UserId>>(mut self, user_id: U) -> Self { - self.0.insert("owner_id".to_owned(), Value::Number(Number::from(user_id.into().0))); + self.0.insert("owner_id".to_owned(), + Value::Number(Number::from(user_id.into().0))); self } @@ -121,7 +125,8 @@ impl EditGuild { /// /// [`Region::UsWest`]: ../model/enum.Region.html#variant.UsWest pub fn region(mut self, region: Region) -> Self { - self.0.insert("region".to_owned(), Value::String(region.name().to_owned())); + self.0 + .insert("region".to_owned(), Value::String(region.name().to_owned())); self } @@ -172,7 +177,8 @@ impl EditGuild { /// [`VerificationLevel`]: ../model/enum.VerificationLevel.html /// [`VerificationLevel::High`]: ../model/enum.VerificationLevel.html#variant.High pub fn verification_level<V>(mut self, verification_level: V) -> Self - where V: Into<VerificationLevel> { + where + V: Into<VerificationLevel>, { let num = Value::Number(Number::from(verification_level.into().num())); self.0.insert("verification_level".to_owned(), num); diff --git a/src/builder/edit_member.rs b/src/builder/edit_member.rs index 3fce146..a88ae17 100644 --- a/src/builder/edit_member.rs +++ b/src/builder/edit_member.rs @@ -1,5 +1,5 @@ -use ::model::{ChannelId, RoleId}; -use ::internal::prelude::*; +use model::{ChannelId, RoleId}; +use internal::prelude::*; /// A builder which edits the properties of a [`Member`], to be used in /// conjunction with [`Member::edit`]. @@ -39,7 +39,8 @@ impl EditMember { /// /// [Manage Nicknames]: ../model/permissions/constant.MANAGE_NICKNAMES.html pub fn nickname(mut self, nickname: &str) -> Self { - self.0.insert("nick".to_owned(), Value::String(nickname.to_owned())); + self.0 + .insert("nick".to_owned(), Value::String(nickname.to_owned())); self } @@ -50,7 +51,10 @@ impl EditMember { /// /// [Manage Roles]: ../model/permissions/constant.MANAGE_ROLES.html pub fn roles(mut self, roles: &[RoleId]) -> Self { - let role_ids = roles.iter().map(|x| Value::Number(Number::from(x.0))).collect(); + let role_ids = roles + .iter() + .map(|x| Value::Number(Number::from(x.0))) + .collect(); self.0.insert("roles".to_owned(), Value::Array(role_ids)); @@ -63,7 +67,8 @@ impl EditMember { /// /// [Move Members]: ../model/permissions/constant.MOVE_MEMBERS.html pub fn voice_channel<C: Into<ChannelId>>(mut self, channel_id: C) -> Self { - self.0.insert("channel_id".to_owned(), Value::Number(Number::from(channel_id.into().0))); + self.0.insert("channel_id".to_owned(), + Value::Number(Number::from(channel_id.into().0))); self } diff --git a/src/builder/edit_profile.rs b/src/builder/edit_profile.rs index 2b54f68..63daec3 100644 --- a/src/builder/edit_profile.rs +++ b/src/builder/edit_profile.rs @@ -1,4 +1,4 @@ -use ::internal::prelude::*; +use internal::prelude::*; /// A builder to edit the current user's settings, to be used in conjunction /// with [`CurrentUser::edit`]. @@ -61,7 +61,8 @@ impl EditProfile { /// /// [provided]: #method.password pub fn email(mut self, email: &str) -> Self { - self.0.insert("email".to_owned(), Value::String(email.to_owned())); + self.0 + .insert("email".to_owned(), Value::String(email.to_owned())); self } @@ -73,7 +74,8 @@ impl EditProfile { /// /// [provided]: #method.password pub fn new_password(mut self, new_password: &str) -> Self { - self.0.insert("new_password".to_owned(), Value::String(new_password.to_owned())); + self.0.insert("new_password".to_owned(), + Value::String(new_password.to_owned())); self } @@ -84,7 +86,8 @@ impl EditProfile { /// [modifying the password]: #method.new_password /// [modifying the associated email address]: #method.email pub fn password(mut self, password: &str) -> Self { - self.0.insert("password".to_owned(), Value::String(password.to_owned())); + self.0 + .insert("password".to_owned(), Value::String(password.to_owned())); self } @@ -96,7 +99,8 @@ impl EditProfile { /// If there are no available discriminators with the requested username, /// an error will occur. pub fn username(mut self, username: &str) -> Self { - self.0.insert("username".to_owned(), Value::String(username.to_owned())); + self.0 + .insert("username".to_owned(), Value::String(username.to_owned())); self } diff --git a/src/builder/edit_role.rs b/src/builder/edit_role.rs index 6be09fe..28aecac 100644 --- a/src/builder/edit_role.rs +++ b/src/builder/edit_role.rs @@ -1,6 +1,6 @@ use std::default::Default; -use ::internal::prelude::*; -use ::model::{Permissions, Role, permissions}; +use internal::prelude::*; +use model::{permissions, Permissions, Role}; /// A builer to create or edit a [`Role`] for use via a number of model methods. /// @@ -48,12 +48,13 @@ impl EditRole { pub fn new(role: &Role) -> Self { let mut map = Map::new(); - #[cfg(feature="utils")] + #[cfg(feature = "utils")] { - map.insert("color".to_owned(), Value::Number(Number::from(role.colour.0))); + map.insert("color".to_owned(), + Value::Number(Number::from(role.colour.0))); } - #[cfg(not(feature="utils"))] + #[cfg(not(feature = "utils"))] { map.insert("color".to_owned(), Value::Number(Number::from(role.colour))); } @@ -62,15 +63,18 @@ impl EditRole { map.insert("managed".to_owned(), Value::Bool(role.managed)); map.insert("mentionable".to_owned(), Value::Bool(role.mentionable)); map.insert("name".to_owned(), Value::String(role.name.clone())); - map.insert("permissions".to_owned(), Value::Number(Number::from(role.permissions.bits()))); - map.insert("position".to_owned(), Value::Number(Number::from(role.position))); + map.insert("permissions".to_owned(), + Value::Number(Number::from(role.permissions.bits()))); + map.insert("position".to_owned(), + Value::Number(Number::from(role.position))); EditRole(map) } /// Sets the colour of the role. pub fn colour(mut self, colour: u64) -> Self { - self.0.insert("color".to_owned(), Value::Number(Number::from(colour))); + self.0 + .insert("color".to_owned(), Value::Number(Number::from(colour))); self } @@ -85,21 +89,24 @@ impl EditRole { /// Whether or not to make the role mentionable, notifying its users. pub fn mentionable(mut self, mentionable: bool) -> Self { - self.0.insert("mentionable".to_owned(), Value::Bool(mentionable)); + self.0 + .insert("mentionable".to_owned(), Value::Bool(mentionable)); self } /// The name of the role to set. pub fn name(mut self, name: &str) -> Self { - self.0.insert("name".to_owned(), Value::String(name.to_owned())); + self.0 + .insert("name".to_owned(), Value::String(name.to_owned())); self } /// The set of permissions to assign the role. pub fn permissions(mut self, permissions: Permissions) -> Self { - self.0.insert("permissions".to_owned(), Value::Number(Number::from(permissions.bits()))); + self.0.insert("permissions".to_owned(), + Value::Number(Number::from(permissions.bits()))); self } @@ -107,7 +114,8 @@ impl EditRole { /// The position to assign the role in the role list. This correlates to the /// role's position in the user list. pub fn position(mut self, position: u8) -> Self { - self.0.insert("position".to_owned(), Value::Number(Number::from(position))); + self.0 + .insert("position".to_owned(), Value::Number(Number::from(position))); self } diff --git a/src/builder/execute_webhook.rs b/src/builder/execute_webhook.rs index e8b9042..9a0c9d9 100644 --- a/src/builder/execute_webhook.rs +++ b/src/builder/execute_webhook.rs @@ -1,6 +1,6 @@ use serde_json::Value; use std::default::Default; -use ::internal::prelude::*; +use internal::prelude::*; /// A builder to create the inner content of a [`Webhook`]'s execution. /// @@ -74,7 +74,8 @@ impl ExecuteWebhook { /// .content("Here's a webhook")); /// ``` pub fn avatar_url(mut self, avatar_url: &str) -> Self { - self.0.insert("avatar_url".to_owned(), Value::String(avatar_url.to_owned())); + self.0.insert("avatar_url".to_owned(), + Value::String(avatar_url.to_owned())); self } @@ -100,7 +101,8 @@ impl ExecuteWebhook { /// /// [`embeds`]: #method.embeds pub fn content(mut self, content: &str) -> Self { - self.0.insert("content".to_owned(), Value::String(content.to_owned())); + self.0 + .insert("content".to_owned(), Value::String(content.to_owned())); self } @@ -161,7 +163,8 @@ impl ExecuteWebhook { /// } /// ``` pub fn username(mut self, username: &str) -> Self { - self.0.insert("username".to_owned(), Value::String(username.to_owned())); + self.0 + .insert("username".to_owned(), Value::String(username.to_owned())); self } diff --git a/src/builder/get_messages.rs b/src/builder/get_messages.rs index 193adca..bca2f0e 100644 --- a/src/builder/get_messages.rs +++ b/src/builder/get_messages.rs @@ -1,5 +1,5 @@ use std::collections::BTreeMap; -use ::model::MessageId; +use model::MessageId; /// Builds a request for a request to the API to retrieve messages. /// @@ -85,11 +85,8 @@ impl GetMessages { /// limitation. If an amount larger than 100 is supplied, it will be /// reduced. pub fn limit(mut self, limit: u64) -> Self { - self.0.insert("limit".to_owned(), if limit > 100 { - 100 - } else { - limit - }); + self.0 + .insert("limit".to_owned(), if limit > 100 { 100 } else { limit }); self } @@ -97,7 +94,5 @@ impl GetMessages { /// This is a function that is here for completeness. You do not need to /// call this - except to clear previous calls to `after`, `around`, and /// `before` - as it is the default value. - pub fn most_recent(self) -> Self { - self - } + pub fn most_recent(self) -> Self { self } } diff --git a/src/builder/mod.rs b/src/builder/mod.rs index 3fc0f05..496d7e1 100644 --- a/src/builder/mod.rs +++ b/src/builder/mod.rs @@ -16,12 +16,7 @@ mod edit_role; mod execute_webhook; mod get_messages; -pub use self::create_embed::{ - CreateEmbed, - CreateEmbedAuthor, - CreateEmbedFooter, - CreateEmbedField, -}; +pub use self::create_embed::{CreateEmbed, CreateEmbedAuthor, CreateEmbedField, CreateEmbedFooter}; pub use self::create_invite::CreateInvite; pub use self::create_message::CreateMessage; pub use self::edit_channel::EditChannel; diff --git a/src/cache/mod.rs b/src/cache/mod.rs index a583e8c..d70d32d 100644 --- a/src/cache/mod.rs +++ b/src/cache/mod.rs @@ -47,8 +47,8 @@ use std::collections::{HashMap, HashSet}; use std::default::Default; use std::sync::{Arc, RwLock}; use std::mem; -use ::model::*; -use ::model::event::*; +use model::*; +use model::event::*; /// A cache of all events received over a [`Shard`], where storing at least /// some data from the event is possible. @@ -169,9 +169,9 @@ impl Cache { /// use serenity::client::CACHE; /// use std::thread; /// use std::time::Duration; - /// + /// /// struct Handler; - /// + /// /// impl EventHandler for Handler { /// fn on_ready(&self, ctx: Context, _: Ready) { /// // Wait some time for guilds to be received. @@ -186,7 +186,7 @@ impl Cache { /// thread::sleep(Duration::from_secs(5)); /// /// println!("{} unknown members", CACHE.read().unwrap().unknown_members()); - /// } + /// } /// } /// /// let mut client = Client::new("token", Handler); client.start().unwrap(); @@ -259,7 +259,7 @@ impl Cache { /// impl EventHandler for Handler { /// fn on_ready(&self, _: Context, _: Ready) { /// println!("Guilds in the Cache: {:?}", CACHE.read().unwrap().all_guilds()); - /// } + /// } /// } /// let mut client = Client::new("token", Handler); /// ``` @@ -366,7 +366,7 @@ impl Cache { /// use serenity::client::CACHE; /// /// struct Handler; - /// + /// /// impl EventHandler for Handler { /// fn on_message(&self, ctx: Context, message: Message) { /// let cache = CACHE.read().unwrap(); @@ -374,14 +374,15 @@ impl Cache { /// let channel = match cache.guild_channel(message.channel_id) { /// Some(channel) => channel, /// None => { - /// if let Err(why) = message.channel_id.say("Could not find guild's channel data") { + /// if let Err(why) = message.channel_id.say("Could not find guild's + /// channel data") { /// println!("Error sending message: {:?}", why); /// } /// /// return; /// }, /// }; - /// } + /// } /// } /// /// let mut client = Client::new("token", Handler); client.start().unwrap(); @@ -478,7 +479,9 @@ impl Cache { /// [`Guild`]: ../model/struct.Guild.html /// [`members`]: ../model/struct.Guild.html#structfield.members pub fn member<G, U>(&self, guild_id: G, user_id: U) -> Option<Member> - where G: Into<GuildId>, U: Into<UserId> { + where + G: Into<GuildId>, + U: Into<UserId>, { self.guilds .get(&guild_id.into()) .and_then(|guild| guild.write().unwrap().members.get(&user_id.into()).cloned()) @@ -513,8 +516,9 @@ impl Cache { /// # } /// ``` #[inline] - pub fn private_channel<C: Into<ChannelId>>(&self, channel_id: C) - -> Option<Arc<RwLock<PrivateChannel>>> { + pub fn private_channel<C: Into<ChannelId>>(&self, + channel_id: C) + -> Option<Arc<RwLock<PrivateChannel>>> { self.private_channels.get(&channel_id.into()).cloned() } @@ -549,7 +553,9 @@ impl Cache { /// # } /// ``` pub fn role<G, R>(&self, guild_id: G, role_id: R) -> Option<Role> - where G: Into<GuildId>, R: Into<RoleId> { + where + G: Into<GuildId>, + R: Into<RoleId>, { self.guilds .get(&guild_id.into()) .and_then(|g| g.read().unwrap().roles.get(&role_id.into()).cloned()) @@ -590,7 +596,9 @@ impl Cache { self.users.get(&user_id.into()).cloned() } - pub(crate) fn update_with_channel_create(&mut self, event: &ChannelCreateEvent) -> Option<Channel> { + pub(crate) fn update_with_channel_create(&mut self, + event: &ChannelCreateEvent) + -> Option<Channel> { match event.channel { Channel::Group(ref group) => { let group = group.clone(); @@ -623,8 +631,13 @@ impl Cache { self.guilds .get_mut(&guild_id) .and_then(|guild| { - guild.write().unwrap().channels.insert(channel_id, channel.clone()) - }).map(Channel::Guild) + guild + .write() + .unwrap() + .channels + .insert(channel_id, channel.clone()) + }) + .map(Channel::Guild) }, Channel::Private(ref channel) => { let channel = channel.clone(); @@ -641,14 +654,16 @@ impl Cache { channel_writer.recipient = self.users[&user_id].clone(); - let ch = self.private_channels.insert(channel_writer.id, channel.clone()); + let ch = self.private_channels + .insert(channel_writer.id, channel.clone()); ch.map(Channel::Private) }, } } pub(crate) fn update_with_channel_delete(&mut self, event: &ChannelDeleteEvent) { - // We ignore these two due to the fact that the delete event for dms/groups will _not_ fire anymore. + // We ignore these two due to the fact that the delete event for dms/groups will _not_ fire + // anymore. let channel = match event.channel { Channel::Guild(ref channel) => channel, Channel::Private(_) | Channel::Group(_) => unreachable!(), @@ -687,22 +702,23 @@ impl Cache { return; } } - - pub(crate) fn update_with_channel_recipient_add(&mut self, event: &mut ChannelRecipientAddEvent) { + + pub(crate) fn update_with_channel_recipient_add(&mut self, + event: &mut ChannelRecipientAddEvent) { self.update_user_entry(&event.user); let user = self.users[&event.user.id].clone(); - self.groups - .get_mut(&event.channel_id) - .map(|group| { - group.write() - .unwrap() - .recipients - .insert(event.user.id, user); - }); + self.groups.get_mut(&event.channel_id).map(|group| { + group + .write() + .unwrap() + .recipients + .insert(event.user.id, user); + }); } - pub(crate) fn update_with_channel_recipient_remove(&mut self, event: &ChannelRecipientRemoveEvent) { + pub(crate) fn update_with_channel_recipient_remove(&mut self, + event: &ChannelRecipientRemoveEvent) { self.groups .get_mut(&event.channel_id) .map(|group| group.write().unwrap().recipients.remove(&event.user.id)); @@ -744,14 +760,13 @@ impl Cache { }; self.channels.insert(channel_id, channel.clone()); - self.guilds - .get_mut(&guild_id) - .map(|guild| { - guild.write() - .unwrap() - .channels - .insert(channel_id, channel.clone()) - }); + self.guilds.get_mut(&guild_id).map(|guild| { + guild + .write() + .unwrap() + .channels + .insert(channel_id, channel.clone()) + }); }, Channel::Private(ref channel) => { self.private_channels @@ -774,11 +789,13 @@ impl Cache { } self.channels.extend(guild.channels.clone()); - self.guilds.insert(event.guild.id, Arc::new(RwLock::new(guild))); + self.guilds + .insert(event.guild.id, Arc::new(RwLock::new(guild))); } - pub(crate) fn update_with_guild_delete(&mut self, event: &GuildDeleteEvent) - -> Option<Arc<RwLock<Guild>>> { + pub(crate) fn update_with_guild_delete(&mut self, + event: &GuildDeleteEvent) + -> Option<Arc<RwLock<Guild>>> { // Remove channel entries for the guild if the guild is found. self.guilds.remove(&event.guild.id).map(|guild| { for channel_id in guild.read().unwrap().channels.keys() { @@ -802,30 +819,28 @@ impl Cache { // Always safe due to being inserted above. event.member.user = self.users[&user_id].clone(); - self.guilds - .get_mut(&event.guild_id) - .map(|guild| { - let mut guild = guild.write().unwrap(); + self.guilds.get_mut(&event.guild_id).map(|guild| { + let mut guild = guild.write().unwrap(); - guild.member_count += 1; - guild.members.insert(user_id, event.member.clone()); - }); + guild.member_count += 1; + guild.members.insert(user_id, event.member.clone()); + }); } - pub(crate) fn update_with_guild_member_remove(&mut self, event: &GuildMemberRemoveEvent) - -> Option<Member> { - self.guilds - .get_mut(&event.guild_id) - .and_then(|guild| { - let mut guild = guild.write().unwrap(); + pub(crate) fn update_with_guild_member_remove(&mut self, + event: &GuildMemberRemoveEvent) + -> Option<Member> { + self.guilds.get_mut(&event.guild_id).and_then(|guild| { + let mut guild = guild.write().unwrap(); - guild.member_count -= 1; - guild.members.remove(&event.user.id) - }) + guild.member_count -= 1; + guild.members.remove(&event.user.id) + }) } - pub(crate) fn update_with_guild_member_update(&mut self, event: &GuildMemberUpdateEvent) - -> Option<Member> { + pub(crate) fn update_with_guild_member_update(&mut self, + event: &GuildMemberUpdateEvent) + -> Option<Member> { self.update_user_entry(&event.user); if let Some(guild) = self.guilds.get_mut(&event.guild_id) { @@ -848,15 +863,16 @@ impl Cache { }; if !found { - guild.members.insert(event.user.id, Member { - deaf: false, - guild_id: event.guild_id, - joined_at: None, - mute: false, - nick: event.nick.clone(), - roles: event.roles.clone(), - user: Arc::new(RwLock::new(event.user.clone())), - }); + guild.members.insert(event.user.id, + Member { + deaf: false, + guild_id: event.guild_id, + joined_at: None, + mute: false, + nick: event.nick.clone(), + roles: event.roles.clone(), + user: Arc::new(RwLock::new(event.user.clone())), + }); } item @@ -876,27 +892,34 @@ impl Cache { } pub(crate) fn update_with_guild_role_create(&mut self, event: &GuildRoleCreateEvent) { - self.guilds - .get_mut(&event.guild_id) - .map(|guild| guild.write().unwrap().roles.insert(event.role.id, event.role.clone())); + self.guilds.get_mut(&event.guild_id).map(|guild| { + guild + .write() + .unwrap() + .roles + .insert(event.role.id, event.role.clone()) + }); } - pub(crate) fn update_with_guild_role_delete(&mut self, event: &GuildRoleDeleteEvent) -> Option<Role> { + pub(crate) fn update_with_guild_role_delete(&mut self, + event: &GuildRoleDeleteEvent) + -> Option<Role> { self.guilds .get_mut(&event.guild_id) .and_then(|guild| guild.write().unwrap().roles.remove(&event.role_id)) } - pub(crate) fn update_with_guild_role_update(&mut self, event: &GuildRoleUpdateEvent) -> Option<Role> { - self.guilds - .get_mut(&event.guild_id) - .and_then(|guild| { - guild.write() - .unwrap() - .roles - .get_mut(&event.role.id) - .map(|role| mem::replace(role, event.role.clone())) - }) + pub(crate) fn update_with_guild_role_update(&mut self, + event: &GuildRoleUpdateEvent) + -> Option<Role> { + self.guilds.get_mut(&event.guild_id).and_then(|guild| { + guild + .write() + .unwrap() + .roles + .get_mut(&event.role.id) + .map(|role| mem::replace(role, event.role.clone())) + }) } pub(crate) fn update_with_guild_unavailable(&mut self, event: &GuildUnavailableEvent) { @@ -905,32 +928,30 @@ impl Cache { } pub(crate) fn update_with_guild_update(&mut self, event: &GuildUpdateEvent) { - self.guilds - .get_mut(&event.guild.id) - .map(|guild| { - let mut guild = guild.write().unwrap(); + self.guilds.get_mut(&event.guild.id).map(|guild| { + let mut guild = guild.write().unwrap(); - guild.afk_timeout = event.guild.afk_timeout; - guild.afk_channel_id.clone_from(&event.guild.afk_channel_id); - guild.icon.clone_from(&event.guild.icon); - guild.name.clone_from(&event.guild.name); - guild.owner_id.clone_from(&event.guild.owner_id); - guild.region.clone_from(&event.guild.region); - guild.roles.clone_from(&event.guild.roles); - guild.verification_level = event.guild.verification_level; - }); + guild.afk_timeout = event.guild.afk_timeout; + guild.afk_channel_id.clone_from(&event.guild.afk_channel_id); + guild.icon.clone_from(&event.guild.icon); + guild.name.clone_from(&event.guild.name); + guild.owner_id.clone_from(&event.guild.owner_id); + guild.region.clone_from(&event.guild.region); + guild.roles.clone_from(&event.guild.roles); + guild.verification_level = event.guild.verification_level; + }); } pub(crate) fn update_with_presences_replace(&mut self, event: &PresencesReplaceEvent) { self.presences.extend({ - let mut p: HashMap<UserId, Presence> = HashMap::default(); + let mut p: HashMap<UserId, Presence> = HashMap::default(); - for presence in &event.presences { - p.insert(presence.user_id, presence.clone()); - } + for presence in &event.presences { + p.insert(presence.user_id, presence.clone()); + } - p - }); + p + }); } pub(crate) fn update_with_presence_update(&mut self, event: &mut PresenceUpdateEvent) { @@ -949,13 +970,16 @@ impl Cache { if event.presence.status == OnlineStatus::Offline { guild.presences.remove(&event.presence.user_id); } else { - guild.presences.insert(event.presence.user_id, event.presence.clone()); + guild + .presences + .insert(event.presence.user_id, event.presence.clone()); } } } else if event.presence.status == OnlineStatus::Offline { self.presences.remove(&event.presence.user_id); } else { - self.presences.insert(event.presence.user_id, event.presence.clone()); + self.presences + .insert(event.presence.user_id, event.presence.clone()); } } @@ -1013,7 +1037,9 @@ impl Cache { } } - guild.voice_states.insert(event.voice_state.user_id, event.voice_state.clone()); + guild + .voice_states + .insert(event.voice_state.user_id, event.voice_state.clone()); } else { // Remove the user from the voice state list guild.voice_states.remove(&event.voice_state.user_id); @@ -1034,7 +1060,7 @@ impl Cache { }, Entry::Occupied(mut e) => { e.get_mut().write().unwrap().clone_from(user); - } + }, } } } diff --git a/src/client/context.rs b/src/client/context.rs index 3053648..a20a316 100644 --- a/src/client/context.rs +++ b/src/client/context.rs @@ -1,17 +1,17 @@ use std::sync::Arc; use typemap::ShareMap; -use ::gateway::Shard; -use ::model::*; +use gateway::Shard; +use model::*; use parking_lot::Mutex; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] use super::CACHE; -#[cfg(feature="builder")] -use ::internal::prelude::*; -#[cfg(feature="builder")] -use ::builder::EditProfile; -#[cfg(feature="builder")] -use ::http; +#[cfg(feature = "builder")] +use internal::prelude::*; +#[cfg(feature = "builder")] +use builder::EditProfile; +#[cfg(feature = "builder")] +use http; /// The context is a general utility struct provided on event dispatches, which /// helps with dealing with the current "context" of the event dispatch. @@ -64,17 +64,17 @@ impl Context { /// # use serenity::model::*; /// # /// struct Handler; - /// + /// /// impl EventHandler for Handler { /// fn on_message(&self, ctx: Context, msg: Message) { /// if msg.content == "!changename" { /// ctx.edit_profile(|e| e.username("Edward Elric")); /// } - /// } + /// } /// } /// let mut client = Client::new("token", Handler); client.start().unwrap(); /// ``` - #[cfg(feature="builder")] + #[cfg(feature = "builder")] pub fn edit_profile<F: FnOnce(EditProfile) -> EditProfile>(&self, f: F) -> Result<CurrentUser> { let mut map = Map::new(); @@ -113,13 +113,13 @@ impl Context { /// # use serenity::model::*; /// # /// struct Handler; - /// + /// /// impl EventHandler for Handler { /// fn on_message(&self, ctx: Context, msg: Message) { /// if msg.content == "!online" { /// ctx.online(); /// } - /// } + /// } /// } /// let mut client = Client::new("token", Handler); client.start().unwrap(); /// ``` @@ -142,13 +142,13 @@ impl Context { /// # use serenity::model::*; /// # /// struct Handler; - /// + /// /// impl EventHandler for Handler { /// fn on_message(&self, ctx: Context, msg: Message) { /// if msg.content == "!idle" { /// ctx.idle(); /// } - /// } + /// } /// } /// let mut client = Client::new("token", Handler); client.start().unwrap(); /// ``` @@ -171,13 +171,13 @@ impl Context { /// # use serenity::model::*; /// # /// struct Handler; - /// + /// /// impl EventHandler for Handler { /// fn on_message(&self, ctx: Context, msg: Message) { /// if msg.content == "!dnd" { /// ctx.dnd(); /// } - /// } + /// } /// } /// let mut client = Client::new("token", Handler); client.start().unwrap(); /// ``` @@ -205,7 +205,7 @@ impl Context { /// impl EventHandler for Handler { /// fn on_ready(&self, ctx: Context, _: Ready) { /// ctx.invisible(); - /// } + /// } /// } /// /// let mut client = Client::new("token", Handler); client.start().unwrap(); @@ -230,13 +230,13 @@ impl Context { /// ```rust,no_run /// # use serenity::prelude::*; /// # use serenity::model::event::ResumedEvent; - /// # + /// # /// struct Handler; /// /// impl EventHandler for Handler { /// fn on_resume(&self, ctx: Context, _: ResumedEvent) { /// ctx.reset_presence(); - /// } + /// } /// } /// /// let mut client = Client::new("token", Handler); client.start().unwrap(); @@ -273,7 +273,7 @@ impl Context { /// } /// /// ctx.set_game(Game::playing(*unsafe { args.get_unchecked(1) })); - /// } + /// } /// } /// /// let mut client = Client::new("token", Handler); client.start().unwrap(); @@ -303,11 +303,11 @@ impl Context { /// # use serenity::model::*; /// # /// struct Handler; - /// + /// /// impl EventHandler for Handler { /// fn on_ready(&self, ctx: Context, _: Ready) { /// ctx.set_game_name("test"); - /// } + /// } /// } /// /// let mut client = Client::new("token", Handler); client.start().unwrap(); @@ -342,13 +342,13 @@ impl Context { /// # use serenity::model::*; /// # /// struct Handler; - /// + /// /// impl EventHandler for Handler { /// fn on_ready(&self, ctx: Context, _: Ready) { /// use serenity::model::OnlineStatus; /// /// ctx.set_presence(None, OnlineStatus::Idle, false); - /// } + /// } /// } /// let mut client = Client::new("token", Handler); client.start().unwrap(); /// ``` @@ -361,7 +361,7 @@ impl Context { /// # use serenity::model::*; /// # /// struct Handler; - /// + /// /// impl EventHandler for Handler { /// fn on_ready(&self, context: Context, _: Ready) { /// use serenity::model::{Game, OnlineStatus}; @@ -370,17 +370,14 @@ impl Context { /// let status = OnlineStatus::DoNotDisturb; /// /// context.set_presence(Some(game), status, false); - /// } + /// } /// } /// let mut client = Client::new("token", Handler); client.start().unwrap(); /// ``` /// /// [`DoNotDisturb`]: ../model/enum.OnlineStatus.html#variant.DoNotDisturb /// [`Idle`]: ../model/enum.OnlineStatus.html#variant.Idle - pub fn set_presence(&self, - game: Option<Game>, - status: OnlineStatus, - afk: bool) { + pub fn set_presence(&self, game: Option<Game>, status: OnlineStatus, afk: bool) { let mut shard = self.shard.lock(); shard.set_presence(game, status, afk) } diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs index d54eb02..fa6193e 100644 --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -5,16 +5,16 @@ use std::time; use super::event_handler::EventHandler; use super::Context; use typemap::ShareMap; -use ::gateway::Shard; -use ::model::event::Event; -use ::model::{Message, GuildId, Channel}; -use chrono::{Utc, Timelike}; +use gateway::Shard; +use model::event::Event; +use model::{Channel, GuildId, Message}; +use chrono::{Timelike, Utc}; use tokio_core::reactor::Handle; -#[cfg(feature="framework")] -use ::Framework; +#[cfg(feature = "framework")] +use Framework; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] use super::CACHE; macro_rules! update { @@ -56,28 +56,27 @@ macro_rules! now { () => (Utc::now().time().second() * 1000) } -fn context(conn: &Arc<Mutex<Shard>>, - data: &Arc<Mutex<ShareMap>>) -> Context { +fn context(conn: &Arc<Mutex<Shard>>, data: &Arc<Mutex<ShareMap>>) -> Context { Context::new(conn.clone(), data.clone()) } -#[cfg(feature="builtin_framework")] +#[cfg(feature = "builtin_framework")] macro_rules! helper { ($enabled:block else $disabled:block) => { $enabled } } -#[cfg(not(feature="builtin_framework"))] +#[cfg(not(feature = "builtin_framework"))] macro_rules! helper { ($enabled:block else $disabled:block) => { $disabled } } -#[cfg(feature="framework")] +#[cfg(feature = "framework")] pub fn dispatch<H: EventHandler + 'static>(event: Event, - conn: &Arc<Mutex<Shard>>, - framework: &Arc<sync::Mutex<Option<Box<Framework>>>>, - data: &Arc<Mutex<ShareMap>>, - event_handler: &Arc<H>, - tokio_handle: &Handle) { + conn: &Arc<Mutex<Shard>>, + framework: &Arc<sync::Mutex<Option<Box<Framework>>>>, + data: &Arc<Mutex<ShareMap>>, + event_handler: &Arc<H>, + tokio_handle: &Handle) { match event { Event::MessageCreate(event) => { let context = context(conn, data); @@ -88,31 +87,28 @@ pub fn dispatch<H: EventHandler + 'static>(event: Event, if let Some(ref mut framework) = *framework.lock().unwrap() { helper! {{ - if framework.initialized() { - framework.dispatch(context, event.message, tokio_handle); - } - } else { - framework.dispatch(context, event.message, tokio_handle); - }} + if framework.initialized() { + framework.dispatch(context, event.message, tokio_handle); + } + } else { + framework.dispatch(context, event.message, tokio_handle); + }} } }, other => handle_event(other, conn, data, event_handler, tokio_handle), } } -#[cfg(not(feature="framework"))] +#[cfg(not(feature = "framework"))] pub fn dispatch<H: EventHandler + 'static>(event: Event, - conn: &Arc<Mutex<Shard>>, - data: &Arc<Mutex<ShareMap>>, - event_handler: &Arc<H>, - tokio_handle: &Handle) { + conn: &Arc<Mutex<Shard>>, + data: &Arc<Mutex<ShareMap>>, + event_handler: &Arc<H>, + tokio_handle: &Handle) { match event { Event::MessageCreate(event) => { let context = context(conn, data); - dispatch_message(context, - event.message, - event_handler, - tokio_handle); + dispatch_message(context, event.message, event_handler, tokio_handle); }, other => handle_event(other, conn, data, event_handler, tokio_handle), } @@ -120,12 +116,12 @@ pub fn dispatch<H: EventHandler + 'static>(event: Event, #[allow(unused_mut)] fn dispatch_message<H: EventHandler + 'static>(context: Context, - mut message: Message, - event_handler: &Arc<H>, - tokio_handle: &Handle) { + mut message: Message, + event_handler: &Arc<H>, + tokio_handle: &Handle) { let h = event_handler.clone(); tokio_handle.spawn_fn(move || { - #[cfg(feature="model")] + #[cfg(feature = "model")] { message.transform_content(); } @@ -138,10 +134,10 @@ fn dispatch_message<H: EventHandler + 'static>(context: Context, #[allow(cyclomatic_complexity, unused_assignments, unused_mut)] fn handle_event<H: EventHandler + 'static>(event: Event, - conn: &Arc<Mutex<Shard>>, - data: &Arc<Mutex<ShareMap>>, - event_handler: &Arc<H>, - tokio_handle: &Handle) { + conn: &Arc<Mutex<Shard>>, + data: &Arc<Mutex<ShareMap>>, + event_handler: &Arc<H>, + tokio_handle: &Handle) { #[cfg(feature="cache")] let mut last_guild_create_time = now!(); @@ -188,7 +184,7 @@ fn handle_event<H: EventHandler + 'static>(event: Event, let context = context(conn, data); match event.channel { - Channel::Private(_) | Channel::Group(_) => {} + Channel::Private(_) | Channel::Group(_) => {}, Channel::Guild(channel) => { let h = event_handler.clone(); tokio_handle.spawn_fn(move || { @@ -276,7 +272,7 @@ fn handle_event<H: EventHandler + 'static>(event: Event, update!(update_with_guild_create, event); - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { last_guild_create_time = now!(); @@ -287,9 +283,11 @@ fn handle_event<H: EventHandler + 'static>(event: Event, let context = context(conn, data); - let guild_amount = cache.guilds.iter() - .map(|(&id, _)| id) - .collect::<Vec<GuildId>>(); + let guild_amount = cache + .guilds + .iter() + .map(|(&id, _)| id) + .collect::<Vec<GuildId>>(); tokio_handle.spawn_fn(move || { h.on_cached(context, guild_amount); @@ -546,8 +544,6 @@ fn handle_event<H: EventHandler + 'static>(event: Event, Ok(()) }); }, - - // Already handled by the framework check macro Event::ReactionAdd(event) => { let h = event_handler.clone(); let context = context(conn, data); diff --git a/src/client/error.rs b/src/client/error.rs index 1a23599..23c9ad9 100644 --- a/src/client/error.rs +++ b/src/client/error.rs @@ -27,9 +27,7 @@ pub enum Error { } impl Display for Error { - fn fmt(&self, f: &mut Formatter) -> FmtResult { - f.write_str(self.description()) - } + fn fmt(&self, f: &mut Formatter) -> FmtResult { f.write_str(self.description()) } } impl StdError for Error { diff --git a/src/client/event_handler.rs b/src/client/event_handler.rs index 09482b8..03a2f2e 100644 --- a/src/client/event_handler.rs +++ b/src/client/event_handler.rs @@ -2,13 +2,13 @@ use serde_json::Value; use std::collections::HashMap; use std::sync::Arc; use super::context::Context; -use ::model::event::*; -use ::model::*; +use model::event::*; +use model::*; use std::sync::RwLock; pub trait EventHandler { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn on_cached(&self, _: Context, _: Vec<GuildId>) {} fn on_channel_create(&self, _: Context, _: Arc<RwLock<GuildChannel>>) {} fn on_private_channel_create(&self, _: Context, _: Arc<RwLock<PrivateChannel>>) {} @@ -16,45 +16,45 @@ pub trait EventHandler { fn on_channel_pins_update(&self, _: Context, _: ChannelPinsUpdateEvent) {} fn on_channel_recipient_addition(&self, _: Context, _: ChannelId, _: User) {} fn on_channel_recipient_removal(&self, _: Context, _: ChannelId, _: User) {} - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn on_channel_update(&self, _: Context, _: Option<Channel>, _: Channel) {} - #[cfg(not(feature="cache"))] + #[cfg(not(feature = "cache"))] fn on_channel_update(&self, _: Context, _: Channel) {} fn on_guild_ban_addition(&self, _: Context, _: GuildId, _: User) {} fn on_guild_ban_removal(&self, _: Context, _: GuildId, _: User) {} - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn on_guild_create(&self, _: Context, _: Guild, _: bool) {} - #[cfg(not(feature="cache"))] + #[cfg(not(feature = "cache"))] fn on_guild_create(&self, _: Context, _: Guild) {} - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn on_guild_delete(&self, _: Context, _: PartialGuild, _: Option<Arc<RwLock<Guild>>>) {} - #[cfg(not(feature="cache"))] + #[cfg(not(feature = "cache"))] fn on_guild_delete(&self, _: Context, _: PartialGuild) {} fn on_guild_emojis_update(&self, _: Context, _: GuildId, _: HashMap<EmojiId, Emoji>) {} fn on_guild_integrations_update(&self, _: Context, _: GuildId) {} fn on_guild_member_addition(&self, _: Context, _: GuildId, _: Member) {} - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn on_guild_member_removal(&self, _: Context, _: GuildId, _: User, _: Option<Member>) {} - #[cfg(not(feature="cache"))] + #[cfg(not(feature = "cache"))] fn on_guild_member_removal(&self, _: Context, _: GuildId, _: User) {} - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn on_guild_member_update(&self, _: Context, _: Option<Member>, _: Member) {} - #[cfg(not(feature="cache"))] + #[cfg(not(feature = "cache"))] fn on_guild_member_update(&self, _: Context, _: GuildMemberUpdateEvent) {} fn on_guild_members_chunk(&self, _: Context, _: GuildId, _: HashMap<UserId, Member>) {} fn on_guild_role_create(&self, _: Context, _: GuildId, _: Role) {} - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn on_guild_role_delete(&self, _: Context, _: GuildId, _: RoleId, _: Option<Role>) {} - #[cfg(not(feature="cache"))] + #[cfg(not(feature = "cache"))] fn on_guild_role_delete(&self, _: Context, _: GuildId, _: RoleId) {} - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn on_guild_role_update(&self, _: Context, _: GuildId, _: Option<Role>, _: Role) {} - #[cfg(not(feature="cache"))] + #[cfg(not(feature = "cache"))] fn on_guild_role_update(&self, _: Context, _: GuildId, _: Role) {} fn on_guild_unavailable(&self, _: Context, _: GuildId) {} - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn on_guild_update(&self, _: Context, _: Option<Arc<RwLock<Guild>>>, _: PartialGuild) {} - #[cfg(not(feature="cache"))] + #[cfg(not(feature = "cache"))] fn on_guild_update(&self, _: Context, _: PartialGuild) {} fn on_message(&self, _: Context, _: Message) {} fn on_message_delete(&self, _: Context, _: ChannelId, _: MessageId) {} @@ -69,9 +69,9 @@ pub trait EventHandler { fn on_resume(&self, _: Context, _: ResumedEvent) {} fn on_typing_start(&self, _: Context, _: TypingStartEvent) {} fn on_unknown(&self, _: Context, _: String, _: Value) {} - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn on_user_update(&self, _: Context, _: CurrentUser, _: CurrentUser) {} - #[cfg(not(feature="cache"))] + #[cfg(not(feature = "cache"))] fn on_user_update(&self, _: Context, _: CurrentUser) {} fn on_voice_server_update(&self, _: Context, _: VoiceServerUpdateEvent) {} fn on_voice_state_update(&self, _: Context, _: Option<GuildId>, _: VoiceState) {} diff --git a/src/client/mod.rs b/src/client/mod.rs index a4e5fe5..7549d19 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -29,15 +29,15 @@ pub use self::error::Error as ClientError; pub use self::event_handler::EventHandler; // Note: the following re-exports are here for backwards compatibility -pub use ::gateway; -pub use ::http as rest; +pub use gateway; +pub use http as rest; -#[cfg(feature="cache")] -pub use ::CACHE; +#[cfg(feature = "cache")] +pub use CACHE; use self::dispatch::dispatch; use std::sync::{self, Arc}; -use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; +use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use parking_lot::Mutex; use tokio_core::reactor::Core; use futures; @@ -46,13 +46,13 @@ use std::mem; use super::gateway::Shard; use typemap::ShareMap; use websocket::result::WebSocketError; -use ::http; -use ::internal::prelude::*; -use ::internal::ws_impl::ReceiverExt; -use ::model::event::*; +use http; +use internal::prelude::*; +use internal::ws_impl::ReceiverExt; +use model::event::*; -#[cfg(feature="framework")] -use ::Framework; +#[cfg(feature = "framework")] +use Framework; static HANDLE_STILL: AtomicBool = ATOMIC_BOOL_INIT; @@ -60,9 +60,7 @@ static HANDLE_STILL: AtomicBool = ATOMIC_BOOL_INIT; pub struct CloseHandle; impl CloseHandle { - pub fn close(self) { - HANDLE_STILL.store(false, Ordering::Relaxed); - } + pub fn close(self) { HANDLE_STILL.store(false, Ordering::Relaxed); } } /// The Client is the way to be able to start sending authenticated requests @@ -97,7 +95,7 @@ impl CloseHandle { /// } /// } /// } -/// +/// /// let mut client = Client::new("my token here", Handler); /// /// client.start(); @@ -161,9 +159,12 @@ pub struct Client<H: EventHandler + 'static> { /// /// impl EventHandler for Handler { /// fn on_message(&self, ctx: Context, _: Message) { reg!(ctx "MessageCreate") } - /// fn on_message_delete(&self, ctx: Context, _: ChannelId, _: MessageId) { reg!(ctx "MessageDelete") } - /// fn on_message_delete_bulk(&self, ctx: Context, _: ChannelId, _: Vec<MessageId>) { reg!(ctx "MessageDeleteBulk") } - /// fn on_message_update(&self, ctx: Context, _: ChannelId, _: MessageId) { reg!(ctx "MessageUpdate") } + /// fn on_message_delete(&self, ctx: Context, _: ChannelId, _: MessageId) { reg!(ctx + /// "MessageDelete") } + /// fn on_message_delete_bulk(&self, ctx: Context, _: ChannelId, _: Vec<MessageId>) { + /// reg!(ctx "MessageDeleteBulk") } + /// fn on_message_update(&self, ctx: Context, _: ChannelId, _: MessageId) { reg!(ctx + /// "MessageUpdate") } /// } /// /// let mut client = Client::new(&env::var("DISCORD_TOKEN").unwrap(), Handler); @@ -183,7 +184,8 @@ pub struct Client<H: EventHandler + 'static> { /// [`Event::MessageDelete`]: ../model/event/enum.Event.html#variant.MessageDelete /// [`Event::MessageDeleteBulk`]: ../model/event/enum.Event.html#variant.MessageDeleteBulk /// [`Event::MessageUpdate`]: ../model/event/enum.Event.html#variant.MessageUpdate - /// [example 05]: https://github.com/zeyla/serenity/tree/master/examples/05_command_framework + /// [example 05]: + /// https://github.com/zeyla/serenity/tree/master/examples/05_command_framework pub data: Arc<Mutex<ShareMap>>, /// A vector of all active shards that have received their [`Event::Ready`] /// payload, and have dispatched to [`on_ready`] if an event handler was @@ -192,7 +194,7 @@ pub struct Client<H: EventHandler + 'static> { /// [`Event::Ready`]: ../model/event/enum.Event.html#variant.Ready /// [`on_ready`]: #method.on_ready event_handler: Arc<H>, - #[cfg(feature="framework")] + #[cfg(feature = "framework")] framework: Arc<sync::Mutex<Option<Box<Framework>>>>, token: Arc<sync::Mutex<String>>, } @@ -209,7 +211,7 @@ impl<H: EventHandler + 'static> Client<H> { /// /// ```rust,no_run /// # use serenity::prelude::EventHandler; - /// struct Handler; + /// struct Handler; /// /// impl EventHandler for Handler {} /// # use std::error::Error; @@ -288,7 +290,7 @@ impl<H: EventHandler + 'static> Client<H> { /// # try_main().unwrap(); /// # } /// ``` - /// + /// /// Using your own framework: /// /// ```rust,ignore @@ -303,8 +305,8 @@ impl<H: EventHandler + 'static> Client<H> { /// /// /// struct MyFramework { - /// commands: HashMap<String, Box<Fn(Message, Vec<String>)>>, - /// } + /// commands: HashMap<String, Box<Fn(Message, Vec<String>)>>, + /// } /// /// impl Framework for MyFramework { /// fn dispatch(&mut self, _: Context, msg: Message, tokio_handle: &Handle) { @@ -314,15 +316,15 @@ impl<H: EventHandler + 'static> Client<H> { /// if !command.starts_with('*') { return; } /// command /// }, - /// None => return, + /// None => return, /// }; - /// + /// /// let command = match self.commands.get(&command) { /// Some(command) => command, None => return, /// }; - /// + /// /// tokio_handle.spawn_fn(move || { (command)(msg, args); Ok() }); - /// } + /// } /// } /// /// struct Handler; @@ -335,7 +337,11 @@ impl<H: EventHandler + 'static> Client<H> { /// use std::env; /// /// let mut client = Client::new(&env::var("DISCORD_TOKEN")?, Handler); - /// client.with_framework(MyFramework { commands: { let mut map = HashMap::new(); map.insert("ping".to_string(), Box::new(|msg, _| msg.channel_id.say("pong!"))); map }}); + /// client.with_framework(MyFramework { commands: { + /// let mut map = HashMap::new(); + /// map.insert("ping".to_string(), Box::new(|msg, _| msg.channel_id.say("pong!"))); + /// map + /// }}); /// # Ok(()) /// # } /// # @@ -348,7 +354,7 @@ impl<H: EventHandler + 'static> Client<H> { /// /// [`on_message`]: #method.on_message /// [framework docs]: ../framework/index.html - #[cfg(feature="framework")] + #[cfg(feature = "framework")] pub fn with_framework<F: Framework + 'static>(&mut self, f: F) { self.framework = Arc::new(sync::Mutex::new(Some(Box::new(f)))); } @@ -415,7 +421,7 @@ impl<H: EventHandler + 'static> Client<H> { /// Start as many shards as needed using autosharding: /// /// ```rust,no_run - /// # use serenity::prelude::EventHandler; + /// # use serenity::prelude::EventHandler; /// # use std::error::Error; /// # /// struct Handler; @@ -474,7 +480,7 @@ impl<H: EventHandler + 'static> Client<H> { /// Start shard 3 of 5: /// /// ```rust,no_run - /// # use serenity::prelude::EventHandler; + /// # use serenity::prelude::EventHandler; /// # use std::error::Error; /// # /// struct Handler; @@ -501,7 +507,7 @@ impl<H: EventHandler + 'static> Client<H> { /// [`start_autosharded`]): /// /// ```rust,no_run - /// # use serenity::prelude::EventHandler; + /// # use serenity::prelude::EventHandler; /// # use std::error::Error; /// # /// struct Handler; @@ -554,7 +560,7 @@ impl<H: EventHandler + 'static> Client<H> { /// Start all of 8 shards: /// /// ```rust,no_run - /// # use serenity::prelude::EventHandler; + /// # use serenity::prelude::EventHandler; /// # use std::error::Error; /// # /// struct Handler; @@ -587,7 +593,8 @@ impl<H: EventHandler + 'static> Client<H> { /// [`start_shard_range`]: #method.start_shard_range /// [Gateway docs]: gateway/index.html#sharding pub fn start_shards(&mut self, total_shards: u64) -> Result<()> { - self.start_connection([0, total_shards - 1, total_shards], http::get_gateway()?.url) + self.start_connection([0, total_shards - 1, total_shards], + http::get_gateway()?.url) } /// Establish a range of sharded connections and start listening for events. @@ -622,7 +629,7 @@ impl<H: EventHandler + 'static> Client<H> { /// ``` /// /// ```rust,no_run - /// # use serenity::prelude::EventHandler; + /// # use serenity::prelude::EventHandler; /// # use std::error::Error; /// # /// struct Handler; @@ -660,9 +667,7 @@ impl<H: EventHandler + 'static> Client<H> { } /// Returns a thread-safe handle for closing shards. - pub fn close_handle(&self) -> CloseHandle { - CloseHandle - } + pub fn close_handle(&self) -> CloseHandle { CloseHandle } // Shard data layout is: // 0: first shard number to initialize @@ -677,8 +682,7 @@ impl<H: EventHandler + 'static> Client<H> { // an error. // // [`ClientError::Shutdown`]: enum.ClientError.html#variant.Shutdown - fn start_connection(&mut self, shard_data: [u64; 3], url: String) - -> Result<()> { + fn start_connection(&mut self, shard_data: [u64; 3], url: String) -> Result<()> { HANDLE_STILL.store(true, Ordering::Relaxed); let mut core = Core::new().unwrap(); @@ -686,7 +690,7 @@ impl<H: EventHandler + 'static> Client<H> { // Update the framework's current user if the feature is enabled. // // This also acts as a form of check to ensure the token is correct. - #[cfg(all(feature="builtin_framework", feature="framework"))] + #[cfg(all(feature = "builtin_framework", feature = "framework"))] { let user = http::get_current_user()?; @@ -706,10 +710,10 @@ impl<H: EventHandler + 'static> Client<H> { let shard_info = [shard_number, shard_data[2]]; let boot = boot_shard(&BootInfo { - gateway_url: gateway_url.clone(), - shard_info: shard_info, - token: self.token.clone(), - }); + gateway_url: gateway_url.clone(), + shard_info: shard_info, + token: self.token.clone(), + }); match boot { Ok(shard) => { @@ -758,9 +762,7 @@ impl<H: EventHandler + 'static> Client<H> { impl<H: EventHandler + 'static> Drop for Client<H> { - fn drop(&mut self) { - self.close_handle().close(); - } + fn drop(&mut self) { self.close_handle().close(); } } struct BootInfo { @@ -769,7 +771,7 @@ struct BootInfo { token: Arc<sync::Mutex<String>>, } -#[cfg(feature="framework")] +#[cfg(feature = "framework")] struct MonitorInfo<H: EventHandler + 'static> { data: Arc<Mutex<ShareMap>>, event_handler: Arc<H>, @@ -780,7 +782,7 @@ struct MonitorInfo<H: EventHandler + 'static> { token: Arc<sync::Mutex<String>>, } -#[cfg(not(feature="framework"))] +#[cfg(not(feature = "framework"))] struct MonitorInfo<H: EventHandler + 'static> { data: Arc<Mutex<ShareMap>>, event_handler: Arc<H>, @@ -840,10 +842,10 @@ fn monitor_shard<H: EventHandler + 'static>(mut info: MonitorInfo<H>) { for _ in 0..3 { let boot = boot_shard(&BootInfo { - gateway_url: info.gateway_url.clone(), - shard_info: info.shard_info, - token: info.token.clone(), - }); + gateway_url: info.gateway_url.clone(), + shard_info: info.shard_info, + token: info.token.clone(), + }); match boot { Ok(new_shard) => { @@ -875,7 +877,9 @@ fn monitor_shard<H: EventHandler + 'static>(mut info: MonitorInfo<H>) { let mut shard = info.shard.lock(); if let Err(e) = shard.shutdown_clean() { - error!("Error shutting down shard {:?}: {:?}", shard.shard_info(), e); + error!("Error shutting down shard {:?}: {:?}", + shard.shard_info(), + e); } } } @@ -883,7 +887,7 @@ fn monitor_shard<H: EventHandler + 'static>(mut info: MonitorInfo<H>) { fn handle_shard<H: EventHandler + 'static>(info: &mut MonitorInfo<H>) { let mut core = Core::new().unwrap(); let handle = core.handle(); - + // This is currently all ducktape. Redo this. while HANDLE_STILL.load(Ordering::Relaxed) { { @@ -896,7 +900,7 @@ fn handle_shard<H: EventHandler + 'static>(info: &mut MonitorInfo<H>) { } } - #[cfg(feature="voice")] + #[cfg(feature = "voice")] { let mut shard = info.shard.lock(); diff --git a/src/constants.rs b/src/constants.rs index b957d1d..91aef17 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -12,31 +12,33 @@ pub const MESSAGE_CODE_LIMIT: u16 = 2000; /// The [UserAgent] sent along with every request. /// /// [UserAgent]: ../hyper/header/struct.UserAgent.html -pub const USER_AGENT: &'static str = concat!("DiscordBot (https://github.com/zeyla/serenity, ", env!("CARGO_PKG_VERSION"), ")"); +pub const USER_AGENT: &'static str = concat!("DiscordBot (https://github.com/zeyla/serenity, ", + env!("CARGO_PKG_VERSION"), + ")"); /// List of messages Discord shows on member join. pub static JOIN_MESSAGES: &'static [&'static str] = &[ - "$user just joined the server - glhf!", - "$user just joined. Everyone, look busy!", - "$user just joined. Can I get a heal?", - "$user joined your party.", - "$user joined. You must construct additional pylons.", - "Ermagherd. $user is here.", - "Welcome, $user. Stay awhile and listen.", - "Welcome, $user. We were expecting you ( ͡° ͜ʖ ͡°)", - "Welcome, $user. We hope you brought pizza.", - "Welcome $user. Leave your weapons by the door.", - "A wild $user appeared.", - "Swoooosh. $user just landed.", - "Brace yourselves. $user just joined the server.", - "$user just joined. Hide your bananas.", - "$user just arrived. Seems OP - please nerf.", - "$user just slid into the server.", - "A $user has spawned in the server.", - "Big $user showed up!", - "Where’s $user? In the server!", - "$user hopped into the server. Kangaroo!!", - "$user just showed up. Hold my beer." + "$user just joined the server - glhf!", + "$user just joined. Everyone, look busy!", + "$user just joined. Can I get a heal?", + "$user joined your party.", + "$user joined. You must construct additional pylons.", + "Ermagherd. $user is here.", + "Welcome, $user. Stay awhile and listen.", + "Welcome, $user. We were expecting you ( ͡° ͜ʖ ͡°)", + "Welcome, $user. We hope you brought pizza.", + "Welcome $user. Leave your weapons by the door.", + "A wild $user appeared.", + "Swoooosh. $user just landed.", + "Brace yourselves. $user just joined the server.", + "$user just joined. Hide your bananas.", + "$user just arrived. Seems OP - please nerf.", + "$user just slid into the server.", + "A $user has spawned in the server.", + "Big $user showed up!", + "Where’s $user? In the server!", + "$user hopped into the server. Kangaroo!!", + "$user just showed up. Hold my beer.", ]; enum_number!( diff --git a/src/error.rs b/src/error.rs index 390d295..185f907 100644 --- a/src/error.rs +++ b/src/error.rs @@ -3,25 +3,25 @@ use std::io::Error as IoError; use std::error::Error as StdError; use std::fmt::{self, Display, Error as FormatError}; use std::num::ParseIntError; -use ::internal::prelude::*; -use ::model::ModelError; +use internal::prelude::*; +use model::ModelError; -#[cfg(feature="hyper")] +#[cfg(feature = "hyper")] use hyper::Error as HyperError; -#[cfg(feature="native-tls")] +#[cfg(feature = "native-tls")] use native_tls::Error as TlsError; -#[cfg(feature="voice")] +#[cfg(feature = "voice")] use opus::Error as OpusError; -#[cfg(feature="websocket")] +#[cfg(feature = "websocket")] use websocket::result::WebSocketError; -#[cfg(feature="client")] -use ::client::ClientError; -#[cfg(feature="gateway")] -use ::gateway::GatewayError; -#[cfg(feature="http")] -use ::http::HttpError; -#[cfg(feature="voice")] -use ::voice::VoiceError; +#[cfg(feature = "client")] +use client::ClientError; +#[cfg(feature = "gateway")] +use gateway::GatewayError; +#[cfg(feature = "http")] +use http::HttpError; +#[cfg(feature = "voice")] +use voice::VoiceError; /// The common result type between most library functions. /// @@ -63,7 +63,8 @@ pub enum Error { Num(ParseIntError), /// Input exceeded a limit. /// - /// *This only exists for the `GuildId::ban` and `Member::ban` functions. For their cases, it's the "reason".* + /// *This only exists for the `GuildId::ban` and `Member::ban` functions. For their cases, + /// it's the "reason".* ExceededLimit, /// Some other error. This is only used for "Expected value <TYPE>" errors, /// when a more detailed error can not be easily provided via the @@ -76,98 +77,78 @@ pub enum Error { /// A [client] error. /// /// [client]: client/index.html - #[cfg(feature="client")] + #[cfg(feature = "client")] Client(ClientError), /// An error from the `gateway` module. - #[cfg(feature="gateway")] + #[cfg(feature = "gateway")] Gateway(GatewayError), /// An error from the [`http`] module. /// /// [`http`]: http/index.html - #[cfg(feature="http")] + #[cfg(feature = "http")] Http(HttpError), /// An error from the `hyper` crate. - #[cfg(feature="hyper")] + #[cfg(feature = "hyper")] Hyper(HyperError), /// An error from the `native-tls` crate. - #[cfg(feature="native-tls")] + #[cfg(feature = "native-tls")] Tls(TlsError), /// An error from the `rust-websocket` crate. - #[cfg(feature="gateway")] + #[cfg(feature = "gateway")] WebSocket(WebSocketError), /// An error from the `opus` crate. - #[cfg(feature="voice")] + #[cfg(feature = "voice")] Opus(OpusError), /// Indicating an error within the [voice module]. /// /// [voice module]: voice/index.html - #[cfg(feature="voice")] + #[cfg(feature = "voice")] Voice(VoiceError), } impl From<FormatError> for Error { - fn from(e: FormatError) -> Error { - Error::Format(e) - } + fn from(e: FormatError) -> Error { Error::Format(e) } } -#[cfg(feature="gateway")] +#[cfg(feature = "gateway")] impl From<GatewayError> for Error { - fn from(e: GatewayError) -> Error { - Error::Gateway(e) - } + fn from(e: GatewayError) -> Error { Error::Gateway(e) } } -#[cfg(feature="hyper")] +#[cfg(feature = "hyper")] impl From<HyperError> for Error { - fn from(e: HyperError) -> Error { - Error::Hyper(e) - } + fn from(e: HyperError) -> Error { Error::Hyper(e) } } impl From<IoError> for Error { - fn from(e: IoError) -> Error { - Error::Io(e) - } + fn from(e: IoError) -> Error { Error::Io(e) } } impl From<JsonError> for Error { - fn from(e: JsonError) -> Error { - Error::Json(e) - } + fn from(e: JsonError) -> Error { Error::Json(e) } } impl From<ParseIntError> for Error { - fn from(e: ParseIntError) -> Error { - Error::Num(e) - } + fn from(e: ParseIntError) -> Error { Error::Num(e) } } impl From<ModelError> for Error { - fn from(e: ModelError) -> Error { - Error::Model(e) - } + fn from(e: ModelError) -> Error { Error::Model(e) } } -#[cfg(feature="voice")] +#[cfg(feature = "voice")] impl From<OpusError> for Error { - fn from(e: OpusError) -> Error { - Error::Opus(e) - } + fn from(e: OpusError) -> Error { Error::Opus(e) } } -#[cfg(feature="native-tls")] +#[cfg(feature = "native-tls")] impl From<TlsError> for Error { - fn from(e: TlsError) -> Error { - Error::Tls(e) - } + fn from(e: TlsError) -> Error { Error::Tls(e) } } -#[cfg(feature="gateway")] +#[cfg(feature = "gateway")] impl From<WebSocketError> for Error { - fn from(e: WebSocketError) -> Error { - Error::WebSocket(e) - } + fn from(e: WebSocketError) -> Error { Error::WebSocket(e) } } impl Display for Error { @@ -175,11 +156,11 @@ impl Display for Error { match *self { Error::Io(ref inner) => inner.fmt(f), Error::Json(ref inner) => inner.fmt(f), - #[cfg(feature="http")] + #[cfg(feature = "http")] Error::Hyper(ref inner) => inner.fmt(f), - #[cfg(feature="gateway")] + #[cfg(feature = "gateway")] Error::WebSocket(ref inner) => inner.fmt(f), - #[cfg(feature="voice")] + #[cfg(feature = "voice")] Error::Opus(ref inner) => inner.fmt(f), _ => f.write_str(self.description()), } @@ -197,32 +178,32 @@ impl StdError for Error { Error::Model(ref inner) => inner.description(), Error::Num(ref inner) => inner.description(), Error::Url(ref inner) => inner, - #[cfg(feature="client")] + #[cfg(feature = "client")] Error::Client(ref inner) => inner.description(), - #[cfg(feature="gateway")] + #[cfg(feature = "gateway")] Error::Gateway(ref inner) => inner.description(), - #[cfg(feature="http")] + #[cfg(feature = "http")] Error::Http(ref inner) => inner.description(), - #[cfg(feature="http")] + #[cfg(feature = "http")] Error::Hyper(ref inner) => inner.description(), - #[cfg(feature="voice")] + #[cfg(feature = "voice")] Error::Opus(ref inner) => inner.description(), - #[cfg(feature="native-tls")] + #[cfg(feature = "native-tls")] Error::Tls(ref inner) => inner.description(), - #[cfg(feature="voice")] + #[cfg(feature = "voice")] Error::Voice(_) => "Voice error", - #[cfg(feature="gateway")] + #[cfg(feature = "gateway")] Error::WebSocket(ref inner) => inner.description(), } } fn cause(&self) -> Option<&StdError> { match *self { - #[cfg(feature="http")] + #[cfg(feature = "http")] Error::Hyper(ref inner) => Some(inner), Error::Json(ref inner) => Some(inner), Error::Io(ref inner) => Some(inner), - #[cfg(feature="gateway")] + #[cfg(feature = "gateway")] Error::WebSocket(ref inner) => Some(inner), _ => None, } @@ -13,9 +13,9 @@ //! **Note**: This module exists for backwards compatibility purposes. Instead, //! prefer to use the root modules directly. -#[cfg(feature="cache")] +#[cfg(feature = "cache")] pub use super::cache; -#[cfg(feature="framework")] +#[cfg(feature = "framework")] pub use super::framework; -#[cfg(feature="voice")] +#[cfg(feature = "voice")] pub use super::voice; diff --git a/src/framework/buckets.rs b/src/framework/buckets.rs index 76a8c0b..95b832b 100644 --- a/src/framework/buckets.rs +++ b/src/framework/buckets.rs @@ -2,7 +2,7 @@ use chrono::Utc; use std::collections::HashMap; use std::default::Default; use client::Context; -use model::{GuildId, ChannelId, UserId}; +use model::{ChannelId, GuildId, UserId}; pub(crate) struct Ratelimit { pub delay: i64, @@ -19,16 +19,18 @@ pub(crate) struct MemberRatelimit { pub(crate) struct Bucket { pub ratelimit: Ratelimit, pub users: HashMap<u64, MemberRatelimit>, - #[cfg(feature="cache")] - pub check: Option<Box<Fn(&mut Context, Option<GuildId>, ChannelId, UserId) -> bool + 'static>>, - #[cfg(not(feature="cache"))] + #[cfg(feature = "cache")] + pub check: + Option<Box<Fn(&mut Context, Option<GuildId>, ChannelId, UserId) -> bool + 'static>>, + #[cfg(not(feature = "cache"))] pub checK: Option<Box<Fn(&mut Context, ChannelId, UserId) -> bool + 'static>>, } impl Bucket { pub fn take(&mut self, user_id: u64) -> i64 { let time = Utc::now().timestamp(); - let user = self.users.entry(user_id) + let user = self.users + .entry(user_id) .or_insert_with(MemberRatelimit::default); if let Some((timespan, limit)) = self.ratelimit.limit { diff --git a/src/framework/command.rs b/src/framework/command.rs index e75ee5e..1484891 100644 --- a/src/framework/command.rs +++ b/src/framework/command.rs @@ -1,12 +1,14 @@ use std::sync::Arc; use super::Configuration; -use ::client::Context; -use ::model::{Message, Permissions}; +use client::Context; +use model::{Message, Permissions}; use std::collections::HashMap; pub type Check = Fn(&mut Context, &Message, &Arc<Command>) -> bool + 'static; pub type Exec = Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + 'static; -pub type Help = Fn(&mut Context, &Message, HashMap<String, Arc<CommandGroup>>, &[String]) -> Result<(), String> + 'static; +pub type Help = Fn(&mut Context, &Message, HashMap<String, Arc<CommandGroup>>, &[String]) + -> Result<(), String> + + 'static; pub type BeforeHook = Fn(&mut Context, &Message, &String) -> bool + 'static; pub type AfterHook = Fn(&mut Context, &Message, &String, Result<(), String>) + 'static; pub(crate) type InternalCommand = Arc<Command>; @@ -67,7 +69,8 @@ pub struct Command { impl Command { pub fn new<F>(f: F) -> Self - where F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + 'static { + where + F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + 'static, { Command { aliases: Vec::new(), checks: Vec::default(), diff --git a/src/framework/configuration.rs b/src/framework/configuration.rs index c74739e..06e7e6a 100644 --- a/src/framework/configuration.rs +++ b/src/framework/configuration.rs @@ -1,9 +1,9 @@ use std::collections::HashSet; use std::default::Default; use super::command::PrefixCheck; -use ::client::Context; -use ::http; -use ::model::{GuildId, Message, UserId}; +use client::Context; +use http; +use model::{GuildId, Message, UserId}; /// The configuration to use for a [`Framework`] associated with a [`Client`] /// instance. @@ -18,7 +18,7 @@ use ::model::{GuildId, Message, UserId}; /// ```rust,no_run /// # use serenity::prelude::EventHandler; /// struct Handler; -/// +/// /// impl EventHandler for Handler {} /// use serenity::Client; /// use std::env; @@ -215,7 +215,8 @@ impl Configuration { /// }))); /// ``` pub fn dynamic_prefix<F>(mut self, dynamic_prefix: F) -> Self - where F: Fn(&mut Context, &Message) -> Option<String> + Send + Sync + 'static { + where + F: Fn(&mut Context, &Message) -> Option<String> + Send + Sync + 'static, { self.dynamic_prefix = Some(Box::new(dynamic_prefix)); self @@ -267,7 +268,7 @@ impl Configuration { if let Ok(current_user) = http::get_current_user() { self.on_mention = Some(vec![ - format!("<@{}>", current_user.id), // Regular mention + format!("<@{}>", current_user.id), // Regular mention format!("<@!{}>", current_user.id), // Nickname mention ]); } diff --git a/src/framework/create_command.rs b/src/framework/create_command.rs index 4f3ab27..d97f6fa 100644 --- a/src/framework/create_command.rs +++ b/src/framework/create_command.rs @@ -1,10 +1,10 @@ -pub use super::{Command, CommandType, CommandGroup}; +pub use super::{Command, CommandGroup, CommandType}; use std::collections::HashMap; use std::default::Default; use std::sync::Arc; -use ::client::Context; -use ::model::{Message, Permissions}; +use client::Context; +use model::{Message, Permissions}; pub struct CreateCommand(pub Command); @@ -52,7 +52,8 @@ impl CreateCommand { /// .desc("Replies to a ping with a pong") /// .exec(ping))); /// - /// fn ping(_context: &mut Context, message: &Message, _args: Vec<String>) -> Result<(), String> { + /// fn ping(_context: &mut Context, message: &Message, _args: Vec<String>) -> Result<(), + /// String> { /// let _ = message.channel_id.say("Pong!"); /// /// Ok(()) @@ -64,7 +65,8 @@ impl CreateCommand { /// } /// ``` pub fn check<F>(mut self, check: F) -> Self - where F: Fn(&mut Context, &Message, &Arc<Command>) -> bool + Send + Sync + 'static { + where + F: Fn(&mut Context, &Message, &Arc<Command>) -> bool + Send + Sync + 'static, { self.0.checks.push(Box::new(check)); self @@ -98,7 +100,8 @@ impl CreateCommand { /// /// [`exec_str`]: #method.exec_str pub fn exec<F>(mut self, func: F) -> Self - where F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static { + where + F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static, { self.0.exec = CommandType::Basic(Box::new(func)); self @@ -110,7 +113,12 @@ impl CreateCommand { /// /// You can return `Err(string)` if there's an error. pub fn exec_help<F>(mut self, f: F) -> Self - where F: Fn(&mut Context, &Message, HashMap<String, Arc<CommandGroup>>, &[String]) -> Result<(), String> + Send + Sync + 'static { + where + F: Fn(&mut Context, &Message, HashMap<String, Arc<CommandGroup>>, &[String]) + -> Result<(), String> + + Send + + Sync + + 'static, { self.0.exec = CommandType::WithCommands(Box::new(f)); self diff --git a/src/framework/create_group.rs b/src/framework/create_group.rs index 88aa6ba..d5b68c3 100644 --- a/src/framework/create_group.rs +++ b/src/framework/create_group.rs @@ -1,11 +1,11 @@ -pub use ext::framework::command::{Command, CommandType, CommandGroup}; +pub use ext::framework::command::{Command, CommandGroup, CommandType}; pub(crate) use ext::framework::command::CommandOrAlias; pub use ext::framework::create_command::CreateCommand; use std::default::Default; use std::sync::Arc; -use ::client::Context; -use ::model::Message; +use client::Context; +use model::Message; /// Used to create command groups /// @@ -27,18 +27,26 @@ pub struct CreateGroup(pub CommandGroup); impl CreateGroup { /// Adds a command to group. pub fn command<F>(mut self, command_name: &str, f: F) -> Self - where F: FnOnce(CreateCommand) -> CreateCommand { + where + F: FnOnce(CreateCommand) -> CreateCommand, { let cmd = f(CreateCommand(Command::default())).0; for n in &cmd.aliases { if let Some(ref prefix) = self.0.prefix { - self.0.commands.insert(format!("{} {}", prefix, n.to_owned()), CommandOrAlias::Alias(format!("{} {}", prefix, command_name.to_string()))); + self.0 + .commands + .insert(format!("{} {}", prefix, n.to_owned()), + CommandOrAlias::Alias(format!("{} {}", + prefix, + command_name.to_string()))); } else { - self.0.commands.insert(n.to_owned(), CommandOrAlias::Alias(command_name.to_string())); + self.0.commands.insert(n.to_owned(), + CommandOrAlias::Alias(command_name.to_string())); } } - self.0.commands.insert(command_name.to_owned(), CommandOrAlias::Command(Arc::new(cmd))); + self.0.commands.insert(command_name.to_owned(), + CommandOrAlias::Command(Arc::new(cmd))); self } @@ -46,10 +54,13 @@ impl CreateGroup { /// Adds a command to group with simplified API. /// You can return Err(string) if there's an error. pub fn on<F>(mut self, command_name: &str, f: F) -> Self - where F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static { + where + F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static, { let cmd = Arc::new(Command::new(f)); - self.0.commands.insert(command_name.to_owned(), CommandOrAlias::Command(cmd)); + self.0 + .commands + .insert(command_name.to_owned(), CommandOrAlias::Command(cmd)); self } diff --git a/src/framework/help_commands.rs b/src/framework/help_commands.rs index d589ded..7f863b4 100644 --- a/src/framework/help_commands.rs +++ b/src/framework/help_commands.rs @@ -28,16 +28,13 @@ use std::sync::Arc; use std::fmt::Write; use super::command::InternalCommand; use super::{Command, CommandGroup, CommandOrAlias}; -use ::client::Context; -use ::model::{ChannelId, Message}; -use ::utils::Colour; +use client::Context; +use model::{ChannelId, Message}; +use utils::Colour; fn error_embed(channel_id: &ChannelId, input: &str) { - let _ = channel_id - .send_message(|m| m - .embed(|e| e - .colour(Colour::dark_red()) - .description(input))); + let _ = + channel_id.send_message(|m| m.embed(|e| e.colour(Colour::dark_red()).description(input))); } fn remove_aliases(cmds: &HashMap<String, CommandOrAlias>) -> HashMap<&String, &InternalCommand> { @@ -74,7 +71,8 @@ fn remove_aliases(cmds: &HashMap<String, CommandOrAlias>) -> HashMap<&String, &I pub fn with_embeds(_: &mut Context, msg: &Message, groups: HashMap<String, Arc<CommandGroup>>, - args: &[String]) -> Result<(), String> { + args: &[String]) + -> Result<(), String> { if !args.is_empty() { let name = args.join(" "); @@ -97,7 +95,7 @@ pub fn with_embeds(_: &mut Context, error_embed(&msg.channel_id, &format!("Did you mean \"{}\"?", name)); return Ok(()); - } + }, } } } @@ -111,28 +109,27 @@ pub fn with_embeds(_: &mut Context, let _ = msg.channel_id.send_message(|m| { m.embed(|e| { - let mut embed = e.colour(Colour::rosewater()) - .title(command_name); + let mut embed = e.colour(Colour::rosewater()).title(command_name); if let Some(ref desc) = command.desc { embed = embed.description(desc); } if let Some(ref usage) = command.usage { - embed = embed.field(|f| f - .name("Usage") - .value(&format!("`{} {}`", command_name, usage))); + embed = embed.field(|f| { + f.name("Usage") + .value(&format!("`{} {}`", command_name, usage)) + }); } if let Some(ref example) = command.example { - embed = embed.field(|f| f - .name("Sample usage") - .value(&format!("`{} {}`", command_name, example))); + embed = embed.field(|f| { + f.name("Sample usage") + .value(&format!("`{} {}`", command_name, example)) + }); } if group_name != "Ungrouped" { - embed = embed.field(|f| f - .name("Group") - .value(&group_name)); + embed = embed.field(|f| f.name("Group").value(&group_name)); } let available = if command.dm_only { @@ -143,9 +140,7 @@ pub fn with_embeds(_: &mut Context, "In DM and guilds" }; - embed = embed.field(|f| f - .name("Available") - .value(available)); + embed = embed.field(|f| f.name("Available").value(available)); embed }) @@ -161,8 +156,8 @@ pub fn with_embeds(_: &mut Context, return Ok(()); } - let _ = msg.channel_id.send_message(|m| m - .embed(|mut e| { + let _ = msg.channel_id.send_message(|m| { + m.embed(|mut e| { e = e.colour(Colour::rosewater()) .description("To get help with an individual command, pass its \ name as an argument to this command."); @@ -200,7 +195,8 @@ pub fn with_embeds(_: &mut Context, } e - })); + }) + }); Ok(()) } @@ -227,7 +223,8 @@ pub fn with_embeds(_: &mut Context, pub fn plain(_: &mut Context, msg: &Message, groups: HashMap<String, Arc<CommandGroup>>, - args: &[String]) -> Result<(), String> { + args: &[String]) + -> Result<(), String> { if !args.is_empty() { let name = args.join(" "); @@ -241,7 +238,7 @@ pub fn plain(_: &mut Context, command_name.to_owned() }; - if name == with_prefix || name == *command_name { + if name == with_prefix || name == *command_name { match *command { CommandOrAlias::Command(ref cmd) => { found = Some((command_name, cmd)); @@ -249,7 +246,7 @@ pub fn plain(_: &mut Context, CommandOrAlias::Alias(ref name) => { let _ = msg.channel_id.say(&format!("Did you mean {:?}?", name)); return Ok(()); - } + }, } } } @@ -280,12 +277,12 @@ pub fn plain(_: &mut Context, result.push_str("**Available:** "); result.push_str(if command.dm_only { - "Only in DM" - } else if command.guild_only { - "Only in guilds" - } else { - "In DM and guilds" - }); + "Only in DM" + } else if command.guild_only { + "Only in guilds" + } else { + "In DM and guilds" + }); result.push_str("\n"); let _ = msg.channel_id.say(&result); @@ -294,7 +291,8 @@ pub fn plain(_: &mut Context, } } - let _ = msg.channel_id.say(&format!("**Error**: Command `{}` not found.", name)); + let _ = msg.channel_id + .say(&format!("**Error**: Command `{}` not found.", name)); return Ok(()); } diff --git a/src/framework/mod.rs b/src/framework/mod.rs index d132b5b..9fddc76 100644 --- a/src/framework/mod.rs +++ b/src/framework/mod.rs @@ -63,7 +63,7 @@ mod create_group; mod buckets; pub(crate) use self::buckets::{Bucket, Ratelimit}; -pub use self::command::{Command, CommandType, CommandGroup}; +pub use self::command::{Command, CommandGroup, CommandType}; pub use self::command::CommandOrAlias; pub use self::configuration::Configuration; pub use self::create_command::CreateCommand; @@ -73,16 +73,16 @@ use self::command::{AfterHook, BeforeHook}; use std::collections::HashMap; use std::default::Default; use std::sync::Arc; -use ::client::Context; -use ::model::{Message, UserId, GuildId, ChannelId}; -use ::model::permissions::Permissions; -use ::utils; +use client::Context; +use model::{ChannelId, GuildId, Message, UserId}; +use model::permissions::Permissions; +use utils; use tokio_core::reactor::Handle; -#[cfg(feature="cache")] -use ::client::CACHE; -#[cfg(feature="cache")] -use ::model::Channel; +#[cfg(feature = "cache")] +use client::CACHE; +#[cfg(feature = "cache")] +use model::Channel; /// A macro to generate "named parameters". This is useful to avoid manually /// using the "arguments" parameter and manually parsing types. @@ -236,16 +236,15 @@ pub struct BuiltinFramework { /// framework check if a [`Event::MessageCreate`] should be processed by /// itself. /// - /// [`EventHandler::on_message`]: ../client/event_handler/trait.EventHandler.html#method.on_message + /// [`EventHandler::on_message`]: + /// ../client/event_handler/trait.EventHandler.html#method.on_message /// [`Event::MessageCreate`]: ../model/event/enum.Event.html#variant.MessageCreate pub initialized: bool, user_info: (u64, bool), } impl BuiltinFramework { - pub fn new() -> Self { - BuiltinFramework::default() - } + pub fn new() -> Self { BuiltinFramework::default() } /// Configures the framework, setting non-default values. All fields are /// optional. Refer to [`Configuration::default`] for more information on @@ -278,7 +277,8 @@ impl BuiltinFramework { /// [`prefix`]: struct.Configuration.html#method.prefix /// [allowing whitespace]: struct.Configuration.html#method.allow_whitespace pub fn configure<F>(mut self, f: F) -> Self - where F: FnOnce(Configuration) -> Configuration { + where + F: FnOnce(Configuration) -> Configuration, { self.configuration = f(self.configuration); self @@ -308,15 +308,17 @@ impl BuiltinFramework { /// .exec_str("pong!"))); /// ``` pub fn bucket<S>(mut self, s: S, delay: i64, time_span: i64, limit: i32) -> Self - where S: Into<String> { - self.buckets.insert(s.into(), Bucket { - ratelimit: Ratelimit { - delay: delay, - limit: Some((time_span, limit)), - }, - users: HashMap::new(), - check: None, - }); + where + S: Into<String>, { + self.buckets.insert(s.into(), + Bucket { + ratelimit: Ratelimit { + delay: delay, + limit: Some((time_span, limit)), + }, + users: HashMap::new(), + check: None, + }); self } @@ -336,10 +338,12 @@ impl BuiltinFramework { /// /// client.with_framework(BuiltinFramework::new() /// .complex_bucket("basic", 2, 10, 3, |_, guild_id, channel_id, user_id| { - /// // check if the guild is `123` and the channel where the command(s) was called: `456` + /// // check if the guild is `123` and the channel where the command(s) was called: + /// `456` /// // and if the user who called the command(s) is `789` /// // otherwise don't apply the bucket at all. - /// guild_id.is_some() && guild_id.unwrap() == 123 && channel_id == 456 && user_id == 789 + /// guild_id.is_some() && guild_id.unwrap() == 123 && channel_id == 456 && user_id + /// == 789 /// }) /// .command("ping", |c| c /// .bucket("basic") @@ -347,19 +351,27 @@ impl BuiltinFramework { /// ``` /// /// [`bucket`]: #method.bucket - #[cfg(feature="cache")] - pub fn complex_bucket<S, Check>(mut self, s: S, delay: i64, time_span: i64, limit: i32, check: Check) -> Self - where Check: Fn(&mut Context, Option<GuildId>, ChannelId, UserId) -> bool + 'static, - S: Into<String> { - self.buckets.insert(s.into(), Bucket { - ratelimit: Ratelimit { - delay, - limit: Some((time_span, limit)), - }, - users: HashMap::new(), - check: Some(Box::new(check)), - }); - + #[cfg(feature = "cache")] + pub fn complex_bucket<S, Check>(mut self, + s: S, + delay: i64, + time_span: i64, + limit: i32, + check: Check) + -> Self + where + Check: Fn(&mut Context, Option<GuildId>, ChannelId, UserId) -> bool + 'static, + S: Into<String>, { + self.buckets.insert(s.into(), + Bucket { + ratelimit: Ratelimit { + delay, + limit: Some((time_span, limit)), + }, + users: HashMap::new(), + check: Some(Box::new(check)), + }); + self } @@ -389,19 +401,27 @@ impl BuiltinFramework { /// ``` /// /// [`bucket`]: #method.bucket - #[cfg(not(feature="cache"))] - pub fn complex_bucket<S, Check>(mut self, s: S, delay: i64, time_span: i64, limit: i32, check: Check) -> Self - where Check: Fn(&mut Context, ChannelId, UserId) -> bool + 'static, - S: Into<String> { - self.buckets.insert(s.into(), Bucket { - ratelimit: Ratelimit { - delay, - limit: Some((time_span, limit)), - }, - users: HashMap::new(), - check: Some(Box::new(check)), - }); - + #[cfg(not(feature = "cache"))] + pub fn complex_bucket<S, Check>(mut self, + s: S, + delay: i64, + time_span: i64, + limit: i32, + check: Check) + -> Self + where + Check: Fn(&mut Context, ChannelId, UserId) -> bool + 'static, + S: Into<String>, { + self.buckets.insert(s.into(), + Bucket { + ratelimit: Ratelimit { + delay, + limit: Some((time_span, limit)), + }, + users: HashMap::new(), + check: Some(Box::new(check)), + }); + self } @@ -427,20 +447,22 @@ impl BuiltinFramework { /// .exec_str("pong!"))); /// ``` pub fn simple_bucket<S>(mut self, s: S, delay: i64) -> Self - where S: Into<String> { - self.buckets.insert(s.into(), Bucket { - ratelimit: Ratelimit { - delay: delay, - limit: None, - }, - users: HashMap::new(), - check: None, - }); + where + S: Into<String>, { + self.buckets.insert(s.into(), + Bucket { + ratelimit: Ratelimit { + delay: delay, + limit: None, + }, + users: HashMap::new(), + check: None, + }); self } - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn is_blocked_guild(&self, message: &Message) -> bool { if let Some(Channel::Guild(channel)) = CACHE.read().unwrap().channel(message.channel_id) { let guild_id = channel.read().unwrap().guild_id; @@ -449,18 +471,23 @@ impl BuiltinFramework { } if let Some(guild) = guild_id.find() { - return self.configuration.blocked_users.contains(&guild.read().unwrap().owner_id); + return self.configuration + .blocked_users + .contains(&guild.read().unwrap().owner_id); } } false } - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn has_correct_permissions(&self, command: &Arc<Command>, message: &Message) -> bool { if !command.required_permissions.is_empty() { if let Some(guild) = message.guild() { - let perms = guild.read().unwrap().permissions_for(message.channel_id, message.author.id); + let perms = guild + .read() + .unwrap() + .permissions_for(message.channel_id, message.author.id); return perms.contains(command.required_permissions); } @@ -476,7 +503,8 @@ impl BuiltinFramework { command: &Arc<Command>, args: usize, to_check: &str, - built: &str) -> Option<DispatchError> { + built: &str) + -> Option<DispatchError> { if self.configuration.ignore_bots && message.author.bot { Some(DispatchError::IgnoredBot) } else if self.configuration.ignore_webhooks && message.webhook_id.is_some() { @@ -512,22 +540,22 @@ impl BuiltinFramework { if let Some(x) = command.min_args { if args < x as usize { return Some(DispatchError::NotEnoughArguments { - min: x, - given: args - }); + min: x, + given: args, + }); } } if let Some(x) = command.max_args { if args > x as usize { return Some(DispatchError::TooManyArguments { - max: x, - given: args - }); + max: x, + given: args, + }); } } - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { if self.is_blocked_guild(message) { return Some(DispatchError::BlockedGuild); @@ -538,7 +566,7 @@ impl BuiltinFramework { } if (!self.configuration.allow_dm && message.is_private()) || - (command.guild_only && message.is_private()) { + (command.guild_only && message.is_private()) { return Some(DispatchError::OnlyForGuilds); } @@ -549,9 +577,14 @@ impl BuiltinFramework { if command.owners_only { Some(DispatchError::OnlyForOwners) - } else if !command.checks.iter().all(|check| (check)(&mut context, message, command)) { + } else if !command + .checks + .iter() + .all(|check| (check)(&mut context, message, command)) { Some(DispatchError::CheckFailed) - } else if self.configuration.blocked_users.contains(&message.author.id) { + } else if self.configuration + .blocked_users + .contains(&message.author.id) { Some(DispatchError::BlockedUser) } else if self.configuration.disabled_commands.contains(to_check) { Some(DispatchError::CommandDisabled(to_check.to_owned())) @@ -603,16 +636,20 @@ impl BuiltinFramework { /// # } /// ``` pub fn on<F, S>(mut self, command_name: S, f: F) -> Self - where F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + 'static, - S: Into<String> { + where + F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + 'static, + S: Into<String>, { { - let ungrouped = self.groups.entry("Ungrouped".to_owned()) + let ungrouped = self.groups + .entry("Ungrouped".to_owned()) .or_insert_with(|| Arc::new(CommandGroup::default())); if let Some(ref mut group) = Arc::get_mut(ungrouped) { let name = command_name.into(); - group.commands.insert(name, CommandOrAlias::Command(Arc::new(Command::new(f)))); + group + .commands + .insert(name, CommandOrAlias::Command(Arc::new(Command::new(f)))); } } @@ -633,10 +670,12 @@ impl BuiltinFramework { /// })); /// ``` pub fn command<F, S>(mut self, command_name: S, f: F) -> Self - where F: FnOnce(CreateCommand) -> CreateCommand, - S: Into<String> { + where + F: FnOnce(CreateCommand) -> CreateCommand, + S: Into<String>, { { - let ungrouped = self.groups.entry("Ungrouped".to_owned()) + let ungrouped = self.groups + .entry("Ungrouped".to_owned()) .or_insert_with(|| Arc::new(CommandGroup::default())); if let Some(ref mut group) = Arc::get_mut(ungrouped) { @@ -645,15 +684,22 @@ impl BuiltinFramework { if let Some(ref prefix) = group.prefix { for v in &cmd.aliases { - group.commands.insert(format!("{} {}", prefix, v.to_owned()), CommandOrAlias::Alias(format!("{} {}", prefix, name))); + group + .commands + .insert(format!("{} {}", prefix, v.to_owned()), + CommandOrAlias::Alias(format!("{} {}", prefix, name))); } } else { for v in &cmd.aliases { - group.commands.insert(v.to_owned(), CommandOrAlias::Alias(name.clone())); + group + .commands + .insert(v.to_owned(), CommandOrAlias::Alias(name.clone())); } } - group.commands.insert(name, CommandOrAlias::Command(Arc::new(cmd))); + group + .commands + .insert(name, CommandOrAlias::Command(Arc::new(cmd))); } } @@ -684,8 +730,9 @@ impl BuiltinFramework { /// .command("pong", |c| c.exec_str("ping!")))); /// ``` pub fn group<F, S>(mut self, group_name: S, f: F) -> Self - where F: FnOnce(CreateGroup) -> CreateGroup, - S: Into<String> { + where + F: FnOnce(CreateGroup) -> CreateGroup, + S: Into<String>, { let group = f(CreateGroup(CommandGroup::default())).0; self.groups.insert(group_name.into(), Arc::new(group)); @@ -694,7 +741,8 @@ impl BuiltinFramework { self } - /// Specify the function that's called in case a command wasn't executed for one reason or another. + /// Specify the function that's called in case a command wasn't executed for one reason or + /// another. /// /// DispatchError represents all possible fail conditions. /// @@ -729,7 +777,8 @@ impl BuiltinFramework { /// })); /// ``` pub fn on_dispatch_error<F>(mut self, f: F) -> Self - where F: Fn(Context, Message, DispatchError) + 'static { + where + F: Fn(Context, Message, DispatchError) + 'static, { self.dispatch_error_handler = Some(Arc::new(f)); self @@ -785,7 +834,8 @@ impl BuiltinFramework { /// ``` /// pub fn before<F>(mut self, f: F) -> Self - where F: Fn(&mut Context, &Message, &String) -> bool + 'static { + where + F: Fn(&mut Context, &Message, &String) -> bool + 'static, { self.before = Some(Arc::new(f)); self @@ -816,7 +866,8 @@ impl BuiltinFramework { /// })); /// ``` pub fn after<F>(mut self, f: F) -> Self - where F: Fn(&mut Context, &Message, &String, Result<(), String>) + 'static { + where + F: Fn(&mut Context, &Message, &String, Result<(), String>) + 'static, { self.after = Some(Arc::new(f)); self @@ -846,12 +897,8 @@ impl ::Framework for BuiltinFramework { 'outer: for position in positions { let mut built = String::new(); - let round = message.content.chars() - .skip(position) - .collect::<String>(); - let round = round.trim() - .split_whitespace() - .collect::<Vec<&str>>(); + let round = message.content.chars().skip(position).collect::<String>(); + let round = round.trim().split_whitespace().collect::<Vec<&str>>(); for i in 0..self.configuration.depth { if i != 0 { @@ -859,16 +906,17 @@ impl ::Framework for BuiltinFramework { } built.push_str(match round.get(i) { - Some(piece) => piece, - None => continue 'outer, - }); + Some(piece) => piece, + None => continue 'outer, + }); let groups = self.groups.clone(); for group in groups.values() { let command_length = built.len(); - if let Some(&CommandOrAlias::Alias(ref points_to)) = group.commands.get(&built) { + if let Some(&CommandOrAlias::Alias(ref points_to)) = + group.commands.get(&built) { built = points_to.to_owned(); } @@ -882,7 +930,8 @@ impl ::Framework for BuiltinFramework { built.clone() }; - if let Some(&CommandOrAlias::Command(ref command)) = group.commands.get(&to_check) { + if let Some(&CommandOrAlias::Command(ref command)) = + group.commands.get(&to_check) { let before = self.before.clone(); let command = command.clone(); let after = self.after.clone(); @@ -901,7 +950,12 @@ impl ::Framework for BuiltinFramework { } }; - if let Some(error) = self.should_fail(&mut context, &message, &command, args.len(), &to_check, &built) { + if let Some(error) = self.should_fail(&mut context, + &message, + &command, + args.len(), + &to_check, + &built) { if let Some(ref handler) = self.dispatch_error_handler { handler(context, message, error); } @@ -921,12 +975,10 @@ impl ::Framework for BuiltinFramework { Ok(()) }, - CommandType::Basic(ref x) => { - (x)(&mut context, &message, args) - }, + CommandType::Basic(ref x) => (x)(&mut context, &message, args), CommandType::WithCommands(ref x) => { (x)(&mut context, &message, groups, &args) - } + }, }; if let Some(after) = after { @@ -943,13 +995,11 @@ impl ::Framework for BuiltinFramework { } } - #[cfg(feature="builtin_framework")] + #[cfg(feature = "builtin_framework")] fn update_current_user(&mut self, user_id: UserId, is_bot: bool) { self.user_info = (user_id.0, is_bot); } - #[cfg(feature="builtin_framework")] - fn initialized(&self) -> bool { - self.initialized - } -}
\ No newline at end of file + #[cfg(feature = "builtin_framework")] + fn initialized(&self) -> bool { self.initialized } +} diff --git a/src/gateway/error.rs b/src/gateway/error.rs index 2e96252..b75c5d4 100644 --- a/src/gateway/error.rs +++ b/src/gateway/error.rs @@ -47,9 +47,7 @@ pub enum Error { } impl Display for Error { - fn fmt(&self, f: &mut Formatter) -> FmtResult { - f.write_str(self.description()) - } + fn fmt(&self, f: &mut Formatter) -> FmtResult { f.write_str(self.description()) } } impl StdError for Error { diff --git a/src/gateway/shard.rs b/src/gateway/shard.rs index 473c17b..af7d5d1 100644 --- a/src/gateway/shard.rs +++ b/src/gateway/shard.rs @@ -12,22 +12,22 @@ use websocket::stream::sync::AsTcpStream; use websocket::sync::client::{Client, ClientBuilder}; use websocket::sync::stream::{TcpStream, TlsStream}; use websocket::WebSocketError; -use ::constants::{self, OpCode, close_codes}; -use ::internal::prelude::*; -use ::internal::ws_impl::SenderExt; -use ::model::event::{Event, GatewayEvent}; -use ::model::{Game, GuildId, OnlineStatus}; +use constants::{self, close_codes, OpCode}; +use internal::prelude::*; +use internal::ws_impl::SenderExt; +use model::event::{Event, GatewayEvent}; +use model::{Game, GuildId, OnlineStatus}; -#[cfg(feature="voice")] +#[cfg(feature = "voice")] use std::sync::mpsc::{self, Receiver as MpscReceiver}; -#[cfg(feature="cache")] -use ::client::CACHE; -#[cfg(feature="voice")] -use ::ext::voice::Manager as VoiceManager; -#[cfg(feature="voice")] -use ::http; -#[cfg(feature="cache")] -use ::utils; +#[cfg(feature = "cache")] +use client::CACHE; +#[cfg(feature = "voice")] +use ext::voice::Manager as VoiceManager; +#[cfg(feature = "voice")] +use http; +#[cfg(feature = "cache")] +use utils; pub type WsClient = Client<TlsStream<TcpStream>>; @@ -93,9 +93,9 @@ pub struct Shard { ws_url: Arc<Mutex<String>>, /// The voice connections that this Shard is responsible for. The Shard will /// update the voice connections' states. - #[cfg(feature="voice")] + #[cfg(feature = "voice")] pub manager: VoiceManager, - #[cfg(feature="voice")] + #[cfg(feature = "voice")] manager_rx: MpscReceiver<Value>, } @@ -200,9 +200,7 @@ impl Shard { /// # /// assert_eq!(shard.shard_info(), [1, 2]); /// ``` - pub fn shard_info(&self) -> [u64; 2] { - self.shard_info - } + pub fn shard_info(&self) -> [u64; 2] { self.shard_info } /// Sets whether the current user is afk. This helps Discord determine where /// to send notifications. @@ -296,12 +294,10 @@ impl Shard { /// # /// use serenity::model::{Game, OnlineStatus}; /// - /// shard.set_presence(Some(Game::playing("Heroes of the Storm")), OnlineStatus::Online, false); + /// shard.set_presence(Some(Game::playing("Heroes of the Storm")), OnlineStatus::Online, + /// false); /// ``` - pub fn set_presence(&mut self, - game: Option<Game>, - mut status: OnlineStatus, - afk: bool) { + pub fn set_presence(&mut self, game: Option<Game>, mut status: OnlineStatus, afk: bool) { if status == OnlineStatus::Offline { status = OnlineStatus::Invisible; } @@ -351,11 +347,9 @@ impl Shard { self.stage = ConnectionStage::Connected; }, - ref _other => { - #[cfg(feature="voice")] - { - self.voice_dispatch(_other); - } + ref _other => #[cfg(feature = "voice")] + { + self.voice_dispatch(_other); }, } @@ -423,9 +417,7 @@ impl Shard { Ok(None) }, - Ok(GatewayEvent::Reconnect) => { - self.reconnect().and(Ok(None)) - }, + Ok(GatewayEvent::Reconnect) => self.reconnect().and(Ok(None)), Err(Error::Gateway(GatewayError::Closed(data))) => { let num = data.as_ref().map(|d| d.status_code); let reason = data.map(|d| d.reason); @@ -486,7 +478,8 @@ impl Shard { } let resume = num.map(|x| { - x != 1000 && x != close_codes::AUTHENTICATION_FAILED && self.session_id.is_some() + x != 1000 && x != close_codes::AUTHENTICATION_FAILED && + self.session_id.is_some() }).unwrap_or(false); if resume { @@ -521,7 +514,7 @@ impl Shard { /// ```rust,no_run /// # use serenity::prelude::*; /// # use serenity::model::*; - /// struct Handler; + /// struct Handler; /// /// impl EventHandler for Handler { /// fn on_message(&self, ctx: Context, msg: Message) { @@ -556,9 +549,9 @@ impl Shard { pub fn shutdown_clean(&mut self) -> Result<()> { { let message = OwnedMessage::Close(Some(CloseData { - status_code: 1000, - reason: String::new(), - })); + status_code: 1000, + reason: String::new(), + })); self.client.send_message(&message)?; } @@ -634,7 +627,8 @@ impl Shard { /// shard.chunk_guilds(&guild_ids, Some(20), Some("do")); /// ``` /// - /// [`Event::GuildMembersChunk`]: ../../model/event/enum.Event.html#variant.GuildMembersChunk + /// [`Event::GuildMembersChunk`]: + /// ../../model/event/enum.Event.html#variant.GuildMembersChunk /// [`Guild`]: ../../model/struct.Guild.html /// [`Member`]: ../../model/struct.Member.html pub fn chunk_guilds(&mut self, guild_ids: &[GuildId], limit: Option<u16>, query: Option<&str>) { @@ -677,19 +671,20 @@ impl Shard { /// /// [`Cache`]: ../ext/cache/struct.Cache.html /// [`Guild`]: ../model/struct.Guild.html - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn guilds_handled(&self) -> u16 { let cache = CACHE.read().unwrap(); let (shard_id, shard_count) = (self.shard_info[0], self.shard_info[1]); - cache.guilds + cache + .guilds .keys() .filter(|guild_id| utils::shard_id(guild_id.0, shard_count) == shard_id) .count() as u16 } - #[cfg(feature="voice")] + #[cfg(feature = "voice")] fn voice_dispatch(&mut self, event: &Event) { if let Event::VoiceStateUpdate(ref update) = *event { if let Some(guild_id) = update.guild_id { @@ -708,7 +703,7 @@ impl Shard { } } - #[cfg(feature="voice")] + #[cfg(feature = "voice")] pub(crate) fn cycle_voice_recv(&mut self) { if let Ok(v) = self.manager_rx.try_recv() { if let Err(why) = self.client.send_json(&v) { @@ -776,7 +771,7 @@ impl Shard { why); why - }) + }); } // Otherwise, we're good to heartbeat. @@ -809,15 +804,11 @@ impl Shard { /// Retrieves the `heartbeat_interval`. #[inline] - pub(crate) fn heartbeat_interval(&self) -> Option<u64> { - self.heartbeat_interval - } + pub(crate) fn heartbeat_interval(&self) -> Option<u64> { self.heartbeat_interval } /// Retrieves the value of when the last heartbeat ack was received. #[inline] - pub(crate) fn last_heartbeat_ack(&self) -> Option<Instant> { - self.heartbeat_instants.1 - } + pub(crate) fn last_heartbeat_ack(&self) -> Option<Instant> { self.heartbeat_instants.1 } fn reconnect(&mut self) -> Result<()> { info!("[Shard {:?}] Attempting to reconnect", self.shard_info); @@ -913,7 +904,7 @@ impl Shard { warn!("[Shard {:?}] Err sending presence update: {:?}", self.shard_info, why); } - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let mut cache = CACHE.write().unwrap(); let current_user_id = cache.user.id; @@ -935,7 +926,8 @@ fn connect(base_url: &str) -> Result<WsClient> { fn set_client_timeout(client: &mut WsClient) -> Result<()> { let stream = client.stream_ref().as_tcp(); - stream.set_read_timeout(Some(StdDuration::from_millis(100)))?; + stream + .set_read_timeout(Some(StdDuration::from_millis(100)))?; stream.set_write_timeout(Some(StdDuration::from_secs(5)))?; Ok(()) diff --git a/src/http/error.rs b/src/http/error.rs index 8e68c44..6e51358 100644 --- a/src/http/error.rs +++ b/src/http/error.rs @@ -18,9 +18,7 @@ pub enum Error { } impl Display for Error { - fn fmt(&self, f: &mut Formatter) -> FmtResult { - f.write_str(self.description()) - } + fn fmt(&self, f: &mut Formatter) -> FmtResult { f.write_str(self.description()) } } impl StdError for Error { diff --git a/src/http/mod.rs b/src/http/mod.rs index 850f800..fcf2331 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -30,17 +30,12 @@ mod error; pub use self::error::Error as HttpError; pub use hyper::status::{StatusClass, StatusCode}; -use hyper::client::{ - Client as HyperClient, - RequestBuilder, - Response as HyperResponse, - Request, -}; +use hyper::client::{Client as HyperClient, Request, RequestBuilder, Response as HyperResponse}; use hyper::header::ContentType; use hyper::method::Method; use hyper::mime::{Mime, SubLevel, TopLevel}; use hyper::net::HttpsConnector; -use hyper::{Error as HyperError, Result as HyperResult, Url, header}; +use hyper::{header, Error as HyperError, Result as HyperResult, Url}; use hyper_native_tls::NativeTlsClient; use multipart::client::Multipart; use self::ratelimiting::Route; @@ -52,9 +47,9 @@ use std::fs::File; use std::io::{ErrorKind as IoErrorKind, Read}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; -use ::constants; -use ::internal::prelude::*; -use ::model::*; +use constants; +use internal::prelude::*; +use model::*; /// An method used for ratelimiting special routes. /// @@ -84,9 +79,7 @@ lazy_static! { /// This is intended for internal use! The only exception are webhooks. /// But really, please don't use this. #[doc(hidden)] -pub fn set_token(token: &str) { - TOKEN.lock().unwrap().clone_from(&token.to_owned()); -} +pub fn set_token(token: &str) { TOKEN.lock().unwrap().clone_from(&token.to_owned()); } /// Adds a [`User`] as a recipient to a [`Group`]. /// @@ -96,11 +89,12 @@ pub fn set_token(token: &str) { /// [`Group::add_recipient`]: ../model/struct.Group.html#method.add_recipient /// [`User`]: ../model/struct.User.html pub fn add_group_recipient(group_id: u64, user_id: u64) -> Result<()> { - verify(204, request!(Route::None, - put, - "/channels/{}/recipients/{}", - group_id, - user_id)) + verify(204, + request!(Route::None, + put, + "/channels/{}/recipients/{}", + group_id, + user_id)) } /// Adds a single [`Role`] to a [`Member`] in a [`Guild`]. @@ -113,12 +107,13 @@ pub fn add_group_recipient(group_id: u64, user_id: u64) -> Result<()> { /// [`Role`]: ../model/struct.Role.html /// [Manage Roles]: ../model/permissions/constant.MANAGE_ROLES.html pub fn add_member_role(guild_id: u64, user_id: u64, role_id: u64) -> Result<()> { - verify(204, request!(Route::GuildsIdMembersIdRolesId(guild_id), - put, - "/guilds/{}/members/{}/roles/{}", - guild_id, - user_id, - role_id)) + verify(204, + request!(Route::GuildsIdMembersIdRolesId(guild_id), + put, + "/guilds/{}/members/{}/roles/{}", + guild_id, + user_id, + role_id)) } /// Bans a [`User`] from a [`Guild`], removing their messages sent in the last @@ -133,13 +128,14 @@ pub fn add_member_role(guild_id: u64, user_id: u64, role_id: u64) -> Result<()> /// [`User`]: ../model/struct.User.html /// [Ban Members]: ../model/permissions/constant.BAN_MEMBERS.html pub fn ban_user(guild_id: u64, user_id: u64, delete_message_days: u8, reason: &str) -> Result<()> { - verify(204, request!(Route::GuildsIdBansUserId(guild_id), - put, - "/guilds/{}/bans/{}?delete_message_days={}&reason={}", - guild_id, - user_id, - delete_message_days, - reason)) + verify(204, + request!(Route::GuildsIdBansUserId(guild_id), + put, + "/guilds/{}/bans/{}?delete_message_days={}&reason={}", + guild_id, + user_id, + delete_message_days, + reason)) } /// Broadcasts that the current user is typing in the given [`Channel`]. @@ -152,10 +148,11 @@ pub fn ban_user(guild_id: u64, user_id: u64, delete_message_days: u8, reason: &s /// /// [`Channel`]: ../model/enum.Channel.html pub fn broadcast_typing(channel_id: u64) -> Result<()> { - verify(204, request!(Route::ChannelsIdTyping(channel_id), - post, - "/channels/{}/typing", - channel_id)) + verify(204, + request!(Route::ChannelsIdTyping(channel_id), + post, + "/channels/{}/typing", + channel_id)) } /// Creates a [`GuildChannel`] in the [`Guild`] given its Id. @@ -231,7 +228,8 @@ pub fn create_emoji(guild_id: u64, map: &Value) -> Result<Emoji> { /// [`Shard`]: ../gateway/struct.Shard.html /// [GameBridge]: https://discordapp.com/developers/docs/topics/gamebridge /// [US West Region]: ../model/enum.Region.html#variant.UsWest -/// [documentation on this endpoint]: https://discordapp.com/developers/docs/resources/guild#create-guild +/// [documentation on this endpoint]: +/// https://discordapp.com/developers/docs/resources/guild#create-guild /// [whitelist]: https://discordapp.com/developers/docs/resources/guild#create-guild pub fn create_guild(map: &Value) -> Result<PartialGuild> { let body = map.to_string(); @@ -253,11 +251,12 @@ pub fn create_guild(map: &Value) -> Result<PartialGuild> { pub fn create_guild_integration(guild_id: u64, integration_id: u64, map: &Value) -> Result<()> { let body = map.to_string(); - verify(204, request!(Route::GuildsIdIntegrations(guild_id), - post(body), - "/guilds/{}/integrations/{}", - guild_id, - integration_id)) + verify(204, + request!(Route::GuildsIdIntegrations(guild_id), + post(body), + "/guilds/{}/integrations/{}", + guild_id, + integration_id)) } /// Creates a [`RichInvite`] for the given [channel][`GuildChannel`]. @@ -286,19 +285,18 @@ pub fn create_invite(channel_id: u64, map: &JsonMap) -> Result<RichInvite> { pub fn create_permission(channel_id: u64, target_id: u64, map: &Value) -> Result<()> { let body = map.to_string(); - verify(204, request!(Route::ChannelsIdPermissionsOverwriteId(channel_id), - put(body), - "/channels/{}/permissions/{}", - channel_id, - target_id)) + verify(204, + request!(Route::ChannelsIdPermissionsOverwriteId(channel_id), + put(body), + "/channels/{}/permissions/{}", + channel_id, + target_id)) } /// Creates a private channel with a user. pub fn create_private_channel(map: &Value) -> Result<PrivateChannel> { let body = map.to_string(); - let response = request!(Route::UsersMeChannels, - post(body), - "/users/@me/channels"); + let response = request!(Route::UsersMeChannels, post(body), "/users/@me/channels"); serde_json::from_reader::<HyperResponse, PrivateChannel>(response).map_err(From::from) } @@ -308,12 +306,13 @@ pub fn create_reaction(channel_id: u64, message_id: u64, reaction_type: &ReactionType) -> Result<()> { - verify(204, request!(Route::ChannelsIdMessagesIdReactionsUserIdType(channel_id), - put, - "/channels/{}/messages/{}/reactions/{}/@me", - channel_id, - message_id, - reaction_type.as_data())) + verify(204, + request!(Route::ChannelsIdMessagesIdReactionsUserIdType(channel_id), + put, + "/channels/{}/messages/{}/reactions/{}/@me", + channel_id, + message_id, + reaction_type.as_data())) } /// Creates a role. @@ -379,30 +378,29 @@ pub fn delete_channel(channel_id: u64) -> Result<Channel> { /// Deletes an emoji from a server. pub fn delete_emoji(guild_id: u64, emoji_id: u64) -> Result<()> { - verify(204, request!(Route::GuildsIdEmojisId(guild_id), - delete, - "/guilds/{}/emojis/{}", - guild_id, - emoji_id)) + verify(204, + request!(Route::GuildsIdEmojisId(guild_id), + delete, + "/guilds/{}/emojis/{}", + guild_id, + emoji_id)) } /// Deletes a guild, only if connected account owns it. pub fn delete_guild(guild_id: u64) -> Result<PartialGuild> { - let response = request!(Route::GuildsId(guild_id), - delete, - "/guilds/{}", - guild_id); + let response = request!(Route::GuildsId(guild_id), delete, "/guilds/{}", guild_id); serde_json::from_reader::<HyperResponse, PartialGuild>(response).map_err(From::from) } /// Remvoes an integration from a guild. pub fn delete_guild_integration(guild_id: u64, integration_id: u64) -> Result<()> { - verify(204, request!(Route::GuildsIdIntegrationsId(guild_id), - delete, - "/guilds/{}/integrations/{}", - guild_id, - integration_id)) + verify(204, + request!(Route::GuildsIdIntegrationsId(guild_id), + delete, + "/guilds/{}/integrations/{}", + guild_id, + integration_id)) } /// Deletes an invite by code. @@ -415,21 +413,23 @@ pub fn delete_invite(code: &str) -> Result<Invite> { /// Deletes a message if created by us or we have /// specific permissions. pub fn delete_message(channel_id: u64, message_id: u64) -> Result<()> { - verify(204, request!(Route::ChannelsIdMessagesId(LightMethod::Delete, channel_id), - delete, - "/channels/{}/messages/{}", - channel_id, - message_id)) + verify(204, + request!(Route::ChannelsIdMessagesId(LightMethod::Delete, channel_id), + delete, + "/channels/{}/messages/{}", + channel_id, + message_id)) } /// Deletes a bunch of messages, only works for bots. pub fn delete_messages(channel_id: u64, map: &Value) -> Result<()> { let body = map.to_string(); - verify(204, request!(Route::ChannelsIdMessagesBulkDelete(channel_id), - post(body), - "/channels/{}/messages/bulk_delete", - channel_id)) + verify(204, + request!(Route::ChannelsIdMessagesBulkDelete(channel_id), + post(body), + "/channels/{}/messages/bulk_delete", + channel_id)) } /// Deletes all of the [`Reaction`]s associated with a [`Message`]. @@ -450,20 +450,22 @@ pub fn delete_messages(channel_id: u64, map: &Value) -> Result<()> { /// [`Message`]: ../model/struct.Message.html /// [`Reaction`]: ../model/struct.Reaction.html pub fn delete_message_reactions(channel_id: u64, message_id: u64) -> Result<()> { - verify(204, request!(Route::ChannelsIdMessagesIdReactions(channel_id), - delete, - "/channels/{}/messages/{}/reactions", - channel_id, - message_id)) + verify(204, + request!(Route::ChannelsIdMessagesIdReactions(channel_id), + delete, + "/channels/{}/messages/{}/reactions", + channel_id, + message_id)) } /// Deletes a permission override from a role or a member in a channel. pub fn delete_permission(channel_id: u64, target_id: u64) -> Result<()> { - verify(204, request!(Route::ChannelsIdPermissionsOverwriteId(channel_id), - delete, - "/channels/{}/permissions/{}", - channel_id, - target_id)) + verify(204, + request!(Route::ChannelsIdPermissionsOverwriteId(channel_id), + delete, + "/channels/{}/permissions/{}", + channel_id, + target_id)) } /// Deletes a reaction from a message if owned by us or @@ -473,24 +475,28 @@ pub fn delete_reaction(channel_id: u64, user_id: Option<u64>, reaction_type: &ReactionType) -> Result<()> { - let user = user_id.map(|uid| uid.to_string()).unwrap_or_else(|| "@me".to_string()); + let user = user_id + .map(|uid| uid.to_string()) + .unwrap_or_else(|| "@me".to_string()); - verify(204, request!(Route::ChannelsIdMessagesIdReactionsUserIdType(channel_id), - delete, - "/channels/{}/messages/{}/reactions/{}/{}", - channel_id, - message_id, - reaction_type.as_data(), - user)) + verify(204, + request!(Route::ChannelsIdMessagesIdReactionsUserIdType(channel_id), + delete, + "/channels/{}/messages/{}/reactions/{}/{}", + channel_id, + message_id, + reaction_type.as_data(), + user)) } /// Deletes a role from a server. Can't remove the default everyone role. pub fn delete_role(guild_id: u64, role_id: u64) -> Result<()> { - verify(204, request!(Route::GuildsIdRolesId(guild_id), - delete, - "/guilds/{}/roles/{}", - guild_id, - role_id)) + verify(204, + request!(Route::GuildsIdRolesId(guild_id), + delete, + "/guilds/{}/roles/{}", + guild_id, + role_id)) } /// Deletes a [`Webhook`] given its Id. @@ -516,7 +522,8 @@ pub fn delete_role(guild_id: u64, role_id: u64) -> Result<()> { /// [`Webhook`]: ../model/struct.Webhook.html /// [`delete_webhook_with_token`]: fn.delete_webhook_with_token.html pub fn delete_webhook(webhook_id: u64) -> Result<()> { - verify(204, request!(Route::WebhooksId, delete, "/webhooks/{}", webhook_id)) + verify(204, + request!(Route::WebhooksId, delete, "/webhooks/{}", webhook_id)) } /// Deletes a [`Webhook`] given its Id and unique token. @@ -540,9 +547,9 @@ pub fn delete_webhook(webhook_id: u64) -> Result<()> { pub fn delete_webhook_with_token(webhook_id: u64, token: &str) -> Result<()> { let client = request_client!(); - verify(204, retry(|| client - .delete(&format!(api!("/webhooks/{}/{}"), webhook_id, token))) - .map_err(Error::Hyper)?) + verify(204, + retry(|| client.delete(&format!(api!("/webhooks/{}/{}"), webhook_id, token))) + .map_err(Error::Hyper)?) } /// Changes channel information. @@ -596,11 +603,12 @@ pub fn edit_guild_embed(guild_id: u64, map: &Value) -> Result<GuildEmbed> { pub fn edit_member(guild_id: u64, user_id: u64, map: &JsonMap) -> Result<()> { let body = serde_json::to_string(map)?; - verify(204, request!(Route::GuildsIdMembersId(guild_id), - patch(body), - "/guilds/{}/members/{}", - guild_id, - user_id)) + verify(204, + request!(Route::GuildsIdMembersId(guild_id), + patch(body), + "/guilds/{}/members/{}", + guild_id, + user_id)) } /// Edits a message by Id. @@ -623,9 +631,7 @@ pub fn edit_message(channel_id: u64, message_id: u64, map: &Value) -> Result<Mes /// /// [`Guild`]: ../model/struct.Guild.html pub fn edit_nickname(guild_id: u64, new_nickname: Option<&str>) -> Result<()> { - let map = json!({ - "nick": new_nickname - }); + let map = json!({ "nick": new_nickname }); let body = map.to_string(); let response = request!(Route::GuildsIdMembersMeNick(guild_id), patch(body), @@ -717,10 +723,7 @@ pub fn edit_role(guild_id: u64, role_id: u64, map: &JsonMap) -> Result<Role> { // external crates being incredibly messy and misleading in the end user's view. pub fn edit_webhook(webhook_id: u64, map: &Value) -> Result<Webhook> { let body = map.to_string(); - let response = request!(Route::WebhooksId, - patch(body), - "/webhooks/{}", - webhook_id); + let response = request!(Route::WebhooksId, patch(body), "/webhooks/{}", webhook_id); serde_json::from_reader::<HyperResponse, Webhook>(response).map_err(From::from) } @@ -755,10 +758,11 @@ pub fn edit_webhook_with_token(webhook_id: u64, token: &str, map: &JsonMap) -> R let body = serde_json::to_string(map)?; let client = request_client!(); - let response = retry(|| client - .patch(&format!(api!("/webhooks/{}/{}"), webhook_id, token)) - .body(&body)) - .map_err(Error::Hyper)?; + let response = retry(|| { + client + .patch(&format!(api!("/webhooks/{}/{}"), webhook_id, token)) + .body(&body) + }).map_err(Error::Hyper)?; serde_json::from_reader::<HyperResponse, Webhook>(response).map_err(From::from) } @@ -823,23 +827,29 @@ pub fn edit_webhook_with_token(webhook_id: u64, token: &str, map: &JsonMap) -> R /// [`Channel`]: ../model/enum.Channel.html /// [`Message`]: ../model/struct.Message.html /// [Discord docs]: https://discordapp.com/developers/docs/resources/webhook#querystring-params -pub fn execute_webhook(webhook_id: u64, token: &str, wait: bool, map: &JsonMap) - -> Result<Option<Message>> { +pub fn execute_webhook(webhook_id: u64, + token: &str, + wait: bool, + map: &JsonMap) + -> Result<Option<Message>> { let body = serde_json::to_string(map)?; let client = request_client!(); - let response = retry(|| client - .post(&format!(api!("/webhooks/{}/{}?wait={}"), webhook_id, token, wait)) - .body(&body) - .header(ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![])))) - .map_err(Error::Hyper)?; + let response = retry(|| { + client + .post(&format!(api!("/webhooks/{}/{}?wait={}"), webhook_id, token, wait)) + .body(&body) + .header(ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![]))) + }).map_err(Error::Hyper)?; if response.status == StatusCode::NoContent { return Ok(None); } - serde_json::from_reader::<HyperResponse, Message>(response).map(Some).map_err(From::from) + serde_json::from_reader::<HyperResponse, Message>(response) + .map(Some) + .map_err(From::from) } /// Gets the active maintenances from Discord's Status API. @@ -848,8 +858,7 @@ pub fn execute_webhook(webhook_id: u64, token: &str, wait: bool, map: &JsonMap) pub fn get_active_maintenances() -> Result<Vec<Maintenance>> { let client = request_client!(); - let response = retry(|| client.get( - status!("/scheduled-maintenances/active.json")))?; + let response = retry(|| client.get(status!("/scheduled-maintenances/active.json")))?; let mut map: BTreeMap<String, Value> = serde_json::from_reader(response)?; @@ -1007,10 +1016,7 @@ pub fn get_emojis(guild_id: u64) -> Result<Vec<Emoji>> { /// Gets guild information. pub fn get_guild(guild_id: u64) -> Result<PartialGuild> { - let response = request!(Route::GuildsId(guild_id), - get, - "/guilds/{}", - guild_id); + let response = request!(Route::GuildsId(guild_id), get, "/guilds/{}", guild_id); serde_json::from_reader::<HyperResponse, PartialGuild>(response).map_err(From::from) } @@ -1047,8 +1053,10 @@ pub fn get_guild_invites(guild_id: u64) -> Result<Vec<RichInvite>> { /// Gets the members of a guild. Optionally pass a `limit` and the Id of the /// user to offset the result by. -pub fn get_guild_members(guild_id: u64, limit: Option<u64>, after: Option<u64>) - -> Result<Vec<Member>> { +pub fn get_guild_members(guild_id: u64, + limit: Option<u64>, + after: Option<u64>) + -> Result<Vec<Member>> { let response = request!(Route::GuildsIdMembers(guild_id), get, "/guilds/{}/members?limit={}&after={}", @@ -1176,7 +1184,7 @@ pub fn get_guilds(target: &GuildPagination, limit: u64) -> Result<Vec<GuildInfo> pub fn get_invite(code: &str, stats: bool) -> Result<Invite> { let mut invite = code; - #[cfg(feature="utils")] + #[cfg(feature = "utils")] { invite = ::utils::parse_invite(invite); } @@ -1221,15 +1229,11 @@ pub fn get_message(channel_id: u64, message_id: u64) -> Result<Message> { } /// Gets X messages from a channel. -pub fn get_messages(channel_id: u64, query: &str) - -> Result<Vec<Message>> { - let url = format!(api!("/channels/{}/messages{}"), - channel_id, - query); +pub fn get_messages(channel_id: u64, query: &str) -> Result<Vec<Message>> { + let url = format!(api!("/channels/{}/messages{}"), channel_id, query); let client = request_client!(); - let response = request(Route::ChannelsIdMessages(channel_id), - || client.get(&url))?; + let response = request(Route::ChannelsIdMessages(channel_id), || client.get(&url))?; serde_json::from_reader::<HyperResponse, Vec<Message>>(response).map_err(From::from) } @@ -1252,10 +1256,10 @@ pub fn get_reaction_users(channel_id: u64, after: Option<u64>) -> Result<Vec<User>> { let mut uri = format!("/channels/{}/messages/{}/reactions/{}?limit={}", - channel_id, - message_id, - reaction_type.as_data(), - limit); + channel_id, + message_id, + reaction_type.as_data(), + limit); if let Some(user_id) = after { write!(uri, "&after={}", user_id)?; @@ -1275,8 +1279,7 @@ pub fn get_reaction_users(channel_id: u64, pub fn get_unresolved_incidents() -> Result<Vec<Incident>> { let client = request_client!(); - let response = retry(|| client.get( - status!("/incidents/unresolved.json")))?; + let response = retry(|| client.get(status!("/incidents/unresolved.json")))?; let mut map: BTreeMap<String, Value> = serde_json::from_reader(response)?; @@ -1292,8 +1295,7 @@ pub fn get_unresolved_incidents() -> Result<Vec<Incident>> { pub fn get_upcoming_maintenances() -> Result<Vec<Maintenance>> { let client = request_client!(); - let response = retry(|| client.get( - status!("/scheduled-maintenances/upcoming.json")))?; + let response = retry(|| client.get(status!("/scheduled-maintenances/upcoming.json")))?; let mut map: BTreeMap<String, Value> = serde_json::from_reader(response)?; @@ -1367,8 +1369,7 @@ pub fn get_webhook(webhook_id: u64) -> Result<Webhook> { pub fn get_webhook_with_token(webhook_id: u64, token: &str) -> Result<Webhook> { let client = request_client!(); - let response = retry(|| client - .get(&format!(api!("/webhooks/{}/{}"), webhook_id, token))) + let response = retry(|| client.get(&format!(api!("/webhooks/{}/{}"), webhook_id, token))) .map_err(Error::Hyper)?; serde_json::from_reader::<HyperResponse, Webhook>(response).map_err(From::from) @@ -1376,35 +1377,38 @@ pub fn get_webhook_with_token(webhook_id: u64, token: &str) -> Result<Webhook> { /// Kicks a member from a guild. pub fn kick_member(guild_id: u64, user_id: u64) -> Result<()> { - verify(204, request!(Route::GuildsIdMembersId(guild_id), - delete, - "/guilds/{}/members/{}", - guild_id, - user_id)) + verify(204, + request!(Route::GuildsIdMembersId(guild_id), + delete, + "/guilds/{}/members/{}", + guild_id, + user_id)) } /// Leaves a group DM. pub fn leave_group(guild_id: u64) -> Result<Group> { - let response = request!(Route::None, - delete, - "/channels/{}", - guild_id); + let response = request!(Route::None, delete, "/channels/{}", guild_id); serde_json::from_reader::<HyperResponse, Group>(response).map_err(From::from) } /// Leaves a guild. pub fn leave_guild(guild_id: u64) -> Result<()> { - verify(204, request!(Route::UsersMeGuildsId, delete, "/users/@me/guilds/{}", guild_id)) + verify(204, + request!(Route::UsersMeGuildsId, + delete, + "/users/@me/guilds/{}", + guild_id)) } /// Deletes a user from group DM. pub fn remove_group_recipient(group_id: u64, user_id: u64) -> Result<()> { - verify(204, request!(Route::None, - delete, - "/channels/{}/recipients/{}", - group_id, - user_id)) + verify(204, + request!(Route::None, + delete, + "/channels/{}/recipients/{}", + group_id, + user_id)) } /// Sends file(s) to a channel. @@ -1416,8 +1420,9 @@ pub fn remove_group_recipient(group_id: u64, user_id: u64) -> Result<()> { /// if the file is too large to send. /// /// [`HttpError::InvalidRequest`]: enum.HttpError.html#variant.InvalidRequest -pub fn send_files<'a, T>(channel_id: u64, files: Vec<T>, map: JsonMap) - -> Result<Message> where T: Into<AttachmentType<'a>> { +pub fn send_files<'a, T>(channel_id: u64, files: Vec<T>, map: JsonMap) -> Result<Message> +where + T: Into<AttachmentType<'a>>, { let uri = format!(api!("/channels/{}/messages"), channel_id); let url = match Url::parse(&uri) { Ok(url) => url, @@ -1427,9 +1432,11 @@ pub fn send_files<'a, T>(channel_id: u64, files: Vec<T>, map: JsonMap) let tc = NativeTlsClient::new()?; let connector = HttpsConnector::new(tc); let mut request = Request::with_connector(Method::Post, url, &connector)?; - request.headers_mut() + request + .headers_mut() .set(header::Authorization(TOKEN.lock().unwrap().clone())); - request.headers_mut() + request + .headers_mut() .set(header::UserAgent(constants::USER_AGENT.to_owned())); let mut request = Multipart::from_request(request)?; @@ -1438,10 +1445,12 @@ pub fn send_files<'a, T>(channel_id: u64, files: Vec<T>, map: JsonMap) for file in files { match file.into() { AttachmentType::Bytes((mut bytes, filename)) => { - request.write_stream(&file_num, &mut bytes, Some(filename), None)?; + request + .write_stream(&file_num, &mut bytes, Some(filename), None)?; }, AttachmentType::File((mut f, filename)) => { - request.write_stream(&file_num, &mut f, Some(filename), None)?; + request + .write_stream(&file_num, &mut f, Some(filename), None)?; }, AttachmentType::Path(p) => { request.write_file(&file_num, &p)?; @@ -1486,20 +1495,22 @@ pub fn send_message(channel_id: u64, map: &Value) -> Result<Message> { /// Pins a message in a channel. pub fn pin_message(channel_id: u64, message_id: u64) -> Result<()> { - verify(204, request!(Route::ChannelsIdPinsMessageId(channel_id), - put, - "/channels/{}/pins/{}", - channel_id, - message_id)) + verify(204, + request!(Route::ChannelsIdPinsMessageId(channel_id), + put, + "/channels/{}/pins/{}", + channel_id, + message_id)) } /// Unbans a user from a guild. pub fn remove_ban(guild_id: u64, user_id: u64) -> Result<()> { - verify(204, request!(Route::GuildsIdBansUserId(guild_id), - delete, - "/guilds/{}/bans/{}", - guild_id, - user_id)) + verify(204, + request!(Route::GuildsIdBansUserId(guild_id), + delete, + "/guilds/{}/bans/{}", + guild_id, + user_id)) } /// Deletes a single [`Role`] from a [`Member`] in a [`Guild`]. @@ -1512,12 +1523,13 @@ pub fn remove_ban(guild_id: u64, user_id: u64) -> Result<()> { /// [`Role`]: ../model/struct.Role.html /// [Manage Roles]: ../model/permissions/constant.MANAGE_ROLES.html pub fn remove_member_role(guild_id: u64, user_id: u64, role_id: u64) -> Result<()> { - verify(204, request!(Route::GuildsIdMembersIdRolesId(guild_id), - delete, - "/guilds/{}/members/{}/roles/{}", - guild_id, - user_id, - role_id)) + verify(204, + request!(Route::GuildsIdMembersIdRolesId(guild_id), + delete, + "/guilds/{}/members/{}/roles/{}", + guild_id, + user_id, + role_id)) } /// Starts removing some members from a guild based on the last time they've been online. @@ -1533,27 +1545,32 @@ pub fn start_guild_prune(guild_id: u64, map: &Value) -> Result<GuildPrune> { /// Starts syncing an integration with a guild. pub fn start_integration_sync(guild_id: u64, integration_id: u64) -> Result<()> { - verify(204, request!(Route::GuildsIdIntegrationsIdSync(guild_id), - post, - "/guilds/{}/integrations/{}/sync", - guild_id, - integration_id)) + verify(204, + request!(Route::GuildsIdIntegrationsIdSync(guild_id), + post, + "/guilds/{}/integrations/{}/sync", + guild_id, + integration_id)) } /// Unpins a message from a channel. pub fn unpin_message(channel_id: u64, message_id: u64) -> Result<()> { - verify(204, request!(Route::ChannelsIdPinsMessageId(channel_id), - delete, - "/channels/{}/pins/{}", - channel_id, - message_id)) + verify(204, + request!(Route::ChannelsIdPinsMessageId(channel_id), + delete, + "/channels/{}/pins/{}", + channel_id, + message_id)) } fn request<'a, F>(route: Route, f: F) -> Result<HyperResponse> - where F: Fn() -> RequestBuilder<'a> { - let response = ratelimiting::perform(route, || f() - .header(header::Authorization(TOKEN.lock().unwrap().clone())) - .header(header::ContentType::json()))?; +where + F: Fn() -> RequestBuilder<'a>, { + let response = ratelimiting::perform(route, || { + f() + .header(header::Authorization(TOKEN.lock().unwrap().clone())) + .header(header::ContentType::json()) + })?; if response.status.class() == StatusClass::Success { Ok(response) @@ -1563,14 +1580,16 @@ fn request<'a, F>(route: Route, f: F) -> Result<HyperResponse> } pub(crate) fn retry<'a, F>(f: F) -> HyperResult<HyperResponse> - where F: Fn() -> RequestBuilder<'a> { - let req = || f() - .header(header::UserAgent(constants::USER_AGENT.to_owned())) - .send(); +where + F: Fn() -> RequestBuilder<'a>, { + let req = || { + f() + .header(header::UserAgent(constants::USER_AGENT.to_owned())) + .send() + }; match req() { - Err(HyperError::Io(ref io)) - if io.kind() == IoErrorKind::ConnectionAborted => req(), + Err(HyperError::Io(ref io)) if io.kind() == IoErrorKind::ConnectionAborted => req(), other => other, } } @@ -1612,27 +1631,19 @@ pub enum AttachmentType<'a> { } impl<'a> From<(&'a [u8], &'a str)> for AttachmentType<'a> { - fn from(params: (&'a [u8], &'a str)) -> AttachmentType { - AttachmentType::Bytes(params) - } + fn from(params: (&'a [u8], &'a str)) -> AttachmentType { AttachmentType::Bytes(params) } } impl<'a> From<&'a str> for AttachmentType<'a> { - fn from(s: &'a str) -> AttachmentType { - AttachmentType::Path(Path::new(s)) - } + fn from(s: &'a str) -> AttachmentType { AttachmentType::Path(Path::new(s)) } } impl<'a> From<&'a PathBuf> for AttachmentType<'a> { - fn from(pathbuf: &'a PathBuf) -> AttachmentType { - AttachmentType::Path(pathbuf.as_path()) - } + fn from(pathbuf: &'a PathBuf) -> AttachmentType { AttachmentType::Path(pathbuf.as_path()) } } impl<'a> From<(&'a File, &'a str)> for AttachmentType<'a> { - fn from(f: (&'a File, &'a str)) -> AttachmentType<'a> { - AttachmentType::File((f.0, f.1)) - } + fn from(f: (&'a File, &'a str)) -> AttachmentType<'a> { AttachmentType::File((f.0, f.1)) } } /// Representation of the method of a query to send for the [`get_guilds`] diff --git a/src/http/ratelimiting.rs b/src/http/ratelimiting.rs index a5b7032..12066a9 100644 --- a/src/http/ratelimiting.rs +++ b/src/http/ratelimiting.rs @@ -47,9 +47,9 @@ use hyper::status::StatusCode; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Duration; -use std::{i64, str, thread}; +use std::{str, thread, i64}; use super::{HttpError, LightMethod}; -use ::internal::prelude::*; +use internal::prelude::*; lazy_static! { /// The global mutex is a mutex unlocked and then immediately re-locked @@ -346,7 +346,8 @@ pub enum Route { } pub(crate) fn perform<'a, F>(route: Route, f: F) -> Result<Response> - where F: Fn() -> RequestBuilder<'a> { +where + F: Fn() -> RequestBuilder<'a>, { loop { // This will block if another thread already has the global // unlocked already (due to receiving an x-ratelimit-global). @@ -364,11 +365,14 @@ pub(crate) fn perform<'a, F>(route: Route, f: F) -> Result<Response> .lock() .expect("routes poisoned") .entry(route) - .or_insert_with(|| Arc::new(Mutex::new(RateLimit { - limit: i64::MAX, - remaining: i64::MAX, - reset: i64::MAX, - }))).clone(); + .or_insert_with(|| { + Arc::new(Mutex::new(RateLimit { + limit: i64::MAX, + remaining: i64::MAX, + reset: i64::MAX, + })) + }) + .clone(); let mut lock = bucket.lock().unwrap(); lock.pre_hook(&route); @@ -395,13 +399,13 @@ pub(crate) fn perform<'a, F>(route: Route, f: F) -> Result<Response> let _ = GLOBAL.lock().expect("global route lock poisoned"); Ok(if let Some(retry_after) = parse_header(&response.headers, "retry-after")? { - debug!("Ratelimited on route {:?} for {:?}ms", route, retry_after); - thread::sleep(Duration::from_millis(retry_after as u64)); + debug!("Ratelimited on route {:?} for {:?}ms", route, retry_after); + thread::sleep(Duration::from_millis(retry_after as u64)); - true - } else { - false - }) + true + } else { + false + }) } else { lock.post_hook(&response, &route) }; @@ -458,7 +462,9 @@ impl RateLimit { if self.remaining == 0 { let delay = (diff * 1000) + 500; - debug!("Pre-emptive ratelimit on route {:?} for {:?}ms", route, delay); + debug!("Pre-emptive ratelimit on route {:?} for {:?}ms", + route, + delay); thread::sleep(Duration::from_millis(delay)); return; @@ -481,26 +487,30 @@ impl RateLimit { } Ok(if response.status != StatusCode::TooManyRequests { - false - } else if let Some(retry_after) = parse_header(&response.headers, "retry-after")? { - debug!("Ratelimited on route {:?} for {:?}ms", route, retry_after); - thread::sleep(Duration::from_millis(retry_after as u64)); + false + } else if let Some(retry_after) = parse_header(&response.headers, "retry-after")? { + debug!("Ratelimited on route {:?} for {:?}ms", route, retry_after); + thread::sleep(Duration::from_millis(retry_after as u64)); - true - } else { - false - }) + true + } else { + false + }) } } fn parse_header(headers: &Headers, header: &str) -> Result<Option<i64>> { match headers.get_raw(header) { - Some(header) => match str::from_utf8(&header[0]) { - Ok(v) => match v.parse::<i64>() { - Ok(v) => Ok(Some(v)), - Err(_) => Err(Error::Http(HttpError::RateLimitI64)), - }, - Err(_) => Err(Error::Http(HttpError::RateLimitUtf8)), + Some(header) => { + match str::from_utf8(&header[0]) { + Ok(v) => { + match v.parse::<i64>() { + Ok(v) => Ok(Some(v)), + Err(_) => Err(Error::Http(HttpError::RateLimitI64)), + } + }, + Err(_) => Err(Error::Http(HttpError::RateLimitUtf8)), + } }, None => Ok(None), } diff --git a/src/internal/macros.rs b/src/internal/macros.rs index c2475d1..7672316 100644 --- a/src/internal/macros.rs +++ b/src/internal/macros.rs @@ -66,7 +66,7 @@ macro_rules! status { } // Enable/disable check for cache -#[cfg(feature="cache")] +#[cfg(feature = "cache")] macro_rules! feature_cache { ($enabled:block else $disabled:block) => { { @@ -75,7 +75,7 @@ macro_rules! feature_cache { } } -#[cfg(not(feature="cache"))] +#[cfg(not(feature = "cache"))] macro_rules! feature_cache { ($enabled:block else $disabled:block) => { { @@ -85,7 +85,7 @@ macro_rules! feature_cache { } // Enable/disable check for framework -#[cfg(feature="framework")] +#[cfg(feature = "framework")] macro_rules! feature_framework { ($enabled:block else $disabled:block) => { { @@ -94,7 +94,7 @@ macro_rules! feature_framework { } } -#[cfg(not(feature="framework"))] +#[cfg(not(feature = "framework"))] macro_rules! feature_framework { ($enabled:block else $disabled:block) => { { @@ -104,7 +104,7 @@ macro_rules! feature_framework { } // Enable/disable check for voice -#[cfg(feature="voice")] +#[cfg(feature = "voice")] macro_rules! feature_voice { ($enabled:block else $disabled:block) => { { @@ -113,7 +113,7 @@ macro_rules! feature_voice { } } -#[cfg(not(feature="voice"))] +#[cfg(not(feature = "voice"))] macro_rules! feature_voice { ($enabled:block else $disabled:block) => { { diff --git a/src/internal/mod.rs b/src/internal/mod.rs index f0b65d8..2ff8067 100644 --- a/src/internal/mod.rs +++ b/src/internal/mod.rs @@ -3,11 +3,11 @@ pub mod macros; pub mod prelude; -#[cfg(feature="gateway")] +#[cfg(feature = "gateway")] pub mod ws_impl; -#[cfg(feature="voice")] +#[cfg(feature = "voice")] mod timer; -#[cfg(feature="voice")] +#[cfg(feature = "voice")] pub use self::timer::Timer; diff --git a/src/internal/prelude.rs b/src/internal/prelude.rs index e629322..21009d4 100644 --- a/src/internal/prelude.rs +++ b/src/internal/prelude.rs @@ -8,7 +8,7 @@ pub type JsonMap = Map<String, Value>; pub use serde_json::{Map, Number, Value}; pub use std::result::Result as StdResult; -pub use ::error::{Error, Result}; +pub use error::{Error, Result}; -#[cfg(feature="client")] -pub use ::client::ClientError; +#[cfg(feature = "client")] +pub use client::ClientError; diff --git a/src/internal/timer.rs b/src/internal/timer.rs index 1b51dda..0bd0d13 100644 --- a/src/internal/timer.rs +++ b/src/internal/timer.rs @@ -46,7 +46,5 @@ impl Timer { } } - pub fn reset(&mut self) { - self.due = Utc::now() + self.duration; - } + pub fn reset(&mut self) { self.due = Utc::now() + self.duration; } } diff --git a/src/internal/ws_impl.rs b/src/internal/ws_impl.rs index 573c4e6..6166f2b 100644 --- a/src/internal/ws_impl.rs +++ b/src/internal/ws_impl.rs @@ -3,12 +3,13 @@ use serde_json; use websocket::message::OwnedMessage; use websocket::sync::stream::{TcpStream, TlsStream}; use websocket::sync::Client as WsClient; -use ::gateway::GatewayError; -use ::internal::prelude::*; +use gateway::GatewayError; +use internal::prelude::*; pub trait ReceiverExt { fn recv_json<F, T>(&mut self, decode: F) -> Result<T> - where F: FnOnce(Value) -> Result<T>; + where + F: FnOnce(Value) -> Result<T>; } pub trait SenderExt { @@ -16,11 +17,14 @@ pub trait SenderExt { } impl ReceiverExt for WsClient<TlsStream<TcpStream>> { - fn recv_json<F, T>(&mut self, decode: F) -> Result<T> where F: FnOnce(Value) -> Result<T> { + fn recv_json<F, T>(&mut self, decode: F) -> Result<T> + where + F: FnOnce(Value) -> Result<T>, { let message = self.recv_message()?; if let OwnedMessage::Ping(ref x) = message { - self.send_message(&OwnedMessage::Pong(x.clone())).map_err(Error::from)?; + self.send_message(&OwnedMessage::Pong(x.clone())) + .map_err(Error::from)?; } let res = match message { @@ -35,9 +39,7 @@ impl ReceiverExt for WsClient<TlsStream<TcpStream>> { why })) }, - OwnedMessage::Close(data) => { - Some(Err(Error::Gateway(GatewayError::Closed(data)))) - }, + OwnedMessage::Close(data) => Some(Err(Error::Gateway(GatewayError::Closed(data)))), OwnedMessage::Text(payload) => { let value = serde_json::from_str(&payload)?; @@ -96,7 +96,7 @@ extern crate serde_derive; #[macro_use] extern crate serde_json; -#[cfg(feature="lazy_static")] +#[cfg(feature = "lazy_static")] #[macro_use] extern crate lazy_static; @@ -106,27 +106,27 @@ extern crate flate2; extern crate serde; extern crate parking_lot; -#[cfg(feature="voice")] +#[cfg(feature = "voice")] extern crate byteorder; -#[cfg(feature="futures")] +#[cfg(feature = "futures")] extern crate futures; -#[cfg(feature="hyper")] +#[cfg(feature = "hyper")] extern crate hyper; -#[cfg(feature="hyper-native-tls")] +#[cfg(feature = "hyper-native-tls")] extern crate hyper_native_tls; -#[cfg(feature="http")] +#[cfg(feature = "http")] extern crate multipart; -#[cfg(feature="native-tls")] +#[cfg(feature = "native-tls")] extern crate native_tls; -#[cfg(feature="voice")] +#[cfg(feature = "voice")] extern crate opus; -#[cfg(feature="voice")] +#[cfg(feature = "voice")] extern crate sodiumoxide; -#[cfg(feature="tokio-core")] +#[cfg(feature = "tokio-core")] extern crate tokio_core; -#[cfg(feature="client")] +#[cfg(feature = "client")] extern crate typemap; -#[cfg(feature="gateway")] +#[cfg(feature = "gateway")] extern crate websocket; #[macro_use] @@ -136,42 +136,42 @@ pub mod constants; pub mod model; pub mod prelude; -#[cfg(feature="builder")] +#[cfg(feature = "builder")] pub mod builder; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] pub mod cache; -#[cfg(feature="client")] +#[cfg(feature = "client")] pub mod client; -#[cfg(any(feature="cache", feature="builtin_framework", feature="voice"))] +#[cfg(any(feature = "cache", feature = "builtin_framework", feature = "voice"))] pub mod ext; -#[cfg(feature="builtin_framework")] +#[cfg(feature = "builtin_framework")] pub mod framework; -#[cfg(feature="gateway")] +#[cfg(feature = "gateway")] pub mod gateway; -#[cfg(feature="http")] +#[cfg(feature = "http")] pub mod http; -#[cfg(feature="utils")] +#[cfg(feature = "utils")] pub mod utils; -#[cfg(feature="voice")] +#[cfg(feature = "voice")] pub mod voice; mod error; pub use error::{Error, Result}; -#[cfg(feature="client")] +#[cfg(feature = "client")] pub use client::Client; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] use cache::Cache; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] use std::sync::RwLock; use model::{Message, UserId}; use client::Context; -use tokio_core::reactor::Handle; +use tokio_core::reactor::Handle; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] lazy_static! { /// A mutable and lazily-initialized static binding. It can be accessed /// across any function and in any context. @@ -212,15 +212,17 @@ lazy_static! { /// This trait allows for serenity to either use its builtin framework, or yours. /// -/// When implementing, be sure to use `tokio_handle.spawn_fn(|| ...; Ok())` when dispatching commands. -/// -/// Note that you may see some other methods in here as well, but they're meant to be internal only for the builtin framework. -#[cfg(feature="framework")] +/// When implementing, be sure to use `tokio_handle.spawn_fn(|| ...; Ok())` when dispatching +/// commands. +/// +/// Note that you may see some other methods in here as well, but they're meant to be internal only +/// for the builtin framework. +#[cfg(feature = "framework")] pub trait Framework { fn dispatch(&mut self, Context, Message, &Handle); - #[cfg(feature="builtin_framework")] + #[cfg(feature = "builtin_framework")] fn update_current_user(&mut self, UserId, bool) {} - #[cfg(feature="builtin_framework")] + #[cfg(feature = "builtin_framework")] fn initialized(&self) -> bool { false } -}
\ No newline at end of file +} diff --git a/src/model/channel/attachment.rs b/src/model/channel/attachment.rs index 2238174..5d47469 100644 --- a/src/model/channel/attachment.rs +++ b/src/model/channel/attachment.rs @@ -1,9 +1,9 @@ -#[cfg(feature="model")] +#[cfg(feature = "model")] use hyper::Client as HyperClient; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::io::Read; -#[cfg(feature="model")] -use ::internal::prelude::*; +#[cfg(feature = "model")] +use internal::prelude::*; /// A file uploaded with a message. Not to be confused with [`Embed`]s. /// @@ -27,7 +27,7 @@ pub struct Attachment { pub width: Option<u64>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Attachment { /// If this attachment is an image, then a tuple of the width and height /// in pixels is returned. @@ -90,7 +90,7 @@ impl Attachment { /// } /// /// fn on_ready(&self, _: Context, ready: Ready) { - /// println!("{} is connected!", ready.user.name); + /// println!("{} is connected!", ready.user.name); /// } /// } /// let token = env::var("DISCORD_TOKEN").expect("token in environment"); diff --git a/src/model/channel/channel_id.rs b/src/model/channel/channel_id.rs index f83062c..62d8820 100644 --- a/src/model/channel/channel_id.rs +++ b/src/model/channel/channel_id.rs @@ -1,18 +1,18 @@ use std::fmt::{Display, Formatter, Result as FmtResult}; -use ::model::*; +use model::*; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::borrow::Cow; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::fmt::Write as FmtWrite; -#[cfg(feature="model")] -use ::builder::{CreateMessage, EditChannel, GetMessages}; -#[cfg(feature="cache")] -use ::CACHE; -#[cfg(feature="model")] -use ::http::{self, AttachmentType}; - -#[cfg(feature="model")] +#[cfg(feature = "model")] +use builder::{CreateMessage, EditChannel, GetMessages}; +#[cfg(feature = "cache")] +use CACHE; +#[cfg(feature = "model")] +use http::{self, AttachmentType}; + +#[cfg(feature = "model")] impl ChannelId { /// Broadcasts that the current user is typing to a channel for the next 5 /// seconds. @@ -35,9 +35,7 @@ impl ChannelId { /// /// [Send Messages]: permissions/constant.SEND_MESSAGES.html #[inline] - pub fn broadcast_typing(&self) -> Result<()> { - http::broadcast_typing(self.0) - } + pub fn broadcast_typing(&self) -> Result<()> { http::broadcast_typing(self.0) } /// Creates a [permission overwrite][`PermissionOverwrite`] for either a /// single [`Member`] or [`Role`] within the channel. @@ -52,8 +50,7 @@ impl ChannelId { /// [`PermissionOverwrite`]: struct.PermissionOverwrite.html /// [`Role`]: struct.Role.html /// [Manage Channels]: permissions/constant.MANAGE_CHANNELS.html - pub fn create_permission(&self, target: &PermissionOverwrite) - -> Result<()> { + pub fn create_permission(&self, target: &PermissionOverwrite) -> Result<()> { let (id, kind) = match target.kind { PermissionOverwriteType::Member(id) => (id.0, "member"), PermissionOverwriteType::Role(id) => (id.0, "role"), @@ -82,16 +79,16 @@ impl ChannelId { /// [`Message::react`]: struct.Message.html#method.react /// [Add Reactions]: permissions/constant.ADD_REACTIONS.html #[inline] - pub fn create_reaction<M, R>(&self, message_id: M, reaction_type: R) - -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { + pub fn create_reaction<M, R>(&self, message_id: M, reaction_type: R) -> Result<()> + where + M: Into<MessageId>, + R: Into<ReactionType>, { http::create_reaction(self.0, message_id.into().0, &reaction_type.into()) } /// Deletes this channel, returning the channel on a successful deletion. #[inline] - pub fn delete(&self) -> Result<Channel> { - http::delete_channel(self.0) - } + pub fn delete(&self) -> Result<Channel> { http::delete_channel(self.0) } /// Deletes a [`Message`] given its Id. /// @@ -123,7 +120,8 @@ impl ChannelId { /// [`Channel::delete_messages`]: enum.Channel.html#method.delete_messages /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html pub fn delete_messages(&self, message_ids: &[MessageId]) -> Result<()> { - let ids = message_ids.into_iter() + let ids = message_ids + .into_iter() .map(|message_id| message_id.0) .collect::<Vec<u64>>(); @@ -153,8 +151,14 @@ impl ChannelId { /// /// [`Reaction`]: struct.Reaction.html /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html - pub fn delete_reaction<M, R>(&self, message_id: M, user_id: Option<UserId>, reaction_type: R) - -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { + pub fn delete_reaction<M, R>(&self, + message_id: M, + user_id: Option<UserId>, + reaction_type: R) + -> Result<()> + where + M: Into<MessageId>, + R: Into<ReactionType>, { http::delete_reaction(self.0, message_id.into().0, user_id.map(|uid| uid.0), @@ -205,7 +209,9 @@ impl ChannelId { /// [`Message`]: struct.Message.html /// [`the limit`]: ../builder/struct.CreateMessage.html#method.content pub fn edit_message<F, M>(&self, message_id: M, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage, M: Into<MessageId> { + where + F: FnOnce(CreateMessage) -> CreateMessage, + M: Into<MessageId>, { let map = f(CreateMessage::default()).0; if let Some(content) = map.get("content") { @@ -220,15 +226,13 @@ impl ChannelId { } /// Search the cache for the channel with the Id. - #[cfg(feature="cache")] - pub fn find(&self) -> Option<Channel> { - CACHE.read().unwrap().channel(*self) - } + #[cfg(feature = "cache")] + pub fn find(&self) -> Option<Channel> { CACHE.read().unwrap().channel(*self) } /// Search the cache for the channel. If it can't be found, the channel is /// requested over REST. pub fn get(&self) -> Result<Channel> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { if let Some(channel) = CACHE.read().unwrap().channel(*self) { return Ok(channel); @@ -243,9 +247,7 @@ impl ChannelId { /// Requires the [Manage Channels] permission. /// [Manage Channels]: permissions/constant.MANAGE_CHANNELS.html #[inline] - pub fn invites(&self) -> Result<Vec<RichInvite>> { - http::get_channel_invites(self.0) - } + pub fn invites(&self) -> Result<Vec<RichInvite>> { http::get_channel_invites(self.0) } /// Gets a message from the channel. /// @@ -254,12 +256,11 @@ impl ChannelId { /// [Read Message History]: permissions/constant.READ_MESSAGE_HISTORY.html #[inline] pub fn message<M: Into<MessageId>>(&self, message_id: M) -> Result<Message> { - http::get_message(self.0, message_id.into().0) - .map(|mut msg| { - msg.transform_content(); + http::get_message(self.0, message_id.into().0).map(|mut msg| { + msg.transform_content(); - msg - }) + msg + }) } /// Gets messages from the channel. @@ -271,7 +272,8 @@ impl ChannelId { /// [`Channel::messages`]: enum.Channel.html#method.messages /// [Read Message History]: permissions/constant.READ_MESSAGE_HISTORY.html pub fn messages<F>(&self, f: F) -> Result<Vec<Message>> - where F: FnOnce(GetMessages) -> GetMessages { + where + F: FnOnce(GetMessages) -> GetMessages, { let mut map = f(GetMessages::default()).0; let mut query = format!("?limit={}", map.remove("limit").unwrap_or(50)); @@ -283,35 +285,35 @@ impl ChannelId { write!(query, "&before={}", before)?; } - http::get_messages(self.0, &query) - .map(|msgs| msgs - .into_iter() + http::get_messages(self.0, &query).map(|msgs| { + msgs.into_iter() .map(|mut msg| { msg.transform_content(); msg - }).collect::<Vec<Message>>()) + }) + .collect::<Vec<Message>>() + }) } /// Returns the name of whatever channel this id holds. - #[cfg(feature="model")] + #[cfg(feature = "model")] pub fn name(&self) -> Option<String> { use self::Channel::*; - Some(match match self.find() { Some(c) => c, None => return None, } { - Guild(channel) => { - channel.read().unwrap().name().to_string() - }, - Group(channel) => { - match channel.read().unwrap().name() { - Cow::Borrowed(name) => name.to_string(), - Cow::Owned(name) => name, - } - }, - Private(channel) => { - channel.read().unwrap().name() - } - }) + Some(match match self.find() { + Some(c) => c, + None => return None, + } { + Guild(channel) => channel.read().unwrap().name().to_string(), + Group(channel) => { + match channel.read().unwrap().name() { + Cow::Borrowed(name) => name.to_string(), + Cow::Owned(name) => name, + } + }, + Private(channel) => channel.read().unwrap().name(), + }) } /// Pins a [`Message`] to the channel. @@ -326,9 +328,7 @@ impl ChannelId { /// /// [`Message`]: struct.Message.html #[inline] - pub fn pins(&self) -> Result<Vec<Message>> { - http::get_pins(self.0) - } + pub fn pins(&self) -> Result<Vec<Message>> { http::get_pins(self.0) } /// Gets the list of [`User`]s who have reacted to a [`Message`] with a /// certain [`Emoji`]. @@ -343,11 +343,15 @@ impl ChannelId { /// [`User`]: struct.User.html /// [Read Message History]: permissions/constant.READ_MESSAGE_HISTORY.html pub fn reaction_users<M, R, U>(&self, - message_id: M, - reaction_type: R, - limit: Option<u8>, - after: Option<U>) - -> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId> { + message_id: M, + reaction_type: R, + limit: Option<u8>, + after: Option<U>) + -> Result<Vec<User>> + where + M: Into<MessageId>, + R: Into<ReactionType>, + U: Into<UserId>, { let limit = limit.map_or(50, |x| if x > 100 { 100 } else { x }); http::get_reaction_users(self.0, @@ -432,7 +436,9 @@ impl ChannelId { /// [Attach Files]: permissions/constant.ATTACH_FILES.html /// [Send Messages]: permissions/constant.SEND_MESSAGES.html pub fn send_files<'a, F, T>(&self, files: Vec<T>, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage, T: Into<AttachmentType<'a>> { + where + F: FnOnce(CreateMessage) -> CreateMessage, + T: Into<AttachmentType<'a>>, { let mut map = f(CreateMessage::default()).0; if let Some(content) = map.get("content") { @@ -468,7 +474,8 @@ impl ChannelId { /// [`CreateMessage`]: ../builder/struct.CreateMessage.html /// [Send Messages]: permissions/constant.SEND_MESSAGES.html pub fn send_message<F>(&self, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage { + where + F: FnOnce(CreateMessage) -> CreateMessage, { let CreateMessage(map, reactions) = f(CreateMessage::default()); Message::check_content_length(&map)?; @@ -502,9 +509,7 @@ impl ChannelId { /// /// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html #[inline] - pub fn webhooks(&self) -> Result<Vec<Webhook>> { - http::get_channel_webhooks(self.0) - } + pub fn webhooks(&self) -> Result<Vec<Webhook>> { http::get_channel_webhooks(self.0) } } impl From<Channel> for ChannelId { @@ -531,33 +536,23 @@ impl<'a> From<&'a Channel> for ChannelId { impl From<PrivateChannel> for ChannelId { /// Gets the Id of a private channel. - fn from(private_channel: PrivateChannel) -> ChannelId { - private_channel.id - } + fn from(private_channel: PrivateChannel) -> ChannelId { private_channel.id } } impl<'a> From<&'a PrivateChannel> for ChannelId { /// Gets the Id of a private channel. - fn from(private_channel: &PrivateChannel) -> ChannelId { - private_channel.id - } + fn from(private_channel: &PrivateChannel) -> ChannelId { private_channel.id } } impl From<GuildChannel> for ChannelId { /// Gets the Id of a guild channel. - fn from(public_channel: GuildChannel) -> ChannelId { - public_channel.id - } + fn from(public_channel: GuildChannel) -> ChannelId { public_channel.id } } impl<'a> From<&'a GuildChannel> for ChannelId { /// Gets the Id of a guild channel. - fn from(public_channel: &GuildChannel) -> ChannelId { - public_channel.id - } + fn from(public_channel: &GuildChannel) -> ChannelId { public_channel.id } } impl Display for ChannelId { - fn fmt(&self, f: &mut Formatter) -> FmtResult { - Display::fmt(&self.0, f) - } + fn fmt(&self, f: &mut Formatter) -> FmtResult { Display::fmt(&self.0, f) } } diff --git a/src/model/channel/embed.rs b/src/model/channel/embed.rs index c0ac1e4..5aea7b0 100644 --- a/src/model/channel/embed.rs +++ b/src/model/channel/embed.rs @@ -1,9 +1,9 @@ -#[cfg(feature="utils")] -use ::utils::Colour; -#[cfg(feature="model")] -use ::internal::prelude::*; -#[cfg(feature="model")] -use ::builder::CreateEmbed; +#[cfg(feature = "utils")] +use utils::Colour; +#[cfg(feature = "model")] +use internal::prelude::*; +#[cfg(feature = "model")] +use builder::CreateEmbed; /// Represents a rich embed which allows using richer markdown, multiple fields /// and more. This was heavily inspired by [slack's attachments]. @@ -20,12 +20,12 @@ pub struct Embed { /// Information about the author of the embed. pub author: Option<EmbedAuthor>, /// The colour code of the embed. - #[cfg(feature="utils")] - #[serde(default, rename="color")] + #[cfg(feature = "utils")] + #[serde(default, rename = "color")] pub colour: Colour, /// The colour code of the embed. - #[cfg(not(feature="utils"))] - #[serde(default, rename="color")] + #[cfg(not(feature = "utils"))] + #[serde(default, rename = "color")] pub colour: u32, /// The description of the embed. /// @@ -42,7 +42,7 @@ pub struct Embed { pub image: Option<EmbedImage>, /// The type of the embed. For embeds not generated by Discord's backend, /// this will always be "rich". - #[serde(rename="type")] + #[serde(rename = "type")] pub kind: String, /// Provider information for the embed. /// @@ -63,7 +63,7 @@ pub struct Embed { pub video: Option<EmbedVideo>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Embed { /// Creates a fake Embed, giving back a `serde_json` map. /// @@ -87,7 +87,9 @@ impl Embed { /// .inline(false))); /// ``` #[inline] - pub fn fake<F>(f: F) -> Value where F: FnOnce(CreateEmbed) -> CreateEmbed { + pub fn fake<F>(f: F) -> Value + where + F: FnOnce(CreateEmbed) -> CreateEmbed, { Value::Object(f(CreateEmbed::default()).0) } } diff --git a/src/model/channel/group.rs b/src/model/channel/group.rs index 116b6c1..42c1249 100644 --- a/src/model/channel/group.rs +++ b/src/model/channel/group.rs @@ -1,14 +1,14 @@ use chrono::{DateTime, FixedOffset}; -use ::model::*; +use model::*; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::borrow::Cow; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::fmt::Write as FmtWrite; -#[cfg(feature="model")] -use ::builder::{CreateMessage, GetMessages}; -#[cfg(feature="model")] -use ::http::{self, AttachmentType}; +#[cfg(feature = "model")] +use builder::{CreateMessage, GetMessages}; +#[cfg(feature = "model")] +use http::{self, AttachmentType}; /// A group channel - potentially including other [`User`]s - separate from a /// [`Guild`]. @@ -18,7 +18,7 @@ use ::http::{self, AttachmentType}; #[derive(Clone, Debug, Deserialize)] pub struct Group { /// The Id of the group channel. - #[serde(rename="id")] + #[serde(rename = "id")] pub channel_id: ChannelId, /// The optional icon of the group channel. pub icon: Option<String>, @@ -31,11 +31,11 @@ pub struct Group { /// The Id of the group owner. pub owner_id: UserId, /// A map of the group's recipients. - #[serde(deserialize_with="deserialize_users")] + #[serde(deserialize_with = "deserialize_users")] pub recipients: HashMap<UserId, Arc<RwLock<User>>>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Group { /// Adds the given user to the group. If the user is already in the group, /// then nothing is done. @@ -59,9 +59,7 @@ impl Group { /// Broadcasts that the current user is typing in the group. #[inline] - pub fn broadcast_typing(&self) -> Result<()> { - self.channel_id.broadcast_typing() - } + pub fn broadcast_typing(&self) -> Result<()> { self.channel_id.broadcast_typing() } /// React to a [`Message`] with a custom [`Emoji`] or unicode character. /// @@ -76,8 +74,10 @@ impl Group { /// [`Message::react`]: struct.Message.html#method.react /// [Add Reactions]: permissions/constant.ADD_REACTIONS.html #[inline] - pub fn create_reaction<M, R>(&self, message_id: M, reaction_type: R) - -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { + pub fn create_reaction<M, R>(&self, message_id: M, reaction_type: R) -> Result<()> + where + M: Into<MessageId>, + R: Into<ReactionType>, { self.channel_id.create_reaction(message_id, reaction_type) } @@ -119,9 +119,16 @@ impl Group { /// [`Reaction`]: struct.Reaction.html /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html #[inline] - pub fn delete_reaction<M, R>(&self, message_id: M, user_id: Option<UserId>, reaction_type: R) - -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { - self.channel_id.delete_reaction(message_id, user_id, reaction_type) + pub fn delete_reaction<M, R>(&self, + message_id: M, + user_id: Option<UserId>, + reaction_type: R) + -> Result<()> + where + M: Into<MessageId>, + R: Into<ReactionType>, { + self.channel_id + .delete_reaction(message_id, user_id, reaction_type) } /// Edits a [`Message`] in the channel given its Id. @@ -145,14 +152,17 @@ impl Group { /// [`the limit`]: ../builder/struct.CreateMessage.html#method.content #[inline] pub fn edit_message<F, M>(&self, message_id: M, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage, M: Into<MessageId> { + where + F: FnOnce(CreateMessage) -> CreateMessage, + M: Into<MessageId>, { self.channel_id.edit_message(message_id, f) } /// Returns the formatted URI of the group's icon if one exists. pub fn icon_url(&self) -> Option<String> { - self.icon.as_ref().map(|icon| - format!(cdn!("/channel-icons/{}/{}.webp"), self.channel_id, icon)) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/channel-icons/{}/{}.webp"), self.channel_id, icon)) } /// Determines if the channel is NSFW. @@ -164,15 +174,11 @@ impl Group { /// /// [`utils::is_nsfw`]: ../utils/fn.is_nsfw.html #[inline] - pub fn is_nsfw(&self) -> bool { - false - } + pub fn is_nsfw(&self) -> bool { false } /// Leaves the group. #[inline] - pub fn leave(&self) -> Result<Group> { - http::leave_group(self.channel_id.0) - } + pub fn leave(&self) -> Result<Group> { http::leave_group(self.channel_id.0) } /// Gets a message from the channel. /// @@ -191,7 +197,8 @@ impl Group { /// [Read Message History]: permissions/constant.READ_MESSAGE_HISTORY.html #[inline] pub fn messages<F>(&self, f: F) -> Result<Vec<Message>> - where F: FnOnce(GetMessages) -> GetMessages { + where + F: FnOnce(GetMessages) -> GetMessages, { self.channel_id.messages(f) } @@ -214,15 +221,13 @@ impl Group { } Cow::Owned(name) - } + }, } } /// Retrieves the list of messages that have been pinned in the group. #[inline] - pub fn pins(&self) -> Result<Vec<Message>> { - self.channel_id.pins() - } + pub fn pins(&self) -> Result<Vec<Message>> { self.channel_id.pins() } /// Gets the list of [`User`]s who have reacted to a [`Message`] with a /// certain [`Emoji`]. @@ -242,8 +247,13 @@ impl Group { reaction_type: R, limit: Option<u8>, after: Option<U>) - -> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId> { - self.channel_id.reaction_users(message_id, reaction_type, limit, after) + -> Result<Vec<User>> + where + M: Into<MessageId>, + R: Into<ReactionType>, + U: Into<UserId>, { + self.channel_id + .reaction_users(message_id, reaction_type, limit, after) } /// Removes a recipient from the group. If the recipient is already not in @@ -272,9 +282,7 @@ impl Group { /// [`ChannelId`]: ../model/struct.ChannelId.html /// [`ModelError::MessageTooLong`]: enum.ModelError.html#variant.MessageTooLong #[inline] - pub fn say(&self, content: &str) -> Result<Message> { - self.channel_id.say(content) - } + pub fn say(&self, content: &str) -> Result<Message> { self.channel_id.say(content) } /// Sends (a) file(s) along with optional message contents. /// @@ -296,7 +304,9 @@ impl Group { /// [Send Messages]: permissions/constant.SEND_MESSAGES.html #[inline] pub fn send_files<'a, F, T>(&self, files: Vec<T>, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage, T: Into<AttachmentType<'a>> { + where + F: FnOnce(CreateMessage) -> CreateMessage, + T: Into<AttachmentType<'a>>, { self.channel_id.send_files(files, f) } diff --git a/src/model/channel/guild_channel.rs b/src/model/channel/guild_channel.rs index 678e601..250e112 100644 --- a/src/model/channel/guild_channel.rs +++ b/src/model/channel/guild_channel.rs @@ -1,20 +1,20 @@ use chrono::{DateTime, FixedOffset}; -use ::model::*; +use model::*; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::fmt::{Display, Formatter, Result as FmtResult}; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::mem; -#[cfg(feature="cache")] -use ::CACHE; -#[cfg(feature="model")] -use ::builder::{CreateInvite, CreateMessage, EditChannel, GetMessages}; -#[cfg(feature="model")] -use ::http::{self, AttachmentType}; -#[cfg(feature="cache")] -use ::internal::prelude::*; -#[cfg(all(feature="model", feature="utils"))] -use ::utils as serenity_utils; +#[cfg(feature = "cache")] +use CACHE; +#[cfg(feature = "model")] +use builder::{CreateInvite, CreateMessage, EditChannel, GetMessages}; +#[cfg(feature = "model")] +use http::{self, AttachmentType}; +#[cfg(feature = "cache")] +use internal::prelude::*; +#[cfg(all(feature = "model", feature = "utils"))] +use utils as serenity_utils; /// Represents a guild's text or voice channel. Some methods are available only /// for voice channels and some are only available for text channels. @@ -36,7 +36,7 @@ pub struct GuildChannel { /// incremented by one. pub guild_id: GuildId, /// The type of the channel. - #[serde(rename="type")] + #[serde(rename = "type")] pub kind: ChannelType, /// The Id of the last message sent in the channel. /// @@ -69,19 +69,16 @@ pub struct GuildChannel { /// Used to tell if the channel is not safe for work. /// Note however, it's recommended to use [`is_nsfw`] as it's gonna be more accurate. /// - /// [`is_nsfw`]: struct.GuildChannel.html#method.is_nsfw - + /// [`is_nsfw`]: struct.GuildChannel.html#method.is_nsfw // This field can or can not be present sometimes, but if it isn't // default to `false`. #[serde(default = "nsfw_false")] pub nsfw: bool, } -fn nsfw_false() -> bool { - false -} +fn nsfw_false() -> bool { false } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl GuildChannel { /// Broadcasts to the channel that the current user is typing. /// @@ -96,9 +93,7 @@ impl GuildChannel { /// /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [Send Messages]: permissions/constant.SEND_MESSAGES.html - pub fn broadcast_typing(&self) -> Result<()> { - self.id.broadcast_typing() - } + pub fn broadcast_typing(&self) -> Result<()> { self.id.broadcast_typing() } /// Creates an invite leading to the given channel. /// @@ -110,8 +105,9 @@ impl GuildChannel { /// let invite = channel.create_invite(|i| i.max_uses(5)); /// ``` pub fn create_invite<F>(&self, f: F) -> Result<RichInvite> - where F: FnOnce(CreateInvite) -> CreateInvite { - #[cfg(feature="cache")] + where + F: FnOnce(CreateInvite) -> CreateInvite, { + #[cfg(feature = "cache")] { let req = permissions::CREATE_INVITE; @@ -235,7 +231,7 @@ impl GuildChannel { /// Deletes this channel, returning the channel on a successful deletion. pub fn delete(&self) -> Result<Channel> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::MANAGE_CHANNELS; @@ -285,8 +281,14 @@ impl GuildChannel { /// [`Reaction`]: struct.Reaction.html /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html #[inline] - pub fn delete_reaction<M, R>(&self, message_id: M, user_id: Option<UserId>, reaction_type: R) - -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { + pub fn delete_reaction<M, R>(&self, + message_id: M, + user_id: Option<UserId>, + reaction_type: R) + -> Result<()> + where + M: Into<MessageId>, + R: Into<ReactionType>, { self.id.delete_reaction(message_id, user_id, reaction_type) } @@ -302,9 +304,10 @@ impl GuildChannel { /// channel.edit(|c| c.name("test").bitrate(86400)); /// ``` pub fn edit<F>(&mut self, f: F) -> Result<()> - where F: FnOnce(EditChannel) -> EditChannel { + where + F: FnOnce(EditChannel) -> EditChannel, { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::MANAGE_CHANNELS; @@ -315,8 +318,10 @@ impl GuildChannel { let mut map = Map::new(); map.insert("name".to_owned(), Value::String(self.name.clone())); - map.insert("position".to_owned(), Value::Number(Number::from(self.position))); - map.insert("type".to_owned(), Value::String(self.kind.name().to_owned())); + map.insert("position".to_owned(), + Value::Number(Number::from(self.position))); + map.insert("type".to_owned(), + Value::String(self.kind.name().to_owned())); let edited = f(EditChannel(map)).0; @@ -351,7 +356,9 @@ impl GuildChannel { /// [`the limit`]: ../builder/struct.CreateMessage.html#method.content #[inline] pub fn edit_message<F, M>(&self, message_id: M, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage, M: Into<MessageId> { + where + F: FnOnce(CreateMessage) -> CreateMessage, + M: Into<MessageId>, { self.id.edit_message(message_id, f) } @@ -359,19 +366,15 @@ impl GuildChannel { /// /// **Note**: Right now this performs a clone of the guild. This will be /// optimized in the future. - #[cfg(feature="cache")] - pub fn guild(&self) -> Option<Arc<RwLock<Guild>>> { - CACHE.read().unwrap().guild(self.guild_id) - } + #[cfg(feature = "cache")] + pub fn guild(&self) -> Option<Arc<RwLock<Guild>>> { CACHE.read().unwrap().guild(self.guild_id) } /// Gets all of the channel's invites. /// /// Requires the [Manage Channels] permission. /// [Manage Channels]: permissions/constant.MANAGE_CHANNELS.html #[inline] - pub fn invites(&self) -> Result<Vec<RichInvite>> { - self.id.invites() - } + pub fn invites(&self) -> Result<Vec<RichInvite>> { self.id.invites() } /// Determines if the channel is NSFW. /// @@ -383,7 +386,7 @@ impl GuildChannel { /// [`ChannelType::Text`]: enum.ChannelType.html#variant.Text /// [`ChannelType::Voice`]: enum.ChannelType.html#variant.Voice /// [`utils::is_nsfw`]: ../utils/fn.is_nsfw.html - #[cfg(feature="utils")] + #[cfg(feature = "utils")] #[inline] pub fn is_nsfw(&self) -> bool { self.kind == ChannelType::Text && (self.nsfw || serenity_utils::is_nsfw(&self.name)) @@ -409,14 +412,13 @@ impl GuildChannel { /// [Read Message History]: permissions/constant.READ_MESSAGE_HISTORY.html #[inline] pub fn messages<F>(&self, f: F) -> Result<Vec<Message>> - where F: FnOnce(GetMessages) -> GetMessages { + where + F: FnOnce(GetMessages) -> GetMessages, { self.id.messages(f) } /// Returns the name of the guild channel. - pub fn name(&self) -> &str { - &self.name - } + pub fn name(&self) -> &str { &self.name } /// Calculates the permissions of a member. /// @@ -471,9 +473,11 @@ impl GuildChannel { /// }; /// /// let current_user_id = CACHE.read().unwrap().user.id; - /// let permissions = channel.read().unwrap().permissions_for(current_user_id).unwrap(); + /// let permissions = + /// channel.read().unwrap().permissions_for(current_user_id).unwrap(); /// - /// if !permissions.contains(permissions::ATTACH_FILES | permissions::SEND_MESSAGES) { + /// if !permissions.contains(permissions::ATTACH_FILES | + /// permissions::SEND_MESSAGES) { /// return; /// } /// @@ -486,7 +490,8 @@ impl GuildChannel { /// }, /// }; /// - /// let _ = msg.channel_id.send_files(vec![(&file, "cat.png")], |m| m.content("here's a cat")); + /// let _ = msg.channel_id.send_files(vec![(&file, "cat.png")], |m| + /// m.content("here's a cat")); /// } /// } /// @@ -506,7 +511,7 @@ impl GuildChannel { /// [`User`]: struct.User.html /// [Attach Files]: permissions/constant.ATTACH_FILES.html /// [Send Messages]: permissions/constant.SEND_MESSAGES.html - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn permissions_for<U: Into<UserId>>(&self, user_id: U) -> Result<Permissions> { self.guild() .ok_or_else(|| Error::Model(ModelError::GuildNotFound)) @@ -515,15 +520,11 @@ impl GuildChannel { /// Pins a [`Message`] to the channel. #[inline] - pub fn pin<M: Into<MessageId>>(&self, message_id: M) -> Result<()> { - self.id.pin(message_id) - } + pub fn pin<M: Into<MessageId>>(&self, message_id: M) -> Result<()> { self.id.pin(message_id) } /// Gets all channel's pins. #[inline] - pub fn pins(&self) -> Result<Vec<Message>> { - self.id.pins() - } + pub fn pins(&self) -> Result<Vec<Message>> { self.id.pins() } /// Gets the list of [`User`]s who have reacted to a [`Message`] with a /// certain [`Emoji`]. @@ -542,8 +543,13 @@ impl GuildChannel { reaction_type: R, limit: Option<u8>, after: Option<U>) - -> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId> { - self.id.reaction_users(message_id, reaction_type, limit, after) + -> Result<Vec<User>> + where + M: Into<MessageId>, + R: Into<ReactionType>, + U: Into<UserId>, { + self.id + .reaction_users(message_id, reaction_type, limit, after) } /// Sends a message with just the given message content in the channel. @@ -557,9 +563,7 @@ impl GuildChannel { /// [`ChannelId`]: struct.ChannelId.html /// [`ModelError::MessageTooLong`]: enum.ModelError.html#variant.MessageTooLong #[inline] - pub fn say(&self, content: &str) -> Result<Message> { - self.id.say(content) - } + pub fn say(&self, content: &str) -> Result<Message> { self.id.say(content) } /// Sends (a) file(s) along with optional message contents. /// @@ -581,7 +585,9 @@ impl GuildChannel { /// [Send Messages]: permissions/constant.SEND_MESSAGES.html #[inline] pub fn send_files<'a, F, T>(&self, files: Vec<T>, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage, T: Into<AttachmentType<'a>> { + where + F: FnOnce(CreateMessage) -> CreateMessage, + T: Into<AttachmentType<'a>>, { self.id.send_files(files, f) } @@ -605,7 +611,7 @@ impl GuildChannel { /// [`Message`]: struct.Message.html /// [Send Messages]: permissions/constant.SEND_MESSAGES.html pub fn send_message<F: FnOnce(CreateMessage) -> CreateMessage>(&self, f: F) -> Result<Message> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::SEND_MESSAGES; @@ -634,15 +640,11 @@ impl GuildChannel { /// /// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html #[inline] - pub fn webhooks(&self) -> Result<Vec<Webhook>> { - self.id.webhooks() - } + pub fn webhooks(&self) -> Result<Vec<Webhook>> { self.id.webhooks() } } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Display for GuildChannel { /// Formats the channel, creating a mention of it. - fn fmt(&self, f: &mut Formatter) -> FmtResult { - Display::fmt(&self.id.mention(), f) - } + fn fmt(&self, f: &mut Formatter) -> FmtResult { Display::fmt(&self.id.mention(), f) } } diff --git a/src/model/channel/message.rs b/src/model/channel/message.rs index 0305271..8b479bc 100644 --- a/src/model/channel/message.rs +++ b/src/model/channel/message.rs @@ -1,19 +1,19 @@ use chrono::{DateTime, FixedOffset}; use serde_json::Value; -use ::model::*; +use model::*; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] use std::fmt::Write; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::mem; -#[cfg(feature="model")] -use ::builder::{CreateEmbed, CreateMessage}; -#[cfg(feature="model")] -use ::constants; -#[cfg(feature="cache")] -use ::CACHE; -#[cfg(feature="model")] -use ::http; +#[cfg(feature = "model")] +use builder::{CreateEmbed, CreateMessage}; +#[cfg(feature = "model")] +use constants; +#[cfg(feature = "cache")] +use CACHE; +#[cfg(feature = "model")] +use http; /// A representation of a message over a guild's text channel, a group, or a /// private channel. @@ -38,7 +38,7 @@ pub struct Message { pub embeds: Vec<Embed>, /// Indicator of the type of message this is, i.e. whether it is a regular /// message or a system message. - #[serde(rename="type")] + #[serde(rename = "type")] pub kind: MessageType, /// Indicator of whether the message mentions everyone. pub mention_everyone: bool, @@ -67,7 +67,7 @@ pub struct Message { pub webhook_id: Option<WebhookId>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Message { /// Retrieves the related channel located in the cache. /// @@ -109,17 +109,14 @@ impl Message { /// }); /// # } /// ``` - #[cfg(feature="cache")] + #[cfg(feature = "cache")] #[inline] - pub fn channel(&self) -> Option<Channel> { - CACHE.read().unwrap().channel(self.channel_id) - } + pub fn channel(&self) -> Option<Channel> { CACHE.read().unwrap().channel(self.channel_id) } - /// A util function for determining whether this message was sent by someone else, or the bot. - #[cfg(all(feature="cache", feature="utils"))] - pub fn is_own(&self) -> bool { - self.author.id == CACHE.read().unwrap().user.id - } + /// A util function for determining whether this message was sent by someone else, or the + /// bot. + #[cfg(all(feature = "cache", feature = "utils"))] + pub fn is_own(&self) -> bool { self.author.id == CACHE.read().unwrap().user.id } /// Deletes the message. /// @@ -136,7 +133,7 @@ impl Message { /// [`ModelError::InvalidUser`]: enum.ModelError.html#variant.InvalidUser /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html pub fn delete(&self) -> Result<()> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::MANAGE_MESSAGES; let is_author = self.author.id == CACHE.read().unwrap().user.id; @@ -164,7 +161,7 @@ impl Message { /// [`Reaction`]: struct.Reaction.html /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html pub fn delete_reactions(&self) -> Result<()> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::MANAGE_MESSAGES; @@ -209,8 +206,9 @@ impl Message { /// [`CreateMessage`]: ../builder/struct.CreateMessage.html /// [`the limit`]: ../builder/struct.CreateMessage.html#method.content pub fn edit<F>(&mut self, f: F) -> Result<()> - where F: FnOnce(CreateMessage) -> CreateMessage { - #[cfg(feature="cache")] + where + F: FnOnce(CreateMessage) -> CreateMessage, { + #[cfg(feature = "cache")] { if self.author.id != CACHE.read().unwrap().user.id { return Err(Error::Model(ModelError::InvalidUser)); @@ -246,7 +244,8 @@ impl Message { pub(crate) fn transform_content(&mut self) { match self.kind { MessageType::PinsAdd => { - self.content = format!("{} pinned a message to this channel. See all the pins.", self.author); + self.content = format!("{} pinned a message to this channel. See all the pins.", + self.author); }, MessageType::MemberJoin => { let sec = self.timestamp.timestamp() as usize; @@ -264,7 +263,7 @@ impl Message { /// Returns message content, but with user and role mentions replaced with /// names and everyone/here mentions cancelled. - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn content_safe(&self) -> String { let mut result = self.content.clone(); @@ -290,8 +289,9 @@ impl Message { } // And finally replace everyone and here mentions. - result.replace("@everyone", "@\u{200B}everyone") - .replace("@here", "@\u{200B}here") + result + .replace("@everyone", "@\u{200B}everyone") + .replace("@here", "@\u{200B}here") } /// Gets the list of [`User`]s who have reacted to a [`Message`] with a @@ -311,9 +311,16 @@ impl Message { /// [`User`]: struct.User.html /// [Read Message History]: permissions/constant.READ_MESSAGE_HISTORY.html #[inline] - pub fn reaction_users<R, U>(&self, reaction_type: R, limit: Option<u8>, after: Option<U>) - -> Result<Vec<User>> where R: Into<ReactionType>, U: Into<UserId> { - self.channel_id.reaction_users(self.id, reaction_type, limit, after) + pub fn reaction_users<R, U>(&self, + reaction_type: R, + limit: Option<u8>, + after: Option<U>) + -> Result<Vec<User>> + where + R: Into<ReactionType>, + U: Into<UserId>, { + self.channel_id + .reaction_users(self.id, reaction_type, limit, after) } /// Returns the associated `Guild` for the message if one is in the cache. @@ -324,9 +331,10 @@ impl Message { /// Requires the `cache` feature be enabled. /// /// [`guild_id`]: #method.guild_id - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn guild(&self) -> Option<Arc<RwLock<Guild>>> { - self.guild_id().and_then(|guild_id| CACHE.read().unwrap().guild(guild_id)) + self.guild_id() + .and_then(|guild_id| CACHE.read().unwrap().guild(guild_id)) } /// Retrieves the Id of the guild that the message was sent in, if sent in @@ -334,7 +342,7 @@ impl Message { /// /// Returns `None` if the channel data or guild data does not exist in the /// cache. - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn guild_id(&self) -> Option<GuildId> { match CACHE.read().unwrap().channel(self.channel_id) { Some(Channel::Guild(ch)) => Some(ch.read().unwrap().guild_id), @@ -343,7 +351,7 @@ impl Message { } /// True if message was sent using direct messages. - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn is_private(&self) -> bool { match CACHE.read().unwrap().channel(self.channel_id) { Some(Channel::Group(_)) | Some(Channel::Private(_)) => true, @@ -383,7 +391,7 @@ impl Message { /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html pub fn pin(&self) -> Result<()> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::MANAGE_MESSAGES; @@ -410,7 +418,7 @@ impl Message { /// [Add Reactions]: permissions/constant.ADD_REACTIONS.html /// [permissions]: permissions pub fn react<R: Into<ReactionType>>(&self, reaction_type: R) -> Result<()> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::ADD_REACTIONS; @@ -419,9 +427,7 @@ impl Message { } } - http::create_reaction(self.channel_id.0, - self.id.0, - &reaction_type.into()) + http::create_reaction(self.channel_id.0, self.id.0, &reaction_type.into()) } /// Replies to the user, mentioning them prior to the content in the form @@ -451,7 +457,7 @@ impl Message { return Err(Error::Model(ModelError::MessageTooLong(length_over))); } - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::SEND_MESSAGES; @@ -485,7 +491,7 @@ impl Message { /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html pub fn unpin(&self) -> Result<()> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::MANAGE_MESSAGES; @@ -563,16 +569,12 @@ impl Message { impl From<Message> for MessageId { /// Gets the Id of a `Message`. - fn from(message: Message) -> MessageId { - message.id - } + fn from(message: Message) -> MessageId { message.id } } impl<'a> From<&'a Message> for MessageId { /// Gets the Id of a `Message`. - fn from(message: &Message) -> MessageId { - message.id - } + fn from(message: &Message) -> MessageId { message.id } } /// A representation of a reaction to a message. @@ -590,7 +592,7 @@ pub struct MessageReaction { /// Indicator of whether the current user has sent the type of reaction. pub me: bool, /// The type of reaction. - #[serde(rename="emoji")] + #[serde(rename = "emoji")] pub reaction_type: ReactionType, } diff --git a/src/model/channel/mod.rs b/src/model/channel/mod.rs index 708e276..02be9d8 100644 --- a/src/model/channel/mod.rs +++ b/src/model/channel/mod.rs @@ -19,14 +19,14 @@ pub use self::reaction::*; use serde::de::Error as DeError; use serde_json; use super::utils::deserialize_u64; -use ::model::*; +use model::*; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::fmt::{Display, Formatter, Result as FmtResult}; -#[cfg(feature="model")] -use ::builder::{CreateMessage, GetMessages}; -#[cfg(feature="model")] -use ::http::AttachmentType; +#[cfg(feature = "model")] +use builder::{CreateMessage, GetMessages}; +#[cfg(feature = "model")] +use http::AttachmentType; /// A container for any channel. #[derive(Clone, Debug)] @@ -46,7 +46,7 @@ pub enum Channel { Private(Arc<RwLock<PrivateChannel>>), } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Channel { /// React to a [`Message`] with a custom [`Emoji`] or unicode character. /// @@ -61,8 +61,10 @@ impl Channel { /// [`Message::react`]: struct.Message.html#method.react /// [Add Reactions]: permissions/constant.ADD_REACTIONS.html #[inline] - pub fn create_reaction<M, R>(&self, message_id: M, reaction_type: R) - -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { + pub fn create_reaction<M, R>(&self, message_id: M, reaction_type: R) -> Result<()> + where + M: Into<MessageId>, + R: Into<ReactionType>, { self.id().create_reaction(message_id, reaction_type) } @@ -111,9 +113,16 @@ impl Channel { /// [`Reaction`]: struct.Reaction.html /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html #[inline] - pub fn delete_reaction<M, R>(&self, message_id: M, user_id: Option<UserId>, reaction_type: R) - -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { - self.id().delete_reaction(message_id, user_id, reaction_type) + pub fn delete_reaction<M, R>(&self, + message_id: M, + user_id: Option<UserId>, + reaction_type: R) + -> Result<()> + where + M: Into<MessageId>, + R: Into<ReactionType>, { + self.id() + .delete_reaction(message_id, user_id, reaction_type) } /// Edits a [`Message`] in the channel given its Id. @@ -137,7 +146,9 @@ impl Channel { /// [`the limit`]: ../builder/struct.CreateMessage.html#method.content #[inline] pub fn edit_message<F, M>(&self, message_id: M, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage, M: Into<MessageId> { + where + F: FnOnce(CreateMessage) -> CreateMessage, + M: Into<MessageId>, { self.id().edit_message(message_id, f) } @@ -146,7 +157,7 @@ impl Channel { /// Refer to [`utils::is_nsfw`] for more details. /// /// [`utils::is_nsfw`]: ../utils/fn.is_nsfw.html - #[cfg(feature="utils")] + #[cfg(feature = "utils")] #[inline] pub fn is_nsfw(&self) -> bool { match *self { @@ -183,7 +194,8 @@ impl Channel { /// [Read Message History]: permissions/constant.READ_MESSAGE_HISTORY.html #[inline] pub fn messages<F>(&self, f: F) -> Result<Vec<Message>> - where F: FnOnce(GetMessages) -> GetMessages { + where + F: FnOnce(GetMessages) -> GetMessages, { self.id().messages(f) } @@ -209,8 +221,13 @@ impl Channel { reaction_type: R, limit: Option<u8>, after: Option<U>) - -> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId> { - self.id().reaction_users(message_id, reaction_type, limit, after) + -> Result<Vec<User>> + where + M: Into<MessageId>, + R: Into<ReactionType>, + U: Into<UserId>, { + self.id() + .reaction_users(message_id, reaction_type, limit, after) } /// Retrieves the Id of the inner [`Group`], [`GuildChannel`], or @@ -238,9 +255,7 @@ impl Channel { /// [`ChannelId`]: struct.ChannelId.html /// [`ModelError::MessageTooLong`]: enum.ModelError.html#variant.MessageTooLong #[inline] - pub fn say(&self, content: &str) -> Result<Message> { - self.id().say(content) - } + pub fn say(&self, content: &str) -> Result<Message> { self.id().say(content) } /// Sends (a) file(s) along with optional message contents. /// @@ -262,7 +277,9 @@ impl Channel { /// [Send Messages]: permissions/constant.SEND_MESSAGES.html #[inline] pub fn send_files<'a, F, T>(&self, files: Vec<T>, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage, T: Into<AttachmentType<'a>> { + where + F: FnOnce(CreateMessage) -> CreateMessage, + T: Into<AttachmentType<'a>>, { self.id().send_files(files, f) } @@ -287,7 +304,8 @@ impl Channel { /// [Send Messages]: permissions/constant.SEND_MESSAGES.html #[inline] pub fn send_message<F>(&self, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage { + where + F: FnOnce(CreateMessage) -> CreateMessage, { self.id().send_message(f) } @@ -313,21 +331,27 @@ impl<'de> Deserialize<'de> for Channel { }; match kind { - 0 | 2 => serde_json::from_value::<GuildChannel>(Value::Object(v)) - .map(|x| Channel::Guild(Arc::new(RwLock::new(x)))) - .map_err(DeError::custom), - 1 => serde_json::from_value::<PrivateChannel>(Value::Object(v)) - .map(|x| Channel::Private(Arc::new(RwLock::new(x)))) - .map_err(DeError::custom), - 3 => serde_json::from_value::<Group>(Value::Object(v)) - .map(|x| Channel::Group(Arc::new(RwLock::new(x)))) - .map_err(DeError::custom), + 0 | 2 => { + serde_json::from_value::<GuildChannel>(Value::Object(v)) + .map(|x| Channel::Guild(Arc::new(RwLock::new(x)))) + .map_err(DeError::custom) + }, + 1 => { + serde_json::from_value::<PrivateChannel>(Value::Object(v)) + .map(|x| Channel::Private(Arc::new(RwLock::new(x)))) + .map_err(DeError::custom) + }, + 3 => { + serde_json::from_value::<Group>(Value::Object(v)) + .map(|x| Channel::Group(Arc::new(RwLock::new(x)))) + .map_err(DeError::custom) + }, _ => Err(DeError::custom("Unknown channel type")), } } } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Display for Channel { /// Formats the channel into a "mentioned" string. /// @@ -344,12 +368,8 @@ impl Display for Channel { /// [`PrivateChannel`]: struct.PrivateChannel.html fn fmt(&self, f: &mut Formatter) -> FmtResult { match *self { - Channel::Group(ref group) => { - Display::fmt(&group.read().unwrap().name(), f) - }, - Channel::Guild(ref ch) => { - Display::fmt(&ch.read().unwrap().id.mention(), f) - }, + Channel::Group(ref group) => Display::fmt(&group.read().unwrap().name(), f), + Channel::Guild(ref ch) => Display::fmt(&ch.read().unwrap().id.mention(), f), Channel::Private(ref ch) => { let channel = ch.read().unwrap(); let recipient = channel.recipient.read().unwrap(); @@ -397,9 +417,9 @@ impl ChannelType { struct PermissionOverwriteData { allow: Permissions, deny: Permissions, - #[serde(deserialize_with="deserialize_u64")] + #[serde(deserialize_with = "deserialize_u64")] id: u64, - #[serde(rename="type")] + #[serde(rename = "type")] kind: String, } @@ -412,7 +432,8 @@ pub struct PermissionOverwrite { } impl<'de> Deserialize<'de> for PermissionOverwrite { - fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<PermissionOverwrite, D::Error> { + fn deserialize<D: Deserializer<'de>>(deserializer: D) + -> StdResult<PermissionOverwrite, D::Error> { let data = PermissionOverwriteData::deserialize(deserializer)?; let kind = match &data.kind[..] { @@ -422,10 +443,10 @@ impl<'de> Deserialize<'de> for PermissionOverwrite { }; Ok(PermissionOverwrite { - allow: data.allow, - deny: data.deny, - kind: kind, - }) + allow: data.allow, + deny: data.deny, + kind: kind, + }) } } diff --git a/src/model/channel/private_channel.rs b/src/model/channel/private_channel.rs index f6d79ed..893bb84 100644 --- a/src/model/channel/private_channel.rs +++ b/src/model/channel/private_channel.rs @@ -1,12 +1,12 @@ use chrono::{DateTime, FixedOffset}; use std::fmt::{Display, Formatter, Result as FmtResult}; use super::deserialize_single_recipient; -use ::model::*; +use model::*; -#[cfg(feature="model")] -use ::builder::{CreateMessage, GetMessages}; -#[cfg(feature="model")] -use ::http::AttachmentType; +#[cfg(feature = "model")] +use builder::{CreateMessage, GetMessages}; +#[cfg(feature = "model")] +use http::AttachmentType; /// A Direct Message text channel with another user. #[derive(Clone, Debug, Deserialize)] @@ -26,19 +26,17 @@ pub struct PrivateChannel { /// This should always be [`ChannelType::Private`]. /// /// [`ChannelType::Private`]: enum.ChannelType.html#variant.Private - #[serde(rename="type")] + #[serde(rename = "type")] pub kind: ChannelType, /// The recipient to the private channel. - #[serde(deserialize_with="deserialize_single_recipient", rename="recipients")] + #[serde(deserialize_with = "deserialize_single_recipient", rename = "recipients")] pub recipient: Arc<RwLock<User>>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl PrivateChannel { /// Broadcasts that the current user is typing to the recipient. - pub fn broadcast_typing(&self) -> Result<()> { - self.id.broadcast_typing() - } + pub fn broadcast_typing(&self) -> Result<()> { self.id.broadcast_typing() } /// React to a [`Message`] with a custom [`Emoji`] or unicode character. /// @@ -52,8 +50,10 @@ impl PrivateChannel { /// [`Message`]: struct.Message.html /// [`Message::react`]: struct.Message.html#method.react /// [Add Reactions]: permissions/constant.ADD_REACTIONS.html - pub fn create_reaction<M, R>(&self, message_id: M, reaction_type: R) - -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { + pub fn create_reaction<M, R>(&self, message_id: M, reaction_type: R) -> Result<()> + where + M: Into<MessageId>, + R: Into<ReactionType>, { self.id.create_reaction(message_id, reaction_type) } @@ -61,9 +61,7 @@ impl PrivateChannel { /// and is equivalent to closing a private channel on the client, which can /// be re-opened. #[inline] - pub fn delete(&self) -> Result<Channel> { - self.id.delete() - } + pub fn delete(&self) -> Result<Channel> { self.id.delete() } /// Deletes all messages by Ids from the given vector in the channel. /// @@ -103,8 +101,14 @@ impl PrivateChannel { /// [`Reaction`]: struct.Reaction.html /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html #[inline] - pub fn delete_reaction<M, R>(&self, message_id: M, user_id: Option<UserId>, reaction_type: R) - -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { + pub fn delete_reaction<M, R>(&self, + message_id: M, + user_id: Option<UserId>, + reaction_type: R) + -> Result<()> + where + M: Into<MessageId>, + R: Into<ReactionType>, { self.id.delete_reaction(message_id, user_id, reaction_type) } @@ -129,7 +133,9 @@ impl PrivateChannel { /// [`the limit`]: ../builder/struct.CreateMessage.html#method.content #[inline] pub fn edit_message<F, M>(&self, message_id: M, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage, M: Into<MessageId> { + where + F: FnOnce(CreateMessage) -> CreateMessage, + M: Into<MessageId>, { self.id.edit_message(message_id, f) } @@ -142,9 +148,7 @@ impl PrivateChannel { /// /// [`utils::is_nsfw`]: ../utils/fn.is_nsfw.html #[inline] - pub fn is_nsfw(&self) -> bool { - false - } + pub fn is_nsfw(&self) -> bool { false } /// Gets a message from the channel. /// @@ -166,14 +170,13 @@ impl PrivateChannel { /// [Read Message History]: permissions/constant.READ_MESSAGE_HISTORY.html #[inline] pub fn messages<F>(&self, f: F) -> Result<Vec<Message>> - where F: FnOnce(GetMessages) -> GetMessages { + where + F: FnOnce(GetMessages) -> GetMessages, { self.id.messages(f) } /// Returns "DM with $username#discriminator". - pub fn name(&self) -> String { - format!("DM with {}", self.recipient.read().unwrap().tag()) - } + pub fn name(&self) -> String { format!("DM with {}", self.recipient.read().unwrap().tag()) } /// Gets the list of [`User`]s who have reacted to a [`Message`] with a /// certain [`Emoji`]. @@ -193,24 +196,25 @@ impl PrivateChannel { reaction_type: R, limit: Option<u8>, after: Option<U>) - -> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId> { - self.id.reaction_users(message_id, reaction_type, limit, after) + -> Result<Vec<User>> + where + M: Into<MessageId>, + R: Into<ReactionType>, + U: Into<UserId>, { + self.id + .reaction_users(message_id, reaction_type, limit, after) } /// Pins a [`Message`] to the channel. /// /// [`Message`]: struct.Message.html #[inline] - pub fn pin<M: Into<MessageId>>(&self, message_id: M) -> Result<()> { - self.id.pin(message_id) - } + pub fn pin<M: Into<MessageId>>(&self, message_id: M) -> Result<()> { self.id.pin(message_id) } /// Retrieves the list of messages that have been pinned in the private /// channel. #[inline] - pub fn pins(&self) -> Result<Vec<Message>> { - self.id.pins() - } + pub fn pins(&self) -> Result<Vec<Message>> { self.id.pins() } /// Sends a message with just the given message content in the channel. /// @@ -223,9 +227,7 @@ impl PrivateChannel { /// [`ChannelId`]: ../model/struct.ChannelId.html /// [`ModelError::MessageTooLong`]: enum.ModelError.html#variant.MessageTooLong #[inline] - pub fn say(&self, content: &str) -> Result<Message> { - self.id.say(content) - } + pub fn say(&self, content: &str) -> Result<Message> { self.id.say(content) } /// Sends (a) file(s) along with optional message contents. /// @@ -247,7 +249,9 @@ impl PrivateChannel { /// [Send Messages]: permissions/constant.SEND_MESSAGES.html #[inline] pub fn send_files<'a, F, T>(&self, files: Vec<T>, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage, T: Into<AttachmentType<'a>> { + where + F: FnOnce(CreateMessage) -> CreateMessage, + T: Into<AttachmentType<'a>>, { self.id.send_files(files, f) } diff --git a/src/model/channel/reaction.rs b/src/model/channel/reaction.rs index e900fff..5ecb038 100644 --- a/src/model/channel/reaction.rs +++ b/src/model/channel/reaction.rs @@ -1,12 +1,12 @@ use serde::de::{Deserialize, Error as DeError, MapAccess, Visitor}; use std::fmt::{Display, Formatter, Result as FmtResult, Write as FmtWrite}; -use ::internal::prelude::*; -use ::model::*; +use internal::prelude::*; +use model::*; -#[cfg(feature="cache")] -use ::CACHE; -#[cfg(feature="model")] -use ::http; +#[cfg(feature = "cache")] +use CACHE; +#[cfg(feature = "model")] +use http; /// An emoji reaction to a message. #[derive(Clone, Debug, Deserialize)] @@ -28,7 +28,7 @@ pub struct Reaction { pub user_id: UserId, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Reaction { /// Deletes the reaction, but only if the current user is the user who made /// the reaction or has permission to. @@ -72,10 +72,7 @@ impl Reaction { Some(self.user_id.0) }}; - http::delete_reaction(self.channel_id.0, - self.message_id.0, - user_id, - &self.emoji) + http::delete_reaction(self.channel_id.0, self.message_id.0, user_id, &self.emoji) } /// Retrieves the list of [`User`]s who have reacted to a [`Message`] with a @@ -106,8 +103,9 @@ impl Reaction { limit: Option<u8>, after: Option<U>) -> Result<Vec<User>> - where R: Into<ReactionType>, - U: Into<UserId> { + where + R: Into<ReactionType>, + U: Into<UserId>, { http::get_reaction_users(self.channel_id.0, self.message_id.0, &reaction_type.into(), @@ -207,13 +205,13 @@ impl<'de> Deserialize<'de> for ReactionType { let name = name.ok_or_else(|| DeError::missing_field("name"))?; Ok(if let Some(id) = id { - ReactionType::Custom { - id: id, - name: name, - } - } else { - ReactionType::Unicode(name) - }) + ReactionType::Custom { + id: id, + name: name, + } + } else { + ReactionType::Unicode(name) + }) } } @@ -223,7 +221,7 @@ impl<'de> Deserialize<'de> for ReactionType { } } -#[cfg(any(feature="model", feature="http"))] +#[cfg(any(feature = "model", feature = "http"))] impl ReactionType { /// Creates a data-esque display of the type. This is not very useful for /// displaying, as the primary client can not render it, but can be useful @@ -233,15 +231,16 @@ impl ReactionType { /// likely little use for it. pub fn as_data(&self) -> String { match *self { - ReactionType::Custom { id, ref name } => { - format!("{}:{}", name, id) - }, + ReactionType::Custom { + id, + ref name, + } => format!("{}:{}", name, id), ReactionType::Unicode(ref unicode) => unicode.clone(), } } } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl From<char> for ReactionType { /// Creates a `ReactionType` from a `char`. /// @@ -264,9 +263,7 @@ impl From<char> for ReactionType { /// # try_main().unwrap(); /// # } /// ``` - fn from(ch: char) -> ReactionType { - ReactionType::Unicode(ch.to_string()) - } + fn from(ch: char) -> ReactionType { ReactionType::Unicode(ch.to_string()) } } impl From<Emoji> for ReactionType { @@ -279,9 +276,7 @@ impl From<Emoji> for ReactionType { } impl From<String> for ReactionType { - fn from(unicode: String) -> ReactionType { - ReactionType::Unicode(unicode) - } + fn from(unicode: String) -> ReactionType { ReactionType::Unicode(unicode) } } impl<'a> From<&'a str> for ReactionType { @@ -301,9 +296,7 @@ impl<'a> From<&'a str> for ReactionType { /// /// foo("🍎"); /// ``` - fn from(unicode: &str) -> ReactionType { - ReactionType::Unicode(unicode.to_owned()) - } + fn from(unicode: &str) -> ReactionType { ReactionType::Unicode(unicode.to_owned()) } } impl Display for ReactionType { @@ -320,7 +313,10 @@ impl Display for ReactionType { /// [`ReactionType::Unicode`]: enum.ReactionType.html#variant.Unicode fn fmt(&self, f: &mut Formatter) -> FmtResult { match *self { - ReactionType::Custom { id, ref name } => { + ReactionType::Custom { + id, + ref name, + } => { f.write_char('<')?; f.write_char(':')?; f.write_str(name)?; diff --git a/src/model/error.rs b/src/model/error.rs index eb52bd8..fa24272 100644 --- a/src/model/error.rs +++ b/src/model/error.rs @@ -44,7 +44,7 @@ use super::Permissions; /// println!("Unexpected error: {:?}", why); /// }, /// } -/// } +/// } /// } /// let token = env::var("DISCORD_BOT_TOKEN")?; /// let mut client = Client::new(&token, Handler); client.start()?; @@ -112,9 +112,7 @@ pub enum Error { } impl Display for Error { - fn fmt(&self, f: &mut Formatter) -> FmtResult { - f.write_str(self.description()) - } + fn fmt(&self, f: &mut Formatter) -> FmtResult { f.write_str(self.description()) } } impl StdError for Error { diff --git a/src/model/event.rs b/src/model/event.rs index 86825fa..32ef560 100644 --- a/src/model/event.rs +++ b/src/model/event.rs @@ -3,18 +3,18 @@ use chrono::{DateTime, FixedOffset}; use serde::de::Error as DeError; use serde_json; -#[cfg(feature="voice")] +#[cfg(feature = "voice")] use serde_json::Error as JsonError; use std::collections::HashMap; use super::utils::deserialize_emojis; use super::*; -use ::constants::VoiceOpCode; -use ::internal::prelude::*; +use constants::VoiceOpCode; +use internal::prelude::*; -#[cfg(feature="gateway")] -use ::constants::OpCode; -#[cfg(feature="gateway")] -use ::gateway::GatewayError; +#[cfg(feature = "gateway")] +use constants::OpCode; +#[cfg(feature = "gateway")] +use gateway::GatewayError; /// Event data for the channel creation event. /// @@ -37,8 +37,8 @@ pub struct ChannelCreateEvent { impl<'de> Deserialize<'de> for ChannelCreateEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - channel: Channel::deserialize(deserializer)?, - }) + channel: Channel::deserialize(deserializer)?, + }) } } @@ -50,8 +50,8 @@ pub struct ChannelDeleteEvent { impl<'de> Deserialize<'de> for ChannelDeleteEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - channel: Channel::deserialize(deserializer)?, - }) + channel: Channel::deserialize(deserializer)?, + }) } } @@ -81,8 +81,8 @@ pub struct ChannelUpdateEvent { impl<'de> Deserialize<'de> for ChannelUpdateEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - channel: Channel::deserialize(deserializer)?, - }) + channel: Channel::deserialize(deserializer)?, + }) } } @@ -106,8 +106,8 @@ pub struct GuildCreateEvent { impl<'de> Deserialize<'de> for GuildCreateEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - guild: Guild::deserialize(deserializer)?, - }) + guild: Guild::deserialize(deserializer)?, + }) } } @@ -119,14 +119,14 @@ pub struct GuildDeleteEvent { impl<'de> Deserialize<'de> for GuildDeleteEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - guild: PartialGuild::deserialize(deserializer)?, - }) + guild: PartialGuild::deserialize(deserializer)?, + }) } } #[derive(Clone, Debug, Deserialize)] pub struct GuildEmojisUpdateEvent { - #[serde(deserialize_with="deserialize_emojis")] + #[serde(deserialize_with = "deserialize_emojis")] pub emojis: HashMap<EmojiId, Emoji>, pub guild_id: GuildId, } @@ -152,9 +152,10 @@ impl<'de> Deserialize<'de> for GuildMemberAddEvent { .map_err(DeError::custom)?; Ok(GuildMemberAddEvent { - guild_id: guild_id, - member: Member::deserialize(Value::Object(map)).map_err(DeError::custom)?, - }) + guild_id: guild_id, + member: Member::deserialize(Value::Object(map)) + .map_err(DeError::custom)?, + }) } } @@ -187,7 +188,8 @@ impl<'de> Deserialize<'de> for GuildMembersChunkEvent { .and_then(|v| GuildId::deserialize(v.clone())) .map_err(DeError::custom)?; - let mut members = map.remove("members").ok_or_else(|| DeError::custom("missing member chunk members"))?; + let mut members = map.remove("members") + .ok_or_else(|| DeError::custom("missing member chunk members"))?; if let Some(members) = members.as_array_mut() { let num = Value::Number(Number::from(guild_id.0)); @@ -199,13 +201,13 @@ impl<'de> Deserialize<'de> for GuildMembersChunkEvent { } } - let members: HashMap<UserId, Member> = Deserialize::deserialize(members) - .map_err(DeError::custom)?; + let members: HashMap<UserId, Member> = + Deserialize::deserialize(members).map_err(DeError::custom)?; Ok(GuildMembersChunkEvent { - guild_id: guild_id, - members: members, - }) + guild_id: guild_id, + members: members, + }) } } @@ -229,7 +231,7 @@ pub struct GuildRoleUpdateEvent { #[derive(Clone, Debug, Deserialize)] pub struct GuildUnavailableEvent { - #[serde(rename="id")] + #[serde(rename = "id")] pub guild_id: GuildId, } @@ -241,8 +243,8 @@ pub struct GuildUpdateEvent { impl<'de> Deserialize<'de> for GuildUpdateEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - guild: PartialGuild::deserialize(deserializer)?, - }) + guild: PartialGuild::deserialize(deserializer)?, + }) } } @@ -254,8 +256,8 @@ pub struct MessageCreateEvent { impl<'de> Deserialize<'de> for MessageCreateEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - message: Message::deserialize(deserializer)?, - }) + message: Message::deserialize(deserializer)?, + }) } } @@ -268,7 +270,7 @@ pub struct MessageDeleteBulkEvent { #[derive(Clone, Copy, Debug, Deserialize)] pub struct MessageDeleteEvent { pub channel_id: ChannelId, - #[serde(rename="id")] + #[serde(rename = "id")] pub message_id: MessageId, } @@ -303,20 +305,27 @@ impl<'de> Deserialize<'de> for PresenceUpdateEvent { let mut map = JsonMap::deserialize(deserializer)?; let guild_id = match map.remove("guild_id") { - Some(v) => serde_json::from_value::<Option<GuildId>>(v).map_err(DeError::custom)?, + Some(v) => { + serde_json::from_value::<Option<GuildId>>(v) + .map_err(DeError::custom)? + }, None => None, }; let roles = match map.remove("roles") { - Some(v) => serde_json::from_value::<Option<Vec<RoleId>>>(v).map_err(DeError::custom)?, + Some(v) => { + serde_json::from_value::<Option<Vec<RoleId>>>(v) + .map_err(DeError::custom)? + }, None => None, }; - let presence = Presence::deserialize(Value::Object(map)).map_err(DeError::custom)?; + let presence = Presence::deserialize(Value::Object(map)) + .map_err(DeError::custom)?; Ok(Self { - guild_id: guild_id, - presence: presence, - roles: roles, - }) + guild_id: guild_id, + presence: presence, + roles: roles, + }) } } @@ -330,8 +339,8 @@ impl<'de> Deserialize<'de> for PresencesReplaceEvent { let presences: Vec<Presence> = Deserialize::deserialize(deserializer)?; Ok(Self { - presences: presences, - }) + presences: presences, + }) } } @@ -343,8 +352,8 @@ pub struct ReactionAddEvent { impl<'de> Deserialize<'de> for ReactionAddEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - reaction: Reaction::deserialize(deserializer)?, - }) + reaction: Reaction::deserialize(deserializer)?, + }) } } @@ -356,8 +365,8 @@ pub struct ReactionRemoveEvent { impl<'de> Deserialize<'de> for ReactionRemoveEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - reaction: Reaction::deserialize(deserializer)?, - }) + reaction: Reaction::deserialize(deserializer)?, + }) } } @@ -376,14 +385,14 @@ pub struct ReadyEvent { impl<'de> Deserialize<'de> for ReadyEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - ready: Ready::deserialize(deserializer)?, - }) + ready: Ready::deserialize(deserializer)?, + }) } } #[derive(Clone, Debug, Deserialize)] pub struct ResumedEvent { - #[serde(rename="_trace")] + #[serde(rename = "_trace")] pub trace: Vec<Option<String>>, } @@ -408,8 +417,8 @@ pub struct UserUpdateEvent { impl<'de> Deserialize<'de> for UserUpdateEvent { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { Ok(Self { - current_user: CurrentUser::deserialize(deserializer)?, - }) + current_user: CurrentUser::deserialize(deserializer)?, + }) } } @@ -436,9 +445,10 @@ impl<'de> Deserialize<'de> for VoiceStateUpdateEvent { }; Ok(VoiceStateUpdateEvent { - guild_id: guild_id, - voice_state: VoiceState::deserialize(Value::Object(map)).map_err(DeError::custom)?, - }) + guild_id: guild_id, + voice_state: VoiceState::deserialize(Value::Object(map)) + .map_err(DeError::custom)?, + }) } } @@ -460,7 +470,7 @@ pub enum GatewayEvent { } impl GatewayEvent { - #[cfg(feature="gateway")] + #[cfg(feature = "gateway")] pub fn decode(value: Value) -> Result<Self> { let mut map = JsonMap::deserialize(value)?; @@ -469,40 +479,41 @@ impl GatewayEvent { .and_then(OpCode::deserialize)?; Ok(match op { - OpCode::Event => { - let s = map.remove("s") - .ok_or_else(|| DeError::custom("expected gateway event sequence")) - .and_then(u64::deserialize)?; - let t = map.remove("t") - .ok_or_else(|| DeError::custom("expected gateway event type")) - .and_then(String::deserialize)?; - let d = map.remove("d") + OpCode::Event => { + let s = map.remove("s") + .ok_or_else(|| DeError::custom("expected gateway event sequence")) + .and_then(u64::deserialize)?; + let t = map.remove("t") + .ok_or_else(|| DeError::custom("expected gateway event type")) + .and_then(String::deserialize)?; + let d = + map.remove("d") .ok_or_else(|| Error::Decode("expected gateway event d", Value::Object(map)))?; - GatewayEvent::Dispatch(s, Event::decode(t, d)?) - }, - OpCode::Heartbeat => { - let s = map.remove("s") - .ok_or_else(|| DeError::custom("Expected heartbeat s")) - .and_then(u64::deserialize)?; - - GatewayEvent::Heartbeat(s) - }, - OpCode::Reconnect => GatewayEvent::Reconnect, - OpCode::InvalidSession => GatewayEvent::InvalidateSession, - OpCode::Hello => { - let mut d = map.remove("d") - .ok_or_else(|| DeError::custom("expected gateway hello d")) - .and_then(JsonMap::deserialize)?; - let interval = d.remove("heartbeat_interval") - .ok_or_else(|| DeError::custom("expected gateway hello interval")) - .and_then(u64::deserialize)?; - - GatewayEvent::Hello(interval) - }, - OpCode::HeartbeatAck => GatewayEvent::HeartbeatAck, - _ => return Err(Error::Gateway(GatewayError::InvalidOpCode)), - }) + GatewayEvent::Dispatch(s, Event::decode(t, d)?) + }, + OpCode::Heartbeat => { + let s = map.remove("s") + .ok_or_else(|| DeError::custom("Expected heartbeat s")) + .and_then(u64::deserialize)?; + + GatewayEvent::Heartbeat(s) + }, + OpCode::Reconnect => GatewayEvent::Reconnect, + OpCode::InvalidSession => GatewayEvent::InvalidateSession, + OpCode::Hello => { + let mut d = map.remove("d") + .ok_or_else(|| DeError::custom("expected gateway hello d")) + .and_then(JsonMap::deserialize)?; + let interval = d.remove("heartbeat_interval") + .ok_or_else(|| DeError::custom("expected gateway hello interval")) + .and_then(u64::deserialize)?; + + GatewayEvent::Hello(interval) + }, + OpCode::HeartbeatAck => GatewayEvent::HeartbeatAck, + _ => return Err(Error::Gateway(GatewayError::InvalidOpCode)), + }) } } @@ -528,7 +539,8 @@ pub enum Event { /// Fires the [`Client::on_channel_pins_update`] event. /// /// [`Channel`]: ../enum.Channel.html - /// [`Client::on_channel_pins_update`]: ../../client/struct.Client.html#on_channel_pins_update + /// [`Client::on_channel_pins_update`]: + /// ../../client/struct.Client.html#on_channel_pins_update ChannelPinsUpdate(ChannelPinsUpdateEvent), /// A [`User`] has been added to a [`Group`]. /// @@ -587,7 +599,8 @@ pub enum Event { /// /// Fires the [`on_message_reaction_remove`] event handler. /// - /// [`on_message_reaction_remove`]: ../client/struct.Client.html#method.on_message_reaction_remove + /// [`on_message_reaction_remove`]: + /// ../client/struct.Client.html#method.on_message_reaction_remove ReactionRemove(ReactionRemoveEvent), /// A request was issued to remove all [`Reaction`]s from a [`Message`]. /// @@ -622,66 +635,110 @@ pub enum Event { impl Event { #[allow(cyclomatic_complexity)] - #[cfg(feature="gateway")] + #[cfg(feature = "gateway")] fn decode(kind: String, value: Value) -> Result<Event> { Ok(match &kind[..] { - "CHANNEL_CREATE" => Event::ChannelCreate(ChannelCreateEvent::deserialize(value)?), - "CHANNEL_DELETE" => Event::ChannelDelete(ChannelDeleteEvent::deserialize(value)?), - "CHANNEL_PINS_UPDATE" => Event::ChannelPinsUpdate(ChannelPinsUpdateEvent::deserialize(value)?), - "CHANNEL_RECIPIENT_ADD" => Event::ChannelRecipientAdd(ChannelRecipientAddEvent::deserialize(value)?), - "CHANNEL_RECIPIENT_REMOVE" => Event::ChannelRecipientRemove(ChannelRecipientRemoveEvent::deserialize(value)?), - "CHANNEL_UPDATE" => Event::ChannelUpdate(ChannelUpdateEvent::deserialize(value)?), - "GUILD_BAN_ADD" => Event::GuildBanAdd(GuildBanAddEvent::deserialize(value)?), - "GUILD_BAN_REMOVE" => Event::GuildBanRemove(GuildBanRemoveEvent::deserialize(value)?), - "GUILD_CREATE" => { - let mut map = JsonMap::deserialize(value)?; - - if map.remove("unavailable").and_then(|v| v.as_bool()).unwrap_or(false) { - Event::GuildUnavailable(GuildUnavailableEvent::deserialize(Value::Object(map))?) - } else { - Event::GuildCreate(GuildCreateEvent::deserialize(Value::Object(map))?) - } - }, - "GUILD_DELETE" => { - let mut map = JsonMap::deserialize(value)?; - - if map.remove("unavailable").and_then(|v| v.as_bool()).unwrap_or(false) { - Event::GuildUnavailable(GuildUnavailableEvent::deserialize(Value::Object(map))?) - } else { - Event::GuildDelete(GuildDeleteEvent::deserialize(Value::Object(map))?) - } - }, - "GUILD_EMOJIS_UPDATE" => Event::GuildEmojisUpdate(GuildEmojisUpdateEvent::deserialize(value)?), - "GUILD_INTEGRATIONS_UPDATE" => Event::GuildIntegrationsUpdate(GuildIntegrationsUpdateEvent::deserialize(value)?), - "GUILD_MEMBER_ADD" => Event::GuildMemberAdd(GuildMemberAddEvent::deserialize(value)?), - "GUILD_MEMBER_REMOVE" => Event::GuildMemberRemove(GuildMemberRemoveEvent::deserialize(value)?), - "GUILD_MEMBER_UPDATE" => Event::GuildMemberUpdate(GuildMemberUpdateEvent::deserialize(value)?), - "GUILD_MEMBERS_CHUNK" => Event::GuildMembersChunk(GuildMembersChunkEvent::deserialize(value)?), - "GUILD_ROLE_CREATE" => Event::GuildRoleCreate(GuildRoleCreateEvent::deserialize(value)?), - "GUILD_ROLE_DELETE" => Event::GuildRoleDelete(GuildRoleDeleteEvent::deserialize(value)?), - "GUILD_ROLE_UPDATE" => Event::GuildRoleUpdate(GuildRoleUpdateEvent::deserialize(value)?), - "GUILD_UPDATE" => Event::GuildUpdate(GuildUpdateEvent::deserialize(value)?), - "MESSAGE_CREATE" => Event::MessageCreate(MessageCreateEvent::deserialize(value)?), - "MESSAGE_DELETE" => Event::MessageDelete(MessageDeleteEvent::deserialize(value)?), - "MESSAGE_DELETE_BULK" => Event::MessageDeleteBulk(MessageDeleteBulkEvent::deserialize(value)?), - "MESSAGE_REACTION_ADD" => Event::ReactionAdd(ReactionAddEvent::deserialize(value)?), - "MESSAGE_REACTION_REMOVE" => Event::ReactionRemove(ReactionRemoveEvent::deserialize(value)?), - "MESSAGE_REACTION_REMOVE_ALL" => Event::ReactionRemoveAll(ReactionRemoveAllEvent::deserialize(value)?), - "MESSAGE_UPDATE" => Event::MessageUpdate(MessageUpdateEvent::deserialize(value)?), - "PRESENCE_UPDATE" => Event::PresenceUpdate(PresenceUpdateEvent::deserialize(value)?), - "PRESENCES_REPLACE" => Event::PresencesReplace(PresencesReplaceEvent::deserialize(value)?), - "READY" => Event::Ready(ReadyEvent::deserialize(value)?), - "RESUMED" => Event::Resumed(ResumedEvent::deserialize(value)?), - "TYPING_START" => Event::TypingStart(TypingStartEvent::deserialize(value)?), - "USER_UPDATE" => Event::UserUpdate(UserUpdateEvent::deserialize(value)?), - "VOICE_SERVER_UPDATE" => Event::VoiceServerUpdate(VoiceServerUpdateEvent::deserialize(value)?), - "VOICE_STATE_UPDATE" => Event::VoiceStateUpdate(VoiceStateUpdateEvent::deserialize(value)?), - "WEBHOOKS_UPDATE" => Event::WebhookUpdate(WebhookUpdateEvent::deserialize(value)?), - _ => Event::Unknown(UnknownEvent { - kind: kind, - value: value, - }), - }) + "CHANNEL_CREATE" => Event::ChannelCreate(ChannelCreateEvent::deserialize(value)?), + "CHANNEL_DELETE" => Event::ChannelDelete(ChannelDeleteEvent::deserialize(value)?), + "CHANNEL_PINS_UPDATE" => { + Event::ChannelPinsUpdate(ChannelPinsUpdateEvent::deserialize(value)?) + }, + "CHANNEL_RECIPIENT_ADD" => { + Event::ChannelRecipientAdd(ChannelRecipientAddEvent::deserialize(value)?) + }, + "CHANNEL_RECIPIENT_REMOVE" => { + Event::ChannelRecipientRemove(ChannelRecipientRemoveEvent::deserialize(value)?) + }, + "CHANNEL_UPDATE" => Event::ChannelUpdate(ChannelUpdateEvent::deserialize(value)?), + "GUILD_BAN_ADD" => Event::GuildBanAdd(GuildBanAddEvent::deserialize(value)?), + "GUILD_BAN_REMOVE" => { + Event::GuildBanRemove(GuildBanRemoveEvent::deserialize(value)?) + }, + "GUILD_CREATE" => { + let mut map = JsonMap::deserialize(value)?; + + if map.remove("unavailable") + .and_then(|v| v.as_bool()) + .unwrap_or(false) { + Event::GuildUnavailable(GuildUnavailableEvent::deserialize(Value::Object(map))?) + } else { + Event::GuildCreate(GuildCreateEvent::deserialize(Value::Object(map))?) + } + }, + "GUILD_DELETE" => { + let mut map = JsonMap::deserialize(value)?; + + if map.remove("unavailable") + .and_then(|v| v.as_bool()) + .unwrap_or(false) { + Event::GuildUnavailable(GuildUnavailableEvent::deserialize(Value::Object(map))?) + } else { + Event::GuildDelete(GuildDeleteEvent::deserialize(Value::Object(map))?) + } + }, + "GUILD_EMOJIS_UPDATE" => { + Event::GuildEmojisUpdate(GuildEmojisUpdateEvent::deserialize(value)?) + }, + "GUILD_INTEGRATIONS_UPDATE" => { + Event::GuildIntegrationsUpdate(GuildIntegrationsUpdateEvent::deserialize(value)?) + }, + "GUILD_MEMBER_ADD" => { + Event::GuildMemberAdd(GuildMemberAddEvent::deserialize(value)?) + }, + "GUILD_MEMBER_REMOVE" => { + Event::GuildMemberRemove(GuildMemberRemoveEvent::deserialize(value)?) + }, + "GUILD_MEMBER_UPDATE" => { + Event::GuildMemberUpdate(GuildMemberUpdateEvent::deserialize(value)?) + }, + "GUILD_MEMBERS_CHUNK" => { + Event::GuildMembersChunk(GuildMembersChunkEvent::deserialize(value)?) + }, + "GUILD_ROLE_CREATE" => { + Event::GuildRoleCreate(GuildRoleCreateEvent::deserialize(value)?) + }, + "GUILD_ROLE_DELETE" => { + Event::GuildRoleDelete(GuildRoleDeleteEvent::deserialize(value)?) + }, + "GUILD_ROLE_UPDATE" => { + Event::GuildRoleUpdate(GuildRoleUpdateEvent::deserialize(value)?) + }, + "GUILD_UPDATE" => Event::GuildUpdate(GuildUpdateEvent::deserialize(value)?), + "MESSAGE_CREATE" => Event::MessageCreate(MessageCreateEvent::deserialize(value)?), + "MESSAGE_DELETE" => Event::MessageDelete(MessageDeleteEvent::deserialize(value)?), + "MESSAGE_DELETE_BULK" => { + Event::MessageDeleteBulk(MessageDeleteBulkEvent::deserialize(value)?) + }, + "MESSAGE_REACTION_ADD" => Event::ReactionAdd(ReactionAddEvent::deserialize(value)?), + "MESSAGE_REACTION_REMOVE" => { + Event::ReactionRemove(ReactionRemoveEvent::deserialize(value)?) + }, + "MESSAGE_REACTION_REMOVE_ALL" => { + Event::ReactionRemoveAll(ReactionRemoveAllEvent::deserialize(value)?) + }, + "MESSAGE_UPDATE" => Event::MessageUpdate(MessageUpdateEvent::deserialize(value)?), + "PRESENCE_UPDATE" => Event::PresenceUpdate(PresenceUpdateEvent::deserialize(value)?), + "PRESENCES_REPLACE" => { + Event::PresencesReplace(PresencesReplaceEvent::deserialize(value)?) + }, + "READY" => Event::Ready(ReadyEvent::deserialize(value)?), + "RESUMED" => Event::Resumed(ResumedEvent::deserialize(value)?), + "TYPING_START" => Event::TypingStart(TypingStartEvent::deserialize(value)?), + "USER_UPDATE" => Event::UserUpdate(UserUpdateEvent::deserialize(value)?), + "VOICE_SERVER_UPDATE" => { + Event::VoiceServerUpdate(VoiceServerUpdateEvent::deserialize(value)?) + }, + "VOICE_STATE_UPDATE" => { + Event::VoiceStateUpdate(VoiceStateUpdateEvent::deserialize(value)?) + }, + "WEBHOOKS_UPDATE" => Event::WebhookUpdate(WebhookUpdateEvent::deserialize(value)?), + _ => { + Event::Unknown(UnknownEvent { + kind: kind, + value: value, + }) + }, + }) } } @@ -735,32 +792,42 @@ pub enum VoiceEvent { /// A voice event denoting that someone is speaking. Speaking(VoiceSpeaking), /// An unknown voice event not registered. - Unknown(VoiceOpCode, Value) + Unknown(VoiceOpCode, Value), } impl VoiceEvent { - #[cfg(feature="voice")] + #[cfg(feature = "voice")] pub(crate) fn decode(value: Value) -> Result<VoiceEvent> { let mut map = JsonMap::deserialize(value)?; let op = match map.remove("op") { - Some(v) => VoiceOpCode::deserialize(v).map_err(JsonError::from).map_err(Error::from)?, + Some(v) => { + VoiceOpCode::deserialize(v) + .map_err(JsonError::from) + .map_err(Error::from)? + }, None => return Err(Error::Decode("expected voice event op", Value::Object(map))), }; let d = match map.remove("d") { - Some(v) => JsonMap::deserialize(v).map_err(JsonError::from).map_err(Error::from)?, + Some(v) => { + JsonMap::deserialize(v) + .map_err(JsonError::from) + .map_err(Error::from)? + }, None => return Err(Error::Decode("expected voice gateway d", Value::Object(map))), }; let v = Value::Object(d); Ok(match op { - VoiceOpCode::Heartbeat => VoiceEvent::Heartbeat(VoiceHeartbeat::deserialize(v)?), - VoiceOpCode::Hello => VoiceEvent::Hello(VoiceHello::deserialize(v)?), - VoiceOpCode::KeepAlive => VoiceEvent::KeepAlive, - VoiceOpCode::SessionDescription => VoiceEvent::Ready(VoiceSessionDescription::deserialize(v)?), - VoiceOpCode::Speaking => VoiceEvent::Speaking(VoiceSpeaking::deserialize(v)?), - other => VoiceEvent::Unknown(other, v), - }) + VoiceOpCode::Heartbeat => VoiceEvent::Heartbeat(VoiceHeartbeat::deserialize(v)?), + VoiceOpCode::Hello => VoiceEvent::Hello(VoiceHello::deserialize(v)?), + VoiceOpCode::KeepAlive => VoiceEvent::KeepAlive, + VoiceOpCode::SessionDescription => { + VoiceEvent::Ready(VoiceSessionDescription::deserialize(v)?) + }, + VoiceOpCode::Speaking => VoiceEvent::Speaking(VoiceSpeaking::deserialize(v)?), + other => VoiceEvent::Unknown(other, v), + }) } } diff --git a/src/model/gateway.rs b/src/model/gateway.rs index 8458bbb..b0aed98 100644 --- a/src/model/gateway.rs +++ b/src/model/gateway.rs @@ -34,7 +34,7 @@ pub struct Game { pub url: Option<String>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Game { /// Creates a `Game` struct that appears as a `Playing <name>` status. /// @@ -51,7 +51,7 @@ impl Game { /// /// command!(game(ctx, _msg, args) { /// let name = args.join(" "); - /// ctx.set_game(Game::playing(&name)); + /// ctx.set_game(Game::playing(&name)); /// }); /// # /// # fn main() {} @@ -80,7 +80,7 @@ impl Game { /// // Assumes command has min_args set to 2. /// command!(stream(ctx, _msg, args, stream: String) { /// let name = args[1..].join(" "); - /// ctx.set_game(Game::streaming(&name, &stream)); + /// ctx.set_game(Game::streaming(&name, &stream)); /// }); /// # /// # fn main() {} @@ -103,13 +103,14 @@ impl<'de> Deserialize<'de> for Game { let name = map.remove("name") .and_then(|v| String::deserialize(v).ok()) .unwrap_or_else(String::new); - let url = map.remove("url").and_then(|v| serde_json::from_value::<String>(v).ok()); + let url = map.remove("url") + .and_then(|v| serde_json::from_value::<String>(v).ok()); Ok(Game { - kind: kind, - name: name, - url: url - }) + kind: kind, + name: name, + url: url, + }) } } @@ -124,9 +125,7 @@ enum_number!( ); impl Default for GameType { - fn default() -> Self { - GameType::Playing - } + fn default() -> Self { GameType::Playing } } /// A representation of the data retrieved from the gateway endpoint. @@ -171,11 +170,13 @@ impl<'de> Deserialize<'de> for Presence { .map_err(DeError::custom)?; let (user_id, user) = if user_map.len() > 1 { - let user = User::deserialize(Value::Object(user_map)).map_err(DeError::custom)?; + let user = User::deserialize(Value::Object(user_map)) + .map_err(DeError::custom)?; (user.id, Some(Arc::new(RwLock::new(user)))) } else { - let user_id = user_map.remove("id") + let user_id = user_map + .remove("id") .ok_or_else(|| DeError::custom("Missing presence user id")) .and_then(|x| UserId::deserialize(x.clone())) .map_err(DeError::custom)?; @@ -184,7 +185,10 @@ impl<'de> Deserialize<'de> for Presence { }; let game = match map.remove("game") { - Some(v) => serde_json::from_value::<Option<Game>>(v).map_err(DeError::custom)?, + Some(v) => { + serde_json::from_value::<Option<Game>>(v) + .map_err(DeError::custom)? + }, None => None, }; let last_modified = match map.remove("last_modified") { @@ -192,7 +196,10 @@ impl<'de> Deserialize<'de> for Presence { None => None, }; let nick = match map.remove("nick") { - Some(v) => serde_json::from_value::<Option<String>>(v).map_err(DeError::custom)?, + Some(v) => { + serde_json::from_value::<Option<String>>(v) + .map_err(DeError::custom)? + }, None => None, }; let status = map.remove("status") @@ -201,13 +208,13 @@ impl<'de> Deserialize<'de> for Presence { .map_err(DeError::custom)?; Ok(Presence { - game: game, - last_modified: last_modified, - nick: nick, - status: status, - user: user, - user_id: user_id, - }) + game: game, + last_modified: last_modified, + nick: nick, + status: status, + user: user, + user_id: user_id, + }) } } @@ -215,15 +222,15 @@ impl<'de> Deserialize<'de> for Presence { #[derive(Clone, Debug, Deserialize)] pub struct Ready { pub guilds: Vec<GuildStatus>, - #[serde(deserialize_with="deserialize_presences")] + #[serde(deserialize_with = "deserialize_presences")] pub presences: HashMap<UserId, Presence>, - #[serde(deserialize_with="deserialize_private_channels")] + #[serde(deserialize_with = "deserialize_private_channels")] pub private_channels: HashMap<ChannelId, Channel>, pub session_id: String, pub shard: Option<[u64; 2]>, - #[serde(default, rename="_trace")] + #[serde(default, rename = "_trace")] pub trace: Vec<String>, pub user: CurrentUser, - #[serde(rename="v")] + #[serde(rename = "v")] pub version: u64, } diff --git a/src/model/guild/audit_log.rs b/src/model/guild/audit_log.rs index a5097b2..020ad77 100644 --- a/src/model/guild/audit_log.rs +++ b/src/model/guild/audit_log.rs @@ -1,5 +1,5 @@ -use super::super::{UserId, AuditLogEntryId}; -use serde::de::{self, Deserialize, Deserializer, Visitor, MapAccess}; +use super::super::{AuditLogEntryId, UserId}; +use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor}; use std::fmt; use std::collections::HashMap; @@ -45,11 +45,11 @@ pub enum Action { #[derive(Deserialize)] pub struct Change { - #[serde(rename="key")] + #[serde(rename = "key")] pub name: String, - #[serde(rename="old_value")] + #[serde(rename = "old_value")] pub old: String, - #[serde(rename="new_value")] + #[serde(rename = "new_value")] pub new: String, } @@ -62,12 +62,12 @@ pub struct AuditLogEntry { /// Determines to what entity an [`action`] was used on. /// /// [`action`]: #structfield.action - #[serde(deserialize_with="deserialize_target", rename="target_type")] + #[serde(deserialize_with = "deserialize_target", rename = "target_type")] pub target: Target, /// Determines what action was done on a [`target`] /// /// [`target`]: #structfield.target - #[serde(deserialize_with="deserialize_action", rename="action_type")] + #[serde(deserialize_with = "deserialize_action", rename = "action_type")] pub action: Action, /// What was the reasoning by doing an action on a target? If there was one. pub reason: Option<String>, @@ -77,7 +77,6 @@ pub struct AuditLogEntry { pub changes: Vec<Change>, /// The id of this entry. pub id: AuditLogEntryId, - } fn deserialize_target<'de, D: Deserializer<'de>>(de: D) -> Result<Target, D::Error> { @@ -92,22 +91,22 @@ fn deserialize_target<'de, D: Deserializer<'de>>(de: D) -> Result<Target, D::Err fn visit_i32<E: de::Error>(self, value: i32) -> Result<Target, E> { Ok(if value < 10 { - Target::Guild - } else if value < 20 { - Target::Channel - } else if value < 30 { - Target::User - } else if value < 40 { - Target::Role - } else if value < 50 { - Target::Invite - } else if value < 60 { - Target::Webhook - } else if value < 70 { - Target::Emoji - } else { - return Err(E::custom(format!("Unexpected target number: {}", value))); - }) + Target::Guild + } else if value < 20 { + Target::Channel + } else if value < 30 { + Target::User + } else if value < 40 { + Target::Role + } else if value < 50 { + Target::Invite + } else if value < 60 { + Target::Webhook + } else if value < 70 { + Target::Emoji + } else { + return Err(E::custom(format!("Unexpected target number: {}", value))); + }) } } @@ -127,58 +126,58 @@ fn deserialize_action<'de, D: Deserializer<'de>>(de: D) -> Result<Action, D::Err fn visit_i32<E: de::Error>(self, value: i32) -> Result<Action, E> { // todo: improve this Ok(if value == 1 { - Action::GuildUpdate - } else if value == 10 { - Action::ChannelCreate - } else if value == 11 { - Action::ChannelUpdate - } else if value == 12 { - Action::ChannelDelete - } else if value == 13 { - Action::ChannelOverwriteCreate - } else if value == 14 { - Action::ChannelOverwriteUpdate - } else if value == 15 { - Action::ChannelOverwriteDelete - } else if value == 20 { - Action::MemberKick - } else if value == 21 { - Action::MemberPrune - } else if value == 22 { - Action::MemberBanAdd - } else if value == 23 { - Action::MemberBanRemove - } else if value == 24 { - Action::MemberUpdate - } else if value == 25 { - Action::MemberRoleUpdate - } else if value == 30 { - Action::RoleCreate - } else if value == 31 { - Action::RoleUpdate - } else if value == 32 { - Action::RoleDelete - } else if value == 40 { - Action::InviteCreate - } else if value == 41 { - Action::InviteUpdate - } else if value == 42 { - Action::InviteDelete - } else if value == 50 { - Action::WebhookCreate - } else if value == 51 { - Action::WebhookUpdate - } else if value == 52 { - Action::WebhookDelete - } else if value == 60 { - Action::EmojiCreate - } else if value == 61 { - Action::EmojiUpdate - } else if value == 62 { - Action::EmojiDelete - } else { - return Err(E::custom(format!("Unexpected action number: {}", value))); - }) + Action::GuildUpdate + } else if value == 10 { + Action::ChannelCreate + } else if value == 11 { + Action::ChannelUpdate + } else if value == 12 { + Action::ChannelDelete + } else if value == 13 { + Action::ChannelOverwriteCreate + } else if value == 14 { + Action::ChannelOverwriteUpdate + } else if value == 15 { + Action::ChannelOverwriteDelete + } else if value == 20 { + Action::MemberKick + } else if value == 21 { + Action::MemberPrune + } else if value == 22 { + Action::MemberBanAdd + } else if value == 23 { + Action::MemberBanRemove + } else if value == 24 { + Action::MemberUpdate + } else if value == 25 { + Action::MemberRoleUpdate + } else if value == 30 { + Action::RoleCreate + } else if value == 31 { + Action::RoleUpdate + } else if value == 32 { + Action::RoleDelete + } else if value == 40 { + Action::InviteCreate + } else if value == 41 { + Action::InviteUpdate + } else if value == 42 { + Action::InviteDelete + } else if value == 50 { + Action::WebhookCreate + } else if value == 51 { + Action::WebhookUpdate + } else if value == 52 { + Action::WebhookDelete + } else if value == 60 { + Action::EmojiCreate + } else if value == 61 { + Action::EmojiUpdate + } else if value == 62 { + Action::EmojiDelete + } else { + return Err(E::custom(format!("Unexpected action number: {}", value))); + }) } } @@ -190,12 +189,12 @@ impl<'de> Deserialize<'de> for AuditLogs { #[derive(Deserialize)] #[serde(field_identifier)] enum Field { - #[serde(rename="audit_log_entries")] - AuditLogEntries + #[serde(rename = "audit_log_entries")] + AuditLogEntries, } struct EntriesVisitor; - + impl<'de> Visitor<'de> for EntriesVisitor { type Value = AuditLogs; @@ -209,16 +208,21 @@ impl<'de> Deserialize<'de> for AuditLogs { match key { Field::AuditLogEntries => { break map.next_value::<Vec<AuditLogEntry>>()?; - } + }, } } }; - Ok(AuditLogs { entries: audit_log_entries.into_iter().map(|entry| (entry.id, entry)).collect() }) + Ok(AuditLogs { + entries: audit_log_entries + .into_iter() + .map(|entry| (entry.id, entry)) + .collect(), + }) } } const FIELD: &'static [&'static str] = &["audit_log_entries"]; de.deserialize_struct("AuditLogs", FIELD, EntriesVisitor) } -}
\ No newline at end of file +} diff --git a/src/model/guild/emoji.rs b/src/model/guild/emoji.rs index 9a8ad39..3893f52 100644 --- a/src/model/guild/emoji.rs +++ b/src/model/guild/emoji.rs @@ -1,17 +1,17 @@ use std::fmt::{Display, Formatter, Result as FmtResult, Write as FmtWrite}; use super::super::{EmojiId, RoleId}; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] use std::mem; -#[cfg(all(feature="cache", feature="model"))] +#[cfg(all(feature = "cache", feature = "model"))] use super::super::ModelError; -#[cfg(feature="cache")] -use ::CACHE; -#[cfg(feature="cache")] -use ::internal::prelude::*; -#[cfg(all(feature="cache", feature="model"))] -use ::http; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] +use CACHE; +#[cfg(feature = "cache")] +use internal::prelude::*; +#[cfg(all(feature = "cache", feature = "model"))] +use http; +#[cfg(feature = "cache")] use super::super::GuildId; /// Represents a custom guild emoji, which can either be created using the API, @@ -38,7 +38,7 @@ pub struct Emoji { pub roles: Vec<RoleId>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Emoji { /// Deletes the emoji. /// @@ -69,7 +69,7 @@ impl Emoji { /// Err(_) => println!("Could not delete emoji.") /// } /// ``` - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn delete(&self) -> Result<()> { match self.find_guild_id() { Some(guild_id) => http::delete_emoji(guild_id.0, self.id.0), @@ -104,7 +104,7 @@ impl Emoji { /// let _ = emoji.edit("blobuwu"); /// assert_eq!(emoji.name, "blobuwu"); /// ``` - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn edit(&mut self, name: &str) -> Result<()> { match self.find_guild_id() { Some(guild_id) => { @@ -149,7 +149,7 @@ impl Emoji { /// println!("{} is owned by {}", emoji.name, guild_id); /// } /// ``` - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn find_guild_id(&self) -> Option<GuildId> { for guild in CACHE.read().unwrap().guilds.values() { let guild = guild.read().unwrap(); @@ -183,9 +183,7 @@ impl Emoji { /// println!("Direct link to emoji image: {}", emoji.url()); /// ``` #[inline] - pub fn url(&self) -> String { - format!(cdn!("/emojis/{}.png"), self.id) - } + pub fn url(&self) -> String { format!(cdn!("/emojis/{}.png"), self.id) } } impl Display for Emoji { @@ -203,21 +201,15 @@ impl Display for Emoji { } impl Display for EmojiId { - fn fmt(&self, f: &mut Formatter) -> FmtResult { - Display::fmt(&self.0, f) - } + fn fmt(&self, f: &mut Formatter) -> FmtResult { Display::fmt(&self.0, f) } } impl From<Emoji> for EmojiId { /// Gets the Id of an `Emoji`. - fn from(emoji: Emoji) -> EmojiId { - emoji.id - } + fn from(emoji: Emoji) -> EmojiId { emoji.id } } impl<'a> From<&'a Emoji> for EmojiId { /// Gets the Id of an `Emoji`. - fn from(emoji: &Emoji) -> EmojiId { - emoji.id - } + fn from(emoji: &Emoji) -> EmojiId { emoji.id } } diff --git a/src/model/guild/feature.rs b/src/model/guild/feature.rs index cfbcabc..40fd3fd 100644 --- a/src/model/guild/feature.rs +++ b/src/model/guild/feature.rs @@ -9,17 +9,17 @@ pub enum Feature { /// /// [`Guild`]: struct.Guild.html /// [`Guild::splash`]: struct.Guild.html#structfield.splash - #[serde(rename="INVITE_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")] + #[serde(rename = "VANITY_URL")] VanityUrl, /// The [`Guild`] has access to VIP voice channel regions. /// /// [`Guild`]: struct.Guild.html - #[serde(rename="VIP_REGIONS")] + #[serde(rename = "VIP_REGIONS")] VipRegions, } diff --git a/src/model/guild/guild_id.rs b/src/model/guild/guild_id.rs index 6fbaddf..a0b69d1 100644 --- a/src/model/guild/guild_id.rs +++ b/src/model/guild/guild_id.rs @@ -1,23 +1,21 @@ use std::fmt::{Display, Formatter, Result as FmtResult}; -use ::model::*; -use ::model::guild::BanOptions; - -#[cfg(feature="cache")] -use ::CACHE; -#[cfg(feature="model")] -use ::builder::{EditGuild, EditMember, EditRole}; -#[cfg(feature="model")] -use ::http; -#[cfg(feature="model")] -use ::internal::prelude::*; - -#[cfg(feature="model")] +use model::*; +use model::guild::BanOptions; + +#[cfg(feature = "cache")] +use CACHE; +#[cfg(feature = "model")] +use builder::{EditGuild, EditMember, EditRole}; +#[cfg(feature = "model")] +use http; +#[cfg(feature = "model")] +use internal::prelude::*; + +#[cfg(feature = "model")] impl GuildId { /// Converts the guild Id into the default channel's Id. #[inline] - pub fn as_channel_id(&self) -> ChannelId { - ChannelId(self.0) - } + pub fn as_channel_id(&self) -> ChannelId { ChannelId(self.0) } /// Ban a [`User`] from the guild. All messages by the /// user within the last given number of days given will be deleted. @@ -42,12 +40,12 @@ impl GuildId { /// Returns a [`ModelError::DeleteMessageDaysAmount`] if the number of /// days' worth of messages to delete is over the maximum. /// - /// [`ModelError::DeleteMessageDaysAmount`]: enum.ModelError.html#variant.DeleteMessageDaysAmount + /// [`ModelError::DeleteMessageDaysAmount`]: + /// enum.ModelError.html#variant.DeleteMessageDaysAmount /// [`Guild::ban`]: struct.Guild.html#method.ban /// [`User`]: struct.User.html /// [Ban Members]: permissions/constant.BAN_MEMBERS.html - pub fn ban<U: Into<UserId>, BO: BanOptions>(&self, user: U, ban_options: BO) - -> Result<()> { + pub fn ban<U: Into<UserId>, BO: BanOptions>(&self, user: U, ban_options: BO) -> Result<()> { let dmd = ban_options.dmd(); if dmd > 7 { return Err(Error::Model(ModelError::DeleteMessageDaysAmount(dmd))); @@ -68,15 +66,11 @@ impl GuildId { /// /// [Ban Members]: permissions/constant.BAN_MEMBERS.html #[inline] - pub fn bans(&self) -> Result<Vec<Ban>> { - http::get_bans(self.0) - } + pub fn bans(&self) -> Result<Vec<Ban>> { http::get_bans(self.0) } /// Gets a list of the guild's audit log entries #[inline] - pub fn audit_logs(&self) -> Result<AuditLogs> { - http::get_audit_logs(self.0) - } + pub fn audit_logs(&self) -> Result<AuditLogs> { http::get_audit_logs(self.0) } /// Gets all of the guild's channels over the REST API. /// @@ -150,8 +144,9 @@ impl GuildId { /// Requires the [Manage Guild] permission. /// /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html - pub fn create_integration<I>(&self, integration_id: I, kind: &str) - -> Result<()> where I: Into<IntegrationId> { + pub fn create_integration<I>(&self, integration_id: I, kind: &str) -> Result<()> + where + I: Into<IntegrationId>, { let integration_id = integration_id.into(); let map = json!({ "id": integration_id.0, @@ -183,9 +178,7 @@ impl GuildId { /// /// [`Guild::delete`]: struct.Guild.html#method.delete #[inline] - pub fn delete(&self) -> Result<PartialGuild> { - http::delete_guild(self.0) - } + pub fn delete(&self) -> Result<PartialGuild> { http::delete_guild(self.0) } /// Deletes an [`Emoji`] from the guild. /// @@ -270,7 +263,9 @@ impl GuildId { /// ``` #[inline] pub fn edit_member<F, U>(&self, user_id: U, f: F) -> Result<()> - where F: FnOnce(EditMember) -> EditMember, U: Into<UserId> { + where + F: FnOnce(EditMember) -> EditMember, + U: Into<UserId>, { http::edit_member(self.0, user_id.into().0, &f(EditMember::default()).0) } @@ -304,7 +299,9 @@ impl GuildId { /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html #[inline] pub fn edit_role<F, R>(&self, role_id: R, f: F) -> Result<Role> - where F: FnOnce(EditRole) -> EditRole, R: Into<RoleId> { + where + F: FnOnce(EditRole) -> EditRole, + R: Into<RoleId>, { http::edit_role(self.0, role_id.into().0, &f(EditRole::default()).0) } @@ -324,32 +321,24 @@ impl GuildId { /// /// [Manage Emojis]: permissions/constant.MANAGE_EMOJIS.html #[inline] - pub fn emojis(&self) -> Result<Vec<Emoji>> { - http::get_emojis(self.0) - } + pub fn emojis(&self) -> Result<Vec<Emoji>> { http::get_emojis(self.0) } /// Search the cache for the guild. - #[cfg(feature="cache")] - pub fn find(&self) -> Option<Arc<RwLock<Guild>>> { - CACHE.read().unwrap().guild(*self) - } + #[cfg(feature = "cache")] + pub fn find(&self) -> Option<Arc<RwLock<Guild>>> { CACHE.read().unwrap().guild(*self) } /// Requests the guild over REST. /// /// Note that this will not be a complete guild, as REST does not send /// all data with a guild retrieval. #[inline] - pub fn get(&self) -> Result<PartialGuild> { - http::get_guild(self.0) - } + pub fn get(&self) -> Result<PartialGuild> { http::get_guild(self.0) } /// Gets all integration of the guild. /// /// This performs a request over the REST API. #[inline] - pub fn integrations(&self) -> Result<Vec<Integration>> { - http::get_guild_integrations(self.0) - } + pub fn integrations(&self) -> Result<Vec<Integration>> { http::get_guild_integrations(self.0) } /// Gets all of the guild's invites. /// @@ -357,9 +346,7 @@ impl GuildId { /// /// [Manage Guild]: permissions/struct.MANAGE_GUILD.html #[inline] - pub fn invites(&self) -> Result<Vec<RichInvite>> { - http::get_guild_invites(self.0) - } + pub fn invites(&self) -> Result<Vec<RichInvite>> { http::get_guild_invites(self.0) } /// Kicks a [`Member`] from the guild. /// @@ -374,9 +361,7 @@ impl GuildId { /// Leaves the guild. #[inline] - pub fn leave(&self) -> Result<()> { - http::leave_guild(self.0) - } + pub fn leave(&self) -> Result<()> { http::leave_guild(self.0) } /// Gets a user's [`Member`] for the guild by Id. /// @@ -395,8 +380,9 @@ impl GuildId { /// /// [`User`]: struct.User.html #[inline] - pub fn members<U>(&self, limit: Option<u64>, after: Option<U>) - -> Result<Vec<Member>> where U: Into<UserId> { + pub fn members<U>(&self, limit: Option<u64>, after: Option<U>) -> Result<Vec<Member>> + where + U: Into<UserId>, { http::get_guild_members(self.0, limit, after.map(|x| x.into().0)) } @@ -405,10 +391,13 @@ impl GuildId { /// Requires the [Move Members] permission. /// /// [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> { + pub fn move_member<C, U>(&self, user_id: U, channel_id: C) -> Result<()> + where + C: Into<ChannelId>, + U: Into<UserId>, { let mut map = Map::new(); - map.insert("channel_id".to_owned(), Value::Number(Number::from(channel_id.into().0))); + map.insert("channel_id".to_owned(), + Value::Number(Number::from(channel_id.into().0))); http::edit_member(self.0, user_id.into().0, &map) } @@ -438,11 +427,9 @@ impl GuildId { /// total, consider using [`utils::shard_id`]. /// /// [`utils::shard_id`]: ../utils/fn.shard_id.html - #[cfg(all(feature="cache", feature="utils"))] + #[cfg(all(feature = "cache", feature = "utils"))] #[inline] - pub fn shard_id(&self) -> u64 { - ::utils::shard_id(self.0, CACHE.read().unwrap().shard_count) - } + pub fn shard_id(&self) -> u64 { ::utils::shard_id(self.0, CACHE.read().unwrap().shard_count) } /// Returns the Id of the shard associated with the guild. /// @@ -465,11 +452,9 @@ impl GuildId { /// /// assert_eq!(guild_id.shard_id(17), 7); /// ``` - #[cfg(all(feature="utils", not(feature="cache")))] + #[cfg(all(feature = "utils", not(feature = "cache")))] #[inline] - pub fn shard_id(&self, shard_count: u64) -> u64 { - ::utils::shard_id(self.0, shard_count) - } + pub fn shard_id(&self, shard_count: u64) -> u64 { ::utils::shard_id(self.0, shard_count) } /// Starts an integration sync for the given integration Id. /// @@ -516,69 +501,49 @@ impl GuildId { /// /// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html #[inline] - pub fn webhooks(&self) -> Result<Vec<Webhook>> { - http::get_guild_webhooks(self.0) - } + pub fn webhooks(&self) -> Result<Vec<Webhook>> { http::get_guild_webhooks(self.0) } } impl Display for GuildId { - fn fmt(&self, f: &mut Formatter) -> FmtResult { - Display::fmt(&self.0, f) - } + fn fmt(&self, f: &mut Formatter) -> FmtResult { Display::fmt(&self.0, f) } } impl From<PartialGuild> for GuildId { /// Gets the Id of a partial guild. - fn from(guild: PartialGuild) -> GuildId { - guild.id - } + fn from(guild: PartialGuild) -> GuildId { guild.id } } impl<'a> From<&'a PartialGuild> for GuildId { /// Gets the Id of a partial guild. - fn from(guild: &PartialGuild) -> GuildId { - guild.id - } + fn from(guild: &PartialGuild) -> GuildId { guild.id } } impl From<GuildInfo> for GuildId { /// Gets the Id of Guild information struct. - fn from(guild_info: GuildInfo) -> GuildId { - guild_info.id - } + fn from(guild_info: GuildInfo) -> GuildId { guild_info.id } } impl<'a> From<&'a GuildInfo> for GuildId { /// Gets the Id of Guild information struct. - fn from(guild_info: &GuildInfo) -> GuildId { - guild_info.id - } + fn from(guild_info: &GuildInfo) -> GuildId { guild_info.id } } impl From<InviteGuild> for GuildId { /// Gets the Id of Invite Guild struct. - fn from(invite_guild: InviteGuild) -> GuildId { - invite_guild.id - } + fn from(invite_guild: InviteGuild) -> GuildId { invite_guild.id } } impl<'a> From<&'a InviteGuild> for GuildId { /// Gets the Id of Invite Guild struct. - fn from(invite_guild: &InviteGuild) -> GuildId { - invite_guild.id - } + fn from(invite_guild: &InviteGuild) -> GuildId { invite_guild.id } } impl From<Guild> for GuildId { /// Gets the Id of Guild. - fn from(live_guild: Guild) -> GuildId { - live_guild.id - } + fn from(live_guild: Guild) -> GuildId { live_guild.id } } impl<'a> From<&'a Guild> for GuildId { /// Gets the Id of Guild. - fn from(live_guild: &Guild) -> GuildId { - live_guild.id - } + fn from(live_guild: &Guild) -> GuildId { live_guild.id } } diff --git a/src/model/guild/integration.rs b/src/model/guild/integration.rs index b276bc3..18da39d 100644 --- a/src/model/guild/integration.rs +++ b/src/model/guild/integration.rs @@ -6,7 +6,7 @@ pub struct Integration { pub id: IntegrationId, pub account: IntegrationAccount, pub enabled: bool, - #[serde(rename="expire_behaviour")] + #[serde(rename = "expire_behaviour")] pub expire_behaviour: u64, pub expire_grace_period: u64, pub kind: String, @@ -19,9 +19,7 @@ pub struct Integration { impl From<Integration> for IntegrationId { /// Gets the Id of integration. - fn from(integration: Integration) -> IntegrationId { - integration.id - } + fn from(integration: Integration) -> IntegrationId { integration.id } } /// Integration account object. diff --git a/src/model/guild/member.rs b/src/model/guild/member.rs index ab817e7..dcf503d 100644 --- a/src/model/guild/member.rs +++ b/src/model/guild/member.rs @@ -1,20 +1,20 @@ use chrono::{DateTime, FixedOffset}; use std::fmt::{Display, Formatter, Result as FmtResult}; use super::deserialize_sync_user; -use ::model::*; +use model::*; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::borrow::Cow; -#[cfg(feature="cache")] -use ::CACHE; -#[cfg(feature="cache")] -use ::internal::prelude::*; -#[cfg(all(feature="cache", feature="model"))] -use ::http; -#[cfg(all(feature="builder", feature="cache", feature="model"))] -use ::builder::EditMember; -#[cfg(all(feature="cache", feature="model", feature="utils"))] -use ::utils::Colour; +#[cfg(feature = "cache")] +use CACHE; +#[cfg(feature = "cache")] +use internal::prelude::*; +#[cfg(all(feature = "cache", feature = "model"))] +use http; +#[cfg(all(feature = "builder", feature = "cache", feature = "model"))] +use builder::EditMember; +#[cfg(all(feature = "cache", feature = "model", feature = "utils"))] +use utils::Colour; pub trait BanOptions { fn dmd(&self) -> u8 { 0 } @@ -22,41 +22,27 @@ pub trait BanOptions { } impl BanOptions for u8 { - fn dmd(&self) -> u8 { - *self - } + fn dmd(&self) -> u8 { *self } } impl BanOptions for str { - fn reason(&self) -> &str { - self - } + fn reason(&self) -> &str { self } } impl BanOptions for String { - fn reason(&self) -> &str { - &self - } + fn reason(&self) -> &str { &self } } impl<'a> BanOptions for (u8, &'a str) { - fn dmd(&self) -> u8 { - self.0 - } + fn dmd(&self) -> u8 { self.0 } - fn reason(&self) -> &str { - self.1 - } + fn reason(&self) -> &str { self.1 } } impl BanOptions for (u8, String) { - fn dmd(&self) -> u8 { - self.0 - } + fn dmd(&self) -> u8 { self.0 } - fn reason(&self) -> &str { - &self.1 - } + fn reason(&self) -> &str { &self.1 } } /// Information about a member of a guild. @@ -77,11 +63,11 @@ pub struct Member { /// Vector of Ids of [`Role`]s given to the member. pub roles: Vec<RoleId>, /// Attached User struct. - #[serde(deserialize_with="deserialize_sync_user")] + #[serde(deserialize_with = "deserialize_sync_user")] pub user: Arc<RwLock<User>>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Member { /// Adds a [`Role`] to the member, editing its roles in-place if the request /// was successful. @@ -90,7 +76,7 @@ impl Member { /// /// [`Role`]: struct.Role.html /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn add_role<R: Into<RoleId>>(&mut self, role_id: R) -> Result<()> { let role_id = role_id.into(); @@ -115,7 +101,7 @@ impl Member { /// /// [`Role`]: struct.Role.html /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn add_roles(&mut self, role_ids: &[RoleId]) -> Result<()> { self.roles.extend_from_slice(role_ids); @@ -127,7 +113,7 @@ impl Member { self.roles.retain(|r| !role_ids.contains(r)); Err(why) - } + }, } } @@ -144,19 +130,22 @@ impl Member { /// [`ModelError::GuildNotFound`]: enum.ModelError.html#variant.GuildNotFound /// /// [Ban Members]: permissions/constant.BAN_MEMBERS.html - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn ban<BO: BanOptions>(&self, ban_options: BO) -> Result<()> { let reason = ban_options.reason(); - + if reason.len() > 512 { return Err(Error::ExceededLimit); } - http::ban_user(self.guild_id.0, self.user.read().unwrap().id.0, ban_options.dmd(), &*reason) + http::ban_user(self.guild_id.0, + self.user.read().unwrap().id.0, + ban_options.dmd(), + &*reason) } /// Determines the member's colour. - #[cfg(all(feature="cache", feature="utils"))] + #[cfg(all(feature = "cache", feature = "utils"))] pub fn colour(&self) -> Option<Colour> { let cache = CACHE.read().unwrap(); let guild = match cache.guilds.get(&self.guild_id) { @@ -172,7 +161,10 @@ impl Member { let default = Colour::default(); - roles.iter().find(|r| r.colour.0 != default.0).map(|r| r.colour) + roles + .iter() + .find(|r| r.colour.0 != default.0) + .map(|r| r.colour) } /// Calculates the member's display name. @@ -180,7 +172,8 @@ impl Member { /// The nickname takes priority over the member's username if it exists. #[inline] pub fn display_name(&self) -> Cow<String> { - self.nick.as_ref() + self.nick + .as_ref() .map(Cow::Borrowed) .unwrap_or_else(|| Cow::Owned(self.user.read().unwrap().name.clone())) } @@ -188,7 +181,9 @@ impl Member { /// Returns the DiscordTag of a Member, taking possible nickname into account. #[inline] pub fn distinct(&self) -> String { - format!("{}#{}", self.display_name(), self.user.read().unwrap().discriminator) + format!("{}#{}", + self.display_name(), + self.user.read().unwrap().discriminator) } /// Edits the member with the given data. See [`Guild::edit_member`] for @@ -199,7 +194,7 @@ impl Member { /// /// [`Guild::edit_member`]: ../model/struct.Guild.html#method.edit_member /// [`EditMember`]: ../builder/struct.EditMember.html - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn edit<F: FnOnce(EditMember) -> EditMember>(&self, f: F) -> Result<()> { let map = f(EditMember::default()).0; @@ -240,7 +235,7 @@ impl Member { /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [Kick Members]: permissions/constant.KICK_MEMBERS.html pub fn kick(&self) -> Result<()> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::KICK_MEMBERS; @@ -265,7 +260,8 @@ impl Member { /// /// ```rust,ignore /// // assuming there's a `member` variable gotten from anything. - /// println!("The permission bits for the member are: {}", member.permissions().expect("permissions").bits); + /// println!("The permission bits for the member are: {}", + /// member.permissions().expect("permissions").bits); /// ``` /// /// # Errors @@ -274,7 +270,7 @@ impl Member { /// found in the cache. /// /// [`ModelError::GuildNotFound`]: enum.ModelError.html#variant.GuildNotFound - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn permissions(&self) -> Result<Permissions> { let guild = match self.guild_id.find() { Some(guild) => guild, @@ -293,7 +289,7 @@ impl Member { /// /// [`Role`]: struct.Role.html /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn remove_role<R: Into<RoleId>>(&mut self, role_id: R) -> Result<()> { let role_id = role_id.into(); @@ -317,7 +313,7 @@ impl Member { /// /// [`Role`]: struct.Role.html /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn remove_roles(&mut self, role_ids: &[RoleId]) -> Result<()> { self.roles.retain(|r| !role_ids.contains(r)); @@ -338,25 +334,29 @@ impl Member { /// This is shorthand for manually searching through the CACHE. /// /// If role data can not be found for the member, then `None` is returned. - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn roles(&self) -> Option<Vec<Role>> { - CACHE.read().unwrap() + CACHE + .read() + .unwrap() .guilds .values() - .find(|guild| guild - .read() - .unwrap() - .members - .values() - .any(|m| m.user.read().unwrap().id == self.user.read().unwrap().id && m.joined_at == self.joined_at)) - .map(|guild| guild - .read() - .unwrap() - .roles - .values() - .filter(|role| self.roles.contains(&role.id)) - .cloned() - .collect()) + .find(|guild| { + guild.read().unwrap().members.values().any(|m| { + m.user.read().unwrap().id == self.user.read().unwrap().id && + m.joined_at == self.joined_at + }) + }) + .map(|guild| { + guild + .read() + .unwrap() + .roles + .values() + .filter(|role| self.roles.contains(&role.id)) + .cloned() + .collect() + }) } /// Unbans the [`User`] from the guild. @@ -371,7 +371,7 @@ impl Member { /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [`User`]: struct.User.html /// [Ban Members]: permissions/constant.BAN_MEMBERS.html - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn unban(&self) -> Result<()> { http::remove_ban(self.guild_id.0, self.user.read().unwrap().id.0) } diff --git a/src/model/guild/mod.rs b/src/model/guild/mod.rs index 17d88e6..70d82cb 100644 --- a/src/model/guild/mod.rs +++ b/src/model/guild/mod.rs @@ -20,16 +20,16 @@ use chrono::{DateTime, FixedOffset}; use serde::de::Error as DeError; use serde_json; use super::utils::*; -use ::model::*; +use model::*; -#[cfg(feature="cache")] -use ::CACHE; -#[cfg(feature="model")] -use ::http; -#[cfg(feature="model")] -use ::builder::{EditGuild, EditMember, EditRole}; -#[cfg(feature="model")] -use ::constants::LARGE_THRESHOLD; +#[cfg(feature = "cache")] +use CACHE; +#[cfg(feature = "model")] +use http; +#[cfg(feature = "model")] +use builder::{EditGuild, EditMember, EditRole}; +#[cfg(feature = "model")] +use constants::LARGE_THRESHOLD; /// A representation of a banning of a user. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Hash)] @@ -121,9 +121,9 @@ pub struct Guild { pub voice_states: HashMap<UserId, VoiceState>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Guild { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] fn has_perms(&self, mut permissions: Permissions) -> Result<bool> { let member = match self.members.get(&CACHE.read().unwrap().user.id) { Some(member) => member, @@ -160,18 +160,18 @@ impl Guild { /// Returns a [`ModelError::DeleteMessageDaysAmount`] if the number of /// days' worth of messages to delete is over the maximum. /// - /// [`ModelError::DeleteMessageDaysAmount`]: enum.ModelError.html#variant.DeleteMessageDaysAmount + /// [`ModelError::DeleteMessageDaysAmount`]: + /// enum.ModelError.html#variant.DeleteMessageDaysAmount /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [`Guild::ban`]: struct.Guild.html#method.ban /// [`User`]: struct.User.html /// [Ban Members]: permissions/constant.BAN_MEMBERS.html - pub fn ban<U: Into<UserId>>(&self, user: U, delete_message_days: u8) - -> Result<()> { + pub fn ban<U: Into<UserId>>(&self, user: U, delete_message_days: u8) -> Result<()> { if delete_message_days > 7 { return Err(Error::Model(ModelError::DeleteMessageDaysAmount(delete_message_days))); } - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::BAN_MEMBERS; @@ -196,7 +196,7 @@ impl Guild { /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [Ban Members]: permissions/constant.BAN_MEMBERS.html pub fn bans(&self) -> Result<Vec<Ban>> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::BAN_MEMBERS; @@ -212,17 +212,13 @@ impl Guild { /// /// [`AuditLogs`]: audit_log/struct.AuditLogs.html #[inline] - pub fn audit_logs(&self) -> Result<AuditLogs> { - self.id.audit_logs() - } + pub fn audit_logs(&self) -> Result<AuditLogs> { self.id.audit_logs() } /// Gets all of the guild's channels over the REST API. /// /// [`Guild`]: struct.Guild.html #[inline] - pub fn channels(&self) -> Result<HashMap<ChannelId, GuildChannel>> { - self.id.channels() - } + pub fn channels(&self) -> Result<HashMap<ChannelId, GuildChannel>> { self.id.channels() } /// Creates a guild with the data provided. /// @@ -282,7 +278,7 @@ impl Guild { /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [Manage Channels]: permissions/constant.MANAGE_CHANNELS.html pub fn create_channel(&self, name: &str, kind: ChannelType) -> Result<GuildChannel> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::MANAGE_CHANNELS; @@ -325,7 +321,8 @@ impl Guild { /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] pub fn create_integration<I>(&self, integration_id: I, kind: &str) -> Result<()> - where I: Into<IntegrationId> { + where + I: Into<IntegrationId>, { self.id.create_integration(integration_id, kind) } @@ -352,8 +349,9 @@ impl Guild { /// [`Role`]: struct.Role.html /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html pub fn create_role<F>(&self, f: F) -> Result<Role> - where F: FnOnce(EditRole) -> EditRole { - #[cfg(feature="cache")] + where + F: FnOnce(EditRole) -> EditRole, { + #[cfg(feature = "cache")] { let req = permissions::MANAGE_ROLES; @@ -377,7 +375,7 @@ impl Guild { /// /// [`ModelError::InvalidUser`]: enum.ModelError.html#variant.InvalidUser pub fn delete(&self) -> Result<PartialGuild> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { if self.owner_id != CACHE.read().unwrap().user.id { let req = permissions::MANAGE_GUILD; @@ -454,8 +452,9 @@ impl Guild { /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html pub fn edit<F>(&mut self, f: F) -> Result<()> - where F: FnOnce(EditGuild) -> EditGuild { - #[cfg(feature="cache")] + where + F: FnOnce(EditGuild) -> EditGuild, { + #[cfg(feature = "cache")] { let req = permissions::MANAGE_GUILD; @@ -516,7 +515,9 @@ impl Guild { /// ``` #[inline] pub fn edit_member<F, U>(&self, user_id: U, f: F) -> Result<()> - where F: FnOnce(EditMember) -> EditMember, U: Into<UserId> { + where + F: FnOnce(EditMember) -> EditMember, + U: Into<UserId>, { self.id.edit_member(user_id, f) } @@ -535,7 +536,7 @@ impl Guild { /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [Change Nickname]: permissions/constant.CHANGE_NICKNAME.html pub fn edit_nickname(&self, new_nickname: Option<&str>) -> Result<()> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::CHANGE_NICKNAME; @@ -562,7 +563,9 @@ impl Guild { /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html #[inline] pub fn edit_role<F, R>(&self, role_id: R, f: F) -> Result<Role> - where F: FnOnce(EditRole) -> EditRole, R: Into<RoleId> { + where + F: FnOnce(EditRole) -> EditRole, + R: Into<RoleId>, { self.id.edit_role(role_id, f) } @@ -572,9 +575,7 @@ impl Guild { /// /// [Manage Emojis]: permissions/constant.MANAGE_EMOJIS.html #[inline] - pub fn emoji<E: Into<EmojiId>>(&self, emoji_id: E) -> Result<Emoji> { - self.id.emoji(emoji_id) - } + pub fn emoji<E: Into<EmojiId>>(&self, emoji_id: E) -> Result<Emoji> { self.id.emoji(emoji_id) } /// Gets a list of all of the guild's emojis. /// @@ -582,31 +583,26 @@ impl Guild { /// /// [Manage Emojis]: permissions/constant.MANAGE_EMOJIS.html #[inline] - pub fn emojis(&self) -> Result<Vec<Emoji>> { - self.id.emojis() - } + pub fn emojis(&self) -> Result<Vec<Emoji>> { self.id.emojis() } /// Gets a partial amount of guild data by its Id. /// /// Requires that the current user be in the guild. #[inline] - pub fn get<G: Into<GuildId>>(guild_id: G) -> Result<PartialGuild> { - guild_id.into().get() - } + pub fn get<G: Into<GuildId>>(guild_id: G) -> Result<PartialGuild> { guild_id.into().get() } /// Returns the formatted URL of the guild's icon, if one exists. pub fn icon_url(&self) -> Option<String> { - self.icon.as_ref().map(|icon| - format!(cdn!("/icons/{}/{}.webp"), self.id, icon)) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/icons/{}/{}.webp"), self.id, icon)) } /// Gets all integration of the guild. /// /// This performs a request over the REST API. #[inline] - pub fn integrations(&self) -> Result<Vec<Integration>> { - self.id.integrations() - } + pub fn integrations(&self) -> Result<Vec<Integration>> { self.id.integrations() } /// Retrieves the active invites for the guild. /// @@ -620,7 +616,7 @@ impl Guild { /// [`ModelError::InvalidPermissions`]: enum.ModelError.html#variant.InvalidPermissions /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html pub fn invites(&self) -> Result<Vec<RichInvite>> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::MANAGE_GUILD; @@ -635,9 +631,7 @@ impl Guild { /// Checks if the guild is 'large'. A guild is considered large if it has /// more than 250 members. #[inline] - pub fn is_large(&self) -> bool { - self.members.len() > LARGE_THRESHOLD as usize - } + pub fn is_large(&self) -> bool { self.members.len() > LARGE_THRESHOLD as usize } /// Kicks a [`Member`] from the guild. /// @@ -646,24 +640,18 @@ impl Guild { /// [`Member`]: struct.Member.html /// [Kick Members]: permissions/constant.KICK_MEMBERS.html #[inline] - pub fn kick<U: Into<UserId>>(&self, user_id: U) -> Result<()> { - self.id.kick(user_id) - } + pub fn kick<U: Into<UserId>>(&self, user_id: U) -> Result<()> { self.id.kick(user_id) } /// Leaves the guild. #[inline] - pub fn leave(&self) -> Result<()> { - self.id.leave() - } + pub fn leave(&self) -> Result<()> { self.id.leave() } /// Gets a user's [`Member`] for the guild by Id. /// /// [`Guild`]: struct.Guild.html /// [`Member`]: struct.Member.html #[inline] - pub fn member<U: Into<UserId>>(&self, user_id: U) -> Result<Member> { - self.id.member(user_id) - } + pub fn member<U: Into<UserId>>(&self, user_id: U) -> Result<Member> { self.id.member(user_id) } /// Gets a list of the guild's members. /// @@ -673,12 +661,14 @@ impl Guild { /// /// [`User`]: struct.User.html #[inline] - pub fn members<U>(&self, limit: Option<u64>, after: Option<U>) - -> Result<Vec<Member>> where U: Into<UserId> { + pub fn members<U>(&self, limit: Option<u64>, after: Option<U>) -> Result<Vec<Member>> + where + U: Into<UserId>, { self.id.members(limit, after) } - /// Gets a list of all the members (satisfying the status provided to the function) in this guild. + /// Gets a list of all the members (satisfying the status provided to the function) in this + /// guild. pub fn members_with_status(&self, status: OnlineStatus) -> Vec<&Member> { let mut members = vec![]; @@ -735,9 +725,12 @@ impl Guild { }; name_matches && discrim_matches - }).or_else(|| self.members.values().find(|member| { - member.nick.as_ref().map_or(false, |nick| nick == name) - })) + }) + .or_else(|| { + self.members + .values() + .find(|member| member.nick.as_ref().map_or(false, |nick| nick == name)) + }) } /// Moves a member to a specific voice channel. @@ -747,15 +740,19 @@ impl Guild { /// [Move Members]: permissions/constant.MOVE_MEMBERS.html #[inline] pub fn move_member<C, U>(&self, user_id: U, channel_id: C) -> Result<()> - where C: Into<ChannelId>, U: Into<UserId> { + where + C: Into<ChannelId>, + U: Into<UserId>, { self.id.move_member(user_id, channel_id) } /// Calculate a [`User`]'s permissions in a given channel in the guild. /// /// [`User`]: struct.User.html - pub fn permissions_for<C, U>(&self, channel_id: C, user_id: U) - -> Permissions where C: Into<ChannelId>, U: Into<UserId> { + pub fn permissions_for<C, U>(&self, channel_id: C, user_id: U) -> Permissions + where + C: Into<ChannelId>, + U: Into<UserId>, { use super::permissions::*; let user_id = user_id.into(); @@ -808,8 +805,8 @@ impl Guild { // If this is a text channel, then throw out voice permissions. if channel.kind == ChannelType::Text { - permissions &= !(CONNECT | SPEAK | MUTE_MEMBERS | - DEAFEN_MEMBERS | MOVE_MEMBERS | USE_VAD); + permissions &= + !(CONNECT | SPEAK | MUTE_MEMBERS | DEAFEN_MEMBERS | MOVE_MEMBERS | USE_VAD); } // Apply the permission overwrites for the channel for each of the @@ -853,17 +850,14 @@ impl Guild { // If the member does not have the `SEND_MESSAGES` permission, then // throw out message-able permissions. if !permissions.contains(SEND_MESSAGES) { - permissions &= !(SEND_TTS_MESSAGES | - MENTION_EVERYONE | - EMBED_LINKS | - ATTACH_FILES); + permissions &= !(SEND_TTS_MESSAGES | MENTION_EVERYONE | EMBED_LINKS | ATTACH_FILES); } // If the member does not have the `READ_MESSAGES` permission, then // throw out actionable permissions. if !permissions.contains(READ_MESSAGES) { - permissions &= KICK_MEMBERS | BAN_MEMBERS | ADMINISTRATOR | - MANAGE_GUILD | CHANGE_NICKNAME | MANAGE_NICKNAMES; + permissions &= KICK_MEMBERS | BAN_MEMBERS | ADMINISTRATOR | MANAGE_GUILD | + CHANGE_NICKNAME | MANAGE_NICKNAMES; } permissions @@ -886,7 +880,7 @@ impl Guild { /// [`Member`]: struct.Member.html /// [Kick Members]: permissions/constant.KICK_MEMBERS.html pub fn prune_count(&self, days: u16) -> Result<GuildPrune> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::KICK_MEMBERS; @@ -908,11 +902,9 @@ impl Guild { /// total, consider using [`utils::shard_id`]. /// /// [`utils::shard_id`]: ../utils/fn.shard_id.html - #[cfg(all(feature="cache", feature="utils"))] + #[cfg(all(feature = "cache", feature = "utils"))] #[inline] - pub fn shard_id(&self) -> u64 { - self.id.shard_id() - } + pub fn shard_id(&self) -> u64 { self.id.shard_id() } /// Returns the Id of the shard associated with the guild. /// @@ -934,16 +926,15 @@ impl Guild { /// /// assert_eq!(guild.shard_id(17), 7); /// ``` - #[cfg(all(feature="utils", not(feature="cache")))] + #[cfg(all(feature = "utils", not(feature = "cache")))] #[inline] - pub fn shard_id(&self, shard_count: u64) -> u64 { - self.id.shard_id(shard_count) - } + pub fn shard_id(&self, shard_count: u64) -> u64 { self.id.shard_id(shard_count) } /// Returns the formatted URL of the guild's splash image, if one exists. pub fn splash_url(&self) -> Option<String> { - self.icon.as_ref().map(|icon| - format!(cdn!("/splashes/{}/{}.webp"), self.id, icon)) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/splashes/{}/{}.webp"), self.id, icon)) } /// Starts an integration sync for the given integration Id. @@ -972,7 +963,7 @@ impl Guild { /// [`Member`]: struct.Member.html /// [Kick Members]: permissions/constant.KICK_MEMBERS.html pub fn start_prune(&self, days: u16) -> Result<GuildPrune> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::KICK_MEMBERS; @@ -997,7 +988,7 @@ impl Guild { /// [`User`]: struct.User.html /// [Ban Members]: permissions/constant.BAN_MEMBERS.html pub fn unban<U: Into<UserId>>(&self, user_id: U) -> Result<()> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::BAN_MEMBERS; @@ -1015,9 +1006,7 @@ impl Guild { /// /// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html #[inline] - pub fn webhooks(&self) -> Result<Vec<Webhook>> { - self.id.webhooks() - } + pub fn webhooks(&self) -> Result<Vec<Webhook>> { self.id.webhooks() } } impl<'de> Deserialize<'de> for Guild { @@ -1032,7 +1021,8 @@ impl<'de> Deserialize<'de> for Guild { 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))); + channel + .insert("guild_id".to_owned(), Value::Number(Number::from(guild_id))); } } } @@ -1047,7 +1037,10 @@ impl<'de> Deserialize<'de> for Guild { } let afk_channel_id = match map.remove("afk_channel_id") { - Some(v) => serde_json::from_value::<Option<ChannelId>>(v).map_err(DeError::custom)?, + Some(v) => { + serde_json::from_value::<Option<ChannelId>>(v) + .map_err(DeError::custom)? + }, None => None, }; let afk_timeout = map.remove("afk_timeout") @@ -1132,28 +1125,28 @@ impl<'de> Deserialize<'de> for Guild { .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, - }) + 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, + }) } } @@ -1193,39 +1186,35 @@ pub struct GuildInfo { pub permissions: Permissions, } -#[cfg(any(feature="model", feature="utils"))] +#[cfg(any(feature = "model", feature = "utils"))] impl GuildInfo { /// Returns the formatted URL of the guild's icon, if the guild has an icon. pub fn icon_url(&self) -> Option<String> { - self.icon.as_ref().map(|icon| - format!(cdn!("/icons/{}/{}.webp"), self.id, icon)) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/icons/{}/{}.webp"), self.id, icon)) } } impl From<PartialGuild> for GuildContainer { - fn from(guild: PartialGuild) -> GuildContainer { - GuildContainer::Guild(guild) - } + fn from(guild: PartialGuild) -> GuildContainer { GuildContainer::Guild(guild) } } impl From<GuildId> for GuildContainer { - fn from(guild_id: GuildId) -> GuildContainer { - GuildContainer::Id(guild_id) - } + fn from(guild_id: GuildId) -> GuildContainer { GuildContainer::Id(guild_id) } } impl From<u64> for GuildContainer { - fn from(id: u64) -> GuildContainer { - GuildContainer::Id(GuildId(id)) - } + fn from(id: u64) -> GuildContainer { GuildContainer::Id(GuildId(id)) } } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl InviteGuild { /// Returns the formatted URL of the guild's splash image, if one exists. pub fn splash_url(&self) -> Option<String> { - self.icon.as_ref().map(|icon| - format!(cdn!("/splashes/{}/{}.webp"), self.id, icon)) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/splashes/{}/{}.webp"), self.id, icon)) } } @@ -1251,7 +1240,7 @@ pub enum GuildStatus { Offline(GuildUnavailable), } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl GuildStatus { /// Retrieves the Id of the inner [`Guild`]. /// diff --git a/src/model/guild/partial_guild.rs b/src/model/guild/partial_guild.rs index 26d4257..d070e54 100644 --- a/src/model/guild/partial_guild.rs +++ b/src/model/guild/partial_guild.rs @@ -1,8 +1,8 @@ use super::super::utils::{deserialize_emojis, deserialize_roles}; -use ::model::*; +use model::*; -#[cfg(feature="model")] -use ::builder::{EditGuild, EditMember, EditRole}; +#[cfg(feature = "model")] +use builder::{EditGuild, EditMember, EditRole}; /// Partial information about a [`Guild`]. This does not include information /// like member data. @@ -16,7 +16,7 @@ pub struct PartialGuild { pub default_message_notifications: u64, pub embed_channel_id: Option<ChannelId>, pub embed_enabled: bool, - #[serde(deserialize_with="deserialize_emojis")] + #[serde(deserialize_with = "deserialize_emojis")] pub emojis: HashMap<EmojiId, Emoji>, pub features: Vec<Feature>, pub icon: Option<String>, @@ -24,13 +24,13 @@ pub struct PartialGuild { pub name: String, pub owner_id: UserId, pub region: String, - #[serde(deserialize_with="deserialize_roles")] + #[serde(deserialize_with = "deserialize_roles")] pub roles: HashMap<RoleId, Role>, pub splash: Option<String>, pub verification_level: VerificationLevel, } -#[cfg(feature="model")] +#[cfg(feature = "model")] 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 @@ -52,7 +52,8 @@ impl PartialGuild { /// Returns a [`ModelError::DeleteMessageDaysAmount`] if the number of /// days' worth of messages to delete is over the maximum. /// - /// [`ModelError::DeleteMessageDaysAmount`]: enum.ModelError.html#variant.DeleteMessageDaysAmount + /// [`ModelError::DeleteMessageDaysAmount`]: + /// enum.ModelError.html#variant.DeleteMessageDaysAmount /// [`User`]: struct.User.html /// [Ban Members]: permissions/constant.BAN_MEMBERS.html pub fn ban<U: Into<UserId>>(&self, user: U, delete_message_days: u8) -> Result<()> { @@ -69,17 +70,13 @@ impl PartialGuild { /// /// [Ban Members]: permissions/constant.BAN_MEMBERS.html #[inline] - pub fn bans(&self) -> Result<Vec<Ban>> { - self.id.bans() - } + pub fn bans(&self) -> Result<Vec<Ban>> { self.id.bans() } /// Gets all of the guild's channels over the REST API. /// /// [`Guild`]: struct.Guild.html #[inline] - pub fn channels(&self) -> Result<HashMap<ChannelId, GuildChannel>> { - self.id.channels() - } + pub fn channels(&self) -> Result<HashMap<ChannelId, GuildChannel>> { self.id.channels() } /// Creates a [`GuildChannel`] in the guild. /// @@ -134,7 +131,8 @@ impl PartialGuild { /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] pub fn create_integration<I>(&self, integration_id: I, kind: &str) -> Result<()> - where I: Into<IntegrationId> { + where + I: Into<IntegrationId>, { self.id.create_integration(integration_id, kind) } @@ -162,9 +160,7 @@ impl PartialGuild { /// /// **Note**: Requires the current user to be the owner of the guild. #[inline] - pub fn delete(&self) -> Result<PartialGuild> { - self.id.delete() - } + pub fn delete(&self) -> Result<PartialGuild> { self.id.delete() } /// Deletes an [`Emoji`] from the guild. /// @@ -209,7 +205,8 @@ impl PartialGuild { /// /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html pub fn edit<F>(&mut self, f: F) -> Result<()> - where F: FnOnce(EditGuild) -> EditGuild { + where + F: FnOnce(EditGuild) -> EditGuild, { match self.id.edit(f) { Ok(guild) => { self.afk_channel_id = guild.afk_channel_id; @@ -264,7 +261,9 @@ impl PartialGuild { /// ``` #[inline] pub fn edit_member<F, U>(&self, user_id: U, f: F) -> Result<()> - where F: FnOnce(EditMember) -> EditMember, U: Into<UserId> { + where + F: FnOnce(EditMember) -> EditMember, + U: Into<UserId>, { self.id.edit_member(user_id, f) } @@ -293,9 +292,7 @@ impl PartialGuild { /// /// [Manage Emojis]: permissions/constant.MANAGE_EMOJIS.html #[inline] - pub fn emoji<E: Into<EmojiId>>(&self, emoji_id: E) -> Result<Emoji> { - self.id.emoji(emoji_id) - } + pub fn emoji<E: Into<EmojiId>>(&self, emoji_id: E) -> Result<Emoji> { self.id.emoji(emoji_id) } /// Gets a list of all of the guild's emojis. /// @@ -303,17 +300,13 @@ impl PartialGuild { /// /// [Manage Emojis]: permissions/constant.MANAGE_EMOJIS.html #[inline] - pub fn emojis(&self) -> Result<Vec<Emoji>> { - self.id.emojis() - } + pub fn emojis(&self) -> Result<Vec<Emoji>> { self.id.emojis() } /// Gets a partial amount of guild data by its Id. /// /// Requires that the current user be in the guild. #[inline] - pub fn get<G: Into<GuildId>>(guild_id: G) -> Result<PartialGuild> { - guild_id.into().get() - } + pub fn get<G: Into<GuildId>>(guild_id: G) -> Result<PartialGuild> { guild_id.into().get() } /// Kicks a [`Member`] from the guild. /// @@ -322,23 +315,20 @@ impl PartialGuild { /// [`Member`]: struct.Member.html /// [Kick Members]: permissions/constant.KICK_MEMBERS.html #[inline] - pub fn kick<U: Into<UserId>>(&self, user_id: U) -> Result<()> { - self.id.kick(user_id) - } + pub fn kick<U: Into<UserId>>(&self, user_id: U) -> Result<()> { self.id.kick(user_id) } /// Returns a formatted URL of the guild's icon, if the guild has an icon. pub fn icon_url(&self) -> Option<String> { - self.icon.as_ref().map(|icon| - format!(cdn!("/icons/{}/{}.webp"), self.id, icon)) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/icons/{}/{}.webp"), self.id, icon)) } /// Gets all integration of the guild. /// /// This performs a request over the REST API. #[inline] - pub fn integrations(&self) -> Result<Vec<Integration>> { - self.id.integrations() - } + pub fn integrations(&self) -> Result<Vec<Integration>> { self.id.integrations() } /// Gets all of the guild's invites. /// @@ -346,23 +336,17 @@ impl PartialGuild { /// /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] - pub fn invites(&self) -> Result<Vec<RichInvite>> { - self.id.invites() - } + pub fn invites(&self) -> Result<Vec<RichInvite>> { self.id.invites() } /// Leaves the guild. #[inline] - pub fn leave(&self) -> Result<()> { - self.id.leave() - } + pub fn leave(&self) -> Result<()> { self.id.leave() } /// Gets a user's [`Member`] for the guild by Id. /// /// [`Guild`]: struct.Guild.html /// [`Member`]: struct.Member.html - pub fn member<U: Into<UserId>>(&self, user_id: U) -> Result<Member> { - self.id.member(user_id) - } + pub fn member<U: Into<UserId>>(&self, user_id: U) -> Result<Member> { self.id.member(user_id) } /// Gets a list of the guild's members. /// @@ -371,8 +355,9 @@ impl PartialGuild { /// [`User`]'s Id. /// /// [`User`]: struct.User.html - pub fn members<U>(&self, limit: Option<u64>, after: Option<U>) - -> Result<Vec<Member>> where U: Into<UserId> { + pub fn members<U>(&self, limit: Option<u64>, after: Option<U>) -> Result<Vec<Member>> + where + U: Into<UserId>, { self.id.members(limit, after) } @@ -383,7 +368,9 @@ impl PartialGuild { /// [Move Members]: permissions/constant.MOVE_MEMBERS.html #[inline] pub fn move_member<C, U>(&self, user_id: U, channel_id: C) -> Result<()> - where C: Into<ChannelId>, U: Into<UserId> { + where + C: Into<ChannelId>, + U: Into<UserId>, { self.id.move_member(user_id, channel_id) } @@ -395,9 +382,7 @@ impl PartialGuild { /// [`Member`]: struct.Member.html /// [Kick Members]: permissions/constant.KICK_MEMBERS.html #[inline] - pub fn prune_count(&self, days: u16) -> Result<GuildPrune> { - self.id.prune_count(days) - } + pub fn prune_count(&self, days: u16) -> Result<GuildPrune> { self.id.prune_count(days) } /// Returns the Id of the shard associated with the guild. /// @@ -409,11 +394,9 @@ impl PartialGuild { /// total, consider using [`utils::shard_id`]. /// /// [`utils::shard_id`]: ../utils/fn.shard_id.html - #[cfg(all(feature="cache", feature="utils"))] + #[cfg(all(feature = "cache", feature = "utils"))] #[inline] - pub fn shard_id(&self) -> u64 { - self.id.shard_id() - } + pub fn shard_id(&self) -> u64 { self.id.shard_id() } /// Returns the Id of the shard associated with the guild. /// @@ -435,16 +418,15 @@ impl PartialGuild { /// /// assert_eq!(guild.shard_id(17), 7); /// ``` - #[cfg(all(feature="utils", not(feature="cache")))] + #[cfg(all(feature = "utils", not(feature = "cache")))] #[inline] - pub fn shard_id(&self, shard_count: u64) -> u64 { - self.id.shard_id(shard_count) - } + pub fn shard_id(&self, shard_count: u64) -> u64 { self.id.shard_id(shard_count) } /// Returns the formatted URL of the guild's splash image, if one exists. pub fn splash_url(&self) -> Option<String> { - self.icon.as_ref().map(|icon| - format!(cdn!("/splashes/{}/{}.webp"), self.id, icon)) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/splashes/{}/{}.webp"), self.id, icon)) } /// Starts an integration sync for the given integration Id. @@ -464,9 +446,7 @@ impl PartialGuild { /// [`User`]: struct.User.html /// [Ban Members]: permissions/constant.BAN_MEMBERS.html #[inline] - pub fn unban<U: Into<UserId>>(&self, user_id: U) -> Result<()> { - self.id.unban(user_id) - } + pub fn unban<U: Into<UserId>>(&self, user_id: U) -> Result<()> { self.id.unban(user_id) } /// Retrieves the guild's webhooks. /// @@ -474,7 +454,5 @@ impl PartialGuild { /// /// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html #[inline] - pub fn webhooks(&self) -> Result<Vec<Webhook>> { - self.id.webhooks() - } + pub fn webhooks(&self) -> Result<Vec<Webhook>> { self.id.webhooks() } } diff --git a/src/model/guild/role.rs b/src/model/guild/role.rs index c7adf0a..3f74498 100644 --- a/src/model/guild/role.rs +++ b/src/model/guild/role.rs @@ -1,15 +1,15 @@ use std::cmp::Ordering; use std::fmt::{Display, Formatter, Result as FmtResult}; -use ::model::*; +use model::*; -#[cfg(feature="cache")] -use ::CACHE; -#[cfg(all(feature="builder", feature="cache", feature="model"))] -use ::builder::EditRole; -#[cfg(feature="cache")] -use ::internal::prelude::*; -#[cfg(all(feature="cache", feature="model"))] -use ::http; +#[cfg(feature = "cache")] +use CACHE; +#[cfg(all(feature = "builder", feature = "cache", feature = "model"))] +use builder::EditRole; +#[cfg(feature = "cache")] +use internal::prelude::*; +#[cfg(all(feature = "cache", feature = "model"))] +use http; /// 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 @@ -23,12 +23,12 @@ pub struct Role { pub id: RoleId, /// The colour of the role. This is an ergonomic representation of the inner /// value. - #[cfg(feature="utils")] - #[serde(rename="color")] + #[cfg(feature = "utils")] + #[serde(rename = "color")] pub colour: Colour, /// The colour of the role. - #[cfg(not(feature="utils"))] - #[serde(rename="color")] + #[cfg(not(feature = "utils"))] + #[serde(rename = "color")] pub colour: u32, /// Indicator of whether the role is pinned above lesser roles. /// @@ -62,18 +62,16 @@ pub struct Role { pub position: i64, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Role { /// Deletes the role. /// /// **Note** Requires the [Manage Roles] permission. /// /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html - #[cfg(feature="cache")] + #[cfg(feature = "cache")] #[inline] - pub fn delete(&self) -> Result<()> { - http::delete_role(self.find_guild()?.0, self.id.0) - } + pub fn delete(&self) -> Result<()> { http::delete_role(self.find_guild()?.0, self.id.0) } /// Edits a [`Role`], optionally setting its new fields. /// @@ -93,9 +91,10 @@ impl Role { /// /// [`Role`]: struct.Role.html /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html - #[cfg(all(feature="builder", feature="cache"))] + #[cfg(all(feature = "builder", feature = "cache"))] pub fn edit<F: FnOnce(EditRole) -> EditRole>(&self, f: F) -> Result<Role> { - self.find_guild().and_then(|guild_id| guild_id.edit_role(self.id, f)) + self.find_guild() + .and_then(|guild_id| guild_id.edit_role(self.id, f)) } /// Searches the cache for the guild that owns the role. @@ -106,7 +105,7 @@ impl Role { /// that contains the role. /// /// [`ModelError::GuildNotFound`]: enum.ModelError.html#variant.GuildNotFound - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn find_guild(&self) -> Result<GuildId> { for guild in CACHE.read().unwrap().guilds.values() { let guild = guild.read().unwrap(); @@ -130,8 +129,7 @@ impl Role { /// The 'precise' argument is used to check if the role's permissions are /// precisely equivalent to the given permissions. If you need only check /// that the role has at least the given permissions, pass `false`. - pub fn has_permissions(&self, permissions: Permissions, precise: bool) - -> bool { + pub fn has_permissions(&self, permissions: Permissions, precise: bool) -> bool { if precise { self.permissions == permissions } else { @@ -143,9 +141,7 @@ impl Role { impl Display for Role { /// Format a mention for the role, pinging its members. // This is in the format of: `<@&ROLE_ID>`. - fn fmt(&self, f: &mut Formatter) -> FmtResult { - Display::fmt(&self.mention(), f) - } + fn fmt(&self, f: &mut Formatter) -> FmtResult { Display::fmt(&self.mention(), f) } } impl Eq for Role {} @@ -161,21 +157,17 @@ impl Ord for Role { } impl PartialEq for Role { - fn eq(&self, other: &Role) -> bool { - self.id == other.id - } + fn eq(&self, other: &Role) -> bool { self.id == other.id } } impl PartialOrd for Role { - fn partial_cmp(&self, other: &Role) -> Option<Ordering> { - Some(self.cmp(other)) - } + fn partial_cmp(&self, other: &Role) -> Option<Ordering> { Some(self.cmp(other)) } } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl RoleId { /// Search the cache for the role. - #[cfg(feature="cache")] + #[cfg(feature = "cache")] pub fn find(&self) -> Option<Role> { let cache = CACHE.read().unwrap(); @@ -196,21 +188,15 @@ impl RoleId { } impl Display for RoleId { - fn fmt(&self, f: &mut Formatter) -> FmtResult { - Display::fmt(&self.0, f) - } + fn fmt(&self, f: &mut Formatter) -> FmtResult { Display::fmt(&self.0, f) } } impl From<Role> for RoleId { /// Gets the Id of a role. - fn from(role: Role) -> RoleId { - role.id - } + fn from(role: Role) -> RoleId { role.id } } impl<'a> From<&'a Role> for RoleId { /// Gets the Id of a role. - fn from(role: &Role) -> RoleId { - role.id - } + fn from(role: &Role) -> RoleId { role.id } } diff --git a/src/model/invite.rs b/src/model/invite.rs index 7ff3fd1..042faa3 100644 --- a/src/model/invite.rs +++ b/src/model/invite.rs @@ -1,14 +1,14 @@ use chrono::{DateTime, FixedOffset}; use super::*; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] use super::{permissions, utils as model_utils}; -#[cfg(feature="model")] -use ::builder::CreateInvite; -#[cfg(feature="model")] -use ::http; -#[cfg(feature="model")] -use ::internal::prelude::*; +#[cfg(feature = "model")] +use builder::CreateInvite; +#[cfg(feature = "model")] +use http; +#[cfg(feature = "model")] +use internal::prelude::*; /// Information about an invite code. /// @@ -40,7 +40,7 @@ pub struct Invite { pub guild: InviteGuild, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Invite { /// Creates an invite for a [`GuildChannel`], providing a builder so that /// fields may optionally be set. @@ -61,10 +61,12 @@ impl Invite { /// [Create Invite]: permissions/constant.CREATE_INVITE.html /// [permission]: permissions/index.html pub fn create<C, F>(channel_id: C, f: F) -> Result<RichInvite> - where C: Into<ChannelId>, F: FnOnce(CreateInvite) -> CreateInvite { + where + C: Into<ChannelId>, + F: FnOnce(CreateInvite) -> CreateInvite, { let channel_id = channel_id.into(); - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::CREATE_INVITE; @@ -89,7 +91,7 @@ impl Invite { /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html /// [permission]: permissions/index.html pub fn delete(&self) -> Result<Invite> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::MANAGE_GUILD; @@ -106,7 +108,7 @@ impl Invite { pub fn get(code: &str, stats: bool) -> Result<Invite> { let mut invite = code; - #[cfg(feature="utils")] + #[cfg(feature = "utils")] { invite = ::utils::parse_invite(invite); } @@ -144,9 +146,7 @@ impl Invite { /// # /// assert_eq!(invite.url(), "https://discord.gg/WxZumR"); /// ``` - pub fn url(&self) -> String { - format!("https://discord.gg/{}", self.code) - } + pub fn url(&self) -> String { format!("https://discord.gg/{}", self.code) } } /// A inimal information about the channel an invite points to. @@ -154,7 +154,7 @@ impl Invite { pub struct InviteChannel { pub id: ChannelId, pub name: String, - #[serde(rename="type")] + #[serde(rename = "type")] pub kind: ChannelType, } @@ -169,7 +169,7 @@ pub struct InviteGuild { pub voice_channel_count: Option<u64>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl InviteGuild { /// Returns the Id of the shard associated with the guild. /// @@ -181,11 +181,9 @@ impl InviteGuild { /// total, consider using [`utils::shard_id`]. /// /// [`utils::shard_id`]: ../utils/fn.shard_id.html - #[cfg(all(feature="cache", feature="utils"))] + #[cfg(all(feature = "cache", feature = "utils"))] #[inline] - pub fn shard_id(&self) -> u64 { - self.id.shard_id() - } + pub fn shard_id(&self) -> u64 { self.id.shard_id() } /// Returns the Id of the shard associated with the guild. /// @@ -207,11 +205,9 @@ impl InviteGuild { /// /// assert_eq!(guild.shard_id(17), 7); /// ``` - #[cfg(all(feature="utils", not(feature="cache")))] + #[cfg(all(feature = "utils", not(feature = "cache")))] #[inline] - pub fn shard_id(&self, shard_count: u64) -> u64 { - self.id.shard_id(shard_count) - } + pub fn shard_id(&self, shard_count: u64) -> u64 { self.id.shard_id(shard_count) } } /// Detailed information about an invite. @@ -255,7 +251,7 @@ pub struct RichInvite { pub uses: u64, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl RichInvite { /// Deletes the invite. /// @@ -275,7 +271,7 @@ impl RichInvite { /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html /// [permission]: permissions/index.html pub fn delete(&self) -> Result<Invite> { - #[cfg(feature="cache")] + #[cfg(feature = "cache")] { let req = permissions::MANAGE_GUILD; @@ -327,7 +323,5 @@ impl RichInvite { /// # /// assert_eq!(invite.url(), "https://discord.gg/WxZumR"); /// ``` - pub fn url(&self) -> String { - format!("https://discord.gg/{}", self.code) - } + pub fn url(&self) -> String { format!("https://discord.gg/{}", self.code) } } diff --git a/src/model/misc.rs b/src/model/misc.rs index 768b694..9420968 100644 --- a/src/model/misc.rs +++ b/src/model/misc.rs @@ -1,11 +1,11 @@ use super::*; -#[cfg(all(feature="model", feature="utils"))] +#[cfg(all(feature = "model", feature = "utils"))] use std::result::Result as StdResult; -#[cfg(all(feature="model", feature="utils"))] +#[cfg(all(feature = "model", feature = "utils"))] use std::str::FromStr; -#[cfg(any(all(feature="cache", feature="utils"), all(feature="model", feature="utils")))] -use ::utils; +#[cfg(any(all(feature = "cache", feature = "utils"), all(feature = "model", feature = "utils")))] +use utils; /// Allows something - such as a channel or role - to be mentioned in a message. pub trait Mentionable { @@ -15,64 +15,44 @@ pub trait Mentionable { } impl Mentionable for ChannelId { - fn mention(&self) -> String { - format!("<#{}>", self.0) - } + fn mention(&self) -> String { format!("<#{}>", self.0) } } impl Mentionable for Channel { fn mention(&self) -> String { match *self { - Channel::Guild(ref x) => { - format!("<#{}>", x.read().unwrap().id.0) - }, - Channel::Private(ref x) => { - format!("<#{}>", x.read().unwrap().id.0) - }, - Channel::Group(ref x) => { - format!("<#{}>", x.read().unwrap().channel_id.0) - } + Channel::Guild(ref x) => format!("<#{}>", x.read().unwrap().id.0), + Channel::Private(ref x) => format!("<#{}>", x.read().unwrap().id.0), + Channel::Group(ref x) => format!("<#{}>", x.read().unwrap().channel_id.0), } } } impl Mentionable for Emoji { - fn mention(&self) -> String { - format!("<:{}:{}>", self.name, self.id.0) - } + fn mention(&self) -> String { format!("<:{}:{}>", self.name, self.id.0) } } impl Mentionable for Member { - fn mention(&self) -> String { - format!("<@{}>", self.user.read().unwrap().id.0) - } + fn mention(&self) -> String { format!("<@{}>", self.user.read().unwrap().id.0) } } impl Mentionable for RoleId { - fn mention(&self) -> String { - format!("<@&{}>", self.0) - } + fn mention(&self) -> String { format!("<@&{}>", self.0) } } impl Mentionable for Role { - fn mention(&self) -> String { - format!("<@&{}>", self.id.0) - } + fn mention(&self) -> String { format!("<@&{}>", self.id.0) } } impl Mentionable for UserId { - fn mention(&self) -> String { - format!("<@{}>", self.0) - } + fn mention(&self) -> String { format!("<@{}>", self.0) } } impl Mentionable for User { - fn mention(&self) -> String { - format!("<@{}>", self.id.0) - } + fn mention(&self) -> String { format!("<@{}>", self.id.0) } } -#[cfg(all(feature="cache", feature="utils"))] +#[cfg(all(feature = "cache", feature = "utils"))] impl FromStr for User { type Err = (); @@ -81,15 +61,15 @@ impl FromStr for User { Some(x) => { match UserId(x as u64).find() { Some(user) => Ok(user.read().unwrap().clone()), - _ => Err(()) + _ => Err(()), } }, - _ => Err(()) + _ => Err(()), } } } -#[cfg(all(feature="model", feature="utils"))] +#[cfg(all(feature = "model", feature = "utils"))] impl FromStr for UserId { type Err = (); @@ -98,7 +78,7 @@ impl FromStr for UserId { } } -#[cfg(all(feature="cache", feature="utils"))] +#[cfg(all(feature = "cache", feature = "utils"))] impl FromStr for Role { type Err = (); @@ -107,15 +87,15 @@ impl FromStr for Role { Some(x) => { match RoleId(x).find() { Some(user) => Ok(user), - _ => Err(()) + _ => Err(()), } }, - _ => Err(()) + _ => Err(()), } } } -#[cfg(all(feature="model", feature="utils"))] +#[cfg(all(feature = "model", feature = "utils"))] impl FromStr for RoleId { type Err = (); @@ -134,25 +114,21 @@ pub struct EmojiIdentifier { pub name: String, } -#[cfg(all(feature="model", feature="utils"))] +#[cfg(all(feature = "model", feature = "utils"))] impl EmojiIdentifier { /// Generates a URL to the emoji's image. #[inline] - pub fn url(&self) -> String { - format!(cdn!("/emojis/{}.png"), self.id) - } + pub fn url(&self) -> String { format!(cdn!("/emojis/{}.png"), self.id) } } -#[cfg(all(feature="model", feature="utils"))] +#[cfg(all(feature = "model", feature = "utils"))] impl FromStr for EmojiIdentifier { type Err = (); - fn from_str(s: &str) -> StdResult<Self, ()> { - utils::parse_emoji(s).ok_or_else(|| ()) - } + fn from_str(s: &str) -> StdResult<Self, ()> { utils::parse_emoji(s).ok_or_else(|| ()) } } -#[cfg(all(feature="model", feature="utils"))] +#[cfg(all(feature = "model", feature = "utils"))] impl FromStr for ChannelId { type Err = (); @@ -161,7 +137,7 @@ impl FromStr for ChannelId { } } -#[cfg(all(feature="cache", feature="model", feature="utils"))] +#[cfg(all(feature = "cache", feature = "model", feature = "utils"))] impl FromStr for Channel { type Err = (); @@ -170,10 +146,10 @@ impl FromStr for Channel { Some(x) => { match ChannelId(x).find() { Some(channel) => Ok(channel), - _ => Err(()) + _ => Err(()), } }, - _ => Err(()) + _ => Err(()), } } } @@ -222,7 +198,7 @@ pub struct IncidentUpdate { /// The type of status update during a service incident. #[derive(Copy, Clone, Debug, Deserialize, Hash, Eq, PartialEq, PartialOrd, Ord, Serialize)] -#[serde(rename_all="snake_case")] +#[serde(rename_all = "snake_case")] pub enum IncidentStatus { Identified, Investigating, diff --git a/src/model/mod.rs b/src/model/mod.rs index 84cd7bf..d8bbb2b 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -37,10 +37,10 @@ use serde::de::Visitor; use std::collections::HashMap; use std::fmt::{Formatter, Result as FmtResult}; use std::sync::{Arc, RwLock}; -use ::internal::prelude::*; +use internal::prelude::*; -#[cfg(feature="utils")] -use ::utils::Colour; +#[cfg(feature = "utils")] +use utils::Colour; fn default_true() -> bool { true } @@ -137,7 +137,7 @@ pub struct ApplicationInfo { /// is private, only the owner may add it to a guild. /// /// [`Guild`]: struct.Guild.html - #[serde(default="default_true")] + #[serde(default = "default_true")] pub bot_public: bool, /// Indicator of whether the bot requires an OAuth2 code grant. pub bot_require_code_grant: bool, @@ -205,33 +205,33 @@ pub struct CurrentApplicationInfo { /// The name of a region that a voice server can be located in. #[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)] pub enum Region { - #[serde(rename="amsterdam")] + #[serde(rename = "amsterdam")] Amsterdam, - #[serde(rename="brazil")] + #[serde(rename = "brazil")] Brazil, - #[serde(rename="eu-central")] + #[serde(rename = "eu-central")] EuCentral, - #[serde(rename="eu-west")] + #[serde(rename = "eu-west")] EuWest, - #[serde(rename="frankfurt")] + #[serde(rename = "frankfurt")] Frankfurt, - #[serde(rename="london")] + #[serde(rename = "london")] London, - #[serde(rename="sydney")] + #[serde(rename = "sydney")] Sydney, - #[serde(rename="us-central")] + #[serde(rename = "us-central")] UsCentral, - #[serde(rename="us-east")] + #[serde(rename = "us-east")] UsEast, - #[serde(rename="us-south")] + #[serde(rename = "us-south")] UsSouth, - #[serde(rename="us-west")] + #[serde(rename = "us-west")] UsWest, - #[serde(rename="vip-amsterdam")] + #[serde(rename = "vip-amsterdam")] VipAmsterdam, - #[serde(rename="vip-us-east")] + #[serde(rename = "vip-us-east")] VipUsEast, - #[serde(rename="vip-us-west")] + #[serde(rename = "vip-us-west")] VipUsWest, } @@ -260,6 +260,6 @@ use serde::{Deserialize, Deserializer}; use std::result::Result as StdResult; fn deserialize_sync_user<'de, D: Deserializer<'de>>(deserializer: D) - -> StdResult<Arc<RwLock<User>>, D::Error> { + -> StdResult<Arc<RwLock<User>>, D::Error> { Ok(Arc::new(RwLock::new(User::deserialize(deserializer)?))) } diff --git a/src/model/permissions.rs b/src/model/permissions.rs index 3968e16..a98fedd 100644 --- a/src/model/permissions.rs +++ b/src/model/permissions.rs @@ -253,231 +253,175 @@ bitflags! { } } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Permissions { /// Shorthand for checking that the set of permissions contains the /// [Add Reactions] permission. /// /// [Add Reactions]: constant.ADD_REACTIONS.html - pub fn add_reactions(&self) -> bool { - self.contains(self::ADD_REACTIONS) - } + pub fn add_reactions(&self) -> bool { self.contains(self::ADD_REACTIONS) } /// Shorthand for checking that the set of permissions contains the /// [Administrator] permission. /// /// [Administrator]: constant.ADMINISTRATOR.html - pub fn administrator(&self) -> bool { - self.contains(self::ADMINISTRATOR) - } + pub fn administrator(&self) -> bool { self.contains(self::ADMINISTRATOR) } /// Shorthand for checking that the set of permissions contains the /// [Attach Files] permission. /// /// [Attach Files]: constant.ATTACH_FILES.html - pub fn attach_files(&self) -> bool { - self.contains(self::ATTACH_FILES) - } + pub fn attach_files(&self) -> bool { self.contains(self::ATTACH_FILES) } /// Shorthand for checking that the set of permissions contains the /// [Ban Members] permission. /// /// [Ban Members]: constant.BAN_MEMBERS.html - pub fn ban_members(&self) -> bool { - self.contains(self::BAN_MEMBERS) - } + pub fn ban_members(&self) -> bool { self.contains(self::BAN_MEMBERS) } /// Shorthand for checking that the set of permissions contains the /// [Change Nickname] permission. /// /// [Change Nickname]: constant.CHANGE_NICKNAME.html - pub fn change_nickname(&self) -> bool { - self.contains(self::CHANGE_NICKNAME) - } + pub fn change_nickname(&self) -> bool { self.contains(self::CHANGE_NICKNAME) } /// Shorthand for checking that the set of permissions contains the /// [Connect] permission. /// /// [Connect]: constant.CONNECT.html - pub fn connect(&self) -> bool { - self.contains(self::CONNECT) - } + pub fn connect(&self) -> bool { self.contains(self::CONNECT) } /// Shorthand for checking that the set of permissions contains the /// [Create Invite] permission. /// /// [Create Invite]: constant.CREATE_INVITE.html - pub fn create_invite(&self) -> bool { - self.contains(self::CREATE_INVITE) - } + pub fn create_invite(&self) -> bool { self.contains(self::CREATE_INVITE) } /// Shorthand for checking that the set of permissions contains the /// [Deafen Members] permission. /// /// [Deafen Members]: constant.DEAFEN_MEMBERS.html - pub fn deafen_members(&self) -> bool { - self.contains(self::DEAFEN_MEMBERS) - } + pub fn deafen_members(&self) -> bool { self.contains(self::DEAFEN_MEMBERS) } /// Shorthand for checking that the set of permissions contains the /// [Embed Links] permission. /// /// [Embed Links]: constant.EMBED_LINKS.html - pub fn embed_links(&self) -> bool { - self.contains(self::EMBED_LINKS) - } + pub fn embed_links(&self) -> bool { self.contains(self::EMBED_LINKS) } /// Shorthand for checking that the set of permissions contains the /// [Use External Emojis] permission. /// /// [Use External Emojis]: constant.USE_EXTERNAL_EMOJIS.html - pub fn external_emojis(&self) -> bool { - self.contains(self::USE_EXTERNAL_EMOJIS) - } + pub fn external_emojis(&self) -> bool { self.contains(self::USE_EXTERNAL_EMOJIS) } /// Shorthand for checking that the set of permissions contains the /// [Kick Members] permission. /// /// [Kick Members]: constant.KICK_MEMBERS.html - pub fn kick_members(&self) -> bool { - self.contains(self::KICK_MEMBERS) - } + pub fn kick_members(&self) -> bool { self.contains(self::KICK_MEMBERS) } /// Shorthand for checking that the set of permissions contains the /// [Manage Channels] permission. /// /// [Manage Channels]: constant.MANAGE_CHANNELS.html - pub fn manage_channels(&self) -> bool { - self.contains(self::MANAGE_CHANNELS) - } + pub fn manage_channels(&self) -> bool { self.contains(self::MANAGE_CHANNELS) } /// Shorthand for checking that the set of permissions contains the /// [Manage Emojis] permission. /// /// [Manage Emojis]: constant.MANAGE_EMOJIS.html - pub fn manage_emojis(&self) -> bool { - self.contains(self::MANAGE_EMOJIS) - } + pub fn manage_emojis(&self) -> bool { self.contains(self::MANAGE_EMOJIS) } /// Shorthand for checking that the set of permissions contains the /// [Manage Guild] permission. /// /// [Manage Guild]: constant.MANAGE_GUILD.html - pub fn manage_guild(&self) -> bool { - self.contains(self::MANAGE_GUILD) - } + pub fn manage_guild(&self) -> bool { self.contains(self::MANAGE_GUILD) } /// Shorthand for checking that the set of permissions contains the /// [Manage Messages] permission. /// /// [Manage Messages]: constant.MANAGE_MESSAGES.html - pub fn manage_messages(&self) -> bool { - self.contains(self::MANAGE_MESSAGES) - } + pub fn manage_messages(&self) -> bool { self.contains(self::MANAGE_MESSAGES) } /// Shorthand for checking that the set of permissions contains the /// [Manage Nicknames] permission. /// /// [Manage Nicknames]: constant.MANAGE_NICKNAMES.html - pub fn manage_nicknames(&self) -> bool { - self.contains(self::MANAGE_NICKNAMES) - } + pub fn manage_nicknames(&self) -> bool { self.contains(self::MANAGE_NICKNAMES) } /// Shorthand for checking that the set of permissions contains the /// [Manage Roles] permission. /// /// [Manage Roles]: constant.MANAGE_ROLES.html - pub fn manage_roles(&self) -> bool { - self.contains(self::MANAGE_ROLES) - } + pub fn manage_roles(&self) -> bool { self.contains(self::MANAGE_ROLES) } /// Shorthand for checking that the set of permissions contains the /// [Manage Webhooks] permission. /// /// [Manage Webhooks]: constant.MANAGE_WEBHOOKS.html - pub fn manage_webhooks(&self) -> bool { - self.contains(self::MANAGE_WEBHOOKS) - } + pub fn manage_webhooks(&self) -> bool { self.contains(self::MANAGE_WEBHOOKS) } /// Shorthand for checking that the set of permissions contains the /// [Mention Everyone] permission. /// /// [Mention Everyone]: constant.MENTION_EVERYONE.html - pub fn mention_everyone(&self) -> bool { - self.contains(self::MENTION_EVERYONE) - } + pub fn mention_everyone(&self) -> bool { self.contains(self::MENTION_EVERYONE) } /// Shorthand for checking that the set of permissions contains the /// [Move Members] permission. /// /// [Move Members]: constant.MOVE_MEMBERS.html - pub fn move_members(&self) -> bool { - self.contains(self::MOVE_MEMBERS) - } + pub fn move_members(&self) -> bool { self.contains(self::MOVE_MEMBERS) } /// Shorthand for checking that the set of permissions contains the /// [Mute Members] permission. /// /// [Mute Members]: constant.MUTE_MEMBERS.html - pub fn mute_members(&self) -> bool { - self.contains(self::MUTE_MEMBERS) - } + pub fn mute_members(&self) -> bool { self.contains(self::MUTE_MEMBERS) } /// Shorthand for checking that the set of permissions contains the /// [Read Message History] permission. /// /// [Read Message History]: constant.READ_MESSAGE_HISTORY.html - pub fn read_message_history(&self) -> bool { - self.contains(self::READ_MESSAGE_HISTORY) - } + pub fn read_message_history(&self) -> bool { self.contains(self::READ_MESSAGE_HISTORY) } /// Shorthand for checking that the set of permissions contains the /// [Read Messages] permission. /// /// [Read Messages]: constant.READ_MESSAGES.html - pub fn read_messages(&self) -> bool { - self.contains(self::READ_MESSAGES) - } + pub fn read_messages(&self) -> bool { self.contains(self::READ_MESSAGES) } /// Shorthand for checking that the set of permissions contains the /// [Send Messages] permission. /// /// [Send Messages]: constant.SEND_MESSAGES.html - pub fn send_messages(&self) -> bool { - self.contains(self::SEND_MESSAGES) - } + pub fn send_messages(&self) -> bool { self.contains(self::SEND_MESSAGES) } /// Shorthand for checking that the set of permissions contains the /// [Send TTS Messages] permission. /// /// [Send TTS Messages]: constant.SEND_TTS_MESSAGES.html - pub fn send_tts_messages(&self) -> bool { - self.contains(self::SEND_TTS_MESSAGES) - } + pub fn send_tts_messages(&self) -> bool { self.contains(self::SEND_TTS_MESSAGES) } /// Shorthand for checking that the set of permissions contains the /// [Speak] permission. /// /// [Speak]: constant.SPEAK.html - pub fn speak(&self) -> bool { - self.contains(self::SPEAK) - } + pub fn speak(&self) -> bool { self.contains(self::SPEAK) } /// Shorthand for checking that the set of permissions contains the /// [Use External Emojis] permission. /// /// [Use External Emojis]: constant.USE_EXTERNAL_EMOJIS.html - pub fn use_external_emojis(&self) -> bool { - self.contains(self::USE_EXTERNAL_EMOJIS) - } + pub fn use_external_emojis(&self) -> bool { self.contains(self::USE_EXTERNAL_EMOJIS) } /// Shorthand for checking that the set of permissions contains the /// [Use VAD] permission. /// /// [Use VAD]: constant.USE_VAD.html - pub fn use_vad(&self) -> bool { - self.contains(self::USE_VAD) - } + pub fn use_vad(&self) -> bool { self.contains(self::USE_VAD) } } impl<'de> Deserialize<'de> for Permissions { @@ -495,19 +439,11 @@ impl<'de> Visitor<'de> for U64Visitor { formatter.write_str("an unsigned 64-bit integer") } - fn visit_i32<E: DeError>(self, value: i32) -> StdResult<u64, E> { - Ok(value as u64) - } + fn visit_i32<E: DeError>(self, value: i32) -> StdResult<u64, E> { Ok(value as u64) } - fn visit_i64<E: DeError>(self, value: i64) -> StdResult<u64, E> { - Ok(value as u64) - } + fn visit_i64<E: DeError>(self, value: i64) -> StdResult<u64, E> { Ok(value as u64) } - fn visit_u32<E: DeError>(self, value: u32) -> StdResult<u64, E> { - Ok(value as u64) - } + fn visit_u32<E: DeError>(self, value: u32) -> StdResult<u64, E> { Ok(value as u64) } - fn visit_u64<E: DeError>(self, value: u64) -> StdResult<u64, E> { - Ok(value) - } + fn visit_u64<E: DeError>(self, value: u64) -> StdResult<u64, E> { Ok(value) } } diff --git a/src/model/user.rs b/src/model/user.rs index e447519..56e5fbf 100644 --- a/src/model/user.rs +++ b/src/model/user.rs @@ -2,23 +2,23 @@ use serde_json; use std::fmt; use super::utils::deserialize_u16; use super::*; -use ::internal::prelude::*; -use ::model::misc::Mentionable; +use internal::prelude::*; +use model::misc::Mentionable; -#[cfg(feature="model")] +#[cfg(feature = "model")] use chrono::NaiveDateTime; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::fmt::Write; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::mem; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] use std::sync::{Arc, RwLock}; -#[cfg(feature="model")] -use ::builder::{CreateMessage, EditProfile}; -#[cfg(feature="cache")] -use ::CACHE; -#[cfg(feature="model")] -use ::http::{self, GuildPagination}; +#[cfg(feature = "model")] +use builder::{CreateMessage, EditProfile}; +#[cfg(feature = "cache")] +use CACHE; +#[cfg(feature = "model")] +use http::{self, GuildPagination}; /// Information about the current user. #[derive(Clone, Debug, Deserialize)] @@ -27,16 +27,16 @@ pub struct CurrentUser { pub avatar: Option<String>, #[serde(default)] pub bot: bool, - #[serde(deserialize_with="deserialize_u16")] + #[serde(deserialize_with = "deserialize_u16")] pub discriminator: u16, pub email: Option<String>, pub mfa_enabled: bool, - #[serde(rename="username")] + #[serde(rename = "username")] pub name: String, pub verified: bool, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl CurrentUser { /// Returns the formatted URL of the user's icon, if one exists. /// @@ -60,17 +60,13 @@ impl CurrentUser { /// } /// ``` #[inline] - pub fn avatar_url(&self) -> Option<String> { - avatar_url(self.id, self.avatar.as_ref()) - } + pub fn avatar_url(&self) -> Option<String> { avatar_url(self.id, self.avatar.as_ref()) } /// Returns the formatted URL to the user's default avatar URL. /// /// This will produce a PNG URL. #[inline] - pub fn default_avatar_url(&self) -> String { - default_avatar_url(self.discriminator) - } + pub fn default_avatar_url(&self) -> String { default_avatar_url(self.discriminator) } /// Edits the current user's profile settings. /// @@ -90,7 +86,8 @@ impl CurrentUser { /// CACHE.write().unwrap().user.edit(|p| p.avatar(Some(&avatar))); /// ``` pub fn edit<F>(&mut self, f: F) -> Result<()> - where F: FnOnce(EditProfile) -> EditProfile { + where + F: FnOnce(EditProfile) -> EditProfile, { let mut map = Map::new(); map.insert("username".to_owned(), Value::String(self.name.clone())); @@ -117,7 +114,8 @@ impl CurrentUser { /// [`avatar_url`]: #method.avatar_url /// [`default_avatar_url`]: #method.default_avatar_url pub fn face(&self) -> String { - self.avatar_url().unwrap_or_else(|| self.default_avatar_url()) + self.avatar_url() + .unwrap_or_else(|| self.default_avatar_url()) } /// Gets a list of guilds that the current user is in. @@ -193,7 +191,9 @@ impl CurrentUser { /// }, /// }; /// - /// assert_eq!(url, "https://discordapp.com/api/oauth2/authorize?client_id=249608697955745802&scope=bot&permissions=19456"); + /// assert_eq!(url, + /// "https://discordapp. + /// com/api/oauth2/authorize?client_id=249608697955745802&scope=bot&permissions=19456"); /// ``` /// /// # Errors @@ -213,7 +213,8 @@ impl CurrentUser { Err(e) => return Err(e), }; - let mut url = format!("https://discordapp.com/api/oauth2/authorize?client_id={}&scope=bot", client_id); + let mut url = format!("https://discordapp.com/api/oauth2/authorize?client_id={}&scope=bot", + client_id); if bits != 0 { write!(url, "&permissions={}", bits)?; @@ -263,9 +264,7 @@ impl CurrentUser { /// println!("The current user's distinct identifier is {}", cache.user.tag()); /// ``` #[inline] - pub fn tag(&self) -> String { - tag(&self.name, self.discriminator) - } + pub fn tag(&self) -> String { tag(&self.name, self.discriminator) } } /// An enum that represents a default avatar. @@ -278,27 +277,25 @@ impl CurrentUser { #[derive(Copy, Clone, Debug, Deserialize, Hash, Eq, PartialEq, PartialOrd, Ord, Serialize)] pub enum DefaultAvatar { /// The avatar when the result is `0`. - #[serde(rename="6debd47ed13483642cf09e832ed0bc1b")] + #[serde(rename = "6debd47ed13483642cf09e832ed0bc1b")] Blurple, /// The avatar when the result is `1`. - #[serde(rename="322c936a8c8be1b803cd94861bdfa868")] + #[serde(rename = "322c936a8c8be1b803cd94861bdfa868")] Grey, /// The avatar when the result is `2`. - #[serde(rename="dd4dbc0016779df1378e7812eabaa04d")] + #[serde(rename = "dd4dbc0016779df1378e7812eabaa04d")] Green, /// The avatar when the result is `3`. - #[serde(rename="0e291f67c9274a1abdddeb3fd919cbaa")] + #[serde(rename = "0e291f67c9274a1abdddeb3fd919cbaa")] Orange, /// The avatar when the result is `4`. - #[serde(rename="1cbd08c76f8af6dddce02c5138971129")] + #[serde(rename = "1cbd08c76f8af6dddce02c5138971129")] Red, } impl DefaultAvatar { /// Retrieves the String hash of the default avatar. - pub fn name(&self) -> Result<String> { - serde_json::to_string(self).map_err(From::from) - } + pub fn name(&self) -> Result<String> { serde_json::to_string(self).map_err(From::from) } } enum_number!( @@ -326,15 +323,15 @@ enum_number!( /// [`Invisible`]: #variant.Invisible #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)] pub enum OnlineStatus { - #[serde(rename="dnd")] + #[serde(rename = "dnd")] DoNotDisturb, - #[serde(rename="idle")] + #[serde(rename = "idle")] Idle, - #[serde(rename="invisible")] + #[serde(rename = "invisible")] Invisible, - #[serde(rename="offline")] + #[serde(rename = "offline")] Offline, - #[serde(rename="online")] + #[serde(rename = "online")] Online, } @@ -351,9 +348,7 @@ impl OnlineStatus { } impl Default for OnlineStatus { - fn default() -> OnlineStatus { - OnlineStatus::Online - } + fn default() -> OnlineStatus { OnlineStatus::Online } } /// Information about a user. @@ -371,46 +366,38 @@ pub struct User { /// the same [`name`]. The name+discriminator pair is always unique. /// /// [`name`]: #structfield.name - #[serde(deserialize_with="deserialize_u16")] + #[serde(deserialize_with = "deserialize_u16")] pub discriminator: u16, /// The account's username. Changing username will trigger a discriminator /// change if the username+discriminator pair becomes non-unique. - #[serde(rename="username")] + #[serde(rename = "username")] pub name: String, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl User { /// Returns the formatted URL of the user's icon, if one exists. /// /// This will produce a WEBP image URL, or GIF if the user has a GIF avatar. #[inline] - pub fn avatar_url(&self) -> Option<String> { - avatar_url(self.id, self.avatar.as_ref()) - } + pub fn avatar_url(&self) -> Option<String> { avatar_url(self.id, self.avatar.as_ref()) } /// Creates a direct message channel between the [current user] and the /// user. This can also retrieve the channel if one already exists. /// /// [current user]: struct.CurrentUser.html #[inline] - pub fn create_dm_channel(&self) -> Result<PrivateChannel> { - self.id.create_dm_channel() - } + pub fn create_dm_channel(&self) -> Result<PrivateChannel> { self.id.create_dm_channel() } /// Retrieves the time that this user was created at. #[inline] - pub fn created_at(&self) -> NaiveDateTime { - self.id.created_at() - } + pub fn created_at(&self) -> NaiveDateTime { self.id.created_at() } /// Returns the formatted URL to the user's default avatar URL. /// /// This will produce a PNG URL. #[inline] - pub fn default_avatar_url(&self) -> String { - default_avatar_url(self.discriminator) - } + pub fn default_avatar_url(&self) -> String { default_avatar_url(self.discriminator) } /// Sends a message to a user through a direct message channel. This is a /// channel that can only be accessed by you and the recipient. @@ -449,7 +436,8 @@ impl User { /// return; /// } /// }; - /// let help = format!("Helpful info here. Invite me with this link: <{}>", url); + /// let help = format!("Helpful info here. Invite me with this link: <{}>", + /// url); /// /// match msg.author.direct_message(|m| m.content(&help)) { /// Ok(_) => { @@ -462,7 +450,7 @@ impl User { /// }, /// }; /// } - /// } + /// } /// } /// /// let mut client = Client::new("token", Handler); @@ -491,9 +479,10 @@ impl User { // // (AKA: Clippy is wrong and so we have to mark as allowing this lint.) #[allow(let_and_return)] - #[cfg(feature="builder")] + #[cfg(feature = "builder")] pub fn direct_message<F>(&self, f: F) -> Result<Message> - where F: FnOnce(CreateMessage) -> CreateMessage { + where + F: FnOnce(CreateMessage) -> CreateMessage, { if self.bot { return Err(Error::Model(ModelError::MessagingBot)); } @@ -550,7 +539,7 @@ impl User { /// /// [`ModelError::MessagingBot`]: enum.ModelError.html#variant.MessagingBot /// [direct_message]: #method.direct_message - #[cfg(feature="builder")] + #[cfg(feature = "builder")] #[inline] pub fn dm<F: FnOnce(CreateMessage) -> CreateMessage>(&self, f: F) -> Result<Message> { self.direct_message(f) @@ -565,7 +554,8 @@ impl User { /// [`avatar_url`]: #method.avatar_url /// [`default_avatar_url`]: #method.default_avatar_url pub fn face(&self) -> String { - self.avatar_url().unwrap_or_else(|| self.default_avatar_url()) + self.avatar_url() + .unwrap_or_else(|| self.default_avatar_url()) } /// Check if a user has a [`Role`]. This will retrieve the [`Guild`] from @@ -590,13 +580,13 @@ impl User { /// [`Cache`]: ../cache/struct.Cache.html // no-cache would warn on guild_id. pub fn has_role<G, R>(&self, guild: G, role: R) -> bool - where G: Into<GuildContainer>, R: Into<RoleId> { + where + G: Into<GuildContainer>, + R: Into<RoleId>, { let role_id = role.into(); match guild.into() { - GuildContainer::Guild(guild) => { - guild.roles.contains_key(&role_id) - }, + GuildContainer::Guild(guild) => guild.roles.contains_key(&role_id), GuildContainer::Id(_guild_id) => { feature_cache! {{ CACHE.read() @@ -631,7 +621,7 @@ impl User { /// impl EventHandler for Handler { /// fn on_message(&self, _: Context, _: Message) { /// // normal message handling here - /// } + /// } /// } /// let mut client = Client::new("token", Handler); /// # @@ -708,15 +698,13 @@ impl User { /// .build(); /// /// let _ = msg.channel_id.say(&content); - /// } - /// } + /// } + /// } /// } /// let mut client = Client::new("token", Handler); client.start().unwrap(); /// ``` #[inline] - pub fn tag(&self) -> String { - tag(&self.name, self.discriminator) - } + pub fn tag(&self) -> String { tag(&self.name, self.discriminator) } } impl fmt::Display for User { @@ -727,7 +715,7 @@ impl fmt::Display for User { } } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl UserId { /// Creates a direct message channel between the [current user] and the /// user. This can also retrieve the channel if one already exists. @@ -742,69 +730,51 @@ impl UserId { } /// Search the cache for the user with the Id. - #[cfg(feature="cache")] - pub fn find(&self) -> Option<Arc<RwLock<User>>> { - CACHE.read().unwrap().user(*self) - } + #[cfg(feature = "cache")] + pub fn find(&self) -> Option<Arc<RwLock<User>>> { CACHE.read().unwrap().user(*self) } /// Gets a user by its Id over the REST API. /// /// **Note**: The current user must be a bot user. #[inline] - pub fn get(&self) -> Result<User> { - http::get_user(self.0) - } + pub fn get(&self) -> Result<User> { http::get_user(self.0) } } impl From<CurrentUser> for UserId { /// Gets the Id of a `CurrentUser` struct. - fn from(current_user: CurrentUser) -> UserId { - current_user.id - } + fn from(current_user: CurrentUser) -> UserId { current_user.id } } impl<'a> From<&'a CurrentUser> for UserId { /// Gets the Id of a `CurrentUser` struct. - fn from(current_user: &CurrentUser) -> UserId { - current_user.id - } + fn from(current_user: &CurrentUser) -> UserId { current_user.id } } impl From<Member> for UserId { /// Gets the Id of a `Member`. - fn from(member: Member) -> UserId { - member.user.read().unwrap().id - } + fn from(member: Member) -> UserId { member.user.read().unwrap().id } } impl<'a> From<&'a Member> for UserId { /// Gets the Id of a `Member`. - fn from(member: &Member) -> UserId { - member.user.read().unwrap().id - } + fn from(member: &Member) -> UserId { member.user.read().unwrap().id } } impl From<User> for UserId { /// Gets the Id of a `User`. - fn from(user: User) -> UserId { - user.id - } + fn from(user: User) -> UserId { user.id } } impl<'a> From<&'a User> for UserId { /// Gets the Id of a `User`. - fn from(user: &User) -> UserId { - user.id - } + fn from(user: &User) -> UserId { user.id } } impl fmt::Display for UserId { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.0, f) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } -#[cfg(feature="model")] +#[cfg(feature = "model")] fn avatar_url(user_id: UserId, hash: Option<&String>) -> Option<String> { hash.map(|hash| { let ext = if hash.starts_with("a_") { @@ -817,17 +787,17 @@ fn avatar_url(user_id: UserId, hash: Option<&String>) -> Option<String> { }) } -#[cfg(feature="model")] +#[cfg(feature = "model")] fn default_avatar_url(discriminator: u16) -> String { cdn!("/embed/avatars/{}.png", discriminator % 5u16) } -#[cfg(feature="model")] +#[cfg(feature = "model")] fn static_avatar_url(user_id: UserId, hash: Option<&String>) -> Option<String> { hash.map(|hash| cdn!("/avatars/{}/{}.webp?size=1024", user_id, hash)) } -#[cfg(feature="model")] +#[cfg(feature = "model")] fn tag(name: &str, discriminator: u16) -> String { // 32: max length of username // 1: `#` diff --git a/src/model/utils.rs b/src/model/utils.rs index f88ecf5..e793df2 100644 --- a/src/model/utils.rs +++ b/src/model/utils.rs @@ -3,15 +3,16 @@ use std::collections::HashMap; use std::sync::{Arc, RwLock}; use super::*; -#[cfg(feature="cache")] -use ::internal::prelude::*; +#[cfg(feature = "cache")] +use internal::prelude::*; -#[cfg(feature="cache")] +#[cfg(feature = "cache")] use super::permissions::Permissions; -#[cfg(feature="cache")] -use ::CACHE; +#[cfg(feature = "cache")] +use CACHE; -pub fn deserialize_emojis<'de, D: Deserializer<'de>>(deserializer: D) +pub fn deserialize_emojis<'de, D: Deserializer<'de>>( + deserializer: D) -> StdResult<HashMap<EmojiId, Emoji>, D::Error> { let vec: Vec<Emoji> = Deserialize::deserialize(deserializer)?; let mut emojis = HashMap::new(); @@ -23,7 +24,8 @@ pub fn deserialize_emojis<'de, D: Deserializer<'de>>(deserializer: D) Ok(emojis) } -pub fn deserialize_guild_channels<'de, D: Deserializer<'de>>(deserializer: D) +pub fn deserialize_guild_channels<'de, D: Deserializer<'de>>( + deserializer: D) -> StdResult<HashMap<ChannelId, Arc<RwLock<GuildChannel>>>, D::Error> { let vec: Vec<GuildChannel> = Deserialize::deserialize(deserializer)?; let mut map = HashMap::new(); @@ -35,7 +37,8 @@ pub fn deserialize_guild_channels<'de, D: Deserializer<'de>>(deserializer: D) Ok(map) } -pub fn deserialize_members<'de, D: Deserializer<'de>>(deserializer: D) +pub fn deserialize_members<'de, D: Deserializer<'de>>( + deserializer: D) -> StdResult<HashMap<UserId, Member>, D::Error> { let vec: Vec<Member> = Deserialize::deserialize(deserializer)?; let mut members = HashMap::new(); @@ -49,7 +52,8 @@ pub fn deserialize_members<'de, D: Deserializer<'de>>(deserializer: D) Ok(members) } -pub fn deserialize_presences<'de, D: Deserializer<'de>>(deserializer: D) +pub fn deserialize_presences<'de, D: Deserializer<'de>>( + deserializer: D) -> StdResult<HashMap<UserId, Presence>, D::Error> { let vec: Vec<Presence> = Deserialize::deserialize(deserializer)?; let mut presences = HashMap::new(); @@ -61,7 +65,8 @@ pub fn deserialize_presences<'de, D: Deserializer<'de>>(deserializer: D) Ok(presences) } -pub fn deserialize_private_channels<'de, D: Deserializer<'de>>(deserializer: D) +pub fn deserialize_private_channels<'de, D: Deserializer<'de>>( + deserializer: D) -> StdResult<HashMap<ChannelId, Channel>, D::Error> { let vec: Vec<Channel> = Deserialize::deserialize(deserializer)?; let mut private_channels = HashMap::new(); @@ -79,7 +84,8 @@ pub fn deserialize_private_channels<'de, D: Deserializer<'de>>(deserializer: D) Ok(private_channels) } -pub fn deserialize_roles<'de, D: Deserializer<'de>>(deserializer: D) +pub fn deserialize_roles<'de, D: Deserializer<'de>>( + deserializer: D) -> StdResult<HashMap<RoleId, Role>, D::Error> { let vec: Vec<Role> = Deserialize::deserialize(deserializer)?; let mut roles = HashMap::new(); @@ -91,7 +97,8 @@ pub fn deserialize_roles<'de, D: Deserializer<'de>>(deserializer: D) Ok(roles) } -pub fn deserialize_single_recipient<'de, D: Deserializer<'de>>(deserializer: D) +pub fn deserialize_single_recipient<'de, D: Deserializer<'de>>( + deserializer: D) -> StdResult<Arc<RwLock<User>>, D::Error> { let mut users: Vec<User> = Deserialize::deserialize(deserializer)?; let user = if users.is_empty() { @@ -103,7 +110,8 @@ pub fn deserialize_single_recipient<'de, D: Deserializer<'de>>(deserializer: D) Ok(Arc::new(RwLock::new(user))) } -pub fn deserialize_users<'de, D: Deserializer<'de>>(deserializer: D) +pub fn deserialize_users<'de, D: Deserializer<'de>>( + deserializer: D) -> StdResult<HashMap<UserId, Arc<RwLock<User>>>, D::Error> { let vec: Vec<User> = Deserialize::deserialize(deserializer)?; let mut users = HashMap::new(); @@ -115,17 +123,16 @@ pub fn deserialize_users<'de, D: Deserializer<'de>>(deserializer: D) Ok(users) } -pub fn deserialize_u16<'de, D: Deserializer<'de>>(deserializer: D) - -> StdResult<u16, D::Error> { +pub fn deserialize_u16<'de, D: Deserializer<'de>>(deserializer: D) -> StdResult<u16, D::Error> { deserializer.deserialize_u16(U16Visitor) } -pub fn deserialize_u64<'de, D: Deserializer<'de>>(deserializer: D) - -> StdResult<u64, D::Error> { +pub fn deserialize_u64<'de, D: Deserializer<'de>>(deserializer: D) -> StdResult<u64, D::Error> { deserializer.deserialize_u64(U64Visitor) } -pub fn deserialize_voice_states<'de, D: Deserializer<'de>>(deserializer: D) +pub fn deserialize_voice_states<'de, D: Deserializer<'de>>( + deserializer: D) -> StdResult<HashMap<UserId, VoiceState>, D::Error> { let vec: Vec<VoiceState> = Deserialize::deserialize(deserializer)?; let mut voice_states = HashMap::new(); @@ -137,7 +144,7 @@ pub fn deserialize_voice_states<'de, D: Deserializer<'de>>(deserializer: D) Ok(voice_states) } -#[cfg(all(feature="cache", feature="model"))] +#[cfg(all(feature = "cache", feature = "model"))] pub fn user_has_perms(channel_id: ChannelId, mut permissions: Permissions) -> Result<bool> { let cache = CACHE.read().unwrap(); let current_user = &cache.user; @@ -168,7 +175,10 @@ pub fn user_has_perms(channel_id: ChannelId, mut permissions: Permissions) -> Re None => return Err(Error::Model(ModelError::ItemMissing)), }; - let perms = guild.read().unwrap().permissions_for(channel_id, current_user.id); + let perms = guild + .read() + .unwrap() + .permissions_for(channel_id, current_user.id); permissions.remove(perms); @@ -199,13 +209,9 @@ impl<'de> Visitor<'de> for U16Visitor { } } - fn visit_i64<E: DeError>(self, v: i64) -> StdResult<Self::Value, E> { - Ok(v as u16) - } + fn visit_i64<E: DeError>(self, v: i64) -> StdResult<Self::Value, E> { Ok(v as u16) } - fn visit_u64<E: DeError>(self, v: u64) -> StdResult<Self::Value, E> { - Ok(v as u16) - } + fn visit_u64<E: DeError>(self, v: u64) -> StdResult<Self::Value, E> { Ok(v as u16) } } pub struct U64Visitor; @@ -232,11 +238,7 @@ impl<'de> Visitor<'de> for U64Visitor { } } - fn visit_i64<E: DeError>(self, v: i64) -> StdResult<Self::Value, E> { - Ok(v as u64) - } + fn visit_i64<E: DeError>(self, v: i64) -> StdResult<Self::Value, E> { Ok(v as u64) } - fn visit_u64<E: DeError>(self, v: u64) -> StdResult<Self::Value, E> { - Ok(v) - } + fn visit_u64<E: DeError>(self, v: u64) -> StdResult<Self::Value, E> { Ok(v) } } diff --git a/src/model/webhook.rs b/src/model/webhook.rs index a858589..9422d46 100644 --- a/src/model/webhook.rs +++ b/src/model/webhook.rs @@ -1,13 +1,13 @@ use super::*; -#[cfg(feature="model")] +#[cfg(feature = "model")] use std::mem; -#[cfg(feature="model")] -use ::builder::ExecuteWebhook; -#[cfg(feature="model")] -use ::internal::prelude::*; -#[cfg(feature="model")] -use ::http; +#[cfg(feature = "model")] +use builder::ExecuteWebhook; +#[cfg(feature = "model")] +use internal::prelude::*; +#[cfg(feature = "model")] +use http; /// A representation of a webhook, which is a low-effort way to post messages to /// channels. They do not necessarily require a bot user or authentication to @@ -42,7 +42,7 @@ pub struct Webhook { pub user: Option<User>, } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl Webhook { /// Deletes the webhook. /// @@ -51,9 +51,7 @@ impl Webhook { /// /// [`http::delete_webhook_with_token`]: ../http/fn.delete_webhook_with_token.html #[inline] - pub fn delete(&self) -> Result<()> { - http::delete_webhook_with_token(self.id.0, &self.token) - } + pub fn delete(&self) -> Result<()> { http::delete_webhook_with_token(self.id.0, &self.token) } /// /// Edits the webhook in-place. All fields are optional. @@ -109,11 +107,12 @@ impl Webhook { let mut map = Map::new(); if let Some(avatar) = avatar { - map.insert("avatar".to_owned(), if avatar.is_empty() { - Value::Null - } else { - Value::String(avatar.to_owned()) - }); + map.insert("avatar".to_owned(), + if avatar.is_empty() { + Value::Null + } else { + Value::String(avatar.to_owned()) + }); } if let Some(name) = name { @@ -178,9 +177,14 @@ impl Webhook { /// .expect("Error executing"); /// ``` #[inline] - pub fn execute<F: FnOnce(ExecuteWebhook) -> ExecuteWebhook>(&self, wait: bool, f: F) - -> Result<Option<Message>> { - http::execute_webhook(self.id.0, &self.token, wait, &f(ExecuteWebhook::default()).0) + pub fn execute<F: FnOnce(ExecuteWebhook) -> ExecuteWebhook>(&self, + wait: bool, + f: F) + -> Result<Option<Message>> { + http::execute_webhook(self.id.0, + &self.token, + wait, + &f(ExecuteWebhook::default()).0) } /// Retrieves the latest information about the webhook, editing the @@ -202,7 +206,7 @@ impl Webhook { } } -#[cfg(feature="model")] +#[cfg(feature = "model")] impl WebhookId { /// Retrieves the webhook by the Id. /// @@ -210,7 +214,5 @@ impl WebhookId { /// /// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html #[inline] - pub fn get(&self) -> Result<Webhook> { - http::get_webhook(self.0) - } + pub fn get(&self) -> Result<Webhook> { http::get_webhook(self.0) } } diff --git a/src/prelude.rs b/src/prelude.rs index c7d8537..ff27bb6 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -14,16 +14,16 @@ //! //! [`serenity::Error`]: ../enum.Error.html -pub use ::error::{Error as SerenityError}; -pub use ::model::Mentionable; +pub use error::Error as SerenityError; +pub use model::Mentionable; -#[cfg(feature="client")] -pub use ::client::{Context, Client, ClientError as ClientError, EventHandler}; -#[cfg(feature="gateway")] -pub use ::gateway::GatewayError; -#[cfg(feature="http")] -pub use ::http::HttpError; -#[cfg(feature="model")] -pub use ::model::ModelError; -#[cfg(feature="voice")] -pub use ::voice::VoiceError; +#[cfg(feature = "client")] +pub use client::{Client, ClientError as ClientError, Context, EventHandler}; +#[cfg(feature = "gateway")] +pub use gateway::GatewayError; +#[cfg(feature = "http")] +pub use http::HttpError; +#[cfg(feature = "model")] +pub use model::ModelError; +#[cfg(feature = "voice")] +pub use voice::VoiceError; diff --git a/src/utils/colour.rs b/src/utils/colour.rs index 6436a06..b52af9a 100644 --- a/src/utils/colour.rs +++ b/src/utils/colour.rs @@ -93,9 +93,7 @@ impl Colour { /// /// [`tuple`]: #method.tuple #[inline] - pub fn new(value: u32) -> Colour { - Colour(value) - } + pub fn new(value: u32) -> Colour { Colour(value) } /// Generates a new Colour from an RGB value, creating an inner u32 /// representation. @@ -140,9 +138,7 @@ impl Colour { /// /// assert_eq!(Colour::new(6573123).r(), 100); /// ``` - pub fn r(&self) -> u8 { - ((self.0 >> 16) & 255) as u8 - } + pub fn r(&self) -> u8 { ((self.0 >> 16) & 255) as u8 } /// Returns the green RGB component of this Colour. /// @@ -153,9 +149,7 @@ impl Colour { /// /// assert_eq!(Colour::new(6573123).g(), 76); /// ``` - pub fn g(&self) -> u8 { - ((self.0 >> 8) & 255) as u8 - } + pub fn g(&self) -> u8 { ((self.0 >> 8) & 255) as u8 } /// Returns the blue RGB component of this Colour. /// @@ -165,9 +159,7 @@ impl Colour { /// use serenity::utils::Colour; /// /// assert_eq!(Colour::new(6573123).b(), 67); - pub fn b(&self) -> u8 { - (self.0 & 255) as u8 - } + pub fn b(&self) -> u8 { (self.0 & 255) as u8 } /// Returns a tuple of the red, green, and blue components of this Colour. /// @@ -185,9 +177,7 @@ impl Colour { /// [`r`]: #method.r /// [`g`]: #method.g /// [`b`]: #method.b - pub fn tuple(&self) -> (u8, u8, u8) { - (self.r(), self.g(), self.b()) - } + pub fn tuple(&self) -> (u8, u8, u8) { (self.r(), self.g(), self.b()) } } impl From<i32> for Colour { @@ -204,9 +194,7 @@ impl From<i32> for Colour { /// /// assert_eq!(Colour::from(0xDEA584).tuple(), (222, 165, 132)); /// ``` - fn from(value: i32) -> Colour { - Colour(value as u32) - } + fn from(value: i32) -> Colour { Colour(value as u32) } } impl From<u32> for Colour { @@ -221,9 +209,7 @@ impl From<u32> for Colour { /// /// assert_eq!(Colour::from(6573123u32).r(), 100); /// ``` - fn from(value: u32) -> Colour { - Colour(value) - } + fn from(value: u32) -> Colour { Colour(value) } } impl From<u64> for Colour { @@ -238,9 +224,7 @@ impl From<u64> for Colour { /// /// assert_eq!(Colour::from(6573123u64).r(), 100); /// ``` - fn from(value: u64) -> Colour { - Colour(value as u32) - } + fn from(value: u64) -> Colour { Colour(value as u32) } } colour! { @@ -304,7 +288,5 @@ colour! { impl Default for Colour { /// Creates a default value for a `Colour`, setting the inner value to `0`. - fn default() -> Colour { - Colour(0) - } + fn default() -> Colour { Colour(0) } } diff --git a/src/utils/message_builder.rs b/src/utils/message_builder.rs index 9132f9d..8fd26e9 100644 --- a/src/utils/message_builder.rs +++ b/src/utils/message_builder.rs @@ -1,7 +1,7 @@ use std::default::Default; -use std::fmt::{self, Write, Display}; +use std::fmt::{self, Display, Write}; use std::ops::Add; -use ::model::{ChannelId, Emoji, Mentionable, RoleId, UserId}; +use model::{ChannelId, Emoji, Mentionable, RoleId, UserId}; /// The Message Builder is an ergonomic utility to easily build a message, /// by adding text and mentioning mentionable structs. @@ -58,9 +58,7 @@ impl MessageBuilder { /// // alternatively: /// let message = MessageBuilder::default(); /// ``` - pub fn new() -> MessageBuilder { - MessageBuilder::default() - } + pub fn new() -> MessageBuilder { MessageBuilder::default() } /// Pulls the inner value out of the builder. /// @@ -92,9 +90,7 @@ impl MessageBuilder { /// /// assert_eq!(content, "test"); /// ``` - pub fn build(self) -> String { - self.0 - } + pub fn build(self) -> String { self.0 } /// Mentions the [`GuildChannel`] in the built message. /// @@ -478,10 +474,8 @@ impl MessageBuilder { } /// Pushes a code-block to your message normalizing content. - pub fn push_codeblock_safe(mut self, content: &str, language: Option<&str>) - -> Self { - let content = &normalize(content) - .replace("```", "'''"); + pub fn push_codeblock_safe(mut self, content: &str, language: Option<&str>) -> Self { + let content = &normalize(content).replace("```", "'''"); self.0.push_str("```"); @@ -550,7 +544,8 @@ impl MessageBuilder { /// ```rust /// use serenity::utils::MessageBuilder; /// - /// let content = MessageBuilder::new().push_line_safe("Hello @everyone").push("How are you?").build(); + /// let content = MessageBuilder::new().push_line_safe("Hello @everyone").push("How are + /// you?").build(); /// /// assert_eq!(content, "Hello @\u{200B}everyone\nHow are you?"); /// ``` @@ -649,7 +644,8 @@ impl MessageBuilder { self } - /// Pushes a strikethrough inline text with added newline to the content normalizing content. + /// Pushes a strikethrough inline text with added newline to the content normalizing + /// content. /// /// # Examples /// @@ -721,9 +717,7 @@ impl Display for MessageBuilder { /// use serenity::utils::MessageBuilder; /// /// - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.0, f) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } @@ -757,7 +751,7 @@ pub struct Content { pub strikethrough: bool, pub inner: String, pub code: bool, - pub underline: bool + pub underline: bool, } impl<T: ToString> Add<T> for Content { @@ -806,10 +800,10 @@ impl Add<ContentModifier> for ContentModifier { impl ContentModifier { fn to_content(&self) -> Content { - let mut nc = Content::default(); - nc.apply(self); + let mut nc = Content::default(); + nc.apply(self); - nc + nc } } @@ -835,12 +829,10 @@ impl Content { } pub fn to_string(&self) -> String { - let capacity = self.inner.len() - + if self.bold { 4 } else { 0 } - + if self.italic { 2 } else { 0 } - + if self.strikethrough { 4 } else { 0 } - + if self.underline { 4 } else { 0 } - + if self.code { 2 } else { 0 }; + let capacity = + self.inner.len() + if self.bold { 4 } else { 0 } + if self.italic { 2 } else { 0 } + + if self.strikethrough { 4 } else { 0 } + + if self.underline { 4 } else { 0 } + if self.code { 2 } else { 0 }; let mut new_str = String::with_capacity(capacity); if self.bold { @@ -890,9 +882,7 @@ impl Content { } impl From<ContentModifier> for Content { - fn from(cm: ContentModifier) -> Content { - cm.to_content() - } + fn from(cm: ContentModifier) -> Content { cm.to_content() } } impl<T: ToString> From<T> for Content { diff --git a/src/utils/mod.rs b/src/utils/mod.rs index d3d728a..9cd68a1 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -6,10 +6,10 @@ mod colour; mod message_builder; pub use self::colour::Colour; -pub use self::message_builder::{MessageBuilder, Content, ContentModifier}; +pub use self::message_builder::{Content, ContentModifier, MessageBuilder}; // Note: Here for BC purposes. -#[cfg(feature="builder")] +#[cfg(feature = "builder")] pub use super::builder; use base64; @@ -17,8 +17,8 @@ use std::ffi::OsStr; use std::fs::File; use std::io::Read; use std::path::Path; -use ::internal::prelude::*; -use ::model::{EmojiIdentifier, EmojiId}; +use internal::prelude::*; +use model::{EmojiId, EmojiIdentifier}; /// Determines if a name is NSFW. /// @@ -299,11 +299,13 @@ pub fn parse_emoji(mention: &str) -> Option<EmojiIdentifier> { } match id.parse::<u64>() { - Ok(x) => Some(EmojiIdentifier { - name: name, - id: EmojiId(x) - }), - _ => None + Ok(x) => { + Some(EmojiIdentifier { + name: name, + id: EmojiId(x), + }) + }, + _ => None, } } else { None @@ -431,6 +433,4 @@ pub fn parse_quotes(s: &str) -> Vec<String> { /// assert_eq!(utils::shard_id(81384788765712384, 17), 7); /// ``` #[inline] -pub fn shard_id(guild_id: u64, shard_count: u64) -> u64 { - (guild_id >> 22) % shard_count -} +pub fn shard_id(guild_id: u64, shard_count: u64) -> u64 { (guild_id >> 22) % shard_count } diff --git a/src/voice/audio.rs b/src/voice/audio.rs index ea8c87a..14b9ccd 100644 --- a/src/voice/audio.rs +++ b/src/voice/audio.rs @@ -12,5 +12,10 @@ pub trait AudioSource: Send { pub trait AudioReceiver: Send { fn speaking_update(&mut self, ssrc: u32, user_id: u64, speaking: bool); - fn voice_packet(&mut self, ssrc: u32, sequence: u16, timestamp: u32, stereo: bool, data: &[i16]); + fn voice_packet(&mut self, + ssrc: u32, + sequence: u16, + timestamp: u32, + stereo: bool, + data: &[i16]); } diff --git a/src/voice/connection.rs b/src/voice/connection.rs index ced6a79..6f8343c 100644 --- a/src/voice/connection.rs +++ b/src/voice/connection.rs @@ -1,10 +1,10 @@ use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt}; use opus::{ - Channels, + packet as opus_packet, Application as CodingMode, + Channels, Decoder as OpusDecoder, Encoder as OpusEncoder, - packet as opus_packet, }; use sodiumoxide::crypto::secretbox::{self, Key, Nonce}; use std::collections::HashMap; @@ -14,18 +14,18 @@ use std::sync::mpsc::{self, Receiver as MpscReceiver, Sender as MpscSender}; use std::sync::{Arc, Mutex}; use std::thread::{self, Builder as ThreadBuilder, JoinHandle}; use std::time::Duration; -use super::audio::{HEADER_LEN, SAMPLE_RATE, AudioReceiver, AudioSource}; +use super::audio::{AudioReceiver, AudioSource, HEADER_LEN, SAMPLE_RATE}; use super::connection_info::ConnectionInfo; -use super::{CRYPTO_MODE, VoiceError, payload}; +use super::{payload, VoiceError, CRYPTO_MODE}; use websocket::client::Url as WebsocketUrl; use websocket::sync::client::ClientBuilder; use websocket::sync::stream::{AsTcpStream, TcpStream, TlsStream}; use websocket::sync::Client as WsClient; -use ::internal::prelude::*; -use ::internal::ws_impl::{ReceiverExt, SenderExt}; -use ::internal::Timer; -use ::model::event::VoiceEvent; -use ::model::UserId; +use internal::prelude::*; +use internal::ws_impl::{ReceiverExt, SenderExt}; +use internal::Timer; +use model::event::VoiceEvent; +use model::UserId; type Client = WsClient<TlsStream<TcpStream>>; @@ -78,8 +78,7 @@ impl Connection { }, VoiceEvent::Heartbeat(_) => continue, other => { - debug!("[Voice] Expected hello/heartbeat; got: {:?}", - other); + debug!("[Voice] Expected hello/heartbeat; got: {:?}", other); return Err(Error::Voice(VoiceError::ExpectedHandshake)); }, @@ -116,7 +115,10 @@ impl Connection { // Find the position in the bytes that contains the first byte of 0, // indicating the "end of the address". - let index = bytes.iter().skip(4).position(|&x| x == 0) + let index = bytes + .iter() + .skip(4) + .position(|&x| x == 0) .ok_or(Error::Voice(VoiceError::FindingByte))?; let pos = 4 + index; @@ -124,12 +126,16 @@ impl Connection { let port_pos = len - 2; let port = (&bytes[port_pos..]).read_u16::<LittleEndian>()?; - client.send_json(&payload::build_select_protocol(addr, port))?; + client + .send_json(&payload::build_select_protocol(addr, port))?; } let key = encryption_key(&mut client)?; - let _ = client.stream_ref().as_tcp().set_read_timeout(Some(Duration::from_millis(25))); + let _ = client + .stream_ref() + .as_tcp() + .set_read_timeout(Some(Duration::from_millis(25))); let mutexed_client = Arc::new(Mutex::new(client)); let thread_items = start_threads(mutexed_client.clone(), &udp)?; @@ -139,23 +145,23 @@ impl Connection { let encoder = OpusEncoder::new(SAMPLE_RATE, Channels::Mono, CodingMode::Audio)?; Ok(Connection { - audio_timer: Timer::new(1000 * 60 * 4), - client: mutexed_client, - decoder_map: HashMap::new(), - destination: destination, - encoder: encoder, - encoder_stereo: false, - key: key, - keepalive_timer: Timer::new(hello.heartbeat_interval), - udp: udp, - sequence: 0, - silence_frames: 0, - speaking: false, - ssrc: hello.ssrc, - thread_items: thread_items, - timestamp: 0, - user_id: info.user_id, - }) + audio_timer: Timer::new(1000 * 60 * 4), + client: mutexed_client, + decoder_map: HashMap::new(), + destination: destination, + encoder: encoder, + encoder_stereo: false, + key: key, + keepalive_timer: Timer::new(hello.heartbeat_interval), + udp: udp, + sequence: 0, + silence_frames: 0, + speaking: false, + ssrc: hello.ssrc, + thread_items: thread_items, + timestamp: 0, + user_id: info.user_id, + }) } #[allow(unused_variables)] @@ -179,35 +185,29 @@ impl Connection { nonce.0[..HEADER_LEN].clone_from_slice(&packet[..HEADER_LEN]); - if let Ok(decrypted) = secretbox::open(&packet[HEADER_LEN..], &nonce, &self.key) { + if let Ok(decrypted) = + secretbox::open(&packet[HEADER_LEN..], &nonce, &self.key) { let channels = opus_packet::get_nb_channels(&decrypted)?; - let entry = self.decoder_map.entry((ssrc, channels)) - .or_insert_with(|| OpusDecoder::new(SAMPLE_RATE, - channels) - .unwrap()); + let entry = + self.decoder_map.entry((ssrc, channels)).or_insert_with( + || OpusDecoder::new(SAMPLE_RATE, channels).unwrap(), + ); let len = entry.decode(&decrypted, &mut buffer, false)?; let is_stereo = channels == Channels::Stereo; - let b = if is_stereo { - len * 2 - } else { - len - }; + let b = if is_stereo { len * 2 } else { len }; receiver.voice_packet(ssrc, seq, timestamp, is_stereo, &buffer[..b]); } }, ReceiverStatus::Websocket(VoiceEvent::Speaking(ev)) => { - receiver.speaking_update(ev.ssrc, - ev.user_id.0, - ev.speaking); + receiver.speaking_update(ev.ssrc, ev.user_id.0, ev.speaking); }, ReceiverStatus::Websocket(other) => { - info!("[Voice] Received other websocket data: {:?}", - other); + info!("[Voice] Received other websocket data: {:?}", other); }, } } @@ -221,7 +221,10 @@ impl Connection { // Send the voice websocket keepalive if it's time if self.keepalive_timer.check() { - self.client.lock().unwrap().send_json(&payload::build_keepalive())?; + self.client + .lock() + .unwrap() + .send_json(&payload::build_keepalive())?; } // Send UDP keepalive if it's time @@ -282,14 +285,10 @@ impl Connection { nonce.0[..HEADER_LEN].clone_from_slice(&packet[..HEADER_LEN]); let sl_index = packet.len() - 16; - let buffer_len = if self.encoder_stereo { - 960 * 2 - } else { - 960 - }; + let buffer_len = if self.encoder_stereo { 960 * 2 } else { 960 }; - let len = self.encoder.encode(&buffer[..buffer_len], - &mut packet[HEADER_LEN..sl_index])?; + let len = self.encoder + .encode(&buffer[..buffer_len], &mut packet[HEADER_LEN..sl_index])?; let crypted = { let slice = &packet[HEADER_LEN..HEADER_LEN + len]; secretbox::seal(slice, &nonce, &self.key) @@ -319,17 +318,11 @@ impl Connection { } else { Channels::Mono }; - self.encoder = OpusEncoder::new(SAMPLE_RATE, - channels, - CodingMode::Audio)?; + self.encoder = OpusEncoder::new(SAMPLE_RATE, channels, CodingMode::Audio)?; self.encoder_stereo = is_stereo; } - let buffer_len = if is_stereo { - 960 * 2 - } else { - 960 - }; + let buffer_len = if is_stereo { 960 * 2 } else { 960 }; match source.read_frame(&mut buffer[..buffer_len]) { Some(len) => len, @@ -357,7 +350,10 @@ impl Connection { self.speaking = speaking; - self.client.lock().unwrap().send_json(&payload::build_speaking(speaking)) + self.client + .lock() + .unwrap() + .send_json(&payload::build_speaking(speaking)) } } @@ -382,8 +378,7 @@ fn generate_url(endpoint: &mut String) -> Result<WebsocketUrl> { } #[inline] -fn encryption_key(client: &mut Client) - -> Result<Key> { +fn encryption_key(client: &mut Client) -> Result<Key> { loop { match client.recv_json(VoiceEvent::decode)? { VoiceEvent::Ready(ready) => { @@ -391,8 +386,7 @@ fn encryption_key(client: &mut Client) return Err(Error::Voice(VoiceError::VoiceModeInvalid)); } - return Key::from_slice(&ready.secret_key) - .ok_or(Error::Voice(VoiceError::KeyGen)); + return Key::from_slice(&ready.secret_key).ok_or(Error::Voice(VoiceError::KeyGen)); }, VoiceEvent::Unknown(op, value) => { debug!("[Voice] Expected ready for key; got: op{}/v{:?}", @@ -405,13 +399,10 @@ fn encryption_key(client: &mut Client) } #[inline] -fn has_valid_mode(modes: &[String]) -> bool { - modes.iter().any(|s| s == CRYPTO_MODE) -} +fn has_valid_mode(modes: &[String]) -> bool { modes.iter().any(|s| s == CRYPTO_MODE) } #[inline] -fn start_threads(client: Arc<Mutex<Client>>, udp: &UdpSocket) - -> Result<ThreadItems> { +fn start_threads(client: Arc<Mutex<Client>>, udp: &UdpSocket) -> Result<ThreadItems> { let (udp_close_sender, udp_close_reader) = mpsc::channel(); let (ws_close_sender, ws_close_reader) = mpsc::channel(); @@ -445,27 +436,25 @@ fn start_threads(client: Arc<Mutex<Client>>, udp: &UdpSocket) let ws_thread = ThreadBuilder::new() .name(format!("{} WS", thread_name)) - .spawn(move || { - loop { - while let Ok(msg) = client.lock().unwrap().recv_json(VoiceEvent::decode) { - if tx_clone.send(ReceiverStatus::Websocket(msg)).is_ok() { - return; - } - } + .spawn(move || loop { + while let Ok(msg) = client.lock().unwrap().recv_json(VoiceEvent::decode) { + if tx_clone.send(ReceiverStatus::Websocket(msg)).is_ok() { + return; + } + } - if ws_close_reader.try_recv().is_ok() { - return; - } + if ws_close_reader.try_recv().is_ok() { + return; + } - thread::sleep(Duration::from_millis(25)); - } - })?; + thread::sleep(Duration::from_millis(25)); + })?; Ok(ThreadItems { - rx: rx, - udp_close_sender: udp_close_sender, - udp_thread: udp_thread, - ws_close_sender: ws_close_sender, - ws_thread: ws_thread, - }) + rx: rx, + udp_close_sender: udp_close_sender, + udp_thread: udp_thread, + ws_close_sender: ws_close_sender, + ws_thread: ws_thread, + }) } diff --git a/src/voice/connection_info.rs b/src/voice/connection_info.rs index d0364ce..91bee80 100644 --- a/src/voice/connection_info.rs +++ b/src/voice/connection_info.rs @@ -1,4 +1,4 @@ -use ::model::{GuildId, UserId}; +use model::{GuildId, UserId}; #[derive(Clone, Debug)] pub struct ConnectionInfo { diff --git a/src/voice/handler.rs b/src/voice/handler.rs index fb157e6..fb1bf28 100644 --- a/src/voice/handler.rs +++ b/src/voice/handler.rs @@ -3,8 +3,8 @@ use std::sync::mpsc::{self, Sender as MpscSender}; use super::{AudioReceiver, AudioSource}; use super::connection_info::ConnectionInfo; use super::Status as VoiceStatus; -use ::constants::VoiceOpCode; -use ::model::{ChannelId, GuildId, UserId, VoiceState}; +use constants::VoiceOpCode; +use model::{ChannelId, GuildId, UserId, VoiceState}; use super::threading; /// The handler is responsible for "handling" a single voice connection, acting @@ -153,12 +153,12 @@ impl Handler { // Safe as all of these being present was already checked. self.send(VoiceStatus::Connect(ConnectionInfo { - endpoint: endpoint, - guild_id: guild_id, - session_id: session_id, - token: token, - user_id: user_id, - })); + endpoint: endpoint, + guild_id: guild_id, + session_id: session_id, + token: token, + user_id: user_id, + })); true } @@ -256,9 +256,7 @@ impl Handler { } /// Stops playing audio from a source, if one is set. - pub fn stop(&mut self) { - self.send(VoiceStatus::SetSender(None)) - } + pub fn stop(&mut self) { self.send(VoiceStatus::SetSender(None)) } /// Switches the current connected voice channel to the given `channel_id`. /// @@ -418,7 +416,5 @@ impl Handler { impl Drop for Handler { /// Leaves the current connected voice channel, if connected to one, and /// forgets all configurations relevant to this Handler. - fn drop(&mut self) { - self.leave(); - } + fn drop(&mut self) { self.leave(); } } diff --git a/src/voice/manager.rs b/src/voice/manager.rs index 528efe7..785aef8 100644 --- a/src/voice/manager.rs +++ b/src/voice/manager.rs @@ -2,7 +2,7 @@ use serde_json::Value; use std::collections::HashMap; use std::sync::mpsc::Sender as MpscSender; use super::Handler; -use ::model::{ChannelId, GuildId, UserId}; +use model::{ChannelId, GuildId, UserId}; /// A manager is a struct responsible for managing [`Handler`]s which belong to /// a single [`Shard`]. This is a fairly complex key-value store, @@ -64,7 +64,9 @@ impl Manager { /// [`get`]: #method.get #[allow(map_entry)] pub fn join<C, G>(&mut self, guild_id: G, channel_id: C) -> &mut Handler - where C: Into<ChannelId>, G: Into<GuildId> { + where + C: Into<ChannelId>, + G: Into<GuildId>, { let channel_id = channel_id.into(); let guild_id = guild_id.into(); diff --git a/src/voice/payload.rs b/src/voice/payload.rs index c2e7c0c..0096ebe 100644 --- a/src/voice/payload.rs +++ b/src/voice/payload.rs @@ -1,6 +1,6 @@ use serde_json::Value; use super::connection_info::ConnectionInfo; -use ::constants::VoiceOpCode; +use constants::VoiceOpCode; #[inline] pub fn build_identify(info: &ConnectionInfo) -> Value { diff --git a/src/voice/streamer.rs b/src/voice/streamer.rs index 4d3b9a9..c755da2 100644 --- a/src/voice/streamer.rs +++ b/src/voice/streamer.rs @@ -4,7 +4,7 @@ use std::ffi::OsStr; use std::io::{ErrorKind as IoErrorKind, Read, Result as IoResult}; use std::process::{Child, Command, Stdio}; use super::{AudioSource, VoiceError}; -use ::internal::prelude::*; +use internal::prelude::*; struct ChildContainer(Child); @@ -17,18 +17,18 @@ impl Read for ChildContainer { struct PcmSource<R: Read + Send + 'static>(bool, R); impl<R: Read + Send> AudioSource for PcmSource<R> { - fn is_stereo(&mut self) -> bool { - self.0 - } + fn is_stereo(&mut self) -> bool { self.0 } fn read_frame(&mut self, buffer: &mut [i16]) -> Option<usize> { for (i, v) in buffer.iter_mut().enumerate() { *v = match self.1.read_i16::<LittleEndian>() { Ok(v) => v, - Err(ref e) => return if e.kind() == IoErrorKind::UnexpectedEof { - Some(i) - } else { - None + Err(ref e) => { + return if e.kind() == IoErrorKind::UnexpectedEof { + Some(i) + } else { + None + } }, } } @@ -43,11 +43,7 @@ pub fn ffmpeg<P: AsRef<OsStr>>(path: P) -> Result<Box<AudioSource>> { /// Will fail if the path is not to a file on the fs. Likely a YouTube URI. let is_stereo = is_stereo(path).unwrap_or(false); - let stereo_val = if is_stereo { - "2" - } else { - "1" - }; + let stereo_val = if is_stereo { "2" } else { "1" }; let args = [ "-f", @@ -74,8 +70,7 @@ pub fn ffmpeg<P: AsRef<OsStr>>(path: P) -> Result<Box<AudioSource>> { } /// Creates a PCM audio source. -pub fn pcm<R: Read + Send + 'static>(is_stereo: bool, reader: R) - -> Box<AudioSource> { +pub fn pcm<R: Read + Send + 'static>(is_stereo: bool, reader: R) -> Box<AudioSource> { Box::new(PcmSource(is_stereo, reader)) } @@ -106,9 +101,11 @@ pub fn ytdl(uri: &str) -> Result<Box<AudioSource>> { }; let uri = match obj.remove("url") { - Some(v) => match v { - Value::String(uri) => uri, - other => return Err(Error::Voice(VoiceError::YouTubeDLUrl(other))), + Some(v) => { + match v { + Value::String(uri) => uri, + other => return Err(Error::Voice(VoiceError::YouTubeDLUrl(other))), + } }, None => return Err(Error::Voice(VoiceError::YouTubeDLUrl(Value::Object(obj)))), }; @@ -117,14 +114,7 @@ pub fn ytdl(uri: &str) -> Result<Box<AudioSource>> { } fn is_stereo(path: &OsStr) -> Result<bool> { - let args = [ - "-v", - "quiet", - "-of", - "json", - "-show-streams", - "-i", - ]; + let args = ["-v", "quiet", "-of", "json", "-show-streams", "-i"]; let out = Command::new("ffprobe") .args(&args) @@ -134,19 +124,19 @@ fn is_stereo(path: &OsStr) -> Result<bool> { let value: Value = serde_json::from_reader(&out.stdout[..])?; - let streams = value.as_object() + let streams = value + .as_object() .and_then(|m| m.get("streams")) .and_then(|v| v.as_array()) .ok_or(Error::Voice(VoiceError::Streams))?; - let check = streams.iter() - .any(|stream| { - let channels = stream.as_object() - .and_then(|m| m.get("channels") - .and_then(|v| v.as_i64())); + let check = streams.iter().any(|stream| { + let channels = stream + .as_object() + .and_then(|m| m.get("channels").and_then(|v| v.as_i64())); - channels == Some(2) - }); + channels == Some(2) + }); Ok(check) } diff --git a/src/voice/threading.rs b/src/voice/threading.rs index fe0aebc..f272282 100644 --- a/src/voice/threading.rs +++ b/src/voice/threading.rs @@ -2,8 +2,8 @@ use std::sync::mpsc::{Receiver as MpscReceiver, TryRecvError}; use std::thread::Builder as ThreadBuilder; use super::connection::Connection; use super::Status; -use ::internal::Timer; -use ::model::GuildId; +use internal::Timer; +use model::GuildId; pub(crate) fn start(guild_id: GuildId, rx: MpscReceiver<Status>) { let name = format!("Serenity Voice (G{})", guild_id); @@ -25,9 +25,7 @@ fn runner(rx: &MpscReceiver<Status>) { match rx.try_recv() { Ok(Status::Connect(info)) => { connection = match Connection::new(info) { - Ok(connection) => { - Some(connection) - }, + Ok(connection) => Some(connection), Err(why) => { warn!("[Voice] Error connecting: {:?}", why); @@ -64,9 +62,7 @@ fn runner(rx: &MpscReceiver<Status>) { // another event. let error = match connection.as_mut() { Some(connection) => { - let cycle = connection.cycle(&mut sender, - &mut receiver, - &mut timer); + let cycle = connection.cycle(&mut sender, &mut receiver, &mut timer); match cycle { Ok(()) => false, |