Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

API: GET /api/nudge-check, how one day stands

Duarte Santos870609755aa3
diff --git a/api/openapi.yaml b/api/openapi.yaml
index 6f3a0c8fc..6d5c403f0 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -1640,6 +1640,45 @@ paths:
wid: { type: string, description: 'The write id (`_wid`) of the stored document; absent before its first write.' }
'401': { $ref: '#/components/responses/Unauthorized' }
+ /api/nudge-check:
+ get:
+ tags: [data]
+ operationId: nudgeCheck
+ summary: Whether a day was trained or excused (the phone's background check)
+ description: |
+ Asked by the phone app in the background before a missed-day nudge or a workout-day
+ reminder it scheduled on itself fires, so a day trained on another device is not
+ nudged. A few bytes instead of the whole document: `done` is true when a workout is
+ dated that day or the day carries a note; `nudge` is whether the server's copy of the
+ nudge rule would still nudge that day (false once it is done, or when the plan has no
+ session for it); `rev` is the profile's revision. Nothing of the workouts themselves.
+ parameters:
+ - name: date
+ in: query
+ required: true
+ schema: { type: string, format: date }
+ description: The day, YYYY-MM-DD, in the phone's own calendar.
+ responses:
+ '200':
+ description: How that day stands.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ date: { type: string, format: date }
+ done: { type: boolean }
+ nudge: { type: boolean }
+ rev: { type: integer }
+ example: { date: "2026-09-14", done: true, nudge: false, rev: 7 }
+ '400':
+ description: '`date-invalid`: not a YYYY-MM-DD date.'
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "date must be YYYY-MM-DD", code: "date-invalid" }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+
/api/media/{hash}:
parameters:
- name: hash
diff --git a/api/server.js b/api/server.js
index a09900c46..35e6ca669 100644
--- a/api/server.js
+++ b/api/server.js
@@ -2247,6 +2247,29 @@ const routes = {
json(res, 200, { rev: doc?._rev || 0, ...(doc?._wid ? { wid: doc._wid } : {}) });
},
+ // The phone app's background check before a missed-day nudge or a workout-day reminder it
+ // scheduled on itself (frontend lib/nudge-check.js, the native NudgeCheck plugin): whether the
+ // day was trained or excused somewhere else since the phone last synced. A few bytes instead of
+ // the whole document, which can be megabytes, because iOS gives a background refresh some
+ // seconds and the phone pays for every byte of it: `done` (a workout dated that day, or a day
+ // note), `nudge` (whether the server's copy of the nudge rule, api/nudge.js, would still nudge
+ // that day; a plan changed on another device moves it too) and the revision. Nothing of the
+ // workouts themselves.
+ 'GET /api/nudge-check': async (req, res) => {
+ const user = readSession(req);
+ if (!user) return json(res, 401, { error: 'not signed in' });
+ const date = new URL(req.url, 'http://x').searchParams.get('date') || '';
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || Number.isNaN(Date.parse(date + 'T00:00:00Z'))) {
+ return json(res, 400, { error: 'date must be YYYY-MM-DD', code: 'date-invalid' });
+ }
+ const doc = readStateCached(user.id) || {};
+ const workouts = Array.isArray(doc.workouts) ? doc.workouts : [];
+ const done = workouts.some(w => w && w.d === date) || excusedOn(doc, date);
+ let nudge = false;
+ try { nudge = !done && !!nudgeFor(doc, date); } catch { nudge = true; } // unreadable: keep what the phone planned
+ json(res, 200, { date, done, nudge, rev: doc._rev || 0 });
+ },
+
'PUT /api/data': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
diff --git a/api/test/server-nudge-check.test.js b/api/test/server-nudge-check.test.js
new file mode 100644
index 000000000..ec6b7501c
--- /dev/null
+++ b/api/test/server-nudge-check.test.js
@@ -0,0 +1,90 @@
+/* GET /api/nudge-check: what the phone app's background check asks before a missed-day nudge or
+ a workout-day reminder it scheduled on itself fires. Whether that day was trained or excused
+ elsewhere, whether the server would still nudge it, and the revision: nothing of the workouts
+ themselves. Real server.js in a child, the same harness as server-admin-delete.test.js. */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
+
+const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SECRET = crypto.randomBytes(32).toString('hex');
+const mintSession = uid => {
+ const payload = `${uid}:${Date.now() + 86400000}:0`;
+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
+};
+const ANA = 'u_ana', BEA = 'u_bea';
+// Push every weekday; 2026-09-14 is a Monday.
+const everyDay = { 0: 'push', 1: 'push', 2: 'push', 3: 'push', 4: 'push', 5: 'push', 6: 'push' };
+const state = {
+ _rev: 7, unit: 'kg', routines: [{ id: 'push', name: 'Push Day' }], week: everyDay, dayPlan: {},
+ workouts: [{ id: 'w1', d: '2026-09-14', routineId: 'push', start: 1, name: 'Secret session', entries: [{ id: 'bench', sets: [{ w: 100, r: 5 }] }] }],
+ dayNotes: { '2026-09-15': { tag: 'sick', _ts: 1 }, '2026-09-16': { _ts: 2 } },
+ reminder: { on: true, nudge: true, time: '08:00' },
+};
+
+async function startServer(t) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-nudgecheck-'));
+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
+ const now = new Date().toISOString();
+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
+ users: [{ id: ANA, name: 'Ana', created: now }, { id: BEA, name: 'Bea', created: now }], creds: [], subs: [], invites: [],
+ }));
+ fs.writeFileSync(path.join(dataDir, `state-${ANA}.json`), JSON.stringify(state));
+ const child = spawn(process.execPath, ['server.js'], {
+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' },
+ });
+ const h = { log: '' };
+ child.stdout.on('data', d => h.log += d);
+ child.stderr.on('data', d => h.log += d);
+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
+ const api = `http://127.0.0.1:${await boundPort(child, () => h.log)}`;
+ h.check = async (date, headers = { Authorization: `Bearer ${mintSession(ANA)}` }) => {
+ const r = await fetch(`${api}/api/nudge-check${date == null ? '' : '?date=' + encodeURIComponent(date)}`, { headers });
+ return { status: r.status, text: await r.text() };
+ };
+ return h;
+}
+
+test('needs a session: a paired phone’s token or a cookie', async t => {
+ const h = await startServer(t);
+ assert.equal((await h.check('2026-09-14', {})).status, 401);
+ assert.equal((await h.check('2026-09-14', { Authorization: 'Bearer nonsense' })).status, 401);
+ const cookie = await h.check('2026-09-14', { Cookie: `gymsid=${mintSession(ANA)}` });
+ assert.equal(cookie.status, 200);
+});
+
+test('a day trained or noted is done; a planned day with nothing is still nudged', async t => {
+ const h = await startServer(t);
+ const ask = async d => JSON.parse((await h.check(d)).text);
+ assert.deepEqual(await ask('2026-09-14'), { date: '2026-09-14', done: true, nudge: false, rev: 7 }, 'a workout');
+ assert.deepEqual(await ask('2026-09-15'), { date: '2026-09-15', done: true, nudge: false, rev: 7 }, 'a day note');
+ // A cleared note (only a stamp) excuses nothing.
+ assert.deepEqual(await ask('2026-09-16'), { date: '2026-09-16', done: false, nudge: true, rev: 7 });
+ assert.deepEqual(await ask('2026-09-17'), { date: '2026-09-17', done: false, nudge: true, rev: 7 });
+});
+
+test('says nothing of the workouts, and nothing of anyone else', async t => {
+ const h = await startServer(t);
+ const mine = await h.check('2026-09-14');
+ assert.equal(Object.keys(JSON.parse(mine.text)).sort().join(), 'date,done,nudge,rev');
+ assert.doesNotMatch(mine.text, /Secret|bench|push|sick/i);
+ // Bea has no state at all: nothing done, nothing planned, revision 0. Ana's day stays hers.
+ const bea = JSON.parse((await h.check('2026-09-14', { Authorization: `Bearer ${mintSession(BEA)}` })).text);
+ assert.deepEqual(bea, { date: '2026-09-14', done: false, nudge: false, rev: 0 });
+});
+
+test('a date that is not one is refused', async t => {
+ const h = await startServer(t);
+ for (const d of [null, '', 'today', '2026-9-14', '2026-13-45', '2026-09-14T00:00']) {
+ const r = await h.check(d);
+ assert.equal(r.status, 400, String(d));
+ assert.equal(JSON.parse(r.text).code, 'date-invalid');
+ }
+});
diff --git a/website/api.html b/website/api.html
index f52000bcd..80bfe2528 100644
--- a/website/api.html
+++ b/website/api.html
@@ -245,7 +245,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
<p class="api-facts">
<span>OpenAPI 3.1.0</span>
<span>openGym v1.4.1</span>
- <span>70 endpoints</span>
+ <span>71 endpoints</span>
<span>AGPL-3.0-or-later</span>
</p>
@@ -1613,6 +1613,42 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
</div>
</div>
</details>
+
+<details class="ep" id="op-nudgeCheck">
+ <summary>
+ <span class="m get">GET</span>
+ <span class="ep-path"><code>/api/nudge-check</code></span>
+ <span class="ep-chev" aria-hidden="true"></span>
+ <span class="ep-sum">Whether a day was trained or excused (the phone's background check)</span>
+ </summary>
+ <div class="ep-body">
+<p>Asked by the phone app in the background before a missed-day nudge or a workout-day reminder it scheduled on itself fires, so a day trained on another device is not nudged. A few bytes instead of the whole document: <code>done</code> is true when a workout is dated that day or the day carries a note; <code>nudge</code> is whether the server's copy of the nudge rule would still nudge that day (false once it is done, or when the plan has no session for it); <code>rev</code> is the profile's revision. Nothing of the workouts themselves.</p>
+ <p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session: the cookie set at sign-in, or <code>Authorization: Bearer &lt;token&gt;</code> from mobile-app pairing.</span></p>
+<p class="ep-h">Query parameters</p><div class="ptab">
+ <div class="prow">
+ <span class="p-name">date<em class="p-req" title="required">required</em></span>
+ <span class="p-type">string <span class="p-hint">(date)</span></span>
+ <span class="p-desc">The day, YYYY-MM-DD, in the phone's own calendar.</span>
+ </div>
+</div>
+
+ <p class="ep-h">Responses</p>
+ <div class="ptab">
+ <div class="prow rrow">
+ <span class="r-code s2">200</span>
+ <span class="p-desc">How that day stands.<span class="r-sig">{ date: string <span class="p-hint">(date)</span>, done: boolean, nudge: boolean, rev: integer }</span></span>
+ </div>
+ <div class="prow rrow">
+ <span class="r-code s4">400</span>
+ <span class="p-desc"><code>date-invalid</code>: not a YYYY-MM-DD date.<span class="r-sig"><code>{&quot;error&quot;:&quot;date must be YYYY-MM-DD&quot;}</code></span></span>
+ </div>
+ <div class="prow rrow">
+ <span class="r-code s4">401</span>
+ <span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{&quot;error&quot;:&quot;not signed in&quot;}</code></span></span>
+ </div>
+ </div>
+ </div>
+</details>
</div>
</section>