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>
176 lines
8.6 KiB
TypeScript
176 lines
8.6 KiB
TypeScript
// Exercises MusicQueueService directly against fake parties - no Express/
|
|
// session/Emby involved. Covers the intricate bits: auto-start on first
|
|
// add, server-authoritative auto-advance via a real timer, pause/resume
|
|
// elapsed-time math, majority vote-skip, and - given how strongly memory
|
|
// leaks have mattered throughout this project (see docs/architecture.md) -
|
|
// that the advance timer is ALWAYS cleared (never left dangling) on skip,
|
|
// on destroy, and is never double-scheduled.
|
|
import { describe, it, mock } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
import { MusicQueueService } from '../src/services/MusicQueueService';
|
|
import { PlaystateService } from '../src/services/PlaystateService';
|
|
import type { AppSocket, Party, PartyMember, MusicState } from '../src/types';
|
|
|
|
function fakeParty(id: string): Party {
|
|
return {
|
|
id,
|
|
mediaType: 'music',
|
|
itemId: '',
|
|
itemName: '',
|
|
itemImageUrl: '',
|
|
queue: [],
|
|
queueIndex: 0,
|
|
hostUserId: 'u-alice',
|
|
createdUtc: Date.now(),
|
|
lastActivityUtc: Date.now(),
|
|
members: new Map(),
|
|
burnInSubtitleIndex: null,
|
|
burnInAudioIndex: null,
|
|
textSubtitleIndex: null,
|
|
streamAudioIndex: null,
|
|
streamQuality: null
|
|
};
|
|
}
|
|
|
|
/** A connected member with a known token - the two things
|
|
* playNext's own markPlayed loop (and index.ts's periodic sweep) both
|
|
* gate on. Not used by most tests in this file at all: `fakeParty`'s
|
|
* own `members` map starts empty, and MusicQueueService's methods never
|
|
* populate it themselves (that's PartyService.join's job) - so unless a
|
|
* test explicitly adds one via this, playNext's markPlayed loop simply
|
|
* has nothing to iterate, same as an empty party in production. */
|
|
function fakeMember(userId: string, userName: string, embyToken: string): PartyMember {
|
|
return {
|
|
userId,
|
|
userName,
|
|
connection: {} as unknown as AppSocket,
|
|
deviceId: null,
|
|
embyToken,
|
|
isPaused: false,
|
|
positionTicks: 0,
|
|
lastUpdatedUtc: Date.now(),
|
|
embySession: null
|
|
};
|
|
}
|
|
|
|
function music(party: Party): MusicState {
|
|
return party.music as MusicState;
|
|
}
|
|
|
|
describe('MusicQueueService', () => {
|
|
it('init() auto-starts the first track and mirrors it onto party.itemName', () => {
|
|
const party = fakeParty('p1');
|
|
MusicQueueService.init(party, { itemId: 't1', itemName: 'Track One', itemImageUrl: '/img/t1', durationTicks: 10_000_000 }, 'u-alice', 'Alice');
|
|
|
|
assert.equal(music(party).current?.track.itemId, 't1');
|
|
assert.equal(music(party).queue.length, 0);
|
|
assert.equal(party.itemName, 'Track One');
|
|
});
|
|
|
|
it('adding a track while one plays queues it instead of jumping the gun', () => {
|
|
const party = fakeParty('p2');
|
|
MusicQueueService.init(party, { itemId: 't1', itemName: 'Track One', itemImageUrl: '/img/t1', durationTicks: 10_000_000 }, 'u-alice', 'Alice');
|
|
MusicQueueService.addTrack(party, { itemId: 't2', itemName: 'Track Two', itemImageUrl: '/img/t2', durationTicks: 30_000_000 }, 'u-bob', 'Bob');
|
|
|
|
assert.equal(music(party).current?.track.itemId, 't1');
|
|
assert.equal(music(party).queue.length, 1);
|
|
});
|
|
|
|
it('voteSkip needs a strict majority of connected members, not any count', () => {
|
|
const party = fakeParty('p3');
|
|
MusicQueueService.init(party, { itemId: 't1', itemName: 'Track One', itemImageUrl: '/img/t1', durationTicks: 10_000_000 }, 'u-alice', 'Alice');
|
|
MusicQueueService.addTrack(party, { itemId: 't2', itemName: 'Track Two', itemImageUrl: '/img/t2', durationTicks: 30_000_000 }, 'u-bob', 'Bob');
|
|
|
|
assert.equal(MusicQueueService.voteSkip(party, 'u-alice', 'Alice', 2), false, 'one of two needed should not skip yet');
|
|
assert.equal(music(party).current?.track.itemId, 't1');
|
|
|
|
assert.equal(MusicQueueService.voteSkip(party, 'u-bob', 'Bob', 2), true, 'the second vote should reach the majority');
|
|
assert.equal(music(party).current?.track.itemId, 't2');
|
|
assert.equal(music(party).skipVotes.size, 0, 'skipping clears the tally for the new track');
|
|
});
|
|
|
|
it('a skip marks the OUTGOING track Played for every connected member with a token, under their own account', (t) => {
|
|
const calls: [string, string, string][] = [];
|
|
t.mock.method(PlaystateService, 'markPlayed', async (embyToken: string, userId: string, itemId: string) => {
|
|
calls.push([embyToken, userId, itemId]);
|
|
});
|
|
|
|
const party = fakeParty('p3b');
|
|
party.members.set('u-alice', fakeMember('u-alice', 'Alice', 'tok-alice'));
|
|
party.members.set('u-bob', fakeMember('u-bob', 'Bob', 'tok-bob'));
|
|
MusicQueueService.init(party, { itemId: 't1', itemName: 'Track One', itemImageUrl: '/img/t1', durationTicks: 10_000_000 }, 'u-alice', 'Alice');
|
|
MusicQueueService.addTrack(party, { itemId: 't2', itemName: 'Track Two', itemImageUrl: '/img/t2', durationTicks: 30_000_000 }, 'u-bob', 'Bob');
|
|
assert.equal(calls.length, 0, 'starting the very first track has nothing outgoing to mark');
|
|
|
|
// connectedMemberCount=2 needs a strict majority (2) to actually
|
|
// skip - same arithmetic as the "needs a strict majority" test above.
|
|
MusicQueueService.voteSkip(party, 'u-alice', 'Alice', 2);
|
|
assert.equal(calls.length, 0, 'one vote of two is not a majority yet - nothing outgoing to mark');
|
|
MusicQueueService.voteSkip(party, 'u-bob', 'Bob', 2);
|
|
|
|
assert.deepEqual(calls.sort(), [['tok-alice', 'u-alice', 't1'], ['tok-bob', 'u-bob', 't1']].sort(), 'marks t1 (outgoing), not t2 (just started)');
|
|
});
|
|
|
|
it('never marks a member Played if they have no connection or no token yet', (t) => {
|
|
let called = false;
|
|
t.mock.method(PlaystateService, 'markPlayed', async () => { called = true; });
|
|
|
|
const party = fakeParty('p3c');
|
|
party.members.set('u-alice', { ...fakeMember('u-alice', 'Alice', 'tok-alice'), connection: null });
|
|
MusicQueueService.init(party, { itemId: 't1', itemName: 'Track One', itemImageUrl: '/img/t1', durationTicks: 10_000_000 }, 'u-alice', 'Alice');
|
|
MusicQueueService.addTrack(party, { itemId: 't2', itemName: 'Track Two', itemImageUrl: '/img/t2', durationTicks: 30_000_000 }, 'u-bob', 'Bob');
|
|
|
|
MusicQueueService.voteSkip(party, 'u-alice', 'Alice', 1);
|
|
|
|
assert.equal(called, false);
|
|
});
|
|
|
|
it('pause freezes elapsed time; resume continues it from where it froze', async () => {
|
|
const party = fakeParty('p4');
|
|
MusicQueueService.init(party, { itemId: 't1', itemName: 'Track One', itemImageUrl: '/img/t1', durationTicks: 600_000_000 }, 'u-alice', 'Alice');
|
|
|
|
MusicQueueService.setPaused(party, true);
|
|
assert.equal(music(party).current?.isPaused, true);
|
|
const frozen = MusicQueueService.getElapsedSeconds(party);
|
|
await sleep(50);
|
|
assert.equal(MusicQueueService.getElapsedSeconds(party), frozen, 'time must not advance while paused');
|
|
|
|
MusicQueueService.setPaused(party, false);
|
|
assert.equal(music(party).current?.isPaused, false);
|
|
await sleep(50);
|
|
assert.ok(MusicQueueService.getElapsedSeconds(party) >= frozen, 'time should advance again after resuming');
|
|
|
|
MusicQueueService.destroy(party); // avoid leaking this test's own long-duration timer
|
|
});
|
|
|
|
it('a short track auto-advances on its own via a real timer, with no client reporting "ended"', async () => {
|
|
const party = fakeParty('p5');
|
|
MusicQueueService.init(party, { itemId: 't1', itemName: 'Track One', itemImageUrl: '/img/t1', durationTicks: 10_000_000 /* 1s */ }, 'u-alice', 'Alice');
|
|
|
|
assert.notEqual(music(party).advanceTimer, null, 'a timer should be scheduled for the auto-advance');
|
|
await sleep(1300); // a bit over the 1s duration
|
|
assert.equal(music(party).current, null, 'nothing queued behind it, so current should now be empty');
|
|
});
|
|
|
|
it('destroy() clears a pending timer - the actual leak-prevention path', (t) => {
|
|
const realClearTimeout = global.clearTimeout;
|
|
const cleared = mock.fn(realClearTimeout);
|
|
global.clearTimeout = cleared as typeof clearTimeout;
|
|
t.after(() => { global.clearTimeout = realClearTimeout; });
|
|
|
|
const party = fakeParty('p6');
|
|
MusicQueueService.init(party, { itemId: 't1', itemName: 'Track One', itemImageUrl: '/img/t1', durationTicks: 600_000_000 /* 60s - stays pending */ }, 'u-alice', 'Alice');
|
|
assert.notEqual(music(party).advanceTimer, null);
|
|
|
|
MusicQueueService.destroy(party);
|
|
assert.equal(cleared.mock.callCount(), 1, 'clearTimeout should have been called exactly once');
|
|
assert.equal(music(party).advanceTimer, null);
|
|
});
|
|
|
|
it('removeVote() is a harmless no-op for a party with no music state at all', () => {
|
|
const videoParty: Party = { ...fakeParty('p7'), mediaType: 'video' };
|
|
delete videoParty.music;
|
|
assert.doesNotThrow(() => MusicQueueService.removeVote(videoParty, 'u-anyone'));
|
|
});
|
|
});
|