fix(subsonic): albums, folders and search list only what the listener can play

getAlbum, getMusicDirectory and search2/3 ignored the listener's quarantine
and listed missing files, which an app then failed to stream; song counts
counted both. They now pass the listener and leave out missing files, as
the mixes already did. Subsonic can't mark a song unplayable, so leaving it
out is how the native apps' greyed-out row comes across.

Song search filters in SQL (SearchPlayableTracks), so a library sync paging
through search3 never gets a short page that reads as the end. Album song
counts come from one query for the whole page (CountPlayableTracksByAlbums)
instead of one per album.

tracks.sql also drops CountTracksByArtist, which nothing called; see the
next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 22:02:00 -05:00
co-authored by Claude Opus 5.5
parent d0675e1817
commit 1ff4bc8258
5 changed files with 296 additions and 37 deletions
+122 -14
View File
@@ -120,6 +120,50 @@ func (q *Queries) CountPlayableTracks(ctx context.Context) (int64, error) {
return count, err return count, err
} }
const countPlayableTracksByAlbums = `-- name: CountPlayableTracksByAlbums :many
SELECT album_id, count(*)::int AS track_count
FROM tracks
WHERE album_id = ANY($1::uuid[])
AND missing_since IS NULL
AND NOT EXISTS (
SELECT 1 FROM quarantine q
WHERE q.user_id = $2 AND q.track_id = tracks.id
)
GROUP BY album_id
`
type CountPlayableTracksByAlbumsParams struct {
AlbumIds []pgtype.UUID
UserID pgtype.UUID
}
type CountPlayableTracksByAlbumsRow struct {
AlbumID pgtype.UUID
TrackCount int32
}
// How many of each album's tracks the listener $2 can play: present on
// disk and not quarantined by them. An album with none is absent.
func (q *Queries) CountPlayableTracksByAlbums(ctx context.Context, arg CountPlayableTracksByAlbumsParams) ([]CountPlayableTracksByAlbumsRow, error) {
rows, err := q.db.Query(ctx, countPlayableTracksByAlbums, arg.AlbumIds, arg.UserID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []CountPlayableTracksByAlbumsRow
for rows.Next() {
var i CountPlayableTracksByAlbumsRow
if err := rows.Scan(&i.AlbumID, &i.TrackCount); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const countSuspectSourceTracks = `-- name: CountSuspectSourceTracks :one const countSuspectSourceTracks = `-- name: CountSuspectSourceTracks :one
SELECT COUNT(*) FROM tracks t SELECT COUNT(*) FROM tracks t
WHERE t.missing_since IS NULL WHERE t.missing_since IS NULL
@@ -145,20 +189,6 @@ func (q *Queries) CountTracksByAlbum(ctx context.Context, albumID pgtype.UUID) (
return count, err return count, err
} }
const countTracksByArtist = `-- name: CountTracksByArtist :one
SELECT COUNT(*) FROM tracks WHERE artist_id = $1
`
// Used by request-progress reporting to count tracks ingested under a
// matched artist (sum across all the artist's albums) while a request
// is still in flight.
func (q *Queries) CountTracksByArtist(ctx context.Context, artistID pgtype.UUID) (int64, error) {
row := q.db.QueryRow(ctx, countTracksByArtist, artistID)
var count int64
err := row.Scan(&count)
return count, err
}
const countTracksMatching = `-- name: CountTracksMatching :one const countTracksMatching = `-- name: CountTracksMatching :one
SELECT COUNT(*) FROM tracks SELECT COUNT(*) FROM tracks
WHERE title ILIKE '%' || $1::text || '%' WHERE title ILIKE '%' || $1::text || '%'
@@ -1261,6 +1291,84 @@ func (q *Queries) MarkTracksRemoved(ctx context.Context, arg MarkTracksRemovedPa
return result.RowsAffected(), nil return result.RowsAffected(), nil
} }
const searchPlayableTracks = `-- name: SearchPlayableTracks :many
SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks
WHERE title ILIKE '%' || $1::text || '%'
AND missing_since IS NULL
AND NOT EXISTS (
SELECT 1 FROM quarantine q
WHERE q.user_id = $2 AND q.track_id = tracks.id
)
ORDER BY title, id
LIMIT $4 OFFSET $3
`
type SearchPlayableTracksParams struct {
Query string
UserID pgtype.UUID
RowOffset int32
RowLimit int32
}
// Subsonic's song search: tracks whose title matches $1 that the listener
// $2 can play, so neither a missing file nor one they quarantined. Subsonic
// has no way to mark a song unplayable, and apps page through the whole
// library with this, so the filter is here rather than after the LIMIT:
// a short page reads to an app as the end of the results.
func (q *Queries) SearchPlayableTracks(ctx context.Context, arg SearchPlayableTracksParams) ([]Track, error) {
rows, err := q.db.Query(ctx, searchPlayableTracks,
arg.Query,
arg.UserID,
arg.RowOffset,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Track
for rows.Next() {
var i Track
if err := rows.Scan(
&i.ID,
&i.Title,
&i.AlbumID,
&i.ArtistID,
&i.TrackNumber,
&i.DiscNumber,
&i.DurationMs,
&i.FilePath,
&i.FileSize,
&i.FileFormat,
&i.Bitrate,
&i.Mbid,
&i.Genre,
&i.AddedAt,
&i.UpdatedAt,
&i.TagSource,
&i.TagSourcesVersion,
&i.TagReadVersion,
&i.MissingSince,
&i.MbidSource,
&i.SongID,
&i.SongKey,
&i.SourceVerdict,
&i.SourceVerdictAt,
&i.EmptiedAt,
&i.RemovedReason,
&i.RemovedBy,
&i.ArtistCredit,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const searchTracks = `-- name: SearchTracks :many const searchTracks = `-- name: SearchTracks :many
SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks
WHERE title ILIKE '%' || $1::text || '%' WHERE title ILIKE '%' || $1::text || '%'
+29 -6
View File
@@ -83,6 +83,35 @@ WHERE title ILIKE '%' || $1::text || '%'
ORDER BY title, id ORDER BY title, id
LIMIT $3 OFFSET $4; LIMIT $3 OFFSET $4;
-- name: SearchPlayableTracks :many
-- Subsonic's song search: tracks whose title matches $1 that the listener
-- $2 can play, so neither a missing file nor one they quarantined. Subsonic
-- has no way to mark a song unplayable, and apps page through the whole
-- library with this, so the filter is here rather than after the LIMIT:
-- a short page reads to an app as the end of the results.
SELECT * FROM tracks
WHERE title ILIKE '%' || sqlc.arg(query)::text || '%'
AND missing_since IS NULL
AND NOT EXISTS (
SELECT 1 FROM quarantine q
WHERE q.user_id = sqlc.arg(user_id) AND q.track_id = tracks.id
)
ORDER BY title, id
LIMIT sqlc.arg(row_limit) OFFSET sqlc.arg(row_offset);
-- name: CountPlayableTracksByAlbums :many
-- How many of each album's tracks the listener $2 can play: present on
-- disk and not quarantined by them. An album with none is absent.
SELECT album_id, count(*)::int AS track_count
FROM tracks
WHERE album_id = ANY(sqlc.arg(album_ids)::uuid[])
AND missing_since IS NULL
AND NOT EXISTS (
SELECT 1 FROM quarantine q
WHERE q.user_id = sqlc.arg(user_id) AND q.track_id = tracks.id
)
GROUP BY album_id;
-- name: CountTracksMatching :one -- name: CountTracksMatching :one
-- $1 = title query, $2 = user_id (NULL to skip quarantine filter). -- $1 = title query, $2 = user_id (NULL to skip quarantine filter).
SELECT COUNT(*) FROM tracks SELECT COUNT(*) FROM tracks
@@ -129,12 +158,6 @@ WHERE NOT EXISTS (
ORDER BY random() ORDER BY random()
LIMIT $2; LIMIT $2;
-- name: CountTracksByArtist :one
-- Used by request-progress reporting to count tracks ingested under a
-- matched artist (sum across all the artist's albums) while a request
-- is still in flight.
SELECT COUNT(*) FROM tracks WHERE artist_id = $1;
-- name: DeleteTrack :one -- name: DeleteTrack :one
-- Hard delete with FK cascade. The CASCADE on track_id from -- Hard delete with FK cascade. The CASCADE on track_id from
-- play_events / general_likes_tracks / quarantine / -- play_events / general_likes_tracks / quarantine /
+60 -12
View File
@@ -138,10 +138,14 @@ func (b *browseHandlers) getArtist(w http.ResponseWriter, r *http.Request) {
WriteFail(w, r, ErrGeneric, "Failed to load albums") WriteFail(w, r, ErrGeneric, "Failed to load albums")
return return
} }
counts, err := playableCounts(r.Context(), q, albums)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load albums")
return
}
refs := make([]AlbumRef, 0, len(albums)) refs := make([]AlbumRef, 0, len(albums))
for _, a := range albums { for _, a := range albums {
count, _ := q.CountTracksByAlbum(r.Context(), a.ID) refs = append(refs, albumRef(a, artist.Name, counts[a.ID], 0))
refs = append(refs, albumRef(a, artist.Name, int(count), 0))
} }
Write(w, r, ArtistResponse{ Write(w, r, ArtistResponse{
Envelope: NewEnvelope("ok"), Envelope: NewEnvelope("ok"),
@@ -194,12 +198,21 @@ func (b *browseHandlers) getAlbum(w http.ResponseWriter, r *http.Request) {
} }
// albumSongs is an album's songs in disc and track order, as getAlbum and // albumSongs is an album's songs in disc and track order, as getAlbum and
// getMusicDirectory both list them. // getMusicDirectory both list them: the ones the listener can play. A
// track they quarantined is hidden from them, as everywhere in Minstrel,
// and a missing file is left out, since Subsonic has no way to show a song
// as unplayable and an app would only fail to stream it.
func albumSongs(ctx context.Context, q *dbq.Queries, album dbq.Album, artistName string) ([]SongRef, error) { func albumSongs(ctx context.Context, q *dbq.Queries, album dbq.Album, artistName string) ([]SongRef, error) {
tracks, err := q.ListTracksByAlbum(ctx, dbq.ListTracksByAlbumParams{AlbumID: album.ID}) all, err := q.ListTracksByAlbum(ctx, dbq.ListTracksByAlbumParams{AlbumID: album.ID, UserID: listenerID(ctx)})
if err != nil { if err != nil {
return nil, err return nil, err
} }
tracks := all[:0]
for _, t := range all {
if !t.MissingSince.Valid {
tracks = append(tracks, t)
}
}
gains := replayGains(ctx, q, tracks) gains := replayGains(ctx, q, tracks)
// Each song is credited to its own artist: on a compilation or a track // Each song is credited to its own artist: on a compilation or a track
// with a guest, that is not the album's. A failed lookup credits the // with a guest, that is not the album's. A failed lookup credits the
@@ -465,9 +478,11 @@ func (b *browseHandlers) search(w http.ResponseWriter, r *http.Request, q *dbq.Q
} }
if songCount > 0 { if songCount > 0 {
tracks, err := q.SearchTracks(r.Context(), dbq.SearchTracksParams{ // Only songs the listener can play: see SearchPlayableTracks for why
Column1: query, Limit: int32(songCount), Offset: int32(songOffset), // the filter can't come after the page is cut.
}) // UserID left zero (NULL) — Subsonic has no per-user quarantine context tracks, err := q.SearchPlayableTracks(r.Context(), dbq.SearchPlayableTracksParams{
Query: query, UserID: listenerID(r.Context()), RowLimit: int32(songCount), RowOffset: int32(songOffset),
})
if err != nil { if err != nil {
WriteFail(w, r, ErrGeneric, "Song search failed") WriteFail(w, r, ErrGeneric, "Song search failed")
return searchHits{}, false return searchHits{}, false
@@ -513,9 +528,8 @@ func songParents(ctx context.Context, q *dbq.Queries, tracks []dbq.Track) (album
} }
// albumRefs converts a list of dbq.Album rows to AlbumRef, resolving artist // albumRefs converts a list of dbq.Album rows to AlbumRef, resolving artist
// name and track count per album. Uses resolveArtistNames for the artist side // names (one query per distinct artist) and each album's song count: the
// (one query per distinct artist) and CountTracksByAlbum per album. For small // songs the listener can play, so it matches what getAlbum lists.
// page sizes (≤ 500) this is well within budget.
func (b *browseHandlers) albumRefs(ctx context.Context, q *dbq.Queries, albums []dbq.Album) ([]AlbumRef, error) { func (b *browseHandlers) albumRefs(ctx context.Context, q *dbq.Queries, albums []dbq.Album) ([]AlbumRef, error) {
// Always return a non-nil slice — JSON clients expect [] on empty results, // Always return a non-nil slice — JSON clients expect [] on empty results,
// not null. Same rationale applies to search3 facet slices. // not null. Same rationale applies to search3 facet slices.
@@ -530,14 +544,48 @@ func (b *browseHandlers) albumRefs(ctx context.Context, q *dbq.Queries, albums [
if err != nil { if err != nil {
return nil, err return nil, err
} }
counts, err := playableCounts(ctx, q, albums)
if err != nil {
return nil, err
}
refs := make([]AlbumRef, 0, len(albums)) refs := make([]AlbumRef, 0, len(albums))
for _, a := range albums { for _, a := range albums {
count, _ := q.CountTracksByAlbum(ctx, a.ID) refs = append(refs, albumRef(a, names[uuidToID(a.ArtistID)], counts[a.ID], 0))
refs = append(refs, albumRef(a, names[uuidToID(a.ArtistID)], int(count), 0))
} }
return refs, nil return refs, nil
} }
// playableCounts is how many of each album's tracks the listener can play,
// by album id: present on disk and not quarantined by them. An album with
// none is absent, so it reads as 0.
func playableCounts(ctx context.Context, q *dbq.Queries, albums []dbq.Album) (map[pgtype.UUID]int, error) {
ids := make([]pgtype.UUID, 0, len(albums))
for _, a := range albums {
ids = append(ids, a.ID)
}
rows, err := q.CountPlayableTracksByAlbums(ctx, dbq.CountPlayableTracksByAlbumsParams{
AlbumIds: ids, UserID: listenerID(ctx),
})
if err != nil {
return nil, err
}
out := make(map[pgtype.UUID]int, len(rows))
for _, row := range rows {
out[row.AlbumID] = int(row.TrackCount)
}
return out, nil
}
// listenerID is the signed-in caller. Every method that lists songs runs
// behind the auth middleware, so it is set there; elsewhere it is the zero
// id, which matches no one's quarantine.
func listenerID(ctx context.Context) pgtype.UUID {
if u, ok := UserFromContext(ctx); ok {
return u.ID
}
return pgtype.UUID{}
}
func atoiDefault(s string, def int) int { func atoiDefault(s string, def int) int {
if s == "" { if s == "" {
return def return def
+80
View File
@@ -0,0 +1,80 @@
package subsonic
import (
"slices"
"testing"
)
// Subsonic apps are shown only the songs the listener can play, as the web
// and Android apps are: a track they quarantined is hidden from them, and a
// missing file is left out, since Subsonic can't mark a song unplayable and
// an app would only fail to stream it. Album song counts agree with the
// songs listed.
//
// In the picks fixture the listener quarantined Ember (Lantern Hours), and
// Jetty's file (Gone Tide's only song) is missing.
func TestSubsonic_ListsOnlyWhatTheListenerCanPlay(t *testing.T) {
f := seedPicks(t)
b := &browseHandlers{pool: f.pool}
lantern := uuidToID(f.albums["Lantern Hours"].ID)
gone := uuidToID(f.albums["Gone Tide"].ID)
var album AlbumResponse
if code := call(t, b.getAlbum, f.user, "id="+lantern, &album); code != 0 {
t.Fatalf("getAlbum: error %d", code)
}
if got := titles(album.Album.Songs); !slices.Equal(got, []string{"Dusk", "Flint"}) || album.Album.SongCount != 2 {
t.Errorf("getAlbum Lantern Hours: %v (songCount %d), want [Dusk Flint] and 2", got, album.Album.SongCount)
}
if code := call(t, b.getAlbum, f.user, "id="+gone, &album); code != 0 {
t.Fatalf("getAlbum Gone Tide: error %d", code)
}
if len(album.Album.Songs) != 0 || album.Album.SongCount != 0 {
t.Errorf("getAlbum Gone Tide: %v (songCount %d), want nothing", titles(album.Album.Songs), album.Album.SongCount)
}
var dir DirectoryResponse
if code := call(t, b.getMusicDirectory, f.user, "id="+lantern, &dir); code != 0 {
t.Fatalf("getMusicDirectory: error %d", code)
}
if got := titles(dir.Directory.Children); !slices.Equal(got, []string{"Dusk", "Flint"}) {
t.Errorf("getMusicDirectory Lantern Hours: %v, want [Dusk Flint]", got)
}
var search SearchResult3Response
if code := call(t, b.search3, f.user, "query=&songCount=50&albumCount=50&artistCount=0", &search); code != 0 {
t.Fatalf("search3: error %d", code)
}
if got := titles(search.SearchResult3.Songs); !slices.Equal(got, []string{"Dusk", "Flint", "Gale", "Harbour", "Inlet"}) {
t.Errorf("search3 songs: %v, want every song but Ember and Jetty", got)
}
// Paging through the library still reaches every playable song: the
// hidden ones don't leave a short page that reads as the end.
var page SearchResult3Response
if code := call(t, b.search3, f.user, "query=&songCount=2&songOffset=2&albumCount=0&artistCount=0", &page); code != 0 {
t.Fatalf("search3 page: error %d", code)
}
if got := titles(page.SearchResult3.Songs); !slices.Equal(got, []string{"Gale", "Harbour"}) {
t.Errorf("search3 second page: %v, want [Gale Harbour]", got)
}
counts := map[string]int{}
for _, a := range search.SearchResult3.Albums {
counts[a.Name] = a.SongCount
}
want := map[string]int{"Lantern Hours": 2, "Paper Boats": 3, "Gone Tide": 0}
for name, n := range want {
if counts[name] != n {
t.Errorf("search3 album %s songCount %d, want %d", name, counts[name], n)
}
}
var artist ArtistResponse
if code := call(t, b.getArtist, f.user, "id="+uuidToID(f.artist.ID), &artist); code != 0 {
t.Fatalf("getArtist: error %d", code)
}
for _, a := range artist.Artist.Albums {
if a.SongCount != want[a.Name] {
t.Errorf("getArtist album %s songCount %d, want %d", a.Name, a.SongCount, want[a.Name])
}
}
}
+5 -5
View File
@@ -213,16 +213,16 @@ func loadStarred(ctx context.Context, q *dbq.Queries, userID pgtype.UUID) ([]Son
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
counts, err := playableCounts(ctx, q, albumRows)
if err != nil {
return nil, nil, nil, err
}
for _, a := range albumRows { for _, a := range albumRows {
artist, err := q.GetArtistByID(ctx, a.ArtistID) artist, err := q.GetArtistByID(ctx, a.ArtistID)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
count, err := q.CountTracksByAlbum(ctx, a.ID) albums = append(albums, albumRef(a, artist.Name, counts[a.ID], 0))
if err != nil {
return nil, nil, nil, err
}
albums = append(albums, albumRef(a, artist.Name, int(count), 0))
} }
artistRows, err := q.ListLikedArtistRows(ctx, dbq.ListLikedArtistRowsParams{ artistRows, err := q.ListLikedArtistRows(ctx, dbq.ListLikedArtistRowsParams{