sonda/internal/opensubsonic/handler_test.go
tgiachi d6064763e7 fix: OpenSubsonic apps can log in: getUser and the calls that follow
Feishin asks getUser right after the login and failed on the missing user. getUser
now says who the login is, with the roles of an app (play, download, playlists,
covers; never admin), and only about the person of the login.

Also answered with nothing, because apps ask them straight away: getArtistInfo(2),
getAlbumInfo(2), getTopSongs, getSimilarSongs(2), getLyrics, getLyricsBySongId,
getInternetRadioStations, getScanStatus, startScan and the play queue calls, and
getStarred, the older way to ask for the favourites.

A call that is not known is now in the server log with its name.
2026-11-16 11:50:44 +01:00

1405 lines
50 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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/favorites"
"git.kmalloc.org/squid/sonda/internal/images"
"git.kmalloc.org/squid/sonda/internal/library"
"git.kmalloc.org/squid/sonda/internal/listening"
"git.kmalloc.org/squid/sonda/internal/playlists"
"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)
}
all := artists
if f.IDs != nil {
var keep []catalog.Artist
for _, a := range artists {
for _, id := range f.IDs {
if a.ID == id {
keep = append(keep, a)
}
}
}
all = keep
}
return catalog.Page[catalog.Artist]{Items: page(all, f), Total: len(all), 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 TestRatingsAreNotKept(t *testing.T) {
m := newMediaServer()
good(t, get(t, m.h, "GET", "/rest/setRating", ok("id", "tr-70", "rating", "5")))
// An app that has no favourites to ask still gets answers.
good(t, get(t, m.h, "GET", "/rest/star", ok("id", "tr-70")))
s := good(t, get(t, m.h, "GET", "/rest/getStarred2", ok()))["starred2"].(map[string]any)
if len(s) != 0 {
t.Fatalf("starred %v", s)
}
}
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)
}
}
// ---- playlists and listens ----
type fakePlaylists struct {
next int64
lists map[int64]*fakeList
}
type fakeList struct {
name, desc string
items []playlists.Item
nextItem int64
}
func newFakePlaylists() *fakePlaylists { return &fakePlaylists{next: 1, lists: map[int64]*fakeList{}} }
var changedAt = time.Unix(1_700_000_500, 0)
func (f *fakePlaylists) view(id int64, l *fakeList) playlists.Playlist {
p := playlists.Playlist{ID: id, Name: l.name, Description: l.desc, TrackCount: len(l.items), CreatedAt: time.Unix(1_700_000_000, 0), UpdatedAt: changedAt}
for _, it := range l.items {
p.DurationMs += it.Track.DurationMs
}
if len(l.items) > 0 && l.items[0].Track.Album != nil {
p.AlbumIDs = []int64{l.items[0].Track.Album.ID}
}
return p
}
func (f *fakePlaylists) Create(_ context.Context, _ int64, name, desc string) (playlists.Playlist, error) {
if strings.TrimSpace(name) == "" {
return playlists.Playlist{}, playlists.ErrInvalidInput
}
id := f.next
f.next++
f.lists[id] = &fakeList{name: name, desc: desc}
return f.view(id, f.lists[id]), nil
}
func (f *fakePlaylists) List(_ context.Context, _ int64, p playlists.Page) (playlists.Listing, error) {
var all []playlists.Playlist
for id := int64(1); id < f.next; id++ {
if l, ok := f.lists[id]; ok {
all = append(all, f.view(id, l))
}
}
if p.Offset >= len(all) {
return playlists.Listing{Items: []playlists.Playlist{}, Total: len(all)}, nil
}
return playlists.Listing{Items: all[p.Offset:], Total: len(all), Limit: p.Limit, Offset: p.Offset}, nil
}
func (f *fakePlaylists) Get(_ context.Context, _, id int64) (playlists.Playlist, error) {
l, ok := f.lists[id]
if !ok {
return playlists.Playlist{}, playlists.ErrNotFound
}
return f.view(id, l), nil
}
func (f *fakePlaylists) Update(_ context.Context, _, id int64, name, desc *string) (playlists.Playlist, error) {
l, ok := f.lists[id]
if !ok {
return playlists.Playlist{}, playlists.ErrNotFound
}
if name != nil {
l.name = *name
}
if desc != nil {
l.desc = *desc
}
return f.view(id, l), nil
}
func (f *fakePlaylists) Delete(_ context.Context, _, id int64) error {
if _, ok := f.lists[id]; !ok {
return playlists.ErrNotFound
}
delete(f.lists, id)
return nil
}
func (f *fakePlaylists) Items(_ context.Context, _, id int64, p playlists.Page) (playlists.ItemsListing, error) {
l, ok := f.lists[id]
if !ok {
return playlists.ItemsListing{}, playlists.ErrNotFound
}
if p.Offset >= len(l.items) {
return playlists.ItemsListing{Items: []playlists.Item{}, Total: len(l.items)}, nil
}
return playlists.ItemsListing{Items: l.items[p.Offset:], Total: len(l.items), Limit: p.Limit, Offset: p.Offset}, nil
}
func (f *fakePlaylists) AddTracks(_ context.Context, _, id int64, ids []int64, _ *int) (playlists.Playlist, error) {
l, ok := f.lists[id]
if !ok {
return playlists.Playlist{}, playlists.ErrNotFound
}
for _, t := range ids {
var track catalog.Track
switch t {
case 70:
track = airbag
case 71:
track = karma
default:
return playlists.Playlist{}, playlists.ErrTrackNotFound
}
l.nextItem++
l.items = append(l.items, playlists.Item{ID: id*100 + l.nextItem, Position: len(l.items), Track: track, Available: true})
}
return f.view(id, l), nil
}
func (f *fakePlaylists) RemoveItem(_ context.Context, _, id, itemID int64) error {
l, ok := f.lists[id]
if !ok {
return playlists.ErrNotFound
}
for i, it := range l.items {
if it.ID == itemID {
l.items = append(l.items[:i], l.items[i+1:]...)
return nil
}
}
return playlists.ErrItemNotFound
}
type fakeListens struct {
events []listening.Event
announced [][2]int64
}
func (f *fakeListens) Record(_ context.Context, e listening.Event) (listening.Result, error) {
if e.TrackID == 99 {
return listening.Result{}, listening.ErrTrackNotFound
}
for _, old := range f.events {
if old.IdempotencyKey == e.IdempotencyKey {
return listening.Result{Created: false, Counted: true}, nil
}
}
f.events = append(f.events, e)
return listening.Result{Created: true, Counted: true}, nil
}
func (f *fakeListens) Announce(userID, trackID int64) {
f.announced = append(f.announced, [2]int64{userID, trackID})
}
type withLists struct {
h http.Handler
lists *fakePlaylists
listens *fakeListens
}
func newListServer() withLists {
gin.SetMode(gin.TestMode)
w := withLists{lists: newFakePlaylists(), listens: &fakeListens{}}
r := gin.New()
Register(r, Deps{
Login: fakeLogin{}, Catalog: &fakeCatalog{}, Libraries: fakeLibraries{}, Extras: fakeExtras{}, ServerVersion: "9.9",
Playlists: w.lists, Listens: w.listens, Announcer: w.listens,
})
w.h = r
return w
}
func ids(r map[string]any) []string {
var out []string
for _, e := range r["entry"].([]any) {
out = append(out, e.(map[string]any)["id"].(string))
}
return out
}
func (w withLists) q(extra ...string) url.Values { return ok(extra...) }
func TestAPlaylistIsMadeWithItsSongs(t *testing.T) {
w := newListServer()
q := ok("name", "Evening")
q.Add("songId", "tr-70")
q.Add("songId", "tr-71")
p := good(t, get(t, w.h, "POST", "/rest/createPlaylist", q))["playlist"].(map[string]any)
if p["id"] != "pl-1" || p["name"] != "Evening" || p["songCount"].(float64) != 2 || p["owner"] != "tom@example.org" || p["public"] != false ||
p["duration"].(float64) != 548 || p["coverArt"] != "al-7" {
t.Fatalf("playlist %v", p)
}
if got := strings.Join(ids(p), ","); got != "tr-70,tr-71" {
t.Fatalf("entries %s", got)
}
if p["changed"] != "2023-11-14T22:21:40.000Z" || p["created"] != "2023-11-14T22:13:20.000Z" {
t.Fatalf("dates %v %v", p["created"], p["changed"])
}
// With no name and no playlist there is nothing to make.
failed(t, get(t, w.h, "GET", "/rest/createPlaylist", ok()), ErrMissingParam)
failed(t, get(t, w.h, "GET", "/rest/createPlaylist", ok("name", " ")), ErrGeneric)
bad := ok("name", "x")
bad.Add("songId", "tr-99")
failed(t, get(t, w.h, "GET", "/rest/createPlaylist", bad), ErrNotFound)
bad = ok("name", "x")
bad.Add("songId", "al-7")
failed(t, get(t, w.h, "GET", "/rest/createPlaylist", bad), ErrNotFound)
}
func TestAPlaylistThatExistsIsReplaced(t *testing.T) {
w := newListServer()
q := ok("name", "Evening")
q.Add("songId", "tr-70")
q.Add("songId", "tr-71")
get(t, w.h, "GET", "/rest/createPlaylist", q)
q = ok("playlistId", "pl-1")
q.Add("songId", "tr-71")
p := good(t, get(t, w.h, "GET", "/rest/createPlaylist", q))["playlist"].(map[string]any)
if p["name"] != "Evening" || strings.Join(ids(p), ",") != "tr-71" {
t.Fatalf("playlist %v", p)
}
failed(t, get(t, w.h, "GET", "/rest/createPlaylist", ok("playlistId", "pl-9")), ErrNotFound)
}
func TestPlaylistsAreListedAndOpened(t *testing.T) {
w := newListServer()
q := ok("name", "One")
q.Add("songId", "tr-70")
get(t, w.h, "GET", "/rest/createPlaylist", q)
get(t, w.h, "GET", "/rest/createPlaylist", ok("name", "Two"))
list := good(t, get(t, w.h, "GET", "/rest/getPlaylists", ok()))["playlists"].(map[string]any)["playlist"].([]any)
if len(list) != 2 || list[0].(map[string]any)["name"] != "One" || list[0].(map[string]any)["songCount"].(float64) != 1 {
t.Fatalf("playlists %v", list)
}
if _, has := list[0].(map[string]any)["entry"]; has {
t.Fatalf("the list holds the songs: %v", list[0])
}
p := good(t, get(t, w.h, "GET", "/rest/getPlaylist", ok("id", "pl-1")))["playlist"].(map[string]any)
if strings.Join(ids(p), ",") != "tr-70" || p["entry"].([]any)[0].(map[string]any)["title"] != "Airbag" {
t.Fatalf("playlist %v", p)
}
empty := good(t, get(t, w.h, "GET", "/rest/getPlaylist", ok("id", "pl-2")))["playlist"].(map[string]any)
if _, has := empty["entry"]; has || empty["songCount"].(float64) != 0 {
t.Fatalf("empty playlist %v", empty)
}
for _, id := range []string{"pl-9", "tr-70", "1", "pl-x"} {
failed(t, get(t, w.h, "GET", "/rest/getPlaylist", ok("id", id)), ErrNotFound)
}
failed(t, get(t, w.h, "GET", "/rest/getPlaylist", ok()), ErrMissingParam)
}
func TestAPlaylistIsChangedAndDeleted(t *testing.T) {
w := newListServer()
q := ok("name", "One")
q.Add("songId", "tr-70")
q.Add("songId", "tr-71")
get(t, w.h, "GET", "/rest/createPlaylist", q)
// Rename, comment, add one song, take out the first (by its place in the list).
u := ok("playlistId", "pl-1", "name", "Renamed", "comment", "for the car")
u.Add("songIdToAdd", "tr-70")
u.Add("songIndexToRemove", "0")
good(t, get(t, w.h, "GET", "/rest/updatePlaylist", u))
p := good(t, get(t, w.h, "GET", "/rest/getPlaylist", ok("id", "pl-1")))["playlist"].(map[string]any)
if p["name"] != "Renamed" || p["comment"] != "for the car" || strings.Join(ids(p), ",") != "tr-71,tr-70" {
t.Fatalf("playlist %v", p)
}
r := ok("playlistId", "pl-1")
r.Add("songIndexToRemove", "5")
failed(t, get(t, w.h, "GET", "/rest/updatePlaylist", r), ErrGeneric)
failed(t, get(t, w.h, "GET", "/rest/updatePlaylist", ok("playlistId", "pl-9", "name", "x")), ErrNotFound)
failed(t, get(t, w.h, "GET", "/rest/updatePlaylist", ok()), ErrMissingParam)
good(t, get(t, w.h, "GET", "/rest/deletePlaylist", ok("id", "pl-1")))
failed(t, get(t, w.h, "GET", "/rest/getPlaylist", ok("id", "pl-1")), ErrNotFound)
failed(t, get(t, w.h, "GET", "/rest/deletePlaylist", ok("id", "pl-1")), ErrNotFound)
failed(t, get(t, w.h, "GET", "/rest/deletePlaylist", ok()), ErrMissingParam)
}
func TestAListenIsRecordedOnceWhateverTheNumberOfTries(t *testing.T) {
w := newListServer()
q := ok("submission", "true", "time", "1700000000000")
q.Add("id", "tr-70")
good(t, get(t, w.h, "GET", "/rest/scrobble", q))
good(t, get(t, w.h, "GET", "/rest/scrobble", q)) // an app tries again
if len(w.listens.events) != 1 {
t.Fatalf("events %+v", w.listens.events)
}
e := w.listens.events[0]
if e.UserID != 1 || e.TrackID != 70 || e.Type != listening.Complete || e.OccurredAt.UnixMilli() != 1_700_000_000_000 || e.DurationPlayedMs != 284_000 || e.IdempotencyKey == "" {
t.Fatalf("event %+v", e)
}
if len(w.listens.announced) != 1 || w.listens.announced[0] != [2]int64{1, 70} {
t.Fatalf("announced %v", w.listens.announced)
}
}
func TestSeveralListensWithTheirTimes(t *testing.T) {
w := newListServer()
q := ok()
q.Add("id", "tr-70")
q.Add("id", "tr-71")
q.Add("time", "1700000000000")
q.Add("time", "1700000300000")
good(t, get(t, w.h, "GET", "/rest/scrobble", q))
if len(w.listens.events) != 2 || w.listens.events[1].TrackID != 71 || w.listens.events[1].OccurredAt.UnixMilli() != 1_700_000_300_000 {
t.Fatalf("events %+v", w.listens.events)
}
if w.listens.events[0].IdempotencyKey == w.listens.events[1].IdempotencyKey {
t.Fatal("two listens share a key")
}
}
func TestAListenWithNoTimeIsNow(t *testing.T) {
w := newListServer()
before := time.Now()
good(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "tr-70")))
if at := w.listens.events[0].OccurredAt; at.Before(before.Add(-time.Second)) || at.After(time.Now().Add(time.Second)) {
t.Fatalf("occurred at %v", at)
}
}
func TestANowPlayingMessageIsNotAListen(t *testing.T) {
w := newListServer()
good(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "tr-70", "submission", "false")))
if len(w.listens.events) != 0 || len(w.listens.announced) != 0 {
t.Fatalf("events %+v", w.listens.events)
}
np := good(t, get(t, w.h, "GET", "/rest/getNowPlaying", ok()))["nowPlaying"].(map[string]any)
if len(np) != 0 {
t.Fatalf("now playing %v", np)
}
}
func TestAListenOfWhatIsNotThereOrIsBadlyAskedFor(t *testing.T) {
w := newListServer()
failed(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "tr-99")), ErrNotFound)
failed(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "al-7")), ErrNotFound)
failed(t, get(t, w.h, "GET", "/rest/scrobble", ok()), ErrMissingParam)
failed(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "tr-70", "time", "soon")), ErrGeneric)
failed(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "tr-70", "submission", "maybe")), ErrGeneric)
if len(w.listens.events) != 0 {
t.Fatalf("events %+v", w.listens.events)
}
}
// ---- favourites ----
type fakeFavorites struct {
at map[string]time.Time // kind + id -> when
last time.Time
}
func newFakeFavorites() *fakeFavorites { return &fakeFavorites{at: map[string]time.Time{}} }
func fkey(kind favorites.Kind, id int64) string { return string(kind) + fmt.Sprint(id) }
var exists = map[string]bool{"artist1": true, "artist4": true, "album7": true, "track70": true, "track71": true}
func (f *fakeFavorites) Add(_ context.Context, _ int64, kind favorites.Kind, id int64) error {
if !exists[fkey(kind, id)] {
return favorites.ErrNotFound
}
f.last = f.last.Add(time.Minute)
f.at[fkey(kind, id)] = f.last
return nil
}
func (f *fakeFavorites) Remove(_ context.Context, _ int64, kind favorites.Kind, id int64) error {
delete(f.at, fkey(kind, id))
return nil
}
func (f *fakeFavorites) IDs(_ context.Context, _ int64) (favorites.All, error) {
all := favorites.All{Artists: []int64{}, Albums: []int64{}, Tracks: []int64{}}
// Newest first, as the real one: the order the tests mark them in, backwards.
for _, id := range []int64{71, 70} {
if _, ok := f.at[fkey(favorites.Track, id)]; ok {
all.Tracks = append(all.Tracks, id)
}
}
if _, ok := f.at[fkey(favorites.Album, 7)]; ok {
all.Albums = append(all.Albums, 7)
}
for _, id := range []int64{4, 1} {
if _, ok := f.at[fkey(favorites.Artist, id)]; ok {
all.Artists = append(all.Artists, id)
}
}
return all, nil
}
func (f *fakeFavorites) Marks(_ context.Context, _ int64, kind favorites.Kind, ids []int64) (map[int64]time.Time, error) {
out := map[int64]time.Time{}
for _, id := range ids {
if at, ok := f.at[fkey(kind, id)]; ok {
out[id] = at
}
}
return out, nil
}
func newStarServer() (http.Handler, *fakeFavorites) {
gin.SetMode(gin.TestMode)
fav := newFakeFavorites()
fav.last = time.Unix(1_700_000_000, 0)
r := gin.New()
Register(r, Deps{Login: fakeLogin{}, Catalog: &fakeCatalog{}, Libraries: fakeLibraries{}, Extras: fakeExtras{}, ServerVersion: "9.9", Favorites: fav})
return r, fav
}
func TestSongsAlbumsAndArtistsAreStarredAndUnstarred(t *testing.T) {
h, fav := newStarServer()
q := ok()
q.Add("id", "tr-70")
q.Add("id", "tr-71")
q.Add("albumId", "al-7")
q.Add("artistId", "ar-1")
good(t, get(t, h, "GET", "/rest/star", q))
if len(fav.at) != 4 {
t.Fatalf("starred %v", fav.at)
}
// An id of any kind is understood by its prefix, in whichever parameter it comes.
other := ok()
other.Add("id", "ar-4")
good(t, get(t, h, "GET", "/rest/star", other))
if _, ok := fav.at["artist4"]; !ok {
t.Fatalf("starred %v", fav.at)
}
un := ok()
un.Add("id", "tr-70")
un.Add("artistId", "ar-4")
good(t, get(t, h, "GET", "/rest/unstar", un))
if _, ok := fav.at["track70"]; ok {
t.Fatalf("still starred %v", fav.at)
}
if len(fav.at) != 3 {
t.Fatalf("starred %v", fav.at)
}
good(t, get(t, h, "GET", "/rest/unstar", un)) // what is not starred is not an error
}
func TestWhatCannotBeStarredIsNotFound(t *testing.T) {
h, fav := newStarServer()
for _, id := range []string{"tr-99", "al-8", "ar-2", "pl-1", "70", "tr-x"} {
q := ok()
q.Add("id", id)
failed(t, get(t, h, "GET", "/rest/star", q), ErrNotFound)
}
failed(t, get(t, h, "GET", "/rest/star", ok()), ErrMissingParam)
failed(t, get(t, h, "GET", "/rest/unstar", ok()), ErrMissingParam)
if len(fav.at) != 0 {
t.Fatalf("starred %v", fav.at)
}
}
func TestStarredThingsAreListedAndMarkedWithTheirDate(t *testing.T) {
h, _ := newStarServer()
q := ok()
q.Add("id", "tr-70")
q.Add("id", "tr-71")
q.Add("albumId", "al-7")
q.Add("artistId", "ar-1")
good(t, get(t, h, "GET", "/rest/star", q))
s := good(t, get(t, h, "GET", "/rest/getStarred2", ok()))["starred2"].(map[string]any)
songs, albums, artists := s["song"].([]any), s["album"].([]any), s["artist"].([]any)
if len(songs) != 2 || songs[0].(map[string]any)["id"] != "tr-71" || len(albums) != 1 || len(artists) != 1 {
t.Fatalf("starred %v", s)
}
if songs[0].(map[string]any)["starred"] == nil || artists[0].(map[string]any)["starred"] == nil || albums[0].(map[string]any)["starred"] == nil {
t.Fatalf("no date on %v", s)
}
// Everywhere a song, an album or an artist is told, the date is there when it is starred.
al := good(t, get(t, h, "GET", "/rest/getAlbum", ok("id", "al-7")))["album"].(map[string]any)
if al["starred"] == nil || al["song"].([]any)[0].(map[string]any)["starred"] == nil {
t.Fatalf("album %v", al)
}
ar := good(t, get(t, h, "GET", "/rest/getArtist", ok("id", "ar-1")))["artist"].(map[string]any)
if ar["starred"] == nil {
t.Fatalf("artist %v", ar)
}
idx := good(t, get(t, h, "GET", "/rest/getArtists", ok()))["artists"].(map[string]any)["index"].([]any)
var starred, plain int
for _, g := range idx {
for _, a := range g.(map[string]any)["artist"].([]any) {
if a.(map[string]any)["starred"] != nil {
starred++
} else {
plain++
}
}
}
if starred != 1 || plain != 3 {
t.Fatalf("starred %d, not %d", starred, plain)
}
if song := good(t, get(t, h, "GET", "/rest/getSong", ok("id", "tr-70")))["song"].(map[string]any); song["starred"] == nil {
t.Fatalf("song %v", song)
}
un := ok()
un.Add("id", "tr-70")
good(t, get(t, h, "GET", "/rest/unstar", un))
if song := good(t, get(t, h, "GET", "/rest/getSong", ok("id", "tr-70")))["song"].(map[string]any); song["starred"] != nil {
t.Fatalf("song %v", song)
}
if n := len(good(t, get(t, h, "GET", "/rest/getStarred2", ok()))["starred2"].(map[string]any)["song"].([]any)); n != 1 {
t.Fatalf("starred songs %d", n)
}
}
// ---- what an app asks for as soon as it has logged in ----
func TestAnAppAsksWhoItIsAndGetsNoPowerOverTheServer(t *testing.T) {
h, _ := newTestServer()
u := good(t, get(t, h, "GET", "/rest/getUser.view", ok("username", "tom@example.org")))["user"].(map[string]any)
if u["username"] != "tom@example.org" || u["email"] != "tom@example.org" || u["scrobblingEnabled"] != true {
t.Fatalf("user %v", u)
}
// An app is for the music: it can play, make playlists and read covers, and it is never an admin.
for role, want := range map[string]bool{
"adminRole": false, "settingsRole": false, "uploadRole": false, "podcastRole": false, "jukeboxRole": false, "shareRole": false,
"commentRole": false, "videoConversionRole": false,
"streamRole": true, "downloadRole": true, "playlistRole": true, "coverArtRole": true,
} {
if got, ok := u[role].(bool); !ok || got != want {
t.Errorf("%s = %v, want %v", role, u[role], want)
}
}
if f := u["folder"].([]any); len(f) != 2 || f[0].(float64) != 1 || f[1].(float64) != 2 {
t.Errorf("folders %v", f)
}
// No name asked for: the person of the login.
if u := good(t, get(t, h, "GET", "/rest/getUser", ok()))["user"].(map[string]any); u["username"] != "tom@example.org" {
t.Errorf("user %v", u)
}
// Another person is not for an app to look at.
failed(t, get(t, h, "GET", "/rest/getUser", ok("username", "ann@example.org")), ErrNotAuthorized)
if u := good(t, get(t, h, "GET", "/rest/getUser", ok("username", "TOM@example.org")))["user"].(map[string]any); u["username"] != "tom@example.org" {
t.Errorf("the same address in capitals: %v", u)
}
}
func TestWhatAnAppAsksThatSondaDoesNotKnowAnswersWithNothing(t *testing.T) {
h, _ := newTestServer()
for method, key := range map[string]string{
"getArtistInfo2": "artistInfo2",
"getArtistInfo": "artistInfo",
"getAlbumInfo2": "albumInfo",
"getAlbumInfo": "albumInfo",
"getTopSongs": "topSongs",
"getSimilarSongs": "similarSongs",
"getSimilarSongs2": "similarSongs2",
"getInternetRadioStations": "internetRadioStations",
"getScanStatus": "scanStatus",
} {
r := good(t, get(t, h, "GET", "/rest/"+method, ok("id", "ar-1")))
if _, has := r[key].(map[string]any); !has {
t.Errorf("%s: no %s in %v", method, key, r)
}
}
if s := good(t, get(t, h, "GET", "/rest/getScanStatus", ok()))["scanStatus"].(map[string]any); s["scanning"] != false {
t.Errorf("scan status %v", s)
}
// A saved queue is not kept: there is none, and saving one is not an error.
good(t, get(t, h, "GET", "/rest/getPlayQueue", ok()))
good(t, get(t, h, "POST", "/rest/savePlayQueue", ok("id", "tr-70")))
// These need a login like the rest.
failed(t, get(t, h, "GET", "/rest/getUser", url.Values{"f": {"json"}}), ErrMissingParam)
}
func TestTheOlderCallsOfAnAppAreAnsweredToo(t *testing.T) {
h, _ := newStarServer()
q := ok()
q.Add("id", "tr-70")
good(t, get(t, h, "GET", "/rest/star", q))
s := good(t, get(t, h, "GET", "/rest/getStarred", ok()))["starred"].(map[string]any)
if songs := s["song"].([]any); len(songs) != 1 || songs[0].(map[string]any)["id"] != "tr-70" {
t.Fatalf("starred %v", s)
}
for method, key := range map[string]string{"getLyricsBySongId": "lyricsList", "getLyrics": "lyrics", "startScan": "scanStatus"} {
if r := good(t, get(t, h, "GET", "/rest/"+method, ok("id", "tr-70"))); r[key] == nil {
t.Errorf("%s: %v", method, r)
}
}
good(t, get(t, h, "GET", "/rest/getPlayQueueByIndex", ok()))
good(t, get(t, h, "POST", "/rest/savePlayQueueByIndex", ok("id", "tr-70", "currentIndex", "0")))
}