feat: the radio stations are in the apps only when the person asks

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
This commit is contained in:
tgiachi 2026-11-16 12:33:09 +01:00
commit ed32aac228
23 changed files with 310 additions and 25 deletions

View file

@ -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. - **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. - **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:<id>` 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:<id>` 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. - **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)). - **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. | | `getAlbumList2` | Random, newest, frequent, recent, by name, by artist, by year, by genre. |
| `getRandomSongs`, `getSongsByGenre`, `search3` | Find songs, albums and artists. | | `getRandomSongs`, `getSongsByGenre`, `search3` | Find songs, albums and artists. |
| `stream`, `download`, `getCoverArt` | The original file (with Range), and covers of albums, artists and songs. | | `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. | | `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`. | | `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. | | `setRating`, `getNowPlaying` | Answered with nothing: there are no ratings, and what you play is nobody else's business. |

View file

@ -323,7 +323,7 @@ func run() error {
OpenSubsonic: &opensubsonic.Deps{ OpenSubsonic: &opensubsonic.Deps{
Login: deviceSvc, Catalog: catalogSvc, Libraries: libraries, Login: deviceSvc, Catalog: catalogSvc, Libraries: libraries,
Extras: subsonicRepo, Lists: subsonicRepo, Streams: streamSvc, Covers: pictures, ArtistImages: pictures, 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, ServerVersion: version,
}, },
Scan: scanControl{ctx: ctx, m: scans}, Scan: scanControl{ctx: ctx, m: scans},

View file

@ -150,7 +150,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
Libraries: deps.Libraries.(opensubsonic.Libraries), ServerVersion: "test", Libraries: deps.Libraries.(opensubsonic.Libraries), ServerVersion: "test",
Extras: subsonic, Lists: subsonic, Streams: deps.Streams.(opensubsonic.Streams), Extras: subsonic, Lists: subsonic, Streams: deps.Streams.(opensubsonic.Streams),
Covers: deps.Images.(opensubsonic.Covers), ArtistImages: deps.ArtistImages.(opensubsonic.ArtistImages), 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 { if deps.About == nil {

View file

@ -16,6 +16,11 @@ type userSettingsHandlers struct{ svc userSettingsService }
type userSettingsJSON struct { type userSettingsJSON struct {
DiscoverFromListening bool `json:"discover_from_listening"` 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) { func writeUserSettingsError(c *gin.Context, err error) {
@ -33,11 +38,11 @@ func (h *userSettingsHandlers) get(c *gin.Context) {
writeUserSettingsError(c, err) writeUserSettingsError(c, err)
return 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. // 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 // 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 // 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 { if err := json.Unmarshal(value, &b); err != nil {
return usersettings.Patch{}, false 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 return p, true
} }
@ -77,5 +87,5 @@ func (h *userSettingsHandlers) update(c *gin.Context) {
writeUserSettingsError(c, err) writeUserSettingsError(c, err)
return return
} }
c.JSON(http.StatusOK, userSettingsJSON{DiscoverFromListening: s.DiscoverFromListening}) c.JSON(http.StatusOK, toUserSettingsJSON(s))
} }

View file

@ -6,6 +6,7 @@ import (
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
"slices" "slices"
"strings"
"testing" "testing"
) )
@ -101,6 +102,16 @@ func TestAnAppSeesTheStationsAsPlaylistsWithOtherSongsEveryTime(t *testing.T) {
q.Set("f", "json") q.Set("f", "json")
return restCall(t, m.h, path, q) 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 var found bool
for _, p := range rest("getPlaylists", url.Values{})["playlists"].(map[string]any)["playlist"].([]any) { for _, p := range rest("getPlaylists", url.Values{})["playlists"].(map[string]any)["playlist"].([]any) {
if p.(map[string]any)["id"] == "rd-all" { if p.(map[string]any)["id"] == "rd-all" {

View file

@ -25,7 +25,7 @@ func TestSettingsStartOffAndStayMine(t *testing.T) {
if r.Code != http.StatusOK { if r.Code != http.StatusOK {
t.Fatalf("%d %v", r.Code, r.Body) 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 { if r.Body["discover_from_listening"] != false {
t.Errorf("settings = %v, want everything off", r.Body) 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 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)
}
}

View file

@ -6198,8 +6198,14 @@ components:
UserSettings: UserSettings:
type: object type: object
additionalProperties: false additionalProperties: false
required: [discover_from_listening] required: [discover_from_listening, radio_in_apps]
properties: 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: discover_from_listening:
type: boolean type: boolean
description: | description: |
@ -6345,6 +6351,7 @@ components:
additionalProperties: false additionalProperties: false
properties: properties:
discover_from_listening: {type: boolean, nullable: true} discover_from_listening: {type: boolean, nullable: true}
radio_in_apps: {type: boolean, nullable: true}
TasteArtist: TasteArtist:
type: object type: object

View file

@ -56,6 +56,7 @@ type Deps struct {
Playlists Playlists Playlists Playlists
Favorites Favorites // optional: with none nothing is a favourite 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 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 Listens Listens
Announcer Announcer // optional Announcer Announcer // optional
ServerVersion string ServerVersion string

View file

@ -24,6 +24,7 @@ import (
"git.kmalloc.org/squid/sonda/internal/mixes" "git.kmalloc.org/squid/sonda/internal/mixes"
"git.kmalloc.org/squid/sonda/internal/playlists" "git.kmalloc.org/squid/sonda/internal/playlists"
"git.kmalloc.org/squid/sonda/internal/streaming" "git.kmalloc.org/squid/sonda/internal/streaming"
"git.kmalloc.org/squid/sonda/internal/usersettings"
) )
const secret = "0123456789abcdef0123456789abcdef0123456789abcdef" 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 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() t.Helper()
gin.SetMode(gin.TestMode) gin.SetMode(gin.TestMode)
r := gin.New() r := gin.New()
Register(r, Deps{ Register(r, Deps{
Login: fakeLogin{}, Catalog: &fakeCatalog{}, Libraries: fakeLibraries{}, Extras: fakeExtras{}, ServerVersion: "9.9", Login: fakeLogin{}, Catalog: &fakeCatalog{}, Libraries: fakeLibraries{}, Extras: fakeExtras{}, ServerVersion: "9.9",
Playlists: newFakePlaylists(), Radio: &fakeRadio{}, Playlists: newFakePlaylists(), Radio: &fakeRadio{}, Settings: settings,
}) })
return r return r
} }
func newRadioServer(t *testing.T) http.Handler {
return newRadioServerWith(t, fakeSettings{radio: true})
}
func TestTheStationsOfTheRadioAreInTheListOfPlaylists(t *testing.T) { func TestTheStationsOfTheRadioAreInTheListOfPlaylists(t *testing.T) {
h := newRadioServer(t) h := newRadioServer(t)
q := ok("name", "Mine") q := ok("name", "Mine")
@ -1496,3 +1508,17 @@ func TestWithNoRadioThePlaylistsAreOnlyTheOnesOfThePerson(t *testing.T) {
t.Fatalf("playlists %v", list) 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)
}
}

View file

@ -11,6 +11,7 @@ import (
"git.kmalloc.org/squid/sonda/internal/listening" "git.kmalloc.org/squid/sonda/internal/listening"
"git.kmalloc.org/squid/sonda/internal/mixes" "git.kmalloc.org/squid/sonda/internal/mixes"
"git.kmalloc.org/squid/sonda/internal/playlists" "git.kmalloc.org/squid/sonda/internal/playlists"
"git.kmalloc.org/squid/sonda/internal/usersettings"
) )
const playlistPrefix = "pl-" const playlistPrefix = "pl-"
@ -55,6 +56,21 @@ func radioPlaylist(m mixes.Mix, owner string, now time.Time) Playlist {
return p 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. // Listens records what a person listened to: *listening.Service.
type Listens interface { type Listens interface {
Record(ctx context.Context, e listening.Event) (listening.Result, error) 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 { for i, p := range all {
out[i] = playlistOf(p, k.principal.Email) 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) stations, err := h.Radio.Radios(k.ctx, k.principal.UserID)
if err != nil { if err != nil {
return nil, failure(err) 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) { 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) return h.station(k, station)
} }
id, bad := idParam(k, playlistPrefix) id, bad := idParam(k, playlistPrefix)

View file

@ -156,8 +156,8 @@ func TestMigrateCreatesSchemaAndIsIdempotent(t *testing.T) {
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&applied); err != nil { if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&applied); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if applied != 35 { if applied != 36 {
t.Errorf("applied migrations = %d, want 35", applied) t.Errorf("applied migrations = %d, want 36", applied)
} }
}) })
} }

View file

@ -29,9 +29,9 @@ type queryer interface {
func getUserSettings(ctx context.Context, q queryer, userID int64) (usersettings.Settings, error) { func getUserSettings(ctx context.Context, q queryer, userID int64) (usersettings.Settings, error) {
var s usersettings.Settings var s usersettings.Settings
err := q.QueryRowContext(ctx, 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). 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) { if errors.Is(err, sql.ErrNoRows) {
return usersettings.Settings{}, usersettings.ErrUserNotFound return usersettings.Settings{}, usersettings.ErrUserNotFound
} }
@ -49,12 +49,23 @@ func (r *UserSettingsRepo) Update(ctx context.Context, userID int64, p usersetti
if err != nil { if err != nil {
return err return err
} }
if p.DiscoverFromListening != nil { // Each setting that the patch names is written on its own, so that the others keep what they have.
cur.DiscoverFromListening = *p.DiscoverFromListening 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, if _, err := tx.ExecContext(ctx,
`INSERT INTO user_settings (user_id, discover_from_listening) VALUES (?, ?) `INSERT INTO user_settings (user_id, `+w.column+`) VALUES (?, ?)
ON CONFLICT (user_id) DO UPDATE SET discover_from_listening = excluded.discover_from_listening`, ON CONFLICT (user_id) DO UPDATE SET `+w.column+` = excluded.`+w.column,
userID, cur.DiscoverFromListening); err != nil { userID, *w.value); err != nil {
if isForeignKeyViolation(err) { if isForeignKeyViolation(err) {
return usersettings.ErrUserNotFound // deleted between the read and the write return usersettings.ErrUserNotFound // deleted between the read and the write
} }

View file

@ -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)
}
})
}

View file

@ -19,11 +19,16 @@ type Settings struct {
// to most. Doing so sends their names to Last.fm, so it is off until the user // to most. Doing so sends their names to Last.fm, so it is off until the user
// turns it on. // turns it on.
DiscoverFromListening bool 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. // Patch changes some settings. A nil field is left alone.
type Patch struct { type Patch struct {
DiscoverFromListening *bool DiscoverFromListening *bool
RadioInApps *bool
} }
// Store keeps the settings. // Store keeps the settings.

View file

@ -33,6 +33,9 @@ func (f *fakeStore) Update(_ context.Context, id int64, p Patch) (Settings, erro
if p.DiscoverFromListening != nil { if p.DiscoverFromListening != nil {
s.DiscoverFromListening = *p.DiscoverFromListening s.DiscoverFromListening = *p.DiscoverFromListening
} }
if p.RadioInApps != nil {
s.RadioInApps = *p.RadioInApps
}
f.byUser[id] = s f.byUser[id] = s
return s, nil return s, nil
} }

View file

@ -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;

View file

@ -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));

