feat(smart): covers on the Smart playlists page
- GET /smart-playlists/{id}/covers and GET /smart-playlists/suggested/{key}/covers say which albums stand for a smart playlist: up to 4 albums that have a cover, in the order of the songs the rules give now (for the variant asked), each once. They are worked out apart from the songs, and the answer may be kept for a few minutes.
- The cards of the Smart playlists page are a grid with the collage. The list shows at once and each card asks for its own covers after that, showing the rings until they arrive or when they cannot be read.
- The pages of a smart playlist and of a suggested one use the same covers for the variant on screen, so only albums that have a cover are shown.
This commit is contained in:
parent
0d69ae48de
commit
82b92eaf08
10 changed files with 648 additions and 67 deletions
|
|
@ -1040,6 +1040,8 @@ func (c *contract) smartPlaylists(t *testing.T, token string) {
|
|||
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/covers", token, nil), 200, "the covers of a suggested one")
|
||||
c.expect(c.call("GET", "/smart-playlists/suggested/nonsense/covers", token, nil), 404, "the covers of an unknown suggested one", "suggested_not_found")
|
||||
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")
|
||||
|
|
@ -1066,6 +1068,9 @@ func (c *contract) smartPlaylists(t *testing.T, token string) {
|
|||
t.Fatalf("smart playlist songs = %v", got)
|
||||
}
|
||||
c.expect(c.call("GET", "/smart-playlists/"+id+"/tracks?variant=2", token, nil), 200, "the songs, another variant")
|
||||
c.expect(c.call("GET", "/smart-playlists/"+id+"/covers?variant=2", token, nil), 200, "the covers of a smart playlist")
|
||||
c.expect(c.call("GET", "/smart-playlists/999999/covers", token, nil), 404, "the covers of an unknown smart playlist", "smart_playlist_not_found")
|
||||
c.expect(c.call("GET", "/smart-playlists/"+id+"/covers?variant=-1", token, nil), 400, "the covers with a bad variant", "invalid_input")
|
||||
c.expect(c.call("GET", "/smart-playlists/"+id+"/tracks?variant=-1", token, nil), 400, "a negative variant", "invalid_input")
|
||||
c.expect(c.call("GET", "/smart-playlists/999999/tracks", token, nil), 404, "the songs of an unknown smart playlist", "smart_playlist_not_found")
|
||||
c.expect(c.call("POST", "/smart-playlists/preview", token, map[string]any{"rules": map[string]any{"min_duration_sec": 30, "liked_artists_only": false}, "sort": "most_played", "limit": 5, "variant": 1}), 200, "preview rules")
|
||||
|
|
|
|||
|
|
@ -335,3 +335,38 @@ func (h *smartHandlers) suggestedSave(c *gin.Context) {
|
|||
name, description := automaticName(c, h.naming, req.AutoName, req.Lang, "smart", tracks, sg.Rules.Summary(), name)
|
||||
keepAsPlaylist(c, h.playlists, user, name, description, tracks)
|
||||
}
|
||||
|
||||
// covers says which albums stand for a smart playlist, for its picture: up to 4 albums that have a cover, in the order of
|
||||
// the songs it gives now. It is apart from the songs so that a list of smart playlists need not wait for all of them.
|
||||
func (h *smartHandlers) covers(c *gin.Context) {
|
||||
id, ok := pathID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
variant, ok := variantOf(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
albums, err := h.svc.Covers(c.Request.Context(), currentUserID(c), id, variant)
|
||||
if err != nil {
|
||||
writeSmartError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "private, max-age=300")
|
||||
c.JSON(http.StatusOK, gin.H{"album_ids": albums})
|
||||
}
|
||||
|
||||
// suggestedCovers is covers for a suggested smart playlist.
|
||||
func (h *smartHandlers) suggestedCovers(c *gin.Context) {
|
||||
variant, ok := variantOf(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
albums, err := h.svc.SuggestedCovers(c.Request.Context(), currentUserID(c), c.Param("key"), variant)
|
||||
if err != nil {
|
||||
writeSuggestedError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "private, max-age=300")
|
||||
c.JSON(http.StatusOK, gin.H{"album_ids": albums})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -127,6 +127,8 @@ type smartService interface {
|
|||
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)
|
||||
Covers(ctx context.Context, userID, id int64, variant int) ([]int64, error)
|
||||
SuggestedCovers(ctx context.Context, userID int64, key string, variant int) ([]int64, error)
|
||||
}
|
||||
|
||||
type feedbackService interface {
|
||||
|
|
@ -300,11 +302,13 @@ func NewRouter(d Deps) *gin.Engine {
|
|||
protected.POST("/smart-playlists/preview", sm.preview)
|
||||
protected.GET("/smart-playlists/suggested", sm.suggestedList)
|
||||
protected.GET("/smart-playlists/suggested/:key/tracks", sm.suggestedTracks)
|
||||
protected.GET("/smart-playlists/suggested/:key/covers", sm.suggestedCovers)
|
||||
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)
|
||||
protected.GET("/smart-playlists/:id/tracks", sm.tracks)
|
||||
protected.GET("/smart-playlists/:id/covers", sm.covers)
|
||||
protected.POST("/smart-playlists/:id/playlist", sm.save)
|
||||
protected.GET("/wishlist", fb.list(feedback.Wishlist))
|
||||
protected.PUT("/wishlist/:id", fb.add(feedback.Wishlist))
|
||||
|
|
|
|||
|
|
@ -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 + "/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", "/api/v1/genres"}, {"GET", sp + "/suggested"}, {"GET", sp + "/suggested/never-played/tracks"}, {"GET", sp + "/suggested/never-played/covers"}, {"GET", sp + "/1/covers"}, {"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 {
|
||||
|
|
@ -397,3 +397,92 @@ func TestPlaysInTheLastDaysAreCountedForTheListenerOnly(t *testing.T) {
|
|||
t.Errorf("a negative window: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheCoversOfASmartPlaylistAreThoseOfTheSongsItGivesNow(t *testing.T) {
|
||||
m := newMixAPI(t)
|
||||
// Songs of "rock song N" come in six albums; give covers to some of them.
|
||||
rows, err := m.db.Query("SELECT DISTINCT t.album_id FROM tracks t WHERE t.title LIKE 'hard song%' ORDER BY t.album_id")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var albums []int64
|
||||
for rows.Next() {
|
||||
var a int64
|
||||
if err := rows.Scan(&a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
albums = append(albums, a)
|
||||
}
|
||||
rows.Close()
|
||||
if len(albums) < 5 {
|
||||
t.Fatalf("albums = %v", albums)
|
||||
}
|
||||
for _, a := range albums[:5] {
|
||||
_, _ = m.db.Exec("DELETE FROM images WHERE kind = 'album' AND owner_id = ?", a)
|
||||
if _, err := m.db.Exec("INSERT INTO images (kind, owner_id, status, checked_at) VALUES ('album', ?, 'ok', 1)", a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
id := smartMade(t, m, map[string]any{"name": "Hard", "sort": "title", "limit": 20, "rules": map[string]any{"genres": []string{"hard rock"}}})
|
||||
r := do(t, m.h, "GET", fmt.Sprintf("%s/%d/covers", sp, id), m.alice, nil)
|
||||
ids, _ := r.Body["album_ids"].([]any)
|
||||
if r.Code != http.StatusOK || len(ids) != 4 {
|
||||
t.Fatalf("covers: %d %v", r.Code, r.Body)
|
||||
}
|
||||
// They are albums of the songs on screen for the same variant.
|
||||
shown := map[float64]bool{}
|
||||
tracks := do(t, m.h, "GET", fmt.Sprintf("%s/%d/tracks", sp, id), m.alice, nil)
|
||||
for _, x := range tracks.Body["tracks"].([]any) {
|
||||
shown[x.(map[string]any)["album"].(map[string]any)["id"].(float64)] = true
|
||||
}
|
||||
for _, a := range ids {
|
||||
if !shown[a.(float64)] {
|
||||
t.Errorf("album %v is not one of the songs of the playlist", a)
|
||||
}
|
||||
}
|
||||
// Rules that give nothing have an empty list, and an unknown playlist is not found.
|
||||
none := smartMade(t, m, map[string]any{"name": "Polka", "rules": map[string]any{"genres": []string{"polka"}}})
|
||||
if r := do(t, m.h, "GET", fmt.Sprintf("%s/%d/covers", sp, none), m.alice, nil); r.Code != http.StatusOK || len(r.Body["album_ids"].([]any)) != 0 {
|
||||
t.Errorf("no songs: %d %v", r.Code, r.Body)
|
||||
}
|
||||
if r := do(t, m.h, "GET", sp+"/999999/covers", m.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "smart_playlist_not_found" {
|
||||
t.Errorf("unknown: %d %v", r.Code, r.Body)
|
||||
}
|
||||
if r := do(t, m.h, "GET", fmt.Sprintf("%s/%d/covers?variant=-1", sp, id), m.alice, nil); r.Code != http.StatusBadRequest {
|
||||
t.Errorf("a negative variant: %d", r.Code)
|
||||
}
|
||||
// Somebody else's is not found either.
|
||||
_, bob := addUser(t, m.h, m.alice, "bob", false)
|
||||
if r := do(t, m.h, "GET", fmt.Sprintf("%s/%d/covers", sp, id), bob, nil); r.Code != http.StatusNotFound {
|
||||
t.Errorf("another user's: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheCoversOfASuggestedOneAreAskedAsOnesOwn(t *testing.T) {
|
||||
m := newMixAPI(t)
|
||||
rows, err := m.db.Query("SELECT DISTINCT album_id FROM tracks WHERE album_id IS NOT NULL ORDER BY album_id LIMIT 3")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var a int64
|
||||
if err := rows.Scan(&a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = m.db.Exec("DELETE FROM images WHERE kind = 'album' AND owner_id = ?", a)
|
||||
if _, err := m.db.Exec("INSERT INTO images (kind, owner_id, status, checked_at) VALUES ('album', ?, 'ok', 1)", a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
r := do(t, m.h, "GET", sp+"/suggested/never-played/covers", m.alice, nil)
|
||||
if r.Code != http.StatusOK || len(r.Body["album_ids"].([]any)) == 0 || len(r.Body["album_ids"].([]any)) > 4 {
|
||||
t.Errorf("covers: %d %v", r.Code, r.Body)
|
||||
}
|
||||
if r := do(t, m.h, "GET", sp+"/suggested/nonsense/covers", 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/covers?variant=x", m.alice, nil); r.Code != http.StatusBadRequest {
|
||||
t.Errorf("bad variant: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1426,6 +1426,34 @@ paths:
|
|||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404': {$ref: '#/components/responses/SuggestedNotFound'}
|
||||
|
||||
/smart-playlists/suggested/{key}/covers:
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/SuggestedKey'}
|
||||
get:
|
||||
tags: [Smart playlists]
|
||||
operationId: getSuggestedSmartPlaylistCovers
|
||||
summary: The covers of a suggested smart playlist
|
||||
description: |
|
||||
Up to 4 albums that have a cover and stand for it, in the order of the songs the rules give now (the ones of
|
||||
`variant`), each once: their covers (`GET /albums/{id}/cover`) make its picture. It is worked out apart from the
|
||||
songs so that a list of smart playlists can show the rest without waiting for the rules of every one of them; the
|
||||
answer may be kept by the client for a few minutes. Empty when none of the songs has an album with a cover.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- name: variant
|
||||
in: query
|
||||
description: The variant that is on screen, from 0 (the songs of the day) up.
|
||||
schema: {type: integer, minimum: 0, maximum: 1000000, default: 0}
|
||||
responses:
|
||||
'200':
|
||||
description: The albums.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/SmartCovers'}
|
||||
'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'}
|
||||
|
|
@ -1540,6 +1568,34 @@ paths:
|
|||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404': {$ref: '#/components/responses/SmartPlaylistNotFound'}
|
||||
|
||||
/smart-playlists/{id}/covers:
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/Id'}
|
||||
get:
|
||||
tags: [Smart playlists]
|
||||
operationId: getSmartPlaylistCovers
|
||||
summary: The covers of a smart playlist
|
||||
description: |
|
||||
Up to 4 albums that have a cover and stand for it, in the order of the songs the rules give now (the ones of
|
||||
`variant`), each once: their covers (`GET /albums/{id}/cover`) make its picture. It is worked out apart from the
|
||||
songs so that a list of smart playlists can show the rest without waiting for the rules of every one of them; the
|
||||
answer may be kept by the client for a few minutes. Empty when none of the songs has an album with a cover.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- name: variant
|
||||
in: query
|
||||
description: The variant that is on screen, from 0 (the songs of the day) up.
|
||||
schema: {type: integer, minimum: 0, maximum: 1000000, default: 0}
|
||||
responses:
|
||||
'200':
|
||||
description: The albums.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/SmartCovers'}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404': {$ref: '#/components/responses/SmartPlaylistNotFound'}
|
||||
|
||||
/smart-playlists/{id}/playlist:
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/Id'}
|
||||
|
|
@ -3833,6 +3889,13 @@ components:
|
|||
limit: {type: integer, minimum: 1, maximum: 500, default: 50}
|
||||
variant: {type: integer, minimum: 0, maximum: 1000000, default: 0}
|
||||
|
||||
SmartCovers:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [album_ids]
|
||||
properties:
|
||||
album_ids: {type: array, maxItems: 4, items: {type: integer, format: int64}}
|
||||
|
||||
SmartTracks:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
|
|
|
|||
|
|
@ -186,6 +186,8 @@ type Store interface {
|
|||
Plays(ctx context.Context, userID int64, minListen time.Duration, since time.Time) (map[int64]int, error)
|
||||
// Tracks returns the songs in the order given, leaving out any that cannot be played.
|
||||
Tracks(ctx context.Context, ids []int64) ([]catalog.Track, error)
|
||||
// AlbumCovers returns, for the songs in the order given, the albums that have a cover, each once, up to limit.
|
||||
AlbumCovers(ctx context.Context, trackIDs []int64, limit int) ([]int64, error)
|
||||
}
|
||||
|
||||
// Taster says what the listener likes: *taste.Service.
|
||||
|
|
@ -519,7 +521,21 @@ func spellings(all []mixes.Genre, genres []string) []string {
|
|||
return out
|
||||
}
|
||||
|
||||
// run works the songs out: the rules, the order and the limit, then the details of the songs.
|
||||
func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort, limit, variant int) ([]catalog.Track, error) {
|
||||
picked, err := s.pick(ctx, userID, id, r, order, limit, variant)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tracks, err := s.store.Tracks(ctx, picked)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read songs: %w", err)
|
||||
}
|
||||
return tracks, nil
|
||||
}
|
||||
|
||||
// pick works out which songs the rules give, in order, as their ids.
|
||||
func (s *Service) pick(ctx context.Context, userID, id int64, r Rules, order Sort, limit, variant int) ([]int64, error) {
|
||||
f := Filter{
|
||||
ArtistIDs: r.ArtistIDs, NotArtistIDs: r.NotArtistIDs, AlbumIDs: r.AlbumIDs, NotAlbumIDs: r.NotAlbumIDs,
|
||||
Formats: r.Formats, MinBitrateKbps: r.MinBitrateKbps,
|
||||
|
|
@ -531,7 +547,7 @@ func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort
|
|||
}
|
||||
f.Genres, f.NotGenres = spellings(all, r.Genres), spellings(all, r.NotGenres)
|
||||
if len(r.Genres) > 0 && len(f.Genres) == 0 {
|
||||
return []catalog.Track{}, nil // no file has any of the genres
|
||||
return []int64{}, nil // no file has any of the genres
|
||||
}
|
||||
}
|
||||
cands, err := s.store.Candidates(ctx, f)
|
||||
|
|
@ -599,11 +615,42 @@ func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort
|
|||
for i, c := range kept {
|
||||
picked[i] = c.TrackID
|
||||
}
|
||||
tracks, err := s.store.Tracks(ctx, picked)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read songs: %w", err)
|
||||
return picked, nil
|
||||
}
|
||||
|
||||
// MaxCoverAlbums is how many albums make the picture of a smart playlist.
|
||||
const MaxCoverAlbums = 4
|
||||
|
||||
// Covers says which albums stand for a smart playlist: up to MaxCoverAlbums albums that have a cover, in the order of the
|
||||
// songs it gives now (the ones of variant), each once. It is the picture of the playlist, and is worked out apart from its
|
||||
// songs so that a list of playlists need not wait for all of them.
|
||||
func (s *Service) Covers(ctx context.Context, userID, id int64, variant int) ([]int64, error) {
|
||||
if err := checkVariant(variant); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tracks, nil
|
||||
p, err := s.store.Get(ctx, userID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
picked, err := s.pick(ctx, userID, p.ID, p.Rules, p.Sort, p.Limit, variant)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.albumCovers(ctx, picked)
|
||||
}
|
||||
|
||||
func (s *Service) albumCovers(ctx context.Context, picked []int64) ([]int64, error) {
|
||||
if len(picked) == 0 {
|
||||
return []int64{}, nil
|
||||
}
|
||||
albums, err := s.store.AlbumCovers(ctx, picked, MaxCoverAlbums)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read covers: %w", err)
|
||||
}
|
||||
if albums == nil {
|
||||
albums = []int64{}
|
||||
}
|
||||
return albums, nil
|
||||
}
|
||||
|
||||
// sortCandidates puts the songs in the order; a tie goes to the lower id. A random order sorts by the
|
||||
|
|
|
|||
|
|
@ -25,6 +25,8 @@ type fakeStore struct {
|
|||
asked []Filter
|
||||
windowed map[int64]int // plays inside the window asked for
|
||||
since []time.Time // the starts of the windows asked for
|
||||
albumOf map[int64]int64 // the album of a song that has a cover
|
||||
coverAsk [][]int64 // the songs asked about
|
||||
saved map[int64]SmartPlaylist // by id
|
||||
nextID int64
|
||||
listened int // how many times history was read
|
||||
|
|
@ -51,6 +53,18 @@ func (f *fakeStore) Plays(_ context.Context, _ int64, _ time.Duration, since tim
|
|||
return f.windowed, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) AlbumCovers(_ context.Context, trackIDs []int64, limit int) ([]int64, error) {
|
||||
f.coverAsk = append(f.coverAsk, trackIDs)
|
||||
out := []int64{}
|
||||
for _, id := range trackIDs {
|
||||
a, ok := f.albumOf[id]
|
||||
if ok && !slices.Contains(out, a) && len(out) < limit {
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Tracks(_ context.Context, ids []int64) ([]catalog.Track, error) {
|
||||
out := make([]catalog.Track, len(ids))
|
||||
for i, id := range ids {
|
||||
|
|
@ -704,3 +718,79 @@ func TestAWindowOfDaysIsChecked(t *testing.T) {
|
|||
t.Errorf("summary = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the albums that stand for a smart playlist ----
|
||||
|
||||
func TestTheAlbumsOfASmartPlaylistAreThoseOfTheSongsItGivesInOrder(t *testing.T) {
|
||||
st := newStore()
|
||||
st.cands = songs(8)
|
||||
// Songs 3, 4, 5, 6 and 7 have albums with a cover; songs 1 and 2 do not. Songs 3 and 5 share an album.
|
||||
st.albumOf = map[int64]int64{3: 30, 4: 40, 5: 30, 6: 60, 7: 70}
|
||||
svc := newService(st, taste.Learned{})
|
||||
p, err := svc.Create(context.Background(), 1, Input{Name: "All", Sort: SortTitle, Limit: 8})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := svc.Covers(context.Background(), 1, p.ID, 0)
|
||||
if err != nil || !slices.Equal(got, []int64{30, 40, 60, 70}) {
|
||||
t.Fatalf("covers = %v, %v: in the order of the songs, each album once, four at most", got, err)
|
||||
}
|
||||
// The songs asked about are the ones the playlist gives, no more.
|
||||
if len(st.coverAsk) != 1 || !slices.Equal(st.coverAsk[0], []int64{1, 2, 3, 4, 5, 6, 7, 8}) {
|
||||
t.Errorf("asked about %v", st.coverAsk)
|
||||
}
|
||||
short, _ := svc.Create(context.Background(), 1, Input{Name: "Three", Sort: SortTitle, Limit: 3})
|
||||
if got, _ := svc.Covers(context.Background(), 1, short.ID, 0); !slices.Equal(got, []int64{30}) {
|
||||
t.Errorf("the limit counts, only song 3 of the first three has a cover: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheCoversFollowTheVariantOfARandomOrderAndAreEmptyNotMissing(t *testing.T) {
|
||||
st := newStore()
|
||||
st.cands = songs(40)
|
||||
st.albumOf = map[int64]int64{}
|
||||
for i := int64(1); i <= 40; i++ {
|
||||
st.albumOf[i] = 100 + i
|
||||
}
|
||||
svc := newService(st, taste.Learned{})
|
||||
p, _ := svc.Create(context.Background(), 1, Input{Name: "Any", Sort: SortRandom, Limit: 10})
|
||||
a, _ := svc.Covers(context.Background(), 1, p.ID, 0)
|
||||
b, _ := svc.Covers(context.Background(), 1, p.ID, 0)
|
||||
c, _ := svc.Covers(context.Background(), 1, p.ID, 1)
|
||||
if !slices.Equal(a, b) || slices.Equal(a, c) {
|
||||
t.Errorf("covers of the day = %v and %v, of variant 1 = %v", a, b, c)
|
||||
}
|
||||
// They are the covers of the songs that the playlist shows for the same variant.
|
||||
_, tracks, _ := svc.Tracks(context.Background(), 1, p.ID, 1)
|
||||
var want []int64
|
||||
for _, tr := range tracks[:4] {
|
||||
want = append(want, st.albumOf[tr.ID])
|
||||
}
|
||||
if !slices.Equal(c, want) {
|
||||
t.Errorf("variant 1 covers = %v, its first songs have %v", c, want)
|
||||
}
|
||||
st.albumOf = nil
|
||||
if none, err := svc.Covers(context.Background(), 1, p.ID, 0); err != nil || none == nil || len(none) != 0 {
|
||||
t.Errorf("no cover at all = %#v, %v", none, err)
|
||||
}
|
||||
if _, err := svc.Covers(context.Background(), 1, 999, 0); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("unknown playlist: %v", err)
|
||||
}
|
||||
if _, err := svc.Covers(context.Background(), 1, p.ID, MaxVariant+1); !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("variant: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheCoversOfASuggestedOneAreThoseOfItsSongs(t *testing.T) {
|
||||
st := newStore()
|
||||
st.cands = songs(6)
|
||||
st.albumOf = map[int64]int64{1: 11, 2: 12, 4: 14}
|
||||
svc := newService(st, taste.Learned{})
|
||||
got, err := svc.SuggestedCovers(context.Background(), 1, "recently-added", 0)
|
||||
if err != nil || !slices.Equal(got, []int64{11, 12, 14}) {
|
||||
t.Errorf("covers = %v, %v: the newest songs first", got, err)
|
||||
}
|
||||
if _, err := svc.SuggestedCovers(context.Background(), 1, "nonsense", 0); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("unknown key: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,6 +40,23 @@ func Suggested() []SuggestedPlaylist {
|
|||
return out
|
||||
}
|
||||
|
||||
// SuggestedCovers says which albums stand for a suggested smart playlist, as Covers does for one of the user's own.
|
||||
func (s *Service) SuggestedCovers(ctx context.Context, userID int64, key string, variant int) ([]int64, error) {
|
||||
if err := checkVariant(variant); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
i := slices.IndexFunc(suggested, func(x SuggestedPlaylist) bool { return x.Key == key })
|
||||
if i < 0 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
sg := suggested[i]
|
||||
picked, err := s.pick(ctx, userID, -int64(i+1), sg.Rules, sg.Sort, sg.Limit, variant)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.albumCovers(ctx, picked)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
|
|
|
|||
|
|
@ -191,6 +191,41 @@ func (r *SmartRepo) Plays(ctx context.Context, userID int64, minListen time.Dura
|
|||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// AlbumCovers returns, for the songs in the order given, the albums that have a cover, each once, up to limit.
|
||||
func (r *SmartRepo) AlbumCovers(ctx context.Context, trackIDs []int64, limit int) ([]int64, error) {
|
||||
out := []int64{}
|
||||
if len(trackIDs) == 0 || limit <= 0 {
|
||||
return out, nil
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx,
|
||||
`SELECT t.id, t.album_id FROM tracks t
|
||||
JOIN images im ON im.kind = 'album' AND im.owner_id = t.album_id AND im.status = 'ok'
|
||||
WHERE t.id IN (?)`, bun.In(trackIDs))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read the covers of songs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
albumOf := map[int64]int64{}
|
||||
for rows.Next() {
|
||||
var track, album int64
|
||||
if err := rows.Scan(&track, &album); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
albumOf[track] = album
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := map[int64]bool{}
|
||||
for _, id := range trackIDs {
|
||||
if a, ok := albumOf[id]; ok && !seen[a] && len(out) < limit {
|
||||
seen[a] = true
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Tracks returns the playable songs among ids, in the order given.
|
||||
func (r *SmartRepo) Tracks(ctx context.Context, ids []int64) ([]catalog.Track, error) {
|
||||
return r.mix.Tracks(ctx, ids)
|
||||
|
|
|
|||
|
|
@ -369,3 +369,46 @@ func TestSmartRepoCountsTheListensOfEachSongSinceAMoment(t *testing.T) {
|
|||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSmartRepoAlbumCoversFollowTheOrderOfTheSongsAndSkipWhatHasNoCover(t *testing.T) {
|
||||
smartBackends(t, smartSongs, func(t *testing.T, e *smartEnv) {
|
||||
ctx := context.Background()
|
||||
cover := func(album string, status string) {
|
||||
t.Helper()
|
||||
if _, err := e.db.Exec("DELETE FROM images WHERE kind = 'album' AND owner_id = ?", e.album[album]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := e.db.Exec("INSERT INTO images (kind, owner_id, status, checked_at) VALUES ('album', ?, ?, 1)", e.album[album], status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// a and b share the album News, c has Alive, d has Reign, e has Blue.
|
||||
cover("News", "ok")
|
||||
cover("Alive", "none")
|
||||
cover("Reign", "ok")
|
||||
cover("Blue", "stale")
|
||||
ids := func(names ...string) []int64 {
|
||||
out := make([]int64, len(names))
|
||||
for i, n := range names {
|
||||
out[i] = e.tracks[n]
|
||||
}
|
||||
return out
|
||||
}
|
||||
got, err := e.repo.AlbumCovers(ctx, ids("d", "c", "b", "a", "e"), 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := []int64{e.album["Reign"], e.album["News"]}; !slices.Equal(got, want) {
|
||||
t.Errorf("covers = %v, want %v: in the order of the songs, News once, no cover and a stale one left out", got, want)
|
||||
}
|
||||
if got, _ := e.repo.AlbumCovers(ctx, ids("d", "a"), 1); !slices.Equal(got, []int64{e.album["Reign"]}) {
|
||||
t.Errorf("limit 1 = %v", got)
|
||||
}
|
||||
if got, err := e.repo.AlbumCovers(ctx, nil, 4); err != nil || got == nil || len(got) != 0 {
|
||||
t.Errorf("no songs = %#v, %v", got, err)
|
||||
}
|
||||
if got, _ := e.repo.AlbumCovers(ctx, ids("c", "e"), 4); len(got) != 0 {
|
||||
t.Errorf("songs of albums with no cover = %v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue