Files
wodify-cli/src/wodify/service.py
T
lucioandClaude Opus 5 5a61890011 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]>
2026-07-25 09:23:19 -07:00

90 lines
3.0 KiB
Python

"""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))