Merge pull request #81 from polyphony-chat/feature/channel/delete

Feature/channel/delete
This commit is contained in:
Flori 2023-05-29 17:56:13 +02:00 committed by GitHub
commit 7ada53a4d4
10 changed files with 258 additions and 77 deletions

View File

@ -48,7 +48,6 @@ pub mod register {
let response_unwrap = response.unwrap(); let response_unwrap = response.unwrap();
let status = response_unwrap.status(); let status = response_unwrap.status();
let response_unwrap_text = response_unwrap.text().await.unwrap(); let response_unwrap_text = response_unwrap.text().await.unwrap();
println!("{}", response_unwrap_text);
let token = from_str::<Token>(&response_unwrap_text).unwrap(); let token = from_str::<Token>(&response_unwrap_text).unwrap();
let token = token.token; let token = token.token;
if status.is_client_error() { if status.is_client_error() {

View File

@ -38,4 +38,42 @@ impl Channel {
}), }),
} }
} }
/// Deletes a channel.
///
/// # Arguments
///
/// * `token` - A string slice that holds the authorization token.
/// * `url_api` - A string slice that holds the URL of the API.
/// * `channel` - A `Channel` object that represents the channel to be deleted.
/// * `limits_user` - A mutable reference to a `Limits` object that represents the user's rate limits.
/// * `limits_instance` - A mutable reference to a `Limits` object that represents the instance's rate limits.
///
/// # Returns
///
/// An `Option` that contains an `InstanceServerError` if an error occurred during the request, or `None` if the request was successful.
pub async fn delete(
self,
token: &str,
url_api: &str,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Option<InstanceServerError> {
let request = Client::new()
.delete(format!("{}/channels/{}/", url_api, self.id.to_string()))
.bearer_auth(token);
match LimitedRequester::new()
.await
.send_request(
request,
crate::api::limits::LimitType::Channel,
limits_instance,
limits_user,
)
.await
{
Ok(_) => None,
Err(e) => return Some(e),
}
}
} }

View File

