Reset and fix
This commit is contained in:
@@ -37,12 +37,13 @@ const Auth = (() => {
|
||||
return (payload.exp * 1000 - Date.now()) < 60 * 60 * 1000; // < 1 hour
|
||||
}
|
||||
|
||||
async function tryDeviceLogin() {
|
||||
async function tryDeviceLogin(signal) {
|
||||
const deviceToken = getDeviceToken();
|
||||
if (!deviceToken) return false;
|
||||
try {
|
||||
const res = await fetch('/api/v1/auth/device-login', {
|
||||
method: 'POST',
|
||||
signal,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ deviceToken }),
|
||||
});
|
||||
@@ -54,12 +55,13 @@ const Auth = (() => {
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
async function autoRefreshIfNeeded() {
|
||||
async function autoRefreshIfNeeded(signal) {
|
||||
const token = getJwt();
|
||||
if (!token || !isTokenExpiringSoon(token)) return;
|
||||
try {
|
||||
const res = await fetch('/api/v1/auth/refresh-token', {
|
||||
method: 'POST',
|
||||
signal,
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (res.ok) {
|
||||
@@ -79,7 +81,7 @@ const Auth = (() => {
|
||||
// ── Api ───────────────────────────────────────────────────────────────────────
|
||||
const Api = (() => {
|
||||
async function _fetch(url, options = {}, retry = true) {
|
||||
await Auth.autoRefreshIfNeeded();
|
||||
await Auth.autoRefreshIfNeeded(options.signal);
|
||||
const jwt = Auth.getJwt();
|
||||
const headers = { ...(options.headers || {}) };
|
||||
if (jwt) headers['Authorization'] = `Bearer ${jwt}`;
|
||||
@@ -93,8 +95,9 @@ const Api = (() => {
|
||||
const res = await fetch(url, { ...options, headers });
|
||||
|
||||
if (res.status === 401 && retry) {
|
||||
const refreshed = await Auth.tryDeviceLogin();
|
||||
const refreshed = await Auth.tryDeviceLogin(options.signal);
|
||||
if (refreshed) return _fetch(url, options, false);
|
||||
if (options.signal?.aborted) throw options.signal.reason || new Error('Request aborted');
|
||||
Auth.clearSession();
|
||||
Page.showSessionExpiredOverlay();
|
||||
throw new Error('Session expired');
|
||||
|
||||
+169
-13
@@ -3,40 +3,196 @@
|
||||
|
||||
const Display = (() => {
|
||||
let _keepAliveEl = null;
|
||||
let _players = [];
|
||||
let _watchdog = null;
|
||||
let _lastWorkout = null;
|
||||
const STALL_MS = 20000;
|
||||
|
||||
function releasePlayer(player) {
|
||||
if (!player.video) return;
|
||||
player.playVersion++;
|
||||
player.video.pause();
|
||||
player.video.removeAttribute('src');
|
||||
// Explicitly release the old media resource before removing the element.
|
||||
player.video.load();
|
||||
}
|
||||
|
||||
function stopWorkoutPlayback() {
|
||||
clearInterval(_watchdog);
|
||||
_watchdog = null;
|
||||
_players.forEach(player => {
|
||||
releasePlayer(player);
|
||||
player.pane.remove();
|
||||
});
|
||||
_players = [];
|
||||
}
|
||||
|
||||
function playPlayer(player) {
|
||||
if (document.hidden || !player.video) return;
|
||||
const version = ++player.playVersion;
|
||||
const promise = player.video.play();
|
||||
if (promise) promise.catch(error => {
|
||||
if (version !== player.playVersion) return;
|
||||
// Safari may require a tap; repeated automatic retries cannot grant it.
|
||||
if (error.name === 'NotAllowedError') {
|
||||
player.blocked = true;
|
||||
player.resume.hidden = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function createPlayer(source, label) {
|
||||
const pane = document.createElement('div');
|
||||
pane.className = 'display-pane';
|
||||
const reps = document.createElement('div');
|
||||
reps.className = 'display-pane-corner';
|
||||
const player = {
|
||||
pane, reps, source, video: null, playVersion: 0, blocked: false,
|
||||
lastTime: 0, lastProgress: Date.now(), healthySince: Date.now(),
|
||||
attempts: 0, retryAt: 0,
|
||||
};
|
||||
if (source) {
|
||||
const video = document.createElement('video');
|
||||
video.className = 'display-pane-video';
|
||||
video.autoplay = true;
|
||||
video.loop = true;
|
||||
video.muted = true;
|
||||
video.defaultMuted = true;
|
||||
video.playsInline = true;
|
||||
video.preload = 'metadata';
|
||||
video.setAttribute('muted', '');
|
||||
video.setAttribute('playsinline', '');
|
||||
// The whole page is screen-mirrored; do not route a single pane remotely.
|
||||
video.disableRemotePlayback = true;
|
||||
video.setAttribute('x-webkit-airplay', 'deny');
|
||||
video.src = source;
|
||||
player.video = video;
|
||||
const resume = document.createElement('button');
|
||||
resume.type = 'button';
|
||||
resume.className = 'display-pane-resume';
|
||||
resume.textContent = 'Tap to resume video';
|
||||
resume.hidden = true;
|
||||
resume.addEventListener('click', () => {
|
||||
player.blocked = false;
|
||||
resume.hidden = true;
|
||||
player.lastProgress = Date.now();
|
||||
playPlayer(player);
|
||||
});
|
||||
player.resume = resume;
|
||||
video.addEventListener('timeupdate', () => {
|
||||
if (document.hidden || video.currentTime === player.lastTime) return;
|
||||
player.lastTime = video.currentTime;
|
||||
player.lastProgress = Date.now();
|
||||
if (!player.healthySince) player.healthySince = Date.now();
|
||||
if (Date.now() - player.healthySince >= 60000) player.attempts = 0;
|
||||
player.blocked = false;
|
||||
resume.hidden = true;
|
||||
});
|
||||
pane.append(video, resume);
|
||||
} else {
|
||||
player.missing = document.createElement('div');
|
||||
player.missing.className = 'display-pane-missing';
|
||||
player.missing.textContent = label;
|
||||
pane.appendChild(player.missing);
|
||||
}
|
||||
pane.appendChild(reps);
|
||||
return player;
|
||||
}
|
||||
|
||||
function checkPlayback() {
|
||||
if (document.hidden) return;
|
||||
const now = Date.now();
|
||||
_players.forEach(player => {
|
||||
const video = player.video;
|
||||
if (!video || player.blocked || now < player.retryAt ||
|
||||
now - player.lastProgress < STALL_MS) return;
|
||||
player.attempts++;
|
||||
// Back off persistently broken/missing media instead of creating a reload storm.
|
||||
player.retryAt = now + Math.min(300000, STALL_MS * (2 ** Math.min(player.attempts - 1, 4)));
|
||||
player.lastProgress = now;
|
||||
player.healthySince = 0;
|
||||
if (video.error || !video.paused || player.attempts > 1) {
|
||||
releasePlayer(player);
|
||||
video.src = player.source;
|
||||
video.load();
|
||||
}
|
||||
playPlayer(player);
|
||||
});
|
||||
}
|
||||
|
||||
function renderWorkout(workout) {
|
||||
const gridEl = document.getElementById('display-video-grid');
|
||||
if (!gridEl) return;
|
||||
_lastWorkout = workout;
|
||||
|
||||
const slots = (workout.videos || []).filter(s => s.video);
|
||||
const count = Math.min(slots.length, 4);
|
||||
|
||||
if (!count) {
|
||||
stopWorkoutPlayback();
|
||||
gridEl.className = 'display-video-grid';
|
||||
gridEl.innerHTML = '<div class="display-no-videos">No exercises assigned.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const jwt = Auth.getJwt();
|
||||
const selectedOrg = Auth.getSelectedOrg();
|
||||
const orgParam = selectedOrg ? `&orgId=${selectedOrg.id}` : '';
|
||||
|
||||
const isPreview = new URLSearchParams(window.location.search).get('preview') === '1';
|
||||
|
||||
gridEl.className = `display-video-grid panes-${count}`;
|
||||
gridEl.innerHTML = slots.slice(0, 4).map(slot => {
|
||||
const streamSrc = slot.video.streamUrl
|
||||
? `${slot.video.streamUrl}?token=${encodeURIComponent(jwt || '')}${orgParam}`
|
||||
: '';
|
||||
return `
|
||||
<div class="display-pane">
|
||||
${streamSrc
|
||||
? `<video class="display-pane-video" src="${streamSrc}" autoplay loop muted playsinline></video>`
|
||||
: `<div class="display-pane-missing">${isPreview ? (slot.video.description || 'Video') : 'Missing Video'}</div>`}
|
||||
${slot.reps ? `<div class="display-pane-corner">${slot.reps}</div>` : ''}
|
||||
</div>`;
|
||||
}).join('');
|
||||
if (!_players.length) gridEl.replaceChildren();
|
||||
slots.slice(0, 4).forEach((slot, index) => {
|
||||
let source = '';
|
||||
if (slot.video.streamUrl) {
|
||||
const url = new URL(slot.video.streamUrl, window.location.href);
|
||||
url.searchParams.set('token', jwt || '');
|
||||
if (selectedOrg) url.searchParams.set('orgId', String(selectedOrg.id));
|
||||
source = url.href;
|
||||
}
|
||||
const label = isPreview ? (slot.video.description || 'Video') : 'Missing Video';
|
||||
let player = _players[index];
|
||||
if (!player || player.source !== source) {
|
||||
const replacement = createPlayer(source, label);
|
||||
if (player) {
|
||||
releasePlayer(player);
|
||||
player.pane.replaceWith(replacement.pane);
|
||||
} else {
|
||||
gridEl.appendChild(replacement.pane);
|
||||
}
|
||||
player = replacement;
|
||||
_players[index] = player;
|
||||
playPlayer(player);
|
||||
}
|
||||
if (player.missing) player.missing.textContent = label;
|
||||
player.reps.textContent = slot.reps ? String(slot.reps) : '';
|
||||
player.reps.hidden = !slot.reps;
|
||||
});
|
||||
_players.splice(count).forEach(player => {
|
||||
releasePlayer(player);
|
||||
player.pane.remove();
|
||||
});
|
||||
if (!_watchdog) _watchdog = setInterval(checkPlayback, 5000);
|
||||
}
|
||||
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
_players.forEach(player => {
|
||||
if (!player.video) return;
|
||||
if (document.hidden) {
|
||||
player.playVersion++;
|
||||
player.video.pause();
|
||||
} else {
|
||||
player.lastProgress = Date.now();
|
||||
player.healthySince = 0;
|
||||
if (!player.blocked) playPlayer(player);
|
||||
}
|
||||
});
|
||||
});
|
||||
window.addEventListener('pagehide', stopWorkoutPlayback);
|
||||
window.addEventListener('pageshow', event => {
|
||||
if (event.persisted && _lastWorkout) renderWorkout(_lastWorkout);
|
||||
});
|
||||
|
||||
function renderCrossfit(workout) {
|
||||
const nameEl = document.getElementById('display-cf-name');
|
||||
const dateEl = document.getElementById('display-cf-date');
|
||||
|
||||
@@ -192,6 +192,18 @@ html, body {
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
.display-pane-resume {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.65);
|
||||
color: #fff;
|
||||
border: 0;
|
||||
font-size: var(--display-font-body);
|
||||
cursor: pointer;
|
||||
}
|
||||
.display-pane-resume[hidden] { display: none; }
|
||||
.display-pane-missing {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
/* VitFit Service Worker — shell-only caching for PWA install */
|
||||
'use strict';
|
||||
|
||||
const CACHE_NAME = 'vitfit-v12';
|
||||
const CACHE_NAME = 'vitfit-v13';
|
||||
const SHELL_ASSETS = [
|
||||
'/',
|
||||
'/index.html',
|
||||
|
||||
@@ -22,32 +22,51 @@
|
||||
const id = params.get('id');
|
||||
if (!id) { document.getElementById('display-video-grid').innerHTML = '<div class="display-no-videos">No workout selected.</div>'; return; }
|
||||
|
||||
Display.startKeepAlive();
|
||||
// Branding must not delay the first workout load if the network hangs.
|
||||
fetch('/api/v1/org/branding/public')
|
||||
.then(async res => {
|
||||
if (res.ok) { const { data } = await res.json(); Display.applyBranding(data); }
|
||||
}).catch(() => {});
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/org/branding/public');
|
||||
if (res.ok) { const { data } = await res.json(); Display.applyBranding(data); }
|
||||
} catch {}
|
||||
let pollTimer = null;
|
||||
let activeRequest = null;
|
||||
let stopped = false;
|
||||
|
||||
async function load() {
|
||||
if (stopped || activeRequest) return;
|
||||
const controller = new AbortController();
|
||||
activeRequest = controller;
|
||||
const timeout = setTimeout(() => controller.abort(), 15000);
|
||||
try {
|
||||
const jwt = Auth.getJwt();
|
||||
const selectedOrg = Auth.getSelectedOrg();
|
||||
const headers = {};
|
||||
if (jwt) headers['Authorization'] = `Bearer ${jwt}`;
|
||||
if (selectedOrg) headers['X-Org-Id'] = String(selectedOrg.id);
|
||||
const res = await fetch(`/api/v1/workouts/${id}`, { headers });
|
||||
if (!res.ok) {
|
||||
document.getElementById('display-workout-name').textContent = 'Workout not found.';
|
||||
return;
|
||||
}
|
||||
const res = await Api.fetch(`/api/v1/workouts/${encodeURIComponent(id)}`, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!res.ok) throw new Error('Workout unavailable');
|
||||
const { data } = await res.json();
|
||||
if (stopped) return;
|
||||
Display.renderWorkout(data);
|
||||
} catch { Display.setOffline(true); }
|
||||
Display.setOffline(false);
|
||||
} catch {
|
||||
if (!stopped) Display.setOffline(true);
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
activeRequest = null;
|
||||
// Schedule after completion so slow requests cannot overlap.
|
||||
if (!stopped) pollTimer = setTimeout(load, 30000);
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('pagehide', () => {
|
||||
stopped = true;
|
||||
clearTimeout(pollTimer);
|
||||
activeRequest?.abort();
|
||||
});
|
||||
window.addEventListener('pageshow', event => {
|
||||
if (!event.persisted) return;
|
||||
stopped = false;
|
||||
load();
|
||||
});
|
||||
load();
|
||||
setInterval(load, 30000);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
|
||||
// A small DOM/media fixture verifies lifecycle behavior without launching the app
|
||||
// or touching the gym's database. Actual Safari decoding still needs an iPad run.
|
||||
function eventTarget(target = {}) {
|
||||
const listeners = new Map();
|
||||
target.addEventListener = (type, callback) => {
|
||||
if (!listeners.has(type)) listeners.set(type, []);
|
||||
listeners.get(type).push(callback);
|
||||
};
|
||||
target.dispatch = (type, event = {}) => {
|
||||
for (const callback of listeners.get(type) || []) callback(event);
|
||||
};
|
||||
return target;
|
||||
}
|
||||
|
||||
function setup(search = '?id=1') {
|
||||
const videos = [];
|
||||
class Element {
|
||||
constructor(tagName) {
|
||||
eventTarget(this);
|
||||
this.tagName = tagName;
|
||||
this.children = [];
|
||||
this.attributes = {};
|
||||
this.hidden = false;
|
||||
this.classList = { toggle: jest.fn() };
|
||||
if (tagName === 'video') {
|
||||
videos.push(this);
|
||||
this.currentTime = 0;
|
||||
this.paused = true;
|
||||
this.play = jest.fn(() => {
|
||||
this.paused = false;
|
||||
return Promise.resolve();
|
||||
});
|
||||
this.pause = jest.fn(() => { this.paused = true; });
|
||||
this.load = jest.fn(() => { this.currentTime = 0; this.error = null; });
|
||||
}
|
||||
}
|
||||
append(...children) {
|
||||
for (const child of children) {
|
||||
this.children.push(child);
|
||||
child.parentNode = this;
|
||||
}
|
||||
}
|
||||
appendChild(child) { this.append(child); }
|
||||
remove() {
|
||||
if (!this.parentNode) return;
|
||||
const parent = this.parentNode;
|
||||
parent.children.splice(parent.children.indexOf(this), 1);
|
||||
this.parentNode = null;
|
||||
}
|
||||
replaceWith(replacement) {
|
||||
const parent = this.parentNode;
|
||||
parent.children[parent.children.indexOf(this)] = replacement;
|
||||
replacement.parentNode = parent;
|
||||
this.parentNode = null;
|
||||
}
|
||||
replaceChildren() { this.children.slice().forEach(child => child.remove()); }
|
||||
set innerHTML(value) { this.replaceChildren(); this.html = value; }
|
||||
setAttribute(key, value) { this.attributes[key] = value; }
|
||||
removeAttribute(key) {
|
||||
delete this.attributes[key];
|
||||
if (key === 'src') this.src = '';
|
||||
}
|
||||
}
|
||||
const grid = new Element('div');
|
||||
const banner = new Element('div');
|
||||
const document = eventTarget({
|
||||
hidden: false,
|
||||
body: new Element('body'),
|
||||
createElement: tag => new Element(tag),
|
||||
getElementById: id => ({ 'display-video-grid': grid, 'display-offline-banner': banner })[id],
|
||||
});
|
||||
const window = eventTarget({ location: { search, href: `https://vitfit.test/workout-display.html${search}` } });
|
||||
const auth = { jwt: 'test-token', org: { id: 3 } };
|
||||
const Api = { fetch: jest.fn() };
|
||||
const context = vm.createContext({
|
||||
document, window, URL, URLSearchParams, Date, AbortController,
|
||||
setInterval, clearInterval, setTimeout, clearTimeout,
|
||||
Auth: { getJwt: () => auth.jwt, getSelectedOrg: () => auth.org },
|
||||
Branding: { apply: jest.fn() }, Api,
|
||||
fetch: jest.fn(() => Promise.resolve({ ok: false })),
|
||||
});
|
||||
const source = fs.readFileSync(path.join(__dirname, '../../public/js/display.js'), 'utf8');
|
||||
vm.runInContext(`${source}\nglobalThis.display = Display;`, context);
|
||||
const workout = { videos: [1, 2, 3, 4].map(id => ({ video: { streamUrl: `/api/v1/videos/stream/${id}.mp4` }, reps: 10 })) };
|
||||
return { context, display: context.display, document, window, grid, videos, auth, workout, Api, banner };
|
||||
}
|
||||
|
||||
beforeEach(() => { jest.useFakeTimers(); jest.setSystemTime(100000); });
|
||||
afterEach(() => { jest.clearAllTimers(); jest.useRealTimers(); });
|
||||
|
||||
test('12 simulated hours of polling and looping retain four players and one watchdog', () => {
|
||||
const { display, workout, videos, grid } = setup();
|
||||
display.renderWorkout(workout);
|
||||
const originals = [...videos];
|
||||
for (let tick = 1; tick <= 8640; tick++) {
|
||||
for (const video of videos) {
|
||||
video.currentTime = tick % 8; // include wraparound at each loop boundary
|
||||
video.dispatch('timeupdate');
|
||||
}
|
||||
jest.advanceTimersByTime(5000);
|
||||
if (tick % 6 === 0) display.renderWorkout(workout);
|
||||
}
|
||||
expect(videos).toEqual(originals);
|
||||
expect(grid.children).toHaveLength(4);
|
||||
for (const video of videos) {
|
||||
expect(video.load).not.toHaveBeenCalled();
|
||||
expect(video.play).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
test('changing repetitions preserves every video and changing one source releases only that player', () => {
|
||||
const { display, workout, videos, grid } = setup();
|
||||
display.renderWorkout(workout);
|
||||
workout.videos[0].reps = 20;
|
||||
display.renderWorkout(workout);
|
||||
expect(videos).toHaveLength(4);
|
||||
expect(grid.children[0].children.at(-1).textContent).toBe('20');
|
||||
const old = videos[1];
|
||||
workout.videos[1].video.streamUrl = '/api/v1/videos/stream/new.mp4';
|
||||
display.renderWorkout(workout);
|
||||
expect(videos).toHaveLength(5);
|
||||
expect(old.pause).toHaveBeenCalledTimes(1);
|
||||
expect(old.load).toHaveBeenCalledTimes(1);
|
||||
expect(old.src).toBe('');
|
||||
expect(videos[0].load).not.toHaveBeenCalled();
|
||||
expect(grid.children).toHaveLength(4);
|
||||
});
|
||||
|
||||
test('a stalled player recovers while progressing players stay loaded, with bounded retries', () => {
|
||||
const { display, workout, videos } = setup();
|
||||
display.renderWorkout(workout);
|
||||
for (let tick = 1; tick <= 60; tick++) {
|
||||
for (const video of videos.slice(1)) {
|
||||
video.currentTime = tick;
|
||||
video.dispatch('timeupdate');
|
||||
}
|
||||
jest.advanceTimersByTime(5000);
|
||||
}
|
||||
// 20s, 40s, 80s, 160s: the next attempt waits until 320s.
|
||||
expect(videos[0].load).toHaveBeenCalledTimes(8);
|
||||
for (const video of videos.slice(1)) expect(video.load).not.toHaveBeenCalled();
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
test('Safari autoplay denial offers a tap and suppresses automatic reloads', async () => {
|
||||
const { display, workout, videos, grid } = setup();
|
||||
display.renderWorkout(workout);
|
||||
const video = videos[0];
|
||||
video.play.mockRejectedValueOnce(Object.assign(new Error('Gesture required'), { name: 'NotAllowedError' }));
|
||||
video.paused = true;
|
||||
jest.advanceTimersByTime(20000);
|
||||
await Promise.resolve();
|
||||
const resume = grid.children[0].children[1];
|
||||
expect(resume.hidden).toBe(false);
|
||||
jest.advanceTimersByTime(600000);
|
||||
expect(video.load).not.toHaveBeenCalled();
|
||||
resume.dispatch('click');
|
||||
expect(resume.hidden).toBe(true);
|
||||
expect(video.play).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
test('hidden pages pause playback and returning pages resume without reloading', () => {
|
||||
const { display, workout, videos, document } = setup();
|
||||
display.renderWorkout(workout);
|
||||
document.hidden = true;
|
||||
document.dispatch('visibilitychange');
|
||||
jest.advanceTimersByTime(600000);
|
||||
for (const video of videos) {
|
||||
expect(video.pause).toHaveBeenCalledTimes(1);
|
||||
expect(video.load).not.toHaveBeenCalled();
|
||||
}
|
||||
document.hidden = false;
|
||||
document.dispatch('visibilitychange');
|
||||
for (const video of videos) expect(video.play).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test('empty workouts and navigation release resources; back navigation restores playback', () => {
|
||||
const { display, workout, videos, window, grid } = setup();
|
||||
display.renderWorkout(workout);
|
||||
window.dispatch('pagehide');
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
for (const video of videos) expect(video.src).toBe('');
|
||||
window.dispatch('pageshow', { persisted: true });
|
||||
expect(grid.children).toHaveLength(4);
|
||||
expect(videos).toHaveLength(8);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
display.renderWorkout({ videos: [] });
|
||||
expect(grid.children).toHaveLength(0);
|
||||
expect(grid.html).toContain('No exercises assigned');
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
test('stream URLs preserve query parameters, scope and refreshed authentication', () => {
|
||||
const { display, workout, videos, auth } = setup();
|
||||
workout.videos[0].video.streamUrl += '?quality=small';
|
||||
display.renderWorkout(workout);
|
||||
const url = new URL(videos[0].src);
|
||||
expect(url.searchParams.get('quality')).toBe('small');
|
||||
expect(url.searchParams.get('orgId')).toBe('3');
|
||||
expect(url.searchParams.get('token')).toBe('test-token');
|
||||
expect(videos[0].disableRemotePlayback).toBe(true);
|
||||
expect(videos[0].attributes['x-webkit-airplay']).toBe('deny');
|
||||
auth.jwt = 'refreshed-token';
|
||||
display.renderWorkout(workout);
|
||||
expect(new URL(videos[4].src).searchParams.get('token')).toBe('refreshed-token');
|
||||
expect(videos[0].src).toBe('');
|
||||
});
|
||||
|
||||
test('polling keeps last data on errors, clears the banner on recovery and never overlaps', async () => {
|
||||
const fixture = setup();
|
||||
const { context, document, Api, workout, banner, window } = fixture;
|
||||
const html = fs.readFileSync(path.join(__dirname, '../../public/workout-display.html'), 'utf8');
|
||||
const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
|
||||
let finish;
|
||||
Api.fetch.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
|
||||
vm.runInContext(script, context);
|
||||
document.dispatch('DOMContentLoaded');
|
||||
jest.advanceTimersByTime(60000);
|
||||
expect(Api.fetch).toHaveBeenCalledTimes(1);
|
||||
finish({ ok: false });
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(banner.classList.toggle).toHaveBeenLastCalledWith('visible', true);
|
||||
Api.fetch.mockResolvedValue({ ok: true, json: async () => ({ data: workout }) });
|
||||
await jest.advanceTimersByTimeAsync(30000);
|
||||
expect(Api.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(banner.classList.toggle).toHaveBeenLastCalledWith('visible', false);
|
||||
expect(fixture.videos).toHaveLength(4);
|
||||
window.dispatch('pagehide');
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
window.dispatch('pageshow', { persisted: true });
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(Api.fetch).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
test('the poll deadline aborts a hung request and permits the next refresh', async () => {
|
||||
const { context, document, Api, workout, banner } = setup();
|
||||
const html = fs.readFileSync(path.join(__dirname, '../../public/workout-display.html'), 'utf8');
|
||||
Api.fetch.mockImplementationOnce((url, { signal }) => new Promise((resolve, reject) => {
|
||||
signal.addEventListener('abort', () => reject(new Error('Aborted')));
|
||||
}));
|
||||
Api.fetch.mockResolvedValue({ ok: true, json: async () => ({ data: workout }) });
|
||||
vm.runInContext(html.match(/<script>([\s\S]*?)<\/script>/)[1], context);
|
||||
document.dispatch('DOMContentLoaded');
|
||||
await jest.advanceTimersByTimeAsync(15000);
|
||||
expect(banner.classList.toggle).toHaveBeenLastCalledWith('visible', true);
|
||||
await jest.advanceTimersByTimeAsync(30000);
|
||||
expect(Api.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(banner.classList.toggle).toHaveBeenLastCalledWith('visible', false);
|
||||
});
|
||||
|
||||
test('authentication requests share the poll deadline; an aborted login retains the session', async () => {
|
||||
const { context } = setup();
|
||||
const items = new Map([
|
||||
['vf_jwt', 'session-token'], ['vf_device', 'device-token'],
|
||||
]);
|
||||
context.localStorage = {
|
||||
getItem: key => items.get(key) || null,
|
||||
setItem: (key, value) => items.set(key, value),
|
||||
removeItem: key => items.delete(key),
|
||||
};
|
||||
context.FormData = class {};
|
||||
context.atob = () => JSON.stringify({ exp: (Date.now() + 1000) / 1000 });
|
||||
const controller = new AbortController();
|
||||
let loginStarted;
|
||||
const started = new Promise(resolve => { loginStarted = resolve; });
|
||||
context.fetch = jest.fn(async (url, options) => {
|
||||
expect(options.signal).toBe(controller.signal);
|
||||
if (url.endsWith('/refresh-token')) return { ok: false };
|
||||
if (url.endsWith('/device-login')) {
|
||||
loginStarted();
|
||||
return new Promise((resolve, reject) => {
|
||||
options.signal.addEventListener('abort', () => reject(new Error('Aborted')));
|
||||
});
|
||||
}
|
||||
return { status: 401 };
|
||||
});
|
||||
const core = fs.readFileSync(path.join(__dirname, '../../public/js/core.js'), 'utf8');
|
||||
vm.runInContext(`${core}\nglobalThis.coreApi = Api;`, context);
|
||||
const request = context.coreApi.fetch('/api/v1/workouts/1', { signal: controller.signal });
|
||||
await started;
|
||||
controller.abort(new Error('Deadline reached'));
|
||||
await expect(request).rejects.toThrow('Deadline reached');
|
||||
expect(items.get('vf_jwt')).toBe('session-token');
|
||||
expect(items.get('vf_device')).toBe('device-token');
|
||||
});
|
||||
Reference in New Issue
Block a user