Add push notifications: rest-timer alert + workout-day reminder
Web Push (VAPID) backend: keys auto-generated on first run, per-user subscriptions, one new dependency (web-push). The rest timer schedules a server-side push on start/extend and cancels it on skip or on-screen completion, so it only actually fires if the tab got suspended before finishing. A per-minute check sends an optional daily reminder on days with a planned routine that hasn't been logged yet. Opt in per-profile in Settings — requires a signed-in passkey profile.
This commit is contained in:
1 parent
84c59129e3
commit
4c2b6344f7
11 files changed
+448
-7
No files matched your search
@@ -18,3 +18,13 @@ RP_NAME=openGym
|
||||
# RP_NAME=openGym
|
||||
#
|
||||
# (Point your proxy at the web container's WEB_PORT. See docs/SELF_HOSTING.md.)
|
||||
|
||||
# ── Notifications (optional) ───────────────────────────────────────────────
|
||||
# Push works out of the box — VAPID keys are generated on first run and saved
|
||||
# to ./data/vapid.json. The only thing worth setting yourself:
|
||||
#
|
||||
# TZ=Europe/Zurich
|
||||
#
|
||||
# Sets the container's timezone so the workout-day reminder fires at the time
|
||||
# you actually pick, not UTC. Find your zone name at
|
||||
# https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
|
||||
@@ -1,5 +1,14 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
- 🔔 Push notifications: rest-timer-over alert (fires even if the app is closed) and an optional
|
||||
daily reminder on days you have a workout planned but haven't logged one yet. Opt in per-profile
|
||||
in Settings — requires a signed-in passkey profile. Backend gains one dependency (`web-push`);
|
||||
VAPID keys are generated on first run.
|
||||
- 🐛 Fixed the rest timer stalling when the tab/app is backgrounded — it's now anchored to a real
|
||||
timestamp instead of a plain per-second counter, so it stays accurate after you come back.
|
||||
|
||||
## v1.0.0 — 2026-07-20
|
||||
|
||||
First public release. A complete, self-hostable gym & body-weight tracker.
|
||||
|
||||
Generated
+160
-1
@@ -7,8 +7,10 @@
|
||||
"": {
|
||||
"name": "gym-api",
|
||||
"version": "1.0.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@simplewebauthn/server": "^13.1.1"
|
||||
"@simplewebauthn/server": "^13.1.1",
|
||||
"web-push": "^3.6.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@hexagon/base64": {
|
||||
@@ -194,6 +196,25 @@
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/agent-base": {
|
||||
"version": "7.1.4",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
|
||||
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1.js": {
|
||||
"version": "5.4.1",
|
||||
"resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz",
|
||||
"integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==",
|
||||
"dependencies": {
|
||||
"bn.js": "^4.0.0",
|
||||
"inherits": "^2.0.1",
|
||||
"minimalistic-assert": "^1.0.0",
|
||||
"safer-buffer": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1js": {
|
||||
"version": "3.0.10",
|
||||
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",
|
||||
@@ -207,6 +228,102 @@
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bn.js": {
|
||||
"version": "4.12.5",
|
||||
"resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.5.tgz",
|
||||
"integrity": "sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ=="
|
||||
},
|
||||
"node_modules/buffer-equal-constant-time": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
|
||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"supports-color": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/ecdsa-sig-formatter": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
||||
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
|
||||
"dependencies": {
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/http_ece": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz",
|
||||
"integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==",
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/https-proxy-agent": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
|
||||
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
|
||||
"dependencies": {
|
||||
"agent-base": "^7.1.2",
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
|
||||
},
|
||||
"node_modules/jwa": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
|
||||
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
|
||||
"dependencies": {
|
||||
"buffer-equal-constant-time": "^1.0.1",
|
||||
"ecdsa-sig-formatter": "1.0.11",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/jws": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
|
||||
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
|
||||
"dependencies": {
|
||||
"jwa": "^2.0.1",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/minimalistic-assert": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz",
|
||||
"integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A=="
|
||||
},
|
||||
"node_modules/minimist": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
||||
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
|
||||
},
|
||||
"node_modules/pvtsutils": {
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
|
||||
@@ -228,6 +345,30 @@
|
||||
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
|
||||
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
]
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
@@ -248,6 +389,24 @@
|
||||
"version": "1.14.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
|
||||
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="
|
||||
},
|
||||
"node_modules/web-push": {
|
||||
"version": "3.6.7",
|
||||
"resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz",
|
||||
"integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==",
|
||||
"dependencies": {
|
||||
"asn1.js": "^5.3.0",
|
||||
"http_ece": "1.2.0",
|
||||
"https-proxy-agent": "^7.0.0",
|
||||
"jws": "^4.0.0",
|
||||
"minimist": "^1.2.5"
|
||||
},
|
||||
"bin": {
|
||||
"web-push": "src/cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -9,6 +9,7 @@
|
||||
"start": "node server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@simplewebauthn/server": "^13.1.1"
|
||||
"@simplewebauthn/server": "^13.1.1",
|
||||
"web-push": "^3.6.7"
|
||||
}
|
||||
}
|
||||
+129
-1
@@ -8,6 +8,7 @@ import {
|
||||
generateRegistrationOptions, verifyRegistrationResponse,
|
||||
generateAuthenticationOptions, verifyAuthenticationResponse
|
||||
} from '@simplewebauthn/server';
|
||||
import webpush from 'web-push';
|
||||
|
||||
const PORT = +(process.env.PORT || 3000);
|
||||
const DATA = process.env.DATA_DIR || '/data';
|
||||
@@ -27,8 +28,9 @@ if (!fs.existsSync(secretFile)) fs.writeFileSync(secretFile, crypto.randomBytes(
|
||||
const SECRET = fs.readFileSync(secretFile, 'utf8').trim();
|
||||
|
||||
const dbFile = path.join(DATA, 'db.json');
|
||||
let db = { users: [], creds: [] };
|
||||
let db = { users: [], creds: [], subs: [] };
|
||||
try { db = JSON.parse(fs.readFileSync(dbFile, 'utf8')); } catch {}
|
||||
db.subs = db.subs || [];
|
||||
function saveDb() { atomicWrite(dbFile, JSON.stringify(db, null, 2)); }
|
||||
function atomicWrite(file, content) {
|
||||
const tmp = file + '.tmp';
|
||||
@@ -36,6 +38,85 @@ function atomicWrite(file, content) {
|
||||
fs.renameSync(tmp, file);
|
||||
}
|
||||
const stateFile = uid => path.join(DATA, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json');
|
||||
function readState(uid) {
|
||||
try { return JSON.parse(fs.readFileSync(stateFile(uid), 'utf8')); } catch { return null; }
|
||||
}
|
||||
|
||||
/* ---------- push notifications (Web Push / VAPID) ---------- */
|
||||
const vapidFile = path.join(DATA, 'vapid.json');
|
||||
let vapid;
|
||||
try { vapid = JSON.parse(fs.readFileSync(vapidFile, 'utf8')); }
|
||||
catch { vapid = webpush.generateVAPIDKeys(); fs.writeFileSync(vapidFile, JSON.stringify(vapid), { mode: 0o600 }); }
|
||||
const VAPID_SUBJECT = process.env.VAPID_SUBJECT || (SECURE ? ORIGIN : 'mailto:admin@localhost');
|
||||
webpush.setVapidDetails(VAPID_SUBJECT, vapid.publicKey, vapid.privateKey);
|
||||
|
||||
async function sendPush(userId, payload) {
|
||||
const subs = db.subs.filter(s => s.userId === userId);
|
||||
if (!subs.length) return;
|
||||
const body = JSON.stringify(payload);
|
||||
let dirty = false;
|
||||
await Promise.all(subs.map(async sub => {
|
||||
try { await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, body); }
|
||||
catch (e) {
|
||||
if (e.statusCode === 404 || e.statusCode === 410) {
|
||||
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
|
||||
}
|
||||
}
|
||||
}));
|
||||
if (dirty) saveDb();
|
||||
}
|
||||
|
||||
// Rest-timer alerts: client schedules on start/extend, cancels on skip or on-screen completion —
|
||||
// this only fires when the tab was backgrounded/suspended and never got to cancel it itself.
|
||||
const restTimers = new Map(); // userId -> Timeout
|
||||
function scheduleRestTimer(userId, sec) {
|
||||
const t = restTimers.get(userId);
|
||||
if (t) clearTimeout(t);
|
||||
restTimers.set(userId, setTimeout(() => {
|
||||
restTimers.delete(userId);
|
||||
sendPush(userId, { title: 'Rest over 💪', body: 'Time for your next set.', tag: 'rest-timer' });
|
||||
}, sec * 1000));
|
||||
}
|
||||
function cancelRestTimer(userId) {
|
||||
const t = restTimers.get(userId);
|
||||
if (t) { clearTimeout(t); restTimers.delete(userId); }
|
||||
}
|
||||
|
||||
// "Workout planned today" reminder — one per user per day, at their chosen time.
|
||||
// Duplicated (not imported) from frontend/src/lib/history.js effectiveRoutineId — tiny pure helper, not worth sharing across the two runtimes.
|
||||
function effectiveRoutineId(S, iso) {
|
||||
const ov = S.dayPlan?.[iso];
|
||||
if (ov === 'rest') return null;
|
||||
if (ov && S.routines?.some(r => r.id === ov)) return ov;
|
||||
const wd = new Date(iso + 'T12:00:00').getDay();
|
||||
return S.week?.[wd] || null;
|
||||
}
|
||||
const todayISO = () => {
|
||||
const d = new Date();
|
||||
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
|
||||
};
|
||||
setInterval(() => {
|
||||
const now = new Date();
|
||||
const hhmm = String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0');
|
||||
const today = todayISO();
|
||||
for (const user of db.users) {
|
||||
if (user.lastReminder === today) continue;
|
||||
if (!db.subs.some(s => s.userId === user.id)) continue;
|
||||
const S = readState(user.id);
|
||||
if (!S?.reminder?.on || S.reminder.time !== hhmm) continue;
|
||||
if ((S.workouts || []).some(w => w.d === today)) continue;
|
||||
const rid = effectiveRoutineId(S, today);
|
||||
if (!rid) continue; // rest day — nothing planned
|
||||
const routine = (S.routines || []).find(r => r.id === rid);
|
||||
user.lastReminder = today;
|
||||
saveDb();
|
||||
sendPush(user.id, {
|
||||
title: routine ? `${routine.emoji || '🏋️'} ${routine.name} today` : 'Workout planned today',
|
||||
body: "It's on your plan — let's go 💪",
|
||||
tag: 'day-reminder'
|
||||
});
|
||||
}
|
||||
}, 60000).unref();
|
||||
|
||||
/* ---------- sessions (signed cookie) ---------- */
|
||||
function sign(payload) {
|
||||
@@ -223,6 +304,53 @@ const routes = {
|
||||
delete body.state.active; // in-progress workouts stay device-local
|
||||
atomicWrite(stateFile(user.id), JSON.stringify(body.state));
|
||||
json(res, 200, { ok: true, ts: body.state._ts || null });
|
||||
},
|
||||
|
||||
'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),
|
||||
|
||||
'POST /api/push/subscribe': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const body = await readBody(req);
|
||||
const sub = body.subscription;
|
||||
if (!sub?.endpoint || !sub?.keys?.p256dh || !sub?.keys?.auth) return json(res, 400, { error: 'invalid subscription' });
|
||||
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint);
|
||||
db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys: sub.keys, created: new Date().toISOString() });
|
||||
saveDb();
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
'POST /api/push/unsubscribe': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const body = await readBody(req);
|
||||
db.subs = db.subs.filter(s => !(s.userId === user.id && s.endpoint === body.endpoint));
|
||||
saveDb();
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
'POST /api/push/test': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
await sendPush(user.id, { title: 'openGym', body: 'Test notification ✅ — this is what alerts look like.', tag: 'test' });
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
'POST /api/push/rest-timer': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const body = await readBody(req);
|
||||
const sec = Math.max(1, Math.min(3600, Math.round(+body.seconds || 0)));
|
||||
if (!sec) return json(res, 400, { error: 'seconds required' });
|
||||
scheduleRestTimer(user.id, sec);
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
'POST /api/push/rest-timer/cancel': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
cancelRestTimer(user.id);
|
||||
json(res, 200, { ok: true });
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+19
-1
@@ -99,7 +99,23 @@ tar czf opengym-backup-$(date +%F).tar.gz data/
|
||||
That archive contains all profiles, passkeys and workout history. Restore by unpacking it back
|
||||
into the project folder. (Individual users can also export their own data as JSON from Settings.)
|
||||
|
||||
## 6. Updating
|
||||
## 6. Notifications
|
||||
|
||||
openGym can push two kinds of alert to your phone/desktop, even when the app isn't open:
|
||||
rest-timer-over, and a reminder on days you have a workout planned but haven't logged one yet.
|
||||
Turn it on per-profile in **Settings → Notifications** (requires a signed-in passkey profile and
|
||||
HTTPS — see section 3).
|
||||
|
||||
No setup needed server-side: VAPID keys are generated on first run and saved to `./data/vapid.json`.
|
||||
The one thing worth setting is your timezone, so the day reminder fires at the time you actually
|
||||
picked rather than UTC:
|
||||
|
||||
```bash
|
||||
# .env
|
||||
TZ=Europe/Zurich
|
||||
```
|
||||
|
||||
## 7. Updating
|
||||
|
||||
```bash
|
||||
git pull
|
||||
@@ -117,4 +133,6 @@ downloaded media are untouched.
|
||||
| "verification failed" on login | `RP_ID`/`ORIGIN` don't match the URL in the address bar. Make them exact, restart. |
|
||||
| Media didn't download | `docker compose logs media`. Re-run `docker compose up -d`, or run `./scripts/fetch-media.sh`. |
|
||||
| Port 8080 already used | Set `WEB_PORT=9090` in `.env` (and update `ORIGIN` for local testing). |
|
||||
| No "Notifications" option in Settings | Requires a signed-in profile and HTTPS (or `localhost`) — guest mode and plain HTTP over LAN can't subscribe. |
|
||||
| Day reminder fires at the wrong time | Set `TZ=Continent/City` in `.env` and restart (see section 6). Defaults to UTC. |
|
||||
| Want to reset a stuck login | Delete the cookie in your browser; sessions are just signed cookies. |
|
||||
@@ -8,6 +8,24 @@ self.addEventListener('activate', e => {
|
||||
Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
|
||||
).then(() => self.clients.claim()))
|
||||
})
|
||||
self.addEventListener('push', e => {
|
||||
const data = e.data ? e.data.json() : {}
|
||||
e.waitUntil(self.registration.showNotification(data.title || 'openGym', {
|
||||
body: data.body || '',
|
||||
icon: 'icon-512.png',
|
||||
badge: 'icon-180.png',
|
||||
tag: data.tag || 'opengym',
|
||||
renotify: true
|
||||
}))
|
||||
})
|
||||
self.addEventListener('notificationclick', e => {
|
||||
e.notification.close()
|
||||
e.waitUntil(self.clients.matchAll({ type: 'window' }).then(clients => {
|
||||
const c = clients.find(c => 'focus' in c)
|
||||
return c ? c.focus() : self.clients.openWindow('./')
|
||||
}))
|
||||
})
|
||||
|
||||
self.addEventListener('fetch', e => {
|
||||
const url = new URL(e.request.url)
|
||||
if (e.request.method !== 'GET' || url.origin !== location.origin) return
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// Web Push subscribe/unsubscribe — requires a signed-in profile (subscriptions are stored
|
||||
// server-side per user, same as everything else under /api).
|
||||
import { api } from './api.js'
|
||||
|
||||
export const pushSupported = () => 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window
|
||||
export const pushPermission = () => (pushSupported() ? Notification.permission : 'unsupported')
|
||||
|
||||
const urlBase64ToUint8Array = b64 => {
|
||||
const padded = (b64 + '='.repeat((4 - b64.length % 4) % 4)).replace(/-/g, '+').replace(/_/g, '/')
|
||||
const raw = atob(padded)
|
||||
return Uint8Array.from([...raw].map(c => c.charCodeAt(0)))
|
||||
}
|
||||
|
||||
export async function enablePush() {
|
||||
if (!pushSupported()) throw new Error('Push notifications are not supported in this browser')
|
||||
const perm = await Notification.requestPermission()
|
||||
if (perm !== 'granted') throw new Error('Notifications permission was not granted')
|
||||
const reg = await navigator.serviceWorker.ready
|
||||
const { key } = await api('/api/push/public-key')
|
||||
const subscription = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(key) })
|
||||
await api('/api/push/subscribe', { method: 'POST', body: JSON.stringify({ subscription: subscription.toJSON() }) })
|
||||
}
|
||||
|
||||
export async function disablePush() {
|
||||
if (!pushSupported()) return
|
||||
const reg = await navigator.serviceWorker.ready
|
||||
const sub = await reg.pushManager.getSubscription()
|
||||
if (!sub) return
|
||||
await sub.unsubscribe()
|
||||
await api('/api/push/unsubscribe', { method: 'POST', body: JSON.stringify({ endpoint: sub.endpoint }) }).catch(() => {})
|
||||
}
|
||||
|
||||
export const sendTestPush = () => api('/api/push/test', { method: 'POST', body: '{}' })
|
||||
@@ -6,7 +6,8 @@ export const DEF = {
|
||||
unit: 'kg', restSec: 90, sound: true,
|
||||
theme: 'dark', accent: 'lime', targetW: null,
|
||||
bodyweight: [], routines: [], week: {}, dayPlan: {},
|
||||
exWeights: {}, workouts: [], active: null
|
||||
exWeights: {}, workouts: [], active: null,
|
||||
reminder: { on: false, time: '08:00' }
|
||||
}
|
||||
const clone = o => JSON.parse(JSON.stringify(o))
|
||||
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { create } from 'zustand'
|
||||
import { uid } from '../lib/format.js'
|
||||
import { beep, vibrate } from '../lib/sound.js'
|
||||
import { api } from '../lib/api.js'
|
||||
import { useStore } from './useStore.js'
|
||||
|
||||
// Fire-and-forget: lets the server push a "rest over" alert if this tab gets suspended
|
||||
// before the local timer completes. No-ops for guests / offline.
|
||||
const pushRestTimer = sec => { if (useStore.getState().user) api('/api/push/rest-timer', { method: 'POST', body: JSON.stringify({ seconds: sec }) }).catch(() => {}) }
|
||||
const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push/rest-timer/cancel', { method: 'POST', body: '{}' }).catch(() => {}) }
|
||||
|
||||
let toastTm = null
|
||||
let timerInt = null
|
||||
let timerTick = null
|
||||
@@ -31,6 +37,7 @@ export const useUI = create((set, get) => ({
|
||||
get().stopRest()
|
||||
const endsAt = Date.now() + sec * 1000
|
||||
set({ timer: { left: sec, total: sec, endsAt } })
|
||||
pushRestTimer(sec)
|
||||
timerTick = () => {
|
||||
const t = get().timer
|
||||
if (!t) return
|
||||
@@ -47,10 +54,17 @@ export const useUI = create((set, get) => ({
|
||||
timerInt = setInterval(timerTick, 1000)
|
||||
document.addEventListener('visibilitychange', timerTick)
|
||||
},
|
||||
addRest(sec) { const t = get().timer; if (t) set({ timer: { ...t, left: t.left + sec, total: t.total + sec, endsAt: t.endsAt + sec * 1000 } }) },
|
||||
addRest(sec) {
|
||||
const t = get().timer
|
||||
if (!t) return
|
||||
const left = t.left + sec
|
||||
set({ timer: { ...t, left, total: t.total + sec, endsAt: t.endsAt + sec * 1000 } })
|
||||
pushRestTimer(left)
|
||||
},
|
||||
stopRest() {
|
||||
if (timerInt) clearInterval(timerInt); timerInt = null
|
||||
if (timerTick) document.removeEventListener('visibilitychange', timerTick); timerTick = null
|
||||
if (get().timer) cancelPushRestTimer()
|
||||
set({ timer: null })
|
||||
}
|
||||
}))
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useRef } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore, DEF, hasData } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { ACCENTS, todayISO } from '../lib/format.js'
|
||||
import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
|
||||
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
|
||||
import { loadStarterPlan, confirmSheet } from '../sheets.jsx'
|
||||
|
||||
export default function Settings() {
|
||||
@@ -82,6 +83,8 @@ export default function Settings() {
|
||||
<div className="small dim" style={{ marginTop: 6 }}>Note: switching units only changes the label — logged numbers are not converted.</div>
|
||||
</div>
|
||||
|
||||
{user && <NotificationsCard S={S} update={update} toast={toast} />}
|
||||
|
||||
<div className="card">
|
||||
<h2>Data</h2>
|
||||
<button className="btn" onClick={doExport}>⬇️ Export backup (JSON)</button>
|
||||
@@ -100,6 +103,53 @@ export default function Settings() {
|
||||
</div>
|
||||
}
|
||||
|
||||
function NotificationsCard({ S, update, toast }) {
|
||||
const [on, setOn] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const supported = pushSupported()
|
||||
|
||||
useEffect(() => {
|
||||
if (!supported) return
|
||||
navigator.serviceWorker.ready.then(reg => reg.pushManager.getSubscription()).then(sub => setOn(!!sub)).catch(() => {})
|
||||
}, [supported])
|
||||
|
||||
const toggle = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
if (on) { await disablePush(); setOn(false); toast('Notifications off') }
|
||||
else { await enablePush(); setOn(true); toast('Notifications on 🔔') }
|
||||
} catch (e) { toast(e.message || 'Could not change notification settings') }
|
||||
setBusy(false)
|
||||
}
|
||||
const test = async () => {
|
||||
try { await sendTestPush(); toast('Test sent — should arrive any second') }
|
||||
catch (e) { toast(e.message || 'Test failed') }
|
||||
}
|
||||
|
||||
return <div className="card">
|
||||
<h2>Notifications</h2>
|
||||
{!supported ? <div className="small dim">Not supported in this browser.</div> : <>
|
||||
<div className="row between" style={{ padding: '8px 0' }}>
|
||||
<div><span>Push notifications</span><div className="small muted">Rest-timer alerts, even if openGym is closed.</div></div>
|
||||
<button className={'chip' + (on ? ' on' : '')} disabled={busy} onClick={toggle}>{on ? 'On 🔔' : 'Off 🔕'}</button>
|
||||
</div>
|
||||
{on && <>
|
||||
<div className="row between" style={{ padding: '8px 0' }}>
|
||||
<span>Workout day reminder</span>
|
||||
<button className={'chip' + (S.reminder?.on ? ' on' : '')} onClick={() => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), on: !s.reminder?.on } })}>{S.reminder?.on ? 'On' : 'Off'}</button>
|
||||
</div>
|
||||
{S.reminder?.on && <div className="row between" style={{ padding: '8px 0' }}>
|
||||
<span>Reminder time</span>
|
||||
<input type="time" className="input" style={{ width: 120 }} value={S.reminder?.time || DEF.reminder.time}
|
||||
onChange={e => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), time: e.target.value } })} />
|
||||
</div>}
|
||||
<div className="small dim" style={{ margin: '6px 0' }}>Only sent on days you have a routine planned and haven't logged a workout yet.</div>
|
||||
<button className="btn sm" onClick={test}>Send test notification</button>
|
||||
</>}
|
||||
</>}
|
||||
</div>
|
||||
}
|
||||
|
||||
function RegisterInline({ close, setUser, pushState, pullState, toast }) {
|
||||
const nameRef = useRef(null)
|
||||
const go = async () => {
|
||||
|
||||
Reference in new issue
Block a user