feat: qbz-1 streaming, gapless prefetch, accurate scrobbling, Range-seek
Port proven playback architecture from qbqt fork: - Bounded VecDeque buffer with condvar backpressure (4MB cap) - decrypt_and_extract_frames for clean FLAC frame extraction from ISOBMFF - Cancel+restart seeking with sub-segment sample skipping - start_prefetch / QueueNext for gapless transitions with pre-started downloads - track_transitioned signaling for scrobbler during gapless playback - Range-request HTTP seeking for non-segmented (MP3) tracks - OnceLock HTTP client singleton with cancel-aware chunked downloads - Accumulated listening time scrobbling (prevents false scrobbles from seeking) - Array-format Last.fm scrobble params (artist[0], track[0], etc.) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
use anyhow::{bail, Result};
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
|
||||
use cbc::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit};
|
||||
use hkdf::Hkdf;
|
||||
use reqwest::Client;
|
||||
use serde_json::Value;
|
||||
use sha2::Sha256;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::models::*;
|
||||
@@ -15,10 +19,66 @@ pub const DEFAULT_APP_SECRET: &str = "e79f8b9be485692b0e5f9dd895826368";
|
||||
pub struct QobuzClient {
|
||||
http: Client,
|
||||
pub auth_token: Option<String>,
|
||||
/// Playback session ID from POST /session/start — sent as X-Session-Id for /file/url.
|
||||
session_id: Option<String>,
|
||||
session_expires_at: Option<u64>,
|
||||
/// `infos` field from the session/start response — used to derive the KEK for track key unwrapping.
|
||||
session_infos: Option<String>,
|
||||
app_id: String,
|
||||
app_secret: String,
|
||||
}
|
||||
|
||||
// ── qbz-1 key derivation helpers ─────────────────────────────────────────────
|
||||
|
||||
type Aes128CbcDec = cbc::Decryptor<aes::Aes128>;
|
||||
|
||||
/// Decode a base64url string (with or without padding).
|
||||
fn b64url_decode(s: &str) -> Result<Vec<u8>> {
|
||||
Ok(URL_SAFE_NO_PAD.decode(s.trim_end_matches('='))?)
|
||||
}
|
||||
|
||||
/// Full qbz-1 key derivation:
|
||||
/// Phase 1: HKDF-SHA256(ikm=hex(app_secret), salt=b64url(infos[0]), info=b64url(infos[1])) → 16-byte KEK
|
||||
/// Phase 2: AES-128-CBC/NoPadding(key=KEK, iv=b64url(key_field[2])).decrypt(b64url(key_field[1]))[..16]
|
||||
fn derive_track_key(session_infos: &str, app_secret_hex: &str, key_field: &str) -> Result<[u8; 16]> {
|
||||
// Phase 1: HKDF
|
||||
let infos_parts: Vec<&str> = session_infos.splitn(2, '.').collect();
|
||||
if infos_parts.len() != 2 {
|
||||
bail!("session_infos must be '<salt_b64>.<info_b64>', got: {session_infos}");
|
||||
}
|
||||
let salt = b64url_decode(infos_parts[0])?;
|
||||
let info = b64url_decode(infos_parts[1])?;
|
||||
let ikm = hex::decode(app_secret_hex)?;
|
||||
|
||||
let hk = Hkdf::<Sha256>::new(Some(&salt), &ikm);
|
||||
let mut kek = [0u8; 16];
|
||||
hk.expand(&info, &mut kek)
|
||||
.map_err(|e| anyhow::anyhow!("HKDF expand failed: {e:?}"))?;
|
||||
|
||||
// Phase 2: AES-128-CBC/NoPadding
|
||||
let key_parts: Vec<&str> = key_field.splitn(3, '.').collect();
|
||||
if key_parts.len() != 3 || key_parts[0] != "qbz-1" {
|
||||
bail!("unexpected key field format: {key_field}");
|
||||
}
|
||||
let ct = b64url_decode(key_parts[1])?;
|
||||
let iv_bytes = b64url_decode(key_parts[2])?;
|
||||
if ct.len() < 16 || iv_bytes.len() < 16 {
|
||||
bail!("key field ciphertext/iv too short ({} / {} bytes)", ct.len(), iv_bytes.len());
|
||||
}
|
||||
|
||||
let iv: [u8; 16] = iv_bytes[..16].try_into()?;
|
||||
let mut buf = ct;
|
||||
let decrypted = Aes128CbcDec::new(&kek.into(), &iv.into())
|
||||
.decrypt_padded_mut::<NoPadding>(&mut buf)
|
||||
.map_err(|e| anyhow::anyhow!("AES-CBC decrypt failed: {e:?}"))?;
|
||||
|
||||
let mut track_key = [0u8; 16];
|
||||
track_key.copy_from_slice(&decrypted[..16]);
|
||||
Ok(track_key)
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
impl QobuzClient {
|
||||
pub fn new() -> Result<Self> {
|
||||
Self::new_with_config(None, None)
|
||||
@@ -44,6 +104,9 @@ impl QobuzClient {
|
||||
Ok(Self {
|
||||
http,
|
||||
auth_token: None,
|
||||
session_id: None,
|
||||
session_expires_at: None,
|
||||
session_infos: None,
|
||||
app_id,
|
||||
app_secret,
|
||||
})
|
||||
@@ -106,20 +169,16 @@ impl QobuzClient {
|
||||
if let Some(token) = &self.auth_token {
|
||||
builder = builder.header("Authorization", format!("Bearer {}", token));
|
||||
}
|
||||
if let Some(sid) = &self.session_id {
|
||||
builder = builder.header("X-Session-Id", sid.as_str());
|
||||
}
|
||||
builder
|
||||
}
|
||||
|
||||
// --- Auth ---
|
||||
|
||||
pub async fn login(&mut self, email: &str, password: &str) -> Result<OAuthLoginResponse> {
|
||||
match self.oauth2_login(email, password).await {
|
||||
Ok(r) => Ok(r),
|
||||
Err(_) => self.legacy_login(email, password).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// NOTE: Qobuz API requires credentials as GET query params — not our choice.
|
||||
async fn oauth2_login(&mut self, email: &str, password: &str) -> Result<OAuthLoginResponse> {
|
||||
pub async fn login(&mut self, email: &str, password: &str) -> Result<OAuthLoginResponse> {
|
||||
let ts = Self::ts();
|
||||
let mut sign_params: Vec<(&str, String)> = vec![
|
||||
("password", password.to_string()),
|
||||
@@ -144,44 +203,14 @@ impl QobuzClient {
|
||||
let body: Value = resp.json().await?;
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|m| m.as_str()).unwrap_or("login failed");
|
||||
bail!("oauth2 login failed ({}): {}", status, msg);
|
||||
}
|
||||
|
||||
self.extract_and_store_token(serde_json::from_value(body)?)
|
||||
}
|
||||
|
||||
async fn legacy_login(&mut self, email: &str, password: &str) -> Result<OAuthLoginResponse> {
|
||||
let ts = Self::ts();
|
||||
let mut sign_params: Vec<(&str, String)> = vec![
|
||||
("email", email.to_string()),
|
||||
("password", password.to_string()),
|
||||
];
|
||||
let sig = self.request_sig("userlogin", &mut sign_params, ts);
|
||||
|
||||
let resp = self
|
||||
.http
|
||||
.get(self.url("user/login"))
|
||||
.query(&[
|
||||
("app_id", self.app_id.as_str()),
|
||||
("email", email),
|
||||
("password", password),
|
||||
("request_ts", ts.to_string().as_str()),
|
||||
("request_sig", sig.as_str()),
|
||||
])
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: Value = resp.json().await?;
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|m| m.as_str()).unwrap_or("login failed");
|
||||
bail!("user login failed ({}): {}", status, msg);
|
||||
bail!("login failed ({}): {}", status, msg);
|
||||
}
|
||||
|
||||
self.extract_and_store_token(serde_json::from_value(body)?)
|
||||
}
|
||||
|
||||
fn extract_and_store_token(&mut self, login: OAuthLoginResponse) -> Result<OAuthLoginResponse> {
|
||||
// auth_token = OAuth2 bearer (preferred) or legacy session token
|
||||
if let Some(token) = login
|
||||
.oauth2
|
||||
.as_ref()
|
||||
@@ -190,9 +219,57 @@ impl QobuzClient {
|
||||
{
|
||||
self.auth_token = Some(token);
|
||||
}
|
||||
// Reset any cached playback session — it belongs to a different auth context.
|
||||
self.session_id = None;
|
||||
self.session_expires_at = None;
|
||||
self.session_infos = None;
|
||||
Ok(login)
|
||||
}
|
||||
|
||||
/// Start a playback session via POST /session/start.
|
||||
/// The returned session_id is required as X-Session-Id when calling /file/url.
|
||||
/// Sessions expire; we cache and reuse until 60s before expiry.
|
||||
async fn ensure_session(&mut self) -> Result<()> {
|
||||
let now = Self::ts();
|
||||
if let (Some(_), Some(exp)) = (&self.session_id, self.session_expires_at) {
|
||||
if now + 60 < exp {
|
||||
return Ok(()); // still valid
|
||||
}
|
||||
}
|
||||
|
||||
let ts = Self::ts();
|
||||
let mut sign_params: Vec<(&str, String)> = vec![
|
||||
("profile", "qbz-1".to_string()),
|
||||
];
|
||||
let sig = self.request_sig("sessionstart", &mut sign_params, ts);
|
||||
|
||||
let resp = self
|
||||
.http
|
||||
.post(self.url("session/start"))
|
||||
.query(&[
|
||||
("app_id", self.app_id.as_str()),
|
||||
("request_ts", ts.to_string().as_str()),
|
||||
("request_sig", sig.as_str()),
|
||||
])
|
||||
.header("Authorization", format!("Bearer {}", self.auth_token.as_deref().unwrap_or("")))
|
||||
.form(&[("profile", "qbz-1")])
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let body = Self::check_response(resp).await?;
|
||||
let session_id = body["session_id"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("session/start: no session_id in response"))?
|
||||
.to_string();
|
||||
let expires_at = body["expires_at"].as_u64().unwrap_or(now + 3600);
|
||||
let infos = body["infos"].as_str().map(|s| s.to_string());
|
||||
eprintln!("[session] started session_id={}... expires_at={} infos={:?}", &session_id[..session_id.len().min(8)], expires_at, infos);
|
||||
self.session_id = Some(session_id);
|
||||
self.session_expires_at = Some(expires_at);
|
||||
self.session_infos = infos;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// --- User ---
|
||||
|
||||
pub async fn get_user(&self) -> Result<UserDto> {
|
||||
@@ -215,7 +292,9 @@ impl QobuzClient {
|
||||
Ok(serde_json::from_value(body)?)
|
||||
}
|
||||
|
||||
pub async fn get_track_url(&self, track_id: i64, format: Format) -> Result<TrackFileUrlDto> {
|
||||
pub async fn get_track_url(&mut self, track_id: i64, format: Format) -> Result<TrackFileUrlDto> {
|
||||
self.ensure_session().await?;
|
||||
|
||||
let ts = Self::ts();
|
||||
let intent = "stream";
|
||||
let mut sign_params: Vec<(&str, String)> = vec![
|
||||
@@ -223,10 +302,10 @@ impl QobuzClient {
|
||||
("intent", intent.to_string()),
|
||||
("track_id", track_id.to_string()),
|
||||
];
|
||||
let sig = self.request_sig("trackgetFileUrl", &mut sign_params, ts);
|
||||
let sig = self.request_sig("fileurl", &mut sign_params, ts);
|
||||
|
||||
let resp = self
|
||||
.get_request("track/getFileUrl")
|
||||
.get_request("file/url")
|
||||
.query(&[
|
||||
("track_id", track_id.to_string()),
|
||||
("format_id", format.id().to_string()),
|
||||
@@ -238,7 +317,24 @@ impl QobuzClient {
|
||||
.await?;
|
||||
|
||||
let body = Self::check_response(resp).await?;
|
||||
Ok(serde_json::from_value(body)?)
|
||||
eprintln!("[file/url] response: {}", serde_json::to_string(&body).unwrap_or_default());
|
||||
let mut url_dto: TrackFileUrlDto = serde_json::from_value(body)?;
|
||||
|
||||
// Unwrap the per-track key: decrypt the CBC-wrapped key using HKDF-derived KEK.
|
||||
if let (Some(key_field), Some(infos)) = (url_dto.key.clone(), self.session_infos.as_deref()) {
|
||||
match derive_track_key(infos, &self.app_secret, &key_field) {
|
||||
Ok(track_key) => {
|
||||
url_dto.key = Some(hex::encode(track_key));
|
||||
eprintln!("[key] track key unwrapped OK");
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[key] track key unwrap failed: {e}");
|
||||
url_dto.key = None; // disable decryption rather than play garbage
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(url_dto)
|
||||
}
|
||||
|
||||
// --- Album ---
|
||||
@@ -289,17 +385,48 @@ impl QobuzClient {
|
||||
// --- Search ---
|
||||
|
||||
pub async fn search(&self, query: &str, offset: u32, limit: u32) -> Result<SearchCatalogDto> {
|
||||
let (tracks, albums, artists) = tokio::try_join!(
|
||||
self.search_tracks(query, offset, limit),
|
||||
self.search_albums(query, offset, limit),
|
||||
self.search_artists(query, offset, limit),
|
||||
)?;
|
||||
Ok(SearchCatalogDto {
|
||||
query: Some(query.to_string()),
|
||||
albums: Some(albums),
|
||||
tracks: Some(tracks),
|
||||
artists: Some(artists),
|
||||
playlists: None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn search_tracks(&self, query: &str, offset: u32, limit: u32) -> Result<SearchResultItems<TrackDto>> {
|
||||
let resp = self
|
||||
.get_request("catalog/search")
|
||||
.query(&[
|
||||
("query", query),
|
||||
("offset", &offset.to_string()),
|
||||
("limit", &limit.to_string()),
|
||||
])
|
||||
.get_request("track/search")
|
||||
.query(&[("query", query), ("offset", &offset.to_string()), ("limit", &limit.to_string())])
|
||||
.send()
|
||||
.await?;
|
||||
let body = Self::check_response(resp).await?;
|
||||
Ok(serde_json::from_value(body)?)
|
||||
Ok(serde_json::from_value(body["tracks"].clone())?)
|
||||
}
|
||||
|
||||
async fn search_albums(&self, query: &str, offset: u32, limit: u32) -> Result<SearchResultItems<AlbumDto>> {
|
||||
let resp = self
|
||||
.get_request("album/search")
|
||||
.query(&[("query", query), ("offset", &offset.to_string()), ("limit", &limit.to_string())])
|
||||
.send()
|
||||
.await?;
|
||||
let body = Self::check_response(resp).await?;
|
||||
Ok(serde_json::from_value(body["albums"].clone())?)
|
||||
}
|
||||
|
||||
async fn search_artists(&self, query: &str, offset: u32, limit: u32) -> Result<SearchResultItems<ArtistDto>> {
|
||||
let resp = self
|
||||
.get_request("artist/search")
|
||||
.query(&[("query", query), ("offset", &offset.to_string()), ("limit", &limit.to_string())])
|
||||
.send()
|
||||
.await?;
|
||||
let body = Self::check_response(resp).await?;
|
||||
Ok(serde_json::from_value(body["artists"].clone())?)
|
||||
}
|
||||
|
||||
// --- Favorites / Library ---
|
||||
@@ -329,34 +456,103 @@ impl QobuzClient {
|
||||
Ok(serde_json::from_value(body)?)
|
||||
}
|
||||
|
||||
pub async fn get_fav_tracks(&self, offset: u32, limit: u32) -> Result<SearchResultItems<TrackDto>> {
|
||||
/// Fetch all favorite IDs (tracks, albums, artists) in one call.
|
||||
async fn get_fav_ids(&self) -> Result<FavIdsDto> {
|
||||
let resp = self
|
||||
.get_request("favorite/getUserFavorites")
|
||||
.query(&[("type", "tracks"), ("offset", &offset.to_string()), ("limit", &limit.to_string())])
|
||||
.get_request("favorite/getUserFavoriteIds")
|
||||
.send()
|
||||
.await?;
|
||||
let body = Self::check_response(resp).await?;
|
||||
Ok(serde_json::from_value(body["tracks"].clone())?)
|
||||
Ok(serde_json::from_value(body)?)
|
||||
}
|
||||
|
||||
/// Batch-fetch tracks by ID via POST /track/getList.
|
||||
async fn get_tracks_by_ids(&self, ids: &[i64]) -> Result<Vec<TrackDto>> {
|
||||
if ids.is_empty() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let resp = self
|
||||
.post_request("track/getList")
|
||||
.json(&serde_json::json!({ "tracks_id": ids }))
|
||||
.send()
|
||||
.await?;
|
||||
let body = Self::check_response(resp).await?;
|
||||
let items: Vec<TrackDto> = serde_json::from_value(
|
||||
body["tracks"]["items"].clone(),
|
||||
)
|
||||
.unwrap_or_default();
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
pub async fn get_fav_tracks(&self, offset: u32, limit: u32) -> Result<SearchResultItems<TrackDto>> {
|
||||
let ids = self.get_fav_ids().await?;
|
||||
let all_ids = ids.tracks.unwrap_or_default();
|
||||
let total = all_ids.len() as i32;
|
||||
let page: Vec<i64> = all_ids
|
||||
.into_iter()
|
||||
.skip(offset as usize)
|
||||
.take(limit as usize)
|
||||
.collect();
|
||||
let items = self.get_tracks_by_ids(&page).await?;
|
||||
Ok(SearchResultItems {
|
||||
items: Some(items),
|
||||
total: Some(total),
|
||||
offset: Some(offset as i32),
|
||||
limit: Some(limit as i32),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn get_fav_albums(&self, offset: u32, limit: u32) -> Result<SearchResultItems<AlbumDto>> {
|
||||
let resp = self
|
||||
.get_request("favorite/getUserFavorites")
|
||||
.query(&[("type", "albums"), ("offset", &offset.to_string()), ("limit", &limit.to_string())])
|
||||
.send()
|
||||
.await?;
|
||||
let body = Self::check_response(resp).await?;
|
||||
Ok(serde_json::from_value(body["albums"].clone())?)
|
||||
let ids = self.get_fav_ids().await?;
|
||||
let all_ids = ids.albums.unwrap_or_default();
|
||||
let total = all_ids.len() as i32;
|
||||
let page: Vec<&str> = all_ids
|
||||
.iter()
|
||||
.skip(offset as usize)
|
||||
.take(limit as usize)
|
||||
.map(|s| s.as_str())
|
||||
.collect();
|
||||
let mut items = Vec::with_capacity(page.len());
|
||||
for album_id in page {
|
||||
match self.get_album(album_id).await {
|
||||
Ok(a) => items.push(a),
|
||||
Err(e) => eprintln!("[fav] failed to fetch album {}: {}", album_id, e),
|
||||
}
|
||||
}
|
||||
Ok(SearchResultItems {
|
||||
items: Some(items),
|
||||
total: Some(total),
|
||||
offset: Some(offset as i32),
|
||||
limit: Some(limit as i32),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn get_fav_artists(&self, offset: u32, limit: u32) -> Result<SearchResultItems<FavArtistDto>> {
|
||||
let resp = self
|
||||
.get_request("favorite/getUserFavorites")
|
||||
.query(&[("type", "artists"), ("offset", &offset.to_string()), ("limit", &limit.to_string())])
|
||||
.send()
|
||||
.await?;
|
||||
let body = Self::check_response(resp).await?;
|
||||
Ok(serde_json::from_value(body["artists"].clone())?)
|
||||
let ids = self.get_fav_ids().await?;
|
||||
let all_ids = ids.artists.unwrap_or_default();
|
||||
let total = all_ids.len() as i32;
|
||||
let page: Vec<i64> = all_ids
|
||||
.into_iter()
|
||||
.skip(offset as usize)
|
||||
.take(limit as usize)
|
||||
.collect();
|
||||
let mut items = Vec::with_capacity(page.len());
|
||||
for artist_id in page {
|
||||
match self.get_artist_page(artist_id).await {
|
||||
Ok(v) => {
|
||||
if let Ok(a) = serde_json::from_value::<FavArtistDto>(v) {
|
||||
items.push(a);
|
||||
}
|
||||
}
|
||||
Err(e) => eprintln!("[fav] failed to fetch artist {}: {}", artist_id, e),
|
||||
}
|
||||
}
|
||||
Ok(SearchResultItems {
|
||||
items: Some(items),
|
||||
total: Some(total),
|
||||
offset: Some(offset as i32),
|
||||
limit: Some(limit as i32),
|
||||
})
|
||||
}
|
||||
|
||||
// --- Playlist management ---
|
||||
|
||||
Reference in New Issue
Block a user