diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryMappers.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryMappers.kt index b90e9359..31847105 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryMappers.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryMappers.kt @@ -6,6 +6,7 @@ import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.models.ArtistRef import com.fabledsword.minstrel.models.TrackRef +import com.fabledsword.minstrel.models.artistImagePath import com.fabledsword.minstrel.models.wire.AlbumDetailWire import com.fabledsword.minstrel.models.wire.AlbumWire import com.fabledsword.minstrel.models.wire.ArtistDetailWire @@ -66,11 +67,14 @@ fun AlbumDetailWire.toAlbumEntity(): CachedAlbumEntity = // source of truth for cache-first reads; mapping to a domain type here // keeps Room types out of the UI layer. +// An artist whose picture the server fetched shows it; the rest fall back +// to an album cover through [coverAlbumId]. fun CachedArtistEntity.toDomain(coverAlbumId: String = ""): ArtistRef = ArtistRef( id = id, name = name, sortName = sortName, + coverUrl = if (artistThumbPath.isNullOrEmpty()) "" else artistImagePath(id), coverAlbumId = coverAlbumId, ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt index 432dcff8..d92a62a2 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt @@ -9,3 +9,11 @@ package com.fabledsword.minstrel.models */ fun albumCoverPath(albumId: String): String = if (albumId.isEmpty()) "" else "http://placeholder.invalid/api/albums/$albumId/cover" + +/** + * Absolute URL of an artist's image, or "" when [artistId] is blank. The + * server answers with the artist's picture, or else their newest album + * cover, through the same placeholder host as [albumCoverPath]. + */ +fun artistImagePath(artistId: String): String = + if (artistId.isEmpty()) "" else "http://placeholder.invalid/api/artists/$artistId/image" diff --git a/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryMappersTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryMappersTest.kt new file mode 100644 index 00000000..7f91c122 --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryMappersTest.kt @@ -0,0 +1,25 @@ +package com.fabledsword.minstrel.library.data + +import com.fabledsword.minstrel.cache.db.entities.CachedArtistEntity +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class LibraryMappersTest { + @Test + fun `a cached artist with a fetched picture shows the artist image`() { + val artist = CachedArtistEntity( + id = "r1", + name = "Tin Orchard", + sortName = "Tin Orchard", + artistThumbPath = "/data/artist-art/r1/thumb.jpg", + ).toDomain(coverAlbumId = "a1") + assertEquals("http://placeholder.invalid/api/artists/r1/image", artist.displayCoverUrl) + } + + @Test + fun `a cached artist without a picture falls back to an album cover`() { + val artist = CachedArtistEntity(id = "r1", name = "Tin Orchard", sortName = "Tin Orchard") + .toDomain(coverAlbumId = "a1") + assertEquals("http://placeholder.invalid/api/albums/a1/cover", artist.displayCoverUrl) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/models/CoverUrlsTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/models/CoverUrlsTest.kt index ecbf67f7..a5595692 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/models/CoverUrlsTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/models/CoverUrlsTest.kt @@ -13,4 +13,14 @@ class CoverUrlsTest { fun `albumCoverPath is empty for a blank id`() { assertEquals("", albumCoverPath("")) } + + @Test + fun `artistImagePath builds the placeholder artist image URL`() { + assertEquals("http://placeholder.invalid/api/artists/r1/image", artistImagePath("r1")) + } + + @Test + fun `artistImagePath is empty for a blank id`() { + assertEquals("", artistImagePath("")) + } } diff --git a/internal/api/api.go b/internal/api/api.go index b7cea155..6d1da824 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -134,6 +134,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev authed.Get("/artists/{id}/tracks", h.handleGetArtistTracks) authed.Get("/artists/{id}/similar", h.handleGetSimilarArtists) authed.Get("/artists/{id}/top-tracks", h.handleGetArtistTopTracks) + authed.Get("/artists/{id}/image", h.handleGetArtistImage) authed.Get("/albums/{id}", h.handleGetAlbum) authed.Get("/albums/{id}/cover", h.handleGetCover) authed.Get("/library/shuffle", h.handleLibraryShuffle) diff --git a/internal/api/artistimage_test.go b/internal/api/artistimage_test.go new file mode 100644 index 00000000..c108c3ef --- /dev/null +++ b/internal/api/artistimage_test.go @@ -0,0 +1,107 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// getArt fetches path and returns the image body, or "" with the status +// when the answer is not an image. +func getArt(t *testing.T, h *handlers, path string) (string, int) { + t.Helper() + w := httptest.NewRecorder() + newLibraryRouter(h).ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + if w.Code != http.StatusOK { + return "", w.Code + } + return w.Body.String(), w.Code +} + +// coverURLs returns the cover_url of every artist in the alphabetical +// listing, by name. +func coverURLs(t *testing.T, h *handlers) map[string]string { + t.Helper() + w := httptest.NewRecorder() + newLibraryRouter(h).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/artists", nil)) + var got Page[ArtistRef] + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode artists: %v body=%s", err, w.Body.String()) + } + out := map[string]string{} + for _, a := range got.Items { + out[a.Name] = a.CoverURL + } + return out +} + +func detailCoverURL(t *testing.T, h *handlers, id string) string { + t.Helper() + w := httptest.NewRecorder() + newLibraryRouter(h).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/artists/"+id, nil)) + var got ArtistDetail + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode artist: %v body=%s", err, w.Body.String()) + } + return got.CoverURL +} + +func exec(t *testing.T, pool *pgxpool.Pool, sql string, args ...any) { + t.Helper() + if _, err := pool.Exec(context.Background(), sql, args...); err != nil { + t.Fatalf("%s: %v", sql, err) + } +} + +// An artist's image is the picture fetched for them, or else their newest +// album cover; artist listings point at it when there is a picture, and the +// artist page whenever the artist has albums. +func TestArtistImage_PictureOrNewestAlbumCover(t *testing.T) { + h, pool := testHandlers(t) + truncateLibrary(t, pool) + 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 + } + orchard := seedArtist(t, pool, "Tin Orchard") + album := seedAlbum(t, pool, orchard.ID, "Paper Boats", 2012) + exec(t, pool, `UPDATE albums SET cover_art_path = $2 WHERE id = $1`, album.ID, write("boats.jpg", "boats")) + quiet := seedArtist(t, pool, "Quiet Field") + orchardImage := "/api/artists/" + uuidToString(orchard.ID) + "/image" + albumCover := "/api/albums/" + uuidToString(album.ID) + "/cover" + + if got, code := getArt(t, h, orchardImage); got != "boats" { + t.Errorf("no picture: got %q (status %d), want the album cover", got, code) + } + if got := coverURLs(t, h); got["Tin Orchard"] != albumCover || got["Quiet Field"] != "" { + t.Errorf("no picture: listing cover_url = %v, want the album cover for Tin Orchard and none for Quiet Field", got) + } + + exec(t, pool, `UPDATE artists SET artist_thumb_path = $2 WHERE id = $1`, orchard.ID, write("thumb.jpg", "thumb")) + if got, code := getArt(t, h, orchardImage); got != "thumb" { + t.Errorf("with a picture: got %q (status %d), want the picture", got, code) + } + if got := coverURLs(t, h); got["Tin Orchard"] != orchardImage { + t.Errorf("with a picture: listing cover_url = %q, want %q", got["Tin Orchard"], orchardImage) + } + + if got := detailCoverURL(t, h, uuidToString(orchard.ID)); got != orchardImage { + t.Errorf("artist page cover_url = %q, want %q", got, orchardImage) + } + if got := detailCoverURL(t, h, uuidToString(quiet.ID)); got != "" { + t.Errorf("artist page with no albums: cover_url = %q, want none", got) + } + if _, code := getArt(t, h, "/api/artists/"+uuidToString(quiet.ID)+"/image"); code != http.StatusNotFound { + t.Errorf("no picture and no albums: status %d, want 404", code) + } +} diff --git a/internal/api/convert.go b/internal/api/convert.go index 7df3914d..9460e5ee 100644 --- a/internal/api/convert.go +++ b/internal/api/convert.go @@ -85,26 +85,41 @@ func streamURLWithExt(trackID pgtype.UUID, ext string) string { return streamURL(trackID) + "." + ext } -// artistRefFrom projects a dbq.Artist into an ArtistRef without cover. -// albumCount must be pre-computed by the caller. Used by code paths that -// don't have a representative-album lookup at hand (artist detail, search, -// liked-artists list). +// artistImageURL returns the /api relative URL of an artist's image. +func artistImageURL(artistID pgtype.UUID) string { + return "/api/artists/" + uuidToString(artistID) + "/image" +} + +// hasArtistPicture reports whether the artist-art providers fetched a +// picture for a. +func hasArtistPicture(a dbq.Artist) bool { + return a.ArtistThumbPath != nil && *a.ArtistThumbPath != "" +} + +// artistRefFrom projects a dbq.Artist into an ArtistRef. albumCount must be +// pre-computed by the caller. CoverURL is the artist's picture when one was +// fetched, and empty otherwise: these code paths (artist detail, search, +// liked-artists list) have no representative-album lookup at hand. func artistRefFrom(a dbq.Artist, albumCount int) ArtistRef { - return ArtistRef{ + ref := ArtistRef{ ID: uuidToString(a.ID), Name: a.Name, SortName: a.SortName, AlbumCount: albumCount, } + if hasArtistPicture(a) { + ref.CoverURL = artistImageURL(a.ID) + } + return ref } -// artistRefFromCovered projects a dbq.Artist into an ArtistRef with the -// derived CoverURL populated from a representative album id (nullable). -// Used by /api/home and /api/artists?sort=alpha which carry the lookup -// in the same query. +// artistRefFromCovered projects a dbq.Artist into an ArtistRef whose CoverURL +// is the artist's picture when one was fetched, or else the cover of a +// representative album id (nullable). Used by /api/home and +// /api/artists?sort=alpha, which carry the album lookup in the same query. func artistRefFromCovered(a dbq.Artist, albumCount int, coverAlbumID pgtype.UUID) ArtistRef { ref := artistRefFrom(a, albumCount) - if coverAlbumID.Valid { + if ref.CoverURL == "" && coverAlbumID.Valid { ref.CoverURL = coverURL(coverAlbumID) } return ref diff --git a/internal/api/library.go b/internal/api/library.go index e407943e..536841ce 100644 --- a/internal/api/library.go +++ b/internal/api/library.go @@ -140,6 +140,12 @@ func (h *handlers) handleGetArtist(w http.ResponseWriter, r *http.Request) { Albums: refs, Genres: nonNilStrings(genres), } + // An artist with albums always gets the image route: it serves the + // artist's picture, or else their newest album cover, so the detail + // header and Subsonic apps show the same image. + if len(rows) > 0 { + detail.CoverURL = artistImageURL(artist.ID) + } if artist.Mbid != nil { detail.MBID = *artist.Mbid } diff --git a/internal/api/library_test.go b/internal/api/library_test.go index 9426bffe..5c7bae5a 100644 --- a/internal/api/library_test.go +++ b/internal/api/library_test.go @@ -38,6 +38,7 @@ func newLibraryRouter(h *handlers) chi.Router { r.Get("/api/artists/{id}", h.handleGetArtist) r.Get("/api/albums/{id}", h.handleGetAlbum) r.Get("/api/albums/{id}/cover", h.handleGetCover) + r.Get("/api/artists/{id}/image", h.handleGetArtistImage) r.Get("/api/tracks/{id}", h.handleGetTrack) r.With(injectFakeUserForTest).Get("/api/tracks/{id}/stream", h.handleGetStream) r.Get("/api/search", h.handleSearch) diff --git a/internal/api/media.go b/internal/api/media.go index 4a577a05..ccf7e11c 100644 --- a/internal/api/media.go +++ b/internal/api/media.go @@ -90,17 +90,37 @@ func (h *handlers) handleGetCover(w http.ResponseWriter, r *http.Request) { writeErr(w, apiErr) return } - path := resolveAlbumCoverPath(r.Context(), q, album) + h.serveArt(w, r, resolveAlbumCoverPath(r.Context(), q, album)) +} + +// handleGetArtistImage implements GET /api/artists/{id}/image: the picture +// the artist-art providers fetched, or else the cover of the artist's most +// recently added album that has one (coverart.ResolveArtistPath). Subsonic +// apps get the same image from getCoverArt. +func (h *handlers) handleGetArtistImage(w http.ResponseWriter, r *http.Request) { + q := dbq.New(h.pool) + artist, apiErr := resolveByID(r, "id", q.GetArtistByID, "artist") + if apiErr != nil { + writeErr(w, apiErr) + return + } + h.serveArt(w, r, coverart.ResolveArtistPath(r.Context(), q, artist)) +} + +// serveArt serves the image file at path, or 404 when path is "" or the +// file is gone. http.ServeContent gives clients Range, If-Modified-Since and +// ETag handling. +func (h *handlers) serveArt(w http.ResponseWriter, r *http.Request, path string) { if path == "" { writeErr(w, &apierror.Error{Status: 404, Code: "not_found", Message: "cover not found"}) return } f, err := os.Open(path) if err != nil { - // resolveAlbumCoverPath saw the file a moment ago; if it vanished - // between stat and open, treat it the same as no-art — the user - // experience (404) matches, and 500 would misleadingly imply a server - // bug rather than a filesystem race. + // The resolver saw the file a moment ago; if it vanished between + // stat and open, treat it the same as no art: the user experience + // (404) matches, and 500 would misleadingly imply a server bug + // rather than a filesystem race. writeErr(w, &apierror.Error{Status: 404, Code: "not_found", Message: "cover not found"}) return } @@ -112,8 +132,8 @@ func (h *handlers) handleGetCover(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", imageContentType(path)) - // Cover bytes change rarely (cover-source enrichment, manual rescan, - // rare MBID-driven re-fetch). One-day max-age + must-revalidate means + // Art changes rarely (cover-source enrichment, manual rescan, rare + // MBID-driven re-fetch). One-day max-age + must-revalidate means // clients skip the conditional GET for the bulk of a session, but // stale art clears within 24h after a re-scan. ServeContent below // still emits Last-Modified for the conditional path when needed. diff --git a/internal/api/types.go b/internal/api/types.go index 561449d1..fb0ce9df 100644 --- a/internal/api/types.go +++ b/internal/api/types.go @@ -42,9 +42,10 @@ type Page[T any] struct { // ArtistRef is the lightweight artist shape used in lists and search results. // SortName is exposed so the SPA's alphabetical-grid divider can group rows -// by the catalogue sort order ("The Copper Lanterns" → "C"). CoverURL is derived from -// a representative album (most-recent with cover_art_path); empty when the -// artist's discography has no cover art. +// by the catalogue sort order ("The Copper Lanterns" → "C"). CoverURL is the +// artist's picture (/api/artists/{id}/image) when one was fetched, else a +// representative album's cover (most-recent with cover_art_path) where the +// listing looks one up; empty when there is neither. type ArtistRef struct { ID string `json:"id"` Name string `json:"name"` diff --git a/web/src/routes/artists/[id]/+page.svelte b/web/src/routes/artists/[id]/+page.svelte index 768dd299..24dbfdb4 100644 --- a/web/src/routes/artists/[id]/+page.svelte +++ b/web/src/routes/artists/[id]/+page.svelte @@ -10,6 +10,7 @@ } from '#lib/api/queries.js'; import { pageTitle } from '#lib/branding.js'; import AlbumCard from '#lib/components/AlbumCard.svelte'; + import Cover from '#lib/components/Cover.svelte'; import ArtistCard from '#lib/components/ArtistCard.svelte'; import CompactTrackCard from '#lib/components/CompactTrackCard.svelte'; import HorizontalScrollRow from '#lib/components/HorizontalScrollRow.svelte'; @@ -78,6 +79,9 @@ {:else if query.data} {@const detail = query.data}
+
+ +

{detail.name}