feat(mixes): a picture for each mix, a collage of album covers

- The server says which albums stand for a mix (album_ids): up to 4 albums that have a cover, by different artists, with most of the songs the mix draws from. The list gives them for every mix and a mix gives its own.
- The Mixes page shows the collage on each card (a 2 by 2 collage with four covers, the first one alone with fewer, the rings with none), and the page of a mix shows it in its header.
- Nothing is fetched for it: a mix has a picture once the covers of its albums were looked up.
This commit is contained in:
tgiachi 2026-11-13 09:58:04 +01:00
commit 1ad0d718c8
7 changed files with 414 additions and 53 deletions

View file

@ -19,11 +19,12 @@ type mixHandlers struct {
}
type mixJSON struct {
ID string `json:"id"`
Kind string `json:"kind"`
Title string `json:"title"`
Genre *string `json:"genre"`
Artists []string `json:"artists"`
ID string `json:"id"`
Kind string `json:"kind"`
Title string `json:"title"`
Genre *string `json:"genre"`
Artists []string `json:"artists"`
AlbumIDs []int64 `json:"album_ids"`
}
type mixWithTracksJSON struct {
@ -37,6 +38,10 @@ func toMixJSON(m mixes.Mix) mixJSON {
if out.Artists == nil {
out.Artists = []string{}
}
out.AlbumIDs = m.AlbumIDs
if out.AlbumIDs == nil {
out.AlbumIDs = []int64{}
}
if m.Genre != "" {
g := m.Genre
out.Genre = &g

View file

@ -236,3 +236,53 @@ func TestAMixIsSavedAsAPlaylistWithTheSongsThatWereShown(t *testing.T) {
t.Errorf("playlists = %v, want 2", list.Body["total"])
}
}
func TestMixesSayWhichAlbumsStandForThem(t *testing.T) {
m := newMixAPI(t)
r := do(t, m.h, "GET", "/api/v1/mixes", m.alice, nil)
for _, x := range r.Body["items"].([]any) {
if ids, ok := x.(map[string]any)["album_ids"].([]any); !ok || len(ids) != 0 {
t.Fatalf("with no cover a mix has an empty list: %v", x)
}
}
// Five of the eight rock albums (one for each artist) get a cover; a mix shows four.
rows, err := m.db.Query("SELECT DISTINCT t.album_id FROM tracks t WHERE t.title LIKE 'rock song%' ORDER BY t.album_id")
if err != nil {
t.Fatal(err)
}
var albums []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
t.Fatal(err)
}
albums = append(albums, id)
}
rows.Close()
if len(albums) != 8 {
t.Fatalf("albums = %v", albums)
}
for _, id := range albums[:5] {
if _, err := m.db.Exec("DELETE FROM images WHERE kind = 'album' AND owner_id = ?", id); err != nil {
t.Fatal(err)
}
if _, err := m.db.Exec("INSERT INTO images (kind, owner_id, status, checked_at) VALUES ('album', ?, 'ok', 1)", id); err != nil {
t.Fatal(err)
}
}
want := []any{float64(albums[0]), float64(albums[1]), float64(albums[2]), float64(albums[3])}
list := do(t, m.h, "GET", "/api/v1/mixes", m.alice, nil)
var got []any
for _, x := range list.Body["items"].([]any) {
if x.(map[string]any)["id"] == "genre:rock" {
got = x.(map[string]any)["album_ids"].([]any)
}
}
if !slices.Equal(got, want) {
t.Errorf("rock albums = %v, want %v", got, want)
}
one := m.get(t, "genre:rock", "")
if ids := one.Body["album_ids"].([]any); !slices.Equal(ids, want) {
t.Errorf("album_ids of the mix = %v", one.Body["album_ids"])
}
}

View file

