From 636e7b506c402f0706407a4ebbb0d0c64ef4c20a Mon Sep 17 00:00:00 2001 From: Ccjcarkbla Date: Wed, 14 Oct 2026 09:51:01 -0400 Subject: [PATCH] Reset and fix --- V2/app/public/js/core.js | 11 +- V2/app/public/js/display.js | 182 ++++++++++++++++-- V2/app/public/styles/display.css | 12 ++ V2/app/public/sw.js | 2 +- V2/app/public/workout-display.html | 53 ++++-- V2/app/tests/unit/display.test.js | 292 +++++++++++++++++++++++++++++ 6 files changed, 517 insertions(+), 35 deletions(-) create mode 100644 V2/app/tests/unit/display.test.js diff --git a/V2/app/public/js/core.js b/V2/app/public/js/core.js index 0de1c3e..2c22e31 100644 --- a/V2/app/public/js/core.js +++ b/V2/app/public/js/core.js @@ -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'); diff --git a/V2/app/public/js/display.js b/V2/app/public/js/display.js index 9dc3e29..c9afccd 100644 --- a/V2/app/public/js/display.js +++ b/V2/app/public/js/display.js @@ -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 = '
No exercises assigned.
'; 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 ` -
- ${streamSrc - ? `` - : `
${isPreview ? (slot.video.description || 'Video') : 'Missing Video'}
`} - ${slot.reps ? `
${slot.reps}
` : ''} -
`; - }).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'); diff --git a/V2/app/public/styles/display.css b/V2/app/public/styles/display.css index 2c5058b..4267304 100644 --- a/V2/app/public/styles/display.css +++ b/V2/app/public/styles/display.css @@ -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%; diff --git a/V2/app/public/sw.js b/V2/app/public/sw.js index 43d37a7..c4321a7 100644 --- a/V2/app/public/sw.js +++ b/V2/app/public/sw.js @@ -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', diff --git a/V2/app/public/workout-display.html b/V2/app/public/workout-display.html index 4035e54..1ce03ac 100644 --- a/V2/app/public/workout-display.html +++ b/V2/app/public/workout-display.html @@ -22,32 +22,51 @@ const id = params.get('id'); if (!id) { document.getElementById('display-video-grid').innerHTML = '
No workout selected.
'; 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); }); diff --git a/V2/app/tests/unit/display.test.js b/V2/app/tests/unit/display.test.js new file mode 100644 index 0000000..3bc0fe9 --- /dev/null +++ b/V2/app/tests/unit/display.test.js @@ -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(/