Compare commits

..

No commits in common. "10a13d3daa4b911e9969a513c9f8d34882be8c15" and "d6329d9a29ae44c20eca01bc703481943c6a9140" have entirely different histories.

27 changed files with 460 additions and 1337 deletions

View File

@ -1,17 +1,5 @@
# Changelog # Changelog
## 2.2.4 | September 30th 2024
- Added a message for if the Spotify AP connection drops
- Added additional timeouts to credential retrieval
- Removed multiple points of failure in `librespot` that could shut down the bot
- Fixed an issue where non-premium users could crash the bot for everyone (See point 3)
## 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

1304
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.4" version = "2.2.2"
edition = "2021" edition = "2021"
rust-version = "1.80.0" rust-version = "1.80.0"
@ -17,8 +17,6 @@ members = [
"spoticord_session", "spoticord_session",
"spoticord_utils", "spoticord_utils",
"spoticord_stats", "spoticord_stats",
"spoticord_api",
"spoticord_api_grpc",
] ]
[features] [features]
@ -32,8 +30,6 @@ spoticord_player = { path = "./spoticord_player" }
spoticord_session = { path = "./spoticord_session" } spoticord_session = { path = "./spoticord_session" }
spoticord_utils = { path = "./spoticord_utils" } spoticord_utils = { path = "./spoticord_utils" }
spoticord_stats = { path = "./spoticord_stats", optional = true } spoticord_stats = { path = "./spoticord_stats", optional = true }
spoticord_api = { path = "./spoticord_api"}
spoticord_api_grpc = { path = "./spoticord_api_grpc"}
anyhow = "1.0.86" anyhow = "1.0.86"
dotenvy = "0.15.7" dotenvy = "0.15.7"
@ -43,8 +39,6 @@ poise = "0.6.1"
serenity = "0.12.2" serenity = "0.12.2"
songbird = { version = "0.4.3", features = ["simd-json"] } songbird = { version = "0.4.3", features = ["simd-json"] }
tokio = { version = "1.39.3", features = ["full"] } tokio = { version = "1.39.3", features = ["full"] }
rustls = { version = "0.23.13", features = ["aws-lc-rs"] }
tonic = "0.12.3"
[profile.release] [profile.release]
opt-level = 3 opt-level = 3

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 libpq-dev RUN apt update && apt install -y ca-certificates
# 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 \

View File

@ -1,16 +0,0 @@
[package]
name = "spoticord_api"
version = "0.1.0"
edition = "2021"
[dependencies]
spoticord_database = { path = "../spoticord_database" }
spoticord_session = { path = "../spoticord_session" }
spoticord_api_grpc = { path = "../spoticord_api_grpc"}
prost = "0.13.3"
tokio = {version = "1.38.0", features = ["io-util", "net", "rt-multi-thread"]}
axum = "0.7.5"
env_logger = "0.11.3"
log = "0.4.21"
thiserror = "1.0.61"
tonic = "0.12.3"

View File

@ -1,39 +0,0 @@
use log::info;
use spoticord_api_grpc::spoticord_api::service::PlayPlaylistRequest;
use spoticord_session::manager::{SessionManager, SessionQuery};
use tonic::{Request, Response, Status};
pub struct SpoticordApi {
pub session: SessionManager,
}
#[tonic::async_trait]
impl spoticord_api_grpc::spoticord_api::service::spoticord_api_server::SpoticordApi
for SpoticordApi
{
async fn play_playlist(
&self,
request: Request<PlayPlaylistRequest>,
) -> Result<Response<spoticord_api_grpc::spoticord_api::service::Response>, Status> {
let playlist = request.into_inner();
info!(
"Playing {} for {}",
playlist.playlist_uri, playlist.discord_user_id
);
let session = self
.session
.get_session(SessionQuery::Owner(playlist.discord_user_id.into()))
.unwrap();
session.queue_playlist(playlist.playlist_uri).await.unwrap();
let response = spoticord_api_grpc::spoticord_api::service::Response {
resp: Option::from(
spoticord_api_grpc::spoticord_api::service::response::Resp::Success(true),
),
};
Ok(Response::new(response))
}
}

