From 014583216aba16205138d94ba40b0676011f5280 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Sun, 7 May 2023 11:32:11 +0200 Subject: [PATCH 01/16] Impl user::get() function --- src/api/users/users.rs | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/api/users/users.rs b/src/api/users/users.rs index 0190944..2692cbb 100644 --- a/src/api/users/users.rs +++ b/src/api/users/users.rs @@ -1 +1,37 @@ -pub fn doathing() {} +use crate::{ + api::{ + limits::Limits, + types::{User, UserObject}, + }, + errors::InstanceServerError, +}; + +impl<'a> User<'a> { + pub async fn get( + token: &String, + url_api: &String, + id: Option<&String>, + instance_limits: &mut Limits, + ) -> Result { + let url: String; + if id.is_none() { + url = format!("{}/users/@me/", url_api); + } else { + url = format!("{}/users/{}", url_api, id.unwrap()); + } + let request = reqwest::Client::new().get(url).bearer_auth(token); + let mut requester = crate::limit::LimitedRequester::new().await; + match requester + .send_request( + request, + crate::api::limits::LimitType::Ip, + instance_limits, + &mut Limits::default(), + ) + .await + { + Ok(result) => Ok(serde_json::from_str(&result.text().await.unwrap()).unwrap()), + Err(e) => Err(e), + } + } +} From 6b4251a3aac581aa0e90f7f9a20eb6f865bf8ddc Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Sun, 7 May 2023 11:32:25 +0200 Subject: [PATCH 02/16] Remove display impl, add default trait --- src/api/policies/instance/limits.rs | 28 ++++++---------------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/src/api/policies/instance/limits.rs b/src/api/policies/instance/limits.rs index 58d55c5..fa797b2 100644 --- a/src/api/policies/instance/limits.rs +++ b/src/api/policies/instance/limits.rs @@ -1,16 +1,17 @@ pub mod limits { - use std::collections::HashMap; + use std::{collections::HashMap, default}; use reqwest::Client; use serde::{Deserialize, Serialize}; use serde_json::from_str; - #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug)] + #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Default)] pub enum LimitType { AuthRegister, AuthLogin, AbsoluteMessage, AbsoluteRegister, + #[default] Global, Ip, Channel, @@ -19,23 +20,6 @@ pub mod limits { Webhook, } - impl std::fmt::Display for LimitType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - LimitType::AuthRegister => write!(f, "auth_register"), - LimitType::AuthLogin => write!(f, "auth_login"), - LimitType::AbsoluteMessage => write!(f, "absolute_message"), - LimitType::AbsoluteRegister => write!(f, "absolute_register"), - LimitType::Global => write!(f, "global"), - LimitType::Ip => write!(f, "ip"), - LimitType::Channel => write!(f, "channel"), - LimitType::Error => write!(f, "error"), - LimitType::Guild => write!(f, "guild"), - LimitType::Webhook => write!(f, "webhook"), - } - } - } - #[derive(Debug, Deserialize, Serialize)] #[allow(non_snake_case)] pub struct User { @@ -134,7 +118,7 @@ pub mod limits { pub absoluteRate: AbsoluteRate, } - #[derive(Clone, Copy, Debug, PartialEq, Eq)] + #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub struct Limit { pub bucket: LimitType, pub limit: u64, @@ -146,7 +130,7 @@ pub mod limits { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, - "Bucket: {}, Limit: {}, Remaining: {}, Reset: {}", + "Bucket: {:?}, Limit: {}, Remaining: {}, Reset: {}", self.bucket, self.limit, self.remaining, self.reset ) } @@ -229,7 +213,7 @@ pub mod limits { } } - #[derive(Debug, Clone)] + #[derive(Debug, Clone, Default)] pub struct Limits { pub limit_absolute_messages: Limit, pub limit_absolute_register: Limit, From 50ecc78da0128e5ee080c7d1e48f238caa48f69b Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Sun, 7 May 2023 11:54:49 +0200 Subject: [PATCH 03/16] add docs, add instance.get_user() --- src/api/users/users.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/api/users/users.rs b/src/api/users/users.rs index 2692cbb..e4d1678 100644 --- a/src/api/users/users.rs +++ b/src/api/users/users.rs @@ -4,9 +4,20 @@ use crate::{ types::{User, UserObject}, }, errors::InstanceServerError, + instance::Instance, }; impl<'a> User<'a> { + /** + Get a user object by id, or get the current user. + # Arguments + * `token` - A valid access token for the API. + * `url_api` - The URL to the API. + * `id` - The id of the user that will be retrieved. If this is None, the current user will be retrieved. + * `instance_limits` - The [`Limits`] of the instance. + # Errors + * [`InstanceServerError`] - If the request fails. + */ pub async fn get( token: &String, url_api: &String, @@ -35,3 +46,29 @@ impl<'a> User<'a> { } } } + +impl<'a> Instance<'a> { + /** + Get a user object by id, or get the current user. + # Arguments + * `token` - A valid access token for the API. + * `id` - The id of the user that will be retrieved. If this is None, the current user will be retrieved. + # Errors + * [`InstanceServerError`] - If the request fails. + # Notes + This function is a wrapper around [`User::get`]. + */ + pub async fn get_user( + &mut self, + token: String, + id: Option<&String>, + ) -> Result { + User::get( + &token, + &self.urls.get_api().to_string(), + id, + &mut self.limits, + ) + .await + } +} From b2fa6db4924d7c1227a9702724df011fa2a3dd08 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Sun, 7 May 2023 12:39:04 +0200 Subject: [PATCH 04/16] Remove lifetime from Instance (see below) Originally, it was planned, that the Instance object would store Users. I have identified, that this was not needed, as it goes beyond the scope of a library; Users of this library are expected to keep track of users themselves. The removal of this user storage also prevented further overcomplications. --- src/api/auth/login.rs | 2 +- src/api/auth/register.rs | 2 +- src/api/policies/instance/instance.rs | 3 +-- src/api/types.rs | 6 +++--- src/api/users/users.rs | 10 +++++++++- src/instance.rs | 9 +++------ 6 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/api/auth/login.rs b/src/api/auth/login.rs index 23add11..f7c4fe6 100644 --- a/src/api/auth/login.rs +++ b/src/api/auth/login.rs @@ -8,7 +8,7 @@ pub mod login { use crate::errors::InstanceServerError; use crate::instance::Instance; - impl<'a> Instance<'a> { + impl Instance { pub async fn login_account( &mut self, login_schema: &LoginSchema, diff --git a/src/api/auth/register.rs b/src/api/auth/register.rs index b4d4fd1..b932b9f 100644 --- a/src/api/auth/register.rs +++ b/src/api/auth/register.rs @@ -8,7 +8,7 @@ pub mod register { instance::{Instance, Token}, }; - impl<'a> Instance<'a> { + impl Instance { /** Registers a new user on the Spacebar server. # Arguments diff --git a/src/api/policies/instance/instance.rs b/src/api/policies/instance/instance.rs index 19e841e..754d0b3 100644 --- a/src/api/policies/instance/instance.rs +++ b/src/api/policies/instance/instance.rs @@ -1,11 +1,10 @@ - use reqwest::Client; use serde_json::from_str; use crate::errors::InstanceServerError; use crate::{api::types::InstancePolicies, instance::Instance}; -impl<'a> Instance<'a> { +impl Instance { /** Gets the instance policies schema. # Errors diff --git a/src/api/types.rs b/src/api/types.rs index e218a83..20f3329 100644 --- a/src/api/types.rs +++ b/src/api/types.rs @@ -157,7 +157,7 @@ pub struct UserObject { #[derive(Debug)] pub struct User<'a> { pub logged_in: bool, - pub belongs_to: &'a mut Instance<'a>, + pub belongs_to: &'a mut Instance, token: String, pub limits: Limits, pub settings: UserSettings, @@ -169,7 +169,7 @@ impl<'a> User<'a> { self.logged_in } - pub fn belongs_to(&mut self) -> &mut Instance<'a> { + pub fn belongs_to(&mut self) -> &mut Instance { self.belongs_to } @@ -187,7 +187,7 @@ impl<'a> User<'a> { pub fn new( logged_in: bool, - belongs_to: &'a mut Instance<'a>, + belongs_to: &'a mut Instance, token: String, limits: Limits, settings: UserSettings, diff --git a/src/api/users/users.rs b/src/api/users/users.rs index e4d1678..77c38af 100644 --- a/src/api/users/users.rs +++ b/src/api/users/users.rs @@ -47,7 +47,7 @@ impl<'a> User<'a> { } } -impl<'a> Instance<'a> { +impl Instance { /** Get a user object by id, or get the current user. # Arguments @@ -72,3 +72,11 @@ impl<'a> Instance<'a> { .await } } + +#[cfg(test)] +mod test { + use super::*; + + #[tokio::test] + async fn get_user() {} +} diff --git a/src/instance.rs b/src/instance.rs index ad877f0..c20eaca 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -11,16 +11,15 @@ use std::fmt; /** The [`Instance`] what you will be using to perform all sorts of actions on the Spacebar server. */ -pub struct Instance<'a> { +pub struct Instance { pub urls: URLBundle, pub instance_info: InstancePolicies, pub requester: LimitedRequester, pub limits: Limits, //pub gateway: Gateway, - pub users: HashMap>, } -impl<'a> Instance<'a> { +impl Instance { /// Creates a new [`Instance`]. /// # Arguments /// * `urls` - The [`URLBundle`] that contains all the URLs that are needed to connect to the Spacebar server. @@ -30,8 +29,7 @@ impl<'a> Instance<'a> { pub async fn new( urls: URLBundle, requester: LimitedRequester, - ) -> Result, InstanceServerError> { - let users: HashMap = HashMap::new(); + ) -> Result { let mut instance = Instance { urls: urls.clone(), instance_info: InstancePolicies::new( @@ -47,7 +45,6 @@ impl<'a> Instance<'a> { ), limits: Limits::check_limits(urls.api).await, requester, - users, }; instance.instance_info = match instance.instance_policies_schema().await { Ok(schema) => schema, From 8f3912c27768555b3c2dda8f2fd2aa933e751a36 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Sun, 7 May 2023 12:39:56 +0200 Subject: [PATCH 05/16] Remove unneccessary imports --- src/api/channels/messages.rs | 2 +- src/api/policies/instance/limits.rs | 2 +- src/api/schemas.rs | 6 +++--- src/api/types.rs | 2 +- src/instance.rs | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/api/channels/messages.rs b/src/api/channels/messages.rs index 1fa840a..6629b1b 100644 --- a/src/api/channels/messages.rs +++ b/src/api/channels/messages.rs @@ -2,7 +2,7 @@ pub mod messages { use reqwest::Client; use serde_json::to_string; - use crate::api::limits::Limits; + use crate::api::types::{Message, PartialDiscordFileAttachment, User}; use crate::limit::LimitedRequester; diff --git a/src/api/policies/instance/limits.rs b/src/api/policies/instance/limits.rs index fa797b2..2818135 100644 --- a/src/api/policies/instance/limits.rs +++ b/src/api/policies/instance/limits.rs @@ -1,5 +1,5 @@ pub mod limits { - use std::{collections::HashMap, default}; + use std::{collections::HashMap}; use reqwest::Client; use serde::{Deserialize, Serialize}; diff --git a/src/api/schemas.rs b/src/api/schemas.rs index 215d7a6..8f151a3 100644 --- a/src/api/schemas.rs +++ b/src/api/schemas.rs @@ -1,11 +1,11 @@ -use std::{collections::HashMap, io::Bytes}; +use std::{collections::HashMap}; use regex::Regex; -use serde::{ser::SerializeMap, Deserialize, Serialize, Serializer}; +use serde::{Deserialize, Serialize}; use crate::errors::FieldFormatError; -use super::{DiscordFileAttachment, Embed}; +use super::{Embed}; /** A struct that represents a well-formed email address. diff --git a/src/api/types.rs b/src/api/types.rs index 20f3329..606897e 100644 --- a/src/api/types.rs +++ b/src/api/types.rs @@ -4,7 +4,7 @@ https://discord.com/developers/docs . I do not feel like re-documenting all of this, as everything is already perfectly explained there. */ -use std::{collections::HashMap, fs::File}; + use serde::{Deserialize, Serialize}; diff --git a/src/instance.rs b/src/instance.rs index c20eaca..79e2944 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -1,10 +1,10 @@ use crate::api::limits::Limits; -use crate::api::types::{InstancePolicies, User}; +use crate::api::types::{InstancePolicies}; use crate::errors::{FieldFormatError, InstanceServerError}; use crate::limit::LimitedRequester; use crate::URLBundle; -use std::collections::HashMap; + use std::fmt; #[derive(Debug)] From 54944fbb0e9d9b0ba19d2f685503720d44dfdb21 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Sun, 7 May 2023 12:41:14 +0200 Subject: [PATCH 06/16] Run clippy --- src/api/channels/messages.rs | 12 ++++++------ src/api/users/users.rs | 2 +- src/gateway.rs | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/api/channels/messages.rs b/src/api/channels/messages.rs index 6629b1b..251f37a 100644 --- a/src/api/channels/messages.rs +++ b/src/api/channels/messages.rs @@ -45,10 +45,10 @@ pub mod messages { ) .await } else { - return Err(crate::errors::InstanceServerError::InvalidFormBodyError { + Err(crate::errors::InstanceServerError::InvalidFormBodyError { error_type: "Not implemented".to_string(), error: "Not implemented".to_string(), - }); + }) } } } @@ -56,7 +56,7 @@ pub mod messages { impl<'a> User<'a> { pub async fn send_message( &mut self, - mut message: &mut crate::api::schemas::MessageSendSchema, + message: &mut crate::api::schemas::MessageSendSchema, channel_id: &String, files: Option>, ) -> Result { @@ -64,7 +64,7 @@ pub mod messages { Message::send( &self.belongs_to.urls.get_api().to_string(), channel_id, - &mut message, + message, files, &token, self, @@ -77,12 +77,12 @@ pub mod messages { #[cfg(test)] mod test { use crate::{ - api::{AuthUsername, LoginSchema, MessageSendSchema, UserObject}, + api::{AuthUsername, LoginSchema}, instance::Instance, limit::LimitedRequester, }; - use super::*; + #[tokio::test] async fn send_message() { diff --git a/src/api/users/users.rs b/src/api/users/users.rs index 77c38af..35461c1 100644 --- a/src/api/users/users.rs +++ b/src/api/users/users.rs @@ -75,7 +75,7 @@ impl Instance { #[cfg(test)] mod test { - use super::*; + #[tokio::test] async fn get_user() {} diff --git a/src/gateway.rs b/src/gateway.rs index d0a1ca8..9dcee48 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -36,11 +36,11 @@ impl<'a> Gateway<'a> { websocket_url: String, token: String, ) -> Result, tokio_tungstenite::tungstenite::Error> { - return Ok(Gateway { + Ok(Gateway { url: websocket_url, token, events: Events::default(), - }); + }) } } From 11be031e98382fd6e360c343957c5ed9cbe2831e Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Sun, 7 May 2023 12:42:52 +0200 Subject: [PATCH 07/16] Remove logged_in from User --- src/api/channels/messages.rs | 6 +----- src/api/types.rs | 13 ------------- 2 files changed, 1 insertion(+), 18 deletions(-) diff --git a/src/api/channels/messages.rs b/src/api/channels/messages.rs index 251f37a..0c50df8 100644 --- a/src/api/channels/messages.rs +++ b/src/api/channels/messages.rs @@ -2,7 +2,6 @@ pub mod messages { use reqwest::Client; use serde_json::to_string; - use crate::api::types::{Message, PartialDiscordFileAttachment, User}; use crate::limit::LimitedRequester; @@ -82,8 +81,6 @@ mod test { limit::LimitedRequester, }; - - #[tokio::test] async fn send_message() { let channel_id = "1104413094102290492".to_string(); @@ -123,8 +120,7 @@ mod test { let token = login_result.token; let settings = login_result.settings; let limits = instance.limits.clone(); - let mut user = - crate::api::types::User::new(true, &mut instance, token, limits, settings, None); + let mut user = crate::api::types::User::new(&mut instance, token, limits, settings, None); let response = user .send_message(&mut message, &channel_id, None) .await diff --git a/src/api/types.rs b/src/api/types.rs index 606897e..47522ba 100644 --- a/src/api/types.rs +++ b/src/api/types.rs @@ -4,8 +4,6 @@ https://discord.com/developers/docs . I do not feel like re-documenting all of this, as everything is already perfectly explained there. */ - - use serde::{Deserialize, Serialize}; use crate::{api::limits::Limits, instance::Instance}; @@ -156,7 +154,6 @@ pub struct UserObject { #[derive(Debug)] pub struct User<'a> { - pub logged_in: bool, pub belongs_to: &'a mut Instance, token: String, pub limits: Limits, @@ -165,10 +162,6 @@ pub struct User<'a> { } impl<'a> User<'a> { - pub fn is_logged_in(&self) -> bool { - self.logged_in - } - pub fn belongs_to(&mut self) -> &mut Instance { self.belongs_to } @@ -177,16 +170,11 @@ impl<'a> User<'a> { self.token.clone() } - pub fn set_logged_in(&mut self, bool: bool) { - self.logged_in = bool; - } - pub fn set_token(&mut self, token: String) { self.token = token; } pub fn new( - logged_in: bool, belongs_to: &'a mut Instance, token: String, limits: Limits, @@ -194,7 +182,6 @@ impl<'a> User<'a> { object: Option, ) -> User<'a> { User { - logged_in, belongs_to, token, limits, From 702cafc0f5e9b0ace45c7a7a8b816888cf3e6509 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Tue, 9 May 2023 13:10:07 +0200 Subject: [PATCH 08/16] make token pub --- src/api/types.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/types.rs b/src/api/types.rs index 47522ba..cb349bd 100644 --- a/src/api/types.rs +++ b/src/api/types.rs @@ -155,7 +155,7 @@ pub struct UserObject { #[derive(Debug)] pub struct User<'a> { pub belongs_to: &'a mut Instance, - token: String, + pub token: String, pub limits: Limits, pub settings: UserSettings, pub object: Option, From 59be7b1cdea1fcd96336968ef7a3e7720fe98626 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Tue, 9 May 2023 14:04:34 +0200 Subject: [PATCH 09/16] Removed empty lines of code --- src/gateway.rs | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/src/gateway.rs b/src/gateway.rs index 9dcee48..57860bb 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -3,23 +3,6 @@ use crate::api::WebSocketEvent; use crate::errors::ObserverError; use crate::gateway::events::Events; - - - - - - - - - - - - - - - - - /** Represents a Gateway connection. A Gateway connection will create observable [`GatewayEvents`](GatewayEvent), which you can subscribe to. Gateway events include all currently From 15ee53b5f4d4f94785a12168910baee43bbc310d Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Tue, 9 May 2023 14:04:46 +0200 Subject: [PATCH 10/16] Made modules public, removed 110 warnings --- src/lib.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 00170d0..e7699e8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,9 +1,9 @@ -mod api; -mod errors; -mod gateway; -mod instance; -mod limit; -mod voice; +pub mod api; +pub mod errors; +pub mod gateway; +pub mod instance; +pub mod limit; +pub mod voice; use url::{ParseError, Url}; #[derive(Clone, Default, Debug, PartialEq, Eq)] From 5971ce1dbc41bab11dcb08cb069e631da871e114 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Tue, 9 May 2023 14:05:03 +0200 Subject: [PATCH 11/16] Make register and login return User --- src/api/auth/login.rs | 16 ++++++++++++++-- src/api/auth/register.rs | 28 ++++++++++++++++++++++------ 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/src/api/auth/login.rs b/src/api/auth/login.rs index f7c4fe6..ca8e135 100644 --- a/src/api/auth/login.rs +++ b/src/api/auth/login.rs @@ -12,7 +12,7 @@ pub mod login { pub async fn login_account( &mut self, login_schema: &LoginSchema, - ) -> Result { + ) -> Result { let requester = &mut self.requester; let json_schema = json!(login_schema); let client = Client::new(); @@ -49,9 +49,21 @@ pub mod login { return Err(InstanceServerError::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 = crate::api::types::User::new( + self, + login_result.token, + cloned_limits, + login_result.settings, + Some(object), + ); - Ok(login_result) + Ok(user) } } } diff --git a/src/api/auth/register.rs b/src/api/auth/register.rs index b932b9f..2d78742 100644 --- a/src/api/auth/register.rs +++ b/src/api/auth/register.rs @@ -5,7 +5,7 @@ pub mod register { use crate::{ api::{limits::LimitType, schemas::RegisterSchema, types::ErrorResponse}, errors::InstanceServerError, - instance::{Instance, Token}, + instance::Instance, }; impl Instance { @@ -19,7 +19,7 @@ pub mod register { pub async fn register_account( &mut self, register_schema: &RegisterSchema, - ) -> Result { + ) -> Result { let json_schema = json!(register_schema); let limited_requester = &mut self.requester; let client = Client::new(); @@ -55,9 +55,25 @@ pub mod register { } return Err(InstanceServerError::InvalidFormBodyError { error_type, error }); } - Ok(Token { - token: response_text_string, - }) + let user_object = self + .get_user(response_text_string.clone(), None) + .await + .unwrap(); + let settings = crate::api::types::User::get_settings( + &response_text_string, + &self.urls.get_api().to_string(), + &mut self.limits, + ) + .await + .unwrap(); + let user: crate::api::types::User = crate::api::types::User::new( + self, + response_text_string.clone(), + cloned_limits, + settings, + Some(user_object), + ); + Ok(user) } } } @@ -117,7 +133,7 @@ mod test { AuthUsername::new("Hiiii".to_string()).unwrap(), Some(AuthPassword::new("mysupersecurepass123!".to_string()).unwrap()), true, - Some(AuthEmail::new("random978234@aaaa.xyz".to_string()).unwrap()), + Some(AuthEmail::new("three12@aaaa.xyz".to_string()).unwrap()), None, None, Some("2000-01-01".to_string()), From 0ba2f568fd06bf0dc9c1132e4a5ecac05d0caeed Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Tue, 9 May 2023 14:05:36 +0200 Subject: [PATCH 12/16] impl get_settings() --- src/api/users/users.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/api/users/users.rs b/src/api/users/users.rs index 35461c1..8b53b6c 100644 --- a/src/api/users/users.rs +++ b/src/api/users/users.rs @@ -1,7 +1,10 @@ +use reqwest::Client; + use crate::{ api::{ limits::Limits, types::{User, UserObject}, + UserSettings, }, errors::InstanceServerError, instance::Instance, @@ -45,6 +48,29 @@ impl<'a> User<'a> { Err(e) => Err(e), } } + + pub async fn get_settings( + token: &String, + url_api: &String, + instance_limits: &mut Limits, + ) -> Result { + let request: reqwest::RequestBuilder = Client::new() + .get(format!("{}/users/@me/settings/", url_api)) + .bearer_auth(token); + let mut requester = crate::limit::LimitedRequester::new().await; + match requester + .send_request( + request, + crate::api::limits::LimitType::Ip, + instance_limits, + &mut Limits::default(), + ) + .await + { + Ok(result) => Ok(serde_json::from_str(&result.text().await.unwrap()).unwrap()), + Err(e) => Err(e), + } + } } impl Instance { @@ -75,7 +101,6 @@ impl Instance { #[cfg(test)] mod test { - #[tokio::test] async fn get_user() {} From d8c8cd079b73438832d19fd0b3419dff7054ded7 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Tue, 9 May 2023 17:19:04 +0200 Subject: [PATCH 13/16] remove println --- src/api/auth/login.rs | 1 - src/api/channels/messages.rs | 1 - src/api/policies/instance/instance.rs | 1 - src/lib.rs | 1 - src/limit.rs | 1 - 5 files changed, 5 deletions(-) diff --git a/src/api/auth/login.rs b/src/api/auth/login.rs index ca8e135..67647f7 100644 --- a/src/api/auth/login.rs +++ b/src/api/auth/login.rs @@ -116,6 +116,5 @@ mod test { .login_account(&login_schema.unwrap()) .await .unwrap(); - println!("{:?}", login_result); } }*/ diff --git a/src/api/channels/messages.rs b/src/api/channels/messages.rs index 0c50df8..082d822 100644 --- a/src/api/channels/messages.rs +++ b/src/api/channels/messages.rs @@ -125,6 +125,5 @@ mod test { .send_message(&mut message, &channel_id, None) .await .unwrap(); - println!("{:?}", response); } } diff --git a/src/api/policies/instance/instance.rs b/src/api/policies/instance/instance.rs index 754d0b3..b13aa89 100644 --- a/src/api/policies/instance/instance.rs +++ b/src/api/policies/instance/instance.rs @@ -52,6 +52,5 @@ mod instance_policies_schema_test { .unwrap(); let schema = test_instance.instance_policies_schema().await.unwrap(); - println!("{:?}", schema); } } diff --git a/src/lib.rs b/src/lib.rs index e7699e8..b69e360 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,7 +30,6 @@ impl URLBundle { /// # Example: /// ```rs /// let url = parse_url("localhost:3000"); - /// println!("{}", url); /// ``` /// `-> Outputs "http://localhost:3000".` pub fn parse_url(url: String) -> String { diff --git a/src/limit.rs b/src/limit.rs index 0dfbbd3..e2a6a59 100644 --- a/src/limit.rs +++ b/src/limit.rs @@ -330,6 +330,5 @@ mod rate_limit { Err(_) => panic!("Request failed"), }; let config: Config = from_str(result.text().await.unwrap().as_str()).unwrap(); - println!("{:?}", config); } } From 478313507ffd20d9aa0e37c199efe1d6b53359a0 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Tue, 9 May 2023 17:19:23 +0200 Subject: [PATCH 14/16] Extend UserObject to match with Spacebars' User --- src/api/types.rs | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/api/types.rs b/src/api/types.rs index cb349bd..e52a2f8 100644 --- a/src/api/types.rs +++ b/src/api/types.rs @@ -134,22 +134,31 @@ pub struct Error { #[derive(Serialize, Deserialize, Debug, Default)] pub struct UserObject { - id: String, + pub id: String, username: String, discriminator: String, avatar: Option, - bot: Option, + bot: bool, system: Option, mfa_enabled: Option, - banner: Option, accent_color: Option, - locale: String, + locale: Option, verified: Option, email: Option, - flags: i8, - premium_type: Option, + flags: String, + premium_since: Option, + premium_type: i8, pronouns: Option, public_flags: Option, + banner: Option, + bio: String, + theme_colors: Option>, + phone: Option, + nsfw_allowed: bool, + premium: bool, + purchased_flags: i32, + premium_usage_flags: i32, + disabled: bool, } #[derive(Debug)] @@ -864,3 +873,8 @@ pub enum AllowedMentionType { Users, Everyone, } + +#[derive(Debug, Serialize, Deserialize)] +pub struct Token { + pub token: String, +} From 8b09d16542285db0bf52ecf9e1e3d35840dd71e9 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Tue, 9 May 2023 17:19:41 +0200 Subject: [PATCH 15/16] Make register and login return UserObject --- src/api/auth/register.rs | 56 ++++++++-------------------------------- src/api/users/users.rs | 11 +++++--- 2 files changed, 19 insertions(+), 48 deletions(-) diff --git a/src/api/auth/register.rs b/src/api/auth/register.rs index 2d78742..be4b56b 100644 --- a/src/api/auth/register.rs +++ b/src/api/auth/register.rs @@ -1,9 +1,9 @@ pub mod register { use reqwest::Client; - use serde_json::json; + use serde_json::{from_str, json}; use crate::{ - api::{limits::LimitType, schemas::RegisterSchema, types::ErrorResponse}, + api::{limits::LimitType, schemas::RegisterSchema, types::ErrorResponse, Token}, errors::InstanceServerError, instance::Instance, }; @@ -43,9 +43,12 @@ pub mod register { let response_unwrap = response.unwrap(); let status = response_unwrap.status(); - let response_text_string = response_unwrap.text().await.unwrap(); + let response_unwrap_text = response_unwrap.text().await.unwrap(); + println!("{}", response_unwrap_text); + let token = from_str::(&response_unwrap_text).unwrap(); + let token = token.token; if status.is_client_error() { - let json: ErrorResponse = serde_json::from_str(&response_text_string).unwrap(); + 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() { @@ -55,12 +58,9 @@ pub mod register { } return Err(InstanceServerError::InvalidFormBodyError { error_type, error }); } - let user_object = self - .get_user(response_text_string.clone(), None) - .await - .unwrap(); + let user_object = self.get_user(token.clone(), None).await.unwrap(); let settings = crate::api::types::User::get_settings( - &response_text_string, + &token, &self.urls.get_api().to_string(), &mut self.limits, ) @@ -68,7 +68,7 @@ pub mod register { .unwrap(); let user: crate::api::types::User = crate::api::types::User::new( self, - response_text_string.clone(), + token.clone(), cloned_limits, settings, Some(user_object), @@ -81,42 +81,9 @@ pub mod register { #[cfg(test)] mod test { use crate::api::schemas::{AuthEmail, AuthPassword, AuthUsername, RegisterSchema}; - use crate::errors::InstanceServerError; use crate::instance::Instance; use crate::limit::LimitedRequester; use crate::URLBundle; - #[tokio::test] - async fn test_incomplete_registration() { - let urls = URLBundle::new( - "http://localhost:3001/api".to_string(), - "http://localhost:3001".to_string(), - "http://localhost:3001".to_string(), - ); - let limited_requester = LimitedRequester::new().await; - let mut test_instance = Instance::new(urls.clone(), limited_requester) - .await - .unwrap(); - let reg = RegisterSchema::new( - AuthUsername::new("hiiii".to_string()).unwrap(), - None, - true, - Some(AuthEmail::new("me@mail.xy".to_string()).unwrap()), - None, - None, - None, - None, - None, - None, - ) - .unwrap(); - assert_eq!( - InstanceServerError::InvalidFormBodyError { - error_type: "date_of_birth".to_string(), - error: "This field is required (BASE_TYPE_REQUIRED)".to_string() - }, - test_instance.register_account(®).await.err().unwrap() - ); - } #[tokio::test] async fn test_registration() { @@ -133,7 +100,7 @@ mod test { AuthUsername::new("Hiiii".to_string()).unwrap(), Some(AuthPassword::new("mysupersecurepass123!".to_string()).unwrap()), true, - Some(AuthEmail::new("three12@aaaa.xyz".to_string()).unwrap()), + Some(AuthEmail::new("four5@aaaa.xyz".to_string()).unwrap()), None, None, Some("2000-01-01".to_string()), @@ -143,6 +110,5 @@ mod test { ) .unwrap(); let token = test_instance.register_account(®).await.unwrap().token; - println!("{}", token); } } diff --git a/src/api/users/users.rs b/src/api/users/users.rs index 8b53b6c..88a68ca 100644 --- a/src/api/users/users.rs +++ b/src/api/users/users.rs @@ -35,16 +35,20 @@ impl<'a> User<'a> { } let request = reqwest::Client::new().get(url).bearer_auth(token); let mut requester = crate::limit::LimitedRequester::new().await; + let mut cloned_limits = instance_limits.clone(); match requester .send_request( request, crate::api::limits::LimitType::Ip, instance_limits, - &mut Limits::default(), + &mut cloned_limits, ) .await { - Ok(result) => Ok(serde_json::from_str(&result.text().await.unwrap()).unwrap()), + Ok(result) => { + let result_text = result.text().await.unwrap(); + Ok(serde_json::from_str::(&result_text).unwrap()) + } Err(e) => Err(e), } } @@ -57,13 +61,14 @@ impl<'a> User<'a> { let request: reqwest::RequestBuilder = Client::new() .get(format!("{}/users/@me/settings/", url_api)) .bearer_auth(token); + let mut cloned_limits = instance_limits.clone(); let mut requester = crate::limit::LimitedRequester::new().await; match requester .send_request( request, crate::api::limits::LimitType::Ip, instance_limits, - &mut Limits::default(), + &mut cloned_limits, ) .await { From 38d9c3ad031a68d0a68cd53260847274c94ccc90 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Tue, 9 May 2023 19:30:52 +0200 Subject: [PATCH 16/16] Change test_registration --- src/api/auth/register.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/auth/register.rs b/src/api/auth/register.rs index be4b56b..186be78 100644 --- a/src/api/auth/register.rs +++ b/src/api/auth/register.rs @@ -100,7 +100,7 @@ mod test { AuthUsername::new("Hiiii".to_string()).unwrap(), Some(AuthPassword::new("mysupersecurepass123!".to_string()).unwrap()), true, - Some(AuthEmail::new("four5@aaaa.xyz".to_string()).unwrap()), + Some(AuthEmail::new("four7@aaaa.xyz".to_string()).unwrap()), None, None, Some("2000-01-01".to_string()),