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
+12
@@ -0,0 +1,12 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
build/
|
||||
dist/
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# Session credentials -- never commit.
|
||||
session.json
|
||||
*.session.json
|
||||
.env
|
||||
@@ -0,0 +1,270 @@
|
||||
# wodify — agent notes
|
||||
|
||||
Read-only client for the **Wodify athlete app** (`claycrossfit.wodify.com`), built so an
|
||||
agent can answer "what's the workout / what did I book / who's coaching / who else is going"
|
||||
**without driving a browser at query time**.
|
||||
|
||||
Replaces browser automation, which was slow and burned a lot of tokens rendering a SPA just to
|
||||
read text back out of the DOM.
|
||||
|
||||
## Hard rule: read-only
|
||||
|
||||
This client must never reserve, cancel, check in, log results, accept terms, change settings,
|
||||
or buy anything. The credential it uses is a *full-session* login — Wodify issues no read-only
|
||||
token — so nothing at the credential layer enforces this. Enforcement lives in two places, and
|
||||
both must stay:
|
||||
|
||||
1. `actions.py::ACTIONS` — an explicit allowlist. Nothing not registered can be called.
|
||||
2. `actions.py::assert_read_only` — rejects any path containing a write marker
|
||||
(`Create`, `Save`, `Reserve`, `Cancel`, `SignIn`, …), applied *even to* allowlisted entries.
|
||||
|
||||
`tests/test_actions.py` asserts both, including that known write endpoints are refused. If you
|
||||
add an action, add a test.
|
||||
|
||||
## How it works
|
||||
|
||||
Wodify's athlete app is OutSystems Reactive. Its data actions are plain JSON POSTs:
|
||||
|
||||
```
|
||||
POST https://<host>/WodifyClient/screenservices/<Module>/<Screen>/<Action>
|
||||
X-CSRFToken: <28 chars>
|
||||
Cookie: nr1W_Theme_UI=…; nr2W_Theme_UI=…; AuthenticationToken=…
|
||||
{"versionInfo": {"moduleVersion": …, "apiVersion": …},
|
||||
"viewName": …, "inputParameters": {…}}
|
||||
```
|
||||
|
||||
Two phases:
|
||||
|
||||
| Phase | Cost | Needs a browser? |
|
||||
|-------|------|------------------|
|
||||
| **prime** | rare — once, then on Wodify redeploys | yes, via CDP |
|
||||
| **query** | one HTTP POST per question | no |
|
||||
|
||||
`prime` attaches to a logged-in Chrome over CDP, captures the cookies, the CSRF token, and each
|
||||
action's `versionInfo` + `inputParameters` shape, and writes them to a cache. `query` then does
|
||||
pure stdlib HTTP.
|
||||
|
||||
### Why prime needs a browser
|
||||
|
||||
- The session bearer `nr1W_Theme_UI` is **HttpOnly** (184 chars). `document.cookie` cannot read
|
||||
it, so it cannot be exported by hand — this is why an earlier cookie-paste approach was
|
||||
impossible, not merely inconvenient.
|
||||
- `X-CSRFToken` is not in `localStorage`, cookies, or any JS global. It only appears on outbound
|
||||
requests, so it has to be sniffed.
|
||||
- `apiVersion` is **per-action**, not global (two actions returned
|
||||
`w5JqiO_2RpM6VdmR6V470Q` and `hBUtX6paK6XbMlXso4zBcw`). Each endpoint needs its own.
|
||||
|
||||
### Self-healing
|
||||
|
||||
Every response carries `versionInfo: {hasModuleVersionChanged, hasApiVersionChanged}`. When
|
||||
either flips true — or a call returns 401/403 — the cache is stale and `prime` must re-run.
|
||||
`client.py` raises `VersionStale` / `SessionExpired` rather than returning wrong data.
|
||||
|
||||
## Dependencies
|
||||
|
||||
The **query path is stdlib-only** (`urllib`, `json`, `gzip`) — deliberate, so the hot path has
|
||||
no install step. `prime` needs `websockets` (declared as the `prime` extra) because CDP is a
|
||||
WebSocket protocol.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
src/wodify/
|
||||
config.py host, CDP URL, cache path, all env-overridable
|
||||
actions.py read-only allowlist + write guard
|
||||
cdp.py minimal CDP client (prime only)
|
||||
prime.py capture cookies / CSRF / versionInfo -> cache
|
||||
client.py HTTP query path (stdlib)
|
||||
store.py SQLite cache (sqlite3, stdlib)
|
||||
service.py cache-through data access -- all fetches go through here
|
||||
render.py compact text output (token-efficient, not a DOM dump)
|
||||
listcmd.py the `list date` / `list workout` commands
|
||||
cli.py python -m wodify <cmd>
|
||||
```
|
||||
|
||||
## The `list` interface
|
||||
|
||||
```
|
||||
wodify list date 2026-07-25 # classes: time, coach, booked/max, title, duration, ID
|
||||
wodify list workout 190917816 # attendee names + the workout for that class
|
||||
```
|
||||
|
||||
`list date` prints IDs; `list workout <id>` consumes one. Both accept `--refresh`
|
||||
(bypass cache), `--json`, and `list workout` also takes `--notes` for the coach's brief.
|
||||
|
||||
A class ID resolves to nothing on its own — it is per-occurrence, and carries neither date
|
||||
nor program. `list date` indexes the day's classes into SQLite, and `list workout` looks the
|
||||
ID up there. Querying an ID for a day never listed returns a message saying exactly that.
|
||||
|
||||
## SQLite cache
|
||||
|
||||
`~/.cache/wodify/wodify.db` (override with `WODIFY_DB`), created mode 600 — it holds other
|
||||
members' names.
|
||||
|
||||
| Table | Holds |
|
||||
|-------|-------|
|
||||
| `payloads` | raw action responses, keyed e.g. `schedule:2026-07-25`, stamped with the local date |
|
||||
| `classes` | one row per class occurrence, so an ID resolves to date + program + limit |
|
||||
|
||||
Freshness is **per local calendar day**: a payload fetched today is reused, one from
|
||||
yesterday is a miss. Past days never change, so this is generous rather than risky; today's
|
||||
schedule can shift, which is what `--refresh` is for. Every command prints whether the answer
|
||||
came from cache or the wire.
|
||||
|
||||
Only `service.py` fetches, so caching cannot be forgotten at a call site.
|
||||
|
||||
## Environment
|
||||
|
||||
| Var | Default | Meaning |
|
||||
|-----|---------|---------|
|
||||
| `WODIFY_HOST` | `claycrossfit.wodify.com` | tenant host |
|
||||
| `WODIFY_CDP_URL` | `http://127.0.0.1:9222` | Chrome CDP root for `prime` |
|
||||
| `WODIFY_CACHE` | `~/.cache/wodify/session.json` | cached headers, mode 600 |
|
||||
|
||||
The cache holds live session credentials. Mode 600, never committed (`.gitignore`), never
|
||||
logged. Anything that prints it is a bug.
|
||||
|
||||
### Priming from this machine
|
||||
|
||||
The logged-in Chrome profile lives on the CDP host, not here. Tunnel first:
|
||||
|
||||
```
|
||||
ssh -L 9222:127.0.0.1:9222 <cdp-host>
|
||||
```
|
||||
|
||||
Then `python -m wodify prime` works locally against the remote profile.
|
||||
|
||||
## Status
|
||||
|
||||
### Working, verified live (2026-07-25)
|
||||
|
||||
`prime` and `bookings` run end-to-end against the real service with **no browser at query
|
||||
time**:
|
||||
|
||||
```
|
||||
$ python -m wodify bookings
|
||||
- 2026-07-20 17:30:00 CrossFit: 5:30 PM [Attended]
|
||||
- 2026-07-22 17:30:00 CrossFit: 5:30 PM [Attended]
|
||||
- 2026-07-24 17:30:00 CrossFit: 5:30 PM [Attended]
|
||||
```
|
||||
|
||||
- `prime` over an SSH tunnel to the CDP host's Chrome: 338-char cookie, 28-char CSRF,
|
||||
`moduleVersion=4qHsLi2Es1qvgd2NhStmPw`
|
||||
- Auth accepted: responses carry `hasApiVersionChanged: false`, so cookie + CSRF + both
|
||||
versions are all valid
|
||||
- 60 tests pass, no network needed
|
||||
|
||||
### The body contract (learned the hard way)
|
||||
|
||||
The `tamird/wodify-race-repro` example uses `inputParameters`. That is right for
|
||||
`ServiceAPI*` actions but **wrong for screen data actions**, which send:
|
||||
|
||||
```json
|
||||
{"versionInfo": {…}, "viewName": "MainScreens.Home",
|
||||
"screenData": {"variables": {…entire screen state, incl. ClientVariables…}}}
|
||||
```
|
||||
|
||||
Sending `inputParameters` — or adding any key not in the captured body — returns
|
||||
`400 Failed to parse JSON request content`. So `prime` stores the **whole body** and `client`
|
||||
patches individual leaves via `set_field`, which only writes keys that already exist.
|
||||
|
||||
Levers that live in `screenData.variables.ClientVariables`: `SelectedDate`, `GymProgramId`,
|
||||
`ActiveLocationId`, `CustomerId`, `UserId`.
|
||||
|
||||
`SelectedDate` must be a **bare `YYYY-MM-DD`**. Every datetime form probed
|
||||
(`…T00:00:00`, `…T00:00:00Z`, `…T07:00:00.000Z`) returns 400 — note the browser's
|
||||
*localStorage* holds `2026-07-24T07:00:00.000Z`, which is not the wire format.
|
||||
|
||||
### WOD content — solved
|
||||
|
||||
The content action is **`WOD_Flow/GetAllWorkoutData_WB/DataActionGetAllWorkoutData`**,
|
||||
`viewName: MainScreens.Exercise`. Content at `Response.ResponseWOD.ResponseWorkout`:
|
||||
`Name`, `Notes` (coach's brief), and `WorkoutComponents.List[].{Name, Comment, IsSection}`.
|
||||
|
||||
Why it took a while to find, recorded so nobody repeats it:
|
||||
|
||||
- `GetWorkoutData_HasWodLeaderboardComponents` **sounds** like the content action but returns
|
||||
a bare `{"Response": true}`. It is registered as `wodflags`, never `workout`.
|
||||
- The content action **does not fire on a cold load of `/WodifyClient/Exercise`** — that
|
||||
screen shows "No workout posted" and issues no content request at all. Enumerating requests
|
||||
on a direct load therefore "proves" the action does not exist. It only fires when the screen
|
||||
is reached properly: class detail → **Go to workout**.
|
||||
- OutSystems also **caches** the data action, so revisiting the same date issues no request.
|
||||
Capturing it requires navigating to a date whose WOD is not already cached.
|
||||
- `ProgramWODList` on `GetClasses` was a red herring — it stays a placeholder record.
|
||||
|
||||
Body contract: `SelectedDate` and `GymProgramId` appear in **two** sibling objects
|
||||
(`RequestCache` *and* `In_Request`). `client.set_field` writes every occurrence, which is why
|
||||
overriding the date works; writing only the first would silently query the wrong day.
|
||||
|
||||
`prime` reproduces the walk via `WORKOUT_WALK_JS` (Schedule → date → class → Go to workout),
|
||||
which also captures the class-detail actions as a side effect. Pass `--workout-date` for a day
|
||||
that actually has a posted WOD; a day with nothing published cannot capture it.
|
||||
|
||||
### Both target workflows work (verified live 2026-07-25)
|
||||
|
||||
```
|
||||
$ python -m wodify bookings --since 2026-07-18 --until 2026-07-25 --attended
|
||||
- 2026-07-20 17:30:00 CrossFit: 5:30 PM [Attended] class_id=190917816
|
||||
- 2026-07-22 17:30:00 CrossFit: 5:30 PM [Attended] class_id=190917818
|
||||
- 2026-07-24 17:30:00 CrossFit: 5:30 PM [Attended] class_id=190917820
|
||||
|
||||
$ python -m wodify workout --date 2026-07-22
|
||||
# CrossFit - Wed, Jul 22
|
||||
## WARM-UP
|
||||
General Warm-Up
|
||||
1:30 Cardio Choice
|
||||
...
|
||||
```
|
||||
|
||||
`bookings` emits `class_id` so the two chain together. Range filtering is client-side: the
|
||||
action returns the whole history in one call, so filtering here is cheaper than negotiating a
|
||||
range with the server.
|
||||
|
||||
The coach's brief (`Notes`) is **excluded unless `--notes`** is passed — it runs to several
|
||||
thousand characters, and small output is the entire reason this client exists.
|
||||
|
||||
### Field-name traps (each one produced confident wrong output)
|
||||
|
||||
These all failed *silently* — plausible output, no error. Worth reading before adding a
|
||||
renderer.
|
||||
|
||||
| Field | Trap |
|
||||
|-------|------|
|
||||
| `PersonName` | attendee name is **not** `Name`. Looking for `Name` returns an empty list on a full class, reading as "nobody came" |
|
||||
| `Description` | the metcon's movements. Reading only `Name`/`Comment` yields goals and RPE with no workout |
|
||||
| `MeasureRepScheme` | strength set scheme, plain text with real newlines (not HTML) |
|
||||
| `FromDate` | the scheduler's date key. It is **not** `SelectedDate` (that is the workout screen), so `--date` was ignored and every query returned today |
|
||||
| `Id` on a class row | **not** `ClassId`. A class row nests `GroupMemberReservationStatus.ClassId == "0"`, so flattening nested dicts up clobbers the real id and collapses every class into one |
|
||||
| `Id == "0"` | OutSystems' empty-record placeholder. Reads exactly like real data; `render._real_records` filters it |
|
||||
|
||||
A related lesson worth keeping: when the attendee list came back empty, the code printed an
|
||||
invented explanation ("Wodify hides names for anonymous members"). That was a fabricated cause
|
||||
for a bug in the same function. Empty results now say only what is true — "None returned" —
|
||||
and speculate about nothing.
|
||||
|
||||
### Known quirks
|
||||
|
||||
- Attendee lists omit **the requesting account**, so a class you attended shows one fewer
|
||||
person than it has reservations. `render.attendee_block` flags the gap rather than letting
|
||||
it look like a miscount.
|
||||
- `schedule` only returns programs the account can see: the request carries
|
||||
`CustomerHasShowAllClassesEnabled: false` and `IncludeDropInsAndFreeTrials: false`. Programs
|
||||
like Open Gym or Personal Training will not appear even if they ran.
|
||||
- `ReservationCount` is reservations, not attendance. For a past class, the attendee list's
|
||||
`HasSignedIn` / `HasNoShow` flags are the real signal.
|
||||
|
||||
### Not yet done
|
||||
- No deploy back to the CDP host / hermes skill rewiring — local build first, by request
|
||||
- `classes` (the Home variant of `GetClasses`) still returns placeholders only; superseded by
|
||||
`schedule` and kept solely as a labelled trap
|
||||
|
||||
## Gotchas found the hard way
|
||||
|
||||
- `/WodifyClient/Exercise` (the workout screen) renders **"No workout posted"** even when a
|
||||
workout exists, unless reached via a class. Irrelevant to this client — we call the data
|
||||
action directly — but do not "verify" against that screen and conclude the data is missing.
|
||||
- A stale `ClassId` **redirects to Home** instead of erroring. `ClassId` is per-occurrence and
|
||||
changes daily.
|
||||
- Capacity is `reserved | limit` and can exceed the limit when the gym overbooks. Report it
|
||||
verbatim.
|
||||
@@ -0,0 +1,136 @@
|
||||
# wodify
|
||||
|
||||
Read-only client for the **Wodify athlete app**. Answers "what's the workout", "what did I
|
||||
book", "who's coaching", "who else is going" with a single HTTP POST — 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: you render a whole page to read a few lines back out of
|
||||
the DOM. Its data actions are plain JSON endpoints, so this talks to them directly.
|
||||
|
||||
## Read-only, by construction
|
||||
|
||||
This client cannot reserve, cancel, check in, log results, accept terms, or buy anything.
|
||||
|
||||
The credential is a full-session login — Wodify issues no read-only token — so enforcement is in
|
||||
the code, not the credential:
|
||||
|
||||
- **Allowlist** (`actions.ACTIONS`): unregistered actions cannot be called.
|
||||
- **Write guard** (`actions.assert_read_only`): any path containing `Create`, `Save`, `Reserve`,
|
||||
`Cancel`, `SignIn`, `Purchase`, … is refused, *including* allowlisted entries, so a careless
|
||||
registry edit still fails closed.
|
||||
|
||||
If you want to book a class, use the app.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pip install -e ".[prime,dev]"
|
||||
```
|
||||
|
||||
The **query path is stdlib-only**. The `prime` extra (`websockets`) is needed only for the
|
||||
occasional capture step.
|
||||
|
||||
## Use
|
||||
|
||||
```bash
|
||||
wodify list date 2026-07-25
|
||||
```
|
||||
|
||||
```
|
||||
TIME COACH BOOKED CLASS DUR ID
|
||||
----- ----------- ------ ----------------------- ----- ---------
|
||||
07:00 Robin Vance 10/10 CrossFit: 7:00 AM 60min 192001199
|
||||
10:00 Pat Doyle 12/12 CrossFit Burn: 10:00 AM 60min 190918189
|
||||
```
|
||||
|
||||
(Names above are illustrative — the tool prints whatever your gym returns.)
|
||||
|
||||
Then feed an ID back in for the workout and the named attendee list:
|
||||
|
||||
```bash
|
||||
wodify list workout 190918189
|
||||
```
|
||||
|
||||
Other commands:
|
||||
|
||||
```bash
|
||||
wodify doctor # config, session and DB status
|
||||
wodify prime # capture session state (needs a logged-in browser)
|
||||
wodify bookings --since 2026-07-18 --attended
|
||||
wodify schedule --date 2026-07-21
|
||||
```
|
||||
|
||||
`--json` gives raw payloads, `--refresh` bypasses the local cache, and
|
||||
`list workout --notes` adds the coach's brief.
|
||||
|
||||
A class ID carries neither its date nor its program — it is per-occurrence. `list date`
|
||||
indexes the day into SQLite; `list workout` resolves the ID from there. Ask for an ID on a day
|
||||
you never listed and it says so rather than guessing.
|
||||
|
||||
## Local SQLite cache
|
||||
|
||||
`~/.cache/wodify/wodify.db` (override with `WODIFY_DB`), created mode `600` because it holds
|
||||
other members' names. Responses are stamped with the local date they were fetched on and
|
||||
reused for the rest of that day; anything older is a miss. Past days never change, so this is
|
||||
safe. Today's schedule can shift — that is what `--refresh` is for.
|
||||
|
||||
Every command states whether the answer came from cache or the network.
|
||||
|
||||
## How priming works
|
||||
|
||||
`prime` attaches over CDP to a Chrome that is already logged in, and captures three things that
|
||||
cannot be obtained any other way:
|
||||
|
||||
| Thing | Why it needs a browser |
|
||||
|-------|------------------------|
|
||||
| `nr1W_Theme_UI` cookie | **HttpOnly** — `document.cookie` cannot read it, so it cannot be copied by hand |
|
||||
| `X-CSRFToken` | Not in cookies, `localStorage`, or any JS global; only appears on outbound requests |
|
||||
| `apiVersion` | **Per-action**, not global — each endpoint's value must be observed from a real call |
|
||||
|
||||
Results are cached at `~/.cache/wodify/session.json`, mode `600`. That file holds live
|
||||
credentials: never commit it, never log it.
|
||||
|
||||
### Priming against a remote profile
|
||||
|
||||
If the logged-in Chrome is on another host, tunnel first:
|
||||
|
||||
```bash
|
||||
ssh -L 9222:127.0.0.1:9222 your-host
|
||||
```
|
||||
|
||||
A minimal setup on that host: Chrome with `--headless=new --remote-debugging-port=9222
|
||||
--remote-debugging-address=127.0.0.1 --user-data-dir=<profile>`, logged in once. Keep the CDP
|
||||
port on loopback — it is unauthenticated, and anything that can reach it can read every cookie
|
||||
in that profile.
|
||||
|
||||
## Staleness is explicit
|
||||
|
||||
Every Wodify response reports `hasModuleVersionChanged` / `hasApiVersionChanged`. When Wodify
|
||||
redeploys, or the session dies, the client raises rather than returning a plausible-looking empty
|
||||
result:
|
||||
|
||||
| Exception | Exit | Meaning |
|
||||
|-----------|------|---------|
|
||||
| `NotPrimedError` | 4 | No cache, or this action was never observed |
|
||||
| `SessionExpiredError` | 2 | Session dead — a human must log in again, then re-prime |
|
||||
| `VersionStaleError` | 3 | Wodify redeployed — re-prime |
|
||||
|
||||
A silently wrong "no workout today" is worse than an error, so there is no fallback path that
|
||||
guesses.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Var | Default |
|
||||
|-----|---------|
|
||||
| `WODIFY_HOST` | `claycrossfit.wodify.com` |
|
||||
| `WODIFY_CDP_URL` | `http://127.0.0.1:9222` |
|
||||
| `WODIFY_CACHE` | `~/.cache/wodify/session.json` |
|
||||
| `WODIFY_LOCATION_ID` | `11644` |
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
python -m pytest -q
|
||||
```
|
||||
|
||||
No network required. The write-guard tests assert that real mutating endpoint names are refused.
|
||||
@@ -0,0 +1,25 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "wodify"
|
||||
version = "0.1.0"
|
||||
description = "Read-only client for the Wodify athlete app (no browser at query time)"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = []
|
||||
|
||||
[project.optional-dependencies]
|
||||
# CDP is a WebSocket protocol, so priming needs a client. The query path is
|
||||
# deliberately stdlib-only.
|
||||
prime = ["websockets>=12"]
|
||||
dev = ["pytest>=8"]
|
||||
|
||||
[project.scripts]
|
||||
wodify = "wodify.cli:main"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
@@ -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}
|
||||
@@ -0,0 +1,78 @@
|
||||
"""The read-only guard is the only thing preventing this client from spending
|
||||
the user's money or taking someone's class spot. Test it hard."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from wodify import actions
|
||||
|
||||
|
||||
def test_every_registered_action_is_read_only():
|
||||
for key, action in actions.ACTIONS.items():
|
||||
actions.assert_read_only(action.path) # must not raise
|
||||
assert action.key == key, "registry key must match Action.key"
|
||||
assert action.path, f"{key} has no path"
|
||||
assert not action.path.startswith("/"), f"{key} path should be relative"
|
||||
|
||||
|
||||
def test_get_returns_action():
|
||||
assert actions.get("bookings").key == "bookings"
|
||||
|
||||
|
||||
def test_unknown_action_rejected():
|
||||
with pytest.raises(actions.UnknownActionError):
|
||||
actions.get("definitely-not-a-real-action")
|
||||
|
||||
|
||||
# Real mutating endpoint names observed in Wodify's client, plus plausible
|
||||
# variants. None may ever pass the guard.
|
||||
@pytest.mark.parametrize("path", [
|
||||
"WodifyClient_Class/Classes/Class/ServiceAPICreateClassReservation",
|
||||
"WodifyClient_Class/Classes/Class/ActionCancelReservation",
|
||||
"WodifyClient_DataFetch_WB/WOD_Flow/SaveWorkoutResult",
|
||||
"WodifyClient/Common/ActionAcceptTermsAndConditions",
|
||||
"WodifyClient_Class/Classes/Class/ClientActionSignInToClass",
|
||||
"WodifyClient/MainScreens/ActionSubmitAppReview",
|
||||
"WodifyClient_Class/Classes/ActionLeaveWaitlist",
|
||||
"WodifyClient/Account/ActionLogout",
|
||||
"WodifyClient/POS/ActionPurchaseItem",
|
||||
"WodifyClient/WOD/ActionAddResult",
|
||||
])
|
||||
def test_write_endpoints_are_refused(path):
|
||||
with pytest.raises(actions.WriteAttemptError):
|
||||
actions.assert_read_only(path)
|
||||
|
||||
|
||||
def test_guard_is_case_insensitive():
|
||||
with pytest.raises(actions.WriteAttemptError):
|
||||
actions.assert_read_only("Module/Screen/ACTIONCREATERESERVATION")
|
||||
|
||||
|
||||
def test_guard_does_not_block_legitimate_read_paths():
|
||||
"""Guard markers must not false-positive on the reads we actually need.
|
||||
|
||||
'GetClassWaitList' in particular has to stay callable -- reading a waitlist
|
||||
is fine, joining or leaving it is not.
|
||||
"""
|
||||
safe = [
|
||||
"WodifyClient_DataFetch_WB/Schedule_OS/GetClassWaitList_WB/DataActionGetClassWaitList",
|
||||
"WodifyClient_DataFetch_WB/Schedule_OS/GetClassAttendees_WB/DataActionGetClassAttendees",
|
||||
"WodifyClient_DataFetch_WB/WOD_Flow/GetWorkoutData_HasWodLeaderboardComponents"
|
||||
"/DataActionGetWorkoutDataHasWodLeaderboardComponents",
|
||||
"WodifyClient_Class/Classes/Attendance/DataActionGetClasses",
|
||||
]
|
||||
for path in safe:
|
||||
actions.assert_read_only(path)
|
||||
|
||||
|
||||
def test_all_expected_actions_registered():
|
||||
expected = {"bookings", "wodflags", "attendees", "classdetail",
|
||||
"coach", "classes", "waitlist"}
|
||||
assert expected <= set(actions.keys())
|
||||
|
||||
|
||||
def test_get_returns_action_for_workout_probe():
|
||||
"""wodflags is deliberately not called 'workout': it returns a boolean, and
|
||||
naming it 'workout' invited reporting 'no workout' from a probe response."""
|
||||
action = actions.get("wodflags")
|
||||
assert "NOT the workout text" in action.summary
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Attendee parsing.
|
||||
|
||||
The name field is PersonName under Response.ClassDetailAttendee.List. An earlier
|
||||
version looked for "Name", found nothing on a full class, and printed an invented
|
||||
explanation about anonymous members -- a fabricated cause for its own bug. These
|
||||
tests exist so that cannot recur.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
|
||||
def _att(name, status="Reserved", signed_in=False, no_show=False,
|
||||
waitlisted=False, anonymous=False, rid=None):
|
||||
return {
|
||||
"PersonName": name,
|
||||
"StatusInClass": status,
|
||||
"HasReserved": True,
|
||||
"HasSignedIn": signed_in,
|
||||
"HasNoShow": no_show,
|
||||
"isWaitlisted": waitlisted,
|
||||
"IsAnonymous": anonymous,
|
||||
"MemberSince": "2025-10-17",
|
||||
"ClassReservationId": rid or f"res-{name}",
|
||||
# Traps: nested zeros that must not be mistaken for the real fields.
|
||||
"ClassId": "0",
|
||||
"ProgramId": "0",
|
||||
}
|
||||
|
||||
|
||||
CLASS = {"Response": {"ClassDetailAttendee": {"List": [
|
||||
_att("Alex Rivera"),
|
||||
_att("Sam Okafor", status="Signed In", signed_in=True),
|
||||
_att("Jordan Kim", no_show=True),
|
||||
_att("Wanda Waits", waitlisted=True),
|
||||
]}}}
|
||||
|
||||
|
||||
def test_person_name_field_is_read():
|
||||
"""Regression: reading "Name" yields nothing and looks like an empty class."""
|
||||
names = render.attendee_names(CLASS)
|
||||
assert "Alex Rivera" in names
|
||||
assert len(names) == 4
|
||||
|
||||
|
||||
def test_waitlisted_separated_from_roster():
|
||||
out = render.attendee_block(CLASS)
|
||||
assert "## Attendees — 3" in out, "waitlisted people are not attendees"
|
||||
assert "Waitlist — 1" in out
|
||||
assert "Wanda Waits" in out
|
||||
|
||||
|
||||
def test_signed_in_marked():
|
||||
assert "Sam Okafor [signed in]" in render.attendee_block(CLASS)
|
||||
|
||||
|
||||
def test_no_show_marked():
|
||||
out = render.attendee_block(CLASS)
|
||||
assert "Jordan Kim" in out and "no-show" in out
|
||||
|
||||
|
||||
def test_capacity_shown_when_supplied():
|
||||
out = render.attendee_block(CLASS, booked=12, limit=12)
|
||||
assert "of 12/12 booked" in out
|
||||
|
||||
|
||||
def test_gap_between_booked_and_listed_is_flagged():
|
||||
"""A class the account attended lists one fewer than booked; say so rather
|
||||
than let it read as a miscount."""
|
||||
out = render.attendee_block(CLASS, booked=4, limit=10) # 3 on roster + 1 waitlisted
|
||||
assert "1 booked not listed" in out
|
||||
|
||||
|
||||
def test_no_gap_note_when_counts_agree():
|
||||
out = render.attendee_block(CLASS, booked=3, limit=10)
|
||||
assert "not listed" not in out
|
||||
|
||||
|
||||
def test_duplicate_reservations_deduplicated():
|
||||
dupe = {"Response": {"ClassDetailAttendee": {"List": [
|
||||
_att("Alex Rivera", rid="r1"), _att("Alex Rivera", rid="r1"),
|
||||
]}}}
|
||||
assert render.attendee_names(dupe) == ["Alex Rivera"]
|
||||
|
||||
|
||||
def test_empty_list_does_not_invent_a_reason():
|
||||
"""Say what is true -- nothing was returned -- and do not speculate why."""
|
||||
out = render.attendee_block({"Response": {"ClassDetailAttendee": {"List": []}}})
|
||||
assert "None returned" in out
|
||||
assert "anonymous" not in out.lower()
|
||||
|
||||
|
||||
def test_falls_back_to_first_last_name():
|
||||
data = {"Response": {"ClassDetailAttendee": {"List": [
|
||||
{"Firstname": "Pat", "LastName": "Doyle", "ClassReservationId": "r9"},
|
||||
]}}}
|
||||
assert render.attendee_names(data) == ["Pat Doyle"]
|
||||
|
||||
|
||||
# --- duration ---------------------------------------------------------------
|
||||
|
||||
def test_duration_basic():
|
||||
assert render.duration_minutes("17:30:00", "18:30:00") == 60
|
||||
|
||||
|
||||
def test_duration_across_midnight():
|
||||
assert render.duration_minutes("23:30:00", "00:30:00") == 60
|
||||
|
||||
|
||||
def test_duration_unparseable_is_none():
|
||||
assert render.duration_minutes("", "") is None
|
||||
assert render.duration_minutes("bogus", "18:30:00") is None
|
||||
|
||||
|
||||
def test_hhmm_trims_seconds():
|
||||
assert render._hhmm("17:30:00") == "17:30"
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Cache handling and error mapping. No network."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from wodify import actions, client
|
||||
|
||||
|
||||
def _cache(**over):
|
||||
base = {
|
||||
"host": "example.wodify.com",
|
||||
"primed_at": "2026-07-25T00:00:00+00:00",
|
||||
"cookie": "nr1W_Theme_UI=a; nr2W_Theme_UI=b",
|
||||
"csrf": "c" * 28,
|
||||
"module_version": "mv",
|
||||
"actions": {
|
||||
actions.ACTIONS["bookings"].path: {
|
||||
"api_version": "av",
|
||||
"view_name": "MainScreens.Home",
|
||||
"body_template": {
|
||||
"viewName": "MainScreens.Home",
|
||||
"screenData": {"variables": {
|
||||
"ClientVariables": {"SelectedDate": "1900-01-01",
|
||||
"GymProgramId": "0"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
base.update(over)
|
||||
return base
|
||||
|
||||
|
||||
def test_cache_round_trip(tmp_path):
|
||||
path = tmp_path / "session.json"
|
||||
client.save_cache(_cache(), path)
|
||||
loaded = client.load_cache(path)
|
||||
assert loaded["csrf"] == "c" * 28
|
||||
assert loaded["cache_version"] == client.CACHE_VERSION
|
||||
|
||||
|
||||
def test_missing_cache_raises_not_primed(tmp_path):
|
||||
with pytest.raises(client.NotPrimedError, match="no session cache"):
|
||||
client.load_cache(tmp_path / "absent.json")
|
||||
|
||||
|
||||
def test_corrupt_cache_raises_not_primed(tmp_path):
|
||||
path = tmp_path / "session.json"
|
||||
path.write_text("{not json", encoding="utf-8")
|
||||
with pytest.raises(client.NotPrimedError, match="unreadable"):
|
||||
client.load_cache(path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["cookie", "csrf", "module_version", "actions"])
|
||||
def test_incomplete_cache_rejected(tmp_path, field):
|
||||
path = tmp_path / "session.json"
|
||||
data = _cache()
|
||||
data[field] = "" if field != "actions" else {}
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
with pytest.raises(client.NotPrimedError, match=field):
|
||||
client.load_cache(path)
|
||||
|
||||
|
||||
def test_set_field_writes_every_existing_occurrence():
|
||||
node = {"a": {"SelectedDate": "x"}, "b": [{"SelectedDate": "y"}, {"other": 1}]}
|
||||
assert client.set_field(node, "SelectedDate", "2026-07-24") == 2
|
||||
assert node["a"]["SelectedDate"] == "2026-07-24"
|
||||
assert node["b"][0]["SelectedDate"] == "2026-07-24"
|
||||
|
||||
|
||||
def test_set_field_does_not_invent_keys():
|
||||
"""OutSystems rejects unknown body keys, so absent fields must stay absent."""
|
||||
node = {"a": {"Existing": 1}}
|
||||
assert client.set_field(node, "ClassId", 42) == 0
|
||||
assert "ClassId" not in node["a"]
|
||||
|
||||
|
||||
def test_overrides_are_applied_to_body(monkeypatch):
|
||||
sent = {}
|
||||
|
||||
def capture(url, body, headers, timeout):
|
||||
sent["body"] = json.loads(body)
|
||||
return 200, json.dumps({"versionInfo": {}, "data": {"ok": True}})
|
||||
|
||||
monkeypatch.setattr(client, "_post", capture)
|
||||
client.call("bookings", {"SelectedDate": "2026-07-24"}, cache=_cache())
|
||||
variables = sent["body"]["screenData"]["variables"]["ClientVariables"]
|
||||
assert variables["SelectedDate"] == "2026-07-24"
|
||||
|
||||
|
||||
def test_none_overrides_are_skipped(monkeypatch):
|
||||
sent = {}
|
||||
|
||||
def capture(url, body, headers, timeout):
|
||||
sent["body"] = json.loads(body)
|
||||
return 200, json.dumps({"versionInfo": {}, "data": {}})
|
||||
|
||||
monkeypatch.setattr(client, "_post", capture)
|
||||
client.call("bookings", {"SelectedDate": None}, cache=_cache())
|
||||
variables = sent["body"]["screenData"]["variables"]["ClientVariables"]
|
||||
assert variables["SelectedDate"] == "1900-01-01", "None must not overwrite"
|
||||
|
||||
|
||||
def test_version_info_is_always_rewritten(monkeypatch):
|
||||
sent = {}
|
||||
|
||||
def capture(url, body, headers, timeout):
|
||||
sent["body"] = json.loads(body)
|
||||
return 200, json.dumps({"versionInfo": {}, "data": {}})
|
||||
|
||||
monkeypatch.setattr(client, "_post", capture)
|
||||
client.call("bookings", {}, cache=_cache())
|
||||
assert sent["body"]["versionInfo"] == {"moduleVersion": "mv", "apiVersion": "av"}
|
||||
|
||||
|
||||
def test_template_is_not_mutated_between_calls(monkeypatch):
|
||||
monkeypatch.setattr(client, "_post",
|
||||
lambda *a, **k: (200, json.dumps({"versionInfo": {}, "data": {}})))
|
||||
cache = _cache()
|
||||
client.call("bookings", {"SelectedDate": "2026-07-24"}, cache=cache)
|
||||
template = cache["actions"][actions.ACTIONS["bookings"].path]["body_template"]
|
||||
assert template["screenData"]["variables"]["ClientVariables"]["SelectedDate"] == "1900-01-01"
|
||||
|
||||
|
||||
def test_missing_body_template_raises(tmp_path):
|
||||
stale = _cache()
|
||||
entry = stale["actions"][actions.ACTIONS["bookings"].path]
|
||||
del entry["body_template"]
|
||||
with pytest.raises(client.NotPrimedError, match="body_template"):
|
||||
client.call("bookings", {}, cache=stale)
|
||||
|
||||
|
||||
def test_action_without_api_version_raises(tmp_path):
|
||||
"""apiVersion is per-action; an unprimed action must fail loudly."""
|
||||
with pytest.raises(client.NotPrimedError, match="per-action"):
|
||||
client.call("attendees", {}, cache=_cache())
|
||||
|
||||
|
||||
def test_call_refuses_unknown_action():
|
||||
with pytest.raises(actions.UnknownActionError):
|
||||
client.call("nope", {}, cache=_cache())
|
||||
|
||||
|
||||
def _stub_post(monkeypatch, status, text):
|
||||
monkeypatch.setattr(client, "_post", lambda *a, **k: (status, text))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [401, 403])
|
||||
def test_auth_failure_maps_to_session_expired(monkeypatch, status):
|
||||
_stub_post(monkeypatch, status, "denied")
|
||||
with pytest.raises(client.SessionExpiredError):
|
||||
client.call("bookings", {}, cache=_cache())
|
||||
|
||||
|
||||
def test_html_login_page_maps_to_session_expired(monkeypatch):
|
||||
_stub_post(monkeypatch, 200, "<html><body>Sign into Wodify</body></html>")
|
||||
with pytest.raises(client.SessionExpiredError, match="login page"):
|
||||
client.call("bookings", {}, cache=_cache())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("flag", ["hasModuleVersionChanged", "hasApiVersionChanged"])
|
||||
def test_version_change_maps_to_version_stale(monkeypatch, flag):
|
||||
_stub_post(monkeypatch, 200, json.dumps({"versionInfo": {flag: True}, "data": {"x": 1}}))
|
||||
with pytest.raises(client.VersionStaleError):
|
||||
client.call("bookings", {}, cache=_cache())
|
||||
|
||||
|
||||
def test_successful_call_returns_data(monkeypatch):
|
||||
payload = {"versionInfo": {"hasModuleVersionChanged": False,
|
||||
"hasApiVersionChanged": False},
|
||||
"data": {"Response": {"List": [{"Id": 1}]}}}
|
||||
_stub_post(monkeypatch, 200, json.dumps(payload))
|
||||
assert client.call("bookings", {}, cache=_cache()) == payload["data"]
|
||||
|
||||
|
||||
def test_server_error_surfaces(monkeypatch):
|
||||
_stub_post(monkeypatch, 500, "boom")
|
||||
with pytest.raises(RuntimeError, match="HTTP 500"):
|
||||
client.call("bookings", {}, cache=_cache())
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Component field coverage.
|
||||
|
||||
Reading only Name/Comment silently dropped the actual movements -- the metcon
|
||||
lives in Description and the strength scheme in MeasureRepScheme. These tests
|
||||
exist so that regression cannot recur quietly.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
STRENGTH = {
|
||||
"Id": "123372266",
|
||||
"IsWeightlifting": True,
|
||||
"Name": "Shoulder Press",
|
||||
"Comment": "<p>--</p><p>Strict overhead pressing progression.</p>",
|
||||
"MeasureRepScheme": "Strict Press\nEvery 2:30 x 4 Sets\nSet 1: 10 Reps",
|
||||
"WODComponentVariableRepScheme": "(1 x 10) (1 x 8) (1 x 6) (1 x 4)",
|
||||
"WODComponentOrder": 2,
|
||||
}
|
||||
|
||||
METCON = {
|
||||
"Id": "123372267",
|
||||
"IsMetcon": True,
|
||||
"Name": '"Hat Trick"',
|
||||
"Comment": "<p>Goals: ~2:00 per set</p><p>RPE: 9/10</p>",
|
||||
"Description": "<p>For Time</p><p>Every 5:00 x 3 Sets</p><p>21 Wall Balls</p>",
|
||||
"Rounds": 3,
|
||||
"EachRoundTypeLabel": "For Time ↓ Shorter is Better",
|
||||
"WODComponentOrder": 3,
|
||||
}
|
||||
|
||||
SECTION = {"Id": "1", "IsSection": True, "Name": "WARM-UP",
|
||||
"Comment": "<p>2:00 Cardio Choice</p>", "WODComponentOrder": 1}
|
||||
|
||||
|
||||
def _wod(components):
|
||||
return {"Response": {"ResponseWOD": {"ResponseWorkout": {
|
||||
"Id": "25201299", "Name": "CrossFit - Mon, Jul 20", "Notes": "",
|
||||
"WorkoutComponents": {"List": components},
|
||||
}}}}
|
||||
|
||||
|
||||
def test_metcon_description_is_rendered():
|
||||
"""Description carries the movements. Without it the output looks complete
|
||||
but contains no workout."""
|
||||
out = render.workout(_wod([METCON]))
|
||||
assert "21 Wall Balls" in out
|
||||
assert "Every 5:00 x 3 Sets" in out
|
||||
|
||||
|
||||
def test_strength_rep_scheme_is_rendered():
|
||||
out = render.workout(_wod([STRENGTH]))
|
||||
assert "Every 2:30 x 4 Sets" in out
|
||||
assert "Set 1: 10 Reps" in out
|
||||
|
||||
|
||||
def test_variable_rep_scheme_included_when_distinct():
|
||||
assert "(1 x 10) (1 x 8)" in render.workout(_wod([STRENGTH]))
|
||||
|
||||
|
||||
def test_variable_rep_scheme_not_duplicated():
|
||||
comp = dict(STRENGTH, WODComponentVariableRepScheme="Every 2:30 x 4 Sets")
|
||||
out = render.workout(_wod([comp]))
|
||||
assert out.count("Every 2:30 x 4 Sets") == 1
|
||||
|
||||
|
||||
def test_rounds_and_scoring_are_surfaced():
|
||||
out = render.workout(_wod([METCON]))
|
||||
assert "3 rounds" in out
|
||||
assert "Shorter is Better" in out
|
||||
|
||||
|
||||
def test_dash_only_comment_is_dropped():
|
||||
"""Authors use '--' as a spacer; it should not appear as content."""
|
||||
comp = {"Id": "9", "Name": "Press", "Comment": "<p>--</p>", "WODComponentOrder": 1}
|
||||
out = render.workout(_wod([comp]))
|
||||
assert "--" not in out
|
||||
|
||||
|
||||
def test_real_comment_is_kept():
|
||||
assert "RPE: 9/10" in render.workout(_wod([METCON]))
|
||||
|
||||
|
||||
def test_dash_spacer_stripped_but_surrounding_comment_kept():
|
||||
"""Live data has '--' as a leading spacer before real prose."""
|
||||
out = render.workout(_wod([STRENGTH]))
|
||||
assert "Strict overhead pressing progression." in out
|
||||
assert "--" not in out
|
||||
|
||||
|
||||
def test_components_sorted_by_wod_component_order():
|
||||
out = render.workout(_wod([METCON, SECTION, STRENGTH]))
|
||||
assert out.index("WARM-UP") < out.index("Shoulder Press") < out.index("Hat Trick")
|
||||
|
||||
|
||||
def test_section_and_component_heading_levels_differ():
|
||||
out = render.workout(_wod([SECTION, METCON]))
|
||||
assert "## WARM-UP" in out
|
||||
assert '### "Hat Trick"' in out
|
||||
|
||||
|
||||
def test_missing_order_does_not_crash():
|
||||
comp = {k: v for k, v in METCON.items() if k != "WODComponentOrder"}
|
||||
assert "21 Wall Balls" in render.workout(_wod([comp]))
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Rendering exists to keep output small. Verify shaping, not exact prose."""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
|
||||
def test_flatten_html_turns_breaks_into_lines():
|
||||
raw = "<p>For Time</p><p>30 Power Cleans<br>30 Toes-to-Bars</p>"
|
||||
out = render.flatten_html(raw)
|
||||
assert "For Time" in out
|
||||
assert "30 Power Cleans" in out
|
||||
assert "<" not in out
|
||||
|
||||
|
||||
def test_flatten_html_unescapes_entities():
|
||||
assert render.flatten_html("<p>135/95lb & 24"</p>") == '135/95lb & 24"'
|
||||
|
||||
|
||||
def test_flatten_html_handles_none_and_empty():
|
||||
assert render.flatten_html(None) == ""
|
||||
assert render.flatten_html("") == ""
|
||||
|
||||
|
||||
def test_flatten_html_collapses_runs_of_blank_lines():
|
||||
assert "\n\n\n" not in render.flatten_html("a<br><br><br><br>b")
|
||||
|
||||
|
||||
def test_find_all_reaches_nested_values():
|
||||
data = {"a": {"b": [{"Description": "x"}, {"c": {"Description": "y"}}]}}
|
||||
assert render.find_all(data, "Description") == ["x", "y"]
|
||||
|
||||
|
||||
def test_first_list_skips_empty_lists():
|
||||
data = {"p": {"List": []}, "q": {"List": [{"Id": 1}]}}
|
||||
assert render.first_list(data) == [{"Id": 1}]
|
||||
|
||||
|
||||
def test_bookings_reports_absence_rather_than_empty_string():
|
||||
assert "No bookings" in render.bookings({"Response": {"List": []}})
|
||||
|
||||
|
||||
def test_bookings_formats_rows():
|
||||
data = {"Response": {"List": [
|
||||
{"Class": {"StartDate": "2026-07-27", "StartTime": "5:30 PM",
|
||||
"ClassName": "CrossFit: 5:30 PM"},
|
||||
"StatusLabel": "Reserved"},
|
||||
]}}
|
||||
out = render.bookings(data)
|
||||
assert "2026-07-27" in out and "CrossFit: 5:30 PM" in out and "[Reserved]" in out
|
||||
|
||||
|
||||
def test_attendees_counts_and_lists():
|
||||
data = {"Response": {"List": [{"Name": "A B"}, {"Name": "C D"}]}}
|
||||
out = render.attendees(data)
|
||||
assert out.startswith("2 attendees:") and "A B" in out and "C D" in out
|
||||
|
||||
|
||||
def test_attendees_reports_absence():
|
||||
assert "No attendees" in render.attendees({"Response": {"List": []}})
|
||||
|
||||
|
||||
def test_workout_reports_absence():
|
||||
assert "No workout content" in render.workout({"Response": {}})
|
||||
|
||||
|
||||
def test_render_falls_back_to_json_for_unmapped_actions():
|
||||
out = render.render("classdetail", {"Response": {"Id": 1}})
|
||||
assert '"Id": 1' in out
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Placeholder filtering is the subtle part: OutSystems returns a single zeroed
|
||||
record for an empty result set, which reads exactly like real data."""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
|
||||
def _wod_response(components):
|
||||
return {"Classes": {"ProgramWODList": {"List": [
|
||||
{"Id": "9001", "Name": "CGE8 2009 Remix", "Notes": "",
|
||||
"WorkoutComponents": {"List": components}},
|
||||
]}}}
|
||||
|
||||
|
||||
EMPTY_PLACEHOLDER = {"Classes": {"ProgramWODList": {"List": [
|
||||
{"Id": "0", "Date": "1900-01-01", "Name": "", "Comments": "",
|
||||
"WorkoutComponents": {"List": []}},
|
||||
]}}}
|
||||
|
||||
|
||||
def test_placeholder_record_is_not_reported_as_content():
|
||||
out = render.workout(EMPTY_PLACEHOLDER)
|
||||
assert out.startswith("No workout content")
|
||||
|
||||
|
||||
def test_real_records_filters_zero_ids():
|
||||
rows = [{"Id": "0"}, {"Id": "12"}, {"Id": 0}, {"nope": 1}]
|
||||
assert render._real_records(rows) == [{"Id": "12"}]
|
||||
|
||||
|
||||
def test_workout_renders_title_and_components():
|
||||
data = _wod_response([
|
||||
{"Id": "1", "Name": "<p>Warm-Up</p>", "Comment": "<p>2:00 Cardio</p>"},
|
||||
{"Id": "2", "Name": "For Time", "Comment": "30 Power Cleans<br>30 Box Jumps"},
|
||||
])
|
||||
out = render.workout(data)
|
||||
assert "# CGE8 2009 Remix" in out
|
||||
assert "Warm-Up" in out and "2:00 Cardio" in out
|
||||
assert "30 Power Cleans" in out and "30 Box Jumps" in out
|
||||
assert "<" not in out
|
||||
|
||||
|
||||
def test_workout_skips_placeholder_components():
|
||||
data = _wod_response([{"Id": "0", "Name": "", "Comment": ""}])
|
||||
assert render.workout(data).startswith("# CGE8 2009 Remix")
|
||||
|
||||
|
||||
def test_workout_deduplicates_identical_blocks():
|
||||
data = _wod_response([
|
||||
{"Id": "1", "Name": "For Time", "Comment": "30 Burpees"},
|
||||
{"Id": "2", "Name": "For Time", "Comment": "30 Burpees"},
|
||||
])
|
||||
assert render.workout(data).count("30 Burpees") == 1
|
||||
|
||||
|
||||
def test_classes_reports_absence_for_placeholder_only():
|
||||
assert "No classes found" in render.classes(EMPTY_PLACEHOLDER)
|
||||
|
||||
|
||||
def test_classes_lists_rows_with_capacity():
|
||||
data = {"Schedules": {"ScheduleList": {"List": [
|
||||
{"Id": "5", "ClassName": "CrossFit: 6:00 AM", "StartTime": "6:00am",
|
||||
"ReservationCount": 5, "ClassLimit": 10},
|
||||
]}}}
|
||||
out = render.classes(data)
|
||||
assert "CrossFit: 6:00 AM" in out and "5 | 10" in out
|
||||
|
||||
|
||||
def test_classes_appends_wod_when_present():
|
||||
data = _wod_response([{"Id": "1", "Name": "For Time", "Comment": "30 Burpees"}])
|
||||
data["Schedules"] = {"ScheduleList": {"List": [
|
||||
{"Id": "5", "ClassName": "CrossFit: 6:00 AM", "StartTime": "6:00am"},
|
||||
]}}
|
||||
out = render.classes(data)
|
||||
assert "CrossFit: 6:00 AM" in out and "30 Burpees" in out
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Schedule parsing.
|
||||
|
||||
Shape from a live capture 2026-07-25: Response.ResponseClassList.Class.List.
|
||||
Two bugs are pinned here because both produced plausible-looking wrong output
|
||||
rather than an error.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
# Abridged real row. GroupMemberReservationStatus.ClassId == "0" is the trap:
|
||||
# flattening nested dicts up clobbers the real Id and collapses every class
|
||||
# into a single row.
|
||||
def _row(cid, name, start, program, booked, coach):
|
||||
return {
|
||||
"Id": cid,
|
||||
"Name": name,
|
||||
"StartTime": start,
|
||||
"EndTime": "13:00:00",
|
||||
"StartDate": "2026-07-20",
|
||||
"ProgramId": program,
|
||||
"ClassLimit": 10,
|
||||
"ReservationCount": booked,
|
||||
"WaitlistCount": 0,
|
||||
"Status": "",
|
||||
"Coaches": {"List": [{"Name": coach, "Id": "5706147"}]},
|
||||
"GroupMemberReservationStatus": {"ClassId": "0", "IsSignedIn": {"List": []}},
|
||||
}
|
||||
|
||||
|
||||
DAY = {"Response": {"ResponseClassList": {"Class": {"List": [
|
||||
_row("190917816", "CrossFit: 5:30 PM", "17:30:00", "133059", 9, "Pat Doyle"),
|
||||
_row("190917671", "CrossFit: 12:00 PM", "12:00:00", "133059", 10, "Chris Nolan"),
|
||||
_row("190918133", "CrossFit Pump: 6:30 PM", "18:30:00", "131311", 7, "Pat Doyle"),
|
||||
]}}}}
|
||||
|
||||
|
||||
def test_all_classes_are_returned_not_collapsed():
|
||||
"""Regression: nested ClassId "0" previously collapsed all rows into one."""
|
||||
rows = render.class_rows(DAY)
|
||||
assert len(rows) == 3
|
||||
assert [r["class_id"] for r in rows] == ["190917671", "190917816", "190918133"]
|
||||
|
||||
|
||||
def test_rows_sorted_by_start_time():
|
||||
assert [r["start"] for r in render.class_rows(DAY)] == \
|
||||
["12:00:00", "17:30:00", "18:30:00"]
|
||||
|
||||
|
||||
def test_real_id_survives_nested_class_id_zero():
|
||||
row = render.class_rows(DAY)[1]
|
||||
assert row["class_id"] == "190917816"
|
||||
assert row["class_id"] != "0"
|
||||
|
||||
|
||||
def test_coach_extracted_from_nested_list():
|
||||
by_id = {r["class_id"]: r for r in render.class_rows(DAY)}
|
||||
assert by_id["190917671"]["coach"] == "Chris Nolan"
|
||||
assert by_id["190918133"]["coach"] == "Pat Doyle"
|
||||
|
||||
|
||||
def test_program_ids_distinguish_workouts():
|
||||
"""Classes in different programs have different WODs, so program_id must
|
||||
survive -- reporting one program's workout for another is a wrong answer."""
|
||||
programs = {r["program_id"] for r in render.class_rows(DAY)}
|
||||
assert programs == {"133059", "131311"}
|
||||
|
||||
|
||||
def test_missing_coach_list_does_not_crash():
|
||||
row = _row("1", "X", "06:00:00", "133059", 1, "Y")
|
||||
row["Coaches"] = {"List": []}
|
||||
assert render.class_rows({"Class": {"List": [row]}})[0]["coach"] == ""
|
||||
|
||||
|
||||
def test_placeholder_rows_dropped():
|
||||
day = {"Class": {"List": [_row("0", "", "00:00:00", "0", 0, "")]}}
|
||||
assert render.class_rows(day) == []
|
||||
|
||||
|
||||
def test_classes_render_includes_capacity_coach_and_id():
|
||||
out = render.classes(DAY)
|
||||
assert "CrossFit: 5:30 PM" in out
|
||||
assert "9 | 10" in out
|
||||
assert "coach=Pat Doyle" in out
|
||||
assert "class_id=190917816" in out
|
||||
assert out.count("\n- ") + 1 == 3, "all three classes should be listed"
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Cache-through behaviour: the second read of the day must not hit the network."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from wodify import service, store
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def conn(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("WODIFY_DB", str(tmp_path / "t.db"))
|
||||
c = store.connect()
|
||||
yield c
|
||||
c.close()
|
||||
|
||||
|
||||
SCHEDULE = {"Response": {"ResponseClassList": {"Class": {"List": [
|
||||
{"Id": "190917816", "Name": "CrossFit: 5:30 PM", "StartTime": "17:30:00",
|
||||
"EndTime": "18:30:00", "StartDate": "2026-07-20", "ProgramId": "133059",
|
||||
"ClassLimit": 10, "ReservationCount": 9, "WaitlistCount": 0,
|
||||
"Coaches": {"List": [{"Name": "Pat Doyle"}]}},
|
||||
]}}}}
|
||||
|
||||
|
||||
def test_first_call_hits_network_second_uses_cache(conn, monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_call(key, overrides=None, **kw):
|
||||
calls.append(key)
|
||||
return SCHEDULE
|
||||
|
||||
monkeypatch.setattr(service.client, "call", fake_call)
|
||||
|
||||
rows, first = service.day_classes(conn, "2026-07-20")
|
||||
assert first.source == "network" and len(rows) == 1
|
||||
assert calls == ["schedule"]
|
||||
|
||||
rows2, second = service.day_classes(conn, "2026-07-20")
|
||||
assert second.source == "cache" and second.cached
|
||||
assert calls == ["schedule"], "second read must not touch the network"
|
||||
assert rows2 == rows
|
||||
|
||||
|
||||
def test_refresh_forces_a_network_read(conn, monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(service.client, "call",
|
||||
lambda k, o=None, **kw: calls.append(k) or SCHEDULE)
|
||||
|
||||
service.day_classes(conn, "2026-07-20")
|
||||
service.day_classes(conn, "2026-07-20", refresh=True)
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_day_classes_indexes_ids_for_later_lookup(conn, monkeypatch):
|
||||
monkeypatch.setattr(service.client, "call", lambda k, o=None, **kw: SCHEDULE)
|
||||
service.day_classes(conn, "2026-07-20")
|
||||
klass = service.resolve_class(conn, "190917816")
|
||||
assert klass["date"] == "2026-07-20"
|
||||
assert klass["program_id"] == "133059"
|
||||
|
||||
|
||||
def test_cache_key_separates_dates(conn, monkeypatch):
|
||||
seen = []
|
||||
monkeypatch.setattr(service.client, "call",
|
||||
lambda k, o=None, **kw: seen.append(dict(o or {})) or SCHEDULE)
|
||||
service.day_classes(conn, "2026-07-20")
|
||||
service.day_classes(conn, "2026-07-21")
|
||||
assert [s["FromDate"] for s in seen] == ["2026-07-20", "2026-07-21"]
|
||||
|
||||
|
||||
def test_workout_cache_key_separates_programs(conn, monkeypatch):
|
||||
seen = []
|
||||
monkeypatch.setattr(service.client, "call",
|
||||
lambda k, o=None, **kw: seen.append(dict(o or {})) or {"x": 1})
|
||||
service.workout(conn, "2026-07-20", "133059")
|
||||
service.workout(conn, "2026-07-20", "131311")
|
||||
service.workout(conn, "2026-07-20", "133059") # cached
|
||||
assert [s.get("GymProgramId") for s in seen] == ["133059", "131311"]
|
||||
|
||||
|
||||
def test_attendees_raises_maxrecords_for_large_classes(conn, monkeypatch):
|
||||
seen = {}
|
||||
monkeypatch.setattr(service.client, "call",
|
||||
lambda k, o=None, **kw: seen.update(o or {}) or {"x": 1})
|
||||
service.attendees(conn, "190918189", 30)
|
||||
assert seen["MaxRecords"] == 30, "must not silently truncate a large class"
|
||||
|
||||
|
||||
def test_attendees_cached_per_class(conn, monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(service.client, "call",
|
||||
lambda k, o=None, **kw: calls.append(o) or {"x": 1})
|
||||
service.attendees(conn, "1", 10)
|
||||
service.attendees(conn, "1", 10)
|
||||
service.attendees(conn, "2", 10)
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_resolve_unknown_class_returns_none(conn):
|
||||
assert service.resolve_class(conn, "999") is None
|
||||
@@ -0,0 +1,100 @@
|
||||
"""SQLite cache behaviour. No network."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as _dt
|
||||
|
||||
import pytest
|
||||
|
||||
from wodify import store
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def conn(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("WODIFY_DB", str(tmp_path / "t.db"))
|
||||
c = store.connect()
|
||||
yield c
|
||||
c.close()
|
||||
|
||||
|
||||
def test_payload_round_trip(conn):
|
||||
store.put_payload(conn, "k", {"a": 1})
|
||||
hit = store.get_payload(conn, "k")
|
||||
assert hit is not None
|
||||
data, fetched_at = hit
|
||||
assert data == {"a": 1} and fetched_at
|
||||
|
||||
|
||||
def test_payload_miss_returns_none(conn):
|
||||
assert store.get_payload(conn, "absent") is None
|
||||
|
||||
|
||||
def test_payload_from_a_different_day_is_a_miss(conn):
|
||||
"""Freshness is per calendar day: yesterday's copy must not be served."""
|
||||
store.put_payload(conn, "k", {"a": 1})
|
||||
yesterday = (_dt.date.today() - _dt.timedelta(days=1)).isoformat()
|
||||
conn.execute("UPDATE payloads SET fetched_on = ?", (yesterday,))
|
||||
conn.commit()
|
||||
assert store.get_payload(conn, "k") is None
|
||||
|
||||
|
||||
def test_payload_overwrite_updates_in_place(conn):
|
||||
store.put_payload(conn, "k", {"v": 1})
|
||||
store.put_payload(conn, "k", {"v": 2})
|
||||
assert store.get_payload(conn, "k")[0] == {"v": 2}
|
||||
assert conn.execute("SELECT COUNT(*) FROM payloads").fetchone()[0] == 1
|
||||
|
||||
|
||||
ROWS = [
|
||||
{"class_id": "190917816", "name": "CrossFit: 5:30 PM", "start": "17:30:00",
|
||||
"end": "18:30:00", "program_id": "133059", "coach": "Pat Doyle",
|
||||
"booked": 9, "limit": 10, "waitlist": 0},
|
||||
{"class_id": "190918133", "name": "CrossFit Pump: 6:30 PM", "start": "18:30:00",
|
||||
"end": "19:30:00", "program_id": "131311", "coach": "Pat Doyle",
|
||||
"booked": 7, "limit": 10, "waitlist": 0},
|
||||
]
|
||||
|
||||
|
||||
def test_upsert_and_read_back_by_date(conn):
|
||||
assert store.upsert_classes(conn, "2026-07-20", ROWS) == 2
|
||||
rows = store.classes_for_date(conn, "2026-07-20")
|
||||
assert [r["class_id"] for r in rows] == ["190917816", "190918133"]
|
||||
assert rows[0]["class_limit"] == 10
|
||||
|
||||
|
||||
def test_get_class_resolves_date_and_program(conn):
|
||||
"""This is what lets `list workout <id>` work: the id alone carries neither."""
|
||||
store.upsert_classes(conn, "2026-07-20", ROWS)
|
||||
klass = store.get_class(conn, "190918133")
|
||||
assert klass["date"] == "2026-07-20"
|
||||
assert klass["program_id"] == "131311"
|
||||
|
||||
|
||||
def test_get_unknown_class_returns_none(conn):
|
||||
assert store.get_class(conn, "does-not-exist") is None
|
||||
|
||||
|
||||
def test_rows_without_class_id_are_skipped(conn):
|
||||
assert store.upsert_classes(conn, "2026-07-20", [{"name": "no id"}]) == 0
|
||||
|
||||
|
||||
def test_upsert_is_idempotent(conn):
|
||||
store.upsert_classes(conn, "2026-07-20", ROWS)
|
||||
store.upsert_classes(conn, "2026-07-20", ROWS)
|
||||
assert conn.execute("SELECT COUNT(*) FROM classes").fetchone()[0] == 2
|
||||
|
||||
|
||||
def test_classes_for_date_can_ignore_freshness(conn):
|
||||
"""Past days do not change, so a stale index is still useful for id lookup."""
|
||||
store.upsert_classes(conn, "2026-07-20", ROWS)
|
||||
conn.execute("UPDATE classes SET fetched_on = '2020-01-01'")
|
||||
conn.commit()
|
||||
assert store.classes_for_date(conn, "2026-07-20") == []
|
||||
assert len(store.classes_for_date(conn, "2026-07-20", fresh_only=False)) == 2
|
||||
|
||||
|
||||
def test_stats_reports_counts(conn):
|
||||
store.upsert_classes(conn, "2026-07-20", ROWS)
|
||||
store.put_payload(conn, "k", {})
|
||||
st = store.stats(conn)
|
||||
assert st["classes"] == 2 and st["days"] == 1
|
||||
assert st["payloads"] == 1 and st["payloads_fresh_today"] == 1
|
||||
@@ -0,0 +1,114 @@
|
||||
"""GetAllWorkoutData's real response shape, plus bookings range filtering.
|
||||
|
||||
Shape taken from a live capture on 2026-07-25: the workout lives at
|
||||
Response.ResponseWOD.ResponseWorkout, not in ProgramWODList.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
LIVE_SHAPE = {
|
||||
"Response": {
|
||||
"HasActiveMembership": True,
|
||||
"ErrorMessage": "",
|
||||
"ResponseWOD": {
|
||||
"WorkoutError": {"HasError": False, "ErrorMessage": ""},
|
||||
"ResponseWorkout": {
|
||||
"Id": "25201299",
|
||||
"Date": "2026-07-25",
|
||||
"Name": "CrossFit - Sat, Jul 25",
|
||||
"Notes": "<h2>Saturday July 25</h2><p>Daily Coach's Brief</p>",
|
||||
"WorkoutComponents": {"List": [
|
||||
{"Id": "123372298", "IsSection": True, "Name": "WARM-UP",
|
||||
"Comment": "<p>General Warm-Up</p><p>2 x</p><p>15 Banded Good Mornings</p>"},
|
||||
{"Id": "123372299", "IsSection": False,
|
||||
"Name": "091022 Games Mash-Up",
|
||||
"Comment": "<p>7 Rounds</p><p>3 Wall Walks</p>"},
|
||||
]},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
UNPOSTED = {
|
||||
"Response": {
|
||||
"ErrorMessage": "",
|
||||
"ResponseWOD": {
|
||||
"WorkoutError": {"HasError": False, "ErrorMessage": ""},
|
||||
"ResponseWorkout": {"Id": "0", "Date": "1900-01-01", "Name": "",
|
||||
"Notes": "", "WorkoutComponents": {"List": []}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def test_live_shape_renders_title_and_components():
|
||||
out = render.workout(LIVE_SHAPE)
|
||||
assert out.startswith("# CrossFit - Sat, Jul 25")
|
||||
assert "## WARM-UP" in out, "IsSection components should be marked as sections"
|
||||
assert "15 Banded Good Mornings" in out
|
||||
assert "091022 Games Mash-Up" in out and "3 Wall Walks" in out
|
||||
assert "<" not in out
|
||||
|
||||
|
||||
def test_coach_brief_excluded_by_default():
|
||||
"""Notes runs to thousands of characters; keeping output small is the point."""
|
||||
assert "Daily Coach's Brief" not in render.workout(LIVE_SHAPE)
|
||||
|
||||
|
||||
def test_coach_brief_included_on_request():
|
||||
out = render.workout(LIVE_SHAPE, notes=True)
|
||||
assert "## Coach's brief" in out and "Daily Coach's Brief" in out
|
||||
|
||||
|
||||
def test_unposted_workout_is_reported_as_not_posted():
|
||||
out = render.workout(UNPOSTED)
|
||||
assert "not posted" in out.lower()
|
||||
assert "# " not in out
|
||||
|
||||
|
||||
# --- bookings range filtering -------------------------------------------------
|
||||
|
||||
BOOKINGS = {"Response": {"List": [
|
||||
{"Class": {"StartDate": "2026-07-20", "StartTime": "17:30:00",
|
||||
"ClassName": "CrossFit: 5:30 PM", "ClassId": "101"},
|
||||
"StatusLabel": "Attended"},
|
||||
{"Class": {"StartDate": "2026-07-22", "StartTime": "17:30:00",
|
||||
"ClassName": "CrossFit: 5:30 PM", "ClassId": "102"},
|
||||
"StatusLabel": "Attended"},
|
||||
{"Class": {"StartDate": "2026-07-27", "StartTime": "17:30:00",
|
||||
"ClassName": "CrossFit: 5:30 PM", "ClassId": "103"},
|
||||
"StatusLabel": "Reserved"},
|
||||
]}}
|
||||
|
||||
|
||||
def test_booking_rows_are_sorted_and_expose_class_id():
|
||||
rows = render.booking_rows(BOOKINGS)
|
||||
assert [r["date"] for r in rows] == ["2026-07-20", "2026-07-22", "2026-07-27"]
|
||||
assert rows[0]["class_id"] == "101"
|
||||
|
||||
|
||||
def test_bookings_since_filter():
|
||||
out = render.bookings(BOOKINGS, since="2026-07-22")
|
||||
assert "2026-07-20" not in out and "2026-07-22" in out and "2026-07-27" in out
|
||||
|
||||
|
||||
def test_bookings_until_filter():
|
||||
out = render.bookings(BOOKINGS, until="2026-07-22")
|
||||
assert "2026-07-27" not in out and "2026-07-20" in out
|
||||
|
||||
|
||||
def test_bookings_attended_only_excludes_future_reservations():
|
||||
out = render.bookings(BOOKINGS, attended_only=True)
|
||||
assert "2026-07-27" not in out
|
||||
assert "2026-07-20" in out and "2026-07-22" in out
|
||||
|
||||
|
||||
def test_bookings_exposes_class_id_for_chaining():
|
||||
"""Requirement: list attended classes, then fetch each one's workout."""
|
||||
assert "class_id=101" in render.bookings(BOOKINGS)
|
||||
|
||||
|
||||
def test_empty_filter_result_reports_pre_filter_count():
|
||||
out = render.bookings(BOOKINGS, since="2030-01-01")
|
||||
assert "No bookings found" in out and "3 returned before filtering" in out
|
||||
@@ -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()))
|
||||
@@ -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]}")
|
||||
@@ -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]}")
|
||||
@@ -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}")
|
||||
@@ -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])
|
||||
Reference in new issue
Block a user