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>
609 lines
19 KiB
Go
609 lines
19 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
|
|
}
|
|
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))
|
|
for _, a := range albums {
|
|
refs = append(refs, albumRef(a, artist.Name, counts[a.ID], 0))
|
|
}
|
|
Write(w, r, ArtistResponse{
|
|
Envelope: NewEnvelope("ok"),
|
|
Artist: ArtistDetail{
|
|
ID: uuidToID(artist.ID),
|
|
Name: artist.Name,
|
|
CoverArt: uuidToID(artist.ID),
|
|
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: 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) {
|
|
all, err := q.ListTracksByAlbum(ctx, dbq.ListTracksByAlbumParams{AlbumID: album.ID, UserID: listenerID(ctx)})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
tracks := all[:0]
|
|
for _, t := range all {
|
|
if !t.MissingSince.Valid {
|
|
tracks = append(tracks, t)
|
|
}
|
|
}
|
|
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 {
|
|
// Only songs the listener can play: see SearchPlayableTracks for why
|
|
// the filter can't come after the page is cut.
|
|
tracks, err := q.SearchPlayableTracks(r.Context(), dbq.SearchPlayableTracksParams{
|
|
Query: query, UserID: listenerID(r.Context()), RowLimit: int32(songCount), RowOffset: int32(songOffset),
|
|
})
|
|
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
|
|
// names (one query per distinct artist) and each album's song count: the
|
|
// songs the listener can play, so it matches what getAlbum lists.
|
|
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
|
|
}
|
|
counts, err := playableCounts(ctx, q, albums)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
refs := make([]AlbumRef, 0, len(albums))
|
|
for _, a := range albums {
|
|
refs = append(refs, albumRef(a, names[uuidToID(a.ArtistID)], counts[a.ID], 0))
|
|
}
|
|
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 {
|
|
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
|
|
}
|