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:
commit
5a61890011
31 files changed
+3576
No files matched your search
@@ -0,0 +1,26 @@
|
||||
"""Read-only client for the Wodify athlete app.
|
||||
|
||||
Never reserves, cancels, checks in, logs results, or changes settings. See
|
||||
``actions.py`` for how that is enforced, and CLAUDE.md for why it matters.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
from .actions import UnknownActionError, WriteAttemptError # noqa: F401
|
||||
from .client import ( # noqa: F401
|
||||
NotPrimedError,
|
||||
SessionExpiredError,
|
||||
VersionStaleError,
|
||||
call,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"__version__",
|
||||
"call",
|
||||
"NotPrimedError",
|
||||
"SessionExpiredError",
|
||||
"VersionStaleError",
|
||||
"UnknownActionError",
|
||||
"WriteAttemptError",
|
||||
]
|
||||
@@ -0,0 +1,3 @@
|
||||
from .cli import main
|
||||
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Read-only action allowlist, and the guard that enforces it.
|
||||
|
||||
The session credential this client uses is a full login -- Wodify issues no
|
||||
read-only token -- so nothing at the credential layer prevents a write. This
|
||||
module *is* the enforcement. Two independent layers, both required:
|
||||
|
||||
1. ``ACTIONS`` -- an explicit allowlist. Anything unregistered cannot be called.
|
||||
2. ``assert_read_only`` -- refuses any path containing a write marker, applied
|
||||
even to allowlisted entries, so a careless registry edit still fails closed.
|
||||
|
||||
Keep both. See tests/test_actions.py.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
|
||||
#: Substrings that mark a mutating OutSystems action. Matched case-insensitively
|
||||
#: against the action path. Deliberately blunt: a false positive is a developer
|
||||
#: annoyance, a false negative charges the user money or takes someone's spot.
|
||||
WRITE_MARKERS: tuple[str, ...] = (
|
||||
"create", "update", "delete", "save", "insert", "remove",
|
||||
"reserve", "cancel", "signin", "checkin", "check_in", "enroll", "book",
|
||||
"waitlistjoin", "leavewaitlist", "like", "comment", "accept", "submit",
|
||||
"purchase", "pay", "charge", "logout", "setresult", "addresult",
|
||||
)
|
||||
|
||||
|
||||
class WriteAttemptError(RuntimeError):
|
||||
"""Raised when something tries to call a mutating endpoint."""
|
||||
|
||||
|
||||
class UnknownActionError(KeyError):
|
||||
"""Raised when an action key is not in the allowlist."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Action:
|
||||
"""A single read-only data action.
|
||||
|
||||
``path`` is everything after ``/screenservices/``.
|
||||
``view_name`` is the OutSystems screen the real client reports.
|
||||
``inputs`` documents the inputParameters keys; an empty tuple means the
|
||||
action takes none. Actual values are supplied per call.
|
||||
"""
|
||||
|
||||
key: str
|
||||
path: str
|
||||
view_name: str
|
||||
summary: str
|
||||
inputs: tuple[str, ...] = ()
|
||||
|
||||
|
||||
_FETCH = "WodifyClient_DataFetch_WB"
|
||||
|
||||
ACTIONS: dict[str, Action] = {
|
||||
a.key: a
|
||||
for a in (
|
||||
Action(
|
||||
key="bookings",
|
||||
path=f"{_FETCH}/Schedule_OS/GetClientAttendancesDataFetch_WB/DataActionGetAttendances",
|
||||
view_name="MainScreens.Home",
|
||||
summary="Classes the user has reserved or attended",
|
||||
inputs=("Request",),
|
||||
),
|
||||
# The actual workout content. Fires only on the properly-reached workout
|
||||
# screen (class detail -> Go to workout), which is why a cold load of
|
||||
# /WodifyClient/Exercise never reveals it.
|
||||
Action(
|
||||
key="workout",
|
||||
path=f"{_FETCH}/WOD_Flow/GetAllWorkoutData_WB/DataActionGetAllWorkoutData",
|
||||
view_name="MainScreens.Exercise",
|
||||
summary="Workout / WOD content for a date and program",
|
||||
inputs=("In_Request",),
|
||||
),
|
||||
# NOTE: despite the name, this returns only {"Response": bool} -- a probe
|
||||
# for whether the WOD has leaderboard components. It is NOT the workout
|
||||
# content; `workout` above is. Keeping it registered because the name is
|
||||
# a trap: something will eventually reach for it expecting content.
|
||||
Action(
|
||||
key="wodflags",
|
||||
path=f"{_FETCH}/WOD_Flow/GetWorkoutData_HasWodLeaderboardComponents"
|
||||
f"/DataActionGetWorkoutDataHasWodLeaderboardComponents",
|
||||
view_name="MainScreens.Home",
|
||||
summary="Boolean probe: does this WOD have leaderboard components "
|
||||
"(NOT the workout text)",
|
||||
inputs=("Request",),
|
||||
),
|
||||
Action(
|
||||
key="attendees",
|
||||
path=f"{_FETCH}/Schedule_OS/GetClassAttendees_WB/DataActionGetClassAttendees",
|
||||
view_name="Classes.Class",
|
||||
summary="Who is signed up for a class",
|
||||
inputs=("Request",),
|
||||
),
|
||||
Action(
|
||||
key="classdetail",
|
||||
path=f"{_FETCH}/Schedule_OS/GetClass_WB/DataActionGetClass",
|
||||
view_name="Classes.Class",
|
||||
summary="Single class: time, program, description",
|
||||
inputs=("Request",),
|
||||
),
|
||||
Action(
|
||||
key="coach",
|
||||
path=f"{_FETCH}/Schedule_OS/GetEmployeesForClass_WB/DataActionGetEmployeesForClass",
|
||||
view_name="Classes.Class",
|
||||
summary="Coach assigned to a class",
|
||||
inputs=("Request",),
|
||||
),
|
||||
# The schedule screen's class list, with reservation counts. This is the
|
||||
# one that actually populates; `classes` below (the Home variant) returns
|
||||
# placeholder records only.
|
||||
Action(
|
||||
key="schedule",
|
||||
path=f"{_FETCH}/Schedule_OS/GetClassList_ForClient_WithReservationCounts_WB"
|
||||
f"/DataActionGetClassList_ForClient_WithReservationCounts",
|
||||
view_name="MainScreens.Scheduler",
|
||||
summary="All classes on a given day, with reservation counts",
|
||||
inputs=("In_Request",),
|
||||
),
|
||||
Action(
|
||||
key="classes",
|
||||
path="WodifyClient_Class/Classes/Attendance/DataActionGetClasses",
|
||||
view_name="Classes.Attendance",
|
||||
summary="Classes via the Home screen variant (returns placeholders; "
|
||||
"prefer 'schedule')",
|
||||
inputs=("Request",),
|
||||
),
|
||||
Action(
|
||||
key="waitlist",
|
||||
path=f"{_FETCH}/Schedule_OS/GetClassWaitList_WB/DataActionGetClassWaitList",
|
||||
view_name="Classes.Class",
|
||||
summary="Waitlist for a class (read only -- never join or leave)",
|
||||
inputs=("Request",),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def assert_read_only(path: str) -> None:
|
||||
"""Raise :class:`WriteAttemptError` if ``path`` looks mutating.
|
||||
|
||||
Applied to every request, including allowlisted ones.
|
||||
"""
|
||||
lowered = path.lower()
|
||||
for marker in WRITE_MARKERS:
|
||||
if marker in lowered:
|
||||
raise WriteAttemptError(
|
||||
f"refusing to call {path!r}: contains write marker {marker!r}. "
|
||||
"This client is read-only by design."
|
||||
)
|
||||
|
||||
|
||||
def get(key: str) -> Action:
|
||||
"""Look up an allowlisted action, verifying it is still read-only."""
|
||||
try:
|
||||
action = ACTIONS[key]
|
||||
except KeyError as exc:
|
||||
known = ", ".join(sorted(ACTIONS))
|
||||
raise UnknownActionError(f"unknown action {key!r}; known: {known}") from exc
|
||||
assert_read_only(action.path)
|
||||
return action
|
||||
|
||||
|
||||
def keys() -> list[str]:
|
||||
return sorted(ACTIONS)
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Minimal Chrome DevTools Protocol client, used only by ``prime``.
|
||||
|
||||
Not a general CDP library -- just enough to read cookies from a logged-in
|
||||
profile and sniff outbound requests. Requires the ``prime`` extra
|
||||
(``pip install -e .[prime]``) because CDP is a WebSocket protocol.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import urllib.request
|
||||
from typing import Any, Callable
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
class CDPUnavailableError(RuntimeError):
|
||||
"""No CDP endpoint reachable."""
|
||||
|
||||
|
||||
def resolve_ws_url(cdp_root: str | None = None, timeout: int = 8) -> str:
|
||||
"""Resolve the browser WebSocket endpoint from the CDP HTTP root.
|
||||
|
||||
The ``/devtools/browser/<GUID>`` path changes on every Chrome launch, so it
|
||||
is always resolved rather than stored.
|
||||
"""
|
||||
root = (cdp_root or config.cdp_url()).rstrip("/")
|
||||
try:
|
||||
with urllib.request.urlopen(f"{root}/json/version", timeout=timeout) as resp:
|
||||
info = json.loads(resp.read().decode("utf-8"))
|
||||
except OSError as exc:
|
||||
raise CDPUnavailableError(
|
||||
f"cannot reach CDP at {root}: {exc}. Is the browser running? "
|
||||
"If it is on another host, tunnel first: ssh -L 9222:127.0.0.1:9222 <host>"
|
||||
) from exc
|
||||
url = info.get("webSocketDebuggerUrl")
|
||||
if not url:
|
||||
raise CDPUnavailableError(f"{root}/json/version had no webSocketDebuggerUrl")
|
||||
return url
|
||||
|
||||
|
||||
class CDPSession:
|
||||
"""A connected CDP session with one attached page target."""
|
||||
|
||||
def __init__(self, ws: Any) -> None:
|
||||
self._ws = ws
|
||||
self._id = 0
|
||||
self.session_id: str | None = None
|
||||
#: Events received while waiting for command replies.
|
||||
self._events: list[dict[str, Any]] = []
|
||||
|
||||
@classmethod
|
||||
async def connect(cls, ws_url: str | None = None) -> "CDPSession":
|
||||
try:
|
||||
import websockets
|
||||
except ImportError as exc: # pragma: no cover - dependency guard
|
||||
raise CDPUnavailableError(
|
||||
"priming needs the 'websockets' package: pip install -e .[prime]"
|
||||
) from exc
|
||||
url = ws_url or resolve_ws_url()
|
||||
ws = await websockets.connect(url, max_size=64 * 1024 * 1024)
|
||||
return cls(ws)
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._ws.close()
|
||||
|
||||
async def call(self, method: str, params: dict[str, Any] | None = None,
|
||||
*, on_target: bool = False) -> dict[str, Any]:
|
||||
self._id += 1
|
||||
msg: dict[str, Any] = {"id": self._id, "method": method, "params": params or {}}
|
||||
if on_target:
|
||||
if not self.session_id:
|
||||
raise RuntimeError(f"{method}: no page target attached")
|
||||
msg["sessionId"] = self.session_id
|
||||
await self._ws.send(json.dumps(msg))
|
||||
while True:
|
||||
raw = json.loads(await self._ws.recv())
|
||||
if raw.get("id") == self._id:
|
||||
if "error" in raw:
|
||||
raise RuntimeError(f"{method}: {raw['error']}")
|
||||
return raw.get("result", {})
|
||||
if raw.get("method"):
|
||||
self._events.append(raw)
|
||||
|
||||
async def open_page(self, url: str = "about:blank") -> None:
|
||||
target = await self.call("Target.createTarget", {"url": url})
|
||||
att = await self.call("Target.attachToTarget",
|
||||
{"targetId": target["targetId"], "flatten": True})
|
||||
self.session_id = att["sessionId"]
|
||||
await self.call("Page.enable", on_target=True)
|
||||
await self.call("Network.enable", on_target=True)
|
||||
|
||||
async def navigate(self, url: str) -> None:
|
||||
await self.call("Page.navigate", {"url": url}, on_target=True)
|
||||
|
||||
async def evaluate(self, expression: str, *, await_promise: bool = False) -> Any:
|
||||
res = await self.call(
|
||||
"Runtime.evaluate",
|
||||
{"expression": expression, "returnByValue": True, "awaitPromise": await_promise},
|
||||
on_target=True,
|
||||
)
|
||||
return (res.get("result") or {}).get("value")
|
||||
|
||||
async def session_cookies(self) -> str:
|
||||
"""Assemble the Cookie header from the browser profile.
|
||||
|
||||
Reads at browser scope so HttpOnly cookies are included -- the session
|
||||
bearer ``nr1W_Theme_UI`` is HttpOnly and invisible to page JS.
|
||||
"""
|
||||
jar = await self.call("Storage.getCookies")
|
||||
wanted = {}
|
||||
for cookie in jar.get("cookies", []):
|
||||
if cookie.get("name") in config.SESSION_COOKIE_NAMES \
|
||||
and config.host() in (cookie.get("domain") or ""):
|
||||
wanted[cookie["name"]] = cookie.get("value", "")
|
||||
missing = [n for n in config.SESSION_COOKIE_NAMES if n not in wanted]
|
||||
if "nr1W_Theme_UI" in missing:
|
||||
raise CDPUnavailableError(
|
||||
"profile has no nr1W_Theme_UI cookie -- the browser is not logged in. "
|
||||
"Log in inside that profile first."
|
||||
)
|
||||
return "; ".join(f"{n}={v}" for n, v in wanted.items())
|
||||
|
||||
async def drain(self, seconds: float,
|
||||
handler: Callable[[dict[str, Any]], None]) -> None:
|
||||
"""Feed every event received over ``seconds`` to ``handler``."""
|
||||
for event in self._events:
|
||||
handler(event)
|
||||
self._events.clear()
|
||||
|
||||
deadline = asyncio.get_event_loop().time() + seconds
|
||||
while asyncio.get_event_loop().time() < deadline:
|
||||
remaining = deadline - asyncio.get_event_loop().time()
|
||||
try:
|
||||
raw = json.loads(await asyncio.wait_for(self._ws.recv(),
|
||||
timeout=max(0.1, min(2.0, remaining))))
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
if raw.get("method"):
|
||||
handler(raw)
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Command line entry point.
|
||||
|
||||
python -m wodify doctor
|
||||
python -m wodify prime
|
||||
python -m wodify bookings
|
||||
python -m wodify workout --date 2026-07-25 --program 133059
|
||||
python -m wodify attendees --class-id 192000647
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as _dt
|
||||
import json
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from . import actions, client, config, render
|
||||
|
||||
|
||||
def _today() -> str:
|
||||
return _dt.date.today().isoformat()
|
||||
|
||||
|
||||
def _overrides(args: argparse.Namespace) -> dict[str, Any]:
|
||||
"""Map CLI flags onto body field names.
|
||||
|
||||
Applied only where the field already exists in the captured body, so
|
||||
passing a flag an action does not accept is harmless rather than fatal.
|
||||
"""
|
||||
out: dict[str, Any] = {}
|
||||
if getattr(args, "date", None):
|
||||
# Screen actions spell the date differently: the workout screen uses
|
||||
# SelectedDate, the scheduler uses FromDate. set_field only writes keys
|
||||
# that already exist, so offering all observed spellings is safe.
|
||||
for field in ("SelectedDate", "FromDate", "StartDate", "ClassDate", "Date"):
|
||||
out[field] = args.date
|
||||
if getattr(args, "class_id", None):
|
||||
out["ClassId"] = args.class_id
|
||||
if getattr(args, "program", None):
|
||||
out["GymProgramId"] = args.program
|
||||
out["ProgramId"] = args.program
|
||||
return out
|
||||
|
||||
|
||||
def cmd_doctor(args: argparse.Namespace) -> int:
|
||||
from . import store
|
||||
print(f"host: {config.host()}")
|
||||
print(f"cdp_url: {config.cdp_url()}")
|
||||
print(f"cache: {config.cache_path()}")
|
||||
print(f"db: {store.db_path()}")
|
||||
try:
|
||||
conn = store.connect()
|
||||
try:
|
||||
st = store.stats(conn)
|
||||
print(f"db stats: {st['classes']} classes over {st['days']} days, "
|
||||
f"{st['payloads']} payloads ({st['payloads_fresh_today']} fresh today)")
|
||||
finally:
|
||||
conn.close()
|
||||
except Exception as exc: # noqa: BLE001 - doctor should never crash
|
||||
print(f"db stats: unavailable ({exc})")
|
||||
print(f"actions: {', '.join(actions.keys())}")
|
||||
try:
|
||||
cache = client.load_cache()
|
||||
except client.NotPrimedError as exc:
|
||||
print(f"\nstatus: NOT PRIMED\n {exc}")
|
||||
return 1
|
||||
age = client.cache_age_days(cache)
|
||||
print(f"\nstatus: primed for {cache.get('host')}")
|
||||
print(f"primed_at: {cache.get('primed_at')}"
|
||||
+ (f" ({age:.1f} days ago)" if age is not None else ""))
|
||||
print(f"cookie: {len(cache.get('cookie', ''))} chars")
|
||||
print(f"csrf: {len(cache.get('csrf', ''))} chars")
|
||||
print(f"module: {cache.get('module_version')}")
|
||||
have = {a.key for a in actions.ACTIONS.values() if a.path in (cache.get("actions") or {})}
|
||||
print(f"captured: {', '.join(sorted(have)) or '(none)'}")
|
||||
missing = sorted(set(actions.keys()) - have)
|
||||
if missing:
|
||||
print(f"missing: {', '.join(missing)} (re-prime while exercising these screens)")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_prime(args: argparse.Namespace) -> int:
|
||||
from . import prime as prime_mod
|
||||
try:
|
||||
summary = prime_mod.prime(workout_date=getattr(args, "workout_date", None))
|
||||
except Exception as exc:
|
||||
print(f"prime failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
for key, value in summary.items():
|
||||
print(f"{key}: {value}")
|
||||
if summary["actions_missing"]:
|
||||
print("\nNote: apiVersion is per-action, so missing entries cannot be queried "
|
||||
"until a prime run observes them.", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_query(args: argparse.Namespace) -> int:
|
||||
try:
|
||||
data = client.call(args.command, _overrides(args))
|
||||
except client.SessionExpiredError as exc:
|
||||
print(f"SESSION EXPIRED: {exc}\n\nA human must log in again inside the browser "
|
||||
f"profile, then run: python -m wodify prime", file=sys.stderr)
|
||||
return 2
|
||||
except client.VersionStaleError as exc:
|
||||
print(f"STALE: {exc}\n\nRun: python -m wodify prime", file=sys.stderr)
|
||||
return 3
|
||||
except client.NotPrimedError as exc:
|
||||
print(f"NOT PRIMED: {exc}", file=sys.stderr)
|
||||
return 4
|
||||
except actions.WriteAttemptError as exc:
|
||||
print(f"REFUSED: {exc}", file=sys.stderr)
|
||||
return 5
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(data, indent=1))
|
||||
elif args.command == "workout":
|
||||
print(render.workout(data, notes=getattr(args, "notes", False)))
|
||||
elif args.command == "bookings":
|
||||
print(render.bookings(
|
||||
data,
|
||||
since=getattr(args, "since", None),
|
||||
until=getattr(args, "until", None),
|
||||
attended_only=getattr(args, "attended", False),
|
||||
))
|
||||
else:
|
||||
print(render.render(args.command, data))
|
||||
return 0
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="wodify",
|
||||
description="Read-only Wodify athlete client. Never reserves, cancels, "
|
||||
"checks in, or logs results.",
|
||||
)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
from . import listcmd
|
||||
listcmd.add_parser(sub)
|
||||
|
||||
sub.add_parser("doctor", help="show config and cache status")
|
||||
pr = sub.add_parser("prime",
|
||||
help="capture session state from a logged-in browser (needs CDP)")
|
||||
pr.add_argument("--workout-date", default=None, metavar="YYYY-MM-DD",
|
||||
help="a date that HAS a posted WOD; required to capture the "
|
||||
"workout action (default: today)")
|
||||
|
||||
for key in actions.keys():
|
||||
action = actions.ACTIONS[key]
|
||||
p = sub.add_parser(key, help=action.summary)
|
||||
p.add_argument("--json", action="store_true", help="raw JSON instead of text")
|
||||
p.add_argument("--date", default=None, metavar="YYYY-MM-DD",
|
||||
help="target date (default: today for date-scoped actions)")
|
||||
p.add_argument("--class-id", type=int, default=None,
|
||||
help="ClassId -- per-occurrence, changes daily")
|
||||
p.add_argument("--program", type=int, default=None, help="ProgramId")
|
||||
if key == "workout":
|
||||
p.add_argument("--notes", action="store_true",
|
||||
help="include the coach's brief (long)")
|
||||
if key == "bookings":
|
||||
p.add_argument("--since", default=None, metavar="YYYY-MM-DD",
|
||||
help="only classes on/after this date")
|
||||
p.add_argument("--until", default=None, metavar="YYYY-MM-DD",
|
||||
help="only classes on/before this date")
|
||||
p.add_argument("--attended", action="store_true",
|
||||
help="only classes actually attended")
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
if args.command == "list":
|
||||
from . import listcmd
|
||||
return listcmd.dispatch(args)
|
||||
if args.command == "doctor":
|
||||
return cmd_doctor(args)
|
||||
if args.command == "prime":
|
||||
return cmd_prime(args)
|
||||
if getattr(args, "date", None) is None and args.command in ("workout", "classes"):
|
||||
args.date = _today()
|
||||
return cmd_query(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Query path: plain HTTP, stdlib only.
|
||||
|
||||
Deliberately dependency-free so the hot path has no install step. ``prime``
|
||||
carries the WebSocket dependency; this module does not.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as _dt
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import stat
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any
|
||||
|
||||
from . import actions, config
|
||||
|
||||
CACHE_VERSION = 1
|
||||
|
||||
|
||||
class NotPrimedError(RuntimeError):
|
||||
"""No usable cache. Run ``wodify prime``."""
|
||||
|
||||
|
||||
class SessionExpiredError(RuntimeError):
|
||||
"""The stored session is no longer valid. A human must re-login."""
|
||||
|
||||
|
||||
class VersionStaleError(RuntimeError):
|
||||
"""Wodify redeployed; cached module/api versions need re-priming."""
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# cache
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def save_cache(payload: dict[str, Any], path: pathlib.Path | None = None) -> pathlib.Path:
|
||||
"""Write the session cache with owner-only permissions.
|
||||
|
||||
The file holds live credentials, so it is created 0600 *before* anything is
|
||||
written to it rather than chmod-ed afterwards.
|
||||
"""
|
||||
path = path or config.cache_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = {**payload, "cache_version": CACHE_VERSION}
|
||||
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, stat.S_IRUSR | stat.S_IWUSR)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||
json.dump(payload, fh, indent=1, sort_keys=True)
|
||||
return path
|
||||
|
||||
|
||||
def load_cache(path: pathlib.Path | None = None) -> dict[str, Any]:
|
||||
path = path or config.cache_path()
|
||||
if not path.exists():
|
||||
raise NotPrimedError(
|
||||
f"no session cache at {path}. Run: python -m wodify prime "
|
||||
"(needs a logged-in Chrome on WODIFY_CDP_URL)"
|
||||
)
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise NotPrimedError(f"session cache at {path} is unreadable: {exc}") from exc
|
||||
|
||||
for field in ("cookie", "csrf", "module_version", "actions"):
|
||||
if not data.get(field):
|
||||
raise NotPrimedError(f"session cache at {path} is missing {field!r}; re-prime")
|
||||
return data
|
||||
|
||||
|
||||
def cache_age_days(cache: dict[str, Any]) -> float | None:
|
||||
stamp = cache.get("primed_at")
|
||||
if not stamp:
|
||||
return None
|
||||
try:
|
||||
then = _dt.datetime.fromisoformat(stamp)
|
||||
except ValueError:
|
||||
return None
|
||||
if then.tzinfo is None:
|
||||
then = then.replace(tzinfo=_dt.timezone.utc)
|
||||
delta = _dt.datetime.now(_dt.timezone.utc) - then
|
||||
return delta.total_seconds() / 86400
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# HTTP
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _post(url: str, body: bytes, headers: dict[str, str], timeout: int) -> tuple[int, str]:
|
||||
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
return resp.status, resp.read().decode("utf-8", errors="replace")
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, exc.read().decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def set_field(node: Any, field: str, value: Any) -> int:
|
||||
"""Set ``field`` to ``value`` everywhere it already exists in ``node``.
|
||||
|
||||
Returns how many places were written. Only pre-existing keys are touched:
|
||||
OutSystems validates the body against the action's contract and rejects
|
||||
unknown keys with "Failed to parse JSON request content".
|
||||
"""
|
||||
written = 0
|
||||
if isinstance(node, dict):
|
||||
for key in list(node):
|
||||
if key == field:
|
||||
node[key] = value
|
||||
written += 1
|
||||
else:
|
||||
written += set_field(node[key], field, value)
|
||||
elif isinstance(node, list):
|
||||
for item in node:
|
||||
written += set_field(item, field, value)
|
||||
return written
|
||||
|
||||
|
||||
def call(
|
||||
action_key: str,
|
||||
overrides: dict[str, Any] | None = None,
|
||||
*,
|
||||
cache: dict[str, Any] | None = None,
|
||||
timeout: int = 30,
|
||||
) -> dict[str, Any]:
|
||||
"""Invoke a read-only data action and return its parsed ``data`` payload.
|
||||
|
||||
``overrides`` maps body field names (e.g. ``SelectedDate``, ``ClassId``) to
|
||||
values, applied wherever those fields already appear in the captured body.
|
||||
|
||||
Raises :class:`SessionExpiredError` or :class:`VersionStaleError` rather
|
||||
than returning something that looks like an empty result -- a silently wrong
|
||||
"nothing found" is worse than an error.
|
||||
"""
|
||||
action = actions.get(action_key) # allowlist + write guard
|
||||
actions.assert_read_only(action.path) # belt and braces
|
||||
|
||||
cache = cache or load_cache()
|
||||
entry = (cache.get("actions") or {}).get(action.path)
|
||||
if not entry or not entry.get("api_version"):
|
||||
raise NotPrimedError(
|
||||
f"action {action_key!r} has no cached apiVersion. "
|
||||
"apiVersion is per-action, so re-prime with this action exercised."
|
||||
)
|
||||
template = entry.get("body_template")
|
||||
if template is None:
|
||||
raise NotPrimedError(
|
||||
f"action {action_key!r} was primed by an older version without a "
|
||||
"body_template; re-prime."
|
||||
)
|
||||
|
||||
payload: dict[str, Any] = json.loads(json.dumps(template)) # deep copy
|
||||
payload["versionInfo"] = {
|
||||
"moduleVersion": cache["module_version"],
|
||||
"apiVersion": entry["api_version"],
|
||||
}
|
||||
payload.setdefault("viewName", entry.get("view_name") or action.view_name)
|
||||
|
||||
for field, value in (overrides or {}).items():
|
||||
if value is not None:
|
||||
set_field(payload, field, value)
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json; charset=UTF-8",
|
||||
"Accept": "application/json",
|
||||
"Accept-Encoding": "identity", # keep stdlib decoding trivial
|
||||
"Accept-Language": "en-US",
|
||||
"X-CSRFToken": cache["csrf"],
|
||||
"Cookie": cache["cookie"],
|
||||
"User-Agent": config.USER_AGENT,
|
||||
"Referer": f"{config.origin()}/WodifyClient/",
|
||||
}
|
||||
|
||||
status, text = _post(
|
||||
config.screenservices_url(action.path),
|
||||
json.dumps(payload).encode("utf-8"),
|
||||
headers,
|
||||
timeout,
|
||||
)
|
||||
|
||||
if status in (401, 403):
|
||||
raise SessionExpiredError(
|
||||
f"{action_key}: HTTP {status}. The stored Wodify session is no longer "
|
||||
"valid -- a human must re-login, then re-prime."
|
||||
)
|
||||
if status >= 400:
|
||||
raise RuntimeError(f"{action_key}: HTTP {status}: {text[:300]}")
|
||||
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
except json.JSONDecodeError as exc:
|
||||
# A login redirect returns HTML, not JSON.
|
||||
if "Sign into" in text or "<html" in text.lower():
|
||||
raise SessionExpiredError(
|
||||
f"{action_key}: got an HTML login page instead of JSON -- session expired."
|
||||
) from exc
|
||||
raise RuntimeError(f"{action_key}: response was not JSON: {text[:200]}") from exc
|
||||
|
||||
info = parsed.get("versionInfo") or {}
|
||||
if info.get("hasModuleVersionChanged") or info.get("hasApiVersionChanged"):
|
||||
raise VersionStaleError(
|
||||
f"{action_key}: Wodify redeployed "
|
||||
f"(module changed={bool(info.get('hasModuleVersionChanged'))}, "
|
||||
f"api changed={bool(info.get('hasApiVersionChanged'))}). Re-prime."
|
||||
)
|
||||
|
||||
return parsed.get("data") or {}
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Configuration, all environment-overridable.
|
||||
|
||||
No secrets live here -- only where to find them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
DEFAULT_HOST = "claycrossfit.wodify.com"
|
||||
DEFAULT_CDP_URL = "http://127.0.0.1:9222"
|
||||
|
||||
# CrossFit Clay. Present as a default so callers need not pass it every time;
|
||||
# a different gym would override via the CLI.
|
||||
DEFAULT_LOCATION_ID = 11644
|
||||
|
||||
|
||||
def host() -> str:
|
||||
return os.environ.get("WODIFY_HOST", DEFAULT_HOST).strip() or DEFAULT_HOST
|
||||
|
||||
|
||||
def origin() -> str:
|
||||
return f"https://{host()}"
|
||||
|
||||
|
||||
def screenservices_url(path: str) -> str:
|
||||
"""Full URL for a screenservices action path.
|
||||
|
||||
``path`` is the part after ``/screenservices/``, e.g.
|
||||
``WodifyClient_DataFetch_WB/Schedule_OS/GetClass_WB/DataActionGetClass``.
|
||||
"""
|
||||
return f"{origin()}/WodifyClient/screenservices/{path.lstrip('/')}"
|
||||
|
||||
|
||||
def module_version_url() -> str:
|
||||
return f"{origin()}/WodifyClient/moduleservices/moduleversioninfo"
|
||||
|
||||
|
||||
def cdp_url() -> str:
|
||||
return os.environ.get("WODIFY_CDP_URL", DEFAULT_CDP_URL).strip() or DEFAULT_CDP_URL
|
||||
|
||||
|
||||
def cache_path() -> pathlib.Path:
|
||||
override = os.environ.get("WODIFY_CACHE", "").strip()
|
||||
if override:
|
||||
return pathlib.Path(override).expanduser()
|
||||
return pathlib.Path.home() / ".cache" / "wodify" / "session.json"
|
||||
|
||||
|
||||
def location_id() -> int:
|
||||
raw = os.environ.get("WODIFY_LOCATION_ID", "").strip()
|
||||
if raw:
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
pass
|
||||
return DEFAULT_LOCATION_ID
|
||||
|
||||
|
||||
# Cookies that actually carry the session. nr1W_Theme_UI is the HttpOnly bearer;
|
||||
# the other two are sent alongside because the real client sends them.
|
||||
SESSION_COOKIE_NAMES = ("nr1W_Theme_UI", "nr2W_Theme_UI", "AuthenticationToken")
|
||||
|
||||
USER_AGENT = (
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36"
|
||||
)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""The `list` command group: `list date <YYYY-MM-DD>` and `list workout <id>`.
|
||||
|
||||
Both go through :mod:`wodify.service`, so a repeat query on the same calendar day
|
||||
is served from SQLite and touches the network not at all.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as _dt
|
||||
import json
|
||||
|
||||
from . import client, render, service, store
|
||||
|
||||
|
||||
def _source_note(*results) -> str:
|
||||
"""One line saying whether this answer came off disk or the wire."""
|
||||
if all(r.cached for r in results if r is not None):
|
||||
stamps = [r.fetched_at for r in results if r is not None and r.fetched_at]
|
||||
when = f" at {min(stamps)}" if stamps else ""
|
||||
return f"(from local cache, fetched{when} — pass --refresh to re-read)"
|
||||
if any(r.cached for r in results if r is not None):
|
||||
return "(partly cached, partly fetched)"
|
||||
return "(fetched from Wodify and cached)"
|
||||
|
||||
|
||||
def cmd_date(args: argparse.Namespace) -> int:
|
||||
date = args.value or _dt.date.today().isoformat()
|
||||
try:
|
||||
_dt.date.fromisoformat(date)
|
||||
except ValueError:
|
||||
print(f"not a date: {date!r} (expected YYYY-MM-DD)")
|
||||
return 2
|
||||
|
||||
conn = store.connect()
|
||||
try:
|
||||
rows, result = service.day_classes(conn, date, refresh=args.refresh)
|
||||
except client.SessionExpiredError as exc:
|
||||
print(f"SESSION EXPIRED: {exc}")
|
||||
return 3
|
||||
except client.VersionStaleError as exc:
|
||||
print(f"STALE: {exc}\nRun: wodify prime")
|
||||
return 4
|
||||
except client.NotPrimedError as exc:
|
||||
print(f"NOT PRIMED: {exc}")
|
||||
return 5
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(rows, indent=1))
|
||||
return 0
|
||||
print(render.day_table(rows, date))
|
||||
print(_source_note(result))
|
||||
print(f"\nNext: wodify list workout <ID>")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_workout(args: argparse.Namespace) -> int:
|
||||
class_id = str(args.value or "").strip()
|
||||
if not class_id.isdigit():
|
||||
print(f"not a class id: {class_id!r} (get one from: wodify list date <date>)")
|
||||
return 2
|
||||
|
||||
conn = store.connect()
|
||||
try:
|
||||
klass = service.resolve_class(conn, class_id)
|
||||
if klass is None:
|
||||
print(f"class {class_id} is not in the local index.\n"
|
||||
f"Class ids are per-occurrence, so the date cannot be derived from "
|
||||
f"the id alone — run 'wodify list date <YYYY-MM-DD>' for the day "
|
||||
f"that class is on first.")
|
||||
return 6
|
||||
|
||||
try:
|
||||
wod = service.workout(conn, klass["date"], klass["program_id"],
|
||||
refresh=args.refresh)
|
||||
att = service.attendees(conn, class_id, klass.get("class_limit"),
|
||||
refresh=args.refresh)
|
||||
except client.SessionExpiredError as exc:
|
||||
print(f"SESSION EXPIRED: {exc}")
|
||||
return 3
|
||||
except client.VersionStaleError as exc:
|
||||
print(f"STALE: {exc}\nRun: wodify prime")
|
||||
return 4
|
||||
except client.NotPrimedError as exc:
|
||||
print(f"NOT PRIMED: {exc}")
|
||||
return 5
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if args.json:
|
||||
print(json.dumps({"class": klass, "workout": wod.data,
|
||||
"attendees": att.data}, indent=1))
|
||||
return 0
|
||||
|
||||
mins = render.duration_minutes(klass.get("start", ""), klass.get("finish", ""))
|
||||
head = f"{klass.get('name') or 'class'} — {klass['date']} " \
|
||||
f"{render._hhmm(klass.get('start', ''))}"
|
||||
if mins:
|
||||
head += f" ({mins}min)"
|
||||
print(head)
|
||||
if klass.get("coach"):
|
||||
print(f"Coach: {klass['coach']}")
|
||||
print(f"Program: {klass.get('program_id') or '-'} ID: {class_id}")
|
||||
print()
|
||||
print(render.attendee_block(att.data, booked=klass.get("booked"),
|
||||
limit=klass.get("class_limit")))
|
||||
print()
|
||||
print(render.workout(wod.data, notes=args.notes))
|
||||
print()
|
||||
print(_source_note(wod, att))
|
||||
return 0
|
||||
|
||||
|
||||
def add_parser(sub) -> None:
|
||||
p = sub.add_parser("list", help="list a day's classes, or one class's workout")
|
||||
inner = p.add_subparsers(dest="what", required=True)
|
||||
|
||||
for name, help_text, metavar in (
|
||||
("date", "classes on a day (default: today)", "YYYY-MM-DD"),
|
||||
("workout", "workout + attendees for one class id", "CLASS_ID"),
|
||||
):
|
||||
q = inner.add_parser(name, help=help_text)
|
||||
q.add_argument("value", nargs="?" if name == "date" else None,
|
||||
metavar=metavar)
|
||||
q.add_argument("--refresh", action="store_true",
|
||||
help="ignore the local cache and re-read from Wodify")
|
||||
q.add_argument("--json", action="store_true", help="raw JSON")
|
||||
if name == "workout":
|
||||
q.add_argument("--notes", action="store_true",
|
||||
help="include the coach's brief (long)")
|
||||
|
||||
|
||||
def dispatch(args: argparse.Namespace) -> int:
|
||||
if args.what == "date":
|
||||
return cmd_date(args)
|
||||
return cmd_workout(args)
|
||||
@@ -0,0 +1,230 @@
|
||||
"""Capture session credentials and per-action metadata from a logged-in browser.
|
||||
|
||||
Run rarely: once after login, and again when Wodify redeploys (the query path
|
||||
raises :class:`~wodify.client.VersionStaleError` when that happens).
|
||||
|
||||
What has to be sniffed rather than read, and why:
|
||||
|
||||
* ``nr1W_Theme_UI`` is HttpOnly -- page JS cannot see it, so it is read at
|
||||
browser scope over CDP.
|
||||
* ``X-CSRFToken`` is not in cookies, localStorage, or any JS global. It appears
|
||||
only on outbound requests.
|
||||
* ``apiVersion`` is **per-action**, so each endpoint's value must be observed
|
||||
from a real call to that endpoint.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime as _dt
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from . import actions, cdp, client, config
|
||||
|
||||
#: Screens to walk so the interesting data actions actually fire. Ordered:
|
||||
#: Home first (it is the reliable entry point and populates client vars).
|
||||
WALK = (
|
||||
("/WodifyClient/Home", 12),
|
||||
("/WodifyClient/Scheduler", 10),
|
||||
)
|
||||
|
||||
#: In-app click walk: Schedule -> a date -> a class -> Go to workout.
|
||||
#:
|
||||
#: This is required, not a nicety. ``GetAllWorkoutData`` (the workout content)
|
||||
#: fires *only* on the properly-reached workout screen -- a direct load of
|
||||
#: /WodifyClient/Exercise never issues it, and OutSystems serves a cached copy if
|
||||
#: the date has not changed. Walking to a class on a specific date forces a real
|
||||
#: request, which is what exposes the apiVersion and body shape.
|
||||
#:
|
||||
#: Clicks are text-matched and confined to navigation. Nothing here touches
|
||||
#: Reserve, Cancel, waitlist, or results controls.
|
||||
WORKOUT_WALK_JS = r"""
|
||||
(async () => {
|
||||
const log = [];
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const clickText = (txt) => {
|
||||
const els = [...document.querySelectorAll('*')].filter(
|
||||
e => e.childElementCount === 0 && e.textContent.trim() === txt);
|
||||
if (!els.length) return false;
|
||||
els[els.length - 1].click();
|
||||
return true;
|
||||
};
|
||||
const clickAria = frag => {
|
||||
const el = [...document.querySelectorAll('[aria-label]')]
|
||||
.find(e => (e.getAttribute('aria-label') || '').includes(frag));
|
||||
if (!el) return false;
|
||||
el.click();
|
||||
return true;
|
||||
};
|
||||
|
||||
log.push('schedule=' + clickText('Schedule'));
|
||||
await sleep(3500);
|
||||
if (__DATE_LABEL__) { log.push('date=' + clickAria(__DATE_LABEL__)); await sleep(3500); }
|
||||
|
||||
const classes = [...document.querySelectorAll('*')]
|
||||
.filter(e => e.childElementCount === 0 && /^[A-Za-z][^,]*:\s*\d{1,2}:\d{2}/.test(e.textContent.trim()))
|
||||
.map(e => e.textContent.trim())
|
||||
.filter((v, i, a) => a.indexOf(v) === i);
|
||||
log.push('classes=' + classes.length);
|
||||
if (!classes.length) return JSON.stringify({log, ok: false, why: 'no classes on that date'});
|
||||
|
||||
log.push('class=' + clickText(classes[0]));
|
||||
await sleep(4000);
|
||||
const hasLink = document.body.innerText.includes('Go to workout');
|
||||
log.push('hasGoToWorkout=' + hasLink);
|
||||
if (!hasLink) return JSON.stringify({log, ok: false, why: 'no workout posted for that class'});
|
||||
|
||||
log.push('goto=' + clickText('Go to workout'));
|
||||
await sleep(5000);
|
||||
return JSON.stringify({log, ok: document.body.innerText.includes('WARM-UP')});
|
||||
})()
|
||||
"""
|
||||
|
||||
#: Paths we want metadata for, indexed for quick lookup.
|
||||
WANTED_PATHS = {a.path for a in actions.ACTIONS.values()}
|
||||
|
||||
|
||||
def _observe(event: dict[str, Any], found: dict[str, dict[str, Any]],
|
||||
csrf: list[str]) -> None:
|
||||
"""Record versionInfo/viewName/input shape for any wanted read action."""
|
||||
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
|
||||
|
||||
for name, value in (req.get("headers") or {}).items():
|
||||
if name.lower() == "x-csrftoken" and value and not csrf:
|
||||
csrf.append(value)
|
||||
|
||||
path = url.split("/screenservices/", 1)[1]
|
||||
if path not in WANTED_PATHS or path in found:
|
||||
return
|
||||
|
||||
body = req.get("postData")
|
||||
if not body:
|
||||
return
|
||||
try:
|
||||
parsed = json.loads(body)
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
|
||||
version = parsed.get("versionInfo") or {}
|
||||
if not version.get("apiVersion"):
|
||||
return
|
||||
|
||||
# Never store a mutating path, even if Wodify reuses a name we allowlisted.
|
||||
actions.assert_read_only(path)
|
||||
|
||||
# Store the whole body minus versionInfo. Screen data actions carry their
|
||||
# parameters in `screenData.variables` -- the entire screen state, including
|
||||
# ClientVariables -- rather than `inputParameters`, so the body *is* the
|
||||
# contract and cannot be reconstructed field by field.
|
||||
body_template = {k: v for k, v in parsed.items() if k != "versionInfo"}
|
||||
|
||||
found[path] = {
|
||||
"api_version": version["apiVersion"],
|
||||
"module_version": version.get("moduleVersion"),
|
||||
"view_name": parsed.get("viewName"),
|
||||
"body_template": body_template,
|
||||
"body_keys": sorted(body_template),
|
||||
}
|
||||
|
||||
|
||||
def _date_label(date: str | None) -> str:
|
||||
"""JS string literal for the aria-label fragment of a schedule date button.
|
||||
|
||||
Wodify labels them like "Friday, July 24, 2026", so match on "July 24".
|
||||
"""
|
||||
if not date:
|
||||
return "null"
|
||||
try:
|
||||
parsed = _dt.date.fromisoformat(date)
|
||||
except ValueError:
|
||||
return "null"
|
||||
return json.dumps(parsed.strftime("%B ") + str(parsed.day))
|
||||
|
||||
|
||||
async def _run(walk=WALK, workout_date: str | None = None) -> dict[str, Any]:
|
||||
session = await cdp.CDPSession.connect()
|
||||
walk_log: Any = None
|
||||
try:
|
||||
cookie = await session.session_cookies()
|
||||
await session.open_page()
|
||||
|
||||
found: dict[str, dict[str, Any]] = {}
|
||||
csrf: list[str] = []
|
||||
|
||||
for path, wait in walk:
|
||||
await session.navigate(config.origin() + path)
|
||||
await session.drain(wait, lambda ev: _observe(ev, found, csrf))
|
||||
|
||||
# Walk to a real workout screen so GetAllWorkoutData (and the class
|
||||
# detail actions) actually fire.
|
||||
script = WORKOUT_WALK_JS.replace("__DATE_LABEL__", _date_label(workout_date))
|
||||
walk_task = asyncio.create_task(session.evaluate(script, await_promise=True))
|
||||
await session.drain(26, lambda ev: _observe(ev, found, csrf))
|
||||
try:
|
||||
walk_log = await asyncio.wait_for(walk_task, timeout=10)
|
||||
except (asyncio.TimeoutError, Exception): # noqa: BLE001 - best effort
|
||||
walk_log = None
|
||||
|
||||
module_version = await session.evaluate(
|
||||
"fetch('/WodifyClient/moduleservices/moduleversioninfo')"
|
||||
".then(r => r.json()).then(j => j.versionToken)",
|
||||
await_promise=True,
|
||||
)
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
if not csrf:
|
||||
raise RuntimeError(
|
||||
"no X-CSRFToken observed. The browser is logged in but made no data "
|
||||
"action calls -- try again, or widen the walk in prime.WALK."
|
||||
)
|
||||
if not module_version:
|
||||
module_version = next(
|
||||
(m["module_version"] for m in found.values() if m.get("module_version")), None
|
||||
)
|
||||
if not module_version:
|
||||
raise RuntimeError("could not determine moduleVersion")
|
||||
|
||||
return {
|
||||
"host": config.host(),
|
||||
"primed_at": _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds"),
|
||||
"cookie": cookie,
|
||||
"csrf": csrf[0],
|
||||
"module_version": module_version,
|
||||
"actions": found,
|
||||
"walk_log": walk_log,
|
||||
}
|
||||
|
||||
|
||||
def prime(workout_date: str | None = None) -> dict[str, Any]:
|
||||
"""Capture and persist session state. Returns a non-secret summary.
|
||||
|
||||
``workout_date`` should be a day that actually has a posted WOD -- the
|
||||
workout action cannot be captured from a day with nothing published.
|
||||
"""
|
||||
payload = asyncio.run(_run(workout_date=workout_date))
|
||||
walk_log = payload.pop("walk_log", None)
|
||||
path = client.save_cache(payload)
|
||||
|
||||
captured = sorted(payload["actions"])
|
||||
missing = sorted(
|
||||
a.key for a in actions.ACTIONS.values() if a.path not in payload["actions"]
|
||||
)
|
||||
return {
|
||||
"cache": str(path),
|
||||
"host": payload["host"],
|
||||
"cookie_chars": len(payload["cookie"]),
|
||||
"csrf_chars": len(payload["csrf"]),
|
||||
"module_version": payload["module_version"],
|
||||
"actions_captured": [
|
||||
k for k, a in sorted(actions.ACTIONS.items()) if a.path in payload["actions"]
|
||||
],
|
||||
"actions_missing": missing,
|
||||
"raw_paths_captured": len(captured),
|
||||
"walk": walk_log,
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
"""Compact text rendering.
|
||||
|
||||
Reason this module exists: the browser approach cost tokens mostly by handing
|
||||
back whole rendered pages. These functions emit the few lines an answer needs.
|
||||
HTML from Wodify's rich-text fields is flattened rather than passed through.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
_TAG = re.compile(r"<[^>]+>")
|
||||
_BREAK = re.compile(r"(?i)</?(br|/?p|/?div|/?li|/?tr)[^>]*>")
|
||||
_BLANKS = re.compile(r"\n{3,}")
|
||||
_SPACES = re.compile(r"[ \t]{2,}")
|
||||
|
||||
|
||||
def flatten_html(raw: str | None) -> str:
|
||||
"""Turn a Wodify rich-text field into plain lines."""
|
||||
if not raw:
|
||||
return ""
|
||||
text = _BREAK.sub("\n", raw)
|
||||
text = _TAG.sub("", text)
|
||||
text = html.unescape(text)
|
||||
text = _SPACES.sub(" ", text)
|
||||
text = "\n".join(line.strip() for line in text.splitlines())
|
||||
return _BLANKS.sub("\n\n", text).strip()
|
||||
|
||||
|
||||
def _walk(node: Any, key: str, out: list[Any]) -> None:
|
||||
"""Collect every value stored under ``key``, at any depth."""
|
||||
if isinstance(node, dict):
|
||||
for k, v in node.items():
|
||||
if k == key:
|
||||
out.append(v)
|
||||
else:
|
||||
_walk(v, key, out)
|
||||
elif isinstance(node, list):
|
||||
for item in node:
|
||||
_walk(item, key, out)
|
||||
|
||||
|
||||
def find_all(data: Any, key: str) -> list[Any]:
|
||||
out: list[Any] = []
|
||||
_walk(data, key, out)
|
||||
return out
|
||||
|
||||
|
||||
def first_list(data: Any) -> list[Any]:
|
||||
"""Best-effort: the first non-empty ``List`` in an OutSystems response."""
|
||||
for candidate in find_all(data, "List"):
|
||||
if isinstance(candidate, list) and candidate:
|
||||
return candidate
|
||||
return []
|
||||
|
||||
|
||||
def _flatten_row(row: dict) -> dict[str, Any]:
|
||||
"""Merge one level of nested dicts up, so field lookups are flat."""
|
||||
flat: dict[str, Any] = {}
|
||||
for value in row.values():
|
||||
if isinstance(value, dict):
|
||||
flat.update(value)
|
||||
flat.update({k: v for k, v in row.items() if not isinstance(v, (dict, list))})
|
||||
return flat
|
||||
|
||||
|
||||
def booking_rows(data: Any) -> list[dict[str, Any]]:
|
||||
"""Structured bookings, newest last. Exposed so callers can chain on them."""
|
||||
out = []
|
||||
for row in first_list(data):
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
flat = _flatten_row(row)
|
||||
date = str(flat.get("StartDate") or flat.get("Date") or "")[:10]
|
||||
out.append({
|
||||
"date": date,
|
||||
"time": str(flat.get("StartTime") or ""),
|
||||
"name": str(flat.get("ClassName") or flat.get("Name")
|
||||
or flat.get("ProgramName") or ""),
|
||||
"status": str(flat.get("StatusLabel") or flat.get("Status") or ""),
|
||||
"class_id": str(flat.get("ClassId") or ""),
|
||||
"program_id": str(flat.get("ProgramId") or ""),
|
||||
})
|
||||
return sorted(out, key=lambda r: (r["date"], r["time"]))
|
||||
|
||||
|
||||
def bookings(data: Any, *, since: str | None = None, until: str | None = None,
|
||||
attended_only: bool = False) -> str:
|
||||
"""Render bookings, optionally restricted to a date range.
|
||||
|
||||
Filtering is client-side: the action returns the user's history in one call,
|
||||
so a range is cheaper to apply here than to negotiate with the server.
|
||||
"""
|
||||
rows = booking_rows(data)
|
||||
total = len(rows)
|
||||
if since:
|
||||
rows = [r for r in rows if r["date"] and r["date"] >= since]
|
||||
if until:
|
||||
rows = [r for r in rows if r["date"] and r["date"] <= until]
|
||||
if attended_only:
|
||||
rows = [r for r in rows if r["status"].lower() in ("attended", "signed in")]
|
||||
|
||||
if not rows:
|
||||
scope = " matching that filter" if (since or until or attended_only) else ""
|
||||
extra = f" ({total} returned before filtering)" if total and scope else ""
|
||||
return f"No bookings found{scope}.{extra}"
|
||||
|
||||
lines = []
|
||||
for r in rows:
|
||||
parts = [p for p in (r["date"], r["time"], r["name"]) if p]
|
||||
line = "- " + (" ".join(parts) or "(unnamed)")
|
||||
if r["status"]:
|
||||
line += f" [{r['status']}]"
|
||||
if r["class_id"] and r["class_id"] != "0":
|
||||
line += f" class_id={r['class_id']}"
|
||||
lines.append(line)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _hhmm(value: str) -> str:
|
||||
"""``17:30:00`` -> ``17:30``. Leaves anything unexpected alone."""
|
||||
parts = str(value or "").split(":")
|
||||
return f"{parts[0]}:{parts[1]}" if len(parts) >= 2 else str(value or "")
|
||||
|
||||
|
||||
def duration_minutes(start: str, finish: str) -> int | None:
|
||||
"""Minutes between two ``HH:MM:SS`` times, or None if unparseable."""
|
||||
def mins(v):
|
||||
bits = str(v or "").split(":")
|
||||
if len(bits) < 2:
|
||||
return None
|
||||
try:
|
||||
return int(bits[0]) * 60 + int(bits[1])
|
||||
except ValueError:
|
||||
return None
|
||||
a, b = mins(start), mins(finish)
|
||||
if a is None or b is None:
|
||||
return None
|
||||
delta = b - a
|
||||
return delta + 24 * 60 if delta < 0 else delta # class crossing midnight
|
||||
|
||||
|
||||
def day_table(rows: list[dict[str, Any]], date: str) -> str:
|
||||
"""The `list date` view: time, coach, booked/max, title, duration, id."""
|
||||
if not rows:
|
||||
return (f"No classes found for {date}. Either nothing ran that day, or the "
|
||||
"programs are ones your account cannot see.")
|
||||
|
||||
header = ["TIME", "COACH", "BOOKED", "CLASS", "DUR", "ID"]
|
||||
table: list[list[str]] = []
|
||||
for r in rows:
|
||||
mins = duration_minutes(r.get("start", ""), r.get("end") or r.get("finish") or "")
|
||||
booked, limit = r.get("booked"), r.get("limit") or r.get("class_limit")
|
||||
table.append([
|
||||
_hhmm(r.get("start", "")),
|
||||
str(r.get("coach") or "-"),
|
||||
f"{booked}/{limit}" if booked is not None and limit else "-",
|
||||
str(r.get("name") or "-"),
|
||||
f"{mins}min" if mins else "-",
|
||||
str(r.get("class_id") or "-"),
|
||||
])
|
||||
|
||||
widths = [max(len(header[i]), *(len(row[i]) for row in table))
|
||||
for i in range(len(header))]
|
||||
lines = [" ".join(h.ljust(widths[i]) for i, h in enumerate(header)).rstrip()]
|
||||
lines.append(" ".join("-" * widths[i] for i in range(len(header))))
|
||||
for row in table:
|
||||
lines.append(" ".join(c.ljust(widths[i]) for i, c in enumerate(row)).rstrip())
|
||||
|
||||
programs = sorted({str(r.get("program_id") or "") for r in rows if r.get("program_id")})
|
||||
lines.append("")
|
||||
lines.append(f"{len(rows)} classes on {date}"
|
||||
+ (f" · programs: {', '.join(programs)}" if len(programs) > 1 else ""))
|
||||
if len(programs) > 1:
|
||||
lines.append("Classes in different programs have different workouts.")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def attendee_rows(data: Any) -> list[dict[str, Any]]:
|
||||
"""Attendees with status, de-duplicated by reservation.
|
||||
|
||||
The name field is ``PersonName``. It is not ``Name`` -- assuming so yields an
|
||||
empty list on a full class, which reads as "nobody came" rather than as a
|
||||
bug.
|
||||
"""
|
||||
rows: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
for container in find_all(data, "ClassDetailAttendee"):
|
||||
items = container.get("List") if isinstance(container, dict) else container
|
||||
if not isinstance(items, list):
|
||||
continue
|
||||
for row in items:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
name = str(row.get("PersonName") or row.get("Name") or "").strip()
|
||||
if not name:
|
||||
first = str(row.get("Firstname") or row.get("FirstName") or "").strip()
|
||||
last = str(row.get("LastName") or "").strip()
|
||||
name = " ".join(p for p in (first, last) if p)
|
||||
key = str(row.get("ClassReservationId") or name)
|
||||
if not name or key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
rows.append({
|
||||
"name": name,
|
||||
"status": str(row.get("StatusInClass") or "").strip(),
|
||||
"signed_in": bool(row.get("HasSignedIn")),
|
||||
"no_show": bool(row.get("HasNoShow")),
|
||||
"waitlisted": bool(row.get("isWaitlisted") or row.get("IsWaitlisted")),
|
||||
"anonymous": bool(row.get("IsAnonymous")),
|
||||
"member_since": str(row.get("MemberSince") or ""),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def attendee_names(data: Any) -> list[str]:
|
||||
"""Just the display names, order preserved."""
|
||||
return [r["name"] for r in attendee_rows(data)]
|
||||
|
||||
|
||||
def attendee_block(data: Any, *, booked: Any = None, limit: Any = None) -> str:
|
||||
"""Named attendee list for the `list workout <id>` view."""
|
||||
rows = attendee_rows(data)
|
||||
cap = f" of {booked}/{limit} booked" if booked is not None and limit else ""
|
||||
if not rows:
|
||||
return "## Attendees\nNone returned for this class."
|
||||
|
||||
roster = [r for r in rows if not r["waitlisted"]]
|
||||
waiting = [r for r in rows if r["waitlisted"]]
|
||||
|
||||
lines = [f"## Attendees — {len(roster)}{cap}"]
|
||||
for i, r in enumerate(roster, 1):
|
||||
marks = []
|
||||
if r["signed_in"]:
|
||||
marks.append("signed in")
|
||||
elif r["status"]:
|
||||
marks.append(r["status"].lower())
|
||||
if r["no_show"]:
|
||||
marks.append("no-show")
|
||||
if r["anonymous"]:
|
||||
marks.append("anonymous")
|
||||
suffix = f" [{', '.join(marks)}]" if marks else ""
|
||||
lines.append(f"{i:>2}. {r['name']}{suffix}")
|
||||
|
||||
if waiting:
|
||||
lines.append(f"\nWaitlist — {len(waiting)}")
|
||||
lines += [f"{i:>2}. {r['name']}" for i, r in enumerate(waiting, 1)]
|
||||
|
||||
# Observed: a class the account itself attended lists one fewer person than
|
||||
# it has reservations, and the account holder is absent. Flag the gap rather
|
||||
# than let the numbers look like a miscount.
|
||||
try:
|
||||
missing = int(booked) - len(roster)
|
||||
except (TypeError, ValueError):
|
||||
missing = 0
|
||||
if missing > 0:
|
||||
lines.append(f"\n({missing} booked not listed — the API omits the requesting "
|
||||
f"account, so your own reservation does not appear here.)")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def attendees(data: Any) -> str:
|
||||
rows = first_list(data)
|
||||
names = []
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
flat: dict[str, Any] = dict(row)
|
||||
for value in row.values():
|
||||
if isinstance(value, dict):
|
||||
flat.update(value)
|
||||
name = flat.get("Name") or " ".join(
|
||||
str(flat[k]) for k in ("FirstName", "LastName") if flat.get(k)
|
||||
)
|
||||
if name:
|
||||
names.append(str(name).strip())
|
||||
if not names:
|
||||
return "No attendees listed."
|
||||
return f"{len(names)} attendees: " + ", ".join(names)
|
||||
|
||||
|
||||
def _real_records(rows: Any) -> list[dict]:
|
||||
"""Drop OutSystems placeholder rows (``Id`` of ``"0"``/``0``/absent).
|
||||
|
||||
OutSystems returns a single zeroed record for an empty result set, which
|
||||
reads exactly like real data unless filtered.
|
||||
"""
|
||||
out = []
|
||||
for row in rows or []:
|
||||
if isinstance(row, dict) and str(row.get("Id", "0")) not in ("0", ""):
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
def _as_int(value: Any) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _render_component(comp: dict) -> str:
|
||||
"""One workout component as text.
|
||||
|
||||
Field roles, learned from live data -- reading only Name/Comment silently
|
||||
drops the actual movements:
|
||||
|
||||
* ``Description`` the metcon itself (movements and rep scheme)
|
||||
* ``MeasureRepScheme`` the strength set scheme, plain text with newlines
|
||||
* ``Comment`` coaching notes, goals, stimulus, RPE
|
||||
* ``EachRoundTypeLabel`` how it is scored
|
||||
"""
|
||||
parts: list[str] = []
|
||||
|
||||
name = flatten_html(str(comp.get("Name") or ""))
|
||||
if name:
|
||||
parts.append(f"## {name}" if comp.get("IsSection") else f"### {name}")
|
||||
|
||||
scoring = str(comp.get("EachRoundTypeLabel") or "").strip()
|
||||
rounds = _as_int(comp.get("Rounds"))
|
||||
meta = []
|
||||
if rounds:
|
||||
meta.append(f"{rounds} rounds")
|
||||
if scoring:
|
||||
meta.append(f"score: {scoring}")
|
||||
if meta:
|
||||
parts.append("_" + " · ".join(meta) + "_")
|
||||
|
||||
# MeasureRepScheme is plain text with real newlines, not HTML.
|
||||
scheme = str(comp.get("MeasureRepScheme") or "").strip()
|
||||
if scheme:
|
||||
parts.append(scheme)
|
||||
|
||||
var_scheme = str(comp.get("WODComponentVariableRepScheme") or "").strip()
|
||||
if var_scheme and var_scheme not in scheme:
|
||||
parts.append(var_scheme)
|
||||
|
||||
description = flatten_html(str(comp.get("Description") or ""))
|
||||
if description:
|
||||
parts.append(description)
|
||||
|
||||
comment = flatten_html(str(comp.get("Comment") or ""))
|
||||
# Authors use lines of dashes as visual spacers. Drop them, and drop the
|
||||
# whole comment if that is all it was.
|
||||
comment = "\n".join(
|
||||
line for line in comment.splitlines() if line.strip().strip("-–—")
|
||||
).strip()
|
||||
if comment:
|
||||
parts.append(comment)
|
||||
|
||||
return "\n\n".join(p for p in parts if p)
|
||||
|
||||
|
||||
def workout(data: Any, *, notes: bool = False) -> str:
|
||||
"""Flatten WOD components into readable blocks.
|
||||
|
||||
``GetAllWorkoutData`` puts the workout at
|
||||
``Response.ResponseWOD.ResponseWorkout``; ``GetClasses`` uses
|
||||
``ProgramWODList``. Both are handled, since either may be the source.
|
||||
|
||||
``Notes`` is the coach's brief -- several thousand characters of prose. It is
|
||||
excluded unless asked for, because keeping output small is the whole reason
|
||||
this client exists.
|
||||
"""
|
||||
wods: list[dict] = []
|
||||
for wod in find_all(data, "ResponseWorkout"):
|
||||
if isinstance(wod, dict) and str(wod.get("Id", "0")) not in ("0", ""):
|
||||
wods.append(wod)
|
||||
for container in find_all(data, "ProgramWODList"):
|
||||
if isinstance(container, dict):
|
||||
wods.extend(_real_records(container.get("List")))
|
||||
|
||||
blocks: list[str] = []
|
||||
for wod in wods:
|
||||
title = str(wod.get("Name") or "").strip()
|
||||
if title:
|
||||
blocks.append(f"# {title}")
|
||||
|
||||
components: list[dict] = []
|
||||
for comp_container in find_all(wod, "WorkoutComponents"):
|
||||
if isinstance(comp_container, dict):
|
||||
components.extend(_real_records(comp_container.get("List")))
|
||||
# WODComponentOrder is the authoring order; without it, sections and
|
||||
# their metcons can come out interleaved.
|
||||
components.sort(key=lambda c: _as_int(c.get("WODComponentOrder")))
|
||||
|
||||
for comp in components:
|
||||
chunk = _render_component(comp)
|
||||
if chunk and chunk not in blocks:
|
||||
blocks.append(chunk)
|
||||
|
||||
if notes:
|
||||
brief = flatten_html(str(wod.get("Notes") or ""))
|
||||
if brief:
|
||||
blocks.append("## Coach's brief\n" + brief)
|
||||
|
||||
if not blocks:
|
||||
errors = [e for e in find_all(data, "ErrorMessage") if isinstance(e, str) and e.strip()]
|
||||
detail = f" Server said: {errors[0]}" if errors else ""
|
||||
return ("No workout content in response -- this is also what an unposted "
|
||||
f"WOD looks like, so treat it as 'not posted', not a failure.{detail}")
|
||||
return "\n\n".join(blocks)
|
||||
|
||||
|
||||
def class_rows(data: Any) -> list[dict[str, Any]]:
|
||||
"""Structured class list for a day. Exposed so callers can chain on it.
|
||||
|
||||
Reads each row's own scalar fields only. Flattening nested dicts up would
|
||||
be wrong here: a class row contains
|
||||
``GroupMemberReservationStatus.ClassId == "0"``, which clobbers the real
|
||||
``Id`` and collapses every class into one.
|
||||
"""
|
||||
rows: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
# The scheduler nests as ResponseClassList.Class.List; be tolerant of the
|
||||
# other containers seen in this API.
|
||||
candidates: list[Any] = []
|
||||
for key in ("Class", "ClassList", "ScheduleList"):
|
||||
for container in find_all(data, key):
|
||||
if isinstance(container, dict) and isinstance(container.get("List"), list):
|
||||
candidates.append(container["List"])
|
||||
|
||||
for items in candidates:
|
||||
for row in _real_records(items):
|
||||
cid = str(row.get("Id") or "")
|
||||
if not cid or cid in seen:
|
||||
continue
|
||||
seen.add(cid)
|
||||
coach = ""
|
||||
coaches = row.get("Coaches")
|
||||
if isinstance(coaches, dict):
|
||||
for entry in coaches.get("List") or []:
|
||||
if isinstance(entry, dict) and entry.get("Name"):
|
||||
coach = str(entry["Name"])
|
||||
break
|
||||
rows.append({
|
||||
"class_id": cid,
|
||||
"name": str(row.get("Name") or row.get("ClassName") or ""),
|
||||
"start": str(row.get("StartTime") or ""),
|
||||
"end": str(row.get("EndTime") or ""),
|
||||
"date": str(row.get("StartDate") or "")[:10],
|
||||
"program_id": str(row.get("ProgramId") or ""),
|
||||
"coach": coach,
|
||||
"booked": row.get("ReservationCount"),
|
||||
"limit": row.get("ClassLimit"),
|
||||
"waitlist": row.get("WaitlistCount"),
|
||||
"status": str(row.get("Status") or ""),
|
||||
})
|
||||
return sorted(rows, key=lambda r: r["start"])
|
||||
|
||||
|
||||
def classes(data: Any) -> str:
|
||||
"""Class list for a day, plus any WOD carried in the same response."""
|
||||
rows = class_rows(data)
|
||||
lines = []
|
||||
for r in rows:
|
||||
bits = [r["start"], r["name"] or "(unnamed)"]
|
||||
line = "- " + " ".join(b for b in bits if b)
|
||||
if r["booked"] is not None and r["limit"]:
|
||||
line += f" {r['booked']} | {r['limit']}"
|
||||
if r["coach"]:
|
||||
line += f" coach={r['coach']}"
|
||||
if r["class_id"]:
|
||||
line += f" class_id={r['class_id']}"
|
||||
lines.append(line)
|
||||
|
||||
wod = workout(data)
|
||||
if not wod.startswith("No workout content"):
|
||||
lines.append("\n" + wod)
|
||||
return "\n".join(lines) if lines else "No classes found for that date."
|
||||
|
||||
|
||||
RENDERERS = {
|
||||
"bookings": bookings,
|
||||
"attendees": attendees,
|
||||
"workout": workout,
|
||||
"classes": classes,
|
||||
"schedule": classes,
|
||||
}
|
||||
|
||||
|
||||
def render(action_key: str, data: Any) -> str:
|
||||
fn = RENDERERS.get(action_key)
|
||||
if fn is None:
|
||||
import json as _json
|
||||
return _json.dumps(data, indent=1)[:4000]
|
||||
return fn(data)
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Cache-through data access.
|
||||
|
||||
Every fetch goes through here so the SQLite cache is not something callers can
|
||||
forget to use. Each function reports whether it hit disk or the network, because
|
||||
"is this stale?" is a question the user will ask.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import sqlite3
|
||||
from typing import Any
|
||||
|
||||
from . import client, render, store
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class Result:
|
||||
"""A payload plus where it came from."""
|
||||
|
||||
data: Any
|
||||
source: str # "cache" or "network"
|
||||
fetched_at: str | None = None
|
||||
|
||||
@property
|
||||
def cached(self) -> bool:
|
||||
return self.source == "cache"
|
||||
|
||||
|
||||
def _through(conn: sqlite3.Connection, key: str, fetch, *, refresh: bool) -> Result:
|
||||
if not refresh:
|
||||
hit = store.get_payload(conn, key)
|
||||
if hit is not None:
|
||||
data, fetched_at = hit
|
||||
return Result(data, "cache", fetched_at)
|
||||
data = fetch()
|
||||
store.put_payload(conn, key, data)
|
||||
return Result(data, "network")
|
||||
|
||||
|
||||
def day_classes(conn: sqlite3.Connection, date: str, *,
|
||||
refresh: bool = False) -> tuple[list[dict[str, Any]], Result]:
|
||||
"""A day's classes, newest cache first. Also indexes them for id lookup."""
|
||||
result = _through(
|
||||
conn, f"schedule:{date}",
|
||||
lambda: client.call("schedule", {"FromDate": date}),
|
||||
refresh=refresh,
|
||||
)
|
||||
rows = render.class_rows(result.data)
|
||||
# Index even on a cache hit: the classes table is what resolves a class id
|
||||
# to its date and program later, and it may have been pruned.
|
||||
store.upsert_classes(conn, date, rows)
|
||||
return rows, result
|
||||
|
||||
|
||||
def workout(conn: sqlite3.Connection, date: str, program_id: str | None, *,
|
||||
refresh: bool = False) -> Result:
|
||||
program = str(program_id or "")
|
||||
overrides: dict[str, Any] = {"SelectedDate": date}
|
||||
if program:
|
||||
overrides["GymProgramId"] = program
|
||||
return _through(
|
||||
conn, f"workout:{date}:{program or 'default'}",
|
||||
lambda: client.call("workout", overrides),
|
||||
refresh=refresh,
|
||||
)
|
||||
|
||||
|
||||
def attendees(conn: sqlite3.Connection, class_id: str,
|
||||
class_limit: int | None = None, *, refresh: bool = False) -> Result:
|
||||
overrides: dict[str, Any] = {"ClassId": str(class_id)}
|
||||
if class_limit:
|
||||
# MaxRecords defaults to 20 in the captured body; raise it if a class is
|
||||
# somehow larger so the list is never silently truncated.
|
||||
overrides["ClassLimit"] = int(class_limit)
|
||||
overrides["MaxRecords"] = max(20, int(class_limit))
|
||||
return _through(
|
||||
conn, f"attendees:{class_id}",
|
||||
lambda: client.call("attendees", overrides),
|
||||
refresh=refresh,
|
||||
)
|
||||
|
||||
|
||||
def resolve_class(conn: sqlite3.Connection, class_id: str) -> dict[str, Any] | None:
|
||||
"""Look up a class id previously seen via :func:`day_classes`.
|
||||
|
||||
Class ids are per-occurrence, so there is no way to derive the date or
|
||||
program from the id alone -- it has to have been indexed by a `list date`.
|
||||
"""
|
||||
return store.get_class(conn, str(class_id))
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Local SQLite cache.
|
||||
|
||||
Wodify data for a past day does not change, and even today's schedule changes
|
||||
slowly, so a same-day cache removes almost all network reads. Anything fetched
|
||||
is stored with the local date it was fetched on; a later query on that same date
|
||||
is served from disk.
|
||||
|
||||
stdlib only (``sqlite3``), keeping the query path dependency-free.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as _dt
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sqlite3
|
||||
import stat
|
||||
from typing import Any, Iterable
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS payloads (
|
||||
key TEXT PRIMARY KEY,
|
||||
fetched_on TEXT NOT NULL,
|
||||
fetched_at TEXT NOT NULL,
|
||||
body TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS classes (
|
||||
class_id TEXT PRIMARY KEY,
|
||||
date TEXT NOT NULL,
|
||||
start TEXT,
|
||||
finish TEXT,
|
||||
name TEXT,
|
||||
program_id TEXT,
|
||||
coach TEXT,
|
||||
booked INTEGER,
|
||||
class_limit INTEGER,
|
||||
waitlist INTEGER,
|
||||
fetched_on TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS classes_by_date ON classes (date);
|
||||
"""
|
||||
|
||||
|
||||
def db_path() -> pathlib.Path:
|
||||
override = os.environ.get("WODIFY_DB", "").strip()
|
||||
if override:
|
||||
return pathlib.Path(override).expanduser()
|
||||
return pathlib.Path.home() / ".cache" / "wodify" / "wodify.db"
|
||||
|
||||
|
||||
def today() -> str:
|
||||
"""Local calendar date. Freshness is per-day, so local is what a user means."""
|
||||
return _dt.date.today().isoformat()
|
||||
|
||||
|
||||
def connect(path: pathlib.Path | None = None) -> sqlite3.Connection:
|
||||
path = path or db_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
existed = path.exists()
|
||||
conn = sqlite3.connect(path)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.executescript(SCHEMA)
|
||||
conn.commit()
|
||||
if not existed:
|
||||
# Attendee names and schedules are personal data; keep it owner-only.
|
||||
try:
|
||||
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
except OSError:
|
||||
pass
|
||||
return conn
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# raw payloads
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def get_payload(conn: sqlite3.Connection, key: str,
|
||||
*, on: str | None = None) -> tuple[Any, str] | None:
|
||||
"""Return ``(data, fetched_at)`` if cached on ``on`` (default today)."""
|
||||
row = conn.execute(
|
||||
"SELECT body, fetched_at FROM payloads WHERE key = ? AND fetched_on = ?",
|
||||
(key, on or today()),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
try:
|
||||
return json.loads(row["body"]), row["fetched_at"]
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
|
||||
|
||||
def put_payload(conn: sqlite3.Connection, key: str, data: Any) -> None:
|
||||
conn.execute(
|
||||
"INSERT INTO payloads (key, fetched_on, fetched_at, body) VALUES (?, ?, ?, ?) "
|
||||
"ON CONFLICT(key) DO UPDATE SET fetched_on=excluded.fetched_on, "
|
||||
"fetched_at=excluded.fetched_at, body=excluded.body",
|
||||
(key, today(), _dt.datetime.now().isoformat(timespec="seconds"),
|
||||
json.dumps(data)),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# classes
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def upsert_classes(conn: sqlite3.Connection, date: str,
|
||||
rows: Iterable[dict[str, Any]]) -> int:
|
||||
"""Store a day's classes so ``workout <id>`` can resolve an id later.
|
||||
|
||||
``date`` is passed explicitly: rows carry the class's own StartDate, which
|
||||
for a scheduler response is the queried day, but relying on it would break
|
||||
quietly if the server ever echoed something else.
|
||||
"""
|
||||
stamp = today()
|
||||
count = 0
|
||||
for row in rows:
|
||||
cid = str(row.get("class_id") or "")
|
||||
if not cid:
|
||||
continue
|
||||
conn.execute(
|
||||
"INSERT INTO classes (class_id, date, start, finish, name, program_id, "
|
||||
"coach, booked, class_limit, waitlist, fetched_on) "
|
||||
"VALUES (?,?,?,?,?,?,?,?,?,?,?) "
|
||||
"ON CONFLICT(class_id) DO UPDATE SET date=excluded.date, "
|
||||
"start=excluded.start, finish=excluded.finish, name=excluded.name, "
|
||||
"program_id=excluded.program_id, coach=excluded.coach, "
|
||||
"booked=excluded.booked, class_limit=excluded.class_limit, "
|
||||
"waitlist=excluded.waitlist, fetched_on=excluded.fetched_on",
|
||||
(cid, row.get("date") or date, row.get("start"), row.get("end"),
|
||||
row.get("name"), row.get("program_id"), row.get("coach"),
|
||||
row.get("booked"), row.get("limit"), row.get("waitlist"), stamp),
|
||||
)
|
||||
count += 1
|
||||
conn.commit()
|
||||
return count
|
||||
|
||||
|
||||
def classes_for_date(conn: sqlite3.Connection, date: str,
|
||||
*, fresh_only: bool = True) -> list[dict[str, Any]]:
|
||||
sql = "SELECT * FROM classes WHERE date = ?"
|
||||
args: list[Any] = [date]
|
||||
if fresh_only:
|
||||
sql += " AND fetched_on = ?"
|
||||
args.append(today())
|
||||
sql += " ORDER BY start"
|
||||
return [dict(r) for r in conn.execute(sql, args).fetchall()]
|
||||
|
||||
|
||||
def get_class(conn: sqlite3.Connection, class_id: str) -> dict[str, Any] | None:
|
||||
row = conn.execute("SELECT * FROM classes WHERE class_id = ?",
|
||||
(str(class_id),)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def stats(conn: sqlite3.Connection) -> dict[str, Any]:
|
||||
payloads = conn.execute("SELECT COUNT(*) AS n FROM payloads").fetchone()["n"]
|
||||
fresh = conn.execute("SELECT COUNT(*) AS n FROM payloads WHERE fetched_on = ?",
|
||||
(today(),)).fetchone()["n"]
|
||||
classes = conn.execute("SELECT COUNT(*) AS n FROM classes").fetchone()["n"]
|
||||
days = conn.execute("SELECT COUNT(DISTINCT date) AS n FROM classes").fetchone()["n"]
|
||||
return {"payloads": payloads, "payloads_fresh_today": fresh,
|
||||
"classes": classes, "days": days}
|
||||
Reference in new issue
Block a user