Merge pull request #83 from polyphony-chat/refactor/less-boilerplate

Refactor/less boilerplate
This commit is contained in:
Flori 2023-05-30 23:11:47 +02:00 committed by GitHub
commit db1afb4578
7 changed files with 148 additions and 163 deletions

View File

@ -4,28 +4,31 @@ use serde_json::{from_str, to_string};
use crate::{ use crate::{
api::limits::Limits, api::limits::Limits,
errors::InstanceServerError, errors::InstanceServerError,
instance::UserMeta,
limit::LimitedRequester, limit::LimitedRequester,
types::{Channel, ChannelModifySchema}, types::{Channel, ChannelModifySchema},
}; };
impl Channel { impl Channel {
pub async fn get( pub async fn get(
token: &str, user: &mut UserMeta,
url_api: &str,
channel_id: &str, channel_id: &str,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Result<Channel, InstanceServerError> { ) -> Result<Channel, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
let request = Client::new() let request = Client::new()
.get(format!("{}/channels/{}/", url_api, channel_id)) .get(format!(
.bearer_auth(token); "{}/channels/{}/",
belongs_to.urls.get_api(),
channel_id
))
.bearer_auth(user.token());
let mut requester = LimitedRequester::new().await; let mut requester = LimitedRequester::new().await;
let result = match requester let result = match requester
.send_request( .send_request(
request, request,
crate::api::limits::LimitType::Guild, crate::api::limits::LimitType::Guild,
limits_instance, &mut belongs_to.limits,
limits_user, &mut user.limits,
) )
.await .await
{ {
@ -36,7 +39,7 @@ impl Channel {
match from_str::<Channel>(&result_text) { match from_str::<Channel>(&result_text) {
Ok(object) => Ok(object), Ok(object) => Ok(object),
Err(e) => Err(InstanceServerError::RequestErrorError { Err(e) => Err(InstanceServerError::RequestErrorError {
url: format!("{}/channels/{}/", url_api, channel_id), url: format!("{}/channels/{}/", belongs_to.urls.get_api(), channel_id),
error: e.to_string(), error: e.to_string(),
}), }),
} }
@ -55,23 +58,22 @@ impl Channel {
/// # Returns /// # Returns
/// ///
/// An `Option` that contains an `InstanceServerError` if an error occurred during the request, or `None` if the request was successful. /// An `Option` that contains an `InstanceServerError` if an error occurred during the request, or `None` if the request was successful.
pub async fn delete( pub async fn delete(self, user: &mut UserMeta) -> Option<InstanceServerError> {
self, let mut belongs_to = user.belongs_to.borrow_mut();
token: &str,
url_api: &str,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Option<InstanceServerError> {
let request = Client::new() let request = Client::new()
.delete(format!("{}/channels/{}/", url_api, self.id.to_string())) .delete(format!(
.bearer_auth(token); "{}/channels/{}/",
belongs_to.urls.get_api(),
self.id.to_string()
))
.bearer_auth(user.token());
match LimitedRequester::new() match LimitedRequester::new()
.await .await
.send_request( .send_request(
request, request,
crate::api::limits::LimitType::Channel, crate::api::limits::LimitType::Channel,
limits_instance, &mut belongs_to.limits,
limits_user, &mut user.limits,
) )
.await .await
{ {
@ -96,23 +98,25 @@ impl Channel {
/// A `Result` that contains a `Channel` object if the request was successful, or an `InstanceServerError` if an error occurred during the request. /// A `Result` that contains a `Channel` object if the request was successful, or an `InstanceServerError` if an error occurred during the request.
pub async fn modify( pub async fn modify(
modify_data: ChannelModifySchema, modify_data: ChannelModifySchema,
token: &str,
url_api: &str,
channel_id: &str, channel_id: &str,
limits_user: &mut Limits, user: &mut UserMeta,
limits_instance: &mut Limits,
) -> Result<Channel, InstanceServerError> { ) -> Result<Channel, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
let request = Client::new() let request = Client::new()
.patch(format!("{}/channels/{}/", url_api, channel_id)) .patch(format!(
.bearer_auth(token) "{}/channels/{}/",
belongs_to.urls.get_api(),
channel_id
))
.bearer_auth(user.token())
.body(to_string(&modify_data).unwrap()); .body(to_string(&modify_data).unwrap());
let channel = match LimitedRequester::new() let channel = match LimitedRequester::new()
.await .await
.send_request( .send_request(
request, request,
crate::api::limits::LimitType::Channel, crate::api::limits::LimitType::Channel,
limits_instance, &mut belongs_to.limits,
limits_user, &mut user.limits,
) )
.await .await
{ {

View File

@ -4,7 +4,6 @@ pub mod messages {
use reqwest::{multipart, Client}; use reqwest::{multipart, Client};
use serde_json::to_string; use serde_json::to_string;
use crate::api::limits::Limits;
use crate::instance::UserMeta; use crate::instance::UserMeta;
use crate::limit::LimitedRequester; use crate::limit::LimitedRequester;
use crate::types::{Message, MessageSendSchema, PartialDiscordFileAttachment}; use crate::types::{Message, MessageSendSchema, PartialDiscordFileAttachment};
@ -21,28 +20,27 @@ pub mod messages {
# Errors # Errors
* [`InstanceServerError`] - If the message cannot be sent. * [`InstanceServerError`] - If the message cannot be sent.
*/ */
pub async fn send<'a>( pub async fn send(
url_api: String, user: &mut UserMeta,
channel_id: String, channel_id: String,
message: &mut MessageSendSchema, message: &mut MessageSendSchema,
files: Option<Vec<PartialDiscordFileAttachment>>, files: Option<Vec<PartialDiscordFileAttachment>>,
token: String,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> { ) -> Result<reqwest::Response, crate::errors::InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
let url_api = belongs_to.urls.get_api();
let mut requester = LimitedRequester::new().await; let mut requester = LimitedRequester::new().await;
if files.is_none() { if files.is_none() {
let message_request = Client::new() let message_request = Client::new()
.post(format!("{}/channels/{}/messages/", url_api, channel_id)) .post(format!("{}/channels/{}/messages/", url_api, channel_id))
.bearer_auth(token) .bearer_auth(user.token())
.body(to_string(message).unwrap()); .body(to_string(message).unwrap());
requester requester
.send_request( .send_request(
message_request, message_request,
crate::api::limits::LimitType::Channel, crate::api::limits::LimitType::Channel,
limits_instance, &mut belongs_to.limits,
limits_user, &mut user.limits,
) )
.await .await
} else { } else {
@ -75,15 +73,15 @@ pub mod messages {
let message_request = Client::new() let message_request = Client::new()
.post(format!("{}/channels/{}/messages/", url_api, channel_id)) .post(format!("{}/channels/{}/messages/", url_api, channel_id))
.bearer_auth(token) .bearer_auth(user.token())
.multipart(form); .multipart(form);
requester requester
.send_request( .send_request(
message_request, message_request,
crate::api::limits::LimitType::Channel, crate::api::limits::LimitType::Channel,
limits_instance, &mut belongs_to.limits,
limits_user, &mut user.limits,
) )
.await .await
} }
@ -91,24 +89,25 @@ pub mod messages {
} }
impl UserMeta { impl UserMeta {
/// Shorthand call for Message::send()
/**
Sends a message to the Spacebar server.
# Arguments
* `url_api` - The URL of the Spacebar server's API.
* `message` - The [`Message`] that will be sent to the Spacebar server.
* `limits_user` - The [`Limits`] of the user.
* `limits_instance` - The [`Limits`] of the instance.
* `requester` - The [`LimitedRequester`] that will be used to make requests to the Spacebar server.
# Errors
* [`InstanceServerError`] - If the message cannot be sent.
*/
pub async fn send_message( pub async fn send_message(
&mut self, &mut self,
message: &mut MessageSendSchema, message: &mut MessageSendSchema,
channel_id: String, channel_id: String,
files: Option<Vec<PartialDiscordFileAttachment>>, files: Option<Vec<PartialDiscordFileAttachment>>,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> { ) -> Result<reqwest::Response, crate::errors::InstanceServerError> {
let token = self.token().clone(); Message::send(self, channel_id, message, files).await
let mut belongs_to = self.belongs_to.borrow_mut();
Message::send(
belongs_to.urls.get_api().to_string(),
channel_id,
message,
files,
token,
&mut self.limits,
&mut belongs_to.limits,
)
.await
} }
} }
} }

View File

@ -27,12 +27,10 @@ impl Guild {
/// ///
pub async fn create( pub async fn create(
user: &mut UserMeta, user: &mut UserMeta,
url_api: &str,
guild_create_schema: GuildCreateSchema, guild_create_schema: GuildCreateSchema,
) -> Result<Guild, crate::errors::InstanceServerError> { ) -> Result<Guild, crate::errors::InstanceServerError> {
let url = format!("{}/guilds/", url_api); let mut belongs_to = user.belongs_to.borrow_mut();
let mut limits_user = user.limits.get_as_mut(); let url = format!("{}/guilds/", belongs_to.urls.get_api());
let mut limits_instance = &mut user.belongs_to.borrow_mut().limits;
let request = reqwest::Client::new() let request = reqwest::Client::new()
.post(url.clone()) .post(url.clone())
.bearer_auth(user.token.clone()) .bearer_auth(user.token.clone())
@ -42,8 +40,8 @@ impl Guild {
.send_request( .send_request(
request, request,
crate::api::limits::LimitType::Guild, crate::api::limits::LimitType::Guild,
limits_instance, &mut belongs_to.limits,
limits_user, &mut user.limits,
) )
.await .await
{ {
@ -51,12 +49,12 @@ impl Guild {
Err(e) => return Err(e), Err(e) => return Err(e),
}; };
let id: GuildCreateResponse = from_str(&result.text().await.unwrap()).unwrap(); let id: GuildCreateResponse = from_str(&result.text().await.unwrap()).unwrap();
let guild = Guild::get( let guild = Guild::_get(
url_api, belongs_to.clone().urls.get_api(),
&id.id, &id.id,
&user.token, &user.token,
&mut limits_user, &mut user.limits,
&mut limits_instance, &mut belongs_to.limits,
) )
.await .await
.unwrap(); .unwrap();
@ -87,14 +85,9 @@ impl Guild {
/// None => println!("Guild deleted successfully"), /// None => println!("Guild deleted successfully"),
/// } /// }
/// ``` /// ```
pub async fn delete( pub async fn delete(user: &mut UserMeta, guild_id: &str) -> Option<InstanceServerError> {
user: &mut UserMeta, let mut belongs_to = user.belongs_to.borrow_mut();
url_api: &str, let url = format!("{}/guilds/{}/delete/", belongs_to.urls.get_api(), guild_id);
guild_id: &str,
) -> Option<InstanceServerError> {
let url = format!("{}/guilds/{}/delete/", url_api, guild_id);
let limits_user = user.limits.get_as_mut();
let limits_instance = &mut user.belongs_to.borrow_mut().limits;
let request = reqwest::Client::new() let request = reqwest::Client::new()
.post(url.clone()) .post(url.clone())
.bearer_auth(user.token.clone()); .bearer_auth(user.token.clone());
@ -103,8 +96,8 @@ impl Guild {
.send_request( .send_request(
request, request,
crate::api::limits::LimitType::Guild, crate::api::limits::LimitType::Guild,
limits_instance, &mut belongs_to.limits,
limits_user, &mut user.limits,
) )
.await; .await;
if result.is_err() { if result.is_err() {
@ -129,19 +122,17 @@ impl Guild {
/// A `Result` containing a `reqwest::Response` if the request was successful, or an `InstanceServerError` if there was an error. /// A `Result` containing a `reqwest::Response` if the request was successful, or an `InstanceServerError` if there was an error.
pub async fn create_channel( pub async fn create_channel(
&self, &self,
url_api: &str, user: &mut UserMeta,
token: &str,
schema: ChannelCreateSchema, schema: ChannelCreateSchema,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Result<Channel, InstanceServerError> { ) -> Result<Channel, InstanceServerError> {
Channel::create( let mut belongs_to = user.belongs_to.borrow_mut();
token, Channel::_create(
url_api, &user.token,
&format!("{}", belongs_to.urls.get_api()),
&self.id.to_string(), &self.id.to_string(),
schema, schema,
limits_user, &mut user.limits,
limits_instance, &mut belongs_to.limits,
) )
.await .await
} }
@ -155,27 +146,22 @@ impl Guild {
/// * `limits_user` - A mutable reference to a `Limits` struct containing the user's rate limits. /// * `limits_user` - A mutable reference to a `Limits` struct containing the user's rate limits.
/// * `limits_instance` - A mutable reference to a `Limits` struct containing the instance's rate limits. /// * `limits_instance` - A mutable reference to a `Limits` struct containing the instance's rate limits.
/// ///
pub async fn channels( pub async fn channels(&self, user: &mut UserMeta) -> Result<Vec<Channel>, InstanceServerError> {
&self, let mut belongs_to = user.belongs_to.borrow_mut();
url_api: &str,
token: &str,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Result<Vec<Channel>, InstanceServerError> {
let request = Client::new() let request = Client::new()
.get(format!( .get(format!(
"{}/guilds/{}/channels/", "{}/guilds/{}/channels/",
url_api, belongs_to.urls.get_api(),
self.id.to_string() self.id.to_string()
)) ))
.bearer_auth(token); .bearer_auth(user.token());
let result = match LimitedRequester::new() let result = match LimitedRequester::new()
.await .await
.send_request( .send_request(
request, request,
crate::api::limits::LimitType::Guild, crate::api::limits::LimitType::Guild,
limits_instance, &mut belongs_to.limits,
limits_user, &mut user.limits,
) )
.await .await
{ {
@ -210,7 +196,21 @@ impl Guild {
/// * `limits_user` - A mutable reference to a `Limits` struct containing the user's rate limits. /// * `limits_user` - A mutable reference to a `Limits` struct containing the user's rate limits.
/// * `limits_instance` - A mutable reference to a `Limits` struct containing the instance's rate limits. /// * `limits_instance` - A mutable reference to a `Limits` struct containing the instance's rate limits.
/// ///
pub async fn get( pub async fn get(user: &mut UserMeta, guild_id: &str) -> Result<Guild, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
Guild::_get(
&format!("{}", belongs_to.urls.get_api()),
guild_id,
&user.token,
&mut user.limits,
&mut belongs_to.limits,
)
.await
}
/// For internal use. Does the same as the public get method, but does not require a second, mutable
/// borrow of `UserMeta::belongs_to`, when used in conjunction with other methods, which borrow `UserMeta::belongs_to`.
async fn _get(
url_api: &str, url_api: &str,
guild_id: &str, guild_id: &str,
token: &str, token: &str,
@ -254,6 +254,23 @@ impl Channel {
/// ///
/// A `Result` containing a `reqwest::Response` if the request was successful, or an `InstanceServerError` if there was an error. /// A `Result` containing a `reqwest::Response` if the request was successful, or an `InstanceServerError` if there was an error.
pub async fn create( pub async fn create(
user: &mut UserMeta,
guild_id: &str,
schema: ChannelCreateSchema,
) -> Result<Channel, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
Channel::_create(
&user.token,
&format!("{}", belongs_to.urls.get_api()),
guild_id,
schema,
&mut user.limits,
&mut belongs_to.limits,
)
.await
}
async fn _create(
token: &str, token: &str,
url_api: &str, url_api: &str,
guild_id: &str, guild_id: &str,

View File

@ -21,12 +21,10 @@ impl UserMeta {
* [`InstanceServerError`] - If the request fails. * [`InstanceServerError`] - If the request fails.
*/ */
pub async fn get( pub async fn get(
token: &String, user: &mut UserMeta,
url_api: &String,
id: Option<&String>, id: Option<&String>,
instance_limits: &mut Limits,
) -> Result<User, InstanceServerError> { ) -> Result<User, InstanceServerError> {
User::get(token, url_api, id, instance_limits).await User::get(user, id).await
} }
pub async fn get_settings( pub async fn get_settings(
@ -116,10 +114,24 @@ impl UserMeta {
impl User { impl User {
pub async fn get( pub async fn get(
token: &String, user: &mut UserMeta,
url_api: &String, id: Option<&String>,
) -> Result<User, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
User::_get(
&user.token(),
&format!("{}", belongs_to.urls.get_api()),
&mut belongs_to.limits,
id,
)
.await
}
async fn _get(
token: &str,
url_api: &str,
limits_instance: &mut Limits,
id: Option<&String>, id: Option<&String>,
instance_limits: &mut Limits,
) -> Result<User, InstanceServerError> { ) -> Result<User, InstanceServerError> {
let url: String; let url: String;
if id.is_none() { if id.is_none() {
@ -129,12 +141,12 @@ impl User {
} }
let request = reqwest::Client::new().get(url).bearer_auth(token); let request = reqwest::Client::new().get(url).bearer_auth(token);
let mut requester = crate::limit::LimitedRequester::new().await; let mut requester = crate::limit::LimitedRequester::new().await;
let mut cloned_limits = instance_limits.clone(); let mut cloned_limits = limits_instance.clone();
match requester match requester
.send_request( .send_request(
request, request,
crate::api::limits::LimitType::Ip, crate::api::limits::LimitType::Ip,
instance_limits, limits_instance,
&mut cloned_limits, &mut cloned_limits,
) )
.await .await
@ -188,11 +200,11 @@ impl Instance {
token: String, token: String,
id: Option<&String>, id: Option<&String>,
) -> Result<User, InstanceServerError> { ) -> Result<User, InstanceServerError> {
UserMeta::get( User::_get(
&token, &token,
&self.urls.get_api().to_string(), &self.urls.get_api().to_string(),
id,
&mut self.limits, &mut self.limits,
id,
) )
.await .await
} }

View File

@ -5,19 +5,13 @@ use chorus::types::{self, Channel};
async fn get_channel() { async fn get_channel() {
let mut bundle = common::setup().await; let mut bundle = common::setup().await;
let bundle_channel = bundle.channel.clone(); let bundle_channel = bundle.channel.clone();
let bundle_user = &mut bundle.user; let mut bundle_user = &mut bundle.user;
assert_eq!( assert_eq!(
bundle_channel, bundle_channel,
Channel::get( Channel::get(&mut bundle_user, &bundle_channel.id.to_string(),)
bundle_user.token.as_str(), .await
bundle.instance.urls.get_api(), .unwrap()
&bundle_channel.id.to_string(),
&mut bundle_user.limits,
&mut bundle.instance.limits
)
.await
.unwrap()
); );
common::teardown(bundle).await common::teardown(bundle).await
} }
@ -25,16 +19,7 @@ async fn get_channel() {
#[tokio::test] #[tokio::test]
async fn delete_channel() { async fn delete_channel() {
let mut bundle = common::setup().await; let mut bundle = common::setup().await;
let result = bundle let result = bundle.channel.clone().delete(&mut bundle.user).await;
.channel
.clone()
.delete(
&bundle.user.token,
bundle.instance.urls.get_api(),
&mut bundle.user.limits,
&mut bundle.instance.limits,
)
.await;
assert!(result.is_none()); assert!(result.is_none());
common::teardown(bundle).await common::teardown(bundle).await
} }
@ -63,11 +48,8 @@ async fn modify_channel() {
}; };
let result = Channel::modify( let result = Channel::modify(
modify_data, modify_data,
&bundle.user.token,
bundle.instance.urls.get_api(),
&bundle.channel.id.to_string(), &bundle.channel.id.to_string(),
&mut bundle.user.limits, &mut bundle.user,
&mut bundle.instance.limits,
) )
.await .await
.unwrap(); .unwrap();

View File

@ -65,19 +65,10 @@ pub async fn setup() -> TestBundle {
video_quality_mode: None, video_quality_mode: None,
}; };
let mut user = instance.register_account(&reg).await.unwrap(); let mut user = instance.register_account(&reg).await.unwrap();
let guild = Guild::create(&mut user, urls.get_api(), guild_create_schema) let guild = Guild::create(&mut user, guild_create_schema).await.unwrap();
let channel = Channel::create(&mut user, &guild.id.to_string(), channel_create_schema)
.await .await
.unwrap(); .unwrap();
let channel = Channel::create(
&user.token,
urls.get_api(),
&guild.id.to_string(),
channel_create_schema,
&mut user.limits,
&mut instance.limits,
)
.await
.unwrap();
TestBundle { TestBundle {
urls, urls,
@ -90,11 +81,6 @@ pub async fn setup() -> TestBundle {
// Teardown method to clean up after a test. // Teardown method to clean up after a test.
pub async fn teardown(mut bundle: TestBundle) { pub async fn teardown(mut bundle: TestBundle) {
Guild::delete( Guild::delete(&mut bundle.user, &bundle.guild.id.to_string()).await;
&mut bundle.user,
bundle.instance.urls.get_api(),
&bundle.guild.id.to_string(),
)
.await;
bundle.user.delete().await; bundle.user.delete().await;
} }

View File

@ -15,17 +15,11 @@ async fn guild_creation_deletion() {
rules_channel_id: None, rules_channel_id: None,
}; };
let guild = Guild::create(&mut bundle.user, bundle.urls.get_api(), guild_create_schema) let guild = Guild::create(&mut bundle.user, guild_create_schema)
.await .await
.unwrap(); .unwrap();
match Guild::delete( match Guild::delete(&mut bundle.user, &guild.id.to_string()).await {
&mut bundle.user,
bundle.urls.get_api(),
&guild.id.to_string(),
)
.await
{
None => assert!(true), None => assert!(true),
Some(_) => assert!(false), Some(_) => assert!(false),
} }
@ -37,16 +31,7 @@ async fn get_channels() {
let mut bundle = common::setup().await; let mut bundle = common::setup().await;
println!( println!(
"{:?}", "{:?}",
bundle bundle.guild.channels(&mut bundle.user).await.unwrap()
.guild
.channels(
bundle.instance.urls.get_api(),
&bundle.user.token,
&mut bundle.user.limits,
&mut bundle.instance.limits,
)
.await
.unwrap()
); );
common::teardown(bundle).await; common::teardown(bundle).await;
} }