View File

@ -1,13 +0,0 @@
[package]
name = "spoticord_api_grpc"
version = "0.1.0"
edition = "2021"
[dependencies]
bytes = "1.6.0"
tonic = "0.12.3"
prost = "0.13.3"
tokio = {version = "1.38.0", features = ["io-util", "test-util"]}
[build-dependencies]
tonic-build = "0.12.3"

View File

@ -1,6 +0,0 @@
use std::io::Result;
fn main() -> Result<()> {
tonic_build::configure().compile_protos(&["src/service.proto"], &["src/"])?;
Ok(())
}

View File

@ -1,21 +0,0 @@
pub mod spoticord_api {
pub mod service {
include!(concat!(env!("OUT_DIR"), "/spoticord_api.service.rs"));
}
}
#[cfg(test)]
mod test {
use crate::spoticord_api::service::{PlayModes, PlayPlaylistRequest};
#[test]
fn test_build_play_playlist() {
let play_playlist = PlayPlaylistRequest {
order: PlayModes::InOrder.into(),
playlist_uri: "test".to_string(),
};
assert_eq!(play_playlist.playlist_uri, "test");
assert_eq!(play_playlist.order, PlayModes::InOrder.into());
}
}

View File

@ -1,32 +0,0 @@
syntax = "proto3";
package spoticord_api.service;
enum PlayModes {
SHUFFLE = 0;
IN_ORDER = 1;
}
message PlayPlaylistRequest {
uint64 discord_user_id = 1;
PlayModes order = 2;
string playlist_uri = 3;
}
enum Error {
SpotifyError = 0;
BotError = 1;
UserNotRegistered = 2;
}
message Response {
oneof resp {
bool success = 1;
Error error = 2;
}
}
service SpoticordApi {
rpc PlayPlaylist(PlayPlaylistRequest) returns (Response);
}

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_audio" name = "spoticord_audio"
version = "2.2.4" version = "2.2.2"
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

