Split up schemas.rs

This commit is contained in:
bitfl0wer 2023-04-25 17:32:30 +02:00
parent ee0d9f2b67
commit 6f2dac6695
7 changed files with 425 additions and 423 deletions

View File

@ -3,7 +3,8 @@ pub mod login {
use serde_json::{from_str, json};
use crate::api::limits::LimitType;
use crate::api::schemas::schemas::{ErrorResponse, LoginResult, LoginSchema};
use crate::api::schemas::LoginSchema;
use crate::api::types::{ErrorResponse, LoginResult};
use crate::errors::InstanceServerError;
use crate::instance::Instance;

View File

@ -3,10 +3,7 @@ pub mod register {
use serde_json::json;
use crate::{
api::{
limits::LimitType,
schemas::schemas::{ErrorResponse, RegisterSchema},
},
api::{limits::LimitType, schemas::RegisterSchema, types::ErrorResponse},
errors::InstanceServerError,
instance::{Instance, Token},
};
@ -67,7 +64,7 @@ pub mod register {
#[cfg(test)]
mod test {
use crate::api::schemas::schemas::{AuthEmail, AuthPassword, AuthUsername, RegisterSchema};
use crate::api::schemas::{AuthEmail, AuthPassword, AuthUsername, RegisterSchema};
use crate::errors::InstanceServerError;
use crate::instance::Instance;
use crate::limit::LimitedRequester;

View File

@ -1,7 +1,9 @@
pub mod auth;
pub mod policies;
pub mod schemas;
pub mod types;
pub use policies::instance::instance::*;
pub use policies::instance::limits::*;
pub use schemas::*;
pub use types::*;

View File

@ -3,7 +3,7 @@ pub mod instance {
use serde_json::from_str;
use crate::errors::InstanceServerError;
use crate::{api::schemas::schemas::InstancePoliciesSchema, instance::Instance};
use crate::{api::types::InstancePolicies, instance::Instance};
impl Instance {
/**
@ -13,7 +13,7 @@ pub mod instance {
*/
pub async fn instance_policies_schema(
&self,
) -> Result<InstancePoliciesSchema, InstanceServerError> {
) -> Result<InstancePolicies, InstanceServerError> {
let client = Client::new();
let endpoint_url = self.urls.get_api().to_string() + "/policies/instance/";
let request = match client.get(&endpoint_url).send().await {
@ -33,7 +33,7 @@ pub mod instance {
}
let body = request.text().await.unwrap();
let instance_policies_schema: InstancePoliciesSchema = from_str(&body).unwrap();
let instance_policies_schema: InstancePolicies = from_str(&body).unwrap();
Ok(instance_policies_schema)
}
}

View File

@ -1,19 +1,17 @@
pub mod schemas {
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fmt};
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::{api::limits::Limits, errors::FieldFormatError, URLBundle};
use crate::errors::FieldFormatError;
/**
A struct that represents a well-formed email address.
/**
A struct that represents a well-formed email address.
*/
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct AuthEmail {
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct AuthEmail {
pub email: String,
}
}
impl AuthEmail {
impl AuthEmail {
/**
Returns a new [`Result<AuthEmail, FieldFormatError>`].
## Arguments
@ -30,22 +28,22 @@ pub mod schemas {
}
return Ok(AuthEmail { email });
}
}
}
/**
A struct that represents a well-formed username.
## Arguments
Please use new() to create a new instance of this struct.
## Errors
You will receive a [`FieldFormatError`], if:
- The username is not between 2 and 32 characters.
/**
A struct that represents a well-formed username.
## Arguments
Please use new() to create a new instance of this struct.
## Errors
You will receive a [`FieldFormatError`], if:
- The username is not between 2 and 32 characters.
*/
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct AuthUsername {
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct AuthUsername {
pub username: String,
}
}
impl AuthUsername {
impl AuthUsername {
/**
Returns a new [`Result<AuthUsername, FieldFormatError>`].
## Arguments
@ -61,22 +59,22 @@ pub mod schemas {
return Ok(AuthUsername { username });
}
}
}
}
/**
A struct that represents a well-formed password.
## Arguments
Please use new() to create a new instance of this struct.
## Errors
You will receive a [`FieldFormatError`], if:
- The password is not between 1 and 72 characters.
/**
A struct that represents a well-formed password.
## Arguments
Please use new() to create a new instance of this struct.
## Errors
You will receive a [`FieldFormatError`], if:
- The password is not between 1 and 72 characters.
*/
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct AuthPassword {
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct AuthPassword {
pub password: String,
}
}
impl AuthPassword {
impl AuthPassword {
/**
Returns a new [`Result<AuthPassword, FieldFormatError>`].
## Arguments
@ -92,21 +90,21 @@ pub mod schemas {
return Ok(AuthPassword { password });
}
}
}
}
/**
A struct that represents a well-formed register request.
## Arguments
Please use new() to create a new instance of this struct.
## Errors
You will receive a [`FieldFormatError`], if:
- The username is not between 2 and 32 characters.
- The password is not between 1 and 72 characters.
/**
A struct that represents a well-formed register request.
## Arguments
Please use new() to create a new instance of this struct.
## Errors
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 {
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct RegisterSchema {
username: String,
password: Option<String>,
consent: bool,
@ -117,9 +115,9 @@ pub mod schemas {
gift_code_sku_id: Option<String>,
captcha_key: Option<String>,
promotional_email_opt_in: Option<bool>,
}
}
impl RegisterSchema {
impl RegisterSchema {
/**
Returns a new [`Result<RegisterSchema, FieldFormatError>`].
## Arguments
@ -177,29 +175,29 @@ pub mod schemas {
promotional_email_opt_in,
});
}
}
}
/**
A struct that represents a well-formed login request.
## Arguments
Please use new() to create a new instance of this struct.
## Errors
You will receive a [`FieldFormatError`], if:
- The username is not between 2 and 32 characters.
- The password is not between 1 and 72 characters.
/**
A struct that represents a well-formed login request.
## Arguments
Please use new() to create a new instance of this struct.
## Errors
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 LoginSchema {
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct LoginSchema {
login: String,
password: String,
undelete: Option<bool>,
captcha_key: Option<String>,
login_source: Option<String>,
gift_code_sku_id: Option<String>,
}
}
impl LoginSchema {
impl LoginSchema {
/**
Returns a new [`Result<LoginSchema, FieldFormatError>`].
## Arguments
@ -231,235 +229,22 @@ pub mod schemas {
gift_code_sku_id,
});
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LoginResult {
token: String,
settings: UserSettings,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct UserSettings {
afk_timeout: i32,
allow_accessibility_detection: bool,
animate_emoji: bool,
animate_stickers: i32,
contact_sync_enabled: bool,
convert_emoticons: bool,
custom_status: Option<String>,
default_guilds_restricted: bool,
detect_platform_accounts: bool,
developer_mode: bool,
disable_games_tab: bool,
enable_tts_command: bool,
explicit_content_filter: i32,
friend_source_flags: FriendSourceFlags,
friend_discovery_flags: Option<i32>,
gateway_connected: bool,
gif_auto_play: bool,
guild_folders: Vec<GuildFolder>,
guild_positions: Vec<i64>,
inline_attachment_media: bool,
inline_embed_media: bool,
locale: String,
message_display_compact: bool,
native_phone_integration_enabled: bool,
render_embeds: bool,
render_reactions: bool,
restricted_guilds: Vec<i64>,
show_current_game: bool,
status: String,
stream_notifications_enabled: bool,
theme: String,
timezone_offset: i32,
view_nsfw_guilds: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FriendSourceFlags {
all: Option<bool>,
mutual_friends: Option<bool>,
mutual_guilds: Option<bool>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GuildFolder {
id: String,
guild_ids: Vec<i64>,
name: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct TotpSchema {
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct TotpSchema {
code: String,
ticket: String,
gift_code_sku_id: Option<String>,
login_source: Option<String>,
}
/**
Represents the result you get from GET: /api/instance/policies/.
*/
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct InstancePoliciesSchema {
instance_name: String,
instance_description: Option<String>,
front_page: Option<String>,
tos_page: Option<String>,
correspondence_email: Option<String>,
correspondence_user_id: Option<String>,
image: Option<String>,
instance_id: Option<String>,
}
impl InstancePoliciesSchema {
pub fn new(
instance_name: String,
instance_description: Option<String>,
front_page: Option<String>,
tos_page: Option<String>,
correspondence_email: Option<String>,
correspondence_user_id: Option<String>,
image: Option<String>,
instance_id: Option<String>,
) -> Self {
InstancePoliciesSchema {
instance_name,
instance_description,
front_page,
tos_page,
correspondence_email,
correspondence_user_id,
image,
instance_id,
}
}
}
impl fmt::Display for InstancePoliciesSchema {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"InstancePoliciesSchema {{ instance_name: {}, instance_description: {}, front_page: {}, tos_page: {}, correspondence_email: {}, correspondence_user_id: {}, image: {}, instance_id: {} }}",
self.instance_name,
self.instance_description.clone().unwrap_or("None".to_string()),
self.front_page.clone().unwrap_or("None".to_string()),
self.tos_page.clone().unwrap_or("None".to_string()),
self.correspondence_email.clone().unwrap_or("None".to_string()),
self.correspondence_user_id.clone().unwrap_or("None".to_string()),
self.image.clone().unwrap_or("None".to_string()),
self.instance_id.clone().unwrap_or("None".to_string()),
)
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ErrorResponse {
pub code: i32,
pub message: String,
pub errors: IntermittentError,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct IntermittentError {
#[serde(flatten)]
pub errors: std::collections::HashMap<String, ErrorField>,
}
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct ErrorField {
#[serde(default)]
pub _errors: Vec<Error>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Error {
pub message: String,
pub code: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct UserObject {
id: String,
username: String,
discriminator: String,
avatar: Option<String>,
bot: Option<bool>,
system: Option<bool>,
mfa_enabled: Option<bool>,
banner: Option<bool>,
accent_color: Option<String>,
locale: String,
verified: Option<bool>,
email: Option<String>,
flags: i8,
premium_type: Option<i8>,
public_flags: Option<i8>,
}
#[derive(Debug)]
pub struct User {
logged_in: bool,
belongs_to: URLBundle,
token: String,
rate_limits: Limits,
pub settings: UserSettings,
pub object: UserObject,
}
impl User {
pub fn is_logged_in(&self) -> bool {
if self.logged_in == true {
true
} else {
false
}
}
pub fn belongs_to(&self) -> URLBundle {
return self.belongs_to.clone();
}
pub fn token(&self) -> String {
return 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: URLBundle,
token: String,
rate_limits: Limits,
settings: UserSettings,
object: UserObject,
) -> User {
User {
logged_in,
belongs_to,
token,
rate_limits,
settings,
object,
}
}
}
}
// I know that some of these tests are... really really basic and unneccessary, but sometimes, I
// just feel like writing tests, so there you go :) -@bitfl0wer
#[cfg(test)]
mod schemas_tests {
use super::schemas::*;
use super::*;
use crate::errors::FieldFormatError;
#[test]

217
src/api/types.rs Normal file
View File

@ -0,0 +1,217 @@
use std::fmt;
use serde::{Deserialize, Serialize};
use crate::{api::limits::Limits, URLBundle};
#[derive(Debug, Serialize, Deserialize)]
pub struct LoginResult {
token: String,
settings: UserSettings,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct UserSettings {
afk_timeout: i32,
allow_accessibility_detection: bool,
animate_emoji: bool,
animate_stickers: i32,
contact_sync_enabled: bool,
convert_emoticons: bool,
custom_status: Option<String>,
default_guilds_restricted: bool,
detect_platform_accounts: bool,
developer_mode: bool,
disable_games_tab: bool,
enable_tts_command: bool,
explicit_content_filter: i32,
friend_source_flags: FriendSourceFlags,
friend_discovery_flags: Option<i32>,
gateway_connected: bool,
gif_auto_play: bool,
guild_folders: Vec<GuildFolder>,
guild_positions: Vec<i64>,
inline_attachment_media: bool,
inline_embed_media: bool,
locale: String,
message_display_compact: bool,
native_phone_integration_enabled: bool,
render_embeds: bool,
render_reactions: bool,
restricted_guilds: Vec<i64>,
show_current_game: bool,
status: String,
stream_notifications_enabled: bool,
theme: String,
timezone_offset: i32,
view_nsfw_guilds: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FriendSourceFlags {
all: Option<bool>,
mutual_friends: Option<bool>,
mutual_guilds: Option<bool>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GuildFolder {
id: String,
guild_ids: Vec<i64>,
name: String,
}
/**
Represents the result you get from GET: /api/instance/policies/.
*/
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct InstancePolicies {
instance_name: String,
instance_description: Option<String>,
front_page: Option<String>,
tos_page: Option<String>,
correspondence_email: Option<String>,
correspondence_user_id: Option<String>,
image: Option<String>,
instance_id: Option<String>,
}
impl InstancePolicies {
pub fn new(
instance_name: String,
instance_description: Option<String>,
front_page: Option<String>,
tos_page: Option<String>,
correspondence_email: Option<String>,
correspondence_user_id: Option<String>,
image: Option<String>,
instance_id: Option<String>,
) -> Self {
InstancePolicies {
instance_name,
instance_description,
front_page,
tos_page,
correspondence_email,
correspondence_user_id,
image,
instance_id,
}
}
}
impl fmt::Display for InstancePolicies {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"InstancePoliciesSchema {{ instance_name: {}, instance_description: {}, front_page: {}, tos_page: {}, correspondence_email: {}, correspondence_user_id: {}, image: {}, instance_id: {} }}",
self.instance_name,
self.instance_description.clone().unwrap_or("None".to_string()),
self.front_page.clone().unwrap_or("None".to_string()),
self.tos_page.clone().unwrap_or("None".to_string()),
self.correspondence_email.clone().unwrap_or("None".to_string()),
self.correspondence_user_id.clone().unwrap_or("None".to_string()),
self.image.clone().unwrap_or("None".to_string()),
self.instance_id.clone().unwrap_or("None".to_string()),
)
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ErrorResponse {
pub code: i32,
pub message: String,
pub errors: IntermittentError,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct IntermittentError {
#[serde(flatten)]
pub errors: std::collections::HashMap<String, ErrorField>,
}
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct ErrorField {
#[serde(default)]
pub _errors: Vec<Error>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Error {
pub message: String,
pub code: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct UserObject {
id: String,
username: String,
discriminator: String,
avatar: Option<String>,
bot: Option<bool>,
system: Option<bool>,
mfa_enabled: Option<bool>,
banner: Option<bool>,
accent_color: Option<String>,
locale: String,
verified: Option<bool>,
email: Option<String>,
flags: i8,
premium_type: Option<i8>,
public_flags: Option<i8>,
}
#[derive(Debug)]
pub struct User {
logged_in: bool,
belongs_to: URLBundle,
token: String,
rate_limits: Limits,
pub settings: UserSettings,
pub object: UserObject,
}
impl User {
pub fn is_logged_in(&self) -> bool {
if self.logged_in == true {
true
} else {
false
}
}
pub fn belongs_to(&self) -> URLBundle {
return self.belongs_to.clone();
}
pub fn token(&self) -> String {
return 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: URLBundle,
token: String,
rate_limits: Limits,
settings: UserSettings,
object: UserObject,
) -> User {
User {
logged_in,
belongs_to,
token,
rate_limits,
settings,
object,
}
}
}

View File

@ -1,5 +1,5 @@
use crate::api::limits::{Limit, LimitType, Limits};
use crate::api::schemas::schemas::{InstancePoliciesSchema, User};
use crate::api::limits::Limits;
use crate::api::types::{InstancePolicies, User};
use crate::errors::{FieldFormatError, InstanceServerError};
use crate::limit::LimitedRequester;
use crate::URLBundle;
@ -13,7 +13,7 @@ The [`Instance`] what you will be using to perform all sorts of actions on the S
*/
pub struct Instance {
pub urls: URLBundle,
pub instance_info: InstancePoliciesSchema,
pub instance_info: InstancePolicies,
pub requester: LimitedRequester,
pub limits: Limits,
//pub gateway: Gateway,
@ -34,7 +34,7 @@ impl Instance {
let users: HashMap<Token, User> = HashMap::new();
let mut instance = Instance {
urls: urls.clone(),
instance_info: InstancePoliciesSchema::new(
instance_info: InstancePolicies::new(
// This is okay, because the instance_info will be overwritten by the instance_policies_schema() function.
"".to_string(),
None,