2021-12-26 20:18:42 +00:00
|
|
|
use std::{
|
|
|
|
collections::HashMap,
|
|
|
|
future::Future,
|
|
|
|
io,
|
|
|
|
pin::Pin,
|
|
|
|
process::exit,
|
2022-01-16 20:29:59 +00:00
|
|
|
sync::{Arc, Weak},
|
2021-12-26 20:18:42 +00:00
|
|
|
task::{Context, Poll},
|
2023-06-01 19:39:35 +00:00
|
|
|
time::{Duration, SystemTime, UNIX_EPOCH},
|
2021-12-26 20:18:42 +00:00
|
|
|
};
|
2019-03-24 14:15:14 +00:00
|
|
|
|
|
|
|
use byteorder::{BigEndian, ByteOrder};
|
|
|
|
use bytes::Bytes;
|
2021-02-10 21:54:35 +00:00
|
|
|
use futures_core::TryStream;
|
2024-10-15 11:36:17 +00:00
|
|
|
use futures_util::StreamExt;
|
2024-09-13 05:35:55 +00:00
|
|
|
use librespot_protocol::authentication::AuthenticationType;
|
2021-06-22 21:57:38 +00:00
|
|
|
use num_traits::FromPrimitive;
|
2021-02-10 21:54:35 +00:00
|
|
|
use once_cell::sync::OnceCell;
|
2021-12-26 21:55:45 +00:00
|
|
|
use parking_lot::RwLock;
|
2024-10-15 11:36:17 +00:00
|
|
|
use pin_project_lite::pin_project;
|
2021-12-10 23:03:35 +00:00
|
|
|
use quick_xml::events::Event;
|
2021-02-13 10:53:23 +00:00
|
|
|
use thiserror::Error;
|
2024-10-15 11:36:17 +00:00
|
|
|
use tokio::{
|
|
|
|
sync::mpsc,
|
|
|
|
time::{sleep, Duration as TokioDuration, Instant as TokioInstant, Sleep},
|
|
|
|
};
|
2021-02-10 21:54:35 +00:00
|
|
|
use tokio_stream::wrappers::UnboundedReceiverStream;
|
2015-06-23 14:38:29 +00:00
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
use crate::{
|
2024-09-13 05:35:55 +00:00
|
|
|
apresolve::{ApResolver, SocketAddress},
|
2021-12-26 20:18:42 +00:00
|
|
|
audio_key::AudioKeyManager,
|
|
|
|
authentication::Credentials,
|
|
|
|
cache::Cache,
|
|
|
|
channel::ChannelManager,
|
|
|
|
config::SessionConfig,
|
2024-09-13 05:35:55 +00:00
|
|
|
connection::{self, AuthenticationError, Transport},
|
2021-12-26 20:18:42 +00:00
|
|
|
http_client::HttpClient,
|
2024-10-19 18:27:26 +00:00
|
|
|
login5::Login5Manager,
|
2021-12-26 20:18:42 +00:00
|
|
|
mercury::MercuryManager,
|
|
|
|
packet::PacketType,
|
2022-08-29 21:51:29 +00:00
|
|
|
protocol::keyexchange::ErrorCode,
|
2021-12-26 20:18:42 +00:00
|
|
|
spclient::SpClient,
|
|
|
|
token::TokenProvider,
|
|
|
|
Error,
|
|
|
|
};
|
2016-05-09 11:22:51 +00:00
|
|
|
|
2021-02-13 10:53:23 +00:00
|
|
|
#[derive(Debug, Error)]
|
|
|
|
pub enum SessionError {
|
|
|
|
#[error(transparent)]
|
|
|
|
AuthenticationError(#[from] AuthenticationError),
|
|
|
|
#[error("Cannot create session: {0}")]
|
|
|
|
IoError(#[from] io::Error),
|
2022-01-16 00:14:00 +00:00
|
|
|
#[error("Session is not connected")]
|
|
|
|
NotConnected,
|
2021-12-26 20:18:42 +00:00
|
|
|
#[error("packet {0} unknown")]
|
|
|
|
Packet(u8),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<SessionError> for Error {
|
|
|
|
fn from(err: SessionError) -> Self {
|
|
|
|
match err {
|
|
|
|
SessionError::AuthenticationError(_) => Error::unauthenticated(err),
|
|
|
|
SessionError::IoError(_) => Error::unavailable(err),
|
2022-01-16 00:14:00 +00:00
|
|
|
SessionError::NotConnected => Error::unavailable(err),
|
2021-12-26 20:18:42 +00:00
|
|
|
SessionError::Packet(_) => Error::unimplemented(err),
|
|
|
|
}
|
|
|
|
}
|
2021-02-13 10:53:23 +00:00
|
|
|
}
|
2021-01-18 13:30:24 +00:00
|
|
|
|
2021-12-10 23:03:35 +00:00
|
|
|
pub type UserAttributes = HashMap<String, String>;
|
|
|
|
|
2021-12-11 19:22:44 +00:00
|
|
|
#[derive(Debug, Clone, Default)]
|
|
|
|
pub struct UserData {
|
|
|
|
pub country: String,
|
|
|
|
pub canonical_username: String,
|
|
|
|
pub attributes: UserAttributes,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Clone, Default)]
|
2018-02-12 19:10:36 +00:00
|
|
|
struct SessionData {
|
2022-01-12 21:09:57 +00:00
|
|
|
client_id: String,
|
2022-08-23 20:23:37 +00:00
|
|
|
client_name: String,
|
|
|
|
client_brand_name: String,
|
|
|
|
client_model_name: String,
|
2021-12-11 22:06:58 +00:00
|
|
|
connection_id: String,
|
2024-09-13 05:35:55 +00:00
|
|
|
auth_data: Vec<u8>,
|
2019-03-25 19:27:30 +00:00
|
|
|
time_delta: i64,
|
2018-04-21 15:46:29 +00:00
|
|
|
invalid: bool,
|
2021-12-11 19:22:44 +00:00
|
|
|
user_data: UserData,
|
2015-12-29 12:13:26 +00:00
|
|
|
}
|
|
|
|
|
2018-02-12 19:13:37 +00:00
|
|
|
struct SessionInternal {
|
2017-08-03 18:31:15 +00:00
|
|
|
config: SessionConfig,
|
2016-01-26 23:01:45 +00:00
|
|
|
data: RwLock<SessionData>,
|
2015-06-23 14:38:29 +00:00
|
|
|
|
2021-06-20 21:09:27 +00:00
|
|
|
http_client: HttpClient,
|
2022-01-16 00:14:00 +00:00
|
|
|
tx_connection: OnceCell<mpsc::UnboundedSender<(u8, Vec<u8>)>>,
|
2017-01-18 20:39:46 +00:00
|
|
|
|
2021-06-21 21:49:37 +00:00
|
|
|
apresolver: OnceCell<ApResolver>,
|
2021-01-21 20:49:39 +00:00
|
|
|
audio_key: OnceCell<AudioKeyManager>,
|
|
|
|
channel: OnceCell<ChannelManager>,
|
|
|
|
mercury: OnceCell<MercuryManager>,
|
2021-11-26 22:21:27 +00:00
|
|
|
spclient: OnceCell<SpClient>,
|
2021-06-19 20:47:39 +00:00
|
|
|
token_provider: OnceCell<TokenProvider>,
|
2024-10-19 18:27:26 +00:00
|
|
|
login5: OnceCell<Login5Manager>,
|
2017-01-29 15:36:39 +00:00
|
|
|
cache: Option<Arc<Cache>>,
|
2017-01-19 22:45:24 +00:00
|
|
|
|
2021-02-20 21:14:15 +00:00
|
|
|
handle: tokio::runtime::Handle,
|
2015-04-25 20:32:07 +00:00
|
|
|
}
|
|
|
|
|
2023-06-01 19:39:35 +00:00
|
|
|
/// A shared reference to a Spotify session.
|
|
|
|
///
|
|
|
|
/// After instantiating, you need to login via [Session::connect].
|
|
|
|
/// You can either implement the whole playback logic yourself by using
|
|
|
|
/// this structs interface directly or hand it to a
|
|
|
|
/// `Player`.
|
|
|
|
///
|
|
|
|
/// *Note*: [Session] instances cannot yet be reused once invalidated. After
|
|
|
|
/// an unexpectedly closed connection, you'll need to create a new [Session].
|
2017-01-18 20:39:46 +00:00
|
|
|
#[derive(Clone)]
|
2018-02-12 19:13:37 +00:00
|
|
|
pub struct Session(Arc<SessionInternal>);
|
2017-01-18 20:39:46 +00:00
|
|
|
|
2015-04-25 20:32:07 +00:00
|
|
|
impl Session {
|
2022-01-16 00:14:00 +00:00
|
|
|
pub fn new(config: SessionConfig, cache: Option<Cache>) -> Self {
|
2021-06-20 21:09:27 +00:00
|
|
|
let http_client = HttpClient::new(config.proxy.as_ref());
|
2017-01-20 02:37:02 +00:00
|
|
|
|
2022-01-16 20:29:59 +00:00
|
|
|
debug!("new Session");
|
2017-01-18 18:41:22 +00:00
|
|
|
|
2022-01-22 20:17:55 +00:00
|
|
|
let session_data = SessionData {
|
|
|
|
client_id: config.client_id.clone(),
|
|
|
|
..SessionData::default()
|
|
|
|
};
|
|
|
|
|
2022-01-16 00:14:00 +00:00
|
|
|
Self(Arc::new(SessionInternal {
|
2021-03-01 02:37:22 +00:00
|
|
|
config,
|
2022-01-22 20:17:55 +00:00
|
|
|
data: RwLock::new(session_data),
|
2021-06-20 21:09:27 +00:00
|
|
|
http_client,
|
2022-01-16 00:14:00 +00:00
|
|
|
tx_connection: OnceCell::new(),
|
2017-01-29 15:36:39 +00:00
|
|
|
cache: cache.map(Arc::new),
|
2021-06-21 21:49:37 +00:00
|
|
|
apresolver: OnceCell::new(),
|
2021-01-21 20:49:39 +00:00
|
|
|
audio_key: OnceCell::new(),
|
|
|
|
channel: OnceCell::new(),
|
|
|
|
mercury: OnceCell::new(),
|
2021-11-26 22:21:27 +00:00
|
|
|
spclient: OnceCell::new(),
|
2021-06-19 20:47:39 +00:00
|
|
|
token_provider: OnceCell::new(),
|
2024-10-19 18:27:26 +00:00
|
|
|
login5: OnceCell::new(),
|
2021-06-21 21:49:37 +00:00
|
|
|
handle: tokio::runtime::Handle::current(),
|
2022-01-16 00:14:00 +00:00
|
|
|
}))
|
|
|
|
}
|
2016-03-13 20:45:31 +00:00
|
|
|
|
2024-09-13 05:35:55 +00:00
|
|
|
async fn connect_inner(
|
|
|
|
&self,
|
2024-09-23 18:44:51 +00:00
|
|
|
access_point: &SocketAddress,
|
2024-09-13 05:35:55 +00:00
|
|
|
credentials: Credentials,
|
|
|
|
) -> Result<(Credentials, Transport), Error> {
|
2024-09-23 18:44:51 +00:00
|
|
|
const MAX_RETRIES: u8 = 1;
|
|
|
|
let mut transport = connection::connect_with_retry(
|
2024-09-13 05:35:55 +00:00
|
|
|
&access_point.0,
|
|
|
|
access_point.1,
|
|
|
|
self.config().proxy.as_ref(),
|
2024-09-23 18:44:51 +00:00
|
|
|
MAX_RETRIES,
|
2024-09-13 05:35:55 +00:00
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
let mut reusable_credentials = connection::authenticate(
|
|
|
|
&mut transport,
|
|
|
|
credentials.clone(),
|
|
|
|
&self.config().device_id,
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
// Might be able to remove this once keymaster is replaced with login5.
|
|
|
|
if credentials.auth_type == AuthenticationType::AUTHENTICATION_SPOTIFY_TOKEN {
|
|
|
|
trace!(
|
|
|
|
"Reconnect using stored credentials as token authed sessions cannot use keymaster."
|
|
|
|
);
|
2024-09-23 18:44:51 +00:00
|
|
|
transport = connection::connect_with_retry(
|
2024-09-13 05:35:55 +00:00
|
|
|
&access_point.0,
|
|
|
|
access_point.1,
|
|
|
|
self.config().proxy.as_ref(),
|
2024-09-23 18:44:51 +00:00
|
|
|
MAX_RETRIES,
|
2024-09-13 05:35:55 +00:00
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
reusable_credentials = connection::authenticate(
|
|
|
|
&mut transport,
|
|
|
|
reusable_credentials.clone(),
|
|
|
|
&self.config().device_id,
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok((reusable_credentials, transport))
|
|
|
|
}
|
|
|
|
|
2021-01-21 20:49:39 +00:00
|
|
|
pub async fn connect(
|
2022-07-27 21:31:11 +00:00
|
|
|
&self,
|
2018-02-11 11:37:08 +00:00
|
|
|
credentials: Credentials,
|
2022-05-20 10:53:44 +00:00
|
|
|
store_credentials: bool,
|
2022-07-27 21:31:11 +00:00
|
|
|
) -> Result<(), Error> {
|
2024-09-23 18:44:51 +00:00
|
|
|
// There currently happen to be 6 APs but anything will do to avoid an infinite loop.
|
|
|
|
const MAX_AP_TRIES: u8 = 6;
|
|
|
|
let mut num_ap_tries = 0;
|
2022-08-29 21:51:29 +00:00
|
|
|
let (reusable_credentials, transport) = loop {
|
|
|
|
let ap = self.apresolver().resolve("accesspoint").await?;
|
|
|
|
info!("Connecting to AP \"{}:{}\"", ap.0, ap.1);
|
2024-09-23 18:44:51 +00:00
|
|
|
match self.connect_inner(&ap, credentials.clone()).await {
|
2024-09-13 05:35:55 +00:00
|
|
|
Ok(ct) => break ct,
|
2022-08-29 21:51:29 +00:00
|
|
|
Err(e) => {
|
2024-09-23 18:44:51 +00:00
|
|
|
num_ap_tries += 1;
|
|
|
|
if MAX_AP_TRIES == num_ap_tries {
|
|
|
|
error!("Tried too many access points");
|
|
|
|
return Err(e);
|
|
|
|
}
|
2022-08-29 21:51:29 +00:00
|
|
|
if let Some(AuthenticationError::LoginFailed(ErrorCode::TryAnotherAP)) =
|
|
|
|
e.error.downcast_ref::<AuthenticationError>()
|
|
|
|
{
|
|
|
|
warn!("Instructed to try another access point...");
|
|
|
|
continue;
|
2024-09-23 18:44:51 +00:00
|
|
|
} else if let Some(AuthenticationError::LoginFailed(..)) =
|
|
|
|
e.error.downcast_ref::<AuthenticationError>()
|
|
|
|
{
|
2022-08-29 21:51:29 +00:00
|
|
|
return Err(e);
|
2024-09-23 18:44:51 +00:00
|
|
|
} else {
|
|
|
|
warn!("Try another access point...");
|
|
|
|
continue;
|
2022-08-29 21:51:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2021-06-21 21:49:37 +00:00
|
|
|
|
2024-09-13 05:35:55 +00:00
|
|
|
let username = reusable_credentials
|
|
|
|
.username
|
|
|
|
.as_ref()
|
|
|
|
.map_or("UNKNOWN", |s| s.as_str());
|
|
|
|
info!("Authenticated as '{username}' !");
|
|
|
|
self.set_username(username);
|
|
|
|
self.set_auth_data(&reusable_credentials.auth_data);
|
2022-01-16 00:14:00 +00:00
|
|
|
if let Some(cache) = self.cache() {
|
2022-05-20 10:53:44 +00:00
|
|
|
if store_credentials {
|
2023-07-13 15:00:03 +00:00
|
|
|
let cred_changed = cache
|
|
|
|
.credentials()
|
|
|
|
.map(|c| c != reusable_credentials)
|
|
|
|
.unwrap_or(true);
|
|
|
|
if cred_changed {
|
|
|
|
cache.save_credentials(&reusable_credentials);
|
|
|
|
}
|
2022-05-20 10:53:44 +00:00
|
|
|
}
|
2021-06-21 21:49:37 +00:00
|
|
|
}
|
|
|
|
|
2024-10-15 11:36:17 +00:00
|
|
|
// This channel serves as a buffer for packets and serializes access to the TcpStream, such
|
|
|
|
// that `self.send_packet` can return immediately and needs no additional synchronization.
|
2022-01-16 00:14:00 +00:00
|
|
|
let (tx_connection, rx_connection) = mpsc::unbounded_channel();
|
|
|
|
self.0
|
|
|
|
.tx_connection
|
|
|
|
.set(tx_connection)
|
|
|
|
.map_err(|_| SessionError::NotConnected)?;
|
|
|
|
|
2021-06-21 21:49:37 +00:00
|
|
|
let (sink, stream) = transport.split();
|
2022-01-16 00:14:00 +00:00
|
|
|
let sender_task = UnboundedReceiverStream::new(rx_connection)
|
2021-02-10 21:54:35 +00:00
|
|
|
.map(Ok)
|
|
|
|
.forward(sink);
|
2024-10-15 11:36:17 +00:00
|
|
|
let session_weak = self.weak();
|
2021-04-12 20:54:32 +00:00
|
|
|
tokio::spawn(async move {
|
2024-10-15 11:36:17 +00:00
|
|
|
if let Err(e) = sender_task.await {
|
2021-04-12 20:54:32 +00:00
|
|
|
error!("{}", e);
|
2024-10-15 11:36:17 +00:00
|
|
|
if let Some(session) = session_weak.try_upgrade() {
|
|
|
|
if !session.is_invalid() {
|
|
|
|
session.shutdown();
|
|
|
|
}
|
|
|
|
}
|
2021-04-12 20:54:32 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2024-10-15 11:36:17 +00:00
|
|
|
tokio::spawn(DispatchTask::new(self.weak(), stream));
|
|
|
|
|
2022-01-16 00:14:00 +00:00
|
|
|
Ok(())
|
2021-06-21 21:49:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn apresolver(&self) -> &ApResolver {
|
|
|
|
self.0
|
|
|
|
.apresolver
|
|
|
|
.get_or_init(|| ApResolver::new(self.weak()))
|
2015-06-23 14:38:29 +00:00
|
|
|
}
|
2015-05-09 10:07:24 +00:00
|
|
|
|
2017-01-18 20:39:46 +00:00
|
|
|
pub fn audio_key(&self) -> &AudioKeyManager {
|
2021-01-21 20:49:39 +00:00
|
|
|
self.0
|
|
|
|
.audio_key
|
|
|
|
.get_or_init(|| AudioKeyManager::new(self.weak()))
|
2017-01-18 20:39:46 +00:00
|
|
|
}
|
2017-01-18 18:41:22 +00:00
|
|
|
|
2017-01-19 22:45:24 +00:00
|
|
|
pub fn channel(&self) -> &ChannelManager {
|
2021-01-21 20:49:39 +00:00
|
|
|
self.0
|
|
|
|
.channel
|
|
|
|
.get_or_init(|| ChannelManager::new(self.weak()))
|
2017-01-19 22:45:24 +00:00
|
|
|
}
|
|
|
|
|
2021-06-21 21:49:37 +00:00
|
|
|
pub fn http_client(&self) -> &HttpClient {
|
|
|
|
&self.0.http_client
|
|
|
|
}
|
|
|
|
|
2017-01-18 21:33:52 +00:00
|
|
|
pub fn mercury(&self) -> &MercuryManager {
|
2021-01-21 20:49:39 +00:00
|
|
|
self.0
|
|
|
|
.mercury
|
|
|
|
.get_or_init(|| MercuryManager::new(self.weak()))
|
2017-01-18 21:33:52 +00:00
|
|
|
}
|
|
|
|
|
2021-11-26 22:21:27 +00:00
|
|
|
pub fn spclient(&self) -> &SpClient {
|
|
|
|
self.0.spclient.get_or_init(|| SpClient::new(self.weak()))
|
|
|
|
}
|
|
|
|
|
2021-06-19 20:47:39 +00:00
|
|
|
pub fn token_provider(&self) -> &TokenProvider {
|
|
|
|
self.0
|
|
|
|
.token_provider
|
|
|
|
.get_or_init(|| TokenProvider::new(self.weak()))
|
|
|
|
}
|
|
|
|
|
2024-10-19 18:27:26 +00:00
|
|
|
pub fn login5(&self) -> &Login5Manager {
|
|
|
|
self.0
|
|
|
|
.login5
|
|
|
|
.get_or_init(|| Login5Manager::new(self.weak()))
|
|
|
|
}
|
|
|
|
|
2019-03-25 19:27:30 +00:00
|
|
|
pub fn time_delta(&self) -> i64 {
|
2021-12-26 21:55:45 +00:00
|
|
|
self.0.data.read().time_delta
|
2019-03-24 14:15:14 +00:00
|
|
|
}
|
|
|
|
|
2021-01-21 20:49:39 +00:00
|
|
|
pub fn spawn<T>(&self, task: T)
|
2018-02-11 11:37:08 +00:00
|
|
|
where
|
2021-01-21 20:49:39 +00:00
|
|
|
T: Future + Send + 'static,
|
|
|
|
T::Output: Send + 'static,
|
2017-01-19 22:45:24 +00:00
|
|
|
{
|
2021-02-20 21:14:15 +00:00
|
|
|
self.0.handle.spawn(task);
|
2017-01-19 22:45:24 +00:00
|
|
|
}
|
|
|
|
|
2017-02-22 04:17:04 +00:00
|
|
|
fn debug_info(&self) {
|
2018-02-11 11:37:08 +00:00
|
|
|
debug!(
|
2022-01-16 20:29:59 +00:00
|
|
|
"Session strong={} weak={}",
|
2018-02-11 11:37:08 +00:00
|
|
|
Arc::strong_count(&self.0),
|
|
|
|
Arc::weak_count(&self.0)
|
|
|
|
);
|
2017-02-22 04:17:04 +00:00
|
|
|
}
|
|
|
|
|
2021-12-11 19:22:44 +00:00
|
|
|
fn check_catalogue(attributes: &UserAttributes) {
|
|
|
|
if let Some(account_type) = attributes.get("type") {
|
|
|
|
if account_type != "premium" {
|
|
|
|
error!("librespot does not support {:?} accounts.", account_type);
|
|
|
|
info!("Please support Spotify and your artists and sign up for a premium account.");
|
|
|
|
|
|
|
|
// TODO: logout instead of exiting
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
pub fn send_packet(&self, cmd: PacketType, data: Vec<u8>) -> Result<(), Error> {
|
2022-01-16 00:14:00 +00:00
|
|
|
match self.0.tx_connection.get() {
|
|
|
|
Some(tx) => Ok(tx.send((cmd as u8, data))?),
|
|
|
|
None => Err(SessionError::NotConnected.into()),
|
|
|
|
}
|
2015-07-02 17:24:25 +00:00
|
|
|
}
|
2015-12-29 12:13:26 +00:00
|
|
|
|
2017-01-29 15:36:39 +00:00
|
|
|
pub fn cache(&self) -> Option<&Arc<Cache>> {
|
2016-03-16 04:07:04 +00:00
|
|
|
self.0.cache.as_ref()
|
|
|
|
}
|
|
|
|
|
2021-06-21 21:49:37 +00:00
|
|
|
pub fn config(&self) -> &SessionConfig {
|
2016-01-26 22:34:57 +00:00
|
|
|
&self.0.config
|
|
|
|
}
|
|
|
|
|
2021-12-30 21:36:38 +00:00
|
|
|
// This clones a fairly large struct, so use a specific getter or setter unless
|
|
|
|
// you need more fields at once, in which case this can spare multiple `read`
|
|
|
|
// locks.
|
2021-12-11 19:22:44 +00:00
|
|
|
pub fn user_data(&self) -> UserData {
|
2021-12-26 21:55:45 +00:00
|
|
|
self.0.data.read().user_data.clone()
|
2016-01-26 22:34:57 +00:00
|
|
|
}
|
|
|
|
|
2016-03-17 03:06:56 +00:00
|
|
|
pub fn device_id(&self) -> &str {
|
2017-01-18 17:07:20 +00:00
|
|
|
&self.config().device_id
|
2016-01-26 22:34:57 +00:00
|
|
|
}
|
2017-01-18 20:39:46 +00:00
|
|
|
|
2022-01-12 21:09:57 +00:00
|
|
|
pub fn client_id(&self) -> String {
|
|
|
|
self.0.data.read().client_id.clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn set_client_id(&self, client_id: &str) {
|
2024-05-11 18:53:46 +00:00
|
|
|
client_id.clone_into(&mut self.0.data.write().client_id);
|
2022-01-12 21:09:57 +00:00
|
|
|
}
|
|
|
|
|
2022-08-23 20:23:37 +00:00
|
|
|
pub fn client_name(&self) -> String {
|
|
|
|
self.0.data.read().client_name.clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn set_client_name(&self, client_name: &str) {
|
2024-05-11 18:53:46 +00:00
|
|
|
client_name.clone_into(&mut self.0.data.write().client_name);
|
2022-08-23 20:23:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn client_brand_name(&self) -> String {
|
|
|
|
self.0.data.read().client_brand_name.clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn set_client_brand_name(&self, client_brand_name: &str) {
|
2024-05-11 18:53:46 +00:00
|
|
|
client_brand_name.clone_into(&mut self.0.data.write().client_brand_name);
|
2022-08-23 20:23:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn client_model_name(&self) -> String {
|
|
|
|
self.0.data.read().client_model_name.clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn set_client_model_name(&self, client_model_name: &str) {
|
2024-05-11 18:53:46 +00:00
|
|
|
client_model_name.clone_into(&mut self.0.data.write().client_model_name);
|
2022-08-23 20:23:37 +00:00
|
|
|
}
|
|
|
|
|
2021-12-11 22:06:58 +00:00
|
|
|
pub fn connection_id(&self) -> String {
|
2021-12-26 21:55:45 +00:00
|
|
|
self.0.data.read().connection_id.clone()
|
2021-12-11 22:06:58 +00:00
|
|
|
}
|
|
|
|
|
2022-01-12 21:09:57 +00:00
|
|
|
pub fn set_connection_id(&self, connection_id: &str) {
|
2024-05-11 18:53:46 +00:00
|
|
|
connection_id.clone_into(&mut self.0.data.write().connection_id);
|
2021-12-11 22:06:58 +00:00
|
|
|
}
|
|
|
|
|
2021-12-11 19:22:44 +00:00
|
|
|
pub fn username(&self) -> String {
|
2021-12-26 21:55:45 +00:00
|
|
|
self.0.data.read().user_data.canonical_username.clone()
|
2021-12-10 23:03:35 +00:00
|
|
|
}
|
|
|
|
|
2022-01-16 00:14:00 +00:00
|
|
|
pub fn set_username(&self, username: &str) {
|
2024-05-11 18:53:46 +00:00
|
|
|
username.clone_into(&mut self.0.data.write().user_data.canonical_username);
|
2022-01-16 00:14:00 +00:00
|
|
|
}
|
|
|
|
|
2024-09-13 05:35:55 +00:00
|
|
|
pub fn auth_data(&self) -> Vec<u8> {
|
|
|
|
self.0.data.read().auth_data.clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn set_auth_data(&self, auth_data: &[u8]) {
|
|
|
|
self.0.data.write().auth_data = auth_data.to_owned();
|
|
|
|
}
|
|
|
|
|
2021-12-30 21:36:38 +00:00
|
|
|
pub fn country(&self) -> String {
|
|
|
|
self.0.data.read().user_data.country.clone()
|
|
|
|
}
|
|
|
|
|
2022-08-23 20:23:37 +00:00
|
|
|
pub fn filter_explicit_content(&self) -> bool {
|
|
|
|
match self.get_user_attribute("filter-explicit-content") {
|
|
|
|
Some(value) => matches!(&*value, "1"),
|
|
|
|
None => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn autoplay(&self) -> bool {
|
2022-09-28 20:59:03 +00:00
|
|
|
if let Some(overide) = self.config().autoplay {
|
|
|
|
return overide;
|
|
|
|
}
|
|
|
|
|
2022-08-23 20:23:37 +00:00
|
|
|
match self.get_user_attribute("autoplay") {
|
|
|
|
Some(value) => matches!(&*value, "1"),
|
|
|
|
None => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-10 23:03:35 +00:00
|
|
|
pub fn set_user_attribute(&self, key: &str, value: &str) -> Option<String> {
|
2021-12-11 19:22:44 +00:00
|
|
|
let mut dummy_attributes = UserAttributes::new();
|
|
|
|
dummy_attributes.insert(key.to_owned(), value.to_owned());
|
|
|
|
Self::check_catalogue(&dummy_attributes);
|
|
|
|
|
2021-12-10 23:03:35 +00:00
|
|
|
self.0
|
|
|
|
.data
|
|
|
|
.write()
|
2021-12-11 19:22:44 +00:00
|
|
|
.user_data
|
|
|
|
.attributes
|
2021-12-10 23:03:35 +00:00
|
|
|
.insert(key.to_owned(), value.to_owned())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn set_user_attributes(&self, attributes: UserAttributes) {
|
2021-12-11 19:22:44 +00:00
|
|
|
Self::check_catalogue(&attributes);
|
|
|
|
|
2021-12-26 21:55:45 +00:00
|
|
|
self.0.data.write().user_data.attributes.extend(attributes)
|
2021-12-10 23:03:35 +00:00
|
|
|
}
|
|
|
|
|
2021-12-30 19:52:49 +00:00
|
|
|
pub fn get_user_attribute(&self, key: &str) -> Option<String> {
|
2024-03-31 11:35:36 +00:00
|
|
|
self.0.data.read().user_data.attributes.get(key).cloned()
|
2021-12-30 19:52:49 +00:00
|
|
|
}
|
|
|
|
|
2018-02-10 09:10:26 +00:00
|
|
|
fn weak(&self) -> SessionWeak {
|
2017-01-18 20:39:46 +00:00
|
|
|
SessionWeak(Arc::downgrade(&self.0))
|
|
|
|
}
|
2017-02-22 04:17:04 +00:00
|
|
|
|
2018-04-21 15:46:29 +00:00
|
|
|
pub fn shutdown(&self) {
|
2024-09-23 18:44:51 +00:00
|
|
|
debug!("Shutdown: Invalidating session");
|
2021-12-26 21:55:45 +00:00
|
|
|
self.0.data.write().invalid = true;
|
2020-01-22 14:14:43 +00:00
|
|
|
self.mercury().shutdown();
|
2020-01-22 14:23:34 +00:00
|
|
|
self.channel().shutdown();
|
2018-04-21 15:46:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn is_invalid(&self) -> bool {
|
2021-12-26 21:55:45 +00:00
|
|
|
self.0.data.read().invalid
|
2018-04-21 15:46:29 +00:00
|
|
|
}
|
2017-01-18 20:39:46 +00:00
|
|
|
}
|
|
|
|
|
2017-02-22 04:17:04 +00:00
|
|
|
#[derive(Clone)]
|
2018-02-12 19:13:37 +00:00
|
|
|
pub struct SessionWeak(Weak<SessionInternal>);
|
2017-02-22 04:17:04 +00:00
|
|
|
|
2017-01-18 20:39:46 +00:00
|
|
|
impl SessionWeak {
|
2018-02-10 09:22:03 +00:00
|
|
|
fn try_upgrade(&self) -> Option<Session> {
|
2017-02-22 04:17:04 +00:00
|
|
|
self.0.upgrade().map(Session)
|
|
|
|
}
|
|
|
|
|
2018-02-10 09:22:03 +00:00
|
|
|
pub(crate) fn upgrade(&self) -> Session {
|
2021-12-26 21:55:45 +00:00
|
|
|
self.try_upgrade()
|
|
|
|
.expect("session was dropped and so should have this component")
|
2017-02-22 04:17:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for SessionInternal {
|
|
|
|
fn drop(&mut self) {
|
2022-01-16 20:29:59 +00:00
|
|
|
debug!("drop Session");
|
2017-02-22 04:17:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-15 11:36:17 +00:00
|
|
|
#[derive(Clone, Copy, Default, Debug, PartialEq)]
|
|
|
|
enum KeepAliveState {
|
|
|
|
#[default]
|
|
|
|
// Expecting a Ping from the server, either after startup or after a PongAck.
|
|
|
|
ExpectingPing,
|
|
|
|
|
|
|
|
// We need to send a Pong at the given time.
|
|
|
|
PendingPong,
|
|
|
|
|
|
|
|
// We just sent a Pong and wait for it be ACK'd.
|
|
|
|
ExpectingPongAck,
|
|
|
|
}
|
|
|
|
|
|
|
|
const INITIAL_PING_TIMEOUT: TokioDuration = TokioDuration::from_secs(20);
|
|
|
|
const PING_TIMEOUT: TokioDuration = TokioDuration::from_secs(80); // 60s expected + 20s buffer
|
|
|
|
const PONG_DELAY: TokioDuration = TokioDuration::from_secs(60);
|
|
|
|
const PONG_ACK_TIMEOUT: TokioDuration = TokioDuration::from_secs(20);
|
|
|
|
|
|
|
|
impl KeepAliveState {
|
|
|
|
fn debug(&self, sleep: &Sleep) {
|
|
|
|
let delay = sleep
|
|
|
|
.deadline()
|
|
|
|
.checked_duration_since(TokioInstant::now())
|
|
|
|
.map(|t| t.as_secs_f64())
|
|
|
|
.unwrap_or(f64::INFINITY);
|
|
|
|
|
|
|
|
trace!("keep-alive state: {:?}, timeout in {:.1}", self, delay);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pin_project! {
|
|
|
|
struct DispatchTask<S>
|
|
|
|
where
|
|
|
|
S: TryStream<Ok = (u8, Bytes)>
|
|
|
|
{
|
|
|
|
session: SessionWeak,
|
|
|
|
keep_alive_state: KeepAliveState,
|
|
|
|
#[pin]
|
|
|
|
stream: S,
|
|
|
|
#[pin]
|
|
|
|
timeout: Sleep,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S> PinnedDrop for DispatchTask<S>
|
|
|
|
where
|
|
|
|
S: TryStream<Ok = (u8, Bytes)>
|
|
|
|
{
|
|
|
|
fn drop(_this: Pin<&mut Self>) {
|
|
|
|
debug!("drop Dispatch");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S> DispatchTask<S>
|
2018-02-11 11:37:08 +00:00
|
|
|
where
|
2024-10-15 11:36:17 +00:00
|
|
|
S: TryStream<Ok = (u8, Bytes)>,
|
|
|
|
{
|
|
|
|
fn new(session: SessionWeak, stream: S) -> Self {
|
|
|
|
Self {
|
|
|
|
session,
|
|
|
|
keep_alive_state: KeepAliveState::ExpectingPing,
|
|
|
|
stream,
|
|
|
|
timeout: sleep(INITIAL_PING_TIMEOUT),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn dispatch(
|
|
|
|
mut self: Pin<&mut Self>,
|
|
|
|
session: &Session,
|
|
|
|
cmd: u8,
|
|
|
|
data: Bytes,
|
|
|
|
) -> Result<(), Error> {
|
|
|
|
use KeepAliveState::*;
|
|
|
|
use PacketType::*;
|
|
|
|
|
|
|
|
let packet_type = FromPrimitive::from_u8(cmd);
|
|
|
|
let cmd = match packet_type {
|
|
|
|
Some(cmd) => cmd,
|
|
|
|
None => {
|
|
|
|
trace!("Ignoring unknown packet {:x}", cmd);
|
|
|
|
return Err(SessionError::Packet(cmd).into());
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
match packet_type {
|
|
|
|
Some(Ping) => {
|
|
|
|
trace!("Received Ping");
|
|
|
|
if self.keep_alive_state != ExpectingPing {
|
|
|
|
warn!("Received unexpected Ping from server")
|
|
|
|
}
|
|
|
|
let mut this = self.as_mut().project();
|
|
|
|
*this.keep_alive_state = PendingPong;
|
|
|
|
this.timeout
|
|
|
|
.as_mut()
|
|
|
|
.reset(TokioInstant::now() + PONG_DELAY);
|
|
|
|
this.keep_alive_state.debug(&this.timeout);
|
|
|
|
|
|
|
|
let server_timestamp = BigEndian::read_u32(data.as_ref()) as i64;
|
|
|
|
let timestamp = SystemTime::now()
|
|
|
|
.duration_since(UNIX_EPOCH)
|
|
|
|
.unwrap_or(Duration::ZERO)
|
|
|
|
.as_secs() as i64;
|
|
|
|
{
|
|
|
|
let mut data = session.0.data.write();
|
|
|
|
data.time_delta = server_timestamp.saturating_sub(timestamp);
|
|
|
|
}
|
|
|
|
|
|
|
|
session.debug_info();
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
Some(PongAck) => {
|
|
|
|
trace!("Received PongAck");
|
|
|
|
if self.keep_alive_state != ExpectingPongAck {
|
|
|
|
warn!("Received unexpected PongAck from server")
|
|
|
|
}
|
|
|
|
let mut this = self.as_mut().project();
|
|
|
|
*this.keep_alive_state = ExpectingPing;
|
|
|
|
this.timeout
|
|
|
|
.as_mut()
|
|
|
|
.reset(TokioInstant::now() + PING_TIMEOUT);
|
|
|
|
this.keep_alive_state.debug(&this.timeout);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
Some(CountryCode) => {
|
|
|
|
let country = String::from_utf8(data.as_ref().to_owned())?;
|
|
|
|
info!("Country: {:?}", country);
|
|
|
|
session.0.data.write().user_data.country = country;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
Some(StreamChunkRes) | Some(ChannelError) => session.channel().dispatch(cmd, data),
|
|
|
|
Some(AesKey) | Some(AesKeyError) => session.audio_key().dispatch(cmd, data),
|
|
|
|
Some(MercuryReq) | Some(MercurySub) | Some(MercuryUnsub) | Some(MercuryEvent) => {
|
|
|
|
session.mercury().dispatch(cmd, data)
|
|
|
|
}
|
|
|
|
Some(ProductInfo) => {
|
|
|
|
let data = std::str::from_utf8(&data)?;
|
|
|
|
let mut reader = quick_xml::Reader::from_str(data);
|
|
|
|
|
|
|
|
let mut buf = Vec::new();
|
|
|
|
let mut current_element = String::new();
|
|
|
|
let mut user_attributes: UserAttributes = HashMap::new();
|
|
|
|
|
|
|
|
loop {
|
|
|
|
match reader.read_event_into(&mut buf) {
|
|
|
|
Ok(Event::Start(ref element)) => {
|
|
|
|
std::str::from_utf8(element)?.clone_into(&mut current_element)
|
|
|
|
}
|
|
|
|
Ok(Event::End(_)) => {
|
|
|
|
current_element = String::new();
|
|
|
|
}
|
|
|
|
Ok(Event::Text(ref value)) => {
|
|
|
|
if !current_element.is_empty() {
|
|
|
|
let _ = user_attributes
|
|
|
|
.insert(current_element.clone(), value.unescape()?.to_string());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(Event::Eof) => break,
|
|
|
|
Ok(_) => (),
|
|
|
|
Err(e) => warn!(
|
|
|
|
"Error parsing XML at position {}: {:?}",
|
|
|
|
reader.buffer_position(),
|
|
|
|
e
|
|
|
|
),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
trace!("Received product info: {:#?}", user_attributes);
|
|
|
|
Session::check_catalogue(&user_attributes);
|
|
|
|
|
|
|
|
session.0.data.write().user_data.attributes = user_attributes;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
Some(SecretBlock)
|
|
|
|
| Some(LegacyWelcome)
|
|
|
|
| Some(UnknownDataAllZeros)
|
|
|
|
| Some(LicenseVersion) => Ok(()),
|
|
|
|
_ => {
|
|
|
|
trace!("Ignoring {:?} packet with data {:#?}", cmd, data);
|
|
|
|
Err(SessionError::Packet(cmd as u8).into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-02-22 04:17:04 +00:00
|
|
|
|
2018-02-11 11:37:08 +00:00
|
|
|
impl<S> Future for DispatchTask<S>
|
|
|
|
where
|
2024-10-15 11:36:17 +00:00
|
|
|
S: TryStream<Ok = (u8, Bytes), Error = std::io::Error>,
|
2021-01-21 20:49:39 +00:00
|
|
|
<S as TryStream>::Ok: std::fmt::Debug,
|
2017-02-22 04:17:04 +00:00
|
|
|
{
|
2021-01-21 20:49:39 +00:00
|
|
|
type Output = Result<(), S::Error>;
|
2017-02-22 04:17:04 +00:00
|
|
|
|
2021-01-21 20:49:39 +00:00
|
|
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
2024-10-15 11:36:17 +00:00
|
|
|
use KeepAliveState::*;
|
|
|
|
|
|
|
|
let session = match self.session.try_upgrade() {
|
2017-02-22 04:17:04 +00:00
|
|
|
Some(session) => session,
|
2021-01-21 20:49:39 +00:00
|
|
|
None => return Poll::Ready(Ok(())),
|
2017-02-22 04:17:04 +00:00
|
|
|
};
|
|
|
|
|
2024-10-15 11:36:17 +00:00
|
|
|
// Process all messages that are immediately ready
|
2017-02-22 04:17:04 +00:00
|
|
|
loop {
|
2024-10-15 11:36:17 +00:00
|
|
|
match self.as_mut().project().stream.try_poll_next(cx) {
|
|
|
|
Poll::Ready(Some(Ok((cmd, data)))) => {
|
|
|
|
let result = self.as_mut().dispatch(&session, cmd, data);
|
|
|
|
if let Err(e) = result {
|
|
|
|
debug!("could not dispatch command: {}", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Poll::Ready(None) => {
|
2020-01-22 10:55:45 +00:00
|
|
|
warn!("Connection to server closed.");
|
|
|
|
session.shutdown();
|
2021-01-21 20:49:39 +00:00
|
|
|
return Poll::Ready(Ok(()));
|
2020-01-24 01:26:16 +00:00
|
|
|
}
|
2024-10-15 11:36:17 +00:00
|
|
|
Poll::Ready(Some(Err(e))) => {
|
2024-09-23 18:44:51 +00:00
|
|
|
error!("Connection to server closed.");
|
2018-04-21 15:46:29 +00:00
|
|
|
session.shutdown();
|
2021-01-21 20:49:39 +00:00
|
|
|
return Poll::Ready(Err(e));
|
2018-04-21 15:46:29 +00:00
|
|
|
}
|
2024-10-15 11:36:17 +00:00
|
|
|
Poll::Pending => break,
|
|
|
|
}
|
|
|
|
}
|
2018-04-21 15:46:29 +00:00
|
|
|
|
2024-10-15 11:36:17 +00:00
|
|
|
// Handle the keep-alive sequence, returning an error when we haven't received a
|
|
|
|
// Ping/PongAck for too long.
|
|
|
|
//
|
|
|
|
// The expected keepalive sequence is
|
|
|
|
// - Server: Ping
|
|
|
|
// - wait 60s
|
|
|
|
// - Client: Pong
|
|
|
|
// - Server: PongAck
|
|
|
|
// - wait 60s
|
|
|
|
// - repeat
|
|
|
|
//
|
|
|
|
// This means that we silently lost connection to Spotify servers if
|
|
|
|
// - we don't receive Ping immediately after connecting,
|
|
|
|
// - we don't receive a Ping 60s after the last PongAck or
|
|
|
|
// - we don't receive a PongAck immediately after our Pong.
|
|
|
|
//
|
|
|
|
// Currently, we add a safety margin of 20s to these expected deadlines.
|
|
|
|
let mut this = self.as_mut().project();
|
|
|
|
if let Poll::Ready(()) = this.timeout.as_mut().poll(cx) {
|
|
|
|
match this.keep_alive_state {
|
|
|
|
ExpectingPing | ExpectingPongAck => {
|
|
|
|
if !session.is_invalid() {
|
|
|
|
session.shutdown();
|
|
|
|
}
|
|
|
|
// TODO: Optionally reconnect (with cached/last credentials?)
|
|
|
|
return Poll::Ready(Err(io::Error::new(
|
|
|
|
io::ErrorKind::TimedOut,
|
|
|
|
format!(
|
|
|
|
"session lost connection to server ({:?})",
|
|
|
|
this.keep_alive_state
|
|
|
|
),
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
PendingPong => {
|
|
|
|
trace!("Sending Pong");
|
|
|
|
// TODO: Ideally, this should flush the `Framed<TcpStream> as Sink`
|
|
|
|
// before starting the timeout.
|
|
|
|
let _ = session.send_packet(PacketType::Pong, vec![0, 0, 0, 0]);
|
|
|
|
*this.keep_alive_state = ExpectingPongAck;
|
|
|
|
this.timeout
|
|
|
|
.as_mut()
|
|
|
|
.reset(TokioInstant::now() + PONG_ACK_TIMEOUT);
|
|
|
|
this.keep_alive_state.debug(&this.timeout);
|
|
|
|
}
|
2021-12-26 20:18:42 +00:00
|
|
|
}
|
2017-02-22 04:17:04 +00:00
|
|
|
}
|
|
|
|
|
2024-10-15 11:36:17 +00:00
|
|
|
Poll::Pending
|
2017-01-18 20:39:46 +00:00
|
|
|
}
|
2015-04-25 20:32:07 +00:00
|
|
|
}
|