pub static TIDAL_AUTH_API_BASE_URL: &str = "https://auth.tidal.com/v1";
pub static TIDAL_V1_API_BASE_URL: &str = "https://api.tidal.com/v1";
pub static TIDAL_V2_API_BASE_URL: &str = "https://openapi.tidal.com/v2";
pub static TIDAL_USER_AGENT: &str = "rust-crate:tidalv2";
const INITIAL_BACKOFF_MILLIS: u64 = 100;
const DEFAULT_MAX_BACKOFF_MILLIS: u64 = 5_000;
const MAX_TOKEN_REFRESH_ATTEMPTS: u8 = 10;
use crate::error::{Error, TidalError, TidalUnknownError};
use arc_swap::ArcSwapOption;
use async_recursion::async_recursion;
use log::{debug, info, trace};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use strum_macros::{AsRefStr, EnumString};
use tokio::sync::{Semaphore, SemaphorePermit};
use tokio::time::sleep;
pub type AuthzCallback = Arc<dyn Fn(Authz) + Send + Sync>;
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DeviceAuthorizationResponse {
#[serde(rename = "verificationUriComplete")]
pub url: String,
pub device_code: String,
pub expires_in: u64,
pub user_code: String,
#[serde(default = "default_device_interval")]
pub interval: u64,
}
fn default_device_interval() -> u64 {
crate::auth::DEFAULT_DEVICE_INTERVAL_SECS
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AuthzToken {
#[serde(rename = "access_token")]
pub access_token: String,
pub client_name: String,
#[serde(rename = "expires_in")]
pub expires_in: i64,
#[serde(rename = "refresh_token")]
pub refresh_token: Option<String>,
pub scope: String,
#[serde(rename = "token_type")]
pub token_type: String,
pub user: crate::models::user::AuthzUser,
#[serde(rename = "user_id")]
pub user_id: i64,
}
impl AuthzToken {
pub fn expires_timestamp(&self) -> u64 {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
now.as_secs() + self.expires_in as u64
}
pub fn authz(&self) -> Authz {
Authz {
access_token: self.access_token.clone(),
refresh_token: self.refresh_token.clone(),
user_id: Some(self.user_id as u64),
country_code: Some(self.user.country_code.clone()),
expires_timestamp: Some(self.expires_timestamp()),
}
}
}
pub struct TidalClient {
pub client: reqwest::Client,
pub(crate) client_id: String,
pub(crate) client_secret: Option<String>,
pub(crate) base_path_api: String,
pub(crate) base_path_auth: String,
pub(crate) user_agent: String,
pub(crate) authz: ArcSwapOption<Authz>,
pub(crate) authz_update_semaphore: Semaphore,
pub(crate) pkce_pending: ArcSwapOption<crate::auth::PkcePending>,
pub(crate) country_code: Option<String>,
pub(crate) on_authz_refresh_callback: Option<AuthzCallback>,
locale: Option<String>,
device_type: Option<DeviceType>,
backoff: Mutex<Option<u64>>,
max_backoff_millis: Option<u64>,
}
pub type BasicAuth = (String, Option<String>);
impl TidalClient {
pub fn new(client_id: String) -> Self {
Self {
client: reqwest::Client::new(),
client_id,
client_secret: None,
authz: ArcSwapOption::from(None),
authz_update_semaphore: Semaphore::new(1),
pkce_pending: ArcSwapOption::from(None),
country_code: None,
on_authz_refresh_callback: None,
base_path_api: TIDAL_V2_API_BASE_URL.to_string(),
base_path_auth: TIDAL_AUTH_API_BASE_URL.to_string(),
user_agent: TIDAL_USER_AGENT.to_string(),
locale: None,
device_type: None,
backoff: Mutex::new(None),
max_backoff_millis: None,
}
}
pub fn with_client(mut self, client: reqwest::Client) -> Self {
self.client = client;
self
}
pub fn with_authz(mut self, authz: Authz) -> Self {
self.authz = ArcSwapOption::from_pointee(authz);
self
}
pub fn with_client_secret(mut self, client_secret: impl Into<String>) -> Self {
self.client_secret = Some(client_secret.into());
self
}
pub fn with_access_token(self, access_token: impl Into<String>) -> Self {
self.with_authz(Authz {
access_token: access_token.into(),
refresh_token: None,
user_id: None,
country_code: None,
expires_timestamp: None,
})
}
pub fn with_device_type(mut self, device_type: DeviceType) -> Self {
self.device_type = Some(device_type);
self
}
pub fn with_locale(mut self, locale: String) -> Self {
self.locale = Some(locale);
self
}
pub fn with_country_code(mut self, country_code: String) -> Self {
self.country_code = Some(country_code);
self
}
pub fn with_user_agent(mut self, user_agent: String) -> Self {
self.user_agent = user_agent;
self
}
pub fn with_authz_refresh_callback<F>(mut self, authz_refresh_callback: F) -> Self
where
F: Fn(Authz) + Send + Sync + 'static,
{
self.on_authz_refresh_callback = Some(Arc::new(authz_refresh_callback));
self
}
pub fn with_max_backoff_millis(mut self, max_backoff_millis: u64) -> Self {
self.max_backoff_millis = Some(max_backoff_millis);
self
}
pub fn get_country_code(&self) -> String {
match &self.country_code {
Some(country_code) => country_code.clone(),
None => match &self.get_authz() {
Some(authz) => authz.country_code.clone().unwrap_or_else(|| "US".into()),
None => "US".into(),
},
}
}
pub fn get_locale(&self) -> String {
self.locale.clone().unwrap_or_else(|| "en_US".into())
}
pub fn get_device_type(&self) -> DeviceType {
self.device_type.unwrap_or(DeviceType::Browser)
}
pub fn get_user_id(&self) -> Option<u64> {
self.get_authz().and_then(|authz| authz.user_id)
}
pub fn set_country_code(&mut self, country_code: String) {
self.country_code = Some(country_code);
}
pub fn set_locale(&mut self, locale: String) {
self.locale = Some(locale);
}
pub fn set_device_type(&mut self, device_type: DeviceType) {
self.device_type = Some(device_type);
}
pub fn set_max_backoff_millis(&mut self, max_backoff_millis: u64) {
self.max_backoff_millis = Some(max_backoff_millis);
}
pub fn get_max_backoff_millis(&self) -> u64 {
self.max_backoff_millis
.unwrap_or(DEFAULT_MAX_BACKOFF_MILLIS)
}
pub fn on_authz_refresh<F>(&mut self, f: F)
where
F: Fn(Authz) + Send + Sync + 'static,
{
self.on_authz_refresh_callback = Some(Arc::new(f));
}
pub fn get_authz(&self) -> Option<Arc<Authz>> {
self.authz.load_full()
}
fn can_renew_token(&self) -> bool {
self.get_authz().is_some_and(|authz| {
authz.token_renewal(self.client_secret.is_some()) != TokenRenewal::None
})
}
async fn refresh_authz(&self) -> Result<(), Error> {
let permit: Option<SemaphorePermit> = self.authz_update_semaphore.try_acquire().ok();
match permit {
Some(permit) => {
let authz = self.get_authz().ok_or(Error::NoAuthzToken)?;
let new_authz = match authz.token_renewal(self.client_secret.is_some()) {
TokenRenewal::RefreshToken(refresh_token) => {
let basic_auth = self
.client_secret
.as_deref()
.map(|secret| (self.client_id.as_str(), secret));
let resp: AuthzToken = self
.post_token(
&[
("client_id", self.client_id.as_str()),
("refresh_token", refresh_token.as_str()),
("grant_type", "refresh_token"),
("scope", "r_usr w_usr"),
],
basic_auth,
)
.await?;
let expires_timestamp = Some(resp.expires_timestamp());
let new_authz = Authz {
access_token: resp.access_token,
refresh_token: resp
.refresh_token
.or_else(|| authz.refresh_token.clone()),
user_id: Some(resp.user.user_id),
country_code: match &authz.country_code {
Some(country_code) => Some(country_code.clone()),
None => Some(resp.user.country_code.clone()),
},
expires_timestamp,
};
self.authz.store(Some(Arc::new(new_authz.clone())));
new_authz
}
TokenRenewal::ClientCredentials => self.client_credentials().await?,
TokenRenewal::None => return Err(Error::NoAuthzToken),
};
trace!("TIDAL API Token refreshed");
drop(permit);
if let Some(cb) = &self.on_authz_refresh_callback {
cb(new_authz);
}
Ok(())
}
None => {
let _ = self.authz_update_semaphore.acquire().await;
Ok(())
}
}
}
pub async fn device_authorization(&self) -> Result<DeviceAuthorizationResponse, Error> {
let mut resp: DeviceAuthorizationResponse = self
.post_auth_form(
crate::auth::DEVICE_AUTHORIZATION_PATH,
&[
("client_id", self.client_id.as_str()),
("scope", "r_usr w_usr"),
],
None,
)
.await?;
resp.url = format!("https://{url}", url = resp.url);
Ok(resp)
}
pub async fn authorize(
&self,
device_code: &str,
client_secret: &str,
) -> Result<AuthzToken, Error> {
let resp: AuthzToken = self
.post_token(
&[
("client_id", self.client_id.as_str()),
("client_secret", client_secret),
("device_code", device_code),
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
("scope", "r_usr w_usr"),
],
None,
)
.await?;
self.store_user_authz(&resp);
Ok(resp)
}
}
#[derive(Debug, Clone)]
pub struct ApiKey {
pub prefix: Option<String>,
pub key: String,
}
impl TidalClient {
pub async fn execute_request<T: DeserializeOwned>(
&self,
req_builder: reqwest::RequestBuilder,
) -> Result<T, Error> {
self.execute_request_with_refresh_attempts(req_builder, 0)
.await
}
#[async_recursion]
async fn execute_request_with_refresh_attempts<T>(
&self,
req_builder: reqwest::RequestBuilder,
token_refresh_attempts: u8,
) -> Result<T, Error>
where
T: DeserializeOwned,
{
self.await_rate_limit_backoff().await;
let original_req_builder = req_builder.try_clone().unwrap();
let mut req_builder = req_builder.header(reqwest::header::USER_AGENT, &self.user_agent);
if let Some(authz) = self.get_authz() {
req_builder = req_builder.header(
reqwest::header::AUTHORIZATION,
&format!("Bearer {}", authz.access_token),
);
}
let req = req_builder.try_clone().unwrap().build()?;
let method = req.method().clone();
let url = req.url().clone();
debug!("Tidal API HTTP Request - Method: {}, URL: {}", method, url);
let resp = self.client.execute(req).await?;
let etag: Option<String> = resp.headers().get("ETag").map(|etag| {
let etag = etag.to_str().expect("Invalid ETag header").to_string();
match serde_json::from_str::<String>(&etag) {
Ok(etag) => etag,
Err(_) => etag,
}
});
let status = resp.status();
let response_headers = resp.headers().clone();
info!(
"HTTP Response - Method: {}, URL: {}, Status: {}",
method, url, status
);
debug!("HTTP Response Headers: {:?}", response_headers);
let status = resp.status();
let body = resp.bytes().await?;
let mut value: serde_json::Value = if body.is_empty() {
serde_json::Value::Null
} else {
match serde_json::from_slice(&body) {
Ok(value) => value,
Err(e) => {
let error_message = String::from_utf8_lossy(&body);
if log::log_enabled!(log::Level::Warn) {
log::warn!("Requested URL: {}", url);
log::warn!("JSON deserialization error: {}", e);
log::warn!("Response: {}", error_message);
}
return Err(Error::TidalError(TidalError::UnknownError(
TidalUnknownError {
status: status.as_u16(),
message: error_message.to_string(),
},
)));
}
}
};
if status.is_success() {
self.reset_rate_limit_backoff();
if let Some(etag) = etag
&& value.get("etag").is_none()
{
value["etag"] = serde_json::Value::String(etag);
}
let resp: T = match serde_json::from_value(value.clone()) {
Ok(t) => t,
Err(e) => {
if log::log_enabled!(log::Level::Warn) {
let problem_value_pretty = serde_json::to_string_pretty(&value).unwrap();
log::warn!("Requested URL: {}", url);
log::warn!("JSON deserialization error: {}", e);
log::warn!("Response: {}", problem_value_pretty);
}
return Err(Error::TidalError(TidalError::UnknownError(
TidalUnknownError {
status: status.as_u16(),
message: e.to_string(),
},
)));
}
};
Ok(resp)
} else {
if status.as_u16() == 429 || status.as_u16() == 500 {
if self.get_max_backoff_millis() == 0 {
self.reset_rate_limit_backoff();
} else {
self.increase_rate_limit_backoff()?;
return self
.execute_request_with_refresh_attempts(
original_req_builder,
token_refresh_attempts,
)
.await;
}
} else {
self.reset_rate_limit_backoff();
}
let tidal_err = match serde_json::from_value::<TidalError>(value.clone()) {
Ok(e) => e,
Err(e) => {
if log::log_enabled!(log::Level::Warn) {
let problem_value_pretty = serde_json::to_string_pretty(&value).unwrap();
log::warn!("Requested URL: {}", url);
log::warn!("Unrecognized TIDAL error shape: {}", e);
log::warn!("Response: {}", problem_value_pretty);
}
return Err(Error::TidalError(TidalError::UnknownError(
TidalUnknownError {
status: status.as_u16(),
message: String::from_utf8_lossy(&body).into_owned(),
},
)));
}
};
if tidal_err.is_expired_token()
&& self.can_renew_token()
&& token_refresh_attempts < MAX_TOKEN_REFRESH_ATTEMPTS
{
trace!("TIDAL API Token expired, refreshing");
self.refresh_authz().await?;
return self
.execute_request_with_refresh_attempts(
original_req_builder,
token_refresh_attempts + 1,
)
.await;
}
if log::log_enabled!(log::Level::Warn) {
let pretty_err = serde_json::to_string_pretty(&tidal_err).unwrap();
log::warn!("Requested URL: {}", url);
log::warn!("TIDAL API Error: {}", pretty_err);
}
Err(Error::TidalError(tidal_err))
}
}
async fn await_rate_limit_backoff(&self) {
if self.get_max_backoff_millis() == 0 {
return;
}
let delay = {
let guard = self
.backoff
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
*guard
};
if let Some(ms) = delay
&& ms > 0
{
sleep(Duration::from_millis(ms)).await;
}
}
fn increase_rate_limit_backoff(&self) -> Result<(), Error> {
let max_backoff = self.get_max_backoff_millis();
if max_backoff == 0 {
return Ok(());
}
let mut guard = self
.backoff
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let next = match *guard {
Some(current) => current.saturating_mul(2),
None => INITIAL_BACKOFF_MILLIS,
};
if next >= max_backoff {
*guard = Some(max_backoff);
return Err(Error::RateLimitBackoffExceeded(max_backoff));
}
*guard = Some(next);
Ok(())
}
fn reset_rate_limit_backoff(&self) {
let mut guard = self
.backoff
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if guard.is_some() {
*guard = None;
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Authz {
pub access_token: String,
#[serde(default)]
pub refresh_token: Option<String>,
#[serde(default)]
pub user_id: Option<u64>,
pub country_code: Option<String>,
pub expires_timestamp: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum TokenRenewal {
RefreshToken(String),
ClientCredentials,
None,
}
impl Authz {
pub fn new(
access_token: String,
refresh_token: Option<String>,
user_id: Option<u64>,
country_code: Option<String>,
expires_timestamp: Option<u64>,
) -> Self {
Self {
access_token,
refresh_token,
user_id,
country_code,
expires_timestamp,
}
}
pub(crate) fn token_renewal(&self, has_client_secret: bool) -> TokenRenewal {
if let Some(refresh_token) = &self.refresh_token
&& !refresh_token.is_empty()
{
return TokenRenewal::RefreshToken(refresh_token.clone());
}
if has_client_secret {
return TokenRenewal::ClientCredentials;
}
TokenRenewal::None
}
}
#[derive(
Debug, Serialize, Deserialize, Default, EnumString, AsRefStr, PartialEq, Eq, Clone, Copy,
)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum DeviceType {
#[default]
Browser,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn authz_without_refresh_token_cannot_renew() {
let authz = Authz::new("tok".to_string(), None, None, None, None);
assert_eq!(authz.token_renewal(false), TokenRenewal::None);
assert_eq!(authz.token_renewal(true), TokenRenewal::ClientCredentials);
}
#[test]
fn authz_with_refresh_token_uses_refresh() {
let authz = Authz::new(
"tok".to_string(),
Some("rt".to_string()),
Some(1),
None,
None,
);
assert!(matches!(
authz.token_renewal(true),
TokenRenewal::RefreshToken(token) if token == "rt"
));
assert!(matches!(
authz.token_renewal(false),
TokenRenewal::RefreshToken(_)
));
}
#[test]
fn empty_refresh_token_falls_back_to_client_credentials() {
let authz = Authz::new("tok".to_string(), Some(String::new()), None, None, None);
assert_eq!(authz.token_renewal(false), TokenRenewal::None);
assert_eq!(authz.token_renewal(true), TokenRenewal::ClientCredentials);
}
#[test]
fn with_access_token_stores_token_only_authz() {
let client = TidalClient::new("client-id".to_string()).with_access_token("abc");
let authz = client.get_authz().expect("authz");
assert_eq!(authz.access_token, "abc");
assert_eq!(authz.refresh_token, None);
assert_eq!(authz.user_id, None);
assert!(!client.can_renew_token());
}
#[test]
fn with_client_secret_enables_client_credentials_renewal() {
let client = TidalClient::new("client-id".to_string())
.with_client_secret("secret")
.with_access_token("abc");
assert!(client.can_renew_token());
assert_eq!(
client
.get_authz()
.unwrap()
.token_renewal(client.client_secret.is_some()),
TokenRenewal::ClientCredentials
);
}
}