feat: favourites of songs, albums and artists, in the API and in apps
A person can mark songs, albums and artists as favourites. They are theirs
alone: never shown to a friend, never sent anywhere. Only what can be played is
listed.
- migration 0035 favorites, internal/favorites, storage.FavoritesRepo
- PUT/DELETE /me/favorites/{kind}/{id}, GET /me/favorites/{kind} and
GET /me/favorites/ids, in the OpenAPI spec
- catalog.Filter IDs now also reads artists by id
- OpenSubsonic: star, unstar, getStarred2, the starred date on songs, albums and
artists, and getAlbumList2 of type starred
This commit is contained in:
parent
17c134ef8b
commit
74f683d26e
28 changed files with 1676 additions and 42 deletions
|
|
@ -37,11 +37,12 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
|||
- **Similar artists.** With Last.fm turned on, `GET /artists/{id}/similar` lists artists similar to an artist, and says which of them you already have. See [External providers](#external-providers). Without it, Sonda makes no outbound network requests at all.
|
||||
- **Friends (federation).** Two Sonda servers can become friends, and the listeners of one can read what the other chose to share. `PUT /federation` (admin) turns federation on, which is off by default, and gives this server a name and a public address (`https`; plain `http` only on a network of your own); the server then makes its own Ed25519 key, kept in the database and never returned. `POST /federation/invites` makes an invite that works once and expires in 24 hours (only a hash of its code is kept). The other admin uses it with `POST /federation/friends`: that server is asked to accept this one, the key it answers with must be the one named in the invite, and the friend waits as `outgoing` until the first admin approves it with `POST /federation/friends/{id}/approve` (`POST /federation/friends/{id}/check` lets the waiting side find out). Either side can remove a friend with `DELETE /federation/friends/{id}`. Nothing is shared until an admin turns on `shared` for a library (`PATCH /libraries/{id}`). A friend's server then reads, with requests signed by its key (the method, the path and query, a date, a nonce and the hash of the body), the routes under `/peer`: the artists, albums and songs that have a file in a shared library, their covers once they are built, and the audio itself with `Range`. A friend never sees a path, a library id, a listen, a taste or a user, never makes this server build a cover or ask a provider, and has a few streams at a time and a number of KiB a second to share (`max_streams`, `max_kib_per_sec`); the admin sees the last requests it made (`GET /federation/requests`, the route and the size, never what was searched for). Sharing a library lets friends play it and, in practice, copy its files. A listener browses the music of a friend with `GET /friends` (the names of the friends whose friendship both admins agreed to, never an address or a key) and `GET /friends/{friend}/artists`, `albums` and `tracks` with `q`, `limit` and `offset`, and one item at a time: this server asks the friend with a signed request, checks the shape of the answer and passes it on, and nothing is kept; the ids are the friend's own. A friend that cannot be reached or no longer takes this server for a friend is told in words. The web app has a Friends section for it, shown only when there is a friend to browse. A listener plays it with `GET /friends/{friend}/tracks/{id}/stream` and sees its covers with `GET /friends/{friend}/albums/{id}/cover`, which accept the access token in the query like the local ones: this server asks the friend with a signed request, forwards `Range` and the conditional headers, and passes on only audio (or a JPEG for a cover) with `Content-Type`, `Content-Length`, `Content-Range`, `Accept-Ranges`, `Last-Modified` and `ETag`, so the friend sees this server and never the listener, and a friend cannot make this server serve anything else. A friend's song plays in the same player as the others but is never reported as a listen and does not feed taste. The admin area has a Federation section for all of it.
|
||||
|
||||
- **Favourites.** `PUT /me/favorites/{kind}/{id}` marks a song, an album or an artist (`kind` is `tracks`, `albums` or `artists`) as a favourite and `DELETE` takes it back; `GET /me/favorites/{kind}` lists them, the newest first, and `GET /me/favorites/ids` gives every id for the hearts of a list. They are yours alone: never shown to a friend and never sent anywhere. Apps that speak OpenSubsonic see them as starred things.
|
||||
- **Other apps.** Apps that speak OpenSubsonic (Symfonium, Feishin, Amperfy, Supersonic and others) can browse, search, play, show covers, use your playlists and report what you listened to, with a password of their own for each app (see [Other apps](#other-apps-opensubsonic)).
|
||||
|
||||
## What is not there yet
|
||||
|
||||
Radio queues, transcoding, stars (favourites), and the ListenBrainz integration. The web client is built into the binary (see [Web app](#web-app)), and its admin area covers everything the API can do for an admin: libraries and scanning, users, the external providers and the bulk jobs.
|
||||
Radio queues, transcoding, ratings, and the ListenBrainz integration. The web client is built into the binary (see [Web app](#web-app)), and its admin area covers everything the API can do for an admin: libraries and scanning, users, the external providers and the bulk jobs.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
|
@ -308,7 +309,8 @@ A device password opens your music in that app and nothing else: it cannot sign
|
|||
| `stream`, `download`, `getCoverArt` | The original file (with Range), and covers of albums, artists and songs. |
|
||||
| `getPlaylists`, `getPlaylist`, `createPlaylist`, `updatePlaylist`, `deletePlaylist` | Your playlists, the same ones as in the web app. |
|
||||
| `scrobble` | A listen is recorded like one made in the web app (and shared on Mastodon if you connected it). A "now playing" message is not recorded. |
|
||||
| `getStarred2`, `star`, `unstar`, `setRating`, `getNowPlaying` | Answered with nothing: there are no stars yet, and what you play is nobody else's business. |
|
||||
| `star`, `unstar`, `getStarred2` | Your favourites (see **Favourites**): songs, albums and artists, with the `starred` date on each, and `getAlbumList2` of type `starred`. |
|
||||
| `setRating`, `getNowPlaying` | Answered with nothing: there are no ratings, and what you play is nobody else's business. |
|
||||
|
||||
Sonda does not transcode: an app always gets the original file, whatever format or bit rate it asks for. The music of friends (federation) is not shown to apps.
|
||||
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import (
|
|||
"git.kmalloc.org/squid/sonda/internal/discover"
|
||||
"git.kmalloc.org/squid/sonda/internal/discovery"
|
||||
"git.kmalloc.org/squid/sonda/internal/duplicates"
|
||||
"git.kmalloc.org/squid/sonda/internal/favorites"
|
||||
"git.kmalloc.org/squid/sonda/internal/federation"
|
||||
"git.kmalloc.org/squid/sonda/internal/feedback"
|
||||
"git.kmalloc.org/squid/sonda/internal/images"
|
||||
|
|
@ -304,6 +305,7 @@ func run() error {
|
|||
deviceSvc := devices.NewService(storage.NewDevicesRepo(db), []byte(cfg.Auth.JWTSecret))
|
||||
catalogSvc := catalog.NewService(storage.NewCatalogRepo(db))
|
||||
streamSvc := streaming.NewService(libraryRepo)
|
||||
favoriteSvc := favorites.NewService(storage.NewFavoritesRepo(db), catalogSvc)
|
||||
listeningSvc := listening.NewService(storage.NewListeningRepo(db), cfg.Listening.MinListen())
|
||||
subsonicRepo := storage.NewSubsonicRepo(db, cfg.Listening.MinListen())
|
||||
|
||||
|
|
@ -316,10 +318,11 @@ func run() error {
|
|||
Listening: listeningSvc,
|
||||
Mastodon: mastodonSvc,
|
||||
Devices: deviceSvc,
|
||||
Favorites: favoriteSvc,
|
||||
OpenSubsonic: &opensubsonic.Deps{
|
||||
Login: deviceSvc, Catalog: catalogSvc, Libraries: libraries,
|
||||
Extras: subsonicRepo, Lists: subsonicRepo, Streams: streamSvc, Covers: pictures, ArtistImages: pictures,
|
||||
Playlists: playlistSvc, Listens: listeningSvc, Announcer: mastodonSvc,
|
||||
Playlists: playlistSvc, Listens: listeningSvc, Announcer: mastodonSvc, Favorites: favoriteSvc,
|
||||
ServerVersion: version,
|
||||
},
|
||||
Scan: scanControl{ctx: ctx, m: scans},
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import (
|
|||
"git.kmalloc.org/squid/sonda/internal/discover"
|
||||
"git.kmalloc.org/squid/sonda/internal/discovery"
|
||||
"git.kmalloc.org/squid/sonda/internal/duplicates"
|
||||
"git.kmalloc.org/squid/sonda/internal/favorites"
|
||||
"git.kmalloc.org/squid/sonda/internal/federation"
|
||||
"git.kmalloc.org/squid/sonda/internal/feedback"
|
||||
"git.kmalloc.org/squid/sonda/internal/images"
|
||||
|
|
@ -140,6 +141,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
|
|||
deps.PeerCovers = images.StoredOnly{Service: imageSvc}
|
||||
deps.CoversJob = jobs.Runner{Ctx: context.Background(), Job: images.NewCoversJob(imageSvc, imageRepo)}
|
||||
deps.ArtistImagesJob = jobs.Runner{Ctx: context.Background(), Job: images.NewArtistImagesJob(imageSvc, imageRepo)}
|
||||
deps.Favorites = favorites.NewService(storage.NewFavoritesRepo(db), deps.Catalog.(favorites.Catalog))
|
||||
mutate(&deps, db)
|
||||
if deps.OpenSubsonic == nil {
|
||||
subsonic := storage.NewSubsonicRepo(db, 20*time.Second)
|
||||
|
|
@ -148,7 +150,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
|
|||
Libraries: deps.Libraries.(opensubsonic.Libraries), ServerVersion: "test",
|
||||
Extras: subsonic, Lists: subsonic, Streams: deps.Streams.(opensubsonic.Streams),
|
||||
Covers: deps.Images.(opensubsonic.Covers), ArtistImages: deps.ArtistImages.(opensubsonic.ArtistImages),
|
||||
Playlists: deps.Playlists.(opensubsonic.Playlists), Listens: deps.Listening.(opensubsonic.Listens), Announcer: deps.Mastodon.(opensubsonic.Announcer),
|
||||
Playlists: deps.Playlists.(opensubsonic.Playlists), Listens: deps.Listening.(opensubsonic.Listens), Announcer: deps.Mastodon.(opensubsonic.Announcer), Favorites: deps.Favorites.(opensubsonic.Favorites),
|
||||
}
|
||||
}
|
||||
if deps.About == nil {
|
||||
|
|
|
|||
|
|
@ -904,6 +904,28 @@ func TestResponsesMatchTheSpec(t *testing.T) {
|
|||
c.expect(c.call("DELETE", "/me/devices/"+idOf(made), token, nil), 404, "take back a device twice", "device_not_found")
|
||||
c.expect(c.call("GET", "/me/devices", "", nil), 401, "devices without a token", "unauthorized")
|
||||
|
||||
// Favourites: what is marked is listed, newest first, and only the person's own.
|
||||
if got := c.expect(c.call("GET", "/me/favorites/ids", token, nil), 200, "no favourites yet"); len(got["tracks"].([]any)) != 0 {
|
||||
c.t.Errorf("favourites = %v", got)
|
||||
}
|
||||
for kind, id := range map[string]string{"tracks": trackID, "albums": albumID, "artists": artistID} {
|
||||
c.expect(c.call("PUT", "/me/favorites/"+kind+"/"+id, token, nil), 204, "mark a favourite "+kind)
|
||||
if got := c.expect(c.call("GET", "/me/favorites/"+kind, token, nil), 200, "favourite "+kind); got["total"] != float64(1) {
|
||||
c.t.Errorf("favourite %s = %v", kind, got)
|
||||
}
|
||||
}
|
||||
if got := c.expect(c.call("GET", "/me/favorites/ids", token, nil), 200, "the favourites"); len(got["albums"].([]any)) != 1 {
|
||||
c.t.Errorf("favourites = %v", got)
|
||||
}
|
||||
c.expect(c.call("DELETE", "/me/favorites/albums/"+albumID, token, nil), 204, "unmark a favourite")
|
||||
c.expect(c.call("DELETE", "/me/favorites/albums/"+albumID, token, nil), 204, "unmark it again")
|
||||
c.expect(c.call("DELETE", "/me/favorites/songs/1", token, nil), 404, "unmark a kind that does not exist", "not_found")
|
||||
c.expect(c.call("PUT", "/me/favorites/tracks/9999", token, nil), 404, "a song that is not there", "track_not_found")
|
||||
c.expect(c.call("PUT", "/me/favorites/songs/1", token, nil), 404, "a kind that does not exist", "not_found")
|
||||
c.expect(c.call("GET", "/me/favorites/songs", token, nil), 404, "favourites of no kind", "not_found")
|
||||
c.expect(c.call("GET", "/me/favorites/tracks?limit=-1", token, nil), 400, "a negative limit", "invalid_input")
|
||||
c.expect(c.call("GET", "/me/favorites/tracks", "", nil), 401, "favourites without a token", "unauthorized")
|
||||
|
||||
// Bringing a Spotify export in: what it did, and what is refused.
|
||||
export := `[{"ts":"2023-05-01T10:00:00Z","ms_played":200000,"master_metadata_track_name":"Nowhere","master_metadata_album_artist_name":"Nobody"}]`
|
||||
imported := c.expect(c.upload("/me/import/spotify", token, export, `{"playlists":[{"name":"P","items":[{"track":{"trackName":"Nowhere","artistName":"Nobody"}}]}]}`), 200, "import a Spotify export")
|
||||
|
|
|
|||
|
|
@ -414,3 +414,44 @@ func TestPlaylistsAndListensOfAnAppAreThoseOfThePerson(t *testing.T) {
|
|||
t.Fatalf("history %v", hist.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStarInAnAppIsAFavouriteInTheWebApp(t *testing.T) {
|
||||
e := newCoversEnv(t)
|
||||
secret := do(t, e.h, "POST", "/api/v1/me/devices", e.token, map[string]any{"name": "Phone"}).Body["secret"].(string)
|
||||
var song int64
|
||||
_ = e.db.QueryRow("SELECT id FROM tracks WHERE title = 'With Art song'").Scan(&song)
|
||||
rest := func(path string, q url.Values) map[string]any {
|
||||
q.Set("apiKey", secret)
|
||||
q.Set("f", "json")
|
||||
rec := httptest.NewRecorder()
|
||||
e.h.ServeHTTP(rec, httptest.NewRequest("GET", "/rest/"+path+"?"+q.Encode(), nil))
|
||||
var out struct {
|
||||
R map[string]any `json:"subsonic-response"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.R["status"] != "ok" {
|
||||
t.Fatalf("%s: %v %s", path, err, rec.Body.String())
|
||||
}
|
||||
return out.R
|
||||
}
|
||||
|
||||
rest("star", url.Values{"id": {"tr-" + itoa(song)}, "albumId": {"al-" + itoa(e.withArt)}})
|
||||
ids := do(t, e.h, "GET", "/api/v1/me/favorites/ids", e.token, nil).Body
|
||||
if len(ids["tracks"].([]any)) != 1 || len(ids["albums"].([]any)) != 1 {
|
||||
t.Fatalf("the web app sees %v", ids)
|
||||
}
|
||||
if n := len(rest("getAlbumList2", url.Values{"type": {"starred"}})["albumList2"].(map[string]any)["album"].([]any)); n != 1 {
|
||||
t.Fatalf("starred albums %d", n)
|
||||
}
|
||||
|
||||
// And the other way round: a favourite made in the web app is starred in the app.
|
||||
do(t, e.h, "DELETE", "/api/v1/me/favorites/tracks/"+itoa(song), e.token, nil)
|
||||
do(t, e.h, "PUT", "/api/v1/me/favorites/tracks/"+itoa(song), e.token, nil)
|
||||
st := rest("getStarred2", url.Values{})["starred2"].(map[string]any)
|
||||
if len(st["song"].([]any)) != 1 || st["song"].([]any)[0].(map[string]any)["starred"] == nil {
|
||||
t.Fatalf("starred %v", st)
|
||||
}
|
||||
rest("unstar", url.Values{"id": {"tr-" + itoa(song)}})
|
||||
if got := do(t, e.h, "GET", "/api/v1/me/favorites/ids", e.token, nil).Body["tracks"].([]any); len(got) != 0 {
|
||||
t.Fatalf("after unstar %v", got)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
99
internal/api/http/favorites_test.go
Normal file
99
internal/api/http/favorites_test.go
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFavouritesNeedASignedInUser(t *testing.T) {
|
||||
h := newTestAPI(t)
|
||||
for _, c := range [][2]string{{"GET", "/api/v1/me/favorites/ids"}, {"GET", "/api/v1/me/favorites/tracks"}, {"PUT", "/api/v1/me/favorites/tracks/1"}, {"DELETE", "/api/v1/me/favorites/tracks/1"}} {
|
||||
if r := do(t, h, c[0], c[1], "", map[string]any{}); r.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s %s: %d", c[0], c[1], r.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSongsAlbumsAndArtistsAreMarkedListedAndUnmarked(t *testing.T) {
|
||||
e := newCoversEnv(t)
|
||||
var song, artist int64
|
||||
if err := e.db.QueryRow("SELECT id FROM tracks WHERE title = 'With Art song'").Scan(&song); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.db.QueryRow("SELECT id FROM artists WHERE name = 'Band'").Scan(&artist); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
put := func(kind string, id int64) resp {
|
||||
return do(t, e.h, "PUT", "/api/v1/me/favorites/"+kind+"/"+itoa(id), e.token, nil)
|
||||
}
|
||||
|
||||
for kind, id := range map[string]int64{"tracks": song, "albums": e.withArt, "artists": artist} {
|
||||
if r := put(kind, id); r.Code != http.StatusNoContent {
|
||||
t.Fatalf("PUT %s: %d %v", kind, r.Code, r.Body)
|
||||
}
|
||||
if r := put(kind, id); r.Code != http.StatusNoContent {
|
||||
t.Fatalf("PUT %s again: %d", kind, r.Code)
|
||||
}
|
||||
}
|
||||
ids := do(t, e.h, "GET", "/api/v1/me/favorites/ids", e.token, nil)
|
||||
sameKeys(t, "ids", ids.Body, "artists", "albums", "tracks")
|
||||
if got := ids.Body["tracks"].([]any); len(got) != 1 || int64(got[0].(float64)) != song {
|
||||
t.Fatalf("ids %v", ids.Body)
|
||||
}
|
||||
|
||||
tracks := do(t, e.h, "GET", "/api/v1/me/favorites/tracks", e.token, nil)
|
||||
items := tracks.Body["items"].([]any)
|
||||
if len(items) != 1 || items[0].(map[string]any)["title"] != "With Art song" || tracks.Body["total"] != float64(1) {
|
||||
t.Fatalf("tracks %v", tracks.Body)
|
||||
}
|
||||
if a := do(t, e.h, "GET", "/api/v1/me/favorites/albums", e.token, nil).Body["items"].([]any); len(a) != 1 || a[0].(map[string]any)["title"] != "With Art" {
|
||||
t.Fatalf("albums %v", a)
|
||||
}
|
||||
if a := do(t, e.h, "GET", "/api/v1/me/favorites/artists", e.token, nil).Body["items"].([]any); len(a) != 1 || a[0].(map[string]any)["name"] != "Band" {
|
||||
t.Fatalf("artists %v", a)
|
||||
}
|
||||
|
||||
if r := do(t, e.h, "DELETE", "/api/v1/me/favorites/tracks/"+itoa(song), e.token, nil); r.Code != http.StatusNoContent {
|
||||
t.Fatalf("DELETE: %d", r.Code)
|
||||
}
|
||||
if r := do(t, e.h, "DELETE", "/api/v1/me/favorites/tracks/"+itoa(song), e.token, nil); r.Code != http.StatusNoContent {
|
||||
t.Fatalf("DELETE twice: %d", r.Code)
|
||||
}
|
||||
if got := do(t, e.h, "GET", "/api/v1/me/favorites/tracks", e.token, nil).Body["items"].([]any); len(got) != 0 {
|
||||
t.Fatalf("after delete %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhatIsNotThereCannotBeMarked(t *testing.T) {
|
||||
e := newCoversEnv(t)
|
||||
for path, code := range map[string]string{
|
||||
"/api/v1/me/favorites/tracks/9999": "track_not_found",
|
||||
"/api/v1/me/favorites/albums/9999": "album_not_found",
|
||||
"/api/v1/me/favorites/artists/9999": "artist_not_found",
|
||||
"/api/v1/me/favorites/songs/1": "not_found",
|
||||
"/api/v1/me/favorites/tracks/0": "invalid_input",
|
||||
"/api/v1/me/favorites/tracks/x": "invalid_input",
|
||||
} {
|
||||
r := do(t, e.h, "PUT", path, e.token, nil)
|
||||
if r.Code < 400 || errCode(r) != code {
|
||||
t.Errorf("PUT %s: %d %v, want %s", path, r.Code, r.Body, code)
|
||||
}
|
||||
}
|
||||
if r := do(t, e.h, "GET", "/api/v1/me/favorites/songs", e.token, nil); r.Code != http.StatusNotFound || errCode(r) != "not_found" {
|
||||
t.Errorf("an unknown kind: %d %v", r.Code, r.Body)
|
||||
}
|
||||
if r := do(t, e.h, "GET", "/api/v1/me/favorites/tracks?limit=-1", e.token, nil); r.Code != http.StatusBadRequest {
|
||||
t.Errorf("a negative limit: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFavouritesAreOfEachPersonAlone(t *testing.T) {
|
||||
e := newCoversEnv(t)
|
||||
var song int64
|
||||
_ = e.db.QueryRow("SELECT id FROM tracks WHERE title = 'With Art song'").Scan(&song)
|
||||
do(t, e.h, "PUT", "/api/v1/me/favorites/tracks/"+itoa(song), e.token, nil)
|
||||
_, bob := addUser(t, e.h, e.token, "bob", false)
|
||||
if got := do(t, e.h, "GET", "/api/v1/me/favorites/ids", bob, nil).Body["tracks"].([]any); len(got) != 0 {
|
||||
t.Fatalf("bob sees %v", got)
|
||||
}
|
||||
}
|
||||
162
internal/api/http/handlers_favorites.go
Normal file
162
internal/api/http/handlers_favorites.go
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.kmalloc.org/squid/sonda/internal/catalog"
|
||||
"git.kmalloc.org/squid/sonda/internal/favorites"
|
||||
)
|
||||
|
||||
// favoriteService is what the handlers need from favorites.Service.
|
||||
type favoriteService interface {
|
||||
Add(ctx context.Context, userID int64, kind favorites.Kind, id int64) error
|
||||
Remove(ctx context.Context, userID int64, kind favorites.Kind, id int64) error
|
||||
Page(ctx context.Context, userID int64, kind favorites.Kind, limit, offset int) ([]int64, int, error)
|
||||
IDs(ctx context.Context, userID int64) (favorites.All, error)
|
||||
Marks(ctx context.Context, userID int64, kind favorites.Kind, ids []int64) (map[int64]time.Time, error)
|
||||
}
|
||||
|
||||
// favoriteHandlers serve the favourites of the signed-in user, who only ever sees their own.
|
||||
type favoriteHandlers struct {
|
||||
svc favoriteService
|
||||
catalog catalogService
|
||||
}
|
||||
|
||||
func (h *favoriteHandlers) kind(c *gin.Context) (favorites.Kind, bool) {
|
||||
kind, ok := favorites.ParseKind(c.Param("kind"))
|
||||
if !ok {
|
||||
writeError(c, http.StatusNotFound, "not_found", "favourites are of artists, albums or tracks")
|
||||
}
|
||||
return kind, ok
|
||||
}
|
||||
|
||||
func (h *favoriteHandlers) ids(c *gin.Context) {
|
||||
all, err := h.svc.IDs(c.Request.Context(), currentUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"artists": all.Artists, "albums": all.Albums, "tracks": all.Tracks})
|
||||
}
|
||||
|
||||
func (h *favoriteHandlers) add(c *gin.Context) {
|
||||
kind, ok := h.kind(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := pathID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
switch err := h.svc.Add(c.Request.Context(), currentUserID(c), kind, id); {
|
||||
case errors.Is(err, favorites.ErrNotFound):
|
||||
writeError(c, http.StatusNotFound, string(kind)+"_not_found", "no such "+string(kind))
|
||||
case err != nil:
|
||||
_ = c.Error(err)
|
||||
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
||||
default:
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *favoriteHandlers) remove(c *gin.Context) {
|
||||
kind, ok := h.kind(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := pathID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.svc.Remove(c.Request.Context(), currentUserID(c), kind, id); err != nil {
|
||||
_ = c.Error(err)
|
||||
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// list is a page of the favourites of a kind, the newest first, in the shape of the catalogue lists.
|
||||
func (h *favoriteHandlers) list(c *gin.Context) {
|
||||
kind, ok := h.kind(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, ok := queryInt(c, "limit")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
offset, ok := queryInt(c, "offset")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
ids, total, err := h.svc.Page(ctx, currentUserID(c), kind, clampInt(limit), clampInt(offset))
|
||||
switch {
|
||||
case errors.Is(err, favorites.ErrInvalid):
|
||||
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
|
||||
return
|
||||
case err != nil:
|
||||
_ = c.Error(err)
|
||||
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
f := catalog.Filter{IDs: ids, Limit: len(ids)}
|
||||
if len(ids) == 0 {
|
||||
c.JSON(http.StatusOK, gin.H{"items": []any{}, "total": total, "limit": pageLimit(limit), "offset": clampInt(offset)})
|
||||
return
|
||||
}
|
||||
switch kind {
|
||||
case favorites.Artist:
|
||||
p, err := h.catalog.Artists(ctx, f)
|
||||
writeFavorites(c, err, ids, total, limit, offset, byID(p.Items, func(a catalog.Artist) int64 { return a.ID }), toArtistJSON)
|
||||
case favorites.Album:
|
||||
p, err := h.catalog.Albums(ctx, f)
|
||||
writeFavorites(c, err, ids, total, limit, offset, byID(p.Items, func(a catalog.Album) int64 { return a.ID }), toAlbumJSON)
|
||||
default:
|
||||
p, err := h.catalog.Tracks(ctx, f)
|
||||
writeFavorites(c, err, ids, total, limit, offset, byID(p.Items, func(t catalog.Track) int64 { return t.ID }), toTrackJSON)
|
||||
}
|
||||
}
|
||||
|
||||
func byID[T any](items []T, id func(T) int64) map[int64]T {
|
||||
m := make(map[int64]T, len(items))
|
||||
for _, it := range items {
|
||||
m[id(it)] = it
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// write answers with the items in the order of the ids.
|
||||
func writeFavorites[T, J any](c *gin.Context, err error, ids []int64, total int, limit, offset int64, items map[int64]T, conv func(T) J) {
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
out := make([]J, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if it, ok := items[id]; ok {
|
||||
out = append(out, conv(it))
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": out, "total": total, "limit": pageLimit(limit), "offset": clampInt(offset)})
|
||||
}
|
||||
|
||||
// pageLimit is the size of the page the service gave for the limit that was asked.
|
||||
func pageLimit(asked int64) int {
|
||||
switch n := clampInt(asked); {
|
||||
case n == 0:
|
||||
return favorites.DefaultLimit
|
||||
case n > favorites.MaxLimit:
|
||||
return favorites.MaxLimit
|
||||
default:
|
||||
return n
|
||||
}
|
||||
}
|
||||
|
|
@ -230,6 +230,7 @@ type Deps struct {
|
|||
Listening listenService
|
||||
Mastodon mastodonService
|
||||
Devices deviceService
|
||||
Favorites favoriteService
|
||||
Scan scanService
|
||||
Libraries libraryService
|
||||
Catalog catalogService
|
||||
|
|
@ -400,6 +401,11 @@ func NewRouter(d Deps) *gin.Engine {
|
|||
protected.GET("/me/mastodon", ma.get)
|
||||
protected.PUT("/me/mastodon", ma.connect)
|
||||
protected.DELETE("/me/mastodon", ma.disconnect)
|
||||
fv := &favoriteHandlers{svc: d.Favorites, catalog: d.Catalog}
|
||||
protected.GET("/me/favorites/ids", fv.ids)
|
||||
protected.GET("/me/favorites/:kind", fv.list)
|
||||
protected.PUT("/me/favorites/:kind/:id", fv.add)
|
||||
protected.DELETE("/me/favorites/:kind/:id", fv.remove)
|
||||
dv := &deviceHandlers{svc: d.Devices}
|
||||
protected.GET("/me/devices", dv.list)
|
||||
protected.POST("/me/devices", dv.create)
|
||||
|
|
|
|||
|
|
@ -2271,6 +2271,92 @@ paths:
|
|||
'204': {description: Disconnected.}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
|
||||
/me/favorites/ids:
|
||||
get:
|
||||
tags: [Taste]
|
||||
operationId: listMyFavoriteIds
|
||||
summary: The ids of all your favourites
|
||||
description: |
|
||||
The ids of every artist, album and track you marked as a favourite, newest first, so that an app can show a
|
||||
heart in any list with one call. Only music that can be played is listed. Yours alone: never shown to a friend.
|
||||
security: [{bearerAuth: []}]
|
||||
responses:
|
||||
'200':
|
||||
description: Your favourites by kind.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/FavoriteIds'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
|
||||
/me/favorites/{kind}:
|
||||
get:
|
||||
tags: [Taste]
|
||||
operationId: listMyFavorites
|
||||
summary: A page of your favourites of one kind
|
||||
description: |
|
||||
The artists, albums or tracks you marked as favourites, the newest favourite first, in the same shape as the
|
||||
lists of the catalogue. Only music that can be played is listed.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/FavoriteKind'}
|
||||
- {$ref: '#/components/parameters/Limit'}
|
||||
- {$ref: '#/components/parameters/Offset'}
|
||||
responses:
|
||||
'200':
|
||||
description: A page of artists, albums or tracks, according to `kind`.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
oneOf:
|
||||
- {$ref: '#/components/schemas/ArtistPage'}
|
||||
- {$ref: '#/components/schemas/AlbumPage'}
|
||||
- {$ref: '#/components/schemas/TrackPage'}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404':
|
||||
description: There are no favourites of that kind (`not_found`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
/me/favorites/{kind}/{id}:
|
||||
put:
|
||||
tags: [Taste]
|
||||
operationId: addMyFavorite
|
||||
summary: Mark something as a favourite
|
||||
description: Marks an artist, album or track of this server as a favourite. Marking it again changes nothing and keeps the first date.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/FavoriteKind'}
|
||||
- {name: id, in: path, required: true, schema: {type: integer, format: int64, minimum: 1}}
|
||||
responses:
|
||||
'204': {description: Marked.}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404':
|
||||
description: There is no such kind (`not_found`), or no such music that can be played (`artist_not_found`, `album_not_found`, `track_not_found`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
delete:
|
||||
tags: [Taste]
|
||||
operationId: removeMyFavorite
|
||||
summary: Take something out of your favourites
|
||||
description: Unmarks it. Unmarking what is not a favourite is not an error.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/FavoriteKind'}
|
||||
- {name: id, in: path, required: true, schema: {type: integer, format: int64, minimum: 1}}
|
||||
responses:
|
||||
'204': {description: Unmarked.}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404':
|
||||
description: There is no such kind (`not_found`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
/me/devices:
|
||||
get:
|
||||
tags: [Taste]
|
||||
|
|
@ -4452,6 +4538,12 @@ components:
|
|||
the body, which is empty). Anything that is not properly signed gets the same `401`.
|
||||
|
||||
parameters:
|
||||
FavoriteKind:
|
||||
name: kind
|
||||
in: path
|
||||
required: true
|
||||
description: What the favourites are of.
|
||||
schema: {type: string, enum: [artists, albums, tracks]}
|
||||
Id:
|
||||
name: id
|
||||
in: path
|
||||
|
|
@ -6083,6 +6175,15 @@ components:
|
|||
name: {type: string}
|
||||
count: {type: integer, description: 'Plays and playlist songs of this artist that were not found.'}
|
||||
|
||||
FavoriteIds:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [artists, albums, tracks]
|
||||
properties:
|
||||
artists: {type: array, items: {type: integer, format: int64}}
|
||||
albums: {type: array, items: {type: integer, format: int64}}
|
||||
tracks: {type: array, items: {type: integer, format: int64}}
|
||||
|
||||
Device:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ type Filter struct {
|
|||
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)
|
||||
IDs []int64 // albums and tracks: only these ids (at most MaxLimit); nil is no limit
|
||||
IDs []int64 // artists, albums and tracks: only these ids (at most MaxLimit); nil is no limit
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
|
|
|||
166
internal/favorites/favorites.go
Normal file
166
internal/favorites/favorites.go
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
// Package favorites keeps the songs, albums and artists a person marked as favourites.
|
||||
//
|
||||
// They are the person's own: never shown to a friend and never sent anywhere. Only music of this server can be a
|
||||
// favourite. A favourite whose music is gone (or cannot be played any more) is not listed, and is listed again if the
|
||||
// music comes back.
|
||||
package favorites
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.kmalloc.org/squid/sonda/internal/catalog"
|
||||
)
|
||||
|
||||
// Kind is what is marked.
|
||||
type Kind string
|
||||
|
||||
// The kinds of favourite.
|
||||
const (
|
||||
Artist Kind = "artist"
|
||||
Album Kind = "album"
|
||||
Track Kind = "track"
|
||||
)
|
||||
|
||||
// Errors returned by the service.
|
||||
var (
|
||||
// ErrNotFound is an item that is not in the catalogue, or a kind that does not exist.
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalid = errors.New("invalid input")
|
||||
)
|
||||
|
||||
// Paging limits of a list of favourites.
|
||||
const (
|
||||
DefaultLimit = 50
|
||||
MaxLimit = 200
|
||||
)
|
||||
|
||||
// ParseKind reads the form a kind has in an address: artists, albums or tracks.
|
||||
func ParseKind(s string) (Kind, bool) {
|
||||
switch s {
|
||||
case "artists":
|
||||
return Artist, true
|
||||
case "albums":
|
||||
return Album, true
|
||||
case "tracks":
|
||||
return Track, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Store keeps the favourites. It lists only items that can be played.
|
||||
type Store interface {
|
||||
// Add marks an item; marking it again keeps the first date.
|
||||
Add(ctx context.Context, userID int64, kind Kind, id int64, at time.Time) error
|
||||
// Remove unmarks an item; one that is not marked is not an error.
|
||||
Remove(ctx context.Context, userID int64, kind Kind, id int64) error
|
||||
// Page returns the ids of a page of the favourites of a kind, the newest first, and how many there are.
|
||||
Page(ctx context.Context, userID int64, kind Kind, limit, offset int) ([]int64, int, error)
|
||||
// IDs returns the ids of every favourite of a kind, the newest first.
|
||||
IDs(ctx context.Context, userID int64, kind Kind) ([]int64, error)
|
||||
// Marks returns when each of the ids that are favourites was marked.
|
||||
Marks(ctx context.Context, userID int64, kind Kind, ids []int64) (map[int64]time.Time, error)
|
||||
}
|
||||
|
||||
// Catalog says what can be a favourite: *catalog.Service.
|
||||
type Catalog interface {
|
||||
Artist(ctx context.Context, id int64) (catalog.Artist, error)
|
||||
Album(ctx context.Context, id int64) (catalog.Album, error)
|
||||
Track(ctx context.Context, id int64) (catalog.Track, error)
|
||||
}
|
||||
|
||||
// Service marks and lists favourites.
|
||||
type Service struct {
|
||||
store Store
|
||||
catalog Catalog
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewService builds a Service.
|
||||
func NewService(store Store, catalog Catalog) *Service {
|
||||
return &Service{store: store, catalog: catalog, now: time.Now}
|
||||
}
|
||||
|
||||
func valid(kind Kind) bool { return kind == Artist || kind == Album || kind == Track }
|
||||
|
||||
// Add marks an item as a favourite of a person.
|
||||
func (s *Service) Add(ctx context.Context, userID int64, kind Kind, id int64) error {
|
||||
if !valid(kind) || id < 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
var err error
|
||||
switch kind {
|
||||
case Artist:
|
||||
var a catalog.Artist
|
||||
if a, err = s.catalog.Artist(ctx, id); err == nil && a.TrackCount == 0 && a.AlbumCount == 0 {
|
||||
err = catalog.ErrNotFound // an artist a provider named, with no music here
|
||||
}
|
||||
case Album:
|
||||
_, err = s.catalog.Album(ctx, id)
|
||||
case Track:
|
||||
_, err = s.catalog.Track(ctx, id)
|
||||
}
|
||||
if errors.Is(err, catalog.ErrNotFound) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("find %s: %w", kind, err)
|
||||
}
|
||||
return s.store.Add(ctx, userID, kind, id, s.now())
|
||||
}
|
||||
|
||||
// Remove unmarks an item.
|
||||
func (s *Service) Remove(ctx context.Context, userID int64, kind Kind, id int64) error {
|
||||
if !valid(kind) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return s.store.Remove(ctx, userID, kind, id)
|
||||
}
|
||||
|
||||
// Page returns a page of the favourites of a kind, the newest first.
|
||||
func (s *Service) Page(ctx context.Context, userID int64, kind Kind, limit, offset int) ([]int64, int, error) {
|
||||
if !valid(kind) {
|
||||
return nil, 0, ErrNotFound
|
||||
}
|
||||
if limit < 0 || offset < 0 {
|
||||
return nil, 0, fmt.Errorf("%w: limit and offset cannot be negative", ErrInvalid)
|
||||
}
|
||||
switch {
|
||||
case limit == 0:
|
||||
limit = DefaultLimit
|
||||
case limit > MaxLimit:
|
||||
limit = MaxLimit
|
||||
}
|
||||
return s.store.Page(ctx, userID, kind, limit, offset)
|
||||
}
|
||||
|
||||
// All is every favourite of a person, by kind, as ids.
|
||||
type All struct {
|
||||
Artists, Albums, Tracks []int64
|
||||
}
|
||||
|
||||
// IDs returns every favourite of a person, for the hearts of a list.
|
||||
func (s *Service) IDs(ctx context.Context, userID int64) (All, error) {
|
||||
var out All
|
||||
for kind, into := range map[Kind]*[]int64{Artist: &out.Artists, Album: &out.Albums, Track: &out.Tracks} {
|
||||
ids, err := s.store.IDs(ctx, userID, kind)
|
||||
if err != nil {
|
||||
return All{}, err
|
||||
}
|
||||
if ids == nil {
|
||||
ids = []int64{}
|
||||
}
|
||||
*into = ids
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Marks returns when each of the ids that are favourites of a person was marked.
|
||||
func (s *Service) Marks(ctx context.Context, userID int64, kind Kind, ids []int64) (map[int64]time.Time, error) {
|
||||
if !valid(kind) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return s.store.Marks(ctx, userID, kind, ids)
|
||||
}
|
||||
202
internal/favorites/favorites_test.go
Normal file
202
internal/favorites/favorites_test.go
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
package favorites
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.kmalloc.org/squid/sonda/internal/catalog"
|
||||
)
|
||||
|
||||
type key struct {
|
||||
user int64
|
||||
kind Kind
|
||||
id int64
|
||||
}
|
||||
|
||||
type memStore struct{ at map[key]time.Time }
|
||||
|
||||
func (m *memStore) Add(_ context.Context, user int64, kind Kind, id int64, at time.Time) error {
|
||||
if m.at == nil {
|
||||
m.at = map[key]time.Time{}
|
||||
}
|
||||
if _, has := m.at[key{user, kind, id}]; !has {
|
||||
m.at[key{user, kind, id}] = at
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memStore) Remove(_ context.Context, user int64, kind Kind, id int64) error {
|
||||
delete(m.at, key{user, kind, id})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memStore) ids(user int64, kind Kind) []int64 {
|
||||
var out []int64
|
||||
for k := range m.at {
|
||||
if k.user == user && k.kind == kind {
|
||||
out = append(out, k.id)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return m.at[key{user, kind, out[i]}].After(m.at[key{user, kind, out[j]}]) })
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *memStore) Page(_ context.Context, user int64, kind Kind, limit, offset int) ([]int64, int, error) {
|
||||
all := m.ids(user, kind)
|
||||
if offset >= len(all) {
|
||||
return []int64{}, len(all), nil
|
||||
}
|
||||
end := min(len(all), offset+limit)
|
||||
return all[offset:end], len(all), nil
|
||||
}
|
||||
|
||||
func (m *memStore) IDs(_ context.Context, user int64, kind Kind) ([]int64, error) {
|
||||
return m.ids(user, kind), nil
|
||||
}
|
||||
|
||||
func (m *memStore) Marks(_ context.Context, user int64, kind Kind, ids []int64) (map[int64]time.Time, error) {
|
||||
out := map[int64]time.Time{}
|
||||
for _, id := range ids {
|
||||
if at, ok := m.at[key{user, kind, id}]; ok {
|
||||
out[id] = at
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// The catalogue of the tests: artist 1 has music, artist 2 was only named by a provider, album 7 and track 70 exist.
|
||||
type fakeCatalog struct{}
|
||||
|
||||
func (fakeCatalog) Artist(_ context.Context, id int64) (catalog.Artist, error) {
|
||||
switch id {
|
||||
case 1:
|
||||
return catalog.Artist{ID: 1, Name: "A", AlbumCount: 1, TrackCount: 2}, nil
|
||||
case 2:
|
||||
return catalog.Artist{ID: 2, Name: "Named only"}, nil
|
||||
}
|
||||
return catalog.Artist{}, catalog.ErrNotFound
|
||||
}
|
||||
|
||||
func (fakeCatalog) Album(_ context.Context, id int64) (catalog.Album, error) {
|
||||
if id == 7 {
|
||||
return catalog.Album{ID: 7}, nil
|
||||
}
|
||||
return catalog.Album{}, catalog.ErrNotFound
|
||||
}
|
||||
|
||||
func (fakeCatalog) Track(_ context.Context, id int64) (catalog.Track, error) {
|
||||
if id == 70 || id == 71 {
|
||||
return catalog.Track{ID: id}, nil
|
||||
}
|
||||
return catalog.Track{}, catalog.ErrNotFound
|
||||
}
|
||||
|
||||
func newService() (*Service, *memStore) {
|
||||
st := &memStore{}
|
||||
s := NewService(st, fakeCatalog{})
|
||||
n := int64(0)
|
||||
s.now = func() time.Time { n++; return time.Unix(1_700_000_000+n, 0) }
|
||||
return s, st
|
||||
}
|
||||
|
||||
func TestOnlyWhatIsInTheCatalogueCanBeAFavourite(t *testing.T) {
|
||||
s, _ := newService()
|
||||
ctx := context.Background()
|
||||
for _, c := range []struct {
|
||||
kind Kind
|
||||
id int64
|
||||
}{{Artist, 1}, {Album, 7}, {Track, 70}} {
|
||||
if err := s.Add(ctx, 1, c.kind, c.id); err != nil {
|
||||
t.Errorf("%s %d: %v", c.kind, c.id, err)
|
||||
}
|
||||
}
|
||||
for _, c := range []struct {
|
||||
kind Kind
|
||||
id int64
|
||||
}{{Artist, 99}, {Artist, 2}, {Album, 8}, {Track, 99}, {Track, 0}, {Track, -1}, {Kind("song"), 70}} {
|
||||
if err := s.Add(ctx, 1, c.kind, c.id); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("%s %d: %v", c.kind, c.id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddingTwiceKeepsTheFirstDateAndRemovingIsForgiving(t *testing.T) {
|
||||
s, st := newService()
|
||||
ctx := context.Background()
|
||||
_ = s.Add(ctx, 1, Track, 70)
|
||||
first := st.at[key{1, Track, 70}]
|
||||
_ = s.Add(ctx, 1, Track, 70)
|
||||
if !st.at[key{1, Track, 70}].Equal(first) {
|
||||
t.Fatal("the date moved")
|
||||
}
|
||||
if err := s.Remove(ctx, 1, Track, 70); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Remove(ctx, 1, Track, 70); err != nil {
|
||||
t.Fatalf("removing what is not a favourite: %v", err)
|
||||
}
|
||||
if err := s.Remove(ctx, 1, Kind("nope"), 1); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("an unknown kind: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEachPersonHasTheirOwnFavourites(t *testing.T) {
|
||||
s, _ := newService()
|
||||
ctx := context.Background()
|
||||
_ = s.Add(ctx, 1, Track, 70)
|
||||
_ = s.Add(ctx, 2, Track, 71)
|
||||
a, _ := s.IDs(ctx, 1)
|
||||
b, _ := s.IDs(ctx, 2)
|
||||
if len(a.Tracks) != 1 || a.Tracks[0] != 70 || len(b.Tracks) != 1 || b.Tracks[0] != 71 {
|
||||
t.Fatalf("%v %v", a, b)
|
||||
}
|
||||
if len(a.Albums) != 0 || a.Albums == nil || a.Artists == nil {
|
||||
t.Fatalf("empty kinds are empty lists: %+v", a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPageIsNewestFirst(t *testing.T) {
|
||||
s, _ := newService()
|
||||
ctx := context.Background()
|
||||
_ = s.Add(ctx, 1, Track, 70)
|
||||
_ = s.Add(ctx, 1, Track, 71)
|
||||
ids, total, err := s.Page(ctx, 1, Track, 1, 0)
|
||||
if err != nil || total != 2 || len(ids) != 1 || ids[0] != 71 {
|
||||
t.Fatalf("%v %d %v", ids, total, err)
|
||||
}
|
||||
if _, _, err := s.Page(ctx, 1, Track, -1, 0); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("negative limit: %v", err)
|
||||
}
|
||||
if _, _, err := s.Page(ctx, 1, Kind("x"), 10, 0); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("unknown kind: %v", err)
|
||||
}
|
||||
if ids, _, _ := s.Page(ctx, 1, Track, 0, 0); len(ids) != 2 {
|
||||
t.Fatalf("default limit gives %v", ids)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseKindReadsThePathForm(t *testing.T) {
|
||||
for in, want := range map[string]Kind{"artists": Artist, "albums": Album, "tracks": Track} {
|
||||
if got, ok := ParseKind(in); !ok || got != want {
|
||||
t.Errorf("%s: %v %v", in, got, ok)
|
||||
}
|
||||
}
|
||||
for _, in := range []string{"", "artist", "songs", "Tracks"} {
|
||||
if _, ok := ParseKind(in); ok {
|
||||
t.Errorf("%q was accepted", in)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarksTellWhenAnItemBecameAFavourite(t *testing.T) {
|
||||
s, _ := newService()
|
||||
ctx := context.Background()
|
||||
_ = s.Add(ctx, 1, Track, 70)
|
||||
m, err := s.Marks(ctx, 1, Track, []int64{70, 71})
|
||||
if err != nil || len(m) != 1 || m[70].IsZero() {
|
||||
t.Fatalf("%v %v", m, err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
package opensubsonic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
|
@ -12,6 +11,7 @@ import (
|
|||
"golang.org/x/text/unicode/norm"
|
||||
|
||||
"git.kmalloc.org/squid/sonda/internal/catalog"
|
||||
"git.kmalloc.org/squid/sonda/internal/favorites"
|
||||
)
|
||||
|
||||
// Ids are strings that say what they are: ar-12 an artist, al-7 an album, tr-99 a song.
|
||||
|
|
@ -99,9 +99,13 @@ func (h *handler) artists(k *call) (*Response, *Error) {
|
|||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
described, err := h.artistList(k, list)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
var index []Index
|
||||
at := map[string]int{}
|
||||
for _, a := range list {
|
||||
for n, a := range list {
|
||||
letter := indexLetter(a.Name)
|
||||
i, ok := at[letter]
|
||||
if !ok {
|
||||
|
|
@ -109,7 +113,7 @@ func (h *handler) artists(k *call) (*Response, *Error) {
|
|||
at[letter] = i
|
||||
index = append(index, Index{Name: letter, Artist: []ArtistID3{}})
|
||||
}
|
||||
index[i].Artist = append(index[i].Artist, artistOf(a))
|
||||
index[i].Artist = append(index[i].Artist, described[n])
|
||||
}
|
||||
sortIndex(index)
|
||||
if index == nil {
|
||||
|
|
@ -168,26 +172,35 @@ func (h *handler) artist(k *call) (*Response, *Error) {
|
|||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
out, err := h.albums(k.ctx, albums)
|
||||
out, err := h.albums(k, albums)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
return &Response{Artist: &ArtistWithAlbums{ArtistID3: artistOf(a), Album: out}}, nil
|
||||
self, err := h.artistList(k, []catalog.Artist{a})
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
return &Response{Artist: &ArtistWithAlbums{ArtistID3: self[0], Album: out}}, nil
|
||||
}
|
||||
|
||||
// albums describes albums, with what the catalogue does not carry.
|
||||
func (h *handler) albums(ctx context.Context, list []catalog.Album) ([]AlbumID3, error) {
|
||||
func (h *handler) albums(k *call, list []catalog.Album) ([]AlbumID3, error) {
|
||||
ids := make([]int64, len(list))
|
||||
for i, a := range list {
|
||||
ids[i] = a.ID
|
||||
}
|
||||
extras, err := h.Extras.Albums(ctx, ids)
|
||||
extras, err := h.Extras.Albums(k.ctx, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
marks, err := h.marks(k, favorites.Album, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]AlbumID3, len(list))
|
||||
for i, a := range list {
|
||||
out[i] = albumOf(a, extras[a.ID])
|
||||
out[i].Starred = stamp(marks[a.ID])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
|
@ -222,11 +235,11 @@ func (h *handler) album(k *call) (*Response, *Error) {
|
|||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
out, err := h.albums(k.ctx, []catalog.Album{al})
|
||||
out, err := h.albums(k, []catalog.Album{al})
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
songs, err := h.songs(k.ctx, tracks)
|
||||
songs, err := h.songs(k, tracks)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
|
|
@ -242,7 +255,7 @@ func (h *handler) song(k *call) (*Response, *Error) {
|
|||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
songs, err := h.songs(k.ctx, []catalog.Track{t})
|
||||
songs, err := h.songs(k, []catalog.Track{t})
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
|
|
@ -262,22 +275,53 @@ func (h *handler) genres(k *call) (*Response, *Error) {
|
|||
}
|
||||
|
||||
// songs describes songs, with what the catalogue does not carry.
|
||||
func (h *handler) songs(ctx context.Context, list []catalog.Track) ([]Child, error) {
|
||||
func (h *handler) songs(k *call, list []catalog.Track) ([]Child, error) {
|
||||
ids := make([]int64, len(list))
|
||||
for i, t := range list {
|
||||
ids[i] = t.ID
|
||||
}
|
||||
extras, err := h.Extras.Tracks(ctx, ids)
|
||||
extras, err := h.Extras.Tracks(k.ctx, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
marks, err := h.marks(k, favorites.Track, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]Child, len(list))
|
||||
for i, t := range list {
|
||||
out[i] = childOf(t, extras[t.ID])
|
||||
out[i].Starred = stamp(marks[t.ID])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// artistList describes artists, with the date each became a favourite of the person.
|
||||
func (h *handler) artistList(k *call, list []catalog.Artist) ([]ArtistID3, error) {
|
||||
ids := make([]int64, len(list))
|
||||
for i, a := range list {
|
||||
ids[i] = a.ID
|
||||
}
|
||||
marks, err := h.marks(k, favorites.Artist, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]ArtistID3, len(list))
|
||||
for i, a := range list {
|
||||
out[i] = artistOf(a)
|
||||
out[i].Starred = stamp(marks[a.ID])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// marks says when each of the ids became a favourite of the person; it is empty when there are no favourites to ask.
|
||||
func (h *handler) marks(k *call, kind favorites.Kind, ids []int64) (map[int64]time.Time, error) {
|
||||
if h.Favorites == nil || len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return h.Favorites.Marks(k.ctx, k.principal.UserID, kind, ids)
|
||||
}
|
||||
|
||||
func childOf(t catalog.Track, e TrackExtra) Child {
|
||||
c := Child{
|
||||
ID: trackID(t.ID), Title: t.Title, Track: t.TrackNo, DiscNumber: t.DiscNo, Duration: seconds(t.DurationMs),
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@ type Deps struct {
|
|||
Covers Covers
|
||||
ArtistImages ArtistImages
|
||||
Playlists Playlists
|
||||
Favorites Favorites // optional: with none nothing is a favourite
|
||||
Listens Listens
|
||||
Announcer Announcer // optional
|
||||
ServerVersion string
|
||||
|
|
@ -92,8 +93,8 @@ func Register(r gin.IRoutes, d Deps) {
|
|||
"getSongsByGenre": h.songsByGenre,
|
||||
"search3": h.search3,
|
||||
"getStarred2": h.starred2,
|
||||
"star": nothing,
|
||||
"unstar": nothing,
|
||||
"star": h.star,
|
||||
"unstar": h.unstar,
|
||||
"setRating": nothing,
|
||||
"stream": h.stream,
|
||||
"download": h.download,
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import (
|
|||
|
||||
"git.kmalloc.org/squid/sonda/internal/catalog"
|
||||
"git.kmalloc.org/squid/sonda/internal/devices"
|
||||
"git.kmalloc.org/squid/sonda/internal/favorites"
|
||||
"git.kmalloc.org/squid/sonda/internal/images"
|
||||
"git.kmalloc.org/squid/sonda/internal/library"
|
||||
"git.kmalloc.org/squid/sonda/internal/listening"
|
||||
|
|
@ -79,7 +80,19 @@ func (c *fakeCatalog) Artists(_ context.Context, f catalog.Filter) (catalog.Page
|
|||
if f.LibraryID != 0 {
|
||||
c.libs = append(c.libs, f.LibraryID)
|
||||
}
|
||||
return catalog.Page[catalog.Artist]{Items: page(artists, f), Total: len(artists), Limit: f.Limit, Offset: f.Offset}, nil
|
||||
all := artists
|
||||
if f.IDs != nil {
|
||||
var keep []catalog.Artist
|
||||
for _, a := range artists {
|
||||
for _, id := range f.IDs {
|
||||
if a.ID == id {
|
||||
keep = append(keep, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
all = keep
|
||||
}
|
||||
return catalog.Page[catalog.Artist]{Items: page(all, f), Total: len(all), Limit: f.Limit, Offset: f.Offset}, nil
|
||||
}
|
||||
|
||||
func (c *fakeCatalog) Albums(_ context.Context, f catalog.Filter) (catalog.Page[catalog.Album], error) {
|
||||
|
|
@ -734,18 +747,15 @@ func TestAnAlbumListThatIsAskedForBadly(t *testing.T) {
|
|||
failed(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "newest", "musicFolderId", "x")), ErrNotFound)
|
||||
}
|
||||
|
||||
func TestStarredThingsAreNone(t *testing.T) {
|
||||
func TestRatingsAreNotKept(t *testing.T) {
|
||||
m := newMediaServer()
|
||||
good(t, get(t, m.h, "GET", "/rest/star", ok("id", "tr-70")))
|
||||
good(t, get(t, m.h, "GET", "/rest/unstar", ok("id", "tr-70")))
|
||||
good(t, get(t, m.h, "GET", "/rest/setRating", ok("id", "tr-70", "rating", "5")))
|
||||
// An app that has no favourites to ask still gets answers.
|
||||
good(t, get(t, m.h, "GET", "/rest/star", ok("id", "tr-70")))
|
||||
s := good(t, get(t, m.h, "GET", "/rest/getStarred2", ok()))["starred2"].(map[string]any)
|
||||
if len(s) != 0 {
|
||||
t.Fatalf("starred %v", s)
|
||||
}
|
||||
if r := good(t, get(t, m.h, "GET", "/rest/getAlbumList2", ok("type", "starred"))); r["albumList2"] == nil {
|
||||
t.Fatalf("starred albums %v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSongsAtRandomAndByGenre(t *testing.T) {
|
||||
|
|
@ -1147,3 +1157,171 @@ func TestAListenOfWhatIsNotThereOrIsBadlyAskedFor(t *testing.T) {
|
|||
t.Fatalf("events %+v", w.listens.events)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- favourites ----
|
||||
|
||||
type fakeFavorites struct {
|
||||
at map[string]time.Time // kind + id -> when
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func newFakeFavorites() *fakeFavorites { return &fakeFavorites{at: map[string]time.Time{}} }
|
||||
|
||||
func fkey(kind favorites.Kind, id int64) string { return string(kind) + fmt.Sprint(id) }
|
||||
|
||||
var exists = map[string]bool{"artist1": true, "artist4": true, "album7": true, "track70": true, "track71": true}
|
||||
|
||||
func (f *fakeFavorites) Add(_ context.Context, _ int64, kind favorites.Kind, id int64) error {
|
||||
if !exists[fkey(kind, id)] {
|
||||
return favorites.ErrNotFound
|
||||
}
|
||||
f.last = f.last.Add(time.Minute)
|
||||
f.at[fkey(kind, id)] = f.last
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeFavorites) Remove(_ context.Context, _ int64, kind favorites.Kind, id int64) error {
|
||||
delete(f.at, fkey(kind, id))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeFavorites) IDs(_ context.Context, _ int64) (favorites.All, error) {
|
||||
all := favorites.All{Artists: []int64{}, Albums: []int64{}, Tracks: []int64{}}
|
||||
// Newest first, as the real one: the order the tests mark them in, backwards.
|
||||
for _, id := range []int64{71, 70} {
|
||||
if _, ok := f.at[fkey(favorites.Track, id)]; ok {
|
||||
all.Tracks = append(all.Tracks, id)
|
||||
}
|
||||
}
|
||||
if _, ok := f.at[fkey(favorites.Album, 7)]; ok {
|
||||
all.Albums = append(all.Albums, 7)
|
||||
}
|
||||
for _, id := range []int64{4, 1} {
|
||||
if _, ok := f.at[fkey(favorites.Artist, id)]; ok {
|
||||
all.Artists = append(all.Artists, id)
|
||||
}
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
func (f *fakeFavorites) Marks(_ context.Context, _ int64, kind favorites.Kind, ids []int64) (map[int64]time.Time, error) {
|
||||
out := map[int64]time.Time{}
|
||||
for _, id := range ids {
|
||||
if at, ok := f.at[fkey(kind, id)]; ok {
|
||||
out[id] = at
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func newStarServer() (http.Handler, *fakeFavorites) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
fav := newFakeFavorites()
|
||||
fav.last = time.Unix(1_700_000_000, 0)
|
||||
r := gin.New()
|
||||
Register(r, Deps{Login: fakeLogin{}, Catalog: &fakeCatalog{}, Libraries: fakeLibraries{}, Extras: fakeExtras{}, ServerVersion: "9.9", Favorites: fav})
|
||||
return r, fav
|
||||
}
|
||||
|
||||
func TestSongsAlbumsAndArtistsAreStarredAndUnstarred(t *testing.T) {
|
||||
h, fav := newStarServer()
|
||||
q := ok()
|
||||
q.Add("id", "tr-70")
|
||||
q.Add("id", "tr-71")
|
||||
q.Add("albumId", "al-7")
|
||||
q.Add("artistId", "ar-1")
|
||||
good(t, get(t, h, "GET", "/rest/star", q))
|
||||
if len(fav.at) != 4 {
|
||||
t.Fatalf("starred %v", fav.at)
|
||||
}
|
||||
|
||||
// An id of any kind is understood by its prefix, in whichever parameter it comes.
|
||||
other := ok()
|
||||
other.Add("id", "ar-4")
|
||||
good(t, get(t, h, "GET", "/rest/star", other))
|
||||
if _, ok := fav.at["artist4"]; !ok {
|
||||
t.Fatalf("starred %v", fav.at)
|
||||
}
|
||||
|
||||
un := ok()
|
||||
un.Add("id", "tr-70")
|
||||
un.Add("artistId", "ar-4")
|
||||
good(t, get(t, h, "GET", "/rest/unstar", un))
|
||||
if _, ok := fav.at["track70"]; ok {
|
||||
t.Fatalf("still starred %v", fav.at)
|
||||
}
|
||||
if len(fav.at) != 3 {
|
||||
t.Fatalf("starred %v", fav.at)
|
||||
}
|
||||
good(t, get(t, h, "GET", "/rest/unstar", un)) // what is not starred is not an error
|
||||
}
|
||||
|
||||
func TestWhatCannotBeStarredIsNotFound(t *testing.T) {
|
||||
h, fav := newStarServer()
|
||||
for _, id := range []string{"tr-99", "al-8", "ar-2", "pl-1", "70", "tr-x"} {
|
||||
q := ok()
|
||||
q.Add("id", id)
|
||||
failed(t, get(t, h, "GET", "/rest/star", q), ErrNotFound)
|
||||
}
|
||||
failed(t, get(t, h, "GET", "/rest/star", ok()), ErrMissingParam)
|
||||
failed(t, get(t, h, "GET", "/rest/unstar", ok()), ErrMissingParam)
|
||||
if len(fav.at) != 0 {
|
||||
t.Fatalf("starred %v", fav.at)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStarredThingsAreListedAndMarkedWithTheirDate(t *testing.T) {
|
||||
h, _ := newStarServer()
|
||||
q := ok()
|
||||
q.Add("id", "tr-70")
|
||||
q.Add("id", "tr-71")
|
||||
q.Add("albumId", "al-7")
|
||||
q.Add("artistId", "ar-1")
|
||||
good(t, get(t, h, "GET", "/rest/star", q))
|
||||
|
||||
s := good(t, get(t, h, "GET", "/rest/getStarred2", ok()))["starred2"].(map[string]any)
|
||||
songs, albums, artists := s["song"].([]any), s["album"].([]any), s["artist"].([]any)
|
||||
if len(songs) != 2 || songs[0].(map[string]any)["id"] != "tr-71" || len(albums) != 1 || len(artists) != 1 {
|
||||
t.Fatalf("starred %v", s)
|
||||
}
|
||||
if songs[0].(map[string]any)["starred"] == nil || artists[0].(map[string]any)["starred"] == nil || albums[0].(map[string]any)["starred"] == nil {
|
||||
t.Fatalf("no date on %v", s)
|
||||
}
|
||||
|
||||
// Everywhere a song, an album or an artist is told, the date is there when it is starred.
|
||||
al := good(t, get(t, h, "GET", "/rest/getAlbum", ok("id", "al-7")))["album"].(map[string]any)
|
||||
if al["starred"] == nil || al["song"].([]any)[0].(map[string]any)["starred"] == nil {
|
||||
t.Fatalf("album %v", al)
|
||||
}
|
||||
ar := good(t, get(t, h, "GET", "/rest/getArtist", ok("id", "ar-1")))["artist"].(map[string]any)
|
||||
if ar["starred"] == nil {
|
||||
t.Fatalf("artist %v", ar)
|
||||
}
|
||||
idx := good(t, get(t, h, "GET", "/rest/getArtists", ok()))["artists"].(map[string]any)["index"].([]any)
|
||||
var starred, plain int
|
||||
for _, g := range idx {
|
||||
for _, a := range g.(map[string]any)["artist"].([]any) {
|
||||
if a.(map[string]any)["starred"] != nil {
|
||||
starred++
|
||||
} else {
|
||||
plain++
|
||||
}
|
||||
}
|
||||
}
|
||||
if starred != 1 || plain != 3 {
|
||||
t.Fatalf("starred %d, not %d", starred, plain)
|
||||
}
|
||||
if song := good(t, get(t, h, "GET", "/rest/getSong", ok("id", "tr-70")))["song"].(map[string]any); song["starred"] == nil {
|
||||
t.Fatalf("song %v", song)
|
||||
}
|
||||
|
||||
un := ok()
|
||||
un.Add("id", "tr-70")
|
||||
good(t, get(t, h, "GET", "/rest/unstar", un))
|
||||
if song := good(t, get(t, h, "GET", "/rest/getSong", ok("id", "tr-70")))["song"].(map[string]any); song["starred"] != nil {
|
||||
t.Fatalf("song %v", song)
|
||||
}
|
||||
if n := len(good(t, get(t, h, "GET", "/rest/getStarred2", ok()))["starred2"].(map[string]any)["song"].([]any)); n != 1 {
|
||||
t.Fatalf("starred songs %d", n)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -234,7 +234,7 @@ func (h *handler) albumList2(k *call) (*Response, *Error) {
|
|||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
out, err := h.albums(k.ctx, albums)
|
||||
out, err := h.albums(k, albums)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
|
|
@ -294,7 +294,7 @@ func (h *handler) songList(k *call, q SongQuery) ([]Child, *Error) {
|
|||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
songs, err := h.songs(k.ctx, tracks)
|
||||
songs, err := h.songs(k, tracks)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
|
|
@ -379,8 +379,8 @@ func (h *handler) search3(k *call) (*Response, *Error) {
|
|||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
for _, a := range artists {
|
||||
res.Artist = append(res.Artist, artistOf(a))
|
||||
if res.Artist, err = h.artistList(k, artists); err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
}
|
||||
if n[1].count > 0 {
|
||||
|
|
@ -392,7 +392,7 @@ func (h *handler) search3(k *call) (*Response, *Error) {
|
|||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
if res.Album, err = h.albums(k.ctx, albums); err != nil {
|
||||
if res.Album, err = h.albums(k, albums); err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
}
|
||||
|
|
@ -405,7 +405,7 @@ func (h *handler) search3(k *call) (*Response, *Error) {
|
|||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
if res.Song, err = h.songs(k.ctx, tracks); err != nil {
|
||||
if res.Song, err = h.songs(k, tracks); err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
}
|
||||
|
|
@ -429,9 +429,5 @@ func window[T any](n, offset int, fetch func(limit, offset int) (catalog.Page[T]
|
|||
return out, nil
|
||||
}
|
||||
|
||||
func (h *handler) starred2(*call) (*Response, *Error) {
|
||||
return &Response{Starred2: &SearchResult{}}, nil
|
||||
}
|
||||
|
||||
// nothing answers the calls that star, unstar or rate: Sonda has no stars yet, and an app should not break for it.
|
||||
// nothing answers the calls that rate: Sonda has no ratings, and an app should not break for it.
|
||||
func nothing(*call) (*Response, *Error) { return &Response{}, nil }
|
||||
|
|
|
|||
|
|
@ -114,7 +114,7 @@ func (h *handler) opened(k *call, id int64) (*Response, *Error) {
|
|||
for i, it := range items {
|
||||
tracks[i] = it.Track
|
||||
}
|
||||
songs, err := h.songs(k.ctx, tracks)
|
||||
songs, err := h.songs(k, tracks)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -144,6 +144,7 @@ type ArtistID3 struct {
|
|||
Name string `xml:"name,attr" json:"name"`
|
||||
AlbumCount int `xml:"albumCount,attr" json:"albumCount"`
|
||||
CoverArt string `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"`
|
||||
Starred string `xml:"starred,attr,omitempty" json:"starred,omitempty"`
|
||||
}
|
||||
|
||||
// ArtistWithAlbums is an artist and its albums.
|
||||
|
|
@ -173,6 +174,7 @@ type AlbumID3 struct {
|
|||
SongCount int `xml:"songCount,attr" json:"songCount"`
|
||||
Duration int `xml:"duration,attr" json:"duration"`
|
||||
Created string `xml:"created,attr" json:"created"`
|
||||
Starred string `xml:"starred,attr,omitempty" json:"starred,omitempty"`
|
||||
Year int `xml:"year,attr,omitempty" json:"year,omitempty"`
|
||||
Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"`
|
||||
DisplayArtist string `xml:"displayArtist,attr,omitempty" json:"displayArtist,omitempty"`
|
||||
|
|
@ -214,6 +216,7 @@ type Child struct {
|
|||
Path string `xml:"path,attr,omitempty" json:"path,omitempty"`
|
||||
DiscNumber int `xml:"discNumber,attr,omitempty" json:"discNumber,omitempty"`
|
||||
Created string `xml:"created,attr,omitempty" json:"created,omitempty"`
|
||||
Starred string `xml:"starred,attr,omitempty" json:"starred,omitempty"`
|
||||
AlbumID string `xml:"albumId,attr,omitempty" json:"albumId,omitempty"`
|
||||
ArtistID string `xml:"artistId,attr,omitempty" json:"artistId,omitempty"`
|
||||
Type string `xml:"type,attr,omitempty" json:"type,omitempty"`
|
||||
|
|
|
|||
141
internal/opensubsonic/starred.go
Normal file
141
internal/opensubsonic/starred.go
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
package opensubsonic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.kmalloc.org/squid/sonda/internal/catalog"
|
||||
"git.kmalloc.org/squid/sonda/internal/favorites"
|
||||
)
|
||||
|
||||
// Favorites keeps the favourites of a person: *favorites.Service. In an app they are the starred things.
|
||||
type Favorites interface {
|
||||
Add(ctx context.Context, userID int64, kind favorites.Kind, id int64) error
|
||||
Remove(ctx context.Context, userID int64, kind favorites.Kind, id int64) error
|
||||
IDs(ctx context.Context, userID int64) (favorites.All, error)
|
||||
Marks(ctx context.Context, userID int64, kind favorites.Kind, ids []int64) (map[int64]time.Time, error)
|
||||
}
|
||||
|
||||
// target is something an app stars or unstars.
|
||||
type target struct {
|
||||
kind favorites.Kind
|
||||
id int64
|
||||
}
|
||||
|
||||
// targets reads what a call stars: song ids in id, albums in albumId, artists in artistId. Each may be given many times,
|
||||
// and the prefix of an id says what it is whatever parameter it came in.
|
||||
func targets(k *call) ([]target, *Error) {
|
||||
var out []target
|
||||
for _, name := range []string{"id", "albumId", "artistId"} {
|
||||
for _, raw := range k.c.Request.Form[name] {
|
||||
var (
|
||||
kind favorites.Kind
|
||||
prefix string
|
||||
)
|
||||
switch {
|
||||
case strings.HasPrefix(raw, trackPrefix):
|
||||
kind, prefix = favorites.Track, trackPrefix
|
||||
case strings.HasPrefix(raw, albumPrefix):
|
||||
kind, prefix = favorites.Album, albumPrefix
|
||||
case strings.HasPrefix(raw, artistPrefix):
|
||||
kind, prefix = favorites.Artist, artistPrefix
|
||||
default:
|
||||
return nil, notFound()
|
||||
}
|
||||
id, bad := idOf(raw, prefix)
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
out = append(out, target{kind, id})
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, missing("id, albumId or artistId")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (h *handler) star(k *call) (*Response, *Error) { return h.mark(k, true) }
|
||||
func (h *handler) unstar(k *call) (*Response, *Error) { return h.mark(k, false) }
|
||||
|
||||
// mark stars or unstars what the call names. Something that cannot be found stops the call, and what came before it
|
||||
// stays starred.
|
||||
func (h *handler) mark(k *call, on bool) (*Response, *Error) {
|
||||
if h.Favorites == nil {
|
||||
return &Response{}, nil
|
||||
}
|
||||
all, bad := targets(k)
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
for _, t := range all {
|
||||
var err error
|
||||
if on {
|
||||
err = h.Favorites.Add(k.ctx, k.principal.UserID, t.kind, t.id)
|
||||
} else {
|
||||
err = h.Favorites.Remove(k.ctx, k.principal.UserID, t.kind, t.id)
|
||||
}
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, favorites.ErrNotFound):
|
||||
return nil, notFound()
|
||||
default:
|
||||
return nil, &Error{Code: ErrGeneric, Message: "the favourite could not be changed"}
|
||||
}
|
||||
}
|
||||
return &Response{}, nil
|
||||
}
|
||||
|
||||
// starred2 is the favourites of the person: artists, albums and songs, the newest first.
|
||||
func (h *handler) starred2(k *call) (*Response, *Error) {
|
||||
res := &SearchResult{}
|
||||
if h.Favorites == nil {
|
||||
return &Response{Starred2: res}, nil
|
||||
}
|
||||
all, err := h.Favorites.IDs(k.ctx, k.principal.UserID)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
artists, err := h.artistsByID(k, all.Artists)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
if res.Artist, err = h.artistList(k, artists); err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
albums, err := h.albumsByID(k.ctx, all.Albums)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
if res.Album, err = h.albums(k, albums); err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
tracks, err := h.tracksByID(k.ctx, all.Tracks)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
if res.Song, err = h.songs(k, tracks); err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
return &Response{Starred2: res}, nil
|
||||
}
|
||||
|
||||
// artistsByID reads artists by their ids, in the order of the ids.
|
||||
func (h *handler) artistsByID(k *call, ids []int64) ([]catalog.Artist, error) {
|
||||
byID := map[int64]catalog.Artist{}
|
||||
rest := ids
|
||||
for len(rest) > 0 {
|
||||
chunk := rest[:min(len(rest), catalog.MaxLimit)]
|
||||
rest = rest[len(chunk):]
|
||||
p, err := h.Catalog.Artists(k.ctx, catalog.Filter{IDs: chunk, Limit: len(chunk)})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, a := range p.Items {
|
||||
byID[a.ID] = a
|
||||
}
|
||||
}
|
||||
return inOrder(ids, byID), nil
|
||||
}
|
||||
|
|
@ -180,6 +180,9 @@ func (r *CatalogRepo) listArtists(ctx context.Context, f catalog.Filter, id int6
|
|||
if id != 0 {
|
||||
w.add("a.id = ?", id)
|
||||
}
|
||||
if f.IDs != nil {
|
||||
w.add("a.id IN (?)", bun.In(f.IDs))
|
||||
}
|
||||
if f.Query != "" {
|
||||
addSearch(&w, "a.search_key", f.Query)
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue