Skip to content

Commit

Permalink
Merge branch 'main' into next
Browse files Browse the repository at this point in the history
  • Loading branch information
vilgotf authored and Tim Vilgot Mikael Fredenberg committed Oct 14, 2023
2 parents 0914338 + b936a54 commit b6df722
Show file tree
Hide file tree
Showing 20 changed files with 278 additions and 50 deletions.
2 changes: 1 addition & 1 deletion examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ version = "0.0.0"

[dev-dependencies]
anyhow = { default-features = false, features = ["std"], version = "1" }
ed25519-dalek = "1"
ed25519-dalek = "2"
futures-util = { default-features = false, version = "0.3" }
hex = "0.4"
hyper = { features = ["client", "server", "http2", "runtime"], version = "0.14" }
Expand Down
2 changes: 1 addition & 1 deletion examples/gateway-reshard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async fn main() -> anyhow::Result<()> {
// Run `gateway_runner` and `reshard` concurrently until the first one
// finishes.
tokio::select! {
// Gateway_runner only finises on errors, so break the loop and exit
// Gateway_runner only finishes on errors, so break the loop and exit
// the program.
_ = gateway_runner(Arc::clone(&client), shards) => break,
// Resharding complete! Time to run `gateway_runner` with the new
Expand Down
6 changes: 3 additions & 3 deletions examples/model-webhook-slash.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use ed25519_dalek::{PublicKey, Verifier, PUBLIC_KEY_LENGTH};
use ed25519_dalek::{Verifier, VerifyingKey, PUBLIC_KEY_LENGTH};
use hex::FromHex;
use hyper::{
header::CONTENT_TYPE,
Expand All @@ -16,8 +16,8 @@ use twilight_model::{
};

/// Public key given from Discord.
static PUB_KEY: Lazy<PublicKey> = Lazy::new(|| {
PublicKey::from_bytes(&<[u8; PUBLIC_KEY_LENGTH] as FromHex>::from_hex("PUBLIC_KEY").unwrap())
static PUB_KEY: Lazy<VerifyingKey> = Lazy::new(|| {
VerifyingKey::from_bytes(&<[u8; PUBLIC_KEY_LENGTH] as FromHex>::from_hex("PUBLIC_KEY").unwrap())
.unwrap()
});

Expand Down
8 changes: 7 additions & 1 deletion twilight-cache-inmemory/src/event/reaction.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{config::ResourceType, InMemoryCache, UpdateCache};
use twilight_model::{
channel::message::{Reaction, ReactionType},
channel::message::{Reaction, ReactionCountDetails, ReactionType},
gateway::payload::incoming::{
ReactionAdd, ReactionRemove, ReactionRemoveAll, ReactionRemoveEmoji,
},
Expand Down Expand Up @@ -39,9 +39,15 @@ impl UpdateCache for ReactionAdd {
.unwrap_or_default();

message.reactions.push(Reaction {
burst_colors: Vec::new(),
count: 1,
count_details: ReactionCountDetails {
burst: 0,
normal: 1,
},
emoji: self.0.emoji.clone(),
me,
me_burst: false,
});
}
}
Expand Down
2 changes: 1 addition & 1 deletion twilight-cache-inmemory/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -861,7 +861,7 @@ impl UpdateCache for Event {
Event::GuildStickersUpdate(v) => c.update(v),
Event::GuildUpdate(v) => c.update(v.deref()),
Event::IntegrationCreate(v) => c.update(v.deref()),
Event::IntegrationDelete(v) => c.update(v.deref()),
Event::IntegrationDelete(v) => c.update(v),
Event::IntegrationUpdate(v) => c.update(v.deref()),
Event::InteractionCreate(v) => c.update(v.deref()),
Event::MemberAdd(v) => c.update(v.deref()),
Expand Down
1 change: 1 addition & 0 deletions twilight-gateway-queue/src/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ async fn runner(
.take(max_concurrency.into())
.collect::<Box<_>>();

#[allow(clippy::ignored_unit_patterns)]
loop {
tokio::select! {
biased;
Expand Down
2 changes: 1 addition & 1 deletion twilight-gateway-queue/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub const LIMIT_PERIOD: Duration = Duration::from_secs(60 * 60 * 24);

/// Abstraction for types processing gateway identify requests.
///
/// For convenience in twilight-gateway, implementors must also implement
/// For convenience in twilight-gateway, implementers must also implement
/// [`Debug`].
pub trait Queue: Debug {
/// Enqueue a shard with this ID.
Expand Down
2 changes: 1 addition & 1 deletion twilight-gateway/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub struct Config {
/// Session information to resume a shard on initialization.
session: Option<Session>,
/// TLS connector for Websocket connections.
// We need this to be public so [`stream`] can re-use TLS on multiple shards
// We need this to be public so [`stream`] can reuse TLS on multiple shards
// if unconfigured.
tls: Arc<Connector>,
/// Token used to authenticate when identifying with the gateway.
Expand Down
4 changes: 2 additions & 2 deletions twilight-http/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -1581,7 +1581,7 @@ Replace references to `Path::WebhooksIdTokenMessageId` with
`CreateInvite::{max_age, max_uses}` now return validation errors, so the results
returned from them need to be handled.

Don't re-use `hyper` clients via the builder. If you need to configure the
Don't reuse `hyper` clients via the builder. If you need to configure the
underlying `hyper` client please create an issue with the reason why.

Errors are no longer enums and don't expose their concrete underlying error
Expand Down Expand Up @@ -1632,7 +1632,7 @@ Return validation errors for `CreateInvite::max_age` and
Remove ability to get current user's DM channels ([#782] - [@vivian]).

Remove `ClientBuilder::hyper_client` and `From<HyperClient> for Client` which
were available to re-use `hyper` clients ([#768] - [@vivian]).
were available to reuse `hyper` clients ([#768] - [@vivian]).

Return updated copy of member when updating a member ([#758] - [@vivian]).

Expand Down
10 changes: 7 additions & 3 deletions twilight-http/src/request/guild/ban/create_ban.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::{
response::{marker::EmptyBody, Response, ResponseFuture},
routing::Route,
};
use serde::Serialize;
use std::future::IntoFuture;
use twilight_model::id::{
marker::{GuildMarker, UserMarker},
Expand All @@ -16,7 +17,9 @@ use twilight_validate::request::{
ValidationError,
};

#[derive(Serialize)]
struct CreateBanFields {
/// Number of seconds to delete messages for, between `0` and `604800`.
delete_message_seconds: Option<u32>,
}

Expand Down Expand Up @@ -120,10 +123,10 @@ impl TryIntoRequest for CreateBan<'_> {
fn try_into_request(self) -> Result<Request, Error> {
let fields = self.fields.map_err(Error::validation)?;
let mut request = Request::builder(&Route::CreateBan {
delete_message_seconds: fields.delete_message_seconds,
guild_id: self.guild_id.get(),
user_id: self.user_id.get(),
});
})
.json(&fields);

if let Some(reason) = self.reason.map_err(Error::validation)? {
request = request.headers(request::audit_header(reason)?);
Expand Down Expand Up @@ -156,10 +159,11 @@ mod tests {
let client = Client::new(String::new());
let request = client
.create_ban(GUILD_ID, USER_ID)
.delete_message_seconds(100)
.reason(REASON)
.try_into_request()?;

assert!(request.body().is_none());
assert!(request.body().is_some());
assert!(request.form().is_none());
assert_eq!(Method::Put, request.method());

Expand Down
30 changes: 30 additions & 0 deletions twilight-http/src/request/guild/create_guild_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ struct CreateGuildChannelFields<'a> {
default_reaction_emoji: Option<&'a DefaultReaction>,
#[serde(skip_serializing_if = "Option::is_none")]
default_sort_order: Option<ForumSortOrder>,
/// Initial `rate_limit_per_user` to set on newly created threads in a channel.
/// This field is copied to the thread at creation time and does not live update.
///
/// This field is only applicable for text, announcement, media, and forum channels.
#[serde(skip_serializing_if = "Option::is_none")]
default_thread_rate_limit_per_user: Option<u16>,
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
kind: Option<ChannelType>,
name: &'a str,
Expand Down Expand Up @@ -86,6 +92,7 @@ impl<'a> CreateGuildChannel<'a> {
default_forum_layout: None,
default_reaction_emoji: None,
default_sort_order: None,
default_thread_rate_limit_per_user: None,
kind: None,
name,
nsfw: None,
Expand Down Expand Up @@ -185,6 +192,29 @@ impl<'a> CreateGuildChannel<'a> {
self
}

/// Set the default number of seconds that a user must wait before before they are
/// able to send another message in any newly-created thread in the channel.
///
/// This field is only applicable for text, announcement, media, and forum channels.
/// The minimum is 0 and the maximum is 21600. This is also known as "Slow Mode". See
/// [Discord Docs/Channel Object].
///
/// [Discord Docs/Channel Object]: https://discordapp.com/developers/docs/resources/channel#channel-object-channel-structure
pub fn default_thread_rate_limit_per_user(
mut self,
default_thread_rate_limit_per_user: u16,
) -> Self {
self.fields = self.fields.and_then(|mut fields| {
validate_rate_limit_per_user(default_thread_rate_limit_per_user)?;

fields.default_thread_rate_limit_per_user = Some(default_thread_rate_limit_per_user);

Ok(fields)
});

self
}

/// Set the kind of channel.
pub fn kind(mut self, kind: ChannelType) -> Self {
if let Ok(fields) = self.fields.as_mut() {
Expand Down
31 changes: 5 additions & 26 deletions twilight-http/src/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ pub enum Route<'a> {
},
/// Route information to create a ban on a user in a guild.
CreateBan {
/// The number of seconds' worth of the user's messages to delete in the
/// guild's channels.
delete_message_seconds: Option<u32>,
/// The ID of the guild.
guild_id: u64,
/// The ID of the user.
Expand Down Expand Up @@ -1695,24 +1692,6 @@ impl Display for Route<'_> {

f.write_str("/auto-moderation/rules")
}
Route::CreateBan {
guild_id,
delete_message_seconds,
user_id,
} => {
f.write_str("guilds/")?;
Display::fmt(guild_id, f)?;
f.write_str("/bans/")?;
Display::fmt(user_id, f)?;
f.write_str("?")?;

if let Some(delete_message_seconds) = delete_message_seconds {
f.write_str("delete_message_seconds=")?;
Display::fmt(delete_message_seconds, f)?;
}

Ok(())
}
Route::CreateChannel { guild_id }
| Route::GetChannels { guild_id }
| Route::UpdateGuildChannels { guild_id } => {
Expand Down Expand Up @@ -1955,7 +1934,9 @@ impl Display for Route<'_> {

f.write_str("/crosspost")
}
Route::DeleteBan { guild_id, user_id } | Route::GetBan { guild_id, user_id } => {
Route::DeleteBan { guild_id, user_id }
| Route::GetBan { guild_id, user_id }
| Route::CreateBan { guild_id, user_id } => {
f.write_str("guilds/")?;
Display::fmt(guild_id, f)?;
f.write_str("/bans/")?;
Expand Down Expand Up @@ -4346,22 +4327,20 @@ mod tests {
fn create_ban() {
let mut route = Route::CreateBan {
guild_id: GUILD_ID,
delete_message_seconds: None,
user_id: USER_ID,
};
assert_eq!(
route.to_string(),
format!("guilds/{GUILD_ID}/bans/{USER_ID}?")
format!("guilds/{GUILD_ID}/bans/{USER_ID}")
);

route = Route::CreateBan {
guild_id: GUILD_ID,
delete_message_seconds: Some(259_200),
user_id: USER_ID,
};
assert_eq!(
route.to_string(),
format!("guilds/{GUILD_ID}/bans/{USER_ID}?delete_message_seconds=259200")
format!("guilds/{GUILD_ID}/bans/{USER_ID}")
);
}

Expand Down
2 changes: 1 addition & 1 deletion twilight-mention/src/timestamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ impl Ord for Timestamp {

impl PartialOrd for Timestamp {
fn partial_cmp(&self, other: &Timestamp) -> Option<Ordering> {
self.unix.partial_cmp(&other.unix)
Some(self.cmp(other))
}
}

Expand Down
15 changes: 15 additions & 0 deletions twilight-model/src/channel/channel_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ pub enum ChannelType {
GuildDirectory,
/// Channel that can only contain threads.
GuildForum,
/// Channel the can only contain threads with media content.
///
/// See the [help center article] for more information.
///
/// [help center article]: https://creator-support.discord.com/hc/en-us/articles/14346342766743
GuildMedia,
Unknown(u8),
}

Expand All @@ -38,6 +44,7 @@ impl From<u8> for ChannelType {
13 => ChannelType::GuildStageVoice,
14 => ChannelType::GuildDirectory,
15 => ChannelType::GuildForum,
16 => ChannelType::GuildMedia,
unknown => ChannelType::Unknown(unknown),
}
}
Expand All @@ -58,6 +65,7 @@ impl From<ChannelType> for u8 {
ChannelType::GuildStageVoice => 13,
ChannelType::GuildDirectory => 14,
ChannelType::GuildForum => 15,
ChannelType::GuildMedia => 16,
ChannelType::Unknown(unknown) => unknown,
}
}
Expand All @@ -77,6 +85,7 @@ impl ChannelType {
/// - [`GuildVoice`][`Self::GuildVoice`]
/// - [`PublicThread`][`Self::PublicThread`]
/// - [`PrivateThread`][`Self::PrivateThread`]
/// - [`GuildMedia`][`Self::GuildMedia`]
pub const fn is_guild(self) -> bool {
matches!(
self,
Expand All @@ -89,6 +98,7 @@ impl ChannelType {
| Self::GuildStageVoice
| Self::GuildText
| Self::GuildVoice
| Self::GuildMedia
)
}

Expand Down Expand Up @@ -121,6 +131,7 @@ impl ChannelType {
Self::Private => "Private",
Self::PrivateThread => "PrivateThread",
Self::PublicThread => "PublicThread",
Self::GuildMedia => "GuildMedia",
Self::Unknown(_) => "Unknown",
}
}
Expand All @@ -141,6 +152,7 @@ mod tests {
const_assert!(ChannelType::GuildStageVoice.is_guild());
const_assert!(ChannelType::GuildText.is_guild());
const_assert!(ChannelType::GuildVoice.is_guild());
const_assert!(ChannelType::GuildMedia.is_guild());

const_assert!(ChannelType::AnnouncementThread.is_thread());
const_assert!(ChannelType::PublicThread.is_thread());
Expand All @@ -159,6 +171,8 @@ mod tests {
serde_test::assert_tokens(&ChannelType::PrivateThread, &[Token::U8(12)]);
serde_test::assert_tokens(&ChannelType::GuildStageVoice, &[Token::U8(13)]);
serde_test::assert_tokens(&ChannelType::GuildDirectory, &[Token::U8(14)]);
serde_test::assert_tokens(&ChannelType::GuildForum, &[Token::U8(15)]);
serde_test::assert_tokens(&ChannelType::GuildMedia, &[Token::U8(16)]);
serde_test::assert_tokens(&ChannelType::Unknown(99), &[Token::U8(99)]);
}

Expand All @@ -175,6 +189,7 @@ mod tests {
assert_eq!("Private", ChannelType::Private.name());
assert_eq!("PrivateThread", ChannelType::PrivateThread.name());
assert_eq!("PublicThread", ChannelType::PublicThread.name());
assert_eq!("GuildMedia", ChannelType::GuildMedia.name());
assert_eq!("Unknown", ChannelType::Unknown(99).name());
}
}
Loading

0 comments on commit b6df722

Please sign in to comment.