diff --git a/README.md b/README.md
index 3bc78934..2e415fb7 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
A self-hosted music server that picks what to play next.
-Minstrel serves your music library to the web, to its own Android app, and to Subsonic apps. Shuffle, radio, likes and play history are worked out on the server, so the web and Android apps get the same mixes and the same history, and what you like and play in a Subsonic app counts too. It is for anyone who keeps their own music collection and wants it to sound like more than a random shuffle.
+Minstrel serves your music library to the web, to its own Android app, and to Subsonic apps. Shuffle, radio, likes and play history are worked out on the server, so the web app, the Android app and Subsonic apps get the same mixes and the same history, and what you like and play in a Subsonic app counts too. It is for anyone who keeps their own music collection and wants it to sound like more than a random shuffle.
@@ -56,7 +56,7 @@ Open `http://: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.
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, but Minstrel's mixes, smart shuffle and radio are not offered to them yet; those are in the web app.
+ **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.
3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token or turn on open registration. Each person gets their own likes, history and recommendations.
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**
- 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.
-- OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse, search, play, like and scrobble. Minstrel's mixes, smart shuffle and radio are not offered to them yet.
+- OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse, search, play, like and scrobble, see the daily mixes and 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.
## Scope and responsible use
diff --git a/internal/api/radio.go b/internal/api/radio.go
index 641ceb58..ebe2b4ec 100644
--- a/internal/api/radio.go
+++ b/internal/api/radio.go
@@ -1,14 +1,10 @@
package api
import (
- "context"
- "encoding/json"
"errors"
- "log/slog"
"net/http"
"strconv"
"strings"
- "time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -26,10 +22,8 @@ type RadioResponse struct {
// handleRadio implements GET /api/radio?seed_track=&limit=.
//
-// Returns the seed at index 0, followed by up to limit-1 weighted-shuffle
-// picks from the user's library, scored by recommendation.Score. The
-// scoring formula folds in contextual_match_score using the user's current
-// session vector (read from the most recent open play_event).
+// Returns the seed at index 0, followed by up to limit-1 picks from
+// recommendation.Picker.Radio.
func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) {
user, ok := requireUser(w, r)
if !ok {
@@ -81,55 +75,15 @@ func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) {
return
}
- currentVec := loadCurrentSessionVector(r, q, user.ID, h.logger)
- // Condition on the current device: the latest play's device is a
- // cheap, request-free proxy for what the user is on right now.
- currentVec.DeviceClass = latestDeviceClass(r.Context(), q, user.ID, h.logger)
-
exclude := parseExcludeParam(r.URL.Query().Get("exclude"))
- // Size the pool to the library: a fixed ~170 candidates samples a shrinking
- // fraction of a growing collection. Degrades to the base limits if the
- // count is unavailable — never fails the request over a sizing hint.
- librarySize := h.librarySize.Get(r.Context(), func(ctx context.Context) (int64, error) {
- return recommendation.CountLibraryTracks(ctx, q)
- })
- limits := recommendation.ScaleForLibrary(
- recommendation.DefaultCandidateSourceLimits(), librarySize,
- )
- candidates, err := recommendation.LoadCandidatesFromSimilarity(
- r.Context(), q, user.ID, seedID,
- h.recCfg.RecentlyPlayedHours, currentVec, exclude, limits,
- // A fresh seed per request: radio is a new session each time
- // and SHOULD draw differently. The system mixes are the surfaces that
- // promise repeatability; this is not one of them.
- strconv.FormatInt(time.Now().UnixNano(), 36),
- )
+ // limit-1 because the seed takes the first slot and is prepended below.
+ picks, err := h.picker().Radio(r.Context(), q, user.ID, seedID, limit-1, exclude)
if err != nil {
- h.logger.Warn("api: radio: similarity-pool failed; falling back to whole-library", "err", err)
- candidates, err = recommendation.LoadCandidates(
- r.Context(), q, user.ID, seedID,
- h.recCfg.RecentlyPlayedHours, currentVec,
- )
- if err != nil {
- h.logger.Error("api: radio: load candidates fallback failed", "err", err)
- writeErr(w, apierror.InternalMsg("candidate load failed", err))
- return
- }
+ h.logger.Error("api: radio: load candidates failed", "err", err)
+ writeErr(w, apierror.InternalMsg("candidate load failed", err))
+ return
}
- // Scoring weights come from the DB-backed tuning —
- // read per request so an admin change takes effect live.
- weights := h.recSettings.Weights(recsettings.ScopeRadio)
- // Diversity caps, so a whole session cannot come back from one artist.
- // Scaled to
- // the requested length so a 20-track radio and a 200-track one are capped
- // alike; Shuffle relaxes them rather than returning a short radio.
- //
- // limit-1 because the seed track occupies the first slot and is prepended
- // below — the caps govern the tracks that FOLLOW it.
- caps := recommendation.RadioDiversityCaps(limit - 1)
- picks := recommendation.Shuffle(candidates, weights, time.Now().UTC(), h.rng, limit-1, caps)
-
out := make([]TrackRef, 0, len(picks)+1)
out = append(out, trackRefFrom(track, album.Title, artist.Name))
for _, p := range picks {
@@ -150,46 +104,16 @@ func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, RadioResponse{Tracks: out})
}
-// loadCurrentSessionVector returns the user's most recent active session
-// vector, or a Seed=true sentinel if none exists / the column is NULL /
-// the JSON fails to unmarshal. Sentinel short-circuits ContextualMatchScore
-// to 0 so the contextual term contributes nothing in cold-start cases.
-func loadCurrentSessionVector(r *http.Request, q *dbq.Queries, userID pgtype.UUID, logger *slog.Logger) recommendation.SessionVector {
- raw, err := q.GetCurrentSessionVectorForUser(r.Context(), userID)
- if err != nil {
- // pgx.ErrNoRows is the common path: no active session yet.
- if !errors.Is(err, pgx.ErrNoRows) {
- logger.Warn("api: radio: load current session vector", "err", err)
- }
- return recommendation.SessionVector{Seed: true}
- }
- if len(raw) == 0 {
- return recommendation.SessionVector{Seed: true}
- }
- var v recommendation.SessionVector
- if jerr := json.Unmarshal(raw, &v); jerr != nil {
- logger.Warn("api: radio: bad session_vector_at_play json", "err", jerr)
- return recommendation.SessionVector{Seed: true}
- }
- return v
-}
-
-// latestDeviceClass returns the device_class of the user's most recent play as
-// the "current device" for context conditioning, or "" when unknown
-// (no plays yet, or the latest play predates device capture). Best-effort: a
-// lookup failure yields a device-agnostic ("") affinity cell.
-func latestDeviceClass(ctx context.Context, q *dbq.Queries, userID pgtype.UUID, logger *slog.Logger) string {
- dc, err := q.GetLatestPlayDeviceClassForUser(ctx, userID)
- if err != nil {
- if !errors.Is(err, pgx.ErrNoRows) {
- logger.Warn("api: radio: latest device class", "err", err)
- }
- return ""
- }
- if dc == nil {
- return ""
- }
- return *dc
+// picker is the shared chooser behind radio, with this server's tuning
+// (recsettings.Service.Picker).
+func (h *handlers) picker() *recommendation.Picker {
+ return h.recSettings.Picker(recsettings.PickerConfig{
+ RecentlyPlayedHours: h.recCfg.RecentlyPlayedHours,
+ MaxLength: h.recCfg.RadioSizeMax,
+ Rand: h.rng,
+ LibrarySize: h.librarySize,
+ Logger: h.logger,
+ })
}
// parseExcludeParam parses a comma-separated list of UUIDs from the
diff --git a/internal/recommendation/radio.go b/internal/recommendation/radio.go
new file mode 100644
index 00000000..ae38710d
--- /dev/null
+++ b/internal/recommendation/radio.go
@@ -0,0 +1,159 @@
+package recommendation
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "strconv"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
+)
+
+// Picker chooses what plays next: a radio after a seed track, or a weighted
+// shuffle of the whole library. Minstrel's own API and the Subsonic API both
+// pick through it, so an app on either one gets the same choices.
+type Picker struct {
+ // Weights returns the scoring weights to use, read on every pick so a
+ // change in the admin tuning applies at once.
+ Weights func() ScoringWeights
+ // Rand is the jitter source for scoring.
+ Rand func() float64
+ // RecentlyPlayedHours keeps a track played this recently out of a pick.
+ RecentlyPlayedHours int
+ // LibrarySize sizes radio's candidate pool to the library. Nil counts on
+ // every pick instead of caching (LibrarySize.Get explains).
+ LibrarySize *LibrarySize
+ // MaxLength is the most tracks one pick returns; 0 leaves it unbounded.
+ MaxLength int
+ Logger *slog.Logger
+}
+
+// bound clamps a requested length to MaxLength.
+func (p *Picker) bound(limit int) int {
+ if p.MaxLength > 0 && limit > p.MaxLength {
+ return p.MaxLength
+ }
+ return limit
+}
+
+func (p *Picker) logger() *slog.Logger {
+ if p.Logger != nil {
+ return p.Logger
+ }
+ return slog.Default()
+}
+
+// Radio returns up to limit tracks to play after seedID, the seed itself not
+// among them. Candidates come from tracks similar to the seed, and fall back
+// to the whole library if that pool cannot be loaded. exclude keeps tracks
+// already queued out.
+func (p *Picker) Radio(ctx context.Context, q *dbq.Queries, userID, seedID pgtype.UUID, limit int, exclude []pgtype.UUID) ([]Candidate, error) {
+ limit = p.bound(limit)
+ if limit <= 0 {
+ return nil, nil
+ }
+ current := p.currentContext(ctx, q, userID)
+ // Size the pool to the library: a fixed ~170 candidates samples a
+ // shrinking fraction of a growing collection.
+ librarySize := p.LibrarySize.Get(ctx, func(ctx context.Context) (int64, error) {
+ return CountLibraryTracks(ctx, q)
+ })
+ limits := ScaleForLibrary(DefaultCandidateSourceLimits(), librarySize)
+ candidates, err := LoadCandidatesFromSimilarity(ctx, q, userID, seedID,
+ p.RecentlyPlayedHours, current, exclude, limits,
+ // A fresh order seed per pick: each radio is a new session and
+ // should draw differently. The system mixes are the surfaces that
+ // promise repeatability; radio is not one of them.
+ strconv.FormatInt(time.Now().UnixNano(), 36),
+ )
+ if err != nil {
+ p.logger().Warn("radio: similarity pool failed; falling back to the whole library", "err", err)
+ candidates, err = LoadCandidates(ctx, q, userID, seedID, p.RecentlyPlayedHours, current)
+ if err != nil {
+ return nil, err
+ }
+ }
+ // Diversity caps scaled to the length asked for, so a 20-track radio
+ // and a 200-track one are capped alike.
+ return Shuffle(candidates, p.Weights(), time.Now().UTC(), p.Rand, limit, RadioDiversityCaps(limit)), nil
+}
+
+// noSeed is a track id no track has. The whole-library candidate query
+// leaves out its seed with `id <> seed`, and a NULL seed would leave out
+// every row, so a shuffle with no seed passes this instead.
+var noSeed = pgtype.UUID{Valid: true}
+
+// Shuffle returns up to limit tracks from the whole library, chosen by the
+// same scoring as radio (what the user likes, skips and has heard lately)
+// rather than at random. keep, when not nil, narrows the library first.
+func (p *Picker) Shuffle(ctx context.Context, q *dbq.Queries, userID pgtype.UUID, limit int, keep func(dbq.Track) bool) ([]Candidate, error) {
+ limit = p.bound(limit)
+ if limit <= 0 {
+ return nil, nil
+ }
+ candidates, err := LoadCandidates(ctx, q, userID, noSeed, p.RecentlyPlayedHours, p.currentContext(ctx, q, userID))
+ if err != nil {
+ return nil, err
+ }
+ if keep != nil {
+ kept := candidates[:0]
+ for _, c := range candidates {
+ if keep(c.Track) {
+ kept = append(kept, c)
+ }
+ }
+ candidates = kept
+ }
+ return Shuffle(candidates, p.Weights(), time.Now().UTC(), p.Rand, limit, RadioDiversityCaps(limit)), nil
+}
+
+// currentContext is what the user is listening in right now: the session
+// vector of their latest open play, conditioned on the device of their latest
+// play. With no session it is the Seed sentinel, which scores the contextual
+// term as nothing.
+func (p *Picker) currentContext(ctx context.Context, q *dbq.Queries, userID pgtype.UUID) SessionVector {
+ v := p.currentSessionVector(ctx, q, userID)
+ v.DeviceClass = p.latestDeviceClass(ctx, q, userID)
+ return v
+}
+
+func (p *Picker) currentSessionVector(ctx context.Context, q *dbq.Queries, userID pgtype.UUID) SessionVector {
+ raw, err := q.GetCurrentSessionVectorForUser(ctx, userID)
+ if err != nil {
+ // No rows is the common case: no session yet.
+ if !errors.Is(err, pgx.ErrNoRows) {
+ p.logger().Warn("radio: load current session vector", "err", err)
+ }
+ return SessionVector{Seed: true}
+ }
+ if len(raw) == 0 {
+ return SessionVector{Seed: true}
+ }
+ var v SessionVector
+ if err := json.Unmarshal(raw, &v); err != nil {
+ p.logger().Warn("radio: bad session_vector_at_play json", "err", err)
+ return SessionVector{Seed: true}
+ }
+ return v
+}
+
+// latestDeviceClass is the device of the user's latest play, or "" when
+// unknown. A failed lookup yields the device-agnostic affinity.
+func (p *Picker) latestDeviceClass(ctx context.Context, q *dbq.Queries, userID pgtype.UUID) string {
+ dc, err := q.GetLatestPlayDeviceClassForUser(ctx, userID)
+ if err != nil {
+ if !errors.Is(err, pgx.ErrNoRows) {
+ p.logger().Warn("radio: latest device class", "err", err)
+ }
+ return ""
+ }
+ if dc == nil {
+ return ""
+ }
+ return *dc
+}
diff --git a/internal/recsettings/picker.go b/internal/recsettings/picker.go
new file mode 100644
index 00000000..d61895a4
--- /dev/null
+++ b/internal/recsettings/picker.go
@@ -0,0 +1,36 @@
+package recsettings
+
+import (
+ "log/slog"
+
+ "git.fabledsword.com/bvandeusen/minstrel/internal/recommendation"
+)
+
+// PickerConfig is what a Picker needs beyond the tuning this service holds.
+type PickerConfig struct {
+ RecentlyPlayedHours int
+ MaxLength int
+ Rand func() float64
+ LibrarySize *recommendation.LibrarySize
+ Logger *slog.Logger
+}
+
+// Picker returns the chooser behind radio and the weighted shuffle, scored by
+// the live radio tuning. Minstrel's API and the Subsonic API both build theirs
+// here, so the two pick alike. A nil service scores with the shipped radio
+// weights.
+func (s *Service) Picker(cfg PickerConfig) *recommendation.Picker {
+ return &recommendation.Picker{
+ Weights: func() recommendation.ScoringWeights {
+ if s == nil {
+ return ShippedRadioWeights()
+ }
+ return s.Weights(ScopeRadio)
+ },
+ Rand: cfg.Rand,
+ RecentlyPlayedHours: cfg.RecentlyPlayedHours,
+ MaxLength: cfg.MaxLength,
+ LibrarySize: cfg.LibrarySize,
+ Logger: cfg.Logger,
+ }
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index 6a26d44e..93f00029 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"log/slog"
+ "math/rand/v2"
"net/http"
"strings"
@@ -26,6 +27,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
"git.fabledsword.com/bvandeusen/minstrel/internal/quarantine"
+ "git.fabledsword.com/bvandeusen/minstrel/internal/recommendation"
"git.fabledsword.com/bvandeusen/minstrel/internal/recsettings"
"git.fabledsword.com/bvandeusen/minstrel/internal/subsonic"
"git.fabledsword.com/bvandeusen/minstrel/internal/tags"
@@ -199,7 +201,15 @@ func (s *Server) Router() http.Handler {
r.With(auth.RequireUser(s.Pool, netSettings.Hops), auth.RequireAdmin()).
Post("/api/admin/scan", s.handleAdminScan)
}
- subsonic.Mount(r, s.Pool, s.Logger, s.SubsonicCfg, writer, netSettings.Hops)
+ // Subsonic apps pick through the same tuning as Minstrel's radio.
+ subsonicPicker := recSettings.Picker(recsettings.PickerConfig{
+ RecentlyPlayedHours: s.RecommendationCfg.RecentlyPlayedHours,
+ MaxLength: s.RecommendationCfg.RadioSizeMax,
+ Rand: rand.Float64,
+ LibrarySize: recommendation.NewLibrarySize(nil),
+ Logger: s.Logger,
+ })
+ subsonic.Mount(r, s.Pool, s.Logger, s.SubsonicCfg, writer, netSettings.Hops, subsonicPicker, playlistsSvc)
}
spa := web.Handler(s.BrandingCfg)
diff --git a/internal/subsonic/mixes.go b/internal/subsonic/mixes.go
new file mode 100644
index 00000000..f6f4a526
--- /dev/null
+++ b/internal/subsonic/mixes.go
@@ -0,0 +1,459 @@
+package subsonic
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "math/rand/v2"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
+ "git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
+ "git.fabledsword.com/bvandeusen/minstrel/internal/recommendation"
+)
+
+// pickHandlers serve what Minstrel chooses for the listener: their playlists
+// and daily mixes, the weighted shuffle, and radio. They answer from the same
+// code as Minstrel's own apps, so a Subsonic app gets the same picks.
+type pickHandlers struct {
+ pool *pgxpool.Pool
+ picker *recommendation.Picker
+ playlists *playlists.Service
+ logger *slog.Logger
+}
+
+// ---- getPlaylists / getPlaylist ----
+
+// PlaylistRef is one playlist in getPlaylists, and the head of getPlaylist.
+type PlaylistRef struct {
+ ID string `json:"id" xml:"id,attr"`
+ Name string `json:"name" xml:"name,attr"`
+ Comment string `json:"comment,omitempty" xml:"comment,attr,omitempty"`
+ Owner string `json:"owner,omitempty" xml:"owner,attr,omitempty"`
+ Public bool `json:"public" xml:"public,attr"`
+ SongCount int `json:"songCount" xml:"songCount,attr"`
+ Duration int `json:"duration" xml:"duration,attr"`
+ Created string `json:"created,omitempty" xml:"created,attr,omitempty"`
+ Changed string `json:"changed,omitempty" xml:"changed,attr,omitempty"`
+ CoverArt string `json:"coverArt,omitempty" xml:"coverArt,attr,omitempty"`
+}
+
+type PlaylistsContainer struct {
+ Playlists []PlaylistRef `json:"playlist" xml:"playlist"`
+}
+
+type PlaylistsResponse struct {
+ Envelope
+ Playlists PlaylistsContainer `json:"playlists" xml:"playlists"`
+}
+
+// PlaylistWithSongs is getPlaylist's body: the playlist and its songs.
+type PlaylistWithSongs struct {
+ PlaylistRef
+ Entries []SongRef `json:"entry" xml:"entry"`
+}
+
+type PlaylistResponse struct {
+ Envelope
+ Playlist PlaylistWithSongs `json:"playlist" xml:"playlist"`
+}
+
+// playlistRef converts a playlist row. Its cover is the first album cover in
+// it: getCoverArt answers for an album id, and a Subsonic app shows that.
+func playlistRef(p *playlists.PlaylistRow) PlaylistRef {
+ ref := PlaylistRef{
+ ID: uuidToID(p.ID),
+ Name: p.Name,
+ Comment: p.Description,
+ Owner: p.OwnerUsername,
+ Public: p.IsPublic,
+ SongCount: int(p.TrackCount),
+ Duration: int(p.DurationSec),
+ Created: timestamptzToRFC3339(p.CreatedAt),
+ Changed: timestamptzToRFC3339(p.UpdatedAt),
+ }
+ if len(p.CoverAlbumIDs) > 0 {
+ ref.CoverArt = uuidToID(p.CoverAlbumIDs[0])
+ }
+ return ref
+}
+
+// getPlaylists lists the caller's daily mixes first, then their own
+// playlists, then other people's public ones. The mixes lead because they are
+// what Minstrel makes fresh each day; within each group the service's order
+// (most recently changed first) stands.
+func (h *pickHandlers) getPlaylists(w http.ResponseWriter, r *http.Request) {
+ user, ok := UserFromContext(r.Context())
+ if !ok {
+ WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
+ return
+ }
+ rows, err := h.playlists.List(r.Context(), user.ID)
+ if err != nil {
+ h.logger.Error("subsonic: list playlists", "err", err)
+ WriteFail(w, r, ErrGeneric, "Playlists unavailable")
+ return
+ }
+ var mixes, own, others []PlaylistRef
+ for i := range rows {
+ p := &rows[i]
+ switch {
+ case p.UserID != user.ID:
+ others = append(others, playlistRef(p))
+ case p.Kind == "system":
+ mixes = append(mixes, playlistRef(p))
+ default:
+ own = append(own, playlistRef(p))
+ }
+ }
+ out := make([]PlaylistRef, 0, len(rows))
+ out = append(append(append(out, mixes...), own...), others...)
+ Write(w, r, PlaylistsResponse{
+ Envelope: NewEnvelope("ok"),
+ Playlists: PlaylistsContainer{Playlists: out},
+ })
+}
+
+// getPlaylist returns one playlist and its songs in playlist order. A song
+// whose file is missing, or that has left the library, keeps its place in
+// Minstrel but is not listed here, since a Subsonic app would try to play it.
+func (h *pickHandlers) getPlaylist(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
+ }
+ id, ok := parseUUID(raw)
+ if !ok {
+ WriteFail(w, r, ErrDataNotFound, "Playlist not found")
+ return
+ }
+ detail, err := h.playlists.Get(r.Context(), user.ID, id)
+ if err != nil {
+ // Someone else's private playlist reads as absent, as it does in
+ // the list.
+ if errors.Is(err, playlists.ErrNotFound) || errors.Is(err, playlists.ErrForbidden) {
+ WriteFail(w, r, ErrDataNotFound, "Playlist not found")
+ return
+ }
+ h.logger.Error("subsonic: get playlist", "err", err)
+ 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)
+ }
+ }
+ q := dbq.New(h.pool)
+ songs, err := songsInOrder(r.Context(), q, ids)
+ if err != nil {
+ h.logger.Error("subsonic: playlist songs", "err", err)
+ WriteFail(w, r, ErrGeneric, "Playlist unavailable")
+ return
+ }
+ head := playlistRef(&detail.PlaylistRow)
+ head.SongCount = len(songs)
+ head.Duration = 0
+ for _, s := range songs {
+ head.Duration += s.Duration
+ }
+ Write(w, r, PlaylistResponse{
+ Envelope: NewEnvelope("ok"),
+ Playlist: PlaylistWithSongs{PlaylistRef: head, Entries: songs},
+ })
+}
+
+// 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.
+func songsInOrder(ctx context.Context, q *dbq.Queries, ids []pgtype.UUID) ([]SongRef, error) {
+ if len(ids) == 0 {
+ return []SongRef{}, nil
+ }
+ rows, err := q.GetTracksByIDs(ctx, ids)
+ if err != nil {
+ return nil, err
+ }
+ byID := make(map[pgtype.UUID]dbq.Track, len(rows))
+ for _, t := range rows {
+ byID[t.ID] = t
+ }
+ tracks := make([]dbq.Track, 0, len(ids))
+ for _, id := range ids {
+ if t, ok := byID[id]; ok {
+ tracks = append(tracks, t)
+ }
+ }
+ return songRefs(ctx, q, tracks)
+}
+
+// songRefs converts tracks to songs, keeping their order.
+func songRefs(ctx context.Context, q *dbq.Queries, tracks []dbq.Track) ([]SongRef, error) {
+ albumTitles, artistNames, err := songParents(ctx, q, tracks)
+ if err != nil {
+ return nil, err
+ }
+ gains := replayGains(ctx, q, tracks)
+ out := make([]SongRef, 0, len(tracks))
+ for _, t := range tracks {
+ out = append(out, songRef(t, albumTitles[t.AlbumID], artistNames[t.ArtistID], gains[t.ID]))
+ }
+ return out, nil
+}
+
+func candidateTracks(picks []recommendation.Candidate) []dbq.Track {
+ out := make([]dbq.Track, len(picks))
+ for i, p := range picks {
+ out[i] = p.Track
+ }
+ return out
+}
+
+// ---- getRandomSongs ----
+
+type RandomSongsContainer struct {
+ Songs []SongRef `json:"song" xml:"song"`
+}
+
+type RandomSongsResponse struct {
+ Envelope
+ RandomSongs RandomSongsContainer `json:"randomSongs" xml:"randomSongs"`
+}
+
+// getRandomSongs is a Subsonic app's shuffle. Minstrel answers with its
+// weighted shuffle, the one its own apps use: songs the listener likes come
+// up more, songs they skip less, and songs heard in the last hour not at all.
+// size defaults to 10, as the Subsonic API defines it, and is capped at the
+// server's radio length. genre, fromYear and toYear narrow the library first.
+func (h *pickHandlers) getRandomSongs(w http.ResponseWriter, r *http.Request) {
+ user, ok := UserFromContext(r.Context())
+ if !ok {
+ WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
+ return
+ }
+ params := r.URL.Query()
+ size := clampInt(atoiDefault(params.Get("size"), 10), 1, 500)
+ q := dbq.New(h.pool)
+ keep, err := randomSongsFilter(r.Context(), q, params.Get("genre"), params.Get("fromYear"), params.Get("toYear"))
+ if err != nil {
+ h.logger.Error("subsonic: random songs filter", "err", err)
+ WriteFail(w, r, ErrGeneric, "Shuffle unavailable")
+ return
+ }
+ picks, err := h.picker.Shuffle(r.Context(), q, user.ID, size, keep)
+ if err != nil {
+ h.logger.Error("subsonic: random songs", "err", err)
+ WriteFail(w, r, ErrGeneric, "Shuffle unavailable")
+ return
+ }
+ songs, err := songRefs(r.Context(), q, candidateTracks(picks))
+ if err != nil {
+ h.logger.Error("subsonic: random songs", "err", err)
+ WriteFail(w, r, ErrGeneric, "Shuffle unavailable")
+ return
+ }
+ Write(w, r, RandomSongsResponse{
+ Envelope: NewEnvelope("ok"),
+ RandomSongs: RandomSongsContainer{Songs: songs},
+ })
+}
+
+// randomSongsFilter builds getRandomSongs' narrowing, or nil when nothing
+// narrows. A genre matches each of a track's genres, split on ; and , the way
+// getAlbumList2 byGenre splits them, so "Rock" reaches a track tagged
+// "Rock;Pop". The years are an album's release year, inclusive; either end
+// may be left open.
+func randomSongsFilter(ctx context.Context, q *dbq.Queries, genre, fromYear, toYear string) (func(dbq.Track) bool, error) {
+ genre = strings.TrimSpace(genre)
+ var albums map[pgtype.UUID]bool
+ if fromYear != "" || toYear != "" {
+ from, ferr := strconv.Atoi(fromYear)
+ if ferr != nil {
+ from = 0
+ }
+ to, terr := strconv.Atoi(toYear)
+ if terr != nil {
+ to = 9999
+ }
+ inRange, err := q.ListAlbumsByYearOrdered(ctx, dbq.ListAlbumsByYearOrderedParams{
+ FromYear: int32(from), ToYear: int32(to), Lim: 1 << 30, Off: 0,
+ })
+ if err != nil {
+ return nil, err
+ }
+ albums = make(map[pgtype.UUID]bool, len(inRange))
+ for _, a := range inRange {
+ albums[a.ID] = true
+ }
+ }
+ if genre == "" && albums == nil {
+ return nil, nil
+ }
+ return func(t dbq.Track) bool {
+ if albums != nil && !albums[t.AlbumID] {
+ return false
+ }
+ return genre == "" || hasGenre(t.Genre, genre)
+ }, nil
+}
+
+func hasGenre(tagged *string, genre string) bool {
+ if tagged == nil {
+ return false
+ }
+ for _, g := range strings.FieldsFunc(*tagged, func(r rune) bool { return r == ';' || r == ',' }) {
+ if strings.EqualFold(strings.TrimSpace(g), genre) {
+ return true
+ }
+ }
+ return false
+}
+
+// ---- getSimilarSongs / getSimilarSongs2 ----
+
+type SimilarSongsContainer struct {
+ Songs []SongRef `json:"song" xml:"song"`
+}
+
+type SimilarSongsResponse struct {
+ Envelope
+ SimilarSongs SimilarSongsContainer `json:"similarSongs" xml:"similarSongs"`
+}
+
+type SimilarSongs2Response struct {
+ Envelope
+ SimilarSongs2 SimilarSongsContainer `json:"similarSongs2" xml:"similarSongs2"`
+}
+
+// getSimilarSongs is a Subsonic app's radio, or "instant mix". Minstrel
+// answers with its own radio. id may be a song, an album or an artist; an
+// album or artist seeds the radio from one of its songs, picked at random.
+// count defaults to 50, as the Subsonic API defines it. The seed song is not
+// in the answer: the app plays it already.
+func (h *pickHandlers) getSimilarSongs(w http.ResponseWriter, r *http.Request) {
+ songs, ok := h.similar(w, r, true)
+ if !ok {
+ return
+ }
+ Write(w, r, SimilarSongsResponse{
+ Envelope: NewEnvelope("ok"),
+ SimilarSongs: SimilarSongsContainer{Songs: songs},
+ })
+}
+
+// getSimilarSongs2 is getSimilarSongs for an artist id, as the ID3 browse
+// methods give.
+func (h *pickHandlers) getSimilarSongs2(w http.ResponseWriter, r *http.Request) {
+ songs, ok := h.similar(w, r, false)
+ if !ok {
+ return
+ }
+ Write(w, r, SimilarSongs2Response{
+ Envelope: NewEnvelope("ok"),
+ SimilarSongs2: SimilarSongsContainer{Songs: songs},
+ })
+}
+
+// similar runs radio for the request's id. anyKind also accepts a song or an
+// album id; otherwise only an artist id is a seed. It writes the failure
+// itself and reports false when there is nothing to answer.
+func (h *pickHandlers) similar(w http.ResponseWriter, r *http.Request, anyKind bool) ([]SongRef, bool) {
+ user, ok := UserFromContext(r.Context())
+ if !ok {
+ WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
+ return nil, false
+ }
+ params := r.URL.Query()
+ raw := params.Get("id")
+ if raw == "" {
+ WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
+ return nil, false
+ }
+ id, ok := parseUUID(raw)
+ if !ok {
+ WriteFail(w, r, ErrDataNotFound, "Not found")
+ return nil, false
+ }
+ count := clampInt(atoiDefault(params.Get("count"), 50), 1, 500)
+ q := dbq.New(h.pool)
+ seed, found, err := radioSeed(r.Context(), q, user.ID, id, anyKind)
+ if err != nil {
+ h.logger.Error("subsonic: similar songs seed", "err", err)
+ WriteFail(w, r, ErrGeneric, "Radio unavailable")
+ return nil, false
+ }
+ if !found {
+ WriteFail(w, r, ErrDataNotFound, "Not found")
+ return nil, false
+ }
+ picks, err := h.picker.Radio(r.Context(), q, user.ID, seed, count, nil)
+ if err != nil {
+ h.logger.Error("subsonic: similar songs", "err", err)
+ WriteFail(w, r, ErrGeneric, "Radio unavailable")
+ return nil, false
+ }
+ songs, err := songRefs(r.Context(), q, candidateTracks(picks))
+ if err != nil {
+ h.logger.Error("subsonic: similar songs", "err", err)
+ WriteFail(w, r, ErrGeneric, "Radio unavailable")
+ return nil, false
+ }
+ return songs, true
+}
+
+// radioSeed finds the song a radio starts from. A song id is its own seed; an
+// album or an artist gives one of its playable songs at random, so asking
+// twice for the same artist need not start from the same song.
+func radioSeed(ctx context.Context, q *dbq.Queries, userID, id pgtype.UUID, anyKind bool) (pgtype.UUID, bool, error) {
+ if anyKind {
+ if t, err := q.GetTrackByID(ctx, id); err == nil && !t.MissingSince.Valid {
+ return t.ID, true, nil
+ }
+ if _, err := q.GetAlbumByID(ctx, id); err == nil {
+ tracks, err := q.ListTracksByAlbum(ctx, dbq.ListTracksByAlbumParams{AlbumID: id, UserID: userID})
+ if err != nil {
+ return pgtype.UUID{}, false, err
+ }
+ ids := make([]pgtype.UUID, 0, len(tracks))
+ for _, t := range tracks {
+ if !t.MissingSince.Valid {
+ ids = append(ids, t.ID)
+ }
+ }
+ return pickOne(ids)
+ }
+ }
+ if _, err := q.GetArtistByID(ctx, id); err != nil {
+ return pgtype.UUID{}, false, nil
+ }
+ rows, err := q.ListArtistTracksForUser(ctx, dbq.ListArtistTracksForUserParams{ArtistID: id, UserID: userID})
+ if err != nil {
+ return pgtype.UUID{}, false, err
+ }
+ ids := make([]pgtype.UUID, 0, len(rows))
+ for _, row := range rows {
+ if !row.Track.MissingSince.Valid {
+ ids = append(ids, row.Track.ID)
+ }
+ }
+ return pickOne(ids)
+}
+
+func pickOne(ids []pgtype.UUID) (pgtype.UUID, bool, error) {
+ if len(ids) == 0 {
+ return pgtype.UUID{}, false, nil
+ }
+ return ids[rand.IntN(len(ids))], true, nil
+}
diff --git a/internal/subsonic/mixes_test.go b/internal/subsonic/mixes_test.go
new file mode 100644
index 00000000..7a2bb5b3
--- /dev/null
+++ b/internal/subsonic/mixes_test.go
@@ -0,0 +1,383 @@
+package subsonic
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "math/rand/v2"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "slices"
+ "strings"
+ "testing"
+
+ "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"
+ "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
+ "git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
+ "git.fabledsword.com/bvandeusen/minstrel/internal/recsettings"
+)
+
+func TestHasGenre_SplitsTheTagLikeByGenre(t *testing.T) {
+ tag := func(s string) *string { return &s }
+ cases := []struct {
+ tagged *string
+ genre string
+ want bool
+ }{
+ {tag("Jazz"), "Jazz", true},
+ {tag("Rock;Jazz"), "jazz", true},
+ {tag("Rock, Jazz"), "Jazz", true},
+ {tag("Jazz Fusion"), "Jazz", false},
+ {tag(""), "Jazz", false},
+ {nil, "Jazz", false},
+ }
+ for _, c := range cases {
+ if got := hasGenre(c.tagged, c.genre); got != c.want {
+ t.Errorf("hasGenre(%v, %q) = %v, want %v", c.tagged, c.genre, got, c.want)
+ }
+ }
+}
+
+// picksFixture is a small library and a listener with playlists:
+//
+// Lantern Hours (1999): Dusk (Jazz), Ember (Jazz;Funk), Flint (Rock)
+// Paper Boats (2012): Gale (Rock), Harbour (Jazz), Inlet (Rock)
+// Gone Tide (2012): Jetty (Jazz), whose file is missing
+//
+// Ember is quarantined by the listener, and Flint was played ten minutes
+// ago, so neither is a shuffle or radio pick.
+type picksFixture struct {
+ pool *pgxpool.Pool
+ user dbq.User
+ other dbq.User
+ tracks map[string]dbq.Track
+ albums map[string]dbq.Album
+ artist dbq.Artist
+}
+
+func seedPicks(t *testing.T) picksFixture {
+ t.Helper()
+ if testing.Short() {
+ t.Skip("skipping in -short mode")
+ }
+ dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL")
+ if dsn == "" {
+ t.Skip("MINSTREL_TEST_DATABASE_URL not set")
+ }
+ if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil {
+ t.Fatalf("migrate: %v", err)
+ }
+ pool, err := pgxpool.New(context.Background(), dsn)
+ if err != nil {
+ t.Fatalf("pool: %v", err)
+ }
+ t.Cleanup(pool.Close)
+ dbtest.ResetDB(t, pool)
+
+ ctx := context.Background()
+ q := dbq.New(pool)
+ f := picksFixture{pool: pool, tracks: map[string]dbq.Track{}, albums: map[string]dbq.Album{}}
+ if f.user, err = q.CreateUser(ctx, dbq.CreateUserParams{
+ Username: dbtest.TestUserPrefix + "listener", PasswordHash: "x", ApiTokenHash: "x",
+ }); err != nil {
+ t.Fatalf("create user: %v", err)
+ }
+ if f.other, err = q.CreateUser(ctx, dbq.CreateUserParams{
+ Username: dbtest.TestUserPrefix + "other", PasswordHash: "x", ApiTokenHash: "y",
+ }); err != nil {
+ t.Fatalf("create other: %v", err)
+ }
+ if f.artist, err = q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Tin Orchard", SortName: "Tin Orchard"}); err != nil {
+ t.Fatalf("artist: %v", err)
+ }
+ albums := []struct {
+ title string
+ year int
+ songs [][2]string // title, genre
+ }{
+ {"Lantern Hours", 1999, [][2]string{{"Dusk", "Jazz"}, {"Ember", "Jazz;Funk"}, {"Flint", "Rock"}}},
+ {"Paper Boats", 2012, [][2]string{{"Gale", "Rock"}, {"Harbour", "Jazz"}, {"Inlet", "Rock"}}},
+ {"Gone Tide", 2012, [][2]string{{"Jetty", "Jazz"}}},
+ }
+ for _, a := range albums {
+ al, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: a.title, SortTitle: a.title, ArtistID: f.artist.ID})
+ if err != nil {
+ t.Fatalf("album %s: %v", a.title, err)
+ }
+ if _, err := pool.Exec(ctx, `UPDATE albums SET release_date = make_date($2::int, 6, 1) WHERE id = $1`, al.ID, a.year); err != nil {
+ t.Fatalf("release date: %v", err)
+ }
+ f.albums[a.title] = al
+ for i, s := range a.songs {
+ genre := s[1]
+ n := int32(i + 1)
+ tr, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
+ Title: s[0], AlbumID: al.ID, ArtistID: f.artist.ID, Genre: &genre, TrackNumber: &n,
+ FilePath: "/tmp/picks-" + s[0] + ".flac", DurationMs: 200_000,
+ })
+ if err != nil {
+ t.Fatalf("track %s: %v", s[0], err)
+ }
+ f.tracks[s[0]] = tr
+ }
+ }
+ f.exec(t, `UPDATE tracks SET missing_since = now() WHERE id = $1`, f.tracks["Jetty"].ID)
+ f.exec(t, `INSERT INTO quarantine (user_id, track_id, reason) VALUES ($1, $2, 'bad_rip')`, f.user.ID, f.tracks["Ember"].ID)
+ var session pgtype.UUID
+ if err := pool.QueryRow(ctx, `INSERT INTO play_sessions (user_id, started_at, last_event_at, client_id)
+ VALUES ($1, now() - interval '10 minutes', now() - interval '10 minutes', 'picks-test') RETURNING id`,
+ f.user.ID).Scan(&session); err != nil {
+ t.Fatalf("play session: %v", err)
+ }
+ f.exec(t, `INSERT INTO play_events (user_id, track_id, session_id, started_at) VALUES ($1, $2, $3, now() - interval '10 minutes')`,
+ f.user.ID, f.tracks["Flint"].ID, session)
+ return f
+}
+
+func (f picksFixture) exec(t *testing.T, sql string, args ...any) {
+ t.Helper()
+ if _, err := f.pool.Exec(context.Background(), sql, args...); err != nil {
+ t.Fatalf("%s: %v", sql, err)
+ }
+}
+
+func (f picksFixture) handlers() *pickHandlers {
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ return &pickHandlers{
+ pool: f.pool,
+ // A nil tuning service scores with the shipped radio weights.
+ picker: (*recsettings.Service)(nil).Picker(recsettings.PickerConfig{
+ RecentlyPlayedHours: 1, MaxLength: 200, Rand: rand.Float64, Logger: logger,
+ }),
+ // Listing and reading playlists touch no collage files, so no data
+ // directory is needed.
+ playlists: playlists.NewService(f.pool, logger, ""),
+ logger: logger,
+ }
+}
+
+// call runs a handler as user and decodes the JSON body into out. It returns
+// the Subsonic error code, 0 on success.
+func call(t *testing.T, h func(http.ResponseWriter, *http.Request), user dbq.User, query string, out any) int {
+ t.Helper()
+ w := httptest.NewRecorder()
+ h(w, httptest.NewRequest(http.MethodGet, "/rest/x?f=json&"+query, nil).
+ WithContext(context.WithValue(context.Background(), userCtxKey, user)))
+ var env struct {
+ Response json.RawMessage `json:"subsonic-response"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
+ t.Fatalf("decode: %v body=%s", err, w.Body.String())
+ }
+ var status struct {
+ Status string `json:"status"`
+ Error *Error `json:"error"`
+ }
+ if err := json.Unmarshal(env.Response, &status); err != nil {
+ t.Fatalf("decode status: %v", err)
+ }
+ if status.Error != nil {
+ return status.Error.Code
+ }
+ if status.Status != "ok" {
+ t.Fatalf("status %q, body=%s", status.Status, w.Body.String())
+ }
+ if out != nil {
+ if err := json.Unmarshal(env.Response, out); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ }
+ return 0
+}
+
+func titles(songs []SongRef) []string {
+ out := make([]string, len(songs))
+ for i, s := range songs {
+ out[i] = s.Title
+ }
+ return out
+}
+
+func (f picksFixture) randomSongs(t *testing.T, query string) []string {
+ t.Helper()
+ var got struct {
+ RandomSongs RandomSongsContainer `json:"randomSongs"`
+ }
+ if code := call(t, f.handlers().getRandomSongs, f.user, query, &got); code != 0 {
+ t.Fatalf("getRandomSongs %s: error %d", query, code)
+ }
+ return titles(got.RandomSongs.Songs)
+}
+
+// The shuffle is the whole playable library, less what the listener has
+// quarantined and what they heard in the last hour.
+func TestGetRandomSongs_IsTheWeightedShuffleOfThePlayableLibrary(t *testing.T) {
+ f := seedPicks(t)
+ got := f.randomSongs(t, "size=50")
+ slices.Sort(got)
+ if want := []string{"Dusk", "Gale", "Harbour", "Inlet"}; !slices.Equal(got, want) {
+ t.Errorf("songs = %v, want %v", got, want)
+ }
+ if got := f.randomSongs(t, "size=2"); len(got) != 2 || got[0] == got[1] {
+ t.Errorf("size=2 = %v, want two different songs", got)
+ }
+ if got := f.randomSongs(t, ""); len(got) != 4 {
+ t.Errorf("no size = %v, want every playable song (fewer than the default of 10)", got)
+ }
+}
+
+func TestGetRandomSongs_NarrowsByGenreAndYear(t *testing.T) {
+ f := seedPicks(t)
+ got := f.randomSongs(t, "size=50&genre=jazz")
+ slices.Sort(got)
+ if want := []string{"Dusk", "Harbour"}; !slices.Equal(got, want) {
+ t.Errorf("genre=jazz = %v, want %v", got, want)
+ }
+ got = f.randomSongs(t, "size=50&fromYear=2000")
+ slices.Sort(got)
+ if want := []string{"Gale", "Harbour", "Inlet"}; !slices.Equal(got, want) {
+ t.Errorf("fromYear=2000 = %v, want %v", got, want)
+ }
+ if got := f.randomSongs(t, "size=50&toYear=2000&genre=Rock"); len(got) != 0 {
+ t.Errorf("rock before 2000 = %v, want none (Flint was just played)", got)
+ }
+}
+
+func (f picksFixture) similar(t *testing.T, method func(http.ResponseWriter, *http.Request), key, id string) ([]string, int) {
+ t.Helper()
+ var got map[string]SimilarSongsContainer
+ code := call(t, method, f.user, "count=10&id="+id, &got)
+ return titles(got[key].Songs), code
+}
+
+// Radio from a song, an album or an artist: every pick is playable, and the
+// seed song is not repeated back.
+func TestGetSimilarSongs_IsRadioFromASongAlbumOrArtist(t *testing.T) {
+ f := seedPicks(t)
+ h := f.handlers()
+ unplayable := []string{"Ember", "Flint", "Jetty"}
+ check := func(name string, got []string, code int, seed string) {
+ t.Helper()
+ if code != 0 {
+ t.Fatalf("%s: error %d", name, code)
+ }
+ if len(got) == 0 {
+ t.Fatalf("%s: no songs", name)
+ }
+ for _, s := range got {
+ if slices.Contains(unplayable, s) || s == seed {
+ t.Errorf("%s: %q among %v", name, s, got)
+ }
+ }
+ }
+ got, code := f.similar(t, h.getSimilarSongs, "similarSongs", uuidToID(f.tracks["Dusk"].ID))
+ check("song", got, code, "Dusk")
+ got, code = f.similar(t, h.getSimilarSongs, "similarSongs", uuidToID(f.albums["Paper Boats"].ID))
+ check("album", got, code, "")
+ got, code = f.similar(t, h.getSimilarSongs2, "similarSongs2", uuidToID(f.artist.ID))
+ check("artist", got, code, "")
+
+ // getSimilarSongs2 takes only an artist; a missing song is no seed.
+ if _, code := f.similar(t, h.getSimilarSongs2, "similarSongs2", uuidToID(f.tracks["Dusk"].ID)); code != ErrDataNotFound {
+ t.Errorf("getSimilarSongs2 with a song id: error %d, want %d", code, ErrDataNotFound)
+ }
+ if _, code := f.similar(t, h.getSimilarSongs, "similarSongs", uuidToID(f.albums["Gone Tide"].ID)); code != ErrDataNotFound {
+ t.Errorf("an album whose only file is missing: error %d, want %d", code, ErrDataNotFound)
+ }
+}
+
+// getPlaylists leads with the listener's daily mixes, then their own
+// playlists, then other people's public ones; someone else's private
+// playlist is neither listed nor readable.
+func TestGetPlaylists_MixesFirstAndOnlyWhatTheListenerMaySee(t *testing.T) {
+ f := seedPicks(t)
+ ctx := context.Background()
+ svc := playlists.NewService(f.pool, nil, "")
+ 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
+ }
+ mine := newPlaylist(f.user, "Road Songs", false, "Inlet", "Jetty", "Dusk")
+ mix := newPlaylist(f.user, "For you", false, "Gale", "Harbour")
+ f.exec(t, `UPDATE playlists SET kind = 'system', system_variant = 'for_you' WHERE id = $1`, mix)
+ shared := newPlaylist(f.other, "Shared", true, "Gale")
+ secret := newPlaylist(f.other, "Secret", false, "Gale")
+
+ h := f.handlers()
+ var list struct {
+ Playlists PlaylistsContainer `json:"playlists"`
+ }
+ if code := call(t, h.getPlaylists, f.user, "", &list); code != 0 {
+ t.Fatalf("getPlaylists: error %d", code)
+ }
+ var names []string
+ for _, p := range list.Playlists.Playlists {
+ names = append(names, p.Name)
+ }
+ if want := []string{"For you", "Road Songs", "Shared"}; !slices.Equal(names, want) {
+ t.Errorf("playlists = %v, want %v", names, want)
+ }
+
+ // Jetty's file is missing, so a Subsonic app is not offered it.
+ var one struct {
+ Playlist PlaylistWithSongs `json:"playlist"`
+ }
+ if code := call(t, h.getPlaylist, f.user, "id="+uuidToID(mine), &one); code != 0 {
+ t.Fatalf("getPlaylist: error %d", code)
+ }
+ if got, want := titles(one.Playlist.Entries), []string{"Inlet", "Dusk"}; !slices.Equal(got, want) {
+ t.Errorf("entries = %v, want %v", got, want)
+ }
+ if one.Playlist.SongCount != 2 || one.Playlist.Duration != 400 {
+ t.Errorf("songCount %d duration %d, want 2 and 400", one.Playlist.SongCount, one.Playlist.Duration)
+ }
+ if code := call(t, h.getPlaylist, f.user, "id="+uuidToID(shared), nil); code != 0 {
+ t.Errorf("someone's public playlist: error %d", code)
+ }
+ if code := call(t, h.getPlaylist, f.user, "id="+uuidToID(secret), nil); code != ErrDataNotFound {
+ t.Errorf("someone's private playlist: error %d, want %d", code, ErrDataNotFound)
+ }
+}
+
+// In XML a playlist's songs are elements, as the Subsonic API names
+// them, while an album's stay .
+func TestPlaylistXML_SongsAreEntries(t *testing.T) {
+ body := PlaylistResponse{
+ Envelope: NewEnvelope("ok"),
+ Playlist: PlaylistWithSongs{
+ PlaylistRef: PlaylistRef{ID: "p1", Name: "Road Songs", SongCount: 1},
+ Entries: []SongRef{{ID: "s1", Title: "Inlet", Type: "music"}},
+ },
+ }
+ w := httptest.NewRecorder()
+ Write(w, httptest.NewRequest(http.MethodGet, "/rest/getPlaylist?f=xml", nil), body)
+ if !strings.Contains(w.Body.String(), `