From 94dbf57544db8d01b0d03ed491792e5acc0d8c61 Mon Sep 17 00:00:00 2001
From: tgiachi {t('mixes.with', { artists: mix.artists.join(', ') })} {t('playlists.meta', { count: mix.tracks.length, duration: formatTime(duration) })}
+ {t('mixes.saved', { name: save.data.name })}
+
+ {t('mixes.open')}
+
+
+ {t(errorMessageKey(save.error instanceof ApiError ? save.error.code : 'unknown'))}
+ ` 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.
- **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.
@@ -292,6 +293,7 @@ Everything lives under `/api/v1`. Bodies are JSON. Errors always look like `{"er
| signed in | `GET /listens` | Your own history, newest first, with `counted` per event. Query: `limit`, `offset`, `counted=true`. |
| signed in | `GET /discover` | Artists you may like, with a score and its parts. Query: `seed` (an artist id, up to 5 times), `limit` (default 20, max 30), `in_library=true\|false`. |
| signed in | `GET`, `HEAD /albums/{id}/cover` | The cover of an album, a JPEG made from your own files. Query: `size=small\|large`. Also accepts `?access_token=`. |
+| signed in | `GET /mixes`, `GET /mixes/{id}`, `POST /mixes/{id}/playlist` | Your mixes: list them, read one (query `variant`), keep one as a playlist. Made for you alone, from your history and your genres; nothing is stored. |
| signed in | `GET /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. |
| signed in | `GET /wishlist`, `PUT /wishlist/{id}`, `DELETE /wishlist/{id}` | Your wishlist: list it (query `limit`, `offset`), add an artist, take one off. |
@@ -378,6 +380,7 @@ internal/taste/ what the listener likes, learned from the listening histo
internal/discover/ the score of an artist you may like, and the suggestions
internal/feedback/ the wishlist and the artists a user is not interested in
internal/playlists/ the playlists of each user
+internal/mixes/ the mixes made for a listener, by genre and by listening
internal/images/ covers made from the pictures in the user's own files
internal/usersettings/ the settings that belong to one user
internal/storage/ SQLite and PostgreSQL through bun, the repositories
diff --git a/cmd/sondad/main.go b/cmd/sondad/main.go
index b727355..e3649ad 100644
--- a/cmd/sondad/main.go
+++ b/cmd/sondad/main.go
@@ -27,6 +27,7 @@ import (
"codeberg.org/squidd/sonda/internal/jobs"
"codeberg.org/squidd/sonda/internal/library"
"codeberg.org/squidd/sonda/internal/listening"
+ "codeberg.org/squidd/sonda/internal/mixes"
"codeberg.org/squidd/sonda/internal/playlists"
"codeberg.org/squidd/sonda/internal/providers"
"codeberg.org/squidd/sonda/internal/providers/commons"
@@ -291,6 +292,7 @@ func run() error {
Discover: discover.NewService(tasteService, discoveries, tags, tasteRepo, userSettings, feedbacks, weights),
Feedback: feedbacks,
Playlists: playlists.NewService(storage.NewPlaylistRepo(db)),
+ Mixes: mixes.NewService(storage.NewMixRepo(db), tasteService, cfg.Listening.MinListen()),
Images: pictures,
CoversJob: jobs.Runner{Ctx: ctx, Job: images.NewCoversJob(pictures, imageRepo)},
ArtistImagesJob: jobs.Runner{Ctx: ctx, Job: images.NewArtistImagesJob(pictures, imageRepo)},
diff --git a/internal/api/http/api_test.go b/internal/api/http/api_test.go
index 7eda8af..7a733f2 100644
--- a/internal/api/http/api_test.go
+++ b/internal/api/http/api_test.go
@@ -26,6 +26,7 @@ import (
"codeberg.org/squidd/sonda/internal/jobs"
"codeberg.org/squidd/sonda/internal/library"
"codeberg.org/squidd/sonda/internal/listening"
+ "codeberg.org/squidd/sonda/internal/mixes"
"codeberg.org/squidd/sonda/internal/playlists"
"codeberg.org/squidd/sonda/internal/providers"
"codeberg.org/squidd/sonda/internal/storage"
@@ -106,6 +107,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
feedbackSvc := feedback.NewService(storage.NewFeedbackRepo(db))
deps.Feedback = feedbackSvc
deps.Playlists = playlists.NewService(storage.NewPlaylistRepo(db))
+ deps.Mixes = mixes.NewService(storage.NewMixRepo(db), deps.Taste.(mixes.Taster), 20*time.Second)
imageRepo := storage.NewImageRepo(db)
imageSvc := images.NewService(filepath.Join(t.TempDir(), "data"), imageRepo, imageRepo)
deps.Images, deps.ArtistImages = imageSvc, imageSvc
diff --git a/internal/api/http/contract_test.go b/internal/api/http/contract_test.go
index dd8c5be..49dc3db 100644
--- a/internal/api/http/contract_test.go
+++ b/internal/api/http/contract_test.go
@@ -822,6 +822,9 @@ func TestResponsesMatchTheSpec(t *testing.T) {
// ---- duplicate songs ----
c.duplicates(t, token, libID)
+ // ---- mixes ----
+ c.mixes(t, token, libID)
+
// ---- every operation in the spec was exercised ----
var missing []string
for _, op := range specOperations(loadSpec(t)) {
@@ -979,3 +982,47 @@ func (c *contract) addOrphan(libraryID string) orphanIDs {
}
return orphanIDs{album: strconv.FormatInt(album, 10), track: strconv.FormatInt(track, 10)}
}
+
+// mixes exercises the mixes. The library gets 40 songs of one genre by 6 artists, enough for a
+// genre mix; they are added last so that nothing that counts songs sees them.
+func (c *contract) mixes(t *testing.T, token, libID string) {
+ t.Helper()
+ ctx := context.Background()
+ repo := storage.NewLibraryRepo(c.db)
+ for i := 0; i < 40; i++ {
+ artist := "Mix artist " + strconv.Itoa(i%6)
+ title := "Mix song " + strconv.Itoa(i)
+ f := library.ParsedFile{
+ FileInfo: library.FileInfo{RelPath: "mixes/" + title + ".flac", Size: 100, MTimeUnix: 1},
+ Metadata: library.Metadata{
+ Tags: library.Tags{Title: title, Album: "Mix album", AlbumArtist: artist, Artists: []string{artist}, TrackNo: i + 1, DiscNo: 1, Genres: []string{"synthwave"}},
+ Properties: library.Properties{Format: "flac", DurationMs: 60000, SampleRate: 44100},
+ },
+ }
+ if _, err := repo.SaveFile(ctx, mustInt(t, libID), f, 0); err != nil {
+ t.Fatal(err)
+ }
+ }
+ c.expect(c.call("GET", "/mixes", "", nil), 401, "mixes without a token", "unauthorized")
+ list := c.expect(c.call("GET", "/mixes", token, nil), 200, "list mixes")
+ var found bool
+ for _, x := range list["items"].([]any) {
+ if x.(map[string]any)["id"] == "genre:synthwave" {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("mixes = %v, want a synthwave mix", list)
+ }
+ mix := c.expect(c.call("GET", "/mixes/genre%3Asynthwave", token, nil), 200, "get a mix")
+ if len(mix["tracks"].([]any)) != 40 {
+ t.Fatalf("mix = %v", mix)
+ }
+ c.expect(c.call("GET", "/mixes/genre%3Asynthwave?variant=3", token, nil), 200, "get another variant")
+ c.expect(c.call("GET", "/mixes/genre%3Asynthwave?variant=-1", token, nil), 400, "a negative variant", "invalid_input")
+ c.expect(c.call("GET", "/mixes/genre%3Apolka", token, nil), 404, "an unknown mix", "mix_not_found")
+ c.expect(c.call("POST", "/mixes/genre%3Asynthwave/playlist", token, map[string]any{"name": "Synth", "variant": 3}), 201, "save a mix as a playlist")
+ c.expect(c.call("POST", "/mixes/genre%3Asynthwave/playlist", token, nil), 201, "save a mix with no body")
+ c.expect(c.call("POST", "/mixes/genre%3Apolka/playlist", token, nil), 404, "save an unknown mix", "mix_not_found")
+ c.expect(c.call("POST", "/mixes/genre%3Asynthwave/playlist", token, map[string]any{"variant": -1}), 400, "save with a negative variant", "invalid_input")
+}
diff --git a/internal/api/http/handlers_mixes.go b/internal/api/http/handlers_mixes.go
new file mode 100644
index 0000000..de90ca9
--- /dev/null
+++ b/internal/api/http/handlers_mixes.go
@@ -0,0 +1,152 @@
+package httpapi
+
+import (
+ "errors"
+ "net/http"
+ "strings"
+
+ "github.com/gin-gonic/gin"
+
+ "codeberg.org/squidd/sonda/internal/catalog"
+ "codeberg.org/squidd/sonda/internal/mixes"
+)
+
+// mixHandlers serve the mixes made for the signed-in user. They are worked out from that user's
+// own history and the genres of the music, and never stored.
+type mixHandlers struct {
+ svc mixService
+ playlists playlistService
+}
+
+type mixJSON struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ Title string `json:"title"`
+ Genre *string `json:"genre"`
+ Artists []string `json:"artists"`
+}
+
+type mixWithTracksJSON struct {
+ mixJSON
+ Variant int `json:"variant"`
+ Tracks []trackJSON `json:"tracks"`
+}
+
+func toMixJSON(m mixes.Mix) mixJSON {
+ out := mixJSON{ID: m.ID, Kind: string(m.Kind), Title: m.Title, Artists: m.Artists}
+ if out.Artists == nil {
+ out.Artists = []string{}
+ }
+ if m.Genre != "" {
+ g := m.Genre
+ out.Genre = &g
+ }
+ return out
+}
+
+func toTracksJSON(tracks []catalog.Track) []trackJSON {
+ out := make([]trackJSON, len(tracks))
+ for i, t := range tracks {
+ out[i] = toTrackJSON(t)
+ }
+ return out
+}
+
+func writeMixError(c *gin.Context, err error) {
+ switch {
+ case errors.Is(err, mixes.ErrNotFound):
+ writeError(c, http.StatusNotFound, "mix_not_found", "no such mix")
+ case errors.Is(err, mixes.ErrInvalidInput):
+ writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
+ default:
+ _ = c.Error(err)
+ writeError(c, http.StatusInternalServerError, "internal", "internal error")
+ }
+}
+
+// variantOf reads the variant of the query string: a whole number from 0 up, 0 when absent.
+func variantOf(c *gin.Context) (int, bool) {
+ v, ok := queryInt(c, "variant")
+ if !ok {
+ return 0, false
+ }
+ if v < 0 || v > mixes.MaxVariant {
+ writeError(c, http.StatusBadRequest, "invalid_input", "variant must be a whole number from 0 up")
+ return 0, false
+ }
+ return int(v), true
+}
+
+func (h *mixHandlers) list(c *gin.Context) {
+ list, err := h.svc.List(c.Request.Context(), currentUserID(c))
+ if err != nil {
+ writeMixError(c, err)
+ return
+ }
+ out := make([]mixJSON, len(list))
+ for i, m := range list {
+ out[i] = toMixJSON(m)
+ }
+ c.JSON(http.StatusOK, gin.H{"items": out})
+}
+
+func (h *mixHandlers) get(c *gin.Context) {
+ variant, ok := variantOf(c)
+ if !ok {
+ return
+ }
+ m, tracks, err := h.svc.Get(c.Request.Context(), currentUserID(c), c.Param("id"), variant)
+ if err != nil {
+ writeMixError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, mixWithTracksJSON{mixJSON: toMixJSON(m), Variant: variant, Tracks: toTracksJSON(tracks)})
+}
+
+type saveMixRequest struct {
+ Name string `json:"name"` // blank: the title of the mix
+ Variant *int `json:"variant"` // absent: the mix of the day
+}
+
+// save makes a playlist of the songs of a mix, the ones that variant shows. A save that fails
+// half way leaves no playlist behind.
+func (h *mixHandlers) save(c *gin.Context) {
+ var req saveMixRequest
+ if c.Request.ContentLength != 0 && !bindJSON(c, &req) {
+ return
+ }
+ variant := 0
+ if req.Variant != nil {
+ variant = *req.Variant
+ }
+ ctx, user := c.Request.Context(), currentUserID(c)
+ m, tracks, err := h.svc.Get(ctx, user, c.Param("id"), variant)
+ if err != nil {
+ writeMixError(c, err)
+ return
+ }
+ if len(tracks) == 0 {
+ writeError(c, http.StatusUnprocessableEntity, "mix_empty", "the mix has no songs to save")
+ return
+ }
+ name := req.Name
+ if strings.TrimSpace(name) == "" {
+ name = m.Title
+ }
+ pl, err := h.playlists.Create(ctx, user, name, "")
+ if err != nil {
+ writePlaylistError(c, err)
+ return
+ }
+ ids := make([]int64, len(tracks))
+ for i, t := range tracks {
+ ids[i] = t.ID
+ }
+ filled, err := h.playlists.AddTracks(ctx, user, pl.ID, ids, nil)
+ if err != nil {
+ _ = h.playlists.Delete(ctx, user, pl.ID)
+ writePlaylistError(c, err)
+ return
+ }
+ c.JSON(http.StatusCreated, toPlaylistJSON(filled))
+}
diff --git a/internal/api/http/mixes_test.go b/internal/api/http/mixes_test.go
new file mode 100644
index 0000000..39414ac
--- /dev/null
+++ b/internal/api/http/mixes_test.go
@@ -0,0 +1,238 @@
+package httpapi
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/url"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/uptrace/bun"
+
+ "codeberg.org/squidd/sonda/internal/library"
+ "codeberg.org/squidd/sonda/internal/listening"
+ "codeberg.org/squidd/sonda/internal/storage"
+)
+
+// mixAPI is a server with 40 rock songs by 8 artists and 36 hard rock songs by 6, and a user.
+type mixAPI struct {
+ h http.Handler
+ db *bun.DB
+ alice string
+}
+
+func newMixAPI(t *testing.T) *mixAPI {
+ t.Helper()
+ h, db := newTestEnvDB(t, func(*Deps, *bun.DB) {})
+ alice := registerAndLogin(t, h)
+ ctx := context.Background()
+ lib := storage.NewLibraryRepo(db)
+ l, err := lib.CreateLibrary(ctx, "m", "/lib/m")
+ if err != nil {
+ t.Fatal(err)
+ }
+ add := func(prefix string, n, artists int, genres ...string) {
+ for i := 0; i < n; i++ {
+ artist := fmt.Sprintf("%s artist %d", prefix, i%artists)
+ title := fmt.Sprintf("%s song %d", prefix, i)
+ f := library.ParsedFile{
+ FileInfo: library.FileInfo{RelPath: prefix + "/" + title + ".flac", Size: 100, MTimeUnix: 1},
+ Metadata: library.Metadata{
+ Tags: library.Tags{Title: title, Album: prefix + " album", AlbumArtist: artist, Artists: []string{artist}, TrackNo: i + 1, DiscNo: 1, Genres: genres},
+ Properties: library.Properties{Format: "flac", DurationMs: 60000, SampleRate: 44100},
+ },
+ }
+ if _, err := lib.SaveFile(ctx, l.ID, f, 0); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ add("rock", 40, 8, "rock")
+ add("hard", 36, 6, "hard rock")
+ return &mixAPI{h: h, db: db, alice: alice}
+}
+
+func (m *mixAPI) get(t *testing.T, id, query string) resp {
+ t.Helper()
+ return do(t, m.h, "GET", "/api/v1/mixes/"+url.PathEscape(id)+query, m.alice, nil)
+}
+
+func trackIDs(t *testing.T, r resp) []float64 {
+ t.Helper()
+ var out []float64
+ for _, x := range r.Body["tracks"].([]any) {
+ out = append(out, x.(map[string]any)["id"].(float64))
+ }
+ return out
+}
+
+func TestMixRoutesNeedASignedInUser(t *testing.T) {
+ m := newMixAPI(t)
+ for _, rt := range []struct{ method, path string }{
+ {"GET", "/api/v1/mixes"}, {"GET", "/api/v1/mixes/genre:rock"}, {"POST", "/api/v1/mixes/genre:rock/playlist"},
+ } {
+ if r := do(t, m.h, rt.method, rt.path, "", nil); r.Code != http.StatusUnauthorized {
+ t.Errorf("%s %s without a token: %d", rt.method, rt.path, r.Code)
+ }
+ }
+}
+
+func TestTheListOfMixesHasTheGenresOfTheLibrary(t *testing.T) {
+ m := newMixAPI(t)
+ r := do(t, m.h, "GET", "/api/v1/mixes", m.alice, nil)
+ if r.Code != http.StatusOK {
+ t.Fatalf("list: %d %v", r.Code, r.Body)
+ }
+ byID := map[string]map[string]any{}
+ for _, x := range r.Body["items"].([]any) {
+ mix := x.(map[string]any)
+ byID[mix["id"].(string)] = mix
+ }
+ rock := byID["genre:rock"]
+ if rock == nil || rock["kind"] != "genre" || rock["title"] != "Rock Mix" || rock["genre"] != "rock" || len(rock["artists"].([]any)) != 3 {
+ t.Fatalf("rock = %v in %v", rock, byID)
+ }
+ if byID["genre:hard rock"] == nil {
+ t.Errorf("hard rock is missing: %v", byID)
+ }
+ unheard := byID["unheard"]
+ if unheard == nil || unheard["kind"] != "unheard" || unheard["genre"] != nil {
+ t.Errorf("unheard = %v", unheard)
+ }
+ if byID["favourites"] != nil || byID["rediscover"] != nil {
+ t.Errorf("mixes that need history are there with none: %v", byID)
+ }
+}
+
+func TestAMixHasItsSongsAndStaysTheSameUntilAnotherVariantIsAsked(t *testing.T) {
+ m := newMixAPI(t)
+ r := m.get(t, "genre:rock", "")
+ if r.Code != http.StatusOK || r.Body["id"] != "genre:rock" || r.Body["variant"] != float64(0) || r.Body["title"] != "Rock Mix" {
+ t.Fatalf("mix: %d %v", r.Code, r.Body)
+ }
+ first := r.Body["tracks"].([]any)[0].(map[string]any)
+ if first["title"] == nil || first["album"] == nil || len(first["artists"].([]any)) != 1 {
+ t.Errorf("a song of the mix = %v", first)
+ }
+ ids := trackIDs(t, r)
+ if len(ids) != 40 {
+ t.Fatalf("%d songs, want the 40 there are (fewer than 50)", len(ids))
+ }
+ if again := trackIDs(t, m.get(t, "genre:rock", "")); !slices.Equal(ids, again) {
+ t.Error("the same mix twice is not the same")
+ }
+ v1 := m.get(t, "genre:rock", "?variant=1")
+ if v1.Body["variant"] != float64(1) || slices.Equal(ids, trackIDs(t, v1)) {
+ t.Errorf("variant 1 = %v", v1.Body["variant"])
+ }
+ // Spaces in the id come percent-encoded.
+ if r := m.get(t, "genre:hard rock", ""); r.Code != http.StatusOK || len(trackIDs(t, r)) != 36 {
+ t.Errorf("hard rock: %d", r.Code)
+ }
+}
+
+func TestSongsSkippedLatelyAreLeftOutOfAMix(t *testing.T) {
+ m := newMixAPI(t)
+ var ids []int64
+ rows, err := m.db.Query("SELECT id FROM tracks WHERE title LIKE 'rock song%' ORDER BY id LIMIT 10")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for rows.Next() {
+ var id int64
+ if err := rows.Scan(&id); err != nil {
+ t.Fatal(err)
+ }
+ ids = append(ids, id)
+ }
+ rows.Close()
+ var userID int64
+ if err := m.db.QueryRow("SELECT id FROM users").Scan(&userID); err != nil {
+ t.Fatal(err)
+ }
+ rec := listening.NewService(storage.NewListeningRepo(m.db), 20*time.Second)
+ record := func(id int64, typ listening.EventType, played int64, key string) {
+ t.Helper()
+ if _, err := rec.Record(context.Background(), listening.Event{UserID: userID, TrackID: id, Type: typ, DurationPlayedMs: played, OccurredAt: time.Now().Add(-time.Hour), IdempotencyKey: key}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i, id := range ids {
+ record(id, listening.Skip, 3000, fmt.Sprintf("skip%d", i))
+ }
+ // The artists also have songs they listened to to the end, so none of them is an avoided artist:
+ // what is left out is the skipped songs and nothing else.
+ for a := 0; a < 8; a++ {
+ for _, n := range []int{16, 24, 32} {
+ var id int64
+ if err := m.db.QueryRow("SELECT id FROM tracks WHERE title = ?", fmt.Sprintf("rock song %d", a+n)).Scan(&id); err != nil {
+ t.Fatal(err)
+ }
+ record(id, listening.Complete, 59000, fmt.Sprintf("done%d-%d", a, n))
+ }
+ }
+ got := trackIDs(t, m.get(t, "genre:rock", ""))
+ if len(got) != 30 {
+ t.Fatalf("%d songs, want 30: ten were skipped", len(got))
+ }
+ for _, id := range got {
+ if slices.Contains(ids, int64(id)) {
+ t.Fatalf("song %v was skipped an hour ago", id)
+ }
+ }
+}
+
+func TestAnUnknownMixOrABadVariantIsRefused(t *testing.T) {
+ m := newMixAPI(t)
+ for _, id := range []string{"nope", "genre:polka", "genre:other", "favourites", "rediscover"} {
+ if r := m.get(t, id, ""); r.Code != http.StatusNotFound || errCode(r) != "mix_not_found" {
+ t.Errorf("%s: %d %v, want 404 mix_not_found", id, r.Code, r.Body)
+ }
+ }
+ for _, q := range []string{"?variant=abc", "?variant=-1", "?variant=99999999999"} {
+ if r := m.get(t, "genre:rock", q); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
+ t.Errorf("%s: %d %v, want 400 invalid_input", q, r.Code, r.Body)
+ }
+ }
+}
+
+func TestAMixIsSavedAsAPlaylistWithTheSongsThatWereShown(t *testing.T) {
+ m := newMixAPI(t)
+ shown := trackIDs(t, m.get(t, "genre:rock", "?variant=2"))
+
+ r := do(t, m.h, "POST", "/api/v1/mixes/genre:rock/playlist", m.alice, map[string]any{"variant": 2})
+ if r.Code != http.StatusCreated || r.Body["name"] != "Rock Mix" || r.Body["track_count"] != float64(len(shown)) {
+ t.Fatalf("save: %d %v", r.Code, r.Body)
+ }
+ pl := int64(r.Body["id"].(float64))
+ items := do(t, m.h, "GET", "/api/v1/playlists/"+id(pl)+"/tracks?limit=200", m.alice, nil)
+ var got []float64
+ for _, it := range items.Body["items"].([]any) {
+ got = append(got, it.(map[string]any)["track"].(map[string]any)["id"].(float64))
+ }
+ if !slices.Equal(got, shown) {
+ t.Errorf("the playlist has %v, the mix showed %v", got, shown)
+ }
+
+ named := do(t, m.h, "POST", "/api/v1/mixes/genre:rock/playlist", m.alice, map[string]any{"name": " For the car "})
+ if named.Code != http.StatusCreated || named.Body["name"] != "For the car" {
+ t.Errorf("named: %d %v", named.Code, named.Body)
+ }
+ if r := do(t, m.h, "POST", "/api/v1/mixes/genre:rock/playlist", m.alice, map[string]any{"name": strings.Repeat("a", 201)}); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
+ t.Errorf("a name that is too long: %d %v", r.Code, r.Body)
+ }
+ if r := do(t, m.h, "POST", "/api/v1/mixes/nope/playlist", m.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "mix_not_found" {
+ t.Errorf("unknown mix: %d %v", r.Code, r.Body)
+ }
+ if r := do(t, m.h, "POST", "/api/v1/mixes/genre:rock/playlist", m.alice, map[string]any{"variant": -3}); r.Code != http.StatusBadRequest {
+ t.Errorf("a negative variant: %d", r.Code)
+ }
+ // A refused save leaves no playlist behind: the two that worked are all there is.
+ list := do(t, m.h, "GET", "/api/v1/playlists", m.alice, nil)
+ if list.Body["total"] != float64(2) {
+ t.Errorf("playlists = %v, want 2", list.Body["total"])
+ }
+}
diff --git a/internal/api/http/router.go b/internal/api/http/router.go
index 3ec66af..52d06a4 100644
--- a/internal/api/http/router.go
+++ b/internal/api/http/router.go
@@ -24,6 +24,7 @@ import (
"codeberg.org/squidd/sonda/internal/jobs"
"codeberg.org/squidd/sonda/internal/library"
"codeberg.org/squidd/sonda/internal/listening"
+ "codeberg.org/squidd/sonda/internal/mixes"
"codeberg.org/squidd/sonda/internal/playlists"
"codeberg.org/squidd/sonda/internal/providers"
"codeberg.org/squidd/sonda/internal/streaming"
@@ -99,6 +100,12 @@ type playlistService interface {
MoveItem(ctx context.Context, userID, id, itemID int64, position int) error
}
+// mixService is what the handlers need from mixes.Service.
+type mixService interface {
+ List(ctx context.Context, userID int64) ([]mixes.Mix, error)
+ Get(ctx context.Context, userID int64, id string, variant int) (mixes.Mix, []catalog.Track, error)
+}
+
type feedbackService interface {
Add(ctx context.Context, userID, artistID int64, kind feedback.Kind) error
Remove(ctx context.Context, userID, artistID int64, kind feedback.Kind) error
@@ -172,6 +179,7 @@ type Deps struct {
Discover discoverService
Feedback feedbackService
Playlists playlistService
+ Mixes mixService
Images coverService
CoversJob jobService
ArtistImagesJob jobService
@@ -251,6 +259,10 @@ func NewRouter(d Deps) *gin.Engine {
protected.POST("/playlists/:id/tracks", pl.addTracks)
protected.DELETE("/playlists/:id/tracks/:item", pl.removeItem)
protected.PATCH("/playlists/:id/tracks/:item", pl.moveItem)
+ mx := &mixHandlers{svc: d.Mixes, playlists: d.Playlists}
+ protected.GET("/mixes", mx.list)
+ protected.GET("/mixes/:id", mx.get)
+ protected.POST("/mixes/:id/playlist", mx.save)
protected.GET("/wishlist", fb.list(feedback.Wishlist))
protected.PUT("/wishlist/:id", fb.add(feedback.Wishlist))
protected.DELETE("/wishlist/:id", fb.remove(feedback.Wishlist))
diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml
index 3714dde..f327ba5 100644
--- a/internal/api/openapi/openapi.yaml
+++ b/internal/api/openapi/openapi.yaml
@@ -37,6 +37,8 @@ tags:
description: What Sonda has learned from your listening, and the settings that are yours.
- name: Playlists
description: Ordered lists of tracks that belong to one user.
+ - name: Mixes
+ description: Playlists made for you, from what you listen to and from the genres of your music.
- name: Discovery
description: Music outside the library, from external providers an admin switched on, and suggestions scored for you.
- name: Providers
@@ -1196,6 +1198,94 @@ paths:
application/json:
schema: {$ref: '#/components/schemas/Error'}
+ /mixes:
+ get:
+ tags: [Mixes]
+ operationId: listMixes
+ summary: Your mixes
+ description: |
+ Playlists that Sonda makes for you, from what you listen to and from the genres of your
+ music. First the ones made for you (`favourites`, `rediscover`: they need some listening
+ history, so they are missing without it; `unheard`, the songs you never played), then
+ one `genre` mix for each genre of the library that has at least 30 songs by at least 4
+ artists, the genres you play most first (and the biggest after them). Spellings of a genre
+ that differ only by case or punctuation are one genre, and `other` and `unknown` are not
+ genres. `title` is in English; a client may say it in its own words from `kind` and
+ `genre`. Nothing is stored and nothing is sent to a provider: a mix is worked out from your
+ own history and the genre tags of your files, for you alone.
+ security: [{bearerAuth: []}]
+ responses:
+ '200':
+ description: The mixes.
+ content:
+ application/json:
+ schema: {$ref: '#/components/schemas/MixList'}
+ '401': {$ref: '#/components/responses/Unauthorized'}
+
+ /mixes/{id}:
+ parameters:
+ - {$ref: '#/components/parameters/MixId'}
+ get:
+ tags: [Mixes]
+ operationId: getMix
+ summary: A mix and its songs
+ description: |
+ Up to 50 songs, at most 3 by one artist and never two by the same artist in a row. They
+ are picked by weighted chance: the artists you play weigh more, songs you never played
+ a bit more, songs played in the last days less, and songs you skipped in the last two weeks
+ and artists you avoid do not come at all. The same mix comes back all day: it changes
+ the next day, or when you ask for another `variant`. The id of a genre mix has the genre
+ in it (`genre:hard rock`), so it must be percent-encoded in the path. A mix you do not
+ have (a genre that is too small, `favourites` with no history) is `mix_not_found`.
+ security: [{bearerAuth: []}]
+ parameters:
+ - name: variant
+ in: query
+ description: Another mix of the same kind, from 0 (the mix of the day) up.
+ schema: {type: integer, minimum: 0, maximum: 1000000, default: 0}
+ responses:
+ '200':
+ description: The mix.
+ content:
+ application/json:
+ schema: {$ref: '#/components/schemas/MixWithTracks'}
+ '400': {$ref: '#/components/responses/InvalidInput'}
+ '401': {$ref: '#/components/responses/Unauthorized'}
+ '404': {$ref: '#/components/responses/MixNotFound'}
+
+ /mixes/{id}/playlist:
+ parameters:
+ - {$ref: '#/components/parameters/MixId'}
+ post:
+ tags: [Mixes]
+ operationId: saveMix
+ summary: Keep a mix as a playlist
+ description: |
+ Makes a playlist of your own with the songs that `variant` of the mix has now, in the
+ same order. The playlist is a copy: it does not change afterwards, and is yours to edit.
+ The body is optional.
+ security: [{bearerAuth: []}]
+ requestBody:
+ required: false
+ content:
+ application/json:
+ schema: {$ref: '#/components/schemas/SaveMix'}
+ 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/MixNotFound'}
+ '409': {$ref: '#/components/responses/PlaylistLimit'}
+ '422':
+ description: The mix has no songs to save (`mix_empty`).
+ content:
+ application/json:
+ schema: {$ref: '#/components/schemas/Error'}
+
/playlists:
get:
tags: [Playlists]
@@ -2409,6 +2499,12 @@ components:
name: offset
in: query
schema: {type: integer, minimum: 0, default: 0}
+ MixId:
+ name: id
+ in: path
+ required: true
+ description: "`favourites`, `rediscover`, `unheard` or `genre:
{title}
+ {mix.artists.length > 0 && {t('nav.mixes')}
+ {query.isError ? (
+
+ {errorLine(t, preview.error)} +
+ ) : preview.isPending ? ( +{t('smart.editor.previewNone')}
+ ) : ( + <> +{t('smart.editor.previewCount', { count: tracks.length, duration: formatTime(duration) })}
+{t('smart.editor.previewMore', { count: tracks.length - 8 })}
} + > + )} +{hint}
} + {genres.length > 0 && ( +{p.description}
} +{t('smart.songs', { count: tracks.length, duration: formatTime(duration) })}
} ++ {t('smart.saved', { name: save.data.name })} + + {t('smart.open')} + +
+ )} + {(save.isError || del.isError) && ( ++ {errorLine(t, save.error ?? del.error)} +
+ )} + + {query.isError ? ( +{t('mixes.with', { artists: mix.artists.join(', ') })}
} -{t('playlists.meta', { count: mix.tracks.length, duration: formatTime(duration) })}
-{t('mixes.with', { artists: mix.artists.join(', ') })}
} +{t('playlists.meta', { count: mix.tracks.length, duration: formatTime(duration) })}
+{description}
+{t('smart.songs', { count: tracks.length, duration: formatTime(duration) })}
} ++ {t('smart.saved', { name: save.data.name })} + + {t('smart.open')} + +
+ )} + {(save.isError || make.isError) && ( ++ {errorLine(t, save.error ?? make.error)} +
+ )} + + {query.isPending ?