@ -3364,13 +3364,21 @@ components:
Mix:
type: object
additionalProperties: false
required: [id, kind, title, genre, artists]
required: [id, kind, title, genre, artists, album_ids]
properties:
id: {type: string, description: "`favourites`, `rediscover`, `unheard` or `genre:<name>`."}
kind: {type: string, enum: [genre, favourites, rediscover, unheard]}
title: {type: string, description: In English.}
genre: {type: string, nullable: true, description: "The genre, for a genre mix; null for the others."}
artists: {type: array, items: {type: string}, description: "A few of the artists it has, up to 3."}
album_ids:
type: array
maxItems: 4
items: {type: integer, format: int64}
description: |
Up to 4 albums that have a cover and stand for the mix, by different artists, the ones with most songs
among those the mix draws from: their covers (`GET /albums/{id}/cover`) make the picture of the mix.
Empty when none has a cover.
MixList:
type: object
@ -3384,13 +3392,14 @@ components:
MixWithTracks:
type: object
additionalProperties: false
required: [id, kind, title, genre, artists, variant, tracks]
required: [id, kind, title, genre, artists, album_ids, variant, tracks]
properties:
id: {type: string}
kind: {type: string, enum: [genre, favourites, rediscover, unheard]}
title: {type: string}
genre: {type: string, nullable: true}
artists: {type: array, items: {type: string}}
album_ids: {type: array, maxItems: 4, items: {type: integer, format: int64}, description: "As in the list of mixes."}
variant: {type: integer, minimum: 0}
tracks:
type: array

View file

@ -41,6 +41,7 @@ const (
unheardGenres = 3 // New to you takes songs from the best genres this many
MaxVariant = 1_000_000
recentPlayFactor = 0.3
CoverAlbums = 4 // albums that stand for a mix, to make its picture
)
// Kind is what a mix is made of.
@ -67,6 +68,9 @@ type Mix struct {
Title string // in English; a client may say it in its own words from the kind and the genre
Genre string // the genre, for a genre mix
Artists []string // a few of the artists it has, up to 3
// AlbumIDs are up to CoverAlbums albums that have a cover and stand for the mix: by different artists, the
// ones with most songs among those the mix draws from. Empty when none of them has a cover.
AlbumIDs []int64
}
// Genre is a genre as the files spell it, with how many songs have it and by how many artists.
@ -104,6 +108,9 @@ type Store interface {
GenreArtists(ctx context.Context, genres []string, limit int) ([]string, error)
// ArtistGenres returns, for each artist, how many of their songs have each genre.
ArtistGenres(ctx context.Context, artistIDs []int64) (map[int64]map[string]int, error)
// Covers returns up to limit albums that have a cover, by different artists, with most playable songs
// of the filter first.
Covers(ctx context.Context, f Filter, limit int) ([]int64, error)
// Pool returns the playable songs of the filter.
Pool(ctx context.Context, f Filter) ([]TrackRef, error)
// History returns what the user did with the songs they did anything with; minListen is how
@ -350,11 +357,24 @@ func (s *Service) List(ctx context.Context, userID int64) ([]Mix, error) {
}
out := make([]Mix, len(st.defs))
for i, d := range st.defs {
out[i] = d.Mix
if out[i], err = s.withCovers(ctx, d); err != nil {
return nil, err
}
}
return out, nil
}
// withCovers gives the mix the albums that stand for it.
func (s *Service) withCovers(ctx context.Context, d definition) (Mix, error) {
ids, err := s.store.Covers(ctx, Filter{Genres: d.raw, ArtistIDs: d.artists}, CoverAlbums)
if err != nil {
return Mix{}, fmt.Errorf("read covers: %w", err)
}
m := d.Mix
m.AlbumIDs = append([]int64{}, ids...)
return m, nil
}
// Get makes one mix: its songs in order. variant 0 is the mix of the day; another number gives
// another mix of the same kind. It gives ErrNotFound for a mix the listener does not have.
func (s *Service) Get(ctx context.Context, userID int64, id string, variant int) (Mix, []catalog.Track, error) {
@ -386,7 +406,11 @@ func (s *Service) Get(ctx context.Context, userID int64, id string, variant int)
if err != nil {
return Mix{}, nil, fmt.Errorf("read songs: %w", err)
}
return def.Mix, tracks, nil
mix, err := s.withCovers(ctx, *def)
if err != nil {
return Mix{}, nil, err
}
return mix, tracks, nil
}
// candidates weighs the songs a mix may take. A song skipped lately is out, and so is every song

