fix(subsonic): answer what the OpenSubsonic spec and Subsonic apps require
- getOpenSubsonicExtensions answers, without credentials, as the spec requires of a server that says openSubsonic=true; it lists apiKeyAuthentication. An apiKey sent with u is error 43 and an unknown apiKey error 44, the extension's codes; a wrong key still counts toward the sign-in throttle. - search3 with an empty query (or two quote marks) matches everything, paged in a stable order, so apps that keep a copy of the library (Symfonium) can download it. A page of songs reads its albums and artists in two queries, not two per song. - getAlbumList2 serves type=starred and highest (the listener's liked albums) and byYear (oldest first, newest first for a backwards range). - Internet radio, podcasts, bookmarks, shares, chat and now-playing answer with an empty list instead of "Method not implemented", so an app shows an empty tab rather than an error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
package subsonic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// mountedRest is the /rest router as the server mounts it. The calls made
|
||||
// against it here never reach the database.
|
||||
func mountedRest() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
Mount(r, nil, slog.New(slog.NewTextHandler(io.Discard, nil)), Config{}, nil, func() int { return 0 })
|
||||
return r
|
||||
}
|
||||
|
||||
func TestGetOpenSubsonicExtensions_AnswersWithoutCredentials(t *testing.T) {
|
||||
h := mountedRest()
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/rest/getOpenSubsonicExtensions.view?f=json", nil))
|
||||
var got struct {
|
||||
Response struct {
|
||||
Status string `json:"status"`
|
||||
OpenSubsonic bool `json:"openSubsonic"`
|
||||
Extensions []OpenSubsonicExtension `json:"openSubsonicExtensions"`
|
||||
} `json:"subsonic-response"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v body=%s", err, w.Body.String())
|
||||
}
|
||||
if got.Response.Status != "ok" || !got.Response.OpenSubsonic {
|
||||
t.Fatalf("status=%q openSubsonic=%v, want ok and true; body=%s", got.Response.Status, got.Response.OpenSubsonic, w.Body.String())
|
||||
}
|
||||
if !slices.ContainsFunc(got.Response.Extensions, func(e OpenSubsonicExtension) bool {
|
||||
return e.Name == "apiKeyAuthentication" && slices.Contains(e.Versions, 1)
|
||||
}) {
|
||||
t.Errorf("extensions = %+v, want apiKeyAuthentication v1", got.Response.Extensions)
|
||||
}
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/rest/getOpenSubsonicExtensions?f=xml", nil))
|
||||
if !strings.Contains(w.Body.String(), `<openSubsonicExtensions name="apiKeyAuthentication"><versions>1</versions></openSubsonicExtensions>`) {
|
||||
t.Errorf("xml body = %s, want an apiKeyAuthentication element", w.Body.String())
|
||||
}
|
||||
|
||||
// Every other method still needs credentials.
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/rest/ping?f=json", nil))
|
||||
if !strings.Contains(w.Body.String(), `"status":"failed"`) || !strings.Contains(w.Body.String(), `"code":10`) {
|
||||
t.Errorf("unauthenticated ping = %s, want a failed response with code 10", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Features Minstrel lacks answer with an empty list an app can render: []
|
||||
// in JSON, never null, and an empty element in XML.
|
||||
func TestEmptyFeatureMethods_AnswerAnEmptyList(t *testing.T) {
|
||||
tests := []struct {
|
||||
handler http.HandlerFunc
|
||||
container string
|
||||
list string
|
||||
}{
|
||||
{handleEmptyInternetRadioStations, "internetRadioStations", "internetRadioStation"},
|
||||
{handleEmptyPodcasts, "podcasts", "channel"},
|
||||
{handleEmptyNewestPodcasts, "newestPodcasts", "episode"},
|
||||
{handleEmptyBookmarks, "bookmarks", "bookmark"},
|
||||
{handleEmptyShares, "shares", "share"},
|
||||
{handleEmptyChatMessages, "chatMessages", "chatMessage"},
|
||||
{handleEmptyNowPlaying, "nowPlaying", "entry"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.container, func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
tc.handler(w, httptest.NewRequest(http.MethodGet, "/rest/x?f=json", nil))
|
||||
var doc map[string]map[string]json.RawMessage
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil {
|
||||
t.Fatalf("decode: %v body=%s", err, w.Body.String())
|
||||
}
|
||||
resp := doc["subsonic-response"]
|
||||
if string(resp["status"]) != `"ok"` {
|
||||
t.Fatalf("status = %s, want ok; body=%s", resp["status"], w.Body.String())
|
||||
}
|
||||
var container map[string]json.RawMessage
|
||||
if err := json.Unmarshal(resp[tc.container], &container); err != nil {
|
||||
t.Fatalf("%s: %v body=%s", tc.container, err, w.Body.String())
|
||||
}
|
||||
if got := string(container[tc.list]); got != "[]" {
|
||||
t.Errorf("%s.%s = %s, want []", tc.container, tc.list, got)
|
||||
}
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
tc.handler(w, httptest.NewRequest(http.MethodGet, "/rest/x?f=xml", nil))
|
||||
var root struct {
|
||||
Status string `xml:"status,attr"`
|
||||
Inner []struct {
|
||||
XMLName xml.Name
|
||||
} `xml:",any"`
|
||||
}
|
||||
if err := xml.Unmarshal(w.Body.Bytes(), &root); err != nil {
|
||||
t.Fatalf("xml: %v body=%s", err, w.Body.String())
|
||||
}
|
||||
if root.Status != "ok" || len(root.Inner) != 1 || root.Inner[0].XMLName.Local != tc.container {
|
||||
t.Errorf("xml body = %s, want ok with one empty <%s>", w.Body.String(), tc.container)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// search3Songs calls search3 with the given query string and returns the
|
||||
// song titles served, or the error code.
|
||||
func (f playHistoryFixture) search3Songs(t *testing.T, query string) (titles []string, code int) {
|
||||
t.Helper()
|
||||
b := &browseHandlers{pool: f.pool}
|
||||
w := httptest.NewRecorder()
|
||||
b.search3(w, httptest.NewRequest(http.MethodGet, "/rest/search3?f=json&artistCount=0&albumCount=0&"+query, nil).
|
||||
WithContext(context.WithValue(context.Background(), userCtxKey, f.user)))
|
||||
var raw struct {
|
||||
Response struct {
|
||||
Status string `json:"status"`
|
||||
Error *Error `json:"error"`
|
||||
Result SearchResult3Container `json:"searchResult3"`
|
||||
} `json:"subsonic-response"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {
|
||||
t.Fatalf("decode: %v body=%s", err, w.Body.String())
|
||||
}
|
||||
if raw.Response.Error != nil {
|
||||
return nil, raw.Response.Error.Code
|
||||
}
|
||||
for _, s := range raw.Response.Result.Songs {
|
||||
titles = append(titles, s.Title)
|
||||
}
|
||||
return titles, 0
|
||||
}
|
||||
|
||||
// An app that keeps a copy of the library downloads it with an empty query,
|
||||
// a page at a time; the pages must cover every song once.
|
||||
func TestSearch3_EmptyQueryPagesThroughEverySong(t *testing.T) {
|
||||
f := seedPlayHistory(t)
|
||||
var all []string
|
||||
for _, offset := range []string{"0", "2", "4", "6"} {
|
||||
page, code := f.search3Songs(t, "query=&songCount=2&songOffset="+offset)
|
||||
if code != 0 {
|
||||
t.Fatalf("empty query, offset %s: error %d", offset, code)
|
||||
}
|
||||
all = append(all, page...)
|
||||
}
|
||||
if want := []string{"A", "B", "C", "D", "E"}; !slices.Equal(all, want) {
|
||||
t.Errorf("songs across pages = %v, want %v", all, want)
|
||||
}
|
||||
if page, code := f.search3Songs(t, `query=""&songCount=2`); code != 0 || !slices.Equal(page, []string{"A", "B"}) {
|
||||
t.Errorf(`query="" = %v (error %d), want the same first page as an empty query`, page, code)
|
||||
}
|
||||
if _, code := f.search3Songs(t, "songCount=2"); code != ErrMissingParameter {
|
||||
t.Errorf("no query parameter: error %d, want %d", code, ErrMissingParameter)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAlbumList2_StarredAndHighestAreTheListenersLikedAlbums(t *testing.T) {
|
||||
f := seedPlayHistory(t)
|
||||
if _, err := f.pool.Exec(context.Background(), `
|
||||
INSERT INTO general_likes_albums (user_id, album_id, liked_at)
|
||||
VALUES ($1, $2, now() - interval '2 days'), ($1, $3, now() - interval '1 day')`,
|
||||
f.user.ID, f.albums["A"].ID, f.albums["B"].ID); err != nil {
|
||||
t.Fatalf("like: %v", err)
|
||||
}
|
||||
for _, listType := range []string{"starred", "highest"} {
|
||||
if got, want := f.albumListTitles(t, "type="+listType), []string{"B", "A"}; !slices.Equal(got, want) {
|
||||
t.Errorf("%s = %v, want %v", listType, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAlbumList2_ByYearOrdersByReleaseAndReversesABackwardsRange(t *testing.T) {
|
||||
f := seedPlayHistory(t)
|
||||
for title, year := range map[string]string{"A": "2001", "B": "1999", "C": "2003", "D": "2010", "E": "2005"} {
|
||||
if _, err := f.pool.Exec(context.Background(),
|
||||
`UPDATE albums SET release_date = make_date($2::int, 6, 1) WHERE id = $1`, f.albums[title].ID, year); err != nil {
|
||||
t.Fatalf("release date: %v", err)
|
||||
}
|
||||
}
|
||||
// C's file is gone, so it is in neither list; B is outside the range.
|
||||
if got, want := f.albumListTitles(t, "type=byYear&fromYear=2000&toYear=2010"), []string{"A", "E", "D"}; !slices.Equal(got, want) {
|
||||
t.Errorf("2000 to 2010 = %v, want %v", got, want)
|
||||
}
|
||||
if got, want := f.albumListTitles(t, "type=byYear&fromYear=2010&toYear=2000"), []string{"D", "E", "A"}; !slices.Equal(got, want) {
|
||||
t.Errorf("2010 to 2000 = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The apiKeyAuthentication extension's own error codes, which apps act on:
|
||||
// 43 for a key sent with a username, 44 for a key that matches no account.
|
||||
func TestAPIKeyAuth_ConflictAndInvalidKeyCodes(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
mountedRest().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/rest/ping?f=json&apiKey=k&u=someone", nil))
|
||||
if !strings.Contains(w.Body.String(), `"code":43`) {
|
||||
t.Errorf("apiKey with u = %s, want error 43", w.Body.String())
|
||||
}
|
||||
|
||||
f := seedPlayHistory(t)
|
||||
h := Middleware(f.pool, Config{}, nil, func() int { return 0 })(http.HandlerFunc(handlePing))
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/rest/ping?f=json&apiKey=not-a-key", nil))
|
||||
if !strings.Contains(w.Body.String(), `"code":44`) {
|
||||
t.Errorf("unknown apiKey = %s, want error 44", w.Body.String())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user