feat: read-only Wodify athlete client

A CLI that answers "what classes ran", "who was there" and "what was the
workout" with a single HTTP POST each -- no browser at query time.

Wodify's athlete app is an OutSystems Reactive SPA. Driving it with a headless
browser works but is slow and, for an LLM agent, expensive: a full page render
to read a few lines back out of the DOM. Its data actions are plain JSON
endpoints, so this talks to them directly.

  wodify list date 2026-07-25      time, coach, booked/max, title, duration, ID
  wodify list workout <id>         attendee names + that class's workout

Two phases. `prime` attaches over CDP to a browser that is already logged in and
captures the session cookies, the CSRF token, and each action's apiVersion and
body shape. Everything after that is stdlib HTTP -- the query path has no
third-party dependencies at all.

Three things genuinely require the browser, which is why priming exists:
- the session bearer nr1W_Theme_UI is HttpOnly, so it cannot be exported by hand
- X-CSRFToken is not in cookies, localStorage, or any JS global
- apiVersion is per-action, not global

Read-only is enforced in code, not by the credential (Wodify issues no
read-only token): an explicit allowlist plus a write-marker guard applied even
to allowlisted paths, so a careless registry edit fails closed. Tests assert
that real mutating endpoint names are refused.

Responses are cached in SQLite, keyed by the local date they were fetched on, so
a repeat query the same day touches no network. All fetching funnels through
service.py so a call site cannot forget the cache.

Staleness is explicit rather than silent: responses carry
hasModuleVersionChanged/hasApiVersionChanged, and the client raises
VersionStale/SessionExpired instead of returning a plausible empty result. That
matters because every bug found while building this produced confident wrong
output rather than an error -- see CLAUDE.md for the field-name traps.

History squashed before first publication: earlier commits embedded real gym
members' names in test fixtures. Fixtures now use fictional names.

