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
+2 -2
View File
@@ -56,7 +56,7 @@ Open `http://<host>:4533/register` and create the first account with that setup
1. **Let the first scan finish.** Minstrel scans the library on startup. Watch it, or scan again, on the **Admin** page (`/admin`). Later scans only pick up what changed. 1. **Let the first scan finish.** Minstrel scans the library on startup. Watch it, or scan again, on the **Admin** page (`/admin`). Later scans only pick up what changed.
2. **Install the Android app.** In **Settings** (`/settings`), the *Install the Android app* card downloads the app this server ships. It updates itself from your server after that. 2. **Install the Android app.** In **Settings** (`/settings`), the *Install the Android app* card downloads the app this server ships. It updates itself from your server after that.
**On an iPhone** there is no Minstrel app; use a Subsonic app such as play:Sub or Amperfy. Make a password for it in **Settings › Connections › Subsonic apps**, and give the app your server's address, your username and that password. Subsonic apps can browse, search, play, like and scrobble. Minstrel's daily mixes appear in them as playlists, and when an app asks the server for random songs or an instant mix it gets Minstrel's smart shuffle and radio. An app that shuffles on the phone instead shuffles at random. **On an iPhone** there is no Minstrel app; use a Subsonic app such as play:Sub or Amperfy. Make a password for it in **Settings › Connections › Subsonic apps**, and give the app your server's address, your username and that password. Subsonic apps can browse, search, play, like and scrobble, and make and edit playlists. Minstrel's daily mixes appear in them as playlists, and when an app asks the server for random songs or an instant mix it gets Minstrel's smart shuffle and radio. An app that shuffles on the phone instead shuffles at random.
3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token for each person; an invite is the only way to an account. Each person gets their own likes, history and recommendations. 3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token for each person; an invite is the only way to an account. Each person gets their own likes, history and recommendations.
4. **Optional: connect ListenBrainz.** Each person adds their own ListenBrainz token in **Settings › Connections**. 4. **Optional: connect ListenBrainz.** Each person adds their own ListenBrainz token in **Settings › Connections**.
@@ -113,7 +113,7 @@ Every image carries a signed Android app, all with the same key, so a phone can
**Clients and accounts** **Clients and accounts**
- A full web app, built into the server. - A full web app, built into the server.
- A native Android app that ships inside the server image, keeps playing what it has cached when the server is out of reach, and updates itself from your server. - A native Android app that ships inside the server image, keeps playing what it has cached when the server is out of reach, and updates itself from your server.
- OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse by artist, album, genre or folder, search, play, like and scrobble, carry a play queue from one device to another, show lyrics (from a `.lrc` file beside the song, or the song's own tags), see the daily mixes and your playlists, and get Minstrel's smart shuffle and radio when they ask for random songs or similar songs. - OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse by artist, album, genre or folder, search, play, like and scrobble, carry a play queue from one device to another, show lyrics (from a `.lrc` file beside the song, or the song's own tags), see the daily mixes, make and edit your playlists, and get Minstrel's smart shuffle and radio when they ask for random songs or similar songs.
- Separate accounts for each person, with invites, and an inbox for what happened while you were away. - Separate accounts for each person, with invites, and an inbox for what happened while you were away.
## Scope and responsible use ## Scope and responsible use
+115 -132
View File
@@ -19,6 +19,7 @@ import (
"log/slog" "log/slog"
"os" "os"
"path/filepath" "path/filepath"
"slices"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
@@ -279,18 +280,8 @@ type UpdateInput struct {
// change something. // change something.
func (s *Service) Update(ctx context.Context, callerID, playlistID pgtype.UUID, in UpdateInput) (*PlaylistRow, error) { func (s *Service) Update(ctx context.Context, callerID, playlistID pgtype.UUID, in UpdateInput) (*PlaylistRow, error) {
q := dbq.New(s.pool) q := dbq.New(s.pool)
existing, err := q.GetPlaylist(ctx, playlistID) if _, err := editable(ctx, q, callerID, playlistID); err != nil {
if err != nil { return nil, err
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("get-before-update: %w", err)
}
if !pgtypeUUIDEqual(existing.UserID, callerID) {
return nil, ErrForbidden
}
if existing.Kind == "system" {
return nil, ErrSystemPlaylistReadonly
} }
params := dbq.UpdatePlaylistParams{ params := dbq.UpdatePlaylistParams{
@@ -334,18 +325,8 @@ func (s *Service) Update(ctx context.Context, callerID, playlistID pgtype.UUID,
// confuse callers about whether the delete took effect). // confuse callers about whether the delete took effect).
func (s *Service) Delete(ctx context.Context, callerID, playlistID pgtype.UUID) error { func (s *Service) Delete(ctx context.Context, callerID, playlistID pgtype.UUID) error {
q := dbq.New(s.pool) q := dbq.New(s.pool)
existing, err := q.GetPlaylist(ctx, playlistID) if _, err := editable(ctx, q, callerID, playlistID); err != nil {
if err != nil { return err
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
return fmt.Errorf("get-before-delete: %w", err)
}
if !pgtypeUUIDEqual(existing.UserID, callerID) {
return ErrForbidden
}
if existing.Kind == "system" {
return ErrSystemPlaylistReadonly
} }
deleted, err := q.DeletePlaylist(ctx, playlistID) deleted, err := q.DeletePlaylist(ctx, playlistID)
@@ -366,30 +347,25 @@ func (s *Service) Delete(ctx context.Context, callerID, playlistID pgtype.UUID)
return nil return nil
} }
// AssertEditable returns nil if the playlist exists, the caller owns it, // editable loads playlistID for a change by callerID. It answers
// AND the playlist is user-created (kind='user'). Returns: // ErrNotFound when the playlist doesn't exist, ErrForbidden when the caller
// - ErrNotFound — playlist doesn't exist // doesn't own it, and ErrSystemPlaylistReadonly for a system mix, which only
// - ErrForbidden — caller is not the owner // Minstrel rebuilds.
// - ErrSystemPlaylistReadonly — playlist exists but kind='system' func editable(ctx context.Context, q *dbq.Queries, callerID, playlistID pgtype.UUID) (dbq.GetPlaylistRow, error) {
//
// Edit handlers call this first; on error, the API layer maps the typed
// error to the appropriate status code.
func (s *Service) AssertEditable(ctx context.Context, callerID, playlistID pgtype.UUID) error {
q := dbq.New(s.pool)
p, err := q.GetPlaylist(ctx, playlistID) p, err := q.GetPlaylist(ctx, playlistID)
if err != nil { if err != nil {
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound return p, ErrNotFound
} }
return fmt.Errorf("playlists: load for editability check: %w", err) return p, fmt.Errorf("get playlist: %w", err)
} }
if !pgtypeUUIDEqual(p.UserID, callerID) { if !pgtypeUUIDEqual(p.UserID, callerID) {
return ErrForbidden return p, ErrForbidden
} }
if p.Kind == "system" { if p.Kind == "system" {
return ErrSystemPlaylistReadonly return p, ErrSystemPlaylistReadonly
} }
return nil return p, nil
} }
// AppendTracks adds the given track ids at the end of the playlist, // AppendTracks adds the given track ids at the end of the playlist,
@@ -400,91 +376,57 @@ func (s *Service) AppendTracks(ctx context.Context, callerID, playlistID pgtype.
if len(trackIDs) == 0 { if len(trackIDs) == 0 {
return fmt.Errorf("%w: at least one track id required", ErrInvalidInput) return fmt.Errorf("%w: at least one track id required", ErrInvalidInput)
} }
q := dbq.New(s.pool) return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
pl, err := q.GetPlaylist(ctx, playlistID) return appendTracks(ctx, tx, playlistID, trackIDs)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
return fmt.Errorf("get playlist: %w", err)
}
if !pgtypeUUIDEqual(pl.UserID, callerID) {
return ErrForbidden
}
if pl.Kind == "system" {
return ErrSystemPlaylistReadonly
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
tq := dbq.New(tx)
for _, tid := range trackIDs {
_, ierr := tq.AppendPlaylistTrack(ctx, dbq.AppendPlaylistTrackParams{
PlaylistID: playlistID,
TrackID: tid,
}) })
if ierr != nil { }
// AppendPlaylistTrack uses INSERT ... SELECT FROM tracks WHERE id = X.
// If X doesn't exist, no row inserts and the :one query errors with
// pgx.ErrNoRows.
if errors.Is(ierr, pgx.ErrNoRows) {
return ErrTrackNotFound
}
return fmt.Errorf("append track: %w", ierr)
}
// Tx-bound: change row commits with the playlist_track row.
if lerr := syncpkg.LogChange(ctx, tx, syncpkg.EntityPlaylistTrack,
syncpkg.EncodePlaylistTrackID(syncpkg.FormatUUID(playlistID), syncpkg.FormatUUID(tid)),
syncpkg.OpUpsert); lerr != nil {
return fmt.Errorf("log change: %w", lerr)
}
}
if err := tq.UpdatePlaylistRollups(ctx, playlistID); err != nil {
return fmt.Errorf("update rollups: %w", err)
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit: %w", err)
}
// Regenerate cover (synchronous). Failure is logged but not returned — // ReplaceTracks makes trackIDs the playlist's whole track list, in order;
// the playlist mutation already committed. // an empty list empties it. The old list goes only if every new track
if _, cerr := GenerateCollage(ctx, s.pool, playlistID, s.dataDir); cerr != nil { // exists.
s.logger.Warn("collage regeneration failed", "playlist_id", playlistID, "err", cerr) func (s *Service) ReplaceTracks(ctx context.Context, callerID, playlistID pgtype.UUID, trackIDs []pgtype.UUID) error {
return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
rows, err := tx.Query(ctx,
`DELETE FROM playlist_tracks WHERE playlist_id = $1 RETURNING track_id`, playlistID)
if err != nil {
return fmt.Errorf("clear tracks: %w", err)
} }
return nil removed, err := pgx.CollectRows(rows, pgx.RowTo[pgtype.UUID])
if err != nil {
return fmt.Errorf("clear tracks: %w", err)
}
for _, tid := range removed {
if err := logTrackChange(ctx, tx, playlistID, tid, syncpkg.OpDelete); err != nil {
return err
}
}
return appendTracks(ctx, tx, playlistID, trackIDs)
})
} }
// RemoveTrack deletes the row at `position` and renumbers subsequent // RemoveTrack deletes the row at `position` and renumbers subsequent
// rows to close the gap. Triggers cover regeneration after. // rows to close the gap. Triggers cover regeneration after.
func (s *Service) RemoveTrack(ctx context.Context, callerID, playlistID pgtype.UUID, position int32) error { func (s *Service) RemoveTrack(ctx context.Context, callerID, playlistID pgtype.UUID, position int32) error {
q := dbq.New(s.pool) return s.RemovePositions(ctx, callerID, playlistID, []int32{position})
pl, err := q.GetPlaylist(ctx, playlistID) }
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
return fmt.Errorf("get playlist: %w", err)
}
if !pgtypeUUIDEqual(pl.UserID, callerID) {
return ErrForbidden
}
if pl.Kind == "system" {
return ErrSystemPlaylistReadonly
}
tx, err := s.pool.Begin(ctx) // RemovePositions deletes the rows at the given positions, all counted
if err != nil { // in the list as it stands before the call, and closes the gaps. A
return fmt.Errorf("begin tx: %w", err) // position repeated is removed once; one with no row is ErrNotFound and
// removes nothing.
func (s *Service) RemovePositions(ctx context.Context, callerID, playlistID pgtype.UUID, positions []int32) error {
if len(positions) == 0 {
return fmt.Errorf("%w: at least one position required", ErrInvalidInput)
} }
defer func() { _ = tx.Rollback(ctx) }() // Highest first, so closing one gap never moves a row still to go.
order := slices.Clone(positions)
slices.Sort(order)
order = slices.Compact(order)
slices.Reverse(order)
return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
tq := dbq.New(tx) tq := dbq.New(tx)
for _, position := range order {
// Capture the track_id before we delete the row — we need it for the // The track id names the change for clients that sync.
// LogChange composite key after the delete commits.
var deletedTrackID pgtype.UUID var deletedTrackID pgtype.UUID
if err := tx.QueryRow(ctx, if err := tx.QueryRow(ctx,
`SELECT track_id FROM playlist_tracks WHERE playlist_id = $1 AND position = $2`, `SELECT track_id FROM playlist_tracks WHERE playlist_id = $1 AND position = $2`,
@@ -495,17 +437,14 @@ func (s *Service) RemoveTrack(ctx context.Context, callerID, playlistID pgtype.U
} }
return fmt.Errorf("lookup track at position: %w", err) return fmt.Errorf("lookup track at position: %w", err)
} }
if err := tq.DeletePlaylistTrack(ctx, dbq.DeletePlaylistTrackParams{ if err := tq.DeletePlaylistTrack(ctx, dbq.DeletePlaylistTrackParams{
PlaylistID: playlistID, PlaylistID: playlistID,
Position: position, Position: position,
}); err != nil { }); err != nil {
return fmt.Errorf("delete track row: %w", err) return fmt.Errorf("delete track row: %w", err)
} }
if lerr := syncpkg.LogChange(ctx, tx, syncpkg.EntityPlaylistTrack, if err := logTrackChange(ctx, tx, playlistID, deletedTrackID, syncpkg.OpDelete); err != nil {
syncpkg.EncodePlaylistTrackID(syncpkg.FormatUUID(playlistID), syncpkg.FormatUUID(deletedTrackID)), return err
syncpkg.OpDelete); lerr != nil {
return fmt.Errorf("log change: %w", lerr)
} }
if err := tq.RenumberPlaylistTracksAfter(ctx, dbq.RenumberPlaylistTracksAfterParams{ if err := tq.RenumberPlaylistTracksAfter(ctx, dbq.RenumberPlaylistTracksAfterParams{
PlaylistID: playlistID, PlaylistID: playlistID,
@@ -513,37 +452,81 @@ func (s *Service) RemoveTrack(ctx context.Context, callerID, playlistID pgtype.U
}); err != nil { }); err != nil {
return fmt.Errorf("renumber: %w", err) return fmt.Errorf("renumber: %w", err)
} }
if err := tq.UpdatePlaylistRollups(ctx, playlistID); err != nil { }
return nil
})
}
// changeTracks runs change in one transaction on a playlist callerID may
// edit, then updates the playlist's song count and length and redraws its
// cover. A cover that fails to draw is logged, not returned: the change
// has already committed.
func (s *Service) changeTracks(ctx context.Context, callerID, playlistID pgtype.UUID, change func(pgx.Tx) error) error {
if _, err := editable(ctx, dbq.New(s.pool), callerID, playlistID); err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if err := change(tx); err != nil {
return err
}
if err := dbq.New(tx).UpdatePlaylistRollups(ctx, playlistID); err != nil {
return fmt.Errorf("update rollups: %w", err) return fmt.Errorf("update rollups: %w", err)
} }
if err := tx.Commit(ctx); err != nil { if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit: %w", err) return fmt.Errorf("commit: %w", err)
} }
if _, cerr := GenerateCollage(ctx, s.pool, playlistID, s.dataDir); cerr != nil { if _, cerr := GenerateCollage(ctx, s.pool, playlistID, s.dataDir); cerr != nil {
s.logger.Warn("collage regeneration failed", "playlist_id", playlistID, "err", cerr) s.logger.Warn("collage regeneration failed", "playlist_id", playlistID, "err", cerr)
} }
return nil return nil
} }
// appendTracks adds trackIDs at the end of the playlist inside tx. A track
// id that matches no track is ErrTrackNotFound.
func appendTracks(ctx context.Context, tx pgx.Tx, playlistID pgtype.UUID, trackIDs []pgtype.UUID) error {
tq := dbq.New(tx)
for _, tid := range trackIDs {
// The insert selects from tracks, so a missing track inserts
// nothing and the :one query answers pgx.ErrNoRows.
if _, err := tq.AppendPlaylistTrack(ctx, dbq.AppendPlaylistTrackParams{
PlaylistID: playlistID,
TrackID: tid,
}); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return ErrTrackNotFound
}
return fmt.Errorf("append track: %w", err)
}
if err := logTrackChange(ctx, tx, playlistID, tid, syncpkg.OpUpsert); err != nil {
return err
}
}
return nil
}
// logTrackChange records a playlist entry's change for clients that sync,
// in the transaction that makes it.
func logTrackChange(ctx context.Context, tx pgx.Tx, playlistID, trackID pgtype.UUID, op syncpkg.Op) error {
if err := syncpkg.LogChange(ctx, tx, syncpkg.EntityPlaylistTrack,
syncpkg.EncodePlaylistTrackID(syncpkg.FormatUUID(playlistID), syncpkg.FormatUUID(trackID)),
op); err != nil {
return fmt.Errorf("log change: %w", err)
}
return nil
}
// Reorder atomically rewrites all positions to the supplied permutation. // Reorder atomically rewrites all positions to the supplied permutation.
// orderedPositions is the new positional order: if the playlist has 4 // orderedPositions is the new positional order: if the playlist has 4
// tracks at positions [0, 1, 2, 3] and the caller wants the order // tracks at positions [0, 1, 2, 3] and the caller wants the order
// (old[3], old[0], old[1], old[2]), they send [3, 0, 1, 2]. // (old[3], old[0], old[1], old[2]), they send [3, 0, 1, 2].
func (s *Service) Reorder(ctx context.Context, callerID, playlistID pgtype.UUID, orderedPositions []int32) error { func (s *Service) Reorder(ctx context.Context, callerID, playlistID pgtype.UUID, orderedPositions []int32) error {
q := dbq.New(s.pool) pl, err := editable(ctx, dbq.New(s.pool), callerID, playlistID)
pl, err := q.GetPlaylist(ctx, playlistID)
if err != nil { if err != nil {
if errors.Is(err, pgx.ErrNoRows) { return err
return ErrNotFound
}
return fmt.Errorf("get playlist: %w", err)
}
if !pgtypeUUIDEqual(pl.UserID, callerID) {
return ErrForbidden
}
if pl.Kind == "system" {
return ErrSystemPlaylistReadonly
} }
if int32(len(orderedPositions)) != pl.TrackCount { if int32(len(orderedPositions)) != pl.TrackCount {
+38 -10
View File
@@ -153,22 +153,21 @@ func (h *pickHandlers) getPlaylist(w http.ResponseWriter, r *http.Request) {
WriteFail(w, r, ErrGeneric, "Playlist unavailable") WriteFail(w, r, ErrGeneric, "Playlist unavailable")
return return
} }
ids := make([]pgtype.UUID, 0, len(detail.Tracks)) if detail.Kind == "system" && detail.SystemVariant != nil {
for _, t := range detail.Tracks { h.recall.remember(user.ID, r.URL.Query().Get("c"), *detail.SystemVariant)
if t.TrackID != nil && !t.Unavailable {
ids = append(ids, *t.TrackID)
} }
} h.writePlaylist(w, r, detail)
q := dbq.New(h.pool) }
songs, err := songsInOrder(r.Context(), q, ids)
// 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 { if err != nil {
h.logger.Error("subsonic: playlist songs", "err", err) h.logger.Error("subsonic: playlist songs", "err", err)
WriteFail(w, r, ErrGeneric, "Playlist unavailable") WriteFail(w, r, ErrGeneric, "Playlist unavailable")
return 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 := playlistRef(&detail.PlaylistRow)
head.SongCount = len(songs) head.SongCount = len(songs)
head.Duration = 0 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 // 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, // of ids; an id with no track is skipped. One query each for the tracks,
// their albums, their artists and their gains. // 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. // playlist is neither listed nor readable.
func TestGetPlaylists_MixesFirstAndOnlyWhatTheListenerMaySee(t *testing.T) { func TestGetPlaylists_MixesFirstAndOnlyWhatTheListenerMaySee(t *testing.T) {
f := seedPicks(t) f := seedPicks(t)
ctx := context.Background() svc := playlists.NewService(f.pool, nil, t.TempDir())
svc := playlists.NewService(f.pool, nil, "")
newPlaylist := func(owner dbq.User, name string, public bool, songs ...string) pgtype.UUID { newPlaylist := func(owner dbq.User, name string, public bool, songs ...string) pgtype.UUID {
t.Helper() return f.newList(t, svc, owner, name, public, songs...)
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
} }
mine := newPlaylist(f.user, "Road Songs", false, "Inlet", "Jetty", "Dusk") mine := newPlaylist(f.user, "Road Songs", false, "Inlet", "Jetty", "Dusk")
mix := newPlaylist(f.user, "For you", false, "Gale", "Harbour") 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, "/getUser", u.getUser)
register(sub, "/getPlaylists", p.getPlaylists) register(sub, "/getPlaylists", p.getPlaylists)
register(sub, "/getPlaylist", p.getPlaylist) 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, "/getRandomSongs", p.getRandomSongs)
register(sub, "/getSimilarSongs", p.getSimilarSongs) register(sub, "/getSimilarSongs", p.getSimilarSongs)
register(sub, "/getSimilarSongs2", p.getSimilarSongs2) register(sub, "/getSimilarSongs2", p.getSimilarSongs2)