From ed32aac228b72af9cc95e07e83cdc8596f542d82 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Mon, 16 Nov 2026 12:33:09 +0100 Subject: [PATCH] feat: the radio stations are in the apps only when the person asks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new setting, radio_in_apps, off until the person turns it on (Settings, Apps and devices, or PATCH /me/settings). With it off, the list of playlists of an OpenSubsonic app is only the playlists of the person, and a station asked for by id is not found. With it on, the stations come as playlists called Radio · Rock. - migration 0036: user_settings.radio_in_apps - usersettings, the settings API and the OpenAPI spec have the new field; the PATCH now keeps each setting apart (naming one no longer sets the other) - Settings has a switch --- README.md | 4 +- cmd/sondad/main.go | 2 +- internal/api/http/api_test.go | 2 +- internal/api/http/handlers_usersettings.go | 18 ++++-- internal/api/http/radio_test.go | 11 ++++ internal/api/http/usersettings_test.go | 29 ++++++++- internal/api/openapi/openapi.yaml | 9 ++- internal/opensubsonic/handler.go | 1 + internal/opensubsonic/handler_test.go | 30 ++++++++- internal/opensubsonic/playlists.go | 31 ++++++++- internal/storage/storage_test.go | 4 +- internal/storage/usersettings.go | 25 ++++++-- internal/storage/usersettings_test.go | 30 +++++++++ internal/usersettings/usersettings.go | 5 ++ internal/usersettings/usersettings_test.go | 3 + migrations/postgres/0036_radio_in_apps.sql | 4 ++ migrations/sqlite/0036_radio_in_apps.sql | 4 ++ web/src/api/schema.d.ts | 7 ++ web/src/components/RadioInAppsSwitch.test.tsx | 64 +++++++++++++++++++ web/src/components/RadioInAppsSwitch.tsx | 38 +++++++++++ web/src/i18n/locales/en.json | 6 +- web/src/i18n/locales/it.json | 6 +- web/src/pages/SettingsPage.tsx | 2 + 23 files changed, 310 insertions(+), 25 deletions(-) create mode 100644 migrations/postgres/0036_radio_in_apps.sql create mode 100644 migrations/sqlite/0036_radio_in_apps.sql create mode 100644 web/src/components/RadioInAppsSwitch.test.tsx create mode 100644 web/src/components/RadioInAppsSwitch.tsx diff --git a/README.md b/README.md index 81a94b4..bfc41b3 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr - **Similar artists.** With Last.fm turned 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. - **Friends (federation).** Two Sonda servers can become friends, and the listeners of one can read what the other chose to share. `PUT /federation` (admin) turns federation on, which is off by default, and gives this server a name and a public address (`https`; plain `http` only on a network of your own); the server then makes its own Ed25519 key, kept in the database and never returned. `POST /federation/invites` makes an invite that works once and expires in 24 hours (only a hash of its code is kept). The other admin uses it with `POST /federation/friends`: that server is asked to accept this one, the key it answers with must be the one named in the invite, and the friend waits as `outgoing` until the first admin approves it with `POST /federation/friends/{id}/approve` (`POST /federation/friends/{id}/check` lets the waiting side find out). Either side can remove a friend with `DELETE /federation/friends/{id}`. Nothing is shared until an admin turns on `shared` for a library (`PATCH /libraries/{id}`). A friend's server then reads, with requests signed by its key (the method, the path and query, a date, a nonce and the hash of the body), the routes under `/peer`: the artists, albums and songs that have a file in a shared library, their covers once they are built, and the audio itself with `Range`. A friend never sees a path, a library id, a listen, a taste or a user, never makes this server build a cover or ask a provider, and has a few streams at a time and a number of KiB a second to share (`max_streams`, `max_kib_per_sec`); the admin sees the last requests it made (`GET /federation/requests`, the route and the size, never what was searched for). Sharing a library lets friends play it and, in practice, copy its files. A listener browses the music of a friend with `GET /friends` (the names of the friends whose friendship both admins agreed to, never an address or a key) and `GET /friends/{friend}/artists`, `albums` and `tracks` with `q`, `limit` and `offset`, and one item at a time: this server asks the friend with a signed request, checks the shape of the answer and passes it on, and nothing is kept; the ids are the friend's own. A friend that cannot be reached or no longer takes this server for a friend is told in words. The web app has a Friends section for it, shown only when there is a friend to browse. A listener plays it with `GET /friends/{friend}/tracks/{id}/stream` and sees its covers with `GET /friends/{friend}/albums/{id}/cover`, which accept the access token in the query like the local ones: this server asks the friend with a signed request, forwards `Range` and the conditional headers, and passes on only audio (or a JPEG for a cover) with `Content-Type`, `Content-Length`, `Content-Range`, `Accept-Ranges`, `Last-Modified` and `ETag`, so the friend sees this server and never the listener, and a friend cannot make this server serve anything else. A friend's song plays in the same player as the others but is never reported as a listen and does not feed taste. The admin area has a Federation section for all of it. -- **Radio.** Stations that Sonda makes by itself from your music, with nothing to set up, and without end: *Everything*, one for each decade that has at least 30 songs by 4 artists (from the year in the tags), and the mixes you have (one for each genre, *Your favourites*, *Rediscover*, *New to you*), plus the radio of an artist from its page. `GET /radio` lists the stations and `GET /radio/{id}` gives up to 50 songs of one, **other songs every time it is asked**, picked like a mix (your taste and your hearts count, nothing skipped lately, at most 3 by one artist); `artist:` is the station of an artist (their songs weigh four times as much, with the songs of the two genres most of theirs have). The web app has a Radio page and a *Start radio* button on every artist, and its player asks for more songs by itself before the queue runs out. Apps that speak OpenSubsonic see each station as a playlist called *Radio · Rock*, with other songs every time it is opened (an app has no way to play a radio that never ends). Nothing is stored and nothing leaves the server. +- **Radio.** Stations that Sonda makes by itself from your music, with nothing to set up, and without end: *Everything*, one for each decade that has at least 30 songs by 4 artists (from the year in the tags), and the mixes you have (one for each genre, *Your favourites*, *Rediscover*, *New to you*), plus the radio of an artist from its page. `GET /radio` lists the stations and `GET /radio/{id}` gives up to 50 songs of one, **other songs every time it is asked**, picked like a mix (your taste and your hearts count, nothing skipped lately, at most 3 by one artist); `artist:` is the station of an artist (their songs weigh four times as much, with the songs of the two genres most of theirs have). The web app has a Radio page and a *Start radio* button on every artist, and its player asks for more songs by itself before the queue runs out. Apps that speak OpenSubsonic see each station as a playlist called *Radio · Rock*, with other songs every time it is opened (an app has no way to play a radio that never ends), but only when you turn on `radio_in_apps` (`PATCH /me/settings`; in Settings, *Show the radio stations in apps*): there are about two dozen of them, so it is off until you ask. Nothing is stored and nothing leaves the server. - **Favourites.** `PUT /me/favorites/{kind}/{id}` marks a song, an album or an artist (`kind` is `tracks`, `albums` or `artists`) as a favourite and `DELETE` takes it back; `GET /me/favorites/{kind}` lists them, the newest first, and `GET /me/favorites/ids` gives every id for the hearts of a list. They are yours alone: never shown to a friend and never sent anywhere. Favourites also teach Sonda your taste: a favourite artist counts as much as three complete listens, a favourite album for its artist 1.5, a favourite song 1 (at most 6 for one artist), and the mixes of what you like give a favourite song more chance (and a song of a favourite album a little more). That feeds Discover, the mixes and the smart playlists that use your taste, and `GET /me/taste`. The web app has a heart on every song, album and artist (and in the player) and a Favourites page. Apps that speak OpenSubsonic see them as starred things. - **Other apps.** Apps that speak OpenSubsonic (Symfonium, Feishin, Amperfy, Supersonic and others) can browse, search, play, show covers, use your playlists and report what you listened to, with a password of their own for each app (see [Other apps](#other-apps-opensubsonic)). @@ -308,7 +308,7 @@ A device password opens your music in that app and nothing else: it cannot sign | `getAlbumList2` | Random, newest, frequent, recent, by name, by artist, by year, by genre. | | `getRandomSongs`, `getSongsByGenre`, `search3` | Find songs, albums and artists. | | `stream`, `download`, `getCoverArt` | The original file (with Range), and covers of albums, artists and songs. | -| `getPlaylists`, `getPlaylist`, `createPlaylist`, `updatePlaylist`, `deletePlaylist` | Your playlists, the same ones as in the web app. After them, each station of the radio is a playlist (`rd-…`, *Radio · Rock*) with other songs every time it is opened; they cannot be changed or deleted. | +| `getPlaylists`, `getPlaylist`, `createPlaylist`, `updatePlaylist`, `deletePlaylist` | Your playlists, the same ones as in the web app. After them, when you turned on *Show the radio stations in apps*, each station of the radio is a playlist (`rd-…`, *Radio · Rock*) with other songs every time it is opened; they cannot be changed or deleted. | | `scrobble` | A listen is recorded like one made in the web app (and shared on Mastodon if you connected it). A "now playing" message is not recorded. | | `star`, `unstar`, `getStarred2` | Your favourites (see **Favourites**): songs, albums and artists, with the `starred` date on each, and `getAlbumList2` of type `starred`. | | `setRating`, `getNowPlaying` | Answered with nothing: there are no ratings, and what you play is nobody else's business. | diff --git a/cmd/sondad/main.go b/cmd/sondad/main.go index cf79443..b10faba 100644 --- a/cmd/sondad/main.go +++ b/cmd/sondad/main.go @@ -323,7 +323,7 @@ func run() error { OpenSubsonic: &opensubsonic.Deps{ Login: deviceSvc, Catalog: catalogSvc, Libraries: libraries, Extras: subsonicRepo, Lists: subsonicRepo, Streams: streamSvc, Covers: pictures, ArtistImages: pictures, - Playlists: playlistSvc, Listens: listeningSvc, Announcer: mastodonSvc, Favorites: favoriteSvc, Radio: mixSvc, + Playlists: playlistSvc, Listens: listeningSvc, Announcer: mastodonSvc, Favorites: favoriteSvc, Radio: mixSvc, Settings: userSettings, ServerVersion: version, }, Scan: scanControl{ctx: ctx, m: scans}, diff --git a/internal/api/http/api_test.go b/internal/api/http/api_test.go index c8a8898..a5afc88 100644 --- a/internal/api/http/api_test.go +++ b/internal/api/http/api_test.go @@ -150,7 +150,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun Libraries: deps.Libraries.(opensubsonic.Libraries), ServerVersion: "test", Extras: subsonic, Lists: subsonic, Streams: deps.Streams.(opensubsonic.Streams), Covers: deps.Images.(opensubsonic.Covers), ArtistImages: deps.ArtistImages.(opensubsonic.ArtistImages), - Playlists: deps.Playlists.(opensubsonic.Playlists), Listens: deps.Listening.(opensubsonic.Listens), Announcer: deps.Mastodon.(opensubsonic.Announcer), Favorites: deps.Favorites.(opensubsonic.Favorites), Radio: deps.Mixes.(opensubsonic.Radio), + Playlists: deps.Playlists.(opensubsonic.Playlists), Listens: deps.Listening.(opensubsonic.Listens), Announcer: deps.Mastodon.(opensubsonic.Announcer), Favorites: deps.Favorites.(opensubsonic.Favorites), Radio: deps.Mixes.(opensubsonic.Radio), Settings: deps.Settings.(opensubsonic.Settings), } } if deps.About == nil { diff --git a/internal/api/http/handlers_usersettings.go b/internal/api/http/handlers_usersettings.go index 3b21e62..ae10007 100644 --- a/internal/api/http/handlers_usersettings.go +++ b/internal/api/http/handlers_usersettings.go @@ -16,6 +16,11 @@ type userSettingsHandlers struct{ svc userSettingsService } type userSettingsJSON struct { DiscoverFromListening bool `json:"discover_from_listening"` + RadioInApps bool `json:"radio_in_apps"` +} + +func toUserSettingsJSON(s usersettings.Settings) userSettingsJSON { + return userSettingsJSON{DiscoverFromListening: s.DiscoverFromListening, RadioInApps: s.RadioInApps} } func writeUserSettingsError(c *gin.Context, err error) { @@ -33,11 +38,11 @@ func (h *userSettingsHandlers) get(c *gin.Context) { writeUserSettingsError(c, err) return } - c.JSON(http.StatusOK, userSettingsJSON{DiscoverFromListening: s.DiscoverFromListening}) + c.JSON(http.StatusOK, toUserSettingsJSON(s)) } // settingKeys are the settings a PATCH may name, spelt exactly like this. -var settingKeys = map[string]bool{"discover_from_listening": true} +var settingKeys = map[string]bool{"discover_from_listening": true, "radio_in_apps": true} // parseSettingsPatch reads the body of PATCH /me/settings. It is strict because // the settings are about privacy: one JSON object and nothing after it, only known @@ -56,7 +61,12 @@ func parseSettingsPatch(body []byte) (usersettings.Patch, bool) { if err := json.Unmarshal(value, &b); err != nil { return usersettings.Patch{}, false } - p.DiscoverFromListening = b + switch key { + case "discover_from_listening": + p.DiscoverFromListening = b + case "radio_in_apps": + p.RadioInApps = b + } } return p, true } @@ -77,5 +87,5 @@ func (h *userSettingsHandlers) update(c *gin.Context) { writeUserSettingsError(c, err) return } - c.JSON(http.StatusOK, userSettingsJSON{DiscoverFromListening: s.DiscoverFromListening}) + c.JSON(http.StatusOK, toUserSettingsJSON(s)) } diff --git a/internal/api/http/radio_test.go b/internal/api/http/radio_test.go index 31e5a91..eb8aed7 100644 --- a/internal/api/http/radio_test.go +++ b/internal/api/http/radio_test.go @@ -6,6 +6,7 @@ import ( "net/http/httptest" "net/url" "slices" + "strings" "testing" ) @@ -101,6 +102,16 @@ func TestAnAppSeesTheStationsAsPlaylistsWithOtherSongsEveryTime(t *testing.T) { q.Set("f", "json") return restCall(t, m.h, path, q) } + // The stations are not in the apps until the person asks. + before, _ := rest("getPlaylists", url.Values{})["playlists"].(map[string]any)["playlist"].([]any) // none at all: the key is absent + for _, p := range before { + if strings.HasPrefix(p.(map[string]any)["id"].(string), "rd-") { + t.Fatalf("a station in the apps before it was asked for: %v", p) + } + } + if r := do(t, m.h, "PATCH", "/api/v1/me/settings", m.alice, map[string]any{"radio_in_apps": true}); r.Code != http.StatusOK { + t.Fatalf("setting: %d %v", r.Code, r.Body) + } var found bool for _, p := range rest("getPlaylists", url.Values{})["playlists"].(map[string]any)["playlist"].([]any) { if p.(map[string]any)["id"] == "rd-all" { diff --git a/internal/api/http/usersettings_test.go b/internal/api/http/usersettings_test.go index 31436fa..72913a8 100644 --- a/internal/api/http/usersettings_test.go +++ b/internal/api/http/usersettings_test.go @@ -25,7 +25,7 @@ func TestSettingsStartOffAndStayMine(t *testing.T) { if r.Code != http.StatusOK { t.Fatalf("%d %v", r.Code, r.Body) } - sameKeys(t, "settings", r.Body, "discover_from_listening") + sameKeys(t, "settings", r.Body, "discover_from_listening", "radio_in_apps") if r.Body["discover_from_listening"] != false { t.Errorf("settings = %v, want everything off", r.Body) } @@ -139,3 +139,30 @@ func TestSettingsOfADeletedAccountAreRefused(t *testing.T) { } func itoa(n int64) string { return strconv.FormatInt(n, 10) } + +func TestTheRadioInAppsSettingStartsOffAndNamesOnlyItself(t *testing.T) { + h := newTestAPI(t) + alice := registerAndLogin(t, h) + if r := do(t, h, "GET", "/api/v1/me/settings", alice, nil); r.Body["radio_in_apps"] != false { + t.Fatalf("at the start: %v", r.Body) + } + r := do(t, h, "PATCH", "/api/v1/me/settings", alice, map[string]any{"radio_in_apps": true}) + if r.Code != http.StatusOK || r.Body["radio_in_apps"] != true || r.Body["discover_from_listening"] != false { + t.Fatalf("turn on: %d %v", r.Code, r.Body) + } + // The other setting is not touched by naming this one, nor this one by naming the other. + r = do(t, h, "PATCH", "/api/v1/me/settings", alice, map[string]any{"discover_from_listening": true}) + if r.Body["radio_in_apps"] != true || r.Body["discover_from_listening"] != true { + t.Fatalf("the other on: %v", r.Body) + } + r = do(t, h, "PATCH", "/api/v1/me/settings", alice, map[string]any{"radio_in_apps": nil}) + if r.Code != http.StatusOK || r.Body["radio_in_apps"] != true { + t.Fatalf("null leaves it alone: %d %v", r.Code, r.Body) + } + if r = do(t, h, "PATCH", "/api/v1/me/settings", alice, map[string]any{"radio_in_apps": "yes"}); r.Code != http.StatusBadRequest { + t.Fatalf("a string: %d", r.Code) + } + if r = do(t, h, "PATCH", "/api/v1/me/settings", alice, map[string]any{"radio_in_app": true}); r.Code != http.StatusBadRequest { + t.Fatalf("a misspelt name: %d", r.Code) + } +} diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml index c7219df..aa8b88d 100644 --- a/internal/api/openapi/openapi.yaml +++ b/internal/api/openapi/openapi.yaml @@ -6198,8 +6198,14 @@ components: UserSettings: type: object additionalProperties: false - required: [discover_from_listening] + required: [discover_from_listening, radio_in_apps] properties: + radio_in_apps: + type: boolean + description: | + When true, the stations of the radio (see `GET /radio`) are in the list of playlists of the apps that speak + OpenSubsonic, as playlists called `Radio · Rock` with other songs every time they are opened. False until you + turn it on: there are about two dozen of them. Nothing is sent anywhere either way. discover_from_listening: type: boolean description: | @@ -6345,6 +6351,7 @@ components: additionalProperties: false properties: discover_from_listening: {type: boolean, nullable: true} + radio_in_apps: {type: boolean, nullable: true} TasteArtist: type: object diff --git a/internal/opensubsonic/handler.go b/internal/opensubsonic/handler.go index c543298..614dcc7 100644 --- a/internal/opensubsonic/handler.go +++ b/internal/opensubsonic/handler.go @@ -56,6 +56,7 @@ type Deps struct { Playlists Playlists Favorites Favorites // optional: with none nothing is a favourite Radio Radio // optional: with none the list of playlists is only the playlists of the person + Settings Settings // optional: with none the stations of the radio are not shown to apps Listens Listens Announcer Announcer // optional ServerVersion string diff --git a/internal/opensubsonic/handler_test.go b/internal/opensubsonic/handler_test.go index 7c90bba..a595ca3 100644 --- a/internal/opensubsonic/handler_test.go +++ b/internal/opensubsonic/handler_test.go @@ -24,6 +24,7 @@ import ( "git.kmalloc.org/squid/sonda/internal/mixes" "git.kmalloc.org/squid/sonda/internal/playlists" "git.kmalloc.org/squid/sonda/internal/streaming" + "git.kmalloc.org/squid/sonda/internal/usersettings" ) const secret = "0123456789abcdef0123456789abcdef0123456789abcdef" @@ -1430,17 +1431,28 @@ func (f *fakeRadio) Radio(_ context.Context, _ int64, id string) (mixes.Mix, []c return mixes.Mix{}, nil, mixes.ErrNotFound } -func newRadioServer(t *testing.T) http.Handler { +type fakeSettings struct{ radio bool } + +func (f fakeSettings) Get(context.Context, int64) (usersettings.Settings, error) { + return usersettings.Settings{RadioInApps: f.radio}, nil +} + +// newRadioServerWith is a server with the radio, and the setting that shows it in the apps on or off. +func newRadioServerWith(t *testing.T, settings Settings) http.Handler { t.Helper() gin.SetMode(gin.TestMode) r := gin.New() Register(r, Deps{ Login: fakeLogin{}, Catalog: &fakeCatalog{}, Libraries: fakeLibraries{}, Extras: fakeExtras{}, ServerVersion: "9.9", - Playlists: newFakePlaylists(), Radio: &fakeRadio{}, + Playlists: newFakePlaylists(), Radio: &fakeRadio{}, Settings: settings, }) return r } +func newRadioServer(t *testing.T) http.Handler { + return newRadioServerWith(t, fakeSettings{radio: true}) +} + func TestTheStationsOfTheRadioAreInTheListOfPlaylists(t *testing.T) { h := newRadioServer(t) q := ok("name", "Mine") @@ -1496,3 +1508,17 @@ func TestWithNoRadioThePlaylistsAreOnlyTheOnesOfThePerson(t *testing.T) { t.Fatalf("playlists %v", list) } } + +func TestTheStationsAreNotInTheAppsUntilThePersonAsks(t *testing.T) { + for name, settings := range map[string]Settings{"the setting is off": fakeSettings{radio: false}, "there is no setting to read": nil} { + h := newRadioServerWith(t, settings) + q := ok("name", "Mine") + q.Add("songId", "tr-70") + get(t, h, "GET", "/rest/createPlaylist", q) + list := good(t, get(t, h, "GET", "/rest/getPlaylists", ok()))["playlists"].(map[string]any)["playlist"].([]any) + if len(list) != 1 || list[0].(map[string]any)["id"] != "pl-1" { + t.Errorf("%s: playlists %v", name, list) + } + failed(t, get(t, h, "GET", "/rest/getPlaylist", ok("id", "rd-all")), ErrNotFound) + } +} diff --git a/internal/opensubsonic/playlists.go b/internal/opensubsonic/playlists.go index 09b8d15..07a009f 100644 --- a/internal/opensubsonic/playlists.go +++ b/internal/opensubsonic/playlists.go @@ -11,6 +11,7 @@ import ( "git.kmalloc.org/squid/sonda/internal/listening" "git.kmalloc.org/squid/sonda/internal/mixes" "git.kmalloc.org/squid/sonda/internal/playlists" + "git.kmalloc.org/squid/sonda/internal/usersettings" ) const playlistPrefix = "pl-" @@ -55,6 +56,21 @@ func radioPlaylist(m mixes.Mix, owner string, now time.Time) Playlist { return p } +// Settings are the choices of a person: *usersettings.Service. +type Settings interface { + Get(ctx context.Context, userID int64) (usersettings.Settings, error) +} + +// radioShown says whether the stations of the radio are in the list of playlists of this person's apps: only when +// there is a radio and the person asked for it (there are two dozen of them). +func (h *handler) radioShown(k *call) (bool, error) { + if h.Radio == nil || h.Settings == nil { + return false, nil + } + s, err := h.Settings.Get(k.ctx, k.principal.UserID) + return s.RadioInApps, err +} + // Listens records what a person listened to: *listening.Service. type Listens interface { Record(ctx context.Context, e listening.Event) (listening.Result, error) @@ -102,7 +118,11 @@ func (h *handler) playlists(k *call) (*Response, *Error) { for i, p := range all { out[i] = playlistOf(p, k.principal.Email) } - if h.Radio != nil { + shown, err := h.radioShown(k) + if err != nil { + return nil, failure(err) + } + if shown { stations, err := h.Radio.Radios(k.ctx, k.principal.UserID) if err != nil { return nil, failure(err) @@ -161,7 +181,14 @@ func (h *handler) opened(k *call, id int64) (*Response, *Error) { } func (h *handler) playlist(k *call) (*Response, *Error) { - if station, ok := strings.CutPrefix(k.param("id"), radioPrefix); ok && h.Radio != nil { + if station, ok := strings.CutPrefix(k.param("id"), radioPrefix); ok { + shown, err := h.radioShown(k) + if err != nil { + return nil, failure(err) + } + if !shown { + return nil, notFound() + } return h.station(k, station) } id, bad := idParam(k, playlistPrefix) diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go index a58ee79..5f88696 100644 --- a/internal/storage/storage_test.go +++ b/internal/storage/storage_test.go @@ -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 != 35 { - t.Errorf("applied migrations = %d, want 35", applied) + if applied != 36 { + t.Errorf("applied migrations = %d, want 36", applied) } }) } diff --git a/internal/storage/usersettings.go b/internal/storage/usersettings.go index 15fa737..856896b 100644 --- a/internal/storage/usersettings.go +++ b/internal/storage/usersettings.go @@ -29,9 +29,9 @@ type queryer interface { 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) + `SELECT COALESCE(s.discover_from_listening, FALSE), COALESCE(s.radio_in_apps, FALSE) FROM users u LEFT JOIN user_settings s ON s.user_id = u.id WHERE u.id = ?`, userID). - Scan(&s.DiscoverFromListening) + Scan(&s.DiscoverFromListening, &s.RadioInApps) if errors.Is(err, sql.ErrNoRows) { return usersettings.Settings{}, usersettings.ErrUserNotFound } @@ -49,12 +49,23 @@ func (r *UserSettingsRepo) Update(ctx context.Context, userID int64, p usersetti if err != nil { return err } - if p.DiscoverFromListening != nil { - cur.DiscoverFromListening = *p.DiscoverFromListening + // Each setting that the patch names is written on its own, so that the others keep what they have. + for _, w := range []struct { + column string + value *bool + into *bool + }{ + {"discover_from_listening", p.DiscoverFromListening, &cur.DiscoverFromListening}, + {"radio_in_apps", p.RadioInApps, &cur.RadioInApps}, + } { + if w.value == nil { + continue + } + *w.into = *w.value 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 { + `INSERT INTO user_settings (user_id, `+w.column+`) VALUES (?, ?) + ON CONFLICT (user_id) DO UPDATE SET `+w.column+` = excluded.`+w.column, + userID, *w.value); err != nil { if isForeignKeyViolation(err) { return usersettings.ErrUserNotFound // deleted between the read and the write } diff --git a/internal/storage/usersettings_test.go b/internal/storage/usersettings_test.go index a1e0b35..cda39a7 100644 --- a/internal/storage/usersettings_test.go +++ b/internal/storage/usersettings_test.go @@ -78,3 +78,33 @@ func TestAForeignKeyFailureIsRecognised(t *testing.T) { } }) } + +func TestTheRadioInAppsSettingIsKeptApartFromTheOthers(t *testing.T) { + forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { + ctx := context.Background() + alice, _ := NewUserRepo(db).CreateUser(ctx, "alice", "h", false) + repo := NewUserSettingsRepo(db) + on, off := true, false + + if got, _ := repo.Get(ctx, alice.ID); got.RadioInApps || got.DiscoverFromListening { + t.Fatalf("new user: %+v, want everything off", got) + } + got, err := repo.Update(ctx, alice.ID, usersettings.Patch{RadioInApps: &on}) + if err != nil || !got.RadioInApps || got.DiscoverFromListening { + t.Fatalf("radio on: %+v %v", got, err) + } + // The other setting turned on and then off does not touch it, and both can be named at once. + if got, _ = repo.Update(ctx, alice.ID, usersettings.Patch{DiscoverFromListening: &on}); !got.RadioInApps || !got.DiscoverFromListening { + t.Fatalf("both on: %+v", got) + } + if got, _ = repo.Update(ctx, alice.ID, usersettings.Patch{DiscoverFromListening: &off, RadioInApps: &off}); got.RadioInApps || got.DiscoverFromListening { + t.Fatalf("both off: %+v", got) + } + if got, _ = repo.Update(ctx, alice.ID, usersettings.Patch{RadioInApps: &on}); !got.RadioInApps { + t.Fatalf("on again: %+v", got) + } + if got, _ = repo.Get(ctx, alice.ID); !got.RadioInApps || got.DiscoverFromListening { + t.Fatalf("kept: %+v", got) + } + }) +} diff --git a/internal/usersettings/usersettings.go b/internal/usersettings/usersettings.go index 9fe8586..6a9cb80 100644 --- a/internal/usersettings/usersettings.go +++ b/internal/usersettings/usersettings.go @@ -19,11 +19,16 @@ type Settings struct { // to most. Doing so sends their names to Last.fm, so it is off until the user // turns it on. DiscoverFromListening bool + // RadioInApps puts the stations of the radio in the list of playlists of the apps that speak OpenSubsonic, as + // playlists with other songs every time. Nothing leaves the server either way: it is only that there are two dozen + // of them, so they come when the user asks. + RadioInApps bool } // Patch changes some settings. A nil field is left alone. type Patch struct { DiscoverFromListening *bool + RadioInApps *bool } // Store keeps the settings. diff --git a/internal/usersettings/usersettings_test.go b/internal/usersettings/usersettings_test.go index a6247a0..68f2840 100644 --- a/internal/usersettings/usersettings_test.go +++ b/internal/usersettings/usersettings_test.go @@ -33,6 +33,9 @@ func (f *fakeStore) Update(_ context.Context, id int64, p Patch) (Settings, erro if p.DiscoverFromListening != nil { s.DiscoverFromListening = *p.DiscoverFromListening } + if p.RadioInApps != nil { + s.RadioInApps = *p.RadioInApps + } f.byUser[id] = s return s, nil } diff --git a/migrations/postgres/0036_radio_in_apps.sql b/migrations/postgres/0036_radio_in_apps.sql new file mode 100644 index 0000000..727fa76 --- /dev/null +++ b/migrations/postgres/0036_radio_in_apps.sql @@ -0,0 +1,4 @@ +-- radio_in_apps: the stations of the radio are in the list of playlists of an app (OpenSubsonic), as playlists with +-- other songs every time. Off until the person asks: there are two dozen of them. + +ALTER TABLE user_settings ADD COLUMN radio_in_apps BOOLEAN NOT NULL DEFAULT FALSE; diff --git a/migrations/sqlite/0036_radio_in_apps.sql b/migrations/sqlite/0036_radio_in_apps.sql new file mode 100644 index 0000000..8ae37c1 --- /dev/null +++ b/migrations/sqlite/0036_radio_in_apps.sql @@ -0,0 +1,4 @@ +-- radio_in_apps: the stations of the radio are in the list of playlists of an app (OpenSubsonic), as playlists with +-- other songs every time. Off until the person asks: there are two dozen of them. + +ALTER TABLE user_settings ADD COLUMN radio_in_apps INTEGER NOT NULL DEFAULT 0 CHECK (radio_in_apps IN (0, 1)); diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index a36778a..4dbe620 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -4345,6 +4345,12 @@ export interface components { last_error?: string; }; UserSettings: { + /** + * @description When true, the stations of the radio (see `GET /radio`) are in the list of playlists of the apps that speak + * OpenSubsonic, as playlists called `Radio · Rock` with other songs every time they are opened. False until you + * turn it on: there are about two dozen of them. Nothing is sent anywhere either way. + */ + radio_in_apps: 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 @@ -4463,6 +4469,7 @@ export interface components { }; UpdateUserSettings: { discover_from_listening?: boolean | null; + radio_in_apps?: boolean | null; }; TasteArtist: { /** Format: int64 */ diff --git a/web/src/components/RadioInAppsSwitch.test.tsx b/web/src/components/RadioInAppsSwitch.test.tsx new file mode 100644 index 0000000..5122a08 --- /dev/null +++ b/web/src/components/RadioInAppsSwitch.test.tsx @@ -0,0 +1,64 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { beforeEach, expect, test, vi } from 'vitest' +import { initI18n } from '@/i18n' +import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch' +import RadioInAppsSwitch from './RadioInAppsSwitch' + +beforeEach(async () => { + vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') + await initI18n() +}) + +function setup(initial: boolean, over: MockRoutes = {}) { + let on = initial + const mocked = mockFetch({ + 'GET /api/v1/me/settings': () => ({ discover_from_listening: false, radio_in_apps: on }), + 'PATCH /api/v1/me/settings': ({ init }) => { + on = JSON.parse(String(init.body)).radio_in_apps + return { discover_from_listening: false, radio_in_apps: on } + }, + ...over, + }) + render( + + + , + ) + return mocked +} + +const switchEl = () => screen.getByRole('switch', { name: 'Show the radio stations in apps' }) + +test('it is off at first, and says what it does', async () => { + setup(false) + await vi.waitFor(() => expect(switchEl()).not.toBeDisabled()) + expect(switchEl()).toHaveAttribute('aria-checked', 'false') + expect(screen.getByText(/Radio · Rock/)).toBeInTheDocument() +}) + +test('turning it on sends the setting, and the switch shows it', async () => { + const { calls } = setup(false) + await vi.waitFor(() => expect(switchEl()).not.toBeDisabled()) + await userEvent.click(switchEl()) + await vi.waitFor(() => expect(switchEl()).toHaveAttribute('aria-checked', 'true')) + const sent = calls.find((c) => c.key === 'PATCH /api/v1/me/settings')! + expect(JSON.parse(String(sent.init.body))).toEqual({ radio_in_apps: true }) +}) + +test('turning it off sends it too', async () => { + const { calls } = setup(true) + await vi.waitFor(() => expect(switchEl()).toHaveAttribute('aria-checked', 'true')) + await userEvent.click(switchEl()) + await vi.waitFor(() => expect(switchEl()).toHaveAttribute('aria-checked', 'false')) + expect(JSON.parse(String(calls.find((c) => c.key === 'PATCH /api/v1/me/settings')!.init.body))).toEqual({ radio_in_apps: false }) +}) + +test('a setting that cannot be kept says so', async () => { + setup(false, { 'PATCH /api/v1/me/settings': () => apiError(500, 'internal', 'x') }) + await vi.waitFor(() => expect(switchEl()).not.toBeDisabled()) + await userEvent.click(switchEl()) + expect(await screen.findByRole('alert')).toBeInTheDocument() + expect(switchEl()).toHaveAttribute('aria-checked', 'false') +}) diff --git a/web/src/components/RadioInAppsSwitch.tsx b/web/src/components/RadioInAppsSwitch.tsx new file mode 100644 index 0000000..09c1873 --- /dev/null +++ b/web/src/components/RadioInAppsSwitch.tsx @@ -0,0 +1,38 @@ +import { useTranslation } from 'react-i18next' +import { ApiError } from '@/api/client' +import { useMySettings, useUpdateSettings } from '@/api/discover' +import { Switch } from '@/components/ui/switch' +import { errorMessageKey } from '@/i18n' + +/** + * Whether the stations of the radio are in the playlists of the apps (Feishin...). They are about two dozen, so they + * come when asked. Nothing leaves the server either way, so it asks nothing before it turns on. + */ +export default function RadioInAppsSwitch() { + const { t } = useTranslation() + const settings = useMySettings() + const update = useUpdateSettings() + const on = settings.data?.radio_in_apps === true + + return ( +
+
+ update.mutate({ radio_in_apps: !on })} + /> + + {t('devices.radio.label')} + +
+

