From 246cdc63d38ef26935b4042645396c0386349732 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Sat, 14 Nov 2026 10:29:08 +0100 Subject: [PATCH] feat: Recently added on Home, with a newest-first order for albums I can now see on Home what I added to the library lately. - GET /albums takes sort=recent: the albums added last first, by the date of the newest file of the album that is not missing, then the newest album. The default stays by title and any other value is invalid_input. - The albums shelf on Home is Recently added and asks for that order; See all leads to /albums?sort=recent, which the albums page understands. - English and Italian. --- README.md | 2 +- internal/api/http/catalog_test.go | 5 ++++ internal/api/http/handlers_catalog.go | 2 +- internal/api/openapi/openapi.yaml | 8 ++++++- internal/catalog/catalog.go | 10 ++++++++ internal/catalog/catalog_test.go | 17 ++++++++++++++ internal/storage/catalog.go | 8 ++++++- internal/storage/catalog_test.go | 34 +++++++++++++++++++++++++++ web/src/api/catalog.ts | 7 +++--- web/src/api/schema.d.ts | 6 ++++- web/src/i18n/locales/en.json | 1 + web/src/i18n/locales/it.json | 1 + web/src/pages/AlbumsPage.tsx | 5 ++-- web/src/pages/HomePage.test.tsx | 18 ++++++++++---- web/src/pages/HomePage.tsx | 6 ++--- web/src/pages/pages.test.tsx | 16 +++++++++++++ 16 files changed, 129 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index c7d3472..f88cac0 100644 --- a/README.md +++ b/README.md @@ -288,7 +288,7 @@ Everything lives under `/api/v1`. Bodies are JSON. Errors always look like `{"er | anyone | `POST /auth/register` | Create the first user (admin). Closed afterwards. | | anyone | `POST /auth/login`, `/auth/refresh`, `/auth/logout` | Open, renew and end a session. | | signed in | `GET /auth/me`, `POST /auth/password` | Your account; change your password (signs you out everywhere). | -| signed in | `GET /artists`, `/albums`, `/tracks` and `/…/{id}` | Browse and search. Query: `q`, `limit` (default 50, max 200), `offset`, `library_id`, `artist_id`, `album_id`. | +| signed in | `GET /artists`, `/albums`, `/tracks` and `/…/{id}` | Browse and search. Query: `q`, `limit` (default 50, max 200), `offset`, `library_id`, `artist_id`, `album_id`, and for `/albums` `sort=recent` (the albums added last first, by the date of their newest file; the default is by title). | | signed in | `GET /artists/{id}/tags` | What Last.fm and MusicBrainz say about the artist's kind of music, from each provider that is on. | | signed in | `GET`, `HEAD /artists/{id}/image`, `GET /artists/{id}/image/credit` | A free picture of the artist from Wikimedia Commons (query `size=small\|large`, also `?access_token=`) and its credit. | | signed in | `GET /artists/{id}/description` | What Wikipedia says about the artist, with its page and licence, from the Wikipedia provider when an admin switched it on. | diff --git a/internal/api/http/catalog_test.go b/internal/api/http/catalog_test.go index 58b0c83..cbc63b3 100644 --- a/internal/api/http/catalog_test.go +++ b/internal/api/http/catalog_test.go @@ -185,6 +185,11 @@ func TestCatalogQueryParametersReachTheService(t *testing.T) { t.Errorf("album filter = %+v (unset paging must stay 0 for the service to default)", fc.last) } + do(t, h, "GET", "/api/v1/albums?sort=recent", tok, nil) + if fc.last.Sort != "recent" { + t.Errorf("album sort = %q", fc.last.Sort) + } + // Special characters survive URL decoding. do(t, h, "GET", "/api/v1/artists?q=100%25+%26+more", tok, nil) if fc.last.Query != "100% & more" { diff --git a/internal/api/http/handlers_catalog.go b/internal/api/http/handlers_catalog.go index 8ec1367..cf63891 100644 --- a/internal/api/http/handlers_catalog.go +++ b/internal/api/http/handlers_catalog.go @@ -80,7 +80,7 @@ func toTrackJSON(t catalog.Track) trackJSON { // parseFilter reads q, limit, offset and the id filters from the query string. // Unset values stay zero so the service can apply its defaults. func parseFilter(c *gin.Context) (catalog.Filter, bool) { - f := catalog.Filter{Query: c.Query("q")} + f := catalog.Filter{Query: c.Query("q"), Sort: c.Query("sort")} for _, p := range []struct { name string dst *int64 diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml index 981b6e7..28e6b22 100644 --- a/internal/api/openapi/openapi.yaml +++ b/internal/api/openapi/openapi.yaml @@ -2432,10 +2432,16 @@ paths: operationId: listAlbums summary: List albums description: | - Albums with a playable track, sorted by title. `artist_id` matches the albums an artist + Albums with a playable track, sorted by title, or with `sort=recent` the ones added last first (by the date of + the newest file of the album that is not missing, which is the best the index knows, then the album that came + last). `artist_id` matches the albums an artist owns plus those where it is credited on a playable track, the same set as its `album_count`. security: [{bearerAuth: []}] parameters: + - name: sort + in: query + description: "`title` (the default) or `recent`. Anything else is `invalid_input`." + schema: {type: string, enum: [title, recent], default: title} - {$ref: '#/components/parameters/Q'} - {$ref: '#/components/parameters/Limit'} - {$ref: '#/components/parameters/Offset'} diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index a3fa656..68a5d8b 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -20,6 +20,12 @@ var ( ErrInvalidQuery = errors.New("invalid query") ) +// The orders of a list of albums. +const ( + SortTitle = "title" + SortRecent = "recent" // by the date of the newest file of the album that is not missing, then the newest album +) + // Paging and search bounds. const ( DefaultLimit = 50 @@ -34,6 +40,7 @@ type Filter struct { LibraryID int64 // only items with a playable file in this library ArtistID int64 // albums: album artist; tracks: credited artist AlbumID int64 // tracks only + Sort string // albums only: "" or SortTitle (by title), SortRecent (the newest files first) Limit int Offset int } @@ -145,6 +152,9 @@ func (s *Service) Albums(ctx context.Context, f Filter) (Page[Album], error) { if err != nil { return Page[Album]{}, err } + if f.Sort != "" && f.Sort != SortTitle && f.Sort != SortRecent { + return Page[Album]{}, fmt.Errorf("%w: sort must be title or recent", ErrInvalidQuery) + } return s.store.ListAlbums(ctx, f) } diff --git a/internal/catalog/catalog_test.go b/internal/catalog/catalog_test.go index 076a4a4..49a7626 100644 --- a/internal/catalog/catalog_test.go +++ b/internal/catalog/catalog_test.go @@ -154,3 +154,20 @@ func TestQueryRejectsNULAndInvalidUTF8(t *testing.T) { t.Errorf("valid Unicode rejected: %v", err) } } + +func TestAlbumsCanBeSortedByTitleOrByWhenTheyWereAdded(t *testing.T) { + for _, sortBy := range []string{"", "title", "recent"} { + st := &recordingStore{} + if _, err := NewService(st).Albums(context.Background(), Filter{Sort: sortBy}); err != nil { + t.Errorf("sort %q: %v", sortBy, err) + } + if st.albumFilter.Sort != sortBy { + t.Errorf("the store saw sort %q, want %q", st.albumFilter.Sort, sortBy) + } + } + for _, sortBy := range []string{"loudest", "Recent", "title desc"} { + if _, err := NewService(&recordingStore{}).Albums(context.Background(), Filter{Sort: sortBy}); !errors.Is(err, ErrInvalidQuery) { + t.Errorf("sort %q: err = %v, want ErrInvalidQuery", sortBy, err) + } + } +} diff --git a/internal/storage/catalog.go b/internal/storage/catalog.go index ea9b591..4ccdbde 100644 --- a/internal/storage/catalog.go +++ b/internal/storage/catalog.go @@ -290,10 +290,16 @@ func (r *CatalogRepo) listAlbums(ctx context.Context, f catalog.Filter, id int64 return page, nil } + order := r.binary("al.title_key") + ", al.id" + if f.Sort == catalog.SortRecent { + // The newest file of the album that is there, then the album that came last. + order = `COALESCE((SELECT MAX(af.mtime_unix) FROM audio_files af JOIN tracks tt ON tt.id = af.track_id + WHERE tt.album_id = al.id AND af.missing_at IS NULL), 0) DESC, al.id DESC` + } rows, err := r.db.QueryContext(ctx, `SELECT al.id, al.title, al.artist_id, ar.name FROM albums al LEFT JOIN artists ar ON ar.id = al.artist_id - WHERE `+w.sql()+` ORDER BY `+r.binary("al.title_key")+`, al.id LIMIT ? OFFSET ?`, + WHERE `+w.sql()+` ORDER BY `+order+` LIMIT ? OFFSET ?`, append(append([]any{}, w.args...), f.Limit, f.Offset)...) if err != nil { return page, fmt.Errorf("list albums: %w", err) diff --git a/internal/storage/catalog_test.go b/internal/storage/catalog_test.go index 4ac770a..8c2732f 100644 --- a/internal/storage/catalog_test.go +++ b/internal/storage/catalog_test.go @@ -552,3 +552,37 @@ func TestCatalogArtistAlbumCountMatchesTheirAlbumList(t *testing.T) { } }) } + +func TestCatalogAlbumsCanComeNewestFirst(t *testing.T) { + forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { + s := seedCatalog(t, db) + ctx := context.Background() + // The date of the newest file that is there: Kind of Blue is the newest, then Various Hits, then Post, then OK Computer. + // Ghost is a file of OK Computer that is gone: its date, the newest of all, does not count. + for prefix, mtime := range map[string]int64{"m/%": 4000, "v/%": 3000, "b/%": 2000, "r/%": 1000} { + if _, err := db.Exec("UPDATE audio_files SET mtime_unix = ? WHERE rel_path LIKE ?", mtime, prefix); err != nil { + t.Fatal(err) + } + } + if _, err := db.Exec("UPDATE audio_files SET mtime_unix = 9000 WHERE track_id = ?", s.track["Ghost"]); err != nil { + t.Fatal(err) + } + got, err := s.repo.ListAlbums(ctx, catalog.Filter{Sort: "recent", Limit: 50}) + if err != nil { + t.Fatal(err) + } + if want := []string{"Kind of Blue", "Various Hits", "Post", "OK Computer"}; !equal(albumTitles(got), want) || got.Total != 4 { + t.Errorf("newest first = %v (total %d), want %v", albumTitles(got), got.Total, want) + } + // A page of it is a page of that order. + page2, _ := s.repo.ListAlbums(ctx, catalog.Filter{Sort: "recent", Limit: 2, Offset: 1}) + if want := []string{"Various Hits", "Post"}; !equal(albumTitles(page2), want) { + t.Errorf("second page = %v, want %v", albumTitles(page2), want) + } + // Without a sort it is still by title. + byTitle, _ := s.repo.ListAlbums(ctx, catalog.Filter{Limit: 50}) + if want := []string{"Kind of Blue", "OK Computer", "Post", "Various Hits"}; !equal(albumTitles(byTitle), want) { + t.Errorf("by title = %v", albumTitles(byTitle)) + } + }) +} diff --git a/web/src/api/catalog.ts b/web/src/api/catalog.ts index 719a579..6bce21e 100644 --- a/web/src/api/catalog.ts +++ b/web/src/api/catalog.ts @@ -44,9 +44,10 @@ export function useArtistList(q?: string, list: ListOptions = {}) { return usePagedList('/artists', { q: q || undefined }, list) } -export function useAlbumList(opts: { q?: string; artistId?: number } & ListOptions = {}) { - const { q, artistId, ...list } = opts - return usePagedList('/albums', { q: q || undefined, artist_id: artistId }, list) +/** `sort: 'recent'` asks for the albums added last first; without it they come by title. */ +export function useAlbumList(opts: { q?: string; artistId?: number; sort?: 'recent' } & ListOptions = {}) { + const { q, artistId, sort, ...list } = opts + return usePagedList('/albums', { q: q || undefined, artist_id: artistId, sort }, list) } export function useTrackList(opts: { q?: string; artistId?: number; albumId?: number } & ListOptions = {}) { diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index 38a4faf..62d3005 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -1704,7 +1704,9 @@ export interface paths { }; /** * List albums - * @description Albums with a playable track, sorted by title. `artist_id` matches the albums an artist + * @description Albums with a playable track, sorted by title, or with `sort=recent` the ones added last first (by the date of + * the newest file of the album that is not missing, which is the best the index knows, then the album that came + * last). `artist_id` matches the albums an artist * owns plus those where it is credited on a playable track, the same set as its `album_count`. */ get: operations["listAlbums"]; @@ -6856,6 +6858,8 @@ export interface operations { listAlbums: { parameters: { query?: { + /** @description `title` (the default) or `recent`. Anything else is `invalid_input`. */ + sort?: "title" | "recent"; /** * @description Case- and accent-insensitive substring of the name or title: `bjork`, `BJORK` and `BJÖRK` all * find `Björk`, and `strasse` finds `Straße`. At most 200 characters. diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 69c01ba..67602fd 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -671,6 +671,7 @@ "greeting_afternoon": "Good afternoon", "greeting_evening": "Good evening", "recent": "Recently played", + "recentlyAdded": "Recently added", "nothingPlayed": "Play something and it will show up here.", "emptyLibrary": "Your library is empty. An admin can add a folder of music and scan it.", "trackGone": "That song is no longer in your library." diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 2037d34..11b4d66 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -671,6 +671,7 @@ "greeting_afternoon": "Buon pomeriggio", "greeting_evening": "Buonasera", "recent": "Ascoltati di recente", + "recentlyAdded": "Aggiunti di recente", "nothingPlayed": "Ascolta qualcosa e comparirà qui.", "emptyLibrary": "La libreria è vuota. Un admin può aggiungere una cartella di musica e scansionarla.", "trackGone": "Quel brano non è più nella tua libreria." diff --git a/web/src/pages/AlbumsPage.tsx b/web/src/pages/AlbumsPage.tsx index 338e627..42412cb 100644 --- a/web/src/pages/AlbumsPage.tsx +++ b/web/src/pages/AlbumsPage.tsx @@ -10,12 +10,13 @@ export default function AlbumsPage() { const { t } = useTranslation() const [params] = useSearchParams() const q = params.get('q') ?? '' - const query = useAlbumList({ q }) + const sort = params.get('sort') === 'recent' ? 'recent' : undefined + const query = useAlbumList({ q, sort }) const items = query.data?.items ?? [] return (
- {t('nav.albums')} + {t(sort ? 'home.recentlyAdded' : 'nav.albums')} {query.isError ? ( query.refetch()} /> ) : query.isPending ? ( diff --git a/web/src/pages/HomePage.test.tsx b/web/src/pages/HomePage.test.tsx index ff67379..e677d7f 100644 --- a/web/src/pages/HomePage.test.tsx +++ b/web/src/pages/HomePage.test.tsx @@ -126,10 +126,20 @@ test('with no history it says to play something', async () => { expect(await screen.findByText('Play something and it will show up here.')).toBeInTheDocument() }) +test('the albums shelf is the albums added last, asked of the server newest first', async () => { + const { calls } = mockFetch(routes()) + renderHome() + await screen.findByRole('region', { name: 'Recently added' }) + expect(screen.queryByRole('region', { name: 'Albums' })).not.toBeInTheDocument() + const asked = calls.filter((c) => c.key === 'GET /api/v1/albums').at(-1)! + expect(asked.url.searchParams.get('sort')).toBe('recent') + expect(asked.url.searchParams.get('limit')).toBe('10') +}) + test('albums and artists have their own shelves with links to their pages', async () => { mockFetch(routes()) renderHome() - const albums = await screen.findByRole('region', { name: 'Albums' }) + const albums = await screen.findByRole('region', { name: 'Recently added' }) expect(await within(albums).findByRole('link', { name: /OK Computer/ })).toHaveAttribute('href', '/albums/9') const artists = await screen.findByRole('region', { name: 'Artists' }) expect(await within(artists).findByRole('link', { name: /Radiohead/ })).toHaveAttribute('href', '/artists/5') @@ -138,8 +148,8 @@ test('albums and artists have their own shelves with links to their pages', asyn test('a shelf with more than ten items links to the whole list', async () => { mockFetch(routes({ 'GET /api/v1/albums': () => page([album], 40) })) renderHome() - const albums = await screen.findByRole('region', { name: 'Albums' }) - expect(await within(albums).findByRole('link', { name: 'See all' })).toHaveAttribute('href', '/albums') + const albums = await screen.findByRole('region', { name: 'Recently added' }) + expect(await within(albums).findByRole('link', { name: 'See all' })).toHaveAttribute('href', '/albums?sort=recent') }) test('an empty library says so instead of showing empty shelves', async () => { @@ -150,7 +160,7 @@ test('an empty library says so instead of showing empty shelves', async () => { })) renderHome() expect(await screen.findByText(/Your library is empty/)).toBeInTheDocument() - expect(screen.queryByRole('region', { name: 'Albums' })).not.toBeInTheDocument() + expect(screen.queryByRole('region', { name: 'Recently added' })).not.toBeInTheDocument() }) test('when the history cannot be read the shelves of albums and artists still show', async () => { diff --git a/web/src/pages/HomePage.tsx b/web/src/pages/HomePage.tsx index 28f28bb..e2157e6 100644 --- a/web/src/pages/HomePage.tsx +++ b/web/src/pages/HomePage.tsx @@ -27,7 +27,7 @@ export default function HomePage() { const queryClient = useQueryClient() const playTracks = usePlayer((s) => s.playTracks) const history = useRecentListens() - const albums = useAlbumList({ pageSize: SHELF }) + const albums = useAlbumList({ pageSize: SHELF, sort: 'recent' }) const artists = useArtistList(undefined, { pageSize: SHELF }) const [playError, setPlayError] = useState(null) // Read once per visit of the page: the greeting does not need to change while it is open. @@ -95,7 +95,7 @@ export default function HomePage() { albums.refetch()} /> ) : ( albumItems.length > 0 && ( -
+
    {albumItems.map((album) => (
  • @@ -104,7 +104,7 @@ export default function HomePage() { ))}
{(albums.data?.total ?? 0) > albumItems.length && ( - + {t('common.seeAll')} )} diff --git a/web/src/pages/pages.test.tsx b/web/src/pages/pages.test.tsx index 91ec687..5adcda0 100644 --- a/web/src/pages/pages.test.tsx +++ b/web/src/pages/pages.test.tsx @@ -456,6 +456,22 @@ test('the albums list shows each album with its artist and links to it', async ( expect(screen.getByRole('link', { name: /Kid A/ })).toHaveAttribute('href', '/albums/10') }) +test('the albums list can come newest first, when the address says so', async () => { + const { calls } = mockFetch({ 'GET /api/v1/albums': () => page([album]) }) + renderPage(, '/albums?sort=recent', '/albums') + await screen.findByRole('link', { name: /OK Computer/ }) + expect(screen.getByRole('heading', { level: 1, name: 'Recently added' })).toBeInTheDocument() + expect(calls.at(-1)!.url.searchParams.get('sort')).toBe('recent') +}) + +test('the albums list is by title unless the address asks otherwise', async () => { + const { calls } = mockFetch({ 'GET /api/v1/albums': () => page([album]) }) + renderPage(, '/albums?sort=nonsense', '/albums') + await screen.findByRole('link', { name: /OK Computer/ }) + expect(calls.at(-1)!.url.searchParams.has('sort')).toBe(false) + expect(screen.getByRole('heading', { level: 1, name: 'Albums' })).toBeInTheDocument() +}) + test('the songs list plays from the song that was clicked', async () => { mockFetch({ 'GET /api/v1/tracks': () => page([track(1), track(2), track(3)]) }) renderPage(, '/songs')