The first public release of Fabled Minstrel #158

Merged
bvandeusen merged 256 commits from dev into main 2026-12-03 21:41:58 -05:00
25 changed files with 220 additions and 41 deletions
Showing only changes of commit 104f9fd141 - Show all commits
@@ -67,6 +67,8 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
CachedNotificationEntity::class,
CachedNotificationSettingsEntity::class,
],
// v14: + cached_playlists.shelfRank, a system mix's place on its Home
// shelf. MIGRATION_13_14 adds it as 0; the next list refresh fills it.
// v13: + cached_playlists.coverAlbumIds and createdAt, the albums Home's
// shelves draw each playlist tile's picture from and when a mix was
// rebuilt. MIGRATION_12_13 adds both empty; the next list refresh fills them.
@@ -90,7 +92,7 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
// on auth_session. Versions before v8 rebuild destructively, which is
// right for them: the next sync refills every row with the new
// columns populated, so there is nothing to migrate by hand.
version = 13,
version = 14,
exportSchema = true,
)
@TypeConverters(MinstrelTypeConverters::class)
@@ -176,3 +178,13 @@ val MIGRATION_12_13: Migration = object : Migration(12, 13) {
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''")
}
}
/**
* v13 → v14: a playlist's place on its Home shelf. Starts at 0 (unranked);
* Home refreshes the playlist list on open, which fills it.
*/
val MIGRATION_13_14: Migration = object : Migration(13, 14) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0")
}
}
@@ -37,7 +37,14 @@ object DatabaseModule {
// and rebuilds. The sync controller refills the cache from the
// server on first launch, so a rebuild loses only the unsynced
// mutation queue.
.addMigrations(MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13)
.addMigrations(
MIGRATION_8_9,
MIGRATION_9_10,
MIGRATION_10_11,
MIGRATION_11_12,
MIGRATION_12_13,
MIGRATION_13_14,
)
.fallbackToDestructiveMigration(dropAllTables = true)
.build()
@@ -35,4 +35,7 @@ data class CachedPlaylistEntity(
/** ISO-8601 creation time; for a system mix, when it was last rebuilt. */
@ColumnInfo(defaultValue = "''")
val createdAt: String = "",
/** Place on its Home shelf, 1 first; 0 when unranked. */
@ColumnInfo(defaultValue = "0")
val shelfRank: Int = 0,
)
@@ -83,6 +83,7 @@ import com.fabledsword.minstrel.nav.ArtistDetail
import com.fabledsword.minstrel.nav.Home
import com.fabledsword.minstrel.nav.PlaylistDetail
import com.fabledsword.minstrel.playlists.assignShelfCovers
import com.fabledsword.minstrel.playlists.byShelfRank
import com.fabledsword.minstrel.playlists.data.PlaylistsRepository
import com.fabledsword.minstrel.playlists.data.playPlaylistShuffled
import com.fabledsword.minstrel.playlists.shelfMeta
@@ -1340,10 +1341,10 @@ internal fun buildSongsLikeRow(
}
/**
* Builds the "Your genres" row: every genre mix, in name order so the
* shelf reads like a stable channel list. No placeholders — a genre mix
* needs listening history or a genre-tagged library, so none built means
* nothing to show. Offline, fully-cached mixes come first and the rest are
* Builds the "Your genres" row: every genre mix, the genres the listener
* plays most first ([byShelfRank], the server's shelf_rank). No
* placeholders — a genre mix needs listening history or a genre-tagged
* library, so none built means nothing to show. Offline, fully-cached mixes come first and the rest are
* greyed. Mirrors the web Home's genreMixPlaylists.
*/
internal fun buildGenreMixRow(
@@ -1352,7 +1353,7 @@ internal fun buildGenreMixRow(
): List<PlaylistRowItem> {
val mixes = owned
.filter { it.systemVariant == "genre_mix" }
.sortedBy { it.name.lowercase() }
.sortedWith(byShelfRank)
if (!offline) return mixes.map { PlaylistRowItem.Real(it) }
val (available, greyed) = mixes.partition { !it.unavailableOffline }
return (available + greyed).map { PlaylistRowItem.Real(it) }
@@ -28,6 +28,8 @@ data class PlaylistRef(
val coverAlbumIds: List<String> = emptyList(),
/** ISO-8601. A system mix is rebuilt in place, so this is when it was last refreshed. */
val createdAt: String = "",
/** Place on its Home shelf, 1 first; 0 when the app orders it itself. See playlists/Shelf.kt byShelfRank. */
val shelfRank: Int = 0,
) {
val isSystem: Boolean get() = systemVariant != null
@@ -28,6 +28,11 @@ data class PlaylistWire(
* the playlist. Home's shelves pick each tile's picture from these.
*/
@SerialName("cover_album_ids") val coverAlbumIds: List<String> = emptyList(),
/**
* A system mix's place on its Home shelf, 1 first: genre mixes are
* numbered by how much the listener plays each genre. 0 when unranked.
*/
@SerialName("shelf_rank") val shelfRank: Int = 0,
)
/**
@@ -86,5 +91,6 @@ data class PlaylistDetailWire(
@SerialName("owner_username") val ownerUsername: String = "",
@SerialName("created_at") val createdAt: String = "",
@SerialName("cover_album_ids") val coverAlbumIds: List<String> = emptyList(),
@SerialName("shelf_rank") val shelfRank: Int = 0,
val tracks: List<PlaylistTrackWire> = emptyList(),
)
@@ -88,6 +88,15 @@ fun shelfMeta(
return parts.joinToString(" · ").replaceFirstChar { it.uppercase() }
}
/**
* Orders a shelf by the rank the server gave each mix (1 first; genre mixes
* lead with the genres the listener plays most). Unranked playlists follow in
* name order, as do ranked ones should two share a rank.
*/
val byShelfRank: Comparator<PlaylistRef> =
compareBy<PlaylistRef> { if (it.shelfRank > 0) it.shelfRank else Int.MAX_VALUE }
.thenBy { it.name.lowercase(Locale.getDefault()) }
/**
* "Songs like Low Tide Choir" → "Low Tide Choir": a Songs like tile labels
* the artist under its circle, so the prefix would only repeat the shelf.
@@ -265,6 +265,7 @@ private fun CachedPlaylistEntity.toDomain(): PlaylistRef =
trackCount = trackCount,
coverAlbumIds = coverAlbumIds.split(',').filter { it.isNotEmpty() },
createdAt = createdAt,
shelfRank = shelfRank,
// Server returns a relative cover path like "/api/playlists/<id>/cover";
// wrap through the placeholder host so BaseUrlInterceptor + the shared
// Coil/OkHttpClient resolve it against the live server. Without this
@@ -284,6 +285,7 @@ private fun PlaylistWire.toEntity(): CachedPlaylistEntity =
systemVariant = systemVariant,
coverAlbumIds = coverAlbumIds.joinToString(","),
createdAt = createdAt,
shelfRank = shelfRank,
)
private fun PlaylistDetailWire.toPlaylistEntity(): CachedPlaylistEntity =
@@ -298,6 +300,7 @@ private fun PlaylistDetailWire.toPlaylistEntity(): CachedPlaylistEntity =
systemVariant = systemVariant,
coverAlbumIds = coverAlbumIds.joinToString(","),
createdAt = createdAt,
shelfRank = shelfRank,
)
private fun PlaylistDetailWire.toPlaylistRef(): PlaylistRef =
@@ -316,6 +319,7 @@ private fun PlaylistDetailWire.toPlaylistRef(): PlaylistRef =
ownerUsername = ownerUsername,
coverAlbumIds = coverAlbumIds,
createdAt = createdAt,
shelfRank = shelfRank,
)
private fun PlaylistTrackWire.toDomain(): PlaylistTrackRef =
@@ -105,13 +105,14 @@ class BuildPlaylistsRowTest {
assertTrue(buildSongsLikeRow(emptyList(), SystemPlaylistsStatus(), offline = true).isEmpty())
}
private fun genreMix(name: String, cached: Boolean) = PlaylistRef(
private fun genreMix(name: String, cached: Boolean, rank: Int = 0) = PlaylistRef(
id = name,
userId = "u",
name = name,
systemVariant = "genre_mix",
trackCount = 50,
fullyCached = cached,
shelfRank = rank,
)
@Test
@@ -131,6 +132,20 @@ class BuildPlaylistsRowTest {
assertEquals(listOf("u1"), carousel)
}
@Test
fun `ranked genre mixes lead with the genre played most, the unranked follow by name`() {
val owned = listOf(
genreMix("Ambient mix", cached = true, rank = 3),
genreMix("Zydeco mix", cached = true),
genreMix("Pop mix", cached = true, rank = 1),
genreMix("Blues mix", cached = true),
genreMix("Jazz mix", cached = true, rank = 2),
)
val names = buildGenreMixRow(owned, offline = false)
.filterIsInstance<PlaylistRowItem.Real>().map { it.playlist.name }
assertEquals(listOf("Pop mix", "Jazz mix", "Ambient mix", "Blues mix", "Zydeco mix"), names)
}
@Test
fun `genre mixes are not refreshable, so a cached one plays offline`() {
assertFalse(genreMix("Jazz mix", cached = true).refreshable)
@@ -70,6 +70,12 @@ class PlaylistsRepositoryCacheMergeTest {
assertEquals("2026-11-23T08:00:00Z", out.createdAt)
}
@Test
fun `a genre mix keeps its shelf rank through the cache`() {
val row = playlist("p", trackCount = 3).copy(shelfRank = 2)
assertEquals(2, mergePlaylistsWithCache(rows = listOf(row), counts = emptyList()).single().shelfRank)
}
@Test
fun `a row cached before cover albums existed has none`() {
val out = mergePlaylistsWithCache(rows = listOf(playlist("p", trackCount = 3)), counts = emptyList())
+9 -4
View File
@@ -45,10 +45,14 @@ type playlistRowView struct {
// 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"`
// ShelfRank is a system mix's place on its Home shelf, 1 first: genre
// mixes are numbered by how much the user listens to each genre.
// Omitted (0) for playlists the client orders itself.
ShelfRank int32 `json:"shelf_rank,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.
@@ -453,6 +457,7 @@ func playlistRowToView(r *playlists.PlaylistRow) playlistRowView {
Kind: r.Kind,
SystemVariant: r.SystemVariant,
Refreshable: r.SystemVariant != nil && playlists.RefreshableSystemKind(*r.SystemVariant),
ShelfRank: r.ShelfRank,
TrackCount: r.TrackCount,
DurationSec: r.DurationSec,
CreatedAt: formatTimestamp(r.CreatedAt),
+1
View File
@@ -448,6 +448,7 @@ type Playlist struct {
Kind string
SystemVariant *string
SeedArtistID pgtype.UUID
ShelfRank int32
}
type PlaylistTrack struct {
+12 -5
View File
@@ -59,7 +59,7 @@ func (q *Queries) AppendPlaylistTrack(ctx context.Context, arg AppendPlaylistTra
const createPlaylist = `-- name: CreatePlaylist :one
INSERT INTO playlists (user_id, name, description, is_public)
VALUES ($1, $2, $3, $4)
RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id
RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank
`
type CreatePlaylistParams struct {
@@ -91,6 +91,7 @@ func (q *Queries) CreatePlaylist(ctx context.Context, arg CreatePlaylistParams)
&i.Kind,
&i.SystemVariant,
&i.SeedArtistID,
&i.ShelfRank,
)
return i, err
}
@@ -132,7 +133,7 @@ func (q *Queries) DeletePlaylistTrack(ctx context.Context, arg DeletePlaylistTra
}
const getPlaylist = `-- name: GetPlaylist :one
SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, u.username AS owner_username
SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, p.shelf_rank, u.username AS owner_username
FROM playlists p
JOIN users u ON u.id = p.user_id
WHERE p.id = $1
@@ -152,6 +153,7 @@ type GetPlaylistRow struct {
Kind string
SystemVariant *string
SeedArtistID pgtype.UUID
ShelfRank int32
OwnerUsername string
}
@@ -172,13 +174,14 @@ func (q *Queries) GetPlaylist(ctx context.Context, id pgtype.UUID) (GetPlaylistR
&i.Kind,
&i.SystemVariant,
&i.SeedArtistID,
&i.ShelfRank,
&i.OwnerUsername,
)
return i, err
}
const getPlaylistsByIDs = `-- name: GetPlaylistsByIDs :many
SELECT id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id FROM playlists WHERE id = ANY($1::uuid[])
SELECT id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank FROM playlists WHERE id = ANY($1::uuid[])
`
// Batched lookup used by /api/library/sync to hydrate upsert payloads
@@ -206,6 +209,7 @@ func (q *Queries) GetPlaylistsByIDs(ctx context.Context, dollar_1 []pgtype.UUID)
&i.Kind,
&i.SystemVariant,
&i.SeedArtistID,
&i.ShelfRank,
); err != nil {
return nil, err
}
@@ -380,7 +384,7 @@ func (q *Queries) ListPlaylistTracks(ctx context.Context, playlistID pgtype.UUID
}
const listPlaylistsForUser = `-- name: ListPlaylistsForUser :many
SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, u.username AS owner_username
SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, p.shelf_rank, u.username AS owner_username
FROM playlists p
JOIN users u ON u.id = p.user_id
WHERE p.user_id = $1 OR p.is_public = true
@@ -401,6 +405,7 @@ type ListPlaylistsForUserRow struct {
Kind string
SystemVariant *string
SeedArtistID pgtype.UUID
ShelfRank int32
OwnerUsername string
}
@@ -429,6 +434,7 @@ func (q *Queries) ListPlaylistsForUser(ctx context.Context, userID pgtype.UUID)
&i.Kind,
&i.SystemVariant,
&i.SeedArtistID,
&i.ShelfRank,
&i.OwnerUsername,
); err != nil {
return nil, err
@@ -480,7 +486,7 @@ SET
is_public = CASE WHEN $5::boolean THEN $6::boolean ELSE is_public END,
updated_at = now()
WHERE id = $7
RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id
RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank
`
type UpdatePlaylistParams struct {
@@ -521,6 +527,7 @@ func (q *Queries) UpdatePlaylist(ctx context.Context, arg UpdatePlaylistParams)
&i.Kind,
&i.SystemVariant,
&i.SeedArtistID,
&i.ShelfRank,
)
return i, err
}
+8 -4
View File
@@ -26,9 +26,9 @@ func (q *Queries) ClearStaleSystemPlaylistInFlight(ctx context.Context) error {
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, $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
kind, system_variant, seed_artist_id, cover_path, shelf_rank
) VALUES ($1, $2, $6, false, 'system', $3, $4, $5, $7)
RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank
`
type CreateSystemPlaylistParams struct {
@@ -38,11 +38,13 @@ type CreateSystemPlaylistParams struct {
SeedArtistID pgtype.UUID
CoverPath *string
Description string
ShelfRank int32
}
// Inserts a system-generated playlist. Used by BuildSystemPlaylists.
// For 'for_you' variant, pass seed_artist_id as NULL (zero-value pgtype.UUID
// with Valid=false).
// with Valid=false). shelf_rank is the mix's place on its Home shelf, 1
// first, or 0 for kinds the clients order themselves.
func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlaylistParams) (Playlist, error) {
row := q.db.QueryRow(ctx, createSystemPlaylist,
arg.UserID,
@@ -51,6 +53,7 @@ func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlay
arg.SeedArtistID,
arg.CoverPath,
arg.Description,
arg.ShelfRank,
)
var i Playlist
err := row.Scan(
@@ -67,6 +70,7 @@ func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlay
&i.Kind,
&i.SystemVariant,
&i.SeedArtistID,
&i.ShelfRank,
)
return i, err
}
@@ -0,0 +1 @@
ALTER TABLE playlists DROP COLUMN shelf_rank;
@@ -0,0 +1,6 @@
-- Where a system mix sits on its Home shelf, 1 first. The genre mix builder
-- numbers its mixes by how much the user listens to each genre, so the
-- "Your genres" shelf leads with their main genres rather than reading
-- A to Z. 0 means unranked: every other playlist, which clients order their
-- own way.
ALTER TABLE playlists ADD COLUMN shelf_rank integer NOT NULL DEFAULT 0;
+4 -3
View File
@@ -253,11 +253,12 @@ SELECT id, user_id, name, description, is_public, kind, system_variant,
-- name: CreateSystemPlaylist :one
-- Inserts a system-generated playlist. Used by BuildSystemPlaylists.
-- For 'for_you' variant, pass seed_artist_id as NULL (zero-value pgtype.UUID
-- with Valid=false).
-- with Valid=false). shelf_rank is the mix's place on its Home shelf, 1
-- first, or 0 for kinds the clients order themselves.
INSERT INTO playlists (
user_id, name, description, is_public,
kind, system_variant, seed_artist_id, cover_path
) VALUES ($1, $2, sqlc.arg(description), false, 'system', $3, $4, $5)
kind, system_variant, seed_artist_id, cover_path, shelf_rank
) VALUES ($1, $2, sqlc.arg(description), false, 'system', $3, $4, $5, sqlc.arg(shelf_rank))
RETURNING *;
-- name: GetSystemPlaylistByVariantForUser :one
+21
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log/slog"
"sort"
"time"
"github.com/jackc/pgx/v5/pgtype"
@@ -123,6 +124,10 @@ func produceGenreMixes(
// shelf does not have yet. It takes tier-3 genres only while the shelf is
// below genreMixMinShelf. build is handed the genres kept so far, whose songs
// the new mix leaves out.
//
// The mixes it keeps are ranked for the shelf in the candidates' own order
// (tier, then score: the genres the user listens to most first), not in the
// order they were picked, which puts specific genres ahead of broad ones.
func selectGenreMixes(
cands []genreCandidate, build func(genreCandidate, []string) []rankedCandidate,
) []builtPlaylist {
@@ -136,6 +141,7 @@ func selectGenreMixes(
owned := map[pgtype.UUID]struct{}{}
kept := []string{}
var out []builtPlaylist
var picked []int // the candidate index of each mix in out
for _, i := range specificFirst(cands, sets) {
c := cands[i]
if len(out) >= genreMixCount {
@@ -160,10 +166,25 @@ func selectGenreMixes(
Variant: "genre_mix",
Tracks: tracks,
})
picked = append(picked, i)
}
rankByCandidate(out, picked)
return out
}
// rankByCandidate numbers each mix's ShelfRank from 1 by its candidate
// index: the lower the index, the more the user listens to the genre.
func rankByCandidate(out []builtPlaylist, picked []int) {
order := make([]int, len(out))
for k := range order {
order[k] = k
}
sort.Slice(order, func(a, b int) bool { return picked[order[a]] < picked[order[b]] })
for rank, k := range order {
out[k].ShelfRank = int32(rank + 1)
}
}
// specificFirst returns the candidates' indexes in rank order, except that
// within each tier the broad genres come after the specific ones.
func specificFirst(cands []genreCandidate, sets []map[pgtype.UUID]struct{}) []int {
+21
View File
@@ -243,3 +243,24 @@ func TestSelectGenreMixes_LibraryGenresOnlyFillAShortShelf(t *testing.T) {
}
}
}
// The shelf leads with the genre the user listens to most, even when it was
// picked after narrower ones: Rock ranks first though Pop Punk was built
// before it.
func TestSelectGenreMixes_ShelfRankFollowsListeningNotPickOrder(t *testing.T) {
cands := []genreCandidate{
genreOf("Rock", 1, songs(1, 1000)), // broad: half its songs are Pop Punk
genreOf("Pop Punk", 1, songs(1, 500)), // specific, so picked first
genreOf("Jazz", 1, songs(3000, 3100)),
}
got := selectGenreMixes(cands, buildN(30))
if names := labels(got); len(names) != 3 || names[0] != "Pop Punk mix" || names[2] != "Rock mix" {
t.Fatalf("pick order = %v, want Pop Punk first and Rock last", names)
}
want := map[string]int32{"Rock mix": 1, "Pop Punk mix": 2, "Jazz mix": 3}
for _, b := range got {
if b.ShelfRank != want[b.Name] {
t.Errorf("%s shelf rank = %d, want %d", b.Name, b.ShelfRank, want[b.Name])
}
}
}
+9 -4
View File
@@ -80,10 +80,13 @@ type PlaylistRow struct {
// 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
UpdatedAt pgtype.Timestamptz
// ShelfRank is a system mix's place on its Home shelf, 1 first; 0 for
// playlists the clients order themselves. Only genre mixes are ranked.
ShelfRank int32
TrackCount int32
DurationSec int32
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// PlaylistDetail extends PlaylistRow with the ordered track list.
@@ -605,6 +608,7 @@ func playlistFromGetRow(r dbq.GetPlaylistRow) *PlaylistRow {
SystemVariant: r.SystemVariant,
SeedArtistID: r.SeedArtistID,
CoverPath: r.CoverPath,
ShelfRank: r.ShelfRank,
TrackCount: r.TrackCount,
DurationSec: r.DurationSec,
CreatedAt: r.CreatedAt,
@@ -624,6 +628,7 @@ func playlistFromListRow(r dbq.ListPlaylistsForUserRow) *PlaylistRow {
SystemVariant: r.SystemVariant,
SeedArtistID: r.SeedArtistID,
CoverPath: r.CoverPath,
ShelfRank: r.ShelfRank,
TrackCount: r.TrackCount,
DurationSec: r.DurationSec,
CreatedAt: r.CreatedAt,
+11 -9
View File
@@ -515,6 +515,9 @@ type builtPlaylist struct {
Variant string
SeedArtistID pgtype.UUID // zero value for non-seeded kinds
Tracks []rankedCandidate
// ShelfRank is the mix's place on its Home shelf, 1 first; 0 leaves
// the order to the clients.
ShelfRank int32
}
// systemPlaylistProducer computes the playlists for one kind for a
@@ -871,8 +874,7 @@ func BuildSystemPlaylists(ctx context.Context, pool *pgxpool.Pool, logger *slog.
if len(bp.Tracks) == 0 {
continue
}
id, err := insertSystemPlaylist(ctx, qtx, userID, bp.Name, bp.Variant,
bp.SeedArtistID, bp.Tracks)
id, err := insertSystemPlaylist(ctx, qtx, userID, bp)
if err != nil {
buildErr = fmt.Errorf("insert %s (%s): %w", bp.Variant, bp.Name, err)
return buildErr
@@ -1066,22 +1068,22 @@ func systemMixDescription(variant string) string {
// in BuildSystemPlaylists overrides it with a 4-cell composite of the
// contributing tracks' album art.
func insertSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.UUID,
name, variant string, seedArtistID pgtype.UUID,
tracks []rankedCandidate) (pgtype.UUID, error) {
variantStr := variant
bp builtPlaylist) (pgtype.UUID, error) {
variantStr := bp.Variant
p, err := qtx.CreateSystemPlaylist(ctx, dbq.CreateSystemPlaylistParams{
UserID: userID,
Name: name,
Description: systemMixDescription(variant),
Name: bp.Name,
Description: systemMixDescription(bp.Variant),
SystemVariant: &variantStr,
SeedArtistID: seedArtistID,
SeedArtistID: bp.SeedArtistID,
CoverPath: nil,
ShelfRank: bp.ShelfRank,
})
if err != nil {
return pgtype.UUID{}, fmt.Errorf("insert playlist row: %w", err)
}
tracks, err = oneCopyPerSong(ctx, qtx, tracks)
tracks, err := oneCopyPerSong(ctx, qtx, bp.Tracks)
if err != nil {
return pgtype.UUID{}, err
}
+4
View File
@@ -80,6 +80,10 @@ export type Playlist = {
// /api/albums/{id}/cover. Absent when the playlist has none. A home shelf
// gives each tile an album no earlier tile shows (lib/playlists/shelf.ts).
cover_album_ids?: string[];
// A system mix's place on its home shelf, 1 first: genre mixes are
// numbered by how much the user listens to each genre. Absent for
// playlists the client orders itself (lib/playlists/shelf.ts byShelfRank).
shelf_rank?: number;
track_count: number;
duration_sec: number;
created_at: string;
+28 -1
View File
@@ -1,6 +1,14 @@
import { describe, expect, test } from 'vitest';
import type { Playlist } from '#lib/api/types.js';
import { assignShelfCovers, refreshedLabel, shelfMeta, shelfTileWidth, songsLikeArtist, washTone } from './shelf.js';
import {
assignShelfCovers,
byShelfRank,
refreshedLabel,
shelfMeta,
shelfTileWidth,
songsLikeArtist,
washTone
} from './shelf.js';
function pl(over: Partial<Playlist>): Playlist {
return {
@@ -149,3 +157,22 @@ describe('shelfTileWidth', () => {
expect(shelfTileWidth(100, 5, 150, 16)).toBe(150);
});
});
describe('byShelfRank', () => {
test('ranked mixes lead in rank order, the unranked follow by name', () => {
const shelf = [
pl({ name: 'Ambient mix', shelf_rank: 3 }),
pl({ name: 'Zydeco mix' }),
pl({ name: 'Pop mix', shelf_rank: 1 }),
pl({ name: 'Blues mix' }),
pl({ name: 'Jazz mix', shelf_rank: 2 })
];
expect([...shelf].sort(byShelfRank).map((p) => p.name)).toEqual([
'Pop mix',
'Jazz mix',
'Ambient mix',
'Blues mix',
'Zydeco mix'
]);
});
});
+9
View File
@@ -66,6 +66,15 @@ export function shelfMeta(playlists: Playlist[], now: Date = new Date()): string
return line.charAt(0).toUpperCase() + line.slice(1);
}
// Orders a shelf by the rank the server gave each mix (1 first; genre mixes
// lead with the genres the user listens to most). Unranked playlists follow
// in name order, as do ranked ones should two share a rank.
export function byShelfRank(a: Playlist, b: Playlist): number {
const ra = a.shelf_rank || Number.MAX_SAFE_INTEGER;
const rb = b.shelf_rank || Number.MAX_SAFE_INTEGER;
return ra - rb || a.name.localeCompare(b.name);
}
// "Songs like Low Tide Choir" → "Low Tide Choir": a Songs like tile labels
// the artist under its circle, so the prefix would only repeat the shelf.
export function songsLikeArtist(p: Playlist): string {
+3 -3
View File
@@ -12,7 +12,7 @@
import { createPlaylistsQuery } from '#lib/api/playlists.js';
import { createSystemPlaylistsStatusQuery } from '#lib/api/me.js';
import type { Playlist } from '#lib/api/types.js';
import { assignShelfCovers, shelfMeta } from '#lib/playlists/shelf.js';
import { assignShelfCovers, byShelfRank, shelfMeta } from '#lib/playlists/shelf.js';
const queryStore = createHomeQuery();
const query = $derived($queryStore);
@@ -52,12 +52,12 @@
);
// Genre mixes: one "{Genre} mix" per genre the user listens to, on their
// own row in name order so the shelf reads like a stable channel list.
// own row, the genres listened to most first (the server's shelf_rank).
// Mirrors Android's buildGenreMixRow (HomeScreen.kt).
const genreMixPlaylists = $derived(
(systemPlaylistsQ.data?.owned ?? [])
.filter((p) => p.system_variant === 'genre_mix')
.sort((a, b) => a.name.localeCompare(b.name))
.sort(byShelfRank)
);
// Secondary system kinds the server generates that don't get pinned