feat(subsonic): an artist's top songs, and the play queue carried between devices
release / go (push) Successful in 1m50s
release / web (push) Successful in 1m14s
release / govulncheck (push) Successful in 44s
release / integration (push) Successful in 4m11s
release / android (push) Successful in 6m15s
release / Build signed APK (push) Successful in 7m51s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped

getTopSongs ranks the named artist's songs by how often they were played
through on this server, then by likes, then in album order, so an artist
nobody has played yet still has songs to offer. Missing files and the
listener's quarantined songs are left out.

savePlayQueue keeps one queue per listener: the songs in order, the one
playing, how far into it, and the app that saved it. getPlayQueue gives it
back to that listener only; a song no longer in the library drops out.
Saving no songs clears it. The queue lives in a new play_queues table,
which backups carry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 17:03:29 -05:00
co-authored by Claude Opus 5.5
parent 8731e9695a
commit b801f81058
15 changed files with 568 additions and 2 deletions
+50
View File
@@ -2,6 +2,7 @@ package subsonic
import (
"net/http"
"strings"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
@@ -92,3 +93,52 @@ func (b *browseHandlers) getSongsByGenre(w http.ResponseWriter, r *http.Request)
SongsByGenre: SongsByGenreContainer{Songs: songs},
})
}
type TopSongsContainer struct {
Songs []SongRef `json:"song" xml:"song"`
}
type TopSongsResponse struct {
Envelope
TopSongs TopSongsContainer `json:"topSongs" xml:"topSongs"`
}
// getTopSongs returns an artist's most played songs on this server, then the
// most liked, then the rest in album order (ListTopTracksForArtistName). The
// app names the artist rather than giving an id. count defaults to 50 and is
// at most 500.
func (b *browseHandlers) getTopSongs(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
artist := strings.TrimSpace(params.Get("artist"))
if artist == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: artist")
return
}
user, ok := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
return
}
count := clampInt(atoiDefault(params.Get("count"), 50), 1, 500)
q := dbq.New(b.pool)
rows, err := q.ListTopTracksForArtistName(r.Context(), dbq.ListTopTracksForArtistNameParams{
ArtistName: artist, UserID: user.ID, Lim: int32(count),
})
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load top songs")
return
}
tracks := make([]dbq.Track, len(rows))
for i, row := range rows {
tracks[i] = row.Track
}
songs, err := songRefs(r.Context(), q, tracks)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load top songs")
return
}
Write(w, r, TopSongsResponse{
Envelope: NewEnvelope("ok"),
TopSongs: TopSongsContainer{Songs: songs},
})
}
+134
View File
@@ -0,0 +1,134 @@
package subsonic
import (
"errors"
"net/http"
"slices"
"strconv"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// A Subsonic app saves its play queue (savePlayQueue) so the same app on
// another device, or another app, can carry on from it (getPlayQueue). The
// server keeps one queue per user and does nothing else with it: Minstrel's
// own apps keep their queue on the device.
// maxPlayQueue is the most songs one saved queue holds. A queue longer than
// any app sends is refused rather than stored, so one request cannot grow a
// row without bound.
const maxPlayQueue = 10000
// PlayQueue is the body of getPlayQueue. Position is milliseconds into the
// current song.
type PlayQueue struct {
Current string `json:"current,omitempty" xml:"current,attr,omitempty"`
Position int64 `json:"position,omitempty" xml:"position,attr,omitempty"`
Username string `json:"username" xml:"username,attr"`
Changed string `json:"changed" xml:"changed,attr"`
ChangedBy string `json:"changedBy" xml:"changedBy,attr"`
Entries []SongRef `json:"entry" xml:"entry"`
}
// PlayQueueResponse carries no playQueue when nothing has been saved, which
// is how the Subsonic server answers too.
type PlayQueueResponse struct {
Envelope
PlayQueue *PlayQueue `json:"playQueue,omitempty" xml:"playQueue,omitempty"`
}
// getPlayQueue returns the queue the listener last saved. A song no longer
// in the library drops out of it; if that was the current song, the queue
// has no current song.
func (b *browseHandlers) getPlayQueue(w http.ResponseWriter, r *http.Request) {
user, ok := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
return
}
q := dbq.New(b.pool)
saved, err := q.GetPlayQueue(r.Context(), user.ID)
if errors.Is(err, pgx.ErrNoRows) {
Write(w, r, PlayQueueResponse{Envelope: NewEnvelope("ok")})
return
}
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load the play queue")
return
}
songs, err := songsInOrder(r.Context(), q, saved.TrackIds)
if err != nil {
WriteFail(w, r, ErrGeneric, "Failed to load the play queue")
return
}
queue := &PlayQueue{
Username: user.Username,
Changed: timestamptzToRFC3339(saved.ChangedAt),
ChangedBy: saved.ChangedBy,
Entries: songs,
}
current := uuidToID(saved.CurrentTrackID)
if current != "" && slices.ContainsFunc(songs, func(s SongRef) bool { return s.ID == current }) {
queue.Current = current
queue.Position = saved.PositionMs
}
Write(w, r, PlayQueueResponse{Envelope: NewEnvelope("ok"), PlayQueue: queue})
}
// savePlayQueue replaces the listener's saved queue with the songs given as
// repeated id parameters, in order, with current the one playing and
// position the milliseconds into it. With no id the saved queue is cleared,
// as OpenSubsonic specifies.
func (b *browseHandlers) savePlayQueue(w http.ResponseWriter, r *http.Request) {
user, ok := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
return
}
params := r.URL.Query()
q := dbq.New(b.pool)
raw := params["id"]
if len(raw) == 0 {
if err := q.DeletePlayQueue(r.Context(), user.ID); err != nil {
WriteFail(w, r, ErrGeneric, "Failed to clear the play queue")
return
}
Write(w, r, NewEnvelope("ok"))
return
}
if len(raw) > maxPlayQueue {
WriteFail(w, r, ErrGeneric, "A play queue holds at most "+strconv.Itoa(maxPlayQueue)+" songs")
return
}
ids := make([]pgtype.UUID, 0, len(raw))
for _, s := range raw {
id, ok := parseUUID(s)
if !ok {
WriteFail(w, r, ErrDataNotFound, "Song not found: "+s)
return
}
ids = append(ids, id)
}
var current pgtype.UUID
if s := params.Get("current"); s != "" {
if current, ok = parseUUID(s); !ok {
WriteFail(w, r, ErrDataNotFound, "Song not found: "+s)
return
}
}
position, err := strconv.ParseInt(params.Get("position"), 10, 64)
if err != nil || position < 0 {
position = 0
}
if err := q.SavePlayQueue(r.Context(), dbq.SavePlayQueueParams{
UserID: user.ID, TrackIds: ids, CurrentTrackID: current,
PositionMs: position, ChangedBy: params.Get("c"),
}); err != nil {
WriteFail(w, r, ErrGeneric, "Failed to save the play queue")
return
}
Write(w, r, NewEnvelope("ok"))
}
+144
View File
@@ -0,0 +1,144 @@
package subsonic
import (
"context"
"slices"
"testing"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// play records plays of a track by a listener, skipped or played through.
func (f picksFixture) play(t *testing.T, user dbq.User, track string, times int, skipped bool) {
t.Helper()
var session pgtype.UUID
if err := f.pool.QueryRow(context.Background(), `INSERT INTO play_sessions (user_id, started_at, last_event_at, client_id)
VALUES ($1, now() - interval '2 days', now() - interval '2 days', 'top-songs-test') RETURNING id`,
user.ID).Scan(&session); err != nil {
t.Fatalf("play session: %v", err)
}
for range times {
f.exec(t, `INSERT INTO play_events (user_id, track_id, session_id, started_at, was_skipped)
VALUES ($1, $2, $3, now() - interval '2 days', $4)`, user.ID, f.tracks[track].ID, session, skipped)
}
}
func (f picksFixture) topSongs(t *testing.T, query string) ([]string, int) {
t.Helper()
var got struct {
TopSongs struct {
Songs *[]SongRef `json:"song"`
} `json:"topSongs"`
}
if code := call(t, f.browse().getTopSongs, f.user, query, &got); code != 0 {
return nil, code
}
if got.TopSongs.Songs == nil {
t.Fatalf("getTopSongs %s: song is null or absent, want a list", query)
}
return titles(*got.TopSongs.Songs), 0
}
// An artist's top songs are the ones played through most on this server, by
// anyone, then the most liked, then the rest in album order. Skips don't
// count, and the listener's quarantined song and the missing file are left
// out.
func TestGetTopSongs_RanksByPlaysThenLikesThenAlbumOrder(t *testing.T) {
f := seedPicks(t)
// The fixture's listener played Flint once.
f.play(t, f.other, "Harbour", 2, false)
f.play(t, f.other, "Inlet", 3, true)
f.exec(t, `INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2)`, f.other.ID, f.tracks["Gale"].ID)
cases := []struct {
query string
want []string
}{
{"artist=Tin+Orchard", []string{"Harbour", "Flint", "Gale", "Dusk", "Inlet"}},
{"artist=tin+orchard&count=2", []string{"Harbour", "Flint"}},
{"artist=Nobody+Here", []string{}},
}
for _, c := range cases {
got, code := f.topSongs(t, c.query)
if code != 0 {
t.Fatalf("%s: error %d", c.query, code)
}
if !slices.Equal(got, c.want) {
t.Errorf("%s = %v, want %v", c.query, got, c.want)
}
}
if _, code := f.topSongs(t, ""); code != ErrMissingParameter {
t.Errorf("no artist: code %d, want %d", code, ErrMissingParameter)
}
}
func (f picksFixture) playQueue(t *testing.T, user dbq.User) *PlayQueue {
t.Helper()
var got struct {
PlayQueue *PlayQueue `json:"playQueue"`
}
if code := call(t, f.browse().getPlayQueue, user, "", &got); code != 0 {
t.Fatalf("getPlayQueue: error %d", code)
}
return got.PlayQueue
}
func (f picksFixture) saveQueue(t *testing.T, query string) int {
t.Helper()
return call(t, f.browse().savePlayQueue, f.user, query, nil)
}
// A saved queue comes back to the same listener, in order with repeats, with
// the current song and position; nobody else sees it; saving no songs clears
// it.
func TestPlayQueue_SavedByOneAppIsWhatTheNextOneGets(t *testing.T) {
f := seedPicks(t)
id := func(title string) string { return uuidToID(f.tracks[title].ID) }
if q := f.playQueue(t, f.user); q != nil {
t.Fatalf("before any save: queue %+v, want none", q)
}
if code := f.saveQueue(t, "id="+id("Gale")+"&id="+id("Harbour")+"&id="+id("Gale")+
"&current="+id("Harbour")+"&position=61000&c=DSub"); code != 0 {
t.Fatalf("savePlayQueue: error %d", code)
}
q := f.playQueue(t, f.user)
if q == nil {
t.Fatal("after a save: no queue")
}
if got, want := titles(q.Entries), []string{"Gale", "Harbour", "Gale"}; !slices.Equal(got, want) {
t.Errorf("entries = %v, want %v", got, want)
}
if q.Current != id("Harbour") || q.Position != 61000 {
t.Errorf("current %q at %d, want Harbour (%s) at 61000", q.Current, q.Position, id("Harbour"))
}
if q.ChangedBy != "DSub" || q.Username != f.user.Username || q.Changed == "" {
t.Errorf("changed by %q, user %q, changed %q; want DSub, %q and a time", q.ChangedBy, q.Username, q.Changed, f.user.Username)
}
if other := f.playQueue(t, f.other); other != nil {
t.Errorf("another listener sees queue %+v, want none", other)
}
// A song that is no longer in the library drops out, and a current song
// that went with it leaves the queue with none.
gone := "00000000-0000-4000-8000-000000000001"
if code := f.saveQueue(t, "id="+id("Gale")+"&id="+gone+"&current="+gone+"&position=5000"); code != 0 {
t.Fatalf("savePlayQueue: error %d", code)
}
q = f.playQueue(t, f.user)
if got := titles(q.Entries); !slices.Equal(got, []string{"Gale"}) || q.Current != "" || q.Position != 0 {
t.Errorf("queue = %v current %q at %d, want [Gale] with no current song", got, q.Current, q.Position)
}
if code := f.saveQueue(t, "id=not-a-song"); code != ErrDataNotFound {
t.Errorf("an id that is not a song: code %d, want %d", code, ErrDataNotFound)
}
if code := f.saveQueue(t, ""); code != 0 {
t.Fatalf("savePlayQueue with no songs: error %d", code)
}
if q := f.playQueue(t, f.user); q != nil {
t.Errorf("after saving no songs: queue %+v, want none", q)
}
}
+3
View File
@@ -71,6 +71,9 @@ func mountAuthed(sub chi.Router, b *browseHandlers, m *mediaHandlers, u *userHan
register(sub, "/search2", b.search2)
register(sub, "/getGenres", b.getGenres)
register(sub, "/getSongsByGenre", b.getSongsByGenre)
register(sub, "/getTopSongs", b.getTopSongs)
register(sub, "/getPlayQueue", b.getPlayQueue)
register(sub, "/savePlayQueue", b.savePlayQueue)
register(sub, "/stream", m.handleStream)
register(sub, "/download", m.handleDownload)
register(sub, "/getCoverArt", m.handleGetCoverArt)