feat(settings): my own settings, starting with Discover from my listening

- GET and PATCH /me/settings: settings that belong to the signed-in user.
- First setting, discover_from_listening, is off by default. When on, Discover
  may start from the artists I listen to most, which sends their names to
  Last.fm.
- New user_settings table (migration 0011, SQLite and PostgreSQL), removed with
  the account. A user with no row has the private defaults.
- A misspelt setting is rejected instead of being ignored.
- Spec, contract test and README updated.

Refs #29
This commit is contained in:
tgiachi 2026-11-11 19:16:26 +01:00
commit e0592c0260
15 changed files with 514 additions and 4 deletions

View file

@ -16,6 +16,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
- **API documentation.** The full API is described in OpenAPI and browsable with Swagger UI, served by Sonda itself. The UI is embedded in the binary, so opening it contacts no other server.
- **Listening history.** Clients report explicit `play`, `complete` and `skip` events. An event counts as a listen when it is `complete`, or when it was played for at least 20 seconds (`listening.min_listen_seconds`); the rule is applied when the history is read, so changing it re-reads the past. You can read your own history, with a `counted` flag on every event. It stays in your database and is never sent anywhere.
- **Your taste.** `GET /me/taste` shows what Sonda has learned from your own listening: the artists you like and the kinds of music (tags) they have in common. A complete listen counts for more than a short one, a skip counts against the artist, and older listens weigh less (they halve every 90 days, `taste.half_life_days`; only the last ten half-lives are read). It is worked out on every request from data already in your database; nothing is sent to any provider.
- **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so nothing about what you listen to can be sent to a provider. When you turn it on, Discover may start from the artists you listen to most, and their names are sent to Last.fm (only if an admin switched it on).
- **Tags.** `GET /artists/{id}/tags` shows what Last.fm and MusicBrainz say kind of music an artist plays, each with its own weights, and the genres of the artist's own files, read offline. See [External providers](#external-providers).
- **Similar artists.** With Last.fm switched on, `GET /artists/{id}/similar` lists artists similar to an artist, and says which of them you already have. See [External providers](#external-providers). Without it, Sonda makes no outbound network requests at all.
@ -229,6 +230,7 @@ Everything lives under `/api/v1`. Bodies are JSON. Errors always look like `{"er
| signed in | `POST /listens` | Record a `play`, `complete` or `skip`; the answer says whether it counts as a listen. |
| signed in | `GET /listens` | Your own history, newest first, with `counted` per event. Query: `limit`, `offset`, `counted=true`. |
| signed in | `GET /me/taste` | The artists and tags Sonda learned you like, from your own listening. Query: `limit` (default 20, max 50). |
| signed in | `GET /me/settings`, `PATCH /me/settings` | Your own settings (today: `discover_from_listening`, off by default). |
| signed in | `GET /library/scan` | Scan status and the last result. |
| admin | `GET`, `POST /libraries`; `PATCH`, `DELETE /libraries/{id}` | Manage libraries. Deleting one removes its index entries, never your files. |
| admin | `POST /library/scan`, `POST /libraries/{id}/scan` | Scan everything, or one library. `?full=true` reads every file again. |
@ -283,6 +285,7 @@ internal/discovery/ similar artists: what the providers said, kept and refres
internal/providers/ external providers: settings, the outbound HTTP client, the Last.fm and MusicBrainz clients
internal/listening/ listen events
internal/taste/ what the listener likes, learned from the listening history
internal/usersettings/ the settings that belong to one user
internal/storage/ SQLite and PostgreSQL through bun, the repositories
internal/streaming/ opening a track's file safely
migrations/ SQL migrations, one folder per database

View file

@ -28,6 +28,7 @@ import (
"codeberg.org/squidd/sonda/internal/storage"
"codeberg.org/squidd/sonda/internal/streaming"
"codeberg.org/squidd/sonda/internal/taste"
"codeberg.org/squidd/sonda/internal/usersettings"
"codeberg.org/squidd/sonda/migrations"
)
@ -150,6 +151,7 @@ func run() error {
Discovery: discoveries,
Tags: tags,
Taste: taste.NewService(storage.NewTasteRepo(db), taste.Options{MinListen: cfg.Listening.MinListen(), HalfLife: cfg.Taste.HalfLife()}),
Settings: usersettings.NewService(storage.NewUserSettingsRepo(db)),
Streams: streaming.NewService(libraryRepo),
})

View file

@ -23,6 +23,7 @@ import (
"codeberg.org/squidd/sonda/internal/storage"
"codeberg.org/squidd/sonda/internal/streaming"
"codeberg.org/squidd/sonda/internal/taste"
"codeberg.org/squidd/sonda/internal/usersettings"
"codeberg.org/squidd/sonda/migrations"
)
@ -88,6 +89,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
Discovery: discovery.NewService(storage.NewDiscoveryRepo(db), &fakeLastfm{}, prov, zap.NewNop()),
Tags: discovery.NewTagService(storage.NewDiscoveryRepo(db), map[string]discovery.TagSource{}, prov, zap.NewNop()),
Taste: taste.NewService(storage.NewTasteRepo(db), taste.Options{MinListen: 20 * time.Second, HalfLife: 90 * 24 * time.Hour}),
Settings: usersettings.NewService(storage.NewUserSettingsRepo(db)),
Streams: streaming.NewService(noFiles{}),
}
mutate(&deps, db)

View file

@ -526,6 +526,17 @@ func TestResponsesMatchTheSpec(t *testing.T) {
c.expect(c.call("GET", "/me/taste?limit=-1", token, nil), 400, "taste with a bad limit", "invalid_input")
c.expect(c.call("GET", "/me/taste?limit=abc", token, nil), 400, "taste with a limit that is not a number", "invalid_input")
// ---- my settings ----
if got := c.expect(c.call("GET", "/me/settings", token, nil), 200, "settings"); got["discover_from_listening"] != false {
t.Fatalf("settings = %v, want everything off", got)
}
if got := c.expect(c.call("PATCH", "/me/settings", token, map[string]any{"discover_from_listening": true}), 200, "turn a setting on"); got["discover_from_listening"] != true {
t.Fatalf("settings = %v", got)
}
c.expect(c.call("PATCH", "/me/settings", token, map[string]any{"discover_from_listening": "yes"}), 400, "a setting that is not a boolean", "invalid_input")
c.expect(c.call("PATCH", "/me/settings", token, map[string]any{"nope": true}), 400, "a setting that does not exist", "invalid_input")
c.expect(c.call("GET", "/me/settings", "", nil), 401, "settings without a token", "unauthorized")
// ---- every operation in the spec was exercised ----
var missing []string
for _, op := range specOperations(loadSpec(t)) {

View file

@ -0,0 +1,58 @@
package httpapi
import (
"encoding/json"
"errors"
"net/http"
"github.com/gin-gonic/gin"
"codeberg.org/squidd/sonda/internal/usersettings"
)
// userSettingsHandlers serve the signed-in user's own settings.
type userSettingsHandlers struct{ svc userSettingsService }
type userSettingsJSON struct {
DiscoverFromListening bool `json:"discover_from_listening"`
}
type updateUserSettingsRequest struct {
DiscoverFromListening *bool `json:"discover_from_listening"` // a pointer: absent means leave it alone
}
func writeUserSettingsError(c *gin.Context, err error) {
if errors.Is(err, usersettings.ErrUserNotFound) {
writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists")
return
}
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
}
func (h *userSettingsHandlers) get(c *gin.Context) {
s, err := h.svc.Get(c.Request.Context(), currentUserID(c))
if err != nil {
writeUserSettingsError(c, err)
return
}
c.JSON(http.StatusOK, userSettingsJSON{DiscoverFromListening: s.DiscoverFromListening})
}
func (h *userSettingsHandlers) update(c *gin.Context) {
// A misspelt setting must not be accepted and ignored: this is about privacy.
var req updateUserSettingsRequest
dec := json.NewDecoder(c.Request.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&req); err != nil {
writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body or unknown setting")
return
}
s, err := h.svc.Update(c.Request.Context(), currentUserID(c),
usersettings.Patch{DiscoverFromListening: req.DiscoverFromListening})
if err != nil {
writeUserSettingsError(c, err)
return
}
c.JSON(http.StatusOK, userSettingsJSON{DiscoverFromListening: s.DiscoverFromListening})
}

View file

@ -18,6 +18,7 @@ import (
"codeberg.org/squidd/sonda/internal/providers"
"codeberg.org/squidd/sonda/internal/streaming"
"codeberg.org/squidd/sonda/internal/taste"
"codeberg.org/squidd/sonda/internal/usersettings"
)
// maxBodyBytes bounds every request body.
@ -75,6 +76,11 @@ type tasteService interface {
Taste(ctx context.Context, userID int64, limit int) (taste.Profile, error)
}
type userSettingsService interface {
Get(ctx context.Context, userID int64) (usersettings.Settings, error)
Update(ctx context.Context, userID int64, p usersettings.Patch) (usersettings.Settings, error)
}
type catalogService 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)
@ -104,6 +110,7 @@ type Deps struct {
Discovery discoveryService
Tags tagService
Taste tasteService
Settings userSettingsService
Streams streamService
}
@ -134,6 +141,9 @@ func NewRouter(d Deps) *gin.Engine {
ts := &tasteHandlers{svc: d.Taste}
protected.GET("/me/taste", ts.taste)
us := &userSettingsHandlers{svc: d.Settings}
protected.GET("/me/settings", us.get)
protected.PATCH("/me/settings", us.update)
lib := &libraryHandlers{scan: d.Scan}
protected.GET("/library/scan", lib.scanStatus)

View file

@ -0,0 +1,75 @@
package httpapi
import (
"net/http"
"testing"
)
func TestSettingsNeedASignedInUser(t *testing.T) {
h := newTestAPI(t)
for _, m := range []string{"GET", "PATCH"} {
if r := do(t, h, m, "/api/v1/me/settings", "", map[string]any{}); r.Code != http.StatusUnauthorized {
t.Errorf("%s without a token: %d", m, r.Code)
}
}
}
func TestSettingsStartOffAndStayMine(t *testing.T) {
h := newTestAPI(t)
alice := registerAndLogin(t, h)
r := do(t, h, "GET", "/api/v1/me/settings", alice, nil)
if r.Code != http.StatusOK {
t.Fatalf("%d %v", r.Code, r.Body)
}
sameKeys(t, "settings", r.Body, "discover_from_listening")
if r.Body["discover_from_listening"] != false {
t.Errorf("settings = %v, want everything off", r.Body)
}
r = do(t, h, "PATCH", "/api/v1/me/settings", alice, map[string]any{"discover_from_listening": true})
if r.Code != http.StatusOK || r.Body["discover_from_listening"] != true {
t.Fatalf("turn on: %d %v", r.Code, r.Body)
}
if r = do(t, h, "GET", "/api/v1/me/settings", alice, nil); r.Body["discover_from_listening"] != true {
t.Errorf("not kept: %v", r.Body)
}
// An empty object changes nothing.
if r = do(t, h, "PATCH", "/api/v1/me/settings", alice, map[string]any{}); r.Code != http.StatusOK || r.Body["discover_from_listening"] != true {
t.Errorf("empty patch: %d %v", r.Code, r.Body)
}
// Another user has their own.
cred := map[string]any{"username": "bob", "password": "longenough"}
if c := do(t, h, "POST", "/api/v1/users", alice, cred); c.Code != http.StatusCreated {
t.Fatalf("create bob: %d %v", c.Code, c.Body)
}
bob, _ := do(t, h, "POST", "/api/v1/auth/login", "", cred).Body["access_token"].(string)
if r = do(t, h, "GET", "/api/v1/me/settings", bob, nil); r.Body["discover_from_listening"] != false {
t.Errorf("bob sees alice's setting: %v", r.Body)
}
}
func TestSettingsRejectWhatIsNotABoolean(t *testing.T) {
h := newTestAPI(t)
alice := registerAndLogin(t, h)
for name, body := range map[string]any{
"a string": map[string]any{"discover_from_listening": "yes"},
"a number": map[string]any{"discover_from_listening": 1},
"null": map[string]any{"discover_from_listening": nil},
"not an object": []any{true},
"a setting that does not exist": map[string]any{"discover_from_listenin": true},
} {
r := do(t, h, "PATCH", "/api/v1/me/settings", alice, body)
if name == "null" {
// null is the same as absent for a pointer field: nothing changes.
if r.Code != http.StatusOK {
t.Errorf("null: %d %v", r.Code, r.Body)
}
continue
}
if r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("%s: %d %v, want 400 invalid_input", name, r.Code, r.Body)
}
}
}

View file

@ -34,7 +34,7 @@ tags:
- name: Playback
description: Streaming and listening history.
- name: Taste
description: What Sonda has learned from your listening.
description: What Sonda has learned from your listening, and the settings that are yours.
- name: Discovery
description: Music outside the library, from external providers an admin switched on.
- name: Providers
@ -691,6 +691,44 @@ paths:
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
/me/settings:
get:
tags: [Taste]
operationId: getMySettings
summary: Your own settings
description: |
Settings that belong to you, not to the server. Everyone starts with the private
defaults: anything that would send something about your taste to a provider is off.
security: [{bearerAuth: []}]
responses:
'200':
description: Your settings.
content:
application/json:
schema: {$ref: '#/components/schemas/UserSettings'}
'401': {$ref: '#/components/responses/Unauthorized'}
patch:
tags: [Taste]
operationId: updateMySettings
summary: Change your own settings
description: |
Changes the settings named in the body and leaves the others alone. An empty object
changes nothing. `null` is the same as leaving a field out.
security: [{bearerAuth: []}]
requestBody:
required: true
content:
application/json:
schema: {$ref: '#/components/schemas/UpdateUserSettings'}
responses:
'200':
description: Your settings as they are now.
content:
application/json:
schema: {$ref: '#/components/schemas/UserSettings'}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
/albums:
get:
tags: [Catalog]
@ -1615,6 +1653,25 @@ components:
type: array
items: {$ref: '#/components/schemas/TasteTag'}
UserSettings:
type: object
additionalProperties: false
required: [discover_from_listening]
properties:
discover_from_listening:
type: boolean
description: |
When true, Discover may start from the artists you listen to most. That sends their
names to Last.fm, which is asked for artists similar to each one (only when an admin
switched Last.fm on). When false, Discover starts only from artists you name yourself.
False until you turn it on.
UpdateUserSettings:
type: object
additionalProperties: false
properties:
discover_from_listening: {type: boolean, nullable: true}
TasteArtist:
type: object
additionalProperties: false

View file

@ -147,7 +147,7 @@ func TestMigrateCreatesSchemaAndIsIdempotent(t *testing.T) {
if err := Migrate(context.Background(), db, fsys); err != nil {
t.Fatalf("second Migrate: %v", err)
}
for _, table := range []string{"artists", "albums", "tracks", "track_artists", "audio_files", "users", "listening_events", "refresh_tokens", "libraries", "provider_settings", "artist_similar", "provider_fetches", "artist_tags", "track_genres"} {
for _, table := range []string{"artists", "albums", "tracks", "track_artists", "audio_files", "users", "listening_events", "refresh_tokens", "libraries", "provider_settings", "artist_similar", "provider_fetches", "artist_tags", "track_genres", "user_settings"} {
if !tableExists(t, db, driver, table) {
t.Errorf("table %s missing", table)
}
@ -156,8 +156,8 @@ func TestMigrateCreatesSchemaAndIsIdempotent(t *testing.T) {
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&applied); err != nil {
t.Fatal(err)
}
if applied != 10 {
t.Errorf("applied migrations = %d, want 10", applied)
if applied != 11 {
t.Errorf("applied migrations = %d, want 11", applied)
}
})
}

View file

@ -0,0 +1,65 @@
package storage
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/usersettings"
)
// UserSettingsRepo stores per-user settings. It implements usersettings.Store.
type UserSettingsRepo struct{ db *bun.DB }
// NewUserSettingsRepo builds a UserSettingsRepo.
func NewUserSettingsRepo(db *bun.DB) *UserSettingsRepo { return &UserSettingsRepo{db: db} }
// Get returns the user's settings: the defaults when no row exists yet.
func (r *UserSettingsRepo) Get(ctx context.Context, userID int64) (usersettings.Settings, error) {
return getUserSettings(ctx, r.db, userID)
}
type queryer interface {
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
func getUserSettings(ctx context.Context, q queryer, userID int64) (usersettings.Settings, error) {
var s usersettings.Settings
err := q.QueryRowContext(ctx,
`SELECT COALESCE(s.discover_from_listening, FALSE)
FROM users u LEFT JOIN user_settings s ON s.user_id = u.id WHERE u.id = ?`, userID).
Scan(&s.DiscoverFromListening)
if errors.Is(err, sql.ErrNoRows) {
return usersettings.Settings{}, usersettings.ErrUserNotFound
}
if err != nil {
return usersettings.Settings{}, fmt.Errorf("read user settings: %w", err)
}
return s, nil
}
// Update applies the patch in one transaction and returns the result.
func (r *UserSettingsRepo) Update(ctx context.Context, userID int64, p usersettings.Patch) (usersettings.Settings, error) {
var out usersettings.Settings
err := r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
cur, err := getUserSettings(ctx, tx, userID)
if err != nil {
return err
}
if p.DiscoverFromListening != nil {
cur.DiscoverFromListening = *p.DiscoverFromListening
if _, err := tx.ExecContext(ctx,
`INSERT INTO user_settings (user_id, discover_from_listening) VALUES (?, ?)
ON CONFLICT (user_id) DO UPDATE SET discover_from_listening = excluded.discover_from_listening`,
userID, cur.DiscoverFromListening); err != nil {
return fmt.Errorf("write user settings: %w", err)
}
}
out = cur
return nil
})
return out, err
}

View file

@ -0,0 +1,65 @@
package storage
import (
"context"
"errors"
"testing"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/usersettings"
)
func TestUserSettingsRepo(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
users := NewUserRepo(db)
alice, _ := users.CreateUser(ctx, "alice", "h", false)
bob, _ := users.CreateUser(ctx, "bob", "h", false)
repo := NewUserSettingsRepo(db)
got, err := repo.Get(ctx, alice.ID)
if err != nil || got.DiscoverFromListening {
t.Fatalf("new user: %+v err=%v, want everything off", got, err)
}
on, off := true, false
if got, err = repo.Update(ctx, alice.ID, usersettings.Patch{DiscoverFromListening: &on}); err != nil || !got.DiscoverFromListening {
t.Fatalf("turn on: %+v err=%v", got, err)
}
// Asked again later, from the database.
if got, _ = repo.Get(ctx, alice.ID); !got.DiscoverFromListening {
t.Error("the setting was not kept")
}
if got, _ = repo.Get(ctx, bob.ID); got.DiscoverFromListening {
t.Error("bob got alice's setting")
}
// An empty patch changes nothing, also for a user with no row yet.
if got, err = repo.Update(ctx, bob.ID, usersettings.Patch{}); err != nil || got.DiscoverFromListening {
t.Errorf("empty patch: %+v err=%v", got, err)
}
if got, err = repo.Update(ctx, alice.ID, usersettings.Patch{}); err != nil || !got.DiscoverFromListening {
t.Errorf("empty patch on a set value: %+v err=%v", got, err)
}
if got, _ = repo.Update(ctx, alice.ID, usersettings.Patch{DiscoverFromListening: &off}); got.DiscoverFromListening {
t.Error("turn off did not work")
}
// Gone with the account.
if _, err := repo.Update(ctx, bob.ID, usersettings.Patch{DiscoverFromListening: &on}); err != nil {
t.Fatal(err)
}
if err := users.DeleteUser(ctx, bob.ID); err != nil {
t.Fatal(err)
}
var n int
if err := db.QueryRow("SELECT COUNT(*) FROM user_settings WHERE user_id = ?", bob.ID).Scan(&n); err != nil || n != 0 {
t.Errorf("rows left for a deleted user: %d err=%v", n, err)
}
if _, err := repo.Get(ctx, bob.ID); !errors.Is(err, usersettings.ErrUserNotFound) {
t.Errorf("Get for a deleted user: err = %v", err)
}
if _, err := repo.Update(ctx, bob.ID, usersettings.Patch{DiscoverFromListening: &on}); !errors.Is(err, usersettings.ErrUserNotFound) {
t.Errorf("Update for a deleted user: err = %v", err)
}
})
}

View file

@ -0,0 +1,52 @@
// Package usersettings keeps the settings that belong to one user.
//
// They are choices about privacy and taste, not about the server: a user with no
// stored settings gets the defaults, and the defaults never send anything to a
// provider.
package usersettings
import (
"context"
"errors"
)
// ErrUserNotFound is returned for an account that no longer exists.
var ErrUserNotFound = errors.New("user not found")
// Settings are the choices of one user.
type Settings struct {
// DiscoverFromListening lets Discover start from the artists the user listens
// to most. Doing so sends their names to Last.fm, so it is off until the user
// turns it on.
DiscoverFromListening bool
}
// Patch changes some settings. A nil field is left alone.
type Patch struct {
DiscoverFromListening *bool
}
// Store keeps the settings.
type Store interface {
// Get returns the settings, the defaults for a user who never set any, or
// ErrUserNotFound.
Get(ctx context.Context, userID int64) (Settings, error)
// Update applies the patch and returns the result, or ErrUserNotFound.
Update(ctx context.Context, userID int64, p Patch) (Settings, error)
}
// Service reads and changes a user's own settings.
type Service struct{ store Store }
// NewService builds a Service.
func NewService(store Store) *Service { return &Service{store: store} }
// Get returns the user's settings.
func (s *Service) Get(ctx context.Context, userID int64) (Settings, error) {
return s.store.Get(ctx, userID)
}
// Update applies the patch and returns the settings as they are now.
func (s *Service) Update(ctx context.Context, userID int64, p Patch) (Settings, error) {
return s.store.Update(ctx, userID, p)
}

View file

@ -0,0 +1,90 @@
package usersettings
import (
"context"
"errors"
"testing"
)
type fakeStore struct {
byUser map[int64]Settings
gone map[int64]bool
err error
}
func (f *fakeStore) Get(_ context.Context, id int64) (Settings, error) {
if f.err != nil {
return Settings{}, f.err
}
if f.gone[id] {
return Settings{}, ErrUserNotFound
}
return f.byUser[id], nil
}
func (f *fakeStore) Update(_ context.Context, id int64, p Patch) (Settings, error) {
if f.err != nil {
return Settings{}, f.err
}
if f.gone[id] {
return Settings{}, ErrUserNotFound
}
s := f.byUser[id]
if p.DiscoverFromListening != nil {
s.DiscoverFromListening = *p.DiscoverFromListening
}
f.byUser[id] = s
return s, nil
}
func newFake() *fakeStore { return &fakeStore{byUser: map[int64]Settings{}, gone: map[int64]bool{}} }
func TestEverythingIsOffUntilTheUserTurnsItOn(t *testing.T) {
s := NewService(newFake())
got, err := s.Get(context.Background(), 1)
if err != nil || got.DiscoverFromListening {
t.Errorf("new user: %+v err=%v, want everything off", got, err)
}
}
func TestPatchChangesOnlyWhatItNames(t *testing.T) {
f := newFake()
s := NewService(f)
on, off := true, false
got, err := s.Update(context.Background(), 1, Patch{DiscoverFromListening: &on})
if err != nil || !got.DiscoverFromListening {
t.Fatalf("turn on: %+v err=%v", got, err)
}
if got, _ = s.Update(context.Background(), 1, Patch{}); !got.DiscoverFromListening {
t.Errorf("an empty patch changed the setting: %+v", got)
}
if got, _ = s.Update(context.Background(), 1, Patch{DiscoverFromListening: &off}); got.DiscoverFromListening {
t.Errorf("turn off: %+v", got)
}
if other, _ := s.Get(context.Background(), 2); other.DiscoverFromListening {
t.Error("a setting of one user leaked to another")
}
}
func TestADeletedAccountIsReported(t *testing.T) {
f := newFake()
f.gone[7] = true
s := NewService(f)
on := true
if _, err := s.Get(context.Background(), 7); !errors.Is(err, ErrUserNotFound) {
t.Errorf("Get: err = %v", err)
}
if _, err := s.Update(context.Background(), 7, Patch{DiscoverFromListening: &on}); !errors.Is(err, ErrUserNotFound) {
t.Errorf("Update: err = %v", err)
}
}
func TestStoreErrorsPassThrough(t *testing.T) {
boom := errors.New("boom")
f := newFake()
f.err = boom
if _, err := NewService(f).Get(context.Background(), 1); !errors.Is(err, boom) {
t.Errorf("err = %v", err)
}
}

View file

@ -0,0 +1,10 @@
-- Settings that belong to one user. A user with no row has the defaults, which are
-- the private ones: everything that sends something to a provider is off.
--
-- discover_from_listening: Discover may start from the artists the user listens to
-- most, which sends their names to Last.fm to ask for similar artists.
CREATE TABLE user_settings (
user_id BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
discover_from_listening BOOLEAN NOT NULL DEFAULT FALSE
);

View file

@ -0,0 +1,10 @@
-- Settings that belong to one user. A user with no row has the defaults, which are
-- the private ones: everything that sends something to a provider is off.
--
-- discover_from_listening: Discover may start from the artists the user listens to
-- most, which sends their names to Last.fm to ask for similar artists.
CREATE TABLE user_settings (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
discover_from_listening INTEGER NOT NULL DEFAULT 0 CHECK (discover_from_listening IN (0, 1))
);