Compare commits

...

11 Commits

Author SHA1 Message Date
Joey Hines 10a13d3daa
initial api impl 2024-10-12 12:15:31 -06:00
DaXcess 666d8b8766
Add date to changelog 2024-09-30 12:02:12 +02:00
Daniel f4fccec209
Merge pull request #41 from SpoticordMusic/dev
Update Spoticord to v2.2.4
2024-09-30 11:45:04 +02:00
DaXcess a49c1f1979
Update deps 2024-09-30 11:08:24 +02:00
DaXcess 58df939280
Made missing KV_URL env error more obvious 2024-09-27 16:15:29 +02:00
DaXcess 41d75a956c
2.2.4-dev.1
- Updated librespot to latest commits + login5 PR merged
- Fix non premium account shutting down bot
- Add additional timeouts to credential retrieval
- Add message for if AP connection drops
2024-09-27 14:53:58 +02:00
DaXcess c05624fc76
Track unexpected disconnects from AP 2024-09-24 22:59:14 +02:00
DaXcess f437473462
2.2.3 2024-09-20 09:34:12 +02:00
DaXcess b9b0051523
Merge branch 'dev' 2024-09-02 19:59:19 +02:00
DaXcess 35cf310228
I forgot to save version 2024-09-02 19:58:58 +02:00
Daniel 8ee2579aec
Merge pull request #37 from SpoticordMusic/dev
Quick update to add additional logging
2024-09-02 19:57:52 +02:00
27 changed files with 1343 additions and 466 deletions

View File

@ -1,5 +1,17 @@
# 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

1316
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.4"
edition = "2021" edition = "2021"
rust-version = "1.80.0" rust-version = "1.80.0"
@ -17,6 +17,8 @@ members = [
"spoticord_session", "spoticord_session",
"spoticord_utils", "spoticord_utils",
"spoticord_stats", "spoticord_stats",
"spoticord_api",
"spoticord_api_grpc",
] ]
[features] [features]
@ -30,6 +32,8 @@ 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"
@ -39,6 +43,8 @@ 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 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 \

View File

