feat(qt): the Local Library union, the settings store and the sweep

Three pieces that only mean anything together: rows in the shared cache,
a union that shows them, and settings that decide whether either
happens.

THE UNION. `get_albums_metadata_page` grows a second, INDEPENDENT
attachment. `plex_cache` stays; `remote_cache` is the shared mirror, and
they attach separately on purpose — a missing Plex cache must not cost
the user their Jellyfin rows. `attach_best_effort` is extracted because
the failure mode of a botched ATTACH is a silently local-only library,
and a failure stays non-fatal: refusing to list any albums because one
server is off turns "Jellyfin is unplugged" into "your library is
empty".

The union takes an ENABLED-SOURCES list, not just a path. The mirror
holds every remote source, so the master toggle has to be a filter
rather than a detach: turning Jellyfin off must hide Jellyfin's rows and
leave Subsonic's alone. That predicate is interpolated into SQL, so it
is VALIDATED rather than escaped — only [a-z] survives, an all-invalid
list yields `0` (show nothing, the safe direction), and a test feeds it
`x'; DROP TABLE local_tracks; --`.

The remote group key is `<source>:<album id>`, matching Plex's
`plex:<hash>`. That namespaces two servers using the same album id AND
lets a source claim an album card that arrives with no source word,
which is every card that round-trips through a QML string property —
`recognises` grew that arm and `claim` strips the prefix, because
carrying it inward is how Plex ended up with two album keys only one of
its queries understood (IC-2).

THE SETTINGS. One store for both servers, keyed by a `server` column,
mirroring the shared-cache decision. What each protocol needs differs
and `is_configured` is the one place that knows: Jellyfin needs its
issued token, Subsonic needs a password because it has no session and
re-derives `md5(password + salt)` per request.

Two identifiers are minted once and persisted, and both are
load-bearing. Jellyfin's DeviceId, because re-authenticating under the
same one revokes the previous token — a constant would make two installs
log each other out, a fresh one per launch drops the last run's token.
Subsonic's salt, because rolling it per request makes every cover URL
unique and the artwork cache keys on the URL.

THE SWEEP. In the frontend, where the runtime and the progress UI are,
writing through the cache handle the SOURCE owns so sweep and reads can
never point at different users. Jellyfin gets progress and a delta path
(45.8 s for 4924 rows); Subsonic needs neither (0.81 s for 6678).
`prune_stale` runs only after a COMPLETED full sweep — a delta never
prunes, because it deliberately does not see unchanged rows and would
read every one of them as deleted. `last_sync_at` is stamped only on
success for the same reason.

Verified against the running binary, twice:

  source registry bound: local_tracks=617 plex=connected
    ephemeral_store=yes remote=none configured
  jellyfin: minted a device id for this install
  subsonic: minted a salt for this install

...and on the second launch, zero re-mints and the same values on disk —
which is the property that keeps a Jellyfin session alive.

qbz-qt 428/428, qbz-app 224/224, qbz-library 100/100, qbz-source 88/88.
Release build clean, zero warnings.

cc
This commit is contained in:
vicrodh committed 2026-08-20 09:20:07 -06:00
1 parent 51aa8ba081
commit 63a4f2daf1
17 files changed
+2159 -35

No files matched your search

