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
8 changed files with 291 additions and 3 deletions
Showing only changes of commit 1a98a23d1f - Show all commits
+31
View File
@@ -137,6 +137,37 @@ func (q *Queries) DeleteAlbumIfEmpty(ctx context.Context, id pgtype.UUID) (Delet
return i, err
}
const deleteEmptyAlbums = `-- name: DeleteEmptyAlbums :many
DELETE FROM albums a
WHERE NOT EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id)
AND a.created_at < now() - interval '10 minutes'
RETURNING a.id
`
// The scan's tidy-up: removes every album no track points to, missing or
// not. A row made in the last ten minutes is left alone, so a file being
// added right now (its album created, its track not yet written) is never
// caught between the two.
func (q *Queries) DeleteEmptyAlbums(ctx context.Context) ([]pgtype.UUID, error) {
rows, err := q.db.Query(ctx, deleteEmptyAlbums)
if err != nil {
return nil, err
}
defer rows.Close()
var items []pgtype.UUID
for rows.Next() {
var id pgtype.UUID
if err := rows.Scan(&id); err != nil {
return nil, err
}
items = append(items, id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getAlbumByArtistAndTitle = `-- name: GetAlbumByArtistAndTitle :one
SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at FROM albums
WHERE albums.artist_id = $1 AND albums.title = $2
+34
View File
@@ -66,6 +66,40 @@ func (q *Queries) DeleteArtistIfEmpty(ctx context.Context, id pgtype.UUID) (pgty
return id_2, err
}
const deleteEmptyArtists = `-- name: DeleteEmptyArtists :many
DELETE FROM artists a
WHERE NOT EXISTS (SELECT 1 FROM albums al WHERE al.artist_id = a.id)
AND NOT EXISTS (SELECT 1 FROM tracks t WHERE t.artist_id = a.id)
AND NOT EXISTS (SELECT 1 FROM playlists p WHERE p.seed_artist_id = a.id)
AND a.created_at < now() - interval '10 minutes'
RETURNING a.id
`
// The scan's tidy-up: removes every artist with no albums and no tracks.
// An artist a Songs like playlist is seeded from is kept, since that
// playlist must always name its seed; it goes when the playlist is next
// rebuilt without it. Rows made in the last ten minutes are left alone, as
// in DeleteEmptyAlbums.
func (q *Queries) DeleteEmptyArtists(ctx context.Context) ([]pgtype.UUID, error) {
rows, err := q.db.Query(ctx, deleteEmptyArtists)
if err != nil {
return nil, err
}
defer rows.Close()
var items []pgtype.UUID
for rows.Next() {
var id pgtype.UUID
if err := rows.Scan(&id); err != nil {
return nil, err
}
items = append(items, id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getArtistByID = `-- name: GetArtistByID :one
SELECT id, name, sort_name, mbid, created_at, updated_at, artist_thumb_path, artist_fanart_path, artist_art_source, artist_art_sources_version FROM artists WHERE id = $1
`
+10
View File
@@ -221,6 +221,16 @@ WHERE a.id = $1
AND NOT EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id)
RETURNING a.id, a.artist_id;
-- name: DeleteEmptyAlbums :many
-- The scan's tidy-up: removes every album no track points to, missing or
-- not. A row made in the last ten minutes is left alone, so a file being
-- added right now (its album created, its track not yet written) is never
-- caught between the two.
DELETE FROM albums a
WHERE NOT EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id)
AND a.created_at < now() - interval '10 minutes'
RETURNING a.id;
-- name: SetAlbumMbidIfNull :exec
-- Heal MBID on existing album rows during rescan. Idempotent —
-- only updates when the existing mbid is NULL.
+13
View File
@@ -70,6 +70,19 @@ LEFT JOIN LATERAL (
ORDER BY artists.sort_name, artists.name, artists.id
LIMIT $1 OFFSET $2;
-- name: DeleteEmptyArtists :many
-- The scan's tidy-up: removes every artist with no albums and no tracks.
-- An artist a Songs like playlist is seeded from is kept, since that
-- playlist must always name its seed; it goes when the playlist is next
-- rebuilt without it. Rows made in the last ten minutes are left alone, as
-- in DeleteEmptyAlbums.
DELETE FROM artists a
WHERE NOT EXISTS (SELECT 1 FROM albums al WHERE al.artist_id = a.id)
AND NOT EXISTS (SELECT 1 FROM tracks t WHERE t.artist_id = a.id)
AND NOT EXISTS (SELECT 1 FROM playlists p WHERE p.seed_artist_id = a.id)
AND a.created_at < now() - interval '10 minutes'
RETURNING a.id;
-- name: DeleteArtistIfEmpty :one
-- Deletes the artist row only when it has no remaining albums
-- AND no remaining tracks (defensive — tracks can in principle exist
+7 -1
View File
@@ -12,7 +12,12 @@ import (
type TagMBIDs struct {
// Release is musicbrainz_albumid: one edition, what albums.mbid stores.
Release string
Artist string
// Artist is the track's own artist (musicbrainz_artistid).
Artist string
// AlbumArtist is musicbrainz_albumartistid: who the album is filed
// under, which on a compilation or a track with a featured artist is
// not the track's artist.
AlbumArtist string
// ReleaseGroup is musicbrainz_releasegroupid. The duplicate resolver
// reads an album's MusicBrainz track lists by it.
ReleaseGroup string
@@ -40,6 +45,7 @@ func ReadTagMBIDs(m tag.Metadata) TagMBIDs {
ids := TagMBIDs{
Release: cleanMBID(info.Get(mbz.Album)),
Artist: cleanMBID(info.Get(mbz.Artist)),
AlbumArtist: cleanMBID(info.Get(mbz.AlbumArtist)),
ReleaseGroup: cleanMBID(info.Get(mbz.ReleaseGroup)),
Recording: cleanMBID(info.Get(mbz.Recording)),
}
+29
View File
@@ -259,3 +259,32 @@ func TestReadTrackAndDisc(t *testing.T) {
}
}
}
// The album artist's id is read from each format's Picard name.
func TestReadTagMBIDs_AlbumArtist(t *testing.T) {
cases := []struct {
name string
meta stubMeta
}{
{"vorbis", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{
"musicbrainz_albumartistid": "aa-1",
"musicbrainz_artistid": "ar-1",
}}},
{"id3v2", stubMeta{format: tag.ID3v2_4, raw: map[string]interface{}{
"TXXX": &tag.Comm{Description: "MusicBrainz Album Artist Id", Text: "aa-1\x00"},
"TXXX_0": &tag.Comm{Description: "MusicBrainz Artist Id", Text: "ar-1"},
}}},
{"mp4", stubMeta{format: tag.MP4, raw: map[string]interface{}{
"MusicBrainz Album Artist Id": "aa-1",
"MusicBrainz Artist Id": "ar-1",
}}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
ids := ReadTagMBIDs(c.meta)
if ids.AlbumArtist != "aa-1" || ids.Artist != "ar-1" {
t.Errorf("album artist = %q, artist = %q; want aa-1 and ar-1", ids.AlbumArtist, ids.Artist)
}
})
}
}
+55 -2
View File
@@ -78,7 +78,13 @@ var audioExtensions = map[string]bool{
// 8: a file tagged with no release group joins the same-named album that
// already holds a track from its folder. Under 7 it took the oldest row,
// which could file a bonus track on a later album of the same name.
const tagReadVersion int16 = 8
// 9: an album is filed under its album artist (ALBUMARTIST / TPE2 / aART,
// with its MusicBrainz id) when the file names one, not under the
// track's artist. A compilation, or an album with one featured-artist
// track, was split into an album per track artist; a re-read files each
// track back on the one album, and the scan's tidy-up removes the rows
// it leaves empty.
const tagReadVersion int16 = 9
type Stats struct {
Scanned int `json:"scanned"`
@@ -214,9 +220,45 @@ func (s *Scanner) Scan(ctx context.Context, progressCb func(Stats)) (Stats, erro
// marked and then healed, is not reported as lost.
s.notifyStillMissing(ctx, stats.marked)
s.announceNewAlbums(ctx)
s.tidyEmptyRows(ctx)
return stats, nil
}
// tidyEmptyRows removes the album rows no track points to any more, and the
// artists left with neither albums nor tracks. Re-filing a track (a re-read
// under a new tag-read version, a moved file, a merged duplicate) can leave
// its old album empty, and an empty album would otherwise still show in
// album lists. An album whose tracks are only missing keeps its row: those
// tracks wait in Needs a file. Not fatal; the next scan tries again.
func (s *Scanner) tidyEmptyRows(ctx context.Context) {
q := dbq.New(s.pool)
albums, err := q.DeleteEmptyAlbums(ctx)
if err != nil {
s.logger.Warn("library scan: removing empty albums failed", "err", err)
return
}
artists, err := q.DeleteEmptyArtists(ctx)
if err != nil {
s.logger.Warn("library scan: removing empty artists failed", "err", err)
}
if len(albums) == 0 && len(artists) == 0 {
return
}
s.logger.Info("library scan: removed empty rows", "albums", len(albums), "artists", len(artists))
for _, c := range []struct {
entity syncpkg.EntityType
ids []pgtype.UUID
}{{syncpkg.EntityAlbum, albums}, {syncpkg.EntityArtist, artists}} {
ids := make([]string, len(c.ids))
for i, id := range c.ids {
ids[i] = syncpkg.FormatUUID(id)
}
if err := syncpkg.LogChanges(ctx, s.pool, c.entity, ids, syncpkg.OpDelete); err != nil {
s.logger.Warn("library scan: logging removed rows failed", "entity", c.entity, "err", err)
}
}
}
// enumerate walks every configured root and returns the audio paths found, in
// walk order, plus a count of walk errors.
//
@@ -345,7 +387,18 @@ func (s *Scanner) scanFile(
if err != nil {
return pgtype.UUID{}, false, fmt.Errorf("artist: %w", err)
}
album, err := s.resolveAlbum(ctx, q, artist.ID, albumTitle, meta.Year(), albumMBID, releaseGroupMBID, filepath.Dir(path))
// The album belongs to its album artist when the file names one: every
// track of a compilation, or of an album with a featured guest, then
// lands on one album instead of one per track artist. The track keeps
// its own artist.
albumArtist := artist
if name := strings.TrimSpace(meta.AlbumArtist()); name != "" && name != artistName {
albumArtist, err = s.resolveArtist(ctx, q, name, ids.AlbumArtist)
if err != nil {
return pgtype.UUID{}, false, fmt.Errorf("album artist: %w", err)
}
}
album, err := s.resolveAlbum(ctx, q, albumArtist.ID, albumTitle, meta.Year(), albumMBID, releaseGroupMBID, filepath.Dir(path))
if err != nil {
return pgtype.UUID{}, false, fmt.Errorf("album: %w", err)
}
+112
View File
@@ -548,3 +548,115 @@ func TestScanFiles_ClearsTheMarkWhenAFileReturnsToItsPath_Integration(t *testing
t.Error("no library change logged, so clients would still show the track as unplayable")
}
}
// An album is filed under its album artist: a compilation's tracks by
// different artists, and an album with one featured-artist track, are each
// one album, and every track keeps its own artist. The row the old filing
// left behind is removed by the scan's tidy-up once a re-read empties it.
func TestScanner_AlbumArtistKeepsAnAlbumTogether_Integration(t *testing.T) {
if testing.Short() {
t.Skip("skipping scanner integration in -short mode")
}
dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
ctx := context.Background()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
if err := db.Migrate(dsn, logger); err != nil {
t.Fatalf("migrate: %v", err)
}
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatalf("pool: %v", err)
}
t.Cleanup(pool.Close)
if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil {
t.Fatalf("truncate: %v", err)
}
root := t.TempDir()
song := func(rel, title, artist, albumArtist, album string) string {
p := filepath.Join(root, rel)
frames := map[string]string{"TIT2": title, "TPE1": artist, "TALB": album}
if albumArtist != "" {
frames["TPE2"] = albumArtist
}
writeTestMP3(t, p, frames)
return p
}
song("Summer Hits/01.mp3", "Wave", "Low Tide Choir", "Various Artists", "Summer Hits")
song("Summer Hits/02.mp3", "Glass", "Paper Lanterns", "Various Artists", "Summer Hits")
song("Night Drive/01.mp3", "Neon", "Paper Lanterns", "Paper Lanterns", "Night Drive")
guest := song("Night Drive/02.mp3", "Static", "Paper Lanterns feat. Low Tide Choir", "Paper Lanterns", "Night Drive")
scanner := New(pool, logger, []string{root}, nil)
if _, err := scanner.Scan(ctx, nil); err != nil {
t.Fatalf("scan: %v", err)
}
type filing struct{ albumArtist, tracks, trackArtists int }
albums := func() map[string]filing {
t.Helper()
rows, err := pool.Query(ctx, `
SELECT a.title, ar.name, count(t.id), count(DISTINCT t.artist_id)
FROM albums a JOIN artists ar ON ar.id = a.artist_id
LEFT JOIN tracks t ON t.album_id = a.id
GROUP BY a.id, a.title, ar.name`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
out := map[string]filing{}
names := map[string]string{}
for rows.Next() {
var title, artist string
var tracks, trackArtists int
if err := rows.Scan(&title, &artist, &tracks, &trackArtists); err != nil {
t.Fatal(err)
}
if _, dup := out[title]; dup {
t.Fatalf("album %q has more than one row", title)
}
names[title] = artist
out[title] = filing{tracks: tracks, trackArtists: trackArtists}
}
if names["Summer Hits"] != "Various Artists" || names["Night Drive"] != "Paper Lanterns" {
t.Fatalf("album artists = %v, want Summer Hits by Various Artists and Night Drive by Paper Lanterns", names)
}
return out
}
got := albums()
if got["Summer Hits"].tracks != 2 || got["Summer Hits"].trackArtists != 2 {
t.Errorf("Summer Hits = %+v, want 2 tracks by 2 artists on one album", got["Summer Hits"])
}
if got["Night Drive"].tracks != 2 || got["Night Drive"].trackArtists != 2 {
t.Errorf("Night Drive = %+v, want 2 tracks by 2 artists on one album", got["Night Drive"])
}
// The guest track as the old filing left it: on an album of its own,
// made long enough ago for the tidy-up, under an older tag-read version.
if _, err := pool.Exec(ctx, `
WITH g AS (SELECT artist_id FROM tracks WHERE file_path = $1),
a AS (INSERT INTO albums (title, sort_title, artist_id, created_at)
SELECT 'Night Drive', 'night drive', artist_id, now() - interval '1 day' FROM g
RETURNING id)
UPDATE tracks SET album_id = (SELECT id FROM a), tag_read_version = 8 WHERE file_path = $1`, guest); err != nil {
t.Fatal(err)
}
if _, err := scanner.Scan(ctx, nil); err != nil {
t.Fatalf("rescan: %v", err)
}
if got := albums(); got["Night Drive"].tracks != 2 {
t.Errorf("after the re-read, Night Drive = %+v, want both tracks back on one album", got["Night Drive"])
}
var empty int
if err := pool.QueryRow(ctx,
`SELECT count(*) FROM albums a WHERE NOT EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id)`,
).Scan(&empty); err != nil {
t.Fatal(err)
}
if empty != 0 {
t.Errorf("%d empty album rows left after the scan, want the tidy-up to remove them", empty)
}
}