fix(qt): replace unavailable library favorites

cx
This commit is contained in:
vicrodh committed 2026-09-05 17:31:17 -06:00
1 parent 7ec9788728
commit 316a0c8f46
22 files changed
+1806 -91

No files matched your search

+6 -2
View File
@@ -28,13 +28,17 @@ use qbz_models::{Album, Artist, Track};
pub use cache::RecoCache;
pub use carousels::{compose_artist_rails, ArtistRailComposition, ARTIST_DISPLAY_CAP};
// Shared catalog text rules. The Library release-replacement picker needs the
// same bracket/edition stripping and similarity semantics as recommendation
// validation; exporting the two pure helpers prevents a third drifting copy.
pub use matching::{normalize as normalize_catalog_name, similarity as catalog_similarity};
// `validate` stays a private module — only this one helper is public, because
// the unavailable-track replacement flow (qbz-qt) needs the ISRC -> streamable
// -track lookup and nothing else in it.
pub use validate::find_by_isrc;
pub use types::{
AlbumReco, ArtistReco, ExternalCarousels, ExtHistory, LocalHistory, RecoSource, TrackReco,
AlbumReco, ArtistReco, ExtHistory, ExternalCarousels, LocalHistory, RecoSource, TrackReco,
};
pub use validate::find_by_isrc;
/// The Qobuz catalog operations the engine needs. Implemented by the frontend
/// over its own `QbzCore`. Every method swallows errors to an empty result.
@@ -6756,3 +6756,60 @@ msgstr "Qobuz-Links in QBZ öffnen"
msgid "Make QBZ the handler for qobuzapp:// links from your browser. Off, the official Qobuz app keeps them; QBZ's own qbz:// links always open here."
msgstr "Macht QBZ zum Handler für qobuzapp://-Links aus dem Browser. Ausgeschaltet behält die offizielle Qobuz-App sie; QBZ-eigene qbz://-Links öffnen immer hier."
msgid "Look for better replacement"
msgstr "Nach einem besseren Ersatz suchen"
msgid "Remove all favorites from this release"
msgstr "Alle Favoriten dieser Veröffentlichung entfernen"
msgid "Remove all favorites from this release?"
msgstr "Alle Favoriten dieser Veröffentlichung entfernen?"
msgid "Remove the album and every track from this release from your Library?"
msgstr "Das Album und alle Titel dieser Veröffentlichung aus deiner Bibliothek entfernen?"
msgid "No replacement releases found"
msgstr "Keine Ersatzveröffentlichungen gefunden"
msgid "Choosing a result opens the release. Your existing favorites are not changed."
msgstr "Die Auswahl öffnet die Veröffentlichung. Deine vorhandenen Favoriten werden nicht geändert."
msgid "No favorites from this release to remove"
msgstr "Keine Favoriten dieser Veröffentlichung zum Entfernen vorhanden"
msgid "Favorites removed from this release"
msgstr "Favoriten dieser Veröffentlichung entfernt"
msgid "Could not remove favorites from this release"
msgstr "Favoriten dieser Veröffentlichung konnten nicht entfernt werden"
msgid "Some favorites could not be removed"
msgstr "Einige Favoriten konnten nicht entfernt werden"
msgid "Replace in Library"
msgstr "In der Bibliothek ersetzen"
msgid "Replacing favorite..."
msgstr "Favorit wird ersetzt..."
msgid "The selected release replaces the unavailable album favorite."
msgstr "Die ausgewählte Veröffentlichung ersetzt das nicht verfügbare favorisierte Album."
msgid "The matching track from the selected release replaces the unavailable favorite."
msgstr "Der passende Titel der ausgewählten Veröffentlichung ersetzt den nicht verfügbaren Favoriten."
msgid "Could not open the selected release"
msgstr "Die ausgewählte Veröffentlichung konnte nicht geöffnet werden"
msgid "Could not find a matching track in this release"
msgstr "In dieser Veröffentlichung wurde kein passender Titel gefunden"
msgid "Could not add the replacement favorite"
msgstr "Der Ersatzfavorit konnte nicht hinzugefügt werden"
msgid "Favorite replaced"
msgstr "Favorit ersetzt"
msgid "The replacement was added, but the unavailable favorite could not be removed"
msgstr "Der Ersatz wurde hinzugefügt, aber der nicht verfügbare Favorit konnte nicht entfernt werden"
@@ -2343,3 +2343,60 @@ msgstr "Open Qobuz links in QBZ"
msgid "Make QBZ the handler for qobuzapp:// links from your browser. Off, the official Qobuz app keeps them; QBZ's own qbz:// links always open here."
msgstr "Make QBZ the handler for qobuzapp:// links from your browser. Off, the official Qobuz app keeps them; QBZ's own qbz:// links always open here."
msgid "Look for better replacement"
msgstr "Look for better replacement"
msgid "Remove all favorites from this release"
msgstr "Remove all favorites from this release"
msgid "Remove all favorites from this release?"
msgstr "Remove all favorites from this release?"
msgid "Remove the album and every track from this release from your Library?"
msgstr "Remove the album and every track from this release from your Library?"
msgid "No replacement releases found"
msgstr "No replacement releases found"
msgid "Choosing a result opens the release. Your existing favorites are not changed."
msgstr "Choosing a result opens the release. Your existing favorites are not changed."
msgid "No favorites from this release to remove"
msgstr "No favorites from this release to remove"
msgid "Favorites removed from this release"
msgstr "Favorites removed from this release"
msgid "Could not remove favorites from this release"
msgstr "Could not remove favorites from this release"
msgid "Some favorites could not be removed"
msgstr "Some favorites could not be removed"
msgid "Replace in Library"
msgstr "Replace in Library"
msgid "Replacing favorite..."
msgstr "Replacing favorite..."
msgid "The selected release replaces the unavailable album favorite."
msgstr "The selected release replaces the unavailable album favorite."
msgid "The matching track from the selected release replaces the unavailable favorite."
msgstr "The matching track from the selected release replaces the unavailable favorite."
msgid "Could not open the selected release"
msgstr "Could not open the selected release"
msgid "Could not find a matching track in this release"
msgstr "Could not find a matching track in this release"
msgid "Could not add the replacement favorite"
msgstr "Could not add the replacement favorite"
msgid "Favorite replaced"
msgstr "Favorite replaced"
msgid "The replacement was added, but the unavailable favorite could not be removed"
msgstr "The replacement was added, but the unavailable favorite could not be removed"
@@ -6762,3 +6762,60 @@ msgstr "Abrir enlaces de Qobuz en QBZ"
msgid "Make QBZ the handler for qobuzapp:// links from your browser. Off, the official Qobuz app keeps them; QBZ's own qbz:// links always open here."
msgstr "Hace que QBZ maneje los enlaces qobuzapp:// que salen de tu navegador. Apagado, la app oficial de Qobuz se queda con ellos; los enlaces qbz:// de QBZ siempre abren aquí."
msgid "Look for better replacement"
msgstr "Buscar un reemplazo mejor"
msgid "Remove all favorites from this release"
msgstr "Eliminar todos los favoritos de este lanzamiento"
msgid "Remove all favorites from this release?"
msgstr "¿Eliminar todos los favoritos de este lanzamiento?"
msgid "Remove the album and every track from this release from your Library?"
msgstr "¿Eliminar de tu Biblioteca el álbum y todas las pistas de este lanzamiento?"
msgid "No replacement releases found"
msgstr "No se encontraron lanzamientos de reemplazo"
msgid "Choosing a result opens the release. Your existing favorites are not changed."
msgstr "Al elegir un resultado se abre el lanzamiento. Tus favoritos actuales no cambian."
msgid "No favorites from this release to remove"
msgstr "No hay favoritos de este lanzamiento para eliminar"
msgid "Favorites removed from this release"
msgstr "Se eliminaron los favoritos de este lanzamiento"
msgid "Could not remove favorites from this release"
msgstr "No se pudieron eliminar los favoritos de este lanzamiento"
msgid "Some favorites could not be removed"
msgstr "No se pudieron eliminar algunos favoritos"
msgid "Replace in Library"
msgstr "Reemplazar en la Biblioteca"
msgid "Replacing favorite..."
msgstr "Reemplazando favorito..."
msgid "The selected release replaces the unavailable album favorite."
msgstr "El lanzamiento seleccionado reemplaza el álbum favorito no disponible."
msgid "The matching track from the selected release replaces the unavailable favorite."
msgstr "La pista equivalente del lanzamiento seleccionado reemplaza el favorito no disponible."
msgid "Could not open the selected release"
msgstr "No se pudo abrir el lanzamiento seleccionado"
msgid "Could not find a matching track in this release"
msgstr "No se encontró una pista equivalente en este lanzamiento"
msgid "Could not add the replacement favorite"
msgstr "No se pudo agregar el favorito de reemplazo"
msgid "Favorite replaced"
msgstr "Favorito reemplazado"
msgid "The replacement was added, but the unavailable favorite could not be removed"
msgstr "Se agregó el reemplazo, pero no se pudo eliminar el favorito no disponible"
@@ -6754,3 +6754,60 @@ msgstr "Ouvrir les liens Qobuz dans QBZ"
msgid "Make QBZ the handler for qobuzapp:// links from your browser. Off, the official Qobuz app keeps them; QBZ's own qbz:// links always open here."
msgstr "Fait de QBZ le gestionnaire des liens qobuzapp:// venant du navigateur. Désactivé, l'application Qobuz officielle les conserve ; les liens qbz:// de QBZ s'ouvrent toujours ici."
msgid "Look for better replacement"
msgstr "Chercher un meilleur remplacement"
msgid "Remove all favorites from this release"
msgstr "Retirer tous les favoris de cette parution"
msgid "Remove all favorites from this release?"
msgstr "Retirer tous les favoris de cette parution ?"
msgid "Remove the album and every track from this release from your Library?"
msgstr "Retirer de votre Bibliothèque l’album et toutes les pistes de cette parution ?"
msgid "No replacement releases found"
msgstr "Aucune parution de remplacement trouvée"
msgid "Choosing a result opens the release. Your existing favorites are not changed."
msgstr "Le résultat choisi ouvre la parution. Vos favoris existants ne sont pas modifiés."
msgid "No favorites from this release to remove"
msgstr "Aucun favori de cette parution à retirer"
msgid "Favorites removed from this release"
msgstr "Favoris de cette parution retirés"
msgid "Could not remove favorites from this release"
msgstr "Impossible de retirer les favoris de cette parution"
msgid "Some favorites could not be removed"
msgstr "Certains favoris n’ont pas pu être retirés"
msgid "Replace in Library"
msgstr "Remplacer dans la bibliothèque"
msgid "Replacing favorite..."
msgstr "Remplacement du favori..."
msgid "The selected release replaces the unavailable album favorite."
msgstr "La parution sélectionnée remplace l’album favori indisponible."
msgid "The matching track from the selected release replaces the unavailable favorite."
msgstr "Le titre correspondant de la parution sélectionnée remplace le favori indisponible."
msgid "Could not open the selected release"
msgstr "Impossible d’ouvrir la parution sélectionnée"
msgid "Could not find a matching track in this release"
msgstr "Aucun titre correspondant trouvé dans cette parution"
msgid "Could not add the replacement favorite"
msgstr "Impossible d’ajouter le favori de remplacement"
msgid "Favorite replaced"
msgstr "Favori remplacé"
msgid "The replacement was added, but the unavailable favorite could not be removed"
msgstr "Le remplacement a été ajouté, mais le favori indisponible n’a pas pu être supprimé"
@@ -6737,3 +6737,60 @@ msgstr "Qobuz のリンクを QBZ で開く"
msgid "Make QBZ the handler for qobuzapp:// links from your browser. Off, the official Qobuz app keeps them; QBZ's own qbz:// links always open here."
msgstr "ブラウザーからの qobuzapp:// リンクを QBZ で処理します。オフの場合は公式の Qobuz アプリが処理します。QBZ 独自の qbz:// リンクは常にここで開きます。"
msgid "Look for better replacement"
msgstr "より良い代替盤を探す"
msgid "Remove all favorites from this release"
msgstr "このリリースのすべてのお気に入りを削除"
msgid "Remove all favorites from this release?"
msgstr "このリリースのすべてのお気に入りを削除しますか?"
msgid "Remove the album and every track from this release from your Library?"
msgstr "このリリースのアルバムとすべてのトラックをライブラリから削除しますか?"
msgid "No replacement releases found"
msgstr "代替リリースが見つかりません"
msgid "Choosing a result opens the release. Your existing favorites are not changed."
msgstr "結果を選ぶとリリースが開きます。現在のお気に入りは変更されません。"
msgid "No favorites from this release to remove"
msgstr "このリリースには削除するお気に入りがありません"
msgid "Favorites removed from this release"
msgstr "このリリースのお気に入りを削除しました"
msgid "Could not remove favorites from this release"
msgstr "このリリースのお気に入りを削除できませんでした"
msgid "Some favorites could not be removed"
msgstr "一部のお気に入りを削除できませんでした"
msgid "Replace in Library"
msgstr "ライブラリ内で置き換え"
msgid "Replacing favorite..."
msgstr "お気に入りを置き換えています..."
msgid "The selected release replaces the unavailable album favorite."
msgstr "選択したリリースで、利用できないお気に入りのアルバムを置き換えます。"
msgid "The matching track from the selected release replaces the unavailable favorite."
msgstr "選択したリリース内の一致する曲で、利用できないお気に入りを置き換えます。"
msgid "Could not open the selected release"
msgstr "選択したリリースを開けませんでした"
msgid "Could not find a matching track in this release"
msgstr "このリリース内に一致する曲が見つかりませんでした"
msgid "Could not add the replacement favorite"
msgstr "置き換え用のお気に入りを追加できませんでした"
msgid "Favorite replaced"
msgstr "お気に入りを置き換えました"
msgid "The replacement was added, but the unavailable favorite could not be removed"
msgstr "置き換えを追加しましたが、利用できないお気に入りを削除できませんでした"
@@ -6744,3 +6744,60 @@ msgstr "Qobuz-links openen in QBZ"
msgid "Make QBZ the handler for qobuzapp:// links from your browser. Off, the official Qobuz app keeps them; QBZ's own qbz:// links always open here."
msgstr "Maakt QBZ de handler voor qobuzapp://-links uit je browser. Uit: de officiële Qobuz-app houdt ze; QBZ's eigen qbz://-links openen altijd hier."
msgid "Look for better replacement"
msgstr "Een betere vervanging zoeken"
msgid "Remove all favorites from this release"
msgstr "Alle favorieten van deze uitgave verwijderen"
msgid "Remove all favorites from this release?"
msgstr "Alle favorieten van deze uitgave verwijderen?"
msgid "Remove the album and every track from this release from your Library?"
msgstr "Het album en alle nummers van deze uitgave uit je bibliotheek verwijderen?"
msgid "No replacement releases found"
msgstr "Geen vervangende uitgaven gevonden"
msgid "Choosing a result opens the release. Your existing favorites are not changed."
msgstr "Als je een resultaat kiest, wordt de uitgave geopend. Je bestaande favorieten blijven ongewijzigd."
msgid "No favorites from this release to remove"
msgstr "Geen favorieten van deze uitgave om te verwijderen"
msgid "Favorites removed from this release"
msgstr "Favorieten van deze uitgave verwijderd"
msgid "Could not remove favorites from this release"
msgstr "Favorieten van deze uitgave konden niet worden verwijderd"
msgid "Some favorites could not be removed"
msgstr "Sommige favorieten konden niet worden verwijderd"
msgid "Replace in Library"
msgstr "Vervangen in bibliotheek"
msgid "Replacing favorite..."
msgstr "Favoriet wordt vervangen..."
msgid "The selected release replaces the unavailable album favorite."
msgstr "De geselecteerde release vervangt het niet-beschikbare favoriete album."
msgid "The matching track from the selected release replaces the unavailable favorite."
msgstr "De overeenkomende track van de geselecteerde release vervangt de niet-beschikbare favoriet."
msgid "Could not open the selected release"
msgstr "De geselecteerde release kon niet worden geopend"
msgid "Could not find a matching track in this release"
msgstr "Er is geen overeenkomende track in deze release gevonden"
msgid "Could not add the replacement favorite"
msgstr "De vervangende favoriet kon niet worden toegevoegd"
msgid "Favorite replaced"
msgstr "Favoriet vervangen"
msgid "The replacement was added, but the unavailable favorite could not be removed"
msgstr "De vervanging is toegevoegd, maar de niet-beschikbare favoriet kon niet worden verwijderd"
@@ -6754,3 +6754,60 @@ msgstr "Abrir links do Qobuz no QBZ"
msgid "Make QBZ the handler for qobuzapp:// links from your browser. Off, the official Qobuz app keeps them; QBZ's own qbz:// links always open here."
msgstr "Torna o QBZ o manipulador dos links qobuzapp:// vindos do navegador. Desligado, o app oficial do Qobuz fica com eles; os links qbz:// do QBZ sempre abrem aqui."
msgid "Look for better replacement"
msgstr "Procurar uma substituição melhor"
msgid "Remove all favorites from this release"
msgstr "Remover todos os favoritos deste lançamento"
msgid "Remove all favorites from this release?"
msgstr "Remover todos os favoritos deste lançamento?"
msgid "Remove the album and every track from this release from your Library?"
msgstr "Remover da sua Biblioteca o álbum e todas as faixas deste lançamento?"
msgid "No replacement releases found"
msgstr "Nenhum lançamento substituto encontrado"
msgid "Choosing a result opens the release. Your existing favorites are not changed."
msgstr "Escolher um resultado abre o lançamento. Seus favoritos atuais não são alterados."
msgid "No favorites from this release to remove"
msgstr "Não há favoritos deste lançamento para remover"
msgid "Favorites removed from this release"
msgstr "Favoritos deste lançamento removidos"
msgid "Could not remove favorites from this release"
msgstr "Não foi possível remover os favoritos deste lançamento"
msgid "Some favorites could not be removed"
msgstr "Não foi possível remover alguns favoritos"
msgid "Replace in Library"
msgstr "Substituir na Biblioteca"
msgid "Replacing favorite..."
msgstr "Substituindo favorito..."
msgid "The selected release replaces the unavailable album favorite."
msgstr "O lançamento selecionado substitui o álbum favorito indisponível."
msgid "The matching track from the selected release replaces the unavailable favorite."
msgstr "A faixa correspondente do lançamento selecionado substitui o favorito indisponível."
msgid "Could not open the selected release"
msgstr "Não foi possível abrir o lançamento selecionado"
msgid "Could not find a matching track in this release"
msgstr "Não foi possível encontrar uma faixa correspondente neste lançamento"
msgid "Could not add the replacement favorite"
msgstr "Não foi possível adicionar o favorito substituto"
msgid "Favorite replaced"
msgstr "Favorito substituído"
msgid "The replacement was added, but the unavailable favorite could not be removed"
msgstr "A substituição foi adicionada, mas o favorito indisponível não pôde ser removido"
@@ -6775,3 +6775,60 @@ msgstr "Открывать ссылки Qobuz в QBZ"
msgid "Make QBZ the handler for qobuzapp:// links from your browser. Off, the official Qobuz app keeps them; QBZ's own qbz:// links always open here."
msgstr "Делает QBZ обработчиком ссылок qobuzapp:// из браузера. Если выключено, их оставляет официальное приложение Qobuz; собственные ссылки qbz:// всегда открываются здесь."
msgid "Look for better replacement"
msgstr "Найти лучшую замену"
msgid "Remove all favorites from this release"
msgstr "Удалить всё избранное из этого релиза"
msgid "Remove all favorites from this release?"
msgstr "Удалить всё избранное из этого релиза?"
msgid "Remove the album and every track from this release from your Library?"
msgstr "Удалить альбом и все треки этого релиза из вашей медиатеки?"
msgid "No replacement releases found"
msgstr "Релизы на замену не найдены"
msgid "Choosing a result opens the release. Your existing favorites are not changed."
msgstr "Выбор результата откроет релиз. Ваше текущее избранное не изменится."
msgid "No favorites from this release to remove"
msgstr "В этом релизе нет избранного для удаления"
msgid "Favorites removed from this release"
msgstr "Избранное этого релиза удалено"
msgid "Could not remove favorites from this release"
msgstr "Не удалось удалить избранное этого релиза"
msgid "Some favorites could not be removed"
msgstr "Некоторые элементы избранного не удалось удалить"
msgid "Replace in Library"
msgstr "Заменить в медиатеке"
msgid "Replacing favorite..."
msgstr "Замена избранного..."
msgid "The selected release replaces the unavailable album favorite."
msgstr "Выбранный релиз заменит недоступный альбом в избранном."
msgid "The matching track from the selected release replaces the unavailable favorite."
msgstr "Соответствующий трек из выбранного релиза заменит недоступный трек в избранном."
msgid "Could not open the selected release"
msgstr "Не удалось открыть выбранный релиз"
msgid "Could not find a matching track in this release"
msgstr "В этом релизе не найден соответствующий трек"
msgid "Could not add the replacement favorite"
msgstr "Не удалось добавить замену в избранное"
msgid "Favorite replaced"
msgstr "Избранное заменено"
msgid "The replacement was added, but the unavailable favorite could not be removed"
msgstr "Замена добавлена, но недоступный элемент не удалось удалить из избранного"
+73 -3
View File
@@ -679,6 +679,40 @@ pub struct AlbumSummary {
/// "In library" tab admits a track through either.
#[serde(default)]
pub artist: Option<Artist>,
/// Release/edition suffix on embedded album rows (for example
/// "Remastered 2021"). Search and favourites payloads carry it even
/// though older endpoints omit it.
#[serde(default)]
pub version: Option<String>,
/// Availability of the release that owns this track. As with the full
/// [`Album`] model, absence means unknown — never unavailable.
#[serde(default)]
pub streamable: Option<bool>,
/// Unix timestamp at which this release becomes streamable, when supplied
/// by the embedding endpoint.
#[serde(default)]
pub streamable_at: Option<i64>,
/// ISO streaming release date, used as the fallback upcoming signal.
#[serde(default)]
pub release_date_stream: Option<String>,
}
impl AlbumSummary {
/// `None` is a terse endpoint, not a withdrawal.
pub fn is_streamable(&self) -> bool {
self.streamable.unwrap_or(true)
}
/// Distinguish a future release from a withdrawn one using the same rule
/// as [`Track::is_upcoming`].
pub fn is_upcoming(&self) -> bool {
!self.is_streamable()
&& upcoming_from(
self.streamable_at,
self.release_date_stream.as_deref(),
chrono::Utc::now(),
)
}
}
/// Album model
@@ -2137,6 +2171,31 @@ mod purchase_deserializer_tests {
assert!(!album.is_streamable());
}
#[test]
fn embedded_album_availability_keeps_unknown_distinct_from_false() {
let absent: AlbumSummary = serde_json::from_str(r#"{"id":"a","title":"A"}"#).unwrap();
assert_eq!(absent.streamable, None);
assert!(absent.is_streamable());
let withdrawn: AlbumSummary = serde_json::from_str(
r#"{"id":"a","title":"A","version":"Remastered","streamable":false}"#,
)
.unwrap();
assert_eq!(withdrawn.streamable, Some(false));
assert!(!withdrawn.is_streamable());
assert!(!withdrawn.is_upcoming());
assert_eq!(withdrawn.version.as_deref(), Some("Remastered"));
}
#[test]
fn embedded_future_album_is_upcoming_not_withdrawn() {
let upcoming: AlbumSummary = serde_json::from_str(
r#"{"id":"a","title":"A","streamable":false,"release_date_stream":"2999-01-01"}"#,
)
.unwrap();
assert!(upcoming.is_upcoming());
}
/// `downloadable` drives three list behaviours (the hide-unavailable filter,
/// the album click gate, the unavailable marker), so its default is not
/// decoration: getting it wrong ships clickable unavailable albums.
@@ -2319,8 +2378,16 @@ mod upcoming_tests {
fn future_streamable_at_wins_over_the_date() {
let now = Utc.with_ymd_and_hms(2026, 9, 2, 12, 0, 0).unwrap();
assert!(upcoming_from(Some(now.timestamp() + 60), None, now));
assert!(upcoming_from(Some(now.timestamp() + 60), Some("2000-01-01"), now));
assert!(!upcoming_from(Some(now.timestamp() - 60), Some("2099-01-01"), now));
assert!(upcoming_from(
Some(now.timestamp() + 60),
Some("2000-01-01"),
now
));
assert!(!upcoming_from(
Some(now.timestamp() - 60),
Some("2099-01-01"),
now
));
// The captured dead track: `streamable_at: null`, past release date.
assert!(!upcoming_from(None, Some("2013-06-21"), now));
}
@@ -2329,7 +2396,10 @@ mod upcoming_tests {
fn release_date_is_the_fallback_and_absence_is_not_upcoming() {
let now = Utc.with_ymd_and_hms(2026, 9, 2, 12, 0, 0).unwrap();
assert!(upcoming_from(None, Some("2026-10-16"), now));
assert!(!upcoming_from(None, Some("2026-09-02"), now), "today is not upcoming");
assert!(
!upcoming_from(None, Some("2026-09-02"), now),
"today is not upcoming"
);
assert!(!upcoming_from(None, Some("not a date"), now));
assert!(!upcoming_from(None, None, now));
}
+32
View File
@@ -66,6 +66,18 @@ pub enum ApiError {
}
impl ApiError {
/// Whether this is the exact terminal 404 sentinel emitted by
/// `QobuzClient::get_album`. Centralising the legacy string-shaped result
/// keeps UI callers from broad `contains("404")` guesses while avoiding a
/// new enum variant that would break every exhaustive error classifier.
pub fn is_album_unavailable(&self, album_id: &str) -> bool {
matches!(
self,
ApiError::ApiResponse(message)
if message == &format!("Album {album_id} not found (404)")
)
}
/// True for errors worth retrying with backoff (issue #467): transport
/// problems (timeout/connect/reset), 5xx server errors, and 429 rate
/// limiting. Terminal errors — a real 404 `TrackUnavailable`, auth or
@@ -81,3 +93,23 @@ impl ApiError {
}
pub type Result<T> = std::result::Result<T, ApiError>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn album_unavailable_recognises_only_the_exact_get_album_404() {
assert!(ApiError::ApiResponse("Album old-id not found (404)".into())
.is_album_unavailable("old-id"));
assert!(
!ApiError::ApiResponse("get_album(old-id) status 500".into())
.is_album_unavailable("old-id")
);
assert!(
!ApiError::ApiResponse("Album another-id not found (404)".into())
.is_album_unavailable("old-id")
);
assert!(!ApiError::OfflineMode.is_album_unavailable("old-id"));
}
}
+18
View File
@@ -70,6 +70,10 @@ Rectangle {
// Explicit catalog withdrawal. Absence/false means the producer made no
// unavailability claim. A complete offline copy keeps the album live.
property bool qobuzUnavailable: false
// Library tombstones opt in to release replacement. Kept separate from
// qobuzUnavailable because a missing local/server source also uses the
// card's pulled presentation but has no Qobuz release to search for.
property bool replacementAffordance: false
property int cacheStatus: 0
readonly property bool pulled: root.qobuzUnavailable
readonly property bool pulledDead: root.pulled && root.cacheStatus !== 3
@@ -352,6 +356,10 @@ Rectangle {
m.push({ "label": root.isFavorite ? t("Remove from Library", r) : t("Add to Library", r),
"icon": root.isFavorite ? "heart-filled" : "heart", "action": "favorite" })
}
if (root.replacementAffordance && root.pulled) {
m.push({ "label": t("Look for better replacement", r),
"icon": "search", "action": "find-release" })
}
if (root.catalogAffordances && !root.pulled) {
// QoL round: the album page's container + offline actions, on the
// card. `catalogAffordances` is the catalog-id guarantee (the
@@ -402,6 +410,16 @@ Rectangle {
// denormalized snapshot and a file:// cache path is dead on any other
// machine, the same reason the pin payload uses it.
if (a === "favorite") { root.toggleFavorite(); return }
if (a === "find-release") {
QbzTrackReplace.openRelease(JSON.stringify({
"targetKind": "album",
"albumId": root.albumId || "",
"albumTitle": root.title || "",
"artist": root.artist || "",
"albumArtist": root.artist || ""
}))
return
}
if (a === "add-playlist") {
if (root.localMode)
// The bulk "album" scope resolves a local group key to its
+28 -4
View File
@@ -28,6 +28,9 @@ Rectangle {
property string artworkUrl: ""
// ADR-008 source glyph (local/Plex) — the Library All-feed arm.
property bool showSourceBadge: false
// Library injects its shared confirmation host. Other TrackCard surfaces
// never receive `releaseUnavailable`, so the callback remains unused.
property var confirmReleaseRemoval: null
color: "transparent"
@@ -298,6 +301,7 @@ Rectangle {
var t = QbzSession.tr
var r = QbzSession.trRev
var m = []
var releaseGone = root.item.releaseUnavailable === true
if (!root.pulledDead) {
m.push({ "label": t("Play", r), "icon": "play-fill", "action": "play" })
m.push({ "label": t("Play next", r), "icon": "list-start", "action": "next" })
@@ -305,10 +309,16 @@ Rectangle {
m.push({ "label": t("Add to queue", r), "icon": "list-end", "action": "queue" })
}
if (root.item.artistId) m.push({ "label": t("Go to artist", r), "icon": "user", "action": "go-artist" })
if (root.item.albumId) m.push({ "label": t("Go to album", r), "icon": "disc", "action": "go-album" })
if (!root.pulledDead)
m.push({ "label": root.favorite ? t("Remove from Library", r) : t("Add to Library", r),
"icon": root.favorite ? "heart-filled" : "heart", "action": "favorite" })
if (root.item.albumId && !releaseGone)
m.push({ "label": t("Go to album", r), "icon": "disc", "action": "go-album" })
m.push({ "label": root.favorite ? t("Remove from Library", r) : t("Add to Library", r),
"icon": root.favorite ? "heart-filled" : "heart", "action": "favorite" })
if (releaseGone) {
m.push({ "label": t("Look for better replacement", r),
"icon": "search", "action": "find-release" })
m.push({ "label": t("Remove all favorites from this release", r),
"icon": "trash-2", "action": "remove-release-favorites" })
}
return m
}
function trackAction(a) {
@@ -322,5 +332,19 @@ Rectangle {
else if (a === "go-artist") QbzArtist.openArtist(root.item.artistId)
else if (a === "go-album") QbzAlbum.openAlbum(root.item.albumId)
else if (a === "favorite") root.toggleFavorite()
else if (a === "find-release") QbzTrackReplace.openRelease(JSON.stringify({
"targetKind": "track",
"albumId": root.item.albumId || "",
"albumTitle": root.item.album || "",
"trackId": root.item.id || "",
"trackTitle": root.item.title || "",
"artist": root.item.artist || root.item.albumArtist || "",
"albumArtist": root.item.albumArtist || root.item.artist || "",
"isrc": root.item.isrc || "",
"durationSecs": root.item.durationSecs || 0
}))
else if (a === "remove-release-favorites"
&& typeof root.confirmReleaseRemoval === "function")
root.confirmReleaseRemoval(root.item)
}
}
@@ -41,6 +41,9 @@ Item {
readonly property bool loading: doc.loading === true
readonly property bool applying: doc.applying === true
readonly property string selectedId: doc.selectedId || ""
readonly property string selectedAlbumId: doc.selectedAlbumId || ""
readonly property bool releaseMode: doc.mode === "release"
readonly property string targetKind: doc.targetKind || "playlist"
// The ONLY local state in the file: what the user has typed but not yet
// submitted. Everything else is Rust's document, so a republish (a late
@@ -86,8 +89,8 @@ Item {
Rectangle {
id: card
anchors.centerIn: parent
width: Math.min(parent.width - 80, 620)
height: Math.min(Math.max(420, panel.implicitHeight + 66), parent.height * 0.9)
width: Math.min(parent.width - 48, 760)
height: Math.min(parent.height - 48, 520)
radius: theme.radiusLg
color: theme.surfaceCard
border.width: 1
@@ -118,7 +121,9 @@ Item {
spacing: 3
Text {
width: parent.width
text: QbzSession.tr("Find available version", QbzSession.trRev)
text: root.releaseMode
? QbzSession.tr("Look for better replacement", QbzSession.trRev)
: QbzSession.tr("Find available version", QbzSession.trRev)
color: theme.textPrimary
font.pixelSize: theme.fontSection
font.weight: theme.weightSemibold
@@ -237,7 +242,7 @@ Item {
width: parent.width
// Fills whatever the card has left between the query row and
// the footer, so the list scrolls instead of the card growing.
height: Math.max(120, card.height - 72 - 1 - 67 - 66)
height: Math.max(120, card.height - 72 - 1 - 67 - 100)
QbzSpinner {
anchors.centerIn: parent
@@ -251,7 +256,9 @@ Item {
anchors.centerIn: parent
width: parent.width - 96
visible: !root.loading && root.rows.length === 0
text: QbzSession.tr("No available version found", QbzSession.trRev)
text: root.releaseMode
? QbzSession.tr("No replacement releases found", QbzSession.trRev)
: QbzSession.tr("No available version found", QbzSession.trRev)
color: theme.textMuted
font.pixelSize: theme.fontLink
horizontalAlignment: Text.AlignHCenter
@@ -276,7 +283,7 @@ Item {
required property var modelData
readonly property bool picked: root.selectedId === modelData.id
width: ListView.view ? ListView.view.width : 0
height: 56
height: 64
radius: theme.radiusSm
color: picked ? theme.surfaceElevated
: (candArea.containsMouse ? theme.surfaceHover : "transparent")
@@ -295,8 +302,8 @@ Item {
// normal first frame, not a failure.
Rectangle {
anchors.verticalCenter: parent.verticalCenter
width: 40
height: 40
width: 46
height: 46
radius: 3
color: theme.surfaceElevated
clip: true
@@ -378,8 +385,11 @@ Item {
Text {
width: parent.width
text: (cand.modelData.artist || "")
+ ((cand.modelData.album || "") !== ""
? " · " + cand.modelData.album : "")
+ (root.releaseMode
? (((cand.modelData.year || "") !== "")
? " · " + cand.modelData.year : "")
: (((cand.modelData.album || "") !== "")
? " · " + cand.modelData.album : ""))
color: theme.textMuted
font.pixelSize: theme.fontLegal
elide: Text.ElideRight
@@ -401,7 +411,7 @@ Item {
}
Text {
anchors.verticalCenter: parent.verticalCenter
text: cand.modelData.duration || ""
text: root.releaseMode ? "" : (cand.modelData.duration || "")
color: theme.textMuted
font.pixelSize: theme.fontLegal
}
@@ -422,57 +432,84 @@ Item {
}
// --- Footer, pinned to the card bottom ---------------------------
Rectangle {
Item {
id: footer
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: footerRow.top
anchors.bottomMargin: 16
height: 1
color: theme.borderSubtle
}
// What the swap will DO to the playlist, said before it is done. The
// reference silently appended; this one takes the dead row's slot, and
// when the reposition call fails the toast says so instead.
Text {
anchors.left: parent.left
anchors.leftMargin: 24
anchors.right: footerRow.left
anchors.rightMargin: 12
anchors.verticalCenter: footerRow.verticalCenter
visible: root.rows.length > 0
text: QbzSession.tr("The replacement takes the unavailable track's place in the playlist.",
QbzSession.trRev)
color: theme.textMuted
font.pixelSize: theme.fontLegal
wrapMode: Text.WordWrap
elide: Text.ElideRight
}
Row {
id: footerRow
anchors.right: parent.right
anchors.rightMargin: 24
anchors.bottom: parent.bottom
anchors.bottomMargin: 16
spacing: 12
height: 100
SettingsButton {
anchors.verticalCenter: parent.verticalCenter
text: QbzSession.tr("Cancel", QbzSession.trRev)
btnHeight: 34
minWidth: 0
enabled: !root.applying
onClicked: QbzTrackReplace.close()
Rectangle {
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
height: 1
color: theme.borderSubtle
}
// The single accent confirm (ADR-008). Disabled until something is
// selected — there is no in-body error state to fall back on.
QbzPrimaryButton {
anchors.verticalCenter: parent.verticalCenter
btnHeight: 34
label: root.applying
? QbzSession.tr("Replacing...", QbzSession.trRev)
: QbzSession.tr("Replace", QbzSession.trRev)
btnEnabled: !root.applying && !root.loading && root.selectedId !== ""
onClicked: QbzTrackReplace.apply()
// State the write separately from the action row. This keeps the
// disclosure readable after the shared third button is added.
Text {
anchors.left: parent.left
anchors.leftMargin: 24
anchors.right: parent.right
anchors.rightMargin: 24
anchors.top: parent.top
anchors.topMargin: 9
visible: root.rows.length > 0
text: root.releaseMode
? (root.targetKind === "album"
? QbzSession.tr("The selected release replaces the unavailable album favorite.",
QbzSession.trRev)
: QbzSession.tr("The matching track from the selected release replaces the unavailable favorite.",
QbzSession.trRev))
: QbzSession.tr("The replacement takes the unavailable track's place in the playlist.",
QbzSession.trRev)
color: theme.textMuted
font.pixelSize: theme.fontLegal
elide: Text.ElideRight
}
Row {
id: footerRow
anchors.right: parent.right
anchors.rightMargin: 24
anchors.bottom: parent.bottom
anchors.bottomMargin: 14
spacing: 10
SettingsButton {
anchors.verticalCenter: parent.verticalCenter
text: QbzSession.tr("Cancel", QbzSession.trRev)
btnHeight: 34
minWidth: 0
enabled: !root.applying
onClicked: QbzTrackReplace.close()
}
SettingsButton {
anchors.verticalCenter: parent.verticalCenter
text: QbzSession.tr("Open album", QbzSession.trRev)
btnHeight: 34
minWidth: 0
enabled: !root.applying && !root.loading
&& root.selectedAlbumId !== ""
onClicked: QbzTrackReplace.openSelectedAlbum()
}
// The single accent mutation (ADR-008). Open album remains a
// neutral inspection action and never writes.
QbzPrimaryButton {
anchors.verticalCenter: parent.verticalCenter
btnHeight: 34
label: root.releaseMode
? (root.applying
? QbzSession.tr("Replacing favorite...", QbzSession.trRev)
: QbzSession.tr("Replace in Library", QbzSession.trRev))
: (root.applying
? QbzSession.tr("Replacing...", QbzSession.trRev)
: QbzSession.tr("Replace", QbzSession.trRev))
btnEnabled: !root.applying && !root.loading && root.selectedId !== ""
onClicked: QbzTrackReplace.apply()
}
}
}
}
+53 -4
View File
@@ -76,6 +76,7 @@ Rectangle {
}
property string activeTab: "all"
property string pendingReleaseRemovalId: ""
readonly property var settingsDoc: {
try { return JSON.parse(QbzBridge.settingsJson) }
@@ -1014,6 +1015,7 @@ Rectangle {
// seed.
function trackMenuModel(item, favorite, pulledDead) {
var m = []
var releaseGone = item.releaseUnavailable === true
if (!pulledDead) {
m.push({ "label": QbzSession.tr("Play", QbzSession.trRev), "icon": "play-fill", "action": "play" })
m.push({ "label": QbzSession.tr("Play next", QbzSession.trRev), "icon": "list-start", "action": "next" })
@@ -1021,12 +1023,26 @@ Rectangle {
m.push({ "label": QbzSession.tr("Add to queue", QbzSession.trRev), "icon": "list-end", "action": "queue" })
}
if (item.artistId !== "") m.push({ "label": QbzSession.tr("Go to artist", QbzSession.trRev), "icon": "user", "action": "go-artist" })
if (item.albumId !== "") m.push({ "label": QbzSession.tr("Go to album", QbzSession.trRev), "icon": "disc", "action": "go-album" })
if (!pulledDead)
m.push({ "label": favorite ? QbzSession.tr("Remove from Library", QbzSession.trRev) : QbzSession.tr("Add to Library", QbzSession.trRev),
"icon": favorite ? "heart-filled" : "heart", "action": "favorite" })
if (item.albumId !== "" && !releaseGone)
m.push({ "label": QbzSession.tr("Go to album", QbzSession.trRev), "icon": "disc", "action": "go-album" })
// A dead favourite is still a favourite. Suppressing this row was the
// bug: it made the tombstone impossible to remove.
m.push({ "label": favorite ? QbzSession.tr("Remove from Library", QbzSession.trRev) : QbzSession.tr("Add to Library", QbzSession.trRev),
"icon": favorite ? "heart-filled" : "heart", "action": "favorite" })
if (releaseGone) {
m.push({ "label": QbzSession.tr("Look for better replacement", QbzSession.trRev),
"icon": "search", "action": "find-release" })
m.push({ "label": QbzSession.tr("Remove all favorites from this release", QbzSession.trRev),
"icon": "trash-2", "action": "remove-release-favorites" })
}
return m
}
function askRemoveReleaseFavorites(item) {
if (!item || (item.albumId || "") === "")
return
root.pendingReleaseRemovalId = item.albumId
releaseRemovalConfirm.open()
}
// Takes the ROW, not the item — "favorite" has to go through the row's
// own property (a write to `item.isFavorite` notifies nothing).
function trackAction(row, a) {
@@ -1041,6 +1057,18 @@ Rectangle {
else if (a === "go-artist") QbzArtist.openArtist(item.artistId)
else if (a === "go-album") QbzAlbum.openAlbum(item.albumId)
else if (a === "favorite") row.toggleFavorite()
else if (a === "find-release") QbzTrackReplace.openRelease(JSON.stringify({
"targetKind": "track",
"albumId": item.albumId || "",
"albumTitle": item.album || "",
"trackId": item.id || "",
"trackTitle": item.title || "",
"artist": item.artist || item.albumArtist || "",
"albumArtist": item.albumArtist || item.artist || "",
"isrc": item.isrc || "",
"durationSecs": item.durationSecs || 0
}))
else if (a === "remove-release-favorites") root.askRemoveReleaseFavorites(item)
}
// ============================ view ===================================
@@ -1635,4 +1663,25 @@ Rectangle {
anchorTop: 62
anchorRight: 32
}
// Release-wide cleanup is destructive enough to confirm: it can remove an
// album heart plus several track hearts in one server batch. Mounted after
// every view overlay so declaration order and QbzConfirmModal's own z=3100
// keep it above the feed and filter popup.
QbzConfirmModal {
id: releaseRemovalConfirm
anchors.fill: parent
title: QbzSession.tr("Remove all favorites from this release?", QbzSession.trRev)
body: QbzSession.tr("Remove the album and every track from this release from your Library?",
QbzSession.trRev)
confirmLabel: QbzSession.tr("Remove", QbzSession.trRev)
danger: true
onConfirmed: {
var albumId = root.pendingReleaseRemovalId
root.pendingReleaseRemovalId = ""
if (albumId !== "")
QbzLibrary.libraryRemoveReleaseFavorites(albumId)
}
onCancelled: root.pendingReleaseRemovalId = ""
}
}
@@ -97,6 +97,8 @@ Item {
isPinned: cell.item.isPinned
qobuzUnavailable: cell.item.qobuzUnavailable === true
|| cell.item.sourceUnavailable === true
replacementAffordance: cell.item.source === "qobuz"
&& cell.item.qobuzUnavailable === true
cacheStatus: cell.item.cacheStatus !== undefined
? cell.item.cacheStatus : 0
// The pin payload's display snapshot: the REMOTE url, never
@@ -143,6 +145,9 @@ Item {
item: cell.item
artSource: cell.view.artMap[cell.item.artKey] || ""
showSourceBadge: cell.view.showLocal
confirmReleaseRemoval: function (item) {
cell.view.askRemoveReleaseFavorites(item)
}
}
}
Component {
@@ -80,6 +80,11 @@ Rectangle {
// its favorite entry instead of being left with a permanent tombstone.
m.push({ "label": feedRow.favorite ? t("Remove from Library", r) : t("Add to Library", r),
"icon": feedRow.favorite ? "heart-filled" : "heart", "action": "favorite" })
if (feedRow.item.source === "qobuz"
&& feedRow.item.qobuzUnavailable === true) {
m.push({ "label": t("Look for better replacement", r),
"icon": "search", "action": "find-release" })
}
return m
}
function albumAction(action) {
@@ -88,6 +93,13 @@ Rectangle {
if (action === "open") QbzAlbum.openAlbum(feedRow.item.id)
else if (action === "play") QbzPlayer.playAlbum(feedRow.item.id)
else if (action === "favorite") feedRow.toggleFavorite()
else if (action === "find-release") QbzTrackReplace.openRelease(JSON.stringify({
"targetKind": "album",
"albumId": feedRow.item.id || "",
"albumTitle": feedRow.item.title || "",
"artist": feedRow.item.artist || "",
"albumArtist": feedRow.item.artist || ""
}))
}
// Settle + rollback + cross-surface walk. `artKey` IS
// `library_qt::feed_key(kind, id)`, the very key the signal carries —
+10
View File
@@ -76,6 +76,12 @@ pub mod qbz_library_bridge {
#[qinvokable]
fn library_toggle_favorite(self: Pin<&mut QbzLibrary>, kind: QString, id: QString);
/// Confirmed Library action: remove the album heart and every track
/// heart belonging to one withdrawn Qobuz release. Downloads and
/// purchase entitlements are untouched.
#[qinvokable]
fn library_remove_release_favorites(self: Pin<&mut QbzLibrary>, album_id: QString);
/// LibraryView row play (PARITY-DEBT #5). `visible_ids_json` is the
/// JSON array of the track ids the view is CURRENTLY rendering, in
/// render order; `clicked_id` is the row that was hit. The Slint
@@ -260,6 +266,10 @@ impl qbz_library_bridge::QbzLibrary {
crate::library_toggle_favorite(kind.to_string(), id.to_string());
}
pub fn library_remove_release_favorites(self: Pin<&mut Self>, album_id: QString) {
crate::library_remove_release_favorites(album_id.to_string());
}
pub fn library_play_visible(
self: Pin<&mut Self>,
visible_ids_json: QString,
+319 -7
View File
@@ -36,6 +36,7 @@ use std::collections::{HashMap, HashSet};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::Instant;
use futures_util::stream::{self, StreamExt};
use qbz_app::settings::local_favorites::{LocalFavItem, LocalFavoritesService, DB_FILE_NAME};
use qbz_app::shell::AppRuntime;
use qbz_app::user_data::UserDataPaths;
@@ -64,13 +65,26 @@ pub struct FeedItem {
pub album: String,
#[serde(rename = "albumId")]
pub album_id: String,
/// Track rows only: the release's MAIN artist name. `artist` is the
/// per-track performer and can differ on classical/features; replacement
/// release ranking must compare like with like.
#[serde(
default,
rename = "albumArtist",
skip_serializing_if = "String::is_empty"
)]
pub album_artist: String,
/// Track rows only: the id of the ALBUM's main artist, beside the
/// performer id in `artist_id`. A favourited track is a member of an
/// artist's "In library" tab through EITHER — `artist_id` alone is the
/// track's performer, which on features, interpreters and re-credited
/// remasters is not the artist whose page is open (issue #737 round,
/// contract §5). Skipped when empty so album/artist rows pay nothing.
#[serde(default, rename = "albumArtistId", skip_serializing_if = "String::is_empty")]
#[serde(
default,
rename = "albumArtistId",
skip_serializing_if = "String::is_empty"
)]
pub album_artist_id: String,
#[serde(rename = "imageUrl")]
pub image_url: String,
@@ -109,6 +123,15 @@ pub struct FeedItem {
skip_serializing_if = "std::ops::Not::not"
)]
pub not_streamable: bool,
/// This track's owning Qobuz release is itself confirmed withdrawn. False
/// also covers UNKNOWN: transport/auth/parse failures must not hide a
/// navigation action or expose destructive release-wide cleanup.
#[serde(
default,
rename = "releaseUnavailable",
skip_serializing_if = "std::ops::Not::not"
)]
pub release_unavailable: bool,
/// The persisted local-favorite snapshot no longer resolves in the
/// active Local Library. Kept separate from `not_streamable`: a Qobuz
/// withdrawal may still play from a complete download, while a missing
@@ -127,6 +150,13 @@ pub struct FeedItem {
pub genre: String,
pub year: String,
pub duration: String,
/// Matching evidence carried by Qobuz favourite-track rows. Omitted for
/// every other feed kind so the high-cardinality mixed document only pays
/// for data the replacement picker can actually use.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub isrc: String,
#[serde(default, rename = "durationSecs", skip_serializing_if = "is_zero_u32")]
pub duration_secs: u32,
pub explicit: bool,
#[serde(rename = "playlistOwned")]
pub playlist_owned: bool,
@@ -156,6 +186,10 @@ fn is_false(value: &bool) -> bool {
!*value
}
fn is_zero_u32(value: &u32) -> bool {
*value == 0
}
fn is_zero_i32(value: &i32) -> bool {
*value == 0
}
@@ -436,6 +470,8 @@ fn map_track(track: Track) -> FeedItem {
// while it was still there.
let not_streamable = !track.is_streamable();
let track_id = track.id.to_string();
let isrc = track.isrc.clone().unwrap_or_default();
let duration_secs = track.duration;
let cache_status = if crate::offline_qt::is_cached(&track_id) {
3
} else {
@@ -454,7 +490,7 @@ fn map_track(track: Track) -> FeedItem {
let album = track
.album
.as_ref()
.map(|a| a.title.clone())
.map(|a| crate::album_qt::format_album_title(&a.title, a.version.as_deref()))
.unwrap_or_default();
let album_id = track
.album
@@ -473,6 +509,12 @@ fn map_track(track: Track) -> FeedItem {
.and_then(|a| a.artist.as_ref())
.map(|x| x.id.to_string())
.unwrap_or_default();
let album_artist = track
.album
.as_ref()
.and_then(|a| a.artist.as_ref())
.map(|x| x.name.clone())
.unwrap_or_default();
let (artist, artist_id) = track
.performer
.map(|p| (p.name, p.id.to_string()))
@@ -488,9 +530,12 @@ fn map_track(track: Track) -> FeedItem {
artist_id,
album,
album_id,
album_artist,
album_artist_id,
genre,
duration: mmss(track.duration),
duration: mmss(duration_secs),
isrc,
duration_secs,
quality_tier: home_qt::quality_tier_from_depth(track.maximum_bit_depth).to_string(),
quality_detail: home_qt::quality_detail_from_parts(
track.maximum_bit_depth,
@@ -742,6 +787,124 @@ async fn ready_offline_album_track_counts() -> std::collections::HashMap<String,
counts
}
/// Three-way release verdict. `Unknown` is deliberately not a bool: collapsing
/// a terse embedded album or a failed probe into `Unavailable` would hide a
/// valid Go-to-album action and expose a destructive bulk action on a network
/// failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ReleaseAvailability {
Available,
Unavailable,
Unknown,
}
fn embedded_release_availability(track: &Track) -> ReleaseAvailability {
let Some(album) = track.album.as_ref() else {
return ReleaseAvailability::Unknown;
};
match album.streamable {
Some(true) => ReleaseAvailability::Available,
Some(false) if album.is_upcoming() => ReleaseAvailability::Available,
Some(false) => ReleaseAvailability::Unavailable,
None => ReleaseAvailability::Unknown,
}
}
/// A successful `/album/get` can prove a release-wide withdrawal either at
/// the album level or through a non-empty track list in which every row is an
/// explicit, non-upcoming withdrawal. Absence is never proof.
fn fetched_release_unavailable(album: &Album) -> bool {
if qbz_models::types::upcoming_now(None, album.release_date_stream.as_deref()) {
return false;
}
if album.streamable == Some(false) {
return true;
}
album
.tracks
.as_ref()
.map(|tracks| {
!tracks.items.is_empty()
&& tracks
.items
.iter()
.all(|track| track.streamable == Some(false) && !track.is_upcoming())
})
.unwrap_or(false)
}
async fn probe_release_availability(
runtime: &Arc<AppRuntime<LoggingAdapter>>,
album_id: String,
) -> (String, ReleaseAvailability) {
let verdict = match runtime.core().get_album(&album_id).await {
Ok(album) if fetched_release_unavailable(&album) => ReleaseAvailability::Unavailable,
Ok(_) => ReleaseAvailability::Available,
Err(qbz_core::CoreError::Api(error)) if error.is_album_unavailable(&album_id) => {
ReleaseAvailability::Unavailable
}
Err(error) => {
log::warn!(
"[qbz-qt] library release availability probe {album_id} failed; keeping it unknown: {error}"
);
ReleaseAvailability::Unknown
}
};
(album_id, verdict)
}
/// Resolve release-wide availability only for favourite tracks already known
/// to be unavailable. Explicit embedded answers cost no request; unknown album
/// ids are de-duplicated and probed with a bounded fan-out.
async fn unavailable_release_ids(
runtime: &Arc<AppRuntime<LoggingAdapter>>,
tracks: &[Track],
) -> HashSet<String> {
let mut verdicts: HashMap<String, ReleaseAvailability> = HashMap::new();
for track in tracks.iter().filter(|track| !track.is_streamable()) {
let Some(album) = track.album.as_ref().filter(|album| !album.id.is_empty()) else {
continue;
};
let incoming = embedded_release_availability(track);
verdicts
.entry(album.id.clone())
.and_modify(|current| {
// A positive availability signal wins over a contradictory
// tombstone signal; refusing valid navigation is the less
// recoverable mistake. Otherwise preserve unavailable over
// unknown.
*current = match (*current, incoming) {
(ReleaseAvailability::Available, _) | (_, ReleaseAvailability::Available) => {
ReleaseAvailability::Available
}
(ReleaseAvailability::Unavailable, _)
| (_, ReleaseAvailability::Unavailable) => ReleaseAvailability::Unavailable,
_ => ReleaseAvailability::Unknown,
}
})
.or_insert(incoming);
}
let to_probe: Vec<String> = verdicts
.iter()
.filter(|(_, verdict)| **verdict == ReleaseAvailability::Unknown)
.map(|(id, _)| id.clone())
.collect();
let probed = stream::iter(to_probe)
.map(|album_id| probe_release_availability(runtime, album_id))
.buffer_unordered(4)
.collect::<Vec<_>>()
.await;
for (id, verdict) in probed {
verdicts.insert(id, verdict);
}
verdicts
.into_iter()
.filter_map(|(id, verdict)| (verdict == ReleaseAvailability::Unavailable).then_some(id))
.collect()
}
/// The whole library load: fan out, normalize, merge (library_all.rs
/// ordering semantics), compute the tab counts.
pub async fn load_library(runtime: &Arc<AppRuntime<LoggingAdapter>>) -> Result<usize, String> {
@@ -853,9 +1016,11 @@ pub async fn load_library(runtime: &Arc<AppRuntime<LoggingAdapter>>) -> Result<u
let mut feed: Vec<FeedItem> = Vec::new();
let tracks: Vec<Track> = parse_items(raw_tracks, "track");
let unavailable_releases = unavailable_release_ids(runtime, &tracks).await;
let n = tracks.len();
for (i, item) in tracks.into_iter().map(map_track).enumerate() {
let mut item = item;
for (i, track) in tracks.into_iter().enumerate() {
let mut item = map_track(track);
item.release_unavailable = unavailable_releases.contains(&item.album_id);
item.added_rank = rank(i, n);
feed.push(item);
}
@@ -1353,7 +1518,10 @@ async fn fetch_purchases(
a.image.best().cloned().unwrap_or_default(),
a.title.clone(),
a.id.clone(),
a.artist.as_ref().map(|x| x.id.to_string()).unwrap_or_default(),
a.artist
.as_ref()
.map(|x| x.id.to_string())
.unwrap_or_default(),
)
})
.unwrap_or_default();
@@ -1543,6 +1711,44 @@ pub async fn toggle_favorite(
}
}
/// Every server-side favourite owned by one Qobuz release: its album heart and
/// the hearts on its member tracks. Purchase representatives can carry a heart
/// too, so membership is read from `is_favorite` as well as the favourites
/// group. `(kind,id)` de-duplication prevents a favourite+purchase duplicate
/// from issuing the same delete twice.
fn release_favorite_targets_from(feed: &[FeedItem], album_id: &str) -> Vec<(String, String)> {
let mut seen = HashSet::new();
let mut targets = Vec::new();
for item in feed.iter().filter(|item| {
item.source == "qobuz"
&& (item.is_favorite || item.group == "favorites")
&& ((item.kind == "album" && item.id == album_id)
|| (item.kind == "track" && item.album_id == album_id))
}) {
let key = (item.kind.clone(), item.id.clone());
if seen.insert(key.clone()) {
targets.push(key);
}
}
targets
}
pub(crate) fn release_favorite_targets(album_id: &str) -> Vec<(String, String)> {
let mut targets = with_library(|data| release_favorite_targets_from(&data.feed, album_id))
.unwrap_or_default();
// A freshly-set album heart can be in the O(1) cache before a Library row
// has been fetched/reconciled. Include it without taking the LIBRARY lock
// recursively through `is_favorite`.
if crate::fav_cache_qt::is_favorite("album", album_id)
&& !targets
.iter()
.any(|(kind, id)| kind == "album" && id == album_id)
{
targets.push(("album".into(), album_id.into()));
}
targets
}
/// The playlist heart is a qbz-LOCAL flag, never a Qobuz favorite — the
/// favorites endpoints have no `playlist_ids` param (inferred OpenAPI
/// §Favorites lists five, none of them playlists), which is exactly why the
@@ -2369,6 +2575,106 @@ mod tests {
}
}
#[test]
fn embedded_release_classification_is_three_way_and_future_safe() {
let unknown: Track =
serde_json::from_str(r#"{"id":1,"streamable":false,"album":{"id":"a","title":"A"}}"#)
.unwrap();
assert_eq!(
embedded_release_availability(&unknown),
ReleaseAvailability::Unknown
);
let live: Track = serde_json::from_str(
r#"{"id":1,"streamable":false,"album":{"id":"a","title":"A","streamable":true}}"#,
)
.unwrap();
assert_eq!(
embedded_release_availability(&live),
ReleaseAvailability::Available
);
let gone: Track = serde_json::from_str(
r#"{"id":1,"streamable":false,"album":{"id":"a","title":"A","streamable":false}}"#,
)
.unwrap();
assert_eq!(
embedded_release_availability(&gone),
ReleaseAvailability::Unavailable
);
let future: Track = serde_json::from_str(
r#"{"id":1,"streamable":false,"album":{"id":"a","title":"A","streamable":false,"release_date_stream":"2999-01-01"}}"#,
)
.unwrap();
assert_eq!(
embedded_release_availability(&future),
ReleaseAvailability::Available
);
}
#[test]
fn fetched_release_needs_positive_withdrawal_evidence() {
let missing_signal: Album = serde_json::from_str(r#"{"id":"a","title":"A"}"#).unwrap();
assert!(!fetched_release_unavailable(&missing_signal));
let album_false: Album =
serde_json::from_str(r#"{"id":"a","title":"A","streamable":false}"#).unwrap();
assert!(fetched_release_unavailable(&album_false));
let all_tracks_false: Album = serde_json::from_str(
r#"{"id":"a","title":"A","streamable":true,"tracks":{"items":[{"id":1,"streamable":false},{"id":2,"streamable":false}],"total":2}}"#,
)
.unwrap();
assert!(fetched_release_unavailable(&all_tracks_false));
let one_live: Album = serde_json::from_str(
r#"{"id":"a","title":"A","streamable":true,"tracks":{"items":[{"id":1,"streamable":false},{"id":2,"streamable":true}],"total":2}}"#,
)
.unwrap();
assert!(!fetched_release_unavailable(&one_live));
}
#[test]
fn release_cleanup_targets_album_and_tracks_once_but_not_purchases_alone() {
let mut album_favorite = album("old-release");
album_favorite.source = "qobuz".into();
album_favorite.group = "favorites".into();
album_favorite.is_favorite = true;
let mut album_purchase_duplicate = album_favorite.clone();
album_purchase_duplicate.group = "purchases".into();
let mut favorite_track = track("11", "One");
favorite_track.source = "qobuz".into();
favorite_track.group = "favorites".into();
favorite_track.album_id = "old-release".into();
favorite_track.is_favorite = true;
let mut purchase_only = track("12", "Two");
purchase_only.source = "qobuz".into();
purchase_only.group = "purchases".into();
purchase_only.album_id = "old-release".into();
purchase_only.is_favorite = false;
let targets = release_favorite_targets_from(
&[
album_favorite,
album_purchase_duplicate,
favorite_track,
purchase_only,
],
"old-release",
);
assert_eq!(
targets,
vec![
("album".to_string(), "old-release".to_string()),
("track".to_string(), "11".to_string()),
]
);
}
/// A server album key must route to the LOCAL detail view.
///
/// The regression this pins: `open_album` asks `is_local_feed_id`, which
@@ -2631,7 +2937,13 @@ mod tests {
// --- Artist page "In library" membership (#737 round, contract §3) ------
fn owned(kind: &str, id: &str, group: &str, artist_id: &str, album_artist_id: &str) -> FeedItem {
fn owned(
kind: &str,
id: &str,
group: &str,
artist_id: &str,
album_artist_id: &str,
) -> FeedItem {
FeedItem {
kind: kind.into(),
group: group.into(),
+73 -1
View File
@@ -525,8 +525,9 @@ mod tray_windows;
// gating, so this mod line is not platform-gated.
mod media_controls_qt;
use std::collections::HashSet;
use std::pin::Pin;
use std::sync::{Arc, Mutex, OnceLock};
use std::sync::{Arc, LazyLock, Mutex, OnceLock};
use cxx_qt::CxxQtThread;
use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QString, QUrl};
@@ -3184,6 +3185,77 @@ pub(crate) fn library_toggle_favorite(kind: String, id: String) {
});
}
/// One release-wide removal at a time per album id. The confirmation modal
/// closes before the async writes settle, so without a backend latch the same
/// menu action could issue duplicate deletes while the first batch is live.
static RELEASE_FAVORITE_REMOVALS: LazyLock<Mutex<HashSet<String>>> =
LazyLock::new(|| Mutex::new(HashSet::new()));
pub(crate) fn library_remove_release_favorites(album_id: String) {
if album_id.is_empty() {
return;
}
{
let mut in_flight = RELEASE_FAVORITE_REMOVALS
.lock()
.unwrap_or_else(|error| error.into_inner());
if !in_flight.insert(album_id.clone()) {
return;
}
}
let runtime = app();
spawn(async move {
let targets = library_qt::release_favorite_targets(&album_id);
let mut removed: Vec<(String, String)> = Vec::new();
let mut failed = 0usize;
for (kind, id) in targets {
match runtime.core().remove_favorite(&kind, &id).await {
Ok(()) => {
library_qt::set_feed_favorite(&kind, &id, false);
fav_cache_qt::set(&kind, &id, false);
removed.push((kind, id));
}
Err(error) => {
failed += 1;
log::error!(
"[qbz-qt] remove release favourites {album_id}: {kind}:{id} failed: {error}"
);
}
}
}
// Reconcile every confirmed server write before publishing, then
// replace the Library model at most once. A purchase representative
// stays and merely loses its heart.
let mut membership_changed = false;
for (kind, id) in &removed {
membership_changed |=
library_qt::reconcile_qobuz_favorite(&runtime, kind, id, false).await;
emit_library_favorite(kind, id, false);
}
if membership_changed {
publish_library_document();
}
RELEASE_FAVORITE_REMOVALS
.lock()
.unwrap_or_else(|error| error.into_inner())
.remove(&album_id);
if removed.is_empty() && failed == 0 {
toast_qt::info(qbz_i18n::t("No favorites from this release to remove"));
} else if failed == 0 {
toast_qt::success(qbz_i18n::t("Favorites removed from this release"));
} else if removed.is_empty() {
toast_qt::error(qbz_i18n::t("Could not remove favorites from this release"));
} else {
toast_qt::error(qbz_i18n::t("Some favorites could not be removed"));
}
});
}
/// A heart's write LANDED with `value`: reconcile the cached feed (a fresh
/// Qobuz favourite joins it, a cleared one leaves; local hearts have their
/// own row pair), fan the settled value out through `emit_library_favorite`,
+19
View File
@@ -56,6 +56,12 @@ pub mod qbz_track_replace_bridge {
#[qinvokable]
fn open(self: Pin<&mut QbzTrackReplace>, payload_json: QString);
/// Library > All track/album tombstone: open the same ranked picker in
/// album-search mode. The footer then offers non-mutating navigation
/// and an explicit add-first favourite replacement.
#[qinvokable]
fn open_release(self: Pin<&mut QbzTrackReplace>, payload_json: QString);
/// Re-run the search with an edited query (the reference's one good
/// idea — the "title artist" guess is often not the right words).
#[qinvokable]
@@ -65,6 +71,11 @@ pub mod qbz_track_replace_bridge {
#[qinvokable]
fn select(self: Pin<&mut QbzTrackReplace>, track_id: QString);
/// Non-mutating third action: open the selected candidate's album in
/// either playlist-track or Library-release mode.
#[qinvokable]
fn open_selected_album(self: Pin<&mut QbzTrackReplace>);
/// Perform the swap: add -> reposition -> remove. See
/// `track_replace_qt.rs`'s header for why that order and why neither
/// failure path rolls anything back.
@@ -123,6 +134,10 @@ impl qbz_track_replace_bridge::QbzTrackReplace {
crate::track_replace_qt::open(&payload_json.to_string());
}
pub fn open_release(self: Pin<&mut Self>, payload_json: QString) {
crate::track_replace_qt::open_release(&payload_json.to_string());
}
pub fn search(self: Pin<&mut Self>, query: QString) {
crate::track_replace_qt::search(&query.to_string());
}
@@ -131,6 +146,10 @@ impl qbz_track_replace_bridge::QbzTrackReplace {
crate::track_replace_qt::select(&track_id.to_string());
}
pub fn open_selected_album(self: Pin<&mut Self>) {
crate::track_replace_qt::open_selected_album();
}
pub fn apply(self: Pin<&mut Self>) {
crate::track_replace_qt::apply();
}
+608 -13
View File
@@ -52,13 +52,16 @@
use std::sync::{LazyLock, Mutex};
use cxx_qt_lib::QString;
use qbz_models::Track;
use qbz_models::{Album, Track};
use qbz_playlist_import::{rank_candidates, ImportTrack};
use serde::{Deserialize, Serialize};
/// The reference's limit, and the matcher's own `SEARCH_LIMIT`. Twenty rows is
/// as many as a human will actually read.
const SEARCH_LIMIT: u32 = 20;
const RELEASE_TITLE_WEIGHT: f32 = 0.75;
const RELEASE_ARTIST_WEIGHT: f32 = 0.25;
const RELEASE_MIN_SCORE: f32 = 0.65;
// ---------------------------------------------------------------------------
// D3 — the session memory of tracks that died under the player
@@ -150,9 +153,36 @@ pub struct DeadRow {
pub duration_secs: u64,
}
/// Withdrawn release opened from Library > All. Album search chooses the new
/// release; the old track evidence lets the explicit primary action resolve
/// and replace the corresponding favourite inside that release.
#[derive(Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReleaseSeed {
/// `track` replaces one favourite with its equivalent inside the chosen
/// release; `album` replaces the withdrawn release favourite itself.
pub target_kind: String,
pub album_id: String,
pub album_title: String,
#[serde(default)]
pub track_id: String,
#[serde(default)]
pub track_title: String,
#[serde(default)]
pub artist: String,
#[serde(default)]
pub album_artist: String,
#[serde(default)]
pub isrc: String,
#[serde(default)]
pub duration_secs: u64,
}
#[derive(Clone, Default, Serialize)]
pub struct CandidateRow {
pub id: String,
#[serde(rename = "albumId")]
pub album_id: String,
pub title: String,
pub artist: String,
pub album: String,
@@ -165,6 +195,9 @@ pub struct CandidateRow {
#[serde(rename = "qualityDetail")]
pub quality_detail: String,
pub duration: String,
/// Release mode uses this for the catalog year. Empty for playlist-track
/// candidates so the existing row layout remains unchanged.
pub year: String,
pub score: f32,
/// ISRC-identical to the dead row: the SAME recording under a new id. The
/// modal says so, because it is the difference between a certainty and a
@@ -180,6 +213,10 @@ pub struct CandidateRow {
#[derive(Clone, Default, Serialize)]
pub struct ReplaceDoc {
pub open: bool,
/// `track` (playlist mutation) or `release` (Library discovery/navigation).
pub mode: String,
#[serde(rename = "targetKind")]
pub target_kind: String,
pub loading: bool,
pub applying: bool,
pub query: String,
@@ -190,6 +227,8 @@ pub struct ReplaceDoc {
pub candidates: Vec<CandidateRow>,
#[serde(rename = "selectedId")]
pub selected_id: String,
#[serde(rename = "selectedAlbumId")]
pub selected_album_id: String,
#[serde(rename = "hasExact")]
pub has_exact: bool,
}
@@ -197,9 +236,11 @@ pub struct ReplaceDoc {
#[derive(Default)]
struct ReplaceState {
open: bool,
mode: String,
loading: bool,
applying: bool,
dead: DeadRow,
release: ReleaseSeed,
query: String,
candidates: Vec<CandidateRow>,
selected_id: String,
@@ -220,13 +261,35 @@ fn with_state<R>(f: impl FnOnce(&mut ReplaceState) -> R) -> R {
fn publish() {
let doc = with_state(|st| ReplaceDoc {
open: st.open,
mode: st.mode.clone(),
target_kind: if st.mode == "release" {
st.release.target_kind.clone()
} else {
"playlist".into()
},
loading: st.loading,
applying: st.applying,
query: st.query.clone(),
dead_title: st.dead.title.clone(),
dead_artist: st.dead.artist.clone(),
dead_title: if st.mode == "release" && st.release.target_kind == "track" {
st.release.track_title.clone()
} else if st.mode == "release" {
st.release.album_title.clone()
} else {
st.dead.title.clone()
},
dead_artist: if st.mode == "release" {
st.release.artist.clone()
} else {
st.dead.artist.clone()
},
candidates: st.candidates.clone(),
selected_id: st.selected_id.clone(),
selected_album_id: st
.candidates
.iter()
.find(|candidate| candidate.id == st.selected_id)
.map(|candidate| candidate.album_id.clone())
.unwrap_or_default(),
has_exact: st.candidates.iter().any(|c| c.exact),
});
let json = serde_json::to_string(&doc).unwrap_or_else(|_| "{}".into());
@@ -258,9 +321,11 @@ pub(crate) fn open(payload_json: &str) {
let query = format!("{} {}", dead.title, dead.artist);
let generation = with_state(|st| {
st.open = true;
st.mode = "track".into();
st.loading = true;
st.applying = false;
st.dead = dead.clone();
st.release = ReleaseSeed::default();
st.query = query.clone();
// A stale list would show the PREVIOUS row's candidates under this
// row's title for as long as the search takes.
@@ -274,37 +339,95 @@ pub(crate) fn open(payload_json: &str) {
crate::spawn(async move { run_search(dead, query, generation).await });
}
/// Open the same ranked-candidate surface in Library RELEASE mode. Unlike the
/// playlist path this does not swap a track: the selected result is opened and
/// all favourite cleanup stays behind its own explicit action.
pub(crate) fn open_release(payload_json: &str) {
let release: ReleaseSeed = match serde_json::from_str(payload_json) {
Ok(seed) => seed,
Err(error) => {
log::warn!("[qbz-qt] release replace: unreadable payload: {error}");
return;
}
};
let valid_target = match release.target_kind.as_str() {
"album" => true,
"track" => !release.track_id.is_empty() && !release.track_title.trim().is_empty(),
_ => false,
};
if release.album_id.is_empty() || release.album_title.trim().is_empty() || !valid_target {
log::warn!("[qbz-qt] release replace: invalid album/track replacement payload, ignored");
return;
}
// The query is intentionally the edition-stripped TITLE ALONE. Artist is
// a ranking signal, not a word that can push the right release beyond the
// API's first 20 hits.
let normalized = qbz_external_reco::normalize_catalog_name(&release.album_title);
let query = if normalized.is_empty() {
release.album_title.trim().to_string()
} else {
normalized
};
let generation = with_state(|st| {
st.open = true;
st.mode = "release".into();
st.loading = true;
st.applying = false;
st.dead = DeadRow::default();
st.release = release.clone();
st.query = query.clone();
st.candidates.clear();
st.selected_id.clear();
st.generation = st.generation.wrapping_add(1);
st.generation
});
publish();
crate::spawn(async move { run_release_search(release, query, generation).await });
}
/// The query is editable and re-searchable (the reference's one good idea).
pub(crate) fn search(query: &str) {
let query = query.trim().to_string();
if query.is_empty() {
return;
}
let Some((dead, generation)) = with_state(|st| {
let Some((mode, dead, release, generation)) = with_state(|st| {
if !st.open || st.applying {
return None;
}
st.query = query.clone();
st.loading = true;
st.generation = st.generation.wrapping_add(1);
Some((st.dead.clone(), st.generation))
Some((
st.mode.clone(),
st.dead.clone(),
st.release.clone(),
st.generation,
))
}) else {
return;
};
publish();
crate::spawn(async move { run_search(dead, query, generation).await });
crate::spawn(async move {
if mode == "release" {
run_release_search(release, query, generation).await;
} else {
run_search(dead, query, generation).await;
}
});
}
/// Pick a candidate. An id that is not in the list is ignored rather than
/// stored: the apply path trusts this field, and a selection the user cannot
/// see is exactly the state the same-id guard exists to keep out.
pub(crate) fn select(track_id: &str) {
pub(crate) fn select(candidate_id: &str) {
let changed = with_state(|st| {
if st.applying || !st.candidates.iter().any(|c| c.id == track_id) {
if st.applying || !st.candidates.iter().any(|c| c.id == candidate_id) {
return false;
}
st.selected_id = track_id.to_string();
st.selected_id = candidate_id.to_string();
true
});
if changed {
@@ -312,12 +435,36 @@ pub(crate) fn select(track_id: &str) {
}
}
/// Non-mutating inspection path shared by both picker modes. Release rows use
/// their own id; playlist-track rows carry their embedded album id. A terse
/// search result with no album id leaves the button disabled in QML and is
/// guarded again here.
pub(crate) fn open_selected_album() {
let album_id = with_state(|st| {
if st.applying || !st.open {
return String::new();
}
st.candidates
.iter()
.find(|candidate| candidate.id == st.selected_id)
.map(|candidate| candidate.album_id.clone())
.unwrap_or_default()
});
if album_id.is_empty() {
return;
}
close();
crate::open_album(album_id);
}
pub(crate) fn close() {
with_state(|st| {
st.open = false;
st.mode.clear();
st.loading = false;
st.applying = false;
st.dead = DeadRow::default();
st.release = ReleaseSeed::default();
st.query.clear();
st.candidates.clear();
st.selected_id.clear();
@@ -451,6 +598,155 @@ async fn run_search(dead: DeadRow, query: String, generation: u64) {
}
}
/// Release search deliberately uses `/album/search` rather than trying to
/// infer a new album id from track hits. The user asked to choose among
/// editions, so one row must equal one release.
async fn run_release_search(release: ReleaseSeed, query: String, generation: u64) {
let runtime = crate::app();
let found = runtime
.core()
.search_albums(&query, SEARCH_LIMIT, 0, None)
.await
.map(|page| page.items)
.unwrap_or_else(|error| {
log::warn!("[qbz-qt] release replace: search '{query}' failed: {error}");
Vec::new()
});
let rows: Vec<CandidateRow> = rank_release_candidates(&release, &found)
.into_iter()
.map(|(album, score)| map_release_candidate(&album, score))
.collect();
let art_urls: Vec<String> = rows
.iter()
.filter(|row| row.art_path.is_empty() && !row.art_url.is_empty())
.map(|row| row.art_url.clone())
.collect();
let landed = with_state(|st| {
if !st.open || st.mode != "release" || st.generation != generation {
return false;
}
st.selected_id = rows.first().map(|row| row.id.clone()).unwrap_or_default();
st.candidates = rows;
st.loading = false;
true
});
if !landed {
return;
}
publish();
if !art_urls.is_empty() {
crate::artwork_qt::download_missing(art_urls).await;
let still_ours = with_state(|st| {
if !st.open || st.mode != "release" || st.generation != generation {
return false;
}
for row in st.candidates.iter_mut() {
if row.art_path.is_empty() && !row.art_url.is_empty() {
row.art_path = crate::artwork_qt::cached_path(&row.art_url);
}
}
true
});
if still_ours {
publish();
}
}
}
fn release_quality(album: &Album) -> (u32, f64) {
let bit_depth = album
.audio_info
.as_ref()
.and_then(|info| info.maximum_bit_depth)
.or(album.maximum_bit_depth)
.unwrap_or(0);
let sample_rate = album
.audio_info
.as_ref()
.and_then(|info| info.maximum_sampling_rate)
.or(album.maximum_sampling_rate)
.unwrap_or(0.0);
(bit_depth, sample_rate)
}
/// Best semantic match first; quality only breaks a score tie. The sort is
/// stable so Qobuz relevance remains the final tie-breaker.
fn rank_release_candidates(seed: &ReleaseSeed, candidates: &[Album]) -> Vec<(Album, f32)> {
let seed_artist = if seed.album_artist.trim().is_empty() {
&seed.artist
} else {
&seed.album_artist
};
let mut ranked: Vec<(Album, f32)> = candidates
.iter()
.filter(|album| album.id != seed.album_id && album.is_streamable())
.map(|album| {
let title = crate::album_qt::format_album_title(&album.title, album.version.as_deref());
let title_score = qbz_external_reco::catalog_similarity(&seed.album_title, &title);
let artist_score =
qbz_external_reco::catalog_similarity(seed_artist, &album.artist.name);
let score = title_score * RELEASE_TITLE_WEIGHT
+ if seed_artist.trim().is_empty() {
0.0
} else {
artist_score * RELEASE_ARTIST_WEIGHT
};
(album.clone(), score)
})
.collect();
fn bucket(score: f32) -> i32 {
(score * 100.0).round() as i32
}
ranked.sort_by(|(a, a_score), (b, b_score)| {
let (a_depth, a_rate) = release_quality(a);
let (b_depth, b_rate) = release_quality(b);
bucket(*b_score)
.cmp(&bucket(*a_score))
.then_with(|| b_depth.cmp(&a_depth))
.then_with(|| b_rate.total_cmp(&a_rate))
});
ranked
}
fn map_release_candidate(album: &Album, score: f32) -> CandidateRow {
let art_url = album.image.best().cloned().unwrap_or_default();
let (bit_depth, sample_rate) = release_quality(album);
let date = album
.dates
.as_ref()
.and_then(|dates| {
dates
.original
.as_deref()
.or(dates.stream.as_deref())
.or(dates.download.as_deref())
})
.or(album.release_date_original.as_deref());
CandidateRow {
id: album.id.clone(),
album_id: album.id.clone(),
title: crate::album_qt::format_album_title(&album.title, album.version.as_deref()),
artist: album.artist.name.clone(),
album: String::new(),
art_path: crate::artwork_qt::cached_path(&art_url),
art_url,
quality_tier: crate::playlist_qt::tier((bit_depth > 0).then_some(bit_depth)).to_string(),
quality_detail: crate::home_qt::quality_detail_from_parts(
(bit_depth > 0).then_some(bit_depth),
(sample_rate > 0.0).then_some(sample_rate),
),
duration: String::new(),
year: qbz_text_utils::dates::release_label(date),
score,
exact: false,
weak: score < RELEASE_MIN_SCORE,
}
}
fn map_candidate(track: &Track, score: f32, exact: bool) -> CandidateRow {
let album = track.album.as_ref();
let art_url = album
@@ -458,6 +754,7 @@ fn map_candidate(track: &Track, score: f32, exact: bool) -> CandidateRow {
.unwrap_or_default();
CandidateRow {
id: track.id.to_string(),
album_id: album.map(|album| album.id.clone()).unwrap_or_default(),
// The version suffix is load-bearing HERE above anywhere else: "(2011
// Remaster)" is often the entire difference between the candidates.
title: match track.version.as_ref().filter(|v| !v.is_empty()) {
@@ -478,6 +775,7 @@ fn map_candidate(track: &Track, score: f32, exact: bool) -> CandidateRow {
track.maximum_sampling_rate,
),
duration: crate::playlist_qt::mmss(track.duration),
year: String::new(),
score,
exact,
// An ISRC hit is never weak, whatever the text says about it.
@@ -489,20 +787,31 @@ fn map_candidate(track: &Track, score: f32, exact: bool) -> CandidateRow {
// Apply: ADD -> REPOSITION -> REMOVE
// ---------------------------------------------------------------------------
/// See the module header for why that order and why neither failure path rolls
/// anything back.
/// See the module header for the playlist transaction. Release mode uses the
/// same safety invariant for favourites: add the live replacement first and
/// only then remove the unavailable heart.
pub(crate) fn apply() {
let Some((dead, selected)) = with_state(|st| {
let Some((mode, dead, release, selected)) = with_state(|st| {
if st.applying || st.selected_id.is_empty() || !st.open {
return None;
}
st.applying = true;
Some((st.dead.clone(), st.selected_id.clone()))
Some((
st.mode.clone(),
st.dead.clone(),
st.release.clone(),
st.selected_id.clone(),
))
}) else {
return;
};
publish();
if mode == "release" {
apply_library_replacement(release, selected);
return;
}
let (Ok(pid), Ok(new_id), Ok(dead_ptid)) = (
dead.playlist_id.parse::<u64>(),
selected.parse::<u64>(),
@@ -581,6 +890,167 @@ pub(crate) fn apply() {
});
}
fn release_track_source(seed: &ReleaseSeed) -> ImportTrack {
ImportTrack {
title: seed.track_title.clone(),
artist: seed.artist.clone(),
album: (!seed.album_title.is_empty()).then(|| seed.album_title.clone()),
duration_ms: (seed.duration_secs > 0).then(|| seed.duration_secs * 1000),
isrc: (!seed.isrc.is_empty()).then(|| seed.isrc.clone()),
provider_id: None,
provider_url: None,
}
}
/// Resolve the old recording inside the release the human selected. Album
/// track payloads can omit `performer`; fill only that absent evidence from the
/// album's main artist before using the shared matcher. ISRC equality remains
/// its 1.0 short-circuit. A text-only guess below the importer's own confidence
/// floor is refused.
fn matching_track_in_release(seed: &ReleaseSeed, album: &Album) -> Option<(Track, f32, bool)> {
let old_id = seed.track_id.parse::<u64>().unwrap_or(0);
let mut candidates = album.tracks.as_ref()?.items.clone();
candidates.retain(|track| track.id != old_id && track.is_streamable());
for track in &mut candidates {
if track.performer.is_none() && !album.artist.name.is_empty() {
track.performer = Some(album.artist.clone());
}
}
let source = release_track_source(seed);
let (track, score) = rank_candidates(&source, &candidates).into_iter().next()?;
let exact = !seed.isrc.trim().is_empty()
&& track
.isrc
.as_deref()
.map(|isrc| seed.isrc.eq_ignore_ascii_case(isrc))
.unwrap_or(false);
(exact || score >= qbz_playlist_import::MIN_MATCH_SCORE).then_some((track, score, exact))
}
fn apply_library_replacement(seed: ReleaseSeed, album_id: String) {
let runtime = crate::app();
crate::spawn(async move {
if seed.target_kind == "album" {
log::info!(
"[qbz-qt] library album replace: {} -> {}",
seed.album_id,
album_id
);
replace_library_favorite(&runtime, "album", &seed.album_id, &album_id).await;
return;
}
let album = match runtime.core().get_album(&album_id).await {
Ok(album) => album,
Err(error) => {
log::error!(
"[qbz-qt] library track replace: selected album {album_id} failed: {error}"
);
stop_applying();
crate::toast_qt::error(qbz_i18n::t("Could not open the selected release"));
return;
}
};
let Some((replacement, score, exact)) = matching_track_in_release(&seed, &album) else {
log::warn!(
"[qbz-qt] library track replace: no confident match for {} in album {album_id}",
seed.track_id
);
stop_applying();
crate::toast_qt::error(qbz_i18n::t(
"Could not find a matching track in this release",
));
return;
};
let new_id = replacement.id.to_string();
if new_id == seed.track_id {
log::error!(
"[qbz-qt] library track replace: selected release resolved to dead id {new_id}"
);
stop_applying();
crate::toast_qt::error(qbz_i18n::t(
"Could not find a matching track in this release",
));
return;
}
log::info!(
"[qbz-qt] library track replace: {} -> {} via album {} (score={score:.3}, exact_isrc={exact})",
seed.track_id,
new_id,
album_id
);
replace_library_favorite(&runtime, "track", &seed.track_id, &new_id).await;
});
}
/// Add-first favourite swap shared by album and track tombstones. Every server
/// success settles the feed/cache independently; a failed removal deliberately
/// keeps both hearts because deleting the new live one would be a second write
/// exposed to the same failure.
async fn replace_library_favorite(
runtime: &std::sync::Arc<qbz_app::shell::AppRuntime<qbz_core::LoggingAdapter>>,
kind: &str,
old_id: &str,
new_id: &str,
) {
if old_id == new_id {
log::error!("[qbz-qt] library {kind} replace: old and new id are both {old_id}");
stop_applying();
crate::toast_qt::error(qbz_i18n::t("Could not add the replacement favorite"));
return;
}
// Add first. A failed create leaves the old favourite untouched.
if let Err(error) = runtime.core().add_favorite(kind, new_id).await {
log::error!("[qbz-qt] library {kind} replace: add favourite {new_id} failed: {error}");
stop_applying();
crate::toast_qt::error(qbz_i18n::t("Could not add the replacement favorite"));
return;
}
crate::fav_cache_qt::set(kind, new_id, true);
crate::library_qt::set_feed_favorite(kind, new_id, true);
let mut membership_changed =
crate::library_qt::reconcile_qobuz_favorite(runtime, kind, new_id, true).await;
crate::emit_library_favorite(kind, new_id, true);
let old_removed = match runtime.core().remove_favorite(kind, old_id).await {
Ok(()) => {
crate::fav_cache_qt::set(kind, old_id, false);
crate::library_qt::set_feed_favorite(kind, old_id, false);
membership_changed |=
crate::library_qt::reconcile_qobuz_favorite(runtime, kind, old_id, false).await;
crate::emit_library_favorite(kind, old_id, false);
if kind == "track" {
if let Ok(old_track_id) = old_id.parse::<u64>() {
session_unavailable::forget(old_track_id);
}
}
true
}
Err(error) => {
log::error!(
"[qbz-qt] library {kind} replace: replacement {new_id} landed but removing {old_id} failed: {error}"
);
false
}
};
if membership_changed {
crate::publish_library_document();
}
close();
if old_removed {
crate::toast_qt::success(qbz_i18n::t("Favorite replaced"));
} else {
crate::toast_qt::error(qbz_i18n::t(
"The replacement was added, but the unavailable favorite could not be removed",
));
}
}
/// Move the freshly-appended replacement into the dead row's slot.
///
/// Returns whether the move actually happened. EVERY exit is a `false` plus a
@@ -658,3 +1128,128 @@ async fn reposition(
}
true
}
#[cfg(test)]
mod tests {
use super::*;
fn album(id: &str, title: &str, artist: &str, depth: u32, rate: f64) -> Album {
serde_json::from_value(serde_json::json!({
"id": id,
"title": title,
"artist": { "id": 1, "name": artist },
"streamable": true,
"maximum_bit_depth": depth,
"maximum_sampling_rate": rate
}))
.expect("album fixture")
}
#[test]
fn release_query_cleanup_strips_edition_noise_and_leading_punctuation() {
assert_eq!(
qbz_external_reco::normalize_catalog_name("...And Justice for All (Remastered 2018)"),
"and justice for all"
);
}
#[test]
fn release_ranking_filters_old_and_unavailable_ids_and_uses_quality_for_ties() {
let seed = ReleaseSeed {
target_kind: "album".into(),
album_id: "old".into(),
album_title: "...And Justice for All (Remastered 2018)".into(),
artist: "Metallica".into(),
album_artist: "Metallica".into(),
..Default::default()
};
let same = album("old", "...And Justice for All", "Metallica", 24, 192.0);
let mut unavailable = album("gone", "...And Justice for All", "Metallica", 24, 192.0);
unavailable.streamable = Some(false);
let cd = album("cd", "...And Justice for All", "Metallica", 16, 44.1);
let hires = album("hires", "...And Justice for All", "Metallica", 24, 96.0);
let wrong_artist = album(
"tribute",
"...And Justice for All",
"Various Artists",
24,
192.0,
);
let ranked = rank_release_candidates(&seed, &[same, unavailable, cd, wrong_artist, hires]);
let ids: Vec<&str> = ranked.iter().map(|(album, _)| album.id.as_str()).collect();
assert_eq!(ids, vec!["hires", "cd", "tribute"]);
}
#[test]
fn release_candidate_keeps_version_year_and_quality_as_decision_aids() {
let mut candidate = album("new", "Album", "Artist", 24, 96.0);
candidate.version = Some("Remastered 2024".into());
candidate.release_date_original = Some("1988-09-07".into());
let row = map_release_candidate(&candidate, 1.0);
assert_eq!(row.title, "Album (Remastered 2024)");
assert_eq!(row.artist, "Artist");
assert!(!row.year.is_empty());
assert!(!row.quality_detail.is_empty());
}
#[test]
fn selected_release_resolves_the_live_equivalent_track() {
let seed = ReleaseSeed {
target_kind: "track".into(),
album_id: "old-album".into(),
album_title: "Album (Remastered 2018)".into(),
track_id: "10".into(),
track_title: "One (Remastered 2018)".into(),
artist: "Metallica".into(),
album_artist: "Metallica".into(),
isrc: "US-OLD-123".into(),
duration_secs: 447,
};
let mut selected = album("new-album", "Album", "Metallica", 24, 96.0);
selected.tracks = Some(qbz_models::TracksContainer {
items: vec![serde_json::from_value(serde_json::json!({
"id": 20,
"title": "One",
"isrc": "US-OLD-123",
"duration": 447,
"streamable": true
}))
.unwrap()],
total: 1,
});
let (track, score, exact) = matching_track_in_release(&seed, &selected).unwrap();
assert_eq!(track.id, 20);
assert_eq!(score, 1.0);
assert!(exact);
}
#[test]
fn selected_release_refuses_an_unrelated_track() {
let seed = ReleaseSeed {
target_kind: "track".into(),
album_id: "old-album".into(),
album_title: "Album".into(),
track_id: "10".into(),
track_title: "One".into(),
artist: "Metallica".into(),
album_artist: "Metallica".into(),
..Default::default()
};
let mut selected = album("new-album", "Album", "Metallica", 24, 96.0);
selected.tracks = Some(qbz_models::TracksContainer {
items: vec![serde_json::from_value(serde_json::json!({
"id": 21,
"title": "Completely Different",
"performer": { "id": 2, "name": "Someone Else" },
"duration": 120,
"streamable": true
}))
.unwrap()],
total: 1,
});
assert!(matching_track_in_release(&seed, &selected).is_none());
}
}