View file

@ -50,6 +50,21 @@ type fakeStore struct {
history map[int64]History
names map[int64]string
asked []Filter
covers map[string][]int64 // key: the first genre spelling or "artists"; the albums to give
coverAsk []Filter
}
func (f *fakeStore) Covers(_ context.Context, fl Filter, limit int) ([]int64, error) {
f.coverAsk = append(f.coverAsk, fl)
key := "artists"
if len(fl.Genres) > 0 {
key = fl.Genres[0]
}
out := f.covers[key]
if len(out) > limit {
out = out[:limit]
}
return out, nil
}
func (f *fakeStore) Genres(context.Context) ([]Genre, error) { return f.genres, nil }
@ -407,3 +422,60 @@ func TestNewToYouNeverHasASongThatWasPlayedOrSkipped(t *testing.T) {
}
}
}
// ---- the albums that stand for a mix ----
func TestEveryMixSaysWhichAlbumsStandForIt(t *testing.T) {
st := library()
st.covers = map[string][]int64{"rock": {11, 12, 13, 14, 15}, "metal": {21}, "jazz+funk": {31, 32}, "artists": {41, 42}}
recent := day.Add(-2 * 24 * time.Hour)
old := day.Add(-60 * 24 * time.Hour)
many := learned(pref(1, 5, recent), pref(2, 4, recent), pref(3, 3, old), pref(4, 2, old), pref(5, 1.5, old))
list, err := newService(st, many).List(context.Background(), 1)
if err != nil {
t.Fatal(err)
}
byID := map[string]Mix{}
for _, m := range list {
byID[m.ID] = m
}
if got := byID["genre:rock"].AlbumIDs; !slices.Equal(got, []int64{11, 12, 13, 14}) {
t.Errorf("rock = %v, want the first four", got)
}
if got := byID["genre:metal"].AlbumIDs; !slices.Equal(got, []int64{21}) {
t.Errorf("metal = %v: a mix with one album with a cover has one", got)
}
if got := byID["genre:jazz funk"].AlbumIDs; !slices.Equal(got, []int64{31, 32}) {
t.Errorf("jazz funk = %v: every spelling is asked", got)
}
if got := byID["favourites"].AlbumIDs; !slices.Equal(got, []int64{41, 42}) {
t.Errorf("favourites = %v", got)
}
if got := byID["genre:pop"].AlbumIDs; got == nil || len(got) != 0 {
t.Errorf("pop = %#v: a mix with no cover says so with an empty list, not nothing", got)
}
// What is asked is what the mix draws from.
var sawArtists, sawGenres bool
for _, f := range st.coverAsk {
sawArtists = sawArtists || len(f.ArtistIDs) > 0
sawGenres = sawGenres || len(f.Genres) > 0
}
if !sawArtists || !sawGenres {
t.Errorf("asked %+v", st.coverAsk)
}
}
func TestOneMixAsksForTheAlbumsOfItself(t *testing.T) {
st := library()
st.covers = map[string][]int64{"rock": {11, 12}}
m, _, err := newService(st, taste.Learned{}).Get(context.Background(), 1, "genre:rock", 0)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(m.AlbumIDs, []int64{11, 12}) {
t.Errorf("albums = %v", m.AlbumIDs)
}
if len(st.coverAsk) != 1 {
t.Errorf("%d questions about covers for one mix: %+v", len(st.coverAsk), st.coverAsk)
}
}

View file

