merge: add-to-playlist redesign — membership index, picker, local drag

cc
This commit is contained in:
vicrodh committed 2026-08-31 03:35:35 -06:00
commit 4c4647bdf4
43 files changed
+3092 -203

No files matched your search

+16
View File
@@ -1500,6 +1500,22 @@ impl<A: FrontendAdapter + Send + Sync + 'static> QbzCore<A> {
.map_err(CoreError::Api)
}
/// Lightweight membership fetch: one playlist's track IDS only
/// (`playlist/get?extra=track_ids`). The membership hydrator's probe —
/// no Track objects, no pagination.
pub async fn get_playlist_track_ids(
&self,
playlist_id: u64,
) -> Result<qbz_models::PlaylistWithTrackIds, CoreError> {
let client = self.client.read().await;
let client = client.as_ref().ok_or(CoreError::NotInitialized)?;
client
.get_playlist_track_ids(playlist_id)
.await
.map_err(CoreError::Api)
}
/// Check how many of `track_ids` are already in the Qobuz playlist
/// `playlist_id`. Mirrors Tauri's `v2_check_playlist_duplicates`
/// (commands_v2/playlists.rs): fetch the playlist's existing track ids and
@@ -6257,3 +6257,15 @@ msgstr "Filterbereiche anzeigen"
msgid "Hide filter panels"
msgstr "Filterbereiche ausblenden"
msgid "Already in"
msgstr "Bereits in"
msgid "Playlist index updating..."
msgstr "Playlist-Index wird aktualisiert..."
msgid "{} of {}"
msgstr "{} von {}"
msgid "Last playlist"
msgstr "Letzte Playlist"
@@ -1877,3 +1877,15 @@ msgstr "Show filter panels"
msgid "Hide filter panels"
msgstr "Hide filter panels"
msgid "Already in"
msgstr "Already in"
msgid "Playlist index updating..."
msgstr "Playlist index updating..."
msgid "{} of {}"
msgstr "{} of {}"
msgid "Last playlist"
msgstr "Last playlist"
@@ -6263,3 +6263,15 @@ msgstr "Mostrar los paneles de filtros"
msgid "Hide filter panels"
msgstr "Ocultar los paneles de filtros"
msgid "Already in"
msgstr "Ya está en"
msgid "Playlist index updating..."
msgstr "Actualizando el índice de playlists..."
msgid "{} of {}"
msgstr "{} de {}"
msgid "Last playlist"
msgstr "Última playlist"
@@ -6255,3 +6255,15 @@ msgstr "Afficher les panneaux de filtres"
msgid "Hide filter panels"
msgstr "Masquer les panneaux de filtres"
msgid "Already in"
msgstr "Déjà dans"
msgid "Playlist index updating..."
msgstr "Mise à jour de l'index des playlists..."
msgid "{} of {}"
msgstr "{} sur {}"
msgid "Last playlist"
msgstr "Dernière playlist"
@@ -6239,3 +6239,15 @@ msgstr "フィルターパネルを表示"
msgid "Hide filter panels"
msgstr "フィルターパネルを非表示"
msgid "Already in"
msgstr "追加済み"
msgid "Playlist index updating..."
msgstr "プレイリストの索引を更新中..."
msgid "{} of {}"
msgstr "{} / {}"
msgid "Last playlist"
msgstr "前回のプレイリスト"
@@ -6245,3 +6245,15 @@ msgstr "Filterpanelen tonen"
msgid "Hide filter panels"
msgstr "Filterpanelen verbergen"
msgid "Already in"
msgstr "Al in"
msgid "Playlist index updating..."
msgstr "Playlist-index wordt bijgewerkt..."
msgid "{} of {}"
msgstr "{} van {}"
msgid "Last playlist"
msgstr "Laatste playlist"
@@ -6255,3 +6255,15 @@ msgstr "Mostrar os painéis de filtros"
msgid "Hide filter panels"
msgstr "Ocultar os painéis de filtros"
msgid "Already in"
msgstr "Já está em"
msgid "Playlist index updating..."
msgstr "Atualizando o índice de playlists..."
msgid "{} of {}"
msgstr "{} de {}"
msgid "Last playlist"
msgstr "Última playlist"
@@ -6275,3 +6275,15 @@ msgstr "Показать панели фильтров"
msgid "Hide filter panels"
msgstr "Скрыть панели фильтров"
msgid "Already in"
msgstr "Уже в"
msgid "Playlist index updating..."
msgstr "Индекс плейлистов обновляется..."
msgid "{} of {}"
msgstr "{} из {}"
msgid "Last playlist"
msgstr "Последний плейлист"
+186 -5
View File
@@ -264,6 +264,11 @@ impl LibraryDatabase {
CREATE INDEX IF NOT EXISTS idx_playlist_local_tracks_playlist
ON playlist_local_tracks(qobuz_playlist_id);
-- The Add-to-Playlist picker asks the inverse question — "which
-- playlists hold this track" (playlist_membership.rs).
CREATE INDEX IF NOT EXISTS idx_playlist_local_tracks_track
ON playlist_local_tracks(local_track_id, qobuz_playlist_id);
-- Plex tracks added to playlists. Kept in its own table because
-- Plex tracks live on a remote server and have a TEXT rating key,
-- not the i64 filesystem id used by local_tracks. No foreign key
@@ -282,6 +287,30 @@ impl LibraryDatabase {
CREATE INDEX IF NOT EXISTS idx_playlist_plex_tracks_playlist
ON playlist_plex_tracks(qobuz_playlist_id);
CREATE INDEX IF NOT EXISTS idx_playlist_plex_tracks_key
ON playlist_plex_tracks(plex_rating_key, qobuz_playlist_id);
-- Jellyfin/Subsonic tracks added to playlists (2026-08-30). Their
-- library rows are media-cache projections with no local_tracks
-- rowid, so they get their own sidecar keyed by the server item
-- id — the plex_rating_key pattern, source-qualified because two
-- protocols share the table.
CREATE TABLE IF NOT EXISTS playlist_remote_tracks (
id INTEGER PRIMARY KEY,
qobuz_playlist_id INTEGER NOT NULL,
source TEXT NOT NULL,
item_id TEXT NOT NULL,
position INTEGER NOT NULL,
added_at INTEGER NOT NULL,
UNIQUE(qobuz_playlist_id, source, item_id)
);
CREATE INDEX IF NOT EXISTS idx_playlist_remote_tracks_playlist
ON playlist_remote_tracks(qobuz_playlist_id);
CREATE INDEX IF NOT EXISTS idx_playlist_remote_tracks_item
ON playlist_remote_tracks(source, item_id, qobuz_playlist_id);
-- Custom track order per playlist (user-defined arrangement)
CREATE TABLE IF NOT EXISTS playlist_track_custom_order (
id INTEGER PRIMARY KEY,
@@ -4995,6 +5024,104 @@ impl LibraryDatabase {
Ok(())
}
/// Attach a Jellyfin/Subsonic track to a Qobuz playlist by its server
/// item id — the Plex pattern, source-qualified. Re-adding MOVES the row
/// to the new slot rather than duplicating it (INSERT OR REPLACE on the
/// UNIQUE key, edge E4).
pub fn add_remote_track_to_playlist(
&self,
qobuz_playlist_id: u64,
source: &str,
item_id: &str,
position: i32,
) -> Result<(), LibraryError> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
self.conn
.execute(
"INSERT OR REPLACE INTO playlist_remote_tracks
(qobuz_playlist_id, source, item_id, position, added_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![qobuz_playlist_id as i64, source, item_id, position, now],
)
.map_err(|e| {
LibraryError::Database(format!("Failed to add remote track to playlist: {}", e))
})?;
Ok(())
}
/// Remove a Jellyfin/Subsonic track from a playlist.
pub fn remove_remote_track_from_playlist(
&self,
qobuz_playlist_id: u64,
source: &str,
item_id: &str,
) -> Result<(), LibraryError> {
self.conn
.execute(
"DELETE FROM playlist_remote_tracks
WHERE qobuz_playlist_id = ?1 AND source = ?2 AND item_id = ?3",
params![qobuz_playlist_id as i64, source, item_id],
)
.map_err(|e| {
LibraryError::Database(format!(
"Failed to remove remote track from playlist: {}",
e
))
})?;
Ok(())
}
/// `(source, item_id, position)` of every remote sidecar row of one
/// playlist, position ASC.
pub fn get_playlist_remote_tracks_with_position(
&self,
qobuz_playlist_id: u64,
) -> Result<Vec<(String, String, i32)>, LibraryError> {
let mut stmt = self
.conn
.prepare(
"SELECT source, item_id, position FROM playlist_remote_tracks
WHERE qobuz_playlist_id = ?1
ORDER BY position ASC, added_at ASC, id ASC",
)
.map_err(|e| LibraryError::Database(format!("Failed to prepare query: {}", e)))?;
let rows = stmt
.query_map(params![qobuz_playlist_id as i64], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, i32>(2)?,
))
})
.map_err(|e| LibraryError::Database(format!("Failed to query: {}", e)))?;
let mut out = Vec::new();
for row in rows {
out.push(
row.map_err(|e| LibraryError::Database(format!("Failed to read row: {}", e)))?,
);
}
Ok(out)
}
/// Number of remote sidecar rows of one playlist.
pub fn get_playlist_remote_track_count(
&self,
qobuz_playlist_id: u64,
) -> Result<u32, LibraryError> {
self.conn
.query_row(
"SELECT COUNT(*) FROM playlist_remote_tracks WHERE qobuz_playlist_id = ?1",
params![qobuz_playlist_id as i64],
|row| row.get::<_, u32>(0),
)
.map_err(|e| LibraryError::Database(format!("Failed to count remote tracks: {}", e)))
}
/// Remove a Plex track from a playlist.
pub fn remove_plex_track_from_playlist(
&self,
@@ -5298,6 +5425,29 @@ impl LibraryDatabase {
*result.entry(playlist_id).or_insert(0) += count;
}
let mut remote_stmt = self
.conn
.prepare(
"SELECT qobuz_playlist_id, COUNT(*) as count
FROM playlist_remote_tracks
GROUP BY qobuz_playlist_id",
)
.map_err(|e| LibraryError::Database(format!("Failed to prepare query: {}", e)))?;
let remote_rows = remote_stmt
.query_map([], |row| {
let playlist_id: i64 = row.get(0)?;
let count: u32 = row.get(1)?;
Ok((playlist_id as u64, count))
})
.map_err(|e| LibraryError::Database(format!("Failed to query: {}", e)))?;
for row in remote_rows {
let (playlist_id, count) =
row.map_err(|e| LibraryError::Database(format!("Failed to read row: {}", e)))?;
*result.entry(playlist_id).or_insert(0) += count;
}
Ok(result)
}
@@ -5357,6 +5507,7 @@ impl LibraryDatabase {
) -> Result<i32, LibraryError> {
let local_count = self.get_playlist_local_track_count(qobuz_playlist_id)?;
let plex_count = self.get_playlist_plex_track_count(qobuz_playlist_id)?;
let remote_count = self.get_playlist_remote_track_count(qobuz_playlist_id)?;
let max_pos: Option<i32> = self
.conn
.query_row(
@@ -5366,6 +5517,9 @@ impl LibraryDatabase {
UNION ALL
SELECT MAX(position) AS p FROM playlist_plex_tracks
WHERE qobuz_playlist_id = ?1
UNION ALL
SELECT MAX(position) AS p FROM playlist_remote_tracks
WHERE qobuz_playlist_id = ?1
)",
params![qobuz_playlist_id as i64],
|row| row.get(0),
@@ -5373,7 +5527,7 @@ impl LibraryDatabase {
.map_err(|e| {
LibraryError::Database(format!("Failed to read max sidecar position: {}", e))
})?;
let count_based = (qobuz_track_count + local_count + plex_count) as i32;
let count_based = (qobuz_track_count + local_count + plex_count + remote_count) as i32;
Ok(count_based.max(max_pos.map(|p| p + 1).unwrap_or(0)))
}
@@ -5455,6 +5609,33 @@ impl LibraryDatabase {
rows.push(("plex", rowid, key, pos));
}
}
{
let mut stmt = self
.conn
.prepare(
"SELECT id, source || ':' || item_id, position FROM playlist_remote_tracks
WHERE qobuz_playlist_id = ?1
ORDER BY position ASC, added_at ASC, id ASC",
)
.map_err(|e| {
LibraryError::Database(format!("Failed to prepare heal query: {}", e))
})?;
let mapped = stmt
.query_map(params![qobuz_playlist_id as i64], |row| {
Ok((
row.get::<_, i64>(0)?,
row.get::<_, String>(1)?,
row.get::<_, i32>(2)?,
))
})
.map_err(|e| LibraryError::Database(format!("Failed to query heal rows: {}", e)))?;
for r in mapped {
let (rowid, key, pos) = r.map_err(|e| {
LibraryError::Database(format!("Failed to read heal row: {}", e))
})?;
rows.push(("remote", rowid, key, pos));
}
}
if rows.is_empty() {
return Ok(Vec::new());
}
@@ -5473,10 +5654,10 @@ impl LibraryDatabase {
let mut next = ((qobuz_track_count as i32) + sidecar_total as i32).max(max_pos + 1);
let mut healed = Vec::with_capacity(moves.len());
for (kind, rowid, reference, old) in moves {
let sql = if kind == "local" {
"UPDATE playlist_local_tracks SET position = ?1 WHERE id = ?2"
} else {
"UPDATE playlist_plex_tracks SET position = ?1 WHERE id = ?2"
let sql = match kind {
"local" => "UPDATE playlist_local_tracks SET position = ?1 WHERE id = ?2",
"plex" => "UPDATE playlist_plex_tracks SET position = ?1 WHERE id = ?2",
_ => "UPDATE playlist_remote_tracks SET position = ?1 WHERE id = ?2",
};
self.conn.execute(sql, params![next, rowid]).map_err(|e| {
LibraryError::Database(format!("Failed to heal sidecar position: {}", e))
+1
View File
@@ -37,6 +37,7 @@ pub mod local_playlists;
mod metadata;
mod models;
mod mount_info;
pub mod playlist_membership;
pub mod qobuz_playlist_snapshot;
pub mod reachability;
mod remote_tag_sidecar;
+40 -2
View File
@@ -23,11 +23,18 @@ pub fn is_local_playlist_id(id: &str) -> bool {
}
/// Track source inside a local playlist.
///
/// Jellyfin/Subsonic rows (2026-08-30) store the SERVER ITEM ID in the
/// `local_path` column — the same convention their library projection uses
/// for `file_path`: that column is "the source-native locator", not always a
/// filesystem path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LocalPlaylistTrackSource {
Qobuz,
Local,
Plex,
Jellyfin,
Subsonic,
}
impl LocalPlaylistTrackSource {
@@ -36,12 +43,16 @@ impl LocalPlaylistTrackSource {
Self::Qobuz => "qobuz",
Self::Local => "local",
Self::Plex => "plex",
Self::Jellyfin => "jellyfin",
Self::Subsonic => "subsonic",
}
}
fn parse(s: &str) -> Self {
match s {
"local" => Self::Local,
"plex" => Self::Plex,
"jellyfin" => Self::Jellyfin,
"subsonic" => Self::Subsonic,
_ => Self::Qobuz,
}
}
@@ -86,12 +97,15 @@ pub struct LocalPlaylistTrack {
pub added_at: i64,
}
/// Input for `add_tracks` — exactly one of the three refs per source.
/// Input for `add_tracks` — exactly one source-native ref per variant.
/// Jellyfin/Subsonic carry the server item id (stored in `local_path`).
#[derive(Debug, Clone)]
pub enum LocalPlaylistTrackInput {
Qobuz(u64),
Local(String),
Plex(String),
Jellyfin(String),
Subsonic(String),
}
fn now_ms() -> i64 {
@@ -154,6 +168,19 @@ pub fn init_schema(conn: &Connection) -> Result<()> {
CREATE INDEX IF NOT EXISTS idx_local_playlist_tracks_playlist
ON local_playlist_tracks(playlist_id, position);
-- Inverse direction for the Add-to-Playlist picker's containment
-- question (playlist_membership.rs). Partial: each row fills exactly
-- one of the three identity columns.
CREATE INDEX IF NOT EXISTS idx_local_playlist_tracks_qobuz
ON local_playlist_tracks(qobuz_track_id, playlist_id)
WHERE qobuz_track_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_local_playlist_tracks_path
ON local_playlist_tracks(local_path, playlist_id)
WHERE local_path IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_local_playlist_tracks_plex
ON local_playlist_tracks(plex_key, playlist_id)
WHERE plex_key IS NOT NULL;
"#,
)?;
// Additive migration (B3): DBs created before the favorite/hidden
@@ -331,7 +358,12 @@ fn hydrate_counts(conn: &Connection, p: &mut LocalPlaylist) -> Result<()> {
match LocalPlaylistTrackSource::parse(&source) {
LocalPlaylistTrackSource::Qobuz => p.qobuz_count = count,
LocalPlaylistTrackSource::Local => p.local_count = count,
LocalPlaylistTrackSource::Plex => p.plex_count = count,
// The three server-backed sources share one bucket: every
// consumer of these counts distinguishes "on this machine" from
// "needs a server", not server brands.
LocalPlaylistTrackSource::Plex
| LocalPlaylistTrackSource::Jellyfin
| LocalPlaylistTrackSource::Subsonic => p.plex_count += count,
}
p.track_count += count;
}
@@ -431,6 +463,12 @@ pub fn add_tracks(
LocalPlaylistTrackInput::Qobuz(id) => ("qobuz", Some(*id as i64), None, None),
LocalPlaylistTrackInput::Local(path) => ("local", None, Some(path.as_str()), None),
LocalPlaylistTrackInput::Plex(key) => ("plex", None, None, Some(key.as_str())),
LocalPlaylistTrackInput::Jellyfin(item) => {
("jellyfin", None, Some(item.as_str()), None)
}
LocalPlaylistTrackInput::Subsonic(item) => {
("subsonic", None, Some(item.as_str()), None)
}
};
let exists: bool = conn
.prepare(
@@ -0,0 +1,671 @@
//! The inverse membership question: WHICH playlists already hold this track?
//!
//! The playlist tables were all indexed forward (`playlist_id` leading);
//! the Add-to-Playlist picker asks the opposite direction. This module owns
//! the typed track reference at that boundary — replacing the loosely encoded
//! `"plex:<key>"` / `"<i64>"` strings — and the containment query across all
//! four membership stores:
//!
//! - `qobuz_playlist_snapshot_tracks` — Qobuz tracks in Qobuz playlists
//! (hydrated by the membership worker; honesty via `index_state`);
//! - `playlist_local_tracks` / `playlist_plex_tracks` — library/Plex sidecars
//! attached to Qobuz playlists (authoritative locally, complete by
//! construction: QBZ is their only writer);
//! - `local_playlist_tracks` — everything inside `local:` playlists (same:
//! locally authoritative).
//!
//! Identity notes. Plex rows are keyed by rating key (their merge keeps it
//! in `file_path`), Jellyfin/Subsonic rows by their source-qualified server
//! item id (`playlist_remote_tracks`, and `local_playlist_tracks.local_path`
//! under their own `source` value); both key spaces are scoped to the single
//! configured server per protocol, the same assumption the sidecar tables
//! have always made. Everything else that lives in the library is its
//! projected row (`track_id` + path).
use std::collections::{HashMap, HashSet};
use rusqlite::{Connection, Result};
/// One selected track at the picker/index boundary.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PlaylistTrackRef {
/// A Qobuz catalog track.
Qobuz(u64),
/// A library-projected row: a local file, or a Jellyfin/Subsonic track
/// (their playlist storage identity is the projection). `path` is the
/// `local_tracks.file_path` value local playlists key on;
/// `qobuz_track_id` is set for offline copies (`qobuz_download` rows),
/// which local playlists store as CATALOG ids while Qobuz-playlist
/// sidecars store the library row — containment must look both ways.
Library {
track_id: i64,
path: Option<String>,
qobuz_track_id: Option<u64>,
},
/// A Plex track by rating key.
Plex { rating_key: String },
/// A Jellyfin/Subsonic track by its server item id (their projected rows
/// carry it in `file_path`; playlists store it source-qualified).
Remote { source: String, item_id: String },
}
impl PlaylistTrackRef {
/// Build the ref for a library row the way the playlist writers key it:
/// Plex rows carry the rating key in `file_path`, Jellyfin/Subsonic rows
/// their server item id; every other source is the projected library row
/// itself (offline copies also carrying their catalog id).
pub fn from_library_row(
source: &str,
track_id: i64,
file_path: &str,
qobuz_track_id: Option<u64>,
) -> Self {
match source {
"plex" => Self::Plex {
rating_key: file_path.to_string(),
},
"jellyfin" | "subsonic" => Self::Remote {
source: source.to_string(),
item_id: file_path.to_string(),
},
_ => Self::Library {
track_id,
path: Some(file_path.to_string()),
qobuz_track_id: qobuz_track_id.filter(|_| source == "qobuz_download"),
},
}
}
}
/// A playlist that contains at least one of the selected refs.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ContainmentTarget {
Qobuz(u64),
Local(String),
}
#[derive(Debug, Clone)]
pub struct PlaylistContainment {
pub target: ContainmentTarget,
/// How many DISTINCT selected refs this playlist holds (the picker's
/// "N of M"). Duplicate rows inside a playlist count once.
pub contained: u32,
}
/// SQLite's default variable cap is 999; stay far under it.
const IN_CHUNK: usize = 400;
fn placeholders(n: usize) -> String {
let mut s = String::with_capacity(n * 2);
for i in 0..n {
if i > 0 {
s.push(',');
}
s.push('?');
}
s
}
/// Every writable playlist containing at least one of `refs`, with the
/// distinct-ref count. Qobuz targets come from the membership snapshot
/// restricted to OWNED, ACTIVE playlists (the strip offers add targets, and a
/// retired header must not resurrect there) plus the sidecar tables; `local:`
/// targets from `local_playlist_tracks`. Whether the Qobuz half may be
/// presented as definitive is `qobuz_playlist_snapshot::index_state`'s call,
/// not this function's.
pub fn playlists_containing(
conn: &Connection,
refs: &[PlaylistTrackRef],
) -> Result<Vec<PlaylistContainment>> {
// ordinal = position in `refs`; contained counts distinct ordinals.
let mut qobuz_ids: Vec<(i64, usize)> = Vec::new();
let mut lib_ids: Vec<(i64, usize)> = Vec::new();
let mut lib_paths: Vec<(&str, usize)> = Vec::new();
let mut plex_keys: Vec<(&str, usize)> = Vec::new();
let mut remote_items: Vec<(&str, &str, usize)> = Vec::new();
for (ordinal, r) in refs.iter().enumerate() {
match r {
PlaylistTrackRef::Qobuz(id) => qobuz_ids.push((*id as i64, ordinal)),
PlaylistTrackRef::Library {
track_id,
path,
qobuz_track_id,
} => {
lib_ids.push((*track_id, ordinal));
if let Some(p) = path {
lib_paths.push((p.as_str(), ordinal));
}
// Offline copies live in local playlists as catalog ids.
if let Some(qid) = qobuz_track_id {
qobuz_ids.push((*qid as i64, ordinal));
}
}
PlaylistTrackRef::Plex { rating_key } => plex_keys.push((rating_key.as_str(), ordinal)),
PlaylistTrackRef::Remote { source, item_id } => {
remote_items.push((source.as_str(), item_id.as_str(), ordinal))
}
}
}
let mut hits: HashMap<ContainmentTarget, HashSet<usize>> = HashMap::new();
let mut collect_qobuz = |rows: Vec<(i64, usize)>| {
for (pid, ordinal) in rows {
hits.entry(ContainmentTarget::Qobuz(pid as u64))
.or_default()
.insert(ordinal);
}
};
// Qobuz refs → snapshot membership of owned active playlists.
for chunk in qobuz_ids.chunks(IN_CHUNK) {
let sql = format!(
"SELECT t.qobuz_playlist_id, t.track_id
FROM qobuz_playlist_snapshot_tracks t
JOIN qobuz_playlist_snapshot h
ON h.qobuz_playlist_id = t.qobuz_playlist_id
WHERE h.is_owned = 1 AND h.inactive = 0
AND t.track_id IN ({})",
placeholders(chunk.len())
);
let mut stmt = conn.prepare(&sql)?;
let rows = stmt.query_map(
rusqlite::params_from_iter(chunk.iter().map(|(id, _)| *id)),
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
)?;
let mut found = Vec::new();
for row in rows {
let (pid, tid) = row?;
for (id, ordinal) in chunk {
if *id == tid {
found.push((pid, *ordinal));
}
}
}
collect_qobuz(found);
}
// Library refs → local-track sidecars on Qobuz playlists.
for chunk in lib_ids.chunks(IN_CHUNK) {
let sql = format!(
"SELECT qobuz_playlist_id, local_track_id FROM playlist_local_tracks
WHERE local_track_id IN ({})",
placeholders(chunk.len())
);
let mut stmt = conn.prepare(&sql)?;
let rows = stmt.query_map(
rusqlite::params_from_iter(chunk.iter().map(|(id, _)| *id)),
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
)?;
let mut found = Vec::new();
for row in rows {
let (pid, tid) = row?;
for (id, ordinal) in chunk {
if *id == tid {
found.push((pid, *ordinal));
}
}
}
collect_qobuz(found);
}
// Plex refs → Plex sidecars on Qobuz playlists.
for chunk in plex_keys.chunks(IN_CHUNK) {
let sql = format!(
"SELECT qobuz_playlist_id, plex_rating_key FROM playlist_plex_tracks
WHERE plex_rating_key IN ({})",
placeholders(chunk.len())
);
let mut stmt = conn.prepare(&sql)?;
let rows = stmt.query_map(
rusqlite::params_from_iter(chunk.iter().map(|(key, _)| *key)),
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)),
)?;
let mut found = Vec::new();
for row in rows {
let (pid, key) = row?;
for (k, ordinal) in chunk {
if *k == key {
found.push((pid, *ordinal));
}
}
}
collect_qobuz(found);
}
// Remote refs → the Jellyfin/Subsonic sidecars on Qobuz playlists,
// source-qualified (the sources come from a fixed vocabulary, so the
// literal in the SQL is safe).
for source in ["jellyfin", "subsonic"] {
let items: Vec<(&str, usize)> = remote_items
.iter()
.filter(|(s, _, _)| *s == source)
.map(|(_, item, ordinal)| (*item, *ordinal))
.collect();
for chunk in items.chunks(IN_CHUNK) {
let sql = format!(
"SELECT qobuz_playlist_id, item_id FROM playlist_remote_tracks
WHERE source = '{source}' AND item_id IN ({})",
placeholders(chunk.len())
);
let mut stmt = conn.prepare(&sql)?;
let rows = stmt.query_map(
rusqlite::params_from_iter(chunk.iter().map(|(item, _)| *item)),
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)),
)?;
let mut found = Vec::new();
for row in rows {
let (pid, item) = row?;
for (i, ordinal) in &chunk[..] {
if *i == item {
found.push((pid, *ordinal));
}
}
}
collect_qobuz(found);
}
}
// All three identity columns of local playlists.
let mut collect_local = |rows: Vec<(String, usize)>| {
for (pid, ordinal) in rows {
hits.entry(ContainmentTarget::Local(pid))
.or_default()
.insert(ordinal);
}
};
for chunk in qobuz_ids.chunks(IN_CHUNK) {
let sql = format!(
"SELECT playlist_id, qobuz_track_id FROM local_playlist_tracks
WHERE qobuz_track_id IN ({})",
placeholders(chunk.len())
);
let mut stmt = conn.prepare(&sql)?;
let rows = stmt.query_map(
rusqlite::params_from_iter(chunk.iter().map(|(id, _)| *id)),
|r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)),
)?;
let mut found = Vec::new();
for row in rows {
let (pid, tid) = row?;
for (id, ordinal) in chunk {
if *id == tid {
found.push((pid.clone(), *ordinal));
}
}
}
collect_local(found);
}
for chunk in lib_paths.chunks(IN_CHUNK) {
// source-qualified: remote rows store their server item id in the
// same column, and a filesystem path must never match one.
let sql = format!(
"SELECT playlist_id, local_path FROM local_playlist_tracks
WHERE source = 'local' AND local_path IN ({})",
placeholders(chunk.len())
);
let mut stmt = conn.prepare(&sql)?;
let rows = stmt.query_map(
rusqlite::params_from_iter(chunk.iter().map(|(p, _)| *p)),
|r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)),
)?;
let mut found = Vec::new();
for row in rows {
let (pid, path) = row?;
for (p, ordinal) in chunk {
if *p == path {
found.push((pid.clone(), *ordinal));
}
}
}
collect_local(found);
}
for chunk in plex_keys.chunks(IN_CHUNK) {
let sql = format!(
"SELECT playlist_id, plex_key FROM local_playlist_tracks
WHERE plex_key IN ({})",
placeholders(chunk.len())
);
let mut stmt = conn.prepare(&sql)?;
let rows = stmt.query_map(
rusqlite::params_from_iter(chunk.iter().map(|(k, _)| *k)),
|r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)),
)?;
let mut found = Vec::new();
for row in rows {
let (pid, key) = row?;
for (k, ordinal) in chunk {
if *k == key {
found.push((pid.clone(), *ordinal));
}
}
}
collect_local(found);
}
for source in ["jellyfin", "subsonic"] {
let items: Vec<(&str, usize)> = remote_items
.iter()
.filter(|(s, _, _)| *s == source)
.map(|(_, item, ordinal)| (*item, *ordinal))
.collect();
for chunk in items.chunks(IN_CHUNK) {
let sql = format!(
"SELECT playlist_id, local_path FROM local_playlist_tracks
WHERE source = '{source}' AND local_path IN ({})",
placeholders(chunk.len())
);
let mut stmt = conn.prepare(&sql)?;
let rows = stmt.query_map(
rusqlite::params_from_iter(chunk.iter().map(|(item, _)| *item)),
|r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)),
)?;
let mut found = Vec::new();
for row in rows {
let (pid, item) = row?;
for (i, ordinal) in &chunk[..] {
if *i == item {
found.push((pid.clone(), *ordinal));
}
}
}
collect_local(found);
}
}
let mut out: Vec<PlaylistContainment> = hits
.into_iter()
.map(|(target, ordinals)| PlaylistContainment {
target,
contained: ordinals.len() as u32,
})
.collect();
// Deterministic order: fullest first, then stable by identity.
out.sort_by(|a, b| {
b.contained.cmp(&a.contained).then_with(|| {
let key = |t: &ContainmentTarget| match t {
ContainmentTarget::Qobuz(id) => (0u8, id.to_string()),
ContainmentTarget::Local(id) => (1u8, id.clone()),
};
key(&a.target).cmp(&key(&b.target))
})
});
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::qobuz_playlist_snapshot as snapshot;
fn conn() -> Connection {
let c = Connection::open_in_memory().unwrap();
snapshot::init_schema(&c).unwrap();
crate::local_playlists::init_schema(&c).unwrap();
// Self-contained copies of the sidecar tables (the database.rs idiom:
// unit tests build only the schema slice they exercise).
c.execute_batch(
"CREATE TABLE playlist_local_tracks (
id INTEGER PRIMARY KEY,
qobuz_playlist_id INTEGER NOT NULL,
local_track_id INTEGER NOT NULL,
position INTEGER NOT NULL,
added_at INTEGER NOT NULL,
UNIQUE(qobuz_playlist_id, local_track_id));
CREATE TABLE playlist_plex_tracks (
id INTEGER PRIMARY KEY,
qobuz_playlist_id INTEGER NOT NULL,
plex_rating_key TEXT NOT NULL,
position INTEGER NOT NULL,
added_at INTEGER NOT NULL,
UNIQUE(qobuz_playlist_id, plex_rating_key));
CREATE TABLE playlist_remote_tracks (
id INTEGER PRIMARY KEY,
qobuz_playlist_id INTEGER NOT NULL,
source TEXT NOT NULL,
item_id TEXT NOT NULL,
position INTEGER NOT NULL,
added_at INTEGER NOT NULL,
UNIQUE(qobuz_playlist_id, source, item_id));",
)
.unwrap();
c
}
/// ONE authoritative list naming every playlist (separate lists would
/// advance the generation and retire the earlier ones — the grace rule
/// working as intended), then a membership snapshot for each.
fn owned_playlists(c: &Connection, playlists: &[(u64, &str, &[u64])]) {
let entries: Vec<snapshot::AuthoritativeEntry> = playlists
.iter()
.map(|(id, name, ids)| snapshot::AuthoritativeEntry {
qobuz_playlist_id: *id,
name: name.to_string(),
owner: None,
track_count: Some(ids.len() as u32),
remote_updated_at: None,
is_owned: true,
})
.collect();
snapshot::record_authoritative_list(c, &entries).unwrap();
for (id, name, ids) in playlists {
snapshot::replace_tracks(c, *id, name, None, ids).unwrap();
}
}
fn contained(rows: &[PlaylistContainment], target: ContainmentTarget) -> Option<u32> {
rows.iter()
.find(|r| r.target == target)
.map(|r| r.contained)
}
#[test]
fn ref_construction_routes_plex_by_stored_key() {
assert_eq!(
PlaylistTrackRef::from_library_row("plex", 99, "12345", None),
PlaylistTrackRef::Plex {
rating_key: "12345".into()
}
);
assert_eq!(
PlaylistTrackRef::from_library_row("jellyfin", 7, "jelly-item", None),
PlaylistTrackRef::Remote {
source: "jellyfin".into(),
item_id: "jelly-item".into(),
}
);
// The catalog id sticks only to offline copies; a stray value on any
// other source is dropped rather than trusted.
assert_eq!(
PlaylistTrackRef::from_library_row("qobuz_download", 8, "/dl/a.flac", Some(555)),
PlaylistTrackRef::Library {
track_id: 8,
path: Some("/dl/a.flac".into()),
qobuz_track_id: Some(555),
}
);
assert_eq!(
PlaylistTrackRef::from_library_row("local", 9, "/m/b.flac", Some(555)),
PlaylistTrackRef::Library {
track_id: 9,
path: Some("/m/b.flac".into()),
qobuz_track_id: None,
}
);
}
#[test]
fn offline_copy_matches_catalog_membership_too() {
let c = conn();
owned_playlists(&c, &[(1, "Qobuz side", &[555])]);
let lp = crate::local_playlists::create(&c, "Local side", None, false).unwrap();
crate::local_playlists::add_tracks(
&c,
&lp,
&[crate::local_playlists::LocalPlaylistTrackInput::Qobuz(555)],
)
.unwrap();
let refs = [PlaylistTrackRef::Library {
track_id: 8,
path: Some("/dl/a.flac".into()),
qobuz_track_id: Some(555),
}];
let rows = playlists_containing(&c, &refs).unwrap();
assert_eq!(contained(&rows, ContainmentTarget::Qobuz(1)), Some(1));
assert_eq!(contained(&rows, ContainmentTarget::Local(lp)), Some(1));
}
#[test]
fn qobuz_containment_counts_distinct_refs() {
let c = conn();
owned_playlists(
&c,
&[
(1, "Both", &[10, 20, 30]),
(2, "One", &[20]),
(3, "Neither", &[99]),
],
);
let rows = playlists_containing(
&c,
&[PlaylistTrackRef::Qobuz(10), PlaylistTrackRef::Qobuz(20)],
)
.unwrap();
assert_eq!(contained(&rows, ContainmentTarget::Qobuz(1)), Some(2));
assert_eq!(contained(&rows, ContainmentTarget::Qobuz(2)), Some(1));
assert_eq!(contained(&rows, ContainmentTarget::Qobuz(3)), None);
// Fullest playlist first.
assert_eq!(rows[0].target, ContainmentTarget::Qobuz(1));
}
#[test]
fn duplicate_membership_rows_count_once() {
let c = conn();
owned_playlists(&c, &[(1, "Dupes", &[10, 10, 10])]);
let rows = playlists_containing(&c, &[PlaylistTrackRef::Qobuz(10)]).unwrap();
assert_eq!(contained(&rows, ContainmentTarget::Qobuz(1)), Some(1));
}
#[test]
fn unowned_and_inactive_playlists_are_not_targets() {
let c = conn();
snapshot::record_authoritative_list(
&c,
&[snapshot::AuthoritativeEntry {
qobuz_playlist_id: 5,
name: "Followed".into(),
owner: None,
track_count: Some(1),
remote_updated_at: None,
is_owned: false,
}],
)
.unwrap();
snapshot::replace_tracks(&c, 5, "Followed", None, &[10]).unwrap();
let rows = playlists_containing(&c, &[PlaylistTrackRef::Qobuz(10)]).unwrap();
assert!(rows.is_empty());
owned_playlists(&c, &[(6, "Mine", &[10])]);
// Retire 6 by two authoritative lists without it.
for _ in 0..2 {
snapshot::record_authoritative_list(&c, &[]).unwrap();
}
let rows = playlists_containing(&c, &[PlaylistTrackRef::Qobuz(10)]).unwrap();
assert!(rows.is_empty());
}
#[test]
fn sidecars_and_local_playlists_answer_by_typed_identity() {
let c = conn();
c.execute_batch(
"INSERT INTO playlist_local_tracks VALUES (NULL, 7, 42, 0, 1);
INSERT INTO playlist_plex_tracks VALUES (NULL, 7, 'rk-9', 1, 1);",
)
.unwrap();
let lp = crate::local_playlists::create(&c, "Local mix", None, false).unwrap();
crate::local_playlists::add_tracks(
&c,
&lp,
&[
crate::local_playlists::LocalPlaylistTrackInput::Qobuz(1000),
crate::local_playlists::LocalPlaylistTrackInput::Local("/music/a.flac".into()),
crate::local_playlists::LocalPlaylistTrackInput::Plex("rk-9".into()),
],
)
.unwrap();
let refs = [
PlaylistTrackRef::Qobuz(1000),
PlaylistTrackRef::Library {
track_id: 42,
path: Some("/music/a.flac".into()),
qobuz_track_id: None,
},
PlaylistTrackRef::Plex {
rating_key: "rk-9".into(),
},
];
let rows = playlists_containing(&c, &refs).unwrap();
// The Qobuz playlist holds the library row and the Plex key (2 of 3);
// the local playlist holds all three.
assert_eq!(contained(&rows, ContainmentTarget::Qobuz(7)), Some(2));
assert_eq!(
contained(&rows, ContainmentTarget::Local(lp.clone())),
Some(3)
);
assert_eq!(rows[0].target, ContainmentTarget::Local(lp));
}
#[test]
fn remote_rows_answer_by_source_qualified_item_id() {
let c = conn();
c.execute_batch(
"INSERT INTO playlist_remote_tracks VALUES (NULL, 7, 'jellyfin', 'item-1', 0, 1);",
)
.unwrap();
let lp = crate::local_playlists::create(&c, "Remote mix", None, false).unwrap();
crate::local_playlists::add_tracks(
&c,
&lp,
&[
crate::local_playlists::LocalPlaylistTrackInput::Jellyfin("item-1".into()),
crate::local_playlists::LocalPlaylistTrackInput::Subsonic("song-9".into()),
],
)
.unwrap();
let jelly = PlaylistTrackRef::from_library_row("jellyfin", 12345, "item-1", None);
let sub = PlaylistTrackRef::Remote {
source: "subsonic".into(),
item_id: "song-9".into(),
};
// The same item id under the WRONG source must not match.
let wrong = PlaylistTrackRef::Remote {
source: "subsonic".into(),
item_id: "item-1".into(),
};
let rows = playlists_containing(&c, &[jelly, sub]).unwrap();
assert_eq!(contained(&rows, ContainmentTarget::Qobuz(7)), Some(1));
assert_eq!(
contained(&rows, ContainmentTarget::Local(lp.clone())),
Some(2)
);
assert!(playlists_containing(&c, &[wrong]).unwrap().is_empty());
// A local FILE path that happens to equal a remote item id never
// cross-matches (the source qualifier on the shared column).
let path_ref = PlaylistTrackRef::Library {
track_id: 1,
path: Some("item-1".into()),
qobuz_track_id: None,
};
let rows = playlists_containing(&c, &[path_ref]).unwrap();
assert!(contained(&rows, ContainmentTarget::Local(lp)).is_none());
}
#[test]
fn empty_refs_answer_nothing() {
let c = conn();
assert!(playlists_containing(&c, &[]).unwrap().is_empty());
}
}
+767 -91
View File
@@ -1,25 +1,35 @@
//! Local snapshot of the user's QOBUZ playlists (offline-mode port, B7/B8).
//! Local snapshot of the user's QOBUZ playlists (offline-mode port, B7/B8;
//! membership index substrate, 2.1.1 Add-to-Playlist redesign).
//!
//! Spec D11 left an HONEST LIMIT: playlist names and membership live only in
//! the Qobuz API, so offline a mixed playlist falls back to a synthesized
//! "Playlist (N local)" name and shows zero Qobuz rows. This module stores a
//! point-in-time snapshot captured opportunistically from data the app
//! ALREADY fetches while online (no new API traffic):
//! point-in-time snapshot captured from data the app fetches while online:
//!
//! - NAMES: every user-playlist list load (sidebar / playlist manager)
//! upserts id + name (+ owner, track_count) for ALL listed playlists —
//! cheap names-only rows, no track membership.
//! - HEADERS: every authoritative user-playlist list load (sidebar / playlist
//! manager) upserts id + name (+ owner, track_count, ownership) for ALL
//! listed playlists and advances the AUTHORITY GENERATION. A header absent
//! from two consecutive authoritative lists is marked `inactive` — never
//! deleted on a single miss, tolerating Qobuz post-write lag.
//! - MEMBERSHIP: opening a playlist DETAIL online full-replaces its snapshot
//! track ids (the detail fetch already returns the full track list).
//! Membership is recorded ONLY for playlists already captured by the
//! names producer (the user's own list) — a merely-viewed public playlist
//! never lands in the snapshot, so the offline surfaces stay the user's.
//! track ids, and the background hydrator does the same from the
//! ids-only `playlist/get?extra=track_ids` fetch. Membership is recorded
//! ONLY for playlists already captured by a header producer (the user's own
//! list) — a merely-viewed public playlist never lands in the snapshot.
//! - MUTATIONS: successful add/remove/create through QBZ update the snapshot
//! incrementally and synchronously, so the picker's containment answer
//! moves without waiting for a re-sync.
//!
//! Rows are point-in-time: offline consumers show them as-is (no staleness
//! UI in v1); `snapped_at` is stamped for the future.
//! Freshness is deliberately NOT one timestamp (that overload is exactly what
//! made an empty membership answer unreadable): `header_updated_at` says when
//! the list last named this playlist, `membership_synced_at` says when the
//! track ids were last authoritative, `membership_count` +
//! `membership_remote_updated_at` are the evidence a later list compares
//! against to decide staleness. `snapped_at` remains for the older offline
//! consumers and is stamped wherever it always was.
//!
//! All functions take `&Connection` (the local_playlists idiom): no Tauri
//! state, no async runtime — testable with in-memory SQLite.
//! All functions take `&Connection` (the local_playlists idiom): no async
//! runtime — testable with in-memory SQLite.
use std::collections::HashMap;
@@ -31,20 +41,69 @@ pub struct SnapshotHeader {
pub qobuz_playlist_id: u64,
pub name: String,
pub owner: Option<String>,
/// The playlist's TOTAL Qobuz track count at snapshot time (not the
/// The playlist's TOTAL Qobuz track count at header time (not the
/// offline-playable subset).
pub track_count: Option<u32>,
/// Unix ms when this header was last written.
/// Unix ms when this header was last written (legacy stamp; kept for the
/// offline consumers that predate the split freshness columns).
pub snapped_at: i64,
/// Unix ms when an authoritative list last named this playlist.
pub header_updated_at: Option<i64>,
/// Unix ms when the membership rows were last authoritative. NULL means
/// membership was never captured — which is NOT "empty playlist".
pub membership_synced_at: Option<i64>,
/// Number of membership rows written at the last sync.
pub membership_count: Option<u32>,
/// The playlist's API `updated_at` as reported by the authoritative list.
pub remote_updated_at: Option<i64>,
/// The API `updated_at` in force when membership was last synced.
pub membership_remote_updated_at: Option<i64>,
/// Last authority generation that listed this playlist.
pub seen_generation: i64,
/// The session user owns (can write to) this playlist. Persisted
/// explicitly instead of being re-inferred from whichever response
/// happened to be loaded.
pub is_owned: bool,
/// Absent from two consecutive authoritative lists. Kept, not deleted, so
/// a Qobuz-side hiccup cannot erase local knowledge.
pub inactive: bool,
}
/// Names-producer input (one listed playlist).
/// Authoritative-list producer input (one listed playlist).
#[derive(Debug, Clone)]
pub struct SnapshotNameEntry {
pub struct AuthoritativeEntry {
pub qobuz_playlist_id: u64,
pub name: String,
pub owner: Option<String>,
pub track_count: Option<u32>,
pub remote_updated_at: Option<i64>,
pub is_owned: bool,
}
/// Why the hydrator wants to refresh a playlist's membership.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StaleReason {
NeverSynced,
CountMismatch,
RemoteRevision,
}
#[derive(Debug, Clone)]
pub struct HydrationCandidate {
pub qobuz_playlist_id: u64,
pub reason: StaleReason,
}
/// The picker's honest tri-state for the containment section.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MembershipIndexState {
/// Every owned active playlist has authoritative membership.
Complete,
/// Some owned playlists still await a membership sync.
Updating { pending: u32 },
/// No authoritative list was ever recorded (fresh profile, or the app has
/// never been online) — an empty containment answer means nothing.
Unavailable,
}
fn now_ms() -> i64 {
@@ -55,8 +114,9 @@ fn now_ms() -> i64 {
.as_millis() as i64
}
/// Create the snapshot tables. Idempotent (`IF NOT EXISTS`), run by
/// `LibraryDatabase::open` next to the rest of the schema.
/// Create the snapshot tables. Idempotent (`IF NOT EXISTS` + pragma-guarded
/// additive ALTERs, the database.rs idiom), run by `LibraryDatabase::open`
/// next to the rest of the schema.
pub fn init_schema(conn: &Connection) -> Result<()> {
conn.execute_batch(
r#"
@@ -76,44 +136,158 @@ pub fn init_schema(conn: &Connection) -> Result<()> {
CREATE INDEX IF NOT EXISTS idx_qobuz_playlist_snapshot_tracks
ON qobuz_playlist_snapshot_tracks(qobuz_playlist_id, position);
"#,
)
}
/// NAMES producer: upsert a header row for every listed playlist. Never
/// touches the membership table. Stamps `snapped_at` = now on each row.
pub fn upsert_names(conn: &Connection, entries: &[SnapshotNameEntry]) -> Result<()> {
if entries.is_empty() {
return Ok(());
}
let ts = now_ms();
let mut stmt = conn.prepare(
"INSERT INTO qobuz_playlist_snapshot
(qobuz_playlist_id, name, owner, track_count, snapped_at)
VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(qobuz_playlist_id) DO UPDATE SET
name = excluded.name,
owner = excluded.owner,
track_count = excluded.track_count,
snapped_at = excluded.snapped_at",
-- The picker's containment question runs in the opposite direction:
-- "which playlists hold THIS track".
CREATE INDEX IF NOT EXISTS idx_qobuz_playlist_snapshot_tracks_track
ON qobuz_playlist_snapshot_tracks(track_id, qobuz_playlist_id);
CREATE TABLE IF NOT EXISTS qobuz_playlist_index_meta (
key TEXT PRIMARY KEY,
value INTEGER NOT NULL
);
"#,
)?;
for e in entries {
stmt.execute(params![
e.qobuz_playlist_id as i64,
e.name,
e.owner,
e.track_count,
ts
])?;
// Additive migration (2.1.1 membership index): the split freshness
// columns. One probe guards the whole batch — they ship together.
let has_freshness: bool = conn
.query_row(
"SELECT COUNT(*) FROM pragma_table_info('qobuz_playlist_snapshot')
WHERE name = 'membership_synced_at'",
[],
|r| r.get::<_, i32>(0),
)
.map(|count| count > 0)
.unwrap_or(false);
if !has_freshness {
conn.execute_batch(
"ALTER TABLE qobuz_playlist_snapshot ADD COLUMN header_updated_at INTEGER;
ALTER TABLE qobuz_playlist_snapshot ADD COLUMN membership_synced_at INTEGER;
ALTER TABLE qobuz_playlist_snapshot ADD COLUMN membership_count INTEGER;
ALTER TABLE qobuz_playlist_snapshot ADD COLUMN remote_updated_at INTEGER;
ALTER TABLE qobuz_playlist_snapshot ADD COLUMN membership_remote_updated_at INTEGER;
ALTER TABLE qobuz_playlist_snapshot ADD COLUMN seen_generation INTEGER NOT NULL DEFAULT 0;
ALTER TABLE qobuz_playlist_snapshot ADD COLUMN is_owned INTEGER NOT NULL DEFAULT 0;
ALTER TABLE qobuz_playlist_snapshot ADD COLUMN inactive INTEGER NOT NULL DEFAULT 0;
-- Backfill: the old single stamp was both header and membership
-- evidence; keep it as the header stamp everywhere, and as the
-- membership stamp only where membership rows actually exist.
UPDATE qobuz_playlist_snapshot
SET header_updated_at = snapped_at
WHERE header_updated_at IS NULL;
UPDATE qobuz_playlist_snapshot
SET membership_synced_at = snapped_at,
membership_count = (
SELECT COUNT(*) FROM qobuz_playlist_snapshot_tracks t
WHERE t.qobuz_playlist_id
= qobuz_playlist_snapshot.qobuz_playlist_id)
WHERE membership_synced_at IS NULL
AND EXISTS (
SELECT 1 FROM qobuz_playlist_snapshot_tracks t
WHERE t.qobuz_playlist_id
= qobuz_playlist_snapshot.qobuz_playlist_id);",
)?;
}
Ok(())
}
// ───────────────────────── Authority generations ─────────────────────────
const GENERATION_KEY: &str = "authority_generation";
/// Last recorded authority generation; 0 when no authoritative list was ever
/// recorded.
pub fn current_generation(conn: &Connection) -> Result<i64> {
conn.query_row(
"SELECT value FROM qobuz_playlist_index_meta WHERE key = ?1",
params![GENERATION_KEY],
|r| r.get(0),
)
.optional()
.map(|v| v.unwrap_or(0))
}
/// HEADERS producer: record one successful authoritative user-playlist list.
/// Upserts every entry, advances the authority generation, and marks headers
/// unseen for TWO consecutive generations `inactive` (the grace that
/// tolerates Qobuz post-write lag). Returns the new generation.
///
/// An EMPTY list is still recorded (a user can genuinely delete every
/// playlist), but the caller must only invoke this for a fetch that
/// succeeded — a network failure must never masquerade as an empty library.
pub fn record_authoritative_list(conn: &Connection, entries: &[AuthoritativeEntry]) -> Result<i64> {
let ts = now_ms();
conn.execute_batch("BEGIN IMMEDIATE")?;
let result = (|| -> Result<i64> {
let generation = current_generation(conn)? + 1;
{
let mut stmt = conn.prepare(
"INSERT INTO qobuz_playlist_snapshot
(qobuz_playlist_id, name, owner, track_count, snapped_at,
header_updated_at, remote_updated_at, seen_generation,
is_owned, inactive)
VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?6, ?7, ?8, 0)
ON CONFLICT(qobuz_playlist_id) DO UPDATE SET
name = excluded.name,
owner = excluded.owner,
track_count = excluded.track_count,
snapped_at = excluded.snapped_at,
header_updated_at = excluded.header_updated_at,
remote_updated_at = excluded.remote_updated_at,
seen_generation = excluded.seen_generation,
is_owned = excluded.is_owned,
inactive = 0",
)?;
for e in entries {
stmt.execute(params![
e.qobuz_playlist_id as i64,
e.name,
e.owner,
e.track_count,
ts,
e.remote_updated_at,
generation,
e.is_owned,
])?;
}
}
conn.execute(
"UPDATE qobuz_playlist_snapshot
SET inactive = 1
WHERE inactive = 0 AND seen_generation <= ?1 - 2",
params![generation],
)?;
conn.execute(
"INSERT INTO qobuz_playlist_index_meta (key, value) VALUES (?1, ?2)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
params![GENERATION_KEY, generation],
)?;
Ok(generation)
})();
match result {
Ok(generation) => {
conn.execute_batch("COMMIT")?;
Ok(generation)
}
Err(e) => {
let _ = conn.execute_batch("ROLLBACK");
Err(e)
}
}
}
// ───────────────────────── Membership producers ─────────────────────────
/// MEMBERSHIP producer: full-replace the snapshot track ids of ONE playlist
/// (detail load) and refresh its header (name / owner / track_count /
/// snapped_at). Returns `false` (writing NOTHING) when the playlist has no
/// header row — i.e. it was never captured by the names producer, so it is
/// not one of the user's listed playlists.
/// (detail load or hydrator fetch) and refresh its header. Stamps
/// `membership_synced_at` / `membership_count`, and copies the HEADER's
/// current `remote_updated_at` into the membership evidence — never a stamp
/// from the fetch itself: `playlist/get` and `getUserPlaylists` do not report
/// comparable `updated_at` values, and trusting the fetch's made the queue
/// re-fetch the same playlist forever (smoke 2026-08-30). Returns `false`
/// (writing NOTHING) when the playlist has no header row — i.e. it was never
/// captured by the headers producer, so it is not one of the user's listed
/// playlists.
pub fn replace_tracks(
conn: &Connection,
qobuz_playlist_id: u64,
@@ -121,35 +295,299 @@ pub fn replace_tracks(
owner: Option<&str>,
track_ids: &[u64],
) -> Result<bool> {
let updated = conn.execute(
"UPDATE qobuz_playlist_snapshot
SET name = ?2, owner = ?3, track_count = ?4, snapped_at = ?5
WHERE qobuz_playlist_id = ?1",
params![
qobuz_playlist_id as i64,
name,
owner,
track_ids.len() as u32,
now_ms()
],
)?;
if updated == 0 {
let ts = now_ms();
conn.execute_batch("BEGIN IMMEDIATE")?;
let result = (|| -> Result<bool> {
let updated = conn.execute(
"UPDATE qobuz_playlist_snapshot
SET name = ?2, owner = ?3, track_count = ?4, snapped_at = ?5,
membership_synced_at = ?5, membership_count = ?4,
membership_remote_updated_at = remote_updated_at
WHERE qobuz_playlist_id = ?1",
params![
qobuz_playlist_id as i64,
name,
owner,
track_ids.len() as u32,
ts,
],
)?;
if updated == 0 {
return Ok(false);
}
conn.execute(
"DELETE FROM qobuz_playlist_snapshot_tracks WHERE qobuz_playlist_id = ?1",
params![qobuz_playlist_id as i64],
)?;
let mut stmt = conn.prepare(
"INSERT INTO qobuz_playlist_snapshot_tracks (qobuz_playlist_id, position, track_id)
VALUES (?1, ?2, ?3)",
)?;
for (pos, tid) in track_ids.iter().enumerate() {
stmt.execute(params![qobuz_playlist_id as i64, pos as i64, *tid as i64])?;
}
Ok(true)
})();
match result {
Ok(wrote) => {
conn.execute_batch("COMMIT")?;
Ok(wrote)
}
Err(e) => {
let _ = conn.execute_batch("ROLLBACK");
Err(e)
}
}
}
/// Incremental MUTATION producer: a successful `playlist/addTracks` appends
/// its ids to the snapshot so the containment answer moves immediately.
/// Applies only when membership was already captured (`membership_synced_at`
/// set) — an uncaptured playlist stays queued for the hydrator instead of
/// pretending an append equals a snapshot. Returns whether it applied.
pub fn apply_added_tracks(
conn: &Connection,
qobuz_playlist_id: u64,
track_ids: &[u64],
) -> Result<bool> {
if track_ids.is_empty() {
return Ok(false);
}
let ts = now_ms();
conn.execute_batch("BEGIN IMMEDIATE")?;
let result = (|| -> Result<bool> {
let captured: Option<i64> = conn
.query_row(
"SELECT membership_synced_at FROM qobuz_playlist_snapshot
WHERE qobuz_playlist_id = ?1",
params![qobuz_playlist_id as i64],
|r| r.get(0),
)
.optional()?
.flatten();
if captured.is_none() {
return Ok(false);
}
let next: i64 = conn.query_row(
"SELECT COALESCE(MAX(position) + 1, 0)
FROM qobuz_playlist_snapshot_tracks
WHERE qobuz_playlist_id = ?1",
params![qobuz_playlist_id as i64],
|r| r.get(0),
)?;
let mut stmt = conn.prepare(
"INSERT INTO qobuz_playlist_snapshot_tracks (qobuz_playlist_id, position, track_id)
VALUES (?1, ?2, ?3)",
)?;
for (offset, tid) in track_ids.iter().enumerate() {
stmt.execute(params![
qobuz_playlist_id as i64,
next + offset as i64,
*tid as i64
])?;
}
conn.execute(
"UPDATE qobuz_playlist_snapshot
SET membership_count = (
SELECT COUNT(*) FROM qobuz_playlist_snapshot_tracks t
WHERE t.qobuz_playlist_id = ?1),
track_count = (
SELECT COUNT(*) FROM qobuz_playlist_snapshot_tracks t
WHERE t.qobuz_playlist_id = ?1),
membership_synced_at = ?2, snapped_at = ?2
WHERE qobuz_playlist_id = ?1",
params![qobuz_playlist_id as i64, ts],
)?;
Ok(true)
})();
match result {
Ok(applied) => {
conn.execute_batch("COMMIT")?;
Ok(applied)
}
Err(e) => {
let _ = conn.execute_batch("ROLLBACK");
Err(e)
}
}
}
/// Incremental MUTATION producer: a successful track removal drops every
/// membership row bearing the removed TRACK ids. Same capture precondition
/// as `apply_added_tracks`.
pub fn apply_removed_tracks(
conn: &Connection,
qobuz_playlist_id: u64,
track_ids: &[u64],
) -> Result<bool> {
if track_ids.is_empty() {
return Ok(false);
}
let ts = now_ms();
conn.execute_batch("BEGIN IMMEDIATE")?;
let result = (|| -> Result<bool> {
let captured: Option<i64> = conn
.query_row(
"SELECT membership_synced_at FROM qobuz_playlist_snapshot
WHERE qobuz_playlist_id = ?1",
params![qobuz_playlist_id as i64],
|r| r.get(0),
)
.optional()?
.flatten();
if captured.is_none() {
return Ok(false);
}
{
let mut stmt = conn.prepare(
"DELETE FROM qobuz_playlist_snapshot_tracks
WHERE qobuz_playlist_id = ?1 AND track_id = ?2",
)?;
for tid in track_ids {
stmt.execute(params![qobuz_playlist_id as i64, *tid as i64])?;
}
}
conn.execute(
"UPDATE qobuz_playlist_snapshot
SET membership_count = (
SELECT COUNT(*) FROM qobuz_playlist_snapshot_tracks t
WHERE t.qobuz_playlist_id = ?1),
track_count = (
SELECT COUNT(*) FROM qobuz_playlist_snapshot_tracks t
WHERE t.qobuz_playlist_id = ?1),
membership_synced_at = ?2, snapped_at = ?2
WHERE qobuz_playlist_id = ?1",
params![qobuz_playlist_id as i64, ts],
)?;
Ok(true)
})();
match result {
Ok(applied) => {
conn.execute_batch("COMMIT")?;
Ok(applied)
}
Err(e) => {
let _ = conn.execute_batch("ROLLBACK");
Err(e)
}
}
}
/// MUTATION producer: a playlist just created through QBZ. Inserts its header
/// at the CURRENT generation (it cannot have been in the last list yet — the
/// grace rule, not a fresh fetch, is what keeps it alive) with an empty,
/// captured membership, so an immediate follow-up add applies incrementally.
pub fn record_created_playlist(
conn: &Connection,
qobuz_playlist_id: u64,
name: &str,
owner: Option<&str>,
) -> Result<()> {
let ts = now_ms();
let generation = current_generation(conn)?;
conn.execute(
"DELETE FROM qobuz_playlist_snapshot_tracks WHERE qobuz_playlist_id = ?1",
"INSERT INTO qobuz_playlist_snapshot
(qobuz_playlist_id, name, owner, track_count, snapped_at,
header_updated_at, membership_synced_at, membership_count,
seen_generation, is_owned, inactive)
VALUES (?1, ?2, ?3, 0, ?4, ?4, ?4, 0, ?5, 1, 0)
ON CONFLICT(qobuz_playlist_id) DO UPDATE SET
name = excluded.name,
owner = excluded.owner,
seen_generation = excluded.seen_generation,
is_owned = 1,
inactive = 0",
params![qobuz_playlist_id as i64, name, owner, ts, generation],
)?;
Ok(())
}
/// MUTATION producer: a playlist deleted through QBZ leaves the target set
/// immediately instead of waiting out the two-generation grace.
pub fn mark_inactive(conn: &Connection, qobuz_playlist_id: u64) -> Result<()> {
conn.execute(
"UPDATE qobuz_playlist_snapshot SET inactive = 1 WHERE qobuz_playlist_id = ?1",
params![qobuz_playlist_id as i64],
)?;
let mut stmt = conn.prepare(
"INSERT INTO qobuz_playlist_snapshot_tracks (qobuz_playlist_id, position, track_id)
VALUES (?1, ?2, ?3)",
)?;
for (pos, tid) in track_ids.iter().enumerate() {
stmt.execute(params![qobuz_playlist_id as i64, pos as i64, *tid as i64])?;
}
Ok(true)
Ok(())
}
// ───────────────────────── Hydration planning ─────────────────────────
/// The membership refreshes the hydrator still owes, oldest debt first.
/// Only owned, active playlists — followed/read-only playlists are
/// informational and must not spend the rate budget.
///
/// Staleness is deliberately NOT "any evidence disagrees" (the 2026-08-30
/// smoke found that fetching forever): a playlist is stale when
///
/// - membership was never captured; or
/// - BOTH sides carry a remote revision and they differ — the authoritative
/// list said the playlist changed since the membership sync; or
/// - a revision comparison is impossible on either side, and the counts
/// disagree (the coarse fallback).
///
/// A successful `replace_tracks` copies the header's current revision into
/// the membership evidence and equalises the counts, so every sync strictly
/// converges: only a NEW authoritative list can make a playlist stale again,
/// and then only the playlists it actually reports changed.
pub fn hydration_queue(conn: &Connection) -> Result<Vec<HydrationCandidate>> {
let mut stmt = conn.prepare(
"SELECT qobuz_playlist_id,
membership_synced_at IS NULL AS never_synced,
(membership_remote_updated_at IS NOT NULL
AND remote_updated_at IS NOT NULL
AND membership_remote_updated_at != remote_updated_at)
AS revision_mismatch
FROM qobuz_playlist_snapshot
WHERE is_owned = 1 AND inactive = 0
AND (membership_synced_at IS NULL
OR (membership_remote_updated_at IS NOT NULL
AND remote_updated_at IS NOT NULL
AND membership_remote_updated_at != remote_updated_at)
OR ((membership_remote_updated_at IS NULL
OR remote_updated_at IS NULL)
AND membership_count IS NOT track_count))
ORDER BY never_synced DESC, revision_mismatch DESC, qobuz_playlist_id",
)?;
let mut out = Vec::new();
for r in stmt.query_map([], |r| {
Ok((
r.get::<_, i64>(0)? as u64,
r.get::<_, bool>(1)?,
r.get::<_, bool>(2)?,
))
})? {
let (pid, never, revision) = r?;
out.push(HydrationCandidate {
qobuz_playlist_id: pid,
reason: if never {
StaleReason::NeverSynced
} else if revision {
StaleReason::RemoteRevision
} else {
StaleReason::CountMismatch
},
});
}
Ok(out)
}
/// The containment section's honest tri-state.
pub fn index_state(conn: &Connection) -> Result<MembershipIndexState> {
if current_generation(conn)? == 0 {
return Ok(MembershipIndexState::Unavailable);
}
let pending = hydration_queue(conn)?.len() as u32;
Ok(if pending == 0 {
MembershipIndexState::Complete
} else {
MembershipIndexState::Updating { pending }
})
}
// ───────────────────────────── Readers ─────────────────────────────
fn row_to_header(r: &rusqlite::Row) -> Result<SnapshotHeader> {
Ok(SnapshotHeader {
qobuz_playlist_id: r.get::<_, i64>("qobuz_playlist_id")? as u64,
@@ -157,26 +595,40 @@ fn row_to_header(r: &rusqlite::Row) -> Result<SnapshotHeader> {
owner: r.get("owner")?,
track_count: r.get("track_count")?,
snapped_at: r.get("snapped_at")?,
header_updated_at: r.get("header_updated_at")?,
membership_synced_at: r.get("membership_synced_at")?,
membership_count: r.get("membership_count")?,
remote_updated_at: r.get("remote_updated_at")?,
membership_remote_updated_at: r.get("membership_remote_updated_at")?,
seen_generation: r.get("seen_generation")?,
is_owned: r.get("is_owned")?,
inactive: r.get("inactive")?,
})
}
const HEADER_COLUMNS: &str = "qobuz_playlist_id, name, owner, track_count, snapped_at, \
header_updated_at, membership_synced_at, membership_count, \
remote_updated_at, membership_remote_updated_at, seen_generation, \
is_owned, inactive";
/// One snapshot header, or None.
pub fn get_header(conn: &Connection, qobuz_playlist_id: u64) -> Result<Option<SnapshotHeader>> {
conn.query_row(
"SELECT qobuz_playlist_id, name, owner, track_count, snapped_at
FROM qobuz_playlist_snapshot WHERE qobuz_playlist_id = ?1",
&format!(
"SELECT {HEADER_COLUMNS} FROM qobuz_playlist_snapshot
WHERE qobuz_playlist_id = ?1"
),
params![qobuz_playlist_id as i64],
row_to_header,
)
.optional()
}
/// All snapshot headers.
/// All snapshot headers, inactive ones included (offline consumers decide).
pub fn all_headers(conn: &Connection) -> Result<Vec<SnapshotHeader>> {
let mut stmt = conn.prepare(
"SELECT qobuz_playlist_id, name, owner, track_count, snapped_at
FROM qobuz_playlist_snapshot",
)?;
let mut stmt = conn.prepare(&format!(
"SELECT {HEADER_COLUMNS} FROM qobuz_playlist_snapshot"
))?;
let mut out = Vec::new();
for r in stmt.query_map([], row_to_header)? {
out.push(r?);
@@ -191,9 +643,7 @@ pub fn track_ids(conn: &Connection, qobuz_playlist_id: u64) -> Result<Vec<u64>>
WHERE qobuz_playlist_id = ?1 ORDER BY position",
)?;
let mut out = Vec::new();
for r in stmt.query_map(params![qobuz_playlist_id as i64], |r| {
r.get::<_, i64>(0)
})? {
for r in stmt.query_map(params![qobuz_playlist_id as i64], |r| r.get::<_, i64>(0))? {
out.push(r? as u64);
}
Ok(out)
@@ -226,19 +676,25 @@ mod tests {
c
}
fn name_entry(id: u64, name: &str, count: u32) -> SnapshotNameEntry {
SnapshotNameEntry {
fn entry(id: u64, name: &str, count: u32) -> AuthoritativeEntry {
AuthoritativeEntry {
qobuz_playlist_id: id,
name: name.to_string(),
owner: Some("me".to_string()),
track_count: Some(count),
remote_updated_at: None,
is_owned: true,
}
}
fn record(c: &Connection, entries: &[AuthoritativeEntry]) -> i64 {
record_authoritative_list(c, entries).unwrap()
}
#[test]
fn roundtrip_header_and_tracks() {
let c = conn();
upsert_names(&c, &[name_entry(42, "Road Trip", 3)]).unwrap();
record(&c, &[entry(42, "Road Trip", 3)]);
let wrote = replace_tracks(&c, 42, "Road Trip", Some("me"), &[30, 10, 20]).unwrap();
assert!(wrote);
@@ -247,6 +703,10 @@ mod tests {
assert_eq!(h.owner.as_deref(), Some("me"));
assert_eq!(h.track_count, Some(3));
assert!(h.snapped_at > 0);
assert!(h.is_owned);
assert!(!h.inactive);
assert_eq!(h.membership_count, Some(3));
assert!(h.membership_synced_at.is_some());
// Snapshot order preserved, not sorted by id.
assert_eq!(track_ids(&c, 42).unwrap(), vec![30, 10, 20]);
@@ -257,7 +717,7 @@ mod tests {
#[test]
fn replace_is_full_replace() {
let c = conn();
upsert_names(&c, &[name_entry(7, "Mix", 3)]).unwrap();
record(&c, &[entry(7, "Mix", 3)]);
replace_tracks(&c, 7, "Mix", None, &[1, 2, 3]).unwrap();
replace_tracks(&c, 7, "Mix renamed", None, &[9]).unwrap();
@@ -279,28 +739,244 @@ mod tests {
#[test]
fn names_only_rows_without_tracks() {
let c = conn();
upsert_names(&c, &[name_entry(1, "A", 10), name_entry(2, "B", 0)]).unwrap();
record(&c, &[entry(1, "A", 10), entry(2, "B", 0)]);
assert_eq!(all_headers(&c).unwrap().len(), 2);
assert!(track_ids(&c, 1).unwrap().is_empty());
assert!(all_track_ids(&c).unwrap().is_empty());
// Re-upserting updates the name in place without creating track rows.
upsert_names(&c, &[name_entry(1, "A renamed", 11)]).unwrap();
// Re-recording updates the name in place without creating track rows,
// and never touches the membership stamp.
record(&c, &[entry(1, "A renamed", 11), entry(2, "B", 0)]);
let h = get_header(&c, 1).unwrap().unwrap();
assert_eq!(h.name, "A renamed");
assert_eq!(h.track_count, Some(11));
assert!(h.membership_synced_at.is_none());
assert!(track_ids(&c, 1).unwrap().is_empty());
}
#[test]
fn replace_refuses_unknown_playlist() {
let c = conn();
// No names row -> the detail producer writes NOTHING (a merely
// No header row -> the detail producer writes NOTHING (a merely
// viewed public playlist must not land in the snapshot).
let wrote = replace_tracks(&c, 99, "Someone's list", None, &[1, 2]).unwrap();
assert!(!wrote);
assert!(get_header(&c, 99).unwrap().is_none());
assert!(track_ids(&c, 99).unwrap().is_empty());
}
#[test]
fn header_upsert_is_not_membership_evidence() {
// The 2.1.0 research finding: header refreshes used to renew the one
// timestamp that also vouched for membership. Now they must not.
let c = conn();
record(&c, &[entry(5, "Mix", 2)]);
replace_tracks(&c, 5, "Mix", None, &[1, 2]).unwrap();
let synced = get_header(&c, 5).unwrap().unwrap().membership_synced_at;
record(&c, &[entry(5, "Mix", 2)]);
let h = get_header(&c, 5).unwrap().unwrap();
assert_eq!(h.membership_synced_at, synced);
assert_eq!(h.membership_count, Some(2));
}
#[test]
fn generations_and_two_generation_grace() {
let c = conn();
assert_eq!(current_generation(&c).unwrap(), 0);
let g1 = record(&c, &[entry(1, "A", 0), entry(2, "B", 0)]);
assert_eq!(g1, 1);
// B missing once: still active (post-write lag tolerance).
record(&c, &[entry(1, "A", 0)]);
assert!(!get_header(&c, 2).unwrap().unwrap().inactive);
// B missing twice: inactive, but never deleted.
record(&c, &[entry(1, "A", 0)]);
let h = get_header(&c, 2).unwrap().unwrap();
assert!(h.inactive);
// B reappears: active again.
record(&c, &[entry(1, "A", 0), entry(2, "B", 0)]);
assert!(!get_header(&c, 2).unwrap().unwrap().inactive);
}
#[test]
fn hydration_queue_reasons_and_order() {
let c = conn();
let mut never = entry(1, "Never", 4);
never.remote_updated_at = Some(100);
// Revision unavailable on this one: the coarse count fallback governs.
let mut counted = entry(2, "Counted", 5);
counted.remote_updated_at = None;
let mut revised = entry(3, "Revised", 1);
revised.remote_updated_at = Some(100);
let mut fresh = entry(4, "Fresh", 1);
fresh.remote_updated_at = Some(100);
let followed = AuthoritativeEntry {
is_owned: false,
..entry(5, "Followed", 9)
};
record(
&c,
&[
never.clone(),
counted.clone(),
revised.clone(),
fresh.clone(),
followed,
],
);
replace_tracks(&c, 2, "Counted", None, &[7]).unwrap();
replace_tracks(&c, 3, "Revised", None, &[7]).unwrap();
replace_tracks(&c, 4, "Fresh", None, &[8]).unwrap();
// Next authoritative list: 2's declared count (5) disagrees with its
// membership (1) and it has no revision signal; 3 changed remotely.
revised.remote_updated_at = Some(200);
record(&c, &[never, counted, revised, fresh]);
let queue = hydration_queue(&c).unwrap();
let ids: Vec<u64> = queue.iter().map(|q| q.qobuz_playlist_id).collect();
assert_eq!(ids, vec![1, 3, 2]);
assert_eq!(queue[0].reason, StaleReason::NeverSynced);
assert_eq!(queue[1].reason, StaleReason::RemoteRevision);
assert_eq!(queue[2].reason, StaleReason::CountMismatch);
match index_state(&c).unwrap() {
MembershipIndexState::Updating { pending } => assert_eq!(pending, 3),
other => panic!("expected Updating, got {other:?}"),
}
}
#[test]
fn successful_sync_settles_the_queue_even_when_the_list_count_lags() {
// The 2026-08-30 smoke: one playlist re-fetched forever. A sync must
// CONVERGE — with revision evidence on both sides equal, a lagging
// list count is the list's problem, not a reason to fetch again.
let c = conn();
let mut e = entry(1, "Lagging", 10);
e.remote_updated_at = Some(100);
record(&c, &[e.clone()]);
replace_tracks(&c, 1, "Lagging", None, &[5, 6, 7]).unwrap();
// The list still reports the stale count 10 and the same revision.
record(&c, &[e]);
assert!(hydration_queue(&c).unwrap().is_empty());
assert_eq!(index_state(&c).unwrap(), MembershipIndexState::Complete);
}
#[test]
fn only_the_playlists_the_list_reports_changed_requeue() {
let c = conn();
let mut a = entry(1, "A", 2);
a.remote_updated_at = Some(100);
let mut b = entry(2, "B", 2);
b.remote_updated_at = Some(100);
record(&c, &[a.clone(), b.clone()]);
replace_tracks(&c, 1, "A", None, &[1, 2]).unwrap();
replace_tracks(&c, 2, "B", None, &[3, 4]).unwrap();
assert!(hydration_queue(&c).unwrap().is_empty());
// Only B changed remotely.
b.remote_updated_at = Some(200);
record(&c, &[a, b]);
let queue = hydration_queue(&c).unwrap();
assert_eq!(queue.len(), 1);
assert_eq!(queue[0].qobuz_playlist_id, 2);
assert_eq!(queue[0].reason, StaleReason::RemoteRevision);
}
#[test]
fn index_state_lifecycle() {
let c = conn();
assert_eq!(index_state(&c).unwrap(), MembershipIndexState::Unavailable);
record(&c, &[entry(1, "A", 1)]);
assert!(matches!(
index_state(&c).unwrap(),
MembershipIndexState::Updating { pending: 1 }
));
replace_tracks(&c, 1, "A", None, &[10]).unwrap();
assert_eq!(index_state(&c).unwrap(), MembershipIndexState::Complete);
}
#[test]
fn incremental_add_and_remove() {
let c = conn();
record(&c, &[entry(1, "A", 2), entry(2, "Uncaptured", 3)]);
replace_tracks(&c, 1, "A", None, &[10, 20]).unwrap();
assert!(apply_added_tracks(&c, 1, &[30, 40]).unwrap());
assert_eq!(track_ids(&c, 1).unwrap(), vec![10, 20, 30, 40]);
let h = get_header(&c, 1).unwrap().unwrap();
assert_eq!(h.membership_count, Some(4));
assert_eq!(h.track_count, Some(4));
assert!(apply_removed_tracks(&c, 1, &[20, 30]).unwrap());
assert_eq!(track_ids(&c, 1).unwrap(), vec![10, 40]);
assert_eq!(
get_header(&c, 1).unwrap().unwrap().membership_count,
Some(2)
);
// A playlist whose membership was never captured refuses the
// increment — the hydrator owns it (its queue entry stays).
assert!(!apply_added_tracks(&c, 2, &[1]).unwrap());
assert!(track_ids(&c, 2).unwrap().is_empty());
assert!(hydration_queue(&c)
.unwrap()
.iter()
.any(|q| q.qobuz_playlist_id == 2));
}
#[test]
fn created_playlist_is_captured_and_survives_one_list_miss() {
let c = conn();
record(&c, &[entry(1, "A", 0)]);
record_created_playlist(&c, 9, "Brand new", Some("me")).unwrap();
let h = get_header(&c, 9).unwrap().unwrap();
assert!(h.is_owned);
assert_eq!(h.membership_count, Some(0));
// Immediate add applies incrementally — no fetch needed.
assert!(apply_added_tracks(&c, 9, &[5]).unwrap());
assert_eq!(track_ids(&c, 9).unwrap(), vec![5]);
// One authoritative list that does not include it yet (Qobuz
// post-write lag): still active.
record(&c, &[entry(1, "A", 0)]);
assert!(!get_header(&c, 9).unwrap().unwrap().inactive);
}
#[test]
fn legacy_schema_backfill() {
// A DB created by the pre-2.1.1 module: single-stamp schema.
let c = Connection::open_in_memory().unwrap();
c.execute_batch(
"CREATE TABLE qobuz_playlist_snapshot (
qobuz_playlist_id INTEGER PRIMARY KEY,
name TEXT NOT NULL, owner TEXT, track_count INTEGER,
snapped_at INTEGER NOT NULL);
CREATE TABLE qobuz_playlist_snapshot_tracks (
qobuz_playlist_id INTEGER NOT NULL,
position INTEGER NOT NULL,
track_id INTEGER NOT NULL);
INSERT INTO qobuz_playlist_snapshot VALUES (1, 'With tracks', NULL, 2, 111);
INSERT INTO qobuz_playlist_snapshot VALUES (2, 'Names only', NULL, 7, 222);
INSERT INTO qobuz_playlist_snapshot_tracks VALUES (1, 0, 10), (1, 1, 20);",
)
.unwrap();
init_schema(&c).unwrap();
let with_tracks = get_header(&c, 1).unwrap().unwrap();
assert_eq!(with_tracks.header_updated_at, Some(111));
assert_eq!(with_tracks.membership_synced_at, Some(111));
assert_eq!(with_tracks.membership_count, Some(2));
let names_only = get_header(&c, 2).unwrap().unwrap();
assert_eq!(names_only.header_updated_at, Some(222));
assert!(names_only.membership_synced_at.is_none());
// Idempotent re-run.
init_schema(&c).unwrap();
}
}
+7
View File
@@ -828,6 +828,10 @@ pub struct Playlist {
pub image_rectangle_mini: Option<Vec<String>>,
pub slug: Option<String>,
pub users_count: Option<u32>,
/// API revision stamp (unix seconds). The membership index reads it as
/// change evidence when the API provides it; absent on some list shapes.
#[serde(default)]
pub updated_at: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -869,6 +873,9 @@ pub struct PlaylistWithTrackIds {
pub images300: Option<Vec<String>>,
pub slug: Option<String>,
pub users_count: Option<u32>,
/// API revision stamp (unix seconds), when the response carries one.
#[serde(default)]
pub updated_at: Option<i64>,
}
/// Result of checking for duplicate tracks in a playlist
+9 -1
View File
@@ -41,6 +41,11 @@ Rectangle {
property string genre: ""
property string year: ""
property string qualityTier: ""
/// Exact stored quality ("24-bit / 96 kHz"), shown by the badge's hover
/// tooltip. Hosts whose model has no detail (un-hydrated Plex/remote
/// rows) may pass the bare filetype ("FLAC") — known limitation, and
/// still truthful; empty shows no tooltip at all.
property string qualityDetail: ""
property string ribbon: ""
property string ribbonKind: ""
// Artwork image source (file://… or "") — the host's cache lookup.
@@ -831,10 +836,13 @@ Rectangle {
elide: Text.ElideRight
}
}
// Icon-only quality badge (QualityBadge.slint).
// Icon-only quality badge (QualityBadge.slint). `label` feeds the
// badge's own hover tooltip with the exact stored quality; the
// badge shows nothing when the host has no detail to give.
QualityMini {
id: qBadge
tier: root.qualityTier
label: root.qualityDetail
anchors.verticalCenter: parent.verticalCenter
}
}
@@ -42,6 +42,20 @@ Item {
readonly property var rows: doc.playlists || []
readonly property var dup: doc.dup || ({})
readonly property int trackCount: doc.trackCount || 0
// Session-local pinned target (last successful add); null when unset,
// deleted, unwritable, or filtered out by the current query.
readonly property var lastUsed: doc.lastUsed || null
// Containment strip: writable playlists already holding carried tracks,
// honest per alreadyState ("loading"|"complete"|"updating"|"unavailable").
readonly property var alreadyIn: doc.alreadyIn || []
readonly property string alreadyState: doc.alreadyState || ""
// The column renders only when it can back a claim: complete with
// matches, or updating (where partial matches show under an explicit
// caveat). It is a SIDE column, not an in-flow strip, so the dropdown
// can never cover it.
readonly property bool alreadyShowing:
root.alreadyState === "updating"
|| (root.alreadyState === "complete" && root.alreadyIn.length > 0)
// The carried payload is LocalLibrary refs (counter wording only).
readonly property bool localMode: doc.localMode === true
readonly property bool creatingOpen: doc.creatingOpen === true
@@ -100,20 +114,23 @@ Item {
anchors.fill: parent
visible: root.doc.open === true && root.dup.open !== true
// Scrim — click outside dismisses.
// Scrim — click outside dismisses. The wheel is eaten too: these
// overlays are plain Items, not Popups, so no modal grab stops the
// page underneath from scrolling (the DiscoverConfigModal contract).
Rectangle {
anchors.fill: parent
color: "#bf000000"
MouseArea {
anchors.fill: parent
onClicked: QbzPlaylistPicker.close()
onWheel: function (wheel) { wheel.accepted = true }
}
}
Rectangle {
id: card
anchors.centerIn: parent
width: Math.min(parent.width - 80, 490)
width: Math.min(parent.width - 80, 735)
// Tauri: min-height 400 / max-height 90vh. The body stretches so
// the footer pins to the bottom.
height: Math.min(Math.max(400, panel.implicitHeight), parent.height * 0.9)
@@ -123,11 +140,17 @@ Item {
border.color: theme.borderSubtle
// NO clip: the dropdown legitimately overflows the card bottom.
// The "Already in" side column's slot. Zero when absent, so the
// main content takes the whole card.
readonly property real rightPanelW: root.alreadyShowing ? 221 : 0
// Swallow clicks so they never reach the scrim; doubles as
// "a click inside the card closes the list" (Tauri parity).
// The wheel stops here too — same reason as the scrim.
MouseArea {
anchors.fill: parent
onClicked: root.dropdownOpen = false
onWheel: function (wheel) { wheel.accepted = true }
}
Column {
@@ -174,10 +197,11 @@ Item {
}
Rectangle { width: parent.width; height: 1; color: theme.borderSubtle }
// --- Body ---------------------------------------------
// --- Body (the MAIN column; the "Already in" side column
// takes the right slot when present) -------------------
Column {
id: body
width: parent.width
width: parent.width - card.rightPanelW
padding: 24
spacing: 16
@@ -368,11 +392,127 @@ Item {
}
}
}
}
}
// --- "Already in" side column -----------------------------
// The containment answer as a right-hand column instead of an
// in-flow strip: the dropdown overlays the MAIN column only, so
// this list stays readable while the playlist list is open.
// Shown if and only if the index can back a claim (complete with
// matches, or updating under the explicit caveat) — an empty
// answer from an incomplete index renders nothing.
Item {
visible: root.alreadyShowing
anchors.top: parent.top
anchors.topMargin: 69
anchors.bottom: footerDivider.top
anchors.right: parent.right
width: card.rightPanelW
Rectangle {
anchors.left: parent.left
anchors.top: parent.top
anchors.bottom: parent.bottom
width: 1
color: theme.borderSubtle
}
Column {
anchors.fill: parent
anchors.leftMargin: 17
anchors.rightMargin: 16
anchors.topMargin: 16
spacing: 8
Text {
text: QbzSession.tr("Already in", QbzSession.trRev)
color: theme.textSecondary
font.pixelSize: theme.fontLegal
font.weight: theme.weightMedium
}
Text {
visible: root.alreadyState === "updating"
width: parent.width
text: QbzSession.tr("Playlist index updating...", QbzSession.trRev)
color: theme.textMuted
font.pixelSize: theme.fontLegal
font.italic: true
wrapMode: Text.WordWrap
}
ListView {
width: parent.width
height: Math.max(0, parent.height - y - 12)
clip: true
spacing: 2
boundsBehavior: Flickable.StopAtBounds
model: root.alreadyIn
delegate: Rectangle {
required property var modelData
width: parent ? parent.width : 0
height: 34
radius: theme.radiusSm
color: alreadyArea.containsMouse
? theme.surfaceHover : "transparent"
QbzIcon {
id: alreadyGlyph
visible: modelData.isLocal === true
anchors.left: parent.left
anchors.leftMargin: 6
anchors.verticalCenter: parent.verticalCenter
name: "hard-drive"
width: 12
height: 12
tintName: "muted"
}
Text {
anchors.left: alreadyGlyph.visible
? alreadyGlyph.right : parent.left
anchors.leftMargin: 6
anchors.right: alreadyCount.visible
? alreadyCount.left : parent.right
anchors.rightMargin: 6
anchors.verticalCenter: parent.verticalCenter
text: modelData.name
color: theme.textPrimary
font.pixelSize: theme.fontLegal
elide: Text.ElideRight
}
// The multi-track answer: "2 of 5". A full or
// single-track containment says it by presence.
Text {
id: alreadyCount
visible: root.trackCount > 1
&& modelData.contained < root.trackCount
anchors.right: parent.right
anchors.rightMargin: 6
anchors.verticalCenter: parent.verticalCenter
text: QbzSession.tr("{} of {}", QbzSession.trRev)
.replace("{}", modelData.contained)
.replace("{}", root.trackCount)
color: theme.textMuted
font.pixelSize: theme.fontLegal
}
MouseArea {
id: alreadyArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
// Selecting it is the useful action: "add the
// missing 3 of 5" is one click plus the
// dup-confirm's only-new answer.
onClicked: root.selectRow(modelData)
}
}
}
}
}
// --- Footer, pinned to the card bottom --------------------
Rectangle {
id: footerDivider
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: footerRow.top
@@ -425,10 +565,14 @@ Item {
// 1 divider + 24 body pad + 20 label row + 8 spacing +
// 43 input + 4 gap.
y: 68 + 1 + 24 + 20 + 8 + 43 + 4
width: parent.width - 48
// create row 41 + 1 divider, 41 per shown row, 41 no-results,
// 1 + 34 overflow. Tauri max-height 320 + border.
height: Math.min(2 + 42 + root.shown * 41
// MAIN column only — the "Already in" side column stays
// readable while the list is open (that is its whole point).
width: parent.width - card.rightPanelW - 48
// create row 41 + 1 divider, pinned last-used 41 + 1, 41 per
// shown row, 41 no-results, 1 + 34 overflow. Tauri max-height
// 320 + border.
height: Math.min(2 + 42 + (root.lastUsed !== null ? 42 : 0)
+ root.shown * 41
+ ((root.rows.length === 0 && root.filterText !== "") ? 41 : 0)
+ (root.overflow > 0 ? 35 : 0), 322)
radius: theme.radiusSm
@@ -487,6 +631,61 @@ Item {
}
Rectangle { width: parent.width; height: 1; color: theme.borderSubtle }
// Session's last successful target, pinned above the
// results. Rust already validated it (still listed,
// still writable) and de-duplicated it from `rows`;
// under a search it only survives a matching query.
Rectangle {
visible: root.lastUsed !== null
width: parent.width
height: visible ? 41 : 0
color: lastUsedArea.containsMouse ? theme.surfaceHover : "transparent"
QbzIcon {
id: lastUsedGlyph
anchors.left: parent.left
anchors.leftMargin: 12
anchors.verticalCenter: parent.verticalCenter
name: "clock"
width: 14
height: 14
tintName: "muted"
}
Text {
anchors.left: lastUsedGlyph.right
anchors.leftMargin: 8
anchors.right: lastUsedCaption.left
anchors.rightMargin: 8
anchors.verticalCenter: parent.verticalCenter
text: root.lastUsed ? root.lastUsed.name : ""
color: theme.textPrimary
font.pixelSize: theme.fontLink
elide: Text.ElideRight
}
Text {
id: lastUsedCaption
anchors.right: parent.right
anchors.rightMargin: 12
anchors.verticalCenter: parent.verticalCenter
text: QbzSession.tr("Last playlist", QbzSession.trRev)
color: theme.textMuted
font.pixelSize: theme.fontLegal
font.italic: true
}
MouseArea {
id: lastUsedArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: root.selectRow(root.lastUsed)
}
}
Rectangle {
visible: root.lastUsed !== null
width: parent.width
height: visible ? 1 : 0
color: theme.borderSubtle
}
Repeater {
model: root.rows.slice(0, root.windowSize)
delegate: Rectangle {
@@ -590,6 +789,7 @@ Item {
MouseArea {
anchors.fill: parent
onClicked: QbzPlaylistPicker.cancelDuplicates()
onWheel: function (wheel) { wheel.accepted = true }
}
}
@@ -601,7 +801,10 @@ Item {
color: theme.surfaceCard
border.width: 1
border.color: theme.borderSubtle
MouseArea { anchors.fill: parent }
MouseArea {
anchors.fill: parent
onWheel: function (wheel) { wheel.accepted = true }
}
Column {
id: dupPanel
+19 -5
View File
@@ -141,6 +141,14 @@ Rectangle {
// `playlist add-tracks` as a QOBUZ catalog id — a local row dropped on a
// playlist would silently add an unrelated catalog track.
property bool draggable: true
/// LOCAL-mode drag arm (2026-08-30): the row IS a drag source, but its
/// `item.id` is a LOCAL library row id, so it enters the shared drag via
/// `dragStartLocal` — a typed payload the drop handlers resolve
/// source-aware, never a number that could be read as a catalog id.
/// Independent of `draggable` on purpose: `catalogRow` below keeps
/// meaning "item.id is a Qobuz catalog id".
property bool localDragSource: false
readonly property bool dragSource: root.draggable || root.localDragSource
/// A live transport guard separate from catalogue availability. The full
/// queue uses it when QConnect is active: incompatible rows stay visible
/// and keep their non-transport menu actions, but cannot play or drag.
@@ -1471,7 +1479,7 @@ Rectangle {
// later, `onCanceled` fired, and the drag died at roughly the row
// boundary — never reaching the sidebar. Arming at 6px and claiming
// the grab there wins the race by construction, because 6 < 10.
preventStealing: (root.reorderDrag && root.draggable && !root.selectMode)
preventStealing: (root.reorderDrag && root.dragSource && !root.selectMode)
|| root.dragging
onPressed: function (mouse) {
if (mouse.button === Qt.RightButton) {
@@ -1491,7 +1499,7 @@ Rectangle {
// A dead row is not a drag source either: dropping it on a sidebar
// playlist would add a track that cannot play, which is precisely
// the state this treatment exists to stop spreading.
if (!pressed || !(pressedButtons & Qt.LeftButton) || !root.draggable
if (!pressed || !(pressedButtons & Qt.LeftButton) || !root.dragSource
|| root.selectMode || root.pulledDead || root.playBlocked) return
const g = mapToItem(null, mouse.x, mouse.y)
const dx = mouse.x - root.downPos.x
@@ -1519,9 +1527,15 @@ Rectangle {
if (!root.dragging && armed) {
root.dragging = true
root.bodyDragStarted(root.number)
QbzShell.dragStart(root.item.id, root.item.title || "",
(root.item.artist || "") + " · " + (root.item.album || ""),
g.x, g.y, root.inlineDragVisual)
if (root.localDragSource)
QbzShell.dragStartLocal(String(root.item.id),
root.item.title || "",
(root.item.artist || "") + " · " + (root.item.album || ""),
g.x, g.y, root.inlineDragVisual)
else
QbzShell.dragStart(root.item.id, root.item.title || "",
(root.item.artist || "") + " · " + (root.item.album || ""),
g.x, g.y, root.inlineDragVisual)
}
if (root.dragging) QbzShell.dragMove(g.x, g.y)
}
@@ -388,6 +388,7 @@ Column {
genre: gcell.modelData.genre
year: gcell.modelData.year
qualityTier: gcell.modelData.qualityTier
qualityDetail: gcell.modelData.qualityDetail || ""
ribbon: gcell.modelData.ribbon || ""
ribbonKind: gcell.modelData.ribbonKind || ""
artSource: root.artOf(gcell.modelData)
@@ -562,6 +563,7 @@ Column {
genre: cell.cardData.genre
year: cell.cardData.year
qualityTier: cell.cardData.qualityTier
qualityDetail: cell.cardData.qualityDetail || ""
ribbon: cell.cardData.ribbon || ""
ribbonKind: cell.cardData.ribbonKind || ""
artSource: root.artOf(cell.cardData)
+19 -7
View File
@@ -1331,14 +1331,22 @@ Rectangle {
font.pixelSize: 13
horizontalAlignment: Text.AlignHCenter
}
Text {
// The SAME bare badge the shared TrackRow's quality cell mounts
// (rows/TrackRow.qml:1048): tier label stacked over the exact
// "24-bit / 96 kHz" line. This fork used to render a lone tier
// word ("HI-RES") even though the document has carried
// qualityDetail all along.
Item {
width: cols.colQuality
anchors.verticalCenter: parent.verticalCenter
text: row.qualityTier === "hires" ? "HI-RES" : (row.qualityTier === "cd" ? "CD" : "")
color: theme.textMuted
font.pixelSize: 10
font.weight: theme.weightBold
horizontalAlignment: Text.AlignHCenter
height: parent.height
QualityBadgeFull {
anchors.centerIn: parent
tier: row.qualityTier || ""
detail: row.qualityDetail || ""
showIcon: false
bare: true
maxTextWidth: cols.colQuality
}
}
// Favorite (live). Reads through the override map so the state
// survives a document republish (see root.localToggles).
@@ -1959,6 +1967,7 @@ Rectangle {
genre: modelData.genre
year: modelData.year
qualityTier: modelData.qualityTier
qualityDetail: modelData.qualityDetail || ""
artSource: root.coverMap[modelData.artUrl] || ""
// artist_qt `map_release` stamps the pin state on every
// release row; SectionRail is the only other reader and
@@ -2636,6 +2645,7 @@ Rectangle {
genre: root.artist.lastRelease ? root.artist.lastRelease.genre : ""
year: root.artist.lastRelease ? root.artist.lastRelease.year : ""
qualityTier: root.artist.lastRelease ? root.artist.lastRelease.qualityTier : ""
qualityDetail: root.artist.lastRelease ? (root.artist.lastRelease.qualityDetail || "") : ""
artSource: root.artist.lastRelease ? (root.coverMap[root.artist.lastRelease.artUrl] || "") : ""
// Same row shape as the release grids (map_release).
isPinned: root.artist.lastRelease ? root.artist.lastRelease.isPinned === true : false
@@ -2785,6 +2795,7 @@ Rectangle {
genre: modelData.genre
year: modelData.year
qualityTier: modelData.qualityTier
qualityDetail: modelData.qualityDetail || ""
artSource: root.coverMap[modelData.artUrl] || ""
isPinned: modelData.isPinned === true
artworkUrl: modelData.artUrl || ""
@@ -2865,6 +2876,7 @@ Rectangle {
genre: modelData.genre
year: modelData.year
qualityTier: modelData.qualityTier
qualityDetail: modelData.qualityDetail || ""
artSource: root.coverMap[modelData.imageUrl] || ""
// These rows are LIBRARY feed items (FeedItem),
// not release cards: the remote url is
+2
View File
@@ -607,6 +607,7 @@ Rectangle {
genre: modelData.genre
year: modelData.year
qualityTier: modelData.qualityTier
qualityDetail: modelData.qualityLabel || modelData.qualityDetail || ""
ribbon: modelData.ribbon
ribbonKind: modelData.ribbonKind
artSource: root.sectionArtOf(modelData)
@@ -1262,6 +1263,7 @@ Rectangle {
genre: modelData.album.genre
year: modelData.album.year
qualityTier: modelData.album.qualityTier
qualityDetail: modelData.album.qualityLabel || modelData.album.qualityDetail || ""
artSource: root.forYouArtOf(modelData.album)
artworkUrl: modelData.album.artUrl || ""
isPinned: modelData.album.isPinned === true
+1
View File
@@ -218,6 +218,7 @@ Rectangle {
genre: crCell.modelData.genre
year: crCell.modelData.year
qualityTier: crCell.modelData.qualityTier
qualityDetail: crCell.modelData.qualityDetail || ""
ribbon: crCell.modelData.ribbon || ""
ribbonKind: crCell.modelData.ribbonKind || ""
artSource: crCell.modelData.artPath || ""
+3
View File
@@ -351,6 +351,7 @@ Rectangle {
genre: resultCell.cardData.genre
year: resultCell.cardData.year
qualityTier: resultCell.cardData.qualityTier
qualityDetail: resultCell.cardData.qualityDetail || ""
artSource: resultCell.cardData.artPath || ""
isFavorite: resultCell.cardData.isFavorite === true
isPinned: resultCell.cardData.isPinned === true
@@ -757,6 +758,7 @@ Rectangle {
genre: (root.mp.album || ({})).genre || ""
year: (root.mp.album || ({})).year || ""
qualityTier: (root.mp.album || ({})).qualityTier || ""
qualityDetail: (root.mp.album || ({})).qualityDetail || ""
artSource: (root.mp.album || ({})).artPath || ""
// search_qt::map_album stamps the heart
// from fav_cache; false inverted the
@@ -879,6 +881,7 @@ Rectangle {
genre: modelData.genre
year: modelData.year
qualityTier: modelData.qualityTier
qualityDetail: modelData.qualityDetail || ""
artSource: modelData.artPath || ""
// search_qt::map_album stamps the heart
// from fav_cache; false made the glyph lie
+1
View File
@@ -63,6 +63,7 @@ Column {
genre: modelData.genre
year: modelData.year
qualityTier: modelData.qualityTier
qualityDetail: modelData.qualityDetail || ""
artSource: root.coverMap[modelData.artUrl] || ""
// The row carries the heart (home_qt / recommendations_qt
// stamp it from fav_cache at build time); hardcoding false
@@ -81,6 +81,7 @@ Item {
genre: cell.item.genre
year: cell.item.year
qualityTier: cell.item.qualityTier
qualityDetail: cell.item.qualityDetail || cell.item.qualityLabel || ""
artSource: cell.view.artMap[cell.item.artKey] || ""
isFavorite: cell.item.isFavorite
isPinned: cell.item.isPinned
@@ -436,6 +436,7 @@ Item {
genre: gcell.modelData.genre
year: gcell.modelData.year
qualityTier: gcell.modelData.qualityTier
qualityDetail: gcell.modelData.qualityDetail || ""
artSource: root.coverMap[gcell.modelData.artUrl] || ""
// The pin payload persists the REMOTE
// url, never the file:// cache path.
@@ -477,6 +477,7 @@ Item {
genre: ""
year: cardCell.slot.year
qualityTier: cardCell.slot.qualityTier
qualityDetail: cardCell.slot.qualityDetail || ""
artSource: cardCell.slot.artPath || (root.view
? (root.view.artMap[cardCell.slot.artKey] || "") : "")
pinArtworkUrl: artSource
@@ -134,9 +134,16 @@ Item {
showFavorite: false
showDownload: false
showMenu: false
// Local rows are NOT drag sources: item.id is a local DB row id and
// the sidebar drop handler forwards it as a Qobuz catalog id.
// Local rows drag through the LOCAL arm: item.id is a local DB row
// id, so the shared drag carries it typed (`dragStartLocal`) and the
// drop handlers resolve it source-aware — the same guardrails as the
// picker. `draggable` stays false so `catalogRow` keeps meaning
// "item.id is a Qobuz catalog id".
draggable: false
// NOT for native-catalog rows: their `item.id` is the catalog seam's
// identity, not a legacy row id the drop resolver can look up — a
// ghost that lands as a silent no-op is worse than no gesture.
localDragSource: !root.nativeActions
qualityStyle: "icon"
// A failed physical row stays clickable so the user can retry after a
// drive returns. The preflight prevents any queue/NPB mutation until
@@ -957,6 +957,7 @@ Rectangle {
readonly property string cSubtitle: root.patchRev >= 0 ? (gcell.live.subtitle || "") : ""
readonly property string cYear: root.patchRev >= 0 ? (gcell.live.yearText || "") : ""
readonly property string cQuality: root.patchRev >= 0 ? (gcell.live.qualityTier || "") : ""
readonly property string cDetail: root.patchRev >= 0 ? (gcell.live.qualityDetail || "") : ""
/// The GRID rung of the cover, NOT the list row's.
/// `artPath` is the 50px thumbnail every list row draws
/// at 40px; this cell's artwork well is 200px, so
@@ -1084,6 +1085,7 @@ Rectangle {
genre: ""
year: gcell.cYear
qualityTier: gcell.cQuality
qualityDetail: gcell.cDetail
artSource: gcell.cArt
// The pin payload / block snapshot url (see
// `cArtUrl`). Without it a pinned My QBZ album
+10
View File
@@ -876,10 +876,20 @@ pub fn add_to_playlist(id: String) {
log::warn!("[qbz-qt] local album add-to-playlist: no version open for album '{id}'");
return;
}
open_picker_for_rows(&tracks);
}
/// The shared tail of every local add-to-playlist entry: source-aware refs
/// (`local_picker_ref_for_track` — Plex and Jellyfin/Subsonic ride their
/// source-native keys, everything else its library row id), then the picker.
pub(crate) fn open_picker_for_rows(tracks: &[qbz_library::LocalTrack]) {
let refs: Vec<String> = tracks
.iter()
.map(crate::local_playlist_qt::local_picker_ref_for_track)
.collect();
if refs.is_empty() {
return;
}
crate::playlist_picker_qt::open_for_local_refs(&crate::app(), refs);
}
+18 -5
View File
@@ -165,6 +165,16 @@ fn resolve_blocking(scope: &str, ids: &[String]) -> Vec<LocalTrack> {
s.tracks_raw
.iter()
.chain(s.detail_raw.iter())
// The Library Explorer's expanded albums live in their own row
// cache. Without these, an Explorer track menu resolved through
// this function silently dropped every merged Plex/remote row —
// "Add to playlist" opened nothing (smoke 2026-08-30).
.chain(s.genre_detail_raw.values().flatten())
.chain(
s.genre_detail_all_tracks
.values()
.flat_map(|arc| arc.iter()),
)
.map(|t| (t.id, t.clone()))
.collect()
});
@@ -182,6 +192,12 @@ fn resolve_blocking(scope: &str, ids: &[String]) -> Vec<LocalTrack> {
.collect()
}
/// Track-scope resolution for callers outside the bulk bars (the shared
/// drag's local payload): same caches, same last-resort DB lookup.
pub(crate) fn resolve_track_rows_blocking(ids: &[String]) -> Vec<LocalTrack> {
resolve_blocking("track", ids)
}
pub(crate) fn resolve_album_ids_blocking(ids: &[String]) -> Vec<LocalTrack> {
ids.iter()
.flat_map(|key| fetch_album_tracks_blocking(key))
@@ -245,11 +261,8 @@ pub(crate) async fn apply(rows: Vec<LocalTrack>, action: &str) -> bool {
if rows.is_empty() {
return false;
}
let refs: Vec<String> = rows
.iter()
.map(crate::local_playlist_qt::local_picker_ref_for_track)
.collect();
crate::playlist_picker_qt::open_for_local_refs(&crate::app(), refs);
// Shared tail: source-aware refs, then the picker.
crate::local_album_actions::open_picker_for_rows(&rows);
false
}
// NO CALLER as of 2026-07-31: no bulk bar offers this action any more.
+175 -7
View File
@@ -242,6 +242,10 @@ pub fn add_local_refs_blocking(id: &str, refs: &[String]) -> usize {
for r in refs {
if let Some(key) = r.strip_prefix("plex:") {
out.push(repo::LocalPlaylistTrackInput::Plex(key.to_string()));
} else if let Some(item) = r.strip_prefix("jellyfin:") {
out.push(repo::LocalPlaylistTrackInput::Jellyfin(item.to_string()));
} else if let Some(item) = r.strip_prefix("subsonic:") {
out.push(repo::LocalPlaylistTrackInput::Subsonic(item.to_string()));
} else if let Ok(rid) = r.parse::<i64>() {
if let Some(input) = local_row_input(db, rid)? {
out.push(input);
@@ -256,6 +260,54 @@ pub fn add_local_refs_blocking(id: &str, refs: &[String]) -> usize {
add_inputs_blocking(id, &entries)
}
/// Resolve carried local-mode refs into the TYPED membership refs the
/// containment index takes (`qbz_library::playlist_membership`). Shares
/// [`local_row_input`]'s worldview: a Plex ref is its rating key, and a
/// library row contributes its path plus — for offline copies — its catalog
/// id. An unresolvable row id still yields a ref (row-id-only), so sidecar
/// membership can answer even when the row vanished from the library.
pub fn membership_refs_blocking(
refs: &[String],
) -> Vec<qbz_library::playlist_membership::PlaylistTrackRef> {
use qbz_library::playlist_membership::PlaylistTrackRef;
with_db(false, |db| {
let mut out = Vec::new();
for r in refs {
if let Some(key) = r.strip_prefix("plex:") {
out.push(PlaylistTrackRef::Plex {
rating_key: key.to_string(),
});
} else if let Some(item) = r.strip_prefix("jellyfin:") {
out.push(PlaylistTrackRef::Remote {
source: "jellyfin".to_string(),
item_id: item.to_string(),
});
} else if let Some(item) = r.strip_prefix("subsonic:") {
out.push(PlaylistTrackRef::Remote {
source: "subsonic".to_string(),
item_id: item.to_string(),
});
} else if let Ok(rid) = r.parse::<i64>() {
out.push(match db.get_track(rid)? {
Some(track) => PlaylistTrackRef::from_library_row(
track.source.as_deref().unwrap_or("local"),
rid,
&track.file_path,
track.qobuz_track_id.map(|v| v as u64),
),
None => PlaylistTrackRef::Library {
track_id: rid,
path: None,
qobuz_track_id: None,
},
});
}
}
Ok(out)
})
.unwrap_or_default()
}
// ──────────────────────────── custom artwork ────────────────────────────
// There is deliberately NO `set_custom_artwork_blocking` twin of the clear
@@ -321,6 +373,24 @@ pub fn resolve_cover_urls_blocking(id: &str, limit: usize) -> Vec<String> {
}
}
}
repo::LocalPlaylistTrackSource::Jellyfin | repo::LocalPlaylistTrackSource::Subsonic => {
if let Some(item) = t.local_path {
let source = t.source.as_str().to_string();
let resolved = crate::media_servers_qt::tracks_by_item_ids_blocking(&[(
source.clone(),
item.clone(),
0,
)]);
if let Some(art) = resolved
.get(&(source, item))
.and_then(|lt| lt.artwork_path.clone())
{
if !covers.contains(&art) {
covers.push(art);
}
}
}
}
// Qobuz rows would fill their slot from the async offline cache in
// the reference; this blocking sidebar helper cannot enter it.
repo::LocalPlaylistTrackSource::Qobuz => {}
@@ -501,7 +571,7 @@ pub fn read_sidecar_rows_blocking(
qobuz_track_count: u32,
include_plex: bool,
) -> Vec<LoadedRow> {
let (mut rows, plex_refs) = with_db(false, |db| {
let (mut rows, plex_refs, remote_refs) = with_db(false, |db| {
match db.heal_playlist_sidecar_positions(playlist_id, qobuz_track_count) {
Ok(healed) => {
for entry in &healed {
@@ -527,7 +597,8 @@ pub fn read_sidecar_rows_blocking(
} else {
Vec::new()
};
Ok((rows, plex_refs))
let remote_refs = db.get_playlist_remote_tracks_with_position(playlist_id)?;
Ok((rows, plex_refs, remote_refs))
})
.unwrap_or_default();
@@ -565,6 +636,36 @@ pub fn read_sidecar_rows_blocking(
},
}));
}
// Jellyfin/Subsonic sidecars — the Plex pattern against the media cache.
// A miss renders the honest Unresolved row, never a vanished one.
if !remote_refs.is_empty() {
let resolved = crate::media_servers_qt::tracks_by_item_ids_blocking(&remote_refs);
rows.extend(
remote_refs
.into_iter()
.map(|(source, item, position)| LoadedRow {
position,
item: match resolved.get(&(source.clone(), item.clone())) {
Some(track) => RowItem::Local(Box::new(track.clone())),
None => {
log::warn!(
"[qbz-qt] playlist {playlist_id}: {source} item {item:?} not in \
the media cache — rendered as unavailable"
);
RowItem::Unresolved {
kind: if source == "jellyfin" {
"jellyfin"
} else {
"subsonic"
},
reference: item,
}
}
},
}),
);
}
rows
}
@@ -615,6 +716,12 @@ pub fn local_picker_ref_for_row(id: &str) -> Option<String> {
.source_item_id_hint
.as_ref()
.map(|key| format!("plex:{key}")),
// Remote rows carry the server item id in the hint slot, same as
// Plex carries the rating key (media_servers_qt::cached_to_local_track).
Some(source @ ("jellyfin" | "subsonic")) => q
.source_item_id_hint
.as_ref()
.map(|item| format!("{source}:{item}")),
Some("local") => Some(q.id.to_string()),
// An OFFLINE COPY row (`local_playback::local_queue_track` tags these
// "qobuz_download"). It reaches this function because `row_to_display`
@@ -644,11 +751,17 @@ pub fn local_picker_ref_for_row(id: &str) -> Option<String> {
/// library row id. A Plex row must NEVER ride its numeric id — the synthetic
/// 2^40 ids do not resolve through `get_track`, and typing one as a Qobuz id
/// is the legacy bug that wrote permanently unresolvable rows.
///
/// Jellyfin/Subsonic rows likewise NEVER ride their numeric id — it is a
/// media-cache rowid, which `local_row_input`'s `get_track` would happily
/// resolve against `local_tracks` (the same number, a DIFFERENT track). Like
/// Plex, their playlist identity is the source-native key their projection
/// keeps in `file_path`: the server item id, carried source-prefixed.
pub fn local_picker_ref_for_track(track: &qbz_library::LocalTrack) -> String {
if track.source.as_deref() == Some("plex") {
format!("plex:{}", track.file_path)
} else {
track.id.to_string()
match track.source.as_deref() {
Some("plex") => format!("plex:{}", track.file_path),
Some(source @ ("jellyfin" | "subsonic")) => format!("{source}:{}", track.file_path),
_ => track.id.to_string(),
}
}
@@ -744,7 +857,14 @@ pub(crate) fn row_to_display(item: &RowItem) -> (PlaylistTrackRow, Option<QueueT
let source = if matches!(item, RowItem::Plex(_)) {
"plex"
} else {
"local"
// Remote sidecar rows resolve into RowItem::Local carrying
// their own source; publishing it is what keeps
// `local_picker_ref_for_row` and the queue typing honest.
match t.source.as_deref() {
Some("jellyfin") => "jellyfin",
Some("subsonic") => "subsonic",
_ => "local",
}
};
let row = PlaylistTrackRow {
id: queue.id.to_string(),
@@ -986,6 +1106,32 @@ pub async fn load(runtime: &Runtime, playlist_id: &str) -> bool {
.unwrap_or_default()
};
// Jellyfin/Subsonic rows: ONE bulk media-cache lookup by item id (their
// item id rides the local_path column, source-qualified).
let remote_refs: Vec<(String, String, i32)> = tracks
.iter()
.filter_map(|t| {
let source = match t.source {
repo::LocalPlaylistTrackSource::Jellyfin => "jellyfin",
repo::LocalPlaylistTrackSource::Subsonic => "subsonic",
_ => return None,
};
t.local_path
.clone()
.map(|item| (source.to_string(), item, 0))
})
.collect();
let remote_resolved: HashMap<(String, String), qbz_library::LocalTrack> =
if remote_refs.is_empty() {
HashMap::new()
} else {
tokio::task::spawn_blocking(move || {
crate::media_servers_qt::tracks_by_item_ids_blocking(&remote_refs)
})
.await
.unwrap_or_default()
};
let mut rows: Vec<LoadedRow> = Vec::new();
let (mut hidden, mut missing_files, mut unresolved) = (0usize, 0usize, 0usize);
for t in tracks {
@@ -1047,6 +1193,28 @@ pub async fn load(runtime: &Runtime, playlist_id: &str) -> bool {
}
}
}
repo::LocalPlaylistTrackSource::Jellyfin | repo::LocalPlaylistTrackSource::Subsonic => {
let source = t.source.as_str();
let item_id = t.local_path.clone().unwrap_or_default();
match remote_resolved.get(&(source.to_string(), item_id.clone())) {
Some(track) => RowItem::Local(Box::new(track.clone())),
None => {
unresolved += 1;
log::warn!(
"[qbz-qt] local playlist {id}: {source} item {item_id:?} not in \
the media cache — rendered as unavailable"
);
RowItem::Unresolved {
kind: if source == "jellyfin" {
"jellyfin"
} else {
"subsonic"
},
reference: item_id,
}
}
}
}
};
rows.push(LoadedRow {
position: t.position,
+99 -1
View File
@@ -318,6 +318,7 @@ mod external_reco_qt;
mod artist_qt;
mod lyrics_qt;
mod playback_qt;
mod playlist_index_qt;
mod playlist_picker_qt;
mod tunnelflow_qt;
// Playlist Importer controller (the `qbz-playlist-import` crate's frontend
@@ -2146,6 +2147,12 @@ pub(crate) fn playlist_move_row(row_id: String, delta: i32) {
// DragTrack enum also carries local-library rows and Plex keys into
// sidecar writes — out of scope, see module POC-NOTEs).
static DRAGGED: Mutex<Vec<u64>> = Mutex::new(Vec::new());
/// LOCAL-mode drag payload: Local Library row ids, resolved to source-aware
/// picker refs at DROP time (the rows can leave the visible cache between
/// press and release; ids survive that, refs are cheap to build once).
/// Mutually exclusive with `DRAGGED` — a drag carries one payload kind, the
/// same invariant the picker's `Payload` enum enforces.
static DRAGGED_LOCAL_ROWS: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// The claimed drop target (sidebar playlist id) — mirrored Rust-side so
/// drag_end never reads the bridge off-thread.
static DRAG_OVER: Mutex<String> = Mutex::new(String::new());
@@ -2164,6 +2171,7 @@ pub(crate) fn drag_start(
) {
let id = track_id.parse::<u64>().unwrap_or(0);
*DRAGGED.lock().unwrap() = if id > 0 { vec![id] } else { Vec::new() };
DRAGGED_LOCAL_ROWS.lock().unwrap().clear();
log::info!("[qbz-qt][drag] start {track_id} ({title})");
shell_bridge::ui(move |mut b| {
b.as_mut().set_drag_count(if id > 0 { 1 } else { 0 });
@@ -2179,6 +2187,35 @@ pub(crate) fn drag_start(
});
}
/// LOCAL-mode twin of [`drag_start`]: a Local Library / Explorer row enters
/// the shared drag carrying its ROW ID, never a number that could be read as
/// a catalog id (the picker's `Payload` invariant, kept at the drag seam).
pub(crate) fn drag_start_local(
row_id: String,
title: String,
subtitle: String,
x: f32,
y: f32,
inline_visual: bool,
) {
DRAGGED.lock().unwrap().clear();
let ok = !row_id.is_empty();
*DRAGGED_LOCAL_ROWS.lock().unwrap() = if ok { vec![row_id.clone()] } else { Vec::new() };
log::info!("[qbz-qt][drag] start local row {row_id} ({title})");
shell_bridge::ui(move |mut b| {
b.as_mut().set_drag_count(if ok { 1 } else { 0 });
b.as_mut().set_drag_title(QString::from(title.as_str()));
b.as_mut()
.set_drag_subtitle(QString::from(subtitle.as_str()));
b.as_mut().set_drag_x(x);
b.as_mut().set_drag_y(y);
b.as_mut().set_drag_inline_visual(inline_visual);
b.as_mut().set_drag_over_playlist_id(QString::default());
b.as_mut().set_drag_over_queue_index(-1);
b.as_mut().set_drag_active(true);
});
}
pub(crate) fn drag_move(x: f32, y: f32) {
shell_bridge::ui(move |mut b| {
b.as_mut().set_drag_x(x);
@@ -2211,9 +2248,70 @@ pub(crate) fn drag_end() {
b.as_mut().set_drag_over_queue_index(-1);
});
let tracks = std::mem::take(&mut *DRAGGED.lock().unwrap());
if tracks.is_empty() {
let local_rows = std::mem::take(&mut *DRAGGED_LOCAL_ROWS.lock().unwrap());
if tracks.is_empty() && local_rows.is_empty() {
return;
}
// LOCAL-mode payload: Explorer / Local Library rows, resolved to
// source-aware refs at drop time and routed through the picker's own
// add matrix — the "same guardrails" contract: a library row id can
// never reach a Qobuz endpoint, a Plex/remote row rides its server key.
if !local_rows.is_empty() {
let runtime = app();
let pid = pid.clone();
spawn(async move {
let rows = tokio::task::spawn_blocking(move || {
local_bulk::resolve_track_rows_blocking(&local_rows)
})
.await
.unwrap_or_default();
if rows.is_empty() {
log::warn!("[qbz-qt][drag] local drop resolved no rows; ignored");
return;
}
if queue_slot >= 0 {
let was_empty = runtime
.core()
.get_queue_state_full()
.await
.upcoming
.is_empty()
&& runtime.core().current_track().await.is_none();
let mut landed = false;
for (n, row) in rows.into_iter().enumerate() {
let qt = local_playback::local_queue_track(&row);
let slot = queue_slot as usize + n;
match queue_qt::insert_dragged_queue_track(&runtime, qt, slot).await {
Ok(()) => landed = true,
Err(e) => log::error!(
"[qbz-qt][drag] queue insert of local row {} at {slot} failed: {e}",
row.id
),
}
}
if was_empty && landed {
queue_qt::set_drop_play_prompt(true);
}
return;
}
if pid.is_empty() {
return;
}
let refs: Vec<String> = rows
.iter()
.map(local_playlist_qt::local_picker_ref_for_track)
.collect();
playlist_picker_qt::add_dropped_payload_to_target(
&runtime,
&pid,
playlist_picker_qt::Payload::LocalRefs(refs),
)
.await;
});
return;
}
// The QUEUE target wins when both are claimed. They cannot both be under
// the pointer geometrically, so this only decides a stale claim — and the
// queue one is the more recent, since the panel overlays the sidebar.
+50
View File
@@ -340,6 +340,56 @@ pub fn purge_cache(kind: MediaServerKind) {
/// - `album_group_key` is the PREFIXED key (`jellyfin:<albumId>`), matching the
/// one the grid's SQL union publishes, so "go to album" from a track row
/// lands on the same page the card opens.
/// Bulk media-cache resolution for playlist refs: `(source, item_id, _)`
/// rows to `(source, item_id) -> LocalTrack`. Misses are simply absent —
/// the caller renders them as honest Unresolved rows. Blocking.
pub fn tracks_by_item_ids_blocking(
refs: &[(String, String, i32)],
) -> std::collections::HashMap<(String, String), qbz_library::LocalTrack> {
let mut out = std::collections::HashMap::new();
for source_name in ["jellyfin", "subsonic"] {
let items: Vec<&str> = refs
.iter()
.filter(|(s, _, _)| s == source_name)
.map(|(_, item, _)| item.as_str())
.collect();
if items.is_empty() {
continue;
}
let (remote, read_source) = if source_name == "jellyfin" {
(qbz_media_cache::RemoteSource::Jellyfin, source_name)
} else {
(qbz_media_cache::RemoteSource::Subsonic, source_name)
};
let read = |conn: &rusqlite::Connection| {
items
.iter()
.filter_map(|item| {
qbz_media_cache::track_by_item_id(conn, remote, item)
.ok()
.flatten()
.map(cached_to_local_track)
.map(|track| ((read_source.to_string(), (*item).to_string()), track))
})
.collect::<Vec<_>>()
};
let resolved = match remote {
qbz_media_cache::RemoteSource::Jellyfin => qbz_source::registry()
.jellyfin()
.cache()
.with(read)
.unwrap_or_default(),
qbz_media_cache::RemoteSource::Subsonic => qbz_source::registry()
.subsonic()
.cache()
.with(read)
.unwrap_or_default(),
};
out.extend(resolved);
}
out
}
pub fn cached_to_local_track(t: qbz_media_cache::CachedTrack) -> qbz_library::LocalTrack {
let source = t.source.clone();
let source_instance = if t.server_id.trim().is_empty() {
+204
View File
@@ -0,0 +1,204 @@
//! Background Qobuz playlist-membership hydrator (2.1.1 picker redesign).
//!
//! The queue itself is pure and lives in
//! `qbz_library::qobuz_playlist_snapshot::hydration_queue` — missing, stale
//! and count/revision-mismatched memberships of OWNED playlists. This driver
//! only walks it: one `playlist/get?extra=track_ids` fetch at a time, paced,
//! with a bounded per-round retry budget, committing each snapshot
//! transactionally through `replace_tracks`. A network failure never touches
//! the previous good snapshot (nothing is written on the error arm).
//!
//! `poke()` is the only entry point. The authoritative-list producers call it
//! after every recorded generation (login, sidebar reload, playlist-manager
//! load), so reconnects and mutations re-arm it for free; a poke while a walk
//! is running coalesces into one more round instead of a second walker.
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use qbz_library::qobuz_playlist_snapshot as repo;
type Runtime = std::sync::Arc<qbz_app::shell::AppRuntime<qbz_core::LoggingAdapter>>;
/// Per-round fetch budget for one playlist before it is parked until the next
/// poke. Transient API errors get a second try; a persistent one must not
/// starve the rest of the queue.
const MAX_ATTEMPTS: u32 = 2;
/// Pace between fetches — the rate-limit courtesy the research doc requires.
const PACE_MS: u64 = 300;
static RUNNING: AtomicBool = AtomicBool::new(false);
static REPOKE: AtomicBool = AtomicBool::new(false);
/// Ask the hydrator to reconcile the membership snapshot with the latest
/// authoritative headers. Cheap and idempotent; safe from any thread.
pub fn poke() {
if crate::offline_fwd::engine().is_offline() {
return;
}
if RUNNING.swap(true, Ordering::SeqCst) {
REPOKE.store(true, Ordering::SeqCst);
return;
}
let runtime = crate::app();
crate::spawn(async move {
loop {
run_round(&runtime).await;
if !REPOKE.swap(false, Ordering::SeqCst) {
break;
}
}
RUNNING.store(false, Ordering::SeqCst);
// A poke can race the store above: it saw RUNNING=true and only set
// REPOKE. Pick that flag up rather than dropping the request.
if REPOKE.swap(false, Ordering::SeqCst) {
poke();
}
});
}
/// Pick the next candidate that still has retry budget and was not already
/// written this round. Pure — the driver's decisions, kept out of the loop so
/// they are testable.
///
/// The `written` set is the FORWARD-PROGRESS GUARD: a playlist successfully
/// synced this round must never be fetched again within it, even if the
/// staleness query still flags it — a queue that cannot be satisfied by a
/// successful write is a data bug to log, not a loop to run. The 2026-08-30
/// smoke hit exactly that: one playlist re-fetched every 500ms for minutes.
fn next_candidate(
queue: &[repo::HydrationCandidate],
failures: &HashMap<u64, u32>,
written: &HashSet<u64>,
) -> Option<u64> {
queue
.iter()
.map(|c| c.qobuz_playlist_id)
.find(|pid| !written.contains(pid) && failures.get(pid).map_or(true, |&n| n < MAX_ATTEMPTS))
}
async fn run_round(runtime: &Runtime) {
let mut failures: HashMap<u64, u32> = HashMap::new();
let mut written: HashSet<u64> = HashSet::new();
loop {
if crate::offline_fwd::engine().is_offline() {
return;
}
let queue = tokio::task::spawn_blocking(|| {
crate::library_db_qt::with_db(false, |db| Ok(db.with_connection(repo::hydration_queue)))
.and_then(Result::ok)
.unwrap_or_default()
})
.await
.unwrap_or_default();
let Some(pid) = next_candidate(&queue, &failures, &written) else {
if let Some(stuck) = queue
.iter()
.find(|c| written.contains(&c.qobuz_playlist_id))
{
// A successful sync that does not settle its queue entry is a
// staleness-rule bug; surface it instead of looping on it.
log::warn!(
"[qbz-qt] playlist index: {} still queued ({:?}) after a successful sync; \
leaving it for the next authoritative list",
stuck.qobuz_playlist_id,
stuck.reason
);
}
crate::playlist_picker_qt::membership_index_progressed();
return;
};
match runtime.core().get_playlist_track_ids(pid).await {
Ok(playlist) => {
let wrote = tokio::task::spawn_blocking(move || {
crate::library_db_qt::with_db(true, |db| {
Ok(db.with_connection(|conn| {
let owner =
Some(playlist.owner.name.as_str()).filter(|o| !o.is_empty());
repo::replace_tracks(
conn,
pid,
&playlist.name,
owner,
&playlist.track_ids,
)
}))
})
})
.await
.ok()
.flatten()
.and_then(Result::ok)
.unwrap_or(false);
if wrote {
written.insert(pid);
} else {
// Header vanished mid-round (deleted / retired). Spend
// the whole budget so the round moves on.
log::debug!("[qbz-qt] playlist index: {pid} lost its header; skipped");
failures.insert(pid, MAX_ATTEMPTS);
}
crate::playlist_picker_qt::membership_index_progressed();
}
Err(e) => {
let n = failures.entry(pid).or_insert(0);
*n += 1;
log::warn!(
"[qbz-qt] playlist index: membership fetch for {pid} failed (attempt {n}): {e}"
);
// Linear backoff on top of the pace below; bounded by
// MAX_ATTEMPTS so this cannot become a spin.
tokio::time::sleep(std::time::Duration::from_millis(700 * *n as u64)).await;
}
}
tokio::time::sleep(std::time::Duration::from_millis(PACE_MS)).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
use repo::{HydrationCandidate, StaleReason};
fn candidates(ids: &[u64]) -> Vec<HydrationCandidate> {
ids.iter()
.map(|&id| HydrationCandidate {
qobuz_playlist_id: id,
reason: StaleReason::NeverSynced,
})
.collect()
}
#[test]
fn next_candidate_skips_exhausted_budgets() {
let queue = candidates(&[1, 2, 3]);
let mut failures = HashMap::new();
let written = HashSet::new();
assert_eq!(next_candidate(&queue, &failures, &written), Some(1));
failures.insert(1, MAX_ATTEMPTS);
assert_eq!(next_candidate(&queue, &failures, &written), Some(2));
failures.insert(2, MAX_ATTEMPTS - 1);
// Budget not exhausted yet: 2 is still first in line.
assert_eq!(next_candidate(&queue, &failures, &written), Some(2));
failures.insert(2, MAX_ATTEMPTS);
failures.insert(3, MAX_ATTEMPTS);
// Everything parked: the round ends instead of spinning.
assert_eq!(next_candidate(&queue, &failures, &written), None);
}
#[test]
fn next_candidate_never_refetches_a_successful_write() {
// The 2026-08-30 infinite loop: a queue entry that survives its own
// successful sync must end the round, not restart it.
let queue = candidates(&[1]);
let failures = HashMap::new();
let mut written = HashSet::new();
assert_eq!(next_candidate(&queue, &failures, &written), Some(1));
written.insert(1);
assert_eq!(next_candidate(&queue, &failures, &written), None);
}
}
+11 -11
View File
@@ -666,17 +666,17 @@ async fn load(runtime: &Runtime) -> PmData {
Vec::new()
})
};
crate::playlist_snapshot_qt::record_names_detached(
remote
.iter()
.map(|playlist| crate::playlist_snapshot_qt::SnapshotNameEntry {
qobuz_playlist_id: playlist.id,
name: playlist.name.clone(),
owner: Some(playlist.owner.name.clone()).filter(|owner| !owner.is_empty()),
track_count: Some(playlist.tracks_count),
})
.collect(),
);
if !(offline && remote.is_empty()) {
// A failed online fetch also lands here as an empty list; recording it
// would start the two-generation retirement clock on every playlist,
// so only a NON-empty list (or a genuinely deleted-everything account,
// which still lists a session user) is recorded.
if let Some(entries) = crate::playlist_snapshot_qt::authoritative_entries(&remote) {
if !entries.is_empty() {
crate::playlist_snapshot_qt::record_authoritative_detached(entries);
}
}
}
let (folders, settings, play_counts, local_counts, locals, fav_ids) =
tokio::task::spawn_blocking(|| {
+311 -15
View File
@@ -120,6 +120,18 @@ pub struct PickerRow {
pub is_local: bool,
}
/// One "Already in" strip card: a writable playlist that already holds some
/// of the carried tracks.
#[derive(Clone, Serialize)]
pub struct AlreadyRow {
pub id: String,
pub name: String,
#[serde(rename = "isLocal")]
pub is_local: bool,
/// How many of the carried tracks it holds (distinct; the "N of M" card).
pub contained: u32,
}
#[derive(Default, Serialize)]
pub struct DupDoc {
pub open: bool,
@@ -154,6 +166,19 @@ pub struct PickerDoc {
pub creating_open: bool,
pub creating: bool,
pub dup: DupDoc,
/// The session's last successful add target, pinned above the list.
/// Present only while it still exists as a writable row, and retained
/// under a search only when it matches the query.
#[serde(rename = "lastUsed")]
pub last_used: Option<PickerRow>,
/// Writable playlists that already hold carried tracks — the containment
/// strip. Meaningful only per `already_state`.
#[serde(rename = "alreadyIn")]
pub already_in: Vec<AlreadyRow>,
/// "loading" | "complete" | "updating" | "unavailable" — the honest
/// tri-state (plus the in-flight arm) the strip renders under.
#[serde(rename = "alreadyState")]
pub already_state: String,
}
/// Everything the modal owns between opens. One mutex: every field is written
@@ -173,6 +198,13 @@ struct PickerState {
/// answer (the reference's `DUP_CONFIRM_STASH`). `None` = sub-modal closed.
dup: Option<DupContext>,
dup_busy: bool,
/// Containment strip rows, `None` while the query is in flight.
already_rows: Option<Vec<AlreadyRow>>,
/// "complete" | "updating" | "unavailable" once resolved.
already_state: &'static str,
/// Monotonic open counter — a containment result landing after the picker
/// was closed and reopened must not dress the NEW payload.
epoch: u64,
}
struct DupContext {
@@ -188,6 +220,24 @@ struct DupContext {
static STATE: std::sync::LazyLock<Mutex<PickerState>> =
std::sync::LazyLock::new(|| Mutex::new(PickerState::default()));
/// Session-local "Last playlist": the id of the last target an add SUCCEEDED
/// against. Never persisted (process exit resets it, by design), never set on
/// a mere open or a failed operation, and validated against the live row list
/// on every publish — a deleted or no-longer-writable playlist simply stops
/// resolving.
static LAST_USED: Mutex<Option<String>> = Mutex::new(None);
/// Record a confirmed successful add. `n` guards the "nothing actually
/// landed" arms (0-row sidecar writes, empty diffs).
fn set_last_used(playlist_id: &str, n: usize) {
if n == 0 {
return;
}
if let Ok(mut g) = LAST_USED.lock() {
*g = Some(playlist_id.to_string());
}
}
/// Case-insensitive substring over the playlist name — the reference's
/// `filter-changed` rank pass reduced to a filter, because QML can drop rows
/// directly and does not need Slint's rank-and-reorder workaround.
@@ -200,10 +250,21 @@ fn publish() {
let doc = {
let st = STATE.lock().unwrap();
let query = st.filter.trim().to_lowercase();
// The pinned last target: resolved against the LIVE row list, so a
// playlist that disappeared or stopped being writable stops pinning;
// under a search it survives only when it matches the query.
let last_used: Option<PickerRow> = LAST_USED
.lock()
.ok()
.and_then(|g| g.clone())
.and_then(|id| st.all_rows.iter().find(|r| r.id == id).cloned())
.filter(|r| matches(&r.name, &query));
let playlists: Vec<PickerRow> = st
.all_rows
.iter()
.filter(|r| matches(&r.name, &query))
// De-duplicated from the pinned row, never listed twice.
.filter(|r| last_used.as_ref().map(|l| l.id != r.id).unwrap_or(true))
.cloned()
.collect();
PickerDoc {
@@ -226,6 +287,13 @@ fn publish() {
},
None => DupDoc::default(),
},
last_used,
already_in: st.already_rows.clone().unwrap_or_default(),
already_state: if st.already_rows.is_none() {
"loading".to_string()
} else {
st.already_state.to_string()
},
}
};
let json = serde_json::to_string(&doc).unwrap_or_else(|_| "{}".into());
@@ -259,7 +327,7 @@ fn open_payload(runtime: &Runtime, payload: Payload) {
if payload.is_empty() {
return;
}
{
let epoch = {
let mut st = STATE.lock().unwrap();
st.open = true;
st.loading = true;
@@ -272,7 +340,11 @@ fn open_payload(runtime: &Runtime, payload: Payload) {
st.creating = false;
st.dup = None;
st.dup_busy = false;
}
st.already_rows = None;
st.already_state = "";
st.epoch += 1;
st.epoch
};
publish();
let runtime = runtime.clone();
@@ -282,13 +354,125 @@ fn open_payload(runtime: &Runtime, payload: Payload) {
let mut st = STATE.lock().unwrap();
// The user may have closed the picker while the fetch was in
// flight; landing rows into a closed picker would re-open it.
if !st.open {
if !st.open || st.epoch != epoch {
return;
}
st.all_rows = rows;
st.loading = false;
}
publish();
refresh_containment(epoch).await;
});
}
/// Compute the containment strip for the CURRENT payload against the live
/// row list, and the honest tri-state it renders under. Row names come from
/// the already-loaded picker rows, which doubles as the writability/liveness
/// join: a containment hit whose playlist is not offered as a target (offline
/// Qobuz half, followed list, deleted) resolves to nothing and is dropped.
async fn refresh_containment(epoch: u64) {
let (payload, rows) = {
let st = STATE.lock().unwrap();
if !st.open || st.epoch != epoch || st.loading {
return;
}
(st.payload.clone(), st.all_rows.clone())
};
let (already, state) = tokio::task::spawn_blocking(move || {
use qbz_library::playlist_membership::{
playlists_containing, ContainmentTarget, PlaylistTrackRef,
};
use qbz_library::qobuz_playlist_snapshot::{index_state, MembershipIndexState};
let refs: Vec<PlaylistTrackRef> = match &payload {
Payload::Qobuz(ids) => ids.iter().map(|&id| PlaylistTrackRef::Qobuz(id)).collect(),
Payload::LocalRefs(strings) => {
crate::local_playlist_qt::membership_refs_blocking(strings)
}
};
// Only the Qobuz snapshot can be incomplete; the sidecar and local
// tables are locally authoritative (QBZ is their only writer).
let snapshot_dependent = refs.iter().any(|r| {
matches!(r, PlaylistTrackRef::Qobuz(_))
|| matches!(
r,
PlaylistTrackRef::Library {
qobuz_track_id: Some(_),
..
}
)
});
let result = crate::library_db_qt::with_db(false, |db| {
Ok(db.with_connection(|conn| {
let contained = playlists_containing(conn, &refs)?;
let state = index_state(conn)?;
Ok::<_, rusqlite::Error>((contained, state))
}))
})
.and_then(Result::ok);
let Some((contained, state)) = result else {
return (Vec::new(), "unavailable");
};
let state = if !snapshot_dependent {
"complete"
} else {
match state {
MembershipIndexState::Complete => "complete",
// "Still updating" would be a lie while offline — nothing is.
MembershipIndexState::Updating { .. } => {
if crate::offline_fwd::engine().is_offline() {
"unavailable"
} else {
"updating"
}
}
MembershipIndexState::Unavailable => "unavailable",
}
};
let already: Vec<AlreadyRow> = contained
.into_iter()
.filter_map(|c| {
let id = match &c.target {
ContainmentTarget::Qobuz(pid) => pid.to_string(),
ContainmentTarget::Local(id) => id.clone(),
};
rows.iter().find(|r| r.id == id).map(|r| AlreadyRow {
id,
name: r.name.clone(),
is_local: r.is_local,
contained: c.contained,
})
})
.take(20)
.collect();
(already, state)
})
.await
.unwrap_or_else(|_| (Vec::new(), "unavailable"));
{
let mut st = STATE.lock().unwrap();
if !st.open || st.epoch != epoch {
return;
}
st.already_rows = Some(already);
st.already_state = state;
}
publish();
}
/// Hydrator progress callback: while the picker is open, each committed
/// membership snapshot (and the final state flip to Complete) re-answers the
/// containment question live.
pub fn membership_index_progressed() {
let epoch = {
let st = STATE.lock().unwrap();
if !st.open || st.loading {
return;
}
st.epoch
};
crate::spawn(async move {
refresh_containment(epoch).await;
});
}
@@ -316,12 +500,25 @@ async fn load(runtime: &Runtime) -> Vec<PickerRow> {
return out;
}
match runtime.core().get_user_playlists().await {
Ok(playlists) => out.extend(playlists.into_iter().map(|p| PickerRow {
id: p.id.to_string(),
name: p.name,
tracks_line: tracks_line(p.tracks_count),
is_local: false,
})),
Ok(playlists) => out.extend(
playlists
.into_iter()
// Followed playlists are read-only on the API and must never
// be offered as add targets. Before the session user id is
// known ownership cannot be told apart, so the pre-existing
// behaviour (list everything) is kept for that window rather
// than blanking the Qobuz half.
.filter(|p| {
!crate::playlist_qt::session_user_known()
|| crate::playlist_qt::owns(p.owner.id)
})
.map(|p| PickerRow {
id: p.id.to_string(),
name: p.name,
tracks_line: tracks_line(p.tracks_count),
is_local: false,
}),
),
Err(e) => log::warn!("[qbz-qt] playlist picker load failed: {e}"),
}
out
@@ -417,6 +614,7 @@ pub fn pick(playlist_id: &str) {
})
.await
.unwrap_or(0);
set_last_used(&open_target, added);
toast_added(added, &name);
refresh_local_target(&runtime, &open_target).await;
});
@@ -438,6 +636,7 @@ pub fn pick(playlist_id: &str) {
let qobuz_count = crate::sidebar_qt::playlist_track_count(pid).unwrap_or(0);
crate::spawn(async move {
let written = write_sidecar_refs(pid, qobuz_count, refs).await;
set_last_used(&pid.to_string(), written);
toast_added(written, &name);
// E12: the open detail re-merges so the rows show up now.
crate::playlist_qt::refresh_after_membership_change(&runtime, pid).await;
@@ -573,17 +772,22 @@ pub fn create_and_add(name: &str) {
crate::toast_qt::error(qbz_i18n::t("Couldn't create the playlist"));
return;
};
let added = tokio::task::spawn_blocking(move || match payload {
Payload::LocalRefs(refs) => {
crate::local_playlist_qt::add_local_refs_blocking(&new_id, &refs)
}
Payload::Qobuz(ids) => {
crate::local_playlist_qt::add_qobuz_tracks_blocking(&new_id, &ids)
let added = tokio::task::spawn_blocking({
let new_id = new_id.clone();
move || match payload {
Payload::LocalRefs(refs) => {
crate::local_playlist_qt::add_local_refs_blocking(&new_id, &refs)
}
Payload::Qobuz(ids) => {
crate::local_playlist_qt::add_qobuz_tracks_blocking(&new_id, &ids)
}
}
})
.await
.unwrap_or(0);
close();
// Create-and-add counts as a use even when the payload was empty.
set_last_used(&new_id, added.max(1));
toast_added(added, &name);
// The new playlist has to appear in the sidebar, or the user's
// only evidence it exists is the toast — and `reload_sidebar`
@@ -597,6 +801,28 @@ pub fn create_and_add(name: &str) {
match runtime.core().create_playlist(&name, None, false).await {
Ok(playlist) => {
let pid = playlist.id;
// Snapshot the newborn header FIRST (owned, empty, captured):
// the incremental producer below refuses playlists it has
// never captured, and the authoritative list will not name
// this one until Qobuz's post-write lag clears.
{
let owner_name = playlist.owner.name.clone();
let created_name = name.clone();
let _ = tokio::task::spawn_blocking(move || {
crate::library_db_qt::with_db(true, |db| {
Ok(db.with_connection(|conn| {
qbz_library::qobuz_playlist_snapshot::record_created_playlist(
conn,
pid,
&created_name,
Some(owner_name.as_str()).filter(|o| !o.is_empty()),
)
}))
})
})
.await;
}
set_last_used(&pid.to_string(), 1);
match payload {
Payload::Qobuz(ids) if !ids.is_empty() => {
add_and_toast(&runtime, pid, ids, name).await;
@@ -633,6 +859,49 @@ pub fn create_and_add(name: &str) {
});
}
/// Shared-drag DROP: the picker's add matrix without the modal. Routes a
/// payload onto a sidebar target the same way `pick` would — local refs to a
/// local playlist or the Qobuz sidecar, Qobuz ids to a local playlist — with
/// the same success tail (last-used, toast, refreshes). The Qobuz-ids-onto-
/// Qobuz-playlist case stays with its pre-existing `playlist_qt::add_tracks`
/// caller and never reaches here.
pub async fn add_dropped_payload_to_target(runtime: &Runtime, target_id: &str, payload: Payload) {
if payload.is_empty() {
return;
}
match crate::local_playlist_qt::PlaylistRef::parse(target_id) {
Some(crate::local_playlist_qt::PlaylistRef::Local(target)) => {
let added = tokio::task::spawn_blocking({
let target = target.clone();
move || match payload {
Payload::LocalRefs(refs) => {
crate::local_playlist_qt::add_local_refs_blocking(&target, &refs)
}
Payload::Qobuz(ids) => {
crate::local_playlist_qt::add_qobuz_tracks_blocking(&target, &ids)
}
}
})
.await
.unwrap_or(0);
set_last_used(&target, added);
toast_added(added, "");
refresh_local_target(runtime, &target).await;
}
Some(crate::local_playlist_qt::PlaylistRef::Qobuz(pid)) => {
let Payload::LocalRefs(refs) = payload else {
return;
};
let qobuz_count = crate::sidebar_qt::playlist_track_count(pid).unwrap_or(0);
let written = write_sidecar_refs(pid, qobuz_count, refs).await;
set_last_used(&pid.to_string(), written);
toast_added(written, "");
crate::playlist_qt::refresh_after_membership_change(runtime, pid).await;
}
None => {}
}
}
/// Seam C — attach local-mode refs to a QOBUZ playlist through the library.db
/// sidecar tables. Returns how many refs were written.
///
@@ -653,6 +922,10 @@ async fn write_sidecar_refs(pid: u64, qobuz_count: u32, refs: Vec<String>) -> us
for r in &refs {
if let Some(key) = r.strip_prefix("plex:") {
db.add_plex_track_to_playlist(pid, key, next)?;
} else if let Some(item) = r.strip_prefix("jellyfin:") {
db.add_remote_track_to_playlist(pid, "jellyfin", item, next)?;
} else if let Some(item) = r.strip_prefix("subsonic:") {
db.add_remote_track_to_playlist(pid, "subsonic", item, next)?;
} else if let Ok(lid) = r.parse::<i64>() {
db.add_local_track_to_playlist(pid, lid, next)?;
} else {
@@ -681,12 +954,35 @@ async fn add_and_toast(runtime: &Runtime, pid: u64, ids: Vec<u64>, name: String)
crate::toast_qt::error(qbz_i18n::t("Failed to add tracks"));
return;
}
set_last_used(&pid.to_string(), n);
snapshot_added_detached(pid, ids);
// The sidebar's per-playlist track count is now stale, and a playlist page
// open on this id must re-merge (the reference's E12 refresh).
crate::playlist_qt::refresh_after_membership_change(runtime, pid).await;
toast_added(n, &name);
}
/// Move the membership snapshot with a CONFIRMED add, off-thread, so the
/// containment answer is already right the next time the picker opens —
/// without waiting for the hydrator or a detail load.
fn snapshot_added_detached(pid: u64, ids: Vec<u64>) {
tokio::task::spawn_blocking(move || {
let applied = crate::library_db_qt::with_db(true, |db| {
Ok(db.with_connection(|conn| {
qbz_library::qobuz_playlist_snapshot::apply_added_tracks(conn, pid, &ids)
}))
})
.and_then(Result::ok)
.unwrap_or(false);
if applied {
membership_index_progressed();
} else {
// Membership never captured: the hydrator owns this playlist.
crate::playlist_index_qt::poke();
}
});
}
/// The shared success toast (the reference's `toast_added_tracks`). Every arm
/// of the matrix ends here, so the wording cannot drift between them. A zero
/// count is silent: the repo layer already logged WHY nothing landed.
+55 -8
View File
@@ -531,6 +531,12 @@ pub fn set_user_playlists(pairs: &[(u64, u64)]) {
}
}
/// Is the session user id known yet? Ownership answers are meaningless (all
/// false) before it is.
pub fn session_user_known() -> bool {
USER_ID.load(std::sync::atomic::Ordering::SeqCst) != 0
}
/// Does the signed-in user own this playlist, by OWNER id? The cheap arm —
/// every card producer already has `owner.id` on the row it is mapping, so it
/// needs no set lookup at all.
@@ -1770,6 +1776,18 @@ pub async fn delete_by_id(
"[qbz-qt] playlist {pid} {}",
if owned { "deleted" } else { "unsubscribed" }
);
if owned {
// Leave the membership index's target set now instead of waiting out
// the authoritative-list retirement grace.
let _ = tokio::task::spawn_blocking(move || {
crate::library_db_qt::with_db(true, |db| {
Ok(db.with_connection(|conn| {
qbz_library::qobuz_playlist_snapshot::mark_inactive(conn, pid)
}))
})
})
.await;
}
Ok(())
}
@@ -1824,24 +1842,53 @@ pub async fn remove_track(runtime: &Arc<AppRuntime<LoggingAdapter>>, playlist_tr
return;
};
let Some(pid) = pid else { return };
// Optimistic removal; the API is the source of truth on failure.
with_doc(|d| {
// Optimistic removal; the API is the source of truth on failure. The
// row's CATALOG id is captured before it goes — the membership snapshot
// speaks track ids, not membership-row ids.
let removed_track_id = with_doc(|d| {
let track_id = d
.tracks
.iter()
.find(|t| t.playlist_track_id == playlist_track_id)
.and_then(|t| t.id.parse::<u64>().ok());
d.tracks
.retain(|t| t.playlist_track_id != playlist_track_id);
d.track_count = d.tracks.len() as i32;
d.total_duration = total_duration_label(&d.tracks);
let doc = d.clone();
publish(&doc);
});
if let Err(e) = runtime
track_id
})
.flatten();
match runtime
.core()
.remove_tracks_from_playlist(pid, &[playlist_track_id])
.await
{
log::error!("[qbz-qt] remove track {playlist_track_id} from playlist {pid} failed: {e}");
// Reload to reconcile (bounded-retry equivalent — the Slint
// reconciles the same way after failed playlist ops).
let _ = load(runtime, pid).await;
Ok(()) => {
if let Some(track_id) = removed_track_id {
let _ = tokio::task::spawn_blocking(move || {
crate::library_db_qt::with_db(true, |db| {
Ok(db.with_connection(|conn| {
qbz_library::qobuz_playlist_snapshot::apply_removed_tracks(
conn,
pid,
&[track_id],
)
}))
})
})
.await;
}
}
Err(e) => {
log::error!(
"[qbz-qt] remove track {playlist_track_id} from playlist {pid} failed: {e}"
);
// Reload to reconcile (bounded-retry equivalent — the Slint
// reconciles the same way after failed playlist ops).
let _ = load(runtime, pid).await;
}
}
}
+40 -8
View File
@@ -9,18 +9,50 @@ use std::collections::{HashMap, HashSet};
use qbz_library::qobuz_playlist_snapshot as repo;
pub use repo::SnapshotNameEntry;
pub use repo::AuthoritativeEntry;
pub fn record_names_detached(entries: Vec<SnapshotNameEntry>) {
if entries.is_empty() {
return;
/// Turn one `get_user_playlists()` response into authoritative snapshot
/// entries. Ownership comes from the session user id; when that id is not
/// known yet the caller must SKIP recording — an all-foreign list would both
/// starve the hydrator and start the two-generation retirement clock.
pub fn authoritative_entries(
playlists: &[qbz_models::Playlist],
) -> Option<Vec<AuthoritativeEntry>> {
if !crate::playlist_qt::session_user_known() {
log::debug!(
"[qbz-qt] playlist snapshot: session user unknown; authoritative list not recorded"
);
return None;
}
Some(
playlists
.iter()
.map(|playlist| AuthoritativeEntry {
qobuz_playlist_id: playlist.id,
name: playlist.name.clone(),
owner: Some(playlist.owner.name.clone()).filter(|owner| !owner.is_empty()),
track_count: Some(playlist.tracks_count),
remote_updated_at: playlist.updated_at,
is_owned: crate::playlist_qt::owns(playlist.owner.id),
})
.collect(),
)
}
pub fn record_authoritative_detached(entries: Vec<AuthoritativeEntry>) {
let write = move || {
let result = crate::library_db_qt::with_db(true, |db| {
Ok(db.with_connection(|conn| repo::upsert_names(conn, &entries)))
Ok(db.with_connection(|conn| repo::record_authoritative_list(conn, &entries)))
});
if let Some(Err(error)) = result {
log::warn!("[qbz-qt] playlist snapshot names write failed: {error}");
match result {
Some(Ok(generation)) => {
log::debug!("[qbz-qt] playlist snapshot: authoritative generation {generation}");
crate::playlist_index_qt::poke();
}
Some(Err(error)) => {
log::warn!("[qbz-qt] playlist snapshot authoritative write failed: {error}")
}
None => {}
}
};
if tokio::runtime::Handle::try_current().is_ok() {
@@ -39,7 +71,7 @@ pub fn record_detail_detached(playlist_id: u64, name: String, owner: String, tra
}))
});
match result {
Some(Ok(true)) => {}
Some(Ok(true)) => crate::playlist_picker_qt::membership_index_progressed(),
Some(Ok(false)) => log::debug!(
"[qbz-qt] playlist snapshot: {playlist_id} is not in the user list; membership skipped"
),
+14 -6
View File
@@ -1316,12 +1316,20 @@ pub async fn insert_dragged_track(
// filters now (F2 + D5), so one row in can legitimately be ZERO rows out —
// and a DRAG of a pulled track into the queue would have PANICKED. The seam
// has already toasted the reason.
let Some(qt) = crate::playback_qt::stamped(
vec![crate::playback_qt::queue_track_for(runtime, track_id).await?],
None,
)
.pop() else {
log::info!("[qbz-qt] queue: dragged track {track_id} was filtered out");
let qt = crate::playback_qt::queue_track_for(runtime, track_id).await?;
insert_dragged_queue_track(runtime, qt, to_slot).await
}
/// The same drop, from an already-built `QueueTrack` — the LOCAL-mode drag's
/// arm (Explorer / Local Library rows), and the shared tail of the Qobuz one.
pub async fn insert_dragged_queue_track(
runtime: &Arc<AppRuntime<LoggingAdapter>>,
track: qbz_models::QueueTrack,
to_slot: usize,
) -> Result<(), String> {
let id = track.id;
let Some(qt) = crate::playback_qt::stamped(vec![track], None).pop() else {
log::info!("[qbz-qt] queue: dragged track {id} was filtered out");
return Ok(());
};
+1 -2
View File
@@ -1519,8 +1519,7 @@ fn open_local_cort_row_in_playlist_picker(row_id: &str) {
);
return;
};
let reference = crate::local_playlist_qt::local_picker_ref_for_track(&track);
crate::playlist_picker_qt::open_for_local_refs(&crate::app(), vec![reference]);
crate::local_album_actions::open_picker_for_rows(std::slice::from_ref(&track));
}
/// "View more" on a section: full search page on the matching tab
+31
View File
@@ -714,6 +714,18 @@ pub mod qbz_shell {
y: f32,
inline_visual: bool,
);
/// LOCAL-mode twin: a Local Library / Explorer row enters the shared
/// drag by ROW ID (resolved to source-aware refs at drop time).
#[qinvokable]
fn drag_start_local(
self: Pin<&mut QbzShell>,
row_id: QString,
title: QString,
subtitle: QString,
x: f32,
y: f32,
inline_visual: bool,
);
#[qinvokable]
fn drag_move(self: Pin<&mut QbzShell>, x: f32, y: f32);
/// A sidebar playlist row claims / releases the drop target.
@@ -1449,6 +1461,25 @@ impl qbz_shell::QbzShell {
);
}
pub fn drag_start_local(
self: Pin<&mut Self>,
row_id: QString,
title: QString,
subtitle: QString,
x: f32,
y: f32,
inline_visual: bool,
) {
crate::drag_start_local(
row_id.to_string(),
title.to_string(),
subtitle.to_string(),
x,
y,
inline_visual,
);
}
pub fn drag_move(self: Pin<&mut Self>, x: f32, y: f32) {
crate::drag_move(x, y);
}
+7 -18
View File
@@ -220,26 +220,15 @@ pub async fn load(runtime: &Arc<AppRuntime<LoggingAdapter>>) {
log::debug!("[qbz-qt] sidebar load: fetching user playlists");
match runtime.core().get_user_playlists().await {
Ok(pls) => {
crate::playlist_snapshot_qt::record_names_detached(
pls.iter()
.map(|playlist| crate::playlist_snapshot_qt::SnapshotNameEntry {
qobuz_playlist_id: playlist.id,
name: playlist.name.clone(),
owner: Some(playlist.owner.name.clone())
.filter(|owner| !owner.is_empty()),
track_count: Some(playlist.tracks_count),
})
.collect(),
);
// Same response, second consumer: the playlist ownership /
// follow snapshot every PlaylistCard's tri-state overlay reads
// (`playlist_qt::set_user_playlists`). This is the earliest point
// in the session where the user's own playlist list exists, and
// it costs no extra request — the alternative was every card
// rendering the "follow a foreign playlist" arm until the Library
// view had been opened at least once.
// Ownership snapshot FIRST — every PlaylistCard's tri-state
// overlay reads it, this is the earliest point in the session
// where the user's own list exists, and `authoritative_entries`
// below depends on the sets this call seeds.
let pairs: Vec<(u64, u64)> = pls.iter().map(|p| (p.id, p.owner.id)).collect();
crate::playlist_qt::set_user_playlists(&pairs);
if let Some(entries) = crate::playlist_snapshot_qt::authoritative_entries(&pls) {
crate::playlist_snapshot_qt::record_authoritative_detached(entries);
}
pls
}
Err(e) => {