feat(smart): covers on the Smart playlists page
- GET /smart-playlists/{id}/covers and GET /smart-playlists/suggested/{key}/covers say which albums stand for a smart playlist: up to 4 albums that have a cover, in the order of the songs the rules give now (for the variant asked), each once. They are worked out apart from the songs, and the answer may be kept for a few minutes.
- The cards of the Smart playlists page are a grid with the collage. The list shows at once and each card asks for its own covers after that, showing the rings until they arrive or when they cannot be read.
- The pages of a smart playlist and of a suggested one use the same covers for the variant on screen, so only albums that have a cover are shown.
This commit is contained in:
parent
0d69ae48de
commit
82b92eaf08
19 changed files with 648 additions and 67 deletions
|
|
@ -22,7 +22,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
|||
- **Artist photos.** `GET /artists/{id}/image` serves a free picture of an artist from Wikimedia Commons, and `GET /artists/{id}/image/credit` says whose it is and under which licence, which you must show next to it. Only free licences are kept (public domain, CC0, CC BY, CC BY-SA): non-commercial, no-derivatives, fair-use and unknown ones are refused, because Sonda stores a copy (`?size=small` is 300 pixels, `large` 1000) in the data folder. With the `commons` provider and the `musicbrainz` one switched on, Sonda follows ids and never a name: the artist's MusicBrainz id, the Wikidata item MusicBrainz links to it, the picture Wikidata names for it, and Commons for its licence. Many artists will have none. Kept for 30 days (a week when there is none) and removed, files included, with the provider's data. To look for the pictures of the whole library in one go, an admin starts a background job like a scan: `POST /library/artist-images` (follow it with `GET /library/artist-images`, stop it with `DELETE /library/artist-images`; `?refresh=true` searches every artist again). It only goes through artists that have a MusicBrainz id, never replaces a picture by a failure, and ends at once, saying so, when a provider it needs is off. See [External providers](#external-providers).
|
||||
- **Album covers.** `GET /albums/{id}/cover` serves the cover of an album from your own files: the picture embedded in them, or else a `cover`, `folder`, `front`, `album` or `albumart` image in the album's folder. It is built the first time it is asked for (a few at a time), scaled (`?size=small` is 300 pixels, `large` 1000) and kept in the data folder (`storage.data_dir`, you can delete it: covers are built again). A picture you replace in a folder is noticed within a week, or at once after a full rescan. When your files have no picture at all and an admin switched on the `coverartarchive` provider, the cover is asked from the Cover Art Archive by the MusicBrainz release group id that the tags of the album's files carry (`MUSICBRAINZ_RELEASEGROUPID`; run a full rescan to read it for music you already indexed); your own files always come first, and only that id leaves the server. An album whose files have no id is looked up in MusicBrainz by its artist and title when the `musicbrainz` provider is on too (see the list of what leaves your server). For an album split in `CD1`/`Disc 2` folders, the picture in the folder above is used. Nothing is sent anywhere unless you switched on the `coverartarchive` provider (see [External providers](#external-providers)). It also takes `?access_token=`, so an `<img>` element can use it. To build the covers of the whole library in one go instead of one album at a time, an admin starts a background job like a scan: `POST /library/covers` (follow it with `GET /library/covers`, stop it with `DELETE /library/covers`; `?refresh=true` searches every album again; it never replaces a cover by "no cover" because a disk was not mounted, and keeps the covers that came from the archive if you switched it off).
|
||||
- **Mixes.** `GET /mixes` lists playlists that Sonda makes for you, like the mixes of a streaming service, from what you listen to and from the genres of your music: one mix for each genre of your library that has at least 30 songs by 4 artists (the genres you play most first), and, once you have some listening history, *Your favourites* and *Rediscover* (artists you like and have not played for a month); *New to you* is the songs you never played. `GET /mixes/{id}` gives a mix of up to 50 songs, at most 3 by one artist and never two of the same artist in a row. They are picked by weighted chance: the artists you play weigh more and songs you skipped lately or artists you avoid are left out. A mix stays the same for a day, and `?variant=2` gives another; `POST /mixes/{id}/playlist` keeps the one you are looking at as a playlist of your own. A mix is worked out when you ask for it, from your own history and the genre tags of your files: nothing is stored and nothing is sent to a provider. The id of a genre mix has the genre in it (`genre:hard rock`), so it is percent-encoded in the path. Each mix says which albums stand for it (`album_ids`: up to 4 albums that have a cover, by different artists, with most of the songs the mix draws from), for a picture made of their covers; the covers are the ones the library already has, so a mix has a picture once the covers of its albums were looked up (browsing the albums, or the covers job), and none is fetched for it.
|
||||
- **Smart playlists.** A smart playlist is a set of rules instead of a list of songs, worked out again every time you open it, so new songs and your listening change it by themselves. `POST /smart-playlists` keeps a name, the rules, an order (`random`, `most_played`, `least_played`, `recently_added` or `title`) and a limit (50 by default, 500 at most); `GET /smart-playlists/{id}/tracks` gives the songs now. Every rule that is set must hold: genres, artists and albums (is, or is not), file formats and a minimum bitrate (about the same file), added in the last N days (by the date of the file), never played, played or not played in the last N days, played at least N times (optionally counting only the plays of the last N days, which is what makes the songs in rotation lately and the top of the year), skipped or not skipped lately, only artists you like or without the ones you avoid, and the length of the song. `POST /smart-playlists/preview` tries rules without keeping them, and `POST /smart-playlists/{id}/playlist` keeps what you see as a normal playlist (a copy). Only the rules are stored; the songs come from the files and from your own history, nothing is sent to a provider, and a smart playlist is yours alone, and `GET /genres` lists the genres to choose from. A random order stays the same for a day, and `?variant=2` gives another. Some are there without anybody making them: `GET /smart-playlists/suggested` lists a fixed set (`recently-added`, `on-rotation`, `top-year`, `most-played`, `never-played`, `forgotten`, `high-quality`, `long-tracks`), the same rules for everyone and worked out on your own library and history, nothing stored; `GET /smart-playlists/suggested/{key}/tracks` gives their songs and `POST /smart-playlists/suggested/{key}/playlist` keeps them as a playlist, and `on-rotation` is the songs you played most in the last 30 days and `top-year` the same over a year, so they change as you listen; a copy of their rules becomes a smart playlist of your own with `POST /smart-playlists`. The year of a song is not in the index yet, so there is no rule about it. A user can have 200.
|
||||
- **Smart playlists.** A smart playlist is a set of rules instead of a list of songs, worked out again every time you open it, so new songs and your listening change it by themselves. `POST /smart-playlists` keeps a name, the rules, an order (`random`, `most_played`, `least_played`, `recently_added` or `title`) and a limit (50 by default, 500 at most); `GET /smart-playlists/{id}/tracks` gives the songs now. Every rule that is set must hold: genres, artists and albums (is, or is not), file formats and a minimum bitrate (about the same file), added in the last N days (by the date of the file), never played, played or not played in the last N days, played at least N times (optionally counting only the plays of the last N days, which is what makes the songs in rotation lately and the top of the year), skipped or not skipped lately, only artists you like or without the ones you avoid, and the length of the song. `POST /smart-playlists/preview` tries rules without keeping them, and `POST /smart-playlists/{id}/playlist` keeps what you see as a normal playlist (a copy). Only the rules are stored; the songs come from the files and from your own history, nothing is sent to a provider, and a smart playlist is yours alone, and `GET /genres` lists the genres to choose from. A random order stays the same for a day, and `?variant=2` gives another. `GET /smart-playlists/{id}/covers` and `GET /smart-playlists/suggested/{key}/covers` say which albums stand for one (up to 4 that have a cover, in the order of the songs it gives now), for its picture; they are apart from the songs so that the list of smart playlists shows at once and each card fills in its cover when it arrives. Some are there without anybody making them: `GET /smart-playlists/suggested` lists a fixed set (`recently-added`, `on-rotation`, `top-year`, `most-played`, `never-played`, `forgotten`, `high-quality`, `long-tracks`), the same rules for everyone and worked out on your own library and history, nothing stored; `GET /smart-playlists/suggested/{key}/tracks` gives their songs and `POST /smart-playlists/suggested/{key}/playlist` keeps them as a playlist, and `on-rotation` is the songs you played most in the last 30 days and `top-year` the same over a year, so they change as you listen; a copy of their rules becomes a smart playlist of your own with `POST /smart-playlists`. The year of a song is not in the index yet, so there is no rule about it. A user can have 200.
|
||||
- **Playlists.** `POST /playlists` makes a playlist (a name and an optional description) and `GET /playlists` lists yours, the one changed last first. `POST /playlists/{id}/tracks` adds 1 to 500 tracks at the end or at a `position`, `GET /playlists/{id}/tracks` lists them in order, `PATCH /playlists/{id}/tracks/{item}` moves one and `DELETE` takes one out; `PATCH /playlists/{id}` renames and `DELETE /playlists/{id}` deletes (the tracks stay in the library). A track can be in a playlist more than once, which is why each place has its own item id. A playlist is yours alone: someone else's answers `playlist_not_found`, as one that does not exist. A track whose files were deleted or moved away stays in the playlist and shows `available: false`; it plays again when the files come back and a scan finds them. Each playlist says which albums stand for it (`album_ids`: up to 4 albums that have a cover, in the order they first appear in it, each once), for a picture made of their covers; nothing is fetched for it. A user can have 1000 playlists of up to 10000 tracks. Nothing is shared and nothing leaves your server.
|
||||
- **Wishlist and "not interested".** `PUT /wishlist/{artist}` puts an artist on your wishlist (`GET /wishlist` lists it, `DELETE` takes it off), and `POST /discover/{artist}/dismiss` hides an artist from your Discover for good (`DELETE` brings it back, `GET /discover/dismissed` lists them). An artist is wished or dismissed, never both, and both lists are yours alone. Discover marks the wished artists it shows (`wishlisted`) and never suggests a dismissed one. The wishlist is a list for you and sends nothing anywhere; Sonda downloads nothing, but an admin can send an artist that Discover showed to their own Lidarr (see [External providers](#external-providers)), which works for an artist that has a MusicBrainz id and that Sonda knows of from a list or from your files. An artist that only Last.fm named is kept while you have it marked (your lists still show it, but other users cannot see that it exists), and goes with the rest of Last.fm's data if an admin removes Last.fm's data. Removing MusicBrainz's data does not touch it.
|
||||
- **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so this setting never sends your listening to a provider. When you turn it on, Discover may start from the artists you listen to most, and their names are sent to Last.fm (only if an admin switched it on). What Last.fm answers is kept in the shared database like any other lookup, so another local user can see, from `retrieved_at` of `GET /artists/{id}/similar`, that someone looked up an artist, but not who.
|
||||
|
|
|
|||
|
|
@ -1040,6 +1040,8 @@ func (c *contract) smartPlaylists(t *testing.T, token string) {
|
|||
t.Fatalf("suggested = %v", sug)
|
||||
}
|
||||
c.expect(c.call("GET", "/smart-playlists/suggested/never-played/tracks", token, nil), 200, "the songs of a suggested one")
|
||||
c.expect(c.call("GET", "/smart-playlists/suggested/never-played/covers", token, nil), 200, "the covers of a suggested one")
|
||||
c.expect(c.call("GET", "/smart-playlists/suggested/nonsense/covers", token, nil), 404, "the covers of an unknown suggested one", "suggested_not_found")
|
||||
c.expect(c.call("GET", "/smart-playlists/suggested/never-played/tracks?variant=-1", token, nil), 400, "a negative variant", "invalid_input")
|
||||
c.expect(c.call("GET", "/smart-playlists/suggested/nonsense/tracks", token, nil), 404, "an unknown suggested one", "suggested_not_found")
|
||||
c.expect(c.call("POST", "/smart-playlists/suggested/never-played/playlist", token, map[string]any{"name": "Fresh ears", "variant": 1}), 201, "keep a suggested one")
|
||||
|
|
@ -1066,6 +1068,9 @@ func (c *contract) smartPlaylists(t *testing.T, token string) {
|
|||
t.Fatalf("smart playlist songs = %v", got)
|
||||
}
|
||||
c.expect(c.call("GET", "/smart-playlists/"+id+"/tracks?variant=2", token, nil), 200, "the songs, another variant")
|
||||
c.expect(c.call("GET", "/smart-playlists/"+id+"/covers?variant=2", token, nil), 200, "the covers of a smart playlist")
|
||||
c.expect(c.call("GET", "/smart-playlists/999999/covers", token, nil), 404, "the covers of an unknown smart playlist", "smart_playlist_not_found")
|
||||
c.expect(c.call("GET", "/smart-playlists/"+id+"/covers?variant=-1", token, nil), 400, "the covers with a bad variant", "invalid_input")
|
||||
c.expect(c.call("GET", "/smart-playlists/"+id+"/tracks?variant=-1", token, nil), 400, "a negative variant", "invalid_input")
|
||||
c.expect(c.call("GET", "/smart-playlists/999999/tracks", token, nil), 404, "the songs of an unknown smart playlist", "smart_playlist_not_found")
|
||||
c.expect(c.call("POST", "/smart-playlists/preview", token, map[string]any{"rules": map[string]any{"min_duration_sec": 30, "liked_artists_only": false}, "sort": "most_played", "limit": 5, "variant": 1}), 200, "preview rules")
|
||||
|
|
|
|||
|
|
@ -335,3 +335,38 @@ func (h *smartHandlers) suggestedSave(c *gin.Context) {
|
|||
name, description := automaticName(c, h.naming, req.AutoName, req.Lang, "smart", tracks, sg.Rules.Summary(), name)
|
||||
keepAsPlaylist(c, h.playlists, user, name, description, tracks)
|
||||
}
|
||||
|
||||
// covers says which albums stand for a smart playlist, for its picture: up to 4 albums that have a cover, in the order of
|
||||
// the songs it gives now. It is apart from the songs so that a list of smart playlists need not wait for all of them.
|
||||
func (h *smartHandlers) covers(c *gin.Context) {
|
||||
id, ok := pathID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
variant, ok := variantOf(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
albums, err := h.svc.Covers(c.Request.Context(), currentUserID(c), id, variant)
|
||||
if err != nil {
|
||||
writeSmartError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "private, max-age=300")
|
||||
c.JSON(http.StatusOK, gin.H{"album_ids": albums})
|
||||
}
|
||||
|
||||
// suggestedCovers is covers for a suggested smart playlist.
|
||||
func (h *smartHandlers) suggestedCovers(c *gin.Context) {
|
||||
variant, ok := variantOf(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
albums, err := h.svc.SuggestedCovers(c.Request.Context(), currentUserID(c), c.Param("key"), variant)
|
||||
if err != nil {
|
||||
writeSuggestedError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "private, max-age=300")
|
||||
c.JSON(http.StatusOK, gin.H{"album_ids": albums})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -127,6 +127,8 @@ type smartService interface {
|
|||
Preview(ctx context.Context, userID int64, in smart.Input, variant int) ([]catalog.Track, error)
|
||||
Genres(ctx context.Context) ([]smart.GenreCount, error)
|
||||
SuggestedTracks(ctx context.Context, userID int64, key string, variant int) (smart.SuggestedPlaylist, []catalog.Track, error)
|
||||
Covers(ctx context.Context, userID, id int64, variant int) ([]int64, error)
|
||||
SuggestedCovers(ctx context.Context, userID int64, key string, variant int) ([]int64, error)
|
||||
}
|
||||
|
||||
type feedbackService interface {
|
||||
|
|
@ -300,11 +302,13 @@ func NewRouter(d Deps) *gin.Engine {
|
|||
protected.POST("/smart-playlists/preview", sm.preview)
|
||||
protected.GET("/smart-playlists/suggested", sm.suggestedList)
|
||||
protected.GET("/smart-playlists/suggested/:key/tracks", sm.suggestedTracks)
|
||||
protected.GET("/smart-playlists/suggested/:key/covers", sm.suggestedCovers)
|
||||
protected.POST("/smart-playlists/suggested/:key/playlist", sm.suggestedSave)
|
||||
protected.GET("/smart-playlists/:id", sm.get)
|
||||
protected.PATCH("/smart-playlists/:id", sm.update)
|
||||
protected.DELETE("/smart-playlists/:id", sm.remove)
|
||||
protected.GET("/smart-playlists/:id/tracks", sm.tracks)
|
||||
protected.GET("/smart-playlists/:id/covers", sm.covers)
|
||||
protected.POST("/smart-playlists/:id/playlist", sm.save)
|
||||
protected.GET("/wishlist", fb.list(feedback.Wishlist))
|
||||
protected.PUT("/wishlist/:id", fb.add(feedback.Wishlist))
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ func smartTracks(t *testing.T, m *mixAPI, id int, query string) []float64 {
|
|||
func TestSmartPlaylistRoutesNeedASignedInUser(t *testing.T) {
|
||||
m := newMixAPI(t)
|
||||
for _, rt := range []struct{ method, path string }{
|
||||
{"GET", "/api/v1/genres"}, {"GET", sp + "/suggested"}, {"GET", sp + "/suggested/never-played/tracks"}, {"POST", sp + "/suggested/never-played/playlist"}, {"GET", sp}, {"POST", sp}, {"POST", sp + "/preview"}, {"GET", sp + "/1"}, {"PATCH", sp + "/1"}, {"DELETE", sp + "/1"},
|
||||
{"GET", "/api/v1/genres"}, {"GET", sp + "/suggested"}, {"GET", sp + "/suggested/never-played/tracks"}, {"GET", sp + "/suggested/never-played/covers"}, {"GET", sp + "/1/covers"}, {"POST", sp + "/suggested/never-played/playlist"}, {"GET", sp}, {"POST", sp}, {"POST", sp + "/preview"}, {"GET", sp + "/1"}, {"PATCH", sp + "/1"}, {"DELETE", sp + "/1"},
|
||||
{"GET", sp + "/1/tracks"}, {"POST", sp + "/1/playlist"},
|
||||
} {
|
||||
if r := do(t, m.h, rt.method, rt.path, "", nil); r.Code != http.StatusUnauthorized {
|
||||
|
|
@ -397,3 +397,92 @@ func TestPlaysInTheLastDaysAreCountedForTheListenerOnly(t *testing.T) {
|
|||
t.Errorf("a negative window: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheCoversOfASmartPlaylistAreThoseOfTheSongsItGivesNow(t *testing.T) {
|
||||
m := newMixAPI(t)
|
||||
// Songs of "rock song N" come in six albums; give covers to some of them.
|
||||
rows, err := m.db.Query("SELECT DISTINCT t.album_id FROM tracks t WHERE t.title LIKE 'hard song%' ORDER BY t.album_id")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var albums []int64
|
||||
for rows.Next() {
|
||||
var a int64
|
||||
if err := rows.Scan(&a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
albums = append(albums, a)
|
||||
}
|
||||
rows.Close()
|
||||
if len(albums) < 5 {
|
||||
t.Fatalf("albums = %v", albums)
|
||||
}
|
||||
for _, a := range albums[:5] {
|
||||
_, _ = m.db.Exec("DELETE FROM images WHERE kind = 'album' AND owner_id = ?", a)
|
||||
if _, err := m.db.Exec("INSERT INTO images (kind, owner_id, status, checked_at) VALUES ('album', ?, 'ok', 1)", a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
id := smartMade(t, m, map[string]any{"name": "Hard", "sort": "title", "limit": 20, "rules": map[string]any{"genres": []string{"hard rock"}}})
|
||||
r := do(t, m.h, "GET", fmt.Sprintf("%s/%d/covers", sp, id), m.alice, nil)
|
||||
ids, _ := r.Body["album_ids"].([]any)
|
||||
if r.Code != http.StatusOK || len(ids) != 4 {
|
||||
t.Fatalf("covers: %d %v", r.Code, r.Body)
|
||||
}
|
||||
// They are albums of the songs on screen for the same variant.
|
||||
shown := map[float64]bool{}
|
||||
tracks := do(t, m.h, "GET", fmt.Sprintf("%s/%d/tracks", sp, id), m.alice, nil)
|
||||
for _, x := range tracks.Body["tracks"].([]any) {
|
||||
shown[x.(map[string]any)["album"].(map[string]any)["id"].(float64)] = true
|
||||
}
|
||||
for _, a := range ids {
|
||||
if !shown[a.(float64)] {
|
||||
t.Errorf("album %v is not one of the songs of the playlist", a)
|
||||
}
|
||||
}
|
||||
// Rules that give nothing have an empty list, and an unknown playlist is not found.
|
||||
none := smartMade(t, m, map[string]any{"name": "Polka", "rules": map[string]any{"genres": []string{"polka"}}})
|
||||
if r := do(t, m.h, "GET", fmt.Sprintf("%s/%d/covers", sp, none), m.alice, nil); r.Code != http.StatusOK || len(r.Body["album_ids"].([]any)) != 0 {
|
||||
t.Errorf("no songs: %d %v", r.Code, r.Body)
|
||||
}
|
||||
if r := do(t, m.h, "GET", sp+"/999999/covers", m.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "smart_playlist_not_found" {
|
||||
t.Errorf("unknown: %d %v", r.Code, r.Body)
|
||||
}
|
||||
if r := do(t, m.h, "GET", fmt.Sprintf("%s/%d/covers?variant=-1", sp, id), m.alice, nil); r.Code != http.StatusBadRequest {
|
||||
t.Errorf("a negative variant: %d", r.Code)
|
||||
}
|
||||
// Somebody else's is not found either.
|
||||
_, bob := addUser(t, m.h, m.alice, "bob", false)
|
||||
if r := do(t, m.h, "GET", fmt.Sprintf("%s/%d/covers", sp, id), bob, nil); r.Code != http.StatusNotFound {
|
||||
t.Errorf("another user's: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheCoversOfASuggestedOneAreAskedAsOnesOwn(t *testing.T) {
|
||||
m := newMixAPI(t)
|
||||
rows, err := m.db.Query("SELECT DISTINCT album_id FROM tracks WHERE album_id IS NOT NULL ORDER BY album_id LIMIT 3")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var a int64
|
||||
if err := rows.Scan(&a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = m.db.Exec("DELETE FROM images WHERE kind = 'album' AND owner_id = ?", a)
|
||||
if _, err := m.db.Exec("INSERT INTO images (kind, owner_id, status, checked_at) VALUES ('album', ?, 'ok', 1)", a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
r := do(t, m.h, "GET", sp+"/suggested/never-played/covers", m.alice, nil)
|
||||
if r.Code != http.StatusOK || len(r.Body["album_ids"].([]any)) == 0 || len(r.Body["album_ids"].([]any)) > 4 {
|
||||
t.Errorf("covers: %d %v", r.Code, r.Body)
|
||||
}
|
||||
if r := do(t, m.h, "GET", sp+"/suggested/nonsense/covers", m.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "suggested_not_found" {
|
||||
t.Errorf("unknown key: %d %v", r.Code, r.Body)
|
||||
}
|
||||
if r := do(t, m.h, "GET", sp+"/suggested/never-played/covers?variant=x", m.alice, nil); r.Code != http.StatusBadRequest {
|
||||
t.Errorf("bad variant: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1426,6 +1426,34 @@ paths:
|
|||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404': {$ref: '#/components/responses/SuggestedNotFound'}
|
||||
|
||||
/smart-playlists/suggested/{key}/covers:
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/SuggestedKey'}
|
||||
get:
|
||||
tags: [Smart playlists]
|
||||
operationId: getSuggestedSmartPlaylistCovers
|
||||
summary: The covers of a suggested smart playlist
|
||||
description: |
|
||||
Up to 4 albums that have a cover and stand for it, in the order of the songs the rules give now (the ones of
|
||||
`variant`), each once: their covers (`GET /albums/{id}/cover`) make its picture. It is worked out apart from the
|
||||
songs so that a list of smart playlists can show the rest without waiting for the rules of every one of them; the
|
||||
answer may be kept by the client for a few minutes. Empty when none of the songs has an album with a cover.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- name: variant
|
||||
in: query
|
||||
description: The variant that is on screen, from 0 (the songs of the day) up.
|
||||
schema: {type: integer, minimum: 0, maximum: 1000000, default: 0}
|
||||
responses:
|
||||
'200':
|
||||
description: The albums.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/SmartCovers'}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404': {$ref: '#/components/responses/SuggestedNotFound'}
|
||||
|
||||
/smart-playlists/suggested/{key}/playlist:
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/SuggestedKey'}
|
||||
|
|
@ -1540,6 +1568,34 @@ paths:
|
|||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404': {$ref: '#/components/responses/SmartPlaylistNotFound'}
|
||||
|
||||
/smart-playlists/{id}/covers:
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/Id'}
|
||||
get:
|
||||
tags: [Smart playlists]
|
||||
operationId: getSmartPlaylistCovers
|
||||
summary: The covers of a smart playlist
|
||||
description: |
|
||||
Up to 4 albums that have a cover and stand for it, in the order of the songs the rules give now (the ones of
|
||||
`variant`), each once: their covers (`GET /albums/{id}/cover`) make its picture. It is worked out apart from the
|
||||
songs so that a list of smart playlists can show the rest without waiting for the rules of every one of them; the
|
||||
answer may be kept by the client for a few minutes. Empty when none of the songs has an album with a cover.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- name: variant
|
||||
in: query
|
||||
description: The variant that is on screen, from 0 (the songs of the day) up.
|
||||
schema: {type: integer, minimum: 0, maximum: 1000000, default: 0}
|
||||
responses:
|
||||
'200':
|
||||
description: The albums.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/SmartCovers'}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404': {$ref: '#/components/responses/SmartPlaylistNotFound'}
|
||||
|
||||
/smart-playlists/{id}/playlist:
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/Id'}
|
||||
|
|
@ -3833,6 +3889,13 @@ components:
|
|||
limit: {type: integer, minimum: 1, maximum: 500, default: 50}
|
||||
variant: {type: integer, minimum: 0, maximum: 1000000, default: 0}
|
||||
|
||||
SmartCovers:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [album_ids]
|
||||
properties:
|
||||
album_ids: {type: array, maxItems: 4, items: {type: integer, format: int64}}
|
||||
|
||||
SmartTracks:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
|
|
|
|||
|
|
@ -186,6 +186,8 @@ type Store interface {
|
|||
Plays(ctx context.Context, userID int64, minListen time.Duration, since time.Time) (map[int64]int, error)
|
||||
// Tracks returns the songs in the order given, leaving out any that cannot be played.
|
||||
Tracks(ctx context.Context, ids []int64) ([]catalog.Track, error)
|
||||
// AlbumCovers returns, for the songs in the order given, the albums that have a cover, each once, up to limit.
|
||||
AlbumCovers(ctx context.Context, trackIDs []int64, limit int) ([]int64, error)
|
||||
}
|
||||
|
||||
// Taster says what the listener likes: *taste.Service.
|
||||
|
|
@ -519,7 +521,21 @@ func spellings(all []mixes.Genre, genres []string) []string {
|
|||
return out
|
||||
}
|
||||
|
||||
// run works the songs out: the rules, the order and the limit, then the details of the songs.
|
||||
func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort, limit, variant int) ([]catalog.Track, error) {
|
||||
picked, err := s.pick(ctx, userID, id, r, order, limit, variant)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tracks, err := s.store.Tracks(ctx, picked)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read songs: %w", err)
|
||||
}
|
||||
return tracks, nil
|
||||
}
|
||||
|
||||
// pick works out which songs the rules give, in order, as their ids.
|
||||
func (s *Service) pick(ctx context.Context, userID, id int64, r Rules, order Sort, limit, variant int) ([]int64, error) {
|
||||
f := Filter{
|
||||
ArtistIDs: r.ArtistIDs, NotArtistIDs: r.NotArtistIDs, AlbumIDs: r.AlbumIDs, NotAlbumIDs: r.NotAlbumIDs,
|
||||
Formats: r.Formats, MinBitrateKbps: r.MinBitrateKbps,
|
||||
|
|
@ -531,7 +547,7 @@ func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort
|
|||
}
|
||||
f.Genres, f.NotGenres = spellings(all, r.Genres), spellings(all, r.NotGenres)
|
||||
if len(r.Genres) > 0 && len(f.Genres) == 0 {
|
||||
return []catalog.Track{}, nil // no file has any of the genres
|
||||
return []int64{}, nil // no file has any of the genres
|
||||
}
|
||||
}
|
||||
cands, err := s.store.Candidates(ctx, f)
|
||||
|
|
@ -599,11 +615,42 @@ func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort
|
|||
for i, c := range kept {
|
||||
picked[i] = c.TrackID
|
||||
}
|
||||
tracks, err := s.store.Tracks(ctx, picked)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read songs: %w", err)
|
||||
return picked, nil
|
||||
}
|
||||
|
||||
// MaxCoverAlbums is how many albums make the picture of a smart playlist.
|
||||
const MaxCoverAlbums = 4
|
||||
|
||||
// Covers says which albums stand for a smart playlist: up to MaxCoverAlbums albums that have a cover, in the order of the
|
||||
// songs it gives now (the ones of variant), each once. It is the picture of the playlist, and is worked out apart from its
|
||||
// songs so that a list of playlists need not wait for all of them.
|
||||
func (s *Service) Covers(ctx context.Context, userID, id int64, variant int) ([]int64, error) {
|
||||
if err := checkVariant(variant); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tracks, nil
|
||||
p, err := s.store.Get(ctx, userID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
picked, err := s.pick(ctx, userID, p.ID, p.Rules, p.Sort, p.Limit, variant)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.albumCovers(ctx, picked)
|
||||
}
|
||||
|
||||
func (s *Service) albumCovers(ctx context.Context, picked []int64) ([]int64, error) {
|
||||
if len(picked) == 0 {
|
||||
return []int64{}, nil
|
||||
}
|
||||
albums, err := s.store.AlbumCovers(ctx, picked, MaxCoverAlbums)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read covers: %w", err)
|
||||
}
|
||||
if albums == nil {
|
||||
albums = []int64{}
|
||||
}
|
||||
return albums, nil
|
||||
}
|
||||
|
||||
// sortCandidates puts the songs in the order; a tie goes to the lower id. A random order sorts by the
|
||||
|
|
|
|||
|
|
@ -25,6 +25,8 @@ type fakeStore struct {
|
|||
asked []Filter
|
||||
windowed map[int64]int // plays inside the window asked for
|
||||
since []time.Time // the starts of the windows asked for
|
||||
albumOf map[int64]int64 // the album of a song that has a cover
|
||||
coverAsk [][]int64 // the songs asked about
|
||||
saved map[int64]SmartPlaylist // by id
|
||||
nextID int64
|
||||
listened int // how many times history was read
|
||||
|
|
@ -51,6 +53,18 @@ func (f *fakeStore) Plays(_ context.Context, _ int64, _ time.Duration, since tim
|
|||
return f.windowed, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) AlbumCovers(_ context.Context, trackIDs []int64, limit int) ([]int64, error) {
|
||||
f.coverAsk = append(f.coverAsk, trackIDs)
|
||||
out := []int64{}
|
||||
for _, id := range trackIDs {
|
||||
a, ok := f.albumOf[id]
|
||||
if ok && !slices.Contains(out, a) && len(out) < limit {
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Tracks(_ context.Context, ids []int64) ([]catalog.Track, error) {
|
||||
out := make([]catalog.Track, len(ids))
|
||||
for i, id := range ids {
|
||||
|
|
@ -704,3 +718,79 @@ func TestAWindowOfDaysIsChecked(t *testing.T) {
|
|||
t.Errorf("summary = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the albums that stand for a smart playlist ----
|
||||
|
||||
func TestTheAlbumsOfASmartPlaylistAreThoseOfTheSongsItGivesInOrder(t *testing.T) {
|
||||
st := newStore()
|
||||
st.cands = songs(8)
|
||||
// Songs 3, 4, 5, 6 and 7 have albums with a cover; songs 1 and 2 do not. Songs 3 and 5 share an album.
|
||||
st.albumOf = map[int64]int64{3: 30, 4: 40, 5: 30, 6: 60, 7: 70}
|
||||
svc := newService(st, taste.Learned{})
|
||||
p, err := svc.Create(context.Background(), 1, Input{Name: "All", Sort: SortTitle, Limit: 8})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := svc.Covers(context.Background(), 1, p.ID, 0)
|
||||
if err != nil || !slices.Equal(got, []int64{30, 40, 60, 70}) {
|
||||
t.Fatalf("covers = %v, %v: in the order of the songs, each album once, four at most", got, err)
|
||||
}
|
||||
// The songs asked about are the ones the playlist gives, no more.
|
||||
if len(st.coverAsk) != 1 || !slices.Equal(st.coverAsk[0], []int64{1, 2, 3, 4, 5, 6, 7, 8}) {
|
||||
t.Errorf("asked about %v", st.coverAsk)
|
||||
}
|
||||
short, _ := svc.Create(context.Background(), 1, Input{Name: "Three", Sort: SortTitle, Limit: 3})
|
||||
if got, _ := svc.Covers(context.Background(), 1, short.ID, 0); !slices.Equal(got, []int64{30}) {
|
||||
t.Errorf("the limit counts, only song 3 of the first three has a cover: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheCoversFollowTheVariantOfARandomOrderAndAreEmptyNotMissing(t *testing.T) {
|
||||
st := newStore()
|
||||
st.cands = songs(40)
|
||||
st.albumOf = map[int64]int64{}
|
||||
for i := int64(1); i <= 40; i++ {
|
||||
st.albumOf[i] = 100 + i
|
||||
}
|
||||
svc := newService(st, taste.Learned{})
|
||||
p, _ := svc.Create(context.Background(), 1, Input{Name: "Any", Sort: SortRandom, Limit: 10})
|
||||
a, _ := svc.Covers(context.Background(), 1, p.ID, 0)
|
||||
b, _ := svc.Covers(context.Background(), 1, p.ID, 0)
|
||||
c, _ := svc.Covers(context.Background(), 1, p.ID, 1)
|
||||
if !slices.Equal(a, b) || slices.Equal(a, c) {
|
||||
t.Errorf("covers of the day = %v and %v, of variant 1 = %v", a, b, c)
|
||||
}
|
||||
// They are the covers of the songs that the playlist shows for the same variant.
|
||||
_, tracks, _ := svc.Tracks(context.Background(), 1, p.ID, 1)
|
||||
var want []int64
|
||||
for _, tr := range tracks[:4] {
|
||||
want = append(want, st.albumOf[tr.ID])
|
||||
}
|
||||
if !slices.Equal(c, want) {
|
||||
t.Errorf("variant 1 covers = %v, its first songs have %v", c, want)
|
||||
}
|
||||
st.albumOf = nil
|
||||
if none, err := svc.Covers(context.Background(), 1, p.ID, 0); err != nil || none == nil || len(none) != 0 {
|
||||
t.Errorf("no cover at all = %#v, %v", none, err)
|
||||
}
|
||||
if _, err := svc.Covers(context.Background(), 1, 999, 0); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("unknown playlist: %v", err)
|
||||
}
|
||||
if _, err := svc.Covers(context.Background(), 1, p.ID, MaxVariant+1); !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("variant: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheCoversOfASuggestedOneAreThoseOfItsSongs(t *testing.T) {
|
||||
st := newStore()
|
||||
st.cands = songs(6)
|
||||
st.albumOf = map[int64]int64{1: 11, 2: 12, 4: 14}
|
||||
svc := newService(st, taste.Learned{})
|
||||
got, err := svc.SuggestedCovers(context.Background(), 1, "recently-added", 0)
|
||||
if err != nil || !slices.Equal(got, []int64{11, 12, 14}) {
|
||||
t.Errorf("covers = %v, %v: the newest songs first", got, err)
|
||||
}
|
||||
if _, err := svc.SuggestedCovers(context.Background(), 1, "nonsense", 0); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("unknown key: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,6 +40,23 @@ func Suggested() []SuggestedPlaylist {
|
|||
return out
|
||||
}
|
||||
|
||||
// SuggestedCovers says which albums stand for a suggested smart playlist, as Covers does for one of the user's own.
|
||||
func (s *Service) SuggestedCovers(ctx context.Context, userID int64, key string, variant int) ([]int64, error) {
|
||||
if err := checkVariant(variant); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
i := slices.IndexFunc(suggested, func(x SuggestedPlaylist) bool { return x.Key == key })
|
||||
if i < 0 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
sg := suggested[i]
|
||||
picked, err := s.pick(ctx, userID, -int64(i+1), sg.Rules, sg.Sort, sg.Limit, variant)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.albumCovers(ctx, picked)
|
||||
}
|
||||
|
||||
// SuggestedTracks works the songs of a suggested smart playlist out for the user. variant 0 is the songs of
|
||||
// the day; with a random order another number gives other ones. An unknown key is ErrNotFound.
|
||||
func (s *Service) SuggestedTracks(ctx context.Context, userID int64, key string, variant int) (SuggestedPlaylist, []catalog.Track, error) {
|
||||
|
|
|
|||
|
|
@ -191,6 +191,41 @@ func (r *SmartRepo) Plays(ctx context.Context, userID int64, minListen time.Dura
|
|||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// AlbumCovers returns, for the songs in the order given, the albums that have a cover, each once, up to limit.
|
||||
func (r *SmartRepo) AlbumCovers(ctx context.Context, trackIDs []int64, limit int) ([]int64, error) {
|
||||
out := []int64{}
|
||||
if len(trackIDs) == 0 || limit <= 0 {
|
||||
return out, nil
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx,
|
||||
`SELECT t.id, t.album_id FROM tracks t
|
||||
JOIN images im ON im.kind = 'album' AND im.owner_id = t.album_id AND im.status = 'ok'
|
||||
WHERE t.id IN (?)`, bun.In(trackIDs))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read the covers of songs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
albumOf := map[int64]int64{}
|
||||
for rows.Next() {
|
||||
var track, album int64
|
||||
if err := rows.Scan(&track, &album); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
albumOf[track] = album
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := map[int64]bool{}
|
||||
for _, id := range trackIDs {
|
||||
if a, ok := albumOf[id]; ok && !seen[a] && len(out) < limit {
|
||||
seen[a] = true
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Tracks returns the playable songs among ids, in the order given.
|
||||
func (r *SmartRepo) Tracks(ctx context.Context, ids []int64) ([]catalog.Track, error) {
|
||||
return r.mix.Tracks(ctx, ids)
|
||||
|
|
|
|||
|
|
@ -369,3 +369,46 @@ func TestSmartRepoCountsTheListensOfEachSongSinceAMoment(t *testing.T) {
|
|||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSmartRepoAlbumCoversFollowTheOrderOfTheSongsAndSkipWhatHasNoCover(t *testing.T) {
|
||||
smartBackends(t, smartSongs, func(t *testing.T, e *smartEnv) {
|
||||
ctx := context.Background()
|
||||
cover := func(album string, status string) {
|
||||
t.Helper()
|
||||
if _, err := e.db.Exec("DELETE FROM images WHERE kind = 'album' AND owner_id = ?", e.album[album]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := e.db.Exec("INSERT INTO images (kind, owner_id, status, checked_at) VALUES ('album', ?, ?, 1)", e.album[album], status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// a and b share the album News, c has Alive, d has Reign, e has Blue.
|
||||
cover("News", "ok")
|
||||
cover("Alive", "none")
|
||||
cover("Reign", "ok")
|
||||
cover("Blue", "stale")
|
||||
ids := func(names ...string) []int64 {
|
||||
out := make([]int64, len(names))
|
||||
for i, n := range names {
|
||||
out[i] = e.tracks[n]
|
||||
}
|
||||
return out
|
||||
}
|
||||
got, err := e.repo.AlbumCovers(ctx, ids("d", "c", "b", "a", "e"), 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := []int64{e.album["Reign"], e.album["News"]}; !slices.Equal(got, want) {
|
||||
t.Errorf("covers = %v, want %v: in the order of the songs, News once, no cover and a stale one left out", got, want)
|
||||
}
|
||||
if got, _ := e.repo.AlbumCovers(ctx, ids("d", "a"), 1); !slices.Equal(got, []int64{e.album["Reign"]}) {
|
||||
t.Errorf("limit 1 = %v", got)
|
||||
}
|
||||
if got, err := e.repo.AlbumCovers(ctx, nil, 4); err != nil || got == nil || len(got) != 0 {
|
||||
t.Errorf("no songs = %#v, %v", got, err)
|
||||
}
|
||||
if got, _ := e.repo.AlbumCovers(ctx, ids("c", "e"), 4); len(got) != 0 {
|
||||
t.Errorf("songs of albums with no cover = %v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
111
web/src/api/schema.d.ts
vendored
111
web/src/api/schema.d.ts
vendored
|
|
@ -1012,6 +1012,32 @@ export interface paths {
|
|||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/smart-playlists/suggested/{key}/covers": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description A key from `GET /smart-playlists/suggested`. */
|
||||
key: components["parameters"]["SuggestedKey"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* The covers of a suggested smart playlist
|
||||
* @description Up to 4 albums that have a cover and stand for it, in the order of the songs the rules give now (the ones of
|
||||
* `variant`), each once: their covers (`GET /albums/{id}/cover`) make its picture. It is worked out apart from the
|
||||
* songs so that a list of smart playlists can show the rest without waiting for the rules of every one of them; the
|
||||
* answer may be kept by the client for a few minutes. Empty when none of the songs has an album with a cover.
|
||||
*/
|
||||
get: operations["getSuggestedSmartPlaylistCovers"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/smart-playlists/suggested/{key}/playlist": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
@ -1093,6 +1119,31 @@ export interface paths {
|
|||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/smart-playlists/{id}/covers": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: components["parameters"]["Id"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* The covers of a smart playlist
|
||||
* @description Up to 4 albums that have a cover and stand for it, in the order of the songs the rules give now (the ones of
|
||||
* `variant`), each once: their covers (`GET /albums/{id}/cover`) make its picture. It is worked out apart from the
|
||||
* songs so that a list of smart playlists can show the rest without waiting for the rules of every one of them; the
|
||||
* answer may be kept by the client for a few minutes. Empty when none of the songs has an album with a cover.
|
||||
*/
|
||||
get: operations["getSmartPlaylistCovers"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/smart-playlists/{id}/playlist": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
@ -2657,6 +2708,9 @@ export interface components {
|
|||
/** @default 0 */
|
||||
variant: number;
|
||||
};
|
||||
SmartCovers: {
|
||||
album_ids: number[];
|
||||
};
|
||||
SmartTracks: {
|
||||
variant: number;
|
||||
/** @description In the order of the playlist. Empty when no song meets the rules. */
|
||||
|
|
@ -4713,6 +4767,35 @@ export interface operations {
|
|||
404: components["responses"]["SuggestedNotFound"];
|
||||
};
|
||||
};
|
||||
getSuggestedSmartPlaylistCovers: {
|
||||
parameters: {
|
||||
query?: {
|
||||
/** @description The variant that is on screen, from 0 (the songs of the day) up. */
|
||||
variant?: number;
|
||||
};
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description A key from `GET /smart-playlists/suggested`. */
|
||||
key: components["parameters"]["SuggestedKey"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The albums. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["SmartCovers"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
404: components["responses"]["SuggestedNotFound"];
|
||||
};
|
||||
};
|
||||
saveSuggestedSmartPlaylist: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
@ -4858,6 +4941,34 @@ export interface operations {
|
|||
404: components["responses"]["SmartPlaylistNotFound"];
|
||||
};
|
||||
};
|
||||
getSmartPlaylistCovers: {
|
||||
parameters: {
|
||||
query?: {
|
||||
/** @description The variant that is on screen, from 0 (the songs of the day) up. */
|
||||
variant?: number;
|
||||
};
|
||||
header?: never;
|
||||
path: {
|
||||
id: components["parameters"]["Id"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The albums. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["SmartCovers"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
404: components["responses"]["SmartPlaylistNotFound"];
|
||||
};
|
||||
};
|
||||
saveSmartPlaylist: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
|
|||
|
|
@ -43,6 +43,28 @@ export function useSmartTracks(id: number, variant: number) {
|
|||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The albums that stand for a smart playlist, for its picture: up to four that have a cover, in the order of its songs.
|
||||
* It is asked apart from the songs, once the list is on screen, and kept for a few minutes.
|
||||
*/
|
||||
export function useSmartCovers(id: number, variant = 0) {
|
||||
return useQuery({
|
||||
queryKey: ['smart-covers', id, variant],
|
||||
queryFn: () => api.get<{ album_ids: number[] }>(`/smart-playlists/${id}/covers`, variant > 0 ? { variant } : undefined).then((r) => r.album_ids),
|
||||
staleTime: 5 * 60_000,
|
||||
})
|
||||
}
|
||||
|
||||
/** The same for a suggested smart playlist. */
|
||||
export function useSuggestedCovers(key: string, variant = 0) {
|
||||
return useQuery({
|
||||
queryKey: ['smart-suggested-covers', key, variant],
|
||||
queryFn: () =>
|
||||
api.get<{ album_ids: number[] }>(`/smart-playlists/suggested/${encodeURIComponent(key)}/covers`, variant > 0 ? { variant } : undefined).then((r) => r.album_ids),
|
||||
staleTime: 5 * 60_000,
|
||||
})
|
||||
}
|
||||
|
||||
/** The songs that rules give, without keeping them. It asks again when the rules change. */
|
||||
export function useSmartPreview(input: SmartInput) {
|
||||
return useQuery({
|
||||
|
|
@ -100,7 +122,7 @@ function refresh(client: QueryClient) {
|
|||
return client.invalidateQueries({
|
||||
predicate: (query) => {
|
||||
const key = query.queryKey[0]
|
||||
return typeof key === 'string' && (key.startsWith('/smart-playlists') || key === 'smart' || key === 'smart-tracks')
|
||||
return typeof key === 'string' && (key.startsWith('/smart-playlists') || key === 'smart' || key === 'smart-tracks' || key === 'smart-covers')
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +0,0 @@
|
|||
import { expect, test } from 'vitest'
|
||||
import type { Track } from '@/api/catalog'
|
||||
import { albumIdsOf } from './covers'
|
||||
|
||||
const t = (album: number | null): Track => ({ id: 1, title: 't', duration_ms: 1, track_no: 1, disc_no: 1, album: album === null ? null : { id: album, title: 'a' }, artists: [], format: 'flac' }) as unknown as Track
|
||||
|
||||
test('the albums of a list of songs are the first ones in order, each once, four at most', () => {
|
||||
expect(albumIdsOf([t(3), t(4), t(3), t(5), t(6), t(7), t(8)])).toEqual([3, 4, 5, 6])
|
||||
expect(albumIdsOf([t(9), t(9)])).toEqual([9])
|
||||
expect(albumIdsOf([])).toEqual([])
|
||||
})
|
||||
|
||||
test('a song with no album is left out', () => {
|
||||
expect(albumIdsOf([t(null), t(2), t(null)])).toEqual([2])
|
||||
})
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
import type { Track } from '@/api/catalog'
|
||||
|
||||
/**
|
||||
* The albums that make the picture of a list of songs that has none of its own (a smart playlist, a suggested one): the
|
||||
* first albums in the order they appear, each once, at most four. They may have no cover yet, in which case the
|
||||
* picture shows the rings of an album with none.
|
||||
*/
|
||||
export function albumIdsOf(tracks: Track[]): number[] {
|
||||
const out: number[] = []
|
||||
for (const t of tracks) {
|
||||
const id = t.album?.id
|
||||
if (id !== undefined && id !== null && !out.includes(id)) out.push(id)
|
||||
if (out.length === 4) break
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
@ -3,14 +3,13 @@ import { useState } from 'react'
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { useDeleteSmart, useSaveSmart, useSmartPlaylist, useSmartTracks } from '@/api/smart'
|
||||
import { useDeleteSmart, useSaveSmart, useSmartCovers, useSmartPlaylist, useSmartTracks } from '@/api/smart'
|
||||
import MixCover from '@/components/MixCover'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import TrackList from '@/components/TrackList'
|
||||
import { Button, buttonVariants } from '@/components/ui/button'
|
||||
import { errorMessageKey } from '@/i18n'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { albumIdsOf } from '@/lib/covers'
|
||||
import { formatTime } from '@/lib/time'
|
||||
import { usePlayer } from '@/player/store'
|
||||
import Confirm from '@/pages/admin/Confirm'
|
||||
|
|
@ -34,6 +33,7 @@ function SmartView({ id }: { id: number }) {
|
|||
const [deleting, setDeleting] = useState(false)
|
||||
const playlist = useSmartPlaylist(id)
|
||||
const query = useSmartTracks(id, variant)
|
||||
const covers = useSmartCovers(id, variant)
|
||||
const save = useSaveSmart()
|
||||
const del = useDeleteSmart()
|
||||
const playTracks = usePlayer((s) => s.playTracks)
|
||||
|
|
@ -53,7 +53,7 @@ function SmartView({ id }: { id: number }) {
|
|||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
<header className="flex flex-wrap items-end gap-6">
|
||||
<MixCover albumIds={albumIdsOf(tracks)} size={232} fluid />
|
||||
<MixCover albumIds={covers.data ?? []} size={232} fluid />
|
||||
<div className="flex min-w-0 flex-1 basis-80 flex-col gap-3">
|
||||
<h1 className="text-4xl font-extrabold tracking-tight md:text-6xl">{p.name}</h1>
|
||||
{p.description && <p className="max-w-2xl text-muted-foreground">{p.description}</p>}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,44 @@
|
|||
import { Plus } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useSmartPlaylists, useSuggested } from '@/api/smart'
|
||||
import { useSmartCovers, useSmartPlaylists, useSuggested, useSuggestedCovers } from '@/api/smart'
|
||||
import { CARD_GRID } from '@/components/cards'
|
||||
import LoadMore from '@/components/LoadMore'
|
||||
import MixCover from '@/components/MixCover'
|
||||
import Section from '@/components/Section'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import { buttonVariants } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/** A card for a suggested smart playlist; it asks for its own covers once it is on screen. */
|
||||
function SuggestedCard({ k }: { k: string }) {
|
||||
const { t } = useTranslation()
|
||||
const covers = useSuggestedCovers(k)
|
||||
return (
|
||||
<Link to={`/smart-playlists/suggested/${k}`} className="flex flex-col gap-3 rounded-xl p-3 hover:bg-secondary">
|
||||
<MixCover albumIds={covers.data ?? []} size={200} fluid />
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="truncate font-bold">{t(`smart.suggested.${k}.name`)}</span>
|
||||
<span className="line-clamp-2 text-sm text-muted-foreground">{t(`smart.suggested.${k}.description`)}</span>
|
||||
</span>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
/** A card for a smart playlist of the user's own. */
|
||||
function SmartCard({ id, name, meta }: { id: number; name: string; meta: string }) {
|
||||
const covers = useSmartCovers(id)
|
||||
return (
|
||||
<Link to={`/smart-playlists/${id}`} className="flex flex-col gap-3 rounded-xl p-3 hover:bg-secondary">
|
||||
<MixCover albumIds={covers.data ?? []} size={200} fluid />
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="truncate font-bold">{name}</span>
|
||||
<span className="text-sm text-muted-foreground">{meta}</span>
|
||||
</span>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
/** Your smart playlists: playlists that are a set of rules, worked out every time they are opened. */
|
||||
export default function SmartPlaylistsPage() {
|
||||
const { t } = useTranslation()
|
||||
|
|
@ -29,11 +59,8 @@ export default function SmartPlaylistsPage() {
|
|||
{suggested.data && (
|
||||
<Section title={t('smart.forYou')}>
|
||||
<div className={CARD_GRID}>
|
||||
{suggested.data.map((s) => (
|
||||
<Link key={s.key} to={`/smart-playlists/suggested/${s.key}`} className="flex min-h-28 flex-col justify-between gap-3 rounded-xl bg-card p-4 text-card-foreground hover:bg-secondary">
|
||||
<span className="text-lg leading-tight font-bold">{t(`smart.suggested.${s.key}.name`)}</span>
|
||||
<span className="line-clamp-3 text-sm text-muted-foreground">{t(`smart.suggested.${s.key}.description`)}</span>
|
||||
</Link>
|
||||
{suggested.data.map((sg) => (
|
||||
<SuggestedCard key={sg.key} k={sg.key} />
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
|
|
@ -48,15 +75,10 @@ export default function SmartPlaylistsPage() {
|
|||
<EmptyMessage>{t('smart.empty')}</EmptyMessage>
|
||||
) : (
|
||||
<>
|
||||
<ul className="flex flex-col">
|
||||
<ul className={CARD_GRID}>
|
||||
{items.map((p) => (
|
||||
<li key={p.id}>
|
||||
<Link to={`/smart-playlists/${p.id}`} className="flex min-h-14 items-center justify-between gap-4 rounded-lg px-4 hover:bg-secondary">
|
||||
<span className="truncate font-semibold">{p.name}</span>
|
||||
<span className="flex-none text-sm text-muted-foreground">
|
||||
{t('smart.meta', { count: p.limit, sort: t(`smart.sort.${p.sort}`) })}
|
||||
</span>
|
||||
</Link>
|
||||
<SmartCard id={p.id} name={p.name} meta={t('smart.meta', { count: p.limit, sort: t(`smart.sort.${p.sort}`) })} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
|
|
|||
|
|
@ -3,13 +3,12 @@ import { useState } from 'react'
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { useCreateSmart, useSaveSuggested, useSuggested, useSuggestedTracks } from '@/api/smart'
|
||||
import { useCreateSmart, useSaveSuggested, useSuggested, useSuggestedCovers, useSuggestedTracks } from '@/api/smart'
|
||||
import MixCover from '@/components/MixCover'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import TrackList from '@/components/TrackList'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { errorMessageKey } from '@/i18n'
|
||||
import { albumIdsOf } from '@/lib/covers'
|
||||
import { formatTime } from '@/lib/time'
|
||||
import { usePlayer } from '@/player/store'
|
||||
import { describeRules } from './smartRules'
|
||||
|
|
@ -30,6 +29,7 @@ function SuggestedView({ name: key }: { name: string }) {
|
|||
const [variant, setVariant] = useState(0)
|
||||
const list = useSuggested()
|
||||
const query = useSuggestedTracks(key, variant)
|
||||
const covers = useSuggestedCovers(key, variant)
|
||||
const save = useSaveSuggested()
|
||||
const make = useCreateSmart()
|
||||
const playTracks = usePlayer((s) => s.playTracks)
|
||||
|
|
@ -52,7 +52,7 @@ function SuggestedView({ name: key }: { name: string }) {
|
|||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
<header className="flex flex-wrap items-end gap-6">
|
||||
<MixCover albumIds={albumIdsOf(tracks)} size={232} fluid />
|
||||
<MixCover albumIds={covers.data ?? []} size={232} fluid />
|
||||
<div className="flex min-w-0 flex-1 basis-80 flex-col gap-3">
|
||||
<h1 className="text-4xl font-extrabold tracking-tight md:text-6xl">{title}</h1>
|
||||
<p className="max-w-2xl text-muted-foreground">{description}</p>
|
||||
|
|
|
|||
|
|
@ -553,22 +553,51 @@ test('a smart playlist that exists keeps needing its name, with Claude on too',
|
|||
|
||||
// --- the picture of a smart playlist --------------------------------------------------------------
|
||||
|
||||
const withAlbums = (variant: number, albums: number[]) => ({
|
||||
variant,
|
||||
tracks: albums.map((album, i) => ({ ...track(i + 1), album: { id: album, title: `Album ${album}` } })),
|
||||
})
|
||||
const coversOf = (el: HTMLElement) => Array.from(el.querySelectorAll('img')).map((img) => img.getAttribute('src'))
|
||||
const albums = (...ids: number[]) => ({ album_ids: ids })
|
||||
const cover = (id: number) => `/api/v1/albums/${id}/cover`
|
||||
|
||||
test('the page of a smart playlist shows a collage of the albums of its first songs', async () => {
|
||||
mockFetch(one({ 'GET /api/v1/smart-playlists/3/tracks': () => withAlbums(0, [31, 32, 31, 33, 34, 35]) }))
|
||||
test('the page of a smart playlist shows a collage of the covers that the server says, for the variant on screen', async () => {
|
||||
const { calls } = mockFetch(
|
||||
one({
|
||||
'GET /api/v1/smart-playlists/3/covers': ({ url }) => (url.searchParams.get('variant') === '1' ? albums(5) : albums(31, 32, 33, 34)),
|
||||
'GET /api/v1/smart-playlists/3/tracks': ({ url }) => tracks(Number(url.searchParams.get('variant') ?? 0), 1, 2),
|
||||
}),
|
||||
)
|
||||
renderApp('/smart-playlists/3')
|
||||
const title = await screen.findByRole('heading', { level: 1, name: 'Fresh rock' })
|
||||
await waitFor(() => expect(coversOf(title.closest('header')!)).toEqual(['/api/v1/albums/31/cover', '/api/v1/albums/32/cover', '/api/v1/albums/33/cover', '/api/v1/albums/34/cover']))
|
||||
await waitFor(() => expect(coversOf(title.closest('header')!)).toEqual([cover(31), cover(32), cover(33), cover(34)]))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Shuffle again' }))
|
||||
await waitFor(() => expect(coversOf(title.closest('header')!)).toEqual([cover(5)]))
|
||||
expect(calls.filter((c) => c.key.endsWith('/covers')).map((c) => c.url.searchParams.get('variant'))).toEqual([null, '1'])
|
||||
})
|
||||
|
||||
test('the page of a suggested one shows it too, and one album shows alone', async () => {
|
||||
mockFetch(suggestedOne({ 'GET /api/v1/smart-playlists/suggested/never-played/tracks': () => withAlbums(0, [41, 41, 41]) }))
|
||||
test('the page of a suggested one shows its covers too', async () => {
|
||||
mockFetch(suggestedOne({ 'GET /api/v1/smart-playlists/suggested/never-played/covers': () => albums(41, 42) }))
|
||||
renderApp('/smart-playlists/suggested/never-played')
|
||||
const title = await screen.findByRole('heading', { level: 1, name: 'Never played' })
|
||||
await waitFor(() => expect(coversOf(title.closest('header')!)).toEqual(['/api/v1/albums/41/cover']))
|
||||
await waitFor(() => expect(coversOf(title.closest('header')!)).toEqual([cover(41)]))
|
||||
})
|
||||
|
||||
test('every card of the list asks for its own covers, and shows the rings until they come', async () => {
|
||||
const { calls } = mockFetch({
|
||||
...suggestedRoutes(),
|
||||
'GET /api/v1/smart-playlists': () => page([smart(3, 'Fresh rock'), smart(4, 'Long ones')]),
|
||||
'GET /api/v1/smart-playlists/suggested/never-played/covers': () => albums(41, 42, 43, 44),
|
||||
'GET /api/v1/smart-playlists/suggested/recently-added/covers': () => albums(),
|
||||
'GET /api/v1/smart-playlists/3/covers': () => albums(7),
|
||||
'GET /api/v1/smart-playlists/4/covers': () => apiError(500, 'unknown'),
|
||||
})
|
||||
renderApp('/smart-playlists')
|
||||
const never = await screen.findByRole('link', { name: /Never played/ })
|
||||
await waitFor(() => expect(coversOf(never)).toEqual([cover(41), cover(42), cover(43), cover(44)]))
|
||||
await waitFor(() => expect(coversOf(screen.getByRole('link', { name: /Fresh rock/ }))).toEqual([cover(7)]))
|
||||
// A card with no cover, and one whose covers could not be read, keep the rings and still link to the playlist.
|
||||
const recent = screen.getByRole('link', { name: /Recently added/ })
|
||||
expect(recent.querySelector('[data-placeholder]')).not.toBeNull()
|
||||
const long = screen.getByRole('link', { name: /Long ones/ })
|
||||
expect(long).toHaveAttribute('href', '/smart-playlists/4')
|
||||
expect(long.querySelector('[data-placeholder]')).not.toBeNull()
|
||||
// The covers were asked for each card, after the lists.
|
||||
expect(calls.filter((c) => c.key.endsWith('/covers')).length).toBe(SUGGESTED.length + 2)
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in a new issue