feat(subsonic): apps can make, change and delete playlists (#8021)
release / web (push) Successful in 1m43s
release / go (push) Successful in 2m21s
release / govulncheck (push) Successful in 20s
release / integration (push) Failing after 4m31s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 2m44s
release / android (push) Canceled after 3m43s

createPlaylist makes a playlist, or with playlistId replaces its songs;
updatePlaylist renames it, sets its comment and visibility, removes songs
by the index the app was shown and adds songs; deletePlaylist deletes it.
A song index counts only the entries getPlaylist lists, so a hidden
entry ahead of it doesn't shift which song goes.

The playlist service gains ReplaceTracks and RemovePositions; the owner
and system-mix checks that each change repeated are one function.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 10:17:15 -05:00
co-authored by Claude Opus 5.5
parent 3491cf4c58
commit df2095baae
7 changed files with 614 additions and 180 deletions
+38 -10
View File
@@ -153,22 +153,21 @@ func (h *pickHandlers) getPlaylist(w http.ResponseWriter, r *http.Request) {
WriteFail(w, r, ErrGeneric, "Playlist unavailable")
return
}
ids := make([]pgtype.UUID, 0, len(detail.Tracks))
for _, t := range detail.Tracks {
if t.TrackID != nil && !t.Unavailable {
ids = append(ids, *t.TrackID)
}
if detail.Kind == "system" && detail.SystemVariant != nil {
h.recall.remember(user.ID, r.URL.Query().Get("c"), *detail.SystemVariant)
}
q := dbq.New(h.pool)
songs, err := songsInOrder(r.Context(), q, ids)
h.writePlaylist(w, r, detail)
}
// writePlaylist answers with a playlist and the songs in it that an app can
// play, as getPlaylist does.
func (h *pickHandlers) writePlaylist(w http.ResponseWriter, r *http.Request, detail *playlists.PlaylistDetail) {
songs, _, err := shownEntries(r.Context(), dbq.New(h.pool), detail)
if err != nil {
h.logger.Error("subsonic: playlist songs", "err", err)
WriteFail(w, r, ErrGeneric, "Playlist unavailable")
return
}
if detail.Kind == "system" && detail.SystemVariant != nil {
h.recall.remember(user.ID, r.URL.Query().Get("c"), *detail.SystemVariant)
}
head := playlistRef(&detail.PlaylistRow)
head.SongCount = len(songs)
head.Duration = 0
@@ -181,6 +180,35 @@ func (h *pickHandlers) getPlaylist(w http.ResponseWriter, r *http.Request) {
})
}
// shownEntries returns the songs of a playlist that a Subsonic app is shown,
// in order, and each one's position in the playlist. An entry whose file is
// missing, or whose song has left the library, is not shown, so an app's
// song index and Minstrel's position differ once one is hidden.
func shownEntries(ctx context.Context, q *dbq.Queries, detail *playlists.PlaylistDetail) ([]SongRef, []int32, error) {
ids := make([]pgtype.UUID, 0, len(detail.Tracks))
candidates := make([]int32, 0, len(detail.Tracks))
for _, t := range detail.Tracks {
if t.TrackID != nil && !t.Unavailable {
ids = append(ids, *t.TrackID)
candidates = append(candidates, t.Position)
}
}
songs, err := songsInOrder(ctx, q, ids)
if err != nil {
return nil, nil, err
}
// songsInOrder drops every entry of an id it can't find and keeps the
// rest in order, so walking both lists pairs each song with its entry.
positions := make([]int32, 0, len(songs))
for i, j := 0, 0; i < len(ids) && j < len(songs); i++ {
if uuidToID(ids[i]) == songs[j].ID {
positions = append(positions, candidates[i])
j++
}
}
return songs, positions, nil
}
// songsInOrder looks up tracks by id and returns them as songs in the order
// of ids; an id with no track is skipped. One query each for the tracks,
// their albums, their artists and their gains.
+2 -17
View File
@@ -303,24 +303,9 @@ func TestGetSimilarSongs_IsRadioFromASongAlbumOrArtist(t *testing.T) {
// playlist is neither listed nor readable.
func TestGetPlaylists_MixesFirstAndOnlyWhatTheListenerMaySee(t *testing.T) {
f := seedPicks(t)
ctx := context.Background()
svc := playlists.NewService(f.pool, nil, "")
svc := playlists.NewService(f.pool, nil, t.TempDir())
newPlaylist := func(owner dbq.User, name string, public bool, songs ...string) pgtype.UUID {
t.Helper()
p, err := svc.Create(ctx, owner.ID, name, "", public)
if err != nil {
t.Fatalf("create %s: %v", name, err)
}
ids := make([]pgtype.UUID, 0, len(songs))
for _, s := range songs {
ids = append(ids, f.tracks[s].ID)
}
if len(ids) > 0 {
if err := svc.AppendTracks(ctx, owner.ID, p.ID, ids); err != nil {
t.Fatalf("append %s: %v", name, err)
}
}
return p.ID
return f.newList(t, svc, owner, name, public, songs...)
}
mine := newPlaylist(f.user, "Road Songs", false, "Inlet", "Jetty", "Dusk")
mix := newPlaylist(f.user, "For you", false, "Gale", "Harbour")
+245
View File
@@ -0,0 +1,245 @@
package subsonic
import (
"errors"
"net/http"
"strconv"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
)
// ---- createPlaylist / updatePlaylist / deletePlaylist ----
//
// A listener changes only their own playlists. Someone else's private
// playlist reads as absent, as it does in getPlaylist; someone else's public
// one, and a daily mix, which Minstrel rebuilds itself, answer "not
// authorized".
// createPlaylist makes a playlist from name and the songs in songId, or, with
// playlistId, replaces that playlist's songs (and its name, when name is
// given). It answers with the playlist, as getPlaylist does.
func (h *pickHandlers) createPlaylist(w http.ResponseWriter, r *http.Request) {
user, ok := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
return
}
params := r.URL.Query()
songs, ok := songIDs(w, r, params["songId"])
if !ok {
return
}
name := params.Get("name")
ctx := r.Context()
var id pgtype.UUID
if raw := params.Get("playlistId"); raw != "" {
detail, ok := h.ownPlaylist(w, r, user, raw)
if !ok {
return
}
id = detail.ID
if err := h.playlists.ReplaceTracks(ctx, user.ID, id, songs); err != nil {
h.failPlaylistChange(w, r, err)
return
}
if name != "" {
if _, err := h.playlists.Update(ctx, user.ID, id, playlists.UpdateInput{Name: &name}); err != nil {
h.failPlaylistChange(w, r, err)
return
}
}
} else {
if name == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: name or playlistId")
return
}
created, err := h.playlists.Create(ctx, user.ID, name, "", false)
if err != nil {
h.failPlaylistChange(w, r, err)
return
}
id = created.ID
if len(songs) > 0 {
if err := h.playlists.AppendTracks(ctx, user.ID, id, songs); err != nil {
// A list that failed to fill isn't the one asked for.
if derr := h.playlists.Delete(ctx, user.ID, id); derr != nil {
h.logger.Warn("subsonic: remove unfilled playlist", "err", derr)
}
h.failPlaylistChange(w, r, err)
return
}
}
}
detail, err := h.playlists.Get(ctx, user.ID, id)
if err != nil {
h.failPlaylistChange(w, r, err)
return
}
h.writePlaylist(w, r, detail)
}
// updatePlaylist renames a playlist (name), sets its comment and whether it is
// public, removes the songs at songIndexToRemove and adds those in
// songIdToAdd at the end. Each index counts the songs as getPlaylist lists
// them before this call, so the song removed is the one the app showed.
func (h *pickHandlers) updatePlaylist(w http.ResponseWriter, r *http.Request) {
user, ok := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
return
}
params := r.URL.Query()
raw := params.Get("playlistId")
if raw == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: playlistId")
return
}
add, ok := songIDs(w, r, params["songIdToAdd"])
if !ok {
return
}
detail, ok := h.ownPlaylist(w, r, user, raw)
if !ok {
return
}
ctx := r.Context()
// Every index is checked before anything changes.
var remove []int32
if indexes := params["songIndexToRemove"]; len(indexes) > 0 {
_, positions, err := shownEntries(ctx, dbq.New(h.pool), detail)
if err != nil {
h.failPlaylistChange(w, r, err)
return
}
for _, s := range indexes {
i, err := strconv.Atoi(s)
if err != nil || i < 0 || i >= len(positions) {
WriteFail(w, r, ErrDataNotFound, "No song at index "+s)
return
}
remove = append(remove, positions[i])
}
}
var in playlists.UpdateInput
if params.Has("name") {
v := params.Get("name")
in.Name = &v
}
if params.Has("comment") {
v := params.Get("comment")
in.Description = &v
}
if params.Has("public") {
v, err := strconv.ParseBool(params.Get("public"))
if err != nil {
WriteFail(w, r, ErrGeneric, "public must be true or false")
return
}
in.IsPublic = &v
}
if in.Name != nil || in.Description != nil || in.IsPublic != nil {
if _, err := h.playlists.Update(ctx, user.ID, detail.ID, in); err != nil {
h.failPlaylistChange(w, r, err)
return
}
}
if len(remove) > 0 {
if err := h.playlists.RemovePositions(ctx, user.ID, detail.ID, remove); err != nil {
h.failPlaylistChange(w, r, err)
return
}
}
if len(add) > 0 {
if err := h.playlists.AppendTracks(ctx, user.ID, detail.ID, add); err != nil {
h.failPlaylistChange(w, r, err)
return
}
}
Write(w, r, NewEnvelope("ok"))
}
// deletePlaylist deletes the playlist id.
func (h *pickHandlers) deletePlaylist(w http.ResponseWriter, r *http.Request) {
user, ok := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
return
}
raw := r.URL.Query().Get("id")
if raw == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
return
}
detail, ok := h.ownPlaylist(w, r, user, raw)
if !ok {
return
}
if err := h.playlists.Delete(r.Context(), user.ID, detail.ID); err != nil {
h.failPlaylistChange(w, r, err)
return
}
Write(w, r, NewEnvelope("ok"))
}
// ownPlaylist loads the playlist raw names for a change by user, or answers
// with why it can't be changed and returns false.
func (h *pickHandlers) ownPlaylist(w http.ResponseWriter, r *http.Request, user dbq.User, raw string) (*playlists.PlaylistDetail, bool) {
id, ok := parseUUID(raw)
if !ok {
WriteFail(w, r, ErrDataNotFound, "Playlist not found")
return nil, false
}
detail, err := h.playlists.Get(r.Context(), user.ID, id)
switch {
case err != nil:
h.failPlaylistChange(w, r, err)
return nil, false
case detail.UserID != user.ID:
h.failPlaylistChange(w, r, playlists.ErrForbidden)
return nil, false
case detail.Kind == "system":
h.failPlaylistChange(w, r, playlists.ErrSystemPlaylistReadonly)
return nil, false
}
return detail, true
}
// failPlaylistChange answers a playlist change the service refused.
func (h *pickHandlers) failPlaylistChange(w http.ResponseWriter, r *http.Request, err error) {
switch {
case errors.Is(err, playlists.ErrNotFound):
WriteFail(w, r, ErrDataNotFound, "Playlist not found")
case errors.Is(err, playlists.ErrTrackNotFound):
WriteFail(w, r, ErrDataNotFound, "Song not found")
case errors.Is(err, playlists.ErrForbidden):
WriteFail(w, r, ErrNotAuthorized, "Only the playlist's owner can change it")
case errors.Is(err, playlists.ErrSystemPlaylistReadonly):
WriteFail(w, r, ErrNotAuthorized, "Minstrel's mixes can't be changed")
case errors.Is(err, playlists.ErrInvalidInput):
WriteFail(w, r, ErrGeneric, "A playlist needs a name")
default:
h.logger.Error("subsonic: change playlist", "err", err)
WriteFail(w, r, ErrGeneric, "Playlist unavailable")
}
}
// songIDs parses repeated song id parameters, or answers that one names no
// song and returns false.
func songIDs(w http.ResponseWriter, r *http.Request, raw []string) ([]pgtype.UUID, bool) {
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 nil, false
}
ids = append(ids, id)
}
return ids, true
}
+190
View File
@@ -0,0 +1,190 @@
package subsonic
import (
"context"
"errors"
"slices"
"testing"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
)
// writeHandlers are the fixture's handlers with a playlist service whose
// covers are drawn into a temporary directory.
func (f picksFixture) writeHandlers(t *testing.T) *pickHandlers {
h := f.handlers()
h.playlists = playlists.NewService(f.pool, h.logger, t.TempDir())
return h
}
// newList makes a playlist owned by owner holding songs, by title.
func (f picksFixture) newList(t *testing.T, svc *playlists.Service, owner dbq.User, name string, public bool, songs ...string) pgtype.UUID {
t.Helper()
ctx := context.Background()
p, err := svc.Create(ctx, owner.ID, name, "", public)
if err != nil {
t.Fatalf("create %s: %v", name, err)
}
if len(songs) > 0 {
if err := svc.AppendTracks(ctx, owner.ID, p.ID, f.ids(songs...)); err != nil {
t.Fatalf("append %s: %v", name, err)
}
}
return p.ID
}
func (f picksFixture) ids(songs ...string) []pgtype.UUID {
out := make([]pgtype.UUID, 0, len(songs))
for _, s := range songs {
out = append(out, f.tracks[s].ID)
}
return out
}
// stored reads a playlist as Minstrel keeps it, hidden entries included.
func stored(t *testing.T, svc *playlists.Service, owner dbq.User, id pgtype.UUID) *playlists.PlaylistDetail {
t.Helper()
d, err := svc.Get(context.Background(), owner.ID, id)
if err != nil {
t.Fatalf("get: %v", err)
}
return d
}
func storedTitles(d *playlists.PlaylistDetail) []string {
out := make([]string, 0, len(d.Tracks))
for _, tr := range d.Tracks {
out = append(out, tr.Title)
}
return out
}
func TestCreatePlaylist_MakesAListOrReplacesOnesSongs(t *testing.T) {
f := seedPicks(t)
h := f.writeHandlers(t)
var made struct {
Playlist PlaylistWithSongs `json:"playlist"`
}
q := "name=Road+Songs&songId=" + uuidToID(f.tracks["Dusk"].ID) + "&songId=" + uuidToID(f.tracks["Gale"].ID)
if code := call(t, h.createPlaylist, f.user, q, &made); code != 0 {
t.Fatalf("create: error %d", code)
}
if made.Playlist.Name != "Road Songs" || !slices.Equal(titles(made.Playlist.Entries), []string{"Dusk", "Gale"}) {
t.Fatalf("made %q with %v, want Road Songs with Dusk, Gale", made.Playlist.Name, titles(made.Playlist.Entries))
}
id, _ := parseUUID(made.Playlist.ID)
if d := stored(t, h.playlists, f.user, id); d.UserID != f.user.ID || d.IsPublic {
t.Errorf("owner %v public %v, want the caller's private list", d.UserID, d.IsPublic)
}
var replaced struct {
Playlist PlaylistWithSongs `json:"playlist"`
}
q = "playlistId=" + made.Playlist.ID + "&name=Night+Drive&songId=" + uuidToID(f.tracks["Inlet"].ID)
if code := call(t, h.createPlaylist, f.user, q, &replaced); code != 0 {
t.Fatalf("replace: error %d", code)
}
if replaced.Playlist.ID != made.Playlist.ID || replaced.Playlist.Name != "Night Drive" ||
!slices.Equal(titles(replaced.Playlist.Entries), []string{"Inlet"}) {
t.Errorf("replaced = %s %q %v, want the same list renamed Night Drive holding Inlet",
replaced.Playlist.ID, replaced.Playlist.Name, titles(replaced.Playlist.Entries))
}
if code := call(t, h.createPlaylist, f.user, "songId="+uuidToID(f.tracks["Dusk"].ID), nil); code != ErrMissingParameter {
t.Errorf("no name or playlistId: error %d, want %d", code, ErrMissingParameter)
}
// A song id that names no song leaves no half-made playlist behind.
notASong := uuidToID(f.albums["Paper Boats"].ID)
if code := call(t, h.createPlaylist, f.user, "name=Broken&songId="+notASong, nil); code != ErrDataNotFound {
t.Errorf("unknown song: error %d, want %d", code, ErrDataNotFound)
}
var n int
if err := f.pool.QueryRow(context.Background(), `SELECT count(*) FROM playlists WHERE name = 'Broken'`).Scan(&n); err != nil {
t.Fatal(err)
}
if n != 0 {
t.Errorf("%d playlists named Broken, want none", n)
}
}
// Jetty's file is missing, so the app is shown Inlet, Dusk, Gale and its
// index 1 is Dusk, though Dusk is third in the stored list.
func TestUpdatePlaylist_IndexesCountTheSongsTheAppWasShown(t *testing.T) {
f := seedPicks(t)
h := f.writeHandlers(t)
id := f.newList(t, h.playlists, f.user, "Road Songs", false, "Inlet", "Jetty", "Dusk", "Gale")
pid := uuidToID(id)
q := "playlistId=" + pid + "&songIndexToRemove=1&songIdToAdd=" + uuidToID(f.tracks["Harbour"].ID) +
"&name=Night+Drive&comment=after+dark&public=true"
if code := call(t, h.updatePlaylist, f.user, q, nil); code != 0 {
t.Fatalf("update: error %d", code)
}
d := stored(t, h.playlists, f.user, id)
if got, want := storedTitles(d), []string{"Inlet", "Jetty", "Gale", "Harbour"}; !slices.Equal(got, want) {
t.Errorf("songs = %v, want %v", got, want)
}
if d.Name != "Night Drive" || d.Description != "after dark" || !d.IsPublic {
t.Errorf("name %q comment %q public %v, want Night Drive, after dark, true", d.Name, d.Description, d.IsPublic)
}
// Shown now: Inlet, Gale, Harbour. Several indexes all count from
// that list.
if code := call(t, h.updatePlaylist, f.user, "playlistId="+pid+"&songIndexToRemove=0&songIndexToRemove=2", nil); code != 0 {
t.Fatalf("remove two: error %d", code)
}
if got, want := storedTitles(stored(t, h.playlists, f.user, id)), []string{"Jetty", "Gale"}; !slices.Equal(got, want) {
t.Errorf("songs = %v, want %v", got, want)
}
// An index past the shown list changes nothing, not even the name.
if code := call(t, h.updatePlaylist, f.user, "playlistId="+pid+"&name=Changed&songIndexToRemove=1", nil); code != ErrDataNotFound {
t.Errorf("index past the end: error %d, want %d", code, ErrDataNotFound)
}
if d := stored(t, h.playlists, f.user, id); d.Name != "Night Drive" || len(d.Tracks) != 2 {
t.Errorf("after a refused update: name %q, %d songs; want it unchanged", d.Name, len(d.Tracks))
}
}
func TestPlaylistWrites_OnlyTheOwnersOwnLists(t *testing.T) {
f := seedPicks(t)
h := f.writeHandlers(t)
shared := uuidToID(f.newList(t, h.playlists, f.other, "Shared", true, "Gale"))
secret := uuidToID(f.newList(t, h.playlists, f.other, "Secret", false, "Gale"))
mixID := f.newList(t, h.playlists, f.user, "For you", false, "Gale")
f.exec(t, `UPDATE playlists SET kind = 'system', system_variant = 'for_you' WHERE id = $1`, mixID)
mix := uuidToID(mixID)
song := uuidToID(f.tracks["Dusk"].ID)
cases := []struct {
list string
want int
}{
{shared, ErrNotAuthorized},
{secret, ErrDataNotFound},
{mix, ErrNotAuthorized},
}
for _, c := range cases {
if code := call(t, h.updatePlaylist, f.user, "playlistId="+c.list+"&songIdToAdd="+song, nil); code != c.want {
t.Errorf("update %s: error %d, want %d", c.list, code, c.want)
}
if code := call(t, h.createPlaylist, f.user, "playlistId="+c.list+"&songId="+song, nil); code != c.want {
t.Errorf("replace %s: error %d, want %d", c.list, code, c.want)
}
if code := call(t, h.deletePlaylist, f.user, "id="+c.list, nil); code != c.want {
t.Errorf("delete %s: error %d, want %d", c.list, code, c.want)
}
}
mine := f.newList(t, h.playlists, f.user, "Mine", false, "Dusk")
if code := call(t, h.deletePlaylist, f.user, "id="+uuidToID(mine), nil); code != 0 {
t.Fatalf("delete own: error %d", code)
}
if _, err := h.playlists.Get(context.Background(), f.user.ID, mine); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("after delete: %v, want not found", err)
}
}
+3
View File
@@ -101,6 +101,9 @@ func mountAuthed(sub chi.Router, b *browseHandlers, m *mediaHandlers, u *userHan
register(sub, "/getUser", u.getUser)
register(sub, "/getPlaylists", p.getPlaylists)
register(sub, "/getPlaylist", p.getPlaylist)
register(sub, "/createPlaylist", p.createPlaylist)
register(sub, "/updatePlaylist", p.updatePlaylist)
register(sub, "/deletePlaylist", p.deletePlaylist)
register(sub, "/getRandomSongs", p.getRandomSongs)
register(sub, "/getSimilarSongs", p.getSimilarSongs)
register(sub, "/getSimilarSongs2", p.getSimilarSongs2)