@ -0,0 +1,16 @@
[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

@ -0,0 +1,39 @@
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

@ -0,0 +1,13 @@
[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

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

View File

@ -0,0 +1,21 @@
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

@ -0,0 +1,32 @@
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.2" version = "2.2.4"
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 exit the process with status 1 // WARNING: Returning an error causes librespot-playback to panic
// 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 exit the process with status 1 // WARNING: Returning an error causes librespot-playback to panic
// 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.0" version = "2.2.4"
edition = "2021" edition = "2021"
[dependencies] [dependencies]

View File

@ -15,3 +15,7 @@ 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,6 +31,10 @@ 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.0" version = "2.2.4"
edition = "2021" edition = "2021"
[dependencies] [dependencies]

View File

@ -35,8 +35,4 @@ 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!( diesel::allow_tables_to_appear_in_same_query!(account, link_request, user,);
account,
link_request,
user,
);

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spoticord_player" name = "spoticord_player"
version = "2.2.0" version = "2.2.4"
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,6 +2,10 @@ 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},
@ -13,13 +17,16 @@ use librespot::{
player::{Player as SpotifyPlayer, PlayerEvent as SpotifyPlayerEvent}, player::{Player as SpotifyPlayer, PlayerEvent as SpotifyPlayerEvent},
}, },
}; };
use log::error; use log::{error, trace};
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::{io::Write, sync::Arc}; use std::{
io::Write,
sync::{atomic::AtomicBool, Arc},
};
use tokio::sync::{mpsc, oneshot, Mutex}; use tokio::sync::{mpsc, oneshot, Mutex};
#[derive(Debug)] #[derive(Debug)]
@ -31,6 +38,7 @@ 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,
} }
@ -41,6 +49,7 @@ pub enum PlayerEvent {
Play, Play,
Stopped, Stopped,
TrackChanged(Box<PlaybackInfo>), TrackChanged(Box<PlaybackInfo>),
ConnectionReset,
} }
pub struct Player { pub struct Player {
@ -57,6 +66,9 @@ 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 {
@ -101,19 +113,38 @@ 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),
..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,
@ -123,15 +154,24 @@ impl Player {
playback_info: None, playback_info: None,
events: event_tx, events: event_tx.clone(),
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(spirc_task); tokio::spawn(async move {
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))
@ -160,6 +200,11 @@ 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) {
@ -173,10 +218,13 @@ 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, .. } => {
@ -258,6 +306,34 @@ 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 {
@ -312,4 +388,11 @@ 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.2" version = "2.2.4"
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,6 +42,9 @@ pub enum SessionCommand {
ShutdownPlayer, ShutdownPlayer,
Disconnect, Disconnect,
DisconnectTimedOut, DisconnectTimedOut,
QueuePlaylist {
playlist_uri: String,
},
} }
pub struct Session { pub struct Session {
@ -101,18 +104,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);
}
};
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 +194,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 +206,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 +218,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 +228,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<(), ()> {
@ -210,7 +239,6 @@ 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) => {
@ -264,6 +292,9 @@ impl Session {
return ControlFlow::Break(()); return ControlFlow::Break(());
} }
SessionCommand::QueuePlaylist { playlist_uri } => {
self.player.queue_playlist(playlist_uri).await;
}
}; };
ControlFlow::Continue(()) ControlFlow::Continue(())
@ -275,6 +306,22 @@ 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(_));
@ -464,13 +511,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, interaction.to_owned(),
behavior, behavior,
)) ))
.await?; .await?;
@ -509,6 +556,14 @@ 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]
@ -519,8 +574,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;
} }
@ -572,7 +629,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: account.username.clone(), username: Some(account.username.to_string()),
auth_type: AuthenticationType::AUTHENTICATION_SPOTIFY_TOKEN, auth_type: AuthenticationType::AUTHENTICATION_SPOTIFY_TOKEN,
auth_data: access_token.into_bytes(), auth_data: access_token.into_bytes(),
}) })
@ -588,7 +645,7 @@ async fn retrieve_credentials(database: &Database, owner: impl AsRef<str>) -> Re
}; };
Ok(Credentials { Ok(Credentials {
username: account.username, username: Some(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.2" version = "2.2.4"
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.4"
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

@ -1,11 +1,12 @@
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::{connection::AuthenticationError, Session, SessionConfig}, core::{Session, SessionConfig},
discovery::Credentials, discovery::Credentials,
protocol::{authentication::AuthenticationType, keyexchange::ErrorCode}, protocol::authentication::AuthenticationType,
}; };
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>,
@ -14,17 +15,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: username.into(), username: Some(username.into()),
auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS, auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS,
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,37 +34,45 @@ 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?; match connect(&session, credentials.clone()).await {
let mut transport = librespot::core::connection::connect(&host, port, None).await?; Ok(creds) => break creds,
Err(e) => {
tries += 1;
if tries > 3 {
return Err(e);
}
match librespot::core::connection::authenticate( tokio::time::sleep(Duration::from_millis(100)).await;
}
}
})
}
/// 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());
}
continue; Ok(creds)
} else {
return Err(e.into());
}
}
};
})
} }

View File

@ -4,6 +4,7 @@ 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;
@ -17,11 +18,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![
@ -73,7 +69,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(std::env::var("KV_URL")?)?; let stats = StatsManager::new(spoticord_config::kv_url())?;
tokio::spawn(background_loop( tokio::spawn(background_loop(
manager.clone(), manager.clone(),
@ -89,7 +85,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 {
@ -100,7 +96,19 @@ 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(())
} }
@ -111,14 +119,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 +139,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}");
} }
} }
} }

View File

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

View File

@ -1,7 +1,5 @@
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;
@ -11,6 +9,11 @@ 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)]