feat(smart): GET /genres, the genres of the library to choose from

Each genre with the number of playable songs, the biggest first and by name among equals. The spellings the files have are one genre, written the way the rules compare them, and tags such as other or unknown are left out.
This commit is contained in:
tgiachi 2026-11-13 09:46:03 +01:00
commit a607070149
7 changed files with 122 additions and 1 deletions

View file

@ -1034,6 +1034,10 @@ func (c *contract) smartPlaylists(t *testing.T, token string) {
t.Helper()
rules := map[string]any{"genres": []string{"synthwave"}, "formats": []string{"flac"}, "never_played": true}
c.expect(c.call("GET", "/smart-playlists", "", nil), 401, "smart playlists without a token", "unauthorized")
genres := c.expect(c.call("GET", "/genres", token, nil), 200, "the genres of the library")
if len(genres["items"].([]any)) == 0 {
t.Fatalf("genres = %v", genres)
}
c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "", "rules": rules}), 400, "a smart playlist with no name", "invalid_input")
c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "x", "sort": "loudest"}), 400, "an unknown order", "invalid_input")
made := c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "Fresh synth", "description": "new", "rules": rules, "sort": "title", "limit": 12}), 201, "make a smart playlist")

View file

@ -233,3 +233,18 @@ func (h *smartHandlers) save(c *gin.Context) {
}
keepAsPlaylist(c, h.playlists, user, name, tracks)
}
// genres lists the genres of the library, to choose from in a rule: each with the number of songs, the
// biggest first, spellings merged the way the rules compare them.
func (h *smartHandlers) genres(c *gin.Context) {
list, err := h.svc.Genres(c.Request.Context())
if err != nil {
writeSmartError(c, err)
return
}
items := make([]gin.H, len(list))
for i, g := range list {
items[i] = gin.H{"name": g.Name, "tracks": g.Tracks}
}
c.JSON(http.StatusOK, gin.H{"items": items})
}

View file

