From 17f70d582dc2f3be8dd640cd675c8a23b5f69ef0 Mon Sep 17 00:00:00 2001
From: tgiachi {description} {t('smart.songs', { count: tracks.length, duration: formatTime(duration) })}
+ {t('smart.saved', { name: save.data.name })}
+
+ {t('smart.open')}
+
+
+ {errorLine(t, save.error ?? make.error)}
+ ` element can use it. To build the covers of the whole library in one go instead of one album at a time, an admin starts a background job like a scan: `POST /library/covers` (follow it with `GET /library/covers`, stop it with `DELETE /library/covers`; `?refresh=true` searches every album again; it never replaces a cover by "no cover" because a disk was not mounted, and keeps the covers that came from the archive if you switched it off).
- **Mixes.** `GET /mixes` lists playlists that Sonda makes for you, like the mixes of a streaming service, from what you listen to and from the genres of your music: one mix for each genre of your library that has at least 30 songs by 4 artists (the genres you play most first), and, once you have some listening history, *Your favourites* and *Rediscover* (artists you like and have not played for a month); *New to you* is the songs you never played. `GET /mixes/{id}` gives a mix of up to 50 songs, at most 3 by one artist and never two of the same artist in a row. They are picked by weighted chance: the artists you play weigh more and songs you skipped lately or artists you avoid are left out. A mix stays the same for a day, and `?variant=2` gives another; `POST /mixes/{id}/playlist` keeps the one you are looking at as a playlist of your own. A mix is worked out when you ask for it, from your own history and the genre tags of your files: nothing is stored and nothing is sent to a provider. The id of a genre mix has the genre in it (`genre:hard rock`), so it is percent-encoded in the path. 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`.
diff --git a/internal/api/http/contract_test.go b/internal/api/http/contract_test.go
index ba50ddb..ddeae2b 100644
--- a/internal/api/http/contract_test.go
+++ b/internal/api/http/contract_test.go
@@ -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)
diff --git a/internal/api/http/handlers_smart.go b/internal/api/http/handlers_smart.go
index 946b9c9..aac6162 100644
--- a/internal/api/http/handlers_smart.go
+++ b/internal/api/http/handlers_smart.go
@@ -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)
+}
diff --git a/internal/api/http/router.go b/internal/api/http/router.go
index 79c26f2..5093653 100644
--- a/internal/api/http/router.go
+++ b/internal/api/http/router.go
@@ -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)
diff --git a/internal/api/http/smart_test.go b/internal/api/http/smart_test.go
index 13f7a5f..efdc5ca 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", "/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)
+ }
+}
diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml
index cdb292b..2d64669 100644
--- a/internal/api/openapi/openapi.yaml
+++ b/internal/api/openapi/openapi.yaml
@@ -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]
diff --git a/internal/smart/smart_test.go b/internal/smart/smart_test.go
index 7947080..025543e 100644
--- a/internal/smart/smart_test.go
+++ b/internal/smart/smart_test.go
@@ -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")
+ }
+}
diff --git a/internal/smart/suggested.go b/internal/smart/suggested.go
new file mode 100644
index 0000000..b3ffa6d
--- /dev/null
+++ b/internal/smart/suggested.go
@@ -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
+}
diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts
index 5344897..fc9dbbb 100644
--- a/web/src/api/schema.d.ts
+++ b/web/src/api/schema.d.ts
@@ -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:
- {items.map((p) => (
-
+ {items.map((p) => (
+
+ {title}
+
+ {describeRules(t, suggested.rules).map((line) => (
+
+ {query.data &&