feat(smart): smart playlists made for everybody, without making them

- A fixed set that is there with no setup: recently added, never played, most played, not heard for a while, high quality files and long tracks. The rules are the same for everyone and are worked out on each one's own library and history, like the mixes; nothing is stored, so they follow the library.
- GET /smart-playlists/suggested, GET /smart-playlists/suggested/{key}/tracks and POST /smart-playlists/suggested/{key}/playlist.
- The Smart playlists page begins with them, with names and descriptions in the language of the page. A suggested one can be played, shuffled again, kept as a playlist, or made one's own: a copy of its rules opens in the editor.
This commit is contained in:
tgiachi 2026-11-13 10:06:58 +01:00
commit 17f70d582d
16 changed files with 920 additions and 28 deletions

View file

@ -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 `<img>` 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. Each mix says which albums stand for it (`album_ids`: up to 4 albums that have a cover, by different artists, with most of the songs the mix draws from), for a picture made of their covers; the covers are the ones the library already has, so a mix has a picture once the covers of its albums were looked up (browsing the albums, or the covers job), and none is fetched for it.
- **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.
- **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. Some are there without anybody making them: `GET /smart-playlists/suggested` lists a fixed set (`recently-added`, `never-played`, `most-played`, `forgotten`, `high-quality`, `long-tracks`), the same rules for everyone and worked out on your own library and history, nothing stored; `GET /smart-playlists/suggested/{key}/tracks` gives their songs and `POST /smart-playlists/suggested/{key}/playlist` keeps them as a playlist, and a copy of their rules becomes a smart playlist of your own with `POST /smart-playlists`. 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.
@ -297,6 +297,7 @@ Everything lives under `/api/v1`. Bodies are JSON. Errors always look like `{"er
| 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/suggested`, `GET /smart-playlists/suggested/{key}/tracks`, `POST /smart-playlists/suggested/{key}/playlist` | The smart playlists Sonda makes for everybody (a fixed set), their songs for you now (query `variant`), and one kept as a normal playlist. |
| 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. |
| signed in | `GET /playlists/{id}/tracks`, `POST /playlists/{id}/tracks`, `PATCH`, `DELETE /playlists/{id}/tracks/{item}` | The tracks of a playlist: list them in order, add some (at the end or at a `position`), move or remove an item. |
@ -346,7 +347,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, with a collage of the covers of its albums (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.
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, with a collage of the covers of its albums (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, which begins with the ones Sonda makes for you (ready to play, to keep as a playlist, or to make your own with a click), and then yours: 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`.

View file

@ -1034,6 +1034,17 @@ 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")
sug := c.expect(c.call("GET", "/smart-playlists/suggested", token, nil), 200, "the suggested smart playlists")
if len(sug["items"].([]any)) < 5 {
t.Fatalf("suggested = %v", sug)
}
c.expect(c.call("GET", "/smart-playlists/suggested/never-played/tracks", token, nil), 200, "the songs of a suggested one")
c.expect(c.call("GET", "/smart-playlists/suggested/never-played/tracks?variant=-1", token, nil), 400, "a negative variant", "invalid_input")
c.expect(c.call("GET", "/smart-playlists/suggested/nonsense/tracks", token, nil), 404, "an unknown suggested one", "suggested_not_found")
c.expect(c.call("POST", "/smart-playlists/suggested/never-played/playlist", token, map[string]any{"name": "Fresh ears", "variant": 1}), 201, "keep a suggested one")
c.expect(c.call("POST", "/smart-playlists/suggested/never-played/playlist", token, nil), 201, "keep a suggested one with no body")
c.expect(c.call("POST", "/smart-playlists/suggested/high-quality/playlist", token, nil), 422, "keep a suggested one with no songs", "smart_playlist_empty")
c.expect(c.call("POST", "/smart-playlists/suggested/nonsense/playlist", token, nil), 404, "keep an unknown suggested one", "suggested_not_found")
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)

View file

@ -248,3 +248,74 @@ func (h *smartHandlers) genres(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"items": items})
}
type suggestedJSON struct {
Key string `json:"key"`
Rules smart.Rules `json:"rules"`
Sort string `json:"sort"`
Limit int `json:"limit"`
}
func toSuggestedJSON(s smart.SuggestedPlaylist) suggestedJSON {
return suggestedJSON{Key: s.Key, Rules: s.Rules, Sort: string(s.Sort), Limit: s.Limit}
}
// suggestedList gives the smart playlists that Sonda makes for everybody: a fixed set, with no songs in it.
func (h *smartHandlers) suggestedList(c *gin.Context) {
list := smart.Suggested()
out := make([]suggestedJSON, len(list))
for i, s := range list {
out[i] = toSuggestedJSON(s)
}
c.JSON(http.StatusOK, gin.H{"items": out})
}
func writeSuggestedError(c *gin.Context, err error) {
if errors.Is(err, smart.ErrNotFound) {
writeError(c, http.StatusNotFound, "suggested_not_found", "no such suggested smart playlist")
return
}
writeSmartError(c, err)
}
// suggestedTracks works the songs of a suggested smart playlist out for the signed-in user.
func (h *smartHandlers) suggestedTracks(c *gin.Context) {
variant, ok := variantOf(c)
if !ok {
return
}
_, tracks, err := h.svc.SuggestedTracks(c.Request.Context(), currentUserID(c), c.Param("key"), variant)
if err != nil {
writeSuggestedError(c, err)
return
}
c.JSON(http.StatusOK, smartTracksJSON{Variant: variant, Tracks: toTracksJSON(tracks)})
}
// suggestedSave makes a normal playlist of the songs a suggested smart playlist gives now.
func (h *smartHandlers) suggestedSave(c *gin.Context) {
var req saveSmartRequest
if c.Request.ContentLength != 0 && !bindJSON(c, &req) {
return
}
variant := 0
if req.Variant != nil {
variant = *req.Variant
}
user := currentUserID(c)
key := c.Param("key")
_, tracks, err := h.svc.SuggestedTracks(c.Request.Context(), user, key, variant)
if err != nil {
writeSuggestedError(c, err)
return
}
if len(tracks) == 0 {
writeError(c, http.StatusUnprocessableEntity, "smart_playlist_empty", "the rules give no songs to save")
return
}
name := strings.TrimSpace(req.Name)
if name == "" {
name = key // a client says the name in its language; this is only for one that does not
}
keepAsPlaylist(c, h.playlists, user, name, tracks)
}

View file

@ -117,6 +117,7 @@ type smartService interface {
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)
SuggestedTracks(ctx context.Context, userID int64, key string, variant int) (smart.SuggestedPlaylist, []catalog.Track, error)
}
type feedbackService interface {
@ -282,6 +283,9 @@ func NewRouter(d Deps) *gin.Engine {
protected.GET("/smart-playlists", sm.list)
protected.POST("/smart-playlists", sm.create)
protected.POST("/smart-playlists/preview", sm.preview)
protected.GET("/smart-playlists/suggested", sm.suggestedList)
protected.GET("/smart-playlists/suggested/:key/tracks", sm.suggestedTracks)
protected.POST("/smart-playlists/suggested/:key/playlist", sm.suggestedSave)
protected.GET("/smart-playlists/:id", sm.get)
protected.PATCH("/smart-playlists/:id", sm.update)
protected.DELETE("/smart-playlists/:id", sm.remove)

View file

@ -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", "/api/v1/genres"}, {"GET", sp}, {"POST", sp}, {"POST", sp + "/preview"}, {"GET", sp + "/1"}, {"PATCH", sp + "/1"}, {"DELETE", sp + "/1"},
{"GET", "/api/v1/genres"}, {"GET", sp + "/suggested"}, {"GET", sp + "/suggested/never-played/tracks"}, {"POST", sp + "/suggested/never-played/playlist"}, {"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 {
@ -279,3 +279,72 @@ func TestTheGenresOfTheLibraryAreListedBiggestFirst(t *testing.T) {
t.Errorf("genres = %v", items)
}
}
func TestSuggestedSmartPlaylistsAreThereForEveryoneWithTheirRules(t *testing.T) {
m := newMixAPI(t)
r := do(t, m.h, "GET", sp+"/suggested", m.alice, nil)
if r.Code != http.StatusOK {
t.Fatalf("suggested: %d %v", r.Code, r.Body)
}
byKey := map[string]map[string]any{}
for _, x := range r.Body["items"].([]any) {
s := x.(map[string]any)
byKey[s["key"].(string)] = s
}
for _, key := range []string{"recently-added", "never-played", "most-played", "forgotten", "high-quality", "long-tracks"} {
if byKey[key] == nil {
t.Errorf("%s is missing from %v", key, byKey)
}
}
never := byKey["never-played"]
if never["sort"] != "random" || never["limit"] != float64(50) || never["rules"].(map[string]any)["never_played"] != true {
t.Errorf("never-played = %v", never)
}
// The list of mine does not have them: they are not stored.
if list := do(t, m.h, "GET", sp, m.alice, nil); list.Body["total"] != float64(0) {
t.Errorf("my smart playlists = %v", list.Body)
}
}
func TestTheSongsOfASuggestedSmartPlaylistAreWorkedOutForTheListener(t *testing.T) {
m := newMixAPI(t)
r := do(t, m.h, "GET", sp+"/suggested/never-played/tracks", m.alice, nil)
if r.Code != http.StatusOK || r.Body["variant"] != float64(0) || len(trackIDs(t, r)) != 50 {
t.Fatalf("never-played: %d, %d songs", r.Code, len(trackIDs(t, r)))
}
first := trackIDs(t, r)
if again := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/never-played/tracks", m.alice, nil)); !slices.Equal(first, again) {
t.Error("the same day gave other songs")
}
if v := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/never-played/tracks?variant=1", m.alice, nil)); slices.Equal(first, v) {
t.Error("another variant gave the same songs")
}
// Nothing was played, so there is no most played, and the library has no 900 kbps file.
if got := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/most-played/tracks", m.alice, nil)); len(got) != 0 {
t.Errorf("most-played with no history = %v", got)
}
if r := do(t, m.h, "GET", sp+"/suggested/nonsense/tracks", m.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "suggested_not_found" {
t.Errorf("unknown key: %d %v", r.Code, r.Body)
}
if r := do(t, m.h, "GET", sp+"/suggested/never-played/tracks?variant=-1", m.alice, nil); r.Code != http.StatusBadRequest {
t.Errorf("negative variant: %d", r.Code)
}
}
func TestASuggestedSmartPlaylistIsKeptAsAPlaylist(t *testing.T) {
m := newMixAPI(t)
shown := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/never-played/tracks?variant=2", m.alice, nil))
r := do(t, m.h, "POST", sp+"/suggested/never-played/playlist", m.alice, map[string]any{"name": "Fresh ears", "variant": 2})
if r.Code != http.StatusCreated || r.Body["name"] != "Fresh ears" || r.Body["track_count"] != float64(len(shown)) {
t.Fatalf("save: %d %v", r.Code, r.Body)
}
if r := do(t, m.h, "POST", sp+"/suggested/never-played/playlist", m.alice, nil); r.Code != http.StatusCreated || r.Body["name"] != "never-played" {
t.Errorf("save with no body: %d %v", r.Code, r.Body)
}
if r := do(t, m.h, "POST", sp+"/suggested/most-played/playlist", m.alice, nil); r.Code != http.StatusUnprocessableEntity || errCode(r) != "smart_playlist_empty" {
t.Errorf("save of an empty one: %d %v", r.Code, r.Body)
}
if r := do(t, m.h, "POST", sp+"/suggested/nonsense/playlist", m.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "suggested_not_found" {
t.Errorf("unknown key: %d %v", r.Code, r.Body)
}
}

View file

@ -1378,6 +1378,84 @@ paths:
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
/smart-playlists/suggested:
get:
tags: [Smart playlists]
operationId: listSuggestedSmartPlaylists
summary: The smart playlists Sonda makes for you
description: |
A fixed set that is there without anybody making it, the same rules for everyone and worked out on your
own library and history: `recently-added`, `never-played`, `most-played`, `forgotten` (played once, but not
in the last 90 days), `high-quality` (bitrate of 900 kbps or more) and `long-tracks` (6 minutes or more).
Nothing is stored for them. A client says their names in its own language from the `key`. To change one,
make a smart playlist of your own from its rules with `POST /smart-playlists`.
security: [{bearerAuth: []}]
responses:
'200':
description: The suggested smart playlists.
content:
application/json:
schema: {$ref: '#/components/schemas/SuggestedSmartPlaylistList'}
'401': {$ref: '#/components/responses/Unauthorized'}
/smart-playlists/suggested/{key}/tracks:
parameters:
- {$ref: '#/components/parameters/SuggestedKey'}
get:
tags: [Smart playlists]
operationId: getSuggestedSmartPlaylistTracks
summary: The songs of a suggested smart playlist, now
description: |
Works the rules out for you, as `GET /smart-playlists/{id}/tracks` does for yours. With the random order
the songs stay the same all day, and another `variant` gives other ones.
security: [{bearerAuth: []}]
parameters:
- name: variant
in: query
description: Other songs for the random order, from 0 (the songs of the day) up.
schema: {type: integer, minimum: 0, maximum: 1000000, default: 0}
responses:
'200':
description: The songs.
content:
application/json:
schema: {$ref: '#/components/schemas/SmartTracks'}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
'404': {$ref: '#/components/responses/SuggestedNotFound'}
/smart-playlists/suggested/{key}/playlist:
parameters:
- {$ref: '#/components/parameters/SuggestedKey'}
post:
tags: [Smart playlists]
operationId: saveSuggestedSmartPlaylist
summary: Keep a suggested smart playlist as a playlist
description: |
Makes a playlist of your own with the songs that `variant` gives now, in the same order. It is a copy,
and is yours to edit. The body is optional; without a name the playlist is called by the `key`.
security: [{bearerAuth: []}]
requestBody:
required: false
content:
application/json:
schema: {$ref: '#/components/schemas/SaveSmartPlaylist'}
responses:
'201':
description: The playlist.
content:
application/json:
schema: {$ref: '#/components/schemas/Playlist'}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
'404': {$ref: '#/components/responses/SuggestedNotFound'}
'409': {$ref: '#/components/responses/PlaylistLimit'}
'422':
description: The rules give no songs to save (`smart_playlist_empty`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/smart-playlists/{id}:
parameters:
- {$ref: '#/components/parameters/Id'}
@ -2705,6 +2783,12 @@ components:
name: offset
in: query
schema: {type: integer, minimum: 0, default: 0}
SuggestedKey:
name: key
in: path
required: true
description: A key from `GET /smart-playlists/suggested`.
schema: {type: string, enum: [recently-added, never-played, most-played, forgotten, high-quality, long-tracks]}
MixId:
name: id
in: path
@ -2761,6 +2845,11 @@ components:
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
SuggestedNotFound:
description: No such suggested smart playlist (`suggested_not_found`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
SmartPlaylistNotFound:
description: No such smart playlist, or it is somebody else's (`smart_playlist_not_found`).
content:
@ -3455,6 +3544,25 @@ components:
min_duration_sec: {type: integer, minimum: 0, maximum: 86400}
max_duration_sec: {type: integer, minimum: 0, maximum: 86400}
SuggestedSmartPlaylist:
type: object
additionalProperties: false
required: [key, rules, sort, limit]
properties:
key: {type: string, enum: [recently-added, never-played, most-played, forgotten, high-quality, long-tracks]}
rules: {$ref: '#/components/schemas/SmartRules'}
sort: {$ref: '#/components/schemas/SmartSort'}
limit: {type: integer, minimum: 1, maximum: 500}
SuggestedSmartPlaylistList:
type: object
additionalProperties: false
required: [items]
properties:
items:
type: array
items: {$ref: '#/components/schemas/SuggestedSmartPlaylist'}
SmartSort:
type: string
enum: [random, most_played, least_played, recently_added, title]

View file

@ -517,3 +517,81 @@ func TestGenresMergeSpellingsLeaveOutWhatIsNotAGenreAndCountTheBiggestFirst(t *t
t.Errorf("got %v, want %v", got, want)
}
}
// ---- the suggested ones ----
func TestSuggestedAreAFixedSetOfValidRules(t *testing.T) {
list := Suggested()
if len(list) < 5 {
t.Fatalf("%d suggested smart playlists", len(list))
}
seen := map[string]bool{}
for _, s := range list {
if s.Key == "" || seen[s.Key] {
t.Errorf("key %q is empty or repeated", s.Key)
}
seen[s.Key] = true
in, err := clean(Input{Rules: s.Rules, Sort: s.Sort, Limit: s.Limit})
if err != nil {
t.Errorf("%s: %v", s.Key, err)
}
if in.Sort != s.Sort || in.Limit != s.Limit || s.Limit < 1 {
t.Errorf("%s: shape changed by cleaning: %+v", s.Key, in)
}
}
for _, want := range []string{"recently-added", "never-played", "most-played", "forgotten", "high-quality", "long-tracks"} {
if !seen[want] {
t.Errorf("%s is missing", want)
}
}
// A caller cannot change the set by changing what it was given.
list[0].Rules.Genres = []string{"x"}
if got := Suggested()[0].Rules.Genres; len(got) != 0 {
t.Errorf("the set was changed: %v", got)
}
}
func TestSuggestedSongsAreWorkedOutFromTheirRulesForTheListener(t *testing.T) {
st := newStore()
st.cands = songs(6)
st.history = map[int64]History{1: {Plays: 4, LastPlayed: daysAgo(2)}, 2: {Plays: 1, LastPlayed: daysAgo(200)}}
svc := newService(st, taste.Learned{})
got, tracks, err := svc.SuggestedTracks(context.Background(), 1, "never-played", 0)
if err != nil || got.Key != "never-played" {
t.Fatalf("%+v, %v", got, err)
}
if ids := ids(tracks); slices.Contains(ids, 1) || slices.Contains(ids, 2) || len(ids) != 4 {
t.Errorf("never played = %v: songs 1 and 2 were played", ids)
}
_, tracks, _ = svc.SuggestedTracks(context.Background(), 1, "forgotten", 0)
if got := ids(tracks); !slices.Equal(got, []int64{2}) {
t.Errorf("forgotten = %v, want the song played once 200 days ago", got)
}
_, tracks, _ = svc.SuggestedTracks(context.Background(), 1, "most-played", 0)
if got := ids(tracks); !slices.Equal(got, []int64{1, 2}) {
t.Errorf("most played = %v, want the played ones, the most first", got)
}
_, tracks, _ = svc.SuggestedTracks(context.Background(), 1, "recently-added", 0)
if got := ids(tracks); len(got) == 0 || got[0] != 1 {
t.Errorf("recently added = %v, want the newest first", got)
}
if _, _, err := svc.SuggestedTracks(context.Background(), 1, "nonsense", 0); !errors.Is(err, ErrNotFound) {
t.Errorf("unknown key: %v", err)
}
if _, _, err := svc.SuggestedTracks(context.Background(), 1, "never-played", MaxVariant+1); !errors.Is(err, ErrInvalidInput) {
t.Errorf("variant: %v", err)
}
}
func TestEachSuggestedRandomOrderIsItsOwn(t *testing.T) {
st := newStore()
st.cands = songs(60)
svc := newService(st, taste.Learned{})
_, a, _ := svc.SuggestedTracks(context.Background(), 1, "never-played", 0)
_, b, _ := svc.SuggestedTracks(context.Background(), 1, "long-tracks", 0)
st.cands = songs(60)
if slices.Equal(ids(a), ids(b)) {
t.Error("two suggested playlists with the same candidates gave the same order")
}
}

View file

@ -0,0 +1,55 @@
package smart
import (
"context"
"slices"
"codeberg.org/squidd/sonda/internal/catalog"
)
// SuggestedPlaylist is a smart playlist that Sonda makes for everybody, with no need to ask: the rules are the
// same for every user and are worked out on each one's own library and history, when it is opened. Nothing is
// stored for it, so it follows the library, and a client says its name in its own language from the key.
type SuggestedPlaylist struct {
Key string // "recently-added", "never-played"...
Rules Rules
Sort Sort
Limit int
}
// suggested is the set. Its rules are valid ones (a test checks it), and a copy of one is a smart playlist
// the user can make their own with Create.
var suggested = []SuggestedPlaylist{
{Key: "recently-added", Rules: Rules{AddedWithinDays: 30}, Sort: SortRecentlyAdded, Limit: 100},
{Key: "never-played", Rules: Rules{NeverPlayed: true}, Sort: SortRandom, Limit: DefaultLimit},
{Key: "most-played", Rules: Rules{MinPlays: 1}, Sort: SortMostPlayed, Limit: DefaultLimit},
{Key: "forgotten", Rules: Rules{MinPlays: 1, NotPlayedWithinDays: 90}, Sort: SortRandom, Limit: DefaultLimit},
{Key: "high-quality", Rules: Rules{MinBitrateKbps: 900}, Sort: SortRandom, Limit: DefaultLimit},
{Key: "long-tracks", Rules: Rules{MinDurationSec: 360}, Sort: SortRandom, Limit: DefaultLimit},
}
// Suggested returns the suggested smart playlists. The list is a copy: changing it changes nothing.
func Suggested() []SuggestedPlaylist {
out := make([]SuggestedPlaylist, len(suggested))
for i, s := range suggested {
s.Rules.Genres = slices.Clone(s.Rules.Genres)
out[i] = s
}
return out
}
// SuggestedTracks works the songs of a suggested smart playlist out for the user. variant 0 is the songs of
// the day; with a random order another number gives other ones. An unknown key is ErrNotFound.
func (s *Service) SuggestedTracks(ctx context.Context, userID int64, key string, variant int) (SuggestedPlaylist, []catalog.Track, error) {
if err := checkVariant(variant); err != nil {
return SuggestedPlaylist{}, nil, err
}
i := slices.IndexFunc(suggested, func(x SuggestedPlaylist) bool { return x.Key == key })
if i < 0 {
return SuggestedPlaylist{}, nil, ErrNotFound
}
sg := suggested[i]
// The seed has an id of its own, below 0 so that it is never one of a kept playlist.
tracks, err := s.run(ctx, userID, -int64(i+1), sg.Rules, sg.Sort, sg.Limit, variant)
return Suggested()[i], tracks, err
}

View file

@ -962,6 +962,78 @@ export interface paths {
patch?: never;
trace?: never;
};
"/smart-playlists/suggested": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The smart playlists Sonda makes for you
* @description A fixed set that is there without anybody making it, the same rules for everyone and worked out on your
* own library and history: `recently-added`, `never-played`, `most-played`, `forgotten` (played once, but not
* in the last 90 days), `high-quality` (bitrate of 900 kbps or more) and `long-tracks` (6 minutes or more).
* Nothing is stored for them. A client says their names in its own language from the `key`. To change one,
* make a smart playlist of your own from its rules with `POST /smart-playlists`.
*/
get: operations["listSuggestedSmartPlaylists"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/smart-playlists/suggested/{key}/tracks": {
parameters: {
query?: never;
header?: never;
path: {
/** @description A key from `GET /smart-playlists/suggested`. */
key: components["parameters"]["SuggestedKey"];
};
cookie?: never;
};
/**
* The songs of a suggested smart playlist, now
* @description Works the rules out for you, as `GET /smart-playlists/{id}/tracks` does for yours. With the random order
* the songs stay the same all day, and another `variant` gives other ones.
*/
get: operations["getSuggestedSmartPlaylistTracks"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/smart-playlists/suggested/{key}/playlist": {
parameters: {
query?: never;
header?: never;
path: {
/** @description A key from `GET /smart-playlists/suggested`. */
key: components["parameters"]["SuggestedKey"];
};
cookie?: never;
};
get?: never;
put?: never;
/**
* Keep a suggested smart playlist as a playlist
* @description Makes a playlist of your own with the songs that `variant` gives now, in the same order. It is a copy,
* and is yours to edit. The body is optional; without a name the playlist is called by the `key`.
*/
post: operations["saveSuggestedSmartPlaylist"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/smart-playlists/{id}": {
parameters: {
query?: never;
@ -2312,6 +2384,16 @@ export interface components {
min_duration_sec?: number;
max_duration_sec?: number;
};
SuggestedSmartPlaylist: {
/** @enum {string} */
key: "recently-added" | "never-played" | "most-played" | "forgotten" | "high-quality" | "long-tracks";
rules: components["schemas"]["SmartRules"];
sort: components["schemas"]["SmartSort"];
limit: number;
};
SuggestedSmartPlaylistList: {
items: components["schemas"]["SuggestedSmartPlaylist"][];
};
/**
* @description A tie always goes to the lower song id.
* @enum {string}
@ -2727,6 +2809,15 @@ export interface components {
"application/json": components["schemas"]["Error"];
};
};
/** @description No such suggested smart playlist (`suggested_not_found`). */
SuggestedNotFound: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description No such smart playlist, or it is somebody else's (`smart_playlist_not_found`). */
SmartPlaylistNotFound: {
headers: {
@ -2788,6 +2879,8 @@ export interface components {
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
Limit: number;
Offset: number;
/** @description A key from `GET /smart-playlists/suggested`. */
SuggestedKey: "recently-added" | "never-played" | "most-played" | "forgotten" | "high-quality" | "long-tracks";
/** @description `favourites`, `rediscover`, `unheard` or `genre:<name>` (percent-encoded). */
MixId: string;
/** @description Only items with a playable file in this library. */
@ -4344,6 +4437,96 @@ export interface operations {
401: components["responses"]["Unauthorized"];
};
};
listSuggestedSmartPlaylists: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The suggested smart playlists. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["SuggestedSmartPlaylistList"];
};
};
401: components["responses"]["Unauthorized"];
};
};
getSuggestedSmartPlaylistTracks: {
parameters: {
query?: {
/** @description Other songs for the random order, from 0 (the songs of the day) up. */
variant?: number;
};
header?: never;
path: {
/** @description A key from `GET /smart-playlists/suggested`. */
key: components["parameters"]["SuggestedKey"];
};
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"]["SuggestedNotFound"];
};
};
saveSuggestedSmartPlaylist: {
parameters: {
query?: never;
header?: never;
path: {
/** @description A key from `GET /smart-playlists/suggested`. */
key: components["parameters"]["SuggestedKey"];
};
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"]["SuggestedNotFound"];
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"];
};
};
};
};
getSmartPlaylist: {
parameters: {
query?: never;

View file

@ -51,6 +51,40 @@ export function useSmartPreview(input: SmartInput) {
})
}
/** A smart playlist that Sonda makes for everybody: a key (its name comes from the texts of the page) and its rules. */
export interface SuggestedSmart extends SmartInput {
key: string
}
/** The smart playlists that are there without making them. */
export function useSuggested() {
return useQuery({
queryKey: ['smart-suggested'],
queryFn: () => api.get<{ items: SuggestedSmart[] }>('/smart-playlists/suggested').then((r) => r.items),
staleTime: 10 * 60_000,
})
}
/** The songs of a suggested one now. The songs on screen stay until the next ones arrive. */
export function useSuggestedTracks(key: string, variant: number) {
return useQuery({
queryKey: ['smart-suggested-tracks', key, variant],
queryFn: () =>
api.get<{ variant: number; tracks: Track[] }>(`/smart-playlists/suggested/${encodeURIComponent(key)}/tracks`, variant > 0 ? { variant } : undefined),
placeholderData: keepPreviousData,
})
}
/** Keeps the songs of a suggested one on screen as a normal playlist of mine. */
export function useSaveSuggested() {
const client = useQueryClient()
return useMutation({
mutationFn: ({ key, ...body }: { key: string; name: string; variant: number }) =>
api.post<Playlist>(`/smart-playlists/suggested/${encodeURIComponent(key)}/playlist`, body),
onSuccess: () => refreshPlaylists(client),
})
}
/** The genres of the library with their songs, the biggest first. */
export function useGenres() {
return useQuery({

View file

@ -529,6 +529,7 @@
"mix_not_found": "This mix is not available now.",
"mix_empty": "This mix has no songs to keep.",
"smart_playlist_not_found": "This smart playlist does not exist.",
"suggested_not_found": "This suggested smart playlist does not exist.",
"smart_playlist_empty": "These rules give no songs to keep."
},
"playlists": {
@ -580,6 +581,18 @@
"open": "Open the playlist"
},
"smart": {
"forYou": "Made for you",
"mine": "My smart playlists",
"makeMine": "Make it mine",
"notFoundSuggested": "This suggested smart playlist does not exist.",
"suggested": {
"recently-added": { "name": "Recently added", "description": "Songs added in the last 30 days, the newest first." },
"never-played": { "name": "Never played", "description": "Songs you have never listened to." },
"most-played": { "name": "Most played", "description": "The songs you have played most." },
"forgotten": { "name": "Not heard in a while", "description": "Songs you played once, but not in the last 90 days." },
"high-quality": { "name": "High quality", "description": "Files of 900 kbps or more." },
"long-tracks": { "name": "Long tracks", "description": "Songs of 6 minutes or more." }
},
"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",

View file

@ -529,6 +529,7 @@
"mix_not_found": "Questo mix ora non è disponibile.",
"mix_empty": "Questo mix non ha brani da salvare.",
"smart_playlist_not_found": "Questa playlist smart non esiste.",
"suggested_not_found": "Questa playlist smart suggerita non esiste.",
"smart_playlist_empty": "Queste regole non danno brani da salvare."
},
"playlists": {
@ -580,6 +581,18 @@
"open": "Apri la playlist"
},
"smart": {
"forYou": "Fatte per te",
"mine": "Le mie playlist smart",
"makeMine": "Fanne una tua",
"notFoundSuggested": "Questa playlist smart suggerita non esiste.",
"suggested": {
"recently-added": { "name": "Aggiunti da poco", "description": "Brani aggiunti negli ultimi 30 giorni, i più nuovi per primi." },
"never-played": { "name": "Mai ascoltati", "description": "Brani che non hai mai ascoltato." },
"most-played": { "name": "I più ascoltati", "description": "I brani che hai ascoltato di più." },
"forgotten": { "name": "Non li senti da un po'", "description": "Brani ascoltati almeno una volta, ma non negli ultimi 90 giorni." },
"high-quality": { "name": "Alta qualità", "description": "File da 900 kbps o più." },
"long-tracks": { "name": "Brani lunghi", "description": "Brani da 6 minuti o più." }
},
"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",

View file

@ -1,8 +1,10 @@
import { Plus } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom'
import { useSmartPlaylists } from '@/api/smart'
import { useSmartPlaylists, useSuggested } from '@/api/smart'
import { CARD_GRID } from '@/components/cards'
import LoadMore from '@/components/LoadMore'
import Section from '@/components/Section'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import { buttonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
@ -11,6 +13,7 @@ import { cn } from '@/lib/utils'
export default function SmartPlaylistsPage() {
const { t } = useTranslation()
const query = useSmartPlaylists()
const suggested = useSuggested()
const items = query.data?.items ?? []
return (
@ -23,29 +26,44 @@ export default function SmartPlaylistsPage() {
</Link>
</div>
{query.isError ? (
<ErrorMessage error={query.error} onRetry={() => query.refetch()} />
) : query.isPending ? (
<Loading />
) : items.length === 0 ? (
<EmptyMessage>{t('smart.empty')}</EmptyMessage>
) : (
<>
<ul className="flex flex-col">
{items.map((p) => (
<li key={p.id}>
<Link to={`/smart-playlists/${p.id}`} className="flex min-h-14 items-center justify-between gap-4 rounded-lg px-4 hover:bg-secondary">
<span className="truncate font-semibold">{p.name}</span>
<span className="flex-none text-sm text-muted-foreground">
{t('smart.meta', { count: p.limit, sort: t(`smart.sort.${p.sort}`) })}
</span>
</Link>
</li>
{suggested.data && (
<Section title={t('smart.forYou')}>
<div className={CARD_GRID}>
{suggested.data.map((s) => (
<Link key={s.key} to={`/smart-playlists/suggested/${s.key}`} className="flex min-h-28 flex-col justify-between gap-3 rounded-xl bg-card p-4 text-card-foreground hover:bg-secondary">
<span className="text-lg leading-tight font-bold">{t(`smart.suggested.${s.key}.name`)}</span>
<span className="line-clamp-3 text-sm text-muted-foreground">{t(`smart.suggested.${s.key}.description`)}</span>
</Link>
))}
</ul>
<LoadMore query={query} />
</>
</div>
</Section>
)}
<Section title={t('smart.mine')}>
{query.isError ? (
<ErrorMessage error={query.error} onRetry={() => query.refetch()} />
) : query.isPending ? (
<Loading />
) : items.length === 0 ? (
<EmptyMessage>{t('smart.empty')}</EmptyMessage>
) : (
<>
<ul className="flex flex-col">
{items.map((p) => (
<li key={p.id}>
<Link to={`/smart-playlists/${p.id}`} className="flex min-h-14 items-center justify-between gap-4 rounded-lg px-4 hover:bg-secondary">
<span className="truncate font-semibold">{p.name}</span>
<span className="flex-none text-sm text-muted-foreground">
{t('smart.meta', { count: p.limit, sort: t(`smart.sort.${p.sort}`) })}
</span>
</Link>
</li>
))}
</ul>
<LoadMore query={query} />
</>
)}
</Section>
</div>
)
}

View file

@ -0,0 +1,126 @@
import { ListPlus, Play, Shuffle, Wand2 } 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 { useCreateSmart, useSaveSuggested, useSuggested, useSuggestedTracks } from '@/api/smart'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import TrackList from '@/components/TrackList'
import { Button } from '@/components/ui/button'
import { errorMessageKey } from '@/i18n'
import { formatTime } from '@/lib/time'
import { usePlayer } from '@/player/store'
import { describeRules } from './smartRules'
/** One of the smart playlists that are there without making them: its songs, and a way to make it one's own. */
export default function SuggestedSmartPage() {
const key = useParams().key ?? ''
return <SuggestedView key={key} name={key} />
}
function errorLine(t: (key: string) => string, error: unknown) {
return t(errorMessageKey(error instanceof ApiError ? error.code : 'unknown'))
}
function SuggestedView({ name: key }: { name: string }) {
const { t } = useTranslation()
const navigate = useNavigate()
const [variant, setVariant] = useState(0)
const list = useSuggested()
const query = useSuggestedTracks(key, variant)
const save = useSaveSuggested()
const make = useCreateSmart()
const playTracks = usePlayer((s) => s.playTracks)
if (query.isError) {
if (query.error instanceof ApiError && query.error.status === 404) return <EmptyMessage>{t('smart.notFoundSuggested')}</EmptyMessage>
return <ErrorMessage error={query.error} onRetry={() => query.refetch()} />
}
const suggested = list.data?.find((s) => s.key === key)
if (list.isError) return <ErrorMessage error={list.error} onRetry={() => list.refetch()} />
if (!suggested) return list.isPending ? <Loading /> : <EmptyMessage>{t('smart.notFoundSuggested')}</EmptyMessage>
const title = t(`smart.suggested.${key}.name`)
const description = t(`smart.suggested.${key}.description`)
const tracks = query.data?.tracks ?? []
const shown = query.data?.variant ?? 0
const waiting = query.isPlaceholderData
const duration = tracks.reduce((sum, track) => sum + track.duration_ms, 0)
return (
<div className="flex flex-col gap-8">
<header className="flex flex-col gap-3">
<h1 className="text-4xl font-extrabold tracking-tight md:text-6xl">{title}</h1>
<p className="max-w-2xl text-muted-foreground">{description}</p>
<ul aria-label={t('smart.rulesTitle')} className="flex flex-wrap gap-2">
{describeRules(t, suggested.rules).map((line) => (
<li key={line} className="rounded-md bg-secondary px-3 py-1 text-sm font-semibold">
{line}
</li>
))}
<li className="rounded-md bg-secondary px-3 py-1 text-sm font-semibold">{t(`smart.sort.${suggested.sort}`)}</li>
</ul>
{query.data && <p className="text-muted-foreground">{t('smart.songs', { count: tracks.length, duration: formatTime(duration) })}</p>}
<div className="flex flex-wrap gap-2">
<Button className="h-12 gap-2 rounded-md px-6" disabled={tracks.length === 0} onClick={() => playTracks(tracks, 0)}>
<Play />
{t('player.play')}
</Button>
{suggested.sort === 'random' && (
<Button
variant="outline"
className="h-12 gap-2"
disabled={waiting}
onClick={() => {
save.reset()
setVariant(variant + 1)
}}
>
<Shuffle />
{t('smart.shuffle')}
</Button>
)}
<Button
variant="outline"
className="h-12 gap-2"
disabled={tracks.length === 0 || waiting || save.isPending}
onClick={() => save.mutate({ key, name: title, variant: shown })}
>
<ListPlus />
{t('smart.save')}
</Button>
<Button
variant="outline"
className="h-12 gap-2"
disabled={make.isPending}
onClick={() =>
make.mutate(
{ name: title, description, rules: suggested.rules, sort: suggested.sort, limit: suggested.limit },
{ onSuccess: (p) => navigate(`/smart-playlists/${p.id}/edit`) },
)
}
>
<Wand2 />
{t('smart.makeMine')}
</Button>
</div>
</header>
{save.isSuccess && (
<p role="status" className="flex flex-wrap items-center gap-3 text-sm">
<span>{t('smart.saved', { name: save.data.name })}</span>
<Link to={`/playlists/${save.data.id}`} className="font-semibold underline">
{t('smart.open')}
</Link>
</p>
)}
{(save.isError || make.isError) && (
<p role="alert" className="text-sm text-destructive">
{errorLine(t, save.error ?? make.error)}
</p>
)}
{query.isPending ? <Loading /> : tracks.length === 0 ? <EmptyMessage>{t('smart.noSongs')}</EmptyMessage> : <TrackList tracks={tracks} />}
</div>
)
}

View file

@ -10,6 +10,7 @@ import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/
import SmartEditorPage from './SmartEditorPage'
import SmartPlaylistPage from './SmartPlaylistPage'
import SmartPlaylistsPage from './SmartPlaylistsPage'
import SuggestedSmartPage from './SuggestedSmartPage'
import { describeRules, formFromRules, rulesFromForm } from './smartRules'
// --- fixtures ---------------------------------------------------------------------------------
@ -52,6 +53,7 @@ function renderApp(path: string) {
<Routes>
<Route path="/smart-playlists" element={<SmartPlaylistsPage />} />
<Route path="/smart-playlists/new" element={<SmartEditorPage />} />
<Route path="/smart-playlists/suggested/:key" element={<SuggestedSmartPage />} />
<Route path="/smart-playlists/:id" element={<SmartPlaylistPage />} />
<Route path="/smart-playlists/:id/edit" element={<SmartEditorPage />} />
<Route path="/playlists/:id" element={<p>THE PLAYLIST PAGE</p>} />
@ -105,10 +107,22 @@ test('the rules are described in words, and no rule says so', async () => {
])
})
// --- the suggested ones ----------------------------------------------------------------------------
const SUGGESTED = [
{ key: 'recently-added', rules: { added_within_days: 30 }, sort: 'recently_added', limit: 100 },
{ key: 'never-played', rules: { never_played: true }, sort: 'random', limit: 50 },
{ key: 'most-played', rules: { min_plays: 1 }, sort: 'most_played', limit: 50 },
]
function suggestedRoutes(over: MockRoutes = {}): MockRoutes {
return { 'GET /api/v1/smart-playlists/suggested': () => ({ items: SUGGESTED }), ...over }
}
// --- 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 })]) })
mockFetch({ ...suggestedRoutes(), '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')
@ -118,7 +132,7 @@ test('the list shows each smart playlist with its order and limit, and a way to
})
test('with none the page explains what a smart playlist is', async () => {
mockFetch({ 'GET /api/v1/smart-playlists': () => page([]) })
mockFetch({ ...suggestedRoutes(), '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()
@ -209,7 +223,7 @@ test('rules that give no songs say so and cannot be played or kept; a refused sa
})
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([]) }))
const { calls } = mockFetch(one({ ...suggestedRoutes(), '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'))
@ -358,3 +372,95 @@ test('a smart playlist that does not exist cannot be edited', async () => {
renderApp('/smart-playlists/3/edit')
expect(await screen.findByText('This smart playlist does not exist.')).toBeInTheDocument()
})
// --- the suggested ones, on the list and on their own page ---------------------------------------------
test('the list begins with the smart playlists that are there without making them, in my language', async () => {
mockFetch({ ...suggestedRoutes(), 'GET /api/v1/smart-playlists': () => page([smart(3, 'Fresh rock')]) })
renderApp('/smart-playlists')
const made = await screen.findByRole('region', { name: 'Made for you' })
const links = within(made).getAllByRole('link')
expect(links.map((l) => l.getAttribute('href'))).toEqual([
'/smart-playlists/suggested/recently-added', '/smart-playlists/suggested/never-played', '/smart-playlists/suggested/most-played',
])
expect(links[0]).toHaveTextContent('Recently added')
expect(links[0]).toHaveTextContent('Songs added in the last 30 days')
const mine = screen.getByRole('region', { name: 'My smart playlists' })
expect(within(mine).getByRole('link', { name: /Fresh rock/ })).toBeInTheDocument()
})
test('the suggested ones are there even when the list of mine fails', async () => {
mockFetch({ ...suggestedRoutes(), 'GET /api/v1/smart-playlists': () => apiError(500, 'unknown') })
renderApp('/smart-playlists')
expect(await screen.findByRole('link', { name: /Never played/ })).toBeInTheDocument()
expect(await screen.findByRole('alert')).toBeInTheDocument()
})
function suggestedOne(over: MockRoutes = {}): MockRoutes {
return {
...suggestedRoutes(),
'GET /api/v1/smart-playlists/suggested/never-played/tracks': () => tracks(0, 1, 2, 3),
...over,
}
}
test('a suggested smart playlist shows its name, its rules and its songs, and cannot be edited or deleted', async () => {
mockFetch(suggestedOne())
renderApp('/smart-playlists/suggested/never-played')
expect(await screen.findByRole('heading', { level: 1, name: 'Never played' })).toBeInTheDocument()
expect(screen.getByText('Songs you have never listened to.')).toBeInTheDocument()
expect(within(screen.getByRole('list', { name: 'Rules' })).getByText('Never played', { selector: 'li' })).toBeInTheDocument()
expect(await screen.findByRole('button', { name: /Song 1/ })).toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Edit' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Delete' })).not.toBeInTheDocument()
})
test('a suggested one plays, shuffles again and is kept as a playlist under its name', async () => {
let saved: unknown
const { calls } = mockFetch(
suggestedOne({
'GET /api/v1/smart-playlists/suggested/never-played/tracks': ({ url }) => tracks(Number(url.searchParams.get('variant') ?? 0), 1, 2),
'POST /api/v1/smart-playlists/suggested/never-played/playlist': ({ init }) => {
saved = JSON.parse(init.body as string)
return json(201, { id: 42, name: 'Never played', 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/suggested/never-played')
await userEvent.click(await screen.findByRole('button', { name: 'Play' }))
expect(usePlayer.getState().queue.map((t) => t.id)).toEqual([1, 2])
await userEvent.click(screen.getByRole('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' }))
expect(await screen.findByRole('status')).toHaveTextContent('Saved as “Never played”')
expect(saved).toEqual({ name: 'Never played', variant: 1 })
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 on a suggested one either', async () => {
mockFetch(suggestedOne({ 'GET /api/v1/smart-playlists/suggested/most-played/tracks': () => tracks(0, 1) }))
renderApp('/smart-playlists/suggested/most-played')
await screen.findByRole('button', { name: 'Play' })
expect(screen.queryByRole('button', { name: 'Shuffle again' })).not.toBeInTheDocument()
})
test('Make it mine makes a smart playlist of my own with the same rules, and opens it to be changed', async () => {
const { calls } = mockFetch(
suggestedOne({
'POST /api/v1/smart-playlists': () => json(201, smart(9, 'Never played', { rules: { never_played: true }, description: 'Songs you have never listened to.' })),
'GET /api/v1/smart-playlists/9': () => smart(9, 'Never played', { rules: { never_played: true } }),
'POST /api/v1/smart-playlists/preview': () => tracks(0, 1),
}),
)
renderApp('/smart-playlists/suggested/never-played')
await userEvent.click(await screen.findByRole('button', { name: 'Make it mine' }))
const post = calls.find((c) => c.key === 'POST /api/v1/smart-playlists')!
expect(body(post)).toEqual({ name: 'Never played', description: 'Songs you have never listened to.', rules: { never_played: true }, sort: 'random', limit: 50 })
expect(await screen.findByRole('heading', { level: 1, name: 'Edit smart playlist' })).toBeInTheDocument()
})
test('a suggested one that does not exist says so', async () => {
mockFetch(suggestedOne({ 'GET /api/v1/smart-playlists/suggested/nonsense/tracks': () => apiError(404, 'suggested_not_found') }))
renderApp('/smart-playlists/suggested/nonsense')
expect(await screen.findByText('This suggested smart playlist does not exist.')).toBeInTheDocument()
})

View file

@ -22,6 +22,7 @@ import SmartPlaylistPage from '@/pages/SmartPlaylistPage'
import SmartPlaylistsPage from '@/pages/SmartPlaylistsPage'
import SettingsPage from '@/pages/SettingsPage'
import SongsPage from '@/pages/SongsPage'
import SuggestedSmartPage from '@/pages/SuggestedSmartPage'
export const routes: RouteObject[] = [
{
@ -41,6 +42,7 @@ export const routes: RouteObject[] = [
{ path: '/playlists/:id', element: <PlaylistPage /> },
{ path: '/smart-playlists', element: <SmartPlaylistsPage /> },
{ path: '/smart-playlists/new', element: <SmartEditorPage /> },
{ path: '/smart-playlists/suggested/:key', element: <SuggestedSmartPage /> },
{ path: '/smart-playlists/:id', element: <SmartPlaylistPage /> },
{ path: '/smart-playlists/:id/edit', element: <SmartEditorPage /> },
{ path: '/settings', element: <SettingsPage /> },