tv-discord: Discord bot + Activity for watching bug.tv together
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
ef7b44f074
36 files changed
+5841
No files matched your search
@@ -0,0 +1,99 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createRooms } = require('../src/room');
|
||||
const { createBotContext } = require('../src/bot');
|
||||
const { handleCommand } = require('../src/bot/commands');
|
||||
const { handleComponent } = require('../src/bot/controls');
|
||||
const { fakeBugtv, stream } = require('./helpers');
|
||||
|
||||
function fakeDiscord() {
|
||||
const edits = [];
|
||||
const voice = new Map([['u1', { id: 'u1', channelId: 'vc', member: { user: { bot: false } } }]]);
|
||||
const guild = { id: 'g', voiceStates: { cache: voice } };
|
||||
const text = { id: 't', guild, messages: { edit: async (id, p) => edits.push({ id, p }), delete: async () => {} } };
|
||||
const vc = { id: 'vc', guild };
|
||||
const channels = new Map([['vc', vc], ['t', text]]);
|
||||
const client = { channels: { cache: channels, fetch: async (id) => channels.get(id) }, users: { cache: new Map() } };
|
||||
return { client, guild, edits, voice };
|
||||
}
|
||||
|
||||
function interaction(guild, extra) {
|
||||
const calls = [];
|
||||
const rec = (name, ret) => async (arg) => {
|
||||
calls.push([name, arg]);
|
||||
return ret;
|
||||
};
|
||||
return {
|
||||
calls,
|
||||
guild,
|
||||
guildId: 'g',
|
||||
channelId: 't',
|
||||
user: { id: 'u1' },
|
||||
deferReply: rec('deferReply'),
|
||||
deferUpdate: rec('deferUpdate'),
|
||||
editReply: rec('editReply', { id: 'm1' }),
|
||||
reply: rec('reply'),
|
||||
update: rec('update'),
|
||||
followUp: rec('followUp'),
|
||||
showModal: rec('showModal'),
|
||||
isAnySelectMenu: () => false,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
test('/watch creates the room, posts the control message; buttons drive the room', async () => {
|
||||
const bugtv = fakeBugtv();
|
||||
const rooms = createRooms({}, { bugtv });
|
||||
const d = fakeDiscord();
|
||||
const ctx = createBotContext({}, rooms, d.client);
|
||||
ctx.updater.stop();
|
||||
|
||||
const w = interaction(d.guild, {
|
||||
commandName: 'watch',
|
||||
options: { getString: () => 'movie:550', getInteger: () => null },
|
||||
});
|
||||
await handleCommand(w, ctx);
|
||||
const room = rooms.get('vc');
|
||||
assert.ok(room);
|
||||
assert.equal(room.state.messageId, 'm1');
|
||||
assert.equal(room.voiceCount, 1);
|
||||
const payload = w.calls.find((c) => c[0] === 'editReply')[1];
|
||||
assert.equal(payload.embeds[0].title, 'Fight Club (1999)');
|
||||
assert.equal(payload.components.length, 5);
|
||||
|
||||
bugtv.last().h.onStreams({ provider: 'a', streams: [stream('a1'), stream('a2', { pixels: 720 })] });
|
||||
assert.equal(room.state.sourceId, 'a1');
|
||||
|
||||
const click = interaction(d.guild, { customId: 'tv:toggle:vc', message: { id: 'm1' } });
|
||||
await handleComponent(click, ctx);
|
||||
assert.equal(click.calls[0][0], 'deferUpdate');
|
||||
assert.equal(room.state.playing, true);
|
||||
|
||||
const sel = interaction(d.guild, { customId: 'tv:src:vc', message: { id: 'm1' }, values: ['a2'], isAnySelectMenu: () => true });
|
||||
await handleComponent(sel, ctx);
|
||||
assert.equal(room.state.sourceId, 'a2');
|
||||
|
||||
// user not in the VC → ephemeral error, no change
|
||||
d.voice.delete('u1');
|
||||
const out = interaction(d.guild, { customId: 'tv:toggle:vc', message: { id: 'm1' } });
|
||||
await handleComponent(out, ctx);
|
||||
assert.equal(out.calls[0][0], 'reply');
|
||||
assert.match(out.calls[0][1].content, /Join <#vc>/);
|
||||
assert.equal(room.state.playing, true);
|
||||
d.voice.set('u1', { id: 'u1', channelId: 'vc', member: { user: { bot: false } } });
|
||||
|
||||
// seek modal submit
|
||||
room.report({ duration: 1000 }, null);
|
||||
const form = interaction(d.guild, { customId: 'tv:seekForm:vc', fields: { getTextInputValue: () => '1:00' } });
|
||||
await handleComponent(form, ctx);
|
||||
assert.ok(Math.abs(room.clock() - 60) < 1);
|
||||
|
||||
// updater edits the message, then the final "Stopped" edit drops components
|
||||
await ctx.updater.flush(room);
|
||||
assert.ok(d.edits.length >= 1);
|
||||
await room.command('stop', {}, 'u1');
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
const last = d.edits[d.edits.length - 1];
|
||||
assert.deepEqual(last.p.components, []);
|
||||
assert.match(last.p.embeds[0].description, /Stopped/);
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
// Fake bug-tv client + controllable clock for room tests.
|
||||
|
||||
function fakeClock(start = Date.parse('2026-01-01T00:00:00Z')) {
|
||||
let now = start;
|
||||
let seq = 0;
|
||||
const timers = new Map();
|
||||
return {
|
||||
now: () => now,
|
||||
setTimeout(fn, ms) {
|
||||
const id = ++seq;
|
||||
timers.set(id, { at: now + ms, fn });
|
||||
return id;
|
||||
},
|
||||
clearTimeout(id) {
|
||||
timers.delete(id);
|
||||
},
|
||||
advance(ms) {
|
||||
const end = now + ms;
|
||||
for (;;) {
|
||||
let next = null;
|
||||
for (const [id, t] of timers) if (t.at <= end && (!next || t.at < next[1].at)) next = [id, t];
|
||||
if (!next) break;
|
||||
timers.delete(next[0]);
|
||||
now = next[1].at;
|
||||
next[1].fn();
|
||||
}
|
||||
now = end;
|
||||
},
|
||||
pending: () => timers.size,
|
||||
};
|
||||
}
|
||||
|
||||
function stream(id, o = {}) {
|
||||
return {
|
||||
id,
|
||||
provider: o.provider || 'p',
|
||||
name: o.name || `${id} name`,
|
||||
title: o.title || '',
|
||||
quality: o.pixels ? `${o.pixels}p` : '',
|
||||
pixels: o.pixels == null ? 1080 : o.pixels,
|
||||
type: o.type || 'm3u8',
|
||||
size: o.size || 0,
|
||||
seeds: o.seeds == null ? null : o.seeds,
|
||||
subtitles: o.subtitles || [],
|
||||
playback: { kind: o.kind || 'hls', url: `/v1/p/${id}/x.m3u8`, ...(o.fallback ? { fallback: `/v1/p/${id}/f` } : {}) },
|
||||
};
|
||||
}
|
||||
|
||||
const SHOW = {
|
||||
id: 1399,
|
||||
name: 'Show',
|
||||
first_air_date: '2011-04-17',
|
||||
poster_path: '/p.jpg',
|
||||
backdrop_path: '/b.jpg',
|
||||
overview: 'A show.',
|
||||
seasons: [
|
||||
{ season_number: 0, episode_count: 5, name: 'Specials' },
|
||||
{ season_number: 1, episode_count: 3, air_date: '2011-04-17' },
|
||||
{ season_number: 2, episode_count: 2, air_date: '2012-04-01' },
|
||||
],
|
||||
};
|
||||
const MOVIE = { id: 550, title: 'Fight Club', release_date: '1999-10-15', poster_path: '/fc.jpg', backdrop_path: '/fcb.jpg', overview: 'Soap.' };
|
||||
const ep = (n, air = '2011-01-01') => ({ episode_number: n, name: `Ep ${n}`, air_date: air, still_path: `/s${n}.jpg`, overview: `ep ${n}` });
|
||||
const SEASONS = { 0: [ep(1)], 1: [ep(1), ep(2), ep(3)], 2: [ep(1), ep(2)] };
|
||||
|
||||
function fakeBugtv() {
|
||||
const calls = { streams: [], prefetch: [] };
|
||||
return {
|
||||
calls,
|
||||
last: () => calls.streams[calls.streams.length - 1],
|
||||
streams(params, h) {
|
||||
calls.streams.push({ params, h });
|
||||
return new Promise(() => {}); // the test drives the handlers
|
||||
},
|
||||
async prefetch(params) {
|
||||
calls.prefetch.push(params);
|
||||
return { queued: [] };
|
||||
},
|
||||
async searchMulti() {
|
||||
return [];
|
||||
},
|
||||
async details(type) {
|
||||
return type === 'tv' ? SHOW : MOVIE;
|
||||
},
|
||||
async season(id, n) {
|
||||
return { season_number: n, episodes: SEASONS[n] || [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { fakeClock, fakeBugtv, stream, SHOW, MOVIE };
|
||||
@@ -0,0 +1,152 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createRooms } = require('../src/room');
|
||||
const { render, progressBar } = require('../src/bot/render');
|
||||
const { parseSeek } = require('../src/bot/controls');
|
||||
const { choiceFor } = require('../src/bot/autocomplete');
|
||||
const { fakeClock, fakeBugtv, stream } = require('./helpers');
|
||||
|
||||
async function bigRoom(media) {
|
||||
const clock = fakeClock();
|
||||
const bugtv = fakeBugtv();
|
||||
const rooms = createRooms({}, { bugtv, now: clock.now, setTimeout: clock.setTimeout, clearTimeout: clock.clearTimeout });
|
||||
const room = rooms.create({ id: '123456789012345678', guildId: 'g', textChannelId: 't' });
|
||||
await room.load(media);
|
||||
const h = bugtv.last().h;
|
||||
const streams = Array.from({ length: 60 }, (_, i) =>
|
||||
stream(`id${String(i).padStart(10, '0')}`, {
|
||||
pixels: [2160, 1080, 720, 480][i % 4],
|
||||
kind: ['hls', 'file', 'remux', 'torrent'][i % 4],
|
||||
provider: `provider-with-a-pretty-long-name-${i}`,
|
||||
name: 'X'.repeat(300),
|
||||
size: 2.1e9,
|
||||
seeds: 12,
|
||||
subtitles: Array.from({ length: 40 }, (_, j) => ({ url: `/v1/subs/${j}`, lang: 'en', label: `English ${'y'.repeat(150)} ${j}` })),
|
||||
}),
|
||||
);
|
||||
h.onStreams({ provider: 'p', streams });
|
||||
room.join('u1');
|
||||
room.report({ duration: 3500, levels: Array.from({ length: 30 }, (_, i) => ({ height: 144 + i * 40, bitrate: i * 1e5 })) }, 'u1');
|
||||
return { room, clock };
|
||||
}
|
||||
|
||||
function checkLimits(out) {
|
||||
assert.ok(out.components.length <= 5, 'max 5 rows');
|
||||
const ids = new Set();
|
||||
for (const row of out.components) {
|
||||
assert.equal(row.type, 1);
|
||||
assert.ok(row.components.length >= 1 && row.components.length <= 5);
|
||||
const selects = row.components.filter((c) => c.type === 3);
|
||||
if (selects.length) assert.equal(row.components.length, 1, 'select alone in its row');
|
||||
for (const c of row.components) {
|
||||
assert.ok(c.custom_id.length <= 100);
|
||||
assert.ok(!ids.has(c.custom_id), `duplicate ${c.custom_id}`);
|
||||
ids.add(c.custom_id);
|
||||
if (c.type === 2 && c.label) assert.ok(c.label.length <= 80);
|
||||
if (c.type === 3) {
|
||||
assert.ok(c.options.length >= 1 && c.options.length <= 25, `${c.custom_id} has ${c.options.length}`);
|
||||
assert.ok(c.placeholder.length <= 150);
|
||||
const values = new Set();
|
||||
let defaults = 0;
|
||||
for (const o of c.options) {
|
||||
assert.ok(o.label.length >= 1 && o.label.length <= 100);
|
||||
assert.ok(o.value.length <= 100);
|
||||
if (o.description) assert.ok(o.description.length <= 100);
|
||||
assert.ok(!values.has(o.value), 'unique values');
|
||||
values.add(o.value);
|
||||
if (o.default) defaults++;
|
||||
}
|
||||
assert.ok(defaults <= 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
const e = out.embeds[0];
|
||||
assert.ok(e.title.length <= 256);
|
||||
assert.ok(e.description.length <= 4096);
|
||||
}
|
||||
|
||||
test('render: movie with 60 sources stays within Discord limits, pages sources', async () => {
|
||||
const { room, clock } = await bigRoom({ type: 'movie', tmdb: 550 });
|
||||
const out = render(room.state, {}, clock.now());
|
||||
checkLimits(out);
|
||||
assert.equal(out.components.length, 5);
|
||||
const src = out.components[2].components[0];
|
||||
assert.equal(src.custom_id, `tv:src:${room.id}`);
|
||||
assert.equal(src.options.length, 25);
|
||||
assert.equal(src.options[24].value, 'page:1');
|
||||
assert.ok(src.options.some((o) => o.default && o.value === room.state.sourceId));
|
||||
assert.match(src.options[0].label, /^4K · HLS · provider-with-a-pretty-long-name-0 · 2\.1 GB$/);
|
||||
const page2 = render(room.state, { srcPage: 2 }, clock.now());
|
||||
checkLimits(page2);
|
||||
const last = page2.components[2].components[0].options;
|
||||
assert.equal(last.length, 13);
|
||||
assert.equal(last[12].value, 'page:0');
|
||||
// buttons: row1 has 5, row2 movie has 4 (no episodes button), prev/next disabled
|
||||
assert.equal(out.components[0].components.length, 5);
|
||||
const row2 = out.components[1].components;
|
||||
assert.deepEqual(
|
||||
row2.map((c) => c.custom_id.split(':')[1]),
|
||||
['prev', 'next', 'launch', 'stop'],
|
||||
);
|
||||
assert.equal(row2[2].style, 1);
|
||||
assert.equal(row2[3].style, 4);
|
||||
assert.equal(out.components[3].components[0].options.length, 25, 'subtitles capped');
|
||||
assert.equal(out.components[4].components[0].disabled, undefined, 'quality enabled once levels reported');
|
||||
assert.match(out.embeds[0].description, /🔘.*0:00 \/ 58:20/);
|
||||
assert.ok(out.embeds[0].image.url.includes('/w1280/'));
|
||||
});
|
||||
|
||||
test('render: series episodes mode swaps in season/episode selects', async () => {
|
||||
const { room, clock } = await bigRoom({ type: 'tv', tmdb: 1399, season: 1, episode: 2 });
|
||||
const out = render(room.state, { mode: 'sources' }, clock.now());
|
||||
checkLimits(out);
|
||||
assert.ok(out.components[1].components.some((c) => c.custom_id === `tv:episodes:${room.id}`));
|
||||
const ep = render(room.state, { mode: 'episodes', seasonData: {} }, clock.now());
|
||||
checkLimits(ep);
|
||||
assert.equal(ep.components.length, 4);
|
||||
assert.equal(ep.components[2].components[0].custom_id, `tv:season:${room.id}`);
|
||||
assert.equal(ep.components[3].components[0].custom_id, `tv:ep:${room.id}`);
|
||||
assert.ok(ep.components[1].components.some((c) => c.custom_id === `tv:sources:${room.id}`));
|
||||
assert.match(out.embeds[0].description, /\*\*S1E2 · Ep 2\*\*/);
|
||||
// a long season pages around the current episode
|
||||
room.state.media.seasons = [{ n: 1, count: 200 }];
|
||||
room.state.media.episode = 100;
|
||||
const long = render(room.state, { mode: 'episodes', seasonData: {} }, clock.now());
|
||||
checkLimits(long);
|
||||
const opts = long.components[3].components[0].options;
|
||||
assert.equal(opts.length, 25);
|
||||
assert.match(opts[0].value, /^page:/);
|
||||
assert.match(opts[24].value, /^page:/);
|
||||
assert.ok(opts.some((o) => o.value === '100' && o.default));
|
||||
});
|
||||
|
||||
test('render: closed state has no components; empty room is fine', async () => {
|
||||
const { room, clock } = await bigRoom({ type: 'movie', tmdb: 550 });
|
||||
const out = render(room.state, {}, clock.now(), { closed: true });
|
||||
assert.deepEqual(out.components, []);
|
||||
assert.match(out.embeds[0].description, /Stopped/);
|
||||
const rooms = createRooms({}, { bugtv: fakeBugtv() });
|
||||
const empty = rooms.create({ id: 'x' });
|
||||
assert.deepEqual(render(empty.state).components, []);
|
||||
});
|
||||
|
||||
test('progress bar and seek parsing', () => {
|
||||
assert.equal(progressBar(50, 100), '▬▬▬▬▬🔘▬▬▬▬▬');
|
||||
assert.equal(progressBar(0, 0), '🔘▬▬▬▬▬▬▬▬▬▬');
|
||||
assert.deepEqual(parseSeek('1:23:45'), { op: 'seek', t: 5025 });
|
||||
assert.deepEqual(parseSeek('83m'), { op: 'seek', t: 4980 });
|
||||
assert.deepEqual(parseSeek('45%', 1000), { op: 'seek', t: 450 });
|
||||
assert.equal(parseSeek('45%', 0), null);
|
||||
assert.deepEqual(parseSeek('90s'), { op: 'seek', t: 90 });
|
||||
assert.deepEqual(parseSeek('90'), { op: 'seek', t: 90 });
|
||||
assert.deepEqual(parseSeek('-30'), { op: 'seekBy', d: -30 });
|
||||
assert.equal(parseSeek('soon'), null);
|
||||
});
|
||||
|
||||
test('autocomplete choice format', () => {
|
||||
assert.deepEqual(choiceFor({ type: 'tv', id: 1399, title: 'Game of Thrones', year: '2011' }), {
|
||||
name: 'Game of Thrones (2011) · Series',
|
||||
value: 'tv:1399',
|
||||
});
|
||||
assert.equal(choiceFor({ type: 'movie', id: 1, title: 'x'.repeat(200), year: '' }).name.length, 100);
|
||||
});
|
||||
@@ -0,0 +1,273 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createRooms, rank, scoreStream, clockOf, GRACE_MS, IDLE_MS } = require('../src/room');
|
||||
const { fakeClock, fakeBugtv, stream } = require('./helpers');
|
||||
|
||||
function setup() {
|
||||
const clock = fakeClock();
|
||||
const bugtv = fakeBugtv();
|
||||
const rooms = createRooms({}, { bugtv, now: clock.now, setTimeout: clock.setTimeout, clearTimeout: clock.clearTimeout });
|
||||
const room = rooms.create({ id: 'vc1', guildId: 'g1', textChannelId: 't1' });
|
||||
const events = [];
|
||||
room.on('change', (state, reason) => events.push(reason));
|
||||
return { clock, bugtv, rooms, room, events };
|
||||
}
|
||||
|
||||
const flush = () => new Promise((r) => setImmediate(r));
|
||||
|
||||
async function loaded(media = { type: 'movie', tmdb: 550 }) {
|
||||
const ctx = setup();
|
||||
await ctx.room.load(media);
|
||||
ctx.h = ctx.bugtv.last().h;
|
||||
ctx.h.onMeta({ providers: ['a', 'b', 'c'] });
|
||||
return ctx;
|
||||
}
|
||||
|
||||
test('ranking: 4K compressed, remux/torrent penalties, direct bonus, last provider', () => {
|
||||
const s4kTorrent = stream('t', { pixels: 2160, kind: 'torrent', seeds: 50 });
|
||||
const s1080hls = stream('h', { pixels: 1080 });
|
||||
const s1080remux = stream('r', { pixels: 1080, kind: 'remux' });
|
||||
const s720direct = stream('d', { pixels: 720, fallback: true });
|
||||
const sNoPx = stream('n', { pixels: 0 });
|
||||
const bad = { id: 'x', playback: { kind: 'weird', url: 'u' } };
|
||||
assert.equal(scoreStream(s4kTorrent), 1150 - 270);
|
||||
assert.equal(scoreStream(sNoPx), 400);
|
||||
assert.equal(scoreStream(s720direct), 760);
|
||||
assert.deepEqual(
|
||||
rank([sNoPx, s720direct, s1080remux, s4kTorrent, bad, s1080hls]).map((s) => s.id),
|
||||
['h', 'r', 't', 'd', 'n'],
|
||||
);
|
||||
assert.equal(rank([s1080hls, stream('h2', { pixels: 1080, provider: 'fav' })], 'fav')[0].id, 'h2');
|
||||
});
|
||||
|
||||
test('auto-pick: ≥1080p hls picks at once', async () => {
|
||||
const { h, room, events } = await loaded();
|
||||
h.onStreams({ provider: 'a', streams: [stream('a1', { pixels: 1080, provider: 'a' })] });
|
||||
assert.equal(room.state.sourceId, 'a1');
|
||||
assert.ok(events.includes('source'));
|
||||
});
|
||||
|
||||
test('auto-pick: lower quality waits the 1.5s grace window and takes the best by then', async () => {
|
||||
const { h, room, clock } = await loaded();
|
||||
h.onStreams({ provider: 'a', streams: [stream('a1', { pixels: 720, provider: 'a' })] });
|
||||
assert.equal(room.state.sourceId, null);
|
||||
clock.advance(GRACE_MS - 100);
|
||||
h.onStreams({ provider: 'b', streams: [stream('b1', { pixels: 1080, kind: 'remux', provider: 'b' })] });
|
||||
assert.equal(room.state.sourceId, null, '1080p remux is not a fast pick');
|
||||
clock.advance(100);
|
||||
assert.equal(room.state.sourceId, 'b1');
|
||||
// later better sources don't steal the pick
|
||||
h.onStreams({ provider: 'c', streams: [stream('c1', { pixels: 2160, provider: 'c' })] });
|
||||
assert.equal(room.state.sourceId, 'b1');
|
||||
assert.equal(room.state.sources[0].id, 'c1');
|
||||
});
|
||||
|
||||
test('auto-pick: nothing playable until done → picks on done, or notice when empty', async () => {
|
||||
const a = await loaded();
|
||||
a.h.onDone({ total: 0 });
|
||||
assert.equal(a.room.state.sourceId, null);
|
||||
assert.equal(a.room.state.scraping, false);
|
||||
assert.match(a.room.state.notice, /No sources/);
|
||||
});
|
||||
|
||||
test('clock math: play / pause / seek / seekBy / clamp', async () => {
|
||||
const { h, room, clock } = await loaded();
|
||||
h.onStreams({ provider: 'a', streams: [stream('a1')] });
|
||||
assert.equal(room.state.playing, false, 'no viewers yet → paused');
|
||||
room.join('u1');
|
||||
assert.equal(room.state.playing, true, 'first viewer starts autoplay');
|
||||
clock.advance(10_000);
|
||||
assert.equal(room.clock(), 10);
|
||||
await room.command('pause', {}, 'u1');
|
||||
clock.advance(5000);
|
||||
assert.equal(room.clock(), 10);
|
||||
await room.command('seek', { t: 100 }, 'u1');
|
||||
assert.equal(room.clock(), 100);
|
||||
await room.command('seekBy', { d: -30 }, 'u1');
|
||||
assert.equal(room.clock(), 70);
|
||||
await room.command('seekBy', { d: -300 }, 'u1');
|
||||
assert.equal(room.clock(), 0);
|
||||
await room.command('toggle', {}, 'u1');
|
||||
clock.advance(2500);
|
||||
assert.equal(room.clock(), 2.5);
|
||||
room.report({ duration: 60 }, 'u1');
|
||||
clock.advance(120_000);
|
||||
assert.equal(room.clock(), 60, 'clamped to duration');
|
||||
assert.equal(clockOf({ position: 5, playing: true, updatedAt: 0, duration: 0 }, 3000), 8);
|
||||
});
|
||||
|
||||
test('failover on fatal error from the leader only, with notice', async () => {
|
||||
const { h, room } = await loaded();
|
||||
h.onStreams({ provider: 'a', streams: [stream('a1', { provider: 'a' }), stream('a2', { pixels: 720, provider: 'a' })] });
|
||||
room.join('leader');
|
||||
room.join('other');
|
||||
assert.equal(room.state.leader, 'leader');
|
||||
assert.equal(room.report({ error: { fatal: true, message: 'boom' } }, 'other'), false);
|
||||
assert.equal(room.state.sourceId, 'a1');
|
||||
room.report({ error: { fatal: false, message: 'meh' } }, 'leader');
|
||||
assert.equal(room.state.sourceId, 'a1');
|
||||
room.report({ error: { fatal: true, message: 'boom' } }, 'leader');
|
||||
assert.equal(room.state.sourceId, 'a2');
|
||||
assert.deepEqual(room.state.failed, ['a1']);
|
||||
assert.match(room.state.notice, /a 1080p failed.*trying a 720p/);
|
||||
// stale report about the old source is ignored
|
||||
assert.equal(room.report({ sourceId: 'a1', error: { fatal: true } }, 'leader'), false);
|
||||
// last one fails while scraping → waits, then the next arriving stream is taken at once
|
||||
room.report({ error: { fatal: true } }, 'leader');
|
||||
assert.equal(room.state.sourceId, null);
|
||||
assert.match(room.state.notice, /waiting/);
|
||||
h.onStreams({ provider: 'b', streams: [stream('b1', { pixels: 480, provider: 'b' })] });
|
||||
assert.equal(room.state.sourceId, 'b1');
|
||||
});
|
||||
|
||||
test('leader re-election on leave; multiple connections per user', async () => {
|
||||
const { room } = setup();
|
||||
room.join('u1');
|
||||
room.join('u2');
|
||||
room.join('u1'); // second device
|
||||
assert.deepEqual(room.state.viewers, ['u1', 'u2']);
|
||||
room.leave('u1');
|
||||
assert.equal(room.state.leader, 'u1', 'still connected once');
|
||||
room.leave('u1');
|
||||
assert.equal(room.state.leader, 'u2');
|
||||
assert.deepEqual(room.state.viewers, ['u2']);
|
||||
room.leave('u2');
|
||||
assert.equal(room.state.leader, null);
|
||||
room.join('u3');
|
||||
assert.equal(room.state.leader, 'u3');
|
||||
});
|
||||
|
||||
test('next / prev across seasons, skipping season 0', async () => {
|
||||
const { room, bugtv } = await loaded({ type: 'tv', tmdb: 1399, season: 1, episode: 3 });
|
||||
assert.deepEqual(room.state.media.seasons, [{ n: 1, count: 3 }, { n: 2, count: 2 }]);
|
||||
assert.equal(room.state.media.episodeTitle, 'Ep 3');
|
||||
let r = await room.command('next', {}, 'u');
|
||||
assert.ok(r.ok);
|
||||
assert.deepEqual([room.state.media.season, room.state.media.episode], [2, 1]);
|
||||
assert.deepEqual(bugtv.last().params, { tmdb: 1399, type: 'tv', season: 2, episode: 1 });
|
||||
await room.command('prev', {}, 'u');
|
||||
assert.deepEqual([room.state.media.season, room.state.media.episode], [1, 3]);
|
||||
await room.command('episode', { season: 1, episode: 1 }, 'u');
|
||||
r = await room.command('prev', {}, 'u');
|
||||
assert.equal(r.ok, false, 'S1E1 has no previous (season 0 skipped)');
|
||||
await room.command('episode', { season: 2, episode: 2 }, 'u');
|
||||
r = await room.command('next', {}, 'u');
|
||||
assert.equal(r.ok, false);
|
||||
});
|
||||
|
||||
test('prefetch next episode once at 80%; ended → next episode', async () => {
|
||||
const { h, room, bugtv, clock } = await loaded({ type: 'tv', tmdb: 1399, season: 1, episode: 2 });
|
||||
h.onStreams({ provider: 'a', streams: [stream('a1')] });
|
||||
room.join('u1');
|
||||
room.report({ duration: 100 }, 'u1');
|
||||
clock.advance(79_000);
|
||||
room.report({ position: 79 }, 'u1');
|
||||
await flush();
|
||||
assert.equal(bugtv.calls.prefetch.length, 0);
|
||||
clock.advance(2000);
|
||||
room.report({ position: 81 }, 'u1');
|
||||
await flush();
|
||||
clock.advance(5000);
|
||||
room.report({ position: 86 }, 'u1');
|
||||
await flush();
|
||||
assert.deepEqual(bugtv.calls.prefetch, [{ tmdb: 1399, type: 'tv', season: 1, episode: 3 }]);
|
||||
room.report({ ended: true }, 'u1');
|
||||
await flush();
|
||||
await flush();
|
||||
assert.equal(room.state.media.episode, 3);
|
||||
assert.equal(room.state.sourceId, null);
|
||||
bugtv.last().h.onStreams({ provider: 'a', streams: [stream('e3')] });
|
||||
assert.equal(room.state.sourceId, 'e3');
|
||||
assert.equal(room.state.playing, true, 'keeps playing into the next episode');
|
||||
assert.equal(room.clock(), 0);
|
||||
});
|
||||
|
||||
test('movie ended pauses at the end', async () => {
|
||||
const { h, room } = await loaded();
|
||||
h.onStreams({ provider: 'a', streams: [stream('a1')] });
|
||||
room.join('u1');
|
||||
room.report({ duration: 50 }, 'u1');
|
||||
room.report({ ended: true }, 'u1');
|
||||
assert.equal(room.state.playing, false);
|
||||
assert.equal(room.clock(), 50);
|
||||
});
|
||||
|
||||
test('drift correction from leader heartbeat, ignored right after a seek', async () => {
|
||||
const { h, room, clock } = await loaded();
|
||||
h.onStreams({ provider: 'a', streams: [stream('a1')] });
|
||||
room.join('u1');
|
||||
clock.advance(20_000);
|
||||
room.report({ position: 15 }, 'u1'); // leader buffered for 5s
|
||||
assert.equal(room.clock(), 15);
|
||||
await room.command('seek', { t: 500 }, 'u1');
|
||||
clock.advance(1000);
|
||||
room.report({ position: 16 }, 'u1'); // heartbeat sent before the seek landed
|
||||
assert.equal(room.clock(), 501);
|
||||
});
|
||||
|
||||
test('idle close after 2 minutes at zero voice members', async () => {
|
||||
const { room, rooms, clock } = await loaded();
|
||||
let closed = null;
|
||||
room.on('closed', (state, reason) => (closed = reason));
|
||||
room.setVoiceCount(0);
|
||||
clock.advance(IDLE_MS - 1000);
|
||||
room.setVoiceCount(1);
|
||||
clock.advance(IDLE_MS);
|
||||
assert.equal(closed, null);
|
||||
room.setVoiceCount(0);
|
||||
clock.advance(IDLE_MS);
|
||||
assert.equal(closed, 'idle');
|
||||
assert.equal(rooms.get('vc1'), null);
|
||||
const r = await room.command('play', {}, 'u');
|
||||
assert.equal(r.ok, false);
|
||||
});
|
||||
|
||||
test('stop closes the room and aborts the scrape', async () => {
|
||||
const { room, rooms, bugtv } = await loaded();
|
||||
let closed = null;
|
||||
room.on('closed', (s, reason) => (closed = reason));
|
||||
await room.command('stop', {}, 'u');
|
||||
assert.equal(closed, 'stop');
|
||||
assert.equal(bugtv.last().h.signal.aborted, true);
|
||||
assert.equal(rooms.get('vc1'), null);
|
||||
});
|
||||
|
||||
test('subtitle / quality validation and rev increments', async () => {
|
||||
const { h, room } = await loaded();
|
||||
h.onStreams({ provider: 'a', streams: [stream('a1', { subtitles: [{ url: '/v1/subs/x', lang: 'en', label: 'English' }] })] });
|
||||
room.join('u1');
|
||||
const rev = room.state.rev;
|
||||
assert.equal((await room.command('subtitle', { index: 0 }, 'u1')).ok, true);
|
||||
assert.equal((await room.command('subtitle', { index: 3 }, 'u1')).ok, false);
|
||||
assert.equal((await room.command('quality', { index: 1 }, 'u1')).ok, false);
|
||||
room.report({ levels: [{ height: 720, bitrate: 3e6 }, { height: 1080, bitrate: 6e6 }] }, 'u1');
|
||||
assert.equal((await room.command('quality', { index: 1 }, 'u1')).ok, true);
|
||||
assert.ok(room.state.rev > rev);
|
||||
});
|
||||
|
||||
test('publicState shape', async () => {
|
||||
const { h, room, clock } = await loaded();
|
||||
h.onStreams({ provider: 'a', streams: [stream('a1')] });
|
||||
room.join('u1');
|
||||
const ps = room.publicState(clock.now());
|
||||
for (const k of ['media', 'stream', 'subtitle', 'quality', 'playing', 'position', 'updatedAt', 'now', 'duration', 'viewers', 'leader', 'rev', 'notice']) {
|
||||
assert.ok(k in ps, k);
|
||||
}
|
||||
assert.equal(ps.stream.id, 'a1');
|
||||
assert.equal(ps.now, clock.now());
|
||||
assert.equal(ps.media.title, 'Fight Club');
|
||||
assert.equal(ps.media.poster, 'https://image.tmdb.org/t/p/w500/fc.jpg');
|
||||
assert.deepEqual(ps.viewers, ['u1']);
|
||||
assert.equal(ps.leader, 'u1');
|
||||
});
|
||||
|
||||
test('rooms registry emits create and reuses rooms', () => {
|
||||
const { rooms, room } = setup();
|
||||
let created = 0;
|
||||
rooms.on('created', () => created++);
|
||||
assert.equal(rooms.create({ id: 'vc1', textChannelId: 't2' }), room);
|
||||
assert.equal(room.state.textChannelId, 't2');
|
||||
rooms.create({ id: 'vc2' });
|
||||
assert.equal(created, 1);
|
||||
assert.equal(rooms.all().length, 2);
|
||||
});
|
||||
@@ -0,0 +1,378 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { EventEmitter } = require('events');
|
||||
const WebSocket = require('ws');
|
||||
const { createServer } = require('../src/server');
|
||||
|
||||
/* ---- fakes ----------------------------------------------------------------- */
|
||||
|
||||
class FakeRoom extends EventEmitter {
|
||||
constructor(id) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.calls = [];
|
||||
this.viewers = new Set();
|
||||
this.rev = 0;
|
||||
this.media = { type: 'movie', tmdb: 550, title: 'Fight Club' };
|
||||
}
|
||||
join(u) {
|
||||
this.calls.push(['join', u]);
|
||||
this.viewers.add(u);
|
||||
}
|
||||
leave(u) {
|
||||
this.calls.push(['leave', u]);
|
||||
this.viewers.delete(u);
|
||||
}
|
||||
command(op, args, u) {
|
||||
this.calls.push(['command', op, args, u]);
|
||||
this.rev++;
|
||||
this.emit('change', {}, op);
|
||||
}
|
||||
report(data, u) {
|
||||
this.calls.push(['report', data, u]);
|
||||
}
|
||||
publicState(now = Date.now()) {
|
||||
return { media: this.media, stream: null, playing: false, position: 0, updatedAt: now, now, viewers: [...this.viewers], leader: null, rev: this.rev, notice: null };
|
||||
}
|
||||
}
|
||||
|
||||
function fakeRooms({ events = false } = {}) {
|
||||
const map = new Map();
|
||||
const rooms = events ? new EventEmitter() : {};
|
||||
rooms.get = (id) => map.get(id);
|
||||
rooms.create = ({ id }) => {
|
||||
const r = new FakeRoom(id);
|
||||
map.set(id, r);
|
||||
if (events) rooms.emit('created', r);
|
||||
return r;
|
||||
};
|
||||
rooms.delete = (id) => map.delete(id);
|
||||
rooms.all = () => [...map.values()];
|
||||
return rooms;
|
||||
}
|
||||
|
||||
const USERS = { good: { id: '111', username: 'alice' }, bob: { id: '222', username: 'bob' } };
|
||||
|
||||
function fakeDiscord() {
|
||||
const calls = [];
|
||||
const fn = async (url, init = {}) => {
|
||||
calls.push([url, init]);
|
||||
const res = (status, body) => ({ ok: status < 300, status, json: async () => body });
|
||||
if (url.endsWith('/oauth2/token')) {
|
||||
const p = new URLSearchParams(init.body);
|
||||
if (p.get('code') === 'goodcode' && p.get('client_secret') === 'sekrit' && p.get('grant_type') === 'authorization_code') {
|
||||
return res(200, { access_token: 'good', token_type: 'Bearer' });
|
||||
}
|
||||
return res(400, { error: 'invalid_grant' });
|
||||
}
|
||||
if (url.endsWith('/users/@me')) {
|
||||
const tok = (init.headers.Authorization || '').replace('Bearer ', '');
|
||||
return USERS[tok] ? res(200, USERS[tok]) : res(401, { message: '401: Unauthorized' });
|
||||
}
|
||||
return res(404, {});
|
||||
};
|
||||
fn.calls = calls;
|
||||
return fn;
|
||||
}
|
||||
|
||||
/* ---- harness --------------------------------------------------------------- */
|
||||
|
||||
const activityDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tvd-act-'));
|
||||
fs.writeFileSync(path.join(activityDir, 'index.html'), '<!doctype html><title>x</title>');
|
||||
fs.mkdirSync(path.join(activityDir, 'dist'));
|
||||
fs.writeFileSync(path.join(activityDir, 'dist', 'main.js'), 'console.log(1)');
|
||||
|
||||
async function start(opts = {}) {
|
||||
const rooms = opts.rooms || fakeRooms();
|
||||
const discordFetch = fakeDiscord();
|
||||
const voice = opts.voice || { '42': new Set(['111', '222']) };
|
||||
const cfg = { applicationId: 'app1', clientSecret: 'sekrit', activityDir, dev: !!opts.dev };
|
||||
const server = createServer(cfg, rooms, {
|
||||
isInVoice: async (c, u) => !!(voice[c] && voice[c].has(u)),
|
||||
discordFetch,
|
||||
log: () => {},
|
||||
});
|
||||
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
const sockets = [];
|
||||
const open = (p = '/ws') => {
|
||||
const ws = new WebSocket(base.replace('http', 'ws') + p);
|
||||
sockets.push(ws);
|
||||
const queue = [];
|
||||
const waiters = [];
|
||||
ws.on('message', (d) => {
|
||||
const m = JSON.parse(d);
|
||||
const i = waiters.findIndex((w) => w.pred(m));
|
||||
if (i >= 0) waiters.splice(i, 1)[0].resolve(m);
|
||||
else queue.push(m);
|
||||
});
|
||||
ws.next = (pred = () => true, ms = 3000) => {
|
||||
const i = queue.findIndex(pred);
|
||||
if (i >= 0) return Promise.resolve(queue.splice(i, 1)[0]);
|
||||
return new Promise((resolve, reject) => {
|
||||
const w = { pred, resolve };
|
||||
waiters.push(w);
|
||||
setTimeout(() => {
|
||||
const j = waiters.indexOf(w);
|
||||
if (j < 0) return;
|
||||
waiters.splice(j, 1);
|
||||
reject(new Error('timeout waiting for message'));
|
||||
}, ms).unref();
|
||||
});
|
||||
};
|
||||
ws.closed = new Promise((r) => ws.on('close', (code) => r(code)));
|
||||
ws.opened = new Promise((r, j) => {
|
||||
ws.on('open', r);
|
||||
ws.on('error', j);
|
||||
});
|
||||
ws.json = (m) => ws.send(JSON.stringify(m));
|
||||
return ws;
|
||||
};
|
||||
const stop = async () => {
|
||||
for (const ws of sockets) ws.terminate();
|
||||
await new Promise((r) => server.close(r));
|
||||
};
|
||||
return { server, rooms, discordFetch, base, open, stop };
|
||||
}
|
||||
|
||||
const tick = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
/* ---- http ------------------------------------------------------------------ */
|
||||
|
||||
test('static files, SPA fallback, config, healthz', async () => {
|
||||
const h = await start();
|
||||
try {
|
||||
let r = await fetch(`${h.base}/`);
|
||||
assert.equal(r.status, 200);
|
||||
assert.match(r.headers.get('content-type'), /text\/html/);
|
||||
assert.equal(r.headers.get('cache-control'), 'no-cache');
|
||||
r = await fetch(`${h.base}/dist/main.js`);
|
||||
assert.match(r.headers.get('content-type'), /javascript/);
|
||||
assert.match(r.headers.get('cache-control'), /max-age/);
|
||||
r = await fetch(`${h.base}/.proxy/dist/main.js`);
|
||||
assert.equal(r.status, 200);
|
||||
r = await fetch(`${h.base}/some/route`);
|
||||
assert.equal(r.status, 200);
|
||||
assert.match(await r.text(), /<title>x/);
|
||||
r = await fetch(`${h.base}/missing.js`);
|
||||
assert.equal(r.status, 404);
|
||||
r = await fetch(`${h.base}/..%2f..%2fetc%2fpasswd`);
|
||||
assert.notEqual(await r.text(), fs.readFileSync('/etc/passwd', 'utf8'));
|
||||
r = await fetch(`${h.base}/api/config`);
|
||||
assert.deepEqual(await r.json(), { applicationId: 'app1', dev: false });
|
||||
r = await fetch(`${h.base}/healthz`);
|
||||
assert.deepEqual(await r.json(), { ok: true });
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('POST /api/token exchanges the code with Discord', async () => {
|
||||
const h = await start();
|
||||
try {
|
||||
let r = await fetch(`${h.base}/api/token`, { method: 'POST', body: JSON.stringify({ code: 'goodcode' }) });
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(await r.json(), { access_token: 'good' });
|
||||
const [url, init] = h.discordFetch.calls[0];
|
||||
assert.equal(url, 'https://discord.com/api/oauth2/token');
|
||||
const p = new URLSearchParams(init.body);
|
||||
assert.equal(p.get('client_id'), 'app1');
|
||||
r = await fetch(`${h.base}/api/token`, { method: 'POST', body: JSON.stringify({ code: 'bad' }) });
|
||||
assert.equal(r.status, 502);
|
||||
r = await fetch(`${h.base}/api/token`, { method: 'POST', body: '{}' });
|
||||
assert.equal(r.status, 400);
|
||||
r = await fetch(`${h.base}/api/token`, { method: 'POST', body: 'nope' });
|
||||
assert.equal(r.status, 400);
|
||||
r = await fetch(`${h.base}/api/token`);
|
||||
assert.equal(r.status, 405);
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
|
||||
/* ---- websocket ------------------------------------------------------------- */
|
||||
|
||||
test('hello: bad token → error + close; not in voice → error + close', async () => {
|
||||
const h = await start();
|
||||
try {
|
||||
const a = h.open();
|
||||
await a.opened;
|
||||
a.json({ t: 'hello', token: 'nope', channelId: '42' });
|
||||
assert.equal((await a.next((m) => m.t === 'error')).message, 'authentication failed');
|
||||
assert.equal(await a.closed, 4001);
|
||||
|
||||
const b = h.open();
|
||||
await b.opened;
|
||||
b.json({ t: 'hello', token: 'good', channelId: '99' });
|
||||
assert.match((await b.next((m) => m.t === 'error')).message, /voice/);
|
||||
assert.equal(await b.closed, 4001);
|
||||
|
||||
// dev hello is refused unless cfg.dev
|
||||
const c = h.open();
|
||||
await c.opened;
|
||||
c.json({ t: 'hello', dev: true, userId: '111', channelId: '42' });
|
||||
await c.next((m) => m.t === 'error');
|
||||
assert.equal(await c.closed, 4001);
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('hello success joins the room; users/@me is cached; leave on close', async () => {
|
||||
const h = await start();
|
||||
const room = h.rooms.create({ id: '42' });
|
||||
try {
|
||||
const a = h.open();
|
||||
await a.opened;
|
||||
a.json({ t: 'hello', token: 'good', channelId: '42' });
|
||||
const w = await a.next((m) => m.t === 'welcome');
|
||||
assert.deepEqual(w.user, { id: '111', username: 'alice' });
|
||||
assert.equal(w.state.media.title, 'Fight Club');
|
||||
assert.deepEqual(room.calls, [['join', '111']]);
|
||||
|
||||
// second socket for the same user: no second join, cached /users/@me
|
||||
const a2 = h.open();
|
||||
await a2.opened;
|
||||
a2.json({ t: 'hello', token: 'good', channelId: '42' });
|
||||
await a2.next((m) => m.t === 'welcome');
|
||||
assert.equal(h.discordFetch.calls.filter(([u]) => u.endsWith('/users/@me')).length, 1);
|
||||
assert.equal(room.calls.length, 1);
|
||||
|
||||
a.close();
|
||||
await tick(100);
|
||||
assert.equal(room.calls.length, 1, 'still one socket open for the user');
|
||||
a2.close();
|
||||
await tick(100);
|
||||
assert.deepEqual(room.calls.at(-1), ['leave', '111']);
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('ping → pong with server time', async () => {
|
||||
const h = await start();
|
||||
try {
|
||||
const a = h.open();
|
||||
await a.opened;
|
||||
a.json({ t: 'ping', at: 123 });
|
||||
const p = await a.next((m) => m.t === 'pong');
|
||||
assert.equal(p.at, 123);
|
||||
assert.ok(Math.abs(p.now - Date.now()) < 1000);
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('cmd and report are forwarded; change broadcasts are coalesced', async () => {
|
||||
const h = await start();
|
||||
const room = h.rooms.create({ id: '42' });
|
||||
try {
|
||||
const a = h.open();
|
||||
const b = h.open();
|
||||
await Promise.all([a.opened, b.opened]);
|
||||
a.json({ t: 'hello', token: 'good', channelId: '42' });
|
||||
b.json({ t: 'hello', token: 'bob', channelId: '42' });
|
||||
await a.next((m) => m.t === 'welcome');
|
||||
await b.next((m) => m.t === 'welcome');
|
||||
await tick(100);
|
||||
// drain anything queued so far
|
||||
while (await a.next((m) => m.t === 'state', 120).catch(() => null));
|
||||
while (await b.next((m) => m.t === 'state', 120).catch(() => null));
|
||||
|
||||
a.json({ t: 'cmd', op: 'seek', args: { t: 90 } });
|
||||
a.json({ t: 'cmd', op: 'play', args: {} });
|
||||
a.json({ t: 'report', duration: 5000 });
|
||||
const s = await b.next((m) => m.t === 'state');
|
||||
assert.equal(s.state.rev, 2, 'two changes → one broadcast with the latest state');
|
||||
await assert.rejects(b.next((m) => m.t === 'state', 200));
|
||||
assert.deepEqual(
|
||||
room.calls.filter((c) => c[0] !== 'join'),
|
||||
[
|
||||
['command', 'seek', { t: 90 }, '111'],
|
||||
['command', 'play', {}, '111'],
|
||||
['report', { duration: 5000 }, '111'],
|
||||
],
|
||||
);
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('cmds are rate limited per socket', async () => {
|
||||
const h = await start();
|
||||
const room = h.rooms.create({ id: '42' });
|
||||
try {
|
||||
const a = h.open();
|
||||
await a.opened;
|
||||
a.json({ t: 'hello', token: 'good', channelId: '42' });
|
||||
await a.next((m) => m.t === 'welcome');
|
||||
for (let i = 0; i < 25; i++) a.json({ t: 'cmd', op: 'toggle' });
|
||||
await a.next((m) => m.t === 'error' && /slow/.test(m.message));
|
||||
const n = room.calls.filter((c) => c[0] === 'command').length;
|
||||
assert.ok(n >= 10 && n < 15, `got ${n} commands through`);
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
|
||||
for (const events of [true, false]) {
|
||||
test(`waiting socket attaches when the room appears (${events ? "rooms 'created' event" : 'poll'})`, async () => {
|
||||
const h = await start({ rooms: fakeRooms({ events }) });
|
||||
try {
|
||||
const a = h.open();
|
||||
await a.opened;
|
||||
a.json({ t: 'hello', token: 'good', channelId: '42' });
|
||||
const w = await a.next((m) => m.t === 'welcome');
|
||||
assert.equal(w.state.media, null);
|
||||
const room = h.rooms.create({ id: '42' });
|
||||
const s = await a.next((m) => m.t === 'state', 4000);
|
||||
assert.equal(s.state.media.title, 'Fight Club');
|
||||
assert.deepEqual(room.calls, [['join', '111']]);
|
||||
a.json({ t: 'cmd', op: 'play' });
|
||||
await a.next((m) => m.t === 'state');
|
||||
assert.equal(room.calls.at(-1)[1], 'play');
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("room 'closed' → empty state, then a new room re-attaches", async () => {
|
||||
const h = await start({ rooms: fakeRooms({ events: true }) });
|
||||
const room = h.rooms.create({ id: '42' });
|
||||
try {
|
||||
const a = h.open();
|
||||
await a.opened;
|
||||
a.json({ t: 'hello', token: 'good', channelId: '42' });
|
||||
await a.next((m) => m.t === 'welcome');
|
||||
room.emit('closed');
|
||||
h.rooms.delete('42');
|
||||
const s = await a.next((m) => m.t === 'state' && m.state.media === null);
|
||||
assert.equal(s.state.stream, null);
|
||||
room.emit('change'); // a dead room must not broadcast anymore
|
||||
await assert.rejects(a.next((m) => m.t === 'state', 200));
|
||||
const room2 = h.rooms.create({ id: '42' });
|
||||
await a.next((m) => m.t === 'state' && m.state.media);
|
||||
assert.deepEqual(room2.calls, [['join', '111']]);
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('dev hello works with cfg.dev; unknown ws path is refused', async () => {
|
||||
const h = await start({ dev: true, voice: { '7': new Set(['5']) } });
|
||||
try {
|
||||
const a = h.open();
|
||||
await a.opened;
|
||||
a.json({ t: 'hello', dev: true, userId: '5', channelId: '7' });
|
||||
const w = await a.next((m) => m.t === 'welcome');
|
||||
assert.equal(w.user.id, '5');
|
||||
const b = h.open('/nope');
|
||||
await assert.rejects(b.opened);
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('path');
|
||||
const { pathToFileURL } = require('url');
|
||||
|
||||
const load = () => import(pathToFileURL(path.join(__dirname, '..', 'activity', 'js', 'sync.js')).href);
|
||||
|
||||
test('targetTime extrapolates while playing, clamps to duration', async () => {
|
||||
const S = await load();
|
||||
const st = { position: 100, playing: true, updatedAt: 1_000_000, duration: 0 };
|
||||
assert.equal(S.targetTime(st, 0, 1_005_000), 105);
|
||||
// local clock 2s behind the server → offset +2000
|
||||
assert.equal(S.targetTime(st, 2000, 1_003_000), 105);
|
||||
assert.equal(S.targetTime({ ...st, playing: false }, 0, 1_005_000), 100);
|
||||
assert.equal(S.targetTime({ ...st, duration: 103 }, 0, 1_005_000), 103);
|
||||
// updatedAt in the future (clock skew) never rewinds
|
||||
assert.equal(S.targetTime(st, 0, 999_000), 100);
|
||||
assert.equal(S.targetTime(null), 0);
|
||||
});
|
||||
|
||||
test('driftAction thresholds', async () => {
|
||||
const S = await load();
|
||||
assert.equal(S.driftAction(10, 10).action, 'none');
|
||||
assert.equal(S.driftAction(10.2, 10).action, 'none');
|
||||
let a = S.driftAction(10.5, 10);
|
||||
assert.equal(a.action, 'rate');
|
||||
assert.equal(a.rate, S.RATE_SLOW);
|
||||
a = S.driftAction(9, 10);
|
||||
assert.equal(a.action, 'rate');
|
||||
assert.equal(a.rate, S.RATE_FAST);
|
||||
assert.equal(S.driftAction(12, 10).action, 'seek');
|
||||
assert.equal(S.driftAction(7, 10).action, 'seek');
|
||||
// cooldown: no seek, nudge instead
|
||||
assert.equal(S.driftAction(7, 10, { canSeek: false }).action, 'rate');
|
||||
// paused: seek once noticeably off, never rate
|
||||
assert.equal(S.driftAction(10.5, 10, { playing: false }).action, 'seek');
|
||||
assert.equal(S.driftAction(10.1, 10, { playing: false }).action, 'none');
|
||||
assert.equal(S.driftAction(10.5, 10, { playing: false, canSeek: false }).action, 'none');
|
||||
});
|
||||
|
||||
test('isJump detects explicit seeks but not ticks', async () => {
|
||||
const S = await load();
|
||||
const now = 2_000_000;
|
||||
const a = { position: 50, playing: true, updatedAt: now - 10_000 };
|
||||
const tickState = { position: 60, playing: true, updatedAt: now };
|
||||
assert.equal(S.isJump(a, tickState, 0, now), false);
|
||||
assert.equal(S.isJump(a, { position: 200, playing: true, updatedAt: now }, 0, now), true);
|
||||
assert.equal(S.isJump(a, { position: 60, playing: false, updatedAt: now }, 0, now), false);
|
||||
assert.equal(S.isJump(null, a, 0, now), true);
|
||||
});
|
||||
|
||||
test('clock offset: sample math and rolling median', async () => {
|
||||
const S = await load();
|
||||
// sent at 1000 (local), server stamped 5100, received at 1200 → rtt 200, offset 5100 - 1100
|
||||
assert.deepEqual(S.offsetSample(1000, 5100, 1200), { offset: 4000, rtt: 200 });
|
||||
assert.equal(S.median([3, 1, 2]), 2);
|
||||
assert.equal(S.median([4, 1, 3, 2]), 2.5);
|
||||
assert.equal(S.median([]), 0);
|
||||
const c = S.createClock(5);
|
||||
assert.equal(c.offset(), 0);
|
||||
for (const o of [100, 105, 9999, 98, 102, 101]) c.add({ offset: o });
|
||||
assert.equal(c.count, 5);
|
||||
assert.equal(c.offset(), 102); // outlier ignored, oldest (100) dropped
|
||||
c.add(NaN);
|
||||
assert.equal(c.count, 5);
|
||||
});
|
||||
|
||||
test('formatTime', async () => {
|
||||
const S = await load();
|
||||
assert.equal(S.formatTime(0), '0:00');
|
||||
assert.equal(S.formatTime(65.9), '1:05');
|
||||
assert.equal(S.formatTime(3725), '1:02:05');
|
||||
});
|
||||
Reference in new issue
Block a user