fix(events): a like made in a Subsonic app reaches the other apps, and an open web tab follows likes and playlist changes (#8077)

The native like endpoints announce a like on the event bus; Subsonic star
and unstar announced nothing, so the web and Android apps showed a stale
heart until they refetched. Subsonic now publishes the same events, through
one shape both surfaces build (eventbus.LikeChanged, eventbus.LedBy).

The web listened only for the nightly rebuild and notifications, so an open
tab ignored likes and playlist changes made in another tab, on Android or
in a Subsonic app. It now refreshes its liked views on any like event and
its playlists (and the open one) on playlist.created/updated/deleted/
tracks_changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 00:02:12 -05:00
co-authored by Claude Opus 5.5
parent 528ea9df0c
commit 8ba1d109c3
11 changed files with 204 additions and 51 deletions
+1 -26
View File
@@ -18,32 +18,7 @@ func (h *handlers) publishLikeEvent(userID, entityID pgtype.UUID, entityType str
if h.eventbus == nil {
return
}
kind := "track.liked"
if !liked {
kind = "track.unliked"
}
if entityType == "album" {
if liked {
kind = "album.liked"
} else {
kind = "album.unliked"
}
}
if entityType == "artist" {
if liked {
kind = "artist.liked"
} else {
kind = "artist.unliked"
}
}
h.eventbus.Publish(eventbus.Event{
Kind: kind,
UserID: uuidToString(userID),
Data: map[string]any{
"entity_type": entityType,
"entity_id": uuidToString(entityID),
},
})
h.eventbus.Publish(eventbus.LikeChanged(uuidToString(userID), entityType, uuidToString(entityID), liked))
}
// publishQuarantineEvent broadcasts a quarantine action. User-side
+3 -14
View File
@@ -10,6 +10,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
)
@@ -49,24 +50,12 @@ func (h *handlers) handleLikeTrack(w http.ResponseWriter, r *http.Request) {
}
// The like is on the song: every copy it reached changes on
// the client too.
for _, t := range withTrack(id, liked) {
for _, t := range eventbus.LedBy(id, liked) {
h.publishLikeEvent(user.ID, t, "track", true)
}
w.WriteHeader(http.StatusNoContent)
}
// withTrack is the tracks a like or unlike changed, led by the one asked for,
// which is reported even when it was already in that state.
func withTrack(id pgtype.UUID, changed []pgtype.UUID) []pgtype.UUID {
out := []pgtype.UUID{id}
for _, t := range changed {
if t != id {
out = append(out, t)
}
}
return out
}
func (h *handlers) handleUnlikeTrack(w http.ResponseWriter, r *http.Request) {
user, ok := requireUser(w, r)
if !ok {
@@ -87,7 +76,7 @@ func (h *handlers) handleUnlikeTrack(w http.ResponseWriter, r *http.Request) {
h.logger.Error("api: soft-delete contextual_likes", "err", err)
// Don't fail the response — soft-delete is best-effort.
}
for _, t := range withTrack(id, unliked) {
for _, t := range eventbus.LedBy(id, unliked) {
h.publishLikeEvent(user.ID, t, "track", false)
}
w.WriteHeader(http.StatusNoContent)
+33
View File
@@ -118,3 +118,36 @@ func (b *Bus) SubscriberCount() int {
defer b.mu.RUnlock()
return len(b.subscribers)
}
// LikeChanged is the event every surface publishes when a like changes, so
// the web and Android apps hear about a like made anywhere, a Subsonic app
// included. entityType is "track", "album" or "artist"; the kind is
// "<entityType>.liked" or "<entityType>.unliked".
func LikeChanged(userID, entityType, entityID string, liked bool) Event {
action := "liked"
if !liked {
action = "unliked"
}
return Event{
Kind: entityType + "." + action,
UserID: userID,
Data: map[string]any{
"entity_type": entityType,
"entity_id": entityID,
},
}
}
// LedBy is the entities a like or unlike reports: every one it changed, led
// by the one asked for, which is reported even when it was already in that
// state (so the asking client always hears back). A like is on the song, so
// it can change several copies at once.
func LedBy[T comparable](asked T, changed []T) []T {
out := []T{asked}
for _, c := range changed {
if c != asked {
out = append(out, c)
}
}
return out
}
+1 -1
View File
@@ -234,7 +234,7 @@ func (s *Server) Router() http.Handler {
return started, err
}
}
subsonic.Mount(r, s.Pool, s.Logger, s.SubsonicCfg, writer, netSettings.Hops, subsonicPicker, playlistsSvc, subsonicScan)
subsonic.Mount(r, s.Pool, s.Logger, s.SubsonicCfg, writer, bus, netSettings.Hops, subsonicPicker, playlistsSvc, subsonicScan)
}
spa := web.Handler(s.BrandingCfg)
+1 -1
View File
@@ -19,7 +19,7 @@ import (
// against it here never reach the database.
func mountedRest() http.Handler {
r := chi.NewRouter()
Mount(r, nil, slog.New(slog.NewTextHandler(io.Discard, nil)), Config{}, nil, func() int { return 0 }, nil, nil, nil)
Mount(r, nil, slog.New(slog.NewTextHandler(io.Discard, nil)), Config{}, nil, nil, func() int { return 0 }, nil, nil, nil)
return r
}
+26 -3
View File
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
)
@@ -49,18 +50,21 @@ func (m *mediaHandlers) handleStar(w http.ResponseWriter, r *http.Request) {
if slices.Contains(liked, trackID) {
_ = playevents.CaptureContextualLikeIfPlaying(r.Context(), q, user.ID, trackID, m.logger)
}
m.publishLike(user.ID, "track", true, eventbus.LedBy(trackID, liked)...)
}
if albumID.Valid {
if err := q.LikeAlbum(r.Context(), dbq.LikeAlbumParams{UserID: user.ID, AlbumID: albumID}); err != nil {
WriteFail(w, r, ErrGeneric, "Could not star album")
return
}
m.publishLike(user.ID, "album", true, albumID)
}
if artistID.Valid {
if err := q.LikeArtist(r.Context(), dbq.LikeArtistParams{UserID: user.ID, ArtistID: artistID}); err != nil {
WriteFail(w, r, ErrGeneric, "Could not star artist")
return
}
m.publishLike(user.ID, "artist", true, artistID)
}
Write(w, r, struct{ Envelope }{Envelope: NewEnvelope("ok")})
}
@@ -76,14 +80,21 @@ func (m *mediaHandlers) handleUnstar(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
q := dbq.New(m.pool)
if t, ok := parseUUID(params.Get("id")); ok {
_, _ = q.UnlikeTrack(r.Context(), dbq.UnlikeTrackParams{UserID: user.ID, TrackID: t})
unliked, err := q.UnlikeTrack(r.Context(), dbq.UnlikeTrackParams{UserID: user.ID, TrackID: t})
_ = playevents.SoftDeleteContextualLikes(r.Context(), q, user.ID, t)
if err == nil {
m.publishLike(user.ID, "track", false, eventbus.LedBy(t, unliked)...)
}
}
if a, ok := parseUUID(params.Get("albumId")); ok {
_ = q.UnlikeAlbum(r.Context(), dbq.UnlikeAlbumParams{UserID: user.ID, AlbumID: a})
if q.UnlikeAlbum(r.Context(), dbq.UnlikeAlbumParams{UserID: user.ID, AlbumID: a}) == nil {
m.publishLike(user.ID, "album", false, a)
}
}
if a, ok := parseUUID(params.Get("artistId")); ok {
_ = q.UnlikeArtist(r.Context(), dbq.UnlikeArtistParams{UserID: user.ID, ArtistID: a})
if q.UnlikeArtist(r.Context(), dbq.UnlikeArtistParams{UserID: user.ID, ArtistID: a}) == nil {
m.publishLike(user.ID, "artist", false, a)
}
}
Write(w, r, struct{ Envelope }{Envelope: NewEnvelope("ok")})
}
@@ -257,3 +268,15 @@ func (m *mediaHandlers) handleSetRating(w http.ResponseWriter, r *http.Request)
}
Write(w, r, NewEnvelope("ok"))
}
// publishLike tells the user's web and Android apps that a star changed
// here, with the same events the native like endpoints send, so an open
// tab's hearts and Liked list follow a like made in a Subsonic app.
func (m *mediaHandlers) publishLike(userID pgtype.UUID, entityType string, liked bool, ids ...pgtype.UUID) {
if m.bus == nil {
return
}
for _, id := range ids {
m.bus.Publish(eventbus.LikeChanged(userID.String(), entityType, id.String(), liked))
}
}
+26
View File
@@ -15,6 +15,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
)
@@ -322,3 +323,28 @@ func TestHandleGetStarred2_LeavesOutMissingAndQuarantinedSongs(t *testing.T) {
t.Fatalf("the web's liked list has %d rows (err %v), want all 3", len(all), err)
}
}
// A star made in a Subsonic app is announced as the native like endpoint
// announces one, so an open web tab or the Android app follows it.
func TestHandleStar_TellsTheOtherApps(t *testing.T) {
pool, user, track, _, _ := testStarPool(t)
m := newStarHandlers(pool)
m.bus = eventbus.New()
events, cancel := m.bus.Subscribe(8)
defer cancel()
req := httptest.NewRequest(http.MethodGet, "/rest/star?id="+uuidToID(track.ID), nil)
w := httptest.NewRecorder()
m.handleStar(w, req.WithContext(context.WithValue(req.Context(), userCtxKey, user)))
if w.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
}
select {
case e := <-events:
if e.Kind != "track.liked" || e.UserID != user.ID.String() || e.Data["entity_id"] != track.ID.String() {
t.Fatalf("event = %+v, want track.liked for the starred track", e)
}
case <-time.After(time.Second):
t.Fatal("no event after a star")
}
}
+4
View File
@@ -18,6 +18,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
)
@@ -31,6 +32,9 @@ type mediaHandlers struct {
// recall credits a scrobble to the daily mix the app last opened
// (see mixRecall); nil credits nothing.
recall *mixRecall
// bus tells the web and Android apps about a star or unstar made here;
// nil (tests) tells no one.
bus *eventbus.Bus
}
func newMediaHandlers(pool *pgxpool.Pool, events *playevents.Writer, logger *slog.Logger) *mediaHandlers {
+6 -1
View File
@@ -14,6 +14,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
"git.fabledsword.com/bvandeusen/minstrel/internal/recommendation"
@@ -34,11 +35,15 @@ import (
//
// startScan starts a library scan for an admin's startScan; nil leaves the
// method answering that scanning is not available.
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, cfg Config, events *playevents.Writer, hops func() int, picker *recommendation.Picker, lists *playlists.Service, startScan StartScan) {
//
// bus carries a star or unstar made here to the web and Android apps, as
// the native like endpoints do; nil tells no one.
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, cfg Config, events *playevents.Writer, bus *eventbus.Bus, hops func() int, picker *recommendation.Picker, lists *playlists.Service, startScan StartScan) {
b := &browseHandlers{pool: pool}
recall := newMixRecall()
m := newMediaHandlers(pool, events, logger)
m.recall = recall
m.bus = bus
u := &userHandlers{lookup: dbq.New(pool).GetUserByUsername, list: dbq.New(pool).ListUsers}
sc := &scanHandlers{pool: pool, start: startScan}
p := &pickHandlers{pool: pool, picker: picker, playlists: lists, logger: logger, recall: recall}