diff --git a/src/api/auth/login.rs b/src/api/auth/login.rs index 85ba0e7..9670d15 100644 --- a/src/api/auth/login.rs +++ b/src/api/auth/login.rs @@ -5,16 +5,13 @@ use reqwest::Client; use serde_json::{from_str, json}; use crate::api::limits::LimitType; -use crate::errors::ChorusLibError; +use crate::errors::{ChorusLibError, ChorusResult}; use crate::instance::{Instance, UserMeta}; use crate::limit::LimitedRequester; use crate::types::{ErrorResponse, LoginResult, LoginSchema}; impl Instance { - pub async fn login_account( - &mut self, - login_schema: &LoginSchema, - ) -> Result { + pub async fn login_account(&mut self, login_schema: &LoginSchema) -> ChorusResult { let json_schema = json!(login_schema); let client = Client::new(); let endpoint_url = self.urls.api.clone() + "/auth/login"; diff --git a/src/api/auth/register.rs b/src/api/auth/register.rs index 0a8ec5c..b22d6ce 100644 --- a/src/api/auth/register.rs +++ b/src/api/auth/register.rs @@ -5,7 +5,7 @@ use serde_json::{from_str, json}; use crate::{ api::limits::LimitType, - errors::ChorusLibError, + errors::{ChorusLibError, ChorusResult}, instance::{Instance, Token, UserMeta}, limit::LimitedRequester, types::{ErrorResponse, RegisterSchema}, @@ -24,7 +24,7 @@ impl Instance { pub async fn register_account( &mut self, register_schema: &RegisterSchema, - ) -> Result { + ) -> ChorusResult { let json_schema = json!(register_schema); let client = Client::new(); let endpoint_url = self.urls.api.clone() + "/auth/register"; diff --git a/src/api/channels/channels.rs b/src/api/channels/channels.rs index 94e0993..08a6617 100644 --- a/src/api/channels/channels.rs +++ b/src/api/channels/channels.rs @@ -3,13 +3,13 @@ use serde_json::to_string; use crate::{ api::common, - errors::ChorusLibError, + errors::{ChorusLibError, ChorusResult}, instance::UserMeta, - types::{Channel, ChannelModifySchema, Message, Snowflake}, + types::{Channel, ChannelModifySchema, GetChannelMessagesSchema, Message, Snowflake}, }; impl Channel { - pub async fn get(user: &mut UserMeta, channel_id: &str) -> Result { + pub async fn get(user: &mut UserMeta, channel_id: &str) -> ChorusResult { let url = user.belongs_to.borrow_mut().urls.api.clone(); let request = Client::new() .get(format!("{}/channels/{}/", url, channel_id)) @@ -43,7 +43,7 @@ impl Channel { /// # Returns /// /// A `Result` that contains a `ChorusLibError` if an error occurred during the request, or `()` if the request was successful. - pub async fn delete(self, user: &mut UserMeta) -> Result<(), ChorusLibError> { + pub async fn delete(self, user: &mut UserMeta) -> ChorusResult<()> { let request = Client::new() .delete(format!( "{}/channels/{}/", @@ -73,7 +73,7 @@ impl Channel { modify_data: ChannelModifySchema, channel_id: Snowflake, user: &mut UserMeta, - ) -> Result { + ) -> ChorusResult { let request = Client::new() .patch(format!( "{}/channels/{}/", @@ -89,4 +89,21 @@ impl Channel { ) .await } + + pub async fn messages( + range: GetChannelMessagesSchema, + channel_id: Snowflake, + user: &mut UserMeta, + ) -> Result, ChorusLibError> { + let request = Client::new() + .get(format!( + "{}/channels/{}/messages", + user.belongs_to.borrow().urls.api, + channel_id + )) + .bearer_auth(user.token()) + .query(&range); + + common::deserialize_response::>(request, user, Default::default()).await + } } diff --git a/src/api/channels/permissions.rs b/src/api/channels/permissions.rs index 361b4e1..0958821 100644 --- a/src/api/channels/permissions.rs +++ b/src/api/channels/permissions.rs @@ -3,7 +3,7 @@ use serde_json::to_string; use crate::{ api::handle_request_as_result, - errors::ChorusLibError, + errors::{ChorusLibError, ChorusResult}, instance::UserMeta, types::{self, PermissionOverwrite, Snowflake}, }; @@ -24,7 +24,7 @@ impl types::Channel { user: &mut UserMeta, channel_id: Snowflake, overwrite: PermissionOverwrite, - ) -> Result<(), ChorusLibError> { + ) -> ChorusResult<()> { let url = { format!( "{}/channels/{}/permissions/{}", @@ -60,7 +60,7 @@ impl types::Channel { user: &mut UserMeta, channel_id: Snowflake, overwrite_id: Snowflake, - ) -> Result<(), ChorusLibError> { + ) -> ChorusResult<()> { let url = format!( "{}/channels/{}/permissions/{}", user.belongs_to.borrow_mut().urls.api, diff --git a/src/api/channels/reactions.rs b/src/api/channels/reactions.rs index 0f04c5e..210fe72 100644 --- a/src/api/channels/reactions.rs +++ b/src/api/channels/reactions.rs @@ -1,6 +1,6 @@ use reqwest::Client; -use crate::{api::handle_request_as_result, errors::ChorusLibError, instance::UserMeta, types}; +use crate::{api::handle_request_as_result, errors::ChorusResult, instance::UserMeta, types}; /** Useful metadata for working with [`types::Reaction`], bundled together nicely. @@ -25,7 +25,7 @@ impl ReactionMeta { # Reference See [https://discord.com/developers/docs/resources/channel#delete-all-reactions](https://discord.com/developers/docs/resources/channel#delete-all-reactions) */ - pub async fn delete_all(&self, user: &mut UserMeta) -> Result<(), ChorusLibError> { + pub async fn delete_all(&self, user: &mut UserMeta) -> ChorusResult<()> { let url = format!( "{}/channels/{}/messages/{}/reactions/", user.belongs_to.borrow().urls.api, @@ -51,7 +51,7 @@ impl ReactionMeta { # Reference See [https://discord.com/developers/docs/resources/channel#get-reactions](https://discord.com/developers/docs/resources/channel#get-reactions) */ - pub async fn get(&self, emoji: &str, user: &mut UserMeta) -> Result<(), ChorusLibError> { + pub async fn get(&self, emoji: &str, user: &mut UserMeta) -> ChorusResult<()> { let url = format!( "{}/channels/{}/messages/{}/reactions/{}/", user.belongs_to.borrow().urls.api, @@ -80,11 +80,7 @@ impl ReactionMeta { # Reference See [https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji](https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji) */ - pub async fn delete_emoji( - &self, - emoji: &str, - user: &mut UserMeta, - ) -> Result<(), ChorusLibError> { + pub async fn delete_emoji(&self, emoji: &str, user: &mut UserMeta) -> ChorusResult<()> { let url = format!( "{}/channels/{}/messages/{}/reactions/{}/", user.belongs_to.borrow().urls.api, @@ -115,7 +111,7 @@ impl ReactionMeta { # Reference See [https://discord.com/developers/docs/resources/channel#create-reaction](https://discord.com/developers/docs/resources/channel#create-reaction) */ - pub async fn create(&self, emoji: &str, user: &mut UserMeta) -> Result<(), ChorusLibError> { + pub async fn create(&self, emoji: &str, user: &mut UserMeta) -> ChorusResult<()> { let url = format!( "{}/channels/{}/messages/{}/reactions/{}/@me/", user.belongs_to.borrow().urls.api, @@ -143,7 +139,7 @@ impl ReactionMeta { # Reference See [https://discord.com/developers/docs/resources/channel#delete-own-reaction](https://discord.com/developers/docs/resources/channel#delete-own-reaction) */ - pub async fn remove(&self, emoji: &str, user: &mut UserMeta) -> Result<(), ChorusLibError> { + pub async fn remove(&self, emoji: &str, user: &mut UserMeta) -> ChorusResult<()> { let url = format!( "{}/channels/{}/messages/{}/reactions/{}/@me/", user.belongs_to.borrow().urls.api, @@ -179,7 +175,7 @@ impl ReactionMeta { user_id: &str, emoji: &str, user: &mut UserMeta, - ) -> Result<(), ChorusLibError> { + ) -> ChorusResult<()> { let url = format!( "{}/channels/{}/messages/{}/reactions/{}/{}", user.belongs_to.borrow().urls.api, diff --git a/src/api/common.rs b/src/api/common.rs index e627c9f..86a972e 100644 --- a/src/api/common.rs +++ b/src/api/common.rs @@ -2,7 +2,11 @@ use reqwest::RequestBuilder; use serde::Deserialize; use serde_json::from_str; -use crate::{errors::ChorusLibError, instance::UserMeta, limit::LimitedRequester}; +use crate::{ + errors::{ChorusLibError, ChorusResult}, + instance::UserMeta, + limit::LimitedRequester, +}; use super::limits::LimitType; @@ -27,7 +31,7 @@ pub async fn handle_request_as_result( request: RequestBuilder, user: &mut UserMeta, limit_type: LimitType, -) -> Result<(), ChorusLibError> { +) -> ChorusResult<()> { match handle_request(request, user, limit_type).await { Ok(_) => Ok(()), Err(e) => Err(ChorusLibError::InvalidResponseError { @@ -40,7 +44,7 @@ pub async fn deserialize_response Deserialize<'a>>( request: RequestBuilder, user: &mut UserMeta, limit_type: LimitType, -) -> Result { +) -> ChorusResult { let response = handle_request(request, user, limit_type).await.unwrap(); let response_text = match response.text().await { Ok(string) => string, diff --git a/src/api/guilds/guilds.rs b/src/api/guilds/guilds.rs index 14bb8b8..d638f0b 100644 --- a/src/api/guilds/guilds.rs +++ b/src/api/guilds/guilds.rs @@ -7,6 +7,7 @@ use crate::api::handle_request; use crate::api::handle_request_as_result; use crate::api::limits::Limits; use crate::errors::ChorusLibError; +use crate::errors::ChorusResult; use crate::instance::Instance; use crate::instance::UserMeta; use crate::limit::LimitedRequester; @@ -32,7 +33,7 @@ impl Guild { pub async fn create( user: &mut UserMeta, guild_create_schema: GuildCreateSchema, - ) -> Result { + ) -> ChorusResult { let url = format!("{}/guilds/", user.belongs_to.borrow().urls.api); let request = reqwest::Client::new() .post(url.clone()) @@ -65,7 +66,7 @@ impl Guild { /// None => println!("Guild deleted successfully"), /// } /// ``` - pub async fn delete(user: &mut UserMeta, guild_id: &str) -> Result<(), ChorusLibError> { + pub async fn delete(user: &mut UserMeta, guild_id: &str) -> ChorusResult<()> { let url = format!( "{}/guilds/{}/delete/", user.belongs_to.borrow().urls.api, @@ -94,7 +95,7 @@ impl Guild { &self, user: &mut UserMeta, schema: ChannelCreateSchema, - ) -> Result { + ) -> ChorusResult { let mut belongs_to = user.belongs_to.borrow_mut(); Channel::_create( &user.token, @@ -116,7 +117,7 @@ impl Guild { /// * `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, user: &mut UserMeta) -> Result, ChorusLibError> { + pub async fn channels(&self, user: &mut UserMeta) -> ChorusResult> { let request = Client::new() .get(format!( "{}/guilds/{}/channels/", @@ -155,7 +156,7 @@ impl Guild { /// * `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) -> Result { + pub async fn get(user: &mut UserMeta, guild_id: &str) -> ChorusResult { let mut belongs_to = user.belongs_to.borrow_mut(); Guild::_get( &format!("{}", belongs_to.urls.api), @@ -175,7 +176,7 @@ impl Guild { token: &str, limits_user: &mut Limits, instance: &mut Instance, - ) -> Result { + ) -> ChorusResult { let request = Client::new() .get(format!("{}/guilds/{}/", url_api, guild_id)) .bearer_auth(token); @@ -214,7 +215,7 @@ impl Channel { user: &mut UserMeta, guild_id: &str, schema: ChannelCreateSchema, - ) -> Result { + ) -> ChorusResult { let mut belongs_to = user.belongs_to.borrow_mut(); Channel::_create( &user.token, @@ -234,7 +235,7 @@ impl Channel { schema: ChannelCreateSchema, limits_user: &mut Limits, instance: &mut Instance, - ) -> Result { + ) -> ChorusResult { let request = Client::new() .post(format!("{}/guilds/{}/channels/", url_api, guild_id)) .bearer_auth(token) diff --git a/src/api/guilds/member.rs b/src/api/guilds/member.rs index 7b18aa7..b0f91a4 100644 --- a/src/api/guilds/member.rs +++ b/src/api/guilds/member.rs @@ -2,7 +2,7 @@ use reqwest::Client; use crate::{ api::{deserialize_response, handle_request_as_result}, - errors::ChorusLibError, + errors::ChorusResult, instance::UserMeta, types, }; @@ -23,7 +23,7 @@ impl types::GuildMember { user: &mut UserMeta, guild_id: &str, member_id: &str, - ) -> Result { + ) -> ChorusResult { let url = format!( "{}/guilds/{}/members/{}/", user.belongs_to.borrow().urls.api, @@ -56,7 +56,7 @@ impl types::GuildMember { guild_id: &str, member_id: &str, role_id: &str, - ) -> Result<(), ChorusLibError> { + ) -> ChorusResult<()> { let url = format!( "{}/guilds/{}/members/{}/roles/{}/", user.belongs_to.borrow().urls.api, diff --git a/src/api/guilds/roles.rs b/src/api/guilds/roles.rs index f05b7f1..841a4ed 100644 --- a/src/api/guilds/roles.rs +++ b/src/api/guilds/roles.rs @@ -3,7 +3,7 @@ use serde_json::to_string; use crate::{ api::deserialize_response, - errors::ChorusLibError, + errors::{ChorusLibError, ChorusResult}, instance::UserMeta, types::{self, RoleCreateModifySchema, RoleObject}, }; @@ -26,7 +26,7 @@ impl types::RoleObject { pub async fn get_all( user: &mut UserMeta, guild_id: &str, - ) -> Result>, ChorusLibError> { + ) -> ChorusResult>> { let url = format!( "{}/guilds/{}/roles/", user.belongs_to.borrow().urls.api, @@ -65,7 +65,7 @@ impl types::RoleObject { user: &mut UserMeta, guild_id: &str, role_id: &str, - ) -> Result { + ) -> ChorusResult { let url = format!( "{}/guilds/{}/roles/{}/", user.belongs_to.borrow().urls.api, @@ -95,7 +95,7 @@ impl types::RoleObject { user: &mut UserMeta, guild_id: &str, role_create_schema: RoleCreateModifySchema, - ) -> Result { + ) -> ChorusResult { let url = format!( "{}/guilds/{}/roles/", user.belongs_to.borrow().urls.api, @@ -129,7 +129,7 @@ impl types::RoleObject { user: &mut UserMeta, guild_id: &str, role_position_update_schema: types::RolePositionUpdateSchema, - ) -> Result { + ) -> ChorusResult { let url = format!( "{}/guilds/{}/roles/", user.belongs_to.borrow().urls.api, @@ -169,7 +169,7 @@ impl types::RoleObject { guild_id: &str, role_id: &str, role_create_schema: RoleCreateModifySchema, - ) -> Result { + ) -> ChorusResult { let url = format!( "{}/guilds/{}/roles/{}", user.belongs_to.borrow().urls.api, diff --git a/src/api/policies/instance/instance.rs b/src/api/policies/instance/instance.rs index 4a47f24..0ea3699 100644 --- a/src/api/policies/instance/instance.rs +++ b/src/api/policies/instance/instance.rs @@ -1,7 +1,7 @@ use reqwest::Client; use serde_json::from_str; -use crate::errors::ChorusLibError; +use crate::errors::{ChorusLibError, ChorusResult}; use crate::instance::Instance; use crate::types::GeneralConfiguration; @@ -9,9 +9,7 @@ impl Instance { /// Gets the instance policies schema. /// # Errors /// [`ChorusLibError`] - If the request fails. - pub async fn general_configuration_schema( - &self, - ) -> Result { + pub async fn general_configuration_schema(&self) -> ChorusResult { let client = Client::new(); let endpoint_url = self.urls.api.clone() + "/policies/instance/"; let request = match client.get(&endpoint_url).send().await { diff --git a/src/api/users/relationships.rs b/src/api/users/relationships.rs index 2584ff5..add61df 100644 --- a/src/api/users/relationships.rs +++ b/src/api/users/relationships.rs @@ -3,7 +3,7 @@ use serde_json::to_string; use crate::{ api::{deserialize_response, handle_request_as_result}, - errors::ChorusLibError, + errors::ChorusResult, instance::UserMeta, types::{self, CreateUserRelationshipSchema, RelationshipType}, }; @@ -16,11 +16,11 @@ impl UserMeta { /// * `user_id` - A string slice that holds the ID of the user to retrieve the mutual relationships with. /// /// # Returns - /// This function returns a [`Result, ChorusLibError>`]. + /// This function returns a [`ChorusResult>`]. pub async fn get_mutual_relationships( &mut self, user_id: &str, - ) -> Result, ChorusLibError> { + ) -> ChorusResult> { let url = format!( "{}/users/{}/relationships/", self.belongs_to.borrow().urls.api, @@ -38,8 +38,8 @@ impl UserMeta { /// Retrieves the authenticated user's relationships. /// /// # Returns - /// This function returns a [`Result, ChorusLibError>`]. - pub async fn get_relationships(&mut self) -> Result, ChorusLibError> { + /// This function returns a [`ChorusResult>`]. + pub async fn get_relationships(&mut self) -> ChorusResult> { let url = format!( "{}/users/@me/relationships/", self.belongs_to.borrow().urls.api @@ -64,7 +64,7 @@ impl UserMeta { pub async fn send_friend_request( &mut self, schema: types::FriendRequestSendSchema, - ) -> Result<(), ChorusLibError> { + ) -> ChorusResult<()> { let url = format!( "{}/users/@me/relationships/", self.belongs_to.borrow().urls.api @@ -92,7 +92,7 @@ impl UserMeta { &mut self, user_id: &str, relationship_type: RelationshipType, - ) -> Result<(), ChorusLibError> { + ) -> ChorusResult<()> { let api_url = self.belongs_to.borrow().urls.api.clone(); match relationship_type { RelationshipType::None => { @@ -137,7 +137,7 @@ impl UserMeta { /// /// # Returns /// This function returns a [`Result`] that holds a [`ChorusLibError`] if the request fails. - pub async fn remove_relationship(&mut self, user_id: &str) -> Result<(), ChorusLibError> { + pub async fn remove_relationship(&mut self, user_id: &str) -> ChorusResult<()> { let url = format!( "{}/users/@me/relationships/{}/", self.belongs_to.borrow().urls.api, diff --git a/src/api/users/users.rs b/src/api/users/users.rs index 4144b03..cd777dc 100644 --- a/src/api/users/users.rs +++ b/src/api/users/users.rs @@ -2,8 +2,8 @@ use reqwest::Client; use serde_json::to_string; use crate::{ - api::{deserialize_response, handle_request_as_result, limits::Limits}, - errors::ChorusLibError, + api::{deserialize_response, handle_request_as_result}, + errors::{ChorusLibError, ChorusResult}, instance::{Instance, UserMeta}, limit::LimitedRequester, types::{User, UserModifySchema, UserSettings}, @@ -22,7 +22,7 @@ impl UserMeta { /// # Errors /// /// * [`ChorusLibError`] - If the request fails. - pub async fn get(user: &mut UserMeta, id: Option<&String>) -> Result { + pub async fn get(user: &mut UserMeta, id: Option<&String>) -> ChorusResult { User::get(user, id).await } @@ -30,7 +30,7 @@ impl UserMeta { token: &String, url_api: &String, instance: &mut Instance, - ) -> Result { + ) -> ChorusResult { User::get_settings(token, url_api, instance).await } @@ -43,10 +43,7 @@ impl UserMeta { /// # Errors /// /// Returns an `ChorusLibError` if the request fails or if a password is required but not provided. - pub async fn modify( - &mut self, - modify_schema: UserModifySchema, - ) -> Result { + pub async fn modify(&mut self, modify_schema: UserModifySchema) -> ChorusResult { if modify_schema.new_password.is_some() || modify_schema.email.is_some() || modify_schema.code.is_some() @@ -74,7 +71,7 @@ impl UserMeta { /// # Returns /// /// Returns `()` if the user was successfully deleted, or a `ChorusLibError` if an error occurred. - pub async fn delete(mut self) -> Result<(), ChorusLibError> { + pub async fn delete(mut self) -> ChorusResult<()> { let request = Client::new() .post(format!( "{}/users/@me/delete/", @@ -86,7 +83,7 @@ impl UserMeta { } impl User { - pub async fn get(user: &mut UserMeta, id: Option<&String>) -> Result { + pub async fn get(user: &mut UserMeta, id: Option<&String>) -> ChorusResult { let mut belongs_to = user.belongs_to.borrow_mut(); User::_get( &user.token(), @@ -102,7 +99,7 @@ impl User { url_api: &str, instance: &mut Instance, id: Option<&String>, - ) -> Result { + ) -> ChorusResult { let url = if id.is_none() { format!("{}/users/@me/", url_api) } else { @@ -130,7 +127,7 @@ impl User { token: &String, url_api: &String, instance: &mut Instance, - ) -> Result { + ) -> ChorusResult { let request: reqwest::RequestBuilder = Client::new() .get(format!("{}/users/@me/settings/", url_api)) .bearer_auth(token); @@ -160,11 +157,7 @@ impl Instance { # Notes This function is a wrapper around [`User::get`]. */ - pub async fn get_user( - &mut self, - token: String, - id: Option<&String>, - ) -> Result { + pub async fn get_user(&mut self, token: String, id: Option<&String>) -> ChorusResult { User::_get(&token, &self.urls.api.clone(), self, id).await } } diff --git a/src/errors.rs b/src/errors.rs index 37c165c..0a689f7 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -9,6 +9,8 @@ custom_error! { EmailError = "The provided email address is in an invalid format.", } +pub type ChorusResult = std::result::Result; + custom_error! { #[derive(PartialEq, Eq)] pub ChorusLibError diff --git a/src/instance.rs b/src/instance.rs index 2bdbbb7..2477217 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -6,7 +6,7 @@ use reqwest::Client; use serde::{Deserialize, Serialize}; use crate::api::limits::Limits; -use crate::errors::{ChorusLibError, FieldFormatError}; +use crate::errors::{ChorusLibError, ChorusResult, FieldFormatError}; use crate::types::{GeneralConfiguration, User, UserSettings}; use crate::UrlBundle; @@ -28,7 +28,7 @@ impl Instance { /// * `requester` - The [`LimitedRequester`] that will be used to make requests to the Spacebar server. /// # Errors /// * [`InstanceError`] - If the instance cannot be created. - pub async fn new(urls: UrlBundle) -> Result { + pub async fn new(urls: UrlBundle) -> ChorusResult { let mut instance = Instance { urls: urls.clone(), // Will be overwritten in the next step diff --git a/src/limit.rs b/src/limit.rs index 9f453a7..4415e0c 100644 --- a/src/limit.rs +++ b/src/limit.rs @@ -2,7 +2,7 @@ use reqwest::{RequestBuilder, Response}; use crate::{ api::limits::{Limit, LimitType, Limits, LimitsMutRef}, - errors::ChorusLibError, + errors::{ChorusLibError, ChorusResult}, instance::Instance, }; @@ -43,7 +43,7 @@ impl LimitedRequester { limit_type: LimitType, instance: &mut Instance, user_rate_limits: &mut Limits, - ) -> Result { + ) -> ChorusResult { if LimitedRequester::can_send_request(limit_type, &instance.limits, user_rate_limits) { let built_request = match request.build() { Ok(request) => request, @@ -256,7 +256,7 @@ mod rate_limit { String::from("wss://localhost:3001/"), String::from("http://localhost:3001/cdn"), ); - let mut request: Option> = None; + let mut request: Option> = None; let mut instance = Instance::new(urls.clone()).await.unwrap(); let mut user_rate_limits = Limits::check_limits(urls.api.clone()).await; diff --git a/src/types/schema/channel.rs b/src/types/schema/channel.rs index eff8277..2a78142 100644 --- a/src/types/schema/channel.rs +++ b/src/types/schema/channel.rs @@ -47,3 +47,50 @@ pub struct ChannelModifySchema { pub default_thread_rate_limit_per_user: Option, pub video_quality_mode: Option, } + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct GetChannelMessagesSchema { + /// Between 1 and 100, defaults to 50. + pub limit: Option, + #[serde(flatten)] + pub anchor: ChannelMessagesAnchor, +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +#[serde(rename_all = "snake_case")] +pub enum ChannelMessagesAnchor { + Before(Snowflake), + Around(Snowflake), + After(Snowflake), +} + +impl GetChannelMessagesSchema { + pub fn before(anchor: Snowflake) -> Self { + Self { + limit: None, + anchor: ChannelMessagesAnchor::Before(anchor), + } + } + + pub fn around(anchor: Snowflake) -> Self { + Self { + limit: None, + anchor: ChannelMessagesAnchor::Around(anchor), + } + } + + pub fn after(anchor: Snowflake) -> Self { + Self { + limit: None, + anchor: ChannelMessagesAnchor::After(anchor), + } + } + + /// Must be between 1 and 100 + pub fn limit(self, limit: i32) -> Self { + Self { + limit: Some(limit), + ..self + } + } +} diff --git a/tests/channel.rs b/tests/channel.rs index 2fad72c..002ee43 100644 --- a/tests/channel.rs +++ b/tests/channel.rs @@ -1,4 +1,7 @@ -use chorus::types::{self, Channel, PermissionFlags, PermissionOverwrite}; +use chorus::types::{ + self, Channel, GetChannelMessagesSchema, MessageSendSchema, PermissionFlags, + PermissionOverwrite, Snowflake, +}; mod common; @@ -77,3 +80,60 @@ async fn modify_channel() { common::teardown(bundle).await } + +#[tokio::test] +async fn get_channel_messages() { + let mut bundle = common::setup().await; + + // First create some messages to read + for _ in 0..10 { + let _ = bundle + .user + .send_message( + &mut MessageSendSchema { + content: Some("A Message!".to_string()), + ..Default::default() + }, + bundle.channel.id, + None, + ) + .await + .unwrap(); + } + + assert_eq!( + Channel::messages( + GetChannelMessagesSchema::before(Snowflake::generate()), + bundle.channel.id, + &mut bundle.user, + ) + .await + .unwrap() + .len(), + 10 + ); + + // around is currently bugged in spacebar: https://github.com/spacebarchat/server/issues/1072 + // assert_eq!( + // Channel::messages( + // GetChannelMessagesSchema::around(Snowflake::generate()).limit(10), + // bundle.channel.id, + // &mut bundle.user, + // ) + // .await + // .unwrap() + // .len(), + // 5 + // ); + + assert!(Channel::messages( + GetChannelMessagesSchema::after(Snowflake::generate()), + bundle.channel.id, + &mut bundle.user, + ) + .await + .unwrap() + .is_empty()); + + common::teardown(bundle).await +} diff --git a/tests/message.rs b/tests/message.rs index a8bd2bd..94f3734 100644 --- a/tests/message.rs +++ b/tests/message.rs @@ -64,20 +64,3 @@ async fn send_message_attachment() { .unwrap(); common::teardown(bundle).await } - -#[tokio::test] -async fn read_messages() { - let mut bundle = common::setup().await; - - // First create some messages to read - let mut message = types::MessageSendSchema { - content: Some("A Message!".to_string()), - ..Default::default() - }; - let _ = bundle - .user - .send_message(&mut message, bundle.channel.id, None) - .await - .unwrap(); - common::teardown(bundle).await -}