Real request logged after the last fix (MediaSourceId in the query
string) shipped: still a 400, now Emby's own "Value cannot be null.
(Parameter 'key')" - a bare .NET Dictionary null-key exception, not
the earlier problem (MediaSourceId was present and well-formed in the
logged request).
This exact message already burned this app once before, in
CatalogService.negotiateStreamTarget's hand-built fallback URL (see
its own long-standing TODO(verify) comment) - diagnosed there as Emby
indexing some internal state by a parameter the request hadn't
supplied. PlaySessionId is the standout remaining candidate: it's how
Emby/Jellyfin clients normally correlate a progress report with the
specific playback/transcode session it belongs to, and evidently
Emby's real Progress handler keys a lookup on it even though the
OpenAPI spec doesn't mark it required.
Fixed the same way MediaSourceId was: CatalogService
.negotiateStreamTarget already reads info.PlaySessionId from the same
PlaybackInfo response (it already used it in the hand-built fallback
URL) - its return type just needed to surface it too. PartyStreamService
now caches it alongside mediaSourceId and exposes both together from
one accessor, getCachedPlaybackIds(partyId), replacing the
round-1 getCachedMediaSourceId. PlaystateService.reportProgress and
index.ts's sweep both thread it through.
Not independently confirmed against a real server yet (no safe way to
fire a real, state-mutating test call without one) - flagged in
docs/architecture.md the same way every other real-server-dependent
guess in this app is, but grounded in this app's own prior confirmed
diagnosis of the identical error message rather than a fresh guess.
Updated catalogService.test's negotiateStreamTarget assertions to
cover playSessionId in both return branches, partyStreamService.test's
mocks/assertions for the new {mediaSourceId, playSessionId} cache
shape, and playstateService.test's request-shape and logging
assertions for the extra PlaySessionId param. Full typecheck/test/build
green (96/96 tests). docs/architecture.md and README.md updated.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
533 lines
24 KiB
TypeScript
533 lines
24 KiB
TypeScript
'use strict';
|
|
|
|
import path from 'path';
|
|
import http from 'http';
|
|
import express, { type NextFunction, type Request, type Response } from 'express';
|
|
import { Server as SocketIoServer } from 'socket.io';
|
|
|
|
import { EMBY_SERVER_URL, PORT } from './config';
|
|
import { Logger } from './Logger';
|
|
import { AuthService, SESSION_COOKIE, SESSION_TTL_MS } from './services/AuthService';
|
|
import { CatalogService, CatalogFetchError, splitPlaylistByMediaType } from './services/CatalogService';
|
|
import { PartyService } from './services/PartyService';
|
|
import { MusicQueueService } from './services/MusicQueueService';
|
|
import { TranscodeService } from './services/TranscodeService';
|
|
import { PartyStreamService } from './services/PartyStreamService';
|
|
import { PlaystateService } from './services/PlaystateService';
|
|
import { SocketGateway } from './realtime/SocketGateway';
|
|
import type { ClientToServerEvents, EmbySession, MediaType, QueueItem, ServerToClientEvents } from './types';
|
|
|
|
const app = express();
|
|
app.set('trust proxy', 1); // behind openresty/nginx - needed for req.secure to reflect the real scheme
|
|
app.use(express.json());
|
|
|
|
// Everything the browser needs - the app shell AND every Emby call - is
|
|
// same-origin from here on. See docs/architecture.md for why: the previous
|
|
// version had the browser call Emby directly and hit real CORS problems.
|
|
// client/dist is esbuild's output (client/src compiled) - see
|
|
// client/build.mjs and docs/architecture.md's TypeScript-migration section.
|
|
app.use(express.static(path.join(__dirname, '..', '..', 'client', 'dist')));
|
|
|
|
function requireSession(req: Request, res: Response, next: NextFunction): void {
|
|
const session = AuthService.sessionFromRequest(req);
|
|
if (!session) {
|
|
res.status(401).json({ error: 'Session expirée, reconnecte-toi.' });
|
|
return;
|
|
}
|
|
req.embySession = session;
|
|
next();
|
|
}
|
|
|
|
/**
|
|
* Express 4 doesn't catch a rejected Promise from an async route handler
|
|
* on its own - an unhandled rejection there would either crash the
|
|
* process or just hang the request forever, depending on Node version.
|
|
* Every route below is wrapped in this so a service throwing
|
|
* (CatalogFetchError, a raw network failure, anything) always turns into
|
|
* a real HTTP response instead - see the error-handling middleware at the
|
|
* bottom of this file for where it actually gets turned into one.
|
|
*/
|
|
function asyncRoute(handler: (req: Request, res: Response) => Promise<void>) {
|
|
return (req: Request, res: Response, next: NextFunction) => {
|
|
handler(req, res).catch(next);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Reads a required `:name` route param. A matched Express route always has
|
|
* one (Express itself guarantees it; none of these routes use an optional
|
|
* `:name?` segment) - this just gives TypeScript the same certainty:
|
|
* `req.params` is an index-signature type, so `noUncheckedIndexedAccess`
|
|
* (tsconfig.json) sees every access as possibly-`undefined` on its own.
|
|
*/
|
|
function param(req: Request, name: string): string {
|
|
return req.params[name] as string;
|
|
}
|
|
|
|
// --- Auth ----------------------------------------------------------------
|
|
// The browser only ever sends a username/password once, to us. From then on
|
|
// it holds an opaque session cookie - never Emby's own access token.
|
|
|
|
app.post('/api/auth/login', asyncRoute(async (req, res) => {
|
|
const { username, password } = req.body || {};
|
|
if (!username || !password) {
|
|
res.status(400).json({ error: "Nom d'utilisateur et mot de passe requis." });
|
|
return;
|
|
}
|
|
|
|
const sessionId = await AuthService.login(username, password);
|
|
if (!sessionId) {
|
|
res.status(401).json({ error: 'Identifiants refusés.' });
|
|
return;
|
|
}
|
|
|
|
res.cookie(SESSION_COOKIE, sessionId, {
|
|
httpOnly: true,
|
|
sameSite: 'lax',
|
|
secure: req.secure,
|
|
maxAge: SESSION_TTL_MS
|
|
});
|
|
res.json({ userName: AuthService.getSession(sessionId)!.userName });
|
|
}));
|
|
|
|
app.post('/api/auth/logout', (req, res) => {
|
|
const cookies = AuthService.parseCookies(req.headers.cookie);
|
|
if (cookies[SESSION_COOKIE]) {
|
|
AuthService.endSession(cookies[SESSION_COOKIE]);
|
|
}
|
|
res.clearCookie(SESSION_COOKIE);
|
|
res.json({ ok: true });
|
|
});
|
|
|
|
app.get('/api/auth/me', requireSession, (req, res) => {
|
|
res.json({ userName: req.embySession!.userName });
|
|
});
|
|
|
|
// --- Catalog (proxied - the browser never talks to Emby directly) --------
|
|
// Thin wrappers over CatalogService - see its own file for the actual
|
|
// Emby calls/DTO shaping.
|
|
|
|
app.get('/api/catalog/search', requireSession, asyncRoute(async (req, res) => {
|
|
const items = await CatalogService.search(req.embySession!, String(req.query.q || ''));
|
|
res.json({ items });
|
|
}));
|
|
|
|
app.get('/api/catalog/item/:itemId', requireSession, asyncRoute(async (req, res) => {
|
|
res.json(await CatalogService.getItem(req.embySession!, param(req, 'itemId')));
|
|
}));
|
|
|
|
// One entry per library, shown in the sidebar - see client/src's Shell.
|
|
app.get('/api/catalog/libraries', requireSession, asyncRoute(async (req, res) => {
|
|
res.json({ libraries: await CatalogService.getLibraries(req.embySession!) });
|
|
}));
|
|
|
|
// Home page carousel: Emby's own "recently added" endpoint, one row per library.
|
|
app.get('/api/catalog/libraries/:libraryId/recent', requireSession, asyncRoute(async (req, res) => {
|
|
res.json({ items: await CatalogService.getRecentItems(req.embySession!, param(req, 'libraryId')) });
|
|
}));
|
|
|
|
// Series -> Seasons -> Episodes, for the "Contenus vidéo en série" browsing page.
|
|
app.get('/api/catalog/series/:seriesId/seasons', requireSession, asyncRoute(async (req, res) => {
|
|
res.json({ seasons: await CatalogService.getSeriesSeasons(req.embySession!, param(req, 'seriesId')) });
|
|
}));
|
|
|
|
app.get('/api/catalog/series/:seriesId/episodes', requireSession, asyncRoute(async (req, res) => {
|
|
const seasonId = typeof req.query.seasonId === 'string' ? req.query.seasonId : undefined;
|
|
res.json({ episodes: await CatalogService.getSeriesEpisodes(req.embySession!, param(req, 'seriesId'), seasonId) });
|
|
}));
|
|
|
|
// Library -> Artists -> Albums -> Tracks, for the "Musique" browsing pages.
|
|
app.get('/api/catalog/libraries/:libraryId/artists', requireSession, asyncRoute(async (req, res) => {
|
|
res.json({ artists: await CatalogService.getArtists(req.embySession!, param(req, 'libraryId')) });
|
|
}));
|
|
|
|
app.get('/api/catalog/artists/:artistId/albums', requireSession, asyncRoute(async (req, res) => {
|
|
res.json({ albums: await CatalogService.getArtistAlbums(req.embySession!, param(req, 'artistId')) });
|
|
}));
|
|
|
|
app.get('/api/catalog/albums/:albumId/tracks', requireSession, asyncRoute(async (req, res) => {
|
|
res.json({ tracks: await CatalogService.getAlbumTracks(req.embySession!, param(req, 'albumId')) });
|
|
}));
|
|
|
|
// A playlist's own contents, in order - for views/playlist. See
|
|
// POST /api/parties below for actually launching one.
|
|
app.get('/api/catalog/playlists/:playlistId/items', requireSession, asyncRoute(async (req, res) => {
|
|
res.json({ items: await CatalogService.getPlaylistItems(req.embySession!, param(req, 'playlistId')) });
|
|
}));
|
|
|
|
// Audio/subtitle tracks available for an item, read from Emby's own playback
|
|
// negotiation (PlaybackInfo) - powers the player's language/subtitle pickers.
|
|
app.get('/api/catalog/item/:itemId/playback-options', requireSession, asyncRoute(async (req, res) => {
|
|
res.json(await CatalogService.getPlaybackOptions(req.embySession!, param(req, 'itemId')));
|
|
}));
|
|
|
|
app.get('/api/catalog/libraries/:libraryId/items', requireSession, asyncRoute(async (req, res) => {
|
|
res.json({ items: await CatalogService.getLibraryItems(req.embySession!, param(req, 'libraryId')) });
|
|
}));
|
|
|
|
// Images/video/audio/subtitles are requested by <img>/<video>/<audio>/
|
|
// <track> elements, which send the session cookie (same-origin) but can't
|
|
// carry a bearer header - so these four routes check the cookie directly
|
|
// instead of using the requireSession middleware's JSON error response,
|
|
// which a browser media element ignores.
|
|
|
|
app.get('/api/catalog/image/:itemId', asyncRoute(async (req, res) => {
|
|
const session = AuthService.sessionFromRequest(req);
|
|
if (!session) { res.status(401).end(); return; }
|
|
await CatalogService.proxyImage(req, res, session, param(req, 'itemId'));
|
|
}));
|
|
|
|
// The party's own shared Emby stream - one negotiated PlaybackInfo
|
|
// session reused by every member, instead of each viewer's own
|
|
// <video>/<audio> negotiating (and getting its own PlaySessionId)
|
|
// independently - see PartyStreamService and docs/architecture.md's
|
|
// "One shared Emby stream per party" section. Keyed by partyId, not
|
|
// itemId - the party object itself is the source of truth for what
|
|
// it's currently streaming and with which audio/quality choice, so
|
|
// there's nothing else a client could usefully put in this URL.
|
|
// requireSession's JSON error doesn't fit here either, same reasoning
|
|
// as the routes above (a <video>/<audio> element can't carry a bearer
|
|
// header).
|
|
app.get('/api/catalog/party-stream/:partyId/master.m3u8', asyncRoute(async (req, res) => {
|
|
const session = AuthService.sessionFromRequest(req);
|
|
if (!session) { res.status(401).end(); return; }
|
|
const party = PartyService.getById(param(req, 'partyId'));
|
|
if (!party || !party.members.has(session.userId)) {
|
|
res.status(403).json({ error: "Tu n'es pas membre de cette watch party." });
|
|
return;
|
|
}
|
|
await PartyStreamService.serveMasterPlaylist(req, res, party, session);
|
|
}));
|
|
|
|
// Everything an HLS playlist references (variant playlists, segments)
|
|
// comes back through here - see EmbyClient.rewritePlaylist.
|
|
app.get('/api/catalog/party-stream/:partyId/raw', asyncRoute(async (req, res) => {
|
|
const session = AuthService.sessionFromRequest(req);
|
|
if (!session) { res.status(401).end(); return; }
|
|
const party = PartyService.getById(param(req, 'partyId'));
|
|
if (!party || !party.members.has(session.userId)) {
|
|
res.status(403).json({ error: "Tu n'es pas membre de cette watch party." });
|
|
return;
|
|
}
|
|
await PartyStreamService.serveRawAsset(req, res, party, session);
|
|
}));
|
|
|
|
// A subtitle track's own text (WebVTT), for the player's native <track> -
|
|
// see CatalogService.proxySubtitle's own comment for why subtitles are
|
|
// rendered this way instead of asking Emby to burn them into the video.
|
|
app.get('/api/catalog/subtitle/:itemId/:subtitleIndex', asyncRoute(async (req, res) => {
|
|
const session = AuthService.sessionFromRequest(req);
|
|
if (!session) { res.status(401).end(); return; }
|
|
await CatalogService.proxySubtitle(req, res, session, param(req, 'itemId'), param(req, 'subtitleIndex'));
|
|
}));
|
|
|
|
// The party's own self-hosted-ffmpeg burn-in stream (PGS/image subtitles
|
|
// only - see TranscodeService and Party.burnInSubtitleIndex's own
|
|
// comment); every other party keeps streaming through the party-stream
|
|
// routes above instead - PartyStreamService, not our own ffmpeg. Keyed
|
|
// by partyId, not itemId, same reasoning as those routes: the party
|
|
// object itself is the source of truth for which audio/subtitle
|
|
// combination is currently burned in, so there's nothing else a client
|
|
// could usefully put in this URL. requireSession's JSON error doesn't
|
|
// fit here either, same reasoning as the routes above.
|
|
app.get('/api/catalog/burn/:partyId/master.m3u8', asyncRoute(async (req, res) => {
|
|
const session = AuthService.sessionFromRequest(req);
|
|
if (!session) { res.status(401).end(); return; }
|
|
const party = PartyService.getById(param(req, 'partyId'));
|
|
if (!party || !party.members.has(session.userId)) {
|
|
res.status(403).json({ error: "Tu n'es pas membre de cette watch party." });
|
|
return;
|
|
}
|
|
if (!party.burnInSubtitleIndex) {
|
|
res.status(409).json({ error: "Cette watch party n'a pas de flux incrusté actif." });
|
|
return;
|
|
}
|
|
await TranscodeService.serveMasterPlaylist(req, res, party, session);
|
|
}));
|
|
|
|
app.get('/api/catalog/burn/:partyId/:segment', asyncRoute(async (req, res) => {
|
|
const session = AuthService.sessionFromRequest(req);
|
|
if (!session) { res.status(401).end(); return; }
|
|
const party = PartyService.getById(param(req, 'partyId'));
|
|
if (!party || !party.members.has(session.userId)) {
|
|
res.status(403).json({ error: "Tu n'es pas membre de cette watch party." });
|
|
return;
|
|
}
|
|
await TranscodeService.serveSegment(req, res, party, param(req, 'segment'));
|
|
}));
|
|
|
|
// --- Parties ---------------------------------------------------------------
|
|
// No REST "list parties" endpoint: the home page's "watch parties en cours"
|
|
// list is live, over Socket.IO's "lobby" room (SocketGateway) - see
|
|
// docs/architecture.md. No join codes either - see PartyService's class
|
|
// comment for why a live list makes one redundant.
|
|
|
|
app.post('/api/parties', requireSession, asyncRoute(async (req, res) => {
|
|
const itemId = req.body?.itemId;
|
|
if (!itemId) {
|
|
res.status(400).json({ error: 'itemId is required.' });
|
|
return;
|
|
}
|
|
|
|
const session = req.embySession!;
|
|
const item = await CatalogService.getRawItem(session, itemId);
|
|
|
|
// A playlist itself was never something Emby could stream - launching
|
|
// one means queuing everything inside it instead, a separate enough
|
|
// shape (video queue vs. seeding the participative music queue several
|
|
// tracks at once) that it's its own function rather than folded into
|
|
// the single-item path below. See docs/architecture.md.
|
|
if (item.Type === 'Playlist') {
|
|
await createPartyFromPlaylist(res, session, itemId);
|
|
return;
|
|
}
|
|
|
|
const mediaType: MediaType = item.Type === 'Audio' ? 'music' : 'video';
|
|
|
|
// Starting a party from an episode queues the rest of the series from
|
|
// there on, so the host can hit "next" (see SocketGateway) instead of
|
|
// everyone having to separately start a new party per episode. Doesn't
|
|
// apply to music - that party's queue is the live, participative one
|
|
// instead (see MusicQueueService.init below).
|
|
let queue: QueueItem[] | null = null;
|
|
if (mediaType === 'video' && item.Type === 'Episode' && item.SeriesId) {
|
|
const all = await CatalogService.getAllSeriesEpisodesRaw(session, item.SeriesId);
|
|
const startIndex = all.findIndex((e) => e.Id === itemId);
|
|
const remaining = startIndex >= 0 ? all.slice(startIndex) : [item];
|
|
queue = remaining.map((e) => ({
|
|
itemId: e.Id,
|
|
itemName: formatEpisodeName(e),
|
|
itemImageUrl: `/api/catalog/image/${e.Id}`
|
|
}));
|
|
}
|
|
|
|
const party = PartyService.create(
|
|
session.userId,
|
|
session.userName,
|
|
itemId,
|
|
queue ? queue[0]!.itemName : item.Name,
|
|
`/api/catalog/image/${itemId}`,
|
|
queue,
|
|
mediaType
|
|
);
|
|
PartyService.setMemberEmbyToken(party, session.userId, session.embyToken);
|
|
|
|
if (mediaType === 'music') {
|
|
MusicQueueService.init(party, {
|
|
itemId,
|
|
itemName: item.Name,
|
|
artistName: item.AlbumArtist || item.Artists?.[0] || null,
|
|
albumName: item.Album || null,
|
|
itemImageUrl: `/api/catalog/image/${itemId}`,
|
|
durationTicks: item.RunTimeTicks || null
|
|
}, session.userId, session.userName);
|
|
}
|
|
|
|
SocketGateway.broadcastLobby(io); // the new party shows up on everyone's home page immediately
|
|
res.json(PartyService.toPublicState(party, session.userId));
|
|
}));
|
|
|
|
function formatEpisodeName(episode: { ParentIndexNumber?: number; IndexNumber?: number; SeriesName?: string; Name: string }): string {
|
|
if (episode.ParentIndexNumber != null && episode.IndexNumber != null) {
|
|
const prefix = `S${episode.ParentIndexNumber}E${episode.IndexNumber}`;
|
|
return episode.SeriesName ? `${episode.SeriesName} - ${prefix} - ${episode.Name}` : `${prefix} - ${episode.Name}`;
|
|
}
|
|
return episode.Name;
|
|
}
|
|
|
|
/**
|
|
* The "launch this playlist" half of POST /api/parties above - kept
|
|
* separate rather than merged into the single-item path, which is
|
|
* already working/relied-upon and doesn't need touching for this.
|
|
* splitPlaylistByMediaType (CatalogService) decides video vs music from
|
|
* the playlist's first item and drops anything that doesn't match (a
|
|
* mixed playlist - not something this app's party model can represent).
|
|
*/
|
|
async function createPartyFromPlaylist(res: Response, session: EmbySession, playlistId: string): Promise<void> {
|
|
const raw = await CatalogService.getPlaylistItemsRaw(session, playlistId);
|
|
const { mediaType, items } = splitPlaylistByMediaType(raw);
|
|
if (!items.length) {
|
|
res.status(400).json({ error: 'Cette playlist est vide.' });
|
|
return;
|
|
}
|
|
if (items.length !== raw.length) {
|
|
Logger.party(`playlist ${playlistId} is mixed-media - keeping only the ${items.length}/${raw.length} ${mediaType} item(s)`);
|
|
}
|
|
|
|
if (mediaType === 'music') {
|
|
const first = items[0]!;
|
|
const party = PartyService.create(
|
|
session.userId, session.userName,
|
|
first.Id, first.Name, `/api/catalog/image/${first.Id}`,
|
|
null, mediaType
|
|
);
|
|
PartyService.setMemberEmbyToken(party, session.userId, session.embyToken);
|
|
// Same mechanism POST /api/parties/:id/tracks already uses (see
|
|
// below) - init seeds+auto-starts the first track, addTrack queues
|
|
// the rest, exactly as if they'd been added one at a time.
|
|
items.forEach((track, i) => {
|
|
const trackInput = {
|
|
itemId: track.Id,
|
|
itemName: track.Name,
|
|
artistName: track.AlbumArtist || track.Artists?.[0] || null,
|
|
albumName: track.Album || null,
|
|
itemImageUrl: `/api/catalog/image/${track.Id}`,
|
|
durationTicks: track.RunTimeTicks || null
|
|
};
|
|
if (i === 0) {
|
|
MusicQueueService.init(party, trackInput, session.userId, session.userName);
|
|
} else {
|
|
MusicQueueService.addTrack(party, trackInput, session.userId, session.userName);
|
|
}
|
|
});
|
|
SocketGateway.broadcastLobby(io);
|
|
res.json(PartyService.toPublicState(party, session.userId));
|
|
return;
|
|
}
|
|
|
|
const queue: QueueItem[] = items.map((e) => ({
|
|
itemId: e.Id,
|
|
itemName: e.Type === 'Episode' ? formatEpisodeName(e) : e.Name,
|
|
itemImageUrl: `/api/catalog/image/${e.Id}`
|
|
}));
|
|
const party = PartyService.create(
|
|
session.userId, session.userName,
|
|
queue[0]!.itemId, queue[0]!.itemName, queue[0]!.itemImageUrl,
|
|
queue, mediaType
|
|
);
|
|
PartyService.setMemberEmbyToken(party, session.userId, session.embyToken);
|
|
SocketGateway.broadcastLobby(io);
|
|
res.json(PartyService.toPublicState(party, session.userId));
|
|
}
|
|
|
|
// Adding a track to a music party's shared queue is REST, not a socket
|
|
// event (see SocketGateway's top comment): the album-browsing page that
|
|
// this is actually called from has no live connection to the party it's
|
|
// adding into - only the player view does. MusicQueueService's own
|
|
// "queueUpdated" broadcast (wired to the real io instance via attachIo,
|
|
// below) reaches anyone actually connected regardless of which page made
|
|
// this request.
|
|
app.post('/api/parties/:partyId/tracks', requireSession, (req, res) => {
|
|
const party = PartyService.getById(param(req, 'partyId'));
|
|
if (!party || party.mediaType !== 'music') {
|
|
res.status(404).json({ error: 'Watch party musique introuvable.' });
|
|
return;
|
|
}
|
|
const session = req.embySession!;
|
|
if (!party.members.has(session.userId)) {
|
|
res.status(403).json({ error: "Tu n'es pas membre de cette watch party." });
|
|
return;
|
|
}
|
|
const track = req.body || {};
|
|
if (!track.itemId) {
|
|
res.status(400).json({ error: 'itemId is required.' });
|
|
return;
|
|
}
|
|
MusicQueueService.addTrack(party, track, session.userId, session.userName);
|
|
SocketGateway.broadcastLobby(io); // the queue/now-playing preview may have just changed
|
|
res.json(PartyService.toPublicState(party, session.userId));
|
|
});
|
|
|
|
app.post('/api/parties/:partyId/join', requireSession, (req, res) => {
|
|
const party = PartyService.getById(param(req, 'partyId'));
|
|
if (!party) {
|
|
res.status(404).json({ error: 'Party introuvable (elle est peut-être terminée).' });
|
|
return;
|
|
}
|
|
const session = req.embySession!;
|
|
PartyService.join(party, session.userId, session.userName);
|
|
PartyService.setMemberEmbyToken(party, session.userId, session.embyToken);
|
|
SocketGateway.broadcastLobby(io); // member count changed - reflect it on the home page immediately
|
|
res.json(PartyService.toPublicState(party, session.userId));
|
|
});
|
|
|
|
app.post('/api/parties/:partyId/leave', requireSession, (req, res) => {
|
|
const party = PartyService.getById(param(req, 'partyId'));
|
|
if (party) {
|
|
// Shared with the socket "leave"/"disconnect" handlers so the host-
|
|
// handoff notification and the lobby refresh only live in one place.
|
|
SocketGateway.applyLeave(io, party, req.embySession!.userId);
|
|
}
|
|
res.json({ ok: true });
|
|
});
|
|
|
|
app.get('/api/parties/:partyId', requireSession, (req, res) => {
|
|
const party = PartyService.getById(param(req, 'partyId'));
|
|
if (!party) {
|
|
res.status(404).json({ error: 'Party introuvable (elle est peut-être terminée).' });
|
|
return;
|
|
}
|
|
res.json(PartyService.toPublicState(party, req.embySession!.userId));
|
|
});
|
|
|
|
// Catches whatever asyncRoute() forwarded (or a synchronous throw) -
|
|
// CatalogFetchError carries its own status/message; anything else is an
|
|
// unexpected bug, logged in full server-side but never leaked to the
|
|
// client beyond a generic message.
|
|
app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {
|
|
if (err instanceof CatalogFetchError) {
|
|
res.status(err.status).json({ error: err.message });
|
|
return;
|
|
}
|
|
console.error('[watchparty] unexpected error', err);
|
|
res.status(500).json({ error: 'Erreur serveur.' });
|
|
});
|
|
|
|
const server = http.createServer(app);
|
|
// Same-origin by default (no `cors` option needed) - the client connects
|
|
// with a bare io() call, consistent with everything else in this app never
|
|
// crossing origins. Socket.IO's own heartbeat (pingInterval/pingTimeout,
|
|
// defaults are fine here) is what detects dead connections - see
|
|
// SocketGateway's top comment for why that matters.
|
|
const io = new SocketIoServer<ClientToServerEvents, ServerToClientEvents>(server);
|
|
SocketGateway.attach(io, (h) => AuthService.parseCookies(h), (id) => AuthService.getSession(id));
|
|
|
|
// Gives MusicQueueService a way to broadcast from its own internal
|
|
// auto-advance timer (no socket/request in scope there at all) and to
|
|
// refresh the home page's lobby card when the timer - not a person
|
|
// clicking anything - changes what's playing. Passed in rather than
|
|
// imported directly from SocketGateway/MusicQueueService to avoid a
|
|
// circular import between the two.
|
|
MusicQueueService.attachIo(io, () => SocketGateway.broadcastLobby(io));
|
|
|
|
setInterval(() => PartyService.removeIdleParties(4 * 60 * 60 * 1000), 10 * 60 * 1000);
|
|
// Shorter idle window than parties themselves: a burn-in session holds a
|
|
// real ffmpeg process + disk, not just an in-memory object, so a paused/
|
|
// abandoned one is worth reclaiming sooner. Mostly a backstop - the
|
|
// normal path is PartyService.leave's destroy branch ending it immediately.
|
|
setInterval(() => TranscodeService.reapIdleSessions(30 * 60 * 1000), 5 * 60 * 1000);
|
|
// Same reasoning as TranscodeService's own reaper just above - a cached
|
|
// negotiation is mostly harmless to keep around, but there's no reason
|
|
// to hold one for a party nobody's actively streaming from any more.
|
|
// Mostly a backstop too - the normal path is PartyService.leave's
|
|
// destroy branch (and an item/track change) ending it immediately.
|
|
setInterval(() => PartyStreamService.reapIdleSessions(30 * 60 * 1000), 5 * 60 * 1000);
|
|
|
|
// Pushes every connected member's own progress to Emby, under their own
|
|
// account - see docs/architecture.md's "Sync watch-party progress back
|
|
// to Emby" section for the full design and its deliberate v1 scope
|
|
// (periodic Progress reports only, no explicit start/stop). Best-effort:
|
|
// PlaystateService.reportProgress swallows its own failures, so one bad
|
|
// token or a transient Emby hiccup never stops the rest of this sweep.
|
|
// MediaSourceId/PlaySessionId come from PartyStreamService's own cache,
|
|
// read-only (getCachedPlaybackIds never negotiates) - both matter to the
|
|
// real Progress endpoint in practice (see PlaystateService.ts), and
|
|
// skipping a party entirely when nothing's cached yet (no one has hit
|
|
// play this session) is simpler and cheaper than this sweep ever
|
|
// negotiating a stream of its own just to get them.
|
|
setInterval(() => {
|
|
for (const party of PartyService.listActive()) {
|
|
const state = PartyService.getCurrentPlaybackState(party);
|
|
if (!state) continue; // nothing currently playing (e.g. an empty music queue)
|
|
const playbackIds = PartyStreamService.getCachedPlaybackIds(party.id);
|
|
if (!playbackIds) continue; // nothing negotiated yet this session - Progress needs it
|
|
for (const member of party.members.values()) {
|
|
if (!member.connection || !member.embyToken) continue;
|
|
PlaystateService.reportProgress(member.embyToken, member.userId, state.itemId, playbackIds.mediaSourceId, playbackIds.playSessionId, state.positionTicks, state.isPaused);
|
|
}
|
|
}
|
|
}, 20 * 1000);
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`[watchparty] listening on :${PORT} (Emby server: ${EMBY_SERVER_URL || 'NOT SET'})`);
|
|
});
|