feat: playlists with a cover, a collage of the covers of their albums

- A playlist says which albums stand for it (album_ids): up to 4 albums that have a cover, in the order they first appear in it, each once, read for a whole page of playlists in one query. An empty one has an empty list.
- The Playlists page is a grid of cards with the collage, and the page of a playlist shows it in its header. The pages of a smart playlist and of a suggested one show a collage of the albums of their first songs.
- Nothing is fetched for it: the covers are the ones the library already has.
This commit is contained in:
tgiachi 2026-11-13 11:32:01 +01:00
commit a1e192066c
6 changed files with 441 additions and 120 deletions

View file

@ -23,6 +23,7 @@ type playlistJSON struct {
DurationMs int64 `json:"duration_ms"`
CreatedAt *string `json:"created_at"`
UpdatedAt *string `json:"updated_at"`
AlbumIDs []int64 `json:"album_ids"`
}
type playlistPageJSON struct {
@ -48,9 +49,13 @@ type playlistItemsJSON struct {
}
func toPlaylistJSON(p playlists.Playlist) playlistJSON {
albums := p.AlbumIDs
if albums == nil {
albums = []int64{}
}
return playlistJSON{
ID: p.ID, Name: p.Name, Description: p.Description, TrackCount: p.TrackCount, DurationMs: p.DurationMs,
CreatedAt: rfc3339(p.CreatedAt), UpdatedAt: rfc3339(p.UpdatedAt),
CreatedAt: rfc3339(p.CreatedAt), UpdatedAt: rfc3339(p.UpdatedAt), AlbumIDs: albums,
}
}

View file

@ -0,0 +1,57 @@
package httpapi
import (
"fmt"
"net/http"
"slices"
"testing"
)
func TestAPlaylistSaysWhichAlbumsStandForIt(t *testing.T) {
m := newMixAPI(t)
id := m.playlistWithSongs(t, "hard song", 6) // six songs by six artists: six albums
empty := do(t, m.h, "POST", "/api/v1/playlists", m.alice, map[string]any{"name": "Empty"})
if ids, ok := empty.Body["album_ids"].([]any); !ok || len(ids) != 0 {
t.Fatalf("an empty playlist = %v, want an empty list", empty.Body["album_ids"])
}
var albums []int64
rows, err := m.db.Query(`SELECT t.album_id FROM tracks t JOIN playlist_items i ON i.track_id = t.id WHERE i.playlist_id = ? ORDER BY i.position`, id)
if err != nil {
t.Fatal(err)
}
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) != 6 {
t.Fatalf("albums = %v", albums)
}
// The second, third, fifth and sixth have a cover; the first and the fourth do not.
for _, i := range []int{1, 2, 4, 5} {
if _, err := m.db.Exec("DELETE FROM images WHERE kind = 'album' AND owner_id = ?", albums[i]); err != nil {
t.Fatal(err)
}
if _, err := m.db.Exec("INSERT INTO images (kind, owner_id, status, checked_at) VALUES ('album', ?, 'ok', 1)", albums[i]); err != nil {
t.Fatal(err)
}
}
want := []any{float64(albums[1]), float64(albums[2]), float64(albums[4]), float64(albums[5])}
one := do(t, m.h, "GET", fmt.Sprintf("/api/v1/playlists/%d", id), m.alice, nil)
if one.Code != http.StatusOK || !slices.Equal(one.Body["album_ids"].([]any), want) {
t.Errorf("get = %d %v, want %v", one.Code, one.Body["album_ids"], want)
}
list := do(t, m.h, "GET", "/api/v1/playlists", m.alice, nil)
var got []any
for _, x := range list.Body["items"].([]any) {
if x.(map[string]any)["id"] == float64(id) {
got = x.(map[string]any)["album_ids"].([]any)
}
}
if !slices.Equal(got, want) {
t.Errorf("list = %v, want %v", got, want)
}
}

View file

@ -3856,7 +3856,7 @@ components:
Playlist:
type: object
additionalProperties: false
required: [id, name, description, track_count, duration_ms, created_at, updated_at]
required: [id, name, description, track_count, duration_ms, created_at, updated_at, album_ids]
properties:
id: {type: integer, format: int64}
name: {type: string}
@ -3865,6 +3865,14 @@ components:
duration_ms: {type: integer, format: int64, description: "Their total length."}
created_at: {type: string, format: date-time}
updated_at: {type: string, format: date-time, description: "When it was last changed, tracks included."}
album_ids:
type: array
maxItems: 4
items: {type: integer, format: int64}
description: |
Up to 4 albums that have a cover and stand for the playlist, in the order they first appear in it, each once:
their covers (`GET /albums/{id}/cover`) make the picture of the playlist. Empty when none of its songs has
an album with a cover.
PlaylistPage:
type: object

