release / web (push) Successful in 1m30s
release / go (push) Successful in 1m59s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m18s
release / android (push) Successful in 4m37s
release / Build signed APK (push) Successful in 5m13s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
390 lines
14 KiB
Go
390 lines
14 KiB
Go
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 struct {
|
|
SimilarSongs SimilarSongsContainer `json:"similarSongs"`
|
|
SimilarSongs2 SimilarSongsContainer `json:"similarSongs2"`
|
|
}
|
|
code := call(t, method, f.user, "count=10&id="+id, &got)
|
|
if key == "similarSongs2" {
|
|
return titles(got.SimilarSongs2.Songs), code
|
|
}
|
|
return titles(got.SimilarSongs.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 <entry> elements, as the Subsonic API names
|
|
// them, while an album's stay <song>.
|
|
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(), `<playlist id="p1" name="Road Songs"`) || !strings.Contains(w.Body.String(), `<entry id="s1"`) {
|
|
t.Errorf("xml = %s, want a playlist element holding entry elements", w.Body.String())
|
|
}
|
|
|
|
album := AlbumResponse{Envelope: NewEnvelope("ok"), Album: AlbumDetail{ID: "a1", Songs: []SongRef{{ID: "s1"}}}}
|
|
w = httptest.NewRecorder()
|
|
Write(w, httptest.NewRequest(http.MethodGet, "/rest/getAlbum?f=xml", nil), album)
|
|
if !strings.Contains(w.Body.String(), `<song id="s1"`) {
|
|
t.Errorf("album xml = %s, want song elements", w.Body.String())
|
|
}
|
|
}
|