122 tests, no network required.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-07-25 09:23:19 -07:00
commit 5a61890011
31 files changed
+3576

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Diagnostic: dump the real top-level shape of a screenservices POST body.
Values are truncated so this can be read safely. Not part of the package --
a one-off used to work out the request contract.
"""
from __future__ import annotations
import asyncio
import json
import sys
sys.path.insert(0, "src")
from wodify import actions, cdp, config # noqa: E402
WANTED = {a.path for a in actions.ACTIONS.values()}
def shape(value, depth=0):
if depth > 2:
return "..."
if isinstance(value, dict):
return {k: shape(v, depth + 1) for k, v in value.items()}
if isinstance(value, list):
return [shape(value[0], depth + 1), f"...({len(value)} items)"] if value else []
if isinstance(value, str):
return value if len(value) <= 40 else f"<str {len(value)}>"
return value
async def main() -> int:
path_arg = sys.argv[1] if len(sys.argv) > 1 else "/WodifyClient/Home"
names_only = "--names" in sys.argv
session = await cdp.CDPSession.connect()
try:
await session.open_page()
await session.navigate(config.origin() + path_arg)
seen: dict[str, dict] = {}
def observe(event):
if event.get("method") != "Network.requestWillBeSent":
return
req = (event.get("params") or {}).get("request") or {}
url = req.get("url") or ""
if "/screenservices/" not in url:
return
path = url.split("/screenservices/", 1)[1]
body = req.get("postData")
if not body or path in seen:
return
try:
parsed = json.loads(body)
except json.JSONDecodeError:
seen[path] = {"_note": "postData truncated or not JSON",
"_len": len(body)}
return
seen[path] = {
"_top_level_keys": sorted(parsed.keys()),
"_body_len": len(body),
**{k: shape(v) for k, v in parsed.items() if k != "versionInfo"},
}
await session.drain(20, observe)
finally:
await session.close()
if names_only:
print(f"screen: {path_arg}\n")
for path in sorted(seen):
print(path)
print(f"\ntotal: {len(seen)}")
return 0
interesting = {p: v for p, v in seen.items() if p in WANTED} or seen
for path, info in list(interesting.items())[:4]:
print("=" * 70)
print(path.split("/")[-1])
print(json.dumps(info, indent=1)[:1800])
print(f"\ntotal screenservices requests seen: {len(seen)}")
return 0
if __name__ == "__main__":
raise SystemExit(asyncio.run(main()))
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Show every non-empty field on each workout component, to find what the
renderer is dropping."""
from __future__ import annotations
import sys
sys.path.insert(0, "src")
from wodify import client, render # noqa: E402
date = sys.argv[1] if len(sys.argv) > 1 else "2026-07-20"
data = client.call("workout", {"SelectedDate": date})
for wod in render.find_all(data, "ResponseWorkout"):
if not isinstance(wod, dict) or str(wod.get("Id", "0")) == "0":
continue
print(f"WOD {wod.get('Name')} keys={sorted(wod)}")
for container in render.find_all(wod, "WorkoutComponents"):
if not isinstance(container, dict):
continue
for comp in container.get("List") or []:
if not isinstance(comp, dict):
continue
print("=" * 70)
for key, value in comp.items():
if isinstance(value, (dict, list)):
if isinstance(value, dict) and value:
print(f" {key}: <dict keys={sorted(value)[:6]}>")
elif isinstance(value, list) and value:
print(f" {key}: <list {len(value)} items>")
continue
if value in ("", 0, False, None, "0", "1900-01-01", "00:00:00"):
continue
text = str(value)
if key in ("Name", "Comment", "PrefixText"):
text = render.flatten_html(text).replace("\n", " | ")
print(f" {key}: {text[:220]}")
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Find the date encoding GetClasses accepts for ClientVariables.SelectedDate."""
from __future__ import annotations
import sys
sys.path.insert(0, "src")
from wodify import client, render # noqa: E402
DATE = sys.argv[1] if len(sys.argv) > 1 else "2026-07-24"
PROGRAM = sys.argv[2] if len(sys.argv) > 2 else "133059"
CANDIDATES = [
DATE,
f"{DATE}T00:00:00",
f"{DATE}T00:00:00Z",
f"{DATE}T07:00:00.000Z",
f"{DATE}T00:00:00.000Z",
]
for value in CANDIDATES:
try:
data = client.call("classes", {"SelectedDate": value, "GymProgramId": PROGRAM})
except Exception as exc: # noqa: BLE001 - probe
print(f"{value!r:32} -> ERROR {type(exc).__name__}: {str(exc)[:110]}")
continue
wods = render.find_all(data, "ProgramWODList")
rows = []
for w in wods:
if isinstance(w, dict):
rows.extend(w.get("List") or [])
real = [r for r in rows if isinstance(r, dict) and r.get("Id") not in (None, "0")]
comps = sum(
len((c or {}).get("List") or [])
for r in real for c in [r.get("WorkoutComponents")]
)
names = [r.get("Name") or "(unnamed)" for r in real]
print(f"{value!r:32} -> wod_records={len(real)} components={comps} names={names[:3]}")
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python3
"""List a day's classes with program ids, to see which share a workout."""
from __future__ import annotations
import sys
sys.path.insert(0, "src")
from wodify import client, render # noqa: E402
date = sys.argv[1] if len(sys.argv) > 1 else "2026-07-20"
rows = render.class_rows(client.call("schedule", {"FromDate": date}))
print(f"{date}: {len(rows)} classes\n")
for r in rows:
cap = f"{r['booked']}|{r['limit']}"
print(f"{r['start']} {r['name']:<28} program={r['program_id']:<8} "
f"{cap:<7} coach={r['coach']:<16} class_id={r['class_id']}")
programs = sorted({r["program_id"] for r in rows if r["program_id"]})
print(f"\ndistinct programs: {programs}")
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python3
"""Print captured body templates (structure only) for chosen actions."""
from __future__ import annotations
import json
import pathlib
import sys
sys.path.insert(0, "src")
from wodify import actions, config # noqa: E402
wanted = sys.argv[1:] or ["attendees", "classdetail", "coach"]
cache = json.loads(pathlib.Path(config.cache_path()).read_text(encoding="utf-8"))
for key in wanted:
action = actions.ACTIONS[key]
entry = (cache.get("actions") or {}).get(action.path) or {}
print("=" * 70)
print(f"{key} view={entry.get('view_name')}")
print(json.dumps(entry.get("body_template"), indent=1)[:1400])