@ -114,11 +114,10 @@ func (r *MixRepo) ArtistGenres(ctx context.Context, artistIDs []int64) (map[int6
return out, rows.Err()
}
// Pool returns the playable songs that have one of the genres or are by one of the artists, with
// their main artist (the one with the lowest id when there are several), in the order of their ids.
func (r *MixRepo) Pool(ctx context.Context, f mixes.Filter) ([]mixes.TrackRef, error) {
// filterCondition is the condition on a song (alias t) for a filter: it has one of the genres or is by
// one of the artists. ok is false when the filter asks for nothing.
func filterCondition(f mixes.Filter) (cond string, args []any, ok bool) {
var or []string
var args []any
if len(f.Genres) > 0 {
or = append(or, "EXISTS (SELECT 1 FROM track_genres g WHERE g.track_id = t.id AND g.genre IN (?))")
args = append(args, bun.In(f.Genres))
@ -128,12 +127,22 @@ func (r *MixRepo) Pool(ctx context.Context, f mixes.Filter) ([]mixes.TrackRef, e
args = append(args, bun.In(f.ArtistIDs))
}
if len(or) == 0 {
return "", nil, false
}
return "(" + strings.Join(or, " OR ") + ")", args, true
}
// Pool returns the playable songs that have one of the genres or are by one of the artists, with
// their main artist (the one with the lowest id when there are several), in the order of their ids.
func (r *MixRepo) Pool(ctx context.Context, f mixes.Filter) ([]mixes.TrackRef, error) {
cond, args, ok := filterCondition(f)
if !ok {
return []mixes.TrackRef{}, nil
}
vis, _ := visible("t", 0)
rows, err := r.db.QueryContext(ctx,
`SELECT t.id, COALESCE((SELECT MIN(ta.artist_id) FROM track_artists ta WHERE ta.track_id = t.id AND ta.role = 'main'), 0)
FROM tracks t WHERE `+vis+` AND (`+strings.Join(or, " OR ")+`) ORDER BY t.id`, args...)
FROM tracks t WHERE `+vis+` AND `+cond+` ORDER BY t.id`, args...)
if err != nil {
return nil, fmt.Errorf("read the pool: %w", err)
}
@ -149,6 +158,49 @@ func (r *MixRepo) Pool(ctx context.Context, f mixes.Filter) ([]mixes.TrackRef, e
return out, rows.Err()
}
// Covers returns up to limit albums that have a cover and playable songs of the filter, the album with
// most of them first, one for each artist (an album with no artist stands for itself).
func (r *MixRepo) Covers(ctx context.Context, f mixes.Filter, limit int) ([]int64, error) {
cond, args, ok := filterCondition(f)
if !ok || limit <= 0 {
return []int64{}, nil
}
vis, _ := visible("t", 0)
// More albums than wanted are read: the ones of an artist that already has one are dropped below.
rows, err := r.db.QueryContext(ctx,
`SELECT a.id, a.artist_id, COUNT(DISTINCT t.id) AS n
FROM albums a
JOIN images i ON i.kind = 'album' AND i.owner_id = a.id AND i.status = 'ok'
JOIN tracks t ON t.album_id = a.id
WHERE `+vis+` AND `+cond+`
GROUP BY a.id, a.artist_id ORDER BY n DESC, a.id LIMIT ?`, append(args, limit*10)...)
if err != nil {
return nil, fmt.Errorf("read covers: %w", err)
}
defer rows.Close()
out := []int64{}
seen := map[int64]bool{}
for rows.Next() {
var (
id, n int64
artist sql.NullInt64
)
if err := rows.Scan(&id, &artist, &n); err != nil {
return nil, err
}
if artist.Valid {
if seen[artist.Int64] {
continue
}
seen[artist.Int64] = true
}
if len(out) < limit {
out = append(out, id)
}
}
return out, rows.Err()
}
// History returns what the user did with each song they did anything with. A play counts as a
// listen when it was completed or lasted minListen; a skip counts as a skip only when it came
// before the listener had heard that much (as in the taste model).

View file

@ -268,3 +268,82 @@ func TestMixRepoTracksComeInTheOrderAskedWithoutTheOnesThatCannotBePlayed(t *tes
}
})
}
// cover gives an album a cover record with the status.
func (e *mixEnv) cover(album int64, status string) {
e.t.Helper()
if _, err := e.db.Exec("DELETE FROM images WHERE kind = 'album' AND owner_id = ?", album); err != nil { // the scan may have made one
e.t.Fatal(err)
}
if _, err := e.db.Exec("INSERT INTO images (kind, owner_id, status, checked_at) VALUES ('album', ?, ?, 1)", album, status); err != nil {
e.t.Fatal(err)
}
}
func (e *mixEnv) albumOf(title string) int64 {
e.t.Helper()
var id int64
if err := e.db.QueryRow("SELECT album_id FROM tracks WHERE id = ?", e.tracks[title]).Scan(&id); err != nil {
e.t.Fatal(err)
}
return id
}
func TestMixRepoCoversAreAlbumsWithACoverByDifferentArtistsWithMostSongsFirst(t *testing.T) {
songs := []mixSong{
{"r1", "Queen", []string{"rock"}}, {"r2", "Queen", []string{"rock"}}, {"r3", "Queen", []string{"rock"}},
{"k1", "Kiss", []string{"rock"}}, {"k2", "Kiss", []string{"rock"}},
{"a1", "ABBA", []string{"rock"}},
{"m1", "Slayer", []string{"metal"}}, {"m2", "Slayer", []string{"metal"}},
{"p1", "Pooh", []string{"pop"}},
}
mixBackends(t, songs, func(t *testing.T, e *mixEnv) {
ctx := context.Background()
queen, kiss, abba, slayer := e.albumOf("r1"), e.albumOf("k1"), e.albumOf("a1"), e.albumOf("m1")
// A second album of Queen, with one song, and a cover too: the artist is not shown twice.
var second int64
if err := e.db.QueryRow("INSERT INTO albums (title, artist_id, title_key, search_key) SELECT 'Second', artist_id, 'second', 'second' FROM albums WHERE id = ? RETURNING id", queen).Scan(&second); err != nil {
t.Fatal(err)
}
if _, err := e.db.Exec("UPDATE tracks SET album_id = ? WHERE id = ?", second, e.tracks["r3"]); err != nil {
t.Fatal(err)
}
e.cover(queen, "ok")
e.cover(second, "ok")
e.cover(kiss, "ok")
e.cover(abba, "none") // no cover
e.cover(slayer, "ok") // another genre
got, err := e.repo.Covers(ctx, mixes.Filter{Genres: []string{"rock"}}, 4)
if err != nil {
t.Fatal(err)
}
if want := []int64{queen, kiss}; !slices.Equal(got, want) {
t.Errorf("rock = %v, want %v: Queen once (the album with most songs), Kiss, and not the album with no cover", got, want)
}
if got, _ := e.repo.Covers(ctx, mixes.Filter{Genres: []string{"rock"}}, 1); !slices.Equal(got, []int64{queen}) {
t.Errorf("limit 1 = %v", got)
}
// By artist, and by genre or artist together.
got, _ = e.repo.Covers(ctx, mixes.Filter{ArtistIDs: []int64{e.artist["Slayer"]}}, 4)
if !slices.Equal(got, []int64{slayer}) {
t.Errorf("artist = %v", got)
}
got, _ = e.repo.Covers(ctx, mixes.Filter{Genres: []string{"metal"}, ArtistIDs: []int64{e.artist["Kiss"]}}, 4)
if len(got) != 2 {
t.Errorf("metal or Kiss = %v, want two albums", got)
}
// Nothing asked for, nothing given.
if got, _ := e.repo.Covers(ctx, mixes.Filter{}, 4); len(got) != 0 {
t.Errorf("no filter = %v", got)
}
// An album whose songs are all gone is not offered.
if _, err := e.db.Exec("UPDATE audio_files SET missing_at = 1 WHERE track_id IN (?, ?)", e.tracks["k1"], e.tracks["k2"]); err != nil {
t.Fatal(err)
}
got, _ = e.repo.Covers(ctx, mixes.Filter{Genres: []string{"rock"}}, 4)
if !slices.Equal(got, []int64{queen}) {
t.Errorf("after Kiss's files went = %v", got)
}
})
}