diff --git a/internal/api/events_publish.go b/internal/api/events_publish.go index 182af2cd..e751e6d4 100644 --- a/internal/api/events_publish.go +++ b/internal/api/events_publish.go @@ -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 diff --git a/internal/api/likes.go b/internal/api/likes.go index 30834886..da03bcb4 100644 --- a/internal/api/likes.go +++ b/internal/api/likes.go @@ -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) diff --git a/internal/eventbus/eventbus.go b/internal/eventbus/eventbus.go index 2b9b01a8..fb133dad 100644 --- a/internal/eventbus/eventbus.go +++ b/internal/eventbus/eventbus.go @@ -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 +// ".liked" or ".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 +} diff --git a/internal/server/server.go b/internal/server/server.go index 0530eead..6a219f81 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -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) diff --git a/internal/subsonic/opensubsonic_test.go b/internal/subsonic/opensubsonic_test.go index e87f28b6..444afbd2 100644 --- a/internal/subsonic/opensubsonic_test.go +++ b/internal/subsonic/opensubsonic_test.go @@ -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 } diff --git a/internal/subsonic/star.go b/internal/subsonic/star.go index 4b7a46b7..3e6c6c6e 100644 --- a/internal/subsonic/star.go +++ b/internal/subsonic/star.go @@ -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)) + } +} diff --git a/internal/subsonic/star_test.go b/internal/subsonic/star_test.go index b994a331..434b7837 100644 --- a/internal/subsonic/star_test.go +++ b/internal/subsonic/star_test.go @@ -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") + } +} diff --git a/internal/subsonic/stream.go b/internal/subsonic/stream.go index 05af691d..d8eac3ed 100644 --- a/internal/subsonic/stream.go +++ b/internal/subsonic/stream.go @@ -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 { diff --git a/internal/subsonic/subsonic.go b/internal/subsonic/subsonic.go index c4fa39c1..e9ab61e1 100644 --- a/internal/subsonic/subsonic.go +++ b/internal/subsonic/subsonic.go @@ -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} diff --git a/web/src/lib/serverEvents.svelte.test.ts b/web/src/lib/serverEvents.svelte.test.ts new file mode 100644 index 00000000..668409ae --- /dev/null +++ b/web/src/lib/serverEvents.svelte.test.ts @@ -0,0 +1,47 @@ +import { afterEach, expect, test, vi } from 'vitest'; +import { flushSync } from 'svelte'; + +vi.mock('#lib/auth/store.svelte.js', () => ({ user: { value: { id: 'u1' } } })); +vi.mock('#lib/query/client.js', () => ({ queryClient: { invalidateQueries: vi.fn() } })); + +import { useServerEvents } from './serverEvents.svelte.js'; +import { queryClient } from '#lib/query/client.js'; +import { qk } from '#lib/api/queries.js'; + +// Stands in for the browser's EventSource: events are dispatched by hand. +class FakeEventSource extends EventTarget { + static last: FakeEventSource; + constructor(public url: string) { + super(); + FakeEventSource.last = this; + } + close(): void {} +} + +function frame(kind: string, data: Record): MessageEvent { + return new MessageEvent(kind, { data: JSON.stringify({ kind, data }) }); +} + +afterEach(() => { + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +// A like or a playlist change made elsewhere (another tab, the Android app, +// a Subsonic app) refreshes what an open tab shows. +test('like and playlist events refresh the views that show them', () => { + vi.stubGlobal('EventSource', FakeEventSource); + const stop = $effect.root(() => useServerEvents()); + flushSync(); + + FakeEventSource.last.dispatchEvent(frame('track.liked', { entity_type: 'track', entity_id: 't1' })); + expect(queryClient.invalidateQueries).toHaveBeenCalledWith({ queryKey: qk.likedIds() }); + expect(queryClient.invalidateQueries).toHaveBeenCalledWith({ queryKey: qk.likedTracks() }); + + vi.mocked(queryClient.invalidateQueries).mockClear(); + FakeEventSource.last.dispatchEvent(frame('playlist.tracks_changed', { playlist_id: 'p1' })); + expect(queryClient.invalidateQueries).toHaveBeenCalledWith({ queryKey: ['playlists'] }); + expect(queryClient.invalidateQueries).toHaveBeenCalledWith({ queryKey: qk.playlist('p1') }); + + stop(); +}); diff --git a/web/src/lib/serverEvents.svelte.ts b/web/src/lib/serverEvents.svelte.ts index b64f6d7a..a3323018 100644 --- a/web/src/lib/serverEvents.svelte.ts +++ b/web/src/lib/serverEvents.svelte.ts @@ -7,16 +7,18 @@ import { user } from '#lib/auth/store.svelte.js'; // It reacts to `playlist.system_rebuilt` — the // daily 03:00 rebuild or a manual refresh — by invalidating the home + // system-playlist query caches so a tab left open across the rebuild stops -// serving yesterday's snapshot. Active playback +// serving yesterday's snapshot. It also follows likes and playlist changes +// made anywhere else (another tab, the Android app, a Subsonic app), so an +// open tab's hearts, Liked lists and playlists don't wait for a navigation. Active playback // self-heals separately on the failure path (store.handleLoadFailure); we // deliberately do NOT yank a playing queue here — that would interrupt a // mid-song listen to restart the new mix at track 0. // Monotonic rebuild counter. Bumped on every playlist.system_rebuilt. -// An open system-playlist DETAIL page can't be invalidated in place (its id -// rotates on rebuild — a refetch would 404), so instead it watches this -// counter and offers a "this mix was refreshed → Refresh" affordance that -// re-resolves the variant to the new playlist. +// An open system-playlist DETAIL page watches this counter and offers a +// "this mix was refreshed → Refresh" affordance that re-resolves the +// variant, rather than swapping the songs under someone reading the list +// (and a mix the rebuild retired has no id left to refetch). let _systemRebuildCount = $state(0); export const systemRebuilt = { get count(): number { @@ -32,6 +34,51 @@ function onSystemRebuilt(): void { queryClient.invalidateQueries({ queryKey: qk.systemPlaylistsStatus() }); } +// The events a like or unlike sends, for a track, album or artist. +const LIKE_EVENTS = [ + 'track.liked', + 'track.unliked', + 'album.liked', + 'album.unliked', + 'artist.liked', + 'artist.unliked' +] as const; + +// A like changed somewhere. Every liked view refetches: a track like changes +// every copy of the song, so patching one id in place would miss the rest. +function onLikeChanged(): void { + for (const queryKey of [qk.likedIds(), qk.likedTracks(), qk.likedAlbums(), qk.likedArtists()]) { + queryClient.invalidateQueries({ queryKey }); + } +} + +// The events a change to a person's own playlist sends. +const PLAYLIST_EVENTS = [ + 'playlist.created', + 'playlist.updated', + 'playlist.deleted', + 'playlist.tracks_changed' +] as const; + +// playlistIdOf reads data.playlist_id from an event frame, or '' when the +// frame carries none or isn't JSON. +export function playlistIdOf(e: Event): string { + try { + const id = JSON.parse((e as MessageEvent).data)?.data?.playlist_id; + return typeof id === 'string' ? id : ''; + } catch { + return ''; + } +} + +// A playlist changed somewhere: the lists refetch, and so does the one +// playlist if it's open or cached. +function onPlaylistChanged(e: Event): void { + queryClient.invalidateQueries({ queryKey: ['playlists'] }); + const id = playlistIdOf(e); + if (id) queryClient.invalidateQueries({ queryKey: qk.playlist(id) }); +} + // A new notification for this user. The frame carries no content — it // is a nudge — so the inbox and badge refetch rather than trusting a payload. function onNotificationCreated(): void { @@ -49,9 +96,13 @@ export function useServerEvents(): void { const es = new EventSource('/api/events/stream'); es.addEventListener('playlist.system_rebuilt', onSystemRebuilt); es.addEventListener('notification.created', onNotificationCreated); + for (const kind of LIKE_EVENTS) es.addEventListener(kind, onLikeChanged); + for (const kind of PLAYLIST_EVENTS) es.addEventListener(kind, onPlaylistChanged); return () => { es.removeEventListener('playlist.system_rebuilt', onSystemRebuilt); es.removeEventListener('notification.created', onNotificationCreated); + for (const kind of LIKE_EVENTS) es.removeEventListener(kind, onLikeChanged); + for (const kind of PLAYLIST_EVENTS) es.removeEventListener(kind, onPlaylistChanged); es.close(); }; });