mirror of
https://github.com/Psychotoxical/psysonic.git
synced 2026-07-21 23:05:46 +00:00
feat(albums): combined browse filters, favorites reconcile, and session restore (#876)
* feat(albums): persist browse sort and genre filter for the session Keep Albums sort and genre selection in an in-memory Zustand store so navigating into album detail and back no longer resets browse context. Fixes #875 (partial). * feat(albums): restore browse filters only when returning from album detail Keep sort in the session store for the app lifetime. Stash genre, year, compilation, starred, and lossless filters when leaving Albums for an album page and restore them on POP (back). Clear the stash when opening Albums from elsewhere via sidebar navigation. * feat(albums): filter quick-clear chips; fix lossless A–Z sort Add inline × on active toolbar filters (genre, year, favorites, lossless, compilations) without opening the popover. Route lossless album browse through advanced search with album sort clauses on Albums and Lossless Albums; client-sort on the network fallback path. * fix(albums): apply year filter when only from or to is set Resolve open-ended year bounds with gte/lte on the local index and partial fromYear/toYear on Subsonic. Update the year filter chip label for single-bound ranges. * refactor(albums): combine browse filters in one query (genre + year + lossless) Replace mutually exclusive load/loadFiltered branches with fetchAlbumBrowsePage that ANDs server-side filters on the local index (genre OR union). Network fallback applies year bounds after genre fetch. Always show sort while a year filter is active. * fix(albums): load favorites filter server-side instead of scanning all albums Starred on Albums was client-only: each page was filtered locally and pendingClientFilterMatch kept paginating the full catalog. Query starred albums via the local index or getAlbumList(starred); apply overrides only for in-session star/unstar. * feat(library): local album/artist favorites via patch-on-use Mirror album- and artist-level stars into the library index (library_patch_album, library_patch_artist, migration 010). Albums and Artists favorites browse use entity starred_at only; normal album catalog stays track-derived so patch stubs do not hide the library. Keep album year on favorite cards via track COALESCE, patch metadata, and safer raw_json merge. * fix(library): reconcile album/artist stars from server, drop stubs Favorites browse uses getAlbumList/getStarred2 as source of truth. library_reconcile_*_stars clears local stars removed elsewhere; patch-on-use updates existing rows only (no stub INSERT). Reconcile on favorites load and after star/unstar in-app. * feat(albums): favorites reconcile, filter combos, and back-navigation fix Album browse keeps filter state when returning from album detail (POP stash read on mount, request-generation guard against stale loads). Favorites use getStarred2 as source of truth: reconcile album.starred_at in the local index (UPDATE only, no stub rows), with a small session cache for instant paint. Combine favorites with lossless or genre via restrictAlbumIds in advanced search. Remove album/artist patch-on-use and migration 010; artist favorites stay network-only. Track patch-on-use unchanged. * feat(albums): catalog year bounds and genre list narrowed by filters Year filter spinners use min/max years from the local track index (not 1900); "from" starts at oldest, "to" at newest, values clamp to catalog. When year, lossless, favorites, or compilation filters are active, the genre picker lists only genres present on matching albums (other filters applied, genre excluded). Adds library_get_catalog_year_bounds for the year UI. * feat(albums): debounce year filter and show genre album counts Debounce year range changes by 350ms before reloading browse. Genre picker lists album counts per genre (from getGenres or from albums matching other active filters) and sorts genres by count descending. * fix(albums): compilation filter detection and scan cap Recognize OpenSubsonic compilation flags (compilation, releaseTypes) so client-side comp filters work on local index rows. Cap background pagination at 500 albums when no matches are visible and show empty state instead of spinning through the whole catalog. * feat(albums): filter compilations via local library index Add `compilation` to advanced search (album entity): reads OpenSubsonic flags from album raw_json. Album browse passes compFilter into library_advanced_search when the index is ready; network-only path keeps client-side filtering with the existing scan cap. * fix(albums): apply compilation filter on track-grouped index browse Album browse uses track aggregation, so compilation clauses were skipped. Filter track raw_json (same SQL as album), merge album flags at sync, and always run the client-side compilation pass as a fallback. * refactor(albums): split browse modules and extract browse_support commands Move album browse fetch/filter logic into focused modules and useAlbumBrowseData; register reconcile/year-bounds Tauri commands from browse_support. Trim dead helpers and barrel exports; fix typecheck in compilation tests. * chore: note PR #876 in CHANGELOG and settings credits * fix(albums): show catalog min/max in partial year filter chip label When only from or to year is set, the active chip now reads e.g. 1990–2020 instead of 1990– or –2025, using indexed catalog bounds when available.
This commit is contained in:
@@ -11,6 +11,7 @@
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
use rusqlite::types::Value as SqlValue;
|
||||
use rusqlite::{params, OptionalExtension};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::dto::{
|
||||
@@ -33,8 +34,10 @@ fn bpm_resolved_sql() -> String {
|
||||
}
|
||||
|
||||
const ALBUM_COLUMNS: &str = "a.server_id, a.id, a.name, a.artist, a.artist_id, \
|
||||
a.song_count, a.duration_sec, a.year, a.genre, a.cover_art_id, a.starred_at, \
|
||||
a.synced_at, a.raw_json";
|
||||
a.song_count, a.duration_sec, \
|
||||
COALESCE(a.year, (SELECT MAX(t.year) FROM track t \
|
||||
WHERE t.server_id = a.server_id AND t.album_id = a.id AND t.deleted = 0)), \
|
||||
a.genre, a.cover_art_id, a.starred_at, a.synced_at, a.raw_json";
|
||||
|
||||
const ARTIST_COLUMNS: &str = "ar.server_id, ar.id, ar.name, ar.album_count, \
|
||||
ar.synced_at, ar.raw_json";
|
||||
@@ -285,6 +288,23 @@ fn map_track_row_resolved_bpm(row: &rusqlite::Row<'_>) -> rusqlite::Result<Libra
|
||||
crate::search::row_to_track_dto_resolved_bpm(row)
|
||||
}
|
||||
|
||||
/// Sync is track-first; the `album` table is often empty or holds only
|
||||
/// patch-on-use stubs. Normal browse must not treat a handful of album rows
|
||||
/// as the full catalog.
|
||||
fn server_has_indexed_tracks(store: &LibraryStore, server_id: &str) -> Result<bool, String> {
|
||||
store
|
||||
.with_read_conn(|conn| {
|
||||
conn.query_row(
|
||||
"SELECT 1 FROM track WHERE server_id = ?1 AND deleted = 0 LIMIT 1",
|
||||
params![server_id],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.optional()
|
||||
.map(|r| r.is_some())
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_album(
|
||||
store: &LibraryStore,
|
||||
@@ -301,6 +321,19 @@ fn build_album(
|
||||
store, req, text, scalar, limit, offset, skip_totals, applied, true,
|
||||
);
|
||||
}
|
||||
// Album browse favorites: album-level stars only (`a.starred_at`), not
|
||||
// track-derived groups with `t.starred_at`.
|
||||
if req.starred_only == Some(true) {
|
||||
return build_album_from_table(store, req, text, scalar, limit, offset, skip_totals, applied);
|
||||
}
|
||||
if server_has_indexed_tracks(store, &req.server_id)? {
|
||||
if let Some(q) = text.and_then(fts_album_prefix_match_query) {
|
||||
return build_album_from_fts(store, req, &q, scalar, limit, offset, skip_totals, applied);
|
||||
}
|
||||
return build_album_from_tracks(
|
||||
store, req, text, scalar, limit, offset, skip_totals, applied, false,
|
||||
);
|
||||
}
|
||||
if !scalar_requires_track_derived_entities(scalar) {
|
||||
let table = build_album_from_table(store, req, text, scalar, limit, offset, skip_totals, applied)?;
|
||||
if !table.0.is_empty() || table.1 > 0 {
|
||||
@@ -344,6 +377,12 @@ fn build_album_from_table(
|
||||
w.push_raw("a.starred_at IS NOT NULL");
|
||||
applied.insert("starred".to_string());
|
||||
}
|
||||
push_album_id_allowlist(
|
||||
&mut w,
|
||||
"a.id",
|
||||
req.restrict_album_ids.as_deref(),
|
||||
applied,
|
||||
);
|
||||
|
||||
let order = order_clause(&req.sort, EntityKind::Album)
|
||||
.unwrap_or_else(|| "ORDER BY a.name COLLATE NOCASE ASC, a.id ASC".to_string());
|
||||
@@ -379,8 +418,12 @@ fn build_album_from_tracks(
|
||||
w.push_param("t.server_id = ?", SqlValue::Text(req.server_id.clone()));
|
||||
w.push_raw("t.album_id IS NOT NULL AND t.album_id != ''");
|
||||
if !include_album_table_rows {
|
||||
// Skip track groups only when the album table has a full row (synced
|
||||
// metadata). Patch-on-use stubs omit `song_count` and must not hide the
|
||||
// track-derived catalog entry.
|
||||
w.push_raw(
|
||||
"NOT EXISTS (SELECT 1 FROM album a WHERE a.server_id = t.server_id AND a.id = t.album_id)",
|
||||
"NOT EXISTS (SELECT 1 FROM album a WHERE a.server_id = t.server_id \
|
||||
AND a.id = t.album_id AND a.song_count IS NOT NULL)",
|
||||
);
|
||||
}
|
||||
if let Some(scope) = trimmed_nonempty(req.library_scope.as_deref()) {
|
||||
@@ -401,6 +444,12 @@ fn build_album_from_tracks(
|
||||
w.push_raw("t.starred_at IS NOT NULL");
|
||||
applied.insert("starred".to_string());
|
||||
}
|
||||
push_album_id_allowlist(
|
||||
&mut w,
|
||||
"t.album_id",
|
||||
req.restrict_album_ids.as_deref(),
|
||||
applied,
|
||||
);
|
||||
|
||||
let select = "t.server_id, t.album_id, MAX(t.album), MAX(t.artist), MAX(t.artist_id), \
|
||||
COUNT(*), SUM(t.duration_sec), MAX(t.year), MAX(t.genre), MAX(t.cover_art_id), \
|
||||
@@ -462,15 +511,12 @@ fn build_artist_from_table(
|
||||
w.push_param("ar.name LIKE ? ESCAPE '\\'", SqlValue::Text(like_contains(t)));
|
||||
applied.insert("text".to_string());
|
||||
}
|
||||
// Only `text` routes to artist with a real column; other registered
|
||||
// fields resolve to `None` (skip). `starredOnly` has no artist column.
|
||||
for c in scalar {
|
||||
if let Some(frag) = resolve_clause(c, EntityKind::Artist)? {
|
||||
applied.insert(c.field.clone());
|
||||
w.push(frag);
|
||||
}
|
||||
}
|
||||
|
||||
let order = order_clause(&req.sort, EntityKind::Artist)
|
||||
.unwrap_or_else(|| "ORDER BY ar.name COLLATE NOCASE ASC, ar.id ASC".to_string());
|
||||
query_rows(
|
||||
@@ -584,6 +630,12 @@ fn build_album_from_fts(
|
||||
w.push_raw("t.starred_at IS NOT NULL");
|
||||
applied.insert("starred".to_string());
|
||||
}
|
||||
push_album_id_allowlist(
|
||||
&mut w,
|
||||
"t.album_id",
|
||||
req.restrict_album_ids.as_deref(),
|
||||
applied,
|
||||
);
|
||||
|
||||
let where_sql = w.where_sql();
|
||||
store.with_read_conn(|conn| {
|
||||
@@ -784,8 +836,7 @@ fn resolve_clause(
|
||||
("year", EntityKind::Album) => "a.year",
|
||||
("starred", EntityKind::Track) => "t.starred_at",
|
||||
("starred", EntityKind::Album) => "a.starred_at",
|
||||
// `starred` routes to artist in the registry, but the `artist`
|
||||
// table has no `starred_at` column — skip rather than error.
|
||||
// `artist` has no `starred_at` column — favorites use the network list.
|
||||
("starred", EntityKind::Artist) => return Ok(None),
|
||||
("mood_group" | "mood_tag", EntityKind::Track) => {
|
||||
return crate::advanced_search_mood::resolve_mood_clause(c);
|
||||
@@ -808,6 +859,13 @@ fn resolve_clause(
|
||||
params: vec![],
|
||||
}));
|
||||
}
|
||||
("compilation", EntityKind::Album) => {
|
||||
return compilation_filter_fragment(&c.field, c.op, c.value.as_ref(), "a");
|
||||
}
|
||||
("compilation", EntityKind::Track) => {
|
||||
return compilation_filter_fragment(&c.field, c.op, c.value.as_ref(), "t");
|
||||
}
|
||||
("compilation", _) => return Ok(None),
|
||||
// `text` is handled by the entity builder (FTS / LIKE), never here.
|
||||
("text", _) => return Ok(None),
|
||||
// Registered but no v1 SQL builder (user_rating / suffix / bit_rate).
|
||||
@@ -872,6 +930,30 @@ fn count_matching_rows(
|
||||
Ok(n.max(0) as u32)
|
||||
}
|
||||
|
||||
/// Restrict album browse to an explicit id set (server favorites ∩ local filters).
|
||||
fn push_album_id_allowlist(
|
||||
w: &mut WhereBuilder,
|
||||
column: &str,
|
||||
ids: Option<&[String]>,
|
||||
applied: &mut BTreeSet<String>,
|
||||
) {
|
||||
let Some(ids) = ids else {
|
||||
return;
|
||||
};
|
||||
applied.insert("albumIds".to_string());
|
||||
if ids.is_empty() {
|
||||
w.push_raw("1 = 0");
|
||||
return;
|
||||
}
|
||||
let placeholders = std::iter::repeat_n("?", ids.len()).collect::<Vec<_>>().join(", ");
|
||||
let sql = format!("{column} IN ({placeholders})");
|
||||
let params = ids
|
||||
.iter()
|
||||
.map(|id| SqlValue::Text(id.clone()))
|
||||
.collect();
|
||||
w.push_params(&sql, params);
|
||||
}
|
||||
|
||||
/// Accumulates `AND`-joined WHERE clauses and their positional params in
|
||||
/// lockstep so anonymous `?` placeholders bind left-to-right.
|
||||
struct WhereBuilder {
|
||||
@@ -1160,6 +1242,48 @@ fn sort_column(field: &str, entity: EntityKind) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
fn compilation_filter_fragment(
|
||||
field: &str,
|
||||
op: FilterOp,
|
||||
value: Option<&Value>,
|
||||
table_alias: &str,
|
||||
) -> Result<Option<SqlFragment>, String> {
|
||||
let comp_sql = crate::album_compilation_filter::compilation_raw_json_sql(table_alias);
|
||||
match op {
|
||||
FilterOp::IsTrue => Ok(Some(SqlFragment {
|
||||
sql: comp_sql,
|
||||
params: vec![],
|
||||
})),
|
||||
FilterOp::Eq => {
|
||||
let want_comp = json_to_bool(field, value)?;
|
||||
let sql = if want_comp {
|
||||
comp_sql
|
||||
} else {
|
||||
format!("NOT ({comp_sql})")
|
||||
};
|
||||
Ok(Some(SqlFragment { sql, params: vec![] }))
|
||||
}
|
||||
_ => Err(filter::FilterError::UnsupportedOp {
|
||||
field: field.to_string(),
|
||||
op: op.as_str(),
|
||||
}
|
||||
.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn json_to_bool(field: &str, v: Option<&Value>) -> Result<bool, String> {
|
||||
match v {
|
||||
Some(Value::Bool(b)) => Ok(*b),
|
||||
Some(Value::Number(n)) => Ok(n.as_i64() == Some(1)),
|
||||
Some(Value::String(s)) => Ok(matches!(s.as_str(), "1" | "true" | "TRUE")),
|
||||
_ => Err(filter::FilterError::BadValue {
|
||||
field: field.to_string(),
|
||||
detail: "expected boolean".to_string(),
|
||||
}
|
||||
.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn json_to_text(field: &str, v: Option<&Value>) -> Result<SqlValue, String> {
|
||||
match v {
|
||||
Some(Value::String(s)) => Ok(SqlValue::Text(s.clone())),
|
||||
@@ -1273,6 +1397,7 @@ mod tests {
|
||||
entity_types: entities.to_vec(),
|
||||
filters: Vec::new(),
|
||||
starred_only: None,
|
||||
restrict_album_ids: None,
|
||||
sort: Vec::new(),
|
||||
limit: 50,
|
||||
offset: 0,
|
||||
@@ -1455,6 +1580,58 @@ mod tests {
|
||||
assert_eq!(resp.tracks[0].id, "t1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_album_browse_uses_track_catalog_when_album_table_is_sparse() {
|
||||
let store = LibraryStore::open_in_memory();
|
||||
insert_album(&store, "s1", "al_stub", "Starred Stub", None, None);
|
||||
store
|
||||
.with_conn("misc", |c| {
|
||||
c.execute(
|
||||
"UPDATE album SET starred_at = 100 WHERE server_id = 's1' AND id = 'al_stub'",
|
||||
[],
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let mut a = track("s1", "t1", "A", "X", "Album A");
|
||||
a.album_id = Some("al_a".into());
|
||||
let mut b = track("s1", "t2", "B", "Y", "Album B");
|
||||
b.album_id = Some("al_b".into());
|
||||
TrackRepository::new(&store)
|
||||
.upsert_batch(&[a, b])
|
||||
.unwrap();
|
||||
let r = req("s1", &[EntityKind::Album]);
|
||||
let resp = run_advanced_search(&store, &r).unwrap();
|
||||
let ids: Vec<&str> = resp.albums.iter().map(|a| a.id.as_str()).collect();
|
||||
assert!(ids.contains(&"al_a"));
|
||||
assert!(ids.contains(&"al_b"));
|
||||
assert!(!ids.contains(&"al_stub"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starred_only_album_entity_uses_album_star_not_track_star() {
|
||||
let store = LibraryStore::open_in_memory();
|
||||
insert_album(&store, "s1", "al_star", "Starred Album", None, None);
|
||||
store
|
||||
.with_conn("misc", |c| {
|
||||
c.execute(
|
||||
"UPDATE album SET starred_at = 100 WHERE server_id = 's1' AND id = 'al_star'",
|
||||
[],
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let mut track_star = track("s1", "t1", "T", "X", "TrackStar Alb");
|
||||
track_star.album_id = Some("al_track_only".into());
|
||||
track_star.starred_at = Some(200);
|
||||
TrackRepository::new(&store)
|
||||
.upsert_batch(&[track_star])
|
||||
.unwrap();
|
||||
let mut r = req("s1", &[EntityKind::Album]);
|
||||
r.starred_only = Some(true);
|
||||
let resp = run_advanced_search(&store, &r).unwrap();
|
||||
assert_eq!(resp.albums.len(), 1);
|
||||
assert_eq!(resp.albums[0].id, "al_star");
|
||||
}
|
||||
|
||||
// ── bpm dual storage ───────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
@@ -1683,6 +1860,36 @@ mod tests {
|
||||
assert_eq!(resp.albums[0].id, "al1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restrict_album_ids_intersects_with_lossless_filter() {
|
||||
let store = LibraryStore::open_in_memory();
|
||||
insert_album(&store, "s1", "al_fav_lossless", "Fav Lossless", None, None);
|
||||
insert_album(&store, "s1", "al_fav_lossy", "Fav Lossy", None, None);
|
||||
insert_album(&store, "s1", "al_other_lossless", "Other Lossless", None, None);
|
||||
let mut flac_fav = track("s1", "t1", "A", "X", "Alb");
|
||||
flac_fav.album_id = Some("al_fav_lossless".into());
|
||||
flac_fav.suffix = Some("flac".into());
|
||||
let mut mp3_fav = track("s1", "t2", "B", "Y", "Alb2");
|
||||
mp3_fav.album_id = Some("al_fav_lossy".into());
|
||||
mp3_fav.suffix = Some("mp3".into());
|
||||
let mut flac_other = track("s1", "t3", "C", "Z", "Alb3");
|
||||
flac_other.album_id = Some("al_other_lossless".into());
|
||||
flac_other.suffix = Some("flac".into());
|
||||
TrackRepository::new(&store)
|
||||
.upsert_batch(&[flac_fav, mp3_fav, flac_other])
|
||||
.unwrap();
|
||||
let mut r = req("s1", &[EntityKind::Album]);
|
||||
r.filters = vec![clause("lossless", FilterOp::IsTrue, None, None)];
|
||||
r.restrict_album_ids = Some(vec![
|
||||
"al_fav_lossless".into(),
|
||||
"al_fav_lossy".into(),
|
||||
]);
|
||||
let resp = run_advanced_search(&store, &r).unwrap();
|
||||
assert_eq!(resp.albums.len(), 1);
|
||||
assert_eq!(resp.albums[0].id, "al_fav_lossless");
|
||||
assert!(resp.applied_filters.contains(&"albumIds".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lossless_and_year_filters_use_track_year_when_album_table_differs() {
|
||||
let store = LibraryStore::open_in_memory();
|
||||
@@ -1743,6 +1950,80 @@ mod tests {
|
||||
assert_eq!(resp.artists[0].id, "ar1");
|
||||
}
|
||||
|
||||
fn insert_album_raw(
|
||||
store: &LibraryStore,
|
||||
server: &str,
|
||||
id: &str,
|
||||
name: &str,
|
||||
raw_json: &str,
|
||||
) {
|
||||
store
|
||||
.with_conn("misc", |c| {
|
||||
c.execute(
|
||||
"INSERT INTO album (server_id, id, name, synced_at, raw_json) \
|
||||
VALUES (?1, ?2, ?3, 1, ?4)",
|
||||
rusqlite::params![server, id, name, raw_json],
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compilation_filter_only_returns_compilation_albums() {
|
||||
let store = LibraryStore::open_in_memory();
|
||||
insert_album_raw(
|
||||
&store,
|
||||
"s1",
|
||||
"al_comp",
|
||||
"Greatest Hits",
|
||||
r#"{"compilation":true}"#,
|
||||
);
|
||||
insert_album_raw(&store, "s1", "al_regular", "Studio", "{}");
|
||||
let mut r = req("s1", &[EntityKind::Album]);
|
||||
r.filters = vec![clause("compilation", FilterOp::IsTrue, None, None)];
|
||||
let resp = run_advanced_search(&store, &r).unwrap();
|
||||
assert_eq!(resp.albums.len(), 1);
|
||||
assert_eq!(resp.albums[0].id, "al_comp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compilation_filter_on_track_grouped_album_browse() {
|
||||
let store = LibraryStore::open_in_memory();
|
||||
let mut comp = track("s1", "t_comp", "Hit", "VA", "Comp Album");
|
||||
comp.album_id = Some("al_comp".into());
|
||||
comp.raw_json = r#"{"compilation":true}"#.into();
|
||||
let mut reg = track("s1", "t_reg", "Song", "Band", "Studio");
|
||||
reg.album_id = Some("al_reg".into());
|
||||
reg.raw_json = "{}".into();
|
||||
TrackRepository::new(&store)
|
||||
.upsert_batch(&[comp, reg])
|
||||
.unwrap();
|
||||
let mut r = req("s1", &[EntityKind::Album]);
|
||||
r.filters = vec![clause("compilation", FilterOp::IsTrue, None, None)];
|
||||
let resp = run_advanced_search(&store, &r).unwrap();
|
||||
assert_eq!(resp.albums.len(), 1);
|
||||
assert_eq!(resp.albums[0].id, "al_comp");
|
||||
assert!(resp.applied_filters.contains(&"compilation".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compilation_eq_false_hides_compilations() {
|
||||
let store = LibraryStore::open_in_memory();
|
||||
insert_album_raw(
|
||||
&store,
|
||||
"s1",
|
||||
"al_comp",
|
||||
"Greatest Hits",
|
||||
r#"{"releaseTypes":["Compilation"]}"#,
|
||||
);
|
||||
insert_album_raw(&store, "s1", "al_regular", "Studio", "{}");
|
||||
let mut r = req("s1", &[EntityKind::Album]);
|
||||
r.filters = vec![clause("compilation", FilterOp::Eq, Some(json!(false)), None)];
|
||||
let resp = run_advanced_search(&store, &r).unwrap();
|
||||
assert_eq!(resp.albums.len(), 1);
|
||||
assert_eq!(resp.albums[0].id, "al_regular");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planned_but_unbuilt_field_is_an_error() {
|
||||
let store = LibraryStore::open_in_memory();
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
//! OpenSubsonic compilation flag in entity `raw_json` (Navidrome: `compilation`,
|
||||
//! `isCompilation`, or `releaseTypes` containing `Compilation`).
|
||||
|
||||
/// SQL predicate on any row with a `raw_json` column (album or track).
|
||||
pub fn compilation_raw_json_sql(table_alias: &str) -> String {
|
||||
let a = table_alias;
|
||||
// `NULL IN (...)` is unknown in SQL — wrap each probe in EXISTS so non-comp rows stay false.
|
||||
format!(
|
||||
"(EXISTS ( \
|
||||
SELECT 1 WHERE json_extract({a}.raw_json, '$.compilation') IN (1, '1', 'true', 'TRUE') \
|
||||
) OR EXISTS ( \
|
||||
SELECT 1 WHERE json_extract({a}.raw_json, '$.isCompilation') IN (1, '1', 'true', 'TRUE') \
|
||||
) OR EXISTS ( \
|
||||
SELECT 1 FROM json_each(COALESCE(json_extract({a}.raw_json, '$.releaseTypes'), '[]')) AS rt \
|
||||
WHERE lower(rt.value) = 'compilation' \
|
||||
))"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sql_mentions_json_paths() {
|
||||
let sql = compilation_raw_json_sql("t");
|
||||
assert!(sql.contains("$.compilation"));
|
||||
assert!(sql.contains("$.releaseTypes"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
//! Album browse helpers: favorites reconcile and catalog year bounds.
|
||||
|
||||
use rusqlite::params;
|
||||
use tauri::State;
|
||||
|
||||
use crate::dto::CatalogYearBoundsDto;
|
||||
use crate::runtime::LibraryRuntime;
|
||||
use crate::store::LibraryStore;
|
||||
|
||||
#[derive(Debug, Clone, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StarredAlbumReconcileItem {
|
||||
pub id: String,
|
||||
pub starred_at: i64,
|
||||
}
|
||||
|
||||
/// Align `album.starred_at` with server favorites: UPDATE existing rows only
|
||||
/// (no INSERT / stub rows). Clears local stars absent from `starred_albums`.
|
||||
#[tauri::command]
|
||||
pub fn library_reconcile_album_stars(
|
||||
runtime: State<'_, LibraryRuntime>,
|
||||
server_id: String,
|
||||
starred_albums: Vec<StarredAlbumReconcileItem>,
|
||||
) -> Result<(), String> {
|
||||
reconcile_album_stars(&runtime, &server_id, &starred_albums)
|
||||
}
|
||||
|
||||
pub(crate) fn reconcile_album_stars(
|
||||
runtime: &LibraryRuntime,
|
||||
server_id: &str,
|
||||
starred: &[StarredAlbumReconcileItem],
|
||||
) -> Result<(), String> {
|
||||
runtime
|
||||
.store
|
||||
.with_conn("misc", |conn| {
|
||||
if starred.is_empty() {
|
||||
conn.execute(
|
||||
"UPDATE album SET starred_at = NULL \
|
||||
WHERE server_id = ?1 AND starred_at IS NOT NULL",
|
||||
params![server_id],
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
let placeholders = std::iter::repeat_n("?", starred.len())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let clear_sql = format!(
|
||||
"UPDATE album SET starred_at = NULL \
|
||||
WHERE server_id = ?1 AND starred_at IS NOT NULL \
|
||||
AND id NOT IN ({placeholders})"
|
||||
);
|
||||
let mut clear_params: Vec<rusqlite::types::Value> =
|
||||
vec![rusqlite::types::Value::Text(server_id.to_string())];
|
||||
for item in starred {
|
||||
clear_params.push(rusqlite::types::Value::Text(item.id.clone()));
|
||||
}
|
||||
conn.execute(
|
||||
&clear_sql,
|
||||
rusqlite::params_from_iter(clear_params.iter()),
|
||||
)?;
|
||||
for item in starred {
|
||||
conn.execute(
|
||||
"UPDATE album SET starred_at = ?3 \
|
||||
WHERE server_id = ?1 AND id = ?2",
|
||||
params![server_id, item.id, item.starred_at],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn catalog_year_bounds_for_server(
|
||||
store: &LibraryStore,
|
||||
server_id: &str,
|
||||
) -> Result<CatalogYearBoundsDto, String> {
|
||||
store
|
||||
.with_read_conn(|conn| {
|
||||
let min_year: Option<i64> = conn.query_row(
|
||||
"SELECT MIN(year) FROM track \
|
||||
WHERE server_id = ?1 AND deleted = 0 AND year IS NOT NULL AND year > 0",
|
||||
params![server_id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let max_year: Option<i64> = conn.query_row(
|
||||
"SELECT MAX(year) FROM track \
|
||||
WHERE server_id = ?1 AND deleted = 0 AND year IS NOT NULL AND year > 0",
|
||||
params![server_id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let min_year = min_year.map(|y| y as i32);
|
||||
let max_year = max_year.map(|y| y as i32);
|
||||
Ok(CatalogYearBoundsDto { min_year, max_year })
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Min/max album years from the local track catalog (for Albums browse filter spinners).
|
||||
#[tauri::command]
|
||||
pub fn library_get_catalog_year_bounds(
|
||||
runtime: State<'_, LibraryRuntime>,
|
||||
server_id: String,
|
||||
) -> Result<CatalogYearBoundsDto, String> {
|
||||
catalog_year_bounds_for_server(&runtime.store, &server_id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::repos::TrackRepository;
|
||||
use crate::runtime::LibraryRuntime;
|
||||
use crate::store::LibraryStore;
|
||||
|
||||
use super::{catalog_year_bounds_for_server, reconcile_album_stars, StarredAlbumReconcileItem};
|
||||
|
||||
fn make_row(server: &str, id: &str, album_id: &str, track: i64) -> crate::repos::TrackRow {
|
||||
crate::repos::TrackRow {
|
||||
server_id: server.into(),
|
||||
id: id.into(),
|
||||
title: format!("T{id}"),
|
||||
title_sort: None,
|
||||
artist: Some("A".into()),
|
||||
artist_id: Some("ar".into()),
|
||||
album: album_id.into(),
|
||||
album_id: Some(album_id.into()),
|
||||
album_artist: None,
|
||||
duration_sec: 200,
|
||||
track_number: Some(track),
|
||||
disc_number: Some(1),
|
||||
year: None,
|
||||
genre: None,
|
||||
suffix: None,
|
||||
bit_rate: None,
|
||||
size_bytes: None,
|
||||
cover_art_id: None,
|
||||
starred_at: None,
|
||||
user_rating: None,
|
||||
play_count: None,
|
||||
played_at: None,
|
||||
server_path: None,
|
||||
library_id: None,
|
||||
isrc: None,
|
||||
mbid_recording: None,
|
||||
bpm: None,
|
||||
replay_gain_track_db: None,
|
||||
replay_gain_album_db: None,
|
||||
content_hash: None,
|
||||
server_updated_at: None,
|
||||
server_created_at: None,
|
||||
deleted: false,
|
||||
synced_at: 1,
|
||||
raw_json: "{}".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn runtime(store: Arc<LibraryStore>) -> LibraryRuntime {
|
||||
LibraryRuntime::new(store)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_album_stars_clears_stale_and_sets_existing_rows() {
|
||||
let store = Arc::new(LibraryStore::open_in_memory());
|
||||
store
|
||||
.with_conn("misc", |c| {
|
||||
c.execute(
|
||||
"INSERT INTO album (server_id, id, name, starred_at, synced_at, raw_json) \
|
||||
VALUES ('s1', 'al_old', 'Old', 1, 1, '{}'), \
|
||||
('s1', 'al_keep', 'Keep', 1, 1, '{}'), \
|
||||
('s1', 'al_new', 'New', NULL, 1, '{}')",
|
||||
[],
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let rt = runtime(store.clone());
|
||||
reconcile_album_stars(
|
||||
&rt,
|
||||
"s1",
|
||||
&[StarredAlbumReconcileItem {
|
||||
id: "al_keep".into(),
|
||||
starred_at: 99,
|
||||
}],
|
||||
)
|
||||
.unwrap();
|
||||
let old: Option<i64> = store
|
||||
.with_conn("misc", |c| {
|
||||
c.query_row(
|
||||
"SELECT starred_at FROM album WHERE server_id = 's1' AND id = 'al_old'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let keep: Option<i64> = store
|
||||
.with_conn("misc", |c| {
|
||||
c.query_row(
|
||||
"SELECT starred_at FROM album WHERE server_id = 's1' AND id = 'al_keep'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let new: Option<i64> = store
|
||||
.with_conn("misc", |c| {
|
||||
c.query_row(
|
||||
"SELECT starred_at FROM album WHERE server_id = 's1' AND id = 'al_new'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
assert!(old.is_none());
|
||||
assert_eq!(keep, Some(99));
|
||||
assert!(new.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_year_bounds_from_indexed_tracks() {
|
||||
let store = Arc::new(LibraryStore::open_in_memory());
|
||||
let mut old = make_row("s1", "t1", "al1", 1);
|
||||
old.year = Some(1985);
|
||||
let mut recent = make_row("s1", "t2", "al2", 1);
|
||||
recent.year = Some(2018);
|
||||
TrackRepository::new(&store)
|
||||
.upsert_batch(&[old, recent])
|
||||
.unwrap();
|
||||
let bounds = catalog_year_bounds_for_server(&store, "s1").unwrap();
|
||||
assert_eq!(bounds.min_year, Some(1985));
|
||||
assert_eq!(bounds.max_year, Some(2018));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_album_stars_clears_all_when_server_list_empty() {
|
||||
let store = Arc::new(LibraryStore::open_in_memory());
|
||||
store
|
||||
.with_conn("misc", |c| {
|
||||
c.execute(
|
||||
"INSERT INTO album (server_id, id, name, starred_at, synced_at, raw_json) \
|
||||
VALUES ('s1', 'al1', 'A', 5, 1, '{}')",
|
||||
[],
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let rt = runtime(store.clone());
|
||||
reconcile_album_stars(&rt, "s1", &[]).unwrap();
|
||||
let starred_at: Option<i64> = store
|
||||
.with_conn("misc", |c| {
|
||||
c.query_row(
|
||||
"SELECT starred_at FROM album WHERE server_id = 's1' AND id = 'al1'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
assert!(starred_at.is_none());
|
||||
}
|
||||
}
|
||||
@@ -373,6 +373,14 @@ pub struct PlaySessionYearBoundsDto {
|
||||
pub max_year: Option<i32>,
|
||||
}
|
||||
|
||||
/// Min/max `year` from indexed tracks for a server (Albums year filter UI).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CatalogYearBoundsDto {
|
||||
pub min_year: Option<i32>,
|
||||
pub max_year: Option<i32>,
|
||||
}
|
||||
|
||||
/// `library_purge_server` outcome.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -478,6 +486,11 @@ pub struct LibraryAdvancedSearchRequest {
|
||||
pub filters: Vec<LibraryFilterClause>,
|
||||
#[serde(default)]
|
||||
pub starred_only: Option<bool>,
|
||||
/// When set, album browse is limited to these ids (e.g. server `getStarred2`
|
||||
/// intersected with local lossless / genre filters). Not combined with
|
||||
/// `starred_only` — use one or the other.
|
||||
#[serde(default)]
|
||||
pub restrict_album_ids: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub sort: Vec<LibrarySortClause>,
|
||||
pub limit: u32,
|
||||
|
||||
@@ -128,6 +128,12 @@ pub const FILTER_FIELD_REGISTRY: &[FilterField] = &[
|
||||
ops: &[FilterOp::IsTrue],
|
||||
status: FilterStatus::V1,
|
||||
},
|
||||
FilterField {
|
||||
id: "compilation",
|
||||
entities: &[EntityKind::Track, EntityKind::Album],
|
||||
ops: &[FilterOp::IsTrue, FilterOp::Eq],
|
||||
status: FilterStatus::V1,
|
||||
},
|
||||
FilterField {
|
||||
id: "bit_rate",
|
||||
entities: &[EntityKind::Track],
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
|
||||
pub(crate) mod bulk_ingest;
|
||||
pub mod advanced_search;
|
||||
pub mod album_compilation_filter;
|
||||
pub mod browse_support;
|
||||
mod advanced_search_mood;
|
||||
pub mod analysis_backfill;
|
||||
pub mod artist_lossless_browse;
|
||||
|
||||
@@ -27,7 +27,9 @@ use serde_json::Value;
|
||||
use super::backoff::{jitter_salt, with_jitter, Backoff};
|
||||
use super::capability::{CapabilityFlags, NavidromeProbeCredentials};
|
||||
use super::error::SyncError;
|
||||
use super::mapping::{navidrome_song_to_track_row, subsonic_song_to_track_row};
|
||||
use super::mapping::{
|
||||
merge_album_open_subsonic_track_raw, navidrome_song_to_track_row, subsonic_song_to_track_row,
|
||||
};
|
||||
use super::progress::{NoopProgress, Progress, ProgressEvent};
|
||||
use super::strategy::IngestStrategy;
|
||||
use super::tombstone::TombstoneReconciler;
|
||||
@@ -488,10 +490,11 @@ impl<'a> DeltaSyncRunner<'a> {
|
||||
.unwrap_or_default();
|
||||
let mut rows: Vec<TrackRow> = Vec::with_capacity(album.song.len());
|
||||
for (i, song) in album.song.iter().enumerate() {
|
||||
let raw = raw_songs
|
||||
let mut raw = raw_songs
|
||||
.get(i)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| serde_json::to_value(song).unwrap_or(Value::Null));
|
||||
merge_album_open_subsonic_track_raw(&raw_album, &mut raw);
|
||||
rows.push(subsonic_song_to_track_row(
|
||||
&self.server_id,
|
||||
song,
|
||||
|
||||
@@ -25,7 +25,9 @@ use super::ingest_parallel::{
|
||||
check_cancel_flag, fetch_albums_parallel, linear_prefetch_depth, retry_fetch,
|
||||
sleep_request_gap, wait_while_bulk_paused, LinearPrefetchQueue, ParallelAlbumFetchOpts,
|
||||
};
|
||||
use super::mapping::{navidrome_song_to_track_row, subsonic_song_to_track_row};
|
||||
use super::mapping::{
|
||||
merge_album_open_subsonic_track_raw, navidrome_song_to_track_row, subsonic_song_to_track_row,
|
||||
};
|
||||
use super::progress::{IngestBatchMetrics, NoopProgress, Progress, ProgressEvent};
|
||||
use super::strategy::IngestStrategy;
|
||||
use crate::bulk_ingest::{restore_track_secondary_indexes, suspend_track_secondary_indexes};
|
||||
@@ -1124,10 +1126,11 @@ impl<'a> InitialSyncRunner<'a> {
|
||||
.unwrap_or_default();
|
||||
let mut rows: Vec<TrackRow> = Vec::with_capacity(album.song.len());
|
||||
for (i, song) in album.song.iter().enumerate() {
|
||||
let raw = raw_songs
|
||||
let mut raw = raw_songs
|
||||
.get(i)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| serde_json::to_value(song).unwrap_or(Value::Null));
|
||||
merge_album_open_subsonic_track_raw(&raw_album, &mut raw);
|
||||
rows.push(subsonic_song_to_track_row(
|
||||
&self.server_id,
|
||||
song,
|
||||
|
||||
@@ -9,6 +9,24 @@ use psysonic_integration::subsonic::Song;
|
||||
/// Project a Subsonic `Song` plus its raw JSON sub-tree into a
|
||||
/// `TrackRow`. `raw_value` is what `track.raw_json` stores verbatim so
|
||||
/// OpenSubsonic extensions survive (spec §5.1 / ADR-7).
|
||||
/// Copy album-level OpenSubsonic fields onto each track `raw_json` during S2/getAlbum
|
||||
/// ingest so track-grouped album browse can filter compilations.
|
||||
pub fn merge_album_open_subsonic_track_raw(raw_album: &Value, raw_song: &mut Value) {
|
||||
let Some(obj) = raw_song.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
for key in ["compilation", "isCompilation", "releaseTypes"] {
|
||||
if obj.contains_key(key) {
|
||||
continue;
|
||||
}
|
||||
if let Some(v) = raw_album.get(key) {
|
||||
if !v.is_null() {
|
||||
obj.insert(key.to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subsonic_song_to_track_row(
|
||||
server_id: &str,
|
||||
song: &Song,
|
||||
@@ -220,6 +238,15 @@ mod tests {
|
||||
assert!(parse_iso_ms_str("9999-99-99").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_album_open_subsonic_track_raw_copies_album_flags() {
|
||||
let album = json!({ "compilation": true, "releaseTypes": ["Compilation"] });
|
||||
let mut song = json!({ "id": "tr_1", "title": "A" });
|
||||
merge_album_open_subsonic_track_raw(&album, &mut song);
|
||||
assert_eq!(song.get("compilation"), Some(&json!(true)));
|
||||
assert_eq!(song.get("releaseTypes"), Some(&json!(["Compilation"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subsonic_song_maps_hot_columns_and_keeps_raw_json() {
|
||||
let raw = json!({
|
||||
|
||||
Reference in New Issue
Block a user