diff --git a/internal/coverart/sidecar.go b/internal/coverart/sidecar.go index 84b8e67a..1a533aa1 100644 --- a/internal/coverart/sidecar.go +++ b/internal/coverart/sidecar.go @@ -7,9 +7,11 @@ package coverart import ( + "cmp" "context" "os" "path/filepath" + "slices" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" ) @@ -57,3 +59,36 @@ func ResolveAlbumPath(ctx context.Context, q *dbq.Queries, album dbq.Album) stri } return FindSidecar(filepath.Dir(tracks[0].FilePath)) } + +// artistAlbumsTried bounds how many of an artist's albums ResolveArtistPath +// looks through for a cover, so an artist with many coverless albums costs a +// few lookups rather than one per album. +const artistAlbumsTried = 10 + +// ResolveArtistPath returns the image file to show for an artist: the +// artist picture the artist-art providers fetched, if its file is there, or +// else the cover of the artist's most recently added album that has one, +// which is what Minstrel's artist cards show. "" means no image was found. +func ResolveArtistPath(ctx context.Context, q *dbq.Queries, artist dbq.Artist) string { + if artist.ArtistThumbPath != nil && *artist.ArtistThumbPath != "" { + if _, err := os.Stat(*artist.ArtistThumbPath); err == nil { + return *artist.ArtistThumbPath + } + } + albums, err := q.ListAlbumsByArtist(ctx, artist.ID) + if err != nil { + return "" + } + slices.SortStableFunc(albums, func(a, b dbq.Album) int { + return cmp.Compare(b.CreatedAt.Time.UnixNano(), a.CreatedAt.Time.UnixNano()) + }) + for i, album := range albums { + if i == artistAlbumsTried { + break + } + if path := ResolveAlbumPath(ctx, q, album); path != "" { + return path + } + } + return "" +} diff --git a/internal/subsonic/artistart_test.go b/internal/subsonic/artistart_test.go new file mode 100644 index 00000000..0cd0256d --- /dev/null +++ b/internal/subsonic/artistart_test.go @@ -0,0 +1,84 @@ +package subsonic + +import ( + "context" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" +) + +// coverArt fetches getCoverArt for id and returns the image bytes, or the +// Subsonic error code when it answered with one. +func (f picksFixture) coverArt(t *testing.T, id string) (string, int) { + t.Helper() + m := newMediaHandlers(f.pool, nil, slog.New(slog.NewTextHandler(io.Discard, nil))) + w := httptest.NewRecorder() + m.handleGetCoverArt(w, httptest.NewRequest(http.MethodGet, "/rest/getCoverArt?f=json&id="+id, nil). + WithContext(context.WithValue(context.Background(), userCtxKey, f.user))) + if w.Header().Get("Content-Type") == "image/jpeg" { + return w.Body.String(), 0 + } + var env struct { + Response struct { + Error *Error `json:"error"` + } `json:"subsonic-response"` + } + if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil || env.Response.Error == nil { + t.Fatalf("getCoverArt %s: neither an image nor an error: %s", id, w.Body.String()) + } + return "", env.Response.Error.Code +} + +// An artist's cover art is their own picture when one was fetched, and +// otherwise the cover of their most recently added album that has one. +func TestGetCoverArt_AnArtistsPictureOrTheirNewestAlbumCover(t *testing.T) { + f := seedPicks(t) + dir := t.TempDir() + write := func(name, body string) string { + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + return path + } + artist := uuidToID(f.artist.ID) + // Every song sits in a folder with no cover.jpg or folder.jpg, so an + // album has a cover only when it is given one below; Gone Tide never is. + f.exec(t, `UPDATE tracks SET file_path = $1 || '/songs/' || title || '.flac'`, dir) + + if _, code := f.coverArt(t, artist); code != ErrDataNotFound { + t.Errorf("no art anywhere: code %d, want %d", code, ErrDataNotFound) + } + + f.exec(t, `UPDATE albums SET created_at = '2020-01-01', cover_art_path = $2 WHERE id = $1`, f.albums["Lantern Hours"].ID, write("old.jpg", "old")) + f.exec(t, `UPDATE albums SET created_at = '2024-01-01', cover_art_path = $2 WHERE id = $1`, f.albums["Paper Boats"].ID, write("new.jpg", "new")) + f.exec(t, `UPDATE albums SET created_at = '2025-01-01' WHERE id = $1`, f.albums["Gone Tide"].ID) + if got, code := f.coverArt(t, artist); got != "new" { + t.Errorf("no artist picture: got %q (code %d), want the newest album cover", got, code) + } + + f.exec(t, `UPDATE artists SET artist_thumb_path = $2 WHERE id = $1`, f.artist.ID, write("thumb.jpg", "thumb")) + if got, code := f.coverArt(t, artist); got != "thumb" { + t.Errorf("with an artist picture: got %q (code %d), want the picture", got, code) + } + f.exec(t, `UPDATE artists SET artist_thumb_path = $2 WHERE id = $1`, f.artist.ID, filepath.Join(dir, "gone.jpg")) + if got, code := f.coverArt(t, artist); got != "new" { + t.Errorf("a picture whose file is gone: got %q (code %d), want the newest album cover", got, code) + } + + // Albums and songs still answer with the album's own cover. + for id, want := range map[string]string{ + uuidToID(f.albums["Lantern Hours"].ID): "old", + uuidToID(f.tracks["Dusk"].ID): "old", + uuidToID(f.tracks["Gale"].ID): "new", + } { + if got, code := f.coverArt(t, id); got != want { + t.Errorf("cover art %s: got %q (code %d), want %q", id, got, code, want) + } + } +} diff --git a/internal/subsonic/browse.go b/internal/subsonic/browse.go index 42ea6443..ed2dd4cf 100644 --- a/internal/subsonic/browse.go +++ b/internal/subsonic/browse.go @@ -148,6 +148,7 @@ func (b *browseHandlers) getArtist(w http.ResponseWriter, r *http.Request) { Artist: ArtistDetail{ ID: uuidToID(artist.ID), Name: artist.Name, + CoverArt: uuidToID(artist.ID), AlbumCount: len(albums), Albums: refs, }, diff --git a/internal/subsonic/info_test.go b/internal/subsonic/info_test.go index 776bbd5c..8d2873e5 100644 --- a/internal/subsonic/info_test.go +++ b/internal/subsonic/info_test.go @@ -166,7 +166,7 @@ func TestGetArtistInfo_IsTheMBIDAndSimilarArtistsInTheLibrary(t *testing.T) { if code := call(t, f.browse().getArtistInfo2, f.user, "id="+id, &got); code != 0 { t.Fatalf("getArtistInfo2 %s: error %d", id, code) } - want := ArtistInfo{MusicBrainzID: mbid, SimilarArtists: []ArtistRef{{ID: uuidToID(other.ID), Name: "Quiet Harbour", AlbumCount: 1}}} + want := ArtistInfo{MusicBrainzID: mbid, SimilarArtists: []ArtistRef{{ID: uuidToID(other.ID), Name: "Quiet Harbour", CoverArt: uuidToID(other.ID), AlbumCount: 1}}} if got.ArtistInfo2.MusicBrainzID != want.MusicBrainzID || !slices.Equal(got.ArtistInfo2.SimilarArtists, want.SimilarArtists) { t.Errorf("getArtistInfo2 %s = %+v, want %+v", id, got.ArtistInfo2, want) } diff --git a/internal/subsonic/stream.go b/internal/subsonic/stream.go index 38b80078..9a4eb92e 100644 --- a/internal/subsonic/stream.go +++ b/internal/subsonic/stream.go @@ -13,6 +13,7 @@ import ( "time" "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" @@ -108,28 +109,33 @@ func (m *mediaHandlers) handleGetCoverArt(w http.ResponseWriter, r *http.Request } q := dbq.New(m.pool) - album, albumErr := q.GetAlbumByID(r.Context(), id) - if albumErr != nil { - // Fall back: maybe the id is a track. Resolve through its album_id. - track, terr := q.GetTrackByID(r.Context(), id) - if terr != nil { - WriteFail(w, r, ErrDataNotFound, "Cover art not found") - return - } - album, albumErr = q.GetAlbumByID(r.Context(), track.AlbumID) - if albumErr != nil { - WriteFail(w, r, ErrDataNotFound, "Cover art not found") - return - } - } - - if path := resolveAlbumCoverPath(r.Context(), q, album); path != "" { + if path := coverArtPath(r.Context(), q, id); path != "" { serveImage(w, r, path) return } WriteFail(w, r, ErrDataNotFound, "Cover art not found") } +// coverArtPath is the image for a cover-art id: an album's cover, a song's +// album cover, or an artist's picture (coverart.ResolveArtistPath). "" when +// the id names none of them or there is no image. +func coverArtPath(ctx context.Context, q *dbq.Queries, id pgtype.UUID) string { + if album, err := q.GetAlbumByID(ctx, id); err == nil { + return resolveAlbumCoverPath(ctx, q, album) + } + if track, err := q.GetTrackByID(ctx, id); err == nil { + album, err := q.GetAlbumByID(ctx, track.AlbumID) + if err != nil { + return "" + } + return resolveAlbumCoverPath(ctx, q, album) + } + if artist, err := q.GetArtistByID(ctx, id); err == nil { + return coverart.ResolveArtistPath(ctx, q, artist) + } + return "" +} + // resolveAlbumCoverPath delegates to coverart.ResolveAlbumPath; kept as a // local alias so the call sites in this file read naturally. func resolveAlbumCoverPath(ctx context.Context, q *dbq.Queries, album dbq.Album) string { diff --git a/internal/subsonic/types.go b/internal/subsonic/types.go index e3d1456e..001f28fc 100644 --- a/internal/subsonic/types.go +++ b/internal/subsonic/types.go @@ -105,9 +105,13 @@ type IndexesResponse struct { // // Like SongRef it carries no XMLName: the field that holds it names the // element, "artist" in listings and "similarArtist" in artist info. +// +// CoverArt is the artist's own id, which getCoverArt answers with the +// artist's picture. type ArtistRef struct { ID string `json:"id" xml:"id,attr"` Name string `json:"name" xml:"name,attr"` + CoverArt string `json:"coverArt,omitempty" xml:"coverArt,attr,omitempty"` AlbumCount int `json:"albumCount,omitempty" xml:"albumCount,attr,omitempty"` } @@ -116,6 +120,7 @@ type ArtistDetail struct { XMLName xml.Name `json:"-" xml:"artist"` ID string `json:"id" xml:"id,attr"` Name string `json:"name" xml:"name,attr"` + CoverArt string `json:"coverArt,omitempty" xml:"coverArt,attr,omitempty"` AlbumCount int `json:"albumCount" xml:"albumCount,attr"` Albums []AlbumRef `json:"album" xml:"album"` } @@ -268,6 +273,7 @@ func artistRef(a dbq.Artist, albumCount int) ArtistRef { return ArtistRef{ ID: uuidToID(a.ID), Name: a.Name, + CoverArt: uuidToID(a.ID), AlbumCount: albumCount, } }