View file

@ -50,8 +50,14 @@ type Playlist struct {
DurationMs int64
CreatedAt time.Time
UpdatedAt time.Time
// AlbumIDs are up to MaxCoverAlbums albums that have a cover and stand for the playlist, in the order they first
// appear in it, each once. Empty when none of its songs has an album with a cover.
AlbumIDs []int64
}
// MaxCoverAlbums is how many albums make the picture of a playlist.
const MaxCoverAlbums = 4
// Item is one place of a playlist. Available says whether the track has a file to play.
type Item struct {
ID int64

View file

@ -65,6 +65,43 @@ func scanSummary(rows interface{ Scan(...any) error }) (playlists.Playlist, erro
return p, nil
}
// attachCovers gives each playlist the albums that stand for it: the first albums that have a cover, in the order they
// appear in the playlist, each once, up to playlists.MaxCoverAlbums. Playlists with none get an empty list.
func attachCovers(ctx context.Context, db bun.IDB, ps []playlists.Playlist) error {
if len(ps) == 0 {
return nil
}
index := map[int64]int{}
ids := make([]int64, len(ps))
for i := range ps {
ps[i].AlbumIDs = []int64{}
index[ps[i].ID] = i
ids[i] = ps[i].ID
}
rows, err := db.QueryContext(ctx,
`SELECT playlist_id, album_id FROM (
SELECT g.playlist_id, g.album_id, ROW_NUMBER() OVER (PARTITION BY g.playlist_id ORDER BY g.first, g.album_id) AS n FROM (
SELECT i.playlist_id, t.album_id, MIN(i.position) AS first
FROM playlist_items i
JOIN tracks t ON t.id = i.track_id
JOIN images im ON im.kind = 'album' AND im.owner_id = t.album_id AND im.status = 'ok'
WHERE i.playlist_id IN (?) AND t.album_id IS NOT NULL
GROUP BY i.playlist_id, t.album_id) g) r
WHERE n <= ? ORDER BY playlist_id, n`, bun.In(ids), playlists.MaxCoverAlbums)
if err != nil {
return fmt.Errorf("read the albums of playlists: %w", err)
}
defer rows.Close()
for rows.Next() {
var playlist, album int64
if err := rows.Scan(&playlist, &album); err != nil {
return err
}
ps[index[playlist]].AlbumIDs = append(ps[index[playlist]].AlbumIDs, album)
}
return rows.Err()
}
// summary reads one playlist of a user, or playlists.ErrNotFound.
func summary(ctx context.Context, db bun.IDB, userID, id int64) (playlists.Playlist, error) {
p, err := scanSummary(db.QueryRowContext(ctx, summarySelect+" WHERE p.id = ? AND p.user_id = ? GROUP BY p.id", id, userID))
@ -74,7 +111,11 @@ func summary(ctx context.Context, db bun.IDB, userID, id int64) (playlists.Playl
if err != nil {
return playlists.Playlist{}, fmt.Errorf("read playlist: %w", err)
}
return p, nil
one := []playlists.Playlist{p}
if err := attachCovers(ctx, db, one); err != nil {
return playlists.Playlist{}, err
}
return one[0], nil
}
// touch sets the updated time of a playlist of the user and so takes its row lock, which is what
@ -151,7 +192,14 @@ func (r *PlaylistRepo) List(ctx context.Context, userID int64, limit, offset int
}
out = append(out, p)
}
return out, total, rows.Err()
if err := rows.Err(); err != nil {
return nil, 0, err
}
rows.Close()
if err := attachCovers(ctx, r.db, out); err != nil {
return nil, 0, err
}
return out, total, nil
}
// Get returns a playlist of the user.

View file

