Merge pull request 'Show the albums added last on Home' (#172) from feat/recently-added into main
This commit is contained in:
commit
f3ab8f0c8e
16 changed files with 129 additions and 17 deletions
|
|
@ -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. |
|
||||
|
|
|
|||
|
|
@ -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" {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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'}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,9 +44,10 @@ export function useArtistList(q?: string, list: ListOptions = {}) {
|
|||
return usePagedList<Artist>('/artists', { q: q || undefined }, list)
|
||||
}
|
||||
|
||||
export function useAlbumList(opts: { q?: string; artistId?: number } & ListOptions = {}) {
|
||||
const { q, artistId, ...list } = opts
|
||||
return usePagedList<Album>('/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<Album>('/albums', { q: q || undefined, artist_id: artistId, sort }, list)
|
||||
}
|
||||
|
||||
export function useTrackList(opts: { q?: string; artistId?: number; albumId?: number } & ListOptions = {}) {
|
||||
|
|
|
|||
6
web/src/api/schema.d.ts
vendored
6
web/src/api/schema.d.ts
vendored
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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."
|
||||
|
|
|
|||
|
|
@ -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."
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<div className="flex flex-col gap-6">
|
||||
<PageTitle>{t('nav.albums')}</PageTitle>
|
||||
<PageTitle>{t(sort ? 'home.recentlyAdded' : 'nav.albums')}</PageTitle>
|
||||
{query.isError ? (
|
||||
<ErrorMessage error={query.error} onRetry={() => query.refetch()} />
|
||||
) : query.isPending ? (
|
||||
|
|
|
|||
|
|
@ -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 () => {
|
||||
|
|
|
|||
|
|
@ -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<string | null>(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() {
|
|||
<ErrorMessage error={albums.error} onRetry={() => albums.refetch()} />
|
||||
) : (
|
||||
albumItems.length > 0 && (
|
||||
<Section title={t('nav.albums')}>
|
||||
<Section title={t('home.recentlyAdded')}>
|
||||
<ul className={CARD_GRID}>
|
||||
{albumItems.map((album) => (
|
||||
<li key={album.id}>
|
||||
|
|
@ -104,7 +104,7 @@ export default function HomePage() {
|
|||
))}
|
||||
</ul>
|
||||
{(albums.data?.total ?? 0) > albumItems.length && (
|
||||
<Link to="/albums" className="inline-flex min-h-11 items-center self-start font-semibold text-primary hover:underline">
|
||||
<Link to="/albums?sort=recent" className="inline-flex min-h-11 items-center self-start font-semibold text-primary hover:underline">
|
||||
{t('common.seeAll')}
|
||||
</Link>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -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(<AlbumsPage />, '/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(<AlbumsPage />, '/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(<SongsPage />, '/songs')
|
||||
|
|
|
|||
Loading…
Reference in a new issue