From f3ba05aeceb3fdb068c03b887a32d0e1bdec5ca4 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Wed, 22 Jul 2026 02:06:19 +0200 Subject: [PATCH] Admin dashboard (phase 2): live 'training now' heartbeat + release v1.1.4 Backend: in-memory presence map + POST /api/activity heartbeat (authed); each /api/admin/users row carries a fresh 'live' snapshot (routine, exercise x/y, sets done/total, started-at) with a ~70s TTL. Disabling a user clears their presence immediately. Frontend: the workout screen pings /api/activity every 20s (signed-in only) and sends a leave signal on unmount (fetch + sendBeacon). The dashboard gains a 'Training now' section and live markers, auto- refreshing every 15s. Cuts the complete admin-dashboard feature (phases 1+2) as v1.1.4. --- CHANGELOG.md | 17 ++++++++++++++++ api/server.js | 36 ++++++++++++++++++++++++++++++++-- frontend/package.json | 2 +- frontend/src/views/Admin.jsx | 20 +++++++++++++++---- frontend/src/views/Workout.jsx | 28 ++++++++++++++++++++++++++ 5 files changed, 96 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3650502..357f269 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## v1.1.4 โ€” 2026-07-22 + +Admin dashboard for self-hosters (opt-in โ€” off by default). + +- ๐Ÿ› ๏ธ **Admin dashboard** (Settings โ†’ Admin dashboard) for whoever runs the instance: a users + overview with workout counts and last-active times, plus a per-user drill-down into their full + workout history and body-weight log. +- ๐ŸŸข **Live "training now"** โ€” see who's mid-workout in real time, with their current exercise and + set progress, updated by a lightweight heartbeat while a workout is on screen. +- ๐Ÿšซ **Disable / enable accounts** โ€” a disabled account is signed out and locked out everywhere + until you re-enable it. +- ๐Ÿ”‘ **Invite-only signup** (optional) โ€” require an invite code to create a profile; generate and + revoke codes from the dashboard. Existing accounts are unaffected. +- โš™๏ธ Configured via environment: `ADMIN_UIDS` (comma-separated user ids who are admins) and + `INVITE_ONLY=1`; both default off, so a fresh instance stays open with no admin. See + `.env.example`. Admin access is gated by your passkey and enforced server-side. + ## v1.1.3 โ€” 2026-07-22 - ๐Ÿ”Ž **Minimize the exercise animation during a workout** (#12). A โคก Minimize / โคข Expand button diff --git a/api/server.js b/api/server.js index d8c6839..7a01862 100644 --- a/api/server.js +++ b/api/server.js @@ -223,6 +223,19 @@ function readBody(req) { } const b64uToBuf = s => Buffer.from(s, 'base64url'); +/* ---------- live presence (in-memory) ---------- */ +// Clients heartbeat /api/activity while a workout is on screen; the admin dashboard reads who's +// live. Purely ephemeral โ€” never persisted. Expires shortly after the last ping. +const presence = new Map(); // uid -> { name, exIdx, exTotal, setsDone, setsTotal, startedAt, updatedAt } +const PRESENCE_TTL = 70000; // ~3.5ร— the 20s client heartbeat +function livePresence(uid) { + const p = presence.get(uid); + if (!p) return null; + if (Date.now() - p.updatedAt > PRESENCE_TTL) { presence.delete(uid); return null; } + return p; +} +setInterval(() => { for (const [k, v] of presence) if (Date.now() - v.updatedAt > PRESENCE_TTL) presence.delete(k); }, 30000).unref(); + /* ---------- routes ---------- */ const routes = { 'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }), @@ -398,6 +411,23 @@ const routes = { json(res, 200, { ok: true }); }, + // Live-workout heartbeat: client pings while a workout is on screen; { active:false } drops it. + 'POST /api/activity': async (req, res) => { + const user = readSession(req); + if (!user) return json(res, 401, { error: 'not signed in' }); + const body = await readBody(req); + if (body.active) { + presence.set(user.id, { + name: String(body.name || '').slice(0, 60), + exIdx: +body.exIdx || 0, exTotal: +body.exTotal || 0, + setsDone: +body.setsDone || 0, setsTotal: +body.setsTotal || 0, + startedAt: +body.startedAt || Date.now(), + updatedAt: Date.now() + }); + } else presence.delete(user.id); + json(res, 200, { ok: true }); + }, + /* ---------- admin dashboard ---------- */ // One row per user, cheap enough for a personal instance (reads each state file once). 'GET /api/admin/users': async (req, res) => { @@ -412,10 +442,11 @@ const routes = { workouts: workouts.length, lastWorkout: last ? last.d : null, lastSync: S._ts || null, - hasPush: db.subs.some(s => s.userId === u.id) + hasPush: db.subs.some(s => s.userId === u.id), + live: livePresence(u.id) }; }); - json(res, 200, { users, invite_only: INVITE_ONLY }); + json(res, 200, { users, invite_only: INVITE_ONLY, now: Date.now() }); }, // Drill-down: full workout history + body-weight log for one user. @@ -442,6 +473,7 @@ const routes = { if (!u) return json(res, 404, { error: 'no such user' }); if (isAdmin(u)) return json(res, 400, { error: 'cannot disable an admin' }); u.disabled = !!body.disabled; + if (u.disabled) presence.delete(u.id); // drop them off "training now" at once saveDb(); json(res, 200, { ok: true, id: u.id, disabled: u.disabled }); }, diff --git a/frontend/package.json b/frontend/package.json index 2517c82..c3383c9 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "opengym-frontend", "private": true, - "version": "1.1.3", + "version": "1.1.4", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsx index 7c72ad8..6f69adb 100644 --- a/frontend/src/views/Admin.jsx +++ b/frontend/src/views/Admin.jsx @@ -19,6 +19,7 @@ const rel = ts => { if (s < 86400) return Math.floor(s / 3600) + 'h ago' return Math.floor(s / 86400) + 'd ago' } +const dur = ms => { const m = Math.max(0, Math.floor(ms / 60000)); return m < 60 ? m + 'm' : Math.floor(m / 60) + 'h' + (m % 60) + 'm' } function UserDetail({ id, onChanged, close }) { const [d, setD] = useState(null) @@ -96,10 +97,12 @@ export default function Admin() { const loadUsers = () => api('/api/admin/users').then(d => { setUsers(d.users); setInviteOnly(d.invite_only) }).catch(e => toast(e.message || 'Failed to load')) const loadInvites = () => api('/api/admin/invites').then(d => setInvites(d.invites)).catch(() => {}) - useEffect(() => { if (user?.admin) { loadUsers(); loadInvites() } }, []) + // poll every 15s so the "training now" section stays live without a manual refresh + useEffect(() => { if (!user?.admin) return; loadUsers(); loadInvites(); const iv = setInterval(loadUsers, 15000); return () => clearInterval(iv) }, []) if (!user?.admin) return null const openUser = id => openSheet(close => ) + const liveUsers = (users || []).filter(u => u.live) const activeCount = (users || []).filter(u => u.lastSync && Date.now() - u.lastSync < 7 * 86400000).length const disabledCount = (users || []).filter(u => u.disabled).length @@ -113,18 +116,27 @@ export default function Admin() {
Users
{users ? users.length : 'โ€”'}
+
Training now
{users ? liveUsers.length : 'โ€”'}
Active 7d
{users ? activeCount : 'โ€”'}
Disabled
{users ? disabledCount : 'โ€”'}
-
Signup
{inviteOnly ? 'invite' : 'open'}
+ {liveUsers.length > 0 &&
+

๐ŸŸข Training now

+ {liveUsers.map(u =>
openUser(u.id)}> +
{u.name}
+
{u.live.name} ยท ex {u.live.exIdx}/{u.live.exTotal} ยท {u.live.setsDone}/{u.live.setsTotal} sets
+ {dur(Date.now() - u.live.startedAt)} +
)} +
} +

