diff --git a/README.md b/README.md
index 6a22fd1..9e6e2e8 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
- **Artist photos.** `GET /artists/{id}/image` serves a free picture of an artist from Wikimedia Commons, and `GET /artists/{id}/image/credit` says whose it is and under which licence, which you must show next to it. Only free licences are kept (public domain, CC0, CC BY, CC BY-SA): non-commercial, no-derivatives, fair-use and unknown ones are refused, because Sonda stores a copy (`?size=small` is 300 pixels, `large` 1000) in the data folder. With the `commons` provider and the `musicbrainz` one switched on, Sonda follows ids and never a name: the artist's MusicBrainz id, the Wikidata item MusicBrainz links to it, the picture Wikidata names for it, and Commons for its licence. Many artists will have none. Kept for 30 days (a week when there is none) and removed, files included, with the provider's data. To look for the pictures of the whole library in one go, an admin starts a background job like a scan: `POST /library/artist-images` (follow it with `GET /library/artist-images`, stop it with `DELETE /library/artist-images`; `?refresh=true` searches every artist again). It only goes through artists that have a MusicBrainz id, never replaces a picture by a failure, and ends at once, saying so, when a provider it needs is off. See [External providers](#external-providers).
- **Album covers.** `GET /albums/{id}/cover` serves the cover of an album from your own files: the picture embedded in them, or else a `cover`, `folder`, `front`, `album` or `albumart` image in the album's folder. It is built the first time it is asked for (a few at a time), scaled (`?size=small` is 300 pixels, `large` 1000) and kept in the data folder (`storage.data_dir`, you can delete it: covers are built again). A picture you replace in a folder is noticed within a week, or at once after a full rescan. When your files have no picture at all and an admin switched on the `coverartarchive` provider, the cover is asked from the Cover Art Archive by the MusicBrainz release group id that the tags of the album's files carry (`MUSICBRAINZ_RELEASEGROUPID`; run a full rescan to read it for music you already indexed); your own files always come first, and only that id leaves the server. An album whose files have no id is looked up in MusicBrainz by its artist and title when the `musicbrainz` provider is on too (see the list of what leaves your server). For an album split in `CD1`/`Disc 2` folders, the picture in the folder above is used. Nothing is sent anywhere unless you switched on the `coverartarchive` provider (see [External providers](#external-providers)). It also takes `?access_token=`, so an `
+ {errorLine(t, preview.error)}
+ {t('smart.editor.previewNone')} {t('smart.editor.previewCount', { count: tracks.length, duration: formatTime(duration) })} {t('smart.editor.previewMore', { count: tracks.length - 8 })} {hint} {p.description} {t('smart.songs', { count: tracks.length, duration: formatTime(duration) })}
+ {t('smart.saved', { name: save.data.name })}
+
+ {t('smart.open')}
+
+
+ {errorLine(t, save.error ?? del.error)}
+ ` element can use it. To build the covers of the whole library in one go instead of one album at a time, an admin starts a background job like a scan: `POST /library/covers` (follow it with `GET /library/covers`, stop it with `DELETE /library/covers`; `?refresh=true` searches every album again; it never replaces a cover by "no cover" because a disk was not mounted, and keeps the covers that came from the archive if you switched it off).
- **Mixes.** `GET /mixes` lists playlists that Sonda makes for you, like the mixes of a streaming service, from what you listen to and from the genres of your music: one mix for each genre of your library that has at least 30 songs by 4 artists (the genres you play most first), and, once you have some listening history, *Your favourites* and *Rediscover* (artists you like and have not played for a month); *New to you* is the songs you never played. `GET /mixes/{id}` gives a mix of up to 50 songs, at most 3 by one artist and never two of the same artist in a row. They are picked by weighted chance: the artists you play weigh more and songs you skipped lately or artists you avoid are left out. A mix stays the same for a day, and `?variant=2` gives another; `POST /mixes/{id}/playlist` keeps the one you are looking at as a playlist of your own. A mix is worked out when you ask for it, from your own history and the genre tags of your files: nothing is stored and nothing is sent to a provider. The id of a genre mix has the genre in it (`genre:hard rock`), so it is percent-encoded in the path.
-- **Smart playlists.** A smart playlist is a set of rules instead of a list of songs, worked out again every time you open it, so new songs and your listening change it by themselves. `POST /smart-playlists` keeps a name, the rules, an order (`random`, `most_played`, `least_played`, `recently_added` or `title`) and a limit (50 by default, 500 at most); `GET /smart-playlists/{id}/tracks` gives the songs now. Every rule that is set must hold: genres, artists and albums (is, or is not), file formats and a minimum bitrate (about the same file), added in the last N days (by the date of the file), never played, played or not played in the last N days, played at least N times, skipped or not skipped lately, only artists you like or without the ones you avoid, and the length of the song. `POST /smart-playlists/preview` tries rules without keeping them, and `POST /smart-playlists/{id}/playlist` keeps what you see as a normal playlist (a copy). Only the rules are stored; the songs come from the files and from your own history, nothing is sent to a provider, and a smart playlist is yours alone. A random order stays the same for a day, and `?variant=2` gives another. The year of a song is not in the index yet, so there is no rule about it. A user can have 200.
+- **Smart playlists.** A smart playlist is a set of rules instead of a list of songs, worked out again every time you open it, so new songs and your listening change it by themselves. `POST /smart-playlists` keeps a name, the rules, an order (`random`, `most_played`, `least_played`, `recently_added` or `title`) and a limit (50 by default, 500 at most); `GET /smart-playlists/{id}/tracks` gives the songs now. Every rule that is set must hold: genres, artists and albums (is, or is not), file formats and a minimum bitrate (about the same file), added in the last N days (by the date of the file), never played, played or not played in the last N days, played at least N times, skipped or not skipped lately, only artists you like or without the ones you avoid, and the length of the song. `POST /smart-playlists/preview` tries rules without keeping them, and `POST /smart-playlists/{id}/playlist` keeps what you see as a normal playlist (a copy). Only the rules are stored; the songs come from the files and from your own history, nothing is sent to a provider, and a smart playlist is yours alone, and `GET /genres` lists the genres to choose from. A random order stays the same for a day, and `?variant=2` gives another. The year of a song is not in the index yet, so there is no rule about it. A user can have 200.
- **Playlists.** `POST /playlists` makes a playlist (a name and an optional description) and `GET /playlists` lists yours, the one changed last first. `POST /playlists/{id}/tracks` adds 1 to 500 tracks at the end or at a `position`, `GET /playlists/{id}/tracks` lists them in order, `PATCH /playlists/{id}/tracks/{item}` moves one and `DELETE` takes one out; `PATCH /playlists/{id}` renames and `DELETE /playlists/{id}` deletes (the tracks stay in the library). A track can be in a playlist more than once, which is why each place has its own item id. A playlist is yours alone: someone else's answers `playlist_not_found`, as one that does not exist. A track whose files were deleted or moved away stays in the playlist and shows `available: false`; it plays again when the files come back and a scan finds them. A user can have 1000 playlists of up to 10000 tracks. Nothing is shared and nothing leaves your server.
- **Wishlist and "not interested".** `PUT /wishlist/{artist}` puts an artist on your wishlist (`GET /wishlist` lists it, `DELETE` takes it off), and `POST /discover/{artist}/dismiss` hides an artist from your Discover for good (`DELETE` brings it back, `GET /discover/dismissed` lists them). An artist is wished or dismissed, never both, and both lists are yours alone. Discover marks the wished artists it shows (`wishlisted`) and never suggests a dismissed one. The wishlist is a list for you and sends nothing anywhere; Sonda downloads nothing, but an admin can send an artist that Discover showed to their own Lidarr (see [External providers](#external-providers)), which works for an artist that has a MusicBrainz id and that Sonda knows of from a list or from your files. An artist that only Last.fm named is kept while you have it marked (your lists still show it, but other users cannot see that it exists), and goes with the rest of Last.fm's data if an admin removes Last.fm's data. Removing MusicBrainz's data does not touch it.
- **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 this setting never sends your listening 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). What Last.fm answers is kept in the shared database like any other lookup, so another local user can see, from `retrieved_at` of `GET /artists/{id}/similar`, that someone looked up an artist, but not who.
@@ -295,6 +295,7 @@ Everything lives under `/api/v1`. Bodies are JSON. Errors always look like `{"er
| signed in | `GET /discover` | Artists you may like, with a score and its parts. Query: `seed` (an artist id, up to 5 times), `limit` (default 20, max 30), `in_library=true\|false`. |
| signed in | `GET`, `HEAD /albums/{id}/cover` | The cover of an album, a JPEG made from your own files. Query: `size=small\|large`. Also accepts `?access_token=`. |
| signed in | `GET /mixes`, `GET /mixes/{id}`, `POST /mixes/{id}/playlist` | Your mixes: list them, read one (query `variant`), keep one as a playlist. Made for you alone, from your history and your genres; nothing is stored. |
+| signed in | `GET /genres` | The genres of the library with their number of songs, the biggest first, spellings merged: what the rules of a smart playlist choose from. |
| signed in | `GET /smart-playlists`, `POST /smart-playlists`, `GET`, `PATCH`, `DELETE /smart-playlists/{id}` | Your smart playlists: list them (query `limit`, `offset`), make one from rules, read, change or delete one. Never anybody else's. |
| signed in | `GET /smart-playlists/{id}/tracks`, `POST /smart-playlists/preview`, `POST /smart-playlists/{id}/playlist` | The songs the rules give now (query `variant`), a preview of rules that are not kept, and a smart playlist kept as a normal playlist. |
| signed in | `GET /playlists`, `POST /playlists`, `GET`, `PATCH`, `DELETE /playlists/{id}` | Your playlists: list them (query `limit`, `offset`), make one, read, rename or delete one. Never anybody else's. |
@@ -345,7 +346,7 @@ npm install
SONDA_URL=http://127.0.0.1:8080 npm run dev # open http://localhost:5173, /api is proxied to Sonda
```
-What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys, a volume slider with mute (remembered in the browser) and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Playlists have a page of their own: make one, put a song in it with the button next to any song (or make a new playlist right there), play it, rename it, delete it, move a song up or down and take one out; a song whose files are gone is shown as not available and skipped when the playlist plays. Mixes have a page too: a card for each mix (the ones from your listening first, then one for each genre), and on a mix its songs, Play, Shuffle again (another set of songs) and Save as playlist, which keeps what you see as a playlist of your own. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. Providers have a card each that says what the provider is sent: turning one on asks first, the API key is write-only (never shown, and gone from the page once saved), and there are a test of the key, the contact or address, removing what a provider gave, and, for Lidarr, the profiles and root folder to use when an artist is added. The bulk jobs (album covers, artist pictures, artist descriptions) each have a card that says what the job sends and to whom: starting one asks first and says it goes through the whole library, reading everything again is a separate choice, a job whose providers are off cannot be started, and the page follows its progress and can stop it. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings.
+What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys, a volume slider with mute (remembered in the browser) and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Playlists have a page of their own: make one, put a song in it with the button next to any song (or make a new playlist right there), play it, rename it, delete it, move a song up or down and take one out; a song whose files are gone is shown as not available and skipped when the playlist plays. Mixes have a page too: a card for each mix (the ones from your listening first, then one for each genre), and on a mix its songs, Play, Shuffle again (another set of songs) and Save as playlist, which keeps what you see as a playlist of your own. Smart playlists have their own page too: make one with an editor of the rules (genres, format and bitrate, when it was added, your listening and taste, the length, the order and the limit) and a live preview of the songs it gives, play it, shuffle it again (for the random order), keep what you see as a playlist, edit it or delete it; rules by artist and album are in the API only, and an edit keeps them. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. Providers have a card each that says what the provider is sent: turning one on asks first, the API key is write-only (never shown, and gone from the page once saved), and there are a test of the key, the contact or address, removing what a provider gave, and, for Lidarr, the profiles and root folder to use when an artist is added. The bulk jobs (album covers, artist pictures, artist descriptions) each have a card that says what the job sends and to whom: starting one asks first and says it goes through the whole library, reading everything again is a separate choice, a job whose providers are off cannot be started, and the page follows its progress and can stop it. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings.
More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). `npm run build` writes to `internal/webui/dist` (git-ignored), not to `web/dist`.
diff --git a/internal/api/http/contract_test.go b/internal/api/http/contract_test.go
index 0f9e48b..ba50ddb 100644
--- a/internal/api/http/contract_test.go
+++ b/internal/api/http/contract_test.go
@@ -1034,6 +1034,10 @@ func (c *contract) smartPlaylists(t *testing.T, token string) {
t.Helper()
rules := map[string]any{"genres": []string{"synthwave"}, "formats": []string{"flac"}, "never_played": true}
c.expect(c.call("GET", "/smart-playlists", "", nil), 401, "smart playlists without a token", "unauthorized")
+ genres := c.expect(c.call("GET", "/genres", token, nil), 200, "the genres of the library")
+ if len(genres["items"].([]any)) == 0 {
+ t.Fatalf("genres = %v", genres)
+ }
c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "", "rules": rules}), 400, "a smart playlist with no name", "invalid_input")
c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "x", "sort": "loudest"}), 400, "an unknown order", "invalid_input")
made := c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "Fresh synth", "description": "new", "rules": rules, "sort": "title", "limit": 12}), 201, "make a smart playlist")
diff --git a/internal/api/http/handlers_smart.go b/internal/api/http/handlers_smart.go
index 11e9f7b..946b9c9 100644
--- a/internal/api/http/handlers_smart.go
+++ b/internal/api/http/handlers_smart.go
@@ -233,3 +233,18 @@ func (h *smartHandlers) save(c *gin.Context) {
}
keepAsPlaylist(c, h.playlists, user, name, tracks)
}
+
+// genres lists the genres of the library, to choose from in a rule: each with the number of songs, the
+// biggest first, spellings merged the way the rules compare them.
+func (h *smartHandlers) genres(c *gin.Context) {
+ list, err := h.svc.Genres(c.Request.Context())
+ if err != nil {
+ writeSmartError(c, err)
+ return
+ }
+ items := make([]gin.H, len(list))
+ for i, g := range list {
+ items[i] = gin.H{"name": g.Name, "tracks": g.Tracks}
+ }
+ c.JSON(http.StatusOK, gin.H{"items": items})
+}
diff --git a/internal/api/http/router.go b/internal/api/http/router.go
index 9236b4d..79c26f2 100644
--- a/internal/api/http/router.go
+++ b/internal/api/http/router.go
@@ -116,6 +116,7 @@ type smartService interface {
Delete(ctx context.Context, userID, id int64) error
Tracks(ctx context.Context, userID, id int64, variant int) (smart.SmartPlaylist, []catalog.Track, error)
Preview(ctx context.Context, userID int64, in smart.Input, variant int) ([]catalog.Track, error)
+ Genres(ctx context.Context) ([]smart.GenreCount, error)
}
type feedbackService interface {
@@ -277,6 +278,7 @@ func NewRouter(d Deps) *gin.Engine {
protected.GET("/mixes/:id", mx.get)
protected.POST("/mixes/:id/playlist", mx.save)
sm := &smartHandlers{svc: d.Smart, playlists: d.Playlists}
+ protected.GET("/genres", sm.genres)
protected.GET("/smart-playlists", sm.list)
protected.POST("/smart-playlists", sm.create)
protected.POST("/smart-playlists/preview", sm.preview)
diff --git a/internal/api/http/smart_test.go b/internal/api/http/smart_test.go
index 5f795d3..13f7a5f 100644
--- a/internal/api/http/smart_test.go
+++ b/internal/api/http/smart_test.go
@@ -32,7 +32,7 @@ func smartTracks(t *testing.T, m *mixAPI, id int, query string) []float64 {
func TestSmartPlaylistRoutesNeedASignedInUser(t *testing.T) {
m := newMixAPI(t)
for _, rt := range []struct{ method, path string }{
- {"GET", sp}, {"POST", sp}, {"POST", sp + "/preview"}, {"GET", sp + "/1"}, {"PATCH", sp + "/1"}, {"DELETE", sp + "/1"},
+ {"GET", "/api/v1/genres"}, {"GET", sp}, {"POST", sp}, {"POST", sp + "/preview"}, {"GET", sp + "/1"}, {"PATCH", sp + "/1"}, {"DELETE", sp + "/1"},
{"GET", sp + "/1/tracks"}, {"POST", sp + "/1/playlist"},
} {
if r := do(t, m.h, rt.method, rt.path, "", nil); r.Code != http.StatusUnauthorized {
@@ -263,3 +263,19 @@ func TestASmartPlaylistIsItsOwnersAlone(t *testing.T) {
t.Errorf("alice's own changed: %d %v", r.Code, r.Body)
}
}
+
+func TestTheGenresOfTheLibraryAreListedBiggestFirst(t *testing.T) {
+ m := newMixAPI(t)
+ r := do(t, m.h, "GET", "/api/v1/genres", m.alice, nil)
+ if r.Code != http.StatusOK {
+ t.Fatalf("genres: %d %v", r.Code, r.Body)
+ }
+ items := r.Body["items"].([]any)
+ if len(items) != 2 {
+ t.Fatalf("genres = %v", items)
+ }
+ first, second := items[0].(map[string]any), items[1].(map[string]any)
+ if first["name"] != "rock" || first["tracks"] != float64(40) || second["name"] != "hard rock" || second["tracks"] != float64(36) {
+ t.Errorf("genres = %v", items)
+ }
+}
diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml
index 91c0958..6999c5a 100644
--- a/internal/api/openapi/openapi.yaml
+++ b/internal/api/openapi/openapi.yaml
@@ -1288,6 +1288,25 @@ paths:
application/json:
schema: {$ref: '#/components/schemas/Error'}
+ /genres:
+ get:
+ tags: [Smart playlists]
+ operationId: listGenres
+ summary: The genres of the library
+ description: |
+ The genres of the playable songs, to choose from in the rules of a smart playlist: each with the number
+ of songs, the biggest first, and by name among equals. The spellings that the files have are one genre
+ (`jazz+funk` and `jazz-funk` are `jazz funk`), written the way the rules compare them; tags such as
+ `other` or `unknown` are left out.
+ security: [{bearerAuth: []}]
+ responses:
+ '200':
+ description: The genres.
+ content:
+ application/json:
+ schema: {$ref: '#/components/schemas/GenreList'}
+ '401': {$ref: '#/components/responses/Unauthorized'}
+
/smart-playlists:
get:
tags: [Smart playlists]
@@ -3385,6 +3404,21 @@ components:
name: {type: string, maxLength: 200, description: "The name of the playlist; blank or absent means the title of the mix."}
variant: {type: integer, minimum: 0, maximum: 1000000, description: "The variant the client showed; absent means the mix of the day."}
+ GenreList:
+ type: object
+ additionalProperties: false
+ required: [items]
+ properties:
+ items:
+ type: array
+ items:
+ type: object
+ additionalProperties: false
+ required: [name, tracks]
+ properties:
+ name: {type: string}
+ tracks: {type: integer, description: Playable songs that have the genre.}
+
SmartRules:
type: object
additionalProperties: false
diff --git a/internal/smart/smart.go b/internal/smart/smart.go
index 3a4609c..a73d580 100644
--- a/internal/smart/smart.go
+++ b/internal/smart/smart.go
@@ -432,6 +432,38 @@ func (s *Service) Update(ctx context.Context, userID, id int64, p Patch) (SmartP
return s.store.Update(ctx, userID, id, SmartPlaylist{Name: in.Name, Description: in.Description, Rules: in.Rules, Sort: in.Sort, Limit: in.Limit}, s.now())
}
+// GenreCount is a genre as it is compared (see Rules) with the number of playable songs that have it.
+type GenreCount struct {
+ Name string
+ Tracks int
+}
+
+// Genres returns the genres of the library to choose from in a rule, the one with most songs first, and
+// by name among equals. The spellings the files have are one genre; "other" and the like are left out.
+func (s *Service) Genres(ctx context.Context) ([]GenreCount, error) {
+ all, err := s.store.Genres(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("read genres: %w", err)
+ }
+ byName := map[string]int{}
+ for _, g := range all {
+ if n := mixes.NormalizeGenre(g.Name); n != "" {
+ byName[n] += g.Tracks
+ }
+ }
+ out := make([]GenreCount, 0, len(byName))
+ for n, c := range byName {
+ out = append(out, GenreCount{n, c})
+ }
+ sort.Slice(out, func(i, j int) bool {
+ if out[i].Tracks != out[j].Tracks {
+ return out[i].Tracks > out[j].Tracks
+ }
+ return out[i].Name < out[j].Name
+ })
+ return out, nil
+}
+
// Delete removes a smart playlist of the user.
func (s *Service) Delete(ctx context.Context, userID, id int64) error {
return s.store.Delete(ctx, userID, id)
diff --git a/internal/smart/smart_test.go b/internal/smart/smart_test.go
index 524e957..7947080 100644
--- a/internal/smart/smart_test.go
+++ b/internal/smart/smart_test.go
@@ -499,3 +499,21 @@ func TestListLowersAPageThatIsTooBigAndRefusesNegatives(t *testing.T) {
t.Errorf("a negative offset: %v", err)
}
}
+
+func TestGenresMergeSpellingsLeaveOutWhatIsNotAGenreAndCountTheBiggestFirst(t *testing.T) {
+ st := newStore()
+ st.genres = []mixes.Genre{
+ {Name: "Rock", Tracks: 30}, {Name: "rock", Tracks: 10},
+ {Name: "Jazz+Funk", Tracks: 5}, {Name: "jazz-funk", Tracks: 7},
+ {Name: "metal", Tracks: 12}, {Name: "Blues", Tracks: 12},
+ {Name: "other", Tracks: 99}, {Name: " ", Tracks: 4},
+ }
+ got, err := newService(st, taste.Learned{}).Genres(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []GenreCount{{"rock", 40}, {"blues", 12}, {"jazz funk", 12}, {"metal", 12}} // a tie goes to the name
+ if !slices.Equal(got, want) {
+ t.Errorf("got %v, want %v", got, want)
+ }
+}
diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts
index cbd02e3..ddc87b3 100644
--- a/web/src/api/schema.d.ts
+++ b/web/src/api/schema.d.ts
@@ -891,6 +891,157 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/genres": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * The genres of the library
+ * @description The genres of the playable songs, to choose from in the rules of a smart playlist: each with the number
+ * of songs, the biggest first, and by name among equals. The spellings that the files have are one genre
+ * (`jazz+funk` and `jazz-funk` are `jazz funk`), written the way the rules compare them; tags such as
+ * `other` or `unknown` are left out.
+ */
+ get: operations["listGenres"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/smart-playlists": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Your smart playlists
+ * @description The smart playlists you made, the one changed last first. Only yours. A smart playlist is a set
+ * of rules: its songs come from `GET /smart-playlists/{id}/tracks`.
+ */
+ get: operations["listSmartPlaylists"];
+ put?: never;
+ /**
+ * Make a smart playlist
+ * @description Keeps a set of rules, an order and a limit under a name. Only that is stored: the songs are worked
+ * out again every time. A user can have 200. Names can repeat. Use `POST /smart-playlists/preview`
+ * to try the rules first.
+ */
+ post: operations["createSmartPlaylist"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/smart-playlists/preview": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Try rules without keeping them
+ * @description Works the songs out for rules that are not kept, the way `GET /smart-playlists/{id}/tracks` would,
+ * so they can be tried while they are written. Nothing is stored.
+ */
+ post: operations["previewSmartPlaylist"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/smart-playlists/{id}": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: components["parameters"]["Id"];
+ };
+ cookie?: never;
+ };
+ /**
+ * A smart playlist
+ * @description Its name, rules, order and limit, without the songs. One of somebody else answers
+ * `smart_playlist_not_found`.
+ */
+ get: operations["getSmartPlaylist"];
+ put?: never;
+ post?: never;
+ /**
+ * Delete a smart playlist
+ * @description Deletes the rules. Playlists that were made from it with `POST /smart-playlists/{id}/playlist` stay.
+ */
+ delete: operations["deleteSmartPlaylist"];
+ options?: never;
+ head?: never;
+ /**
+ * Change a smart playlist
+ * @description Changes what is given. The rules, when given, replace the old ones whole. An empty description clears
+ * it; a name cannot be empty.
+ */
+ patch: operations["updateSmartPlaylist"];
+ trace?: never;
+ };
+ "/smart-playlists/{id}/tracks": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: components["parameters"]["Id"];
+ };
+ cookie?: never;
+ };
+ /**
+ * The songs of a smart playlist, now
+ * @description Works the rules out on the playable songs of the library, with your own listening history and taste
+ * for the rules that use them, puts them in the order and cuts the end at the limit. A song whose files
+ * are gone is never offered. Nothing is stored, and nothing is asked of a provider. With the random
+ * order the songs stay the same all day, and another `variant` gives other ones.
+ */
+ get: operations["getSmartPlaylistTracks"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/smart-playlists/{id}/playlist": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: components["parameters"]["Id"];
+ };
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Keep a smart playlist as a playlist
+ * @description Makes a playlist of your own with the songs that `variant` gives now, in the same order. The playlist
+ * is a copy: it does not change afterwards, and is yours to edit. The body is optional.
+ */
+ post: operations["saveSmartPlaylist"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/playlists": {
parameters: {
query?: never;
@@ -2110,6 +2261,110 @@ export interface components {
/** @description The variant the client showed; absent means the mix of the day. */
variant?: number;
};
+ GenreList: {
+ items: {
+ name: string;
+ /** @description Playable songs that have the genre. */
+ tracks: number;
+ }[];
+ };
+ /**
+ * @description Every rule that is set must hold; one that is absent, empty, false or 0 does not count. Of a list rule a
+ * song needs to match one item.
+ */
+ SmartRules: {
+ /** @description Kept lower case, with `+`, `-`, `_` and `/` taken for spaces: `jazz+funk` and `jazz-funk` are one genre. */
+ genres?: string[];
+ /** @description Leaves out songs of these genres. */
+ not_genres?: string[];
+ /** @description Songs whose main artist is one of these. */
+ artist_ids?: number[];
+ not_artist_ids?: number[];
+ album_ids?: number[];
+ not_album_ids?: number[];
+ /** @description File formats in lower case (`flac`, `mpeg`). A song counts when a file of it that is not missing has one of them. */
+ formats?: string[];
+ /** @description Needs a file of the song with this bitrate or more (the same file as `formats`). */
+ min_bitrate_kbps?: number;
+ /** @description About the date of the file, which is the best the index knows. */
+ added_within_days?: number;
+ /** @description Songs you never listened to. */
+ never_played?: boolean;
+ played_within_days?: number;
+ /** @description Songs not played for this many days (the ones never played too). */
+ not_played_within_days?: number;
+ min_plays?: number;
+ skipped_within_days?: number;
+ /** @description Leaves out songs skipped in the last days. */
+ not_skipped_within_days?: number;
+ /** @description Only songs by artists you like. */
+ liked_artists_only?: boolean;
+ /** @description Leaves out songs by artists you avoid. */
+ without_avoided_artists?: boolean;
+ min_duration_sec?: number;
+ max_duration_sec?: number;
+ };
+ /**
+ * @description A tie always goes to the lower song id.
+ * @enum {string}
+ */
+ SmartSort: "random" | "most_played" | "least_played" | "recently_added" | "title";
+ SmartPlaylist: {
+ /** Format: int64 */
+ id: number;
+ name: string;
+ description: string;
+ rules: components["schemas"]["SmartRules"];
+ sort: components["schemas"]["SmartSort"];
+ /** @description The most songs it gives. */
+ limit: number;
+ /** Format: date-time */
+ created_at: string;
+ /** Format: date-time */
+ updated_at: string;
+ };
+ SmartPlaylistPage: {
+ items: components["schemas"]["SmartPlaylist"][];
+ total: number;
+ limit: number;
+ offset: number;
+ };
+ CreateSmartPlaylist: {
+ /** @description Trimmed. */
+ name: string;
+ description?: string;
+ rules?: components["schemas"]["SmartRules"];
+ sort?: components["schemas"]["SmartSort"];
+ /** @default 50 */
+ limit: number;
+ };
+ /** @description What is given changes; the rules replace the old ones whole. */
+ UpdateSmartPlaylist: {
+ name?: string;
+ description?: string;
+ rules?: components["schemas"]["SmartRules"];
+ sort?: components["schemas"]["SmartSort"];
+ limit?: number;
+ };
+ PreviewSmartPlaylist: {
+ rules?: components["schemas"]["SmartRules"];
+ sort?: components["schemas"]["SmartSort"];
+ /** @default 50 */
+ limit: number;
+ /** @default 0 */
+ variant: number;
+ };
+ SmartTracks: {
+ variant: number;
+ /** @description In the order of the playlist. Empty when no song meets the rules. */
+ tracks: components["schemas"]["Track"][];
+ };
+ SaveSmartPlaylist: {
+ /** @description The name of the playlist; blank or absent means the name of the smart playlist. */
+ name?: string;
+ /** @description The variant the client showed; absent means the songs of the day. */
+ variant?: number;
+ };
Playlist: {
/** Format: int64 */
id: number;
@@ -2464,6 +2719,15 @@ export interface components {
"application/json": components["schemas"]["Error"];
};
};
+ /** @description No such smart playlist, or it is somebody else's (`smart_playlist_not_found`). */
+ SmartPlaylistNotFound: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
/** @description No such playlist, or it is somebody else's (`playlist_not_found`). */
PlaylistNotFound: {
headers: {
@@ -3964,6 +4228,258 @@ export interface operations {
};
};
};
+ listGenres: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The genres. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["GenreList"];
+ };
+ };
+ 401: components["responses"]["Unauthorized"];
+ };
+ };
+ listSmartPlaylists: {
+ parameters: {
+ query?: {
+ /** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
+ limit?: components["parameters"]["Limit"];
+ offset?: components["parameters"]["Offset"];
+ };
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description A page of smart playlists. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SmartPlaylistPage"];
+ };
+ };
+ 400: components["responses"]["InvalidInput"];
+ 401: components["responses"]["Unauthorized"];
+ };
+ };
+ createSmartPlaylist: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["CreateSmartPlaylist"];
+ };
+ };
+ responses: {
+ /** @description The smart playlist. */
+ 201: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SmartPlaylist"];
+ };
+ };
+ 400: components["responses"]["InvalidInput"];
+ 401: components["responses"]["Unauthorized"];
+ /** @description A user can have 200 smart playlists (`limit_reached`). */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ };
+ };
+ previewSmartPlaylist: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["PreviewSmartPlaylist"];
+ };
+ };
+ responses: {
+ /** @description The songs. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SmartTracks"];
+ };
+ };
+ 400: components["responses"]["InvalidInput"];
+ 401: components["responses"]["Unauthorized"];
+ };
+ };
+ getSmartPlaylist: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: components["parameters"]["Id"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The smart playlist. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SmartPlaylist"];
+ };
+ };
+ 400: components["responses"]["InvalidInput"];
+ 401: components["responses"]["Unauthorized"];
+ 404: components["responses"]["SmartPlaylistNotFound"];
+ };
+ };
+ deleteSmartPlaylist: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: components["parameters"]["Id"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Deleted. */
+ 204: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ 400: components["responses"]["InvalidInput"];
+ 401: components["responses"]["Unauthorized"];
+ 404: components["responses"]["SmartPlaylistNotFound"];
+ };
+ };
+ updateSmartPlaylist: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: components["parameters"]["Id"];
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["UpdateSmartPlaylist"];
+ };
+ };
+ responses: {
+ /** @description The smart playlist as it is now. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SmartPlaylist"];
+ };
+ };
+ 400: components["responses"]["InvalidInput"];
+ 401: components["responses"]["Unauthorized"];
+ 404: components["responses"]["SmartPlaylistNotFound"];
+ };
+ };
+ getSmartPlaylistTracks: {
+ parameters: {
+ query?: {
+ /** @description Other songs for the random order, from 0 (the songs of the day) up. */
+ variant?: number;
+ };
+ header?: never;
+ path: {
+ id: components["parameters"]["Id"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The songs. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SmartTracks"];
+ };
+ };
+ 400: components["responses"]["InvalidInput"];
+ 401: components["responses"]["Unauthorized"];
+ 404: components["responses"]["SmartPlaylistNotFound"];
+ };
+ };
+ saveSmartPlaylist: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: components["parameters"]["Id"];
+ };
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["SaveSmartPlaylist"];
+ };
+ };
+ responses: {
+ /** @description The playlist. */
+ 201: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Playlist"];
+ };
+ };
+ 400: components["responses"]["InvalidInput"];
+ 401: components["responses"]["Unauthorized"];
+ 404: components["responses"]["SmartPlaylistNotFound"];
+ 409: components["responses"]["PlaylistLimit"];
+ /** @description The rules give no songs to save (`smart_playlist_empty`). */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ };
+ };
listPlaylists: {
parameters: {
query?: {
diff --git a/web/src/api/smart.ts b/web/src/api/smart.ts
new file mode 100644
index 0000000..5f3d0af
--- /dev/null
+++ b/web/src/api/smart.ts
@@ -0,0 +1,104 @@
+import { keepPreviousData, useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'
+import { api } from './client'
+import { usePagedList, type ListOptions, type Track } from './catalog'
+import type { Playlist } from './playlists'
+import { refresh as refreshPlaylists } from './playlists'
+import type { components } from './schema'
+
+export type SmartPlaylist = components['schemas']['SmartPlaylist']
+export type SmartRules = components['schemas']['SmartRules']
+export type SmartSort = components['schemas']['SmartSort']
+
+export const SORTS: readonly SmartSort[] = ['random', 'most_played', 'least_played', 'recently_added', 'title']
+export const DEFAULT_LIMIT = 50
+export const MAX_LIMIT = 500
+
+/** What makes a smart playlist, or the preview of one. */
+export interface SmartInput {
+ rules: SmartRules
+ sort: SmartSort
+ limit: number
+}
+
+/** Your smart playlists, the one changed last first. */
+export function useSmartPlaylists(opts: ListOptions = {}) {
+ return usePagedList
{t(existing ? 'smart.editor.titleEdit' : 'smart.editor.titleNew')}
+ {t('smart.editor.preview')}
+ {preview.isError ? (
+
+ {tracks.slice(0, 8).map((track, i) => (
+
+ {tracks.length > 8 &&
+ {genres.map((g) => (
+
+ )}
+ {p.name}
+ {p.description &&
+ {describeRules(t, p.rules).map((line) => (
+
+ {query.data && {t('nav.smartPlaylists')}
+
+
+ {items.map((p) => (
+
+