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 `` 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('/smart-playlists', {}, opts) +} + +export function useSmartPlaylist(id: number | null) { + return useQuery({ + queryKey: ['smart', id], + queryFn: () => api.get(`/smart-playlists/${id}`), + enabled: id !== null, + }) +} + +/** The songs of a smart playlist now. The songs on screen stay until the next ones arrive. */ +export function useSmartTracks(id: number, variant: number) { + return useQuery({ + queryKey: ['smart-tracks', id, variant], + queryFn: () => api.get<{ variant: number; tracks: Track[] }>(`/smart-playlists/${id}/tracks`, variant > 0 ? { variant } : undefined), + placeholderData: keepPreviousData, + }) +} + +/** The songs that rules give, without keeping them. It asks again when the rules change. */ +export function useSmartPreview(input: SmartInput) { + return useQuery({ + queryKey: ['smart-preview', input], + queryFn: () => api.post<{ variant: number; tracks: Track[] }>('/smart-playlists/preview', input), + placeholderData: keepPreviousData, + }) +} + +/** The genres of the library with their songs, the biggest first. */ +export function useGenres() { + return useQuery({ + queryKey: ['genres'], + queryFn: () => api.get<{ items: { name: string; tracks: number }[] }>('/genres').then((r) => r.items), + staleTime: 5 * 60_000, + }) +} + +function refresh(client: QueryClient) { + return client.invalidateQueries({ + predicate: (query) => { + const key = query.queryKey[0] + return typeof key === 'string' && (key.startsWith('/smart-playlists') || key === 'smart' || key === 'smart-tracks') + }, + }) +} + +export function useCreateSmart() { + const client = useQueryClient() + return useMutation({ + mutationFn: (body: SmartInput & { name: string; description: string }) => api.post('/smart-playlists', body), + onSuccess: () => refresh(client), + }) +} + +export function useUpdateSmart() { + const client = useQueryClient() + return useMutation({ + mutationFn: ({ id, ...body }: Partial & { id: number; name?: string; description?: string }) => + api.patch(`/smart-playlists/${id}`, body), + onSuccess: () => refresh(client), + }) +} + +export function useDeleteSmart() { + const client = useQueryClient() + return useMutation({ + mutationFn: (id: number) => api.del(`/smart-playlists/${id}`), + onSuccess: () => refresh(client), + }) +} + +/** Keeps the songs on screen as a normal playlist of mine. */ +export function useSaveSmart() { + const client = useQueryClient() + return useMutation({ + mutationFn: ({ id, ...body }: { id: number; name: string; variant: number }) => api.post(`/smart-playlists/${id}/playlist`, body), + onSuccess: () => refreshPlaylists(client), + }) +} diff --git a/web/src/components/layout/Sidebar.tsx b/web/src/components/layout/Sidebar.tsx index 0bbbbe7..919a7c1 100644 --- a/web/src/components/layout/Sidebar.tsx +++ b/web/src/components/layout/Sidebar.tsx @@ -12,6 +12,7 @@ const LINKS = [ { to: '/songs', key: 'nav.songs', end: false, adminOnly: false }, { to: '/mixes', key: 'nav.mixes', end: false, adminOnly: false }, { to: '/playlists', key: 'nav.playlists', end: false, adminOnly: false }, + { to: '/smart-playlists', key: 'nav.smartPlaylists', end: false, adminOnly: false }, { to: '/admin', key: 'nav.admin', end: false, adminOnly: true }, { to: '/settings', key: 'nav.settings', end: false, adminOnly: false }, ] diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 85b3bb9..bedd3c4 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -13,6 +13,7 @@ "songs": "Songs", "mixes": "Mixes", "playlists": "Playlists", + "smartPlaylists": "Smart playlists", "admin": "Admin", "settings": "Settings" }, @@ -526,7 +527,9 @@ "track_not_found": "This song no longer exists.", "invalid_position": "That place no longer exists. Reload the playlist.", "mix_not_found": "This mix is not available now.", - "mix_empty": "This mix has no songs to keep." + "mix_empty": "This mix has no songs to keep.", + "smart_playlist_not_found": "This smart playlist does not exist.", + "smart_playlist_empty": "These rules give no songs to keep." }, "playlists": { "empty": "You have no playlists yet. Make one below, or put a song in a new one with the playlist button next to it.", @@ -575,5 +578,103 @@ "save": "Save as playlist", "saved": "Saved as “{{name}}”.", "open": "Open the playlist" + }, + "smart": { + "empty": "You have no smart playlists yet. A smart playlist is a set of rules, like “rock I have never played”, and its songs change by themselves.", + "new": "New smart playlist", + "meta_one": "{{sort}} · up to {{count}} song", + "meta_other": "{{sort}} · up to {{count}} songs", + "notFound": "This smart playlist does not exist.", + "rulesTitle": "Rules", + "edit": "Edit", + "delete": "Delete", + "deleteTitle": "Delete {{name}}?", + "deleteBody": "The smart playlist is deleted. Playlists you made from it stay.", + "deleteConfirm": "Delete", + "shuffle": "Shuffle again", + "save": "Save as playlist", + "saved": "Saved as “{{name}}”.", + "open": "Open the playlist", + "noSongs": "No song meets these rules now.", + "songs_one": "{{count}} song · {{duration}}", + "songs_other": "{{count}} songs · {{duration}}", + "sort": { + "random": "Random", + "most_played": "Most played", + "least_played": "Least played", + "recently_added": "Recently added", + "title": "By title" + }, + "rule": { + "none": "No rules: every song", + "genres": "Genres: {{list}}", + "notGenres": "Not these genres: {{list}}", + "artists_one": "Only {{count}} chosen artist", + "artists_other": "Only {{count}} chosen artists", + "notArtists_one": "Without {{count}} chosen artist", + "notArtists_other": "Without {{count}} chosen artists", + "albums_one": "Only {{count}} chosen album", + "albums_other": "Only {{count}} chosen albums", + "notAlbums_one": "Without {{count}} chosen album", + "notAlbums_other": "Without {{count}} chosen albums", + "formats": "Formats: {{list}}", + "minBitrate": "At least {{kbps}} kbps", + "added_one": "Added in the last {{count}} day", + "added_other": "Added in the last {{count}} days", + "neverPlayed": "Never played", + "played_one": "Played in the last {{count}} day", + "played_other": "Played in the last {{count}} days", + "notPlayed_one": "Not played for {{count}} day", + "notPlayed_other": "Not played for {{count}} days", + "minPlays_one": "Played at least {{count}} time", + "minPlays_other": "Played at least {{count}} times", + "skipped_one": "Skipped in the last {{count}} day", + "skipped_other": "Skipped in the last {{count}} days", + "notSkipped_one": "Not skipped in the last {{count}} day", + "notSkipped_other": "Not skipped in the last {{count}} days", + "liked": "Only artists I like", + "noAvoided": "Without artists I avoid", + "minLength": "At least {{minutes}} min long", + "maxLength": "At most {{minutes}} min long" + }, + "editor": { + "titleNew": "New smart playlist", + "titleEdit": "Edit smart playlist", + "name": "Name", + "description": "Description", + "genres": "Genres", + "genresHint": "Songs with any of these genres. Type one and press Enter.", + "notGenres": "Leave out genres", + "addGenre": "Add genre", + "removeGenre": "Remove {{genre}}", + "format": "File format", + "formatAny": "Any", + "formatFlac": "FLAC", + "formatMp3": "MP3", + "formatKept": "Other (kept)", + "minBitrate": "Minimum bitrate (kbps)", + "added": "Added in the last (days)", + "listening": "My listening", + "neverPlayed": "Never played", + "played": "Played in the last (days)", + "notPlayed": "Not played for (days)", + "minPlays": "Played at least (times)", + "notSkipped": "Not skipped in the last (days)", + "taste": "My taste", + "liked": "Only artists I like", + "noAvoided": "Leave out artists I avoid", + "length": "Length of the song", + "minMinutes": "At least (minutes)", + "maxMinutes": "At most (minutes)", + "order": "Order", + "limit": "Most songs", + "preview": "Preview", + "previewCount": "{{count}} songs · {{duration}}", + "previewMore": "and {{count}} more", + "previewNone": "No song meets these rules.", + "save": "Save", + "cancel": "Cancel", + "blank": "Leave a number blank for no rule." + } } } diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index cd9c39e..cbbcc16 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -13,6 +13,7 @@ "songs": "Brani", "mixes": "Mix", "playlists": "Playlist", + "smartPlaylists": "Playlist smart", "admin": "Admin", "settings": "Impostazioni" }, @@ -526,7 +527,9 @@ "track_not_found": "Questo brano non esiste più.", "invalid_position": "Quel posto non esiste più. Ricarica la playlist.", "mix_not_found": "Questo mix ora non è disponibile.", - "mix_empty": "Questo mix non ha brani da salvare." + "mix_empty": "Questo mix non ha brani da salvare.", + "smart_playlist_not_found": "Questa playlist smart non esiste.", + "smart_playlist_empty": "Queste regole non danno brani da salvare." }, "playlists": { "empty": "Non hai ancora nessuna playlist. Creane una qui sotto, oppure metti un brano in una nuova con il pulsante accanto al brano.", @@ -575,5 +578,103 @@ "save": "Salva come playlist", "saved": "Salvato come “{{name}}”.", "open": "Apri la playlist" + }, + "smart": { + "empty": "Non hai ancora playlist smart. Una playlist smart è un insieme di regole, come «rock che non ho mai ascoltato», e i suoi brani cambiano da soli.", + "new": "Nuova playlist smart", + "meta_one": "{{sort}} · fino a {{count}} brano", + "meta_other": "{{sort}} · fino a {{count}} brani", + "notFound": "Questa playlist smart non esiste.", + "rulesTitle": "Regole", + "edit": "Modifica", + "delete": "Elimina", + "deleteTitle": "Eliminare {{name}}?", + "deleteBody": "La playlist smart viene eliminata. Le playlist che hai fatto da essa restano.", + "deleteConfirm": "Elimina", + "shuffle": "Rimescola", + "save": "Salva come playlist", + "saved": "Salvata come «{{name}}».", + "open": "Apri la playlist", + "noSongs": "Ora nessun brano rispetta queste regole.", + "songs_one": "{{count}} brano · {{duration}}", + "songs_other": "{{count}} brani · {{duration}}", + "sort": { + "random": "Casuale", + "most_played": "Più ascoltati", + "least_played": "Meno ascoltati", + "recently_added": "Aggiunti da poco", + "title": "Per titolo" + }, + "rule": { + "none": "Nessuna regola: tutti i brani", + "genres": "Generi: {{list}}", + "notGenres": "Senza questi generi: {{list}}", + "artists_one": "Solo {{count}} artista scelto", + "artists_other": "Solo {{count}} artisti scelti", + "notArtists_one": "Senza {{count}} artista scelto", + "notArtists_other": "Senza {{count}} artisti scelti", + "albums_one": "Solo {{count}} album scelto", + "albums_other": "Solo {{count}} album scelti", + "notAlbums_one": "Senza {{count}} album scelto", + "notAlbums_other": "Senza {{count}} album scelti", + "formats": "Formati: {{list}}", + "minBitrate": "Almeno {{kbps}} kbps", + "added_one": "Aggiunti nell'ultimo giorno", + "added_other": "Aggiunti negli ultimi {{count}} giorni", + "neverPlayed": "Mai ascoltati", + "played_one": "Ascoltati nell'ultimo giorno", + "played_other": "Ascoltati negli ultimi {{count}} giorni", + "notPlayed_one": "Non ascoltati da {{count}} giorno", + "notPlayed_other": "Non ascoltati da {{count}} giorni", + "minPlays_one": "Ascoltati almeno {{count}} volta", + "minPlays_other": "Ascoltati almeno {{count}} volte", + "skipped_one": "Saltati nell'ultimo giorno", + "skipped_other": "Saltati negli ultimi {{count}} giorni", + "notSkipped_one": "Non saltati nell'ultimo giorno", + "notSkipped_other": "Non saltati negli ultimi {{count}} giorni", + "liked": "Solo artisti che amo", + "noAvoided": "Senza artisti che evito", + "minLength": "Lunghi almeno {{minutes}} min", + "maxLength": "Lunghi al massimo {{minutes}} min" + }, + "editor": { + "titleNew": "Nuova playlist smart", + "titleEdit": "Modifica playlist smart", + "name": "Nome", + "description": "Descrizione", + "genres": "Generi", + "genresHint": "Brani con uno qualsiasi di questi generi. Scrivine uno e premi Invio.", + "notGenres": "Escludi generi", + "addGenre": "Aggiungi genere", + "removeGenre": "Togli {{genre}}", + "format": "Formato del file", + "formatAny": "Qualsiasi", + "formatFlac": "FLAC", + "formatMp3": "MP3", + "formatKept": "Altro (mantenuto)", + "minBitrate": "Bitrate minimo (kbps)", + "added": "Aggiunti negli ultimi (giorni)", + "listening": "Quello che ascolto", + "neverPlayed": "Mai ascoltati", + "played": "Ascoltati negli ultimi (giorni)", + "notPlayed": "Non ascoltati da (giorni)", + "minPlays": "Ascoltati almeno (volte)", + "notSkipped": "Non saltati negli ultimi (giorni)", + "taste": "I miei gusti", + "liked": "Solo artisti che amo", + "noAvoided": "Escludi artisti che evito", + "length": "Durata del brano", + "minMinutes": "Almeno (minuti)", + "maxMinutes": "Al massimo (minuti)", + "order": "Ordine", + "limit": "Massimo di brani", + "preview": "Anteprima", + "previewCount": "{{count}} brani · {{duration}}", + "previewMore": "e altri {{count}}", + "previewNone": "Nessun brano rispetta queste regole.", + "save": "Salva", + "cancel": "Annulla", + "blank": "Lascia vuoto un numero per nessuna regola." + } } } diff --git a/web/src/pages/SmartEditorPage.tsx b/web/src/pages/SmartEditorPage.tsx new file mode 100644 index 0000000..48d6544 --- /dev/null +++ b/web/src/pages/SmartEditorPage.tsx @@ -0,0 +1,295 @@ +import { X } from 'lucide-react' +import { useEffect, useId, useMemo, useState, type FormEvent } from 'react' +import { useTranslation } from 'react-i18next' +import { Link, useNavigate, useParams } from 'react-router-dom' +import { ApiError } from '@/api/client' +import { + DEFAULT_LIMIT, + MAX_LIMIT, + SORTS, + useCreateSmart, + useGenres, + useSmartPlaylist, + useSmartPreview, + useUpdateSmart, + type SmartPlaylist, + type SmartSort, +} from '@/api/smart' +import ChoiceGroup from '@/components/ChoiceGroup' +import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status' +import { Button, buttonVariants } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { errorMessageKey } from '@/i18n' +import { formatTime } from '@/lib/time' +import { cn } from '@/lib/utils' +import { EMPTY_FORM, formFromRules, rulesFromForm, type RuleForm } from './smartRules' + +/** The editor of a new smart playlist, or of one that exists (`/smart-playlists/:id/edit`). */ +export default function SmartEditorPage() { + const { t } = useTranslation() + const param = useParams().id + const id = param === undefined ? null : Number(param) + const existing = useSmartPlaylist(id !== null && Number.isInteger(id) && id > 0 ? id : null) + + if (id === null) return + if (!Number.isInteger(id) || id < 1) return {t('smart.notFound')} + if (existing.isError) { + if (existing.error instanceof ApiError && existing.error.status === 404) return {t('smart.notFound')} + return existing.refetch()} /> + } + if (!existing.data) return + return +} + +/** `value` once it has stopped changing for `ms`. */ +function useDebounced(value: T, ms: number): T { + const [out, setOut] = useState(value) + const key = JSON.stringify(value) + useEffect(() => { + const timer = setTimeout(() => setOut(value), ms) + return () => clearTimeout(timer) + // The text of the value is the dependency: a new object with the same content is no change. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key, ms]) + return out +} + +function errorLine(t: (key: string) => string, error: unknown) { + return t(errorMessageKey(error instanceof ApiError ? error.code : 'unknown')) +} + +function SmartEditor({ existing }: { existing: SmartPlaylist | null }) { + const { t } = useTranslation() + const navigate = useNavigate() + const create = useCreateSmart() + const update = useUpdateSmart() + const [name, setName] = useState(existing?.name ?? '') + const [description, setDescription] = useState(existing?.description ?? '') + const [form, setForm] = useState(existing ? formFromRules(existing.rules) : EMPTY_FORM) + const [sort, setSort] = useState(existing?.sort ?? 'random') + const [limitText, setLimitText] = useState(String(existing?.limit ?? DEFAULT_LIMIT)) + + const set = (key: K, value: RuleForm[K]) => setForm((f) => ({ ...f, [key]: value })) + const rules = useMemo(() => rulesFromForm(form, existing?.rules), [form, existing]) + const limit = Math.min(MAX_LIMIT, Math.max(1, Math.floor(Number(limitText)) || DEFAULT_LIMIT)) + const input = useDebounced({ rules, sort, limit }, 500) + const preview = useSmartPreview(input) + const ready = name.trim() !== '' + const pending = create.isPending || update.isPending + const failure = create.error ?? update.error + + function submit(event: FormEvent) { + event.preventDefault() + if (!ready || pending) return + const body = { name: name.trim(), description: description.trim(), rules, sort, limit } + if (existing) update.mutate({ id: existing.id, ...body }, { onSuccess: () => navigate(`/smart-playlists/${existing.id}`) }) + else create.mutate(body, { onSuccess: (p) => navigate(`/smart-playlists/${p.id}`) }) + } + + const tracks = preview.data?.tracks ?? [] + const duration = tracks.reduce((sum, track) => sum + track.duration_ms, 0) + + return ( +
+

