Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(http, gateway, model, validate): Add support for premium apps #2282

Merged
merged 25 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
f9f00df
add initial entitlement structure
suneettipirneni Sep 26, 2023
8053319
start implementing request structure
suneettipirneni Sep 26, 2023
8b6cd8d
add get entitlements route
suneettipirneni Sep 27, 2023
d1f5b20
Add create test entitlement route
suneettipirneni Sep 27, 2023
eec8e21
add delete test entitlement route
suneettipirneni Sep 27, 2023
3509480
entitlement create event
suneettipirneni Sep 28, 2023
bab4c79
entitlement update event
suneettipirneni Sep 28, 2023
02141c4
entitlement delete event
suneettipirneni Sep 28, 2023
4992b3d
update interactions to support premium apps
suneettipirneni Sep 28, 2023
faaea85
update interaction caching
suneettipirneni Sep 28, 2023
73410c0
update standby
suneettipirneni Sep 28, 2023
ff27531
fix doc import
suneettipirneni Sep 28, 2023
fdfec12
add SKU structure
suneettipirneni Sep 28, 2023
dcf6ba2
add get SKUs route
suneettipirneni Sep 28, 2023
68cd4aa
Merge branch 'main' into feat/monetization
suneettipirneni Oct 8, 2023
82ed05b
make requeste changes
suneettipirneni Oct 8, 2023
28d5de2
add updated changes
suneettipirneni Oct 21, 2023
050a6b6
Merge branch 'main' of https://github.com/twilight-rs/twilight into f…
suneettipirneni Dec 31, 2023
9ad49c5
Merge remote-tracking branch 'origin/main' into feat/monetization
Erk- Apr 13, 2024
765250c
fix up merge
Erk- Apr 13, 2024
d0c6447
resolve comments
Erk- Apr 13, 2024
8bb1a24
clippy and fmt
Erk- Apr 13, 2024
3cfca3a
ord does not make sense for flags
Erk- Apr 13, 2024
54957d2
fix a test
Erk- Apr 13, 2024
783ec23
Merge remote-tracking branch 'origin/main' into feat/monetization
Erk- May 14, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions twilight-cache-inmemory/src/event/interaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ mod tests {
}),
target_id: None,
}))),
entitlements: Vec::new(),
guild_id: Some(Id::new(3)),
guild_locale: None,
id: Id::new(4),
Expand Down
3 changes: 3 additions & 0 deletions twilight-cache-inmemory/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,9 @@ impl<CacheModels: CacheableModels> UpdateCache<CacheModels> for Event {
| Event::BanAdd(_)
| Event::BanRemove(_)
| Event::CommandPermissionsUpdate(_)
| Event::EntitlementCreate(_)
| Event::EntitlementDelete(_)
| Event::EntitlementUpdate(_)
| Event::GatewayClose(_)
| Event::GatewayHeartbeat(_)
| Event::GatewayHeartbeatAck
Expand Down
9 changes: 9 additions & 0 deletions twilight-gateway/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ bitflags! {
///
/// [`AutoModerationRule`]: crate::guild::auto_moderation::AutoModerationRule
const AUTO_MODERATION_RULE_UPDATE = 1 << 74;
/// An entitlement has been created.
const ENTITLEMENT_CREATE = 1 << 76;
/// An entitlement has been deleted.
const ENTITLEMENT_DELETE = 1 << 77;
/// An entitlement has been updated.
const ENTITLEMENT_UPDATE = 1 << 78;
/// User has been banned from a guild.
const BAN_ADD = 1;
/// User has been unbanned from a guild.
Expand Down Expand Up @@ -330,6 +336,9 @@ impl From<EventType> for EventTypeFlags {
EventType::ChannelPinsUpdate => Self::CHANNEL_PINS_UPDATE,
EventType::ChannelUpdate => Self::CHANNEL_UPDATE,
EventType::CommandPermissionsUpdate => Self::COMMAND_PERMISSIONS_UPDATE,
EventType::EntitlementCreate => Self::ENTITLEMENT_CREATE,
EventType::EntitlementDelete => Self::ENTITLEMENT_DELETE,
EventType::EntitlementUpdate => Self::ENTITLEMENT_UPDATE,
EventType::GatewayClose => Self::empty(),
EventType::GatewayHeartbeat => Self::GATEWAY_HEARTBEAT,
EventType::GatewayHeartbeatAck => Self::GATEWAY_HEARTBEAT_ACK,
Expand Down
6 changes: 6 additions & 0 deletions twilight-http-ratelimiting/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,10 @@ pub enum Path {
ChannelsIdTyping(u64),
/// Operating on a channel's webhooks.
ChannelsIdWebhooks(u64),
/// Operating on an application's entitlements.
ApplicationIdEntitlements(u64),
/// Operating on an application's SKUs.
ApplicationIdSKUs(u64),
suneettipirneni marked this conversation as resolved.
Show resolved Hide resolved
/// Operating with the gateway information.
Gateway,
/// Operating with the gateway information tailored to the current user.
Expand Down Expand Up @@ -337,6 +341,7 @@ impl FromStr for Path {
["applications", "me"] => ApplicationsMe,
["applications", id, "commands"] => ApplicationCommand(parse_id(id)?),
["applications", id, "commands", _] => ApplicationCommandId(parse_id(id)?),
["applications", id, "entitlements"] => ApplicationIdEntitlements(parse_id(id)?),
["applications", id, "guilds", _, "commands"]
| ["applications", id, "guilds", _, "commands", "permissions"] => {
ApplicationGuildCommand(parse_id(id)?)
Expand All @@ -345,6 +350,7 @@ impl FromStr for Path {
| ["applications", id, "guilds", _, "commands", _, "permissions"] => {
ApplicationGuildCommandId(parse_id(id)?)
}
["applications", id, "skus"] => ApplicationIdSKUs(parse_id(id)?),
["channels", id] => ChannelsId(parse_id(id)?),
["channels", id, "followers"] => ChannelsIdFollowers(parse_id(id)?),
["channels", id, "invites"] => ChannelsIdInvites(parse_id(id)?),
Expand Down
118 changes: 115 additions & 3 deletions twilight-http/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ mod interaction;

pub use self::{builder::ClientBuilder, interaction::InteractionClient};

use crate::request::application::monetization::{
CreateTestEntitlement, CreateTestEntitlementOwner, DeleteTestEntitlement, GetEntitlements,
GetSKUs,
};
#[allow(deprecated)]
use crate::{
client::connector::Connector,
error::{Error, ErrorType},
Expand Down Expand Up @@ -104,9 +109,9 @@ use twilight_model::{
http::{channel_position::Position, permission_overwrite::PermissionOverwrite},
id::{
marker::{
ApplicationMarker, AutoModerationRuleMarker, ChannelMarker, EmojiMarker, GuildMarker,
IntegrationMarker, MessageMarker, RoleMarker, ScheduledEventMarker, StickerMarker,
UserMarker, WebhookMarker,
ApplicationMarker, AutoModerationRuleMarker, ChannelMarker, EmojiMarker,
EntitlementMarker, GuildMarker, IntegrationMarker, MessageMarker, RoleMarker,
ScheduledEventMarker, SkuMarker, StickerMarker, UserMarker, WebhookMarker,
},
Id,
},
Expand Down Expand Up @@ -775,6 +780,29 @@ impl Client {
GetEmojis::new(self, guild_id)
}

/// Get the entitlements for an application.
///
/// # Examples
///
/// Get emojis for the application `100`:
///
/// ```no_run
/// # use twilight_http::Client;
/// # use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let application_id = Id::new(100);
///
/// client.entitlements(application_id).await?;
/// # Ok(()) }
laralove143 marked this conversation as resolved.
Show resolved Hide resolved
/// ```
pub const fn entitlements(&self, application_id: Id<ApplicationMarker>) -> GetEntitlements<'_> {
GetEntitlements::new(self, application_id)
}

/// Get an emoji for a guild by the the guild's ID and emoji's ID.
///
/// # Examples
Expand Down Expand Up @@ -2557,6 +2585,90 @@ impl Client {
DeleteGuildSticker::new(self, guild_id, sticker_id)
}

/// Creates a test entitlement to a given SKU for a given guild or user. Discord
/// will act as though that user or guild has entitlement to your premium offering.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::{Client, request::application::monetization::CreateTestEntitlementOwner};
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let application_id = Id::new(1);
/// let sku_id = Id::new(2);
/// let owner = CreateTestEntitlementOwner::Guild(Id::new(3));
///
/// client.create_test_entitlement(
/// application_id,
/// sku_id,
/// owner,
/// ).await?;
///
/// # Ok(()) }
pub const fn create_test_entitlement(
&self,
application_id: Id<ApplicationMarker>,
sku_id: Id<SkuMarker>,
owner: CreateTestEntitlementOwner,
) -> CreateTestEntitlement<'_> {
CreateTestEntitlement::new(self, application_id, sku_id, owner)
}

/// Deletes a currently-active test entitlement. Discord will act as though that user or
/// guild no longer has entitlement to your premium offering.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let application_id = Id::new(1);
/// let entitlement_id = Id::new(2);
///
/// client.delete_test_entitlement(
/// application_id,
/// entitlement_id,
/// ).await?;
///
/// # Ok(()) }
pub const fn delete_test_entitlement(
&self,
application_id: Id<ApplicationMarker>,
entitlement_id: Id<EntitlementMarker>,
) -> DeleteTestEntitlement<'_> {
DeleteTestEntitlement::new(self, application_id, entitlement_id)
}

/// Returns all SKUs for a given application.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let application_id = Id::new(1);
///
/// let skus = client.get_skus(application_id).await?;
///
/// # Ok(()) }
pub const fn get_skus(&self, application_id: Id<ApplicationMarker>) -> GetSKUs<'_> {
GetSKUs::new(self, application_id)
}

/// Execute a request, returning a future resolving to a [`Response`].
///
/// # Errors
Expand Down
1 change: 1 addition & 0 deletions twilight-http/src/request/application/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod command;
pub mod interaction;
pub mod monetization;
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
use std::future::IntoFuture;

use serde::ser::{Serialize, SerializeStruct, Serializer};
use twilight_model::{
application::monetization::Entitlement,
id::{
marker::{ApplicationMarker, GuildMarker, SkuMarker, UserMarker},
Id,
},
};

use crate::{
request::{Request, TryIntoRequest},
response::ResponseFuture,
routing::Route,
Client, Error, Response,
};

/// Owner of a test entitlement.
pub enum CreateTestEntitlementOwner {
Guild(Id<GuildMarker>),
User(Id<UserMarker>),
}

impl CreateTestEntitlementOwner {
pub const fn id(&self) -> u64 {
match self {
CreateTestEntitlementOwner::Guild(id) => id.get(),
CreateTestEntitlementOwner::User(id) => id.get(),
}
}

pub const fn kind(&self) -> u8 {
match self {
CreateTestEntitlementOwner::Guild(_) => 1,
CreateTestEntitlementOwner::User(_) => 2,
}
}
}

struct CreateTestEntitlementFields {
sku_id: Id<SkuMarker>,
owner: CreateTestEntitlementOwner,
}

impl Serialize for CreateTestEntitlementFields {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("CreateTestEntitlementFields", 2)?;
state.serialize_field("sku_id", &self.sku_id.get())?;
state.serialize_field("owner_id", &self.owner.id())?;
state.serialize_field("owner_type", &self.owner.kind())?;
state.end()
}
}

pub struct CreateTestEntitlement<'a> {
application_id: Id<ApplicationMarker>,
fields: CreateTestEntitlementFields,
http: &'a Client,
}

impl<'a> CreateTestEntitlement<'a> {
pub(crate) const fn new(
http: &'a Client,
application_id: Id<ApplicationMarker>,
sku_id: Id<SkuMarker>,
owner: CreateTestEntitlementOwner,
) -> Self {
Self {
application_id,
fields: CreateTestEntitlementFields { sku_id, owner },
http,
}
}
}

impl IntoFuture for CreateTestEntitlement<'_> {
type Output = Result<Response<Entitlement>, Error>;

type IntoFuture = ResponseFuture<Entitlement>;

fn into_future(self) -> Self::IntoFuture {
let http = self.http;

match self.try_into_request() {
Ok(request) => http.request(request),
Err(source) => ResponseFuture::error(source),
}
}
}

impl TryIntoRequest for CreateTestEntitlement<'_> {
fn try_into_request(self) -> Result<Request, Error> {
Request::builder(&Route::CreateTestEntitlement {
application_id: self.application_id.get(),
})
.json(&self.fields)
.build()
}
}

#[cfg(test)]
mod tests {
use serde_test::Token;
use twilight_model::id::Id;

use super::{CreateTestEntitlementFields, CreateTestEntitlementOwner};

#[test]
fn fields_serialization() {
let value = CreateTestEntitlementFields {
sku_id: Id::new(1),
owner: CreateTestEntitlementOwner::Guild(Id::new(2)),
};

serde_test::assert_ser_tokens(
&value,
&[
Token::Struct {
name: "CreateTestEntitlementFields",
len: 2,
},
Token::Str("sku_id"),
Token::U64(1),
Token::Str("owner_id"),
Token::U64(2),
Token::Str("owner_type"),
Token::U8(1),
Token::StructEnd,
],
);
}
}
Loading