import { queryClient } from '#lib/query/client.js'; import { qk } from '#lib/api/queries.js'; import { user } from '#lib/auth/store.svelte.js'; // Inbound server events over SSE. The web client's OUTBOUND half (play // events) lives in player/events.svelte.ts; this is the inbound listener. // 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. 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 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 { return _systemRebuildCount; } }; function onSystemRebuilt(): void { _systemRebuildCount++; queryClient.invalidateQueries({ queryKey: qk.home() }); // Prefix match invalidates every kind ('user' | 'system' | 'all'). queryClient.invalidateQueries({ queryKey: ['playlists'] }); 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 { queryClient.invalidateQueries({ queryKey: ['notifications'] }); } // Wire once from +layout.svelte's mount. Opens the stream only while // authenticated and closes it on logout; EventSource auto-reconnects on // transient network drops. export function useServerEvents(): void { $effect(() => { if (!user.value) return; // Absent under SSR / jsdom — the listener simply no-ops there. if (typeof EventSource === 'undefined') return; 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(); }; }); }