{t(existing ? 'smart.editor.titleEdit' : 'smart.editor.titleNew')}

+
+
+
+ + setName(e.target.value)} /> +
+
+ + setDescription(e.target.value)} /> +
+ + set('genres', g)} /> + set('notGenres', g)} /> + + set('format', v)} + choices={[ + { value: 'any', label: t('smart.editor.formatAny') }, + { value: 'flac', label: t('smart.editor.formatFlac') }, + { value: 'mpeg', label: t('smart.editor.formatMp3') }, + ...(form.format === 'kept' ? [{ value: 'kept' as const, label: t('smart.editor.formatKept') }] : []), + ]} + /> +
+ set('minBitrate', v)} /> + set('addedDays', v)} /> +
+ +
+ {t('smart.editor.listening')} + set('neverPlayed', v)} /> +
+ set('playedDays', v)} /> + set('notPlayedDays', v)} /> + set('minPlays', v)} /> + set('notSkippedDays', v)} /> +
+
+ +
+ {t('smart.editor.taste')} + set('likedOnly', v)} /> + set('noAvoided', v)} /> +
+ +
+ {t('smart.editor.length')} +
+ set('minMinutes', v)} /> + set('maxMinutes', v)} /> +
+
+

{t('smart.editor.blank')}

+ + + label={t('smart.editor.order')} + value={sort} + onChange={setSort} + choices={SORTS.map((s) => ({ value: s, label: t(`smart.sort.${s}`) }))} + /> +
+ +
+ + {failure && ( +

+ {errorLine(t, failure)} +

+ )} +
+ + + {t('smart.editor.cancel')} + +
+ + +
+

