Compare commits
No commits in common. "10a13d3daa4b911e9969a513c9f8d34882be8c15" and "d6329d9a29ae44c20eca01bc703481943c6a9140" have entirely different histories.
10a13d3daa
...
d6329d9a29
12
CHANGELOG.md
12
CHANGELOG.md
|
@ -1,17 +1,5 @@
|
|||
# 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
|
||||
|
||||
- Added backtrace logging to player creation to figure out some mystery crashes
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "spoticord"
|
||||
version = "2.2.4"
|
||||
version = "2.2.2"
|
||||
edition = "2021"
|
||||
rust-version = "1.80.0"
|
||||
|
||||
|
@ -17,8 +17,6 @@ members = [
|
|||
"spoticord_session",
|
||||
"spoticord_utils",
|
||||
"spoticord_stats",
|
||||
"spoticord_api",
|
||||
"spoticord_api_grpc",
|
||||
]
|
||||
|
||||
[features]
|
||||
|
@ -32,8 +30,6 @@ spoticord_player = { path = "./spoticord_player" }
|
|||
spoticord_session = { path = "./spoticord_session" }
|
||||
spoticord_utils = { path = "./spoticord_utils" }
|
||||
spoticord_stats = { path = "./spoticord_stats", optional = true }
|
||||
spoticord_api = { path = "./spoticord_api"}
|
||||
spoticord_api_grpc = { path = "./spoticord_api_grpc"}
|
||||
|
||||
anyhow = "1.0.86"
|
||||
dotenvy = "0.15.7"
|
||||
|
@ -43,8 +39,6 @@ poise = "0.6.1"
|
|||
serenity = "0.12.2"
|
||||
songbird = { version = "0.4.3", features = ["simd-json"] }
|
||||
tokio = { version = "1.39.3", features = ["full"] }
|
||||
rustls = { version = "0.23.13", features = ["aws-lc-rs"] }
|
||||
tonic = "0.12.3"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
|
|
|
@ -45,7 +45,7 @@ ARG TARGETPLATFORM
|
|||
ENV TARGETPLATFORM=${TARGETPLATFORM}
|
||||
|
||||
# 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 --from=builder \
|
||||
|
@ -63,4 +63,4 @@ RUN if [ "${TARGETPLATFORM}" = "linux/amd64" ]; then \
|
|||
# Delete unused binaries
|
||||
RUN rm -rvf /tmp/x86_64 /tmp/aarch64
|
||||
|
||||
ENTRYPOINT [ "/usr/local/bin/spoticord" ]
|
||||
ENTRYPOINT [ "/usr/local/bin/spoticord" ]
|
|
@ -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"
|
|
@ -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))
|
||||
}
|
||||
}
|
|
@ -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"
|
|
@ -1,6 +0,0 @@
|
|||
use std::io::Result;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
tonic_build::configure().compile_protos(&["src/service.proto"], &["src/"])?;
|
||||
Ok(())
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "spoticord_audio"
|
||||
version = "2.2.4"
|
||||
version = "2.2.2"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
|
|
@ -24,7 +24,7 @@ impl StreamSink {
|
|||
impl Sink for StreamSink {
|
||||
fn start(&mut self) -> SinkResult<()> {
|
||||
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()));
|
||||
}
|
||||
|
@ -34,7 +34,7 @@ impl Sink for StreamSink {
|
|||
|
||||
fn stop(&mut self) -> SinkResult<()> {
|
||||
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()));
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "spoticord_config"
|
||||
version = "2.2.4"
|
||||
version = "2.2.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
@ -15,7 +15,3 @@ pub static SPOTIFY_CLIENT_SECRET: LazyLock<String> = LazyLock::new(|| {
|
|||
std::env::var("SPOTIFY_CLIENT_SECRET")
|
||||
.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"));
|
||||
|
|
|
@ -31,10 +31,6 @@ pub fn link_url() -> &'static str {
|
|||
&env::LINK_URL
|
||||
}
|
||||
|
||||
pub fn kv_url() -> &'static str {
|
||||
&env::KV_URL
|
||||
}
|
||||
|
||||
pub fn get_spotify(token: Token) -> AuthCodeSpotify {
|
||||
AuthCodeSpotify::from_token_with_config(
|
||||
token,
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "spoticord_database"
|
||||
version = "2.2.4"
|
||||
version = "2.2.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
@ -35,4 +35,8 @@ diesel::table! {
|
|||
diesel::joinable!(account -> 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,
|
||||
);
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "spoticord_player"
|
||||
version = "2.2.4"
|
||||
version = "2.2.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
|
|
@ -2,10 +2,6 @@ pub mod info;
|
|||
|
||||
use anyhow::Result;
|
||||
use info::PlaybackInfo;
|
||||
use librespot::connect::spirc::SpircLoadCommand;
|
||||
use librespot::core::SpotifyId;
|
||||
use librespot::metadata::{Metadata, Playlist};
|
||||
use librespot::protocol::spirc::TrackRef;
|
||||
use librespot::{
|
||||
connect::{config::ConnectConfig, spirc::Spirc},
|
||||
core::{http_client::HttpClientError, Session as SpotifySession, SessionConfig},
|
||||
|
@ -17,16 +13,13 @@ use librespot::{
|
|||
player::{Player as SpotifyPlayer, PlayerEvent as SpotifyPlayerEvent},
|
||||
},
|
||||
};
|
||||
use log::{error, trace};
|
||||
use log::error;
|
||||
use songbird::{input::RawAdapter, tracks::TrackHandle, Call};
|
||||
use spoticord_audio::{
|
||||
sink::{SinkEvent, StreamSink},
|
||||
stream::Stream,
|
||||
};
|
||||
use std::{
|
||||
io::Write,
|
||||
sync::{atomic::AtomicBool, Arc},
|
||||
};
|
||||
use std::{io::Write, sync::Arc};
|
||||
use tokio::sync::{mpsc, oneshot, Mutex};
|
||||
|
||||
#[derive(Debug)]
|
||||
|
@ -38,7 +31,6 @@ enum PlayerCommand {
|
|||
|
||||
GetPlaybackInfo(oneshot::Sender<Option<PlaybackInfo>>),
|
||||
GetLyrics(oneshot::Sender<Option<Lyrics>>),
|
||||
QueuePlaylist { uri: String },
|
||||
|
||||
Shutdown,
|
||||
}
|
||||
|
@ -49,7 +41,6 @@ pub enum PlayerEvent {
|
|||
Play,
|
||||
Stopped,
|
||||
TrackChanged(Box<PlaybackInfo>),
|
||||
ConnectionReset,
|
||||
}
|
||||
|
||||
pub struct Player {
|
||||
|
@ -66,9 +57,6 @@ pub struct Player {
|
|||
commands: mpsc::Receiver<PlayerCommand>,
|
||||
spotify_events: mpsc::UnboundedReceiver<SpotifyPlayerEvent>,
|
||||
sink_events: mpsc::UnboundedReceiver<SinkEvent>,
|
||||
|
||||
/// A shared boolean that reflects whether this Player has shut down
|
||||
shutdown: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Player {
|
||||
|
@ -113,38 +101,19 @@ impl Player {
|
|||
);
|
||||
let rx_player = player.get_player_event_channel();
|
||||
|
||||
let device_name = device_name.into();
|
||||
let mut tries = 0;
|
||||
let (spirc, spirc_task) = Spirc::new(
|
||||
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 player = Self {
|
||||
session,
|
||||
|
@ -154,24 +123,15 @@ impl Player {
|
|||
|
||||
playback_info: None,
|
||||
|
||||
events: event_tx.clone(),
|
||||
events: event_tx,
|
||||
|
||||
commands: rx,
|
||||
spotify_events: rx_player,
|
||||
sink_events: rx_sink,
|
||||
|
||||
shutdown: shutdown.clone(),
|
||||
};
|
||||
|
||||
// Launch it all!
|
||||
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(spirc_task);
|
||||
tokio::spawn(player.run());
|
||||
|
||||
Ok((PlayerHandle { commands: tx }, event_rx))
|
||||
|
@ -200,11 +160,6 @@ impl Player {
|
|||
else => break,
|
||||
}
|
||||
}
|
||||
|
||||
self.shutdown
|
||||
.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
|
||||
trace!("End of Player::run");
|
||||
}
|
||||
|
||||
async fn handle_command(&mut self, command: PlayerCommand) {
|
||||
|
@ -218,13 +173,10 @@ impl Player {
|
|||
PlayerCommand::GetLyrics(tx) => self.get_lyrics(tx).await,
|
||||
|
||||
PlayerCommand::Shutdown => self.commands.close(),
|
||||
PlayerCommand::QueuePlaylist { uri } => self.queue_playlist(uri).await,
|
||||
};
|
||||
}
|
||||
|
||||
async fn handle_spotify_event(&mut self, event: SpotifyPlayerEvent) {
|
||||
trace!("Spotify event received: {event:#?}");
|
||||
|
||||
match event {
|
||||
SpotifyPlayerEvent::PositionCorrection { position_ms, .. }
|
||||
| SpotifyPlayerEvent::Seeked { position_ms, .. } => {
|
||||
|
@ -306,34 +258,6 @@ impl Player {
|
|||
|
||||
_ = 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 {
|
||||
|
@ -388,11 +312,4 @@ impl PlayerHandle {
|
|||
pub async fn shutdown(&self) {
|
||||
_ = 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()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "spoticord_session"
|
||||
version = "2.2.4"
|
||||
version = "2.2.2"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
|
|
@ -42,9 +42,6 @@ pub enum SessionCommand {
|
|||
ShutdownPlayer,
|
||||
Disconnect,
|
||||
DisconnectTimedOut,
|
||||
QueuePlaylist {
|
||||
playlist_uri: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
|
@ -104,36 +101,18 @@ impl Session {
|
|||
|
||||
// Grab user credentials and info before joining call
|
||||
let credentials =
|
||||
match retrieve_credentials(&session_manager.database(), owner.to_string()).await {
|
||||
Ok(credentials) => credentials,
|
||||
Err(why) => {
|
||||
error!("Failed to retrieve credentials: {why}");
|
||||
|
||||
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());
|
||||
}
|
||||
};
|
||||
retrieve_credentials(&session_manager.database(), owner.to_string()).await?;
|
||||
let device_name = session_manager
|
||||
.database()
|
||||
.get_user(owner.to_string())
|
||||
.await?
|
||||
.device_name;
|
||||
|
||||
// Hello Discord I'm here
|
||||
let call = match session_manager
|
||||
let call = session_manager
|
||||
.songbird()
|
||||
.join(guild_id, voice_channel_id)
|
||||
.await
|
||||
{
|
||||
Ok(call) => call,
|
||||
Err(why) => {
|
||||
error!("Failed to join voice channel: {why}");
|
||||
|
||||
return Err(why.into());
|
||||
}
|
||||
};
|
||||
.await?;
|
||||
|
||||
// Make sure call guard is dropped or else we can't execute session.run
|
||||
{
|
||||
|
@ -194,8 +173,6 @@ impl Session {
|
|||
loop {
|
||||
tokio::select! {
|
||||
opt_command = self.commands.recv() => {
|
||||
trace!("Received command: {opt_command:#?}");
|
||||
|
||||
let Some(command) = opt_command else {
|
||||
break;
|
||||
};
|
||||
|
@ -206,8 +183,6 @@ impl Session {
|
|||
},
|
||||
|
||||
opt_event = self.events.recv(), if self.active => {
|
||||
trace!("Received event: {opt_event:#?}");
|
||||
|
||||
let Some(event) = opt_event else {
|
||||
self.shutdown_player().await;
|
||||
continue;
|
||||
|
@ -218,8 +193,6 @@ impl Session {
|
|||
|
||||
// Internal communication channel
|
||||
Some(command) = self.commands_inner_rx.recv() => {
|
||||
trace!("Received internal command: {command:#?}");
|
||||
|
||||
if self.handle_command(command).await.is_break() {
|
||||
break;
|
||||
}
|
||||
|
@ -228,8 +201,6 @@ impl Session {
|
|||
else => break,
|
||||
}
|
||||
}
|
||||
|
||||
trace!("End of Session::run");
|
||||
}
|
||||
|
||||
async fn handle_command(&mut self, command: SessionCommand) -> ControlFlow<(), ()> {
|
||||
|
@ -239,6 +210,7 @@ impl Session {
|
|||
SessionCommand::GetOwner(sender) => _ = sender.send(self.owner),
|
||||
SessionCommand::GetPlayer(sender) => _ = sender.send(self.player.clone()),
|
||||
SessionCommand::GetActive(sender) => _ = sender.send(self.active),
|
||||
|
||||
SessionCommand::CreatePlaybackEmbed(handle, interaction, behavior) => {
|
||||
match PlaybackEmbed::create(self, handle, interaction, behavior).await {
|
||||
Ok(opt_handle) => {
|
||||
|
@ -292,9 +264,6 @@ impl Session {
|
|||
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
SessionCommand::QueuePlaylist { playlist_uri } => {
|
||||
self.player.queue_playlist(playlist_uri).await;
|
||||
}
|
||||
};
|
||||
|
||||
ControlFlow::Continue(())
|
||||
|
@ -306,22 +275,6 @@ impl Session {
|
|||
PlayerEvent::Pause => self.start_timeout(),
|
||||
PlayerEvent::Stopped => self.shutdown_player().await,
|
||||
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(_));
|
||||
|
@ -511,13 +464,13 @@ impl SessionHandle {
|
|||
/// This playback embed will automatically update when certain events happen
|
||||
pub async fn create_playback_embed(
|
||||
&self,
|
||||
interaction: &CommandInteraction,
|
||||
interaction: CommandInteraction,
|
||||
behavior: playback_embed::UpdateBehavior,
|
||||
) -> Result<()> {
|
||||
self.commands
|
||||
.send(SessionCommand::CreatePlaybackEmbed(
|
||||
self.clone(),
|
||||
interaction.to_owned(),
|
||||
interaction,
|
||||
behavior,
|
||||
))
|
||||
.await?;
|
||||
|
@ -556,14 +509,6 @@ impl SessionHandle {
|
|||
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]
|
||||
|
@ -574,10 +519,8 @@ impl songbird::EventHandler for SessionHandle {
|
|||
}
|
||||
|
||||
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(_) => {
|
||||
debug!("Bot disconnected from voice gateway, cleaning up");
|
||||
debug!("Bot disconnected from call, cleaning up");
|
||||
|
||||
self.disconnect().await;
|
||||
}
|
||||
|
@ -629,7 +572,7 @@ async fn retrieve_credentials(database: &Database, owner: impl AsRef<str>) -> Re
|
|||
None => {
|
||||
let access_token = database.get_access_token(&account.user_id).await?;
|
||||
let credentials = spotify::request_session_token(Credentials {
|
||||
username: Some(account.username.to_string()),
|
||||
username: account.username.clone(),
|
||||
auth_type: AuthenticationType::AUTHENTICATION_SPOTIFY_TOKEN,
|
||||
auth_data: access_token.into_bytes(),
|
||||
})
|
||||
|
@ -645,7 +588,7 @@ async fn retrieve_credentials(database: &Database, owner: impl AsRef<str>) -> Re
|
|||
};
|
||||
|
||||
Ok(Credentials {
|
||||
username: Some(account.username),
|
||||
username: account.username,
|
||||
auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS,
|
||||
auth_data: BASE64.decode(token)?,
|
||||
})
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "spoticord_stats"
|
||||
version = "2.2.4"
|
||||
version = "2.2.2"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "spoticord_utils"
|
||||
version = "2.2.4"
|
||||
version = "2.2.2"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
@ -9,4 +9,3 @@ anyhow = "1.0.86"
|
|||
base64 = "0.22.1"
|
||||
log = "0.4.22"
|
||||
poise = "0.6.1"
|
||||
tokio = { version = "1.40.0", features = ["time"], default-features = false }
|
||||
|
|
|
@ -1,12 +1,11 @@
|
|||
use anyhow::Result;
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
|
||||
use librespot::{
|
||||
core::{Session, SessionConfig},
|
||||
core::{connection::AuthenticationError, Session, SessionConfig},
|
||||
discovery::Credentials,
|
||||
protocol::authentication::AuthenticationType,
|
||||
protocol::{authentication::AuthenticationType, keyexchange::ErrorCode},
|
||||
};
|
||||
use log::debug;
|
||||
use std::time::Duration;
|
||||
use log::trace;
|
||||
|
||||
pub async fn validate_token(
|
||||
username: impl Into<String>,
|
||||
|
@ -15,17 +14,17 @@ pub async fn validate_token(
|
|||
let auth_data = BASE64.decode(token.into())?;
|
||||
|
||||
let credentials = Credentials {
|
||||
username: Some(username.into()),
|
||||
username: username.into(),
|
||||
auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS,
|
||||
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?;
|
||||
|
||||
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)));
|
||||
}
|
||||
|
@ -34,45 +33,37 @@ pub async fn validate_token(
|
|||
}
|
||||
|
||||
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 mut tries = 0;
|
||||
|
||||
Ok(loop {
|
||||
match connect(&session, credentials.clone()).await {
|
||||
Ok(creds) => break creds,
|
||||
Err(e) => {
|
||||
tries += 1;
|
||||
if tries > 3 {
|
||||
return Err(e);
|
||||
}
|
||||
let (host, port) = session.apresolver().resolve("accesspoint").await?;
|
||||
let mut transport = librespot::core::connection::connect(&host, port, None).await?;
|
||||
|
||||
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(
|
||||
match librespot::core::connection::authenticate(
|
||||
&mut transport,
|
||||
credentials.clone(),
|
||||
&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());
|
||||
}
|
||||
}
|
||||
};
|
||||
})
|
||||
}
|
||||
|
|
30
src/bot.rs
30
src/bot.rs
|
@ -4,7 +4,6 @@ use anyhow::{anyhow, Result};
|
|||
use log::{debug, info};
|
||||
use poise::{serenity_prelude, Framework, FrameworkContext, FrameworkOptions};
|
||||
use serenity::all::{ActivityData, FullEvent, Ready, ShardManager};
|
||||
use spoticord_api::SpoticordApi;
|
||||
use spoticord_database::Database;
|
||||
use spoticord_session::manager::SessionManager;
|
||||
|
||||
|
@ -18,6 +17,11 @@ pub type FrameworkError<'a> = poise::FrameworkError<'a, Data, anyhow::Error>;
|
|||
|
||||
type Data = SessionManager;
|
||||
|
||||
// pub struct Data {
|
||||
// pub database: Database,
|
||||
// pub session_manager: SessionManager,
|
||||
// }
|
||||
|
||||
pub fn framework_opts() -> FrameworkOptions<Data, anyhow::Error> {
|
||||
poise::FrameworkOptions {
|
||||
commands: vec![
|
||||
|
@ -69,7 +73,7 @@ pub async fn setup(
|
|||
let manager = SessionManager::new(songbird, database);
|
||||
|
||||
#[cfg(feature = "stats")]
|
||||
let stats = StatsManager::new(spoticord_config::kv_url())?;
|
||||
let stats = StatsManager::new(std::env::var("KV_URL")?)?;
|
||||
|
||||
tokio::spawn(background_loop(
|
||||
manager.clone(),
|
||||
|
@ -85,7 +89,7 @@ async fn event_handler(
|
|||
ctx: &serenity_prelude::Context,
|
||||
event: &FullEvent,
|
||||
_framework: FrameworkContext<'_, Data, anyhow::Error>,
|
||||
data: &Data,
|
||||
_data: &Data,
|
||||
) -> Result<()> {
|
||||
if let FullEvent::Ready { data_about_bot } = event {
|
||||
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)));
|
||||
|
||||
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(())
|
||||
}
|
||||
|
@ -119,14 +111,14 @@ async fn background_loop(
|
|||
#[cfg(feature = "stats")] mut stats_manager: spoticord_stats::StatsManager,
|
||||
) {
|
||||
#[cfg(feature = "stats")]
|
||||
use log::error;
|
||||
use log::{error, trace};
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(60)) => {
|
||||
#[cfg(feature = "stats")]
|
||||
{
|
||||
debug!("Retrieving active sessions count for stats");
|
||||
trace!("Retrieving active sessions count for stats");
|
||||
|
||||
let mut count = 0;
|
||||
|
||||
|
@ -139,7 +131,7 @@ async fn background_loop(
|
|||
if let Err(why) = stats_manager.set_active_count(count) {
|
||||
error!("Failed to update active sessions: {why}");
|
||||
} else {
|
||||
debug!("Active session count set to: {count}");
|
||||
trace!("Active session count set to: {count}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -38,7 +38,10 @@ pub async fn playing(
|
|||
};
|
||||
|
||||
session
|
||||
.create_playback_embed(context.interaction, update_behavior.unwrap_or_default())
|
||||
.create_playback_embed(
|
||||
context.interaction.clone(),
|
||||
update_behavior.unwrap_or_default(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
mod bot;
|
||||
mod commands;
|
||||
// mod session;
|
||||
// mod utils;
|
||||
|
||||
use log::{error, info};
|
||||
use poise::Framework;
|
||||
|
@ -9,11 +11,6 @@ use spoticord_database::Database;
|
|||
|
||||
#[tokio::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
|
||||
if std::env::var("RUST_LOG").is_err() {
|
||||
#[cfg(debug_assertions)]
|
||||
|
|
Loading…
Reference in New Issue