Skip to content

Commit

Permalink
Set Http::application_id in ready event handler (#1772)
Browse files Browse the repository at this point in the history
  • Loading branch information
vaporoxx authored and arqunis committed Apr 18, 2022
1 parent 440f0fa commit c5f9cbe
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 42 deletions.
4 changes: 3 additions & 1 deletion src/client/bridge/gateway/shard_queuer.rs
Expand Up @@ -178,14 +178,16 @@ impl ShardQueuer {
async fn start(&mut self, shard_id: u64, shard_total: u64) -> Result<()> {
let shard_info = [shard_id, shard_total];

let shard = Shard::new(
let mut shard = Shard::new(
Arc::clone(&self.ws_url),
&self.cache_and_http.http.token,
shard_info,
self.intents,
)
.await?;

shard.set_http(Arc::clone(&self.cache_and_http.http));

let mut runner = ShardRunner::new(ShardRunnerOptions {
data: Arc::clone(&self.data),
event_handler: self.event_handler.as_ref().map(Arc::clone),
Expand Down
5 changes: 0 additions & 5 deletions src/client/mod.rs
Expand Up @@ -370,11 +370,6 @@ impl Future for ClientBuilder {
let intents = self.intents;
let http = Arc::new(self.http.take().unwrap());

// TODO: It should not be required for all users of serenity to set the application_id or get a panic.
if http.application_id == 0 {
panic!("Please provide an Application Id in order to use interactions features.");
}

#[cfg(feature = "voice")]
let voice_manager = self.voice_manager.take();

Expand Down
14 changes: 14 additions & 0 deletions src/gateway/shard.rs
Expand Up @@ -22,6 +22,7 @@ use super::{
};
use crate::client::bridge::gateway::ChunkGuildFilter;
use crate::constants::{self, close_codes};
use crate::http::Http;
use crate::internal::prelude::*;
#[cfg(feature = "native_tls_backend")]
use crate::internal::ws_impl::create_native_tls_client;
Expand Down Expand Up @@ -79,6 +80,7 @@ pub struct Shard {
/// [`latency`]: fn@Self::latency
heartbeat_instants: (Option<Instant>, Option<Instant>),
heartbeat_interval: Option<u64>,
http: Option<Arc<Http>>,
/// This is used by the heartbeater to determine whether the last
/// heartbeat was sent without an acknowledgement, and whether to reconnect.
// This _must_ be set to `true` in `Shard::handle_event`'s
Expand Down Expand Up @@ -156,6 +158,7 @@ impl Shard {
current_presence,
heartbeat_instants,
heartbeat_interval,
http: None,
last_heartbeat_acknowledged,
seq,
stage,
Expand All @@ -168,6 +171,13 @@ impl Shard {
})
}

/// Sets the associated [`Http`] client.
///
/// This will update the client's application id after the shard receives a READY payload.
pub fn set_http(&mut self, http: Arc<Http>) {
self.http = Some(http);
}

/// Retrieves the current presence of the shard.
#[inline]
pub fn current_presence(&self) -> &CurrentPresence {
Expand Down Expand Up @@ -330,6 +340,10 @@ impl Shard {

self.session_id = Some(ready.ready.session_id.clone());
self.stage = ConnectionStage::Connected;

if let Some(ref http) = self.http {
http.set_application_id(ready.ready.application.id.0);
}
},
Event::Resumed(_) => {
info!("[Shard {:?}] Resumed", self.shard_info);
Expand Down
89 changes: 53 additions & 36 deletions src/http/client.rs
@@ -1,4 +1,6 @@
#![allow(clippy::missing_errors_doc)]

use std::sync::atomic::{AtomicU64, Ordering};
use std::{borrow::Cow, fmt, str::FromStr, sync::Arc};

use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
Expand Down Expand Up @@ -147,10 +149,7 @@ impl HttpBuilder {
pub fn build(self) -> Http {
let token = self.token;

// TODO: It should not be required for all users of serenity to set the application_id or get a panic.
let application_id = self
.application_id
.expect("Expected application Id in order to use interacions features");
let application_id = AtomicU64::new(self.application_id.unwrap_or_default());

let client = self.client.unwrap_or_else(|| {
let builder = configure_client_backend(Client::builder());
Expand Down Expand Up @@ -206,7 +205,7 @@ pub struct Http {
pub ratelimiter_disabled: bool,
pub proxy: Option<Url>,
pub token: String,
pub application_id: u64,
application_id: AtomicU64,
}

impl fmt::Debug for Http {
Expand All @@ -230,17 +229,17 @@ impl Http {
ratelimiter_disabled: false,
proxy: None,
token: token.to_string(),
application_id: 0,
application_id: AtomicU64::new(0),
}
}

pub fn new_with_application_id(application_id: u64) -> Self {
let builder = configure_client_backend(Client::builder());
let built = builder.build().expect("Cannot build reqwest::Client");

let mut data = Self::new(built, "");
let data = Self::new(built, "");

data.application_id = application_id;
data.set_application_id(application_id);

data
}
Expand All @@ -260,13 +259,31 @@ impl Http {
}

pub fn new_with_token_application_id(token: &str, application_id: u64) -> Self {
let mut base = Self::new_with_token(token);
let base = Self::new_with_token(token);

base.application_id = application_id;
base.set_application_id(application_id);

base
}

pub fn application_id(&self) -> Option<u64> {
let application_id = self.application_id.load(Ordering::Relaxed);

if application_id == 0 {
None
} else {
Some(application_id)
}
}

fn try_application_id(&self) -> Result<u64> {
self.application_id().ok_or_else(|| HttpError::ApplicationIdMissing.into())
}

pub fn set_application_id(&self, application_id: u64) {
self.application_id.store(application_id, Ordering::Relaxed);
}

/// Adds a [`User`] to a [`Guild`] with a valid OAuth2 access token.
///
/// Returns the created [`Member`] object, or nothing if the user is already a member of the guild.
Expand Down Expand Up @@ -488,7 +505,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::CreateFollowupMessage {
application_id: self.application_id,
application_id: self.try_application_id()?,
interaction_token,
},
})
Expand All @@ -513,7 +530,7 @@ impl Http {
}),
headers: None,
route: RouteInfo::CreateFollowupMessage {
application_id: self.application_id,
application_id: self.try_application_id()?,
interaction_token,
},
})
Expand All @@ -540,7 +557,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::CreateGlobalApplicationCommand {
application_id: self.application_id,
application_id: self.try_application_id()?,
},
})
.await
Expand All @@ -556,7 +573,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::CreateGlobalApplicationCommands {
application_id: self.application_id,
application_id: self.try_application_id()?,
},
})
.await
Expand All @@ -573,7 +590,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::CreateGuildApplicationCommands {
application_id: self.application_id,
application_id: self.try_application_id()?,
guild_id,
},
})
Expand Down Expand Up @@ -640,7 +657,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::CreateGuildApplicationCommand {
application_id: self.application_id,
application_id: self.try_application_id()?,
guild_id,
},
})
Expand Down Expand Up @@ -975,7 +992,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::DeleteFollowupMessage {
application_id: self.application_id,
application_id: self.try_application_id()?,
interaction_token,
message_id,
},
Expand All @@ -990,7 +1007,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::DeleteGlobalApplicationCommand {
application_id: self.application_id,
application_id: self.try_application_id()?,
command_id,
},
})
Expand Down Expand Up @@ -1021,7 +1038,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::DeleteGuildApplicationCommand {
application_id: self.application_id,
application_id: self.try_application_id()?,
guild_id,
command_id,
},
Expand Down Expand Up @@ -1145,7 +1162,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::DeleteOriginalInteractionResponse {
application_id: self.application_id,
application_id: self.try_application_id()?,
interaction_token,
},
})
Expand Down Expand Up @@ -1366,7 +1383,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::EditFollowupMessage {
application_id: self.application_id,
application_id: self.try_application_id()?,
interaction_token,
message_id,
},
Expand Down Expand Up @@ -1395,7 +1412,7 @@ impl Http {
}),
headers: None,
route: RouteInfo::EditFollowupMessage {
application_id: self.application_id,
application_id: self.try_application_id()?,
interaction_token,
message_id,
},
Expand All @@ -1418,7 +1435,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::GetFollowupMessage {
application_id: self.application_id,
application_id: self.try_application_id()?,
interaction_token,
message_id,
},
Expand All @@ -1443,7 +1460,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::EditGlobalApplicationCommand {
application_id: self.application_id,
application_id: self.try_application_id()?,
command_id,
},
})
Expand Down Expand Up @@ -1488,7 +1505,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::EditGuildApplicationCommand {
application_id: self.application_id,
application_id: self.try_application_id()?,
guild_id,
command_id,
},
Expand All @@ -1514,7 +1531,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::EditGuildApplicationCommandPermission {
application_id: self.application_id,
application_id: self.try_application_id()?,
guild_id,
command_id,
},
Expand All @@ -1539,7 +1556,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::EditGuildApplicationCommandsPermissions {
application_id: self.application_id,
application_id: self.try_application_id()?,
guild_id,
},
})
Expand Down Expand Up @@ -1734,7 +1751,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::GetOriginalInteractionResponse {
application_id: self.application_id,
application_id: self.try_application_id()?,
interaction_token,
},
})
Expand All @@ -1756,7 +1773,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::EditOriginalInteractionResponse {
application_id: self.application_id,
application_id: self.try_application_id()?,
interaction_token,
},
})
Expand Down Expand Up @@ -2634,7 +2651,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::GetGlobalApplicationCommands {
application_id: self.application_id,
application_id: self.try_application_id()?,
},
})
.await
Expand All @@ -2650,7 +2667,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::GetGlobalApplicationCommand {
application_id: self.application_id,
application_id: self.try_application_id()?,
command_id,
},
})
Expand Down Expand Up @@ -2693,7 +2710,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::GetGuildApplicationCommands {
application_id: self.application_id,
application_id: self.try_application_id()?,
guild_id,
},
})
Expand All @@ -2711,7 +2728,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::GetGuildApplicationCommand {
application_id: self.application_id,
application_id: self.try_application_id()?,
guild_id,
command_id,
},
Expand All @@ -2729,7 +2746,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::GetGuildApplicationCommandsPermissions {
application_id: self.application_id,
application_id: self.try_application_id()?,
guild_id,
},
})
Expand All @@ -2747,7 +2764,7 @@ impl Http {
multipart: None,
headers: None,
route: RouteInfo::GetGuildApplicationCommandPermissions {
application_id: self.application_id,
application_id: self.try_application_id()?,
guild_id,
command_id,
},
Expand Down Expand Up @@ -3856,7 +3873,7 @@ impl Default for Http {
ratelimiter_disabled: false,
proxy: None,
token: "".to_string(),
application_id: 0,
application_id: AtomicU64::new(0),
}
}
}

0 comments on commit c5f9cbe

Please sign in to comment.