{t('smart.editor.preview')}

+ {preview.isError ? ( +

+ {errorLine(t, preview.error)} +

+ ) : preview.isPending ? ( + + ) : tracks.length === 0 ? ( +

{t('smart.editor.previewNone')}

+ ) : ( + <> +

{t('smart.editor.previewCount', { count: tracks.length, duration: formatTime(duration) })}

+
    + {tracks.slice(0, 8).map((track, i) => ( +
  1. + {track.title} + {track.artists.map((a) => a.name).join(', ')} +
  2. + ))} +
+ {tracks.length > 8 &&

{t('smart.editor.previewMore', { count: tracks.length - 8 })}

} + + )} +
+
+
+ ) +} + +function NumberField({ + label, value, onChange, min = 0, max, step = '1', +}: { + label: string + value: string + onChange: (value: string) => void + min?: number + max?: number + step?: string +}) { + const id = useId() + return ( +
+ + onChange(e.target.value)} /> +
+ ) +} + +function Check({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) { + return ( + + ) +} + +/** Genres as chips. A name is added with Enter, a comma or the button; the library's genres are offered while typing. */ +function GenreField({ label, hint, genres, onChange }: { label: string; hint?: string; genres: string[]; onChange: (genres: string[]) => void }) { + const { t } = useTranslation() + const id = useId() + const known = useGenres() + const [text, setText] = useState('') + + function add() { + const g = text.trim().toLowerCase().replace(/\s+/g, ' ') + setText('') + if (g && !genres.includes(g)) onChange([...genres, g]) + } + + return ( +
+ + {hint &&

{hint}

} + {genres.length > 0 && ( +
    + {genres.map((g) => ( +
  • + {g} + +
  • + ))} +
+ )} +
+ { + const v = e.target.value + if (v.endsWith(',')) { + setText(v.slice(0, -1)) + queueMicrotask(add) + } else setText(v) + }} + onKeyDown={(e) => { + if (e.key === 'Enter') { + e.preventDefault() + add() + } + }} + /> + + {(known.data ?? []).slice(0, 150).map((g) => ( + + +
+
+ ) +} diff --git a/web/src/pages/SmartPlaylistPage.tsx b/web/src/pages/SmartPlaylistPage.tsx new file mode 100644 index 0000000..c707eab --- /dev/null +++ b/web/src/pages/SmartPlaylistPage.tsx @@ -0,0 +1,142 @@ +import { ListPlus, Pencil, Play, Shuffle, Trash2 } from 'lucide-react' +import { useState } from 'react' +import { useTranslation } from 'react-i18next' +import { Link, useNavigate, useParams } from 'react-router-dom' +import { ApiError } from '@/api/client' +import { useDeleteSmart, useSaveSmart, useSmartPlaylist, useSmartTracks } from '@/api/smart' +import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status' +import TrackList from '@/components/TrackList' +import { Button, buttonVariants } from '@/components/ui/button' +import { errorMessageKey } from '@/i18n' +import { cn } from '@/lib/utils' +import { formatTime } from '@/lib/time' +import { usePlayer } from '@/player/store' +import Confirm from '@/pages/admin/Confirm' +import { describeRules } from './smartRules' + +export default function SmartPlaylistPage() { + const { t } = useTranslation() + const id = Number(useParams().id) + if (!Number.isInteger(id) || id < 1) return {t('smart.notFound')} + return +} + +function errorLine(t: (key: string) => string, error: unknown) { + return t(errorMessageKey(error instanceof ApiError ? error.code : 'unknown')) +} + +function SmartView({ id }: { id: number }) { + const { t } = useTranslation() + const navigate = useNavigate() + const [variant, setVariant] = useState(0) + const [deleting, setDeleting] = useState(false) + const playlist = useSmartPlaylist(id) + const query = useSmartTracks(id, variant) + const save = useSaveSmart() + const del = useDeleteSmart() + const playTracks = usePlayer((s) => s.playTracks) + + if (playlist.isError) { + if (playlist.error instanceof ApiError && playlist.error.status === 404) return {t('smart.notFound')} + return playlist.refetch()} /> + } + if (!playlist.data) return + const p = playlist.data + const tracks = query.data?.tracks ?? [] + const shown = query.data?.variant ?? 0 + // The songs on screen are still the old ones while the next come: nothing is kept or shuffled then. + const waiting = query.isPlaceholderData + const duration = tracks.reduce((sum, track) => sum + track.duration_ms, 0) + + return ( +
+
+

{p.name}

+ {p.description &&

{p.description}

} +
    + {describeRules(t, p.rules).map((line) => ( +
  • + {line} +
  • + ))} +
  • {t(`smart.sort.${p.sort}`)}
  • +
+ {query.data &&

{t('smart.songs', { count: tracks.length, duration: formatTime(duration) })}

} +
+ + {p.sort === 'random' && ( + + )} + + + + {t('smart.edit')} + + +
+
+ + {save.isSuccess && ( +

+ {t('smart.saved', { name: save.data.name })} + + {t('smart.open')} + +

+ )} + {(save.isError || del.isError) && ( +

+ {errorLine(t, save.error ?? del.error)} +

+ )} + + {query.isError ? ( + query.refetch()} /> + ) : query.isPending ? ( + + ) : tracks.length === 0 ? ( + {t('smart.noSongs')} + ) : ( + + )} + + {deleting && ( + setDeleting(false)} + onConfirm={() => { + setDeleting(false) + del.mutate(id, { onSuccess: () => navigate('/smart-playlists') }) + }} + /> + )} +
+ ) +} diff --git a/web/src/pages/SmartPlaylistsPage.tsx b/web/src/pages/SmartPlaylistsPage.tsx new file mode 100644 index 0000000..053eff9 --- /dev/null +++ b/web/src/pages/SmartPlaylistsPage.tsx @@ -0,0 +1,51 @@ +import { Plus } from 'lucide-react' +import { useTranslation } from 'react-i18next' +import { Link } from 'react-router-dom' +import { useSmartPlaylists } from '@/api/smart' +import LoadMore from '@/components/LoadMore' +import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status' +import { buttonVariants } from '@/components/ui/button' +import { cn } from '@/lib/utils' + +/** Your smart playlists: playlists that are a set of rules, worked out every time they are opened. */ +export default function SmartPlaylistsPage() { + const { t } = useTranslation() + const query = useSmartPlaylists() + const items = query.data?.items ?? [] + + return ( +
+
+

