feat(purchases): detail polish and a Downloads section in the nav flyout

The purchase detail badges what was bought on every row (DSD128 on a
DSD purchase, not the catalog's 24/352.8), marks the formats already on
disk with a check in the dropdown, offers a track filter, links to the
album in the Local Library once its folder is indexed, and gives the
download the accent while Play drops to a plain control of the same
size — on this screen the download is the point.

Downloads are process-wide and survive leaving the page; the nav flyout
now lists the purchases with a download in flight under "Downloads · N"
so the user can find them again, each row reopening its detail.

cc
This commit is contained in:
vicrodh committed 2026-09-02 01:30:12 -06:00
1 parent fd44d38cd3
commit 07e683f5ef
12 files changed
+325 -29

No files matched your search

@@ -6354,4 +6354,7 @@ msgid "Sort: Release date"
msgstr "Sortierung: Veröffentlichungsdatum"
msgid "Until the purchased file is downloaded, Play streams the best quality Qobuz offers for this album. Once it is on disk, Play uses your copy."
msgstr "Solange die gekaufte Datei nicht heruntergeladen ist, streamt Wiedergabe die beste Qualität, die Qobuz für dieses Album anbietet. Sobald sie auf der Festplatte liegt, verwendet Wiedergabe deine Kopie."
msgstr "Solange die gekaufte Datei nicht heruntergeladen ist, streamt Wiedergabe die beste Qualität, die Qobuz für dieses Album anbietet. Sobald sie auf der Festplatte liegt, verwendet Wiedergabe deine Kopie."
msgid "Open in Local Library"
msgstr "In lokaler Bibliothek öffnen"
@@ -6360,4 +6360,7 @@ msgid "Sort: Release date"
msgstr "Orden: Fecha de lanzamiento"
msgid "Until the purchased file is downloaded, Play streams the best quality Qobuz offers for this album. Once it is on disk, Play uses your copy."
msgstr "Mientras no descargues el archivo comprado, Reproducir usa la mejor calidad que Qobuz ofrece para este álbum. Cuando ya esté en disco, Reproducir usa tu copia."
msgstr "Mientras no descargues el archivo comprado, Reproducir usa la mejor calidad que Qobuz ofrece para este álbum. Cuando ya esté en disco, Reproducir usa tu copia."
msgid "Open in Local Library"
msgstr "Abrir en Biblioteca local"
@@ -6352,4 +6352,7 @@ msgid "Sort: Release date"
msgstr "Tri : Date de sortie"
msgid "Until the purchased file is downloaded, Play streams the best quality Qobuz offers for this album. Once it is on disk, Play uses your copy."
msgstr "Tant que le fichier acheté n’est pas téléchargé, Lecture diffuse la meilleure qualité que Qobuz propose pour cet album. Une fois sur le disque, Lecture utilise votre copie."
msgstr "Tant que le fichier acheté n’est pas téléchargé, Lecture diffuse la meilleure qualité que Qobuz propose pour cet album. Une fois sur le disque, Lecture utilise votre copie."
msgid "Open in Local Library"
msgstr "Ouvrir dans la bibliothèque locale"
@@ -6335,4 +6335,7 @@ msgid "Sort: Release date"
msgstr "並び替え: 発売日"
msgid "Until the purchased file is downloaded, Play streams the best quality Qobuz offers for this album. Once it is on disk, Play uses your copy."
msgstr "購入したファイルをダウンロードするまでは、このアルバムに Qobuz が提供する最高品質でストリーミング再生します。ディスクに保存されると、再生はあなたのコピーを使います。"
msgstr "購入したファイルをダウンロードするまでは、このアルバムに Qobuz が提供する最高品質でストリーミング再生します。ディスクに保存されると、再生はあなたのコピーを使います。"
msgid "Open in Local Library"
msgstr "ローカルライブラリで開く"
@@ -6342,4 +6342,7 @@ msgid "Sort: Release date"
msgstr "Sorteren: Releasedatum"
msgid "Until the purchased file is downloaded, Play streams the best quality Qobuz offers for this album. Once it is on disk, Play uses your copy."
msgstr "Zolang het gekochte bestand niet is gedownload, streamt Afspelen de beste kwaliteit die Qobuz voor dit album biedt. Zodra het op schijf staat, gebruikt Afspelen jouw kopie."
msgstr "Zolang het gekochte bestand niet is gedownload, streamt Afspelen de beste kwaliteit die Qobuz voor dit album biedt. Zodra het op schijf staat, gebruikt Afspelen jouw kopie."
msgid "Open in Local Library"
msgstr "Openen in lokale bibliotheek"
@@ -6352,4 +6352,7 @@ msgid "Sort: Release date"
msgstr "Ordenar: Data de lançamento"
msgid "Until the purchased file is downloaded, Play streams the best quality Qobuz offers for this album. Once it is on disk, Play uses your copy."
msgstr "Enquanto o ficheiro comprado não for descarregado, Reproduzir transmite a melhor qualidade que a Qobuz oferece para este álbum. Assim que estiver no disco, Reproduzir usa a sua cópia."
msgstr "Enquanto o ficheiro comprado não for descarregado, Reproduzir transmite a melhor qualidade que a Qobuz oferece para este álbum. Assim que estiver no disco, Reproduzir usa a sua cópia."
msgid "Open in Local Library"
msgstr "Abrir na Biblioteca local"
@@ -6373,4 +6373,7 @@ msgid "Sort: Release date"
msgstr "Сортировка: Дата выхода"
msgid "Until the purchased file is downloaded, Play streams the best quality Qobuz offers for this album. Once it is on disk, Play uses your copy."
msgstr "Пока купленный файл не скачан, воспроизведение идёт в лучшем качестве, которое Qobuz предлагает для этого альбома. Как только он окажется на диске, воспроизводится ваша копия."
msgstr "Пока купленный файл не скачан, воспроизведение идёт в лучшем качестве, которое Qobuz предлагает для этого альбома. Как только он окажется на диске, воспроизводится ваша копия."
msgid "Open in Local Library"
msgstr "Открыть в локальной библиотеке"
+33
View File
@@ -6784,6 +6784,39 @@ impl LibraryDatabase {
.map_err(|e| LibraryError::Database(format!("Failed to collect purchase files: {}", e)))
}
/// The DISTINCT folders the registered downloads of one purchased album
/// sit in (a folder per format, e.g. `…/Album [DSF][DSD128]` and
/// `…/Album [FLAC][16-bit,44.1kHz]`), newest first. No stat, no prune.
pub fn get_downloaded_purchase_folders(
&self,
album_id: &str,
) -> Result<Vec<String>, LibraryError> {
let mut stmt = self
.conn
.prepare(
"SELECT file_path FROM downloaded_purchases
WHERE album_id = ?1 ORDER BY downloaded_at DESC",
)
.map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?;
let paths = stmt
.query_map(rusqlite::params![album_id], |row| row.get::<_, String>(0))
.map_err(|e| {
LibraryError::Database(format!("Failed to query purchase folders: {}", e))
})?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| LibraryError::Database(format!("Failed to collect folders: {}", e)))?;
let mut folders: Vec<String> = Vec::new();
for p in paths {
if let Some(dir) = std::path::Path::new(&p).parent() {
let dir = dir.to_string_lossy().into_owned();
if !folders.contains(&dir) {
folders.push(dir);
}
}
}
Ok(folders)
}
/// Remove ONE downloaded purchase record (e.g. the user deleted the file).
///
/// The table's primary key is `(track_id, format_id)` — the same purchased
+33 -4
View File
@@ -116,7 +116,8 @@ Item {
// (QbzSession.trRev is the translation revision counter every other
// tr() call site binds to).
readonly property var sections:
buildSections(QbzSession.trRev, showRecommendations, localTabOrder)
buildSections(QbzSession.trRev, showRecommendations, localTabOrder,
QbzPurchases.activeDownloadsJson)
function trs(s) { return QbzSession.tr(s, QbzSession.trRev) }
@@ -129,7 +130,7 @@ Item {
// `icon`"; a non-empty path is a user-supplied image
// rendered raw by shell/NavSectionGlyph.qml. Only the
// MyQBZ section can carry one. }
function buildSections(rev, reco, localOrder) {
function buildSections(rev, reco, localOrder, downloadsJson) {
// Discover — glyph-less rows (Slint has-glyph: false).
var discover = [
{ "label": nav.trs("Home"), "icon": "", "view": "home", "tab": "home", "enabled": true },
@@ -173,7 +174,29 @@ Item {
"icon": "folder-open", "view": "", "tab": "", "enabled": true,
"hasSubmenu": true, "submenu": nav.openMediaEntries()
})
return [
// Purchases in flight. A download is process-wide and survives
// leaving its page (purchases_qt's store), so this is how the user
// finds it again — and sees at a glance that something is still
// running. Absent entirely while nothing downloads.
var downloads = []
try {
var active = JSON.parse(downloadsJson || "[]")
for (var di = 0; di < active.length; di++)
downloads.push({
"label": active[di].title || nav.trs("Purchases"),
"icon": "cloud-download", "view": "", "tab": "", "enabled": true,
"action": "openPurchase", "albumId": active[di].id || ""
})
} catch (e) {}
var downloadsSection = downloads.length === 0 ? [] : [{
"id": "downloads",
"icon": "cloud-download",
"label": nav.trs("Downloads") + " · " + downloads.length,
"qobuz": true,
"enabled": true,
"entries": downloads
}]
return downloadsSection.concat([
{
"id": "discover",
"icon": "compass",
@@ -234,7 +257,7 @@ Item {
{ "label": nav.trs("Mixtapes"), "icon": "cassette-tape", "view": "mixtapes", "tab": "", "enabled": true }
]
}
]
])
}
/// Second-level catalog for Local Library > Open. When a medium already
@@ -356,6 +379,12 @@ Item {
QbzLocal.ephemeralClear()
return
}
if (entry.action === "openPurchase") {
// Same two-step every purchase entry uses: record, then route.
QbzPurchases.openAlbum(entry.albumId || "")
QbzShell.navigateTo("purchase-album")
return
}
if (entry.view === "") return
if (entry.tab && entry.tab !== "")
QbzShell.navigateToTab(entry.view, entry.tab)
+87 -4
View File
@@ -104,13 +104,43 @@ Rectangle {
if (root.formats[i].id === want) return i
return 0
}
// "✓" after every format whose download is COMPLETE for the whole album
// (`FormatRow.downloaded`, from the registry): the dropdown then says
// which versions are already on disk without opening each one.
readonly property var formatLabels: {
var out = []
for (var i = 0; i < root.formats.length; i++)
out.push(root.formats[i].label || "")
out.push((root.formats[i].label || "")
+ (root.formats[i].downloaded === true ? " ✓" : ""))
return out
}
// The track filter's text and its matcher (title / performer, case-folded).
property string query: ""
function matches(track) {
var q = root.query.trim().toLowerCase()
if (q === "")
return true
var t = (track.title || "").toLowerCase()
var a = (track.artist || "").toLowerCase()
return t.indexOf(q) >= 0 || a.indexOf(q) >= 0
}
readonly property int trackTotal: {
var n = 0
for (var d = 0; d < root.discs.length; d++)
n += (root.discs[d].tracks || []).length
return n
}
readonly property int matchCount: {
var n = 0
for (var d = 0; d < root.discs.length; d++) {
var ts = root.discs[d].tracks || []
for (var i = 0; i < ts.length; i++)
if (root.matches(ts[i])) n++
}
return n
}
// Click-to-play is gated on `streamable`, which on THIS screen defaults
// FALSE (§G.3 / §2.6): these tracks come from the catalog album, not from
// the purchases list. The album Play button therefore only appears when
@@ -445,9 +475,15 @@ Rectangle {
width: parent.width
spacing: 12
// On THIS screen the download is the point and Play
// is the convenience, so the accent goes to the
// cloud and both share one intermediate size — the
// 44px primary Play of the catalog album page read as
// the main event here (smoke 2026-09-02).
QbzCircleAction {
visible: root.anyStreamable
primary: true
primary: false
diameterOverride: 38
name: "play-fill"
anchors.verticalCenter: parent.verticalCenter
onClicked: QbzPlayer.playAlbum(root.doc.id || "")
@@ -458,7 +494,9 @@ Rectangle {
// it (§4.3: the four formats come from album metadata,
// and an album can legitimately offer none).
QbzCircleAction {
primary: !root.anyStreamable
primary: true
compactPrimary: true
diameterOverride: 38
name: "cloud-download"
btnEnabled: !(root.progress.active === true)
&& root.formats.length > 0
@@ -500,6 +538,20 @@ Rectangle {
btnEnabled: !(root.progress.active === true)
onClicked: QbzPurchases.chooseDestination()
}
// The album is ALREADY in the Local Library: jump to
// it. `localAlbumId` is the download folder the
// library indexed (purchases_qt::resolve_local_album),
// which is exactly the id the local album page opens.
IconTextButton {
visible: (root.doc.localAlbumId || "") !== ""
anchors.verticalCenter: parent.verticalCenter
label: root.t("Open in Local Library")
iconName: "hard-drive"
onClicked: {
QbzLocal.openAlbum(root.doc.localAlbumId)
QbzShell.navigateTo("localalbum")
}
}
// GOODIES — album-level only, never per-track, and
// completely absent when the list is empty (§14.3).
// Not disabled, not an empty state: the owner's
@@ -772,6 +824,35 @@ Rectangle {
width: parent.width - 64
spacing: 0
// Track filter — the Local Library album page's "Filter
// tracks" box, so a 30-track purchase is searchable in place.
// Presentation-only: rows that do not match collapse to 0px.
Item {
visible: root.discs.length > 0
width: parent.width
height: visible ? 44 : 0
QbzLineEdit {
id: trackFilter
anchors.right: parent.right
anchors.verticalCenter: parent.verticalCenter
width: 260
sm: true
searchMode: true
placeholder: root.t("Filter tracks")
text: root.query
onEdited: function (v) { root.query = v }
}
Text {
anchors.right: trackFilter.left
anchors.rightMargin: 12
anchors.verticalCenter: parent.verticalCenter
visible: root.query.trim() !== ""
text: root.matchCount + " / " + root.trackTotal
color: theme.textMuted
font.pixelSize: theme.fontLegal
}
}
// Column header. The arms MIRROR the delegate's arms below —
// no heart, no shared offline column, no ⋯ — and
// `trailingReserve` is the 28px status cell plus its 14px gap,
@@ -839,7 +920,9 @@ Rectangle {
required property var modelData
required property int index
width: parent ? parent.width : 0
height: 50
readonly property bool shown: root.matches(modelData)
visible: shown
height: shown ? 50 : 0
readonly property bool streamable: modelData.streamable === true
readonly property string trackId: modelData.id || ""
+8
View File
@@ -60,6 +60,11 @@ pub mod qbz_purchases_bridge {
/// (re-opening the same album, or a filter toggle that changes nothing
/// visible), the same trick `QbzSession.trRev` plays.
#[qproperty(i32, purchases_rev)]
/// The purchases with a download IN FLIGHT right now, as a JSON array
/// of `{ id, title }` — the nav flyout's "Downloads · N" section. A
/// download is process-wide and survives leaving its page; this is
/// how the user finds it again. `"[]"` while nothing runs.
#[qproperty(QString, active_downloads_json)]
type QbzPurchases = super::QbzPurchasesRust;
/// Registers this object's Qt-thread hop (Main.qml boots EVERY domain
@@ -189,6 +194,7 @@ pub struct QbzPurchasesRust {
list_json: QString,
album_json: QString,
purchases_rev: i32,
active_downloads_json: QString,
}
impl Default for QbzPurchasesRust {
@@ -199,6 +205,8 @@ impl Default for QbzPurchasesRust {
list_json: QString::from("{}"),
album_json: QString::from("{}"),
purchases_rev: 0,
// Same rule: the flyout JSON.parses it on the first frame.
active_downloads_json: QString::from("[]"),
}
}
}
+136 -14
View File
@@ -214,6 +214,9 @@ struct ListDoc {
struct FormatRow {
id: u32,
label: String,
/// Every track of the album is registered as downloaded IN THIS FORMAT
/// (the registry, not the transient store): the dropdown marks it.
downloaded: bool,
}
/// One detail-screen track.
@@ -328,6 +331,11 @@ struct AlbumDoc {
goodies_progress: GoodiesProgressDoc,
#[serde(rename = "addToLibraryVisible")]
add_to_library_visible: bool,
/// The download folder of this album that the Local Library has indexed
/// (`""` = none yet). It is the id the local album page opens, so the
/// detail can link straight to the copy on disk.
#[serde(rename = "localAlbumId")]
local_album_id: String,
}
// ---------------------------------------------------------------------------
@@ -410,6 +418,9 @@ struct AlbumDownload {
#[derive(Debug, Default)]
struct DownloadStore {
albums: HashMap<String, AlbumDownload>,
/// Album titles for the nav flyout's Downloads section — the store keys
/// by id and a menu row cannot show an id.
titles: HashMap<String, String>,
/// `album_id -> abort?` (the reference's module-level `abortFlags`, NOT
/// part of the store itself — cooperative cancellation checked BETWEEN
/// tracks).
@@ -452,6 +463,29 @@ impl DownloadStore {
self.entry(album_id).statuses.insert(track_id, status);
}
fn remember_title(&mut self, album_id: &str, title: &str) {
self.titles.insert(album_id.to_string(), title.to_string());
}
/// The albums with anything in flight — a whole-album loop, a single
/// track, or goodies — as the flyout's `{ id, title }` rows.
fn active_downloads(&self) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = self
.albums
.iter()
.filter(|(_, a)| {
a.downloading_all
|| a.goodies_active
|| a.statuses
.values()
.any(|st| matches!(st, DlStatus::Downloading))
})
.map(|(id, _)| (id.clone(), self.titles.get(id).cloned().unwrap_or_default()))
.collect();
out.sort();
out
}
/// Resolve the album folder from the FIRST successful track (`:160-165`).
fn resolve_album_folder(&mut self, album_id: &str, folder: &str) {
self.entry(album_id).resolved_album_folder = Some(folder.to_string());
@@ -655,9 +689,9 @@ fn tier(hires: bool, bit_depth: Option<u32>) -> String {
/// The badge for what the account BOUGHT. A DSD purchase streams as CD
/// (`hires:false`, 16/44.1 on the catalog — the live DSD64 album), so the
/// catalog's depth/rate describe the stream, not the purchase; the entitlement
/// ids are the only honest source. The badge control knows hires | cd | mp3,
/// so DSD rides the hires tier and says which DSD it is in the detail line.
/// Anything without a DSD id keeps the catalog-derived pair unchanged.
/// ids are the only honest source. 55/56 wear the `dsd` tier (the DSD mark)
/// with the multiple in the detail line; anything without a DSD id keeps the
/// catalog-derived pair unchanged.
fn purchased_quality(
hires: bool,
bit_depth: Option<u32>,
@@ -665,10 +699,10 @@ fn purchased_quality(
entitlement: &[u32],
) -> (String, String) {
if entitlement.contains(&56) {
return ("hires".to_string(), "DSD128".to_string());
return ("dsd".to_string(), "DSD128".to_string());
}
if entitlement.contains(&55) {
return ("hires".to_string(), "DSD64".to_string());
return ("dsd".to_string(), "DSD64".to_string());
}
(
tier(hires, bit_depth),
@@ -818,6 +852,9 @@ struct DetailState {
/// The folder the user picked for THIS album, before any download has
/// rewritten the store's copy to the album subfolder.
destination: String,
/// See `AlbumDoc::local_album_id`. Resolved on load and after every
/// download / add-to-library, never guessed.
local_album_id: String,
}
static LIST: Mutex<Option<ListState>> = Mutex::new(None);
@@ -888,8 +925,19 @@ fn publish_list() {
fn publish_album() {
let json =
with_detail(|s| serde_json::to_string(&build_album_doc(s)).unwrap_or_else(|_| "{}".into()));
let active = with_store(|st| {
serde_json::to_string(
&st.active_downloads()
.into_iter()
.map(|(id, title)| serde_json::json!({ "id": id, "title": title }))
.collect::<Vec<_>>(),
)
.unwrap_or_else(|_| "[]".into())
});
crate::purchases_bridge::ui(move |mut b| {
b.as_mut().set_album_json(QString::from(json.as_str()));
b.as_mut()
.set_active_downloads_json(QString::from(active.as_str()));
let next = b.as_ref().purchases_rev() + 1;
b.as_mut().set_purchases_rev(next);
});
@@ -1045,6 +1093,12 @@ fn album_row(a: &PurchaseAlbum) -> AlbumRow {
}
fn track_row(t: &PurchaseTrack) -> TrackRow {
let track_quality = purchased_quality(
t.hires,
t.maximum_bit_depth,
t.maximum_sampling_rate,
&t.downloadable_format_ids,
);
let (album_title, album_id, url) = match &t.album {
Some(al) => (
al.title.clone(),
@@ -1063,8 +1117,8 @@ fn track_row(t: &PurchaseTrack) -> TrackRow {
art_path: cached_art(&url),
artwork_url: url,
duration: t.duration,
quality_tier: tier(t.hires, t.maximum_bit_depth),
quality_detail: quality_detail(t.maximum_bit_depth, t.maximum_sampling_rate),
quality_tier: track_quality.0,
quality_detail: track_quality.1,
streamable: t.streamable,
downloaded: t.downloaded,
purchased_at: t.purchased_at.unwrap_or(0),
@@ -1139,6 +1193,7 @@ fn build_album_doc(s: &DetailState) -> AlbumDoc {
progress: ProgressDoc::default(),
goodies_progress: GoodiesProgressDoc::default(),
add_to_library_visible: false,
local_album_id: String::new(),
};
};
@@ -1158,6 +1213,12 @@ fn build_album_doc(s: &DetailState) -> AlbumDoc {
let mut discs: Vec<DiscRow> = Vec::new();
for t in tracks {
let number = t.media_number.unwrap_or(1);
let row_quality = purchased_quality(
t.hires,
t.maximum_bit_depth,
t.maximum_sampling_rate,
&album.downloadable_format_ids,
);
let row = AlbumTrackRow {
id: t.id.to_string(),
title: t.title.clone(),
@@ -1165,8 +1226,10 @@ fn build_album_doc(s: &DetailState) -> AlbumDoc {
artist: t.performer.name.clone(),
track_number: t.track_number,
duration: t.duration,
quality_tier: tier(t.hires, t.maximum_bit_depth),
quality_detail: quality_detail(t.maximum_bit_depth, t.maximum_sampling_rate),
// The purchase's own quality (DSD128 on a DSD purchase), not the
// catalog's 24/352.8 that no stream ever delivers.
quality_tier: row_quality.0,
quality_detail: row_quality.1,
streamable: t.streamable,
// `isDownloadedForFormat || status === 'complete'` (`:446`, and the
// per-row derive at `:406-415`). BOTH halves are format-scoped,
@@ -1247,6 +1310,10 @@ fn build_album_doc(s: &DetailState) -> AlbumDoc {
.map(|f| FormatRow {
id: f.id,
label: f.label.clone(),
downloaded: !tracks.is_empty()
&& tracks
.iter()
.all(|t| t.downloaded_format_ids.contains(&f.id)),
})
.collect(),
selected_format_id: selected.unwrap_or(0) as i32,
@@ -1289,6 +1356,7 @@ fn build_album_doc(s: &DetailState) -> AlbumDoc {
&& dl_ref
.and_then(|d| d.resolved_album_folder.as_ref())
.is_some(),
local_album_id: s.local_album_id.clone(),
}
}
@@ -1852,6 +1920,7 @@ async fn load_album(generation: u64, album_id: String) {
});
let reg = ensure_registry().await;
let local_album_id = resolve_local_album(album_id.clone()).await;
let album =
svc::build_purchase_album(&catalog, &purchases, &reg.downloaded_ids, &reg.format_map);
@@ -1875,6 +1944,7 @@ async fn load_album(generation: u64, album_id: String) {
s.album = Some(album);
s.catalog = Some(catalog);
s.formats = formats;
s.local_album_id = local_album_id;
s.art_path = cached_art(&cover_url);
s.loading = false;
s.error.clear();
@@ -2049,7 +2119,10 @@ pub fn download_track(track_id: String) {
let Some(plan) = ensure_destination(plan).await else {
return;
};
with_store(|st| st.merge_track_start(&plan.album_id, track_id, plan.format_id));
with_store(|st| {
st.remember_title(&plan.album_id, &plan.album_title);
st.merge_track_start(&plan.album_id, track_id, plan.format_id)
});
publish_album();
let Some(client) = snapshot_client().await else {
@@ -2102,7 +2175,10 @@ async fn build_context(catalog: &Album) -> svc::PurchaseAlbumContext {
}
async fn run_album_download(plan: DownloadPlan) {
with_store(|st| st.seed_album(&plan.album_id, plan.format_id));
with_store(|st| {
st.remember_title(&plan.album_id, &plan.album_title);
st.seed_album(&plan.album_id, plan.format_id)
});
publish_album();
let Some(client) = snapshot_client().await else {
@@ -2395,10 +2471,51 @@ fn toast_album_outcome(plan: &DownloadPlan) {
}
}
/// The download folder of `album_id` the Local Library has INDEXED, or `""`.
/// Walks the registry's folders for the album (newest first) and asks the
/// library for rows under each; the first folder with rows is the local album
/// id (`local_bridge::open_album_by_id` opens a plain local album by its
/// folder path). Off the UI thread; a missing library answers `""`.
async fn resolve_local_album(album_id: String) -> String {
tokio::task::spawn_blocking(move || {
crate::library_db_qt::with_db(false, |db| {
for folder in db.get_downloaded_purchase_folders(&album_id)? {
if !db.list_folder_tracks(&folder, false)?.is_empty() {
return Ok(folder);
}
}
Ok(String::new())
})
.unwrap_or_default()
})
.await
.unwrap_or_default()
}
/// Recompute `local_album_id` for the open detail and republish if it moved.
async fn refresh_local_album_link() {
let Some(album_id) = with_detail(|s| (!s.album_id.is_empty()).then(|| s.album_id.clone()))
else {
return;
};
let id = resolve_local_album(album_id.clone()).await;
let changed = with_detail(|s| {
if s.album_id != album_id || s.local_album_id == id {
return false;
}
s.local_album_id = id;
true
});
if changed {
publish_album();
}
}
/// Re-read the registry and re-annotate everything the download just changed, so
/// the green checks survive a reload instead of living only in the transient
/// store.
async fn refresh_after_download() {
refresh_local_album_link().await;
let reg = read_registry().await;
set_registry(reg.clone());
@@ -2554,6 +2671,11 @@ pub fn add_to_library() {
// re-walk the user's entire library, which on a large one is minutes of
// disk for a single new album.
crate::settings_qt::library::scan(Some(folder_id));
// The scan runs on its own; the link appears once its rows exist.
// One look after a generous delay is enough for an album-sized
// folder, and re-entering the page resolves it again anyway.
tokio::time::sleep(std::time::Duration::from_secs(4)).await;
refresh_local_album_link().await;
});
}
@@ -3025,12 +3147,12 @@ mod tests {
// ---- What was bought, not what streams -------------------------------
#[test]
fn a_dsd_purchase_badges_as_hires_with_the_dsd_in_the_detail() {
fn a_dsd_purchase_wears_the_dsd_tier_with_the_multiple_in_the_detail() {
// Rust In Peace on the live account: hires:false, 16/44.1, [55].
let (tier, detail) = purchased_quality(false, Some(16), Some(44.1), &[55]);
assert_eq!((tier.as_str(), detail.as_str()), ("hires", "DSD64"));
assert_eq!((tier.as_str(), detail.as_str()), ("dsd", "DSD64"));
let (tier, detail) = purchased_quality(true, Some(24), Some(352.8), &[56]);
assert_eq!((tier.as_str(), detail.as_str()), ("hires", "DSD128"));
assert_eq!((tier.as_str(), detail.as_str()), ("dsd", "DSD128"));
// A FLAC purchase keeps the catalog-derived pair untouched.
let (tier, detail) = purchased_quality(true, Some(24), Some(96.0), &[7, 6, 5]);
assert_eq!(tier, "hires");