🎧 Your Personal Streaming Service
Go airsonicmadsonicmedia-servermusicmusic-servernavidromeopensubsonicraspberry-piself-hostedstreamerstreaming-apistreaming-audiosubsonicsubsonic-server
feat(playlists): per-user starred/rating annotations (backend) (#5749)
Deluan Quintãoca27335d0671
diff --git a/db/migrations/20260714120000_add_playlist_average_rating.sql b/db/migrations/20260714120000_add_playlist_average_rating.sqlnew file mode 100644index 000000000..5db642986--- /dev/null+++ b/db/migrations/20260714120000_add_playlist_average_rating.sql@@ -0,0 +1,5 @@+-- +goose Up+ALTER TABLE playlist ADD COLUMN average_rating REAL NOT NULL DEFAULT 0;++-- +goose Down+ALTER TABLE playlist DROP COLUMN average_rating;diff --git a/model/playlist.go b/model/playlist.goindex dc549f039..262774aa7 100644--- a/model/playlist.go+++ b/model/playlist.go@@ -10,6 +10,8 @@ import ()type Playlist struct {+ Annotations `structs:"-"`+ID string `structs:"id" json:"id"`Name string `structs:"name" json:"name"`Comment string `structs:"comment" json:"comment"`@@ -121,6 +123,7 @@ type Playlists []Playlisttype PlaylistRepository interface {ResourceRepository+ AnnotatedRepositoryCountAll(options ...QueryOptions) (int64, error)Exists(id string) (bool, error)Put(pls *Playlist, cols ...string) errordiff --git a/persistence/persistence.go b/persistence/persistence.goindex 1164eb70f..93f0e3e71 100644--- a/persistence/persistence.go+++ b/persistence/persistence.go@@ -193,6 +193,7 @@ func (s *SQLStore) GC(ctx context.Context, libraryIDs ...int) error {trace(ctx, "clean album annotations", func() error { return s.Album(ctx).(*albumRepository).cleanAnnotations() }),trace(ctx, "clean artist annotations", func() error { return s.Artist(ctx).(*artistRepository).cleanAnnotations() }),trace(ctx, "clean media file annotations", func() error { return s.MediaFile(ctx).(*mediaFileRepository).cleanAnnotations() }),+ trace(ctx, "clean playlist annotations", func() error { return s.Playlist(ctx).(*playlistRepository).cleanAnnotations() }),trace(ctx, "clean media file bookmarks", func() error { return s.MediaFile(ctx).(*mediaFileRepository).cleanBookmarks() }),trace(ctx, "purge non used tags", func() error { return s.Tag(ctx).(*tagRepository).purgeUnused() }),trace(ctx, "remove orphan playlist tracks", func() error { return s.Playlist(ctx).(*playlistRepository).removeOrphans() }),diff --git a/persistence/playlist_repository.go b/persistence/playlist_repository.goindex 4152505d2..fe1f50689 100644--- a/persistence/playlist_repository.go+++ b/persistence/playlist_repository.go@@ -203,8 +203,9 @@ func (r *playlistRepository) GetPlaylists(mediaFileId string) (model.Playlists,}func (r *playlistRepository) selectPlaylist(options ...model.QueryOptions) SelectBuilder {- return r.newSelect(options...).Join("user on user.id = owner_id").+ sel := r.newSelect(options...).Join("user on user.id = owner_id").Columns(r.tableName+".*", "user.user_name as owner_name")+ return r.withAnnotation(sel, r.tableName+".id")}func (r *playlistRepository) updateTracks(id string, tracks model.MediaFiles) error {diff --git a/persistence/playlist_repository_test.go b/persistence/playlist_repository_test.goindex cfabd0983..c5b16b88f 100644--- a/persistence/playlist_repository_test.go+++ b/persistence/playlist_repository_test.go@@ -1,11 +1,14 @@package persistenceimport (+ "slices"+"github.com/navidrome/navidrome/log""github.com/navidrome/navidrome/model""github.com/navidrome/navidrome/model/request". "github.com/onsi/ginkgo/v2". "github.com/onsi/gomega"+ "github.com/pocketbase/dbx")var _ = Describe("PlaylistRepository", func() {@@ -71,6 +74,98 @@ var _ = Describe("PlaylistRepository", func() {})})+ Describe("Annotations", func() {+ var plsID string++ BeforeEach(func() {+ pls := model.Playlist{Name: "Annotated", OwnerID: "userid"}+ Expect(repo.Put(&pls)).To(Succeed())+ plsID = pls.ID+ })++ countAnnotations := func() int {+ var count int+ Expect(GetDBXBuilder().NewQuery(+ "SELECT count(*) FROM annotation WHERE item_type = 'playlist' AND item_id = {:id}").+ Bind(dbx.Params{"id": plsID}).Row(&count)).To(Succeed())+ return count+ }++ It("stores and reads back starred", func() {+ Expect(repo.SetStar(true, plsID)).To(Succeed())++ p, err := repo.Get(plsID)+ Expect(err).ToNot(HaveOccurred())+ Expect(p.Starred).To(BeTrue())+ Expect(p.StarredAt).ToNot(BeNil())+ })++ It("stores and reads back rating and average_rating", func() {+ Expect(repo.SetRating(4, plsID)).To(Succeed())++ p, err := repo.Get(plsID)+ Expect(err).ToNot(HaveOccurred())+ Expect(p.Rating).To(Equal(4))+ Expect(p.RatedAt).ToNot(BeNil())+ Expect(p.AverageRating).To(Equal(4.0))+ })++ It("keeps annotations isolated per user", func() {+ Expect(repo.SetStar(true, plsID)).To(Succeed())++ otherCtx := request.WithUser(log.NewContext(GinkgoT().Context()),+ model.User{ID: "otheruser", UserName: "otheruser", IsAdmin: true})+ otherRepo := NewPlaylistRepository(otherCtx, GetDBXBuilder())++ p, err := otherRepo.Get(plsID)+ Expect(err).ToNot(HaveOccurred())+ Expect(p.Starred).To(BeFalse())+ })++ It("reads starred back through GetAll", func() {+ Expect(repo.SetStar(true, plsID)).To(Succeed())++ all, err := repo.GetAll()+ Expect(err).ToNot(HaveOccurred())+ idx := slices.IndexFunc(all, func(p model.Playlist) bool { return p.ID == plsID })+ Expect(idx).To(BeNumerically(">=", 0))+ Expect(all[idx].Starred).To(BeTrue())+ })++ It("does not leak an annotation row of another item_type sharing the playlist id", func() {+ // Older builds (and the star fallthrough) can leave a media_file-typed row+ // under a playlist id; the item_type-scoped join must not surface or dupe it.+ _, err := GetDBXBuilder().NewQuery(+ "INSERT INTO annotation (user_id, item_id, item_type, starred) VALUES ({:uid}, {:id}, 'media_file', 1)").+ Bind(dbx.Params{"uid": "userid", "id": plsID}).Execute()+ Expect(err).ToNot(HaveOccurred())++ p, err := repo.Get(plsID)+ Expect(err).ToNot(HaveOccurred())+ Expect(p.Starred).To(BeFalse())++ all, err := repo.GetAll()+ Expect(err).ToNot(HaveOccurred())+ matches := 0+ for _, pl := range all {+ if pl.ID == plsID {+ matches+++ }+ }+ Expect(matches).To(Equal(1))+ })++ It("relies on the annotation sweep, not Delete, to clean up annotations", func() {+ Expect(repo.SetStar(true, plsID)).To(Succeed())++ Expect(repo.Delete(plsID)).To(Succeed())+ Expect(countAnnotations()).To(Equal(1))++ Expect(repo.(*playlistRepository).cleanAnnotations()).To(Succeed())+ Expect(countAnnotations()).To(Equal(0))+ })+ })+It("Put/Exists/Delete", func() {By("saves the playlist to the DB")newPls := model.Playlist{Name: "Great!", OwnerID: "userid"}diff --git a/persistence/sql_annotations.go b/persistence/sql_annotations.goindex 78b7938a1..46ad6a0de 100644--- a/persistence/sql_annotations.go+++ b/persistence/sql_annotations.go@@ -67,7 +67,8 @@ func (r sqlRepository) withAnnotation(query SelectBuilder, idField string) Selecquery = query.LeftJoin("annotation on ("+"annotation.item_id = "+idField+- " AND annotation.user_id = '"+userID+"')").+ " AND annotation.item_type = ?"++ " AND annotation.user_id = ?)", r.tableName, userID).Columns("coalesce(starred, 0) as starred","coalesce(rating, 0) as rating",diff --git a/server/subsonic/media_annotation.go b/server/subsonic/media_annotation.goindex e8b0278c1..27170c11b 100644--- a/server/subsonic/media_annotation.go+++ b/server/subsonic/media_annotation.go@@ -2,6 +2,7 @@ package subsonicimport ("context"+ "errors""fmt""math""net/http"@@ -52,6 +53,9 @@ func (api *Router) setRating(ctx context.Context, id string, rating int) error {case *model.Album:repo = api.ds.Album(ctx)resource = "album"+ case *model.Playlist:+ repo = api.ds.Playlist(ctx)+ resource = "playlist"default:repo = api.ds.MediaFile(ctx)resource = "song"@@ -104,48 +108,50 @@ func (api *Router) Unstar(r *http.Request) (*responses.Subsonic, error) {}func (api *Router) setStar(ctx context.Context, star bool, ids ...string) error {- if len(ids) == 0 {- return nil- }- log.Debug(ctx, "Changing starred", "ids", ids, "starred", star)if len(ids) == 0 {log.Warn(ctx, "Cannot star/unstar an empty list of ids")return nil}- event := &events.RefreshResource{}+ log.Debug(ctx, "Changing starred", "ids", ids, "starred", star)err := api.ds.WithTxImmediate(func(tx model.DataStore) error {+ event := &events.RefreshResource{}+ changed := falsefor _, id := range ids {- exist, err := tx.Album(ctx).Exists(id)+ var repo model.AnnotatedRepository+ var resource string+ entity, err := model.GetEntityByID(ctx, tx, id)if err != nil {- return err- }- if exist {- err = tx.Album(ctx).SetStar(star, id)- if err != nil {+ if !errors.Is(err, model.ErrNotFound) {return err}- event = event.With("album", id)+ log.Warn(ctx, "Cannot star/unstar unknown id, skipping", "id", id)continue}- exist, err = tx.Artist(ctx).Exists(id)- if err != nil {- return err- }- if exist {- err = tx.Artist(ctx).SetStar(star, id)- if err != nil {- return err- }- event = event.With("artist", id)- continue+ switch entity.(type) {+ case *model.Artist:+ repo = tx.Artist(ctx)+ resource = "artist"+ case *model.Album:+ repo = tx.Album(ctx)+ resource = "album"+ case *model.Playlist:+ repo = tx.Playlist(ctx)+ resource = "playlist"+ default:+ repo = tx.MediaFile(ctx)+ resource = "song"}- err = tx.MediaFile(ctx).SetStar(star, id)- if err != nil {+ if err := repo.SetStar(star, id); err != nil {return err}- event = event.With("song", id)+ event = event.With(resource, id)+ changed = true+ }+ // Skip the broadcast when nothing changed: an empty RefreshResource+ // serializes as a "{*:*}" wildcard, forcing every client to refresh.+ if changed {+ api.broker.SendMessage(ctx, event)}- api.broker.SendMessage(ctx, event)return nil})if err != nil {diff --git a/server/subsonic/media_annotation_test.go b/server/subsonic/media_annotation_test.goindex 487335d1a..1b16dfc68 100644--- a/server/subsonic/media_annotation_test.go+++ b/server/subsonic/media_annotation_test.go@@ -185,6 +185,64 @@ var _ = Describe("MediaAnnotationController", func() {Expect(playTracker.ReportedPlayback[0].ClientName).To(BeEmpty())})})++ Describe("Star/Unstar playlists", func() {+ var plRepo *tests.MockPlaylistRepo++ BeforeEach(func() {+ plRepo = tests.CreateMockPlaylistRepo()+ plRepo.SetData(model.Playlists{{ID: "pl-1", Name: "My Playlist", OwnerID: "u1"}})+ ds.(*tests.MockDataStore).MockedPlaylist = plRepo+ })++ It("stars a playlist by dispatching to the Playlist repo", func() {+ r := newGetRequest("id=pl-1")++ _, err := router.Star(r)++ Expect(err).ToNot(HaveOccurred())+ Expect(plRepo.Starred).To(HaveKeyWithValue("pl-1", true))+ })++ It("unstars a playlist by dispatching to the Playlist repo", func() {+ r := newGetRequest("id=pl-1")++ _, err := router.Unstar(r)++ Expect(err).ToNot(HaveOccurred())+ Expect(plRepo.Starred).To(HaveKeyWithValue("pl-1", false))+ })+ })++ Describe("SetRating playlists", func() {+ var plRepo *tests.MockPlaylistRepo++ BeforeEach(func() {+ plRepo = tests.CreateMockPlaylistRepo()+ plRepo.SetData(model.Playlists{{ID: "pl-1", Name: "My Playlist", OwnerID: "u1"}})+ ds.(*tests.MockDataStore).MockedPlaylist = plRepo+ })++ It("rates a playlist by dispatching to the Playlist repo", func() {+ r := newGetRequest("id=pl-1", "rating=4")++ _, err := router.SetRating(r)++ Expect(err).ToNot(HaveOccurred())+ Expect(plRepo.Ratings).To(HaveKeyWithValue("pl-1", 4))+ })+ })++ Describe("Star with an unresolvable id", func() {+ It("skips the id without broadcasting an empty (wildcard) refresh", func() {+ r := newGetRequest("id=does-not-exist")++ _, err := router.Star(r)++ Expect(err).ToNot(HaveOccurred())+ Expect(eventBroker.Events).To(BeEmpty())+ })+ })})type fakePlayTracker struct {diff --git a/server/subsonic/playlists_test.go b/server/subsonic/playlists_test.goindex 1d5f6a70a..697dd5852 100644--- a/server/subsonic/playlists_test.go+++ b/server/subsonic/playlists_test.go@@ -2,6 +2,7 @@ package subsonicimport ("context"+ "encoding/json""time""github.com/navidrome/navidrome/conf"@@ -248,6 +249,27 @@ var _ = Describe("buildPlaylist", func() {})})})++ Describe("annotation leakage", func() {+ It("does not serialize starred/rating even when the model carries them", func() {+ p := model.Playlist{ID: "pl-1", Name: "My Playlist"}+ p.Starred = true+ p.Rating = 5++ resp := router.buildPlaylist(ctx, p)++ data, err := json.Marshal(resp)+ Expect(err).ToNot(HaveOccurred())+ var fields map[string]any+ Expect(json.Unmarshal(data, &fields)).To(Succeed())+ Expect(fields).ToNot(HaveKey("starred"))+ Expect(fields).ToNot(HaveKey("starredAt"))+ Expect(fields).ToNot(HaveKey("rating"))+ Expect(fields).ToNot(HaveKey("userRating"))+ Expect(fields).ToNot(HaveKey("averageRating"))+ Expect(fields).ToNot(HaveKey("playCount"))+ })+ })})var _ = Describe("UpdatePlaylist", func() {diff --git a/tests/mock_playlist_repo.go b/tests/mock_playlist_repo.goindex 9b38ea5b5..b7df5361f 100644--- a/tests/mock_playlist_repo.go+++ b/tests/mock_playlist_repo.go@@ -2,6 +2,7 @@ package testsimport ("errors"+ "time""github.com/deluan/rest""github.com/navidrome/navidrome/model"@@ -19,8 +20,11 @@ type MockPlaylistRepo struct {model.PlaylistRepositoryData map[string]*model.Playlist // keyed by IDPathMap map[string]*model.Playlist // keyed by path+ All model.PlaylistsLast *model.PlaylistDeleted []string+ Starred map[string]bool // itemID -> starred+ Ratings map[string]int // itemID -> ratingErr boolTracksRepo model.PlaylistTrackRepository}@@ -29,6 +33,14 @@ func (m *MockPlaylistRepo) SetError(err bool) {m.Err = err}+func (m *MockPlaylistRepo) SetData(pls model.Playlists) {+ m.Data = make(map[string]*model.Playlist, len(pls))+ m.All = pls+ for i, p := range m.All {+ m.Data[p.ID] = &m.All[i]+ }+}+func (m *MockPlaylistRepo) Get(id string) (*model.Playlist, error) {if m.Err {return nil, errors.New("error")@@ -45,6 +57,13 @@ func (m *MockPlaylistRepo) GetWithTracks(id string, _, _ bool) (*model.Playlist,return m.Get(id)}+func (m *MockPlaylistRepo) GetAll(_ ...model.QueryOptions) (model.Playlists, error) {+ if m.Err {+ return nil, errors.New("error")+ }+ return m.All, nil+}+func (m *MockPlaylistRepo) Put(pls *model.Playlist, _ ...string) error {if m.Err {return errors.New("error")@@ -79,6 +98,44 @@ func (m *MockPlaylistRepo) Delete(id string) error {return nil}+func (m *MockPlaylistRepo) SetStar(starred bool, ids ...string) error {+ if m.Err {+ return errors.New("error")+ }+ if m.Starred == nil {+ m.Starred = map[string]bool{}+ }+ for _, id := range ids {+ m.Starred[id] = starred+ }+ return nil+}++func (m *MockPlaylistRepo) SetRating(rating int, id string) error {+ if m.Err {+ return errors.New("error")+ }+ if m.Ratings == nil {+ m.Ratings = map[string]int{}+ }+ m.Ratings[id] = rating+ return nil+}++func (m *MockPlaylistRepo) IncPlayCount(string, time.Time) error {+ if m.Err {+ return errors.New("error")+ }+ return nil+}++func (m *MockPlaylistRepo) ReassignAnnotation(string, string) error {+ if m.Err {+ return errors.New("error")+ }+ return nil+}+func (m *MockPlaylistRepo) Tracks(_ string, _ bool) model.PlaylistTrackRepository {return m.TracksRepo}