Files
minstrel/internal/subsonic/browse.go
T
bvandeusenandClaude Opus 5.5 8731e9695a
release / web (push) Successful in 1m16s
release / go (push) Successful in 1m47s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 3m59s
release / android (push) Successful in 4m30s
release / Build signed APK (push) Successful in 4m56s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 15s
release / Verify release artifacts (tag releases only) (push) Skipped
feat(subsonic): browse by genre and by folder
Subsonic apps can now list genres and play one (getGenres,
getSongsByGenre), and apps that browse by folder, such as DSub, can open
an artist to its albums and an album to its songs (getMusicDirectory),
with the album lists and search they use in that mode (getAlbumList,
search2).

Genres are split and counted as the web's genre index counts them, now
with an album count beside the song count. A genre's songs leave out the
listener's quarantined ones and missing files. Folders are Minstrel's
artists and albums, under the same ids as the tag-based calls.

getAlbumList2 and search3 now share their selection with the folder
versions, so the two modes list and find the same things.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:40:21 -05:00

560 lines
18 KiB
Go

package subsonic
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// browseHandlers carries the shared pgxpool used by every browse endpoint.
// Handlers are methods so Mount can register them without package globals.
type browseHandlers struct {
pool *pgxpool.Pool
}
// Subsonic's "ignoredArticles" is advisory — it tells clients which leading
// words to strip when computing their own index buckets. The server is
// responsible for storing sort_name in the desired form; this attr exists
// for backwards compatibility with clients that regroup client-side.
const ignoredArticles = "The El La Los Las Le Les"
// getMusicFolders always returns a single folder: Minstrel serves one library,
// and clients use the folder id as an opaque cookie, so it is 1.
func (b *browseHandlers) getMusicFolders(w http.ResponseWriter, r *http.Request) {
Write(w, r, MusicFoldersResponse{
Envelope: NewEnvelope("ok"),
MusicFolders: MusicFoldersContainer{
MusicFolders: []MusicFolder{{ID: 1, Name: "Music"}},
},
})
}
// getIndexes is the legacy namespace — identical shape to getArtists but with
// a lastModified attr. We report the max(updated_at) across artists so clients
// can short-circuit re-sync when nothing has changed.
func (b *browseHandlers) getIndexes(w http.ResponseWriter, r *http.Request) {
q := dbq.New(b.pool)
indexes, lastMod, err := b.buildArtistIndexes(r.Context(), q)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load artists")
return
}
Write(w, r, IndexesResponse{
Envelope: NewEnvelope("ok"),
Indexes: IndexesContainer{
LastModified: lastMod,
IgnoredArticles: ignoredArticles,
Indexes: indexes,
},
})
}
// getArtists is the ID3 equivalent of getIndexes. Same bucketing, no
// lastModified. Most modern clients prefer this endpoint.
func (b *browseHandlers) getArtists(w http.ResponseWriter, r *http.Request) {
q := dbq.New(b.pool)
indexes, _, err := b.buildArtistIndexes(r.Context(), q)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load artists")
return
}
Write(w, r, ArtistsResponse{
Envelope: NewEnvelope("ok"),
Artists: ArtistsContainer{
IgnoredArticles: ignoredArticles,
Indexes: indexes,
},
})
}
// buildArtistIndexes fetches every artist, buckets them by first letter, and
// returns indexes + the unix-ms timestamp of the most recently updated artist.
func (b *browseHandlers) buildArtistIndexes(ctx context.Context, q *dbq.Queries) ([]Index, int64, error) {
artists, err := q.ListArtists(ctx)
if err != nil {
return nil, 0, err
}
buckets := make(map[string][]ArtistRef)
var order []string
var lastMod int64
for _, a := range artists {
if a.UpdatedAt.Valid {
ms := a.UpdatedAt.Time.UnixMilli()
if ms > lastMod {
lastMod = ms
}
}
albums, err := q.ListAlbumsByArtist(ctx, a.ID)
if err != nil {
return nil, 0, err
}
ref := artistRef(a, len(albums))
letter := indexLetter(a.SortName)
if _, seen := buckets[letter]; !seen {
order = append(order, letter)
}
buckets[letter] = append(buckets[letter], ref)
}
indexes := make([]Index, 0, len(order))
for _, letter := range order {
indexes = append(indexes, Index{Name: letter, Artists: buckets[letter]})
}
return indexes, lastMod, nil
}
// getArtist returns one artist with its nested albums. id is a UUID string.
func (b *browseHandlers) getArtist(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
if idStr == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
return
}
id, ok := parseUUID(idStr)
if !ok {
WriteFail(w, r, ErrDataNotFound, "Artist not found")
return
}
q := dbq.New(b.pool)
artist, err := q.GetArtistByID(r.Context(), id)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
WriteFail(w, r, ErrDataNotFound, "Artist not found")
return
}
WriteFail(w, r, ErrGeneric, "Failed to load artist")
return
}
albums, err := q.ListAlbumsByArtist(r.Context(), id)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load albums")
return
}
refs := make([]AlbumRef, 0, len(albums))
for _, a := range albums {
count, _ := q.CountTracksByAlbum(r.Context(), a.ID)
refs = append(refs, albumRef(a, artist.Name, int(count), 0))
}
Write(w, r, ArtistResponse{
Envelope: NewEnvelope("ok"),
Artist: ArtistDetail{
ID: uuidToID(artist.ID),
Name: artist.Name,
AlbumCount: len(albums),
Albums: refs,
},
})
}
// getAlbum returns one album with its full track list.
func (b *browseHandlers) getAlbum(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
if idStr == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
return
}
id, ok := parseUUID(idStr)
if !ok {
WriteFail(w, r, ErrDataNotFound, "Album not found")
return
}
q := dbq.New(b.pool)
album, err := q.GetAlbumByID(r.Context(), id)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
WriteFail(w, r, ErrDataNotFound, "Album not found")
return
}
WriteFail(w, r, ErrGeneric, "Failed to load album")
return
}
artist, err := q.GetArtistByID(r.Context(), album.ArtistID)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load album artist")
return
}
songs, err := albumSongs(r.Context(), q, album, artist.Name)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load tracks")
return
}
Write(w, r, AlbumResponse{
Envelope: NewEnvelope("ok"),
Album: albumDetail(album, artist.Name, songs),
})
}
// albumSongs is an album's songs in disc and track order, as getAlbum and
// getMusicDirectory both list them.
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})
if err != nil {
return nil, err
}
gains := replayGains(ctx, q, tracks)
// 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
// album's artist rather than failing the album.
names, _ := db.TrackArtistNames(ctx, q, album.ID)
songs := make([]SongRef, 0, len(tracks))
for _, t := range tracks {
songs = append(songs, songRef(t, album.Title, names.For(t.ArtistID, artistName), gains[t.ID]))
}
return songs, nil
}
// getSong returns a single track by id. Parent metadata (album/artist name)
// is included so clients can render the song outside an album context.
func (b *browseHandlers) getSong(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
if idStr == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
return
}
id, ok := parseUUID(idStr)
if !ok {
WriteFail(w, r, ErrDataNotFound, "Song not found")
return
}
q := dbq.New(b.pool)
track, err := q.GetTrackByID(r.Context(), id)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
WriteFail(w, r, ErrDataNotFound, "Song not found")
return
}
WriteFail(w, r, ErrGeneric, "Failed to load song")
return
}
album, err := q.GetAlbumByID(r.Context(), track.AlbumID)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load song album")
return
}
artist, err := q.GetArtistByID(r.Context(), track.ArtistID)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load song artist")
return
}
Write(w, r, SongResponse{
Envelope: NewEnvelope("ok"),
Song: songRef(track, album.Title, artist.Name, replayGains(r.Context(), q, []dbq.Track{track})[track.ID]),
})
}
// getAlbumList2 returns a paged album list filtered by type (listAlbums).
func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
q := dbq.New(b.pool)
albums, ok := b.listAlbums(w, r, q)
if !ok {
return
}
refs, err := b.albumRefs(r.Context(), q, albums)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to resolve albums")
return
}
Write(w, r, AlbumList2Response{
Envelope: NewEnvelope("ok"),
AlbumList2: AlbumList2Container{Albums: refs},
})
}
// listAlbums is the page of albums getAlbumList and getAlbumList2 ask for,
// or false once it has written the failure. Supported types match the
// Subsonic spec § getAlbumList2. "recent" and "frequent" read the caller's
// own play history: most recently played first, and most played first.
// "starred" and "highest" are both the caller's liked albums, newest like
// first: a like is the only rating Minstrel keeps.
func (b *browseHandlers) listAlbums(w http.ResponseWriter, r *http.Request, q *dbq.Queries) ([]dbq.Album, bool) {
params := r.URL.Query()
listType := params.Get("type")
if listType == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: type")
return nil, false
}
size := clampInt(atoiDefault(params.Get("size"), 10), 1, 500)
offset := atoiDefault(params.Get("offset"), 0)
if offset < 0 {
offset = 0
}
var albums []dbq.Album
var err error
switch listType {
case "newest":
albums, err = q.ListAlbumsNewest(r.Context(), dbq.ListAlbumsNewestParams{
Limit: int32(size), Offset: int32(offset),
})
case "alphabeticalByName":
albums, err = q.ListAlbumsAlphaByName(r.Context(), dbq.ListAlbumsAlphaByNameParams{
Limit: int32(size), Offset: int32(offset),
})
case "alphabeticalByArtist":
rows, rerr := q.ListAlbumsAlphaByArtist(r.Context(), dbq.ListAlbumsAlphaByArtistParams{
Limit: int32(size), Offset: int32(offset),
})
if rerr != nil {
err = rerr
break
}
albums = make([]dbq.Album, len(rows))
for i, row := range rows {
albums[i] = row.Album
}
case "random":
albums, err = q.ListAlbumsRandom(r.Context(), int32(size))
case "byGenre":
genre := params.Get("genre")
if genre == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: genre")
return nil, false
}
// The query splits tracks.genre on [;,] rather than comparing the
// whole column, so a client asking for "Rock" also reaches tracks
// tagged "Rock;Pop".
albums, err = q.ListAlbumsByGenre(r.Context(), dbq.ListAlbumsByGenreParams{
Genre: genre, Lim: int32(size), Off: int32(offset),
})
case "byYear":
from, ferr := strconv.Atoi(params.Get("fromYear"))
to, terr := strconv.Atoi(params.Get("toYear"))
if ferr != nil || terr != nil {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: fromYear and toYear")
return nil, false
}
albums, err = q.ListAlbumsByYearOrdered(r.Context(), dbq.ListAlbumsByYearOrderedParams{
FromYear: int32(from), ToYear: int32(to), Lim: int32(size), Off: int32(offset),
})
case "starred", "highest":
user, ok := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
return nil, false
}
albums, err = q.ListLikedAlbumRows(r.Context(), dbq.ListLikedAlbumRowsParams{
UserID: user.ID, Limit: int32(size), Offset: int32(offset),
})
case "recent", "frequent":
user, ok := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
return nil, false
}
if listType == "recent" {
albums, err = q.ListAlbumsRecentlyPlayedByUser(r.Context(), dbq.ListAlbumsRecentlyPlayedByUserParams{
UserID: user.ID, Lim: int32(size), Off: int32(offset),
})
} else {
albums, err = q.ListAlbumsFrequentlyPlayedByUser(r.Context(), dbq.ListAlbumsFrequentlyPlayedByUserParams{
UserID: user.ID, Lim: int32(size), Off: int32(offset),
})
}
default:
WriteFail(w, r, ErrGeneric, "Invalid list type: "+listType)
return nil, false
}
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to list albums")
return nil, false
}
return albums, true
}
// search3 runs three independent searches — artist name, album title, song
// title — each bounded by its own count/offset (search).
func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
q := dbq.New(b.pool)
hits, ok := b.search(w, r, q)
if !ok {
return
}
albums, err := b.albumRefs(r.Context(), q, hits.albums)
if err != nil {
WriteFail(w, r, ErrGeneric, "Album search failed")
return
}
Write(w, r, SearchResult3Response{
Envelope: NewEnvelope("ok"),
SearchResult3: SearchResult3Container{
Artists: hits.artists,
Albums: albums,
Songs: hits.songs,
},
})
}
// searchHits is what one search found, before its albums are rendered as
// ID3 albums (search3) or as folders (search2).
type searchHits struct {
artists []ArtistRef
albums []dbq.Album
songs []SongRef
}
// search runs the three searches search2 and search3 share, or returns false
// once it has written the failure. The Subsonic spec lets the caller page
// each facet separately, which is why the params triplicate.
//
// An empty query matches everything, paged in a stable order. Apps that keep
// a copy of the library (Symfonium) download it this way, a page of songs at
// a time; refusing it leaves them a request per album or an empty library.
// Some send the empty query as two quote marks.
func (b *browseHandlers) search(w http.ResponseWriter, r *http.Request, q *dbq.Queries) (searchHits, bool) {
params := r.URL.Query()
if !params.Has("query") {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: query")
return searchHits{}, false
}
query := strings.TrimSpace(params.Get("query"))
if query == `""` {
query = ""
}
artistCount := clampInt(atoiDefault(params.Get("artistCount"), 20), 0, 500)
artistOffset := atoiDefault(params.Get("artistOffset"), 0)
albumCount := clampInt(atoiDefault(params.Get("albumCount"), 20), 0, 500)
albumOffset := atoiDefault(params.Get("albumOffset"), 0)
songCount := clampInt(atoiDefault(params.Get("songCount"), 20), 0, 500)
songOffset := atoiDefault(params.Get("songOffset"), 0)
// The query goes through ILIKE '%' || query || '%', so it matches
// substrings, and an empty query matches every row.
needle := &query
// JSON marshaling of nil slices produces `null`, which some clients reject.
// Initialize each facet to an empty slice so absent matches render as `[]`.
hits := searchHits{artists: []ArtistRef{}, songs: []SongRef{}}
if artistCount > 0 {
artists, err := q.SearchArtists(r.Context(), dbq.SearchArtistsParams{
Column1: needle, Limit: int32(artistCount), Offset: int32(artistOffset),
})
if err != nil {
WriteFail(w, r, ErrGeneric, "Artist search failed")
return searchHits{}, false
}
for _, a := range artists {
albums, aerr := q.ListAlbumsByArtist(r.Context(), a.ID)
if aerr != nil {
WriteFail(w, r, ErrGeneric, "Artist search failed")
return searchHits{}, false
}
hits.artists = append(hits.artists, artistRef(a, len(albums)))
}
}
if albumCount > 0 {
albums, err := q.SearchAlbums(r.Context(), dbq.SearchAlbumsParams{
Column1: needle, Limit: int32(albumCount), Offset: int32(albumOffset),
})
if err != nil {
WriteFail(w, r, ErrGeneric, "Album search failed")
return searchHits{}, false
}
hits.albums = albums
}
if songCount > 0 {
tracks, err := q.SearchTracks(r.Context(), dbq.SearchTracksParams{
Column1: query, Limit: int32(songCount), Offset: int32(songOffset),
}) // UserID left zero (NULL) — Subsonic has no per-user quarantine context
if err != nil {
WriteFail(w, r, ErrGeneric, "Song search failed")
return searchHits{}, false
}
// One query each for the page's albums and artists, not two per
// song: a library download asks for every song in pages of 500.
songs, serr := songRefs(r.Context(), q, tracks)
if serr != nil {
WriteFail(w, r, ErrGeneric, "Song search failed")
return searchHits{}, false
}
hits.songs = songs
}
return hits, true
}
// songParents reads the album titles and artist names of tracks, in one
// query for each.
func songParents(ctx context.Context, q *dbq.Queries, tracks []dbq.Track) (albumTitles, artistNames map[pgtype.UUID]string, err error) {
albumIDs := make([]pgtype.UUID, 0, len(tracks))
artistIDs := make([]pgtype.UUID, 0, len(tracks))
for _, t := range tracks {
albumIDs = append(albumIDs, t.AlbumID)
artistIDs = append(artistIDs, t.ArtistID)
}
albums, err := q.GetAlbumsByIDs(ctx, albumIDs)
if err != nil {
return nil, nil, err
}
artists, err := q.GetArtistsByIDs(ctx, artistIDs)
if err != nil {
return nil, nil, err
}
albumTitles = make(map[pgtype.UUID]string, len(albums))
for _, a := range albums {
albumTitles[a.ID] = a.Title
}
artistNames = make(map[pgtype.UUID]string, len(artists))
for _, a := range artists {
artistNames[a.ID] = a.Name
}
return albumTitles, artistNames, nil
}
// albumRefs converts a list of dbq.Album rows to AlbumRef, resolving artist
// name and track count per album. Uses resolveArtistNames for the artist side
// (one query per distinct artist) and CountTracksByAlbum per album. For small
// page sizes (≤ 500) this is well within budget.
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,
// not null. Same rationale applies to search3 facet slices.
if len(albums) == 0 {
return []AlbumRef{}, nil
}
ids := make([]pgtype.UUID, 0, len(albums))
for _, a := range albums {
ids = append(ids, a.ArtistID)
}
names, err := resolveArtistNames(ctx, q, ids)
if err != nil {
return nil, err
}
refs := make([]AlbumRef, 0, len(albums))
for _, a := range albums {
count, _ := q.CountTracksByAlbum(ctx, a.ID)
refs = append(refs, albumRef(a, names[uuidToID(a.ArtistID)], int(count), 0))
}
return refs, nil
}
func atoiDefault(s string, def int) int {
if s == "" {
return def
}
n, err := strconv.Atoi(strings.TrimSpace(s))
if err != nil {
return def
}
return n
}
func clampInt(v, lo, hi int) int {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}