Apps can play and browse: stream and download send the original file (Range, HEAD), getCoverArt serves the cover of an album, an artist or the album of a song (300 pixels or less is the small one), getAlbumList2 knows every kind of list, getRandomSongs and getSongsByGenre list songs, search3 finds artists, albums and songs, and the starred calls answer with nothing so apps do not break. - catalog.Filter has IDs to read albums and songs by id - storage.SubsonicRepo answers the album and song lists (random, newest, frequent, recent, by name, by artist, by year, by genre)
801 lines
29 KiB
Go
801 lines
29 KiB
Go
package opensubsonic
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"encoding/xml"
|
||
"fmt"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"net/url"
|
||
"os"
|
||
"strings"
|
||
"testing"
|
||
"time"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
|
||
"git.kmalloc.org/squid/sonda/internal/catalog"
|
||
"git.kmalloc.org/squid/sonda/internal/devices"
|
||
"git.kmalloc.org/squid/sonda/internal/images"
|
||
"git.kmalloc.org/squid/sonda/internal/library"
|
||
"git.kmalloc.org/squid/sonda/internal/streaming"
|
||
)
|
||
|
||
const secret = "0123456789abcdef0123456789abcdef0123456789abcdef"
|
||
|
||
type fakeLogin struct{}
|
||
|
||
func (fakeLogin) ByKey(_ context.Context, key string) (devices.Principal, error) {
|
||
if key == secret {
|
||
return devices.Principal{UserID: 1, DeviceID: 5, Email: "tom@example.org"}, nil
|
||
}
|
||
return devices.Principal{}, devices.ErrBadCredentials
|
||
}
|
||
|
||
func (fakeLogin) ByToken(_ context.Context, email, token, salt string) (devices.Principal, error) {
|
||
if email == "tom@example.org" && token == "tok-"+salt {
|
||
return devices.Principal{UserID: 1, DeviceID: 5, Email: email}, nil
|
||
}
|
||
return devices.Principal{}, devices.ErrBadCredentials
|
||
}
|
||
|
||
func (fakeLogin) ByPassword(_ context.Context, email, password string) (devices.Principal, error) {
|
||
if email == "tom@example.org" && password == secret {
|
||
return devices.Principal{UserID: 1, DeviceID: 5, Email: email}, nil
|
||
}
|
||
return devices.Principal{}, devices.ErrBadCredentials
|
||
}
|
||
|
||
type fakeLibraries struct{}
|
||
|
||
func (fakeLibraries) List(context.Context) ([]library.Library, error) {
|
||
return []library.Library{{ID: 1, Name: "Rock"}, {ID: 2, Name: "Jazz"}}, nil
|
||
}
|
||
|
||
// The catalogue of the tests: Radiohead (OK Computer, 2 songs), Björk (nothing to play but a name), 3 Doors Down.
|
||
type fakeCatalog struct{ libs []int64 }
|
||
|
||
var (
|
||
artists = []catalog.Artist{
|
||
{ID: 3, Name: "3 Doors Down", AlbumCount: 0, TrackCount: 1},
|
||
{ID: 2, Name: "Björk", AlbumCount: 0, TrackCount: 1},
|
||
{ID: 1, Name: "Radiohead", AlbumCount: 1, TrackCount: 2},
|
||
{ID: 4, Name: "Radio Dept", AlbumCount: 0, TrackCount: 1},
|
||
}
|
||
okComputer = catalog.Album{ID: 7, Title: "OK Computer", Artist: &catalog.ArtistRef{ID: 1, Name: "Radiohead"}, TrackCount: 2, DurationMs: 600_400}
|
||
airbag = catalog.Track{ID: 70, Title: "Airbag", DurationMs: 284_000, TrackNo: 1, DiscNo: 1, Album: &catalog.AlbumRef{ID: 7, Title: "OK Computer"},
|
||
Artists: []catalog.ArtistRef{{ID: 1, Name: "Radiohead"}}, Format: "flac",
|
||
ReplayGain: &catalog.ReplayGain{TrackGain: ptr(-6.5)}}
|
||
karma = catalog.Track{ID: 71, Title: "Karma Police", DurationMs: 264_400, TrackNo: 2, DiscNo: 1, Album: &catalog.AlbumRef{ID: 7, Title: "OK Computer"},
|
||
Artists: []catalog.ArtistRef{{ID: 1, Name: "Radiohead"}, {ID: 9, Name: "Guest"}}, Format: "mp3"}
|
||
)
|
||
|
||
func ptr(f float64) *float64 { return &f }
|
||
|
||
func (c *fakeCatalog) Artists(_ context.Context, f catalog.Filter) (catalog.Page[catalog.Artist], error) {
|
||
if f.LibraryID != 0 {
|
||
c.libs = append(c.libs, f.LibraryID)
|
||
}
|
||
return catalog.Page[catalog.Artist]{Items: page(artists, f), Total: len(artists), Limit: f.Limit, Offset: f.Offset}, nil
|
||
}
|
||
|
||
func (c *fakeCatalog) Albums(_ context.Context, f catalog.Filter) (catalog.Page[catalog.Album], error) {
|
||
var all []catalog.Album
|
||
if f.ArtistID == 0 || f.ArtistID == 1 {
|
||
all = []catalog.Album{okComputer}
|
||
}
|
||
if f.IDs != nil {
|
||
var keep []catalog.Album
|
||
for _, a := range all {
|
||
for _, id := range f.IDs {
|
||
if a.ID == id {
|
||
keep = append(keep, a)
|
||
}
|
||
}
|
||
}
|
||
all = keep
|
||
}
|
||
return catalog.Page[catalog.Album]{Items: page(all, f), Total: len(all), Limit: f.Limit, Offset: f.Offset}, nil
|
||
}
|
||
|
||
func (c *fakeCatalog) Tracks(_ context.Context, f catalog.Filter) (catalog.Page[catalog.Track], error) {
|
||
var all []catalog.Track
|
||
if f.AlbumID == 7 || f.IDs != nil {
|
||
all = []catalog.Track{airbag, karma}
|
||
}
|
||
if f.IDs != nil {
|
||
var keep []catalog.Track
|
||
for _, t := range all {
|
||
for _, id := range f.IDs {
|
||
if t.ID == id {
|
||
keep = append(keep, t)
|
||
}
|
||
}
|
||
}
|
||
all = keep
|
||
}
|
||
return catalog.Page[catalog.Track]{Items: page(all, f), Total: len(all), Limit: f.Limit, Offset: f.Offset}, nil
|
||
}
|
||
|
||
func (c *fakeCatalog) Artist(_ context.Context, id int64) (catalog.Artist, error) {
|
||
for _, a := range artists {
|
||
if a.ID == id {
|
||
return a, nil
|
||
}
|
||
}
|
||
return catalog.Artist{}, catalog.ErrNotFound
|
||
}
|
||
|
||
func (c *fakeCatalog) Album(_ context.Context, id int64) (catalog.Album, error) {
|
||
if id == 7 {
|
||
return okComputer, nil
|
||
}
|
||
return catalog.Album{}, catalog.ErrNotFound
|
||
}
|
||
|
||
func (c *fakeCatalog) Track(_ context.Context, id int64) (catalog.Track, error) {
|
||
switch id {
|
||
case 70:
|
||
return airbag, nil
|
||
case 71:
|
||
return karma, nil
|
||
}
|
||
return catalog.Track{}, catalog.ErrNotFound
|
||
}
|
||
|
||
func page[T any](all []T, f catalog.Filter) []T {
|
||
if f.Offset >= len(all) {
|
||
return []T{}
|
||
}
|
||
end := len(all)
|
||
if f.Limit > 0 && f.Offset+f.Limit < end {
|
||
end = f.Offset + f.Limit
|
||
}
|
||
return all[f.Offset:end]
|
||
}
|
||
|
||
type fakeExtras struct{}
|
||
|
||
func (fakeExtras) Tracks(_ context.Context, ids []int64) (map[int64]TrackExtra, error) {
|
||
out := map[int64]TrackExtra{}
|
||
for _, id := range ids {
|
||
switch id {
|
||
case 70:
|
||
out[id] = TrackExtra{Year: 1997, Genres: []string{"alternative rock", "art rock"}, Size: 29_000_000, BitrateKbps: 900, Suffix: "flac", AddedAt: time.Unix(1_700_000_000, 0)}
|
||
case 71:
|
||
out[id] = TrackExtra{Size: 6_000_000, BitrateKbps: 320, Suffix: "mp3", AddedAt: time.Unix(1_700_000_100, 0)}
|
||
}
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
func (fakeExtras) Albums(_ context.Context, ids []int64) (map[int64]AlbumExtra, error) {
|
||
out := map[int64]AlbumExtra{}
|
||
for _, id := range ids {
|
||
if id == 7 {
|
||
out[id] = AlbumExtra{Year: 1997, Genres: []string{"alternative rock", "art rock"}, AddedAt: time.Unix(1_700_000_000, 0)}
|
||
}
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
func (fakeExtras) Genres(context.Context) ([]Genre, error) {
|
||
return []Genre{{Name: "alternative rock", Songs: 1, Albums: 1}, {Name: "art rock", Songs: 1, Albums: 1}}, nil
|
||
}
|
||
|
||
func newTestServer() (http.Handler, *fakeCatalog) {
|
||
gin.SetMode(gin.TestMode)
|
||
cat := &fakeCatalog{}
|
||
r := gin.New()
|
||
Register(r, Deps{Login: fakeLogin{}, Catalog: cat, Libraries: fakeLibraries{}, Extras: fakeExtras{}, ServerVersion: "9.9"})
|
||
return r, cat
|
||
}
|
||
|
||
// get makes a request to /rest and returns the recorder.
|
||
func get(t *testing.T, h http.Handler, method, path string, q url.Values) *httptest.ResponseRecorder {
|
||
t.Helper()
|
||
var req *http.Request
|
||
if method == http.MethodPost {
|
||
req = httptest.NewRequest(method, path, strings.NewReader(q.Encode()))
|
||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||
} else {
|
||
req = httptest.NewRequest(method, path+"?"+q.Encode(), nil)
|
||
}
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
return rec
|
||
}
|
||
|
||
// ok is the parameters of a call that is logged in with the API key and answers in JSON.
|
||
func ok(extra ...string) url.Values {
|
||
q := url.Values{"apiKey": {secret}, "f": {"json"}, "v": {"1.16.1"}, "c": {"test"}}
|
||
for i := 0; i+1 < len(extra); i += 2 {
|
||
q.Set(extra[i], extra[i+1])
|
||
}
|
||
return q
|
||
}
|
||
|
||
// body decodes the JSON answer and returns the content of subsonic-response.
|
||
func body(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
|
||
t.Helper()
|
||
var out struct {
|
||
R map[string]any `json:"subsonic-response"`
|
||
}
|
||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.R == nil {
|
||
t.Fatalf("not an answer: %v: %s", err, rec.Body.String())
|
||
}
|
||
return out.R
|
||
}
|
||
|
||
func good(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
|
||
t.Helper()
|
||
if rec.Code != http.StatusOK {
|
||
t.Fatalf("HTTP %d: %s", rec.Code, rec.Body.String())
|
||
}
|
||
r := body(t, rec)
|
||
if r["status"] != "ok" {
|
||
t.Fatalf("status %v: %s", r["status"], rec.Body.String())
|
||
}
|
||
return r
|
||
}
|
||
|
||
func failed(t *testing.T, rec *httptest.ResponseRecorder, code int) {
|
||
t.Helper()
|
||
r := body(t, rec)
|
||
e, _ := r["error"].(map[string]any)
|
||
if r["status"] != "failed" || e == nil || int(e["code"].(float64)) != code {
|
||
t.Fatalf("want error %d, got %s", code, rec.Body.String())
|
||
}
|
||
}
|
||
|
||
func TestTheAnswerSaysWhoIsAnswering(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
rec := get(t, h, "GET", "/rest/ping", ok())
|
||
r := good(t, rec)
|
||
if r["version"] != APIVersion || r["type"] != "sonda" || r["serverVersion"] != "9.9" || r["openSubsonic"] != true {
|
||
t.Fatalf("envelope %v", r)
|
||
}
|
||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
|
||
t.Fatalf("content type %q", ct)
|
||
}
|
||
if rec.Header().Get("Access-Control-Allow-Origin") != "*" {
|
||
t.Fatal("a web app on another address cannot read the answer")
|
||
}
|
||
}
|
||
|
||
func TestTheDefaultAnswerIsXML(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
q := ok()
|
||
q.Del("f")
|
||
rec := get(t, h, "GET", "/rest/ping.view", q)
|
||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/xml") {
|
||
t.Fatalf("content type %q", ct)
|
||
}
|
||
var r struct {
|
||
XMLName xml.Name `xml:"subsonic-response"`
|
||
Xmlns string `xml:"xmlns,attr"`
|
||
Status string `xml:"status,attr"`
|
||
Version string `xml:"version,attr"`
|
||
}
|
||
if err := xml.Unmarshal(rec.Body.Bytes(), &r); err != nil || r.Status != "ok" || r.Version != APIVersion || r.Xmlns != "http://subsonic.org/restapi" {
|
||
t.Fatalf("%v %+v: %s", err, r, rec.Body.String())
|
||
}
|
||
}
|
||
|
||
func TestACallCanBeAFormPost(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
good(t, get(t, h, "POST", "/rest/ping", ok()))
|
||
}
|
||
|
||
func TestTheLoginIsChecked(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
|
||
// The API key, a token with its salt, and the password, each for a person.
|
||
good(t, get(t, h, "GET", "/rest/ping", ok()))
|
||
good(t, get(t, h, "GET", "/rest/ping", url.Values{"u": {"tom@example.org"}, "t": {"tok-abc123"}, "s": {"abc123"}, "f": {"json"}}))
|
||
good(t, get(t, h, "GET", "/rest/ping", url.Values{"u": {"tom@example.org"}, "p": {secret}, "f": {"json"}}))
|
||
|
||
for name, q := range map[string]struct {
|
||
q url.Values
|
||
code int
|
||
}{
|
||
"nothing": {url.Values{"f": {"json"}}, ErrMissingParam},
|
||
"no password": {url.Values{"u": {"tom@example.org"}, "f": {"json"}}, ErrMissingParam},
|
||
"a token with no salt": {url.Values{"u": {"tom@example.org"}, "t": {"x"}, "f": {"json"}}, ErrMissingParam},
|
||
"a wrong password": {url.Values{"u": {"tom@example.org"}, "p": {"nope"}, "f": {"json"}}, ErrWrongLogin},
|
||
"a wrong token": {url.Values{"u": {"tom@example.org"}, "t": {"bad"}, "s": {"abc"}, "f": {"json"}}, ErrWrongLogin},
|
||
"a wrong key": {url.Values{"apiKey": {"nope"}, "f": {"json"}}, ErrBadAPIKey},
|
||
"a key and a user": {url.Values{"apiKey": {secret}, "u": {"tom@example.org"}, "f": {"json"}}, ErrAuthConflict},
|
||
"a key and a token": {url.Values{"apiKey": {secret}, "t": {"x"}, "s": {"y"}, "f": {"json"}}, ErrAuthConflict},
|
||
"a key and a password": {url.Values{"apiKey": {secret}, "p": {secret}, "f": {"json"}}, ErrAuthConflict},
|
||
"a token and a password": {url.Values{"u": {"tom@example.org"}, "t": {"tok-a"}, "s": {"a"}, "p": {secret}, "f": {"json"}}, ErrAuthConflict},
|
||
} {
|
||
rec := get(t, h, "GET", "/rest/ping", q.q)
|
||
if rec.Code != http.StatusOK {
|
||
t.Errorf("%s: HTTP %d, a failed call is still a 200", name, rec.Code)
|
||
}
|
||
failed(t, rec, q.code)
|
||
}
|
||
}
|
||
|
||
func TestAFailedLoginIsAnswerdInTheFormatAskedFor(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
rec := get(t, h, "GET", "/rest/ping.view", url.Values{"u": {"x"}, "p": {"y"}})
|
||
if !strings.Contains(rec.Body.String(), `<error code="40"`) {
|
||
t.Fatal(rec.Body.String())
|
||
}
|
||
}
|
||
|
||
func TestAnUnknownCallIsAnError(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
failed(t, get(t, h, "GET", "/rest/doesNotExist", ok()), ErrGeneric)
|
||
}
|
||
|
||
func TestTheServerSpeaksTheExtensionsItHas(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
r := good(t, get(t, h, "GET", "/rest/getOpenSubsonicExtensions", ok()))
|
||
names := map[string]bool{}
|
||
for _, e := range r["openSubsonicExtensions"].([]any) {
|
||
m := e.(map[string]any)
|
||
names[m["name"].(string)] = true
|
||
if len(m["versions"].([]any)) == 0 {
|
||
t.Errorf("%v has no version", m)
|
||
}
|
||
}
|
||
if !names["apiKeyAuthentication"] || !names["formPost"] {
|
||
t.Fatalf("extensions %v", names)
|
||
}
|
||
}
|
||
|
||
func TestExtensionsAreAnsweredWithoutALogin(t *testing.T) {
|
||
// An app asks what the server speaks before it has the person's password.
|
||
h, _ := newTestServer()
|
||
good(t, get(t, h, "GET", "/rest/getOpenSubsonicExtensions", url.Values{"f": {"json"}}))
|
||
}
|
||
|
||
func TestLicenseAndTokenInfo(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
if l := good(t, get(t, h, "GET", "/rest/getLicense", ok()))["license"].(map[string]any); l["valid"] != true {
|
||
t.Fatalf("license %v", l)
|
||
}
|
||
if ti := good(t, get(t, h, "GET", "/rest/tokenInfo", ok()))["tokenInfo"].(map[string]any); ti["username"] != "tom@example.org" {
|
||
t.Fatalf("token info %v", ti)
|
||
}
|
||
}
|
||
|
||
func TestMusicFoldersAreTheLibraries(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
f := good(t, get(t, h, "GET", "/rest/getMusicFolders", ok()))["musicFolders"].(map[string]any)["musicFolder"].([]any)
|
||
if len(f) != 2 || f[0].(map[string]any)["name"] != "Rock" || f[1].(map[string]any)["id"].(float64) != 2 {
|
||
t.Fatalf("folders %v", f)
|
||
}
|
||
}
|
||
|
||
func TestArtistsAreGroupedByTheirFirstLetter(t *testing.T) {
|
||
h, cat := newTestServer()
|
||
a := good(t, get(t, h, "GET", "/rest/getArtists", ok("musicFolderId", "2")))["artists"].(map[string]any)
|
||
if a["ignoredArticles"] != "" {
|
||
t.Fatalf("articles %v", a["ignoredArticles"])
|
||
}
|
||
var names []string
|
||
got := map[string][]string{}
|
||
for _, i := range a["index"].([]any) {
|
||
m := i.(map[string]any)
|
||
names = append(names, m["name"].(string))
|
||
for _, ar := range m["artist"].([]any) {
|
||
got[m["name"].(string)] = append(got[m["name"].(string)], ar.(map[string]any)["name"].(string))
|
||
}
|
||
}
|
||
if strings.Join(names, ",") != "#,B,R" {
|
||
t.Fatalf("groups %v", names)
|
||
}
|
||
if strings.Join(got["R"], ",") != "Radiohead,Radio Dept" || got["#"][0] != "3 Doors Down" {
|
||
t.Fatalf("artists %v", got)
|
||
}
|
||
first := a["index"].([]any)[2].(map[string]any)["artist"].([]any)[0].(map[string]any)
|
||
if first["id"] != "ar-1" || first["albumCount"].(float64) != 1 {
|
||
t.Fatalf("artist %v", first)
|
||
}
|
||
if len(cat.libs) == 0 || cat.libs[0] != 2 {
|
||
t.Fatalf("the folder was not asked for: %v", cat.libs)
|
||
}
|
||
}
|
||
|
||
func TestAnArtistHasItsAlbums(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
a := good(t, get(t, h, "GET", "/rest/getArtist", ok("id", "ar-1")))["artist"].(map[string]any)
|
||
if a["id"] != "ar-1" || a["name"] != "Radiohead" || a["albumCount"].(float64) != 1 {
|
||
t.Fatalf("artist %v", a)
|
||
}
|
||
al := a["album"].([]any)[0].(map[string]any)
|
||
if al["id"] != "al-7" || al["name"] != "OK Computer" || al["artistId"] != "ar-1" || al["artist"] != "Radiohead" ||
|
||
al["coverArt"] != "al-7" || al["songCount"].(float64) != 2 || al["duration"].(float64) != 600 ||
|
||
al["year"].(float64) != 1997 || al["genre"] != "alternative rock" || al["created"] != "2023-11-14T22:13:20.000Z" {
|
||
t.Fatalf("album %v", al)
|
||
}
|
||
}
|
||
|
||
func TestAnArtistWithNoAlbumsHasNoAlbumList(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
a := good(t, get(t, h, "GET", "/rest/getArtist", ok("id", "ar-2")))["artist"].(map[string]any)
|
||
if _, has := a["album"]; has {
|
||
t.Fatalf("artist %v", a)
|
||
}
|
||
}
|
||
|
||
func TestAnAlbumHasItsSongs(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
al := good(t, get(t, h, "GET", "/rest/getAlbum", ok("id", "al-7")))["album"].(map[string]any)
|
||
songs := al["song"].([]any)
|
||
if len(songs) != 2 || al["name"] != "OK Computer" {
|
||
t.Fatalf("album %v", al)
|
||
}
|
||
s := songs[0].(map[string]any)
|
||
want := map[string]any{
|
||
"id": "tr-70", "parent": "al-7", "isDir": false, "title": "Airbag", "album": "OK Computer", "artist": "Radiohead",
|
||
"track": 1.0, "discNumber": 1.0, "year": 1997.0, "genre": "alternative rock", "coverArt": "al-7", "size": 29000000.0,
|
||
"contentType": "audio/flac", "suffix": "flac", "duration": 284.0, "bitRate": 900.0, "albumId": "al-7", "artistId": "ar-1",
|
||
"type": "music", "mediaType": "song", "isVideo": false, "displayArtist": "Radiohead", "path": "Radiohead/OK Computer/01 - Airbag.flac",
|
||
}
|
||
for k, v := range want {
|
||
if s[k] != v {
|
||
t.Errorf("%s = %v, want %v", k, s[k], v)
|
||
}
|
||
}
|
||
if g := s["genres"].([]any); len(g) != 2 || g[1].(map[string]any)["name"] != "art rock" {
|
||
t.Errorf("genres %v", g)
|
||
}
|
||
if rg := s["replayGain"].(map[string]any); rg["trackGain"] != -6.5 {
|
||
t.Errorf("replay gain %v", rg)
|
||
}
|
||
k := songs[1].(map[string]any)
|
||
if k["contentType"] != "audio/mpeg" || k["artist"] != "Radiohead & Guest" || k["displayArtist"] != "Radiohead & Guest" {
|
||
t.Errorf("second song %v", k)
|
||
}
|
||
if a := k["artists"].([]any); len(a) != 2 || a[1].(map[string]any)["id"] != "ar-9" {
|
||
t.Errorf("artists of the second song %v", a)
|
||
}
|
||
}
|
||
|
||
func TestASongByItself(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
s := good(t, get(t, h, "GET", "/rest/getSong", ok("id", "tr-71")))["song"].(map[string]any)
|
||
if s["title"] != "Karma Police" || s["id"] != "tr-71" {
|
||
t.Fatalf("song %v", s)
|
||
}
|
||
}
|
||
|
||
func TestTheIdsOfThingsThatAreNotThereAreNotFound(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
for _, c := range [][2]string{
|
||
{"getArtist", "ar-99"}, {"getAlbum", "al-99"}, {"getSong", "tr-99"},
|
||
{"getArtist", "al-7"}, {"getAlbum", "tr-70"}, {"getSong", "12"}, {"getSong", "tr-x"}, {"getSong", "tr--1"},
|
||
} {
|
||
failed(t, get(t, h, "GET", "/rest/"+c[0], ok("id", c[1])), ErrNotFound)
|
||
}
|
||
for _, m := range []string{"getArtist", "getAlbum", "getSong"} {
|
||
failed(t, get(t, h, "GET", "/rest/"+m, ok()), ErrMissingParam)
|
||
}
|
||
}
|
||
|
||
func TestGenresHaveTheirSongsAndAlbums(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
g := good(t, get(t, h, "GET", "/rest/getGenres", ok()))["genres"].(map[string]any)["genre"].([]any)
|
||
if len(g) != 2 || g[0].(map[string]any)["value"] != "alternative rock" || g[0].(map[string]any)["songCount"].(float64) != 1 {
|
||
t.Fatalf("genres %v", g)
|
||
}
|
||
}
|
||
|
||
func TestXMLHasTheValuesAsAttributesAndTheListsAsElements(t *testing.T) {
|
||
h, _ := newTestServer()
|
||
q := ok("id", "al-7")
|
||
q.Del("f")
|
||
got := get(t, h, "GET", "/rest/getAlbum", q).Body.String()
|
||
for _, want := range []string{`<album id="al-7" name="OK Computer"`, `<song id="tr-70" parent="al-7" isDir="false" title="Airbag"`, `<artists id="ar-1" name="Radiohead">`} {
|
||
if !strings.Contains(got, want) {
|
||
t.Errorf("missing %s in %s", want, got)
|
||
}
|
||
}
|
||
q = ok()
|
||
q.Del("f")
|
||
if g := get(t, h, "GET", "/rest/getGenres", q).Body.String(); !strings.Contains(g, `<genre songCount="1" albumCount="1">alternative rock</genre>`) {
|
||
t.Errorf("genres %s", g)
|
||
}
|
||
}
|
||
|
||
func TestAccentsAreTakenOffForTheLetterOfAnArtist(t *testing.T) {
|
||
for name, want := range map[string]string{"Édith Piaf": "E", "Ünïcode Band": "U", "björk": "B", "3 Doors Down": "#", "": "#", "!!!": "#", "Ζωή": "Ζ"} {
|
||
if got := indexLetter(name); got != want {
|
||
t.Errorf("%q: %q, want %q", name, got, want)
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---- media, lists, search ----
|
||
|
||
type fakeLists struct {
|
||
albumQ []AlbumQuery
|
||
songQ []SongQuery
|
||
}
|
||
|
||
func (f *fakeLists) AlbumIDs(_ context.Context, q AlbumQuery) ([]int64, error) {
|
||
f.albumQ = append(f.albumQ, q)
|
||
if q.Offset > 0 {
|
||
return []int64{}, nil
|
||
}
|
||
return []int64{7}, nil
|
||
}
|
||
|
||
func (f *fakeLists) SongIDs(_ context.Context, q SongQuery) ([]int64, error) {
|
||
f.songQ = append(f.songQ, q)
|
||
return []int64{71, 70}, nil // not in the order of the catalogue
|
||
}
|
||
|
||
type fakeStreams struct{ opened []int64 }
|
||
|
||
func (f *fakeStreams) Open(_ context.Context, id int64) (*streaming.Stream, error) {
|
||
f.opened = append(f.opened, id)
|
||
switch id {
|
||
case 70:
|
||
file, err := os.Open(songFile)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return &streaming.Stream{File: file, Name: "airbag.flac", ModTime: time.Unix(1_700_000_000, 0), ContentType: "audio/flac"}, nil
|
||
case 71:
|
||
return nil, streaming.ErrFileMissing
|
||
}
|
||
return nil, streaming.ErrNotFound
|
||
}
|
||
|
||
type fakeCovers struct{ sizes []images.Size }
|
||
|
||
func (f *fakeCovers) AlbumCover(_ context.Context, id int64, size images.Size) (*images.Cover, error) {
|
||
f.sizes = append(f.sizes, size)
|
||
if id != 7 {
|
||
return nil, images.ErrNoCover
|
||
}
|
||
file, err := os.Open(coverFile)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return &images.Cover{File: file, ModTime: time.Unix(1_700_000_000, 0), ETag: "abc"}, nil
|
||
}
|
||
|
||
func (f *fakeCovers) ArtistImage(_ context.Context, id int64, size images.Size) (*images.Cover, error) {
|
||
f.sizes = append(f.sizes, size)
|
||
if id != 1 {
|
||
return nil, images.ErrNoImage
|
||
}
|
||
file, err := os.Open(coverFile)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return &images.Cover{File: file, ModTime: time.Unix(1_700_000_000, 0), ETag: "def"}, nil
|
||
}
|
||
|
||
var songFile, coverFile string
|
||
|
||
func TestMain(m *testing.M) {
|
||
dir, err := os.MkdirTemp("", "opensubsonic")
|
||
if err != nil {
|
||
panic(err)
|
||
}
|
||
songFile, coverFile = dir+"/song.flac", dir+"/cover.jpg"
|
||
_ = os.WriteFile(songFile, []byte("0123456789"), 0o600)
|
||
_ = os.WriteFile(coverFile, []byte("JPEGDATA"), 0o600)
|
||
code := m.Run()
|
||
_ = os.RemoveAll(dir)
|
||
os.Exit(code)
|
||
}
|
||
|
||
type media struct {
|
||
h http.Handler
|
||
cat *fakeCatalog
|
||
lists *fakeLists
|
||
streams *fakeStreams
|
||
covers *fakeCovers
|
||
}
|
||
|
||
func newMediaServer() media {
|
||
gin.SetMode(gin.TestMode)
|
||
m := media{cat: &fakeCatalog{}, lists: &fakeLists{}, streams: &fakeStreams{}, covers: &fakeCovers{}}
|
||
r := gin.New()
|
||
Register(r, Deps{
|
||
Login: fakeLogin{}, Catalog: m.cat, Libraries: fakeLibraries{}, Extras: fakeExtras{}, ServerVersion: "9.9",
|
||
Lists: m.lists, Streams: m.streams, Covers: m.covers, ArtistImages: m.covers,
|
||
})
|
||
m.h = r
|
||
return m
|
||
}
|
||
|
||
func TestASongIsStreamedWithRangeAndWithoutRevealingTheToken(t *testing.T) {
|
||
m := newMediaServer()
|
||
rec := get(t, m.h, "GET", "/rest/stream", ok("id", "tr-70"))
|
||
if rec.Code != 200 || rec.Body.String() != "0123456789" || rec.Header().Get("Content-Type") != "audio/flac" {
|
||
t.Fatalf("%d %q %q", rec.Code, rec.Body.String(), rec.Header().Get("Content-Type"))
|
||
}
|
||
if rec.Header().Get("Referrer-Policy") != "no-referrer" || rec.Header().Get("X-Content-Type-Options") != "nosniff" || rec.Header().Get("Accept-Ranges") != "bytes" {
|
||
t.Fatalf("headers %v", rec.Header())
|
||
}
|
||
|
||
req := httptest.NewRequest("GET", "/rest/stream.view?"+ok("id", "tr-70").Encode(), nil)
|
||
req.Header.Set("Range", "bytes=2-5")
|
||
part := httptest.NewRecorder()
|
||
m.h.ServeHTTP(part, req)
|
||
if part.Code != http.StatusPartialContent || part.Body.String() != "2345" {
|
||
t.Fatalf("range: %d %q", part.Code, part.Body.String())
|
||
}
|
||
|
||
head := httptest.NewRecorder()
|
||
m.h.ServeHTTP(head, httptest.NewRequest("HEAD", "/rest/stream?"+ok("id", "tr-70").Encode(), nil))
|
||
if head.Code != 200 || head.Body.Len() != 0 || head.Header().Get("Content-Length") != "10" {
|
||
t.Fatalf("head: %d %q %v", head.Code, head.Body.String(), head.Header())
|
||
}
|
||
}
|
||
|
||
func TestDownloadSendsTheFileAsAnAttachment(t *testing.T) {
|
||
m := newMediaServer()
|
||
rec := get(t, m.h, "GET", "/rest/download", ok("id", "tr-70"))
|
||
if rec.Code != 200 || rec.Body.String() != "0123456789" {
|
||
t.Fatalf("%d %q", rec.Code, rec.Body.String())
|
||
}
|
||
if cd := rec.Header().Get("Content-Disposition"); !strings.HasPrefix(cd, "attachment") || !strings.Contains(cd, "airbag.flac") {
|
||
t.Fatalf("disposition %q", cd)
|
||
}
|
||
}
|
||
|
||
func TestAStreamThatCannotBeServedIsAnErrorInTheFormatAskedFor(t *testing.T) {
|
||
m := newMediaServer()
|
||
failed(t, get(t, m.h, "GET", "/rest/stream", ok("id", "tr-99")), ErrNotFound)
|
||
failed(t, get(t, m.h, "GET", "/rest/stream", ok("id", "tr-71")), ErrNotFound) // the file is gone
|
||
failed(t, get(t, m.h, "GET", "/rest/stream", ok("id", "al-7")), ErrNotFound)
|
||
failed(t, get(t, m.h, "GET", "/rest/stream", ok()), ErrMissingParam)
|
||
failed(t, get(t, m.h, "GET", "/rest/download", ok("id", "tr-99")), ErrNotFound)
|
||
// No login, no music.
|
||
failed(t, get(t, m.h, "GET", "/rest/stream", url.Values{"id": {"tr-70"}, "f": {"json"}}), ErrMissingParam)
|
||
failed(t, get(t, m.h, "GET", "/rest/stream", url.Values{"id": {"tr-70"}, "apiKey": {"nope"}, "f": {"json"}}), ErrBadAPIKey)
|
||
if len(m.streams.opened) != 3 {
|
||
t.Fatalf("files opened without a login: %v", m.streams.opened)
|
||
}
|
||
}
|
||
|
||
func TestACoverIsAnAlbumAnArtistOrTheAlbumOfASong(t *testing.T) {
|
||
m := newMediaServer()
|
||
for _, id := range []string{"al-7", "tr-70", "ar-1"} {
|
||
rec := get(t, m.h, "GET", "/rest/getCoverArt", ok("id", id))
|
||
if rec.Code != 200 || rec.Body.String() != "JPEGDATA" || rec.Header().Get("Content-Type") != "image/jpeg" {
|
||
t.Fatalf("%s: %d %q", id, rec.Code, rec.Body.String())
|
||
}
|
||
}
|
||
if rec := get(t, m.h, "GET", "/rest/getCoverArt", ok("id", "al-7")); rec.Header().Get("ETag") != `"abc"` || !strings.Contains(rec.Header().Get("Cache-Control"), "max-age") {
|
||
t.Fatalf("headers %v", rec.Header())
|
||
}
|
||
failed(t, get(t, m.h, "GET", "/rest/getCoverArt", ok("id", "al-8")), ErrNotFound)
|
||
failed(t, get(t, m.h, "GET", "/rest/getCoverArt", ok("id", "ar-2")), ErrNotFound)
|
||
failed(t, get(t, m.h, "GET", "/rest/getCoverArt", ok("id", "tr-99")), ErrNotFound)
|
||
failed(t, get(t, m.h, "GET", "/rest/getCoverArt", ok("id", "pl-1")), ErrNotFound)
|
||
failed(t, get(t, m.h, "GET", "/rest/getCoverArt", ok()), ErrMissingParam)
|
||
}
|
||
|
||
func TestACoverIsSmallUpTo300PixelsAndLargeAbove(t *testing.T) {
|
||
m := newMediaServer()
|
||
for _, size := range []string{"", "0", "150", "300", "301", "1200", "x"} {
|
||
get(t, m.h, "GET", "/rest/getCoverArt", ok("id", "al-7", "size", size))
|
||
}
|
||
want := []images.Size{images.Large, images.Large, images.Small, images.Small, images.Large, images.Large, images.Large}
|
||
if fmt.Sprint(m.covers.sizes) != fmt.Sprint(want) {
|
||
t.Fatalf("sizes %v, want %v", m.covers.sizes, want)
|
||
}
|
||
}
|
||
|
||
func TestAlbumListsAskForWhatTheAppWantsAndAnswerInTheOrderOfTheList(t *testing.T) {
|
||
m := newMediaServer()
|
||
r := good(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "byYear", "fromYear", "1990", "toYear", "2000", "size", "5", "offset", "0", "musicFolderId", "2")))
|
||
al := r["albumList2"].(map[string]any)["album"].([]any)
|
||
if len(al) != 1 || al[0].(map[string]any)["id"] != "al-7" {
|
||
t.Fatalf("list %v", r)
|
||
}
|
||
q := m.lists.albumQ[0]
|
||
if q.Type != "byYear" || q.FromYear != 1990 || q.ToYear != 2000 || q.Size != 5 || q.LibraryID != 2 || q.UserID != 1 {
|
||
t.Fatalf("query %+v", q)
|
||
}
|
||
|
||
get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "newest"))
|
||
if q := m.lists.albumQ[1]; q.Size != 10 || q.Offset != 0 {
|
||
t.Fatalf("defaults %+v", q)
|
||
}
|
||
get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "newest", "size", "9000"))
|
||
if q := m.lists.albumQ[2]; q.Size != 500 {
|
||
t.Fatalf("size is not limited: %+v", q)
|
||
}
|
||
get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "byGenre", "genre", "Jazz"))
|
||
if q := m.lists.albumQ[3]; q.Genre != "Jazz" {
|
||
t.Fatalf("genre %+v", q)
|
||
}
|
||
|
||
empty := good(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "random", "offset", "5")))
|
||
if _, ok := empty["albumList2"].(map[string]any); !ok {
|
||
t.Fatalf("an empty list is still a list: %v", empty)
|
||
}
|
||
}
|
||
|
||
func TestAnAlbumListThatIsAskedForBadly(t *testing.T) {
|
||
m := newMediaServer()
|
||
failed(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok()), ErrMissingParam)
|
||
failed(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "nope")), ErrGeneric)
|
||
failed(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "byYear", "fromYear", "1990")), ErrMissingParam)
|
||
failed(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "byGenre")), ErrMissingParam)
|
||
failed(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "newest", "size", "many")), ErrGeneric)
|
||
failed(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "newest", "offset", "-1")), ErrGeneric)
|
||
failed(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "newest", "musicFolderId", "x")), ErrNotFound)
|
||
}
|
||
|
||
func TestStarredThingsAreNone(t *testing.T) {
|
||
m := newMediaServer()
|
||
good(t, get(t, m.h, "GET", "/rest/star", ok("id", "tr-70")))
|
||
good(t, get(t, m.h, "GET", "/rest/unstar", ok("id", "tr-70")))
|
||
good(t, get(t, m.h, "GET", "/rest/setRating", ok("id", "tr-70", "rating", "5")))
|
||
s := good(t, get(t, m.h, "GET", "/rest/getStarred2", ok()))["starred2"].(map[string]any)
|
||
if len(s) != 0 {
|
||
t.Fatalf("starred %v", s)
|
||
}
|
||
if r := good(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "starred"))); r["albumList2"] == nil {
|
||
t.Fatalf("starred albums %v", r)
|
||
}
|
||
}
|
||
|
||
func TestSongsAtRandomAndByGenre(t *testing.T) {
|
||
m := newMediaServer()
|
||
r := good(t, get(t, m.h, "GET", "/rest/getRandomSongs", ok("size", "2", "genre", "Rock", "fromYear", "1990", "toYear", "2000", "musicFolderId", "1")))
|
||
songs := r["randomSongs"].(map[string]any)["song"].([]any)
|
||
// The songs come back in the order the list gave them.
|
||
if len(songs) != 2 || songs[0].(map[string]any)["id"] != "tr-71" || songs[1].(map[string]any)["id"] != "tr-70" {
|
||
t.Fatalf("songs %v", songs)
|
||
}
|
||
q := m.lists.songQ[0]
|
||
if !q.Random || q.Size != 2 || q.Genre != "Rock" || q.FromYear != 1990 || q.ToYear != 2000 || q.LibraryID != 1 {
|
||
t.Fatalf("query %+v", q)
|
||
}
|
||
|
||
r = good(t, get(t, m.h, "GET", "/rest/getSongsByGenre", ok("genre", "Rock", "count", "3", "offset", "4")))
|
||
if len(r["songsByGenre"].(map[string]any)["song"].([]any)) != 2 {
|
||
t.Fatalf("songs %v", r)
|
||
}
|
||
if q := m.lists.songQ[1]; q.Random || q.Size != 3 || q.Offset != 4 || q.Genre != "Rock" {
|
||
t.Fatalf("query %+v", q)
|
||
}
|
||
failed(t, get(t, m.h, "GET", "/rest/getSongsByGenre", ok()), ErrMissingParam)
|
||
if m.lists.songQ = nil; true {
|
||
get(t, m.h, "GET", "/rest/getRandomSongs", ok())
|
||
if q := m.lists.songQ[0]; q.Size != 10 {
|
||
t.Fatalf("default size %+v", q)
|
||
}
|
||
}
|
||
}
|
||
|
||
func TestSearchFindsArtistsAlbumsAndSongs(t *testing.T) {
|
||
m := newMediaServer()
|
||
r := good(t, get(t, m.h, "GET", "/rest/search3", ok("query", "", "artistCount", "2", "artistOffset", "1", "albumCount", "5", "songCount", "0")))["searchResult3"].(map[string]any)
|
||
artists := r["artist"].([]any)
|
||
if len(artists) != 2 || artists[0].(map[string]any)["name"] != "Björk" {
|
||
t.Fatalf("artists %v", artists)
|
||
}
|
||
if albums := r["album"].([]any); len(albums) != 1 || albums[0].(map[string]any)["id"] != "al-7" {
|
||
t.Fatalf("albums %v", albums)
|
||
}
|
||
if _, has := r["song"]; has {
|
||
t.Fatalf("songs were not asked for: %v", r["song"])
|
||
}
|
||
failed(t, get(t, m.h, "GET", "/rest/search3", ok()), ErrMissingParam)
|
||
}
|
||
|
||
func TestSearchReadsAsManyAsAskedEvenAboveAPageOfTheCatalogue(t *testing.T) {
|
||
m := newMediaServer()
|
||
// 500 songs asked: the answer is as many as there are, read page by page; the fake has none outside album 7.
|
||
r := good(t, get(t, m.h, "GET", "/rest/search3", ok("query", "x", "songCount", "500", "artistCount", "0", "albumCount", "0")))["searchResult3"].(map[string]any)
|
||
if _, has := r["artist"]; has {
|
||
t.Fatalf("%v", r)
|
||
}
|
||
}
|