watchparty/server/test/embySessionService.test.ts
Nicolas ceea7432ef
Some checks failed
Publier l'image Docker / test (pull_request) Failing after 5s
Publier l'image Docker / publish (pull_request) Has been skipped
Report watch-party streams to Emby's own Sessions API (admin dashboard)
Asked for directly: Emby's admin "now playing" dashboard should see
this app's streams the same way it sees a real web/mobile/TV client's.
This is exactly the follow-up "Sync watch-party progress back to Emby"
already anticipated and deliberately deferred at the time ("wiring
clean start/stop into every transition... is real complexity for a
secondary payoff") - that section also explains why this app abandoned
Emby's session-shaped PlayingItems endpoints entirely in favor of
direct UserData writes. Given that history (two separate rounds of a
wrong-but-schema-plausible request shape for that other, now-abandoned
endpoint family), this one was built checking the real API first
rather than assuming.

Confirmed against the real server's own /openapi.json that the actual
session-lifecycle family is POST /Sessions/Playing (start),
/Sessions/Playing/Progress, and /Sessions/Playing/Stopped - distinct
from PlayingItems. None of the three schemas declare a required list
at all, which - given the neighboring history - was read as "don't
trust that": ItemId/MediaSourceId/PlaySessionId/PositionTicks are sent
on every call anyway, matching what a real client obviously would,
rather than risking a repeat of "technically matches the schema, still
400s".

One real Emby session per PARTY MEMBER, not one per party - a faithful
copy of how a real client behaves, and the actual point of "let admin
see who's watching what" would be lost by collapsing everyone onto one
shared entry. New server/src/services/EmbySessionService.ts mirrors
PlaystateService's own best-effort shape (every failure caught and
logged, never thrown) but stays its own class - PlaystateService's own
opening comment is specifically about why it doesn't use a
session-shaped endpoint, so folding this into it would muddy that
exact distinction.

Getting a MediaSourceId/PlaySessionId per member needed a new
CatalogService.negotiatePlaybackSession - a fresh PlaybackInfo
negotiation under that specific member's own account, since Emby scopes
PlaybackInfo per user and PartyStreamService's existing shared
negotiation is never guaranteed valid for reporting under everyone
else's account too. Returns null on any failure rather than throwing -
this only ever feeds an admin-dashboard nicety, never something that
should disrupt real playback.

Driven entirely from index.ts's existing periodic sweep rather than new
hooks scattered across every queue-advance/track-skip call site -
that sweep already visits every connected member on every ~20s tick,
already positioned to notice a member's current item no longer matches
their cached session and react (stop the old one if any, negotiate
fresh ids, start the new one; same item as last tick just sends
Progress with the cached ids). PartyMember gained the nullable
embySession field this tracks. Explicit stop calls also happen at
PartyService.leave() (alongside the existing CastTokenService
.revokeForMember) and removeIdleParties (a backstop for a disconnect
that never triggered a clean leave).

Verified: full typecheck/test/build (134/134 server tests - new
coverage for negotiatePlaybackSession's null-on-any-failure contract,
every EmbySessionService method's exact request shape, that a non-ok
response/thrown error is swallowed not propagated, and that leave()
calls stop with a member's real cached session info but only when they
actually had one open). Not verified: an actual live write against the
real server - deliberately not attempted, since that would mean using
a real account's Emby token for a genuine state-changing call, beyond
the read-only diagnostic use this session's shared API key was ever
meant for. So while the request shape is checked against the real
schema and the per-member logic is unit-tested in full, whether Emby's
dashboard actually displays these sessions the way a native client's
would - correct device/client labeling in particular, since this app
never sends the X-Emby-Authorization Device/Client/Version header a
real client would, only X-Emby-Token - is genuinely unconfirmed. Worth
watching the real dashboard the first time a party runs after this ships.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 23:45:14 +02:00

91 lines
3.6 KiB
TypeScript

// Exercises EmbySessionService directly against a mocked EmbyClient - no
// real Emby server involved. Covers the request shape each of the three
// Sessions-API calls sends and that a failure (a non-ok response, or a
// thrown error) is swallowed rather than propagated - see the class's
// own comment for why none of this may ever be allowed to disrupt real
// playback over an admin-dashboard nicety.
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { EmbySessionService } from '../src/services/EmbySessionService';
import { EmbyClient } from '../src/emby/EmbyClient';
function okResponse(): Response {
return new Response(null, { status: 204 }) as unknown as Response;
}
describe('EmbySessionService', () => {
it('start() POSTs to /Sessions/Playing with the negotiated ids and the given position/pause state', async (t) => {
let capturedPath = '';
let capturedToken = '';
let capturedBody: unknown = null;
t.mock.method(EmbyClient, 'fetch', async (path: string, token: string, options: { body?: unknown }) => {
capturedPath = path;
capturedToken = token;
capturedBody = options.body;
return okResponse();
});
await EmbySessionService.start('tok1', 'item1', 'src1', 'play1', 12_345, false);
assert.equal(capturedPath, '/Sessions/Playing');
assert.equal(capturedToken, 'tok1');
assert.deepEqual(capturedBody, {
ItemId: 'item1',
MediaSourceId: 'src1',
PlaySessionId: 'play1',
PositionTicks: 12_345,
IsPaused: false,
PlayMethod: 'Transcode',
CanSeek: true
});
});
it('progress() POSTs to /Sessions/Playing/Progress', async (t) => {
let capturedPath = '';
t.mock.method(EmbyClient, 'fetch', async (path: string) => {
capturedPath = path;
return okResponse();
});
await EmbySessionService.progress('tok1', 'item1', 'src1', 'play1', 999, true);
assert.equal(capturedPath, '/Sessions/Playing/Progress');
});
it('stop() POSTs to /Sessions/Playing/Stopped', async (t) => {
let capturedPath = '';
let capturedBody: unknown = null;
t.mock.method(EmbyClient, 'fetch', async (path: string, _token: string, options: { body?: unknown }) => {
capturedPath = path;
capturedBody = options.body;
return okResponse();
});
await EmbySessionService.stop('tok1', 'item1', 'src1', 'play1', 42);
assert.equal(capturedPath, '/Sessions/Playing/Stopped');
assert.deepEqual(capturedBody, { ItemId: 'item1', MediaSourceId: 'src1', PlaySessionId: 'play1', PositionTicks: 42 });
});
it('rounds a fractional PositionTicks rather than sending a non-integer', async (t) => {
let capturedBody: { PositionTicks?: number } = {};
t.mock.method(EmbyClient, 'fetch', async (_path: string, _token: string, options: { body?: unknown }) => {
capturedBody = options.body as { PositionTicks?: number };
return okResponse();
});
await EmbySessionService.progress('tok1', 'item1', 'src1', 'play1', 12_345.6, false);
assert.equal(capturedBody.PositionTicks, 12_346);
});
it('a non-ok response is logged, not thrown', async (t) => {
t.mock.method(EmbyClient, 'fetch', async () => new Response(null, { status: 401 }) as unknown as Response);
await assert.doesNotReject(() => EmbySessionService.start('tok1', 'item1', 'src1', 'play1', 0, false));
});
it('a thrown network error is logged, not propagated', async (t) => {
t.mock.method(EmbyClient, 'fetch', async () => { throw new Error('network down'); });
await assert.doesNotReject(() => EmbySessionService.stop('tok1', 'item1', 'src1', 'play1', 0));
});
});