main
DaXcess 2024-09-20 07:32:08 +00:00
parent b9b0051523
commit f437473462
No known key found for this signature in database
GPG Key ID: CF78CC72F0FD5EAD
15 changed files with 414 additions and 340 deletions

View File

@ -1,5 +1,10 @@
# Changelog # Changelog
## 2.2.3 | September 20th 2024
- Made backend changes to librespot to prevent deadlocking by not waiting for thread shutdowns
- Added retrying to Spotify login logic to reduce the chance of the bot failing to connect
## 2.2.2 | September 2nd 2024 ## 2.2.2 | September 2nd 2024
- Added backtrace logging to player creation to figure out some mystery crashes - Added backtrace logging to player creation to figure out some mystery crashes

601
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord" name = "spoticord"
version = "2.2.2" version = "2.2.3"
edition = "2021" edition = "2021"
rust-version = "1.80.0" rust-version = "1.80.0"

View File

@ -45,7 +45,7 @@ ARG TARGETPLATFORM
ENV TARGETPLATFORM=${TARGETPLATFORM} ENV TARGETPLATFORM=${TARGETPLATFORM}
# Add extra runtime dependencies here # Add extra runtime dependencies here
RUN apt update && apt install -y ca-certificates RUN apt update && apt install -y ca-certificates libpq-dev
# Copy spoticord binaries from builder to /tmp so we can dynamically use them # Copy spoticord binaries from builder to /tmp so we can dynamically use them
COPY --from=builder \ COPY --from=builder \
@ -63,4 +63,4 @@ RUN if [ "${TARGETPLATFORM}" = "linux/amd64" ]; then \
# Delete unused binaries # Delete unused binaries
RUN rm -rvf /tmp/x86_64 /tmp/aarch64 RUN rm -rvf /tmp/x86_64 /tmp/aarch64
ENTRYPOINT [ "/usr/local/bin/spoticord" ] ENTRYPOINT [ "/usr/local/bin/spoticord" ]

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_audio" name = "spoticord_audio"
version = "2.2.2" version = "2.2.3"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_config" name = "spoticord_config"
version = "2.2.2" version = "2.2.3"
edition = "2021" edition = "2021"
[dependencies] [dependencies]

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_database" name = "spoticord_database"
version = "2.2.2" version = "2.2.3"
edition = "2021" edition = "2021"
[dependencies] [dependencies]

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_player" name = "spoticord_player"
version = "2.2.2" version = "2.2.3"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -101,18 +101,36 @@ impl Player {
); );
let rx_player = player.get_player_event_channel(); let rx_player = player.get_player_event_channel();
let (spirc, spirc_task) = Spirc::new( let device_name = device_name.into();
ConnectConfig { let mut tries = 0;
name: device_name.into(),
initial_volume: Some((0.75f32 * u16::MAX as f32) as u16), let (spirc, spirc_task) = loop {
..Default::default() match Spirc::new(
}, ConnectConfig {
session.clone(), name: device_name.clone(),
credentials, initial_volume: Some((0.75f32 * u16::MAX as f32) as u16),
player, ..Default::default()
mixer, },
) session.clone(),
.await?; credentials.clone(),
player.clone(),
mixer.clone(),
)
.await
{
Ok(spirc) => break spirc,
Err(why) => {
tries += 1;
if tries > 3 {
error!("Failed to connect to Spirc: {why}");
return Err(why.into());
}
continue;
}
}
};
let (tx, rx) = mpsc::channel(16); let (tx, rx) = mpsc::channel(16);
let player = Self { let player = Self {

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_session" name = "spoticord_session"
version = "2.2.2" version = "2.2.3"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -101,18 +101,36 @@ impl Session {
// Grab user credentials and info before joining call // Grab user credentials and info before joining call
let credentials = let credentials =
retrieve_credentials(&session_manager.database(), owner.to_string()).await?; match retrieve_credentials(&session_manager.database(), owner.to_string()).await {
let device_name = session_manager Ok(credentials) => credentials,
.database() Err(why) => {
.get_user(owner.to_string()) error!("Failed to retrieve credentials: {why}");
.await?
.device_name; return Err(why.into());
}
};
let device_name = match session_manager.database().get_user(owner.to_string()).await {
Ok(user) => user.device_name,
Err(why) => {
error!("Failed to get database user: {why}");
return Err(why.into());
}
};
// Hello Discord I'm here // Hello Discord I'm here
let call = session_manager let call = match session_manager
.songbird() .songbird()
.join(guild_id, voice_channel_id) .join(guild_id, voice_channel_id)
.await?; .await
{
Ok(call) => call,
Err(why) => {
error!("Failed to join voice channel: {why}");
return Err(why.into());
}
};
// Make sure call guard is dropped or else we can't execute session.run // Make sure call guard is dropped or else we can't execute session.run
{ {
@ -173,6 +191,8 @@ impl Session {
loop { loop {
tokio::select! { tokio::select! {
opt_command = self.commands.recv() => { opt_command = self.commands.recv() => {
trace!("Received command: {opt_command:#?}");
let Some(command) = opt_command else { let Some(command) = opt_command else {
break; break;
}; };
@ -183,6 +203,8 @@ impl Session {
}, },
opt_event = self.events.recv(), if self.active => { opt_event = self.events.recv(), if self.active => {
trace!("Received event: {opt_event:#?}");
let Some(event) = opt_event else { let Some(event) = opt_event else {
self.shutdown_player().await; self.shutdown_player().await;
continue; continue;
@ -193,6 +215,8 @@ impl Session {
// Internal communication channel // Internal communication channel
Some(command) = self.commands_inner_rx.recv() => { Some(command) = self.commands_inner_rx.recv() => {
trace!("Received internal command: {command:#?}");
if self.handle_command(command).await.is_break() { if self.handle_command(command).await.is_break() {
break; break;
} }
@ -201,6 +225,8 @@ impl Session {
else => break, else => break,
} }
} }
trace!("End of Session::run");
} }
async fn handle_command(&mut self, command: SessionCommand) -> ControlFlow<(), ()> { async fn handle_command(&mut self, command: SessionCommand) -> ControlFlow<(), ()> {
@ -519,8 +545,10 @@ impl songbird::EventHandler for SessionHandle {
} }
match event { match event {
// NOTE: Discord can randomly make the driver disconnect when users join/leave the voice channel
// Nothing we can do about it at this time since that is an issue with either Discord or Songbird
EventContext::DriverDisconnect(_) => { EventContext::DriverDisconnect(_) => {
debug!("Bot disconnected from call, cleaning up"); debug!("Bot disconnected from voice gateway, cleaning up");
self.disconnect().await; self.disconnect().await;
} }

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_stats" name = "spoticord_stats"
version = "2.2.2" version = "2.2.3"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_utils" name = "spoticord_utils"
version = "2.2.2" version = "2.2.3"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
@ -9,3 +9,4 @@ anyhow = "1.0.86"
base64 = "0.22.1" base64 = "0.22.1"
log = "0.4.22" log = "0.4.22"
poise = "0.6.1" poise = "0.6.1"
tokio = { version = "1.40.0", features = ["time"], default-features = false }

View File

@ -5,7 +5,8 @@ use librespot::{
discovery::Credentials, discovery::Credentials,
protocol::{authentication::AuthenticationType, keyexchange::ErrorCode}, protocol::{authentication::AuthenticationType, keyexchange::ErrorCode},
}; };
use log::trace; use log::debug;
use std::time::Duration;
pub async fn validate_token( pub async fn validate_token(
username: impl Into<String>, username: impl Into<String>,
@ -19,12 +20,12 @@ pub async fn validate_token(
auth_data, auth_data,
}; };
trace!("Validating session token for {}", credentials.username); debug!("Validating session token for {}", credentials.username);
let new_credentials = request_session_token(credentials.clone()).await?; let new_credentials = request_session_token(credentials.clone()).await?;
if credentials.auth_data != new_credentials.auth_data { if credentials.auth_data != new_credentials.auth_data {
trace!("New session token retrieved for {}", credentials.username); debug!("New session token retrieved for {}", credentials.username);
return Ok(Some(BASE64.encode(new_credentials.auth_data))); return Ok(Some(BASE64.encode(new_credentials.auth_data)));
} }
@ -33,14 +34,29 @@ pub async fn validate_token(
} }
pub async fn request_session_token(credentials: Credentials) -> Result<Credentials> { pub async fn request_session_token(credentials: Credentials) -> Result<Credentials> {
trace!("Requesting session token for {}", credentials.username); debug!("Requesting session token for {}", credentials.username);
let session = Session::new(SessionConfig::default(), None); let session = Session::new(SessionConfig::default(), None);
let mut tries = 0; let mut tries = 0;
Ok(loop { Ok(loop {
let (host, port) = session.apresolver().resolve("accesspoint").await?; let (host, port) = session.apresolver().resolve("accesspoint").await?;
let mut transport = librespot::core::connection::connect(&host, port, None).await?;
let mut transport = match librespot::core::connection::connect(&host, port, None).await {
Ok(transport) => transport,
Err(why) => {
// Retry
tries += 1;
if tries > 3 {
return Err(why.into());
}
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
}
};
match librespot::core::connection::authenticate( match librespot::core::connection::authenticate(
&mut transport, &mut transport,
@ -59,6 +75,8 @@ pub async fn request_session_token(credentials: Credentials) -> Result<Credentia
return Err(e.into()); return Err(e.into());
} }
tokio::time::sleep(Duration::from_millis(100)).await;
continue; continue;
} else { } else {
return Err(e.into()); return Err(e.into());

View File

@ -17,11 +17,6 @@ pub type FrameworkError<'a> = poise::FrameworkError<'a, Data, anyhow::Error>;
type Data = SessionManager; type Data = SessionManager;
// pub struct Data {
// pub database: Database,
// pub session_manager: SessionManager,
// }
pub fn framework_opts() -> FrameworkOptions<Data, anyhow::Error> { pub fn framework_opts() -> FrameworkOptions<Data, anyhow::Error> {
poise::FrameworkOptions { poise::FrameworkOptions {
commands: vec![ commands: vec![
@ -111,14 +106,14 @@ async fn background_loop(
#[cfg(feature = "stats")] mut stats_manager: spoticord_stats::StatsManager, #[cfg(feature = "stats")] mut stats_manager: spoticord_stats::StatsManager,
) { ) {
#[cfg(feature = "stats")] #[cfg(feature = "stats")]
use log::{error, trace}; use log::error;
loop { loop {
tokio::select! { tokio::select! {
_ = tokio::time::sleep(std::time::Duration::from_secs(60)) => { _ = tokio::time::sleep(std::time::Duration::from_secs(60)) => {
#[cfg(feature = "stats")] #[cfg(feature = "stats")]
{ {
trace!("Retrieving active sessions count for stats"); debug!("Retrieving active sessions count for stats");
let mut count = 0; let mut count = 0;
@ -131,7 +126,7 @@ async fn background_loop(
if let Err(why) = stats_manager.set_active_count(count) { if let Err(why) = stats_manager.set_active_count(count) {
error!("Failed to update active sessions: {why}"); error!("Failed to update active sessions: {why}");
} else { } else {
trace!("Active session count set to: {count}"); debug!("Active session count set to: {count}");
} }
} }
} }