Merge pull request #128 from SpecificProtagonist/deep_winter

Always use Snowflakes in args
This commit is contained in:
Flori 2023-06-22 19:44:15 +02:00 committed by GitHub
commit f647f14d82
13 changed files with 90 additions and 120 deletions

View File

@ -9,7 +9,7 @@ use crate::{
};
impl Channel {
pub async fn get(user: &mut UserMeta, channel_id: &str) -> ChorusResult<Channel> {
pub async fn get(user: &mut UserMeta, channel_id: Snowflake) -> ChorusResult<Channel> {
let url = user.belongs_to.borrow_mut().urls.api.clone();
let request = Client::new()
.get(format!("{}/channels/{}/", url, channel_id))

View File

@ -1,6 +1,11 @@
use reqwest::Client;
use crate::{api::handle_request_as_result, errors::ChorusResult, instance::UserMeta, types};
use crate::{
api::handle_request_as_result,
errors::ChorusResult,
instance::UserMeta,
types::{self, Snowflake},
};
/**
Useful metadata for working with [`types::Reaction`], bundled together nicely.
@ -157,7 +162,7 @@ impl ReactionMeta {
This endpoint requires the MANAGE_MESSAGES permission to be present on the current user.
# Arguments
* `user_id` - A string slice containing the ID of the user whose reaction is to be deleted.
* `user_id` - ID of the user whose reaction is to be deleted.
* `emoji` - A string slice containing the emoji to delete. The `emoji` must be URL Encoded or
the request will fail with 10014: Unknown Emoji. To use custom emoji, you must encode it in the
format name:id with the emoji name and emoji id.
@ -172,7 +177,7 @@ impl ReactionMeta {
*/
pub async fn delete_user(
&self,
user_id: &str,
user_id: Snowflake,
emoji: &str,
user: &mut UserMeta,
) -> ChorusResult<()> {

View File

@ -11,6 +11,7 @@ use crate::errors::ChorusResult;
use crate::instance::Instance;
use crate::instance::UserMeta;
use crate::limit::LimitedRequester;
use crate::types::Snowflake;
use crate::types::{Channel, ChannelCreateSchema, Guild, GuildCreateSchema};
impl Guild {
@ -48,7 +49,7 @@ impl Guild {
///
/// * `user` - A mutable reference to a `User` instance.
/// * `instance` - A mutable reference to an `Instance` instance.
/// * `guild_id` - A `String` representing the ID of the guild to delete.
/// * `guild_id` - ID of the guild to delete.
///
/// # Returns
///
@ -66,7 +67,7 @@ impl Guild {
/// None => println!("Guild deleted successfully"),
/// }
/// ```
pub async fn delete(user: &mut UserMeta, guild_id: &str) -> ChorusResult<()> {
pub async fn delete(user: &mut UserMeta, guild_id: Snowflake) -> ChorusResult<()> {
let url = format!(
"{}/guilds/{}/delete/",
user.belongs_to.borrow().urls.api,
@ -96,14 +97,12 @@ impl Guild {
user: &mut UserMeta,
schema: ChannelCreateSchema,
) -> ChorusResult<Channel> {
let mut belongs_to = user.belongs_to.borrow_mut();
Channel::_create(
&user.token,
&format!("{}", belongs_to.urls.api),
&self.id.to_string(),
self.id,
schema,
&mut user.limits,
&mut belongs_to,
&mut user.belongs_to.borrow_mut(),
)
.await
}
@ -151,34 +150,26 @@ impl Guild {
/// # 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.
/// * `guild_id` - 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(user: &mut UserMeta, guild_id: &str) -> ChorusResult<Guild> {
pub async fn get(user: &mut UserMeta, guild_id: Snowflake) -> ChorusResult<Guild> {
let mut belongs_to = user.belongs_to.borrow_mut();
Guild::_get(
&format!("{}", belongs_to.urls.api),
guild_id,
&user.token,
&mut user.limits,
&mut belongs_to,
)
.await
Guild::_get(guild_id, &user.token, &mut user.limits, &mut belongs_to).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,
guild_id: &str,
guild_id: Snowflake,
token: &str,
limits_user: &mut Limits,
instance: &mut Instance,
) -> ChorusResult<Guild> {
let request = Client::new()
.get(format!("{}/guilds/{}/", url_api, guild_id))
.get(format!("{}/guilds/{}/", instance.urls.api, guild_id))
.bearer_auth(token);
let response = match LimitedRequester::send_request(
request,
@ -213,13 +204,12 @@ impl Channel {
/// A `Result` containing a `reqwest::Response` if the request was successful, or an `ChorusLibError` if there was an error.
pub async fn create(
user: &mut UserMeta,
guild_id: &str,
guild_id: Snowflake,
schema: ChannelCreateSchema,
) -> ChorusResult<Channel> {
let mut belongs_to = user.belongs_to.borrow_mut();
Channel::_create(
&user.token,
&format!("{}", belongs_to.urls.api),
guild_id,
schema,
&mut user.limits,
@ -230,14 +220,16 @@ impl Channel {
async fn _create(
token: &str,
url_api: &str,
guild_id: &str,
guild_id: Snowflake,
schema: ChannelCreateSchema,
limits_user: &mut Limits,
instance: &mut Instance,
) -> ChorusResult<Channel> {
let request = Client::new()
.post(format!("{}/guilds/{}/channels/", url_api, guild_id))
.post(format!(
"{}/guilds/{}/channels/",
instance.urls.api, guild_id
))
.bearer_auth(token)
.body(to_string(&schema).unwrap());
let result = match LimitedRequester::send_request(
@ -254,7 +246,7 @@ impl Channel {
match from_str::<Channel>(&result.text().await.unwrap()) {
Ok(object) => Ok(object),
Err(e) => Err(ChorusLibError::RequestErrorError {
url: format!("{}/guilds/{}/channels/", url_api, guild_id),
url: format!("{}/guilds/{}/channels/", instance.urls.api, guild_id),
error: e.to_string(),
}),
}

View File

@ -4,7 +4,7 @@ use crate::{
api::{deserialize_response, handle_request_as_result},
errors::ChorusResult,
instance::UserMeta,
types,
types::{self, Snowflake},
};
impl types::GuildMember {
@ -21,8 +21,8 @@ impl types::GuildMember {
/// A [`Result`] containing a [`GuildMember`] if the request succeeds, or a [`ChorusLibError`] if the request fails.
pub async fn get(
user: &mut UserMeta,
guild_id: &str,
member_id: &str,
guild_id: Snowflake,
member_id: Snowflake,
) -> ChorusResult<types::GuildMember> {
let url = format!(
"{}/guilds/{}/members/{}/",
@ -53,9 +53,9 @@ impl types::GuildMember {
/// An `Result` containing a `ChorusLibError` if the request fails, or `()` if the request succeeds.
pub async fn add_role(
user: &mut UserMeta,
guild_id: &str,
member_id: &str,
role_id: &str,
guild_id: Snowflake,
member_id: Snowflake,
role_id: Snowflake,
) -> ChorusResult<()> {
let url = format!(
"{}/guilds/{}/members/{}/roles/{}/",
@ -82,9 +82,9 @@ impl types::GuildMember {
/// A `Result` containing a `ChorusLibError` if the request fails, or `()` if the request succeeds.
pub async fn remove_role(
user: &mut UserMeta,
guild_id: &str,
member_id: &str,
role_id: &str,
guild_id: Snowflake,
member_id: Snowflake,
role_id: Snowflake,
) -> Result<(), crate::errors::ChorusLibError> {
let url = format!(
"{}/guilds/{}/members/{}/roles/{}/",

View File

@ -5,7 +5,7 @@ use crate::{
api::deserialize_response,
errors::{ChorusLibError, ChorusResult},
instance::UserMeta,
types::{self, RoleCreateModifySchema, RoleObject},
types::{self, RoleCreateModifySchema, RoleObject, Snowflake},
};
impl types::RoleObject {
@ -25,7 +25,7 @@ impl types::RoleObject {
/// Returns a [`ChorusLibError`] if the request fails or if the response is invalid.
pub async fn get_all(
user: &mut UserMeta,
guild_id: &str,
guild_id: Snowflake,
) -> ChorusResult<Option<Vec<RoleObject>>> {
let url = format!(
"{}/guilds/{}/roles/",
@ -63,8 +63,8 @@ impl types::RoleObject {
/// Returns a [`ChorusLibError`] if the request fails or if the response is invalid.
pub async fn get(
user: &mut UserMeta,
guild_id: &str,
role_id: &str,
guild_id: Snowflake,
role_id: Snowflake,
) -> ChorusResult<RoleObject> {
let url = format!(
"{}/guilds/{}/roles/{}/",
@ -93,7 +93,7 @@ impl types::RoleObject {
/// Returns a [`ChorusLibError`] if the request fails or if the response is invalid.
pub async fn create(
user: &mut UserMeta,
guild_id: &str,
guild_id: Snowflake,
role_create_schema: RoleCreateModifySchema,
) -> ChorusResult<RoleObject> {
let url = format!(
@ -127,7 +127,7 @@ impl types::RoleObject {
/// Returns a [`ChorusLibError`] if the request fails or if the response is invalid.
pub async fn position_update(
user: &mut UserMeta,
guild_id: &str,
guild_id: Snowflake,
role_position_update_schema: types::RolePositionUpdateSchema,
) -> ChorusResult<RoleObject> {
let url = format!(
@ -166,8 +166,8 @@ impl types::RoleObject {
/// Returns a [`ChorusLibError`] if the request fails or if the response is invalid.
pub async fn update(
user: &mut UserMeta,
guild_id: &str,
role_id: &str,
guild_id: Snowflake,
role_id: Snowflake,
role_create_schema: RoleCreateModifySchema,
) -> ChorusResult<RoleObject> {
let url = format!(

View File

@ -5,7 +5,7 @@ use crate::{
api::{deserialize_response, handle_request_as_result},
errors::ChorusResult,
instance::UserMeta,
types::{self, CreateUserRelationshipSchema, RelationshipType},
types::{self, CreateUserRelationshipSchema, RelationshipType, Snowflake},
};
impl UserMeta {
@ -13,13 +13,13 @@ impl UserMeta {
///
/// # Arguments
///
/// * `user_id` - A string slice that holds the ID of the user to retrieve the mutual relationships with.
/// * `user_id` - ID of the user to retrieve the mutual relationships with.
///
/// # Returns
/// This function returns a [`ChorusResult<Vec<PublicUser>>`].
pub async fn get_mutual_relationships(
&mut self,
user_id: &str,
user_id: Snowflake,
) -> ChorusResult<Vec<types::PublicUser>> {
let url = format!(
"{}/users/{}/relationships/",
@ -78,7 +78,7 @@ impl UserMeta {
///
/// # Arguments
///
/// * `user_id` - A string slice that holds the ID of the user to modify the relationship with.
/// * `user_id` - ID of the user to modify the relationship with.
/// * `relationship_type` - A [`RelationshipType`] enum that specifies the type of relationship to modify.
/// * [`RelationshipType::None`]: Removes the relationship between the two users.
/// * [`RelationshipType::Friends`] | [`RelationshipType::Incoming`] | [`RelationshipType::Outgoing`]:
@ -90,7 +90,7 @@ impl UserMeta {
/// This function returns an [`Result`] that holds a [`ChorusLibError`] if the request fails.
pub async fn modify_user_relationship(
&mut self,
user_id: &str,
user_id: Snowflake,
relationship_type: RelationshipType,
) -> ChorusResult<()> {
let api_url = self.belongs_to.borrow().urls.api.clone();
@ -133,11 +133,11 @@ impl UserMeta {
///
/// # Arguments
///
/// * `user_id` - A string slice that holds the ID of the user to remove the relationship with.
/// * `user_id` - ID of the user to remove the relationship with.
///
/// # Returns
/// This function returns a [`Result`] that holds a [`ChorusLibError`] if the request fails.
pub async fn remove_relationship(&mut self, user_id: &str) -> ChorusResult<()> {
pub async fn remove_relationship(&mut self, user_id: Snowflake) -> ChorusResult<()> {
let url = format!(
"{}/users/@me/relationships/{}/",
self.belongs_to.borrow().urls.api,

View File

@ -1,13 +1,13 @@
use serde::{Deserialize, Serialize};
use crate::types::entities::PublicUser;
use crate::types::{entities::PublicUser, Snowflake};
#[derive(Debug, Deserialize, Default, Serialize, Clone, PartialEq, Eq)]
pub struct GuildMember {
pub user: Option<PublicUser>,
pub nick: Option<String>,
pub avatar: Option<String>,
pub roles: Vec<String>,
pub roles: Vec<Snowflake>,
pub joined_at: String,
pub premium_since: Option<String>,
pub deaf: bool,

View File

@ -13,9 +13,7 @@ async fn get_channel() {
assert_eq!(
bundle_channel,
Channel::get(bundle_user, &bundle_channel.id.to_string())
.await
.unwrap()
Channel::get(bundle_user, bundle_channel.id).await.unwrap()
);
common::teardown(bundle).await
}
@ -23,7 +21,7 @@ async fn get_channel() {
#[tokio::test]
async fn delete_channel() {
let mut bundle = common::setup().await;
let result = bundle.channel.clone().delete(&mut bundle.user).await;
let result = Channel::delete(bundle.channel.clone(), &mut bundle.user).await;
assert!(result.is_ok());
common::teardown(bundle).await
}

View File

@ -1,4 +1,5 @@
use chorus::{
errors::ChorusResult,
instance::{Instance, UserMeta},
types::{
Channel, ChannelCreateSchema, Guild, GuildCreateSchema, RegisterSchema,
@ -63,7 +64,7 @@ pub async fn setup() -> TestBundle {
};
let mut user = instance.register_account(&reg).await.unwrap();
let guild = Guild::create(&mut user, guild_create_schema).await.unwrap();
let channel = Channel::create(&mut user, &guild.id.to_string(), channel_create_schema)
let channel = Channel::create(&mut user, guild.id, channel_create_schema)
.await
.unwrap();
@ -77,8 +78,7 @@ pub async fn setup() -> TestBundle {
position: None,
color: None,
};
let guild_id = guild.id.clone().to_string();
let role = chorus::types::RoleObject::create(&mut user, &guild_id, role_create_schema)
let role = chorus::types::RoleObject::create(&mut user, guild.id, role_create_schema)
.await
.unwrap();
@ -95,6 +95,8 @@ pub async fn setup() -> TestBundle {
// Teardown method to clean up after a test.
#[allow(dead_code)]
pub async fn teardown(mut bundle: TestBundle) {
Guild::delete(&mut bundle.user, &bundle.guild.id.to_string()).await;
bundle.user.delete().await;
Guild::delete(&mut bundle.user, bundle.guild.id)
.await
.unwrap();
bundle.user.delete().await.unwrap()
}

View File

@ -20,9 +20,7 @@ async fn guild_creation_deletion() {
.await
.unwrap();
assert!(Guild::delete(&mut bundle.user, &guild.id.to_string())
.await
.is_ok());
assert!(Guild::delete(&mut bundle.user, guild.id).await.is_ok());
common::teardown(bundle).await
}

View File

@ -1,38 +1,25 @@
use chorus::{errors::ChorusResult, types::GuildMember};
mod common;
#[tokio::test]
async fn add_remove_role() {
async fn add_remove_role() -> ChorusResult<()> {
let mut bundle = common::setup().await;
let guild_id = &bundle.guild.id.to_string();
let role_id = &bundle.role.id.to_string();
let user_id = &bundle.user.object.id.to_string();
chorus::types::GuildMember::add_role(&mut bundle.user, guild_id, user_id, role_id).await;
let member = chorus::types::GuildMember::get(&mut bundle.user, guild_id, user_id)
let guild = bundle.guild.id;
let role = bundle.role.id;
let member_id = bundle.user.object.id;
GuildMember::add_role(&mut bundle.user, guild, member_id, role).await?;
let member = GuildMember::get(&mut bundle.user, guild, member_id)
.await
.unwrap();
let mut role_found = false;
for role in member.roles.iter() {
if role == role_id {
println!("Role found: {:?}", role);
role_found = true;
}
}
if !role_found {
panic!()
}
chorus::types::GuildMember::remove_role(&mut bundle.user, guild_id, user_id, role_id).await;
let member = chorus::types::GuildMember::get(&mut bundle.user, guild_id, user_id)
assert!(member.roles.contains(&role));
GuildMember::remove_role(&mut bundle.user, guild, member_id, role).await?;
let member = GuildMember::get(&mut bundle.user, guild, member_id)
.await
.unwrap();
for role in member.roles.iter() {
if role != role_id {
role_found = false;
} else {
panic!();
}
}
if role_found {
panic!()
}
common::teardown(bundle).await
assert!(!member.roles.contains(&role));
common::teardown(bundle).await;
Ok(())
}

View File

@ -21,7 +21,7 @@ async fn test_get_mutual_relationships() {
};
other_user.send_friend_request(friend_request_schema).await;
let relationships = user
.get_mutual_relationships(&other_user.object.id.to_string())
.get_mutual_relationships(other_user.object.id)
.await
.unwrap();
println!("{:?}", relationships);
@ -65,10 +65,7 @@ async fn test_modify_relationship_friends() {
let user = &mut bundle.user;
let mut other_user = belongs_to.register_account(&register_schema).await.unwrap();
other_user
.modify_user_relationship(
&user.object.id.to_string(),
types::RelationshipType::Friends,
)
.modify_user_relationship(user.object.id, types::RelationshipType::Friends)
.await;
let relationships = user.get_relationships().await.unwrap();
assert_eq!(relationships.get(0).unwrap().id, other_user.object.id);
@ -82,11 +79,8 @@ async fn test_modify_relationship_friends() {
relationships.get(0).unwrap().relationship_type,
RelationshipType::Outgoing
);
user.modify_user_relationship(
other_user.object.id.to_string().as_str(),
RelationshipType::Friends,
)
.await;
user.modify_user_relationship(other_user.object.id, RelationshipType::Friends)
.await;
assert_eq!(
other_user
.get_relationships()
@ -97,8 +91,7 @@ async fn test_modify_relationship_friends() {
.relationship_type,
RelationshipType::Friends
);
user.remove_relationship(other_user.object.id.to_string().as_str())
.await;
user.remove_relationship(other_user.object.id).await;
assert_eq!(
other_user.get_relationships().await.unwrap(),
Vec::<Relationship>::new()
@ -120,10 +113,7 @@ async fn test_modify_relationship_block() {
let user = &mut bundle.user;
let mut other_user = belongs_to.register_account(&register_schema).await.unwrap();
other_user
.modify_user_relationship(
&user.object.id.to_string(),
types::RelationshipType::Blocked,
)
.modify_user_relationship(user.object.id, types::RelationshipType::Blocked)
.await;
let relationships = user.get_relationships().await.unwrap();
assert_eq!(relationships, Vec::<Relationship>::new());
@ -133,9 +123,7 @@ async fn test_modify_relationship_block() {
relationships.get(0).unwrap().relationship_type,
RelationshipType::Blocked
);
other_user
.remove_relationship(user.object.id.to_string().as_str())
.await;
other_user.remove_relationship(user.object.id).await;
assert_eq!(
other_user.get_relationships().await.unwrap(),
Vec::<Relationship>::new()

View File

@ -17,12 +17,12 @@ async fn create_and_get_roles() {
position: None,
color: None,
};
let guild_id = bundle.guild.id.clone().to_string();
let role = types::RoleObject::create(&mut bundle.user, &guild_id, role_create_schema)
let guild = bundle.guild.id;
let role = types::RoleObject::create(&mut bundle.user, guild, role_create_schema)
.await
.unwrap();
let expected = types::RoleObject::get_all(&mut bundle.user, &guild_id)
let expected = types::RoleObject::get_all(&mut bundle.user, guild)
.await
.unwrap()
.unwrap()[2]
@ -35,8 +35,8 @@ async fn create_and_get_roles() {
#[tokio::test]
async fn get_singular_role() {
let mut bundle = common::setup().await;
let guild_id = &bundle.guild.id.to_string();
let role_id = &bundle.role.id.to_string();
let guild_id = bundle.guild.id;
let role_id = bundle.role.id;
let role = bundle.role.clone();
let same_role = chorus::types::RoleObject::get(&mut bundle.user, guild_id, role_id)
.await