refactor: resync with qbqt baseline and restore genre browser
Some checks failed
Build for Windows / build-windows (push) Has been cancelled

This commit is contained in:
joren
2026-03-30 22:36:39 +02:00
parent 200ef39d04
commit 3346b424b3
26 changed files with 8533 additions and 446 deletions

View File

@@ -40,7 +40,11 @@ fn b64url_decode(s: &str) -> Result<Vec<u8>> {
/// 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]> {
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 {
@@ -63,7 +67,11 @@ fn derive_track_key(session_infos: &str, app_secret_hex: &str, key_field: &str)
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());
bail!(
"key field ciphertext/iv too short ({} / {} bytes)",
ct.len(),
iv_bytes.len()
);
}
let iv: [u8; 16] = iv_bytes[..16].try_into()?;
@@ -202,7 +210,10 @@ impl QobuzClient {
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");
let msg = body
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("login failed");
bail!("login failed ({}): {}", status, msg);
}
@@ -238,9 +249,7 @@ impl QobuzClient {
}
let ts = Self::ts();
let mut sign_params: Vec<(&str, String)> = vec![
("profile", "qbz-1".to_string()),
];
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
@@ -251,7 +260,10 @@ impl QobuzClient {
("request_ts", ts.to_string().as_str()),
("request_sig", sig.as_str()),
])
.header("Authorization", format!("Bearer {}", self.auth_token.as_deref().unwrap_or("")))
.header(
"Authorization",
format!("Bearer {}", self.auth_token.as_deref().unwrap_or("")),
)
.form(&[("profile", "qbz-1")])
.send()
.await?;
@@ -263,7 +275,12 @@ impl QobuzClient {
.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);
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;
@@ -292,7 +309,11 @@ impl QobuzClient {
Ok(serde_json::from_value(body)?)
}
pub async fn get_track_url(&mut 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();
@@ -317,11 +338,15 @@ impl QobuzClient {
.await?;
let body = Self::check_response(resp).await?;
eprintln!("[file/url] response: {}", serde_json::to_string(&body).unwrap_or_default());
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()) {
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));
@@ -370,12 +395,39 @@ impl QobuzClient {
let resp = self
.get_request("artist/getReleasesList")
.query(&[
("artist_id", artist_id.to_string()),
("artist_id", artist_id.to_string()),
("release_type", release_type.to_string()),
("sort", "release_date".to_string()),
("order", "desc".to_string()),
("limit", limit.to_string()),
("offset", offset.to_string()),
("sort", "release_date".to_string()),
("order", "desc".to_string()),
("limit", limit.to_string()),
("offset", offset.to_string()),
])
.send()
.await?;
Self::check_response(resp).await
}
// --- Browse ---
pub async fn get_genres(&self) -> Result<Value> {
let resp = self.get_request("genre/list").send().await?;
Self::check_response(resp).await
}
pub async fn get_featured_albums(
&self,
genre_id: i64,
kind: &str,
limit: u32,
offset: u32,
) -> Result<Value> {
let resp = self
.get_request("album/getFeatured")
.query(&[
("type", kind.to_string()),
("genre_id", genre_id.to_string()),
("limit", limit.to_string()),
("offset", offset.to_string()),
])
.send()
.await?;
@@ -384,54 +436,74 @@ impl QobuzClient {
// --- Search ---
pub async fn most_popular_search(&self, query: &str, limit: u32) -> Result<serde_json::Value> {
let resp = self
.get_request("most-popular/get")
.query(&[("query", query), ("offset", "0"), ("limit", &limit.to_string())])
.send()
.await?;
Self::check_response(resp).await
}
pub async fn search(&self, query: &str, offset: u32, limit: u32) -> Result<SearchCatalogDto> {
let (tracks, albums, artists) = tokio::try_join!(
let (tracks_res, albums_res, artists_res) = tokio::join!(
self.search_tracks(query, offset, limit),
self.search_albums(query, offset, limit),
self.search_artists(query, offset, limit),
)?;
);
// Convert successful Results into Some(value) and Errors into None
Ok(SearchCatalogDto {
query: Some(query.to_string()),
albums: Some(albums),
tracks: Some(tracks),
artists: Some(artists),
tracks: tracks_res.ok(),
albums: albums_res.ok(),
artists: artists_res.ok(),
playlists: None,
})
}
async fn search_tracks(&self, query: &str, offset: u32, limit: u32) -> Result<SearchResultItems<TrackDto>> {
async fn search_tracks(
&self,
query: &str,
offset: u32,
limit: u32,
) -> Result<SearchResultItems<TrackDto>> {
let resp = self
.get_request("track/search")
.query(&[("query", query), ("offset", &offset.to_string()), ("limit", &limit.to_string())])
.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["tracks"].clone())?)
}
async fn search_albums(&self, query: &str, offset: u32, limit: u32) -> Result<SearchResultItems<AlbumDto>> {
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())])
.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>> {
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())])
.query(&[
("query", query),
("offset", &offset.to_string()),
("limit", &limit.to_string()),
])
.send()
.await?;
let body = Self::check_response(resp).await?;
@@ -443,14 +515,22 @@ impl QobuzClient {
pub async fn get_user_playlists(&self, offset: u32, limit: u32) -> Result<UserPlaylistsDto> {
let resp = self
.get_request("playlist/getUserPlaylists")
.query(&[("offset", &offset.to_string()), ("limit", &limit.to_string())])
.query(&[
("offset", &offset.to_string()),
("limit", &limit.to_string()),
])
.send()
.await?;
let body = Self::check_response(resp).await?;
Ok(serde_json::from_value(body)?)
}
pub async fn get_playlist(&self, playlist_id: i64, offset: u32, limit: u32) -> Result<PlaylistDto> {
pub async fn get_playlist(
&self,
playlist_id: i64,
offset: u32,
limit: u32,
) -> Result<PlaylistDto> {
let resp = self
.get_request("playlist/get")
.query(&[
@@ -486,14 +566,16 @@ impl QobuzClient {
.send()
.await?;
let body = Self::check_response(resp).await?;
let items: Vec<TrackDto> = serde_json::from_value(
body["tracks"]["items"].clone(),
)
.unwrap_or_default();
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>> {
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;
@@ -511,7 +593,11 @@ impl QobuzClient {
})
}
pub async fn get_fav_albums(&self, offset: u32, limit: u32) -> Result<SearchResultItems<AlbumDto>> {
pub async fn get_fav_albums(
&self,
offset: u32,
limit: u32,
) -> Result<SearchResultItems<AlbumDto>> {
let ids = self.get_fav_ids().await?;
let all_ids = ids.albums.unwrap_or_default();
let total = all_ids.len() as i32;
@@ -536,7 +622,11 @@ impl QobuzClient {
})
}
pub async fn get_fav_artists(&self, offset: u32, limit: u32) -> Result<SearchResultItems<FavArtistDto>> {
pub async fn get_fav_artists(
&self,
offset: u32,
limit: u32,
) -> Result<SearchResultItems<FavArtistDto>> {
let ids = self.get_fav_ids().await?;
let all_ids = ids.artists.unwrap_or_default();
let total = all_ids.len() as i32;
@@ -549,8 +639,40 @@ impl QobuzClient {
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);
let id = v.get("id").and_then(|i| i.as_i64());
let name = v
.get("name")
.and_then(|n| n.get("display"))
.and_then(|d| d.as_str())
.map(|s| s.to_string());
let mut image_dto = None;
if let Some(imgs) = v.get("images") {
if let Some(portrait) = imgs.get("portrait") {
if let (Some(hash), Some(format)) = (
portrait.get("hash").and_then(|h| h.as_str()),
portrait.get("format").and_then(|f| f.as_str()),
) {
image_dto = Some(ImageDto {
small: Some(format!("https://static.qobuz.com/images/artists/covers/small/{}.{}", hash, format)),
thumbnail: Some(format!("https://static.qobuz.com/images/artists/covers/small/{}.{}", hash, format)),
large: Some(format!("https://static.qobuz.com/images/artists/covers/large/{}.{}", hash, format)),
back: None,
});
}
}
}
if id.is_some() && name.is_some() {
items.push(FavArtistDto {
id,
name,
albums_count: v
.get("albums_count")
.and_then(|c| c.as_i64())
.map(|c| c as i32),
image: image_dto,
});
}
}
Err(e) => eprintln!("[fav] failed to fetch artist {}: {}", artist_id, e),
@@ -569,7 +691,11 @@ impl QobuzClient {
pub async fn create_playlist(&self, name: &str) -> Result<PlaylistDto> {
let resp = self
.post_request("playlist/create")
.form(&[("name", name), ("is_public", "false"), ("is_collaborative", "false")])
.form(&[
("name", name),
("is_public", "false"),
("is_collaborative", "false"),
])
.send()
.await?;
let body = Self::check_response(resp).await?;
@@ -581,7 +707,7 @@ impl QobuzClient {
.post_request("playlist/addTracks")
.form(&[
("playlist_id", playlist_id.to_string()),
("track_ids", track_id.to_string()),
("track_ids", track_id.to_string()),
("no_duplicate", "true".to_string()),
])
.send()
@@ -600,11 +726,15 @@ impl QobuzClient {
Ok(())
}
pub async fn delete_track_from_playlist(&self, playlist_id: i64, playlist_track_id: i64) -> Result<()> {
pub async fn delete_track_from_playlist(
&self,
playlist_id: i64,
playlist_track_id: i64,
) -> Result<()> {
let resp = self
.post_request("playlist/deleteTracks")
.form(&[
("playlist_id", playlist_id.to_string()),
("playlist_id", playlist_id.to_string()),
("playlist_track_ids", playlist_track_id.to_string()),
])
.send()