diff --git a/cmd/sondad/main.go b/cmd/sondad/main.go index 3856e8f..6d91ef7 100644 --- a/cmd/sondad/main.go +++ b/cmd/sondad/main.go @@ -34,6 +34,7 @@ import ( "git.kmalloc.org/squid/sonda/internal/mastodon" "git.kmalloc.org/squid/sonda/internal/mixes" "git.kmalloc.org/squid/sonda/internal/naming" + "git.kmalloc.org/squid/sonda/internal/opensubsonic" "git.kmalloc.org/squid/sonda/internal/playlists" "git.kmalloc.org/squid/sonda/internal/providers" "git.kmalloc.org/squid/sonda/internal/providers/anthropic" @@ -299,18 +300,26 @@ func run() error { mastodonSvc := mastodon.NewService(storage.NewMastodonRepo(db), mastodon.NewRemote(providers.UserAgent(version, "")), logger) go mastodonSvc.Run(ctx) + // Other apps (OpenSubsonic) log in with the password of a device, never with the account password. + deviceSvc := devices.NewService(storage.NewDevicesRepo(db), []byte(cfg.Auth.JWTSecret)) + catalogSvc := catalog.NewService(storage.NewCatalogRepo(db)) + router := httpapi.NewRouter(httpapi.Deps{ - Logger: logger, - Build: build(), - Stats: stats.NewService(storage.NewStatsRepo(db), cfg.Listening.MinListen()), - Auth: auth.NewService(storage.NewUserRepo(db), storage.NewRefreshRepo(db), tokens, cfg.Auth.RefreshTTL()), - Tokens: tokens, - Listening: listening.NewService(storage.NewListeningRepo(db), cfg.Listening.MinListen()), - Mastodon: mastodonSvc, - Devices: devices.NewService(storage.NewDevicesRepo(db), []byte(cfg.Auth.JWTSecret)), + Logger: logger, + Build: build(), + Stats: stats.NewService(storage.NewStatsRepo(db), cfg.Listening.MinListen()), + Auth: auth.NewService(storage.NewUserRepo(db), storage.NewRefreshRepo(db), tokens, cfg.Auth.RefreshTTL()), + Tokens: tokens, + Listening: listening.NewService(storage.NewListeningRepo(db), cfg.Listening.MinListen()), + Mastodon: mastodonSvc, + Devices: deviceSvc, + OpenSubsonic: &opensubsonic.Deps{ + Login: deviceSvc, Catalog: catalogSvc, Libraries: libraries, + Extras: storage.NewSubsonicRepo(db), ServerVersion: version, + }, Scan: scanControl{ctx: ctx, m: scans}, Libraries: libraries, - Catalog: catalog.NewService(storage.NewCatalogRepo(db)), + Catalog: catalogSvc, Providers: providerSettings, Lidarr: lidarrClient, LidarrArtists: lidarr.NewService(discoveryRepo, providerSettings, lidarrClient), diff --git a/internal/api/http/api_test.go b/internal/api/http/api_test.go index 2e82e6a..e0dc35b 100644 --- a/internal/api/http/api_test.go +++ b/internal/api/http/api_test.go @@ -32,6 +32,7 @@ import ( "git.kmalloc.org/squid/sonda/internal/mastodon" "git.kmalloc.org/squid/sonda/internal/mixes" "git.kmalloc.org/squid/sonda/internal/naming" + "git.kmalloc.org/squid/sonda/internal/opensubsonic" "git.kmalloc.org/squid/sonda/internal/playlists" "git.kmalloc.org/squid/sonda/internal/providers" "git.kmalloc.org/squid/sonda/internal/providers/anthropic" @@ -140,6 +141,12 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun deps.CoversJob = jobs.Runner{Ctx: context.Background(), Job: images.NewCoversJob(imageSvc, imageRepo)} deps.ArtistImagesJob = jobs.Runner{Ctx: context.Background(), Job: images.NewArtistImagesJob(imageSvc, imageRepo)} mutate(&deps, db) + if deps.OpenSubsonic == nil { + deps.OpenSubsonic = &opensubsonic.Deps{ + Login: deps.Devices.(opensubsonic.Login), Catalog: deps.Catalog.(opensubsonic.Catalog), + Libraries: deps.Libraries.(opensubsonic.Libraries), Extras: storage.NewSubsonicRepo(db), ServerVersion: "test", + } + } if deps.About == nil { deps.About = about.NewService(storage.NewDiscoveryRepo(db), noWikipedia{}, prov, []string{"en"}, zap.NewNop()) } diff --git a/internal/api/http/opensubsonic_test.go b/internal/api/http/opensubsonic_test.go new file mode 100644 index 0000000..164309c --- /dev/null +++ b/internal/api/http/opensubsonic_test.go @@ -0,0 +1,110 @@ +package httpapi + +import ( + "crypto/md5" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "testing" +) + +// rest asks the API for a call of /rest and returns the answer inside subsonic-response. +func rest(t *testing.T, h http.Handler, method string, q url.Values) map[string]any { + t.Helper() + q.Set("f", "json") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("GET", "/rest/"+method+"?"+q.Encode(), nil)) + 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("%s: not an answer: %v: %s", method, err, rec.Body.String()) + } + return out.R +} + +func errorCode(r map[string]any) int { + e, _ := r["error"].(map[string]any) + if e == nil { + return -1 + } + return int(e["code"].(float64)) +} + +func TestAnAppLogsInWithThePasswordOfADevice(t *testing.T) { + h := newTestAPI(t) + alice := registerAndLogin(t, h) + made := do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "Feishin"}) + secret, _ := made.Body["secret"].(string) + id := itoa(int64(made.Body["id"].(float64))) + + if r := rest(t, h, "ping", url.Values{"apiKey": {secret}}); r["status"] != "ok" { + t.Fatalf("API key: %v", r) + } + if r := rest(t, h, "ping", url.Values{"u": {"alice@example.org"}, "p": {secret}}); r["status"] != "ok" { + t.Fatalf("password: %v", r) + } + salt := "c19f3a" + sum := md5.Sum([]byte(secret + salt)) + token := hex.EncodeToString(sum[:]) + if r := rest(t, h, "ping", url.Values{"u": {"Alice@Example.org"}, "t": {token}, "s": {salt}}); r["status"] != "ok" { + t.Fatalf("token: %v", r) + } + if r := rest(t, h, "tokenInfo", url.Values{"apiKey": {secret}}); r["tokenInfo"].(map[string]any)["username"] != "alice@example.org" { + t.Fatalf("token info: %v", r) + } + + // The use of the device shows in the list. + list := do(t, h, "GET", "/api/v1/me/devices", alice, nil).Body["devices"].([]any) + if _, used := list[0].(map[string]any)["last_used_at"]; !used { + t.Fatalf("the device was used but the list does not say: %v", list) + } + + // The password of the account is not a password for apps. + if r := rest(t, h, "ping", url.Values{"u": {"alice@example.org"}, "p": {"longenough"}}); errorCode(r) != 40 { + t.Fatalf("account password: %v", r) + } + if r := rest(t, h, "ping", url.Values{"apiKey": {"longenough"}}); errorCode(r) != 44 { + t.Fatalf("account password as a key: %v", r) + } + + // A device that is taken back stops working at once. + if r := do(t, h, "DELETE", "/api/v1/me/devices/"+id, alice, nil); r.Code != http.StatusNoContent { + t.Fatalf("revoke: %d", r.Code) + } + for name, q := range map[string]url.Values{ + "key": {"apiKey": {secret}}, + "password": {"u": {"alice@example.org"}, "p": {secret}}, + "token": {"u": {"alice@example.org"}, "t": {token}, "s": {salt}}, + } { + if r := rest(t, h, "ping", q); r["status"] != "failed" { + t.Errorf("%s after revoke: %v", name, r) + } + } +} + +func TestADeviceOpensTheMusicAndNotTheAccount(t *testing.T) { + h := newTestAPI(t) + alice := registerAndLogin(t, h) + secret := do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "Phone"}).Body["secret"].(string) + + // The secret is not a token of the main API, in any of the places a token can be. + if r := do(t, h, "GET", "/api/v1/me/devices", secret, nil); r.Code != http.StatusUnauthorized { + t.Fatalf("secret as a bearer token: %d", r.Code) + } + if r := do(t, h, "GET", "/api/v1/me/devices?access_token="+secret, "", nil); r.Code != http.StatusUnauthorized { + t.Fatalf("secret as an access_token: %d", r.Code) + } + + // An empty library answers with empty lists. + r := rest(t, h, "getArtists", url.Values{"apiKey": {secret}}) + if r["status"] != "ok" || len(r["artists"].(map[string]any)["index"].([]any)) != 0 { + t.Fatalf("artists of nothing: %v", r) + } + r = rest(t, h, "getGenres", url.Values{"apiKey": {secret}}) + if r["status"] != "ok" { + t.Fatalf("genres of nothing: %v", r) + } +} diff --git a/internal/api/http/router.go b/internal/api/http/router.go index 0cc6d5b..c71aaa2 100644 --- a/internal/api/http/router.go +++ b/internal/api/http/router.go @@ -28,6 +28,7 @@ import ( "git.kmalloc.org/squid/sonda/internal/mastodon" "git.kmalloc.org/squid/sonda/internal/mixes" "git.kmalloc.org/squid/sonda/internal/naming" + "git.kmalloc.org/squid/sonda/internal/opensubsonic" "git.kmalloc.org/squid/sonda/internal/playlists" "git.kmalloc.org/squid/sonda/internal/providers" "git.kmalloc.org/squid/sonda/internal/smart" @@ -268,6 +269,8 @@ type Deps struct { PeerCovers coverService // The shape of a track, for the seek bar. Waveform waveformService + // OpenSubsonic is the API that other apps use, at /rest. It is optional: with none, /rest does not exist. + OpenSubsonic *opensubsonic.Deps // Web is the built web app, served on / and for its own links. It is optional: with none (a build // without the app) / shows a page that says how to build it, and the API works the same. Web fs.FS @@ -299,6 +302,9 @@ func NewRouter(d Deps) *gin.Engine { r := gin.New() _ = r.SetTrustedProxies(nil) // use the socket address; no forwarded-header trust yet r.Use(gin.Recovery(), limitBody(maxBodyBytes), requestLog(d.Logger)) + if d.OpenSubsonic != nil { + opensubsonic.Register(r, *d.OpenSubsonic) + } r.NoRoute(noRoute(d.Web)) v1 := r.Group("/api/v1") diff --git a/internal/devices/devices.go b/internal/devices/devices.go index 01aa66a..71cf6b8 100644 --- a/internal/devices/devices.go +++ b/internal/devices/devices.go @@ -15,8 +15,10 @@ import ( "crypto/aes" "crypto/cipher" "crypto/hkdf" + "crypto/md5" //nolint:gosec // Subsonic's token login is md5(secret + salt): the protocol asks for it. "crypto/rand" "crypto/sha256" + "crypto/subtle" "encoding/hex" "errors" "fmt" @@ -31,6 +33,8 @@ var ( ErrNotFound = errors.New("device not found") ErrInvalidName = errors.New("the name must have 1 to 60 characters") ErrTooMany = errors.New("there are too many devices: remove one first") + // ErrBadCredentials is every way a login can fail: a wrong secret, a wrong person, none at all. + ErrBadCredentials = errors.New("wrong user name or password") ) const ( @@ -39,6 +43,8 @@ const ( // MaxName is the longest name, in characters. MaxName = 60 secretSize = 24 + // touchEvery is how often the use of a device is noted: a client asks all the time. + touchEvery = 10 * time.Minute ) // Device is what a person sees of a device: never the secret. @@ -56,6 +62,7 @@ type Row struct { Name string KeyHash string // hex sha256 of the secret, to find it when only the secret is known Sealed []byte // the secret, sealed + Email string // the address of the person: only when the row comes from a lookup by key or by address CreatedAt time.Time LastUsedAt *time.Time } @@ -68,6 +75,13 @@ type Store interface { List(ctx context.Context, userID int64) ([]Row, error) // Delete removes a device of a person, with ErrNotFound when there is none. Delete(ctx context.Context, userID, id int64) error + // ByKeyHash finds a device by the hash of its secret, with the address of its person, or ErrNotFound. + ByKeyHash(ctx context.Context, hash string) (Row, error) + // ByEmail returns the devices of the person with that address (lower case), with the address; none when + // there is no such person. + ByEmail(ctx context.Context, email string) ([]Row, error) + // Touch notes when a device was last used. + Touch(ctx context.Context, id int64, at time.Time) error } // Service makes and takes back device passwords. @@ -171,3 +185,80 @@ func KeyHash(secret string) string { func device(r Row) Device { return Device{ID: r.ID, Name: r.Name, CreatedAt: r.CreatedAt, LastUsedAt: r.LastUsedAt} } + +// Principal is who a login of a device is: the person, and which of their devices it was. +type Principal struct { + UserID int64 + DeviceID int64 + Email string +} + +// ByKey logs in with an API key, which is the secret of a device. +func (s *Service) ByKey(ctx context.Context, key string) (Principal, error) { + if key == "" { + return Principal{}, ErrBadCredentials + } + row, err := s.store.ByKeyHash(ctx, KeyHash(key)) + if errors.Is(err, ErrNotFound) { + return Principal{}, ErrBadCredentials + } + if err != nil { + return Principal{}, fmt.Errorf("find device: %w", err) + } + return s.used(ctx, row), nil +} + +// ByToken logs in the Subsonic way: the person's address and md5(secret + salt) of one of their devices. +func (s *Service) ByToken(ctx context.Context, email, token, salt string) (Principal, error) { + token = strings.ToLower(token) + return s.match(ctx, email, func(secret string) bool { + if token == "" || salt == "" { + return false + } + sum := md5.Sum([]byte(secret + salt)) //nolint:gosec // see the import + return same(hex.EncodeToString(sum[:]), token) + }) +} + +// ByPassword logs in with a person's address and the secret of one of their devices, written as it is or as +// "enc:" and its bytes in hex. +func (s *Service) ByPassword(ctx context.Context, email, password string) (Principal, error) { + if rest, ok := strings.CutPrefix(password, "enc:"); ok { + raw, err := hex.DecodeString(rest) + if err != nil { + return Principal{}, ErrBadCredentials + } + password = string(raw) + } + return s.match(ctx, email, func(secret string) bool { return password != "" && same(secret, password) }) +} + +// match finds the device of the person whose secret the check accepts. It opens every device of the person, which is +// at most MaxDevices. +func (s *Service) match(ctx context.Context, email string, ok func(secret string) bool) (Principal, error) { + rows, err := s.store.ByEmail(ctx, strings.ToLower(strings.TrimSpace(email))) + if err != nil { + return Principal{}, fmt.Errorf("find devices: %w", err) + } + found := -1 + for i, r := range rows { + secret, err := s.Reveal(r.Sealed) + if err == nil && ok(secret) && found < 0 { + found = i // keep going: the time must not tell which device it was + } + } + if found < 0 { + return Principal{}, ErrBadCredentials + } + return s.used(ctx, rows[found]), nil +} + +func (s *Service) used(ctx context.Context, r Row) Principal { + now := s.now() + if r.LastUsedAt == nil || now.Sub(*r.LastUsedAt) >= touchEvery { + _ = s.store.Touch(ctx, r.ID, now) // a failure to note the use does not stop the login + } + return Principal{UserID: r.UserID, DeviceID: r.ID, Email: r.Email} +} + +func same(a, b string) bool { return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 } diff --git a/internal/devices/devices_test.go b/internal/devices/devices_test.go index 4d676fa..c485132 100644 --- a/internal/devices/devices_test.go +++ b/internal/devices/devices_test.go @@ -3,6 +3,8 @@ package devices import ( "bytes" "context" + "crypto/md5" + "encoding/hex" "errors" "strings" "testing" @@ -11,8 +13,44 @@ import ( // memStore keeps the rows in memory, like the database would, and lets a test look at what was stored. type memStore struct { - rows []Row - nextID int64 + rows []Row + nextID int64 + emails map[int64]string // user id -> email + touched map[int64]time.Time +} + +func (m *memStore) ByKeyHash(_ context.Context, hash string) (Row, error) { + for _, r := range m.rows { + if r.KeyHash == hash { + r.Email = m.emails[r.UserID] + return r, nil + } + } + return Row{}, ErrNotFound +} + +func (m *memStore) ByEmail(_ context.Context, email string) ([]Row, error) { + var out []Row + for _, r := range m.rows { + if m.emails[r.UserID] == email { + r.Email = email + out = append(out, r) + } + } + return out, nil +} + +func (m *memStore) Touch(_ context.Context, id int64, at time.Time) error { + if m.touched == nil { + m.touched = map[int64]time.Time{} + } + m.touched[id] = at + for i := range m.rows { + if m.rows[i].ID == id { + m.rows[i].LastUsedAt = &at + } + } + return nil } func (m *memStore) Create(_ context.Context, r Row) (Row, error) { @@ -43,7 +81,7 @@ func (m *memStore) Delete(_ context.Context, userID, id int64) error { } func newService() (*Service, *memStore) { - st := &memStore{} + st := &memStore{emails: map[int64]string{1: "alice@example.org", 2: "bob@example.org"}} s := NewService(st, []byte(strings.Repeat("k", 32))) s.now = func() time.Time { return time.Unix(1_700_000_000, 0) } return s, st @@ -146,3 +184,89 @@ func TestRevokeIsForTheOwnerOnly(t *testing.T) { t.Fatalf("twice: %v", err) } } + +func md5hex(s string) string { + sum := md5.Sum([]byte(s)) + return hex.EncodeToString(sum[:]) +} + +func TestAnApiKeyFindsItsDevice(t *testing.T) { + s, st := newService() + d, secret, _ := s.Create(context.Background(), 1, "Phone") + p, err := s.ByKey(context.Background(), secret) + if err != nil || p.UserID != 1 || p.DeviceID != d.ID || p.Email != "alice@example.org" { + t.Fatalf("ByKey = %+v, %v", p, err) + } + if _, err := s.ByKey(context.Background(), strings.Repeat("0", 48)); !errors.Is(err, ErrBadCredentials) { + t.Fatalf("a key nobody has: %v", err) + } + if _, err := s.ByKey(context.Background(), ""); !errors.Is(err, ErrBadCredentials) { + t.Fatalf("no key: %v", err) + } + if st.touched[d.ID].IsZero() { + t.Fatal("the use of the device was not noted") + } +} + +func TestATokenIsChecked(t *testing.T) { + s, _ := newService() + _, secret, _ := s.Create(context.Background(), 1, "Phone") + _, other, _ := s.Create(context.Background(), 1, "Laptop") + ctx := context.Background() + + if p, err := s.ByToken(ctx, "Alice@Example.org ", md5hex(secret+"c19f3a"), "c19f3a"); err != nil || p.UserID != 1 { + t.Fatalf("right token: %+v, %v", p, err) + } + if p, err := s.ByToken(ctx, "alice@example.org", md5hex(other+"salt12"), "salt12"); err != nil || p.UserID != 1 { + t.Fatalf("the other device: %+v, %v", p, err) + } + for name, c := range map[string][3]string{ + "wrong secret": {"alice@example.org", md5hex("nope" + "salt12"), "salt12"}, + "wrong user": {"bob@example.org", md5hex(secret + "salt12"), "salt12"}, + "unknown user": {"zed@example.org", md5hex(secret + "salt12"), "salt12"}, + "no salt": {"alice@example.org", md5hex(secret), ""}, + "no token": {"alice@example.org", "", "salt12"}, + } { + if _, err := s.ByToken(ctx, c[0], c[1], c[2]); !errors.Is(err, ErrBadCredentials) { + t.Errorf("%s: %v", name, err) + } + } +} + +func TestAPlainPasswordIsChecked(t *testing.T) { + s, _ := newService() + _, secret, _ := s.Create(context.Background(), 1, "Phone") + ctx := context.Background() + if p, err := s.ByPassword(ctx, "alice@example.org", secret); err != nil || p.UserID != 1 { + t.Fatalf("plain: %+v, %v", p, err) + } + if p, err := s.ByPassword(ctx, "alice@example.org", "enc:"+hex.EncodeToString([]byte(secret))); err != nil || p.UserID != 1 { + t.Fatalf("hex: %+v, %v", p, err) + } + for _, pw := range []string{"", "nope", "enc:zz", "enc:" + hex.EncodeToString([]byte("nope"))} { + if _, err := s.ByPassword(ctx, "alice@example.org", pw); !errors.Is(err, ErrBadCredentials) { + t.Errorf("%q: %v", pw, err) + } + } + if _, err := s.ByPassword(ctx, "bob@example.org", secret); !errors.Is(err, ErrBadCredentials) { + t.Errorf("someone else's: %v", err) + } +} + +func TestTheUseOfADeviceIsNotedOncePerTenMinutes(t *testing.T) { + s, st := newService() + d, secret, _ := s.Create(context.Background(), 1, "Phone") + ctx := context.Background() + _, _ = s.ByKey(ctx, secret) + first := st.touched[d.ID] + s.now = func() time.Time { return first.Add(5 * time.Minute) } + _, _ = s.ByKey(ctx, secret) + if !st.touched[d.ID].Equal(first) { + t.Fatal("noted again after five minutes") + } + s.now = func() time.Time { return first.Add(11 * time.Minute) } + _, _ = s.ByKey(ctx, secret) + if !st.touched[d.ID].Equal(first.Add(11 * time.Minute)) { + t.Fatal("not noted after eleven minutes") + } +} diff --git a/internal/opensubsonic/browse.go b/internal/opensubsonic/browse.go new file mode 100644 index 0000000..fb67904 --- /dev/null +++ b/internal/opensubsonic/browse.go @@ -0,0 +1,355 @@ +package opensubsonic + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "time" + "unicode" + + "golang.org/x/text/unicode/norm" + + "git.kmalloc.org/squid/sonda/internal/catalog" +) + +// Ids are strings that say what they are: ar-12 an artist, al-7 an album, tr-99 a song. +const ( + artistPrefix = "ar-" + albumPrefix = "al-" + trackPrefix = "tr-" +) + +func artistID(id int64) string { return artistPrefix + strconv.FormatInt(id, 10) } +func albumID(id int64) string { return albumPrefix + strconv.FormatInt(id, 10) } +func trackID(id int64) string { return trackPrefix + strconv.FormatInt(id, 10) } + +// idParam reads the id parameter, which must start with the prefix. A parameter that is not there is a missing one; +// one that is not an id of that kind is an id that is not found. +func idParam(k *call, prefix string) (int64, *Error) { + raw := k.param("id") + if raw == "" { + return 0, missing("id") + } + n, err := strconv.ParseInt(strings.TrimPrefix(raw, prefix), 10, 64) + if !strings.HasPrefix(raw, prefix) || err != nil || n < 1 { + return 0, notFound() + } + return n, nil +} + +func notFound() *Error { return &Error{Code: ErrNotFound, Message: "data not found"} } + +func failure(err error) *Error { + if errors.Is(err, catalog.ErrNotFound) { + return notFound() + } + return &Error{Code: ErrGeneric, Message: "the music could not be read"} +} + +// every reads all the pages of a list. +func every[T any](fetch func(offset int) (catalog.Page[T], error)) ([]T, error) { + var all []T + for { + p, err := fetch(len(all)) + if err != nil { + return nil, err + } + all = append(all, p.Items...) + if len(p.Items) == 0 || len(all) >= p.Total { + return all, nil + } + } +} + +func (h *handler) tokenInfo(k *call) (*Response, *Error) { + return &Response{TokenInfo: &TokenInfo{Username: k.principal.Email}}, nil +} + +func (h *handler) musicFolders(k *call) (*Response, *Error) { + libs, err := h.Libraries.List(k.ctx) + if err != nil { + return nil, failure(err) + } + out := make([]MusicFolder, len(libs)) + for i, l := range libs { + out[i] = MusicFolder{ID: l.ID, Name: l.Name} + } + return &Response{MusicFolders: &MusicFolders{MusicFolder: out}}, nil +} + +func (h *handler) artists(k *call) (*Response, *Error) { + var lib int64 + if v := k.param("musicFolderId"); v != "" { + n, err := strconv.ParseInt(v, 10, 64) + if err != nil || n < 1 { + return nil, notFound() + } + lib = n + } + list, err := every(func(offset int) (catalog.Page[catalog.Artist], error) { + return h.Catalog.Artists(k.ctx, catalog.Filter{LibraryID: lib, Limit: catalog.MaxLimit, Offset: offset}) + }) + if err != nil { + return nil, failure(err) + } + var index []Index + at := map[string]int{} + for _, a := range list { + letter := indexLetter(a.Name) + i, ok := at[letter] + if !ok { + i = len(index) + at[letter] = i + index = append(index, Index{Name: letter, Artist: []ArtistID3{}}) + } + index[i].Artist = append(index[i].Artist, artistOf(a)) + } + sortIndex(index) + if index == nil { + index = []Index{} + } + return &Response{Artists: &ArtistsID3{Index: index}}, nil +} + +// indexLetter is the letter an artist is listed under: its first letter in capitals, or # for a name that starts +// with anything else. +func indexLetter(name string) string { + for _, r := range name { + if unicode.IsLetter(r) { + // "É" is listed with E: take the letter that is left when the accent is taken off. + for _, base := range norm.NFD.String(string(r)) { + return string(unicode.ToUpper(base)) + } + } + break + } + return "#" +} + +// sortIndex puts # first and the letters in order. The artists inside a group keep the order of the catalogue. +func sortIndex(index []Index) { + for i := 1; i < len(index); i++ { + for j := i; j > 0 && indexBefore(index[j].Name, index[j-1].Name); j-- { + index[j], index[j-1] = index[j-1], index[j] + } + } +} + +func indexBefore(a, b string) bool { + if a == "#" || b == "#" { + return a == "#" && b != "#" + } + return a < b +} + +func artistOf(a catalog.Artist) ArtistID3 { + return ArtistID3{ID: artistID(a.ID), Name: a.Name, AlbumCount: a.AlbumCount} +} + +func (h *handler) artist(k *call) (*Response, *Error) { + id, bad := idParam(k, artistPrefix) + if bad != nil { + return nil, bad + } + a, err := h.Catalog.Artist(k.ctx, id) + if err != nil { + return nil, failure(err) + } + albums, err := every(func(offset int) (catalog.Page[catalog.Album], error) { + return h.Catalog.Albums(k.ctx, catalog.Filter{ArtistID: id, Limit: catalog.MaxLimit, Offset: offset}) + }) + if err != nil { + return nil, failure(err) + } + out, err := h.albums(k.ctx, albums) + if err != nil { + return nil, failure(err) + } + return &Response{Artist: &ArtistWithAlbums{ArtistID3: artistOf(a), Album: out}}, nil +} + +// albums describes albums, with what the catalogue does not carry. +func (h *handler) albums(ctx context.Context, list []catalog.Album) ([]AlbumID3, error) { + ids := make([]int64, len(list)) + for i, a := range list { + ids[i] = a.ID + } + extras, err := h.Extras.Albums(ctx, ids) + if err != nil { + return nil, err + } + out := make([]AlbumID3, len(list)) + for i, a := range list { + out[i] = albumOf(a, extras[a.ID]) + } + return out, nil +} + +func albumOf(a catalog.Album, e AlbumExtra) AlbumID3 { + out := AlbumID3{ + ID: albumID(a.ID), Name: a.Title, CoverArt: albumID(a.ID), SongCount: a.TrackCount, Duration: seconds(a.DurationMs), + Created: stamp(e.AddedAt), Year: e.Year, Genres: genresOf(e.Genres), + } + if len(e.Genres) > 0 { + out.Genre = e.Genres[0] + } + if a.Artist != nil { + out.Artist, out.ArtistID, out.DisplayArtist = a.Artist.Name, artistID(a.Artist.ID), a.Artist.Name + out.Artists = []ArtistRef{{ID: artistID(a.Artist.ID), Name: a.Artist.Name}} + } + return out +} + +func (h *handler) album(k *call) (*Response, *Error) { + id, bad := idParam(k, albumPrefix) + if bad != nil { + return nil, bad + } + al, err := h.Catalog.Album(k.ctx, id) + if err != nil { + return nil, failure(err) + } + tracks, err := every(func(offset int) (catalog.Page[catalog.Track], error) { + return h.Catalog.Tracks(k.ctx, catalog.Filter{AlbumID: id, Limit: catalog.MaxLimit, Offset: offset}) + }) + if err != nil { + return nil, failure(err) + } + out, err := h.albums(k.ctx, []catalog.Album{al}) + if err != nil { + return nil, failure(err) + } + songs, err := h.songs(k.ctx, tracks) + if err != nil { + return nil, failure(err) + } + return &Response{Album: &AlbumWithSongs{AlbumID3: out[0], Song: songs}}, nil +} + +func (h *handler) song(k *call) (*Response, *Error) { + id, bad := idParam(k, trackPrefix) + if bad != nil { + return nil, bad + } + t, err := h.Catalog.Track(k.ctx, id) + if err != nil { + return nil, failure(err) + } + songs, err := h.songs(k.ctx, []catalog.Track{t}) + if err != nil { + return nil, failure(err) + } + return &Response{Song: &songs[0]}, nil +} + +func (h *handler) genres(k *call) (*Response, *Error) { + list, err := h.Extras.Genres(k.ctx) + if err != nil { + return nil, failure(err) + } + out := make([]GenreEntry, len(list)) + for i, g := range list { + out[i] = GenreEntry{Value: g.Name, SongCount: g.Songs, AlbumCount: g.Albums} + } + return &Response{Genres: &Genres{Genre: out}}, nil +} + +// songs describes songs, with what the catalogue does not carry. +func (h *handler) songs(ctx context.Context, list []catalog.Track) ([]Child, error) { + ids := make([]int64, len(list)) + for i, t := range list { + ids[i] = t.ID + } + extras, err := h.Extras.Tracks(ctx, ids) + if err != nil { + return nil, err + } + out := make([]Child, len(list)) + for i, t := range list { + out[i] = childOf(t, extras[t.ID]) + } + return out, nil +} + +func childOf(t catalog.Track, e TrackExtra) Child { + c := Child{ + ID: trackID(t.ID), Title: t.Title, Track: t.TrackNo, DiscNumber: t.DiscNo, Duration: seconds(t.DurationMs), + Year: e.Year, Size: e.Size, BitRate: e.BitrateKbps, Suffix: e.Suffix, ContentType: contentType(e.Suffix), + Created: stamp(e.AddedAt), Type: "music", MediaType: "song", Genres: genresOf(e.Genres), + } + if len(e.Genres) > 0 { + c.Genre = e.Genres[0] + } + names := make([]string, len(t.Artists)) + for i, a := range t.Artists { + names[i] = a.Name + c.Artists = append(c.Artists, ArtistRef{ID: artistID(a.ID), Name: a.Name}) + } + if len(names) > 0 { + c.Artist = strings.Join(names, " & ") + c.DisplayArtist = c.Artist + c.ArtistID = artistID(t.Artists[0].ID) + } + albumName := "" + if t.Album != nil { + albumName = t.Album.Title + c.Album, c.AlbumID, c.Parent, c.CoverArt = t.Album.Title, albumID(t.Album.ID), albumID(t.Album.ID), albumID(t.Album.ID) + } + c.Path = pathOf(c.Artist, albumName, t, e.Suffix) + if g := t.ReplayGain; g != nil { + c.ReplayGain = &ReplayGain{TrackGain: g.TrackGain, AlbumGain: g.AlbumGain, TrackPeak: g.TrackPeak, AlbumPeak: g.AlbumPeak} + } + return c +} + +// pathOf is a made-up path, "Artist/Album/01 - Title.flac": Sonda does not tell where its files are. +func pathOf(artist, album string, t catalog.Track, suffix string) string { + clean := strings.NewReplacer("/", "-", "\\", "-").Replace + name := t.Title + if t.TrackNo > 0 { + name = fmt.Sprintf("%02d - %s", t.TrackNo, name) + } + if suffix != "" { + name += "." + suffix + } + var parts []string + for _, p := range []string{artist, album} { + if p != "" { + parts = append(parts, clean(p)) + } + } + return strings.Join(append(parts, clean(name)), "/") +} + +func contentType(suffix string) string { + switch suffix { + case "mp3": + return "audio/mpeg" + case "flac": + return "audio/flac" + case "": + return "" + } + return "application/octet-stream" +} + +func genresOf(names []string) []ItemGenre { + var out []ItemGenre + for _, n := range names { + out = append(out, ItemGenre{Name: n}) + } + return out +} + +// seconds rounds milliseconds to the seconds an app shows. +func seconds(ms int64) int { return int((ms + 500) / 1000) } + +// stamp is a moment in the form of the Subsonic API: UTC, to the millisecond. A moment that is not known is left out. +func stamp(t time.Time) string { + if t.IsZero() { + return "" + } + return t.UTC().Format("2006-01-02T15:04:05.000Z") +} diff --git a/internal/opensubsonic/handler.go b/internal/opensubsonic/handler.go new file mode 100644 index 0000000..fc8e4ed --- /dev/null +++ b/internal/opensubsonic/handler.go @@ -0,0 +1,192 @@ +// Package opensubsonic speaks the OpenSubsonic API (Subsonic 1.16.1 and its open extensions), so that apps like +// Symfonium, Feishin or Amperfy can play the music of a Sonda server. +// +// It is mounted at /rest. A call logs in with the password of a device (see package devices), never with the account +// password: as an API key (`apiKey`), as Subsonic's token (`u`, `t`, `s`) or as the password itself (`u`, `p`). What +// a call can do is limited to the music of the person whose device it is. +package opensubsonic + +import ( + "context" + "encoding/json" + "encoding/xml" + "errors" + "net/http" + "strings" + + "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/library" +) + +// Login checks the passwords of devices: *devices.Service. +type Login interface { + ByKey(ctx context.Context, key string) (devices.Principal, error) + ByToken(ctx context.Context, email, token, salt string) (devices.Principal, error) + ByPassword(ctx context.Context, email, password string) (devices.Principal, error) +} + +// Catalog is what the calls need from catalog.Service. +type Catalog interface { + Artists(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Artist], error) + Albums(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Album], error) + Tracks(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Track], error) + Artist(ctx context.Context, id int64) (catalog.Artist, error) + Album(ctx context.Context, id int64) (catalog.Album, error) + Track(ctx context.Context, id int64) (catalog.Track, error) +} + +// Libraries lists the libraries: *library.Libraries. +type Libraries interface { + List(ctx context.Context) ([]library.Library, error) +} + +// Deps are the services the calls use. +type Deps struct { + Login Login + Catalog Catalog + Libraries Libraries + Extras Extras + ServerVersion string +} + +type handler struct { + Deps + calls map[string]func(*call) (*Response, *Error) +} + +// call is one request, with who made it. +type call struct { + c *gin.Context + ctx context.Context + principal devices.Principal +} + +// param is the value of a parameter, from the address or the form. +func (k *call) param(name string) string { return k.c.Request.Form.Get(name) } + +// Register mounts the API at /rest/{method} and /rest/{method}.view, for GET and for a form POST. +func Register(r gin.IRoutes, d Deps) { + h := &handler{Deps: d} + h.calls = map[string]func(*call) (*Response, *Error){ + "ping": func(*call) (*Response, *Error) { return &Response{}, nil }, + "getLicense": func(*call) (*Response, *Error) { return &Response{License: &License{Valid: true}}, nil }, + "tokenInfo": h.tokenInfo, + "getMusicFolders": h.musicFolders, + "getArtists": h.artists, + "getArtist": h.artist, + "getAlbum": h.album, + "getSong": h.song, + "getGenres": h.genres, + "getOpenSubsonicExtensions": nil, // answered before the login: see serve + } + r.GET("/rest/:method", h.serve) + r.POST("/rest/:method", h.serve) +} + +// extensions are the OpenSubsonic extensions that are spoken. +var extensions = []Extension{ + {Name: "apiKeyAuthentication", Versions: []int{1}}, + {Name: "formPost", Versions: []int{1}}, +} + +func (h *handler) serve(c *gin.Context) { + // A web app on another address reads the answers too. What opens a call is a password of its own, never a cookie. + c.Header("Access-Control-Allow-Origin", "*") + _ = c.Request.ParseForm() // a malformed form only means the parameters are missing + method := strings.TrimSuffix(c.Param("method"), ".view") + asJSON := c.Request.Form.Get("f") == "json" + + resp, fail := h.dispatch(c, method) + if fail != nil { + resp = &Response{Error: fail} + } + h.write(c, asJSON, resp) +} + +func (h *handler) dispatch(c *gin.Context, method string) (*Response, *Error) { + if method == "getOpenSubsonicExtensions" { // an app asks what is spoken before it has a password + return &Response{OpenSubsonicExtensions: extensions}, nil + } + fn, known := h.calls[method] + if !known || fn == nil { + return nil, &Error{Code: ErrGeneric, Message: "unknown method: " + method} + } + k := &call{c: c, ctx: c.Request.Context()} + p, fail := h.login(k) + if fail != nil { + return nil, fail + } + k.principal = p + return fn(k) +} + +// login checks who is calling: an API key, or an address with a token or a password. +func (h *handler) login(k *call) (devices.Principal, *Error) { + key, user, token, salt, password := k.param("apiKey"), k.param("u"), k.param("t"), k.param("s"), k.param("p") + if key != "" { + if user != "" || token != "" || salt != "" || password != "" { + return devices.Principal{}, &Error{Code: ErrAuthConflict, Message: "apiKey cannot be used with u, p, t or s"} + } + p, err := h.Login.ByKey(k.ctx, key) + return h.checked(p, err, ErrBadAPIKey, "invalid API key") + } + if user == "" { + return devices.Principal{}, missing("u") + } + switch { + case (token != "" || salt != "") && password != "": + return devices.Principal{}, &Error{Code: ErrAuthConflict, Message: "use either p or t and s"} + case token != "" && salt != "": + p, err := h.Login.ByToken(k.ctx, user, token, salt) + return h.checked(p, err, ErrWrongLogin, "wrong username or password") + case token != "" || salt != "": + return devices.Principal{}, missing("s and t") + case password != "": + p, err := h.Login.ByPassword(k.ctx, user, password) + return h.checked(p, err, ErrWrongLogin, "wrong username or password") + } + return devices.Principal{}, missing("p") +} + +func (h *handler) checked(p devices.Principal, err error, code int, message string) (devices.Principal, *Error) { + switch { + case err == nil: + return p, nil + case errors.Is(err, devices.ErrBadCredentials): + return p, &Error{Code: code, Message: message} + default: + return p, &Error{Code: ErrGeneric, Message: "the login could not be checked"} + } +} + +func missing(name string) *Error { + return &Error{Code: ErrMissingParam, Message: "required parameter is missing: " + name} +} + +// write fills the envelope and writes the answer as JSON or as XML. +func (h *handler) write(c *gin.Context, asJSON bool, r *Response) { + r.Xmlns = "http://subsonic.org/restapi" + r.Version, r.Type, r.ServerVersion, r.OpenSubsonic = APIVersion, "sonda", h.ServerVersion, true + r.Status = "ok" + if r.Error != nil { + r.Status = "failed" + } + if asJSON { + out, err := json.Marshal(map[string]*Response{"subsonic-response": r}) + if err != nil { + c.Status(http.StatusInternalServerError) + return + } + c.Data(http.StatusOK, "application/json; charset=utf-8", out) + return + } + out, err := xml.Marshal(r) + if err != nil { + c.Status(http.StatusInternalServerError) + return + } + c.Data(http.StatusOK, "text/xml; charset=utf-8", append([]byte(xml.Header), out...)) +} diff --git a/internal/opensubsonic/handler_test.go b/internal/opensubsonic/handler_test.go new file mode 100644 index 0000000..66fff3d --- /dev/null +++ b/internal/opensubsonic/handler_test.go @@ -0,0 +1,487 @@ +package opensubsonic + +import ( + "context" + "encoding/json" + "encoding/xml" + "net/http" + "net/http/httptest" + "net/url" + "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/library" +) + +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} + } + 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 { + all = []catalog.Track{airbag, karma} + } + 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(), ``} { + 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, `alternative rock`) { + 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) + } + } +} diff --git a/internal/opensubsonic/response.go b/internal/opensubsonic/response.go new file mode 100644 index 0000000..f952ae3 --- /dev/null +++ b/internal/opensubsonic/response.go @@ -0,0 +1,188 @@ +package opensubsonic + +import "encoding/xml" + +// The answer of every call is one Response, written as JSON or as XML: the same tree has the tags of both. In XML +// the plain values are attributes and the lists are child elements; in JSON everything is a field and the lists are +// arrays. A field that is not set is left out of both. + +// APIVersion is the Subsonic API that is spoken. +const APIVersion = "1.16.1" + +// Response is the envelope of an answer. +type Response struct { + XMLName xml.Name `xml:"subsonic-response" json:"-"` + Xmlns string `xml:"xmlns,attr" json:"-"` + Status string `xml:"status,attr" json:"status"` + Version string `xml:"version,attr" json:"version"` + Type string `xml:"type,attr" json:"type"` + ServerVersion string `xml:"serverVersion,attr" json:"serverVersion"` + OpenSubsonic bool `xml:"openSubsonic,attr" json:"openSubsonic"` + + Error *Error `xml:"error" json:"error,omitempty"` + License *License `xml:"license" json:"license,omitempty"` + OpenSubsonicExtensions []Extension `xml:"openSubsonicExtensions" json:"openSubsonicExtensions,omitempty"` + TokenInfo *TokenInfo `xml:"tokenInfo" json:"tokenInfo,omitempty"` + MusicFolders *MusicFolders `xml:"musicFolders" json:"musicFolders,omitempty"` + Artists *ArtistsID3 `xml:"artists" json:"artists,omitempty"` + Artist *ArtistWithAlbums `xml:"artist" json:"artist,omitempty"` + Album *AlbumWithSongs `xml:"album" json:"album,omitempty"` + Song *Child `xml:"song" json:"song,omitempty"` + Genres *Genres `xml:"genres" json:"genres,omitempty"` +} + +// Error codes of the Subsonic API. +const ( + ErrGeneric = 0 + ErrMissingParam = 10 + ErrWrongLogin = 40 + ErrAuthConflict = 43 + ErrBadAPIKey = 44 + ErrNotAuthorized = 50 + ErrNotFound = 70 + errUnsupportedAuth = 42 +) + +// Error is the reason a call failed. +type Error struct { + Code int `xml:"code,attr" json:"code"` + Message string `xml:"message,attr,omitempty" json:"message,omitempty"` +} + +// License says the server is licensed: it always is. +type License struct { + Valid bool `xml:"valid,attr" json:"valid"` +} + +// Extension is an OpenSubsonic extension that the server speaks. +type Extension struct { + Name string `xml:"name,attr" json:"name"` + Versions []int `xml:"versions" json:"versions"` +} + +// TokenInfo says whose the login of the call is. +type TokenInfo struct { + Username string `xml:"username,attr" json:"username"` +} + +// MusicFolders are the libraries. +type MusicFolders struct { + MusicFolder []MusicFolder `xml:"musicFolder" json:"musicFolder"` +} + +// MusicFolder is one library. +type MusicFolder struct { + ID int64 `xml:"id,attr" json:"id"` + Name string `xml:"name,attr" json:"name"` +} + +// ArtistsID3 are the artists, in groups by their first letter. +type ArtistsID3 struct { + IgnoredArticles string `xml:"ignoredArticles,attr" json:"ignoredArticles"` + Index []Index `xml:"index" json:"index"` +} + +// Index is the artists whose name starts with one letter. +type Index struct { + Name string `xml:"name,attr" json:"name"` + Artist []ArtistID3 `xml:"artist" json:"artist"` +} + +// ArtistID3 is an artist. +type ArtistID3 struct { + ID string `xml:"id,attr" json:"id"` + Name string `xml:"name,attr" json:"name"` + AlbumCount int `xml:"albumCount,attr" json:"albumCount"` + CoverArt string `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"` +} + +// ArtistWithAlbums is an artist and its albums. +type ArtistWithAlbums struct { + ArtistID3 + Album []AlbumID3 `xml:"album" json:"album,omitempty"` +} + +// ArtistRef is an artist credited on a song or an album, in the OpenSubsonic fields. +type ArtistRef struct { + ID string `xml:"id,attr" json:"id"` + Name string `xml:"name,attr" json:"name"` +} + +// ItemGenre is a genre of a song or an album, in the OpenSubsonic fields. +type ItemGenre struct { + Name string `xml:"name,attr" json:"name"` +} + +// AlbumID3 is an album. +type AlbumID3 struct { + ID string `xml:"id,attr" json:"id"` + Name string `xml:"name,attr" json:"name"` + Artist string `xml:"artist,attr,omitempty" json:"artist,omitempty"` + ArtistID string `xml:"artistId,attr,omitempty" json:"artistId,omitempty"` + CoverArt string `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"` + SongCount int `xml:"songCount,attr" json:"songCount"` + Duration int `xml:"duration,attr" json:"duration"` + Created string `xml:"created,attr" json:"created"` + Year int `xml:"year,attr,omitempty" json:"year,omitempty"` + Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"` + DisplayArtist string `xml:"displayArtist,attr,omitempty" json:"displayArtist,omitempty"` + Artists []ArtistRef `xml:"artists" json:"artists,omitempty"` + Genres []ItemGenre `xml:"genres" json:"genres,omitempty"` +} + +// AlbumWithSongs is an album and its songs. +type AlbumWithSongs struct { + AlbumID3 + Song []Child `xml:"song" json:"song,omitempty"` +} + +// ReplayGain is how loud a song is, as its file says. +type ReplayGain struct { + TrackGain *float64 `xml:"trackGain,attr,omitempty" json:"trackGain,omitempty"` + AlbumGain *float64 `xml:"albumGain,attr,omitempty" json:"albumGain,omitempty"` + TrackPeak *float64 `xml:"trackPeak,attr,omitempty" json:"trackPeak,omitempty"` + AlbumPeak *float64 `xml:"albumPeak,attr,omitempty" json:"albumPeak,omitempty"` +} + +// Child is a song. +type Child struct { + ID string `xml:"id,attr" json:"id"` + Parent string `xml:"parent,attr,omitempty" json:"parent,omitempty"` + IsDir bool `xml:"isDir,attr" json:"isDir"` + Title string `xml:"title,attr" json:"title"` + Album string `xml:"album,attr,omitempty" json:"album,omitempty"` + Artist string `xml:"artist,attr,omitempty" json:"artist,omitempty"` + Track int `xml:"track,attr,omitempty" json:"track,omitempty"` + Year int `xml:"year,attr,omitempty" json:"year,omitempty"` + Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"` + CoverArt string `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"` + Size int64 `xml:"size,attr,omitempty" json:"size,omitempty"` + ContentType string `xml:"contentType,attr,omitempty" json:"contentType,omitempty"` + Suffix string `xml:"suffix,attr,omitempty" json:"suffix,omitempty"` + Duration int `xml:"duration,attr,omitempty" json:"duration,omitempty"` + BitRate int `xml:"bitRate,attr,omitempty" json:"bitRate,omitempty"` + Path string `xml:"path,attr,omitempty" json:"path,omitempty"` + DiscNumber int `xml:"discNumber,attr,omitempty" json:"discNumber,omitempty"` + Created string `xml:"created,attr,omitempty" json:"created,omitempty"` + AlbumID string `xml:"albumId,attr,omitempty" json:"albumId,omitempty"` + ArtistID string `xml:"artistId,attr,omitempty" json:"artistId,omitempty"` + Type string `xml:"type,attr,omitempty" json:"type,omitempty"` + MediaType string `xml:"mediaType,attr,omitempty" json:"mediaType,omitempty"` + IsVideo bool `xml:"isVideo,attr" json:"isVideo"` + DisplayArtist string `xml:"displayArtist,attr,omitempty" json:"displayArtist,omitempty"` + Artists []ArtistRef `xml:"artists" json:"artists,omitempty"` + Genres []ItemGenre `xml:"genres" json:"genres,omitempty"` + ReplayGain *ReplayGain `xml:"replayGain" json:"replayGain,omitempty"` +} + +// Genres are the genres of the music. +type Genres struct { + Genre []GenreEntry `xml:"genre" json:"genre"` +} + +// GenreEntry is a genre, with how many songs and albums have it. +type GenreEntry struct { + Value string `xml:",chardata" json:"value"` + SongCount int `xml:"songCount,attr" json:"songCount"` + AlbumCount int `xml:"albumCount,attr" json:"albumCount"` +} diff --git a/internal/opensubsonic/store.go b/internal/opensubsonic/store.go new file mode 100644 index 0000000..86cebf4 --- /dev/null +++ b/internal/opensubsonic/store.go @@ -0,0 +1,40 @@ +package opensubsonic + +import ( + "context" + "time" +) + +// TrackExtra is what an app asks about a song that the catalogue does not carry: from its tags and its first file. +type TrackExtra struct { + Year int // 0 when the file has none + Genres []string + Size int64 // bytes + BitrateKbps int // 0 when unknown + Suffix string // the extension of the file, without the dot + AddedAt time.Time +} + +// AlbumExtra is the same for an album. +type AlbumExtra struct { + Year int // the earliest year of its songs, 0 when none has one + Genres []string + AddedAt time.Time // when its oldest file arrived +} + +// Genre is a genre of the music, with how much of it there is. +type Genre struct { + Name string + Songs int + Albums int +} + +// Extras reads what the catalogue does not carry. +type Extras interface { + // Tracks returns the extras of the songs that can be played; a song that cannot is left out. + Tracks(ctx context.Context, ids []int64) (map[int64]TrackExtra, error) + // Albums returns the extras of the albums that can be played. + Albums(ctx context.Context, ids []int64) (map[int64]AlbumExtra, error) + // Genres returns every genre of the songs that can be played. + Genres(ctx context.Context) ([]Genre, error) +} diff --git a/internal/storage/devices.go b/internal/storage/devices.go index 4932b9c..c201769 100644 --- a/internal/storage/devices.go +++ b/internal/storage/devices.go @@ -2,6 +2,8 @@ package storage import ( "context" + "database/sql" + "errors" "fmt" "time" @@ -70,3 +72,61 @@ func (r *DevicesRepo) Delete(ctx context.Context, userID, id int64) error { } return nil } + +// deviceWithEmail is a device with the address of its person. +type deviceWithEmail struct { + deviceRow `bun:",extend"` + Email string `bun:"email"` +} + +func (r deviceWithEmail) device() devices.Row { + out := r.deviceRow.device() + out.Email = r.Email + return out +} + +// ByKeyHash finds a device by the hash of its secret, with the address of its person, or devices.ErrNotFound. +func (r *DevicesRepo) ByKeyHash(ctx context.Context, hash string) (devices.Row, error) { + var row deviceWithEmail + err := r.db.NewSelect(). + TableExpr("device_passwords AS d"). + ColumnExpr("d.id, d.user_id, d.name, d.key_hash, d.sealed, d.created_at, d.last_used_at, u.email"). + Join("JOIN users AS u ON u.id = d.user_id"). + Where("d.key_hash = ?", hash). + Limit(1).Scan(ctx, &row) + if errors.Is(err, sql.ErrNoRows) { + return devices.Row{}, devices.ErrNotFound + } + if err != nil { + return devices.Row{}, fmt.Errorf("find device by key: %w", err) + } + return row.device(), nil +} + +// ByEmail returns the devices of the person with that address (lower case), with the address. +func (r *DevicesRepo) ByEmail(ctx context.Context, email string) ([]devices.Row, error) { + var rows []deviceWithEmail + err := r.db.NewSelect(). + TableExpr("device_passwords AS d"). + ColumnExpr("d.id, d.user_id, d.name, d.key_hash, d.sealed, d.created_at, d.last_used_at, u.email"). + Join("JOIN users AS u ON u.id = d.user_id"). + Where("LOWER(u.email) = ?", email). + Order("d.id"). + Scan(ctx, &rows) + if err != nil { + return nil, fmt.Errorf("find devices by address: %w", err) + } + out := make([]devices.Row, len(rows)) + for i, row := range rows { + out[i] = row.device() + } + return out, nil +} + +// Touch notes when a device was last used. +func (r *DevicesRepo) Touch(ctx context.Context, id int64, at time.Time) error { + if _, err := r.db.NewUpdate().Model((*deviceRow)(nil)).Set("last_used_at = ?", at.Unix()).Where("id = ?", id).Exec(ctx); err != nil { + return fmt.Errorf("touch device: %w", err) + } + return nil +} diff --git a/internal/storage/devices_test.go b/internal/storage/devices_test.go index 6c83afc..9973908 100644 --- a/internal/storage/devices_test.go +++ b/internal/storage/devices_test.go @@ -80,3 +80,39 @@ func TestDevicesGoWithTheirPerson(t *testing.T) { } }) } + +func TestADeviceIsFoundByItsKeyAndByTheAddressOfItsPerson(t *testing.T) { + forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { + ctx := context.Background() + repo := NewDevicesRepo(db) + alice, bob := seedUser(t, db, "alice@example.org"), seedUser(t, db, "bob@example.org") + at := time.Unix(1_700_000_000, 0) + a1, _ := repo.Create(ctx, devices.Row{UserID: alice, Name: "Phone", KeyHash: "h1", Sealed: []byte{1}, CreatedAt: at}) + _, _ = repo.Create(ctx, devices.Row{UserID: alice, Name: "Laptop", KeyHash: "h2", Sealed: []byte{2}, CreatedAt: at}) + _, _ = repo.Create(ctx, devices.Row{UserID: bob, Name: "Tablet", KeyHash: "h3", Sealed: []byte{3}, CreatedAt: at}) + + got, err := repo.ByKeyHash(ctx, "h1") + if err != nil || got.ID != a1.ID || got.UserID != alice || got.Email != "alice@example.org" { + t.Fatalf("ByKeyHash = %+v, %v", got, err) + } + if _, err := repo.ByKeyHash(ctx, "nope"); !errors.Is(err, devices.ErrNotFound) { + t.Fatalf("an unknown key: %v", err) + } + rows, err := repo.ByEmail(ctx, "alice@example.org") + if err != nil || len(rows) != 2 || rows[0].Email != "alice@example.org" { + t.Fatalf("ByEmail = %+v, %v", rows, err) + } + if rows, err := repo.ByEmail(ctx, "zed@example.org"); err != nil || len(rows) != 0 { + t.Fatalf("an unknown address: %+v, %v", rows, err) + } + + used := at.Add(time.Hour) + if err := repo.Touch(ctx, a1.ID, used); err != nil { + t.Fatal(err) + } + got, _ = repo.ByKeyHash(ctx, "h1") + if got.LastUsedAt == nil || !got.LastUsedAt.Equal(used) { + t.Fatalf("last used = %v", got.LastUsedAt) + } + }) +} diff --git a/internal/storage/subsonic.go b/internal/storage/subsonic.go new file mode 100644 index 0000000..bc41d5c --- /dev/null +++ b/internal/storage/subsonic.go @@ -0,0 +1,149 @@ +package storage + +import ( + "context" + "fmt" + "path" + "strings" + "time" + + "github.com/uptrace/bun" + + "git.kmalloc.org/squid/sonda/internal/opensubsonic" +) + +// SubsonicRepo reads what the OpenSubsonic API needs and the catalogue does not carry. It implements +// opensubsonic.Extras. Only files that are not missing count, like everywhere else. +type SubsonicRepo struct{ db *bun.DB } + +// NewSubsonicRepo builds a SubsonicRepo. +func NewSubsonicRepo(db *bun.DB) *SubsonicRepo { return &SubsonicRepo{db: db} } + +// Tracks returns the extras of the songs that can be played, with three queries whatever the number of songs. +func (r *SubsonicRepo) Tracks(ctx context.Context, ids []int64) (map[int64]opensubsonic.TrackExtra, error) { + out := map[int64]opensubsonic.TrackExtra{} + if len(ids) == 0 { + return out, nil + } + rows, err := r.db.QueryContext(ctx, + `SELECT f.track_id, f.id, f.rel_path, f.size_bytes, COALESCE(f.bitrate, 0), f.mtime_unix, COALESCE(t.year, 0) + FROM audio_files f JOIN tracks t ON t.id = f.track_id + WHERE f.track_id IN (?) AND f.missing_at IS NULL ORDER BY f.id`, bun.In(ids)) + if err != nil { + return nil, fmt.Errorf("read the files of songs: %w", err) + } + defer rows.Close() + for rows.Next() { + var ( + trackID, fileID, size, mtime int64 + rel string + bitrate, year int + ) + if err := rows.Scan(&trackID, &fileID, &rel, &size, &bitrate, &mtime, &year); err != nil { + return nil, err + } + if _, seen := out[trackID]; seen { // the first file that can be played says it + continue + } + out[trackID] = opensubsonic.TrackExtra{ + Year: year, Size: size, BitrateKbps: bitrate, + Suffix: strings.TrimPrefix(strings.ToLower(path.Ext(rel)), "."), AddedAt: time.Unix(mtime, 0), + } + } + if err := rows.Err(); err != nil { + return nil, err + } + + genres, err := r.genresOf(ctx, `SELECT g.track_id, g.genre FROM track_genres g WHERE g.track_id IN (?) ORDER BY g.track_id, g.genre`, ids) + if err != nil { + return nil, err + } + for id, g := range genres { + if e, ok := out[id]; ok { + e.Genres = g + out[id] = e + } + } + return out, nil +} + +// Albums returns the extras of the albums that can be played. +func (r *SubsonicRepo) Albums(ctx context.Context, ids []int64) (map[int64]opensubsonic.AlbumExtra, error) { + out := map[int64]opensubsonic.AlbumExtra{} + if len(ids) == 0 { + return out, nil + } + rows, err := r.db.QueryContext(ctx, + `SELECT t.album_id, COALESCE(MIN(CASE WHEN t.year > 0 THEN t.year END), 0), MIN(f.mtime_unix) + FROM tracks t JOIN audio_files f ON f.track_id = t.id AND f.missing_at IS NULL + WHERE t.album_id IN (?) GROUP BY t.album_id`, bun.In(ids)) + if err != nil { + return nil, fmt.Errorf("read the albums: %w", err) + } + defer rows.Close() + for rows.Next() { + var id, year, mtime int64 + if err := rows.Scan(&id, &year, &mtime); err != nil { + return nil, err + } + out[id] = opensubsonic.AlbumExtra{Year: int(year), AddedAt: time.Unix(mtime, 0)} + } + if err := rows.Err(); err != nil { + return nil, err + } + + genres, err := r.genresOf(ctx, + `SELECT DISTINCT t.album_id, g.genre FROM track_genres g JOIN tracks t ON t.id = g.track_id + WHERE t.album_id IN (?) ORDER BY t.album_id, g.genre`, ids) + if err != nil { + return nil, err + } + for id, g := range genres { + if e, ok := out[id]; ok { + e.Genres = g + out[id] = e + } + } + return out, nil +} + +// genresOf runs a query of (id, genre) rows, in order, and gathers the genres of each id. +func (r *SubsonicRepo) genresOf(ctx context.Context, query string, ids []int64) (map[int64][]string, error) { + rows, err := r.db.QueryContext(ctx, query, bun.In(ids)) + if err != nil { + return nil, fmt.Errorf("read genres: %w", err) + } + defer rows.Close() + out := map[int64][]string{} + for rows.Next() { + var id int64 + var genre string + if err := rows.Scan(&id, &genre); err != nil { + return nil, err + } + out[id] = append(out[id], genre) + } + return out, rows.Err() +} + +// Genres returns every genre of the songs that can be played, with the songs and the albums that have it. +func (r *SubsonicRepo) Genres(ctx context.Context) ([]opensubsonic.Genre, error) { + vis, _ := visible("t", 0) + rows, err := r.db.QueryContext(ctx, + `SELECT g.genre, COUNT(DISTINCT t.id), COUNT(DISTINCT t.album_id) + FROM track_genres g JOIN tracks t ON t.id = g.track_id + WHERE `+vis+` GROUP BY g.genre ORDER BY g.genre`) + if err != nil { + return nil, fmt.Errorf("read genres: %w", err) + } + defer rows.Close() + out := []opensubsonic.Genre{} + for rows.Next() { + var g opensubsonic.Genre + if err := rows.Scan(&g.Name, &g.Songs, &g.Albums); err != nil { + return nil, err + } + out = append(out, g) + } + return out, rows.Err() +} diff --git a/internal/storage/subsonic_test.go b/internal/storage/subsonic_test.go new file mode 100644 index 0000000..08ea10a --- /dev/null +++ b/internal/storage/subsonic_test.go @@ -0,0 +1,83 @@ +package storage + +import ( + "context" + "testing" + + "github.com/uptrace/bun" +) + +func TestTheExtrasOfSongsAndAlbumsComeFromTheirTagsAndFiles(t *testing.T) { + forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { + ctx := context.Background() + s := seedCatalog(t, db) + repo := NewSubsonicRepo(db) + + exec := func(q string, args ...any) { + t.Helper() + if _, err := db.ExecContext(ctx, q, args...); err != nil { + t.Fatal(err) + } + } + airbag, paranoid, kind := s.track["Airbag"], s.track["Paranoid Android"], s.track["So What"] + exec("UPDATE tracks SET year = 1997 WHERE id = ?", airbag) + exec("UPDATE tracks SET year = 1998 WHERE id = ?", paranoid) + exec("INSERT INTO track_genres (track_id, genre) VALUES (?, 'rock'), (?, 'art rock'), (?, 'rock')", airbag, airbag, paranoid) + exec("UPDATE audio_files SET size_bytes = 4242, bitrate = 320, mtime_unix = 1000 WHERE track_id = ? AND missing_at IS NULL AND rel_path LIKE 'r/%'", airbag) + exec("UPDATE audio_files SET mtime_unix = 500 WHERE track_id = ?", paranoid) + + tracks, err := repo.Tracks(ctx, []int64{airbag, kind, s.track["Ghost"]}) + if err != nil { + t.Fatal(err) + } + a := tracks[airbag] + if a.Year != 1997 || a.Size != 4242 || a.BitrateKbps != 320 || a.Suffix != "flac" || a.AddedAt.Unix() != 1000 { + t.Errorf("Airbag: %+v", a) + } + if len(a.Genres) != 2 || a.Genres[0] != "art rock" || a.Genres[1] != "rock" { + t.Errorf("genres of Airbag: %v", a.Genres) + } + if k := tracks[kind]; k.Year != 0 || k.Suffix != "mp3" || len(k.Genres) != 0 { + t.Errorf("So What: %+v", k) + } + if _, ok := tracks[s.track["Ghost"]]; ok { + t.Error("a song with no file to play has extras") + } + + var ok int64 + if err := db.QueryRowContext(ctx, "SELECT id FROM albums WHERE title = 'OK Computer'").Scan(&ok); err != nil { + t.Fatal(err) + } + albums, err := repo.Albums(ctx, []int64{ok}) + if err != nil { + t.Fatal(err) + } + al := albums[ok] + if al.Year != 1997 || al.AddedAt.Unix() != 1 && al.AddedAt.Unix() != 500 { + t.Errorf("OK Computer: %+v", al) + } + if len(al.Genres) != 2 || al.Genres[0] != "art rock" || al.Genres[1] != "rock" { + t.Errorf("genres of the album: %v", al.Genres) + } + + genres, err := repo.Genres(ctx) + if err != nil || len(genres) != 2 { + t.Fatalf("Genres = %+v, %v", genres, err) + } + if g := genres[1]; g.Name != "rock" || g.Songs != 2 || g.Albums != 1 { + t.Errorf("rock = %+v", g) + } + }) +} + +func TestNoIdsNoExtras(t *testing.T) { + forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { + repo := NewSubsonicRepo(db) + if m, err := repo.Tracks(context.Background(), nil); err != nil || len(m) != 0 { + t.Fatalf("%v, %v", m, err) + } + if m, err := repo.Albums(context.Background(), nil); err != nil || len(m) != 0 { + t.Fatalf("%v, %v", m, err) + } + }) +}