+4
View File
@@ -6234,6 +6234,7 @@ dependencies = [
"rustls",
"serde",
"serde_json",
"tempfile",
"tokio",
"uuid 1.22.0",
]
@@ -6672,9 +6673,11 @@ dependencies = [
"qbz-external-reco",
"qbz-i18n",
"qbz-integrations",
"qbz-jellyfin",
"qbz-library",
"qbz-log",
"qbz-lyrics",
"qbz-media-cache",
"qbz-media-controls",
"qbz-mixtape",
"qbz-models",
@@ -6684,6 +6687,7 @@ dependencies = [
"qbz-plex",
"qbz-qobuz",
"qbz-source",
"qbz-subsonic",
"qbz-text-utils",
"qbz-theme",
"qconnect-app",
+4
View File
@@ -27,3 +27,7 @@ rand = "0.10"
# TLS provider selection
rustls = { version = "0.23", features = ["aws_lc_rs"] }
[dev-dependencies]
# A temp user dir for the settings-store tests.
tempfile = "3"
@@ -0,0 +1,546 @@
//! Per-user connection settings for the media servers QBZ reads.
//!
//! ONE store for Jellyfin and Subsonic, keyed by a `server` column — the same
//! decision `qbz-media-cache` makes about their tracks, for the same reason:
//! the two carry the same fields, and a store per server means every future one
//! copies a file. Plex keeps its own ([`super::plex`]) until it folds into the
//! shared pair; see that crate's header for why that is a separate change.
//!
//! Mirrors [`super::plex`]'s shape: a small SQLite table, opened globally via
//! [`MediaServerStore::new`] and re-pointed at the active user's directory by
//! [`MediaServerState::init_at`] at login, so credentials are scoped per Qobuz
//! user.
//!
//! # What is stored, and what deliberately is not
//!
//! **Jellyfin** stores its `access_token` — the server issues it and the
//! password is never needed again. **Subsonic has no session**: every request
//! carries `md5(password + salt)`, so the password itself must be kept.
//!
//! That asymmetry is the protocol's, not a shortcut. It is also why `salt` is
//! persisted rather than generated per request: a rolling salt would make every
//! cover URL unique per request, and the artwork cache keys on the URL, so each
//! pass would re-download every cover. The salt is not a secret — it travels in
//! clear beside the token — its job is to keep one password from hashing to the
//! same value on two installs.
//!
//! `device_id` is Jellyfin's, and it is load-bearing: the server keys its
//! SESSION on it, and re-authenticating under the same one revokes the previous
//! token (measured against 10.11.11). Generated once and persisted, so two QBZ
//! installs never log each other out and a relaunch does not drop the token.
use log::info;
use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::sync::{Arc, Mutex};
/// Which server a settings row describes. The wire values are the same words
/// `qbz_source::SourceId` and `qbz_media_cache::RemoteSource` use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MediaServerKind {
Jellyfin,
Subsonic,
}
impl MediaServerKind {
pub const fn as_str(self) -> &'static str {
match self {
MediaServerKind::Jellyfin => "jellyfin",
MediaServerKind::Subsonic => "subsonic",
}
}
pub fn from_word(w: &str) -> Option<Self> {
match w {
"jellyfin" => Some(MediaServerKind::Jellyfin),
"subsonic" | "navidrome" | "gonic" | "airsonic" | "astiga" => {
Some(MediaServerKind::Subsonic)
}
_ => None,
}
}
pub const ALL: [MediaServerKind; 2] = [MediaServerKind::Jellyfin, MediaServerKind::Subsonic];
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MediaServerSettings {
/// Master toggle. Default OFF — integrations are opt-in.
pub enabled: bool,
/// Collapse chevron state for the settings panel.
pub ui_collapsed: bool,
/// `proto://host:port`, resolved. Empty = not configured.
pub base_url: String,
/// Display name reported by the server, for the panel's "connected to …".
pub server_name: String,
/// The server's own id, threaded into the cache as `server_id`.
pub server_id: String,
/// Jellyfin: the account name. Subsonic: the account name, sent on every
/// request.
pub username: String,
/// Jellyfin: the issued `AccessToken`. Empty for Subsonic.
pub token: String,
/// Subsonic ONLY: the password, because the protocol re-derives its token
/// on every request. Empty for Jellyfin, which never needs it again.
pub password: String,
/// Subsonic ONLY: the FIXED per-install salt. See the module header.
pub salt: String,
/// Jellyfin ONLY: the stable per-install `DeviceId`. See the module header.
pub device_id: String,
/// Picked library / music-folder ids. Empty = none chosen yet, which the
/// sync reads as "all of them" on its first run.
pub selected_libraries: Vec<String>,
/// Unix seconds of the last COMPLETED sweep. 0 = never swept.
///
/// Only a completed sweep updates it, because it is what a delta sync asks
/// the server about — stamping it after a partial one would silently skip
/// whatever the interrupted run never saw.
pub last_sync_at: i64,
/// Tracks in the cache at the end of that sweep, for the panel's summary.
pub last_sync_tracks: i64,
}
impl MediaServerSettings {
/// Is this server usable right now — enabled, addressed, and carrying
/// whatever credential its protocol needs?
///
/// The two protocols disagree about what "credentialed" means, and this is
/// the ONE place that knows: Jellyfin needs its issued token, Subsonic
/// needs a username and password.
pub fn is_configured(&self, kind: MediaServerKind) -> bool {
if !self.enabled || self.base_url.trim().is_empty() {
return false;
}
match kind {
MediaServerKind::Jellyfin => !self.token.trim().is_empty(),
MediaServerKind::Subsonic => {
!self.username.trim().is_empty() && !self.password.is_empty()
}
}
}
}
pub struct MediaServerStore {
conn: Connection,
}
impl MediaServerStore {
fn open_at(dir: &Path) -> Result<Self, String> {
std::fs::create_dir_all(dir)
.map_err(|e| format!("Failed to create data directory: {e}"))?;
let conn = Connection::open(dir.join("media_servers.db"))
.map_err(|e| format!("Failed to open media server settings: {e}"))?;
conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;")
.map_err(|e| format!("Failed to set pragmas: {e}"))?;
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS media_server_settings (
server TEXT PRIMARY KEY,
enabled INTEGER NOT NULL DEFAULT 0,
ui_collapsed INTEGER NOT NULL DEFAULT 0,
base_url TEXT NOT NULL DEFAULT '',
server_name TEXT NOT NULL DEFAULT '',
server_id TEXT NOT NULL DEFAULT '',
username TEXT NOT NULL DEFAULT '',
token TEXT NOT NULL DEFAULT '',
password TEXT NOT NULL DEFAULT '',
salt TEXT NOT NULL DEFAULT '',
device_id TEXT NOT NULL DEFAULT '',
selected_libraries TEXT NOT NULL DEFAULT '',
last_sync_at INTEGER NOT NULL DEFAULT 0,
last_sync_tracks INTEGER NOT NULL DEFAULT 0
);",
)
.map_err(|e| format!("Failed to init media server schema: {e}"))?;
info!("[MediaServers] Database initialized");
Ok(Self { conn })
}
pub fn new() -> Result<Self, String> {
let dir = dirs::data_dir()
.ok_or("Could not determine data directory")?
.join("qbz");
Self::open_at(&dir)
}
pub fn new_at(base_dir: &Path) -> Result<Self, String> {
Self::open_at(base_dir)
}
/// Read one server's settings. A row that has never been written comes back
/// as defaults (disabled, unconfigured) rather than an error — "the user
/// has not set this up" is not a failure.
pub fn get(&self, kind: MediaServerKind) -> Result<MediaServerSettings, String> {
let row = self.conn.query_row(
"SELECT enabled, ui_collapsed, base_url, server_name, server_id, username,
token, password, salt, device_id, selected_libraries,
last_sync_at, last_sync_tracks
FROM media_server_settings WHERE server = ?1",
params![kind.as_str()],
|r| {
Ok(MediaServerSettings {
enabled: r.get::<_, i64>(0)? != 0,
ui_collapsed: r.get::<_, i64>(1)? != 0,
base_url: r.get(2)?,
server_name: r.get(3)?,
server_id: r.get(4)?,
username: r.get(5)?,
token: r.get(6)?,
password: r.get(7)?,
salt: r.get(8)?,
device_id: r.get(9)?,
selected_libraries: split_ids(&r.get::<_, String>(10)?),
last_sync_at: r.get(11)?,
last_sync_tracks: r.get(12)?,
})
},
);
match row {
Ok(s) => Ok(s),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(MediaServerSettings::default()),
Err(e) => Err(format!("Failed to read media server settings: {e}")),
}
}
/// Write one server's settings wholesale.
///
/// One UPSERT rather than a setter per field: the settings panel edits a
/// form and saves it, and a dozen single-column setters is how `plex.rs`
/// grew to 723 lines.
pub fn put(&self, kind: MediaServerKind, s: &MediaServerSettings) -> Result<(), String> {
self.conn
.execute(
"INSERT INTO media_server_settings
(server, enabled, ui_collapsed, base_url, server_name, server_id,
username, token, password, salt, device_id, selected_libraries,
last_sync_at, last_sync_tracks)
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14)
ON CONFLICT(server) DO UPDATE SET
enabled=excluded.enabled, ui_collapsed=excluded.ui_collapsed,
base_url=excluded.base_url, server_name=excluded.server_name,
server_id=excluded.server_id, username=excluded.username,
token=excluded.token, password=excluded.password,
salt=excluded.salt, device_id=excluded.device_id,
selected_libraries=excluded.selected_libraries,
last_sync_at=excluded.last_sync_at,
last_sync_tracks=excluded.last_sync_tracks",
params![
kind.as_str(),
i64::from(s.enabled),
i64::from(s.ui_collapsed),
s.base_url.trim(),
s.server_name,
s.server_id,
s.username.trim(),
s.token.trim(),
s.password,
s.salt,
s.device_id,
s.selected_libraries.join(","),
s.last_sync_at,
s.last_sync_tracks,
],
)
.map(|_| ())
.map_err(|e| format!("Failed to write media server settings: {e}"))
}
/// Forget one server's credentials, keeping the row so its UI state and its
/// picked libraries survive a reconnect.
pub fn disconnect(&self, kind: MediaServerKind) -> Result<(), String> {
self.conn
.execute(
"UPDATE media_server_settings
SET enabled = 0, token = '', password = '', server_id = '',
server_name = '', last_sync_at = 0, last_sync_tracks = 0
WHERE server = ?1",
params![kind.as_str()],
)
.map(|_| ())
.map_err(|e| format!("Failed to disconnect media server: {e}"))
}
}
fn split_ids(raw: &str) -> Vec<String> {
raw.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(String::from)
.collect()
}
/// The process-global store, re-pointed at the active user at login.
#[derive(Clone)]
pub struct MediaServerState {
store: Arc<Mutex<Option<MediaServerStore>>>,
}
impl Default for MediaServerState {
fn default() -> Self {
Self::new()
}
}
impl MediaServerState {
pub fn new() -> Self {
Self {
store: Arc::new(Mutex::new(None)),
}
}
/// Bind to the active user's directory. Called from the auth path.
pub fn init_at(&self, dir: &Path) {
match MediaServerStore::new_at(dir) {
Ok(s) => {
if let Ok(mut slot) = self.store.lock() {
*slot = Some(s);
}
}
Err(e) => log::error!("[MediaServers] init failed: {e}"),
}
}
/// Drop the handle (logout).
pub fn reset(&self) {
if let Ok(mut slot) = self.store.lock() {
*slot = None;
}
}
/// Read. Unbound or unreadable answers with DEFAULTS — i.e. "disabled" —
/// which is the safe direction: a settings read that fails must not make an
/// unconfigured server look configured.
pub fn get(&self, kind: MediaServerKind) -> MediaServerSettings {
self.store
.lock()
.ok()
.and_then(|g| g.as_ref().and_then(|s| s.get(kind).ok()))
.unwrap_or_default()
}
pub fn put(&self, kind: MediaServerKind, s: &MediaServerSettings) {
if let Ok(g) = self.store.lock() {
if let Some(store) = g.as_ref() {
if let Err(e) = store.put(kind, s) {
log::error!("[MediaServers] write failed: {e}");
}
}
}
}
pub fn disconnect(&self, kind: MediaServerKind) {
if let Ok(g) = self.store.lock() {
if let Some(store) = g.as_ref() {
let _ = store.disconnect(kind);
}
}
}
/// Every server the user has switched on AND finished configuring.
///
/// This is what the Local Library union filters on, so "enabled" alone is
/// not enough: a server that is toggled on but has no credentials yet would
/// contribute a `source IN (...)` arm over rows that were never swept.
pub fn configured_words(&self) -> Vec<&'static str> {
MediaServerKind::ALL
.iter()
.filter(|k| self.get(**k).is_configured(**k))
.map(|k| k.as_str())
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
fn store() -> (TempDir, MediaServerStore) {
let t = TempDir::new().unwrap();
let s = MediaServerStore::new_at(t.path()).unwrap();
(t, s)
}
/// A server the user has never touched reads as defaults, not as an error.
#[test]
fn an_unwritten_server_reads_as_disabled() {
let (_t, s) = store();
let jf = s.get(MediaServerKind::Jellyfin).unwrap();
assert!(!jf.enabled);
assert!(jf.base_url.is_empty());
assert!(!jf.is_configured(MediaServerKind::Jellyfin));
}
#[test]
fn settings_round_trip_per_server_without_bleeding() {
let (_t, s) = store();
let jf = MediaServerSettings {
enabled: true,
base_url: "http://jf:8096".into(),
username: "admin".into(),
token: "tok".into(),
device_id: "qbz-abc".into(),
selected_libraries: vec!["lib1".into(), "lib2".into()],
..Default::default()
};
s.put(MediaServerKind::Jellyfin, &jf).unwrap();
let got = s.get(MediaServerKind::Jellyfin).unwrap();
assert_eq!(got.base_url, "http://jf:8096");
assert_eq!(got.token, "tok");
assert_eq!(got.selected_libraries, vec!["lib1", "lib2"]);
// The other server is untouched.
assert!(!s.get(MediaServerKind::Subsonic).unwrap().enabled);
}
/// The two protocols disagree about what "credentialed" means, and this is
/// the one place that knows. Getting it backwards would either refuse a
/// working server or hand the sync a connection it cannot authenticate.
#[test]
fn configured_means_a_different_thing_for_each_protocol() {
// Jellyfin: an issued token, and the password is never needed again.
let mut jf = MediaServerSettings {
enabled: true,
base_url: "http://jf:8096".into(),
username: "admin".into(),
..Default::default()
};
assert!(!jf.is_configured(MediaServerKind::Jellyfin), "no token yet");
jf.token = "tok".into();
assert!(jf.is_configured(MediaServerKind::Jellyfin));
// Subsonic: no session at all, so the PASSWORD is what it needs.
let mut sub = MediaServerSettings {
enabled: true,
base_url: "http://nd:4533".into(),
username: "admin".into(),
..Default::default()
};
assert!(!sub.is_configured(MediaServerKind::Subsonic), "no password yet");
sub.password = "pw".into();
assert!(sub.is_configured(MediaServerKind::Subsonic));
// ...and a Jellyfin-style token does NOT make it configured.
let token_only = MediaServerSettings {
token: "tok".into(),
..sub.clone()
};
let token_only = MediaServerSettings {
password: String::new(),
..token_only
};
assert!(!token_only.is_configured(MediaServerKind::Subsonic));
}
/// A disabled or unaddressed server is never configured, whatever else it
/// holds — that is what makes the master toggle actually remove its rows
/// from the Local Library union.
#[test]
fn the_master_toggle_and_the_address_both_gate_it() {
let full = MediaServerSettings {
enabled: true,
base_url: "http://jf:8096".into(),
token: "tok".into(),
..Default::default()
};
assert!(full.is_configured(MediaServerKind::Jellyfin));
assert!(!MediaServerSettings {
enabled: false,
..full.clone()
}
.is_configured(MediaServerKind::Jellyfin));
assert!(!MediaServerSettings {
base_url: " ".into(),
..full
}
.is_configured(MediaServerKind::Jellyfin));
}
/// Disconnect clears the CREDENTIALS and keeps the picked libraries, so a
/// reconnect does not make the user choose them again.
#[test]
fn disconnect_forgets_the_credentials_but_not_the_choices() {
let (_t, s) = store();
s.put(
MediaServerKind::Subsonic,
&MediaServerSettings {
enabled: true,
base_url: "http://nd:4533".into(),
username: "admin".into(),
password: "pw".into(),
salt: "fixed".into(),
selected_libraries: vec!["1".into()],
last_sync_tracks: 6678,
..Default::default()
},
)
.unwrap();
s.disconnect(MediaServerKind::Subsonic).unwrap();
let got = s.get(MediaServerKind::Subsonic).unwrap();
assert!(!got.enabled);
assert!(got.password.is_empty(), "the password survived a disconnect");
assert_eq!(got.last_sync_tracks, 0);
// Kept on purpose.
assert_eq!(got.base_url, "http://nd:4533");
assert_eq!(got.username, "admin");
assert_eq!(got.salt, "fixed");
assert_eq!(got.selected_libraries, vec!["1"]);
}
#[test]
fn brand_spellings_fold_to_subsonic() {
for w in ["subsonic", "navidrome", "gonic", "airsonic", "astiga"] {
assert_eq!(
MediaServerKind::from_word(w),
Some(MediaServerKind::Subsonic),
"{w}"
);
}
assert_eq!(
MediaServerKind::from_word("jellyfin"),
Some(MediaServerKind::Jellyfin)
);
assert_eq!(MediaServerKind::from_word("plex"), None);
assert_eq!(MediaServerKind::from_word("emby"), None);
}
/// Only a server that is enabled AND finished gets into the union filter.
/// A half-configured one would otherwise widen the SQL over rows that were
/// never swept.
#[test]
fn only_fully_configured_servers_reach_the_union_filter() {
let t = TempDir::new().unwrap();
let state = MediaServerState::new();
state.init_at(t.path());
assert!(state.configured_words().is_empty());
state.put(
MediaServerKind::Jellyfin,
&MediaServerSettings {
enabled: true,
base_url: "http://jf:8096".into(),
token: "tok".into(),
..Default::default()
},
);
// Enabled but with no password — not configured.
state.put(
MediaServerKind::Subsonic,
&MediaServerSettings {
enabled: true,
base_url: "http://nd:4533".into(),
username: "admin".into(),
..Default::default()
},
);
assert_eq!(state.configured_words(), vec!["jellyfin"]);
}
/// An UNBOUND state reads as disabled rather than panicking or looking
/// configured — the same safe direction the rest of the app takes.
#[test]
fn an_unbound_state_reports_nothing_configured() {
let state = MediaServerState::new();
assert!(!state.get(MediaServerKind::Jellyfin).enabled);
assert!(state.configured_words().is_empty());
}
}
+1
View File
@@ -11,6 +11,7 @@ pub mod payload_cache;
pub mod pinned_items;
pub mod playback;
pub mod playlist_play_history;
pub mod media_servers;
pub mod plex;
pub mod album_play_history;
pub mod reco_store;
+334 -29
View File
@@ -33,6 +33,27 @@ pub struct LibraryDatabase {
conn: Connection,
}
/// A SQL predicate restricting the shared remote mirror to the sources the user
/// has enabled.
///
/// The words are VALIDATED, not escaped: only `[a-z]` survives, and anything
/// else drops the entry. They arrive from `SourceId::as_str`, so they are
/// already a closed set — but this string is interpolated into SQL, and a
/// validator that cannot be bypassed beats an escape that can be forgotten.
/// An all-invalid list yields `0`, which shows nothing rather than everything.
fn remote_source_filter(sources: &[&str]) -> String {
let clean: Vec<String> = sources
.iter()
.filter(|w| !w.is_empty() && w.chars().all(|c| c.is_ascii_lowercase()))
.map(|w| format!("'{w}'"))
.collect();
if clean.is_empty() {
"0".to_string()
} else {
format!("source IN ({})", clean.join(", "))
}
}
impl LibraryDatabase {
/// Open or create database at path
pub fn open(db_path: &Path) -> Result<Self, LibraryError> {
@@ -2104,29 +2125,28 @@ impl LibraryDatabase {
include_qobuz_downloads: bool,
exclude_network_folders: bool,
plex_cache_path: Option<&std::path::Path>,
remote_cache_path: Option<&std::path::Path>,
remote_sources: &[&str],
group_mode: crate::album_grouping::AlbumGroupMode,
) -> Result<crate::models::AlbumsMetadataPage, LibraryError> {
// Best-effort ATTACH of the Plex cache so the union below can
// see `plex_cache.plex_cache_tracks`. DETACH first defensively
// so a stale attachment from a previous call (or another
// connection user) doesn't fail the new one. Failure to
// attach is non-fatal — we fall back to local-only.
let plex_attached = if let Some(path) = plex_cache_path {
if path.exists() {
let _ = self.conn.execute("DETACH DATABASE plex_cache", []);
let path_str = path.to_string_lossy().replace('\'', "''");
self.conn
.execute(
&format!("ATTACH DATABASE '{}' AS plex_cache", path_str),
[],
)
.is_ok()
} else {
false
}
} else {
false
};
// TWO attachments, deliberately. `plex_cache` is the original
// per-source mirror; `remote_cache` is the shared one every source
// added after it writes into (`qbz-media-cache`), keyed by a `source`
// column. Plex will fold into the second and this will collapse back
// to one — see that crate's header for why it is not folded in the
// same change that introduced Jellyfin and Subsonic.
//
// Best-effort, and independently so: a missing or unreadable Plex
// cache must not cost the user their Jellyfin rows, and vice versa.
let plex_attached = self.attach_best_effort("plex_cache", plex_cache_path);
// The shared mirror holds EVERY remote source, so which of them the
// union may show is a separate question from whether the file is
// there. Turning Jellyfin off has to hide Jellyfin's rows without
// touching Subsonic's, and an empty list means "no remote source is
// enabled" — do not attach at all.
let remote_filter = remote_source_filter(remote_sources);
let remote_attached = !remote_sources.is_empty()
&& self.attach_best_effort("remote_cache", remote_cache_path);
let result = self.get_albums_metadata_page_inner(
offset,
limit,
@@ -2136,14 +2156,41 @@ impl LibraryDatabase {
include_qobuz_downloads,
exclude_network_folders,
plex_attached,
remote_attached,
&remote_filter,
group_mode,
);
if plex_attached {
let _ = self.conn.execute("DETACH DATABASE plex_cache", []);
}
if remote_attached {
let _ = self.conn.execute("DETACH DATABASE remote_cache", []);
}
result
}
/// ATTACH `path` under `alias`, reporting whether the union may use it.
///
/// DETACH first, defensively: a stale attachment left by a previous call
/// (or by another user of this connection) makes the new ATTACH fail, and
/// the failure mode of that is a silently local-only library.
///
/// A failure is NON-FATAL by design. The alternative — refusing to list any
/// albums because one mirror is missing — turns "your Jellyfin server is
/// off" into "your music library is empty".
fn attach_best_effort(&self, alias: &str, path: Option<&std::path::Path>) -> bool {
let Some(path) = path.filter(|p| p.exists()) else {
return false;
};
let _ = self
.conn
.execute(&format!("DETACH DATABASE {alias}"), []);
let path_str = path.to_string_lossy().replace('\'', "''");
self.conn
.execute(&format!("ATTACH DATABASE '{path_str}' AS {alias}"), [])
.is_ok()
}
/// Resolve a folder cover for an album that has no `artwork_path` in the
/// index — e.g. an offline-cached (CMAF) album whose downloader wrote a
/// `cover.jpg` into the track folder but didn't backfill `artwork_path`.
@@ -2214,6 +2261,8 @@ impl LibraryDatabase {
include_qobuz_downloads: bool,
exclude_network_folders: bool,
plex_attached: bool,
remote_attached: bool,
remote_filter: &str,
group_mode: crate::album_grouping::AlbumGroupMode,
) -> Result<crate::models::AlbumsMetadataPage, LibraryError> {
let source_filter = if include_qobuz_downloads {
@@ -2318,10 +2367,59 @@ impl LibraryDatabase {
""
};
let unioned_clause = if plex_attached {
"SELECT * FROM aggregated UNION ALL SELECT * FROM plex_aggregated"
// The SHARED remote mirror: Jellyfin, Subsonic, and whatever comes
// next. ONE arm for all of them because the table carries a `source`
// column — that is the entire reason it exists.
//
// The group key is `<source>:<album id>`, matching Plex's `plex:<hash>`
// convention: it namespaces two servers that happen to use the same
// album id, and it is what lets a source `claim` an album card that
// arrives with no source word (which is every card that round-trips
// through a QML string property).
//
// Unlike Plex there is no bit-depth guess here. Both protocols report
// it directly — Jellyfin in MediaSources, Subsonic as an OpenSubsonic
// field — and the mappers already fold "not applicable" (Jellyfin's
// null, Subsonic's 0) to NULL. Inventing 16 for a lossless CD-rate row
// would be guessing where the server answered.
let remote_cte = if remote_attached {
format!(r#",
remote_aggregated AS (
SELECT
source || ':' || album_id AS group_key,
COALESCE(NULLIF(TRIM(album), ''), 'Unknown Album') AS title,
CASE WHEN COUNT(DISTINCT album_artist) > 1
THEN 'Various Artists'
ELSE COALESCE(NULLIF(MIN(album_artist), ''), MIN(artist), 'Unknown Artist')
END AS artist,
GROUP_CONCAT(DISTINCT artist) AS all_artists,
MIN(year) AS year,
CAST(NULL AS TEXT) AS catalog_number,
MAX(CASE WHEN artwork_token IS NOT NULL THEN artwork_token END) AS artwork,
COUNT(*) AS track_count,
CAST(SUM(COALESCE(duration_ms, 0)) / 1000 AS INTEGER) AS total_duration,
COALESCE(MAX(container), MAX(codec)) AS format,
MAX(bit_depth) AS bit_depth,
CAST(MAX(sample_rate_hz) AS REAL) AS sample_rate,
CAST(NULL AS TEXT) AS source_folders,
source AS source
FROM remote_cache.remote_cache_tracks
WHERE album_id != '' AND {remote_filter}
GROUP BY source, album_id
)"#)
} else {
"SELECT * FROM aggregated"
String::new()
};
let unioned_clause = match (plex_attached, remote_attached) {
(true, true) => {
"SELECT * FROM aggregated \
UNION ALL SELECT * FROM plex_aggregated \
UNION ALL SELECT * FROM remote_aggregated"
}
(true, false) => "SELECT * FROM aggregated UNION ALL SELECT * FROM plex_aggregated",
(false, true) => "SELECT * FROM aggregated UNION ALL SELECT * FROM remote_aggregated",
(false, false) => "SELECT * FROM aggregated",
};
let query = format!(
@@ -2378,7 +2476,7 @@ impl LibraryDatabase {
MAX(source) AS source
FROM grouped
GROUP BY group_key
){plex_cte},
){plex_cte}{remote_cte},
filtered AS (
SELECT * FROM ({unioned_clause})
WHERE ?1 = 0 OR (title LIKE ?2 OR artist LIKE ?2)
@@ -2463,6 +2561,8 @@ impl LibraryDatabase {
include_qobuz_downloads,
exclude_network_folders,
plex_attached,
remote_attached,
remote_filter,
group_mode,
)?;
}
@@ -2481,6 +2581,8 @@ impl LibraryDatabase {
include_qobuz_downloads: bool,
exclude_network_folders: bool,
plex_attached: bool,
remote_attached: bool,
remote_filter: &str,
group_mode: crate::album_grouping::AlbumGroupMode,
) -> Result<u64, LibraryError> {
let source_filter = if include_qobuz_downloads {
@@ -2518,10 +2620,33 @@ impl LibraryDatabase {
} else {
""
};
let unioned_clause = if plex_attached {
"SELECT * FROM aggregated UNION ALL SELECT * FROM plex_aggregated"
// Grouped and filtered EXACTLY as the page query groups and filters
// it — same key, same `album_id != ''` guard. A count that disagrees
// with the page it counts is worse than no count: the grid renders a
// scrollbar for rows that are not there.
let remote_cte = if remote_attached {
format!(r#",
remote_aggregated AS (
SELECT
source || ':' || album_id AS group_key,
COALESCE(NULLIF(TRIM(album), ''), 'Unknown Album') AS title,
COALESCE(NULLIF(MIN(album_artist), ''), MIN(artist), 'Unknown Artist') AS artist
FROM remote_cache.remote_cache_tracks
WHERE album_id != '' AND {remote_filter}
GROUP BY source, album_id
)"#)
} else {
"SELECT * FROM aggregated"
String::new()
};
let unioned_clause = match (plex_attached, remote_attached) {
(true, true) => {
"SELECT * FROM aggregated \
UNION ALL SELECT * FROM plex_aggregated \
UNION ALL SELECT * FROM remote_aggregated"
}
(true, false) => "SELECT * FROM aggregated UNION ALL SELECT * FROM plex_aggregated",
(false, true) => "SELECT * FROM aggregated UNION ALL SELECT * FROM remote_aggregated",
(false, false) => "SELECT * FROM aggregated",
};
let query = format!(
@@ -2558,7 +2683,7 @@ impl LibraryDatabase {
END AS artist
FROM grouped
GROUP BY group_key
){plex_cte}
){plex_cte}{remote_cte}
SELECT COUNT(*)
FROM ({unioned_clause})
WHERE ?1 = 0 OR (title LIKE ?2 OR artist LIKE ?2)
@@ -2567,6 +2692,7 @@ impl LibraryDatabase {
source_filter = source_filter,
network_filter = network_filter,
plex_cte = plex_cte,
remote_cte = remote_cte,
unioned_clause = unioned_clause,
);
@@ -7095,3 +7221,182 @@ mod sidecar_position_tests {
assert!(db.heal_playlist_sidecar_positions(7, 5).unwrap().is_empty());
}
}
#[cfg(test)]
mod remote_union_tests {
use super::*;
use tempfile::TempDir;
/// A local library with one album, plus a shared remote mirror holding one
/// Jellyfin album and one Subsonic album.
fn bench() -> (TempDir, LibraryDatabase, std::path::PathBuf) {
let tmp = TempDir::new().unwrap();
let db = LibraryDatabase::open(&tmp.path().join("library.db")).unwrap();
let mut t = LocalTrack::default();
t.file_path = "/m/local/01.flac".into();
t.title = "Local One".into();
t.album = "Local Album".into();
t.album_artist = Some("Local Artist".into());
t.artist = "Local Artist".into();
t.album_group_key = "/m/local".into();
t.album_group_title = "Local Album".into();
t.duration_secs = 100;
t.format = crate::AudioFormat::Flac;
t.bit_depth = Some(16);
t.sample_rate = 44100.0;
db.insert_track(&t).unwrap();
// The shared mirror, written with plain SQL so this test does not
// depend on `qbz-media-cache` (which depends on nothing here, and must
// keep not depending on it).
let remote = tmp.path().join("remote_cache.db");
let conn = rusqlite::Connection::open(&remote).unwrap();
conn.execute_batch(
"CREATE TABLE remote_cache_tracks (
id INTEGER PRIMARY KEY AUTOINCREMENT, source TEXT NOT NULL,
item_id TEXT NOT NULL, server_id TEXT NOT NULL DEFAULT '',
library_id TEXT NOT NULL DEFAULT '', title TEXT NOT NULL DEFAULT '',
artist TEXT NOT NULL DEFAULT '', album_artist TEXT NOT NULL DEFAULT '',
album TEXT NOT NULL DEFAULT '', album_id TEXT NOT NULL DEFAULT '',
track_number INTEGER, disc_number INTEGER,
duration_ms INTEGER NOT NULL DEFAULT 0, year INTEGER, genre TEXT,
container TEXT NOT NULL DEFAULT '', codec TEXT, bit_depth INTEGER,
sample_rate_hz INTEGER, channels INTEGER, bitrate_kbps INTEGER,
artwork_token TEXT, size_bytes INTEGER, updated_at INTEGER NOT NULL,
UNIQUE (source, item_id));",
)
.unwrap();
let mut add = |source: &str, item: &str, album: &str, album_id: &str, depth: i64| {
conn.execute(
"INSERT INTO remote_cache_tracks
(source,item_id,title,artist,album_artist,album,album_id,
duration_ms,container,bit_depth,sample_rate_hz,updated_at)
VALUES (?1,?2,?3,?4,?4,?5,?6,120000,'flac',?7,96000,1)",
rusqlite::params![source, item, format!("{item} title"), "Remote Artist", album, album_id, depth],
)
.unwrap();
};
add("jellyfin", "jf-1", "Jellyfin Album", "jf-alb", 24);
add("jellyfin", "jf-2", "Jellyfin Album", "jf-alb", 24);
add("subsonic", "sub-1", "Subsonic Album", "sub-alb", 16);
(tmp, db, remote)
}
fn titles(db: &LibraryDatabase, remote: Option<&std::path::Path>, sources: &[&str]) -> Vec<String> {
let page = db
.get_albums_metadata_page(
0,
50,
None,
"title",
"asc",
true,
false,
None,
remote,
sources,
crate::album_grouping::AlbumGroupMode::Folder,
)
.unwrap();
let mut v: Vec<String> = page.albums.iter().map(|a| a.title.clone()).collect();
v.sort();
v
}
/// Both mirrors' albums appear beside the local ones, in ONE result set —
/// which is the entire point of unioning rather than concatenating pages.
#[test]
fn enabled_remote_albums_join_the_local_ones() {
let (_t, db, remote) = bench();
assert_eq!(
titles(&db, Some(&remote), &["jellyfin", "subsonic"]),
vec!["Jellyfin Album", "Local Album", "Subsonic Album"]
);
}
/// Turning ONE source off hides ITS rows and leaves the other's alone. The
/// mirror is shared, so this is a filter rather than a detach — and getting
/// it wrong takes the wrong server's music off the screen.
#[test]
fn disabling_one_source_leaves_the_other_visible() {
let (_t, db, remote) = bench();
assert_eq!(
titles(&db, Some(&remote), &["subsonic"]),
vec!["Local Album", "Subsonic Album"]
);
assert_eq!(
titles(&db, Some(&remote), &["jellyfin"]),
vec!["Jellyfin Album", "Local Album"]
);
}
/// No source enabled, or no mirror on disk: local-only, and NOT an error.
/// Refusing to list any albums because a server is off would turn "Jellyfin
/// is unplugged" into "your library is empty".
#[test]
fn no_enabled_sources_is_local_only_not_a_failure() {
let (_t, db, remote) = bench();
assert_eq!(titles(&db, Some(&remote), &[]), vec!["Local Album"]);
assert_eq!(titles(&db, None, &["jellyfin"]), vec!["Local Album"]);
let missing = std::path::PathBuf::from("/nonexistent/remote_cache.db");
assert_eq!(titles(&db, Some(&missing), &["jellyfin"]), vec!["Local Album"]);
}
/// The two tracks of the Jellyfin album collapse into ONE card, and the
/// quality the server reported survives the aggregation. A grouping bug
/// here shows as duplicate cards, which is what the album_id key prevents.
#[test]
fn a_remote_album_aggregates_its_tracks_and_keeps_its_quality() {
let (_t, db, remote) = bench();
let page = db
.get_albums_metadata_page(
0,
50,
None,
"title",
"asc",
true,
false,
None,
Some(&remote),
&["jellyfin"],
crate::album_grouping::AlbumGroupMode::Folder,
)
.unwrap();
let jf = page
.albums
.iter()
.find(|a| a.title == "Jellyfin Album")
.expect("the jellyfin album");
assert_eq!(jf.track_count, 2, "the two tracks did not group into one card");
assert_eq!(jf.bit_depth, Some(24));
assert_eq!(jf.sample_rate, 96000.0);
assert_eq!(jf.source, "jellyfin", "the row lost its source word");
// The group key is PREFIXED, which is what lets the source claim the
// card when it comes back with no source word attached.
assert_eq!(jf.id, "jellyfin:jf-alb");
assert_eq!(page.total, 2, "the count disagrees with the page it counts");
}
/// The interpolated filter is validated, not escaped. Anything that is not
/// plain lowercase drops out, and an all-invalid list shows NOTHING rather
/// than everything — the safe direction for a predicate that reaches SQL.
#[test]
fn the_source_filter_rejects_anything_that_is_not_a_source_word() {
assert_eq!(remote_source_filter(&["jellyfin"]), "source IN ('jellyfin')");
assert_eq!(
remote_source_filter(&["jellyfin", "subsonic"]),
"source IN ('jellyfin', 'subsonic')"
);
assert_eq!(remote_source_filter(&[]), "0");
assert_eq!(remote_source_filter(&["x'; DROP TABLE local_tracks; --"]), "0");
assert_eq!(remote_source_filter(&["Jellyfin"]), "0");
assert_eq!(remote_source_filter(&[""]), "0");
// One bad entry does not smuggle itself in beside a good one.
assert_eq!(
remote_source_filter(&["jellyfin", "'; --"]),
"source IN ('jellyfin')"
);
}
}
+6
View File
@@ -79,6 +79,12 @@ qbz-library = { path = "../qbz-library" }
# library.db's mixtape tables rather than each growing their own.
qbz-mixtape = { path = "../qbz-mixtape" }
qbz-source = { path = "../qbz-source" }
# The media-server protocol crates. `qbz-qt` needs them directly for the SYNC
# (which lives here, where the tokio runtime and the progress UI are) and for
# `Credentials`, which the settings glue derives.
qbz-jellyfin = { path = "../qbz-jellyfin" }
qbz-subsonic = { path = "../qbz-subsonic" }
qbz-media-cache = { path = "../qbz-media-cache" }
# Cast: Chromecast + DLNA discovery, the two device families and the local
# media server (src/cast_qt.rs drives it — nothing is reimplemented).
qbz-cast = { path = "../qbz-cast" }
+5
View File
@@ -215,6 +215,10 @@ async fn bind_per_user_stores(dir: &std::path::Path, user_id: u64) {
// Plex playback work at all: an unbound `DbPool` refuses every read, and
// `PlexSource` with no credentials answers `NotConfigured` — which is
// exactly what shipped for one build when this line was missing.
// The media-server settings store FIRST: `source_wiring::bind_user` ends
// with `report_wiring`, which asks it which remote sources are configured.
// Bound after, that probe would report "none" on every login.
crate::media_servers_qt::init_for_user(dir);
crate::source_wiring::bind_user(dir, user_id);
// MyQBZ: branding (label + icon, read by the sidebar/nav flyout on frame
// 1) and the grids + mixtape schema.
@@ -471,6 +475,7 @@ where
// handles, the Plex art memo, the ephemeral session store. Without this
// the next account inherits the previous one's handles out of a `'static`
// registry.
crate::media_servers_qt::reset();
crate::source_wiring::teardown();
crate::offline_fwd::teardown();
// The offline download cache (index.db/library connections + the cached
+8
View File
@@ -851,6 +851,12 @@ fn all_local_feed_blocking() -> Vec<FeedItem> {
let mut out: Vec<FeedItem> = Vec::new();
let plex_on = crate::local_plex::is_enabled();
let plex_path = crate::local_plex::cache_db_path();
// The SHARED remote mirror, and which of its sources may show. Both gates
// matter: the path short-circuits the ATTACH for a user with no media
// server, and the words are what make the master toggle actually remove a
// server's rows from the grid (the mirror holds them all).
let remote_path = crate::media_servers_qt::remote_cache_path();
let remote_words = crate::media_servers_qt::configured_words();
let mode = group_mode();
// The hearts, once. The reference asks the store per row
@@ -882,6 +888,8 @@ fn all_local_feed_blocking() -> Vec<FeedItem> {
/* include_qobuz_downloads */ true,
/* exclude_network_folders */ false,
plex_path.as_deref(),
remote_path.as_deref(),
&remote_words,
mode,
)
.map(|p| p.albums)
+16
View File
@@ -34,6 +34,12 @@ use crate::local_state::{group_mode, state, with_art, with_db, TRACKS_PAGE};
pub fn load_albums_blocking() -> Result<Vec<AlbumRow>, String> {
let mode = group_mode();
let plex_path = crate::local_plex::cache_db_path();
// The SHARED remote mirror, and which of its sources may show. Both gates
// matter: the path short-circuits the ATTACH for a user with no media
// server, and the words are what make the master toggle actually remove a
// server's rows from the grid (the mirror holds them all).
let remote_path = crate::media_servers_qt::remote_cache_path();
let remote_words = crate::media_servers_qt::configured_words();
let page = with_db(|db| {
db.get_albums_metadata_page(
0,
@@ -44,6 +50,8 @@ pub fn load_albums_blocking() -> Result<Vec<AlbumRow>, String> {
/* include_qobuz_downloads */ true,
/* exclude_network_folders */ false,
plex_path.as_deref(),
remote_path.as_deref(),
&remote_words,
mode,
)
})
@@ -104,6 +112,12 @@ pub fn load_artists_blocking() -> Result<Vec<ArtistRow>, String> {
let plex_on = crate::local_plex::is_enabled();
let mode = group_mode();
let plex_path = crate::local_plex::cache_db_path();
// The SHARED remote mirror, and which of its sources may show. Both gates
// matter: the path short-circuits the ATTACH for a user with no media
// server, and the words are what make the master toggle actually remove a
// server's rows from the grid (the mirror holds them all).
let remote_path = crate::media_servers_qt::remote_cache_path();
let remote_words = crate::media_servers_qt::configured_words();
// ONE db open for the three reads the merge needs. The album set is the
// SAME query the Albums tab runs (Plex-aware union when the toggle is on),
@@ -123,6 +137,8 @@ pub fn load_artists_blocking() -> Result<Vec<ArtistRow>, String> {
/* include_qobuz_downloads */ true,
/* exclude_network_folders */ false,
plex_path.as_deref(),
remote_path.as_deref(),
&remote_words,
mode,
)?
.albums
+154
View File
@@ -125,6 +125,12 @@ pub mod qbz_local {
/// A manual sync is in flight (`plex-syncing`) — the Sync button's
/// busy state.
#[qproperty(bool, plex_syncing)]
/// Media-server sweep state. TWO properties rather than one, because
/// the two questions have different answers: `media_syncing` gates the
/// spinner, and `media_sync_progress` ("1500/4924") is what makes a
/// 45.8-second Jellyfin sweep legible instead of a frozen button.
#[qproperty(bool, media_syncing)]
#[qproperty(QString, media_sync_progress)]
/// Tracks written by the last sync; -1 = never synced this session.
#[qproperty(i32, plex_last_sync_tracks)]
/// Raw error text from the last Plex operation ("" when fine). QML
@@ -299,6 +305,37 @@ pub mod qbz_local {
/// Header Sync button (#573): re-fetch the Plex sections + tracks
/// into the shared cache DB, then reload the browse documents in
/// place. No-op when `plexAvailable` is false.
/// ── Media servers (Jellyfin / Subsonic) ─────────────────────────
///
/// One set of invokables for both, discriminated by a `server` word
/// ("jellyfin" | "subsonic"), because the panel is the same form twice
/// and the store behind it is one table. An unknown word is refused
/// with a toast rather than silently ignored.
///
/// TEST the address before asking for a password: it separates "wrong
/// address" from "wrong password", which is the difference between a
/// user fixing a typo and a user thinking the feature is broken.
#[qinvokable]
fn media_test(self: Pin<&mut QbzLocal>, server: QString, url: QString);
/// Authenticate and persist. Runs a first sweep on success.
#[qinvokable]
fn media_connect(
self: Pin<&mut QbzLocal>,
server: QString,
url: QString,
username: QString,
password: QString,
);
/// Master toggle. OFF collapses the union back immediately; the cache
/// is KEPT so turning it on again does not re-sweep.
#[qinvokable]
fn media_set_enabled(self: Pin<&mut QbzLocal>, server: QString, enabled: bool);
/// Sweep now. `full` forces a complete pass instead of a delta.
#[qinvokable]
fn media_sync(self: Pin<&mut QbzLocal>, server: QString, full: bool);
/// Sign out: clear credentials and purge this server's cached rows.
#[qinvokable]
fn media_disconnect(self: Pin<&mut QbzLocal>, server: QString);
#[qinvokable]
fn sync_plex(self: Pin<&mut QbzLocal>);
/// Master toggle. Turning it OFF collapses the browse union back to
@@ -404,6 +441,8 @@ pub struct QbzLocalRust {
plex_enabled: bool,
plex_available: bool,
plex_syncing: bool,
media_syncing: bool,
media_sync_progress: QString,
plex_last_sync_tracks: i32,
plex_error: QString,
plex_sections_json: QString,
@@ -447,6 +486,8 @@ impl Default for QbzLocalRust {
plex_enabled: false,
plex_available: false,
plex_syncing: false,
media_syncing: false,
media_sync_progress: QString::default(),
plex_last_sync_tracks: -1,
plex_error: QString::default(),
plex_sections_json: QString::from("[]"),
@@ -685,6 +726,84 @@ impl qbz_local::QbzLocal {
run_sync();
}
// ── Media servers (Jellyfin / Subsonic) ─────────────────────────────
pub fn media_test(self: Pin<&mut Self>, server: QString, url: QString) {
let (Some(kind), url) = (media_kind(&server), url.to_string()) else {
return;
};
crate::spawn(async move {
match crate::media_servers_qt::probe(kind, &url).await {
Ok(name) => crate::toast_qt::success(format!("Connected to {name}")),
Err(e) => crate::toast_qt::error(e),
}
});
}
pub fn media_connect(
self: Pin<&mut Self>,
server: QString,
url: QString,
username: QString,
password: QString,
) {
let Some(kind) = media_kind(&server) else {
return;
};
let (url, user, pass) = (url.to_string(), username.to_string(), password.to_string());
crate::spawn(async move {
match crate::media_servers_qt::connect(kind, &url, &user, &pass).await {
Ok(()) => {
crate::toast_qt::success(qbz_i18n::t("Connected"));
run_media_sync(kind, true).await;
}
Err(e) => crate::toast_qt::error(e),
}
});
}
pub fn media_set_enabled(self: Pin<&mut Self>, server: QString, enabled: bool) {
let Some(kind) = media_kind(&server) else {
return;
};
crate::spawn(async move {
let mut cfg = crate::media_servers_qt::get(kind);
cfg.enabled = enabled;
crate::media_servers_qt::put(kind, &cfg);
// The union IS the query — the grid/tracks/badges must re-run.
reload_browse();
});
}
pub fn media_sync(self: Pin<&mut Self>, server: QString, full: bool) {
let Some(kind) = media_kind(&server) else {
return;
};
// Refuse HERE rather than letting the sweep's own guard reject it: a
// second click should say why, and by the time the guard sees it the
// caller has already been told the task started.
if crate::media_sync_qt::is_syncing(kind) {
crate::toast_qt::info(qbz_i18n::t("A sync is already running"));
return;
}
crate::spawn(async move { run_media_sync(kind, full).await });
}
pub fn media_disconnect(self: Pin<&mut Self>, server: QString) {
let Some(kind) = media_kind(&server) else {
return;
};
crate::spawn(async move {
crate::media_servers_qt::disconnect(kind);
// Purge the rows too: leaving them would keep a signed-out
// server's music in the grid until something else cleared it,
// and the master-toggle path deliberately does NOT purge (so it
// can be undone cheaply). Disconnect is the destructive one.
crate::media_servers_qt::purge_cache(kind);
reload_browse();
});
}
pub fn plex_set_enabled(self: Pin<&mut Self>, enabled: bool) {
crate::spawn(async move {
let _ = tokio::task::spawn_blocking(move || plex::set_enabled(enabled)).await;
@@ -956,3 +1075,38 @@ pub(crate) fn open_album_by_id(id: String) {
});
}
/// Map the QML `server` word to a kind, toasting on an unknown one.
///
/// A silent `return` would make a typo in QML look like a dead button; this at
/// least says which word was not understood.
fn media_kind(server: &QString) -> Option<qbz_app::settings::media_servers::MediaServerKind> {
let w = server.to_string();
let kind = qbz_app::settings::media_servers::MediaServerKind::from_word(w.trim());
if kind.is_none() {
log::error!("[qbz-qt] media server: unknown server word {w:?}");
}
kind
}
/// Run a sweep and report it, then reload the browse documents so the new rows
/// appear without the user navigating away and back.
async fn run_media_sync(kind: qbz_app::settings::media_servers::MediaServerKind, full: bool) {
use qbz_app::settings::media_servers::MediaServerKind;
let result = match kind {
MediaServerKind::Jellyfin => crate::media_sync_qt::sync_jellyfin(full).await,
MediaServerKind::Subsonic => crate::media_sync_qt::sync_subsonic(full).await,
};
match result {
Ok(r) => {
log::info!(
"[qbz-qt] {} sync: {} saved, {} pruned, {} cached",
kind.as_str(),
r.saved,
r.pruned,
r.total
);
reload_browse();
}
Err(e) => crate::toast_qt::error(e),
}
}
+7
View File
@@ -128,6 +128,13 @@ mod bridge;
// The registry's injections: Plex credentials, the ephemeral store, the user
// binding and the album-identity mode. See its header.
mod source_wiring;
// Jellyfin / Subsonic: the per-user settings store plus the two gates the
// Local Library union reads. The credential glue itself is in `source_wiring`.
mod media_servers_qt;
// The library sweep. Lives in the frontend because it needs the tokio runtime
// and a channel to the progress UI; it writes through the cache handle the
// SOURCE owns, so sweep and reads can never point at different users.
mod media_sync_qt;
mod custom_theme_qt;
mod diagnostics_qt;
mod discover_config_qt;
+300
View File
@@ -0,0 +1,300 @@
//! Jellyfin / Subsonic glue for this frontend.
//!
//! The Qt-side sibling of `local_plex`, and deliberately smaller than it: the
//! persisted model lives in `qbz_app::settings::media_servers` and every
//! runtime concern lives in `qbz-jellyfin` / `qbz-subsonic` / `qbz-source`
//! (ADR-006). This file owns three things only:
//!
//! 1. a process-global `MediaServerState` bound to the ACTIVE user
//! (`<data_dir>/qbz/users/<uid>/media_servers.db`);
//! 2. the gates the Local Library reads — [`configured_words`] and
//! [`remote_cache_path`], which together decide whether a remote row
//! appears in the grid at all;
//! 3. the identifiers whose STABILITY is load-bearing — Jellyfin's
//! `DeviceId` and Subsonic's salt — generated once and persisted.
//!
//! The credential glue that `qbz-source` consumes lives in `source_wiring`
//! beside the rest of the registry's injections, so there is one place to look
//! when a source answers "not configured".
use std::path::PathBuf;
use std::sync::LazyLock;
use qbz_app::settings::media_servers::{MediaServerKind, MediaServerSettings, MediaServerState};
static STATE: LazyLock<MediaServerState> = LazyLock::new(MediaServerState::new);
/// Bind the store to the active user. Called from `auth_qt`.
pub fn init_for_user(base_dir: &std::path::Path) {
STATE.init_at(base_dir);
// Mint the two stable identifiers ONCE, now, rather than at first use.
// Both are load-bearing and both are easy to get wrong lazily: a Jellyfin
// DeviceId minted per connection attempt revokes the previous token, and a
// salt minted per request re-downloads every cover.
ensure_identities();
}
pub fn reset() {
STATE.reset();
}
pub fn get(kind: MediaServerKind) -> MediaServerSettings {
STATE.get(kind)
}
pub fn put(kind: MediaServerKind, s: &MediaServerSettings) {
STATE.put(kind, s);
}
pub fn disconnect(kind: MediaServerKind) {
STATE.disconnect(kind);
}
/// Which remote sources the Local Library union may show.
///
/// ENABLED **and** finished configuring — see
/// `MediaServerSettings::is_configured`. A server that is toggled on but has no
/// credentials yet would widen the union's `source IN (…)` over rows nothing
/// ever swept.
pub fn configured_words() -> Vec<&'static str> {
STATE.configured_words()
}
/// The shared remote mirror for the active user, or `None` when no remote
/// source is configured.
///
/// `None` short-circuits the ATTACH in `get_albums_metadata_page`: a user with
/// no media server should not pay for a database open on every page.
pub fn remote_cache_path() -> Option<PathBuf> {
if configured_words().is_empty() {
return None;
}
let uid = qbz_app::user_data::UserDataPaths::load_last_user_id().unwrap_or(0);
Some(
dirs::data_dir()?
.join("qbz")
.join("users")
.join(uid.to_string())
.join("remote_cache.db"),
)
}
/// Generate-once, persist-forever identifiers.
///
/// **Jellyfin's `DeviceId`.** The server keys its SESSION on it, and a second
/// `AuthenticateByName` under the same one REVOKES the previous token —
/// measured against 10.11.11:
///
/// ```text
/// same DeviceId: auth -> T1, auth -> T2; T1 = 401, T2 = 200
/// different DeviceId: auth -> A, auth -> B; A = 200, B = 200
/// ```
///
/// So it must be stable per INSTALL: a constant shared by every QBZ would make
/// two installs log each other out, and a fresh one per launch drops the
/// previous run's token and litters the server's devices page.
///
/// **Subsonic's salt.** `t = md5(password + salt)`, and the salt travels in
/// clear — it is not a secret. Fixing it per install is deliberate: rolling it
/// per request would make every cover URL unique, and the artwork cache keys on
/// the URL, so each pass would re-download every cover.
fn ensure_identities() {
let mut jf = STATE.get(MediaServerKind::Jellyfin);
if jf.device_id.is_empty() {
jf.device_id = format!("qbz-{}", random_hex(16));
STATE.put(MediaServerKind::Jellyfin, &jf);
log::info!("[qbz-qt] jellyfin: minted a device id for this install");
}
let mut sub = STATE.get(MediaServerKind::Subsonic);
if sub.salt.is_empty() {
sub.salt = random_hex(8);
STATE.put(MediaServerKind::Subsonic, &sub);
log::info!("[qbz-qt] subsonic: minted a salt for this install");
}
}
/// `len` hex characters of process-and-time entropy.
///
/// Not cryptographic, and it does not need to be: both consumers want
/// UNIQUENESS across installs, not unpredictability. The salt is transmitted in
/// clear by the protocol itself, and the device id is a label the server files
/// a session under. Pulling in an RNG crate for two strings that are generated
/// once per install would be more dependency than the job.
fn random_hex(len: usize) -> String {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut out = String::with_capacity(len);
let mut seed = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0)
^ (std::process::id() as u64) << 32;
while out.len() < len {
let mut h = DefaultHasher::new();
seed.hash(&mut h);
seed = h.finish();
out.push_str(&format!("{seed:016x}"));
}
out.truncate(len);
out
}
/// The `Credentials` a Subsonic call needs, derived from the stored password
/// and the install's fixed salt.
pub fn subsonic_credentials() -> Option<(String, qbz_subsonic::Credentials)> {
let s = STATE.get(MediaServerKind::Subsonic);
if !s.is_configured(MediaServerKind::Subsonic) {
return None;
}
Some((
s.base_url.clone(),
qbz_subsonic::Credentials::new(&s.username, &s.password, &s.salt),
))
}
/// `(base_url, access_token)` when Jellyfin is usable right now.
pub fn jellyfin_server() -> Option<(String, String)> {
let s = STATE.get(MediaServerKind::Jellyfin);
s.is_configured(MediaServerKind::Jellyfin)
.then(|| (s.base_url.clone(), s.token.clone()))
}
// ---------------------------------------------------------------------------
// Connect / probe / purge — the settings panel's verbs
// ---------------------------------------------------------------------------
/// "Test connection", BEFORE the user is asked for a password.
///
/// Returns the server's display name. The point is to separate "wrong address"
/// from "wrong password": without it, every failure looks like bad credentials
/// and the user retypes a password that was never the problem.
///
/// Jellyfin has an unauthenticated probe (`/System/Info/Public`), so its test is
/// genuinely credential-free. Subsonic has none — `ping.view` needs credentials
/// — so its "test" can only confirm the address is reachable, and it reports
/// that honestly rather than claiming more.
pub async fn probe(kind: MediaServerKind, url: &str) -> Result<String, String> {
match kind {
MediaServerKind::Jellyfin => qbz_jellyfin::probe(url)
.await
.map(|i| format!("{} {}", i.server_name, i.version))
.map_err(|e| e.to_string()),
MediaServerKind::Subsonic => {
// No credential-free endpoint exists. A `ping` with an empty user
// returns the protocol's own "missing parameter" — which still
// proves a Subsonic server answered at this address, and that is
// exactly what the test is for.
let creds = qbz_subsonic::Credentials::new("", "", "probe");
let client = qbz_subsonic::SubsonicClient::new(url, creds).map_err(|e| e.to_string())?;
match client.ping().await {
Ok(i) => Ok(format!("{} {}", i.kind, i.version)),
// A protocol-level error means a Subsonic server IS there.
Err(qbz_subsonic::SubsonicError::Unauthorized)
| Err(qbz_subsonic::SubsonicError::Api { .. }) => {
Ok("a Subsonic server (sign in to continue)".to_string())
}
Err(e) => Err(e.to_string()),
}
}
}
}
/// Authenticate and persist.
///
/// What gets stored differs per protocol, and the asymmetry is the protocol's:
/// Jellyfin issues a token and never needs the password again; Subsonic has no
/// session, so the password is kept and its token is re-derived per request.
pub async fn connect(
kind: MediaServerKind,
url: &str,
username: &str,
password: &str,
) -> Result<(), String> {
let mut cfg = get(kind);
match kind {
MediaServerKind::Jellyfin => {
// The DeviceId must be the PERSISTED one: authenticating under a
// fresh id every time revokes the previous token and litters the
// server's device list. `init_for_user` minted it.
let session =
qbz_jellyfin::authenticate(url, &cfg.device_id, username, password)
.await
.map_err(|e| e.to_string())?;
let info = qbz_jellyfin::probe(url).await.ok();
cfg.base_url = qbz_jellyfin::normalize_base_url(url);
cfg.token = session.access_token;
// The USER ID, not the typed name: every `/Items` call keys on it,
// and the two are not interchangeable.
cfg.username = session.user_id;
cfg.server_id = session.server_id;
cfg.server_name = info.map(|i| i.server_name).unwrap_or_default();
// The password is deliberately NOT stored — the token replaced it.
cfg.password = String::new();
}
MediaServerKind::Subsonic => {
let creds = qbz_subsonic::Credentials::new(username, password, &cfg.salt);
let client = qbz_subsonic::SubsonicClient::new(url, creds).map_err(|e| e.to_string())?;
let info = client.ping().await.map_err(|e| e.to_string())?;
if !info.open_subsonic {
// Not fatal: the library still lists and still plays. But
// without the OpenSubsonic fields there is no bitDepth or
// samplingRate, so every quality badge degrades to unknown —
// and a user who cares about that deserves to hear it now
// rather than wonder later.
log::warn!(
"[qbz-qt] subsonic: {} is not OpenSubsonic — quality badges will be unavailable",
info.kind
);
}
cfg.base_url = qbz_subsonic::normalize_base_url(url);
cfg.username = username.to_string();
// KEPT, because the protocol re-derives its token on every request.
cfg.password = password.to_string();
cfg.token = String::new();
cfg.server_name = format!("{} {}", info.kind, info.version);
}
}
cfg.enabled = true;
put(kind, &cfg);
Ok(())
}
/// Drop this server's cached rows.
///
/// Only from DISCONNECT. The master toggle deliberately keeps them: turning a
/// server off should be cheap to undo, and re-sweeping a 5000-track Jellyfin
/// library costs 46 seconds.
pub fn purge_cache(kind: MediaServerKind) {
let source = match kind {
MediaServerKind::Jellyfin => qbz_media_cache::RemoteSource::Jellyfin,
MediaServerKind::Subsonic => qbz_media_cache::RemoteSource::Subsonic,
};
let handle = match kind {
MediaServerKind::Jellyfin => qbz_source::registry().jellyfin().cache(),
MediaServerKind::Subsonic => qbz_source::registry().subsonic().cache(),
};
match handle.with_mut(|c| qbz_media_cache::clear(c, source)) {
Some(Ok(n)) => log::info!("[qbz-qt] {} cache purged: {n} rows", kind.as_str()),
Some(Err(e)) => log::error!("[qbz-qt] {} cache purge failed: {e}", kind.as_str()),
None => log::warn!("[qbz-qt] {} cache purge: no user bound", kind.as_str()),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The identifiers must be unique per install. They are generated once and
/// persisted, so the only property worth pinning here is that two draws do
/// not collide — a fixed string would silently make every install share a
/// Jellyfin session.
#[test]
fn the_generated_identifiers_are_the_right_length_and_differ() {
let a = random_hex(16);
let b = random_hex(16);
assert_eq!(a.len(), 16);
assert_eq!(random_hex(8).len(), 8);
assert_ne!(a, b, "two draws collided — every install would share a session");
assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
}
}
+585
View File
@@ -0,0 +1,585 @@
//! The library sweep: a media server's catalog into the shared cache.
//!
//! Lives here rather than in `qbz-source` because it needs the tokio runtime
//! and a channel to the progress UI, and that crate deliberately has neither
//! (design 02 §8). It writes through the cache handle the SOURCE owns, so the
//! sweep and every read agree about which user's mirror they are touching.
//!
//! # The two protocols cost very different amounts, and the code says so
//!
//! Measured on 2026-08-20:
//!
//! | | rows | wall | per track |
//! |---|---|---|---|
//! | Jellyfin | 4924 | **45.8 s** | 9.3 ms |
//! | Subsonic | 6678 | **0.81 s** | 0.12 ms |
//!
//! Jellyfin's cost is server-side media-info hydration, demanded by
//! `Fields=MediaSources` — the only way to get `BitDepth` / `SampleRate`.
//! `Fields=MediaStreams` trims 29 % of the bytes and saves nothing. Subsonic
//! ships the same facts as ordinary OpenSubsonic song fields, for free.
//!
//! So Jellyfin gets a progress report and a delta path; Subsonic needs neither
//! and is simply run to completion.
//!
//! # Two rules the prune depends on
//!
//! 1. **`prune_stale` runs only after a sweep that COMPLETED.** It deletes rows
//! the sweep did not touch, which is how a track deleted on the server
//! disappears here. A connection dropped halfway would otherwise read as
//! "the server deleted everything the sweep never got to".
//! 2. **A delta sweep never prunes**, for the same reason with the sign
//! flipped: it deliberately does not see unchanged rows, so every one of
//! them looks stale.
use std::sync::atomic::{AtomicBool, Ordering};
use qbz_app::settings::media_servers::{MediaServerKind, MediaServerSettings};
use qbz_media_cache::{CachedLibrary, CachedTrack, RemoteSource};
/// One sweep at a time, per source. A second one would fight the first for the
/// cache's write lock and double the server's load to produce the same rows.
static JELLYFIN_BUSY: AtomicBool = AtomicBool::new(false);
static SUBSONIC_BUSY: AtomicBool = AtomicBool::new(false);
fn busy_flag(kind: MediaServerKind) -> &'static AtomicBool {
match kind {
MediaServerKind::Jellyfin => &JELLYFIN_BUSY,
MediaServerKind::Subsonic => &SUBSONIC_BUSY,
}
}
/// Is a sweep running for this server right now?
pub fn is_syncing(kind: MediaServerKind) -> bool {
busy_flag(kind).load(Ordering::Relaxed)
}
/// RAII guard so an early return — or a `?` — cannot leave the flag stuck on.
/// A stuck flag means the sync button never works again until a restart.
struct BusyGuard(&'static AtomicBool);
impl BusyGuard {
fn acquire(kind: MediaServerKind) -> Option<Self> {
let flag = busy_flag(kind);
flag.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.ok()
.map(|_| BusyGuard(flag))
}
}
impl Drop for BusyGuard {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
/// What a finished sweep reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SyncReport {
/// Rows written or refreshed.
pub saved: usize,
/// Rows deleted because the server no longer has them. Always 0 for a
/// delta sweep — see the module header.
pub pruned: usize,
/// Tracks in the cache afterwards.
pub total: u64,
}
/// Push a progress line to the UI. Cheap enough to call per page; the pages are
/// seconds apart on Jellyfin and there are 14 of them on Subsonic.
fn report(kind: MediaServerKind, done: u64, total: u64) {
log::info!("[qbz-qt] {} sync: {done}/{total}", kind.as_str());
let text = format!("{done}/{total}");
crate::local_bridge::ui(move |mut b| {
b.as_mut()
.set_media_sync_progress(cxx_qt_lib::QString::from(text.as_str()));
});
}
/// Raise/lower the spinner flag and clear the progress text when it goes down.
///
/// Separate from [`BusyGuard`] on purpose: that guard is process state and must
/// be released synchronously on every path, while this hop crosses to the Qt
/// thread and cannot be done from a `Drop`.
fn set_syncing_ui(on: bool) {
crate::local_bridge::ui(move |mut b| {
b.as_mut().set_media_syncing(on);
if !on {
b.as_mut()
.set_media_sync_progress(cxx_qt_lib::QString::default());
}
});
}
// ---------------------------------------------------------------------------
// Jellyfin
// ---------------------------------------------------------------------------
/// Sweep a Jellyfin server into the cache.
///
/// `full` forces a complete pass; otherwise a server that has been swept before
/// gets a DELTA (`minDateLastSaved`), which Jellyfin honours — verified: a
/// future-dated delta returns zero rows. That turns a re-sync from 45.8 s into
/// the cost of whatever actually changed.
pub async fn sync_jellyfin(full: bool) -> Result<SyncReport, String> {
let kind = MediaServerKind::Jellyfin;
let Some(_guard) = BusyGuard::acquire(kind) else {
return Err("a jellyfin sync is already running".into());
};
let cfg = crate::media_servers_qt::get(kind);
if !cfg.is_configured(kind) {
return Err("jellyfin is not configured".into());
}
set_syncing_ui(true);
let out = sync_jellyfin_inner(cfg, full).await;
set_syncing_ui(false);
out
}
async fn sync_jellyfin_inner(
cfg: MediaServerSettings,
full: bool,
) -> Result<SyncReport, String> {
let kind = MediaServerKind::Jellyfin;
let client = qbz_jellyfin::JellyfinClient::new(&cfg.base_url, &cfg.token, &cfg.username)
.map_err(|e| e.to_string())?;
// `username` holds the Jellyfin USER ID for the API's purposes — see
// `connect_jellyfin`, which stores the id the auth response returned rather
// than the typed name, because every `/Items` call keys on the id.
let libraries = client.music_libraries().await.map_err(|e| e.to_string())?;
if libraries.is_empty() {
return Err("this jellyfin server exposes no music library".into());
}
let wanted: Vec<&qbz_jellyfin::MusicLibrary> = if cfg.selected_libraries.is_empty() {
// Never chosen: take them all. Matching the Plex flow, where the first
// fetch default-selects everything rather than showing an empty grid
// until the user opens settings.
libraries.iter().collect()
} else {
libraries
.iter()
.filter(|l| cfg.selected_libraries.contains(&l.id))
.collect()
};
let delta = (!full && cfg.last_sync_at > 0).then(|| iso8601(cfg.last_sync_at));
let started = qbz_media_cache::sweep_start();
let mut saved = 0usize;
for lib in &wanted {
let total = client
.track_count(Some(&lib.id))
.await
.map_err(|e| e.to_string())?;
let mut offset = 0u64;
loop {
let (page, _) = client
.tracks_page(Some(&lib.id), offset, delta.as_deref())
.await
.map_err(|e| e.to_string())?;
if page.is_empty() {
break;
}
let rows: Vec<CachedTrack> = page
.iter()
.map(|t| jellyfin_row(t, &cfg.server_id, &lib.id))
.collect();
saved += write_rows(RemoteSource::Jellyfin, &rows)?;
offset += page.len() as u64;
report(kind, offset.min(total), total);
if page.len() < qbz_jellyfin::PAGE_SIZE as usize {
break;
}
}
}
write_libraries(
RemoteSource::Jellyfin,
&libraries
.iter()
.map(|l| CachedLibrary {
source: "jellyfin".into(),
library_id: l.id.clone(),
name: l.name.clone(),
server_id: cfg.server_id.clone(),
})
.collect::<Vec<_>>(),
)?;
// A DELTA never prunes: it did not ask about unchanged rows, so every one
// of them would look stale.
let pruned = if delta.is_none() {
prune(RemoteSource::Jellyfin, started)?
} else {
0
};
finish(kind, cfg, saved, pruned, RemoteSource::Jellyfin)
}
fn jellyfin_row(t: &qbz_jellyfin::JellyfinTrack, server_id: &str, library_id: &str) -> CachedTrack {
CachedTrack {
id: 0,
source: "jellyfin".into(),
item_id: t.id.clone(),
server_id: server_id.to_string(),
library_id: library_id.to_string(),
title: t.title.clone(),
artist: t.artist.clone(),
album_artist: t.album_artist.clone(),
album: t.album.clone(),
album_id: t.album_id.clone(),
track_number: t.track_number,
disc_number: t.disc_number,
duration_ms: t.duration_ms,
year: t.year,
genre: t.genre.clone(),
container: t.container.clone(),
codec: t.codec.clone(),
bit_depth: t.bit_depth,
sample_rate_hz: t.sample_rate_hz,
channels: t.channels,
bitrate_kbps: t.bitrate_bps.map(|b| b / 1000),
// `<albumId>/<tag>`, because a Jellyfin image tag alone is not
// addressable — the url hangs off the ITEM and the tag only versions
// it. `JellyfinSource::artwork_token` splits it back apart.
artwork_token: t
.album_image_tag
.as_ref()
.filter(|_| !t.album_id.is_empty())
.map(|tag| format!("{}/{}", t.album_id, tag)),
size_bytes: None,
}
}
/// Jellyfin wants `minDateLastSaved` as ISO-8601 UTC.
///
/// Hand-rolled from a Unix timestamp rather than pulling in `chrono`: this is
/// the only date this crate formats, the civil-calendar arithmetic below is
/// fixed-rule (proleptic Gregorian, no zones, no leap seconds), and the value
/// is only ever compared by the server against its own stamps.
fn iso8601(unix_secs: i64) -> String {
let days = unix_secs.div_euclid(86_400);
let secs = unix_secs.rem_euclid(86_400);
let (h, m, s) = (secs / 3600, (secs % 3600) / 60, secs % 60);
// Days since 1970-01-01 -> civil date (Howard Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let mth = if mp < 10 { mp + 3 } else { mp - 9 };
let year = if mth <= 2 { y + 1 } else { y };
format!("{year:04}-{mth:02}-{d:02}T{h:02}:{m:02}:{s:02}Z")
}
// ---------------------------------------------------------------------------
// Subsonic
// ---------------------------------------------------------------------------
/// Sweep a Subsonic-compatible server into the cache.
///
/// No delta — the protocol offers none — and none is needed: the whole library
/// costs under a second because quality rides along with every song.
///
/// The sweep MODE is detected rather than assumed. `search3` with an empty
/// query enumerated 6678 tracks in 14 requests on Navidrome, but that is the
/// behaviour most likely to differ on a server that was never on the bench, so
/// a probe decides and the portable `getAlbumList2` + `getAlbum` walk is the
/// fallback.
pub async fn sync_subsonic(_full: bool) -> Result<SyncReport, String> {
let kind = MediaServerKind::Subsonic;
let Some(_guard) = BusyGuard::acquire(kind) else {
return Err("a subsonic sync is already running".into());
};
let cfg = crate::media_servers_qt::get(kind);
let Some((base, creds)) = crate::media_servers_qt::subsonic_credentials() else {
return Err("subsonic is not configured".into());
};
set_syncing_ui(true);
let out = sync_subsonic_inner(cfg, base, creds).await;
set_syncing_ui(false);
out
}
async fn sync_subsonic_inner(
cfg: MediaServerSettings,
base: String,
creds: qbz_subsonic::Credentials,
) -> Result<SyncReport, String> {
let kind = MediaServerKind::Subsonic;
let client = qbz_subsonic::SubsonicClient::new(&base, creds).map_err(|e| e.to_string())?;
let folders = client.music_folders().await.unwrap_or_default();
let started = qbz_media_cache::sweep_start();
let mode = client.detect_sweep_mode().await;
log::info!("[qbz-qt] subsonic sync: {mode:?}");
let mut saved = 0usize;
match mode {
qbz_subsonic::SweepMode::Search3 => {
let mut offset = 0u32;
loop {
let page = client.search_page(offset).await.map_err(|e| e.to_string())?;
if page.is_empty() {
break;
}
let rows: Vec<CachedTrack> = page.iter().map(subsonic_row).collect();
saved += write_rows(RemoteSource::Subsonic, &rows)?;
offset += page.len() as u32;
report(kind, offset as u64, offset as u64);
if (page.len() as u32) < qbz_subsonic::PAGE_SIZE {
break;
}
}
}
qbz_subsonic::SweepMode::PerAlbum => {
let mut offset = 0u32;
let mut albums: Vec<String> = Vec::new();
loop {
let page = client.album_ids(offset).await.map_err(|e| e.to_string())?;
if page.is_empty() {
break;
}
offset += page.len() as u32;
let done = page.len() as u32;
albums.extend(page);
if done < qbz_subsonic::PAGE_SIZE {
break;
}
}
let total = albums.len() as u64;
for (i, id) in albums.iter().enumerate() {
// One dead album must not abort a 675-request sweep. Logged and
// skipped, exactly as `resolve_collection_tracks` treats a
// failed item: partial beats total failure.
match client.album_tracks(id).await {
Ok(t) => {
let rows: Vec<CachedTrack> = t.iter().map(subsonic_row).collect();
saved += write_rows(RemoteSource::Subsonic, &rows)?;
}
Err(e) => log::warn!("[qbz-qt] subsonic sync: album {id} failed ({e}) — skipped"),
}
if i % 25 == 0 {
report(kind, i as u64, total);
}
}
}
}
write_libraries(
RemoteSource::Subsonic,
&folders
.iter()
.map(|f| CachedLibrary {
source: "subsonic".into(),
library_id: f.id.clone(),
name: f.name.clone(),
server_id: String::new(),
})
.collect::<Vec<_>>(),
)?;
let pruned = prune(RemoteSource::Subsonic, started)?;
finish(kind, cfg, saved, pruned, RemoteSource::Subsonic)
}
fn subsonic_row(t: &qbz_subsonic::SubsonicTrack) -> CachedTrack {
CachedTrack {
id: 0,
source: "subsonic".into(),
item_id: t.id.clone(),
server_id: String::new(),
library_id: String::new(),
title: t.title.clone(),
artist: t.artist.clone(),
album_artist: t.album_artist.clone(),
album: t.album.clone(),
album_id: t.album_id.clone(),
track_number: t.track_number,
disc_number: t.disc_number,
duration_ms: t.duration_ms,
year: t.year,
genre: t.genre.clone(),
container: t.suffix.clone(),
codec: t.content_type.clone(),
bit_depth: t.bit_depth,
sample_rate_hz: t.sample_rate_hz,
channels: t.channels,
bitrate_kbps: t.bitrate_kbps,
// The OPAQUE coverArt id, verbatim. Never parsed, never built.
artwork_token: t.cover_art.clone(),
size_bytes: t.size,
}
}
// ---------------------------------------------------------------------------
// Cache plumbing — through the SOURCE's handle, never a second connection
// ---------------------------------------------------------------------------
/// The cache handle for a source. Going through the registry rather than
/// opening our own connection is what keeps the sweep and every read pointed at
/// the same user's mirror: `bind_user` moves them together.
fn handle(source: RemoteSource) -> &'static qbz_source::CacheHandle {
match source {
RemoteSource::Jellyfin => qbz_source::registry().jellyfin().cache(),
RemoteSource::Subsonic => qbz_source::registry().subsonic().cache(),
}
}
fn write_rows(source: RemoteSource, rows: &[CachedTrack]) -> Result<usize, String> {
handle(source)
.with_mut(|c| qbz_media_cache::save_tracks(c, source, rows))
.ok_or_else(|| "the remote cache is not bound to a user".to_string())?
}
fn write_libraries(source: RemoteSource, libs: &[CachedLibrary]) -> Result<(), String> {
handle(source)
.with_mut(|c| qbz_media_cache::save_libraries(c, source, libs))
.ok_or_else(|| "the remote cache is not bound to a user".to_string())?
}
fn prune(source: RemoteSource, started: i64) -> Result<usize, String> {
handle(source)
.with_mut(|c| qbz_media_cache::prune_stale(c, source, started))
.ok_or_else(|| "the remote cache is not bound to a user".to_string())?
}
fn count(source: RemoteSource) -> u64 {
handle(source)
.with(|c| qbz_media_cache::count(c, source).unwrap_or(0))
.unwrap_or(0)
}
/// Stamp the sweep and report.
///
/// `last_sync_at` is written ONLY here, at the end of a run that finished —
/// every failure path above returns early without touching it. That is what
/// makes the next delta sound: a stamp written after a partial sweep would tell
/// the server "I have everything up to now", and the rows the interrupted run
/// never saw would never be asked for again.
fn finish(
kind: MediaServerKind,
mut cfg: MediaServerSettings,
saved: usize,
pruned: usize,
source: RemoteSource,
) -> Result<SyncReport, String> {
let total = count(source);
cfg.last_sync_at = qbz_media_cache::sweep_start();
cfg.last_sync_tracks = total as i64;
crate::media_servers_qt::put(kind, &cfg);
log::info!(
"[qbz-qt] {} sync finished: {saved} saved, {pruned} pruned, {total} cached",
kind.as_str()
);
Ok(SyncReport {
saved,
pruned,
total,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// The delta parameter Jellyfin is handed. A wrong date is not a crash —
/// it is a sweep that silently returns the wrong set, so the arithmetic is
/// pinned against known instants.
#[test]
fn the_delta_timestamp_is_iso8601_utc() {
assert_eq!(iso8601(0), "1970-01-01T00:00:00Z");
assert_eq!(iso8601(1_000_000_000), "2001-09-09T01:46:40Z");
// A leap day, which is where a hand-rolled civil calendar goes wrong.
assert_eq!(iso8601(1_709_164_800), "2024-02-29T00:00:00Z");
assert_eq!(iso8601(1_709_251_199), "2024-02-29T23:59:59Z");
assert_eq!(iso8601(1_709_251_200), "2024-03-01T00:00:00Z");
// A non-leap century, the other classic off-by-one.
assert_eq!(iso8601(951_782_400), "2000-02-29T00:00:00Z");
}
/// The busy flag must survive an early return. A stuck flag means the sync
/// button never works again until the app restarts.
#[test]
fn the_busy_guard_releases_on_drop() {
let kind = MediaServerKind::Jellyfin;
assert!(!is_syncing(kind));
{
let _g = BusyGuard::acquire(kind).expect("first acquire");
assert!(is_syncing(kind));
// A second sweep is refused rather than queued.
assert!(BusyGuard::acquire(kind).is_none());
}
assert!(!is_syncing(kind), "the flag stuck after the guard dropped");
// ...and the other source was never blocked by it.
assert!(!is_syncing(MediaServerKind::Subsonic));
}
/// A Jellyfin art token is only useful with the item it hangs off, so a row
/// with a tag and no album id must carry NO token rather than a broken one.
#[test]
fn a_jellyfin_art_token_needs_its_album_id() {
let mut t = qbz_jellyfin::JellyfinTrack {
id: "i".into(),
title: String::new(),
artist: String::new(),
album_artist: String::new(),
album: String::new(),
album_id: "alb".into(),
track_number: None,
disc_number: None,
duration_ms: 0,
year: None,
genre: None,
container: String::new(),
codec: None,
bit_depth: None,
sample_rate_hz: None,
channels: None,
bitrate_bps: None,
album_image_tag: Some("tag".into()),
server_path: None,
};
assert_eq!(
jellyfin_row(&t, "srv", "lib").artwork_token.as_deref(),
Some("alb/tag")
);
t.album_id = String::new();
assert_eq!(jellyfin_row(&t, "srv", "lib").artwork_token, None);
t.album_id = "alb".into();
t.album_image_tag = None;
assert_eq!(jellyfin_row(&t, "srv", "lib").artwork_token, None);
}
/// Bitrate crosses the boundary in different units: Jellyfin reports bits
/// per second, Subsonic kilobits. The cache stores kbps.
#[test]
fn bitrate_is_normalised_to_kbps_from_both_wires() {
let jf = qbz_jellyfin::JellyfinTrack {
id: "i".into(),
title: String::new(),
artist: String::new(),
album_artist: String::new(),
album: String::new(),
album_id: "a".into(),
track_number: None,
disc_number: None,
duration_ms: 0,
year: None,
genre: None,
container: String::new(),
codec: None,
bit_depth: None,
sample_rate_hz: None,
channels: None,
bitrate_bps: Some(3_120_281),
album_image_tag: None,
server_path: None,
};
assert_eq!(jellyfin_row(&jf, "s", "l").bitrate_kbps, Some(3120));
}
}
@@ -132,6 +132,10 @@ pub fn fetch_local_and_plex(artist_name: &str) -> Vec<Candidate> {
return Vec::new();
}
let plex_path = crate::local_plex::cache_db_path();
// The shared remote mirror + the enabled sources, same gates the Albums
// tab uses — the builder must see the SAME set the grid shows.
let remote_path = crate::media_servers_qt::remote_cache_path();
let remote_words = crate::media_servers_qt::configured_words();
// Map INSIDE the `with_db` closure so `db.resolve_album_cover_fallback` is
// reachable (mirrors the Albums grid): the cover PATH rides on the
// candidate's `artwork_url`, so the saved collection item carries it and the
@@ -153,6 +157,8 @@ pub fn fetch_local_and_plex(artist_name: &str) -> Vec<Candidate> {
// the builder must see the SAME set the Albums tab shows.
/* exclude_network_folders */ false,
plex_path.as_deref(),
remote_path.as_deref(),
&remote_words,
// My QBZ collections are artist-scoped CANDIDATES, not the Albums
// view — keep the metadata grouping regardless of the user's Local
// Library identity-mode pref.
+48 -1
View File
@@ -66,6 +66,37 @@ impl qbz_source::PlexCreds for PlexCredsGlue {
}
}
/// `JellyfinSource`'s view of the media-server settings store.
struct JellyfinGlue;
impl qbz_source::JellyfinCreds for JellyfinGlue {
fn is_enabled(&self) -> bool {
crate::media_servers_qt::jellyfin_server().is_some()
}
fn server(&self) -> Option<(String, String)> {
crate::media_servers_qt::jellyfin_server()
}
}
/// `SubsonicSource`'s view of the same store.
///
/// It hands over a derived `Credentials` rather than a bearer token because
/// Subsonic has no session: every request carries `md5(password + salt)`, so
/// the token is computed here, from the stored password and the install's
/// fixed salt.
struct SubsonicGlue;
impl qbz_source::SubsonicCreds for SubsonicGlue {
fn is_enabled(&self) -> bool {
crate::media_servers_qt::subsonic_credentials().is_some()
}
fn server(&self) -> Option<(String, qbz_subsonic::Credentials)> {
crate::media_servers_qt::subsonic_credentials()
}
}
/// `LocalSource`'s view of the session-scoped ephemeral store.
struct EphemeralGlue;
@@ -90,6 +121,8 @@ impl qbz_source::EphemeralTracks for EphemeralGlue {
pub(crate) fn install() {
let registry = qbz_source::registry();
registry.plex().set_creds(Some(Arc::new(PlexCredsGlue)));
registry.jellyfin().set_creds(Some(Arc::new(JellyfinGlue)));
registry.subsonic().set_creds(Some(Arc::new(SubsonicGlue)));
registry.local().set_ephemeral(Some(Arc::new(EphemeralGlue)));
// Reads BEFORE a user is bound (splash, session restore) must resolve the
// way `local_state::with_db` already resolves them — through
@@ -167,8 +200,20 @@ fn report_wiring() {
} else {
"NO"
};
// The remote pair reports what the union will actually see, which is the
// question that matters: a server can be enabled and still contribute
// nothing because it was never swept.
let remote = {
let words = crate::media_servers_qt::configured_words();
if words.is_empty() {
"none configured".to_string()
} else {
words.join("+")
}
};
log::info!(
"[qbz-qt] source registry bound: local_tracks={tracks} plex={plex} ephemeral_store={ephemeral}"
"[qbz-qt] source registry bound: local_tracks={tracks} plex={plex} \
ephemeral_store={ephemeral} remote={remote}"
);
}
@@ -184,6 +229,8 @@ pub(crate) fn teardown() {
// rather than left cleared — `PlexSource::teardown` drops the handle.
let registry = qbz_source::registry();
registry.plex().set_creds(Some(Arc::new(PlexCredsGlue)));
registry.jellyfin().set_creds(Some(Arc::new(JellyfinGlue)));
registry.subsonic().set_creds(Some(Arc::new(SubsonicGlue)));
registry.local().set_ephemeral(Some(Arc::new(EphemeralGlue)));
registry
.local()
+68 -3
View File
@@ -116,6 +116,12 @@ impl Default for JellyfinSource {
/// class of inference the seam exists to delete.
pub(crate) fn recognises(raw: &RawRef) -> bool {
raw.source == Some(SourceId::JELLYFIN)
// The PREFIXED album key the Local Library grid publishes. Without
// this arm an album card carrying no source word — which is every card
// that round-trips through a QML string property — would be claimed by
// nobody and the album page would open empty. Plex solves the same
// problem the same way, with its `plex:` keys.
|| raw.id.trim().starts_with("jellyfin:")
|| raw
.numeric()
.map(|n| RemoteSource::of_id(n as i64) == Some(RemoteSource::Jellyfin))
@@ -137,14 +143,20 @@ impl Source for JellyfinSource {
Some(match kind {
// An album id is the server's own, opaque and non-numeric.
ItemKind::Album => {
if id.is_empty() {
// The grid publishes `jellyfin:<server album id>`; a producer
// that holds the raw id may pass it bare. STRIP the prefix —
// the cache and the server both speak the raw id, and carrying
// the prefixed form inward is how Plex ended up with two album
// keys only one of its queries understood (survey IC-2).
let bare = id.strip_prefix("jellyfin:").unwrap_or(id).trim();
if bare.is_empty() {
Err(SourceError::BadIdShape {
by: SourceId::JELLYFIN,
id: id.to_string(),
why: "a jellyfin album id is the server's item id, never empty",
why: "a jellyfin album id is the server's own id, never empty",
})
} else {
Ok(MediaRef::new(SourceId::JELLYFIN, ItemKind::Album, id))
Ok(MediaRef::new(SourceId::JELLYFIN, ItemKind::Album, bare))
}
}
// A TRACK arrives in one of two shapes and both must normalise to
@@ -439,6 +451,59 @@ mod tests {
}));
}
/// The grid's album key is PREFIXED, and it must round-trip: recognised
/// with no source word at all, and stripped back to the raw server id the
/// cache and the server both speak.
#[test]
fn a_prefixed_album_key_is_recognised_and_stripped() {
let s = connected();
// No source word — the shape a QML string property hands back.
let raw = RawRef {
kind: Some(ItemKind::Album),
id: "jellyfin:alb-1".into(),
..Default::default()
};
assert!(recognises(&raw), "an unlabelled prefixed key was not recognised");
let m = s.claim(&raw).unwrap().unwrap();
assert_eq!(m.id(), "alb-1", "the prefix was carried inward");
// A bare id with the source word still works.
let bare = s
.claim(&RawRef {
source: Some(SourceId::JELLYFIN),
kind: Some(ItemKind::Album),
id: "alb-1".into(),
..Default::default()
})
.unwrap()
.unwrap();
assert_eq!(bare.id(), "alb-1");
// A prefix with nothing after it is a named error, not an empty lookup.
let err = s
.claim(&RawRef {
kind: Some(ItemKind::Album),
id: "jellyfin:".into(),
..Default::default()
})
.unwrap()
.unwrap_err();
assert!(matches!(err, SourceError::BadIdShape { by: SourceId::JELLYFIN, .. }));
}
/// ...and it must not answer for the NEIGHBOUR's prefix.
#[test]
fn it_does_not_recognise_the_other_prefix() {
assert!(!recognises(&RawRef {
kind: Some(ItemKind::Album),
id: "subsonic:al-abc".into(),
..Default::default()
}));
assert!(!recognises(&RawRef {
kind: Some(ItemKind::Album),
id: "plex:5677211365378243606".into(),
..Default::default()
}));
}
#[test]
fn an_empty_album_id_is_a_named_error_not_a_lookup() {
let s = connected();
+67 -2
View File
@@ -103,6 +103,12 @@ impl Default for SubsonicSource {
/// `SourceId::from_word` has already folded), or the namespace bit.
pub(crate) fn recognises(raw: &RawRef) -> bool {
raw.source == Some(SourceId::SUBSONIC)
// The PREFIXED album key the Local Library grid publishes. Without
// this arm an album card carrying no source word — which is every card
// that round-trips through a QML string property — would be claimed by
// nobody and the album page would open empty. Plex solves the same
// problem the same way, with its `plex:` keys.
|| raw.id.trim().starts_with("subsonic:")
|| raw
.numeric()
.map(|n| RemoteSource::of_id(n as i64) == Some(RemoteSource::Subsonic))
@@ -123,14 +129,20 @@ impl Source for SubsonicSource {
let kind = raw.kind.unwrap_or(ItemKind::Track);
Some(match kind {
ItemKind::Album => {
if id.is_empty() {
// The grid publishes `subsonic:<server album id>`; a producer
// that holds the raw id may pass it bare. STRIP the prefix —
// the cache and the server both speak the raw id, and carrying
// the prefixed form inward is how Plex ended up with two album
// keys only one of its queries understood (survey IC-2).
let bare = id.strip_prefix("subsonic:").unwrap_or(id).trim();
if bare.is_empty() {
Err(SourceError::BadIdShape {
by: SourceId::SUBSONIC,
id: id.to_string(),
why: "a subsonic album id is the server's own id, never empty",
})
} else {
Ok(MediaRef::new(SourceId::SUBSONIC, ItemKind::Album, id))
Ok(MediaRef::new(SourceId::SUBSONIC, ItemKind::Album, bare))
}
}
// Same two shapes as Jellyfin, same reason for preferring the hint:
@@ -355,6 +367,59 @@ mod tests {
}
}
/// The grid's album key is PREFIXED, and it must round-trip: recognised
/// with no source word at all, and stripped back to the raw server id the
/// cache and the server both speak.
#[test]
fn a_prefixed_album_key_is_recognised_and_stripped() {
let s = connected();
// No source word — the shape a QML string property hands back.
let raw = RawRef {
kind: Some(ItemKind::Album),
id: "subsonic:al-abc".into(),
..Default::default()
};
assert!(recognises(&raw), "an unlabelled prefixed key was not recognised");
let m = s.claim(&raw).unwrap().unwrap();
assert_eq!(m.id(), "al-abc", "the prefix was carried inward");
// A bare id with the source word still works.
let bare = s
.claim(&RawRef {
source: Some(SourceId::SUBSONIC),
kind: Some(ItemKind::Album),
id: "al-abc".into(),
..Default::default()
})
.unwrap()
.unwrap();
assert_eq!(bare.id(), "al-abc");
// A prefix with nothing after it is a named error, not an empty lookup.
let err = s
.claim(&RawRef {
kind: Some(ItemKind::Album),
id: "subsonic:".into(),
..Default::default()
})
.unwrap()
.unwrap_err();
assert!(matches!(err, SourceError::BadIdShape { by: SourceId::SUBSONIC, .. }));
}
/// ...and it must not answer for the NEIGHBOUR's prefix.
#[test]
fn it_does_not_recognise_the_other_prefix() {
assert!(!recognises(&RawRef {
kind: Some(ItemKind::Album),
id: "jellyfin:alb-1".into(),
..Default::default()
}));
assert!(!recognises(&RawRef {
kind: Some(ItemKind::Album),
id: "plex:5677211365378243606".into(),
..Default::default()
}));
}
#[test]
fn a_track_normalises_to_the_server_id_from_the_hint() {
let s = connected();