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.
This commit is contained in:
tgiachi 2026-11-14 10:29:08 +01:00
commit 246cdc63d3
7 changed files with 129 additions and 17 deletions

View file

@ -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" {

View file

@ -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

View file

@ -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'}

View file

@ -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)
}

View file

@ -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)
}
}
}

View file

@ -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)

View file

@ -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))
}
})
}