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:
2026-11-25 13:14:31 -05:00
co-authored by Claude Opus 5.5
parent 1efc65ee10
commit cd78529ae8
14 changed files with 575 additions and 50 deletions
+1 -1
View File
@@ -1000,7 +1000,7 @@ func (q *Queries) ListRecentlyAddedAlbumsWithArtist(ctx context.Context, limit i
const searchAlbums = `-- name: SearchAlbums :many const searchAlbums = `-- name: SearchAlbums :many
SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid, announced_at FROM albums SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid, announced_at FROM albums
WHERE title ILIKE '%' || $1 || '%' WHERE title ILIKE '%' || $1 || '%'
ORDER BY sort_title ORDER BY sort_title, id
LIMIT $2 OFFSET $3 LIMIT $2 OFFSET $3
` `
+1 -1
View File
@@ -441,7 +441,7 @@ func (q *Queries) ListTrackArtistsForAlbum(ctx context.Context, albumID pgtype.U
const searchArtists = `-- name: SearchArtists :many const searchArtists = `-- name: SearchArtists :many
SELECT id, name, sort_name, mbid, created_at, updated_at, artist_thumb_path, artist_fanart_path, artist_art_source, artist_art_sources_version FROM artists SELECT id, name, sort_name, mbid, created_at, updated_at, artist_thumb_path, artist_fanart_path, artist_art_source, artist_art_sources_version FROM artists
WHERE name ILIKE '%' || $1 || '%' WHERE name ILIKE '%' || $1 || '%'
ORDER BY sort_name ORDER BY sort_name, id
LIMIT $2 OFFSET $3 LIMIT $2 OFFSET $3
` `
+66
View File
@@ -166,6 +166,72 @@ func (q *Queries) ListAlbumsByGenreWithArtist(ctx context.Context, arg ListAlbum
return items, nil return items, nil
} }
const listAlbumsByYearOrdered = `-- name: ListAlbumsByYearOrdered :many
SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at FROM albums
WHERE albums.release_date IS NOT NULL
AND EXTRACT(YEAR FROM albums.release_date)::int
BETWEEN LEAST($1::int, $2::int)
AND GREATEST($1::int, $2::int)
AND EXISTS (
SELECT 1 FROM tracks
WHERE tracks.album_id = albums.id
AND tracks.missing_since IS NULL
)
ORDER BY CASE WHEN $1::int <= $2::int THEN albums.release_date END ASC,
CASE WHEN $1::int > $2::int THEN albums.release_date END DESC,
albums.sort_title, albums.id
LIMIT $4 OFFSET $3
`
type ListAlbumsByYearOrderedParams struct {
FromYear int32
ToYear int32
Off int32
Lim int32
}
// Subsonic getAlbumList2 type=byYear: albums released within an inclusive
// year range, oldest first, or newest first when the caller asks for the
// range backwards (fromYear > toYear), as the Subsonic API defines it.
func (q *Queries) ListAlbumsByYearOrdered(ctx context.Context, arg ListAlbumsByYearOrderedParams) ([]Album, error) {
rows, err := q.db.Query(ctx, listAlbumsByYearOrdered,
arg.FromYear,
arg.ToYear,
arg.Off,
arg.Lim,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Album
for rows.Next() {
var i Album
if err := rows.Scan(
&i.ID,
&i.Title,
&i.SortTitle,
&i.ArtistID,
&i.ReleaseDate,
&i.Mbid,
&i.CoverArtPath,
&i.CreatedAt,
&i.UpdatedAt,
&i.CoverArtSource,
&i.CoverArtSourcesVersion,
&i.ReleaseGroupMbid,
&i.AnnouncedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAlbumsByYearRangeWithArtist = `-- name: ListAlbumsByYearRangeWithArtist :many const listAlbumsByYearRangeWithArtist = `-- name: ListAlbumsByYearRangeWithArtist :many
SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name
FROM albums FROM albums
+1 -1
View File
@@ -1091,7 +1091,7 @@ WHERE title ILIKE '%' || $1::text || '%'
SELECT 1 FROM quarantine q SELECT 1 FROM quarantine q
WHERE q.user_id = $2 AND q.track_id = tracks.id WHERE q.user_id = $2 AND q.track_id = tracks.id
) )
ORDER BY title ORDER BY title, id
LIMIT $3 OFFSET $4 LIMIT $3 OFFSET $4
` `
+1 -1
View File
@@ -175,7 +175,7 @@ LIMIT sqlc.arg(lim) OFFSET sqlc.arg(off);
-- name: SearchAlbums :many -- name: SearchAlbums :many
SELECT * FROM albums SELECT * FROM albums
WHERE title ILIKE '%' || $1 || '%' WHERE title ILIKE '%' || $1 || '%'
ORDER BY sort_title ORDER BY sort_title, id
LIMIT $2 OFFSET $3; LIMIT $2 OFFSET $3;
-- name: CountAlbumsMatching :one -- name: CountAlbumsMatching :one
+1 -1
View File
@@ -27,7 +27,7 @@ SELECT * FROM artists ORDER BY sort_name;
-- name: SearchArtists :many -- name: SearchArtists :many
SELECT * FROM artists SELECT * FROM artists
WHERE name ILIKE '%' || $1 || '%' WHERE name ILIKE '%' || $1 || '%'
ORDER BY sort_name ORDER BY sort_name, id
LIMIT $2 OFFSET $3; LIMIT $2 OFFSET $3;
-- name: ListArtistsAlpha :many -- name: ListArtistsAlpha :many
+19
View File
@@ -144,3 +144,22 @@ JOIN LATERAL regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genr
WHERE tracks.artist_id = $1 AND trim(g.genre) <> '' WHERE tracks.artist_id = $1 AND trim(g.genre) <> ''
AND tracks.missing_since IS NULL AND tracks.missing_since IS NULL
ORDER BY trim(g.genre); ORDER BY trim(g.genre);
-- name: ListAlbumsByYearOrdered :many
-- Subsonic getAlbumList2 type=byYear: albums released within an inclusive
-- year range, oldest first, or newest first when the caller asks for the
-- range backwards (fromYear > toYear), as the Subsonic API defines it.
SELECT albums.* FROM albums
WHERE albums.release_date IS NOT NULL
AND EXTRACT(YEAR FROM albums.release_date)::int
BETWEEN LEAST(sqlc.arg(from_year)::int, sqlc.arg(to_year)::int)
AND GREATEST(sqlc.arg(from_year)::int, sqlc.arg(to_year)::int)
AND EXISTS (
SELECT 1 FROM tracks
WHERE tracks.album_id = albums.id
AND tracks.missing_since IS NULL
)
ORDER BY CASE WHEN sqlc.arg(from_year)::int <= sqlc.arg(to_year)::int THEN albums.release_date END ASC,
CASE WHEN sqlc.arg(from_year)::int > sqlc.arg(to_year)::int THEN albums.release_date END DESC,
albums.sort_title, albums.id
LIMIT sqlc.arg(lim) OFFSET sqlc.arg(off);
+1 -1
View File
@@ -80,7 +80,7 @@ WHERE title ILIKE '%' || $1::text || '%'
SELECT 1 FROM quarantine q SELECT 1 FROM quarantine q
WHERE q.user_id = $2 AND q.track_id = tracks.id WHERE q.user_id = $2 AND q.track_id = tracks.id
) )
ORDER BY title ORDER BY title, id
LIMIT $3 OFFSET $4; LIMIT $3 OFFSET $4;
-- name: CountTracksMatching :one -- name: CountTracksMatching :one
+7 -2
View File
@@ -61,7 +61,7 @@ func Middleware(pool *pgxpool.Pool, cfg Config, guard *auth.LoginGuard, hops fun
return return
} }
user, code, msg := authenticate(r, pool, cfg) user, code, msg := authenticate(r, pool, cfg)
if code == ErrWrongCredentials { if code == ErrWrongCredentials || code == ErrInvalidAPIKey {
guard.Fail(account, addr) guard.Fail(account, addr)
} }
if code != 0 { if code != 0 {
@@ -80,10 +80,15 @@ func authenticate(r *http.Request, pool *pgxpool.Pool, cfg Config) (dbq.User, in
params := r.URL.Query() params := r.URL.Query()
if apiKey := params.Get("apiKey"); apiKey != "" { if apiKey := params.Get("apiKey"); apiKey != "" {
// The apiKeyAuthentication extension forbids a username beside the
// key, so a request can never name one account and prove another.
if params.Has("u") {
return dbq.User{}, ErrConflictingAuth, "Send apiKey without u"
}
user, err := q.GetUserByAPITokenHash(r.Context(), auth.HashAPIToken(apiKey)) user, err := q.GetUserByAPITokenHash(r.Context(), auth.HashAPIToken(apiKey))
if err != nil { if err != nil {
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return dbq.User{}, ErrWrongCredentials, "Invalid apiKey" return dbq.User{}, ErrInvalidAPIKey, "Invalid apiKey"
} }
return dbq.User{}, ErrGeneric, "Auth lookup failed" return dbq.User{}, ErrGeneric, "Auth lookup failed"
} }
+69 -16
View File
@@ -243,7 +243,8 @@ func (b *browseHandlers) getSong(w http.ResponseWriter, r *http.Request) {
// getAlbumList2 returns a paged album list filtered by type. Supported types // getAlbumList2 returns a paged album list filtered by type. Supported types
// match the Subsonic spec § getAlbumList2. "recent" and "frequent" read the // match the Subsonic spec § getAlbumList2. "recent" and "frequent" read the
// caller's own play history: most recently played first, and most played // caller's own play history: most recently played first, and most played
// first. // first. "starred" and "highest" are both the caller's liked albums, newest
// like first: a like is the only rating Minstrel keeps.
func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) { func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query() params := r.URL.Query()
listType := params.Get("type") listType := params.Get("type")
@@ -296,6 +297,25 @@ func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
albums, err = q.ListAlbumsByGenre(r.Context(), dbq.ListAlbumsByGenreParams{ albums, err = q.ListAlbumsByGenre(r.Context(), dbq.ListAlbumsByGenreParams{
Genre: genre, Lim: int32(size), Off: int32(offset), Genre: genre, Lim: int32(size), Off: int32(offset),
}) })
case "byYear":
from, ferr := strconv.Atoi(params.Get("fromYear"))
to, terr := strconv.Atoi(params.Get("toYear"))
if ferr != nil || terr != nil {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: fromYear and toYear")
return
}
albums, err = q.ListAlbumsByYearOrdered(r.Context(), dbq.ListAlbumsByYearOrderedParams{
FromYear: int32(from), ToYear: int32(to), Lim: int32(size), Off: int32(offset),
})
case "starred", "highest":
user, ok := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
return
}
albums, err = q.ListLikedAlbumRows(r.Context(), dbq.ListLikedAlbumRowsParams{
UserID: user.ID, Limit: int32(size), Offset: int32(offset),
})
case "recent", "frequent": case "recent", "frequent":
user, ok := UserFromContext(r.Context()) user, ok := UserFromContext(r.Context())
if !ok { if !ok {
@@ -334,13 +354,21 @@ func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
// search3 runs three independent searches — artist name, album title, song // search3 runs three independent searches — artist name, album title, song
// title — each bounded by its own count/offset. The Subsonic spec lets the // title — each bounded by its own count/offset. The Subsonic spec lets the
// caller page each facet separately, which is why the params triplicate. // caller page each facet separately, which is why the params triplicate.
//
// An empty query matches everything, paged in a stable order. Apps that keep
// a copy of the library (Symfonium) download it this way, a page of songs at
// a time; refusing it leaves them a request per album or an empty library.
// Some send the empty query as two quote marks.
func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) { func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query() params := r.URL.Query()
query := params.Get("query") if !params.Has("query") {
if query == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: query") WriteFail(w, r, ErrMissingParameter, "Missing required parameter: query")
return return
} }
query := strings.TrimSpace(params.Get("query"))
if query == `""` {
query = ""
}
artistCount := clampInt(atoiDefault(params.Get("artistCount"), 20), 0, 500) artistCount := clampInt(atoiDefault(params.Get("artistCount"), 20), 0, 500)
artistOffset := atoiDefault(params.Get("artistOffset"), 0) artistOffset := atoiDefault(params.Get("artistOffset"), 0)
albumCount := clampInt(atoiDefault(params.Get("albumCount"), 20), 0, 500) albumCount := clampInt(atoiDefault(params.Get("albumCount"), 20), 0, 500)
@@ -349,8 +377,8 @@ func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
songOffset := atoiDefault(params.Get("songOffset"), 0) songOffset := atoiDefault(params.Get("songOffset"), 0)
q := dbq.New(b.pool) q := dbq.New(b.pool)
// Subsonic clients send "" as a wildcard in some implementations; we pass // The query goes through ILIKE '%' || query || '%', so it matches
// the literal query through sqlc's ILIKE param so it matches substrings. // substrings, and an empty query matches every row.
needle := &query needle := &query
// JSON marshaling of nil slices produces `null`, which some clients reject. // JSON marshaling of nil slices produces `null`, which some clients reject.
@@ -404,18 +432,15 @@ func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
return return
} }
gains := replayGains(r.Context(), q, tracks) gains := replayGains(r.Context(), q, tracks)
// One query each for the page's albums and artists, not two per
// song: a library download asks for every song in pages of 500.
albumTitles, artistNames, perr := songParents(r.Context(), q, tracks)
if perr != nil {
WriteFail(w, r, ErrGeneric, "Song search failed")
return
}
for _, t := range tracks { for _, t := range tracks {
album, aerr := q.GetAlbumByID(r.Context(), t.AlbumID) result.Songs = append(result.Songs, songRef(t, albumTitles[t.AlbumID], artistNames[t.ArtistID], gains[t.ID]))
if aerr != nil {
WriteFail(w, r, ErrGeneric, "Song search failed")
return
}
artist, aerr := q.GetArtistByID(r.Context(), t.ArtistID)
if aerr != nil {
WriteFail(w, r, ErrGeneric, "Song search failed")
return
}
result.Songs = append(result.Songs, songRef(t, album.Title, artist.Name, gains[t.ID]))
} }
} }
@@ -425,6 +450,34 @@ func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
}) })
} }
// songParents reads the album titles and artist names of tracks, in one
// query for each.
func songParents(ctx context.Context, q *dbq.Queries, tracks []dbq.Track) (albumTitles, artistNames map[pgtype.UUID]string, err error) {
albumIDs := make([]pgtype.UUID, 0, len(tracks))
artistIDs := make([]pgtype.UUID, 0, len(tracks))
for _, t := range tracks {
albumIDs = append(albumIDs, t.AlbumID)
artistIDs = append(artistIDs, t.ArtistID)
}
albums, err := q.GetAlbumsByIDs(ctx, albumIDs)
if err != nil {
return nil, nil, err
}
artists, err := q.GetArtistsByIDs(ctx, artistIDs)
if err != nil {
return nil, nil, err
}
albumTitles = make(map[pgtype.UUID]string, len(albums))
for _, a := range albums {
albumTitles[a.ID] = a.Title
}
artistNames = make(map[pgtype.UUID]string, len(artists))
for _, a := range artists {
artistNames[a.ID] = a.Name
}
return albumTitles, artistNames, nil
}
// albumRefs converts a list of dbq.Album rows to AlbumRef, resolving artist // albumRefs converts a list of dbq.Album rows to AlbumRef, resolving artist
// name and track count per album. Uses resolveArtistNames for the artist side // name and track count per album. Uses resolveArtistNames for the artist side
// (one query per distinct artist) and CountTracksByAlbum per album. For small // (one query per distinct artist) and CountTracksByAlbum per album. For small
+7 -3
View File
@@ -11,7 +11,11 @@ const (
ErrServerTooOld = 30 ErrServerTooOld = 30
ErrWrongCredentials = 40 ErrWrongCredentials = 40
ErrTokenNotSupported = 41 ErrTokenNotSupported = 41
ErrNotAuthorized = 50 // OpenSubsonic apiKeyAuthentication: an apiKey sent with u, and an
ErrTrialExpired = 60 // apiKey that matches no account.
ErrDataNotFound = 70 ErrConflictingAuth = 43
ErrInvalidAPIKey = 44
ErrNotAuthorized = 50
ErrTrialExpired = 60
ErrDataNotFound = 70
) )
+145
View File
@@ -0,0 +1,145 @@
package subsonic
import (
"encoding/xml"
"net/http"
)
// OpenSubsonicExtension names one OpenSubsonic extension and the versions of
// it the server supports.
type OpenSubsonicExtension struct {
XMLName xml.Name `json:"-" xml:"openSubsonicExtensions"`
Name string `json:"name" xml:"name,attr"`
Versions []int `json:"versions" xml:"versions"`
}
// OpenSubsonicExtensionsResponse is the body of getOpenSubsonicExtensions.
type OpenSubsonicExtensionsResponse struct {
Envelope
Extensions []OpenSubsonicExtension `json:"openSubsonicExtensions" xml:"openSubsonicExtensions"`
}
// openSubsonicExtensions lists what Minstrel implements beyond Subsonic
// 1.16.1. apiKeyAuthentication is the apiKey parameter the auth middleware
// accepts. Add an entry only for an extension the server fully serves:
// apps switch behaviour on this list.
var openSubsonicExtensions = []OpenSubsonicExtension{
{Name: "apiKeyAuthentication", Versions: []int{1}},
}
// handleGetOpenSubsonicExtensions answers without credentials: every
// response says openSubsonic=true, and the OpenSubsonic spec has apps call
// this before signing in to learn which extensions, such as API keys, they
// can use to sign in.
func handleGetOpenSubsonicExtensions(w http.ResponseWriter, r *http.Request) {
Write(w, r, OpenSubsonicExtensionsResponse{
Envelope: NewEnvelope("ok"),
Extensions: openSubsonicExtensions,
})
}
// Features Minstrel does not have answer with an empty list rather than an
// error. Apps fetch these to fill their own screens (a radio tab, a podcasts
// tab, who else is listening) and many show an error banner, or stop
// loading the screen, on a failed call; an empty list just leaves the tab
// empty. Each container's list is non-nil so JSON renders [] and not null.
type emptyList struct{}
type internetRadioStationsResponse struct {
Envelope
Stations struct {
XMLName xml.Name `json:"-" xml:"internetRadioStations"`
Stations []emptyList `json:"internetRadioStation" xml:"internetRadioStation"`
} `json:"internetRadioStations" xml:"internetRadioStations"`
}
type podcastsResponse struct {
Envelope
Podcasts struct {
XMLName xml.Name `json:"-" xml:"podcasts"`
Channels []emptyList `json:"channel" xml:"channel"`
} `json:"podcasts" xml:"podcasts"`
}
type NewestpodcastsResponse struct {
Envelope
NewestPodcasts struct {
XMLName xml.Name `json:"-" xml:"newestPodcasts"`
Episodes []emptyList `json:"episode" xml:"episode"`
} `json:"newestPodcasts" xml:"newestPodcasts"`
}
type bookmarksResponse struct {
Envelope
Bookmarks struct {
XMLName xml.Name `json:"-" xml:"bookmarks"`
Bookmarks []emptyList `json:"bookmark" xml:"bookmark"`
} `json:"bookmarks" xml:"bookmarks"`
}
type sharesResponse struct {
Envelope
Shares struct {
XMLName xml.Name `json:"-" xml:"shares"`
Shares []emptyList `json:"share" xml:"share"`
} `json:"shares" xml:"shares"`
}
type chatMessagesResponse struct {
Envelope
ChatMessages struct {
XMLName xml.Name `json:"-" xml:"chatMessages"`
Messages []emptyList `json:"chatMessage" xml:"chatMessage"`
} `json:"chatMessages" xml:"chatMessages"`
}
type nowPlayingResponse struct {
Envelope
NowPlaying struct {
XMLName xml.Name `json:"-" xml:"nowPlaying"`
Entries []emptyList `json:"entry" xml:"entry"`
} `json:"nowPlaying" xml:"nowPlaying"`
}
func handleEmptyInternetRadioStations(w http.ResponseWriter, r *http.Request) {
resp := internetRadioStationsResponse{Envelope: NewEnvelope("ok")}
resp.Stations.Stations = []emptyList{}
Write(w, r, resp)
}
func handleEmptyPodcasts(w http.ResponseWriter, r *http.Request) {
resp := podcastsResponse{Envelope: NewEnvelope("ok")}
resp.Podcasts.Channels = []emptyList{}
Write(w, r, resp)
}
func handleEmptyNewestPodcasts(w http.ResponseWriter, r *http.Request) {
resp := NewestpodcastsResponse{Envelope: NewEnvelope("ok")}
resp.NewestPodcasts.Episodes = []emptyList{}
Write(w, r, resp)
}
func handleEmptyBookmarks(w http.ResponseWriter, r *http.Request) {
resp := bookmarksResponse{Envelope: NewEnvelope("ok")}
resp.Bookmarks.Bookmarks = []emptyList{}
Write(w, r, resp)
}
func handleEmptyShares(w http.ResponseWriter, r *http.Request) {
resp := sharesResponse{Envelope: NewEnvelope("ok")}
resp.Shares.Shares = []emptyList{}
Write(w, r, resp)
}
func handleEmptyChatMessages(w http.ResponseWriter, r *http.Request) {
resp := chatMessagesResponse{Envelope: NewEnvelope("ok")}
resp.ChatMessages.Messages = []emptyList{}
Write(w, r, resp)
}
func handleEmptyNowPlaying(w http.ResponseWriter, r *http.Request) {
resp := nowPlayingResponse{Envelope: NewEnvelope("ok")}
resp.NowPlaying.Entries = []emptyList{}
Write(w, r, resp)
}
+216
View File
@@ -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())
}
}
+40 -23
View File
@@ -28,39 +28,56 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, cfg Config, ev
b := &browseHandlers{pool: pool} b := &browseHandlers{pool: pool}
m := newMediaHandlers(pool, events, logger) m := newMediaHandlers(pool, events, logger)
u := &userHandlers{lookup: dbq.New(pool).GetUserByUsername} u := &userHandlers{lookup: dbq.New(pool).GetUserByUsername}
r.Route("/rest", func(sub chi.Router) { r.Route("/rest", func(rest chi.Router) {
sub.Use(Middleware(pool, cfg, auth.NewLoginGuard(), hops)) // The one method the OpenSubsonic spec has answer without credentials.
register(sub, "/ping", handlePing) register(rest, "/getOpenSubsonicExtensions", handleGetOpenSubsonicExtensions)
register(sub, "/getLicense", handleGetLicense) rest.Group(func(sub chi.Router) {
register(sub, "/getMusicFolders", b.getMusicFolders) sub.Use(Middleware(pool, cfg, auth.NewLoginGuard(), hops))
register(sub, "/getIndexes", b.getIndexes) mountAuthed(sub, b, m, u)
register(sub, "/getArtists", b.getArtists) })
register(sub, "/getArtist", b.getArtist)
register(sub, "/getAlbum", b.getAlbum)
register(sub, "/getAlbumList2", b.getAlbumList2)
register(sub, "/getSong", b.getSong)
register(sub, "/search3", b.search3)
register(sub, "/stream", m.handleStream)
register(sub, "/download", m.handleDownload)
register(sub, "/getCoverArt", m.handleGetCoverArt)
register(sub, "/scrobble", m.handleScrobble)
register(sub, "/star", m.handleStar)
register(sub, "/unstar", m.handleUnstar)
register(sub, "/getStarred", m.handleGetStarred)
register(sub, "/getStarred2", m.handleGetStarred2)
register(sub, "/getUser", u.getUser)
// Subsonic clients expect every /rest/* miss to come back as a // Subsonic clients expect every /rest/* miss to come back as a
// Subsonic-shaped error envelope, not chi's plain-text 404. Without // Subsonic-shaped error envelope, not chi's plain-text 404. Without
// this, hitting an unimplemented method (Feishin's first-login probe // this, hitting an unimplemented method (Feishin's first-login probe
// hits getUser, getPlaylists, etc.) breaks the client's parser and // hits getUser, getPlaylists, etc.) breaks the client's parser and
// surfaces as a generic "failed to log in". // surfaces as a generic "failed to log in".
sub.NotFound(func(w http.ResponseWriter, r *http.Request) { rest.NotFound(func(w http.ResponseWriter, r *http.Request) {
WriteFail(w, r, ErrGeneric, "Method not implemented") WriteFail(w, r, ErrGeneric, "Method not implemented")
}) })
}) })
} }
// mountAuthed registers every method that needs a signed-in user.
func mountAuthed(sub chi.Router, b *browseHandlers, m *mediaHandlers, u *userHandlers) {
register(sub, "/ping", handlePing)
register(sub, "/getLicense", handleGetLicense)
register(sub, "/getMusicFolders", b.getMusicFolders)
register(sub, "/getIndexes", b.getIndexes)
register(sub, "/getArtists", b.getArtists)
register(sub, "/getArtist", b.getArtist)
register(sub, "/getAlbum", b.getAlbum)
register(sub, "/getAlbumList2", b.getAlbumList2)
register(sub, "/getSong", b.getSong)
register(sub, "/search3", b.search3)
register(sub, "/stream", m.handleStream)
register(sub, "/download", m.handleDownload)
register(sub, "/getCoverArt", m.handleGetCoverArt)
register(sub, "/scrobble", m.handleScrobble)
register(sub, "/star", m.handleStar)
register(sub, "/unstar", m.handleUnstar)
register(sub, "/getStarred", m.handleGetStarred)
register(sub, "/getStarred2", m.handleGetStarred2)
register(sub, "/getUser", u.getUser)
// Features Minstrel doesn't have: an empty list, not an error
// (opensubsonic.go says why).
register(sub, "/getInternetRadioStations", handleEmptyInternetRadioStations)
register(sub, "/getPodcasts", handleEmptyPodcasts)
register(sub, "/getNewestPodcasts", handleEmptyNewestPodcasts)
register(sub, "/getBookmarks", handleEmptyBookmarks)
register(sub, "/getShares", handleEmptyShares)
register(sub, "/getChatMessages", handleEmptyChatMessages)
register(sub, "/getNowPlaying", handleEmptyNowPlaying)
}
func register(r chi.Router, path string, h func(http.ResponseWriter, *http.Request)) { func register(r chi.Router, path string, h func(http.ResponseWriter, *http.Request)) {
r.Get(path, h) r.Get(path, h)
r.Post(path, h) r.Post(path, h)