feat(qbz-qt): close the two declared debts on the album and artist pages

The Last.fm similar-albums row exists now. The recommendation building was
already frontend-agnostic in qbz-external-reco, so this only adapts QbzCore to
its catalog trait and publishes the result; the row seeds on the album's artist
and excludes what the two Qobuz rows already show, including ids the
pre-resolution dedup misses. Resolved rows cache per album for thirty days in
the same store the Discover tab uses, so re-opening an album makes no Last.fm
or Qobuz calls, and only a non-empty result is cached — a transient failure
must not hide the row until restart. With Last.fm not connected it resolves to
nothing and makes no network call, so the rail simply never appears.

Relationship rows navigate. They carry a name rather than a catalog id, so the
click resolves through MusicBrainz first and only a CONFIRMED match opens an
artist — landing the user on a same-name musician is worse than a row that does
nothing. The role travels with the name so a match in another role is not
mistaken for this one.

cc
This commit is contained in:
vicrodh committed 2026-07-28 16:45:45 -06:00
1 parent 960715c4ac
commit d76f694781
8 files changed
+282 -5

No files matched your search

+2
View File
@@ -6612,6 +6612,7 @@ dependencies = [
name = "qbz-qt"
version = "2.0.2"
dependencies = [
"async-trait",
"cxx",
"cxx-qt",
"cxx-qt-build",
@@ -6625,6 +6626,7 @@ dependencies = [
"qbz-cache",
"qbz-core",
"qbz-credentials",
"qbz-external-reco",
"qbz-i18n",
"qbz-integrations",
"qbz-library",
+3
View File
@@ -40,6 +40,9 @@ qbz-i18n = { path = "../qbz-i18n" }
qbz-log = { path = "../qbz-log" }
qbz-theme = { path = "../qbz-theme" }
qbz-integrations = { path = "../qbz-integrations" }
# Last.fm "similar albums" row on the album page (external_reco_qt.rs).
qbz-external-reco = { path = "../qbz-external-reco" }
async-trait = "0.1"
rusqlite = { version = "0.31", features = ["bundled"] }
image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }
+15
View File
@@ -86,6 +86,10 @@ Rectangle {
for (var i = 0; i < more.length; i++) if (more[i].artUrl) urls.push(more[i].artUrl)
var sug = album.suggestions || []
for (i = 0; i < sug.length; i++) if (sug[i].artUrl) urls.push(sug[i].artUrl)
// The Last.fm row's covers ride the same dispatch — without this its
// cards would render as empty frames.
var sim = album.similarAlbums || []
for (i = 0; i < sim.length; i++) if (sim[i].artUrl) urls.push(sim[i].artUrl)
if (urls.length > 0) QbzShell.sidebarArtworkWindow(JSON.stringify(urls))
}
@@ -731,6 +735,17 @@ Rectangle {
items: album.suggestions || []
coverMap: root.coverMap
}
// Last.fm row. Absent — not empty — when Last.fm is not connected:
// external_reco_qt returns nothing and makes no network call, so the
// rail simply never becomes visible. Reuses the same delegate as the
// two Qobuz rows rather than a fourth card variant.
Item { visible: (album.similarAlbums || []).length > 0; width: 1; height: 40 }
SectionRail {
visible: (album.similarAlbums || []).length > 0
title: QbzSession.tr("Similar albums", QbzSession.trRev)
items: album.similarAlbums || []
coverMap: root.coverMap
}
}
}
+14 -5
View File
@@ -554,6 +554,10 @@ Rectangle {
property string title: ""
property var rows: []
property string iconName: "user"
/// The MusicBrainz role this group represents ("member", "producer",
/// …) — passed to the resolver so a same-name match in another role is
/// not treated as this musician.
property string roleKey: ""
property bool expanded: false
signal toggled()
visible: rows.length > 0
@@ -574,11 +578,13 @@ Rectangle {
label: modelData.name
tooltip: modelData.tooltip
iconName: relGroup.iconName
// POC-NOTE: the Slint row resolves the musician through
// MusicBrainz and lands on the Qobuz artist (or its
// MusicianPageView). Neither exists here, so the row is
// informational — see GLUE in the handoff report.
navigable: false
// Relationship rows carry a NAME, not a catalog id, so the
// click resolves through MusicBrainz first. Only a confirmed
// match navigates (resolve_musician logs and stays put
// otherwise) — landing the user on a same-name artist is worse
// than the row doing nothing.
navigable: true
onClicked: QbzArtist.resolveMusician(modelData.name, relGroup.roleKey || "")
}
}
Text {
@@ -1561,6 +1567,7 @@ Rectangle {
&& (mbRelationships.members || []).length > 0
title: QbzSession.tr("Members & Former", QbzSession.trRev)
rows: mbRelationships.members || []
roleKey: "member"
iconName: "user"
expanded: root.membersExpanded
onToggled: root.membersExpanded = !root.membersExpanded
@@ -1570,6 +1577,7 @@ Rectangle {
&& (mbRelationships.groups || []).length > 0
title: QbzSession.tr("Member Of", QbzSession.trRev)
rows: mbRelationships.groups || []
roleKey: "member of"
iconName: "music"
expanded: root.groupsExpanded
onToggled: root.groupsExpanded = !root.groupsExpanded
@@ -1579,6 +1587,7 @@ Rectangle {
&& (mbRelationships.collaborators || []).length > 0
title: QbzSession.tr("Collaborators", QbzSession.trRev)
rows: mbRelationships.collaborators || []
roleKey: "collaborator"
iconName: "user"
expanded: root.collabsExpanded
onToggled: root.collabsExpanded = !root.collabsExpanded
+46
View File
@@ -126,6 +126,10 @@ pub struct AlbumViewData {
#[serde(rename = "moreFromArtist")]
pub more_from_artist: Vec<AlbumCardData>,
pub suggestions: Vec<AlbumCardData>,
/// Last.fm "similar albums" — empty (and silent) unless the user connected
/// Last.fm. See external_reco_qt.rs.
#[serde(rename = "similarAlbums")]
pub similar_albums: Vec<AlbumCardData>,
}
fn mmss(secs: u32) -> String {
@@ -504,6 +508,22 @@ pub async fn load_more_from_artist(
.collect()
}
/// One Last.fm recommendation as the card shape the two Qobuz rows already use,
/// so the third row reuses their delegate instead of a fourth card variant.
fn reco_to_card(r: qbz_external_reco::AlbumReco) -> AlbumCardData {
AlbumCardData {
id: r.qobuz_album_id,
title: r.title,
artist: r.artist,
artist_id: r.artist_id,
genre: String::new(),
year: r.year,
quality_tier: r.quality_tier,
quality_detail: r.quality_label,
art_url: r.artwork_url,
}
}
/// "Listening suggestions" — /album/suggest, minus the open album.
pub async fn load_suggestions(
runtime: &Arc<AppRuntime<LoggingAdapter>>,
@@ -566,6 +586,32 @@ pub async fn load_album_view(
);
data.more_from_artist = more;
data.suggestions = suggestions;
// Last.fm row: seeded on the album's artist, excluding what the two Qobuz
// rows already show. A no-op with Last.fm disconnected — no network call.
let exclude_pairs: Vec<(String, String)> = data
.more_from_artist
.iter()
.chain(data.suggestions.iter())
.map(|c| (c.artist.to_lowercase(), c.title.to_lowercase()))
.collect();
let exclude_ids: std::collections::HashSet<String> = data
.more_from_artist
.iter()
.chain(data.suggestions.iter())
.map(|c| c.id.clone())
.chain(std::iter::once(album_id.to_string()))
.collect();
data.similar_albums = crate::external_reco_qt::similar_albums(
runtime,
album_id,
&data.header.artist,
&exclude_pairs,
&exclude_ids,
)
.await
.into_iter()
.map(reco_to_card)
.collect();
let json = serde_json::to_string(&data).map_err(|e| e.to_string())?;
log::info!(
"[qbz-qt][perf] album load: {:?} ({} tracks, {} more, {} suggestions)",
+8
View File
@@ -52,6 +52,10 @@ pub mod qbz_artist_bridge {
/// Open the artist detail view (pushes "artist" on the nav stack).
#[qinvokable]
fn open_artist(self: Pin<&mut QbzArtist>, artist_id: QString);
/// Artist-network / relationship row: resolve a musician NAME (they
/// carry no catalog id) and open their artist page when confident.
#[qinvokable]
fn resolve_musician(self: Pin<&mut QbzArtist>, name: QString, role: QString);
/// ArtistView per-section "Load more" — the next releases page.
#[qinvokable]
@@ -110,4 +114,8 @@ impl qbz_artist_bridge::QbzArtist {
pub fn load_release_section(self: Pin<&mut Self>, artist_id: QString, release_type: QString, offset: i32) {
crate::load_release_section(artist_id.to_string(), release_type.to_string(), offset);
}
pub fn resolve_musician(self: Pin<&mut Self>, name: QString, role: QString) {
crate::resolve_musician(name.to_string(), role.to_string());
}
}
+175
View File
@@ -0,0 +1,175 @@
//! Last.fm "similar albums" row on the album page.
//!
//! Port of `qbz/src/external_reco.rs` (`CoreRecoCatalog` +
//! `load_similar_albums_seeded`). The recommendation building itself lives in
//! `qbz-external-reco` and is frontend-agnostic (ADR-006); this module only
//! adapts `QbzCore` to its `RecoCatalog` trait and publishes the result.
//!
//! Strictly opt-in: with Last.fm not connected the row resolves to nothing and
//! NO network call is made. The resolved row is cached per album for 30 days in
//! the same `RecoCache` the Discover tab uses, so re-opening an album costs
//! zero Last.fm and zero Qobuz traffic. Only a NON-EMPTY result is cached — a
//! transient Last.fm failure must not hide the row until the app restarts.
use std::collections::HashSet;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
use async_trait::async_trait;
use qbz_app::shell::AppRuntime;
use qbz_core::LoggingAdapter;
use qbz_external_reco::{
build_similar_albums_seeded, AlbumReco, LastFmHandle, LocalHistory, RecoCache, RecoCatalog,
RecoInputs,
};
use qbz_integrations::lastfm::LastFmClient;
use qbz_integrations::musicbrainz::MusicBrainzClient;
use qbz_models::{Album, Artist, Track};
/// Same 30-day TTL as the Slint side.
const LASTFM_SIMILAR_TTL_SECS: i64 = 30 * 24 * 60 * 60;
static CACHE_DIR: OnceLock<Option<std::path::PathBuf>> = OnceLock::new();
fn cache_dir() -> Option<std::path::PathBuf> {
CACHE_DIR
.get_or_init(|| dirs::cache_dir().map(|d| d.join("qbz")))
.clone()
}
/// The daily rotation seed, so the row varies day to day but is stable within
/// one day (matching the Slint `rotation_seed`).
fn rotation_seed() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() / 86_400)
.unwrap_or(0)
}
// ── RecoCatalog over QbzCore (errors -> empty) ──────────────────────────────
struct CoreRecoCatalog {
runtime: Arc<AppRuntime<LoggingAdapter>>,
}
#[async_trait]
impl RecoCatalog for CoreRecoCatalog {
async fn search_tracks(&self, query: &str, limit: usize) -> Vec<Track> {
self.runtime
.core()
.search_tracks(query, limit as u32, 0, None)
.await
.map(|p| p.items)
.unwrap_or_default()
}
async fn search_artists(&self, query: &str, limit: usize) -> Vec<Artist> {
self.runtime
.core()
.search_artists(query, limit as u32, 0, None)
.await
.map(|p| p.items)
.unwrap_or_default()
}
async fn search_albums(&self, query: &str, limit: usize) -> Vec<Album> {
self.runtime
.core()
.search_albums(query, limit as u32, 0, None)
.await
.map(|p| p.items)
.unwrap_or_default()
}
async fn artist_top_tracks(&self, artist_id: u64, limit: usize) -> Vec<Track> {
self.runtime
.core()
.get_artist_tracks(artist_id, limit as u32, 0)
.await
.map(|c| c.items)
.unwrap_or_default()
}
async fn artist_albums(&self, artist_id: u64, limit: usize) -> Vec<Album> {
self.runtime
.core()
.get_artist_albums(artist_id, Some(limit as u32), Some(0))
.await
.map(|a| a.items)
.unwrap_or_default()
}
async fn featured_albums(&self, kind: &str, limit: usize) -> Vec<Album> {
self.runtime
.core()
.get_featured_albums(kind, limit as u32, 0, None)
.await
.map(|p| p.items)
.unwrap_or_default()
}
async fn get_artist(&self, artist_id: u64) -> Option<Artist> {
self.runtime.core().get_artist(artist_id).await.ok()
}
}
// ── Loader ──────────────────────────────────────────────────────────────────
/// Resolve the Last.fm similar-album row for one album. Empty (and silent)
/// when Last.fm is not connected.
pub async fn similar_albums(
runtime: &Arc<AppRuntime<LoggingAdapter>>,
album_id: &str,
seed_artist: &str,
exclude_pairs: &[(String, String)],
exclude_ids: &HashSet<String>,
) -> Vec<AlbumReco> {
let cfg = crate::integrations_qt::scrobble_settings();
if !cfg.lastfm_is_authed() || cfg.lastfm_username.is_empty() {
return Vec::new();
}
let cache = cache_dir()
.and_then(|dir| RecoCache::open_at(&dir).ok())
.map(Mutex::new);
let cache_key = format!("album_lastfm:{album_id}");
// Cache hit: the row without any Last.fm or Qobuz traffic.
if let Some(c) = &cache {
if let Some(json) = c
.lock()
.ok()
.and_then(|g| g.get_results(&cache_key, LASTFM_SIMILAR_TTL_SECS))
{
if let Ok(cached) = serde_json::from_str::<Vec<AlbumReco>>(&json) {
return cached;
}
}
}
let lastfm_client = LastFmClient::new();
let mb_client = MusicBrainzClient::new();
let catalog = CoreRecoCatalog {
runtime: runtime.clone(),
};
let inputs = RecoInputs {
lastfm: Some(LastFmHandle {
username: cfg.lastfm_username.clone(),
client: &lastfm_client,
}),
listenbrainz: None,
musicbrainz: &mb_client,
catalog: &catalog,
cache: cache.as_ref(),
local: LocalHistory::default(),
rotation_seed: rotation_seed(),
};
let mut recos = build_similar_albums_seeded(&inputs, seed_artist, exclude_pairs).await;
// Drop any that resolved to an id the page's own Qobuz row already shows —
// the pre-resolution artist|title dedup can miss those.
recos.retain(|r| !exclude_ids.contains(&r.qobuz_album_id));
// Only a non-empty result is cached; an empty one is likely transient.
if !recos.is_empty() {
if let Some(c) = &cache {
if let (Ok(g), Ok(json)) = (c.lock(), serde_json::to_string(&recos)) {
g.put_results(&cache_key, &json);
}
}
}
recos
}
+19
View File
@@ -54,6 +54,7 @@ mod quality_state;
mod offline_fwd;
mod album_qt;
mod track_info_qt;
mod external_reco_qt;
mod ambient_qt;
mod artist_qt;
mod lyrics_qt;
@@ -889,6 +890,24 @@ pub(crate) fn large_cycle_spectrum() {
shell_bridge::ui(move |mut b| b.as_mut().set_large_spectrum_mode(mode));
}
/// Artist-network row click: resolve a musician NAME to a Qobuz artist and open
/// their page. Only a CONFIRMED match navigates — a guess would drop the user on
/// the wrong artist, which is worse than the row doing nothing.
pub(crate) fn resolve_musician(name: String, role: String) {
let runtime = app();
spawn(async move {
match runtime.core().musicbrainz_resolve_musician(&name, &role).await {
Ok(r) => match (r.confidence, r.qobuz_artist_id) {
(qbz_integrations::musicbrainz::MusicianConfidence::Confirmed, Some(id)) => {
open_artist(id.to_string());
}
_ => log::info!("[qbz-qt] musician '{name}' not confidently resolved; not navigating"),
},
Err(e) => log::warn!("[qbz-qt] musician resolve failed for '{name}': {e}"),
}
});
}
/// Artist-card overlay play (ArtistGridCard): Popular tracks with the
/// studio-discography fallback.
pub(crate) fn play_artist_card(artist_id: String) {