@ -447,3 +447,97 @@ func TestAddingAtTheSameTimeKeepsEveryPositionUnique(t *testing.T) {
}
})
}
// ---- the albums that stand for a playlist ----
func TestAPlaylistSaysWhichAlbumsStandForItInTheOrderTheyAppear(t *testing.T) {
songs := []mixSong{
{"s1", "A1", nil}, {"s2", "A2", nil}, {"s3", "A3", nil}, {"s4", "A4", nil}, {"s5", "A5", nil}, {"s6", "A6", nil}, {"s7", "A7", nil},
}
mixBackends(t, songs, func(t *testing.T, e *mixEnv) {
ctx := context.Background()
repo := NewPlaylistRepo(e.db)
alb := func(title string) int64 { return e.albumOf(title) }
// A3 has no cover; a second song of A1 comes later; A7 has a cover but comes last, after four others.
for _, s := range []string{"s1", "s2", "s4", "s5", "s6", "s7"} {
e.cover(alb(s), "ok")
}
e.cover(alb("s3"), "none")
p, err := repo.Create(ctx, e.user, "Mixed", "", time.Unix(1_700_000_000, 0))
if err != nil {
t.Fatal(err)
}
if p.AlbumIDs == nil || len(p.AlbumIDs) != 0 {
t.Errorf("an empty playlist = %#v, want an empty list", p.AlbumIDs)
}
order := []string{"s3", "s2", "s1", "s2", "s4", "s5", "s6", "s7"} // s3 has no cover, s2 comes twice
ids := make([]int64, len(order))
for i, s := range order {
ids[i] = e.tracks[s]
}
got, err := repo.AddTracks(ctx, e.user, p.ID, ids, nil, time.Unix(1_700_000_100, 0))
if err != nil {
t.Fatal(err)
}
want := []int64{alb("s2"), alb("s1"), alb("s4"), alb("s5")}
if !slices.Equal(got.AlbumIDs, want) {
t.Errorf("after adding = %v, want %v: in order, each once, no cover skipped, four at most", got.AlbumIDs, want)
}
if again, _ := repo.Get(ctx, e.user, p.ID); !slices.Equal(again.AlbumIDs, want) {
t.Errorf("get = %v", again.AlbumIDs)
}
list, _, err := repo.List(ctx, e.user, 10, 0)
if err != nil || len(list) != 1 || !slices.Equal(list[0].AlbumIDs, want) {
t.Errorf("list = %+v, %v", list, err)
}
// Taking the first songs out moves the albums.
items, _, _ := repo.Items(ctx, e.user, p.ID, 100, 0)
if err := repo.RemoveItem(ctx, e.user, p.ID, items[1].ID, time.Unix(1_700_000_200, 0)); err != nil { // the first s2
t.Fatal(err)
}
if after, _ := repo.Get(ctx, e.user, p.ID); !slices.Equal(after.AlbumIDs, []int64{alb("s1"), alb("s2"), alb("s4"), alb("s5")}) {
t.Errorf("after taking a song out = %v", after.AlbumIDs)
}
})
}
func TestSeveralPlaylistsOfAPageEachGetTheirOwnAlbums(t *testing.T) {
songs := []mixSong{{"s1", "A1", nil}, {"s2", "A2", nil}, {"s3", "A3", nil}}
mixBackends(t, songs, func(t *testing.T, e *mixEnv) {
ctx := context.Background()
repo := NewPlaylistRepo(e.db)
for _, s := range []string{"s1", "s2", "s3"} {
e.cover(e.albumOf(s), "ok")
}
mk := func(name string, titles ...string) {
t.Helper()
p, err := repo.Create(ctx, e.user, name, "", time.Unix(1_700_000_000, 0))
if err != nil {
t.Fatal(err)
}
ids := make([]int64, len(titles))
for i, s := range titles {
ids[i] = e.tracks[s]
}
if len(ids) > 0 {
if _, err := repo.AddTracks(ctx, e.user, p.ID, ids, nil, time.Unix(1_700_000_000, 0)); err != nil {
t.Fatal(err)
}
}
}
mk("one", "s1", "s2")
mk("two", "s3")
mk("none")
list, _, err := repo.List(ctx, e.user, 10, 0)
if err != nil || len(list) != 3 {
t.Fatalf("%+v, %v", list, err)
}
byName := map[string][]int64{}
for _, p := range list {
byName[p.Name] = p.AlbumIDs
}
if !slices.Equal(byName["one"], []int64{e.albumOf("s1"), e.albumOf("s2")}) || !slices.Equal(byName["two"], []int64{e.albumOf("s3")}) || byName["none"] == nil || len(byName["none"]) != 0 {
t.Errorf("albums = %v", byName)
}
})
}