@ -116,6 +116,7 @@ type smartService interface {
Delete(ctx context.Context, userID, id int64) error
Tracks(ctx context.Context, userID, id int64, variant int) (smart.SmartPlaylist, []catalog.Track, error)
Preview(ctx context.Context, userID int64, in smart.Input, variant int) ([]catalog.Track, error)
Genres(ctx context.Context) ([]smart.GenreCount, error)
}
type feedbackService interface {
@ -277,6 +278,7 @@ func NewRouter(d Deps) *gin.Engine {
protected.GET("/mixes/:id", mx.get)
protected.POST("/mixes/:id/playlist", mx.save)
sm := &smartHandlers{svc: d.Smart, playlists: d.Playlists}
protected.GET("/genres", sm.genres)
protected.GET("/smart-playlists", sm.list)
protected.POST("/smart-playlists", sm.create)
protected.POST("/smart-playlists/preview", sm.preview)

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", sp}, {"POST", sp}, {"POST", sp + "/preview"}, {"GET", sp + "/1"}, {"PATCH", sp + "/1"}, {"DELETE", sp + "/1"},
{"GET", "/api/v1/genres"}, {"GET", sp}, {"POST", sp}, {"POST", sp + "/preview"}, {"GET", sp + "/1"}, {"PATCH", sp + "/1"}, {"DELETE", sp + "/1"},
{"GET", sp + "/1/tracks"}, {"POST", sp + "/1/playlist"},
} {
if r := do(t, m.h, rt.method, rt.path, "", nil); r.Code != http.StatusUnauthorized {
@ -263,3 +263,19 @@ func TestASmartPlaylistIsItsOwnersAlone(t *testing.T) {
t.Errorf("alice's own changed: %d %v", r.Code, r.Body)
}
}
func TestTheGenresOfTheLibraryAreListedBiggestFirst(t *testing.T) {
m := newMixAPI(t)
r := do(t, m.h, "GET", "/api/v1/genres", m.alice, nil)
if r.Code != http.StatusOK {
t.Fatalf("genres: %d %v", r.Code, r.Body)
}
items := r.Body["items"].([]any)
if len(items) != 2 {
t.Fatalf("genres = %v", items)
}
first, second := items[0].(map[string]any), items[1].(map[string]any)
if first["name"] != "rock" || first["tracks"] != float64(40) || second["name"] != "hard rock" || second["tracks"] != float64(36) {
t.Errorf("genres = %v", items)
}
}

View file

@ -1288,6 +1288,25 @@ paths:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/genres:
get:
tags: [Smart playlists]
operationId: listGenres
summary: The genres of the library
description: |
The genres of the playable songs, to choose from in the rules of a smart playlist: each with the number
of songs, the biggest first, and by name among equals. The spellings that the files have are one genre
(`jazz+funk` and `jazz-funk` are `jazz funk`), written the way the rules compare them; tags such as
`other` or `unknown` are left out.
security: [{bearerAuth: []}]
responses:
'200':
description: The genres.
content:
application/json:
schema: {$ref: '#/components/schemas/GenreList'}
'401': {$ref: '#/components/responses/Unauthorized'}
/smart-playlists:
get:
tags: [Smart playlists]
@ -3385,6 +3404,21 @@ components:
name: {type: string, maxLength: 200, description: "The name of the playlist; blank or absent means the title of the mix."}
variant: {type: integer, minimum: 0, maximum: 1000000, description: "The variant the client showed; absent means the mix of the day."}
GenreList:
type: object
additionalProperties: false
required: [items]
properties:
items:
type: array
items:
type: object
additionalProperties: false
required: [name, tracks]
properties:
name: {type: string}
tracks: {type: integer, description: Playable songs that have the genre.}
SmartRules:
type: object
additionalProperties: false

View file

@ -432,6 +432,38 @@ func (s *Service) Update(ctx context.Context, userID, id int64, p Patch) (SmartP
return s.store.Update(ctx, userID, id, SmartPlaylist{Name: in.Name, Description: in.Description, Rules: in.Rules, Sort: in.Sort, Limit: in.Limit}, s.now())
}
// GenreCount is a genre as it is compared (see Rules) with the number of playable songs that have it.
type GenreCount struct {
Name string
Tracks int
}
// Genres returns the genres of the library to choose from in a rule, the one with most songs first, and
// by name among equals. The spellings the files have are one genre; "other" and the like are left out.
func (s *Service) Genres(ctx context.Context) ([]GenreCount, error) {
all, err := s.store.Genres(ctx)
if err != nil {
return nil, fmt.Errorf("read genres: %w", err)
}
byName := map[string]int{}
for _, g := range all {
if n := mixes.NormalizeGenre(g.Name); n != "" {
byName[n] += g.Tracks
}
}
out := make([]GenreCount, 0, len(byName))
for n, c := range byName {
out = append(out, GenreCount{n, c})
}
sort.Slice(out, func(i, j int) bool {
if out[i].Tracks != out[j].Tracks {
return out[i].Tracks > out[j].Tracks
}
return out[i].Name < out[j].Name
})
return out, nil
}
// Delete removes a smart playlist of the user.
func (s *Service) Delete(ctx context.Context, userID, id int64) error {
return s.store.Delete(ctx, userID, id)

View file

@ -499,3 +499,21 @@ func TestListLowersAPageThatIsTooBigAndRefusesNegatives(t *testing.T) {
t.Errorf("a negative offset: %v", err)
}
}
func TestGenresMergeSpellingsLeaveOutWhatIsNotAGenreAndCountTheBiggestFirst(t *testing.T) {
st := newStore()
st.genres = []mixes.Genre{
{Name: "Rock", Tracks: 30}, {Name: "rock", Tracks: 10},
{Name: "Jazz+Funk", Tracks: 5}, {Name: "jazz-funk", Tracks: 7},
{Name: "metal", Tracks: 12}, {Name: "Blues", Tracks: 12},
{Name: "other", Tracks: 99}, {Name: " ", Tracks: 4},
}
got, err := newService(st, taste.Learned{}).Genres(context.Background())
if err != nil {
t.Fatal(err)
}
want := []GenreCount{{"rock", 40}, {"blues", 12}, {"jazz funk", 12}, {"metal", 12}} // a tie goes to the name
if !slices.Equal(got, want) {
t.Errorf("got %v, want %v", got, want)
}
}