diff --git a/internal/api/library.go b/internal/api/library.go index 685bf952..e407943e 100644 --- a/internal/api/library.go +++ b/internal/api/library.go @@ -10,6 +10,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" ) @@ -75,10 +76,16 @@ func (h *handlers) handleGetAlbum(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("lookup failed", err)) return } + // Each track is named by its own artist: on a compilation or a track + // with a guest, that is not the album's. + names, err := db.TrackArtistNames(r.Context(), q, album.ID) + if err != nil { + h.logger.Warn("api: album track artists failed; naming the album artist", "err", err) + } refs := make([]TrackRef, 0, len(tracks)) durSec := 0 for _, t := range tracks { - ref := trackRefFrom(t, album.Title, artistName) + ref := trackRefFrom(t, album.Title, names.For(t.ArtistID, artistName)) refs = append(refs, ref) durSec += ref.DurationSec } diff --git a/internal/api/library_test.go b/internal/api/library_test.go index d5d29756..9f4a665f 100644 --- a/internal/api/library_test.go +++ b/internal/api/library_test.go @@ -149,6 +149,34 @@ func TestHandleGetAlbum_HappyPath(t *testing.T) { } } +func TestHandleGetAlbum_EachTrackNamesItsOwnArtist(t *testing.T) { + h, pool := testHandlers(t) + truncateLibrary(t, pool) + various := seedArtist(t, pool, "Various Artists") + first := seedArtist(t, pool, "Harbour Choir") + guest := seedArtist(t, pool, "Ruby Lane") + album := seedAlbum(t, pool, various.ID, "Sunday Morning Static", 2024) + seedTrack(t, pool, album.ID, first.ID, "Low Light", 1, 200_000) + seedTrack(t, pool, album.ID, guest.ID, "Saltlines", 2, 200_000) + + req := httptest.NewRequest(http.MethodGet, "/api/albums/"+uuidToString(album.ID), nil) + w := httptest.NewRecorder() + newLibraryRouter(h).ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status = %d body = %s", w.Code, w.Body.String()) + } + var got AlbumDetail + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v body=%s", err, w.Body.String()) + } + if got.ArtistName != "Various Artists" { + t.Errorf("album artist = %q, want Various Artists", got.ArtistName) + } + if len(got.Tracks) != 2 || got.Tracks[0].ArtistName != "Harbour Choir" || got.Tracks[1].ArtistName != "Ruby Lane" { + t.Errorf("track artists = %+v, want each track's own artist, not the album's", got.Tracks) + } +} + func TestHandleGetAlbum_NoTracks(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) diff --git a/internal/db/artistnames.go b/internal/db/artistnames.go new file mode 100644 index 00000000..0d759eaf --- /dev/null +++ b/internal/db/artistnames.go @@ -0,0 +1,37 @@ +package db + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" + + "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" +) + +// ArtistNames names the artists credited on an album's tracks. A track's own +// artist differs from its album's on a compilation (Various Artists) and on a +// track with a featured guest, so an album's track list names each track by +// its own artist. +type ArtistNames map[pgtype.UUID]string + +// TrackArtistNames reads the artists credited on the album's tracks. +func TrackArtistNames(ctx context.Context, q *dbq.Queries, albumID pgtype.UUID) (ArtistNames, error) { + rows, err := q.ListTrackArtistsForAlbum(ctx, albumID) + if err != nil { + return nil, err + } + out := make(ArtistNames, len(rows)) + for _, r := range rows { + out[r.ID] = r.Name + } + return out, nil +} + +// For is the name of artist id, or fallback when it is unknown (including on +// a nil ArtistNames, as a failed lookup returns). +func (n ArtistNames) For(id pgtype.UUID, fallback string) string { + if name, ok := n[id]; ok && name != "" { + return name + } + return fallback +} diff --git a/internal/db/dbq/artists.sql.go b/internal/db/dbq/artists.sql.go index 2f5080e1..3f5e905b 100644 --- a/internal/db/dbq/artists.sql.go +++ b/internal/db/dbq/artists.sql.go @@ -404,6 +404,40 @@ func (q *Queries) ListArtistsNewest(ctx context.Context, arg ListArtistsNewestPa return items, nil } +const listTrackArtistsForAlbum = `-- name: ListTrackArtistsForAlbum :many +SELECT DISTINCT ar.id, ar.name + FROM artists ar + JOIN tracks t ON t.artist_id = ar.id + WHERE t.album_id = $1 +` + +type ListTrackArtistsForAlbumRow struct { + ID pgtype.UUID + Name string +} + +// The artists credited on an album's tracks. They differ from the album's own +// artist on a compilation and on a track with a featured guest. +func (q *Queries) ListTrackArtistsForAlbum(ctx context.Context, albumID pgtype.UUID) ([]ListTrackArtistsForAlbumRow, error) { + rows, err := q.db.Query(ctx, listTrackArtistsForAlbum, albumID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListTrackArtistsForAlbumRow + for rows.Next() { + var i ListTrackArtistsForAlbumRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const searchArtists = `-- name: SearchArtists :many 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 name ILIKE '%' || $1 || '%' diff --git a/internal/db/queries/artists.sql b/internal/db/queries/artists.sql index b9f3aeaf..5d8b89a9 100644 --- a/internal/db/queries/artists.sql +++ b/internal/db/queries/artists.sql @@ -43,6 +43,14 @@ SELECT COUNT(*) FROM artists; -- name: CountArtistsMatching :one SELECT COUNT(*) FROM artists WHERE name ILIKE '%' || $1::text || '%'; +-- name: ListTrackArtistsForAlbum :many +-- The artists credited on an album's tracks. They differ from the album's own +-- artist on a compilation and on a track with a featured guest. +SELECT DISTINCT ar.id, ar.name + FROM artists ar + JOIN tracks t ON t.artist_id = ar.id + WHERE t.album_id = $1; + -- name: GetArtistsByIDs :many -- Batched lookup used by M5c suggestion attribution to resolve top-3 -- contributing seed UUIDs back to artist names in one round-trip. diff --git a/internal/subsonic/browse.go b/internal/subsonic/browse.go index 99b18a14..5ba26c4f 100644 --- a/internal/subsonic/browse.go +++ b/internal/subsonic/browse.go @@ -11,6 +11,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" + "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" ) @@ -186,9 +187,13 @@ func (b *browseHandlers) getAlbum(w http.ResponseWriter, r *http.Request) { return } gains := replayGains(r.Context(), q, tracks) + // Each song is credited to its own artist: on a compilation or a track + // with a guest, that is not the album's. A failed lookup credits the + // album's artist rather than failing the album. + names, _ := db.TrackArtistNames(r.Context(), q, album.ID) songs := make([]SongRef, 0, len(tracks)) for _, t := range tracks { - songs = append(songs, songRef(t, album.Title, artist.Name, gains[t.ID])) + songs = append(songs, songRef(t, album.Title, names.For(t.ArtistID, artist.Name), gains[t.ID])) } Write(w, r, AlbumResponse{ Envelope: NewEnvelope("ok"), diff --git a/internal/subsonic/getalbum_test.go b/internal/subsonic/getalbum_test.go new file mode 100644 index 00000000..582b3e60 --- /dev/null +++ b/internal/subsonic/getalbum_test.go @@ -0,0 +1,86 @@ +package subsonic + +import ( + "context" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "git.fabledsword.com/bvandeusen/minstrel/internal/db" + "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" +) + +// A compilation's songs are credited to their own performers, as Subsonic +// clients show them, not all to Various Artists. +func TestGetAlbum_EachSongCreditsItsOwnArtist(t *testing.T) { + if testing.Short() { + t.Skip("skipping in -short mode") + } + dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("MINSTREL_TEST_DATABASE_URL not set") + } + if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { + t.Fatalf("migrate: %v", err) + } + pool, err := pgxpool.New(context.Background(), dsn) + if err != nil { + t.Fatalf("pool: %v", err) + } + t.Cleanup(pool.Close) + dbtest.ResetDB(t, pool) + + ctx := context.Background() + q := dbq.New(pool) + artist := func(name string) dbq.Artist { + a, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: name, SortName: name}) + if err != nil { + t.Fatalf("artist %s: %v", name, err) + } + return a + } + various, first, guest := artist("Various Artists"), artist("Harbour Choir"), artist("Ruby Lane") + album, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "Sunday Morning Static", SortTitle: "Sunday Morning Static", ArtistID: various.ID}) + if err != nil { + t.Fatalf("album: %v", err) + } + n1, n2 := int32(1), int32(2) + for _, tr := range []dbq.UpsertTrackParams{ + {Title: "Low Light", AlbumID: album.ID, ArtistID: first.ID, TrackNumber: &n1, FilePath: "/tmp/getalbum-1.flac", DurationMs: 100_000}, + {Title: "Saltlines", AlbumID: album.ID, ArtistID: guest.ID, TrackNumber: &n2, FilePath: "/tmp/getalbum-2.flac", DurationMs: 100_000}, + } { + if _, err := q.UpsertTrack(ctx, tr); err != nil { + t.Fatalf("track %s: %v", tr.Title, err) + } + } + + b := &browseHandlers{pool: pool} + req := httptest.NewRequest(http.MethodGet, "/rest/getAlbum?f=json&id="+uuidToID(album.ID), nil) + w := httptest.NewRecorder() + b.getAlbum(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status = %d body=%s", w.Code, w.Body.String()) + } + var raw struct { + Response struct { + Album AlbumDetail `json:"album"` + } `json:"subsonic-response"` + } + if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil { + t.Fatalf("decode: %v body=%s", err, w.Body.String()) + } + got := raw.Response.Album + if got.Artist != "Various Artists" { + t.Errorf("album artist = %q, want Various Artists", got.Artist) + } + if len(got.Songs) != 2 || got.Songs[0].Artist != "Harbour Choir" || got.Songs[1].Artist != "Ruby Lane" { + t.Errorf("songs = %+v, want each song credited to its own artist", got.Songs) + } +}