diff --git a/examples/gateway_observers.rs b/examples/gateway_observers.rs index a43d17cd..81371796 100644 --- a/examples/gateway_observers.rs +++ b/examples/gateway_observers.rs @@ -52,7 +52,7 @@ impl Subscriber for ExampleObserver { #[tokio::main(flavor = "current_thread")] async fn main() { - let gateway_websocket_url = GATEWAY_URL.to_string(); + let gateway_websocket_url = GATEWAY_URL; // These options specify the encoding format, compression, etc // diff --git a/examples/gateway_simple.rs b/examples/gateway_simple.rs index 7f662874..aa6e0e0f 100644 --- a/examples/gateway_simple.rs +++ b/examples/gateway_simple.rs @@ -25,8 +25,8 @@ use wasmtimer::tokio::sleep; /// This example creates a simple gateway connection and a session with an Identify event #[tokio::main(flavor = "current_thread")] async fn main() { - let gateway_websocket_url = GATEWAY_URL.to_string(); - + let gateway_websocket_url = GATEWAY_URL; + // These options specify the encoding format, compression, etc // // For most cases the defaults should work, though some implementations @@ -34,7 +34,9 @@ async fn main() { let options = GatewayOptions::default(); // Initiate the gateway connection, starting a listener in one thread and a heartbeat handler in another - let gateway = Gateway::spawn(gateway_websocket_url, options).await.unwrap(); + let gateway = Gateway::spawn(gateway_websocket_url, options) + .await + .unwrap(); // At this point, we are connected to the server and are sending heartbeats, however we still haven't authenticated diff --git a/src/api/auth/login.rs b/src/api/auth/login.rs index 7c58e0e7..3a9a9eeb 100644 --- a/src/api/auth/login.rs +++ b/src/api/auth/login.rs @@ -30,13 +30,12 @@ impl Instance { // 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 user = - ChorusUser::shell(Arc::new(RwLock::new(self.clone())), "None".to_string()).await; - + let mut user = ChorusUser::shell(Arc::new(RwLock::new(self.clone())), "None").await; + let login_result = chorus_request .deserialize_response::(&mut user) .await?; - user.set_token(login_result.token); + user.set_token(&login_result.token); user.settings = login_result.settings; let object = User::get(&mut user, None).await?; diff --git a/src/api/auth/mod.rs b/src/api/auth/mod.rs index 498080e8..b9050e14 100644 --- a/src/api/auth/mod.rs +++ b/src/api/auth/mod.rs @@ -22,9 +22,8 @@ pub mod register; impl Instance { /// Logs into an existing account on the spacebar server, using only a token. - pub async fn login_with_token(&mut self, token: String) -> ChorusResult { - let mut user = - ChorusUser::shell(Arc::new(RwLock::new(self.clone())), token).await; + pub async fn login_with_token(&mut self, token: &str) -> ChorusResult { + let mut user = ChorusUser::shell(Arc::new(RwLock::new(self.clone())), token).await; let object = User::get(&mut user, None).await?; let settings = User::get_settings(&mut user).await?; diff --git a/src/api/auth/register.rs b/src/api/auth/register.rs index 6b94a4d7..821a52ff 100644 --- a/src/api/auth/register.rs +++ b/src/api/auth/register.rs @@ -37,14 +37,13 @@ impl Instance { // 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 user = - ChorusUser::shell(Arc::new(RwLock::new(self.clone())), "None".to_string()).await; - + let mut user = ChorusUser::shell(Arc::new(RwLock::new(self.clone())), "None").await; + let token = chorus_request .deserialize_response::(&mut user) .await? .token; - user.set_token(token); + user.set_token(&token); let object = User::get(&mut user, None).await?; let settings = User::get_settings(&mut user).await?; diff --git a/src/api/channels/messages.rs b/src/api/channels/messages.rs index 6387d12c..a682c21c 100644 --- a/src/api/channels/messages.rs +++ b/src/api/channels/messages.rs @@ -112,7 +112,7 @@ impl Message { let result = request.send_request(user).await?; let result_json = result.json::().await.unwrap(); if !result_json.is_object() { - return Err(search_error(result_json.to_string())); + return Err(search_error(result_json.to_string().as_str())); } let value_map = result_json.as_object().unwrap(); if let Some(messages) = value_map.get("messages") { @@ -123,7 +123,7 @@ impl Message { } // The code below might be incorrect. We'll cross that bridge when we come to it if !value_map.contains_key("code") || !value_map.contains_key("retry_after") { - return Err(search_error(result_json.to_string())); + return Err(search_error(result_json.to_string().as_str())); } let code = value_map.get("code").unwrap().as_u64().unwrap(); let retry_after = value_map.get("retry_after").unwrap().as_u64().unwrap(); @@ -482,7 +482,7 @@ impl Message { } } -fn search_error(result_text: String) -> ChorusError { +fn search_error(result_text: &str) -> ChorusError { ChorusError::InvalidResponse { error: format!( "Got unexpected Response, or Response which is not valid JSON. Response: \n{}", diff --git a/src/gateway/gateway.rs b/src/gateway/gateway.rs index f1fc03cc..976769d2 100644 --- a/src/gateway/gateway.rs +++ b/src/gateway/gateway.rs @@ -48,7 +48,7 @@ impl Gateway { /// # Note /// The websocket url should begin with the prefix wss:// or ws:// (for unsecure connections) pub async fn spawn( - websocket_url: String, + websocket_url: &str, options: GatewayOptions, ) -> Result { let url = options.add_to_url(websocket_url); diff --git a/src/gateway/options.rs b/src/gateway/options.rs index 23942b23..4ff6178b 100644 --- a/src/gateway/options.rs +++ b/src/gateway/options.rs @@ -25,8 +25,8 @@ impl GatewayOptions { /// Adds the options to an existing gateway url /// /// Returns the new url - pub(crate) fn add_to_url(&self, url: String) -> String { - let mut url = url; + pub(crate) fn add_to_url(&self, url: &str) -> String { + let mut url = url.to_string(); let mut parameters = Vec::with_capacity(2); diff --git a/src/instance.rs b/src/instance.rs index f826ab58..455b3eff 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -110,7 +110,7 @@ impl Instance { } pub async fn is_limited(api_url: &str) -> ChorusResult> { - let api_url = UrlBundle::parse_url(api_url.to_string()); + let api_url = UrlBundle::parse_url(api_url); let client = Client::new(); let request = client .get(format!("{}/policies/instance/limits", &api_url)) @@ -163,8 +163,8 @@ impl ChorusUser { self.token.clone() } - pub fn set_token(&mut self, token: String) { - self.token = token; + pub fn set_token(&mut self, token: &str) { + self.token = token.to_string(); } /// Creates a new [ChorusUser] from existing data. @@ -195,16 +195,16 @@ impl ChorusUser { /// registering or logging in to the Instance, where you do not yet have a User object, but still /// need to make a RateLimited request. To use the [`GatewayHandle`], you will have to identify /// first. - pub(crate) async fn shell(instance: Shared, token: String) -> ChorusUser { + pub(crate) async fn shell(instance: Shared, token: &str) -> ChorusUser { let settings = Arc::new(RwLock::new(UserSettings::default())); let object = Arc::new(RwLock::new(User::default())); - let wss_url = instance.read().unwrap().urls.wss.clone(); + let wss_url = &instance.read().unwrap().urls.wss.clone(); // Dummy gateway object let gateway = Gateway::spawn(wss_url, GatewayOptions::default()) .await .unwrap(); ChorusUser { - token, + token: token.to_string(), belongs_to: instance.clone(), limits: instance .read() diff --git a/src/lib.rs b/src/lib.rs index b16f12ba..5744e1d8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -186,7 +186,7 @@ pub struct UrlBundle { impl UrlBundle { /// Creates a new UrlBundle from the relevant urls. - pub fn new(root: String, api: String, wss: String, cdn: String) -> Self { + pub fn new(root: &str, api: &str, wss: &str, cdn: &str) -> Self { Self { root: UrlBundle::parse_url(root), api: UrlBundle::parse_url(api), @@ -203,17 +203,17 @@ impl UrlBundle { /// let url = parse_url("localhost:3000"); /// ``` /// `-> Outputs "http://localhost:3000".` - pub fn parse_url(url: String) -> String { - let url = match Url::parse(&url) { + pub fn parse_url(url: &str) -> String { + let url = match Url::parse(url) { Ok(url) => { if url.scheme() == "localhost" { - return UrlBundle::parse_url(format!("http://{}", url)); + return UrlBundle::parse_url(&format!("http://{}", url)); } url } Err(ParseError::RelativeUrlWithoutBase) => { let url_fmt = format!("http://{}", url); - return UrlBundle::parse_url(url_fmt); + return UrlBundle::parse_url(&url_fmt); } Err(_) => panic!("Invalid URL"), // TODO: should not panic here }; @@ -236,7 +236,7 @@ impl UrlBundle { /// of the above approaches fail, it is very likely that the instance is misconfigured, unreachable, or that /// a wrong URL was provided. pub async fn from_root_url(url: &str) -> ChorusResult { - let parsed = UrlBundle::parse_url(url.to_string()); + let parsed = UrlBundle::parse_url(url); let client = reqwest::Client::new(); let request_wellknown = client .get(format!("{}/.well-known/spacebar", &parsed)) @@ -274,10 +274,10 @@ impl UrlBundle { .await { Ok(UrlBundle::new( - url.to_string(), - body.api_endpoint, - body.gateway, - body.cdn, + url, + &body.api_endpoint, + &body.gateway, + &body.cdn, )) } else { Err(ChorusError::RequestFailed { @@ -294,13 +294,13 @@ mod lib { #[test] fn test_parse_url() { - let mut result = UrlBundle::parse_url(String::from("localhost:3000/")); - assert_eq!(result, String::from("http://localhost:3000")); - result = UrlBundle::parse_url(String::from("https://some.url.com/")); - assert_eq!(result, String::from("https://some.url.com")); - result = UrlBundle::parse_url(String::from("https://some.url.com/")); - assert_eq!(result, String::from("https://some.url.com")); - result = UrlBundle::parse_url(String::from("https://some.url.com")); + let mut result = UrlBundle::parse_url("localhost:3000/"); + assert_eq!(result, "http://localhost:3000"); + result = UrlBundle::parse_url("https://some.url.com/"); assert_eq!(result, String::from("https://some.url.com")); + result = UrlBundle::parse_url("https://some.url.com/"); + assert_eq!(result, "https://some.url.com"); + result = UrlBundle::parse_url("https://some.url.com"); + assert_eq!(result, "https://some.url.com"); } } diff --git a/src/types/utils/jwt.rs b/src/types/utils/jwt.rs index ba6f8872..09397234 100644 --- a/src/types/utils/jwt.rs +++ b/src/types/utils/jwt.rs @@ -9,8 +9,8 @@ use jsonwebtoken::{ }; use serde::{Deserialize, Serialize}; -pub fn generate_token(id: &Snowflake, email: String, jwt_key: &str) -> String { - let claims = Claims::new(&email, id); +pub fn generate_token(id: &Snowflake, email: &str, jwt_key: &str) -> String { + let claims = Claims::new(email, id); build_token(&claims, jwt_key).unwrap() } diff --git a/src/voice/gateway/gateway.rs b/src/voice/gateway/gateway.rs index ba4df806..1b5981cb 100644 --- a/src/voice/gateway/gateway.rs +++ b/src/voice/gateway/gateway.rs @@ -41,7 +41,7 @@ pub struct VoiceGateway { impl VoiceGateway { #[allow(clippy::new_ret_no_self)] - pub async fn spawn(websocket_url: String) -> Result { + pub async fn spawn(websocket_url: &str) -> Result { // Append the needed things to the websocket url let processed_url = format!("wss://{}/?v=7", websocket_url); trace!("VGW: Connecting to {}", processed_url.clone()); @@ -110,7 +110,7 @@ impl VoiceGateway { }); Ok(VoiceGatewayHandle { - url: websocket_url.clone(), + url: websocket_url.to_string(), events: shared_events, websocket_send: shared_websocket_send.clone(), kill_send: kill_send.clone(), diff --git a/src/voice/gateway/handle.rs b/src/voice/gateway/handle.rs index 8750f12f..b265b71e 100644 --- a/src/voice/gateway/handle.rs +++ b/src/voice/gateway/handle.rs @@ -72,7 +72,7 @@ impl VoiceGatewayHandle { /// Sends a speaking event to the gateway pub async fn send_speaking(&self, to_send: Speaking) { - let to_send_value = serde_json::to_value(&to_send).unwrap(); + let to_send_value = serde_json::to_value(to_send).unwrap(); trace!("VGW: Sending Speaking"); diff --git a/tests/auth.rs b/tests/auth.rs index 705328ae..9f0cbfdb 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -79,11 +79,7 @@ async fn test_login_with_token() { let mut bundle = common::setup().await; let token = &bundle.user.token; - let other_user = bundle - .instance - .login_with_token(token.clone()) - .await - .unwrap(); + let other_user = bundle.instance.login_with_token(token).await.unwrap(); assert_eq!( bundle.user.object.read().unwrap().id, other_user.object.read().unwrap().id @@ -98,8 +94,8 @@ async fn test_login_with_token() { async fn test_login_with_invalid_token() { let mut bundle = common::setup().await; - let token = "invalid token lalalalala".to_string(); - let other_user = bundle.instance.login_with_token(token.clone()).await; + let token = "invalid token lalalalala"; + let other_user = bundle.instance.login_with_token(token).await; assert!(other_user.is_err()); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index f2f0663e..94c51ed2 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -10,7 +10,7 @@ use chorus::{ instance::{ChorusUser, Instance}, types::{ Channel, ChannelCreateSchema, Guild, GuildCreateSchema, RegisterSchema, - RoleCreateModifySchema, RoleObject, Shared + RoleCreateModifySchema, RoleObject, Shared, }, UrlBundle, }; @@ -50,7 +50,7 @@ impl TestBundle { limits: self.user.limits.clone(), settings: self.user.settings.clone(), object: self.user.object.clone(), - gateway: Gateway::spawn(self.instance.urls.wss.clone(), GatewayOptions::default()) + gateway: Gateway::spawn(&self.instance.urls.wss, GatewayOptions::default()) .await .unwrap(), } @@ -59,9 +59,12 @@ impl TestBundle { // Set up a test by creating an Instance and a User. Reduces Test boilerplate. pub(crate) async fn setup() -> TestBundle { - // So we can get logs when tests fail - let _ = simple_logger::SimpleLogger::with_level(simple_logger::SimpleLogger::new(), log::LevelFilter::Debug).init(); + let _ = simple_logger::SimpleLogger::with_level( + simple_logger::SimpleLogger::new(), + log::LevelFilter::Debug, + ) + .init(); let instance = Instance::new("http://localhost:3001/api").await.unwrap(); // Requires the existence of the below user. @@ -121,10 +124,10 @@ pub(crate) async fn setup() -> TestBundle { .unwrap(); let urls = UrlBundle::new( - "http://localhost:3001/api".to_string(), - "http://localhost:3001/api".to_string(), - "ws://localhost:3001/".to_string(), - "http://localhost:3001".to_string(), + "http://localhost:3001/api", + "http://localhost:3001/api", + "ws://localhost:3001/", + "http://localhost:3001", ); TestBundle { urls, diff --git a/tests/gateway.rs b/tests/gateway.rs index 1c8f56a8..ccd96eff 100644 --- a/tests/gateway.rs +++ b/tests/gateway.rs @@ -31,7 +31,7 @@ use wasmtimer::tokio::sleep; async fn test_gateway_establish() { let bundle = common::setup().await; - let _: GatewayHandle = Gateway::spawn(bundle.urls.wss.clone(), GatewayOptions::default()) + let _: GatewayHandle = Gateway::spawn(&bundle.urls.wss, GatewayOptions::default()) .await .unwrap(); common::teardown(bundle).await @@ -55,7 +55,7 @@ impl Subscriber for GatewayReadyObserver { async fn test_gateway_authenticate() { let bundle = common::setup().await; - let gateway: GatewayHandle = Gateway::spawn(bundle.urls.wss.clone(), GatewayOptions::default()) + let gateway: GatewayHandle = Gateway::spawn(&bundle.urls.wss, GatewayOptions::default()) .await .unwrap();