From ec017838a2cf8d0367a3b07343d43f0d9fc33654 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Mon, 23 Nov 2026 15:59:44 -0500 Subject: [PATCH] feat(playlists): playlists list their cover albums, and system mixes say what they hold Each playlist on the wire (list and get) carries cover_album_ids: up to six distinct albums with art, in the order they first appear. A shelf of playlist tiles takes each tile's first album that no tile before it shows, so no cover repeats along the shelf. System mixes are stored with a one-line description of what they are built from, written in one place so the web and Android apps show the same words. Songs like and genre mixes have none; their names say it. Co-Authored-By: Claude Opus 5.5 --- internal/api/playlists.go | 17 +++- internal/db/dbq/playlists.sql.go | 45 +++++++++ internal/db/dbq/system_playlists.sql.go | 4 +- internal/db/queries/playlists.sql | 19 ++++ internal/db/queries/system_playlists.sql | 2 +- internal/playlists/cover_albums_db_test.go | 111 +++++++++++++++++++++ internal/playlists/service.go | 41 +++++++- internal/playlists/system.go | 25 +++++ 8 files changed, 256 insertions(+), 8 deletions(-) create mode 100644 internal/playlists/cover_albums_db_test.go diff --git a/internal/api/playlists.go b/internal/api/playlists.go index a1b22da7..6e797c3a 100644 --- a/internal/api/playlists.go +++ b/internal/api/playlists.go @@ -39,10 +39,16 @@ type playlistRowView struct { Refreshable bool `json:"refreshable"` SeedArtistID *string `json:"seed_artist_id,omitempty"` CoverURL string `json:"cover_url,omitempty"` - TrackCount int32 `json:"track_count"` - DurationSec int32 `json:"duration_sec"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` + // CoverAlbumIDs are up to six distinct albums with cover art, in + // track order (each album's art is /api/albums/{id}/cover). A shelf + // of playlist tiles gives each tile the first of its albums no tile + // before it already shows, so no cover repeats along the shelf. + // Omitted when the playlist has none. + CoverAlbumIDs []string `json:"cover_album_ids,omitempty"` + TrackCount int32 `json:"track_count"` + DurationSec int32 `json:"duration_sec"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` } // playlistTrackView is one row of a playlist's track list on the wire. @@ -459,6 +465,9 @@ func playlistRowToView(r *playlists.PlaylistRow) playlistRowView { if r.CoverPath != nil && *r.CoverPath != "" { v.CoverURL = "/api/playlists/" + v.ID + "/cover" } + for _, id := range r.CoverAlbumIDs { + v.CoverAlbumIDs = append(v.CoverAlbumIDs, uuidToString(id)) + } return v } diff --git a/internal/db/dbq/playlists.sql.go b/internal/db/dbq/playlists.sql.go index 78c134bd..6c19e2df 100644 --- a/internal/db/dbq/playlists.sql.go +++ b/internal/db/dbq/playlists.sql.go @@ -260,6 +260,51 @@ func (q *Queries) ListAllPlaylistTracksForCollage(ctx context.Context, arg ListA return items, nil } +const listPlaylistCoverAlbums = `-- name: ListPlaylistCoverAlbums :many +SELECT s.playlist_id, + (array_agg(s.album_id ORDER BY s.first_position))[1:6]::uuid[] AS album_ids +FROM ( + SELECT pt.playlist_id, t.album_id, MIN(pt.position) AS first_position + FROM playlist_tracks pt + JOIN tracks t ON t.id = pt.track_id + JOIN albums a ON a.id = t.album_id + WHERE pt.playlist_id = ANY($1::uuid[]) + AND a.cover_art_path IS NOT NULL + AND a.cover_art_path <> '' + GROUP BY pt.playlist_id, t.album_id +) s +GROUP BY s.playlist_id +` + +type ListPlaylistCoverAlbumsRow struct { + PlaylistID pgtype.UUID + AlbumIds []pgtype.UUID +} + +// The albums a playlist's tiles can show: up to six distinct albums with +// cover art per playlist, in the order they first appear in its tracks. +// More than one per playlist, so a shelf of tiles can give each one a +// cover no other tile on the shelf is already showing. +func (q *Queries) ListPlaylistCoverAlbums(ctx context.Context, playlistIds []pgtype.UUID) ([]ListPlaylistCoverAlbumsRow, error) { + rows, err := q.db.Query(ctx, listPlaylistCoverAlbums, playlistIds) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListPlaylistCoverAlbumsRow + for rows.Next() { + var i ListPlaylistCoverAlbumsRow + if err := rows.Scan(&i.PlaylistID, &i.AlbumIds); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const listPlaylistTracks = `-- name: ListPlaylistTracks :many SELECT pt.playlist_id, pt.position, pt.track_id, pt.title, pt.artist_name, pt.album_title, pt.duration_sec, pt.added_at, pt.pick_kind, t.id AS live_track_id, diff --git a/internal/db/dbq/system_playlists.sql.go b/internal/db/dbq/system_playlists.sql.go index 0a892e48..a986855a 100644 --- a/internal/db/dbq/system_playlists.sql.go +++ b/internal/db/dbq/system_playlists.sql.go @@ -27,7 +27,7 @@ const createSystemPlaylist = `-- name: CreateSystemPlaylist :one INSERT INTO playlists ( user_id, name, description, is_public, kind, system_variant, seed_artist_id, cover_path -) VALUES ($1, $2, '', false, 'system', $3, $4, $5) +) VALUES ($1, $2, $6, false, 'system', $3, $4, $5) RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id ` @@ -37,6 +37,7 @@ type CreateSystemPlaylistParams struct { SystemVariant *string SeedArtistID pgtype.UUID CoverPath *string + Description string } // Inserts a system-generated playlist. Used by BuildSystemPlaylists. @@ -49,6 +50,7 @@ func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlay arg.SystemVariant, arg.SeedArtistID, arg.CoverPath, + arg.Description, ) var i Playlist err := row.Scan( diff --git a/internal/db/queries/playlists.sql b/internal/db/queries/playlists.sql index 92585184..41f05473 100644 --- a/internal/db/queries/playlists.sql +++ b/internal/db/queries/playlists.sql @@ -122,3 +122,22 @@ LIMIT $2; -- Batched lookup used by /api/library/sync to hydrate upsert payloads --. Mirror of GetArtistsByIDs. SELECT * FROM playlists WHERE id = ANY($1::uuid[]); + +-- name: ListPlaylistCoverAlbums :many +-- The albums a playlist's tiles can show: up to six distinct albums with +-- cover art per playlist, in the order they first appear in its tracks. +-- More than one per playlist, so a shelf of tiles can give each one a +-- cover no other tile on the shelf is already showing. +SELECT s.playlist_id, + (array_agg(s.album_id ORDER BY s.first_position))[1:6]::uuid[] AS album_ids +FROM ( + SELECT pt.playlist_id, t.album_id, MIN(pt.position) AS first_position + FROM playlist_tracks pt + JOIN tracks t ON t.id = pt.track_id + JOIN albums a ON a.id = t.album_id + WHERE pt.playlist_id = ANY(sqlc.arg(playlist_ids)::uuid[]) + AND a.cover_art_path IS NOT NULL + AND a.cover_art_path <> '' + GROUP BY pt.playlist_id, t.album_id +) s +GROUP BY s.playlist_id; diff --git a/internal/db/queries/system_playlists.sql b/internal/db/queries/system_playlists.sql index f5f76d0f..09f71ddd 100644 --- a/internal/db/queries/system_playlists.sql +++ b/internal/db/queries/system_playlists.sql @@ -257,7 +257,7 @@ SELECT id, user_id, name, description, is_public, kind, system_variant, INSERT INTO playlists ( user_id, name, description, is_public, kind, system_variant, seed_artist_id, cover_path -) VALUES ($1, $2, '', false, 'system', $3, $4, $5) +) VALUES ($1, $2, sqlc.arg(description), false, 'system', $3, $4, $5) RETURNING *; -- name: GetSystemPlaylistByVariantForUser :one diff --git a/internal/playlists/cover_albums_db_test.go b/internal/playlists/cover_albums_db_test.go new file mode 100644 index 00000000..fb1fd8c5 --- /dev/null +++ b/internal/playlists/cover_albums_db_test.go @@ -0,0 +1,111 @@ +package playlists_test + +import ( + "context" + "path/filepath" + "slices" + "testing" + + "github.com/jackc/pgx/v5/pgtype" + + "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" +) + +// A playlist's cover albums are its distinct albums that have art, in the +// order they first appear, at most six: a shelf of tiles picks from them so +// no two tiles show the same cover. +func TestCoverAlbums_DistinctCoveredInTrackOrderCappedAtSix(t *testing.T) { + pool := newPool(t) + ctx := context.Background() + q := dbq.New(pool) + user := seedUser(t, pool, "covers") + svc := playlists.NewService(pool, nil, t.TempDir()) + + // Eight albums, one track each; album B has no art. A second track on + // album A comes third, so A must be counted once. + tracks := map[string]dbq.Track{} + for _, name := range []string{"A", "B", "C", "D", "E", "F", "G", "H"} { + tracks[name] = seedTrack(t, pool, "song "+name, "artist "+name) + if name != "B" { + if _, err := pool.Exec(ctx, `UPDATE albums SET cover_art_path = $2 WHERE id = $1`, + tracks[name].AlbumID, name+".jpg"); err != nil { + t.Fatalf("set cover %s: %v", name, err) + } + } + } + againOnA, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ + Title: "song A2", AlbumID: tracks["A"].AlbumID, ArtistID: tracks["A"].ArtistID, + DurationMs: 1000, FilePath: filepath.Join(t.TempDir(), "a2.mp3"), + FileSize: 100, FileFormat: "mp3", + }) + if err != nil { + t.Fatalf("seed second track on A: %v", err) + } + + pl, err := svc.Create(ctx, user.ID, "Shelf test", "", false) + if err != nil { + t.Fatalf("Create: %v", err) + } + order := []pgtype.UUID{tracks["A"].ID, tracks["B"].ID, againOnA.ID} + for _, name := range []string{"C", "D", "E", "F", "G", "H"} { + order = append(order, tracks[name].ID) + } + if err := svc.AppendTracks(ctx, user.ID, pl.ID, order); err != nil { + t.Fatalf("AppendTracks: %v", err) + } + + var want []string + for _, name := range []string{"A", "C", "D", "E", "F", "G"} { + want = append(want, uuidString(tracks[name].AlbumID)) + } + ids := func(in []pgtype.UUID) []string { + out := make([]string, 0, len(in)) + for _, id := range in { + out = append(out, uuidString(id)) + } + return out + } + + detail, err := svc.Get(ctx, user.ID, pl.ID) + if err != nil { + t.Fatalf("Get: %v", err) + } + if got := ids(detail.CoverAlbumIDs); !slices.Equal(got, want) { + t.Errorf("Get cover albums = %v, want %v", got, want) + } + + rows, err := svc.List(ctx, user.ID) + if err != nil { + t.Fatalf("List: %v", err) + } + i := slices.IndexFunc(rows, func(r playlists.PlaylistRow) bool { return r.ID == pl.ID }) + if i < 0 { + t.Fatal("List did not return the playlist") + } + if got := ids(rows[i].CoverAlbumIDs); !slices.Equal(got, want) { + t.Errorf("List cover albums = %v, want %v", got, want) + } +} + +// A playlist with no covered albums lists none, rather than failing the +// List call that carries every other playlist. +func TestCoverAlbums_EmptyPlaylistHasNone(t *testing.T) { + pool := newPool(t) + ctx := context.Background() + user := seedUser(t, pool, "nocovers") + svc := playlists.NewService(pool, nil, t.TempDir()) + pl, err := svc.Create(ctx, user.ID, "Empty", "", false) + if err != nil { + t.Fatalf("Create: %v", err) + } + rows, err := svc.List(ctx, user.ID) + if err != nil { + t.Fatalf("List: %v", err) + } + for _, r := range rows { + if r.ID == pl.ID && len(r.CoverAlbumIDs) != 0 { + t.Errorf("cover albums = %v, want none", r.CoverAlbumIDs) + } + } +} diff --git a/internal/playlists/service.go b/internal/playlists/service.go index 8661525c..ade73431 100644 --- a/internal/playlists/service.go +++ b/internal/playlists/service.go @@ -75,6 +75,11 @@ type PlaylistRow struct { SystemVariant *string // 'for_you' | 'songs_like_artist' | nil SeedArtistID pgtype.UUID // Valid=true only for 'songs_like_artist' CoverPath *string + // CoverAlbumIDs are up to six distinct albums with cover art, in the + // order they first appear in the playlist. Filled by List and Get; + // empty for a playlist with no covers, and on the rows Create and + // Update return. + CoverAlbumIDs []pgtype.UUID TrackCount int32 DurationSec int32 CreatedAt pgtype.Timestamptz @@ -200,10 +205,16 @@ func (s *Service) Get(ctx context.Context, callerID, playlistID pgtype.UUID) (*P tracks = append(tracks, pt) } - return &PlaylistDetail{ + detail := &PlaylistDetail{ PlaylistRow: *playlistFromGetRow(row), Tracks: tracks, - }, nil + } + covers, err := coverAlbums(ctx, q, []pgtype.UUID{playlistID}) + if err != nil { + return nil, err + } + detail.CoverAlbumIDs = covers[playlistID] + return detail, nil } // List returns all playlists visible to callerID: every playlist owned @@ -216,8 +227,34 @@ func (s *Service) List(ctx context.Context, callerID pgtype.UUID) ([]PlaylistRow return nil, fmt.Errorf("list playlists: %w", err) } out := make([]PlaylistRow, 0, len(rows)) + ids := make([]pgtype.UUID, 0, len(rows)) for _, r := range rows { out = append(out, *playlistFromListRow(r)) + ids = append(ids, r.ID) + } + covers, err := coverAlbums(ctx, q, ids) + if err != nil { + return nil, err + } + for i := range out { + out[i].CoverAlbumIDs = covers[out[i].ID] + } + return out, nil +} + +// coverAlbums looks up the cover albums of several playlists in one query, +// keyed by playlist id. A playlist with no covered albums is absent. +func coverAlbums(ctx context.Context, q *dbq.Queries, ids []pgtype.UUID) (map[pgtype.UUID][]pgtype.UUID, error) { + out := make(map[pgtype.UUID][]pgtype.UUID, len(ids)) + if len(ids) == 0 { + return out, nil + } + rows, err := q.ListPlaylistCoverAlbums(ctx, ids) + if err != nil { + return nil, fmt.Errorf("list cover albums: %w", err) + } + for _, r := range rows { + out[r.PlaylistID] = r.AlbumIds } return out, nil } diff --git a/internal/playlists/system.go b/internal/playlists/system.go index 98373d9b..5567da7b 100644 --- a/internal/playlists/system.go +++ b/internal/playlists/system.go @@ -1028,6 +1028,30 @@ func pickHeadAndTail( return out } +// systemMixDescription is the one line a client shows under a system mix's +// name, saying what the mix is built from. Kept here so the web and Android +// apps show the same words. Songs like and genre mixes have none: their names +// already say what they hold. +func systemMixDescription(variant string) string { + switch variant { + case "for_you": + return "Built around the songs you play most" + case "discover": + return "Songs you haven’t heard that fit your taste" + case "deep_cuts": + return "Lesser-played tracks by artists you love" + case "rediscover": + return "Albums you loved and haven’t played lately" + case "new_for_you": + return "Recent additions picked for you" + case "on_this_day": + return "What you were playing around this date" + case "first_listens": + return "Songs you’ve never played" + } + return "" +} + // insertSystemPlaylist inserts a kind='system' playlists row plus its // playlist_tracks via AppendPlaylistTrack (which // does the snapshot lookup from tracks/albums/artists). Then recomputes @@ -1047,6 +1071,7 @@ func insertSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.U p, err := qtx.CreateSystemPlaylist(ctx, dbq.CreateSystemPlaylistParams{ UserID: userID, Name: name, + Description: systemMixDescription(variant), SystemVariant: &variantStr, SeedArtistID: seedArtistID, CoverPath: nil,