@ -78,8 +78,6 @@ pub mod messages {
.bearer_auth(token) .bearer_auth(token)
.multipart(form); .multipart(form);
println!("[Request Headers: ] {:?}", message_request);
requester requester
.send_request( .send_request(
message_request, message_request,

View File

@ -19,32 +19,20 @@ impl Guild {
/// ///
/// # Returns /// # Returns
/// ///
/// A `Result<String>` containing the ID of the newly created guild, or an error if the request fails. /// A `Result<Guild>` containing the object of the newly created guild, or an error if the request fails.
/// ///
/// # Errors /// # Errors
/// ///
/// Returns an `InstanceServerError` if the request fails. /// Returns an `InstanceServerError` if the request fails.
/// ///
/// # Examples
///
/// ```rs
/// let guild_create_schema = chorus::api::schemas::GuildCreateSchema::new(insert args here);
///
/// let result = Guild::create(&mut user, &mut instance, &guild_create_schema).await;
///
/// match result {
/// Ok(guild_id) => println!("Created guild with ID {}", guild_id),
/// Err(e) => println!("Failed to create guild: {}", e),
/// }
/// ```
pub async fn create( pub async fn create(
user: &mut UserMeta, user: &mut UserMeta,
url_api: &str, url_api: &str,
guild_create_schema: GuildCreateSchema, guild_create_schema: GuildCreateSchema,
) -> Result<String, crate::errors::InstanceServerError> { ) -> Result<Guild, crate::errors::InstanceServerError> {
let url = format!("{}/guilds/", url_api); let url = format!("{}/guilds/", url_api);
let limits_user = user.limits.get_as_mut(); let mut limits_user = user.limits.get_as_mut();
let limits_instance = &mut user.belongs_to.borrow_mut().limits; 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())
@ -63,7 +51,16 @@ 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();
Ok(id.id) let guild = Guild::get(
url_api,
&id.id,
&user.token,
&mut limits_user,
&mut limits_instance,
)
.await
.unwrap();
Ok(guild)
} }
/// Deletes a guild. /// Deletes a guild.
@ -93,7 +90,7 @@ impl Guild {
pub async fn delete( pub async fn delete(
user: &mut UserMeta, user: &mut UserMeta,
url_api: &str, url_api: &str,
guild_id: String, guild_id: &str,
) -> Option<InstanceServerError> { ) -> Option<InstanceServerError> {
let url = format!("{}/guilds/{}/delete/", url_api, guild_id); let url = format!("{}/guilds/{}/delete/", url_api, guild_id);
let limits_user = user.limits.get_as_mut(); let limits_user = user.limits.get_as_mut();
@ -148,6 +145,97 @@ impl Guild {
) )
.await .await
} }
/// Returns a `Result` containing a vector of `Channel` structs if the request was successful, or an `InstanceServerError` if there was an error.
///
/// # Arguments
///
/// * `url_api` - A string slice that holds the URL of the API.
/// * `token` - A string slice that holds the authorization token.
/// * `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.
///
pub async fn channels(
&self,
url_api: &str,
token: &str,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Result<Vec<Channel>, InstanceServerError> {
let request = Client::new()
.get(format!(
"{}/guilds/{}/channels/",
url_api,
self.id.to_string()
))
.bearer_auth(token);
let result = match LimitedRequester::new()
.await
.send_request(
request,
crate::api::limits::LimitType::Guild,
limits_instance,
limits_user,
)
.await
{
Ok(result) => result,
Err(e) => return Err(e),
};
let stringed_response = match result.text().await {
Ok(value) => value,
Err(e) => {
return Err(InstanceServerError::InvalidResponseError {
error: e.to_string(),
})
}
};
let _: Vec<Channel> = match from_str(&stringed_response) {
Ok(result) => return Ok(result),
Err(e) => {
return Err(InstanceServerError::InvalidResponseError {
error: e.to_string(),
})
}
};
}
/// Returns a `Result` containing a `Guild` struct if the request was successful, or an `InstanceServerError` if there was an error.
///
/// # Arguments
///
/// * `url_api` - A string slice that holds the URL of the API.
/// * `guild_id` - A string slice that holds the ID of the guild.
/// * `token` - A string slice that holds the authorization token.
/// * `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.
///
pub async fn get(
url_api: &str,
guild_id: &str,
token: &str,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Result<Guild, InstanceServerError> {
let request = Client::new()
.get(format!("{}/guilds/{}/", url_api, guild_id))
.bearer_auth(token);
let response = match LimitedRequester::new()
.await
.send_request(
request,
crate::api::limits::LimitType::Guild,
limits_instance,
limits_user,
)
.await
{
Ok(response) => response,
Err(e) => return Err(e),
};
let guild: Guild = from_str(&response.text().await.unwrap()).unwrap();
Ok(guild)
}
} }
impl Channel { impl Channel {

View File

@ -26,30 +26,7 @@ impl UserMeta {
id: Option<&String>, id: Option<&String>,
instance_limits: &mut Limits, instance_limits: &mut Limits,
) -> Result<User, InstanceServerError> { ) -> Result<User, InstanceServerError> {
let url: String; User::get(token, url_api, id, instance_limits).await
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;
let mut cloned_limits = instance_limits.clone();
match requester
.send_request(
request,
crate::api::limits::LimitType::Ip,
instance_limits,
&mut cloned_limits,
)
.await
{
Ok(result) => {
let result_text = result.text().await.unwrap();
Ok(serde_json::from_str::<User>(&result_text).unwrap())
}
Err(e) => Err(e),
}
} }
pub async fn get_settings( pub async fn get_settings(
@ -57,23 +34,7 @@ impl UserMeta {
url_api: &String, url_api: &String,
instance_limits: &mut Limits, instance_limits: &mut Limits,
) -> Result<UserSettings, InstanceServerError> { ) -> Result<UserSettings, InstanceServerError> {
let request: reqwest::RequestBuilder = Client::new() User::get_settings(token, url_api, instance_limits).await
.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 cloned_limits,
)
.await
{
Ok(result) => Ok(serde_json::from_str(&result.text().await.unwrap()).unwrap()),
Err(e) => Err(e),
}
} }
/// Modify the current user's `UserObject`. /// Modify the current user's `UserObject`.
@ -153,6 +114,64 @@ impl UserMeta {
} }
} }
impl User {
pub async fn get(
token: &String,
url_api: &String,
id: Option<&String>,
instance_limits: &mut Limits,
) -> Result<User, InstanceServerError> {
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;
let mut cloned_limits = instance_limits.clone();
match requester
.send_request(
request,
crate::api::limits::LimitType::Ip,
instance_limits,
&mut cloned_limits,
)
.await
{
Ok(result) => {
let result_text = result.text().await.unwrap();
Ok(serde_json::from_str::<User>(&result_text).unwrap())
}
Err(e) => Err(e),
}
}
pub async fn get_settings(
token: &String,
url_api: &String,
instance_limits: &mut Limits,
) -> Result<UserSettings, InstanceServerError> {
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 cloned_limits,
)
.await
{
Ok(result) => Ok(serde_json::from_str(&result.text().await.unwrap()).unwrap()),
Err(e) => Err(e),
}
}
}
impl Instance { impl Instance {
/** /**
Get a user object by id, or get the current user. Get a user object by id, or get the current user.

View File

@ -23,6 +23,7 @@ custom_error! {
NoPermission = "You do not have the permissions needed to perform this action.", NoPermission = "You do not have the permissions needed to perform this action.",
NotFound{error: String} = "The provided resource hasn't been found: {}", NotFound{error: String} = "The provided resource hasn't been found: {}",
PasswordRequiredError = "You need to provide your current password to authenticate for this action.", PasswordRequiredError = "You need to provide your current password to authenticate for this action.",
InvalidResponseError{error: String} = "The response is malformed and cannot be processed. Error: {}",
} }
custom_error! { custom_error! {

View File

@ -23,21 +23,21 @@ pub struct Guild {
pub owner_id: Option<Snowflake>, pub owner_id: Option<Snowflake>,
pub permissions: Option<String>, pub permissions: Option<String>,
pub afk_channel_id: Option<Snowflake>, pub afk_channel_id: Option<Snowflake>,
pub afk_timeout: Option<u8>, pub afk_timeout: Option<u32>,
pub widget_enabled: Option<bool>, pub widget_enabled: Option<bool>,
pub widget_channel_id: Option<Snowflake>, pub widget_channel_id: Option<Snowflake>,
pub verification_level: Option<u8>, pub verification_level: Option<u8>,
pub default_message_notifications: Option<u8>, pub default_message_notifications: Option<u8>,
pub explicit_content_filter: Option<u8>, pub explicit_content_filter: Option<u8>,
#[cfg_attr(feature = "sqlx", sqlx(skip))] #[cfg_attr(feature = "sqlx", sqlx(skip))]
pub roles: Vec<RoleObject>, pub roles: Option<Vec<RoleObject>>,
#[cfg_attr(feature = "sqlx", sqlx(skip))] #[cfg_attr(feature = "sqlx", sqlx(skip))]
pub emojis: Vec<Emoji>, pub emojis: Option<Vec<Emoji>>,
#[cfg_attr(feature = "sqlx", sqlx(skip))] #[cfg_attr(feature = "sqlx", sqlx(skip))]
pub features: Option<Vec<String>>, pub features: Option<Vec<String>>,
pub application_id: Option<String>, pub application_id: Option<String>,
pub system_channel_id: Option<Snowflake>, pub system_channel_id: Option<Snowflake>,
pub system_channel_flags: Option<u8>, pub system_channel_flags: Option<u32>,
pub rules_channel_id: Option<Snowflake>, pub rules_channel_id: Option<Snowflake>,
pub rules_channel: Option<String>, pub rules_channel: Option<String>,
pub max_presences: Option<u64>, pub max_presences: Option<u64>,
@ -49,8 +49,8 @@ pub struct Guild {
pub premium_subscription_count: Option<u64>, pub premium_subscription_count: Option<u64>,
pub preferred_locale: Option<String>, pub preferred_locale: Option<String>,
pub public_updates_channel_id: Option<Snowflake>, pub public_updates_channel_id: Option<Snowflake>,
pub max_video_channel_users: Option<u8>, pub max_video_channel_users: Option<u32>,
pub max_stage_video_channel_users: Option<u8>, pub max_stage_video_channel_users: Option<u32>,
pub approximate_member_count: Option<u64>, pub approximate_member_count: Option<u64>,
pub approximate_presence_count: Option<u64>, pub approximate_presence_count: Option<u64>,
#[cfg(feature = "sqlx")] #[cfg(feature = "sqlx")]
@ -62,7 +62,7 @@ pub struct Guild {
pub stickers: Option<Vec<Sticker>>, pub stickers: Option<Vec<Sticker>>,
pub premium_progress_bar_enabled: Option<bool>, pub premium_progress_bar_enabled: Option<bool>,
#[cfg_attr(feature = "sqlx", sqlx(skip))] #[cfg_attr(feature = "sqlx", sqlx(skip))]
pub joined_at: String, pub joined_at: Option<String>,
#[cfg_attr(feature = "sqlx", sqlx(skip))] #[cfg_attr(feature = "sqlx", sqlx(skip))]
pub bans: Option<Vec<GuildBan>>, pub bans: Option<Vec<GuildBan>>,
pub primary_category_id: Option<Snowflake>, pub primary_category_id: Option<Snowflake>,

View File

@ -21,3 +21,18 @@ async fn get_channel() {
); );
common::teardown(bundle).await common::teardown(bundle).await
} }
#[tokio::test]
async fn delete_channel() {
let mut bundle = common::setup().await;
let result = bundle
.channel
.delete(
&bundle.user.token,
bundle.instance.urls.get_api(),
&mut bundle.user.limits,
&mut bundle.instance.limits,
)
.await;
assert!(result.is_none());
}

View File

@ -9,7 +9,7 @@ pub struct TestBundle {
pub urls: URLBundle, pub urls: URLBundle,
pub user: UserMeta, pub user: UserMeta,
pub instance: Instance, pub instance: Instance,
pub guild_id: String, pub guild: Guild,
pub channel: Channel, pub channel: Channel,
} }
@ -65,13 +65,13 @@ 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_id = Guild::create(&mut user, urls.get_api(), guild_create_schema) let guild = Guild::create(&mut user, urls.get_api(), guild_create_schema)
.await .await
.unwrap(); .unwrap();
let channel = Channel::create( let channel = Channel::create(
&user.token, &user.token,
urls.get_api(), urls.get_api(),
guild_id.as_str(), &guild.id.to_string(),
channel_create_schema, channel_create_schema,
&mut user.limits, &mut user.limits,
&mut instance.limits, &mut instance.limits,
@ -83,7 +83,7 @@ pub async fn setup() -> TestBundle {
urls, urls,
user, user,
instance, instance,
guild_id, guild,
channel, channel,
} }
} }
@ -93,7 +93,7 @@ pub async fn teardown(mut bundle: TestBundle) {
Guild::delete( Guild::delete(
&mut bundle.user, &mut bundle.user,
bundle.instance.urls.get_api(), bundle.instance.urls.get_api(),
bundle.guild_id, &bundle.guild.id.to_string(),
) )
.await; .await;
bundle.user.delete().await; bundle.user.delete().await;

View File

@ -19,11 +19,34 @@ async fn guild_creation_deletion() {
.await .await
.unwrap(); .unwrap();
println!("{}", guild); match Guild::delete(
&mut bundle.user,
match Guild::delete(&mut bundle.user, bundle.urls.get_api(), guild).await { bundle.urls.get_api(),
&guild.id.to_string(),
)
.await
{
None => assert!(true), None => assert!(true),
Some(_) => assert!(false), Some(_) => assert!(false),
} }
common::teardown(bundle).await common::teardown(bundle).await
} }
#[tokio::test]
async fn get_channels() {
let mut bundle = common::setup().await;
println!(
"{:?}",
bundle
.guild
.channels(
bundle.instance.urls.get_api(),
&bundle.user.token,
&mut bundle.user.limits,
&mut bundle.instance.limits,
)
.await
.unwrap()
);
common::teardown(bundle).await;
}