watchparty/client/js/party.js
Nicolas b6019bd211
All checks were successful
Publier l'image Docker / publish (push) Successful in 7s
Live lobby, host handoff reflected live, remove join codes, fix player scroll
Three requested changes plus one found-in-passing bug fix:

1. Home page's "watch parties en cours" is now a live Socket.IO
   subscription (connectLobby -> "lobby" room), not a one-shot fetch -
   updates the instant anything changes anywhere (create/join/leave).
   Host name + member count come from the snapshot; elapsed time ticks
   purely client-side from a createdUtc timestamp (no point pushing a
   recomputed duration every second for every viewer). home.js returns
   this subscription from its router cleanup, same leak-prevention
   pattern as the player's socket.

2. Host handoff is now live end to end, not just correct in the data
   model. PartyManager.leave already promoted another member and
   destroyed an empty party (that part predates this change) - what
   was missing was any way for an already-open follower player to find
   out it became host. applyLeave (shared by the socket leave/
   disconnect handlers and the REST leave endpoint, so this and the
   lobby broadcast only live in one place) now emits a personal
   "hostChanged" to the new host's own socket; player.js's becomeHost()
   unlocks controls live. becomeHost is written to tolerate being
   called more than once safely (addEventListener no-ops on a repeat
   identical listener; the heartbeat setInterval is explicitly guarded
   since it has no such idempotence - calling it twice would leak the
   first interval, the exact bug class the previous pass fixed).

3. No more join codes - PartyManager no longer generates or tracks
   one. The live lobby list is the only discovery mechanism now; a
   code copied out of band doesn't add anything on top of a list
   that's already always current. POST /api/parties/:partyId/join
   replaces :joinCode; the "Rejoindre avec un code" UI is gone.

Found while touching this: the home page's "Rejoindre" button used to
navigate to the player WITHOUT ever calling the join endpoint first -
it loaded fine (GET /api/parties/:id never checked membership) but the
realtime "join" was silently rejected server-side (not an actual
member), so sync never worked for anyone joining this way. Fixed to
await joinParty() before navigating, matching how the library grid's
tiles already did it.

Also: .playerWrap was width:100%/height:100vh inside .mainContent's own
padding, so the two stacked and made the page taller than the
viewport - an outer scrollbar despite the video already being full-
height. Changed to position:fixed/inset:0 so it fills the real
viewport regardless of ancestor padding.

Verified live against a real running server (see session history):
lobby subscription renders host/member-count/ticking-elapsed correctly
from a faked "parties" push (createdUtc 2:05 in the past rendered
"2:06" after ~1s more, proving the client-side tick is real, not
static); the join-then-navigate fix calls the join endpoint before
navigating; .playerWrap computes to position:fixed with all four
insets at 0.

docs/architecture.md has the full writeup.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 23:47:12 +02:00

93 lines
3.3 KiB
JavaScript

// Party REST + realtime - same origin as everything else, auth is the
// session cookie (see embyApi.js), so no headers/tokens to pass around here.
// Realtime is Socket.IO (window.io, loaded via <script> in index.html) -
// gives us automatic reconnection and, on the server side, heartbeat-based
// dead-connection detection for free (see server/src/socketHandler.js).
//
// No join codes: joining happens straight from the home page's live list
// (connectLobby below) by party id - see docs/architecture.md.
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 function createParty(itemId) {
return apiFetch('/api/parties', { method: 'POST', body: JSON.stringify({ itemId }) });
}
export function joinParty(partyId) {
return apiFetch(`/api/parties/${encodeURIComponent(partyId)}/join`, { method: 'POST' });
}
export function leaveParty(partyId) {
return apiFetch(`/api/parties/${partyId}/leave`, { method: 'POST' });
}
export function getParty(partyId) {
return apiFetch(`/api/parties/${partyId}`);
}
/**
* Live "watch parties en cours" feed for the home page. `onParties` gets
* called with the full current list on subscribe, and again every time any
* party anywhere changes (created, someone joined/left, host handed off).
* Caller MUST call .disconnect() when navigating away (see home.js's router
* cleanup) - same leak-prevention pattern as connectParty below.
*/
export function connectLobby(onParties) {
const socket = window.io();
socket.on('connect', () => socket.emit('subscribeLobby'));
socket.on('parties', onParties);
return {
disconnect() {
socket.disconnect();
}
};
}
/**
* Opens the realtime connection for a party. Returns an object the caller
* MUST eventually call .leave() on (e.g. from a router cleanup function -
* see router.js/player.js) - otherwise the socket, and whatever it's
* keeping alive via closures, never gets released.
*/
export function connectParty(partyId, { onMembers, onPlaystate, onItemChanged, onHostChanged, onError, onClose } = {}) {
const socket = window.io();
// Reconnects (Socket.IO retries automatically) re-fire "connect", so this
// also covers rejoining after a transient network drop, not just the
// first connection.
socket.on('connect', () => {
socket.emit('join', { partyId });
});
if (onMembers) socket.on('members', onMembers);
if (onPlaystate) socket.on('playstate', onPlaystate);
if (onItemChanged) socket.on('itemChanged', onItemChanged);
if (onHostChanged) socket.on('hostChanged', onHostChanged);
if (onError) socket.on('errorMessage', (msg) => onError(msg.message));
if (onClose) socket.on('disconnect', onClose);
return {
sendPlaystate(isPaused, positionTicks) {
socket.emit('playstate', { isPaused, positionTicks });
},
/** Host-only: advance the party's queue (e.g. to the next episode). */
next() {
socket.emit('next');
},
leave() {
socket.emit('leave');
socket.disconnect();
}
};
}