From f641dbb14facbcfd2ad3ac5e5b3d3bcd28423314 Mon Sep 17 00:00:00 2001 From: Flori Weber Date: Sun, 11 Jun 2023 13:52:31 +0200 Subject: [PATCH] Reformat entire project, optimize imports --- src/api/auth/login.rs | 130 ++++++++-------- src/api/auth/mod.rs | 5 +- src/api/auth/register.rs | 144 +++++++++--------- src/api/channels/messages.rs | 2 +- src/api/channels/mod.rs | 9 +- src/api/channels/reactions.rs | 10 +- src/api/guilds/guilds.rs | 14 +- src/api/guilds/member.rs | 2 +- src/api/guilds/mod.rs | 8 +- src/api/guilds/roles.rs | 16 +- src/api/mod.rs | 9 +- src/api/policies/instance/instance.rs | 2 +- src/api/policies/instance/limits.rs | 6 - src/api/policies/instance/mod.rs | 5 +- src/api/policies/mod.rs | 3 +- src/api/users/mod.rs | 3 +- src/api/users/users.rs | 4 +- src/gateway.rs | 37 ++--- src/instance.rs | 10 +- src/lib.rs | 4 +- src/limit.rs | 46 +++--- src/types/config/mod.rs | 2 +- src/types/config/types/guild_configuration.rs | 19 +-- .../config/types/subconfigs/limits/rates.rs | 2 +- .../config/types/subconfigs/register/email.rs | 1 + .../config/types/subconfigs/register/mod.rs | 7 +- .../config/types/subconfigs/security/mod.rs | 5 +- src/types/entities/application.rs | 5 +- src/types/entities/attachment.rs | 1 - src/types/entities/guild.rs | 2 +- src/types/entities/message.rs | 1 - src/types/entities/mod.rs | 45 +++--- src/types/entities/template.rs | 3 +- src/types/events/call.rs | 10 +- src/types/events/channel.rs | 5 +- src/types/events/guild.rs | 8 +- src/types/events/heartbeat.rs | 3 +- src/types/events/hello.rs | 3 +- src/types/events/identify.rs | 6 +- src/types/events/lazy_request.rs | 1 + src/types/events/message.rs | 1 + src/types/events/mod.rs | 53 ++++--- src/types/events/passive_update.rs | 3 +- src/types/events/presence.rs | 3 +- src/types/events/ready.rs | 5 +- src/types/events/relationship.rs | 3 +- src/types/events/request_members.rs | 3 +- src/types/events/resume.rs | 3 +- src/types/events/thread.rs | 3 +- src/types/events/user.rs | 3 +- src/types/events/voice.rs | 3 +- src/types/interfaces/activity.rs | 3 +- src/types/interfaces/guild_welcome_screen.rs | 3 +- src/types/interfaces/interaction.rs | 5 +- src/types/interfaces/mod.rs | 11 +- src/types/schema/apierror.rs | 4 +- src/types/schema/auth.rs | 4 +- src/types/schema/guild.rs | 3 +- src/types/schema/message.rs | 3 +- src/types/schema/mod.rs | 19 +-- src/types/schema/role.rs | 3 +- src/types/utils/mod.rs | 7 +- tests/auth.rs | 5 +- tests/channel.rs | 13 +- tests/common/mod.rs | 2 +- tests/guild.rs | 3 +- tests/message.rs | 7 +- tests/roles.rs | 4 +- 68 files changed, 411 insertions(+), 369 deletions(-) diff --git a/src/api/auth/login.rs b/src/api/auth/login.rs index 55d7799..aeafec2 100644 --- a/src/api/auth/login.rs +++ b/src/api/auth/login.rs @@ -1,72 +1,70 @@ -pub mod login { - use std::cell::RefCell; - use std::rc::Rc; +use std::cell::RefCell; +use std::rc::Rc; - use reqwest::Client; - use serde_json::{from_str, json}; +use reqwest::Client; +use serde_json::{from_str, json}; - use crate::api::limits::LimitType; - use crate::errors::ChorusLibError; - use crate::instance::{Instance, UserMeta}; - use crate::limit::LimitedRequester; - use crate::types::{ErrorResponse, LoginResult, LoginSchema}; +use crate::api::limits::LimitType; +use crate::errors::ChorusLibError; +use crate::instance::{Instance, UserMeta}; +use crate::limit::LimitedRequester; +use crate::types::{ErrorResponse, LoginResult, LoginSchema}; - impl Instance { - pub async fn login_account( - &mut self, - login_schema: &LoginSchema, - ) -> Result { - let mut requester = LimitedRequester::new().await; - let json_schema = json!(login_schema); - let client = Client::new(); - let endpoint_url = self.urls.get_api().to_string() + "/auth/login"; - let request_builder = client.post(endpoint_url).body(json_schema.to_string()); - // We do not have a user yet, and the UserRateLimits will not be affected by a login - // request (since login is an instance wide limit), which is why we are just cloning the - // instances' limits to pass them on as user_rate_limits later. - let mut cloned_limits = self.limits.clone(); - let response = requester - .send_request( - request_builder, - LimitType::AuthRegister, - &mut self.limits, - &mut cloned_limits, - ) - .await; - if response.is_err() { - return Err(ChorusLibError::NoResponse); - } - - let response_unwrap = response.unwrap(); - let status = response_unwrap.status(); - let response_text_string = response_unwrap.text().await.unwrap(); - if status.is_client_error() { - let json: ErrorResponse = serde_json::from_str(&response_text_string).unwrap(); - let error_type = json.errors.errors.iter().next().unwrap().0.to_owned(); - let mut error = "".to_string(); - for (_, value) in json.errors.errors.iter() { - for error_item in value._errors.iter() { - error += &(error_item.message.to_string() + " (" + &error_item.code + ")"); - } - } - return Err(ChorusLibError::InvalidFormBodyError { error_type, error }); - } - - let cloned_limits = self.limits.clone(); - let login_result: LoginResult = from_str(&response_text_string).unwrap(); - let object = self - .get_user(login_result.token.clone(), None) - .await - .unwrap(); - let user = UserMeta::new( - Rc::new(RefCell::new(self.clone())), - login_result.token, - cloned_limits, - login_result.settings, - object, - ); - - Ok(user) +impl Instance { + pub async fn login_account( + &mut self, + login_schema: &LoginSchema, + ) -> Result { + let mut requester = LimitedRequester::new().await; + let json_schema = json!(login_schema); + let client = Client::new(); + let endpoint_url = self.urls.get_api().to_string() + "/auth/login"; + let request_builder = client.post(endpoint_url).body(json_schema.to_string()); + // We do not have a user yet, and the UserRateLimits will not be affected by a login + // request (since login is an instance wide limit), which is why we are just cloning the + // instances' limits to pass them on as user_rate_limits later. + let mut cloned_limits = self.limits.clone(); + let response = requester + .send_request( + request_builder, + LimitType::AuthRegister, + &mut self.limits, + &mut cloned_limits, + ) + .await; + if response.is_err() { + return Err(ChorusLibError::NoResponse); } + + let response_unwrap = response.unwrap(); + let status = response_unwrap.status(); + let response_text_string = response_unwrap.text().await.unwrap(); + if status.is_client_error() { + let json: ErrorResponse = serde_json::from_str(&response_text_string).unwrap(); + let error_type = json.errors.errors.iter().next().unwrap().0.to_owned(); + let mut error = "".to_string(); + for (_, value) in json.errors.errors.iter() { + for error_item in value._errors.iter() { + error += &(error_item.message.to_string() + " (" + &error_item.code + ")"); + } + } + return Err(ChorusLibError::InvalidFormBodyError { error_type, error }); + } + + let cloned_limits = self.limits.clone(); + let login_result: LoginResult = from_str(&response_text_string).unwrap(); + let object = self + .get_user(login_result.token.clone(), None) + .await + .unwrap(); + let user = UserMeta::new( + Rc::new(RefCell::new(self.clone())), + login_result.token, + cloned_limits, + login_result.settings, + object, + ); + + Ok(user) } } diff --git a/src/api/auth/mod.rs b/src/api/auth/mod.rs index 3093e74..933382c 100644 --- a/src/api/auth/mod.rs +++ b/src/api/auth/mod.rs @@ -1,5 +1,6 @@ +pub use login::*; +pub use register::*; + pub mod login; pub mod register; -pub use login::*; -pub use register::*; diff --git a/src/api/auth/register.rs b/src/api/auth/register.rs index d961fbf..d8c4847 100644 --- a/src/api/auth/register.rs +++ b/src/api/auth/register.rs @@ -1,79 +1,77 @@ -pub mod register { - use std::{cell::RefCell, rc::Rc}; +use std::{cell::RefCell, rc::Rc}; - use reqwest::Client; - use serde_json::{from_str, json}; +use reqwest::Client; +use serde_json::{from_str, json}; - use crate::{ - api::limits::LimitType, - errors::ChorusLibError, - instance::{Instance, Token, UserMeta}, - limit::LimitedRequester, - types::{ErrorResponse, RegisterSchema}, - }; +use crate::{ + api::limits::LimitType, + errors::ChorusLibError, + instance::{Instance, Token, UserMeta}, + limit::LimitedRequester, + types::{ErrorResponse, RegisterSchema}, +}; - impl Instance { - /** - Registers a new user on the Spacebar server. - # Arguments - * `register_schema` - The [`RegisterSchema`] that contains all the information that is needed to register a new user. - # Errors - * [`ChorusLibError`] - If the server does not respond. - */ - pub async fn register_account( - &mut self, - register_schema: &RegisterSchema, - ) -> Result { - let json_schema = json!(register_schema); - let mut limited_requester = LimitedRequester::new().await; - let client = Client::new(); - let endpoint_url = self.urls.get_api().to_string() + "/auth/register"; - let request_builder = client.post(endpoint_url).body(json_schema.to_string()); - // We do not have a user yet, and the UserRateLimits will not be affected by a login - // request (since register is an instance wide limit), which is why we are just cloning - // the instances' limits to pass them on as user_rate_limits later. - let mut cloned_limits = self.limits.clone(); - let response = limited_requester - .send_request( - request_builder, - LimitType::AuthRegister, - &mut self.limits, - &mut cloned_limits, - ) - .await; - if response.is_err() { - return Err(ChorusLibError::NoResponse); - } - - let response_unwrap = response.unwrap(); - let status = response_unwrap.status(); - let response_unwrap_text = response_unwrap.text().await.unwrap(); - let token = from_str::(&response_unwrap_text).unwrap(); - let token = token.token; - if status.is_client_error() { - let json: ErrorResponse = serde_json::from_str(&token).unwrap(); - let error_type = json.errors.errors.iter().next().unwrap().0.to_owned(); - let mut error = "".to_string(); - for (_, value) in json.errors.errors.iter() { - for error_item in value._errors.iter() { - error += &(error_item.message.to_string() + " (" + &error_item.code + ")"); - } - } - return Err(ChorusLibError::InvalidFormBodyError { error_type, error }); - } - let user_object = self.get_user(token.clone(), None).await.unwrap(); - let settings = - UserMeta::get_settings(&token, &self.urls.get_api().to_string(), &mut self.limits) - .await - .unwrap(); - let user: UserMeta = UserMeta::new( - Rc::new(RefCell::new(self.clone())), - token.clone(), - cloned_limits, - settings, - user_object, - ); - Ok(user) +impl Instance { + /** + Registers a new user on the Spacebar server. + # Arguments + * `register_schema` - The [`RegisterSchema`] that contains all the information that is needed to register a new user. + # Errors + * [`ChorusLibError`] - If the server does not respond. + */ + pub async fn register_account( + &mut self, + register_schema: &RegisterSchema, + ) -> Result { + let json_schema = json!(register_schema); + let mut limited_requester = LimitedRequester::new().await; + let client = Client::new(); + let endpoint_url = self.urls.get_api().to_string() + "/auth/register"; + let request_builder = client.post(endpoint_url).body(json_schema.to_string()); + // We do not have a user yet, and the UserRateLimits will not be affected by a login + // request (since register is an instance wide limit), which is why we are just cloning + // the instances' limits to pass them on as user_rate_limits later. + let mut cloned_limits = self.limits.clone(); + let response = limited_requester + .send_request( + request_builder, + LimitType::AuthRegister, + &mut self.limits, + &mut cloned_limits, + ) + .await; + if response.is_err() { + return Err(ChorusLibError::NoResponse); } + + let response_unwrap = response.unwrap(); + let status = response_unwrap.status(); + let response_unwrap_text = response_unwrap.text().await.unwrap(); + let token = from_str::(&response_unwrap_text).unwrap(); + let token = token.token; + if status.is_client_error() { + let json: ErrorResponse = serde_json::from_str(&token).unwrap(); + let error_type = json.errors.errors.iter().next().unwrap().0.to_owned(); + let mut error = "".to_string(); + for (_, value) in json.errors.errors.iter() { + for error_item in value._errors.iter() { + error += &(error_item.message.to_string() + " (" + &error_item.code + ")"); + } + } + return Err(ChorusLibError::InvalidFormBodyError { error_type, error }); + } + let user_object = self.get_user(token.clone(), None).await.unwrap(); + let settings = + UserMeta::get_settings(&token, &self.urls.get_api().to_string(), &mut self.limits) + .await + .unwrap(); + let user: UserMeta = UserMeta::new( + Rc::new(RefCell::new(self.clone())), + token.clone(), + cloned_limits, + settings, + user_object, + ); + Ok(user) } } diff --git a/src/api/channels/messages.rs b/src/api/channels/messages.rs index d511e24..f40feb8 100644 --- a/src/api/channels/messages.rs +++ b/src/api/channels/messages.rs @@ -1,6 +1,6 @@ use http::header::CONTENT_DISPOSITION; use http::HeaderMap; -use reqwest::{multipart, Client}; +use reqwest::{Client, multipart}; use serde_json::to_string; use crate::instance::UserMeta; diff --git a/src/api/channels/mod.rs b/src/api/channels/mod.rs index 94b42b6..f6e56ce 100644 --- a/src/api/channels/mod.rs +++ b/src/api/channels/mod.rs @@ -1,9 +1,10 @@ +pub use channels::*; +pub use messages::*; +pub use permissions::*; +pub use reactions::*; + pub mod channels; pub mod messages; pub mod permissions; pub mod reactions; -pub use channels::*; -pub use messages::*; -pub use permissions::*; -pub use reactions::*; diff --git a/src/api/channels/reactions.rs b/src/api/channels/reactions.rs index 9bd7adc..e46adba 100644 --- a/src/api/channels/reactions.rs +++ b/src/api/channels/reactions.rs @@ -28,7 +28,7 @@ impl ReactionMeta { # Reference See [https://discord.com/developers/docs/resources/channel#delete-all-reactions](https://discord.com/developers/docs/resources/channel#delete-all-reactions) - */ + */ pub async fn delete_all( &self, user: &mut UserMeta, @@ -66,7 +66,7 @@ impl ReactionMeta { # Reference See [https://discord.com/developers/docs/resources/channel#get-reactions](https://discord.com/developers/docs/resources/channel#get-reactions) - */ + */ pub async fn get( &self, emoji: &str, @@ -108,7 +108,7 @@ impl ReactionMeta { # Reference See [https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji](https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji) - */ + */ pub async fn delete_emoji( &self, emoji: &str, @@ -154,7 +154,7 @@ impl ReactionMeta { # Reference See [https://discord.com/developers/docs/resources/channel#create-reaction](https://discord.com/developers/docs/resources/channel#create-reaction) - */ + */ pub async fn create( &self, emoji: &str, @@ -241,7 +241,7 @@ impl ReactionMeta { # Reference See [https://discord.com/developers/docs/resources/channel#delete-own-reaction](https://discord.com/developers/docs/resources/channel#delete-own-reaction) - */ + */ pub async fn delete_user( &self, user_id: &str, diff --git a/src/api/guilds/guilds.rs b/src/api/guilds/guilds.rs index 56912e7..850696f 100644 --- a/src/api/guilds/guilds.rs +++ b/src/api/guilds/guilds.rs @@ -56,8 +56,8 @@ impl Guild { &mut user.limits, &mut belongs_to.limits, ) - .await - .unwrap(); + .await + .unwrap(); Ok(guild) } @@ -134,7 +134,7 @@ impl Guild { &mut user.limits, &mut belongs_to.limits, ) - .await + .await } /// Returns a `Result` containing a vector of `Channel` structs if the request was successful, or an `ChorusLibError` if there was an error. @@ -173,7 +173,7 @@ impl Guild { Err(e) => { return Err(ChorusLibError::InvalidResponseError { error: e.to_string(), - }) + }); } }; let _: Vec = match from_str(&stringed_response) { @@ -181,7 +181,7 @@ impl Guild { Err(e) => { return Err(ChorusLibError::InvalidResponseError { error: e.to_string(), - }) + }); } }; } @@ -205,7 +205,7 @@ impl Guild { &mut user.limits, &mut belongs_to.limits, ) - .await + .await } /// For internal use. Does the same as the public get method, but does not require a second, mutable @@ -267,7 +267,7 @@ impl Channel { &mut user.limits, &mut belongs_to.limits, ) - .await + .await } async fn _create( diff --git a/src/api/guilds/member.rs b/src/api/guilds/member.rs index a6ec7d7..7b0f5d5 100644 --- a/src/api/guilds/member.rs +++ b/src/api/guilds/member.rs @@ -43,7 +43,7 @@ impl types::GuildMember { Err(e) => { return Err(ChorusLibError::InvalidResponseError { error: e.to_string(), - }) + }); } }; let member = from_str::(&response_text); diff --git a/src/api/guilds/mod.rs b/src/api/guilds/mod.rs index 1138a50..7577479 100644 --- a/src/api/guilds/mod.rs +++ b/src/api/guilds/mod.rs @@ -1,7 +1,7 @@ -pub mod guilds; -pub mod member; -pub mod roles; - pub use guilds::*; pub use roles::*; pub use roles::*; + +pub mod guilds; +pub mod member; +pub mod roles; diff --git a/src/api/guilds/roles.rs b/src/api/guilds/roles.rs index b2e9b31..f8b3be4 100644 --- a/src/api/guilds/roles.rs +++ b/src/api/guilds/roles.rs @@ -48,7 +48,7 @@ impl types::RoleObject { Err(e) => { return Err(ChorusLibError::InvalidResponseError { error: e.to_string(), - }) + }); } }; @@ -105,7 +105,7 @@ impl types::RoleObject { Err(e) => { return Err(ChorusLibError::InvalidResponseError { error: e.to_string(), - }) + }); } }; @@ -139,7 +139,7 @@ impl types::RoleObject { Err(e) => { return Err(ChorusLibError::FormCreationError { error: e.to_string(), - }) + }); } }; let request = Client::new().post(url).bearer_auth(user.token()).body(body); @@ -161,7 +161,7 @@ impl types::RoleObject { Err(e) => { return Err(ChorusLibError::InvalidResponseError { error: e.to_string(), - }) + }); } }; Ok(role) @@ -194,7 +194,7 @@ impl types::RoleObject { Err(e) => { return Err(ChorusLibError::FormCreationError { error: e.to_string(), - }) + }); } }; let request = Client::new() @@ -216,7 +216,7 @@ impl types::RoleObject { Err(e) => { return Err(ChorusLibError::InvalidResponseError { error: e.to_string(), - }) + }); } }; Ok(role) @@ -256,7 +256,7 @@ impl types::RoleObject { Err(e) => { return Err(ChorusLibError::FormCreationError { error: e.to_string(), - }) + }); } }; let request = Client::new() @@ -281,7 +281,7 @@ impl types::RoleObject { Err(e) => { return Err(ChorusLibError::InvalidResponseError { error: e.to_string(), - }) + }); } }; Ok(role) diff --git a/src/api/mod.rs b/src/api/mod.rs index 0bac755..375aff1 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -1,10 +1,11 @@ +pub use channels::messages::*; +pub use guilds::*; +pub use policies::instance::instance::*; +pub use policies::instance::limits::*; + pub mod auth; pub mod channels; pub mod guilds; pub mod policies; pub mod users; -pub use channels::messages::*; -pub use guilds::*; -pub use policies::instance::instance::*; -pub use policies::instance::limits::*; diff --git a/src/api/policies/instance/instance.rs b/src/api/policies/instance/instance.rs index 055568f..c775195 100644 --- a/src/api/policies/instance/instance.rs +++ b/src/api/policies/instance/instance.rs @@ -10,7 +10,7 @@ impl Instance { Gets the instance policies schema. # Errors [`ChorusLibError`] - If the request fails. - */ + */ pub async fn general_configuration_schema( &self, ) -> Result { diff --git a/src/api/policies/instance/limits.rs b/src/api/policies/instance/limits.rs index 1c96883..98e0fc8 100644 --- a/src/api/policies/instance/limits.rs +++ b/src/api/policies/instance/limits.rs @@ -47,7 +47,6 @@ pub mod limits { #[derive(Debug, Deserialize, Serialize)] #[allow(non_snake_case)] - pub struct Guild { pub maxRoles: u64, pub maxEmojis: u64, @@ -58,7 +57,6 @@ pub mod limits { #[derive(Debug, Deserialize, Serialize)] #[allow(non_snake_case)] - pub struct Message { pub maxCharacters: u64, pub maxTTSCharacters: u64, @@ -70,7 +68,6 @@ pub mod limits { #[derive(Debug, Deserialize, Serialize)] #[allow(non_snake_case)] - pub struct Channel { pub maxPins: u64, pub maxTopic: u64, @@ -102,7 +99,6 @@ pub mod limits { #[derive(Debug, Deserialize, Serialize)] #[allow(non_snake_case)] - pub struct AuthRoutes { pub login: Window, pub register: Window, @@ -110,7 +106,6 @@ pub mod limits { #[derive(Debug, Deserialize, Serialize)] #[allow(non_snake_case)] - pub struct AbsoluteRate { pub register: AbsoluteWindow, pub sendMessage: AbsoluteWindow, @@ -125,7 +120,6 @@ pub mod limits { #[derive(Debug, Deserialize, Serialize)] #[allow(non_snake_case)] - pub struct Config { pub user: User, pub guild: Guild, diff --git a/src/api/policies/instance/mod.rs b/src/api/policies/instance/mod.rs index b05078e..79c7ffe 100644 --- a/src/api/policies/instance/mod.rs +++ b/src/api/policies/instance/mod.rs @@ -1,5 +1,6 @@ +pub use instance::*; +pub use limits::*; + pub mod instance; pub mod limits; -pub use instance::*; -pub use limits::*; diff --git a/src/api/policies/mod.rs b/src/api/policies/mod.rs index 6b4a5bc..7f7a7e4 100644 --- a/src/api/policies/mod.rs +++ b/src/api/policies/mod.rs @@ -1,3 +1,4 @@ +pub use instance::limits::*; + pub mod instance; -pub use instance::limits::*; diff --git a/src/api/users/mod.rs b/src/api/users/mod.rs index 3bad41b..554bc22 100644 --- a/src/api/users/mod.rs +++ b/src/api/users/mod.rs @@ -1,3 +1,4 @@ +pub use users::*; + pub mod users; -pub use users::*; diff --git a/src/api/users/users.rs b/src/api/users/users.rs index 1d35f32..b7028d5 100644 --- a/src/api/users/users.rs +++ b/src/api/users/users.rs @@ -115,7 +115,7 @@ impl User { &mut belongs_to.limits, id, ) - .await + .await } async fn _get( @@ -197,6 +197,6 @@ impl Instance { &mut self.limits, id, ) - .await + .await } } diff --git a/src/gateway.rs b/src/gateway.rs index 85c3515..ebe6bfa 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -1,11 +1,9 @@ -use crate::errors::ObserverError; -use crate::gateway::events::Events; -use crate::types; -use futures_util::stream::SplitSink; +use std::sync::Arc; + use futures_util::SinkExt; +use futures_util::stream::SplitSink; use futures_util::StreamExt; use native_tls::TlsConnector; -use std::sync::Arc; use tokio::net::TcpStream; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TryRecvError; @@ -15,8 +13,12 @@ use tokio::task; use tokio::task::JoinHandle; use tokio::time; use tokio::time::Instant; -use tokio_tungstenite::MaybeTlsStream; use tokio_tungstenite::{connect_async_tls_with_config, Connector, WebSocketStream}; +use tokio_tungstenite::MaybeTlsStream; + +use crate::errors::ObserverError; +use crate::gateway::events::Events; +use crate::types; // Gateway opcodes /// Opcode received when the server dispatches a [crate::types::WebSocketEvent] @@ -72,7 +74,7 @@ Represents a handle to a Gateway connection. A Gateway connection will create ob [`GatewayEvents`](GatewayEvent), which you can subscribe to. Gateway events include all currently implemented [Types] with the trait [`WebSocketEvent`] Using this handle you can also send Gateway Events directly. -*/ + */ pub struct GatewayHandle { pub url: String, pub events: Arc>, @@ -201,7 +203,7 @@ impl Gateway { TlsConnector::builder().build().unwrap(), )), ) - .await + .await { Ok(websocket_stream) => websocket_stream, Err(e) => return Err(e), @@ -1198,7 +1200,7 @@ impl Gateway { /** Handles sending heartbeats to the gateway in another thread -*/ + */ struct HeartbeatHandler { /// The heartbeat interval in milliseconds pub heartbeat_interval: u128, @@ -1267,7 +1269,7 @@ impl HeartbeatHandler { /** Used to communicate with the main thread. Either signifies a sequence number update or a received heartbeat ack -*/ + */ #[derive(Clone, Copy, Debug)] struct HeartbeatThreadCommunication { /// The opcode for the communication we received @@ -1287,8 +1289,7 @@ pub trait Observer: std::fmt::Debug { /** GatewayEvent is a wrapper around a WebSocketEvent. It is used to notify the observers of a change in the WebSocketEvent. GatewayEvents are observable. -*/ - + */ #[derive(Default, Debug)] pub struct GatewayEvent { observers: Vec + Sync + Send>>>, @@ -1307,7 +1308,7 @@ impl GatewayEvent { /** Returns true if the GatewayEvent is observed by at least one Observer. - */ + */ pub fn is_observed(&self) -> bool { self.is_observed } @@ -1318,7 +1319,7 @@ impl GatewayEvent { # Errors Returns an error if the GatewayEvent is already observed. Error type: [`ObserverError::AlreadySubscribedError`] - */ + */ pub fn subscribe( &mut self, observable: Arc + Sync + Send>>, @@ -1333,7 +1334,7 @@ impl GatewayEvent { /** Unsubscribes an Observer from the GatewayEvent. - */ + */ pub fn unsubscribe(&mut self, observable: Arc + Sync + Send>>) { // .retain()'s closure retains only those elements of the vector, which have a different // pointer value than observable. @@ -1346,7 +1347,7 @@ impl GatewayEvent { /** Updates the GatewayEvent's data and notifies the observers. - */ + */ async fn update_data(&mut self, new_event_data: T) { self.event_data = new_event_data; self.notify().await; @@ -1354,7 +1355,7 @@ impl GatewayEvent { /** Notifies the observers of the GatewayEvent. - */ + */ async fn notify(&self) { for observer in &self.observers { observer.lock().await.update(&self.event_data); @@ -1364,6 +1365,7 @@ impl GatewayEvent { mod events { use super::*; + #[derive(Default, Debug)] pub struct Events { pub application: Application, @@ -1528,6 +1530,7 @@ mod example { #[derive(Debug)] struct Consumer; + impl Observer for Consumer { fn update(&self, data: &types::GatewayResume) { println!("{}", data.token) diff --git a/src/instance.rs b/src/instance.rs index 524735b..42b7298 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -1,3 +1,7 @@ +use std::cell::RefCell; +use std::fmt; +use std::rc::Rc; + use serde::{Deserialize, Serialize}; use crate::api::limits::Limits; @@ -5,10 +9,6 @@ use crate::errors::{ChorusLibError, FieldFormatError}; use crate::types::{GeneralConfiguration, User, UserSettings}; use crate::URLBundle; -use std::cell::RefCell; -use std::fmt; -use std::rc::Rc; - #[derive(Debug, Clone)] /** The [`Instance`] what you will be using to perform all sorts of actions on the Spacebar server. @@ -47,7 +47,7 @@ impl Instance { Err(e) => { return Err(ChorusLibError::CantGetInfoError { error: e.to_string(), - }) + }); } }; Ok(instance) diff --git a/src/lib.rs b/src/lib.rs index a849188..2e25d3d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +use url::{ParseError, Url}; + #[cfg(feature = "client")] pub mod api; pub mod errors; @@ -11,9 +13,7 @@ pub mod types; #[cfg(feature = "client")] pub mod voice; -use url::{ParseError, Url}; #[derive(Clone, Default, Debug, PartialEq, Eq)] - /// A URLBundle is a struct which bundles together the API-, Gateway- and CDN-URLs of a Spacebar /// instance. pub struct URLBundle { diff --git a/src/limit.rs b/src/limit.rs index 70f5c06..4cf0d7d 100644 --- a/src/limit.rs +++ b/src/limit.rs @@ -1,10 +1,11 @@ -use crate::{ - api::limits::{Limit, LimitType, Limits, LimitsMutRef}, - errors::ChorusLibError, -}; +use std::collections::VecDeque; use reqwest::{Client, RequestBuilder, Response}; -use std::collections::VecDeque; + +use crate::{ + api::limits::{Limit, Limits, LimitsMutRef, LimitType}, + errors::ChorusLibError, +}; // Note: There seem to be some overlapping request limiters. We need to make sure that sending a // request checks for all the request limiters that apply, and blocks if any of the limiters are 0 @@ -64,7 +65,7 @@ impl LimitedRequester { - There has been an error with processing (unwrapping) the [`Response`](`reqwest::Response`) - The call to [`update_limits`](`crate::limits::update_limits`) yielded errors. Read the methods' Errors section for more information. - */ + */ pub async fn send_request( &mut self, request: RequestBuilder, @@ -79,7 +80,7 @@ impl LimitedRequester { return Err(ChorusLibError::RequestErrorError { url: "".to_string(), error: e.to_string(), - }) + }); } }; let result = self.http.execute(built_request).await; @@ -88,7 +89,7 @@ impl LimitedRequester { Err(e) => { return Err(ChorusLibError::ReceivedErrorCodeError { error_code: e.to_string(), - }) + }); } }; self.update_limits( @@ -104,7 +105,7 @@ impl LimitedRequester { _ => { return Err(ChorusLibError::ReceivedErrorCodeError { error_code: response.status().as_str().to_string(), - }) + }); } } } else { @@ -148,7 +149,7 @@ impl LimitedRequester { &LimitType::Ip, &limit_type, ] - .to_vec(); + .to_vec(); for limit in constant_limits.iter() { match rate_limits.to_hash_map().get(limit) { Some(limit) => { @@ -158,21 +159,21 @@ impl LimitedRequester { // AbsoluteRegister and AuthRegister can cancel each other out. if limit.bucket == LimitType::AbsoluteRegister && rate_limits - .to_hash_map() - .get(&LimitType::AuthRegister) - .unwrap() - .remaining - == 0 + .to_hash_map() + .get(&LimitType::AuthRegister) + .unwrap() + .remaining + == 0 { return false; } if limit.bucket == LimitType::AuthRegister && rate_limits - .to_hash_map() - .get(&LimitType::AbsoluteRegister) - .unwrap() - .remaining - == 0 + .to_hash_map() + .get(&LimitType::AbsoluteRegister) + .unwrap() + .remaining + == 0 { return false; } @@ -281,10 +282,11 @@ impl LimitedRequester { mod rate_limit { use serde_json::from_str; - use super::*; use crate::{api::limits::Config, URLBundle}; - #[tokio::test] + use super::*; + + #[tokio::test] async fn create_limited_requester() { let _urls = URLBundle::new( String::from("http://localhost:3001/api/"), diff --git a/src/types/config/mod.rs b/src/types/config/mod.rs index 521d303..181147b 100644 --- a/src/types/config/mod.rs +++ b/src/types/config/mod.rs @@ -172,7 +172,7 @@ fn insert_into(value: &mut Value, path: &[&str], new_value: Value) { #[cfg(test)] mod test { - use crate::types::config::{generate_pairs, pairs_to_config, ConfigValue}; + use crate::types::config::{ConfigValue, generate_pairs, pairs_to_config}; #[test] fn test_pairs() { diff --git a/src/types/config/types/guild_configuration.rs b/src/types/config/types/guild_configuration.rs index 2dc4d5b..2afbc6a 100644 --- a/src/types/config/types/guild_configuration.rs +++ b/src/types/config/types/guild_configuration.rs @@ -1,20 +1,21 @@ -use serde::{Deserialize, Serialize}; -#[cfg(feature = "sqlx")] -use sqlx::{ - database::{HasArguments, HasValueRef}, - encode::IsNull, - error::BoxDynError, - Decode, Encode, MySql, -}; use std::fmt::{Display, Formatter}; use std::io::Write; use std::ops::{Deref, DerefMut}; use std::str::FromStr; +use serde::{Deserialize, Serialize}; +#[cfg(feature = "sqlx")] +use sqlx::{ + database::{HasArguments, HasValueRef}, + Decode, + Encode, + encode::IsNull, error::BoxDynError, MySql, +}; + +use crate::types::{Error, GuildError}; use crate::types::config::types::subconfigs::guild::{ autojoin::AutoJoinConfiguration, discovery::DiscoverConfiguration, }; -use crate::types::{Error, GuildError}; #[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] diff --git a/src/types/config/types/subconfigs/limits/rates.rs b/src/types/config/types/subconfigs/limits/rates.rs index 9d0cab1..07ebf0d 100644 --- a/src/types/config/types/subconfigs/limits/rates.rs +++ b/src/types/config/types/subconfigs/limits/rates.rs @@ -1,7 +1,7 @@ use serde::{Deserialize, Serialize}; use crate::types::config::types::subconfigs::limits::ratelimits::{ - route::RouteRateLimit, RateLimitOptions, + RateLimitOptions, route::RouteRateLimit, }; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/src/types/config/types/subconfigs/register/email.rs b/src/types/config/types/subconfigs/register/email.rs index ac99bfc..8688cd2 100644 --- a/src/types/config/types/subconfigs/register/email.rs +++ b/src/types/config/types/subconfigs/register/email.rs @@ -9,6 +9,7 @@ pub struct RegistrationEmailConfiguration { #[serde(default)] pub domains: Vec, } + impl Default for RegistrationEmailConfiguration { fn default() -> Self { Self { diff --git a/src/types/config/types/subconfigs/register/mod.rs b/src/types/config/types/subconfigs/register/mod.rs index ad92571..7535f0b 100644 --- a/src/types/config/types/subconfigs/register/mod.rs +++ b/src/types/config/types/subconfigs/register/mod.rs @@ -1,7 +1,8 @@ +pub use date_of_birth::DateOfBirthConfiguration; +pub use email::RegistrationEmailConfiguration; +pub use password::PasswordConfiguration; + mod date_of_birth; mod email; mod password; -pub use date_of_birth::DateOfBirthConfiguration; -pub use email::RegistrationEmailConfiguration; -pub use password::PasswordConfiguration; diff --git a/src/types/config/types/subconfigs/security/mod.rs b/src/types/config/types/subconfigs/security/mod.rs index ceeb0d3..b9a0ee1 100644 --- a/src/types/config/types/subconfigs/security/mod.rs +++ b/src/types/config/types/subconfigs/security/mod.rs @@ -1,5 +1,6 @@ +pub use captcha::{CaptchaConfiguration, CaptchaService}; +pub use twofactor::TwoFactorConfiguration; + mod captcha; mod twofactor; -pub use captcha::{CaptchaConfiguration, CaptchaService}; -pub use twofactor::TwoFactorConfiguration; diff --git a/src/types/entities/application.rs b/src/types/entities/application.rs index 56b16ae..13c90e0 100644 --- a/src/types/entities/application.rs +++ b/src/types/entities/application.rs @@ -1,10 +1,11 @@ -use crate::types::utils::Snowflake; -use crate::types::{Team, User}; use bitflags::{bitflags, Flags}; use serde::{Deserialize, Serialize}; use serde_json::Value; use serde_repr::{Deserialize_repr, Serialize_repr}; +use crate::types::{Team, User}; +use crate::types::utils::Snowflake; + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "sqlx", derive(sqlx::FromRow))] pub struct Application { diff --git a/src/types/entities/attachment.rs b/src/types/entities/attachment.rs index 5bdfede..423bac6 100644 --- a/src/types/entities/attachment.rs +++ b/src/types/entities/attachment.rs @@ -23,7 +23,6 @@ pub struct Attachment { } #[derive(Debug, Serialize, Deserialize, Clone)] - pub struct PartialDiscordFileAttachment { pub id: Option, pub filename: String, diff --git a/src/types/entities/guild.rs b/src/types/entities/guild.rs index f9fa2e2..9e31abd 100644 --- a/src/types/entities/guild.rs +++ b/src/types/entities/guild.rs @@ -2,12 +2,12 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_repr::{Deserialize_repr, Serialize_repr}; -use crate::types::types::guild_configuration::GuildFeaturesList; use crate::types::{ entities::{Channel, Emoji, RoleObject, Sticker, User, VoiceState, Webhook}, interfaces::WelcomeScreenObject, utils::Snowflake, }; +use crate::types::types::guild_configuration::GuildFeaturesList; /// See https://discord.com/developers/docs/resources/guild #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] diff --git a/src/types/entities/message.rs b/src/types/entities/message.rs index f864014..a64ea0d 100644 --- a/src/types/entities/message.rs +++ b/src/types/entities/message.rs @@ -170,7 +170,6 @@ pub struct EmbedAuthor { } #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] - pub struct EmbedField { name: String, value: String, diff --git a/src/types/entities/mod.rs b/src/types/entities/mod.rs index d27c76e..2cf8fbd 100644 --- a/src/types/entities/mod.rs +++ b/src/types/entities/mod.rs @@ -1,3 +1,26 @@ +pub use application::*; +pub use attachment::*; +pub use audit_log::*; +pub use auto_moderation::*; +pub use channel::*; +pub use config::*; +pub use emoji::*; +pub use guild::*; +pub use guild_member::*; +pub use integration::*; +pub use message::*; +pub use relationship::*; +pub use role::*; +pub use security_key::*; +pub use stage_instance::*; +pub use sticker::*; +pub use team::*; +pub use template::*; +pub use user::*; +pub use user_settings::*; +pub use voice_state::*; +pub use webhook::*; + mod application; mod attachment; mod audit_log; @@ -21,25 +44,3 @@ mod user_settings; mod voice_state; mod webhook; -pub use application::*; -pub use attachment::*; -pub use audit_log::*; -pub use auto_moderation::*; -pub use channel::*; -pub use config::*; -pub use emoji::*; -pub use guild::*; -pub use guild_member::*; -pub use integration::*; -pub use message::*; -pub use relationship::*; -pub use role::*; -pub use security_key::*; -pub use stage_instance::*; -pub use sticker::*; -pub use team::*; -pub use template::*; -pub use user::*; -pub use user_settings::*; -pub use voice_state::*; -pub use webhook::*; diff --git a/src/types/entities/template.rs b/src/types/entities/template.rs index aa87251..c2a2aca 100644 --- a/src/types/entities/template.rs +++ b/src/types/entities/template.rs @@ -21,7 +21,8 @@ pub struct GuildTemplate { pub updated_at: DateTime, pub source_guild_id: String, #[cfg_attr(feature = "sqlx", sqlx(skip))] - pub source_guild: Vec, // Unsure how a {recursive: Guild} looks like, might be a Vec? + pub source_guild: Vec, + // Unsure how a {recursive: Guild} looks like, might be a Vec? #[cfg_attr(feature = "sqlx", sqlx(skip))] pub serialized_source_guild: Vec, } diff --git a/src/types/events/call.rs b/src/types/events/call.rs index 3c58635..5201374 100644 --- a/src/types/events/call.rs +++ b/src/types/events/call.rs @@ -10,12 +10,14 @@ pub struct CallCreate { pub voice_states: Vec, /// Seems like a vec of channel ids pub ringing: Vec, - pub region: String, // milan + pub region: String, + // milan pub message_id: String, /// What is this? pub embedded_activities: Vec, pub channel_id: String, } + impl WebSocketEvent for CallCreate {} #[derive(Debug, Deserialize, Serialize, Default)] @@ -25,11 +27,13 @@ impl WebSocketEvent for CallCreate {} pub struct CallUpdate { /// Seems like a vec of channel ids pub ringing: Vec, - pub region: String, // milan + pub region: String, + // milan pub message_id: String, pub guild_id: Option, pub channel_id: String, } + impl WebSocketEvent for CallUpdate {} #[derive(Debug, Deserialize, Serialize, Default)] @@ -39,6 +43,7 @@ impl WebSocketEvent for CallUpdate {} pub struct CallDelete { pub channel_id: String, } + impl WebSocketEvent for CallDelete {} #[derive(Debug, Deserialize, Serialize, Default)] @@ -48,4 +53,5 @@ impl WebSocketEvent for CallDelete {} pub struct CallSync { pub channel_id: String, } + impl WebSocketEvent for CallSync {} diff --git a/src/types/events/channel.rs b/src/types/events/channel.rs index adafa9f..8a2b035 100644 --- a/src/types/events/channel.rs +++ b/src/types/events/channel.rs @@ -1,8 +1,9 @@ -use crate::types::entities::Channel; -use crate::types::events::WebSocketEvent; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; +use crate::types::entities::Channel; +use crate::types::events::WebSocketEvent; + #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#channel-pins-update pub struct ChannelPinsUpdate { diff --git a/src/types/events/guild.rs b/src/types/events/guild.rs index d1c8fe4..acea876 100644 --- a/src/types/events/guild.rs +++ b/src/types/events/guild.rs @@ -1,9 +1,10 @@ -use crate::types::entities::{Guild, PublicUser, UnavailableGuild}; -use crate::types::events::WebSocketEvent; -use crate::types::{AuditLogEntry, Emoji, GuildMember, GuildScheduledEvent, RoleObject, Sticker}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; +use crate::types::{AuditLogEntry, Emoji, GuildMember, GuildScheduledEvent, RoleObject, Sticker}; +use crate::types::entities::{Guild, PublicUser, UnavailableGuild}; +use crate::types::events::WebSocketEvent; + use super::PresenceUpdate; #[derive(Debug, Deserialize, Serialize, Default)] @@ -26,6 +27,7 @@ impl Default for GuildCreateDataOption { GuildCreateDataOption::UnavailableGuild(UnavailableGuild::default()) } } + impl WebSocketEvent for GuildCreate {} #[derive(Debug, Default, Deserialize, Serialize)] diff --git a/src/types/events/heartbeat.rs b/src/types/events/heartbeat.rs index be9e3f8..4b8db77 100644 --- a/src/types/events/heartbeat.rs +++ b/src/types/events/heartbeat.rs @@ -1,6 +1,7 @@ -use crate::types::events::WebSocketEvent; use serde::{Deserialize, Serialize}; +use crate::types::events::WebSocketEvent; + #[derive(Debug, Default, Deserialize, Serialize)] pub struct GatewayHeartbeat { pub op: u8, diff --git a/src/types/events/hello.rs b/src/types/events/hello.rs index 214f211..66ba182 100644 --- a/src/types/events/hello.rs +++ b/src/types/events/hello.rs @@ -1,6 +1,7 @@ -use crate::types::events::WebSocketEvent; use serde::{Deserialize, Serialize}; +use crate::types::events::WebSocketEvent; + #[derive(Debug, Default, Deserialize, Serialize)] pub struct GatewayHello { pub op: i32, diff --git a/src/types/events/identify.rs b/src/types/events/identify.rs index c4b55f4..0ee5296 100644 --- a/src/types/events/identify.rs +++ b/src/types/events/identify.rs @@ -1,7 +1,8 @@ -use crate::types::events::{PresenceUpdate, WebSocketEvent}; use serde::{Deserialize, Serialize}; use serde_with::serde_as; +use crate::types::events::{PresenceUpdate, WebSocketEvent}; + #[derive(Debug, Deserialize, Serialize)] pub struct GatewayIdentifyPayload { pub token: String, @@ -9,7 +10,8 @@ pub struct GatewayIdentifyPayload { #[serde(skip_serializing_if = "Option::is_none")] pub compress: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub large_threshold: Option, //default: 50 + pub large_threshold: Option, + //default: 50 #[serde(skip_serializing_if = "Option::is_none")] pub shard: Option>, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/src/types/events/lazy_request.rs b/src/types/events/lazy_request.rs index 2bf3038..3258267 100644 --- a/src/types/events/lazy_request.rs +++ b/src/types/events/lazy_request.rs @@ -24,4 +24,5 @@ pub struct LazyRequest { #[serde(skip_serializing_if = "Option::is_none")] pub channels: Option>>>, } + impl WebSocketEvent for LazyRequest {} diff --git a/src/types/events/message.rs b/src/types/events/message.rs index ef3e900..f368e5c 100644 --- a/src/types/events/message.rs +++ b/src/types/events/message.rs @@ -126,4 +126,5 @@ pub struct MessageACK { pub flags: Option, pub channel_id: String, } + impl WebSocketEvent for MessageACK {} diff --git a/src/types/events/mod.rs b/src/types/events/mod.rs index 2889e6d..6333544 100644 --- a/src/types/events/mod.rs +++ b/src/types/events/mod.rs @@ -1,31 +1,5 @@ use serde::{Deserialize, Serialize}; -mod application; -mod auto_moderation; -mod call; -mod channel; -mod guild; -mod heartbeat; -mod hello; -mod identify; -mod integration; -mod interaction; -mod invite; -mod lazy_request; -mod message; -mod passive_update; -mod presence; -mod ready; -mod relationship; -mod request_members; -mod resume; -mod session; -mod stage_instance; -mod thread; -mod user; -mod voice; -mod webhooks; - pub use application::*; pub use auto_moderation::*; pub use call::*; @@ -52,6 +26,32 @@ pub use user::*; pub use voice::*; pub use webhooks::*; +mod application; +mod auto_moderation; +mod call; +mod channel; +mod guild; +mod heartbeat; +mod hello; +mod identify; +mod integration; +mod interaction; +mod invite; +mod lazy_request; +mod message; +mod passive_update; +mod presence; +mod ready; +mod relationship; +mod request_members; +mod resume; +mod session; +mod stage_instance; +mod thread; +mod user; +mod voice; +mod webhooks; + pub trait WebSocketEvent {} #[derive(Debug, Default, Serialize, Clone)] @@ -79,7 +79,6 @@ impl WebSocketEvent for GatewaySendPayload {} /// /// Similar to [GatewaySendPayload], except we send a [Value] for d whilst we receive a [serde_json::value::RawValue] /// Also, we never need to sent the event name - pub struct GatewayReceivePayload<'a> { #[serde(rename = "op")] pub op_code: u8, diff --git a/src/types/events/passive_update.rs b/src/types/events/passive_update.rs index 7417467..8e5ab6c 100644 --- a/src/types/events/passive_update.rs +++ b/src/types/events/passive_update.rs @@ -1,8 +1,9 @@ use serde::{Deserialize, Serialize}; -use super::{ChannelUnreadUpdateObject, WebSocketEvent}; use crate::types::{GuildMember, VoiceState}; +use super::{ChannelUnreadUpdateObject, WebSocketEvent}; + #[derive(Debug, Deserialize, Serialize, Default)] /// Officially Undocumented /// diff --git a/src/types/events/presence.rs b/src/types/events/presence.rs index dd49fde..43cb275 100644 --- a/src/types/events/presence.rs +++ b/src/types/events/presence.rs @@ -1,7 +1,8 @@ +use serde::{Deserialize, Serialize}; + use crate::types::events::WebSocketEvent; use crate::types::interfaces::Activity; use crate::types::PublicUser; -use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize, Default, Clone)] /// See https://discord.com/developers/docs/topics/gateway-events#presence-update-presence-update-event-fields diff --git a/src/types/events/ready.rs b/src/types/events/ready.rs index c559f0b..70ab11b 100644 --- a/src/types/events/ready.rs +++ b/src/types/events/ready.rs @@ -1,8 +1,9 @@ +use serde::{Deserialize, Serialize}; + +use crate::types::{Activity, GuildMember, PresenceUpdate, VoiceState}; use crate::types::entities::{Guild, User}; use crate::types::events::{Session, WebSocketEvent}; use crate::types::interfaces::ClientStatusObject; -use crate::types::{Activity, GuildMember, PresenceUpdate, VoiceState}; -use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize, Default)] /// Sort of documented, though most fields are left out diff --git a/src/types/events/relationship.rs b/src/types/events/relationship.rs index c9b79c0..5271193 100644 --- a/src/types/events/relationship.rs +++ b/src/types/events/relationship.rs @@ -1,6 +1,7 @@ -use crate::types::{events::WebSocketEvent, Relationship, RelationshipType, Snowflake}; use serde::{Deserialize, Serialize}; +use crate::types::{events::WebSocketEvent, Relationship, RelationshipType, Snowflake}; + #[derive(Debug, Deserialize, Serialize, Default)] /// See https://github.com/spacebarchat/server/issues/204 pub struct RelationshipAdd { diff --git a/src/types/events/request_members.rs b/src/types/events/request_members.rs index 67f37ce..2432df4 100644 --- a/src/types/events/request_members.rs +++ b/src/types/events/request_members.rs @@ -1,6 +1,7 @@ -use crate::types::events::WebSocketEvent; use serde::{Deserialize, Serialize}; +use crate::types::events::WebSocketEvent; + #[derive(Debug, Deserialize, Serialize, Default)] /// See https://discord.com/developers/docs/topics/gateway-events#request-guild-members-request-guild-members-structure pub struct GatewayRequestGuildMembers { diff --git a/src/types/events/resume.rs b/src/types/events/resume.rs index 362de98..6b55aef 100644 --- a/src/types/events/resume.rs +++ b/src/types/events/resume.rs @@ -1,6 +1,7 @@ -use crate::types::events::WebSocketEvent; use serde::{Deserialize, Serialize}; +use crate::types::events::WebSocketEvent; + #[derive(Debug, Deserialize, Serialize, Default)] pub struct GatewayResume { pub token: String, diff --git a/src/types/events/thread.rs b/src/types/events/thread.rs index 0cc5f91..6739ee2 100644 --- a/src/types/events/thread.rs +++ b/src/types/events/thread.rs @@ -1,6 +1,7 @@ +use serde::{Deserialize, Serialize}; + use crate::types::entities::{Channel, ThreadMember}; use crate::types::events::WebSocketEvent; -use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#thread-create diff --git a/src/types/events/user.rs b/src/types/events/user.rs index cfdae5c..e49b5b9 100644 --- a/src/types/events/user.rs +++ b/src/types/events/user.rs @@ -1,7 +1,8 @@ +use serde::{Deserialize, Serialize}; + use crate::types::entities::PublicUser; use crate::types::events::WebSocketEvent; use crate::types::utils::Snowflake; -use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Deserialize, Serialize)] /// See https://discord.com/developers/docs/topics/gateway-events#user-update diff --git a/src/types/events/voice.rs b/src/types/events/voice.rs index 8af9c66..14924aa 100644 --- a/src/types/events/voice.rs +++ b/src/types/events/voice.rs @@ -1,6 +1,7 @@ -use crate::types::{events::WebSocketEvent, VoiceState}; use serde::{Deserialize, Serialize}; +use crate::types::{events::WebSocketEvent, VoiceState}; + #[derive(Debug, Deserialize, Serialize, Default)] /// See https://discord.com/developers/docs/topics/gateway-events#update-voice-state /// diff --git a/src/types/interfaces/activity.rs b/src/types/interfaces/activity.rs index 42ecc43..94a7168 100644 --- a/src/types/interfaces/activity.rs +++ b/src/types/interfaces/activity.rs @@ -1,6 +1,7 @@ -use crate::types::entities::Emoji; use serde::{Deserialize, Serialize}; +use crate::types::entities::Emoji; + #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Activity { name: String, diff --git a/src/types/interfaces/guild_welcome_screen.rs b/src/types/interfaces/guild_welcome_screen.rs index 0260ab3..4912a78 100644 --- a/src/types/interfaces/guild_welcome_screen.rs +++ b/src/types/interfaces/guild_welcome_screen.rs @@ -1,6 +1,7 @@ -use crate::types::utils::Snowflake; use serde::{Deserialize, Serialize}; +use crate::types::utils::Snowflake; + #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] pub struct WelcomeScreenObject { pub enabled: bool, diff --git a/src/types/interfaces/interaction.rs b/src/types/interfaces/interaction.rs index 0827078..dd131c8 100644 --- a/src/types/interfaces/interaction.rs +++ b/src/types/interfaces/interaction.rs @@ -1,8 +1,9 @@ -use crate::types::entities::{AllowedMention, Embed}; -use crate::types::utils::Snowflake; use serde::{Deserialize, Serialize}; use serde_json::Value; +use crate::types::entities::{AllowedMention, Embed}; +use crate::types::utils::Snowflake; + #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] pub struct Interaction { pub id: Snowflake, diff --git a/src/types/interfaces/mod.rs b/src/types/interfaces/mod.rs index 0f99ae2..d74c33d 100644 --- a/src/types/interfaces/mod.rs +++ b/src/types/interfaces/mod.rs @@ -1,11 +1,12 @@ +pub use activity::*; +pub use connected_account::*; +pub use guild_welcome_screen::*; +pub use interaction::*; +pub use status::*; + mod activity; mod connected_account; mod guild_welcome_screen; mod interaction; mod status; -pub use activity::*; -pub use connected_account::*; -pub use guild_welcome_screen::*; -pub use interaction::*; -pub use status::*; diff --git a/src/types/schema/apierror.rs b/src/types/schema/apierror.rs index 95e72a5..b3401d8 100644 --- a/src/types/schema/apierror.rs +++ b/src/types/schema/apierror.rs @@ -61,8 +61,8 @@ impl poem::error::ResponseError for APIError { } fn as_response(&self) -> Response - where - Self: std::error::Error + Send + Sync + 'static, + where + Self: std::error::Error + Send + Sync + 'static, { Response::builder() .status(self.status()) diff --git a/src/types/schema/auth.rs b/src/types/schema/auth.rs index 68c4546..fc7a1ad 100644 --- a/src/types/schema/auth.rs +++ b/src/types/schema/auth.rs @@ -1,7 +1,8 @@ -use crate::errors::FieldFormatError; use regex::Regex; use serde::{Deserialize, Serialize}; +use crate::errors::FieldFormatError; + /** A struct that represents a well-formed email address. */ @@ -100,7 +101,6 @@ You will receive a [`FieldFormatError`], if: - The username is not between 2 and 32 characters. - The password is not between 1 and 72 characters. */ - #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct RegisterSchema { diff --git a/src/types/schema/guild.rs b/src/types/schema/guild.rs index 835f6ad..cb0dac8 100644 --- a/src/types/schema/guild.rs +++ b/src/types/schema/guild.rs @@ -1,6 +1,7 @@ -use crate::types::entities::Channel; use serde::{Deserialize, Serialize}; +use crate::types::entities::Channel; + #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] /// Represents the schema which needs to be sent to create a Guild. diff --git a/src/types/schema/message.rs b/src/types/schema/message.rs index 6121f5f..7ff27f1 100644 --- a/src/types/schema/message.rs +++ b/src/types/schema/message.rs @@ -1,7 +1,8 @@ +use serde::{Deserialize, Serialize}; + use crate::types::entities::{ AllowedMention, Component, Embed, MessageReference, PartialDiscordFileAttachment, }; -use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] diff --git a/src/types/schema/mod.rs b/src/types/schema/mod.rs index 2e5c4f0..53795ec 100644 --- a/src/types/schema/mod.rs +++ b/src/types/schema/mod.rs @@ -1,11 +1,3 @@ -mod apierror; -mod auth; -mod channel; -mod guild; -mod message; -mod role; -mod user; - pub use apierror::*; pub use auth::*; pub use channel::*; @@ -14,11 +6,20 @@ pub use message::*; pub use role::*; pub use user::*; +mod apierror; +mod auth; +mod channel; +mod guild; +mod message; +mod role; +mod user; + #[cfg(test)] mod schemas_tests { - use super::*; use crate::errors::FieldFormatError; + use super::*; + #[test] fn password_too_short() { assert_eq!( diff --git a/src/types/schema/role.rs b/src/types/schema/role.rs index 65faa39..aa8c5af 100644 --- a/src/types/schema/role.rs +++ b/src/types/schema/role.rs @@ -1,6 +1,7 @@ -use crate::types::Snowflake; use serde::{Deserialize, Serialize}; +use crate::types::Snowflake; + #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] /// Represents the schema which needs to be sent to create or modify a Role. diff --git a/src/types/utils/mod.rs b/src/types/utils/mod.rs index ec2fd4a..9dfb0f9 100644 --- a/src/types/utils/mod.rs +++ b/src/types/utils/mod.rs @@ -1,8 +1,9 @@ +pub use regexes::*; +pub use rights::Rights; +pub use snowflake::{DeconstructedSnowflake, Snowflake}; + pub mod jwt; mod regexes; mod rights; mod snowflake; -pub use regexes::*; -pub use rights::Rights; -pub use snowflake::{DeconstructedSnowflake, Snowflake}; diff --git a/tests/auth.rs b/tests/auth.rs index e80849a..c3aae92 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -1,6 +1,7 @@ -mod common; use chorus::types; +mod common; + #[tokio::test] async fn test_registration() { let mut bundle = common::setup().await; @@ -16,7 +17,7 @@ async fn test_registration() { None, None, ) - .unwrap(); + .unwrap(); bundle.instance.register_account(®).await.unwrap(); common::teardown(bundle).await; } diff --git a/tests/channel.rs b/tests/channel.rs index 8ae8e58..d1464be 100644 --- a/tests/channel.rs +++ b/tests/channel.rs @@ -1,6 +1,7 @@ -mod common; use chorus::types::{self, Channel, PermissionFlags, PermissionOverwrite}; +mod common; + #[tokio::test] async fn get_channel() { let mut bundle = common::setup().await; @@ -9,7 +10,7 @@ async fn get_channel() { assert_eq!( bundle_channel, - Channel::get(&mut bundle_user, &bundle_channel.id.to_string(),) + Channel::get(&mut bundle_user, &bundle_channel.id.to_string()) .await .unwrap() ); @@ -51,8 +52,8 @@ async fn modify_channel() { &bundle.channel.id.to_string(), &mut bundle.user, ) - .await - .unwrap(); + .await + .unwrap(); assert_eq!(result.name, Some("beepboop".to_string())); let permission_override = PermissionFlags::from_vec(Vec::from([ @@ -71,14 +72,14 @@ async fn modify_channel() { bundle.channel.id.to_string().as_str(), permission_override.clone(), ) - .await; + .await; Channel::delete_permission( &mut bundle.user, bundle.channel.id.to_string().as_str(), &permission_override.id, ) - .await; + .await; common::teardown(bundle).await } diff --git a/tests/common/mod.rs b/tests/common/mod.rs index c58c79a..a26fe76 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -38,7 +38,7 @@ pub async fn setup() -> TestBundle { None, None, ) - .unwrap(); + .unwrap(); let guild_create_schema = GuildCreateSchema { name: Some("Test-Guild!".to_string()), region: None, diff --git a/tests/guild.rs b/tests/guild.rs index 8143532..3f7037c 100644 --- a/tests/guild.rs +++ b/tests/guild.rs @@ -1,6 +1,7 @@ -mod common; use chorus::types::{Guild, GuildCreateSchema}; +mod common; + #[tokio::test] async fn guild_creation_deletion() { let mut bundle = common::setup().await; diff --git a/tests/message.rs b/tests/message.rs index 6ccda0b..d614538 100644 --- a/tests/message.rs +++ b/tests/message.rs @@ -1,9 +1,10 @@ -mod common; - -use chorus::types; use std::fs::File; use std::io::{BufReader, Read}; +use chorus::types; + +mod common; + #[tokio::test] async fn send_message() { let mut bundle = common::setup().await; diff --git a/tests/roles.rs b/tests/roles.rs index 2663d25..fd80de3 100644 --- a/tests/roles.rs +++ b/tests/roles.rs @@ -1,7 +1,7 @@ -mod common; - use chorus::types::{self, RoleCreateModifySchema}; +mod common; + #[tokio::test] async fn create_and_get_roles() { let mut bundle = common::setup().await;