Users

{(users || []).map(u =>
openUser(u.id)} style={u.disabled ? { opacity: .55 } : null}> -
{u.name} {u.admin && admin}{u.disabled && off}
-
{u.workouts} workouts{u.lastWorkout ? ' ยท last ' + fmtDate(u.lastWorkout) : ''} ยท synced {rel(u.lastSync)}
+
{u.live && '๐ŸŸข '}{u.name} {u.admin && admin}{u.disabled && off}
+
{u.live ? 'training now ยท ' + u.live.name : u.workouts + ' workouts' + (u.lastWorkout ? ' ยท last ' + fmtDate(u.lastWorkout) : '') + ' ยท synced ' + rel(u.lastSync)}
{u.hasPush && ๐Ÿ””}โ€บ
)} {users && !users.length &&
No users yet.
} diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index a9654fd..ef03abb 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -7,6 +7,7 @@ import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActiv import { fmtNum, fmtDate, todayISO, DAYN } from '../lib/format.js' import { beep, vibrate } from '../lib/sound.js' import { t } from '../lib/i18n.js' +import { api } from '../lib/api.js' import Media from '../components/Media.jsx' import NumField from '../components/NumField.jsx' import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet } from '../sheets.jsx' @@ -147,6 +148,33 @@ function ActiveWorkout() { else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged ๐Ÿƒ')) } + // Live-presence heartbeat so the admin dashboard can show who's training now. Signed-in only โ€” + // guests have no server session. Reads fresh state each tick so progress stays current. + useEffect(() => { + if (!useStore.getState().user) return + let stopped = false + const ping = active => { + const A2 = useStore.getState().S.active + if (!A2) return + const u = supersetUnits(A2.entries) + const c = Math.min(A2.cur, Math.max(0, A2.entries.length - 1)) + const ui = u.findIndex(x => x.includes(c)) + const tot = A2.entries.reduce((n, e) => n + e.sets.length, 0) + api('/api/activity', { method: 'POST', body: JSON.stringify({ + active, name: A2.name, exIdx: ui + 1, exTotal: u.length, + setsDone: setsDoneActive(A2), setsTotal: tot, startedAt: A2.start + }) }).catch(() => {}) + } + ping(true) + const iv = setInterval(() => { if (!stopped) ping(true) }, 20000) + return () => { + stopped = true; clearInterval(iv) + // best-effort "left" signal: sendBeacon survives a tab close, fetch covers in-app nav + try { navigator.sendBeacon?.('/api/activity', new Blob([JSON.stringify({ active: false })], { type: 'application/json' })) } catch { /* */ } + api('/api/activity', { method: 'POST', body: JSON.stringify({ active: false }) }).catch(() => {}) + } + }, []) + return