{t('devices.radio.help')}

+ {update.isError && ( +

+ {t(errorMessageKey(update.error instanceof ApiError ? update.error.code : 'unknown'))} +

+ )} +
+ ) +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index c0a6bcd..89a49b7 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -105,7 +105,11 @@ "password": "Password", "copy": "Copy password", "copied": "Copied", - "done": "Done" + "done": "Done", + "radio": { + "label": "Show the radio stations in apps", + "help": "In apps like Feishin the stations of the radio come as playlists called “Radio · Rock”, with other songs every time you open one. There are about two dozen, so they are off until you ask." + } }, "favorites": { "add": "Add to favourites", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 2f1a9d1..e8edf28 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -105,7 +105,11 @@ "password": "Password", "copy": "Copia password", "copied": "Copiata", - "done": "Fatto" + "done": "Fatto", + "radio": { + "label": "Mostra le stazioni radio nelle app", + "help": "Nelle app come Feishin le stazioni della radio arrivano come playlist chiamate «Radio · Rock», con brani diversi ogni volta che ne apri una. Sono circa due dozzine, quindi restano spente finché non lo chiedi." + } }, "favorites": { "add": "Aggiungi ai preferiti", diff --git a/web/src/pages/SettingsPage.tsx b/web/src/pages/SettingsPage.tsx index 82f3769..223e272 100644 --- a/web/src/pages/SettingsPage.tsx +++ b/web/src/pages/SettingsPage.tsx @@ -6,6 +6,7 @@ import { logout, useSession } from '@/auth/session' import ChoiceGroup from '@/components/ChoiceGroup' import ListeningSwitch from '@/components/ListeningSwitch' import DevicesBlock from '@/components/DevicesBlock' +import RadioInAppsSwitch from '@/components/RadioInAppsSwitch' import MastodonBlock from '@/components/MastodonBlock' import Section from '@/components/Section' import VersionLabel from '@/components/VersionLabel' @@ -188,6 +189,7 @@ export default function SettingsPage() {
+
-- 2.54.0