All checks were successful
Publier l'image Docker / publish (push) Successful in 10s
Requested: Socket.IO instead of raw WebSockets, and explicit attention
to memory leaks. Auditing for the second turned up two real, concrete
leaks, independent of the transport library:
1. Server-side: a raw `ws` server has no idea a client is gone unless
it gets a proper close frame - a sleeping laptop, a network drop, a
killed tab never fire 'close', so the PartyMember's socket
reference (and everything it closes over) sat in memory forever,
and the party was never cleaned up by anything else either
(removeIdleParties only looks at lastActivityUtc). Socket.IO's
built-in heartbeat (pingInterval/pingTimeout) detects and closes
these out on its own - a real, not just cosmetic, reason to prefer
it here.
2. Client-side: router.js only ever did currentRoot.innerHTML = ''
between routes, destroying DOM but never telling the outgoing
view's JS to stop. Leaving the player any way other than its own
"Quitter" button (a sidebar link, browser back) left the 3s
heartbeat setInterval, the realtime connection, and the hls.js
instance all running against a detached <video> indefinitely, for
as long as the tab stayed open.
Fixes:
- server/src/socketHandler.js replaces wsHandler.js: same protocol
(see its own top comment), over Socket.IO. Rooms (socket.join/
io.to) replace manually iterating party.members to broadcast.
Error event renamed to "errorMessage" - Socket.IO reserves "error".
- server/src/index.js: socket.io server instead of a raw
WebSocketServer, same-origin (no CORS config needed).
- client/js/party.js: socket.io-client (window.io, loaded via
<script> in index.html) instead of hand-rolled WebSocket + JSON
framing - also gets automatic reconnection for free.
- router.js: route() handlers may now return a cleanup function;
render() calls whatever the previous view returned before switching
to the next route, regardless of how navigation happened.
- player.js returns a cleanup that clears the heartbeat, destroys
hls, disconnects the socket, and removes its document-level click
listener (now named, not inline-anonymous, specifically so it CAN
be removed - an anonymous one added fresh per visit would itself
have been a slow leak even with everything else fixed). The
"Quitter" button is now just navigate('/home') - cleanup runs the
same way regardless of how you leave.
Verified for real (see session history): a real Socket.IO client
connected to a really-running local server end to end. Then, with
document.addEventListener/removeEventListener and setInterval/
clearInterval instrumented, drove the router through repeated "join a
party, then navigate away without clicking Quitter" cycles - adds and
removes matched exactly every time (3/3 listeners over three cycles,
2/2 intervals over two), nothing left pending.
docs/architecture.md has the full writeup under "Realtime transport:
Socket.IO, and two real memory leaks".
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
270 lines
10 KiB
JavaScript
270 lines
10 KiB
JavaScript
import { streamUrl, getPlaybackOptions } from '../embyApi.js';
|
|
import { getParty, leaveParty, connectParty } from '../party.js';
|
|
import { navigate } from '../router.js';
|
|
import { escapeHtml } from '../tiles.js';
|
|
|
|
const TICKS_PER_SECOND = 10000000; // Emby/.NET convention: 1 tick = 100ns
|
|
const DRIFT_TOLERANCE_SECONDS = 1.5;
|
|
|
|
// "Quality" is really "max transcoding bitrate", the same simplification
|
|
// Emby's/Jellyfin's own web clients use - not true adaptive-bitrate
|
|
// switching. See docs/architecture.md.
|
|
const QUALITY_PRESETS = [
|
|
{ label: 'Auto (qualité source)', value: '' },
|
|
{ label: '1080p (~8 Mbps)', value: '8000000' },
|
|
{ label: '720p (~4 Mbps)', value: '4000000' },
|
|
{ label: '480p (~1.5 Mbps)', value: '1500000' }
|
|
];
|
|
|
|
export function renderPartyPlayer(root, params) {
|
|
const partyId = params.id;
|
|
|
|
root.innerHTML = `
|
|
<div class="playerWrap">
|
|
<video id="video" playsinline></video>
|
|
|
|
<p id="loadingNotice" class="loadingNotice">Chargement du flux...</p>
|
|
<div id="playerError" class="playerError hide">
|
|
<p id="playerErrorText"></p>
|
|
<button id="playerErrorRetry" class="linklike">Réessayer</button>
|
|
</div>
|
|
|
|
<div class="overlay">
|
|
<span id="itemTitle" class="itemTitle"></span>
|
|
<span>Code: <span id="code" class="code"></span></span>
|
|
<span id="members" class="members"></span>
|
|
<button id="nextBtn" class="linklike hide">Épisode suivant →</button>
|
|
|
|
<div id="settingsWrap" class="settingsWrap hide">
|
|
<button id="settingsBtn" class="iconBtn" title="Paramètres de lecture" aria-label="Paramètres de lecture">⚙</button>
|
|
<div id="settingsPanel" class="settingsPanel hide">
|
|
<label>Langue <select id="audioSelect"></select></label>
|
|
<label>Sous-titres <select id="subtitleSelect"><option value="">Aucun</option></select></label>
|
|
<label>Qualité <select id="qualitySelect"></select></label>
|
|
</div>
|
|
</div>
|
|
|
|
<button id="leaveBtn" class="linklike">Quitter</button>
|
|
</div>
|
|
|
|
<p id="followerNotice" class="followerNotice hide">L'hôte contrôle la lecture.</p>
|
|
</div>`;
|
|
|
|
const video = root.querySelector('#video');
|
|
const loadingNotice = root.querySelector('#loadingNotice');
|
|
const errorBox = root.querySelector('#playerError');
|
|
const errorText = root.querySelector('#playerErrorText');
|
|
const itemTitleEl = root.querySelector('#itemTitle');
|
|
const codeEl = root.querySelector('#code');
|
|
const membersEl = root.querySelector('#members');
|
|
const nextBtn = root.querySelector('#nextBtn');
|
|
const followerNotice = root.querySelector('#followerNotice');
|
|
const settingsWrap = root.querySelector('#settingsWrap');
|
|
const settingsBtn = root.querySelector('#settingsBtn');
|
|
const settingsPanel = root.querySelector('#settingsPanel');
|
|
const audioSelect = root.querySelector('#audioSelect');
|
|
const subtitleSelect = root.querySelector('#subtitleSelect');
|
|
const qualitySelect = root.querySelector('#qualitySelect');
|
|
|
|
qualitySelect.innerHTML = QUALITY_PRESETS.map((q) => `<option value="${q.value}">${q.label}</option>`).join('');
|
|
|
|
// Named (not inline-anonymous) specifically so cleanup() below can remove
|
|
// this exact listener - document.addEventListener is a page-lifetime
|
|
// target, so an anonymous one added on every visit to this route would
|
|
// never be reachable to remove, and would pile up across visits. This was
|
|
// the actual leak: every join-a-party-then-navigate-away-without-"Quitter"
|
|
// used to leave one of these (plus the heartbeat interval, the socket,
|
|
// and the hls.js instance) running forever - see router.js's cleanup hook.
|
|
function onDocumentClick(e) {
|
|
if (!settingsWrap.contains(e.target)) settingsPanel.classList.add('hide');
|
|
}
|
|
document.addEventListener('click', onDocumentClick);
|
|
|
|
settingsBtn.addEventListener('click', (e) => {
|
|
e.stopPropagation();
|
|
settingsPanel.classList.toggle('hide');
|
|
});
|
|
|
|
let isHost = false;
|
|
let conn = null;
|
|
let hls = null;
|
|
let currentItemId = null;
|
|
let suppressLocalEvents = false; // avoid feeding our own correction back as a new event
|
|
let heartbeat = null;
|
|
|
|
function showError(message, detail) {
|
|
loadingNotice.classList.add('hide');
|
|
errorText.textContent = message;
|
|
errorBox.classList.remove('hide');
|
|
console.error('[watchparty player]', message, detail || '');
|
|
}
|
|
|
|
function clearError() {
|
|
errorBox.classList.add('hide');
|
|
}
|
|
|
|
function applyRemoteState(msg) {
|
|
suppressLocalEvents = true;
|
|
const targetSeconds = msg.positionTicks / TICKS_PER_SECOND;
|
|
if (Math.abs(video.currentTime - targetSeconds) > DRIFT_TOLERANCE_SECONDS) {
|
|
video.currentTime = targetSeconds;
|
|
}
|
|
if (msg.isPaused && !video.paused) video.pause();
|
|
if (!msg.isPaused && video.paused) video.play().catch(() => {});
|
|
setTimeout(() => { suppressLocalEvents = false; }, 250);
|
|
}
|
|
|
|
function sendLocalState() {
|
|
if (!isHost || suppressLocalEvents || !conn) return;
|
|
conn.sendPlaystate(video.paused, Math.round(video.currentTime * TICKS_PER_SECOND));
|
|
}
|
|
|
|
async function loadTrackOptions(itemId) {
|
|
try {
|
|
const options = await getPlaybackOptions(itemId);
|
|
audioSelect.innerHTML = options.audioTracks.length
|
|
? options.audioTracks.map((t) => `<option value="${t.index}">${escapeHtml(t.label)}</option>`).join('')
|
|
: '<option value="">Piste par défaut</option>';
|
|
subtitleSelect.innerHTML = '<option value="">Aucun</option>' +
|
|
options.subtitleTracks.map((t) => `<option value="${t.index}">${escapeHtml(t.label)}</option>`).join('');
|
|
} catch (err) {
|
|
console.error('[watchparty player] playback-options failed', err);
|
|
// Non-fatal: playback can still work with Emby's own defaults, just without a picker.
|
|
}
|
|
}
|
|
|
|
function loadVideo(itemId, resumeSeconds, wasPlaying) {
|
|
currentItemId = itemId;
|
|
clearError();
|
|
loadingNotice.classList.remove('hide');
|
|
|
|
if (hls) {
|
|
hls.destroy();
|
|
hls = null;
|
|
}
|
|
|
|
const src = streamUrl(itemId, {
|
|
AudioStreamIndex: audioSelect.value,
|
|
SubtitleStreamIndex: subtitleSelect.value,
|
|
MaxStreamingBitrate: qualitySelect.value
|
|
});
|
|
|
|
const resume = () => {
|
|
loadingNotice.classList.add('hide');
|
|
if (resumeSeconds) video.currentTime = resumeSeconds;
|
|
if (wasPlaying) video.play().catch(() => {});
|
|
};
|
|
|
|
if (window.Hls && window.Hls.isSupported()) {
|
|
hls = new window.Hls();
|
|
hls.on(window.Hls.Events.MANIFEST_PARSED, resume);
|
|
hls.on(window.Hls.Events.ERROR, (event, data) => {
|
|
if (!data.fatal) return;
|
|
showError(
|
|
"Erreur de lecture (HLS) - le flux n'a pas pu être chargé depuis Emby.",
|
|
data
|
|
);
|
|
});
|
|
hls.loadSource(src);
|
|
hls.attachMedia(video);
|
|
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
|
|
// Safari plays HLS natively - no hls.js involved, so wire the plain
|
|
// <video> element's own error event instead.
|
|
video.src = src;
|
|
video.addEventListener('loadedmetadata', resume, { once: true });
|
|
video.addEventListener('error', () => {
|
|
showError('Erreur de lecture vidéo.', video.error);
|
|
});
|
|
} else {
|
|
showError("Ce navigateur ne sait pas lire de flux HLS et hls.js n'a pas pu se charger.");
|
|
}
|
|
}
|
|
|
|
// Changing language/subtitles/quality means a fresh transcode (Emby bakes
|
|
// the selection in server-side - see index.js) - reload at the same
|
|
// position instead of restarting from zero.
|
|
function reloadWithCurrentOptions() {
|
|
loadVideo(currentItemId, video.currentTime, !video.paused);
|
|
}
|
|
|
|
[audioSelect, subtitleSelect, qualitySelect].forEach((sel) => {
|
|
sel.addEventListener('change', () => {
|
|
settingsPanel.classList.add('hide');
|
|
reloadWithCurrentOptions();
|
|
});
|
|
});
|
|
|
|
root.querySelector('#playerErrorRetry').addEventListener('click', () => {
|
|
if (currentItemId) loadVideo(currentItemId, video.currentTime, true);
|
|
});
|
|
|
|
async function onItemChanged(msg) {
|
|
itemTitleEl.textContent = msg.itemName || '';
|
|
nextBtn.classList.toggle('hide', !(isHost && msg.hasNext));
|
|
await loadTrackOptions(msg.itemId);
|
|
loadVideo(msg.itemId, 0, true);
|
|
}
|
|
|
|
async function init() {
|
|
let party;
|
|
try {
|
|
party = await getParty(partyId);
|
|
} catch (err) {
|
|
alert(err.message);
|
|
navigate('/home');
|
|
return;
|
|
}
|
|
|
|
isHost = party.youAreHost;
|
|
itemTitleEl.textContent = party.itemName || '';
|
|
codeEl.textContent = party.joinCode;
|
|
video.controls = isHost;
|
|
settingsWrap.classList.toggle('hide', !isHost);
|
|
followerNotice.classList.toggle('hide', isHost);
|
|
nextBtn.classList.toggle('hide', !(isHost && party.hasNext));
|
|
|
|
await loadTrackOptions(party.itemId);
|
|
loadVideo(party.itemId, 0, false);
|
|
|
|
conn = connectParty(partyId, {
|
|
onMembers: renderMembers,
|
|
onPlaystate: applyRemoteState,
|
|
onItemChanged,
|
|
onError: (message) => alert(message),
|
|
onClose: () => {}
|
|
});
|
|
|
|
if (isHost) {
|
|
video.addEventListener('play', sendLocalState);
|
|
video.addEventListener('pause', sendLocalState);
|
|
video.addEventListener('seeked', sendLocalState);
|
|
video.addEventListener('ended', () => {
|
|
if (!nextBtn.classList.contains('hide')) conn.next();
|
|
});
|
|
heartbeat = setInterval(sendLocalState, 3000);
|
|
}
|
|
}
|
|
|
|
function renderMembers(members) {
|
|
membersEl.textContent = members
|
|
.map((m) => m.userName + (m.isHost ? ' (hôte)' : ''))
|
|
.join(', ');
|
|
}
|
|
|
|
nextBtn.addEventListener('click', () => { if (conn) conn.next(); });
|
|
root.querySelector('#leaveBtn').addEventListener('click', () => navigate('/home'));
|
|
|
|
init();
|
|
|
|
// Called by router.js right before it renders whatever route comes next -
|
|
// whether that's from clicking "Quitter" (navigate above) or leaving any
|
|
// other way (sidebar link, browser back, ...). This is the fix for the
|
|
// actual leak: previously, only the "Quitter" button ran any of this.
|
|
return function cleanup() {
|
|
if (heartbeat) clearInterval(heartbeat);
|
|
if (hls) hls.destroy();
|
|
document.removeEventListener('click', onDocumentClick);
|
|
if (conn) conn.leave();
|
|
leaveParty(partyId).catch(() => {});
|
|
};
|
|
}
|