Skip to content

Commit

Permalink
Merge branch 'release/0.2.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
Juici committed Jan 16, 2020
2 parents dfaf65d + 16294b3 commit 38df9f7
Show file tree
Hide file tree
Showing 45 changed files with 4,397 additions and 817 deletions.
1 change: 1 addition & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
github: Juici
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Rust/Cargo
/target
**/*.rs.bk
Cargo.lock

# Discord Token
examples/.token
13 changes: 9 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "strife"
version = "0.0.1"
version = "0.2.0"
authors = ["James Whaley <[email protected]>"]
description = "A lightweight library for the Discord API."
license = "MIT"
Expand All @@ -15,6 +15,10 @@ keywords = ["discord", "api", "async"]

edition = "2018"

[features]
default = []
systime_ratelimits = []

[dependencies]
async-std = "1.3"
bitflags = "1.2"
Expand All @@ -25,11 +29,12 @@ hyper = "0.13"
hyper-tls = "0.4"
int-enum = { version = "0.3", features = ["serialize", "convert"] }
log = "0.4"
num-traits = "0.2"
remain = "0.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "1.0"

[features]
default = []
systime_ratelimits = []
[dev-dependencies]
pretty_env_logger = "0.3"
tokio = { version = "0.2", features = ["full"] }
32 changes: 32 additions & 0 deletions examples/current_user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use std::env;
use std::fs;

use strife::http::unstable::{Request, Route};
use strife::model::user::ClientUser;
use strife::{Error, Http};

#[tokio::main]
async fn main() -> Result<(), Error> {
// Initialize pretty logging.
pretty_env_logger::init();

// Get token from `DISCORD_TOKEN` environment variable or `.token` file.
let token = env::var("DISCORD_TOKEN")
.or_else(|_| fs::read_to_string(".token"))
.expect("missing discord token");

// Create an http client using our token.
let http = Http::new(token);

// Request information on the current user.
let user: ClientUser = http.request(Request::new(Route::GetCurrentUser)).await?;

println!(
"Client User: {name}#{discriminator} ({id})",
name = user.name,
discriminator = user.discriminator,
id = user.id
);

Ok(())
}
9 changes: 0 additions & 9 deletions src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,6 @@ impl Client {
S: AsRef<str>,
H: EventHandler + Send + Sync + 'static,
{
let token = token.as_ref().trim();

// Prepend "Bot " to token if required.
let token = if token.starts_with("Bot ") {
token.to_string()
} else {
format!("Bot {}", token)
};

let _http = Http::new(token);

// TODO: thread pool
Expand Down
2 changes: 1 addition & 1 deletion src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ pub const MESSAGE_MAX_LENGTH: usize = 2000;
pub const USER_AGENT: &str = concat!("DiscordBot (", pkg_repo!(), ", ", pkg_version!(), ")");

/// Gateway opcodes.
#[int_enum::int_enum(u8)]
#[non_exhaustive]
#[int_enum::int_enum(u8)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum OpCode {
/// Dispatches an event.
Expand Down
10 changes: 9 additions & 1 deletion src/http/client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use async_std::sync::Arc;

use bytes::Bytes;
use serde::de::DeserializeOwned;

use crate::internal::prelude::*;
Expand All @@ -17,7 +18,14 @@ pub struct Http {
impl Http {
/// Creates a new HTTP client with the given API token.
pub fn new<S: AsRef<str>>(token: S) -> Http {
let token = token.as_ref();
// Trim whitespace from token.
let token = token.as_ref().trim();
// Add "Bot " prefix to token if necessary.
let token = if token.starts_with("Bot ") {
Bytes::copy_from_slice(token.as_bytes())
} else {
Bytes::from(format!("Bot {}", token))
};

let client = hyper::Client::builder().build(HttpsConnector::new());
let client = Arc::new(client);
Expand Down
7 changes: 5 additions & 2 deletions src/http/ratelimit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,12 @@ pub struct RateLimiter {

impl RateLimiter {
/// Creates a new rate limit manager.
pub fn new<S: AsRef<str>>(client: Arc<HyperClient>, token: S) -> RateLimiter {
pub fn new<T>(client: Arc<HyperClient>, token: T) -> RateLimiter
where
T: Into<Bytes>,
{
RateLimiter {
token: Bytes::copy_from_slice(token.as_ref().as_bytes()),
token: token.into(),
client,
global: Default::default(),
routes: Default::default(),
Expand Down
13 changes: 12 additions & 1 deletion src/http/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::fmt::Write;

use hyper::Method as HttpMethod;

use crate::model::channel::OverwriteId;
use crate::model::channel::permissions::OverwriteId;
use crate::model::guild::{AuditLogEvent, Emoji};
use crate::model::id::*;

Expand Down Expand Up @@ -249,6 +249,11 @@ pub enum Bucket {
UsersMeChannels,
/// Route:
/// ```text
/// /users/@me/guilds
/// ```
UsersMeGuilds,
/// Route:
/// ```text
/// /users/@me/guilds/{guild.id}
/// ```
UsersMeGuildsId(GuildId),
Expand Down Expand Up @@ -469,6 +474,7 @@ pub enum Route<'a> {
channel_id: ChannelId,
},
GetCurrentUser,
GetCurrentUserGuilds,
GetEmoji {
guild_id: GuildId,
emoji_id: EmojiId,
Expand Down Expand Up @@ -652,6 +658,7 @@ impl<'a> Route<'a> {
GetChannels { .. } => Method::Get,
GetChannelWebhooks { .. } => Method::Get,
GetCurrentUser => Method::Get,
GetCurrentUserGuilds => Method::Get,
GetEmoji { .. } => Method::Get,
GetGateway => Method::Get,
GetGuild { .. } => Method::Get,
Expand Down Expand Up @@ -816,6 +823,8 @@ impl<'a> Route<'a> {

GetCurrentUser | EditCurrentUser | GetUser { .. } => Bucket::UsersId,

GetCurrentUserGuilds => Bucket::UsersMeGuilds,

LeaveGuild { guild_id } => Bucket::UsersMeGuildsId(guild_id),

CreatePrivateChannel => Bucket::UsersMeChannels,
Expand Down Expand Up @@ -1131,6 +1140,8 @@ impl<'a> Route<'a> {

GetCurrentUser | EditCurrentUser => Cow::from(api!("/users/@me")),

GetCurrentUserGuilds => Cow::from(api!("/users/@me/guilds")),

GetUser { user_id } => Cow::from(api!("/users/{}", user_id)),

LeaveGuild { guild_id } => Cow::from(api!("/user/@me/guilds/{}", guild_id)),
Expand Down
46 changes: 27 additions & 19 deletions src/internal/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,12 @@ macro_rules! pkg_repo {
}

#[doc(hidden)]
macro_rules! api_base {
macro_rules! __api {
() => {
"https://discordapp.com/api/v6"
};
}

#[doc(hidden)]
macro_rules! __api {
(@s $s:expr) => {
concat!(api_base!(), $s)
concat!(__api!(), $s)
};
(@s $s:expr; @a $($arg:expr),*) => {
format!(__api!(@s $s), $($arg),*)
Expand Down Expand Up @@ -61,6 +57,9 @@ macro_rules! __api {
}

macro_rules! api {
() => {
__api!()
};
($s:expr) => {
__api!(@s $s)
};
Expand Down Expand Up @@ -114,37 +113,46 @@ macro_rules! wrap {
};
}

macro_rules! impl_to_snowflake {
($T:ident: |$_self:ident| $($map:tt)*) => {
#[doc(hidden)]
impl $crate::model::snowflake::private::Sealed for $T {}

impl $crate::model::snowflake::ToSnowflake for $T {
fn snowflake(&self) -> $crate::model::snowflake::Snowflake {
match self {
$_self => { $($map)* }
}
}
}
};
}

#[cfg(test)]
mod tests {
const ID: u64 = 80351110224678912;

#[test]
fn test_basic() {
assert_eq!(api_base!(), api!(""));
assert_eq!(concat!(api_base!(), "/guilds"), api!("/guilds"));
assert_eq!(concat!(api!(), "/guilds"), api!("/guilds"));
}

#[test]
fn test_arg() {
assert_eq!(
format!("{}/guilds/{}/audit-logs", api_base!(), ID),
format!("{}/guilds/{}/audit-logs", api!(), ID),
api!("/guilds/{}/audit-logs", ID)
);
assert_eq!(
format!("{}/guilds/{}/audit-logs", api_base!(), ID),
format!("{}/guilds/{}/audit-logs", api!(), ID),
api!("/guilds/{}/audit-logs", ID; [])
);
}

#[test]
fn test_query_basic() {
let user_id: u64 = 123;
let url = format!(
"{}/guilds/{}/audit-logs?&user_id={}",
api_base!(),
ID,
user_id
);
let url = format!("{}/guilds/{}/audit-logs?&user_id={}", api!(), ID, user_id);

assert_eq!(
url,
Expand All @@ -157,7 +165,7 @@ mod tests {
#[test]
fn test_query_none() {
let user_id: Option<u64> = None;
let url = format!("{}/guilds/{}/audit-logs?", api_base!(), ID);
let url = format!("{}/guilds/{}/audit-logs?", api!(), ID);

assert_eq!(
url,
Expand All @@ -172,7 +180,7 @@ mod tests {
let user_id: Option<u64> = Some(456);
let url = format!(
"{}/guilds/{}/audit-logs?&user_id={}",
api_base!(),
api!(),
ID,
user_id.unwrap()
);
Expand All @@ -194,7 +202,7 @@ mod tests {

let url = format!(
"{}/guilds/{}/audit-logs?&user_id={}&limit={}&action_type={}",
api_base!(),
api!(),
ID,
user_id,
limit,
Expand Down
4 changes: 4 additions & 0 deletions src/internal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ mod macros;

pub mod prelude;

#[macro_use]
#[doc(hidden)]
pub mod test;

/// From core::fmt::num [impl_Display] macro.
///
/// [impl_Display]: https://doc.rust-lang.org/src/core/fmt/num.rs.html#192-238
Expand Down
Loading

0 comments on commit 38df9f7

Please sign in to comment.