{t('nav.smartPlaylists')}

+ + + {t('smart.new')} + +
+ + {query.isError ? ( + query.refetch()} /> + ) : query.isPending ? ( + + ) : items.length === 0 ? ( + {t('smart.empty')} + ) : ( + <> +
    + {items.map((p) => ( +
  • + + {p.name} + + {t('smart.meta', { count: p.limit, sort: t(`smart.sort.${p.sort}`) })} + + +
  • + ))} +
+ + + )} +
+ ) +} diff --git a/web/src/pages/smart.test.tsx b/web/src/pages/smart.test.tsx new file mode 100644 index 0000000..c0510d9 --- /dev/null +++ b/web/src/pages/smart.test.tsx @@ -0,0 +1,360 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, Route, Routes } from 'react-router-dom' +import { beforeEach, expect, test, vi } from 'vitest' +import { sessionStore } from '@/auth/session' +import { initI18n } from '@/i18n' +import { usePlayer } from '@/player/store' +import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch' +import SmartEditorPage from './SmartEditorPage' +import SmartPlaylistPage from './SmartPlaylistPage' +import SmartPlaylistsPage from './SmartPlaylistsPage' +import { describeRules, formFromRules, rulesFromForm } from './smartRules' + +// --- fixtures --------------------------------------------------------------------------------- + +function track(n: number) { + return { + id: n, + title: `Song ${n}`, + duration_ms: 200_000, + track_no: n, + disc_no: 1, + album: { id: 9, title: 'OK Computer' }, + artists: [{ id: 5, name: 'Radiohead' }], + format: 'flac', + } +} + +function smart(id: number, name: string, over: object = {}) { + return { + id, + name, + description: '', + rules: { genres: ['rock'], never_played: true }, + sort: 'random', + limit: 50, + created_at: '2026-11-01T10:00:00Z', + updated_at: '2026-11-02T10:00:00Z', + ...over, + } +} + +const page = (items: object[]) => ({ items, total: items.length, limit: 50, offset: 0 }) +const tracks = (variant: number, ...ns: number[]) => ({ variant, tracks: ns.map(track) }) + +function renderApp(path: string) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return render( + + + + } /> + } /> + } /> + } /> + THE PLAYLIST PAGE

} /> +
+
+
, + ) +} + +const json = (status: number, body: object) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) +const body = (c: RecordedCall) => JSON.parse(c.init.body as string) + +beforeEach(async () => { + vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') + await initI18n() + sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: false } }) + usePlayer.setState({ queue: [], original: [], index: 0, playing: false, positionMs: 0, shuffle: false, repeat: 'off', seekMs: null, seekId: 0, playId: 0 }) +}) + +// --- the rules, as the editor holds them --------------------------------------------------------- + +test('rules go into the form and come back unchanged, keeping what the form has no field for', () => { + const rules = { + genres: ['rock', 'metal'], not_genres: ['pop'], artist_ids: [3, 4], not_album_ids: [7], formats: ['flac'], min_bitrate_kbps: 900, + added_within_days: 30, never_played: true, played_within_days: 7, not_played_within_days: 60, min_plays: 2, + skipped_within_days: 5, not_skipped_within_days: 14, liked_artists_only: true, without_avoided_artists: true, + min_duration_sec: 90, max_duration_sec: 600, + } + expect(rulesFromForm(formFromRules(rules), rules)).toEqual(rules) +}) + +test('a blank field is no rule, and what the form cannot show survives a change', () => { + const base = { artist_ids: [3], formats: ['ogg', 'opus'], skipped_within_days: 2, min_plays: 5 } + const form = { ...formFromRules(base), minPlays: '', addedDays: ' 12 ' } + expect(formFromRules(base).format).toBe('kept') + expect(rulesFromForm(form, base)).toEqual({ artist_ids: [3], formats: ['ogg', 'opus'], skipped_within_days: 2, added_within_days: 12 }) + expect(rulesFromForm({ ...form, format: 'mpeg' }, base).formats).toEqual(['mpeg']) + expect(rulesFromForm({ ...form, addedDays: '-3' }, {})).toEqual({}) +}) + +test('the rules are described in words, and no rule says so', async () => { + const { default: i18n } = await import('i18next') + const t = i18n.t.bind(i18n) + expect(describeRules(t, {})).toEqual(['No rules: every song']) + expect(describeRules(t, { genres: ['rock'], added_within_days: 1, min_plays: 3, min_duration_sec: 90, liked_artists_only: true })).toEqual([ + 'Genres: rock', + 'Added in the last 1 day', + 'Played at least 3 times', + 'Only artists I like', + 'At least 1.5 min long', + ]) +}) + +// --- the list --------------------------------------------------------------------------------- + +test('the list shows each smart playlist with its order and limit, and a way to make one', async () => { + mockFetch({ 'GET /api/v1/smart-playlists': () => page([smart(3, 'Fresh rock'), smart(4, 'Long ones', { sort: 'most_played', limit: 1 })]) }) + renderApp('/smart-playlists') + const link = await screen.findByRole('link', { name: /Fresh rock/ }) + expect(link).toHaveAttribute('href', '/smart-playlists/3') + expect(link).toHaveTextContent('Random · up to 50 songs') + expect(screen.getByRole('link', { name: /Long ones/ })).toHaveTextContent('Most played · up to 1 song') + expect(screen.getByRole('link', { name: 'New smart playlist' })).toHaveAttribute('href', '/smart-playlists/new') +}) + +test('with none the page explains what a smart playlist is', async () => { + mockFetch({ 'GET /api/v1/smart-playlists': () => page([]) }) + renderApp('/smart-playlists') + expect(await screen.findByText(/no smart playlists yet/i)).toBeInTheDocument() + expect(screen.getByRole('link', { name: 'New smart playlist' })).toBeInTheDocument() +}) + +// --- one smart playlist --------------------------------------------------------------------------- + +function one(over: MockRoutes = {}, p = smart(3, 'Fresh rock', { description: 'new things' })): MockRoutes { + return { + 'GET /api/v1/smart-playlists/3': () => p, + 'GET /api/v1/smart-playlists/3/tracks': () => tracks(0, 1, 2, 3), + ...over, + } +} + +test('a smart playlist shows its name, its rules in words and its songs', async () => { + mockFetch(one()) + renderApp('/smart-playlists/3') + expect(await screen.findByRole('heading', { level: 1, name: 'Fresh rock' })).toBeInTheDocument() + expect(screen.getByText('new things')).toBeInTheDocument() + const rules = screen.getByRole('list', { name: 'Rules' }) + expect(within(rules).getByText('Genres: rock')).toBeInTheDocument() + expect(within(rules).getByText('Never played')).toBeInTheDocument() + expect(within(rules).getByText('Random')).toBeInTheDocument() + expect(await screen.findByRole('button', { name: /Song 1/ })).toBeInTheDocument() + expect(screen.getByText(/3 songs/)).toBeInTheDocument() + expect(screen.getByRole('link', { name: 'Edit' })).toHaveAttribute('href', '/smart-playlists/3/edit') +}) + +test('Play starts the songs from the first', async () => { + mockFetch(one()) + renderApp('/smart-playlists/3') + await userEvent.click(await screen.findByRole('button', { name: 'Play' })) + expect(usePlayer.getState().queue.map((t) => t.id)).toEqual([1, 2, 3]) +}) + +test('Shuffle again asks for the next variant, and only a random order has it', async () => { + const { calls } = mockFetch( + one({ + 'GET /api/v1/smart-playlists/3/tracks': ({ url }) => { + const variant = Number(url.searchParams.get('variant') ?? 0) + return tracks(variant, 10 * variant + 1, 10 * variant + 2) + }, + }), + ) + renderApp('/smart-playlists/3') + await screen.findByRole('button', { name: /Song 1(?!\d)/ }) + await userEvent.click(screen.getByRole('button', { name: 'Shuffle again' })) + expect(await screen.findByRole('button', { name: /Song 11/ })).toBeInTheDocument() + expect(calls.filter((c) => c.key.endsWith('/tracks')).map((c) => c.url.searchParams.get('variant'))).toEqual([null, '1']) +}) + +test('an order that is not random has no Shuffle again', async () => { + mockFetch(one({}, smart(3, 'Top', { sort: 'most_played' }))) + renderApp('/smart-playlists/3') + await screen.findByRole('button', { name: 'Play' }) + expect(screen.queryByRole('button', { name: 'Shuffle again' })).not.toBeInTheDocument() +}) + +test('Save as playlist keeps the variant on screen under the name, and links to the playlist', async () => { + let saved: unknown + mockFetch( + one({ + 'GET /api/v1/smart-playlists/3/tracks': ({ url }) => tracks(Number(url.searchParams.get('variant') ?? 0), 1, 2), + 'POST /api/v1/smart-playlists/3/playlist': ({ init }) => { + saved = JSON.parse(init.body as string) + return json(201, { id: 42, name: 'Fresh rock', description: '', track_count: 2, duration_ms: 400_000, created_at: '2026-11-12T10:00:00Z', updated_at: '2026-11-12T10:00:00Z' }) + }, + }), + ) + renderApp('/smart-playlists/3') + await userEvent.click(await screen.findByRole('button', { name: 'Shuffle again' })) + await waitFor(() => expect(screen.getByRole('button', { name: 'Save as playlist' })).toBeEnabled()) + await userEvent.click(screen.getByRole('button', { name: 'Save as playlist' })) + const status = await screen.findByRole('status') + expect(status).toHaveTextContent('Saved as “Fresh rock”') + expect(saved).toEqual({ name: 'Fresh rock', variant: 1 }) + await userEvent.click(within(status).getByRole('link', { name: 'Open the playlist' })) + expect(await screen.findByText('THE PLAYLIST PAGE')).toBeInTheDocument() +}) + +test('rules that give no songs say so and cannot be played or kept; a refused save says why', async () => { + mockFetch(one({ 'GET /api/v1/smart-playlists/3/tracks': () => tracks(0), 'POST /api/v1/smart-playlists/3/playlist': () => apiError(422, 'smart_playlist_empty') })) + renderApp('/smart-playlists/3') + expect(await screen.findByText(/No song meets these rules now/)).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Play' })).toBeDisabled() + expect(screen.getByRole('button', { name: 'Save as playlist' })).toBeDisabled() +}) + +test('a smart playlist is deleted after asking, and the page goes back to the list', async () => { + const { calls } = mockFetch(one({ 'DELETE /api/v1/smart-playlists/3': () => new Response(null, { status: 204 }), 'GET /api/v1/smart-playlists': () => page([]) })) + renderApp('/smart-playlists/3') + await userEvent.click(await screen.findByRole('button', { name: 'Delete' })) + const dialog = await screen.findByRole('alertdialog').catch(() => screen.findByRole('dialog')) + expect(within(dialog).getByText(/Delete Fresh rock\?/)).toBeInTheDocument() + expect(calls.some((c) => c.key === 'DELETE /api/v1/smart-playlists/3')).toBe(false) + await userEvent.click(within(dialog).getByRole('button', { name: 'Delete' })) + expect(await screen.findByText(/no smart playlists yet/i)).toBeInTheDocument() + expect(calls.some((c) => c.key === 'DELETE /api/v1/smart-playlists/3')).toBe(true) +}) + +test('a smart playlist that does not exist says so', async () => { + mockFetch({ 'GET /api/v1/smart-playlists/3': () => apiError(404, 'smart_playlist_not_found'), 'GET /api/v1/smart-playlists/3/tracks': () => apiError(404, 'smart_playlist_not_found') }) + renderApp('/smart-playlists/3') + expect(await screen.findByText('This smart playlist does not exist.')).toBeInTheDocument() +}) + +// --- the editor --------------------------------------------------------------------------------- + +const previewCalls = (calls: RecordedCall[]) => calls.filter((c) => c.key === 'POST /api/v1/smart-playlists/preview') + +function editorRoutes(over: MockRoutes = {}): MockRoutes { + return { + 'GET /api/v1/genres': () => ({ items: [{ name: 'rock', tracks: 40 }, { name: 'hard rock', tracks: 36 }] }), + 'POST /api/v1/smart-playlists/preview': () => tracks(0, 1, 2, 3), + ...over, + } +} + +test('a new smart playlist is made from the rules that were set, and its page opens', async () => { + const { calls } = mockFetch( + editorRoutes({ + 'POST /api/v1/smart-playlists': () => json(201, smart(7, 'Fresh', { rules: {} })), + 'GET /api/v1/smart-playlists/7': () => smart(7, 'Fresh', { rules: {} }), + 'GET /api/v1/smart-playlists/7/tracks': () => tracks(0, 1), + }), + ) + renderApp('/smart-playlists/new') + const save = await screen.findByRole('button', { name: 'Save' }) + expect(save).toBeDisabled() // a name is needed + await userEvent.type(screen.getByRole('textbox', { name: 'Name' }), ' Fresh ') + await userEvent.type(screen.getByRole('combobox', { name: 'Genres' }), 'Rock{Enter}') + expect(screen.getByRole('button', { name: 'Remove rock' })).toBeInTheDocument() + await userEvent.type(screen.getByRole('spinbutton', { name: 'Added in the last (days)' }), '30') + await userEvent.click(screen.getByRole('radio', { name: 'FLAC' })) + await userEvent.click(screen.getByRole('checkbox', { name: 'Never played' })) + await userEvent.click(screen.getByRole('radio', { name: 'Recently added' })) + await userEvent.click(save) + + const post = calls.find((c) => c.key === 'POST /api/v1/smart-playlists')! + expect(body(post)).toEqual({ + name: 'Fresh', description: '', sort: 'recently_added', limit: 50, + rules: { genres: ['rock'], formats: ['flac'], added_within_days: 30, never_played: true }, + }) + expect(await screen.findByRole('heading', { level: 1, name: 'Fresh' })).toBeInTheDocument() +}) + +test('the preview follows the rules, a moment after they stop changing', async () => { + const { calls } = mockFetch(editorRoutes()) + renderApp('/smart-playlists/new') + expect(await screen.findByText('3 songs · 10:00')).toBeInTheDocument() + expect(body(previewCalls(calls)[0])).toEqual({ rules: {}, sort: 'random', limit: 50 }) + expect(screen.getByText('Song 1')).toBeInTheDocument() + + await userEvent.type(screen.getByRole('combobox', { name: 'Genres' }), 'hard rock,') + await waitFor(() => expect(previewCalls(calls).length).toBe(2), { timeout: 3000 }) + expect(body(previewCalls(calls)[1]).rules).toEqual({ genres: ['hard rock'] }) + // Typing in a field is one request, not one for every key. + await userEvent.type(screen.getByRole('spinbutton', { name: 'Played at least (times)' }), '12') + await waitFor(() => expect(previewCalls(calls).length).toBe(3), { timeout: 3000 }) + expect(body(previewCalls(calls)[2]).rules).toEqual({ genres: ['hard rock'], min_plays: 12 }) +}) + +test('rules that give nothing, and a preview that fails, are said in words', async () => { + mockFetch(editorRoutes({ 'POST /api/v1/smart-playlists/preview': () => tracks(0) })) + renderApp('/smart-playlists/new') + expect(await screen.findByText('No song meets these rules.')).toBeInTheDocument() +}) + +test('the length is in minutes and goes to the server in seconds', async () => { + const { calls } = mockFetch(editorRoutes()) + renderApp('/smart-playlists/new') + await userEvent.type(await screen.findByRole('spinbutton', { name: 'At least (minutes)' }), '1.5') + await userEvent.type(screen.getByRole('spinbutton', { name: 'At most (minutes)' }), '10') + await waitFor(() => expect(body(previewCalls(calls).at(-1)!).rules).toEqual({ min_duration_sec: 90, max_duration_sec: 600 }), { timeout: 3000 }) +}) + +test('editing keeps what the editor cannot show, and changes only what was changed', async () => { + const existing = smart(3, 'Fresh rock', { rules: { genres: ['rock'], artist_ids: [3, 4], formats: ['ogg'], min_plays: 5 }, sort: 'title', limit: 20 }) + const { calls } = mockFetch( + editorRoutes({ + 'GET /api/v1/smart-playlists/3': () => existing, + 'GET /api/v1/smart-playlists/3/tracks': () => tracks(0, 1), + 'PATCH /api/v1/smart-playlists/3': () => existing, + }), + ) + renderApp('/smart-playlists/3/edit') + expect(await screen.findByRole('heading', { level: 1, name: 'Edit smart playlist' })).toBeInTheDocument() + expect(screen.getByRole('textbox', { name: 'Name' })).toHaveValue('Fresh rock') + expect(screen.getByRole('button', { name: 'Remove rock' })).toBeInTheDocument() + expect(screen.getByRole('spinbutton', { name: 'Played at least (times)' })).toHaveValue(5) + expect(screen.getByRole('spinbutton', { name: 'Most songs' })).toHaveValue(20) + expect(screen.getByRole('radio', { name: 'Other (kept)' })).toBeChecked() + expect(screen.getByRole('radio', { name: 'By title' })).toBeChecked() + + await userEvent.clear(screen.getByRole('spinbutton', { name: 'Played at least (times)' })) + await userEvent.type(screen.getByRole('spinbutton', { name: 'Played at least (times)' }), '2') + await userEvent.click(screen.getByRole('button', { name: 'Save' })) + await waitFor(() => expect(calls.some((c) => c.key === 'PATCH /api/v1/smart-playlists/3')).toBe(true)) + const patch = calls.find((c) => c.key === 'PATCH /api/v1/smart-playlists/3')! + expect(body(patch)).toEqual({ + name: 'Fresh rock', description: '', sort: 'title', limit: 20, + rules: { artist_ids: [3, 4], formats: ['ogg'], genres: ['rock'], min_plays: 2 }, + }) +}) + +test('a refused save says why and keeps what was typed', async () => { + mockFetch(editorRoutes({ 'POST /api/v1/smart-playlists': () => apiError(409, 'limit_reached') })) + renderApp('/smart-playlists/new') + await userEvent.type(await screen.findByRole('textbox', { name: 'Name' }), 'One more') + await userEvent.click(screen.getByRole('button', { name: 'Save' })) + expect(await screen.findByText(/Limit reached/)).toBeInTheDocument() + expect(screen.getByRole('textbox', { name: 'Name' })).toHaveValue('One more') +}) + +test('the limit is kept between 1 and 500', async () => { + const { calls } = mockFetch(editorRoutes()) + renderApp('/smart-playlists/new') + const limit = await screen.findByRole('spinbutton', { name: 'Most songs' }) + await userEvent.clear(limit) + await userEvent.type(limit, '9999') + await waitFor(() => expect(body(previewCalls(calls).at(-1)!).limit).toBe(500), { timeout: 3000 }) +}) + +test('a genre can be taken out again, and the same one is not added twice', async () => { + mockFetch(editorRoutes()) + renderApp('/smart-playlists/new') + const input = await screen.findByRole('combobox', { name: 'Genres' }) + await userEvent.type(input, 'rock{Enter}Rock{Enter}') + expect(screen.getAllByRole('button', { name: 'Remove rock' })).toHaveLength(1) + await userEvent.click(screen.getByRole('button', { name: 'Remove rock' })) + expect(screen.queryByRole('button', { name: 'Remove rock' })).not.toBeInTheDocument() +}) + +test('a smart playlist that does not exist cannot be edited', async () => { + mockFetch(editorRoutes({ 'GET /api/v1/smart-playlists/3': () => apiError(404, 'smart_playlist_not_found') })) + renderApp('/smart-playlists/3/edit') + expect(await screen.findByText('This smart playlist does not exist.')).toBeInTheDocument() +}) diff --git a/web/src/pages/smartRules.ts b/web/src/pages/smartRules.ts new file mode 100644 index 0000000..765c2cb --- /dev/null +++ b/web/src/pages/smartRules.ts @@ -0,0 +1,121 @@ +import type { TFunction } from 'i18next' +import type { SmartRules } from '@/api/smart' + +/** The rules as the editor holds them: numbers are text, so that a blank field means "no rule". */ +export interface RuleForm { + genres: string[] + notGenres: string[] + format: 'any' | 'flac' | 'mpeg' | 'kept' + minBitrate: string + addedDays: string + neverPlayed: boolean + playedDays: string + notPlayedDays: string + minPlays: string + notSkippedDays: string + likedOnly: boolean + noAvoided: boolean + minMinutes: string + maxMinutes: string +} + +export const EMPTY_FORM: RuleForm = { + genres: [], notGenres: [], format: 'any', minBitrate: '', addedDays: '', neverPlayed: false, playedDays: '', notPlayedDays: '', + minPlays: '', notSkippedDays: '', likedOnly: false, noAvoided: false, minMinutes: '', maxMinutes: '', +} + +const text = (n: number | undefined) => (n ? String(n) : '') +const minutes = (sec: number | undefined) => (sec ? String(Number((sec / 60).toFixed(2))) : '') + +function formatOf(formats: string[] | undefined): RuleForm['format'] { + if (!formats || formats.length === 0) return 'any' + if (formats.length === 1 && formats[0] === 'flac') return 'flac' + if (formats.length === 1 && formats[0] === 'mpeg') return 'mpeg' + return 'kept' +} + +export function formFromRules(r: SmartRules): RuleForm { + return { + genres: r.genres ?? [], + notGenres: r.not_genres ?? [], + format: formatOf(r.formats), + minBitrate: text(r.min_bitrate_kbps), + addedDays: text(r.added_within_days), + neverPlayed: r.never_played ?? false, + playedDays: text(r.played_within_days), + notPlayedDays: text(r.not_played_within_days), + minPlays: text(r.min_plays), + notSkippedDays: text(r.not_skipped_within_days), + likedOnly: r.liked_artists_only ?? false, + noAvoided: r.without_avoided_artists ?? false, + minMinutes: minutes(r.min_duration_sec), + maxMinutes: minutes(r.max_duration_sec), + } +} + +/** A whole number from 0 up; blank or anything else is 0, which is "no rule". */ +const whole = (v: string) => { + const n = Math.floor(Number(v.trim())) + return Number.isFinite(n) && n > 0 ? n : 0 +} + +/** + * The rules of the form. `base` is what the playlist had: what the editor has no field for (artists, albums, skipped + * lately, a format it does not offer) is kept as it was, and what it has a field for comes from the form alone. + */ +export function rulesFromForm(f: RuleForm, base: SmartRules = {}): SmartRules { + const out: SmartRules = {} + for (const key of ['artist_ids', 'not_artist_ids', 'album_ids', 'not_album_ids', 'skipped_within_days'] as const) { + if (base[key] !== undefined) Object.assign(out, { [key]: base[key] }) + } + if (f.genres.length) out.genres = f.genres + if (f.notGenres.length) out.not_genres = f.notGenres + if (f.format === 'flac' || f.format === 'mpeg') out.formats = [f.format] + if (f.format === 'kept' && base.formats) out.formats = base.formats + const numbers: [keyof SmartRules, string][] = [ + ['min_bitrate_kbps', f.minBitrate], ['added_within_days', f.addedDays], ['played_within_days', f.playedDays], + ['not_played_within_days', f.notPlayedDays], ['min_plays', f.minPlays], ['not_skipped_within_days', f.notSkippedDays], + ] + for (const [key, value] of numbers) { + const n = whole(value) + if (n > 0) Object.assign(out, { [key]: n }) + } + if (f.neverPlayed) out.never_played = true + if (f.likedOnly) out.liked_artists_only = true + if (f.noAvoided) out.without_avoided_artists = true + const min = Math.round(Number(f.minMinutes.trim() || 0) * 60) + const max = Math.round(Number(f.maxMinutes.trim() || 0) * 60) + if (min > 0) out.min_duration_sec = min + if (max > 0) out.max_duration_sec = max + return out +} + +/** The rules in words, one line each; a playlist with none says it takes every song. */ +export function describeRules(t: TFunction, r: SmartRules): string[] { + const list = (items: string[] | undefined) => (items ?? []).join(', ') + const lines: string[] = [] + const add = (cond: unknown, key: string, opts: Record = {}) => { + if (cond) lines.push(t(`smart.rule.${key}`, opts)) + } + add(r.genres?.length, 'genres', { list: list(r.genres) }) + add(r.not_genres?.length, 'notGenres', { list: list(r.not_genres) }) + add(r.artist_ids?.length, 'artists', { count: r.artist_ids?.length }) + add(r.not_artist_ids?.length, 'notArtists', { count: r.not_artist_ids?.length }) + add(r.album_ids?.length, 'albums', { count: r.album_ids?.length }) + add(r.not_album_ids?.length, 'notAlbums', { count: r.not_album_ids?.length }) + add(r.formats?.length, 'formats', { list: list(r.formats) }) + add(r.min_bitrate_kbps, 'minBitrate', { kbps: r.min_bitrate_kbps }) + add(r.added_within_days, 'added', { count: r.added_within_days }) + add(r.never_played, 'neverPlayed') + add(r.played_within_days, 'played', { count: r.played_within_days }) + add(r.not_played_within_days, 'notPlayed', { count: r.not_played_within_days }) + add(r.min_plays, 'minPlays', { count: r.min_plays }) + add(r.skipped_within_days, 'skipped', { count: r.skipped_within_days }) + add(r.not_skipped_within_days, 'notSkipped', { count: r.not_skipped_within_days }) + add(r.liked_artists_only, 'liked') + add(r.without_avoided_artists, 'noAvoided') + add(r.min_duration_sec, 'minLength', { minutes: Number(((r.min_duration_sec ?? 0) / 60).toFixed(2)) }) + add(r.max_duration_sec, 'maxLength', { minutes: Number(((r.max_duration_sec ?? 0) / 60).toFixed(2)) }) + if (lines.length === 0) lines.push(t('smart.rule.none')) + return lines +} diff --git a/web/src/router.tsx b/web/src/router.tsx index d42c322..0b5662a 100644 --- a/web/src/router.tsx +++ b/web/src/router.tsx @@ -17,6 +17,9 @@ import NotFoundPage from '@/pages/NotFoundPage' import PlaylistPage from '@/pages/PlaylistPage' import PlaylistsPage from '@/pages/PlaylistsPage' import SearchPage from '@/pages/SearchPage' +import SmartEditorPage from '@/pages/SmartEditorPage' +import SmartPlaylistPage from '@/pages/SmartPlaylistPage' +import SmartPlaylistsPage from '@/pages/SmartPlaylistsPage' import SettingsPage from '@/pages/SettingsPage' import SongsPage from '@/pages/SongsPage' @@ -36,6 +39,10 @@ export const routes: RouteObject[] = [ { path: '/mixes/:id', element: }, { path: '/playlists', element: }, { path: '/playlists/:id', element: }, + { path: '/smart-playlists', element: }, + { path: '/smart-playlists/new', element: }, + { path: '/smart-playlists/:id', element: }, + { path: '/smart-playlists/:id/edit', element: }, { path: '/settings', element: }, { path: '/admin',