@ -24,7 +24,7 @@ impl StreamSink {
impl Sink for StreamSink { impl Sink for StreamSink {
fn start(&mut self) -> SinkResult<()> { fn start(&mut self) -> SinkResult<()> {
if let Err(_why) = self.sender.send(SinkEvent::Start) { if let Err(_why) = self.sender.send(SinkEvent::Start) {
// WARNING: Returning an error causes librespot-playback to panic // WARNING: Returning an error causes librespot-playback to exit the process with status 1
// return Err(SinkError::ConnectionRefused(_why.to_string())); // return Err(SinkError::ConnectionRefused(_why.to_string()));
} }
@ -34,7 +34,7 @@ impl Sink for StreamSink {
fn stop(&mut self) -> SinkResult<()> { fn stop(&mut self) -> SinkResult<()> {
if let Err(_why) = self.sender.send(SinkEvent::Stop) { if let Err(_why) = self.sender.send(SinkEvent::Stop) {
// WARNING: Returning an error causes librespot-playback to panic // WARNING: Returning an error causes librespot-playback to exit the process with status 1
// return Err(SinkError::ConnectionRefused(_why.to_string())); // return Err(SinkError::ConnectionRefused(_why.to_string()));
} }

View File

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

View File

@ -15,7 +15,3 @@ pub static SPOTIFY_CLIENT_SECRET: LazyLock<String> = LazyLock::new(|| {
std::env::var("SPOTIFY_CLIENT_SECRET") std::env::var("SPOTIFY_CLIENT_SECRET")
.expect("missing SPOTIFY_CLIENT_SECRET environment variable") .expect("missing SPOTIFY_CLIENT_SECRET environment variable")
}); });
// Locked behind `stats` feature
pub static KV_URL: LazyLock<String> =
LazyLock::new(|| std::env::var("KV_URL").expect("missing KV_URL environment variable"));

View File

@ -31,10 +31,6 @@ pub fn link_url() -> &'static str {
&env::LINK_URL &env::LINK_URL
} }
pub fn kv_url() -> &'static str {
&env::KV_URL
}
pub fn get_spotify(token: Token) -> AuthCodeSpotify { pub fn get_spotify(token: Token) -> AuthCodeSpotify {
AuthCodeSpotify::from_token_with_config( AuthCodeSpotify::from_token_with_config(
token, token,

View File

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

View File

@ -35,4 +35,8 @@ diesel::table! {
diesel::joinable!(account -> user (user_id)); diesel::joinable!(account -> user (user_id));
diesel::joinable!(link_request -> user (user_id)); diesel::joinable!(link_request -> user (user_id));
diesel::allow_tables_to_appear_in_same_query!(account, link_request, user,); diesel::allow_tables_to_appear_in_same_query!(
account,
link_request,
user,
);

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_player" name = "spoticord_player"
version = "2.2.4" version = "2.2.0"
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

@ -2,10 +2,6 @@ pub mod info;
use anyhow::Result; use anyhow::Result;
use info::PlaybackInfo; use info::PlaybackInfo;
use librespot::connect::spirc::SpircLoadCommand;
use librespot::core::SpotifyId;
use librespot::metadata::{Metadata, Playlist};
use librespot::protocol::spirc::TrackRef;
use librespot::{ use librespot::{
connect::{config::ConnectConfig, spirc::Spirc}, connect::{config::ConnectConfig, spirc::Spirc},
core::{http_client::HttpClientError, Session as SpotifySession, SessionConfig}, core::{http_client::HttpClientError, Session as SpotifySession, SessionConfig},
@ -17,16 +13,13 @@ use librespot::{
player::{Player as SpotifyPlayer, PlayerEvent as SpotifyPlayerEvent}, player::{Player as SpotifyPlayer, PlayerEvent as SpotifyPlayerEvent},
}, },
}; };
use log::{error, trace}; use log::error;
use songbird::{input::RawAdapter, tracks::TrackHandle, Call}; use songbird::{input::RawAdapter, tracks::TrackHandle, Call};
use spoticord_audio::{ use spoticord_audio::{
sink::{SinkEvent, StreamSink}, sink::{SinkEvent, StreamSink},
stream::Stream, stream::Stream,
}; };
use std::{ use std::{io::Write, sync::Arc};
io::Write,
sync::{atomic::AtomicBool, Arc},
};
use tokio::sync::{mpsc, oneshot, Mutex}; use tokio::sync::{mpsc, oneshot, Mutex};
#[derive(Debug)] #[derive(Debug)]
@ -38,7 +31,6 @@ enum PlayerCommand {
GetPlaybackInfo(oneshot::Sender<Option<PlaybackInfo>>), GetPlaybackInfo(oneshot::Sender<Option<PlaybackInfo>>),
GetLyrics(oneshot::Sender<Option<Lyrics>>), GetLyrics(oneshot::Sender<Option<Lyrics>>),
QueuePlaylist { uri: String },
Shutdown, Shutdown,
} }
@ -49,7 +41,6 @@ pub enum PlayerEvent {
Play, Play,
Stopped, Stopped,
TrackChanged(Box<PlaybackInfo>), TrackChanged(Box<PlaybackInfo>),
ConnectionReset,
} }
pub struct Player { pub struct Player {
@ -66,9 +57,6 @@ pub struct Player {
commands: mpsc::Receiver<PlayerCommand>, commands: mpsc::Receiver<PlayerCommand>,
spotify_events: mpsc::UnboundedReceiver<SpotifyPlayerEvent>, spotify_events: mpsc::UnboundedReceiver<SpotifyPlayerEvent>,
sink_events: mpsc::UnboundedReceiver<SinkEvent>, sink_events: mpsc::UnboundedReceiver<SinkEvent>,
/// A shared boolean that reflects whether this Player has shut down
shutdown: Arc<AtomicBool>,
} }
impl Player { impl Player {
@ -113,38 +101,19 @@ impl Player {
); );
let rx_player = player.get_player_event_channel(); let rx_player = player.get_player_event_channel();
let device_name = device_name.into(); let (spirc, spirc_task) = Spirc::new(
let mut tries = 0; ConnectConfig {
name: device_name.into(),
initial_volume: Some((0.75f32 * u16::MAX as f32) as u16),
..Default::default()
},
session.clone(),
credentials,
player,
mixer,
)
.await?;
let (spirc, spirc_task) = loop {
match Spirc::new(
ConnectConfig {
name: device_name.clone(),
initial_volume: Some((0.75f32 * u16::MAX as f32) as u16),
..Default::default()
},
session.clone(),
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 shutdown = Arc::new(AtomicBool::new(false));
let (tx, rx) = mpsc::channel(16); let (tx, rx) = mpsc::channel(16);
let player = Self { let player = Self {
session, session,
@ -154,24 +123,15 @@ impl Player {
playback_info: None, playback_info: None,
events: event_tx.clone(), events: event_tx,
commands: rx, commands: rx,
spotify_events: rx_player, spotify_events: rx_player,
sink_events: rx_sink, sink_events: rx_sink,
shutdown: shutdown.clone(),
}; };
// Launch it all! // Launch it all!
tokio::spawn(async move { tokio::spawn(spirc_task);
spirc_task.await;
// If the shutdown flag isn't set, we most likely lost connection to the Spotify AP
if !shutdown.load(std::sync::atomic::Ordering::SeqCst) {
_ = event_tx.send(PlayerEvent::ConnectionReset).await;
}
});
tokio::spawn(player.run()); tokio::spawn(player.run());
Ok((PlayerHandle { commands: tx }, event_rx)) Ok((PlayerHandle { commands: tx }, event_rx))
@ -200,11 +160,6 @@ impl Player {
else => break, else => break,
} }
} }
self.shutdown
.store(true, std::sync::atomic::Ordering::SeqCst);
trace!("End of Player::run");
} }
async fn handle_command(&mut self, command: PlayerCommand) { async fn handle_command(&mut self, command: PlayerCommand) {
@ -218,13 +173,10 @@ impl Player {
PlayerCommand::GetLyrics(tx) => self.get_lyrics(tx).await, PlayerCommand::GetLyrics(tx) => self.get_lyrics(tx).await,
PlayerCommand::Shutdown => self.commands.close(), PlayerCommand::Shutdown => self.commands.close(),
PlayerCommand::QueuePlaylist { uri } => self.queue_playlist(uri).await,
}; };
} }
async fn handle_spotify_event(&mut self, event: SpotifyPlayerEvent) { async fn handle_spotify_event(&mut self, event: SpotifyPlayerEvent) {
trace!("Spotify event received: {event:#?}");
match event { match event {
SpotifyPlayerEvent::PositionCorrection { position_ms, .. } SpotifyPlayerEvent::PositionCorrection { position_ms, .. }
| SpotifyPlayerEvent::Seeked { position_ms, .. } => { | SpotifyPlayerEvent::Seeked { position_ms, .. } => {
@ -306,34 +258,6 @@ impl Player {
_ = tx.send(Some(lyrics)); _ = tx.send(Some(lyrics));
} }
async fn queue_playlist(&self, playlist_uri: String) {
let playlist = Playlist::get(&self.session, &SpotifyId::from_uri(&playlist_uri).unwrap())
.await
.unwrap();
let tracks = playlist
.tracks()
.map(|track_id| {
let mut track = TrackRef::new();
track.set_gid(Vec::from(track_id.to_raw()));
track
})
.collect();
self.spirc.activate().unwrap();
self.spirc
.load(SpircLoadCommand {
context_uri: playlist_uri,
start_playing: true,
shuffle: true,
repeat: true,
playing_track_index: 0,
tracks,
})
.unwrap();
}
} }
impl Drop for Player { impl Drop for Player {
@ -388,11 +312,4 @@ impl PlayerHandle {
pub async fn shutdown(&self) { pub async fn shutdown(&self) {
_ = self.commands.send(PlayerCommand::Shutdown).await; _ = self.commands.send(PlayerCommand::Shutdown).await;
} }
pub async fn queue_playlist(&self, playlist_uri: String) {
self.commands
.send(PlayerCommand::QueuePlaylist { uri: playlist_uri })
.await
.unwrap()
}
} }

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_session" name = "spoticord_session"
version = "2.2.4" version = "2.2.2"
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

@ -42,9 +42,6 @@ pub enum SessionCommand {
ShutdownPlayer, ShutdownPlayer,
Disconnect, Disconnect,
DisconnectTimedOut, DisconnectTimedOut,
QueuePlaylist {
playlist_uri: String,
},
} }
pub struct Session { pub struct Session {
@ -104,36 +101,18 @@ impl Session {
// Grab user credentials and info before joining call // Grab user credentials and info before joining call
let credentials = let credentials =
match retrieve_credentials(&session_manager.database(), owner.to_string()).await { retrieve_credentials(&session_manager.database(), owner.to_string()).await?;
Ok(credentials) => credentials, let device_name = session_manager
Err(why) => { .database()
error!("Failed to retrieve credentials: {why}"); .get_user(owner.to_string())
.await?
return Err(why); .device_name;
}
};
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 = match session_manager let call = 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
{ {
@ -194,8 +173,6 @@ 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;
}; };
@ -206,8 +183,6 @@ 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;
@ -218,8 +193,6 @@ 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;
} }
@ -228,8 +201,6 @@ 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<(), ()> {
@ -239,6 +210,7 @@ impl Session {
SessionCommand::GetOwner(sender) => _ = sender.send(self.owner), SessionCommand::GetOwner(sender) => _ = sender.send(self.owner),
SessionCommand::GetPlayer(sender) => _ = sender.send(self.player.clone()), SessionCommand::GetPlayer(sender) => _ = sender.send(self.player.clone()),
SessionCommand::GetActive(sender) => _ = sender.send(self.active), SessionCommand::GetActive(sender) => _ = sender.send(self.active),
SessionCommand::CreatePlaybackEmbed(handle, interaction, behavior) => { SessionCommand::CreatePlaybackEmbed(handle, interaction, behavior) => {
match PlaybackEmbed::create(self, handle, interaction, behavior).await { match PlaybackEmbed::create(self, handle, interaction, behavior).await {
Ok(opt_handle) => { Ok(opt_handle) => {
@ -292,9 +264,6 @@ impl Session {
return ControlFlow::Break(()); return ControlFlow::Break(());
} }
SessionCommand::QueuePlaylist { playlist_uri } => {
self.player.queue_playlist(playlist_uri).await;
}
}; };
ControlFlow::Continue(()) ControlFlow::Continue(())
@ -306,22 +275,6 @@ impl Session {
PlayerEvent::Pause => self.start_timeout(), PlayerEvent::Pause => self.start_timeout(),
PlayerEvent::Stopped => self.shutdown_player().await, PlayerEvent::Stopped => self.shutdown_player().await,
PlayerEvent::TrackChanged(_) => {} PlayerEvent::TrackChanged(_) => {}
PlayerEvent::ConnectionReset => {
self.disconnect().await;
_ = self
.text_channel
.send_message(
&self.context,
CreateMessage::new().embed(
CreateEmbed::new()
.title("Spotify connection lost")
.description("The bot has lost connection to the Spotify AP servers.\nThis is most likely caused by a connection reset on Spotify's end.\n\nUse `/join` to resummon the bot to your voice channel.")
.color(Colors::Error),
),
)
.await;
}
} }
let force_edit = !matches!(event, PlayerEvent::TrackChanged(_)); let force_edit = !matches!(event, PlayerEvent::TrackChanged(_));
@ -511,13 +464,13 @@ impl SessionHandle {
/// This playback embed will automatically update when certain events happen /// This playback embed will automatically update when certain events happen
pub async fn create_playback_embed( pub async fn create_playback_embed(
&self, &self,
interaction: &CommandInteraction, interaction: CommandInteraction,
behavior: playback_embed::UpdateBehavior, behavior: playback_embed::UpdateBehavior,
) -> Result<()> { ) -> Result<()> {
self.commands self.commands
.send(SessionCommand::CreatePlaybackEmbed( .send(SessionCommand::CreatePlaybackEmbed(
self.clone(), self.clone(),
interaction.to_owned(), interaction,
behavior, behavior,
)) ))
.await?; .await?;
@ -556,14 +509,6 @@ impl SessionHandle {
error!("Failed to send command: {why}"); error!("Failed to send command: {why}");
} }
} }
pub async fn queue_playlist(&self, playlist_uri: String) -> Result<()> {
self.commands
.send(SessionCommand::QueuePlaylist { playlist_uri })
.await?;
Ok(())
}
} }
#[async_trait] #[async_trait]
@ -574,10 +519,8 @@ 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 voice gateway, cleaning up"); debug!("Bot disconnected from call, cleaning up");
self.disconnect().await; self.disconnect().await;
} }
@ -629,7 +572,7 @@ async fn retrieve_credentials(database: &Database, owner: impl AsRef<str>) -> Re
None => { None => {
let access_token = database.get_access_token(&account.user_id).await?; let access_token = database.get_access_token(&account.user_id).await?;
let credentials = spotify::request_session_token(Credentials { let credentials = spotify::request_session_token(Credentials {
username: Some(account.username.to_string()), username: account.username.clone(),
auth_type: AuthenticationType::AUTHENTICATION_SPOTIFY_TOKEN, auth_type: AuthenticationType::AUTHENTICATION_SPOTIFY_TOKEN,
auth_data: access_token.into_bytes(), auth_data: access_token.into_bytes(),
}) })
@ -645,7 +588,7 @@ async fn retrieve_credentials(database: &Database, owner: impl AsRef<str>) -> Re
}; };
Ok(Credentials { Ok(Credentials {
username: Some(account.username), username: account.username,
auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS, auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS,
auth_data: BASE64.decode(token)?, auth_data: BASE64.decode(token)?,
}) })

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_stats" name = "spoticord_stats"
version = "2.2.4" version = "2.2.2"
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.4" version = "2.2.2"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
@ -9,4 +9,3 @@ 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

@ -1,12 +1,11 @@
use anyhow::Result; use anyhow::Result;
use base64::{engine::general_purpose::STANDARD as BASE64, Engine}; use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use librespot::{ use librespot::{
core::{Session, SessionConfig}, core::{connection::AuthenticationError, Session, SessionConfig},
discovery::Credentials, discovery::Credentials,
protocol::authentication::AuthenticationType, protocol::{authentication::AuthenticationType, keyexchange::ErrorCode},
}; };
use log::debug; use log::trace;
use std::time::Duration;
pub async fn validate_token( pub async fn validate_token(
username: impl Into<String>, username: impl Into<String>,
@ -15,17 +14,17 @@ pub async fn validate_token(
let auth_data = BASE64.decode(token.into())?; let auth_data = BASE64.decode(token.into())?;
let credentials = Credentials { let credentials = Credentials {
username: Some(username.into()), username: username.into(),
auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS, auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS,
auth_data, auth_data,
}; };
debug!("Validating session token for {:?}", credentials.username); trace!("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 {
debug!("New session token retrieved for {:?}", credentials.username); trace!("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)));
} }
@ -34,45 +33,37 @@ 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> {
debug!("Requesting session token for {:?}", credentials.username); trace!("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 {
match connect(&session, credentials.clone()).await { let (host, port) = session.apresolver().resolve("accesspoint").await?;
Ok(creds) => break creds, let mut transport = librespot::core::connection::connect(&host, port, None).await?;
Err(e) => {
tries += 1;
if tries > 3 {
return Err(e);
}
tokio::time::sleep(Duration::from_millis(100)).await; match librespot::core::connection::authenticate(
}
}
})
}
/// Wrapper around session connecting that times out if an operation is still busy after 3 seconds
async fn connect(session: &Session, credentials: Credentials) -> Result<Credentials> {
const TIMEOUT: Duration = Duration::from_secs(3);
let (host, port) =
tokio::time::timeout(TIMEOUT, session.apresolver().resolve("accesspoint")).await??;
// `connect` already has a 3 second timeout internally
let mut transport = librespot::core::connection::connect(&host, port, None).await?;
let creds = tokio::time::timeout(
TIMEOUT,
librespot::core::connection::authenticate(
&mut transport, &mut transport,
credentials.clone(), credentials.clone(),
&session.config().device_id, &session.config().device_id,
), )
) .await
.await??; {
Ok(creds) => break creds,
Err(e) => {
if let Some(AuthenticationError::LoginFailed(ErrorCode::TryAnotherAP)) =
e.error.downcast_ref::<AuthenticationError>()
{
tries += 1;
if tries > 3 {
return Err(e.into());
}
Ok(creds) continue;
} else {
return Err(e.into());
}
}
};
})
} }

View File

@ -4,7 +4,6 @@ use anyhow::{anyhow, Result};
use log::{debug, info}; use log::{debug, info};
use poise::{serenity_prelude, Framework, FrameworkContext, FrameworkOptions}; use poise::{serenity_prelude, Framework, FrameworkContext, FrameworkOptions};
use serenity::all::{ActivityData, FullEvent, Ready, ShardManager}; use serenity::all::{ActivityData, FullEvent, Ready, ShardManager};
use spoticord_api::SpoticordApi;
use spoticord_database::Database; use spoticord_database::Database;
use spoticord_session::manager::SessionManager; use spoticord_session::manager::SessionManager;
@ -18,6 +17,11 @@ 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![
@ -69,7 +73,7 @@ pub async fn setup(
let manager = SessionManager::new(songbird, database); let manager = SessionManager::new(songbird, database);
#[cfg(feature = "stats")] #[cfg(feature = "stats")]
let stats = StatsManager::new(spoticord_config::kv_url())?; let stats = StatsManager::new(std::env::var("KV_URL")?)?;
tokio::spawn(background_loop( tokio::spawn(background_loop(
manager.clone(), manager.clone(),
@ -85,7 +89,7 @@ async fn event_handler(
ctx: &serenity_prelude::Context, ctx: &serenity_prelude::Context,
event: &FullEvent, event: &FullEvent,
_framework: FrameworkContext<'_, Data, anyhow::Error>, _framework: FrameworkContext<'_, Data, anyhow::Error>,
data: &Data, _data: &Data,
) -> Result<()> { ) -> Result<()> {
if let FullEvent::Ready { data_about_bot } = event { if let FullEvent::Ready { data_about_bot } = event {
if let Some(shard) = data_about_bot.shard { if let Some(shard) = data_about_bot.shard {
@ -96,19 +100,7 @@ async fn event_handler(
} }
ctx.set_activity(Some(ActivityData::listening(spoticord_config::MOTD))); ctx.set_activity(Some(ActivityData::listening(spoticord_config::MOTD)));
}
let api_server = SpoticordApi {
session: data.clone(),
};
tokio::spawn(async move {
tonic::transport::Server::builder()
.add_service(spoticord_api_grpc::spoticord_api::service::spoticord_api_server::SpoticordApiServer::new(api_server))
.serve("127.0.0.1:8080".parse().unwrap())
.await
.unwrap();
});
};
Ok(()) Ok(())
} }
@ -119,14 +111,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; use log::{error, trace};
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")]
{ {
debug!("Retrieving active sessions count for stats"); trace!("Retrieving active sessions count for stats");
let mut count = 0; let mut count = 0;
@ -139,7 +131,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 {
debug!("Active session count set to: {count}"); trace!("Active session count set to: {count}");
} }
} }
} }

View File

@ -38,7 +38,10 @@ pub async fn playing(
}; };
session session
.create_playback_embed(context.interaction, update_behavior.unwrap_or_default()) .create_playback_embed(
context.interaction.clone(),
update_behavior.unwrap_or_default(),
)
.await?; .await?;
Ok(()) Ok(())

View File

@ -1,5 +1,7 @@
mod bot; mod bot;
mod commands; mod commands;
// mod session;
// mod utils;
use log::{error, info}; use log::{error, info};
use poise::Framework; use poise::Framework;
@ -9,11 +11,6 @@ use spoticord_database::Database;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
// Force aws-lc-rs as default crypto provider
// Since multiple dependencies either enable aws_lc_rs or ring, they cause a clash, so we have to
// explicitly tell rustls to use the aws-lc-rs provider
_ = rustls::crypto::aws_lc_rs::default_provider().install_default();
// Setup logging // Setup logging
if std::env::var("RUST_LOG").is_err() { if std::env::var("RUST_LOG").is_err() {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]