All checks were successful
Publier l'image Docker / publish (push) Successful in 7s
The last deferred piece from the original spec. Chosen permission model (asked, not assumed): anyone can add a track to the shared queue any time; anyone can pause/resume directly; skipping the current track needs a strict majority vote of currently connected members. No host for playback - a genuinely different shape of shared state than video's "host drives, everyone follows", which is why it's a separate service (server/src/musicQueueService.js, MusicQueueService) rather than more branches in partyManager.js/socketHandler.js's existing video-shaped logic. Server: - musicQueueService.js: owns a music party's queue/current-track/pause/ vote-skip state. Server-authoritative timing (no client is "the host" reporting position) - a wall-clock startedUtc plus the track's known duration is the only state; auto-advance is one setTimeout scheduled for exactly when that runs out, not any client reporting "it ended" (which could race across several players finishing near-simultaneously with no host to arbitrate). attachIo(io, onTrackChanged), called once at startup like PartyManager's own wiring, lets it broadcast "queueUpdated" from inside that timer's callback, which has no socket/request in scope at all. - The timer is the one new leak surface this adds, given how much this project has already had to fix real leaks - destroy(party) clears it, wired into both of partyManager.js's existing destruction paths (leave's last-member case, removeIdleParties' sweep). - Party gained mediaType: 'video'|'music' (inferred server-side from the clicked item's Emby Type - the client never has to know or say which). - Three new catalog endpoints (Artists -> Albums -> Tracks), same reasoning as the existing Shows -> Seasons -> Episodes: a real Emby endpoint per level, not generic recursive /Items guessing. - Audio streams through the *same* /master.m3u8 route as video (Emby's PlaybackInfo negotiation isn't video-specific) - the one difference is the hand-built-fallback path prefix (/Audio/ vs /Videos/), which the client tags via a mediaType=audio query hint rather than costing an extra Emby round trip to detect server-side. - Adding a track is REST (POST /api/parties/:partyId/tracks), not a socket event like voteSkip/musicPlaystate - it needs to work from the player's inline browse-and-add panel regardless of realtime-connection specifics, and MusicQueueService's own broadcast reaches everyone connected either way. Client: - player.js's renderPartyPlayer is now a small dispatcher: fetches the party once, then delegates to renderVideoPlayer or the new renderMusicPlayer (views/musicPlayer.js) based on mediaType. Can't be async despite awaiting that fetch - route()'s contract needs its cleanup function back synchronously (router.js's `typeof cleanup === 'function'` check would silently skip a Promise, reintroducing the exact leak class already fixed once) - solved with a mutable box returned immediately, filled in once the fetch resolves. - musicPlayer.js: not full-viewport/theater-mode like the video player (no image to declutter around, sidebar stays up) - which is what makes its own inline Artist -> Album -> Track browser work for "add tracks while listening" without navigating away and losing player state or threading party context through query params across three route levels. - New views/artist.js, views/album.js (library.js's music branch renders an artist grid instead of the old placeholder). tiles.js's DRILL_DOWN table generalizes the old single seriesHref special-case now that there are three drill-down targets, not two. - party.js: addTrackToQueue (REST) alongside voteSkip/setMusicPaused (socket) on the existing connectParty() connection object. Real bug found while testing, not just the mock's fault: applyMusicState used to update the queue list/vote button *after* the current-track branch, which calls loadTrack() - and loadTrack()'s hls.js setup can throw. Since JS doesn't roll back earlier statements when a later one throws but does abort everything after it, an exception there took the unrelated queue list and vote tally down with it, and on the first render escaped all the way to the dispatcher's catch, which alerts and bounces back to /home - discarding the whole view over what's really just "this one track's audio failed to load". Fixed by reordering (queue/vote/icon updates - which can't fail - before the track-loading branch, mirroring how player.js's onItemChanged already updates title/next-button before calling loadVideo) and wrapping loadTrack's hls.js setup in its own try/catch so a failure there logs and stops instead of propagating. Verified server-side directly against the real shipped modules (not reimplemented mocks): 18 checks against musicQueueService.js alone (auto -start, queueing, vote-skip majority, pause/resume elapsed-time math, a real setTimeout auto-advance, timer cleanup on destroy - instrumented setTimeout/clearTimeout counting, same technique as the earlier client -side leak tests) and 7 more through socketHandler.js + partyManager.js together (no-ops on a video party, a non-host pausing/resuming, a two-vote majority skip, the resulting broadcast really reaching the room). Client-side against the real local server with mocked fetch/Hls/ io: the full browsing chain, party creation, the dispatcher choosing the right player (and still choosing video when mediaType is absent - back -compat), now-playing/vote-tally/queue rendering and updates including a live track change, play/pause and vote-skip emitting the right events, the inline browse-and-add panel POSTing the right payload, and the crash fix re-confirmed fixed via the same broken scenario that first found it. Not verified: the real Emby round trip for any of this (Artists/albums -tracks response shapes, audio PlaybackInfo/TranscodingUrl behavior, actual playback quality) - same limit as everything else in this project tested without live Emby access. docs/architecture.md has the full writeup. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
118 lines
3.8 KiB
JavaScript
118 lines
3.8 KiB
JavaScript
// Talks ONLY to our own backend now - never directly to Emby. The backend
|
|
// holds the real Emby session (server/src/embyAuth.js); this module just
|
|
// wraps fetch calls to our own /api/* routes. See docs/architecture.md for
|
|
// why this changed from the first version (CORS, plus not wanting the
|
|
// browser to hold an Emby token at all).
|
|
|
|
async function apiFetch(path, options = {}) {
|
|
const res = await fetch(path, {
|
|
credentials: 'same-origin',
|
|
...options,
|
|
headers: { 'Content-Type': 'application/json', ...(options.headers || {}) }
|
|
});
|
|
if (!res.ok) {
|
|
const body = await res.json().catch(() => ({}));
|
|
throw new Error(body.error || `Request failed: ${res.status}`);
|
|
}
|
|
return res.json();
|
|
}
|
|
|
|
export const auth = {
|
|
userName: null,
|
|
get isLoggedIn() { return !!this.userName; }
|
|
};
|
|
|
|
/** Call once on app start to find out if our session cookie is still valid. */
|
|
export async function restoreSession() {
|
|
try {
|
|
const data = await apiFetch('/api/auth/me');
|
|
auth.userName = data.userName;
|
|
return true;
|
|
} catch (err) {
|
|
auth.userName = null;
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function login(username, password) {
|
|
const data = await apiFetch('/api/auth/login', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ username, password })
|
|
});
|
|
auth.userName = data.userName;
|
|
return data;
|
|
}
|
|
|
|
export async function logout() {
|
|
await apiFetch('/api/auth/logout', { method: 'POST' }).catch(() => {});
|
|
auth.userName = null;
|
|
}
|
|
|
|
export async function searchItems(query) {
|
|
if (!query || query.trim().length < 2) return [];
|
|
const data = await apiFetch(`/api/catalog/search?q=${encodeURIComponent(query)}`);
|
|
return data.items || [];
|
|
}
|
|
|
|
export async function getItem(itemId) {
|
|
return apiFetch(`/api/catalog/item/${itemId}`);
|
|
}
|
|
|
|
export async function getLibraries() {
|
|
const data = await apiFetch('/api/catalog/libraries');
|
|
return data.libraries || [];
|
|
}
|
|
|
|
export async function getLibraryItems(libraryId) {
|
|
const data = await apiFetch(`/api/catalog/libraries/${libraryId}/items`);
|
|
return data.items || [];
|
|
}
|
|
|
|
export async function getRecentItems(libraryId) {
|
|
const data = await apiFetch(`/api/catalog/libraries/${libraryId}/recent`);
|
|
return data.items || [];
|
|
}
|
|
|
|
export async function getSeriesSeasons(seriesId) {
|
|
const data = await apiFetch(`/api/catalog/series/${seriesId}/seasons`);
|
|
return data.seasons || [];
|
|
}
|
|
|
|
export async function getSeriesEpisodes(seriesId, seasonId) {
|
|
const data = await apiFetch(`/api/catalog/series/${seriesId}/episodes?seasonId=${encodeURIComponent(seasonId)}`);
|
|
return data.episodes || [];
|
|
}
|
|
|
|
export async function getArtists(libraryId) {
|
|
const data = await apiFetch(`/api/catalog/libraries/${libraryId}/artists`);
|
|
return data.artists || [];
|
|
}
|
|
|
|
export async function getArtistAlbums(artistId) {
|
|
const data = await apiFetch(`/api/catalog/artists/${artistId}/albums`);
|
|
return data.albums || [];
|
|
}
|
|
|
|
export async function getAlbumTracks(albumId) {
|
|
const data = await apiFetch(`/api/catalog/albums/${albumId}/tracks`);
|
|
return data.tracks || [];
|
|
}
|
|
|
|
export async function getPlaybackOptions(itemId) {
|
|
return apiFetch(`/api/catalog/item/${itemId}/playback-options`);
|
|
}
|
|
|
|
/** `options` may carry AudioStreamIndex/SubtitleStreamIndex/MaxStreamingBitrate/mediaType. */
|
|
export function streamUrl(itemId, options = {}) {
|
|
const qs = new URLSearchParams(
|
|
Object.fromEntries(Object.entries(options).filter(([, v]) => v !== '' && v != null))
|
|
).toString();
|
|
return `/api/catalog/stream/${itemId}/master.m3u8${qs ? '?' + qs : ''}`;
|
|
}
|
|
|
|
/** Same stream, tagged for a music track - see server/src/index.js's
|
|
* /master.m3u8 route for why mediaType is the one thing that matters here
|
|
* (its hand-built-fallback path is genuinely different for audio). */
|
|
export function audioStreamUrl(itemId) {
|
|
return streamUrl(itemId, { mediaType: 'audio' });
|
|
}
|