View file

@ -4345,6 +4345,12 @@ export interface components {
last_error?: string; last_error?: string;
}; };
UserSettings: { 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 * @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 * 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: { UpdateUserSettings: {
discover_from_listening?: boolean | null; discover_from_listening?: boolean | null;
radio_in_apps?: boolean | null;
}; };
TasteArtist: { TasteArtist: {
/** Format: int64 */ /** Format: int64 */

View file

@ -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(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })}>
<RadioInAppsSwitch />
</QueryClientProvider>,
)
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')
})

View file

@ -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 (
<div className="flex max-w-xl flex-col gap-3">
<div className="flex items-center gap-4">
<Switch
checked={on}
aria-labelledby="radio-apps-label"
disabled={settings.data === undefined || update.isPending}
onClick={() => update.mutate({ radio_in_apps: !on })}
/>
<span id="radio-apps-label" className="font-semibold">
{t('devices.radio.label')}
</span>
</div>
<p className="text-sm text-muted-foreground">{t('devices.radio.help')}</p>
{update.isError && (
<p role="alert" className="text-sm text-destructive">
{t(errorMessageKey(update.error instanceof ApiError ? update.error.code : 'unknown'))}
</p>
)}
</div>
)
}

Some files were not shown because too many files have changed in this diff Show more