"""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 import re from typing import Any from . import actions, cdp, client, config _STAMP = re.compile(r"^\[\d{4}-\d\d-\d\dT[\d:.]+Z\]:?\s*") #: 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), } #: How many distinct page errors to keep. Enough to name the failure, not a log. MAX_PAGE_ERRORS = 5 def _observe_errors(event: dict[str, Any], errors: list[str]) -> None: """Collect a one-line summary of each distinct page error. Only ever reported back to the operator. A page that throws on every data action captures nothing, and without this the only symptom is an empty result that looks like "Wodify moved its endpoints again". """ method = event.get("method") params = event.get("params") or {} chunks: list[str] = [] if method == "Runtime.exceptionThrown": details = params.get("exceptionDetails") or {} exc = details.get("exception") or {} chunks.append(str(exc.get("description") or details.get("text") or "")) elif method == "Runtime.consoleAPICalled" and params.get("type") == "error": for arg in params.get("args") or []: chunks.append(str(arg.get("description") or arg.get("value") or "")) lines = [ln.strip() for chunk in chunks for ln in chunk.splitlines() if ln.strip()] if not lines: return # The app stamps its own console errors ("[2026-11-11T05:02:11.964Z]: ..."); # drop the stamp so identical errors de-duplicate. message = next((m for m in (_STAMP.sub("", ln).strip() for ln in lines) if m), "") # First stack frame says *where*, which is the half that identifies a # broken runtime ("... at Controller.callServerDataSource"). frame = next((ln.split(" (", 1)[0] for ln in lines if ln.startswith("at ")), "") summary = (f"{message} {frame}".strip())[:200] if summary and summary not in errors and len(errors) < MAX_PAGE_ERRORS: errors.append(summary) 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] = [] page_errors: list[str] = [] def on_event(ev: dict[str, Any]) -> None: _observe(ev, found, csrf) _observe_errors(ev, page_errors) for path, wait in walk: await session.navigate(config.origin() + path) await session.drain(wait, on_event) # Walk to a real workout screen so GetAllWorkoutData (and the class # detail actions) actually fire. The walk and the request-observer run # concurrently on purpose: the requests we want are triggered *by* the # walk. CDPSession multiplexes one socket reader, so this is safe. script = WORKOUT_WALK_JS.replace("__DATE_LABEL__", _date_label(workout_date)) walk_task = asyncio.create_task(session.evaluate(script, await_promise=True)) drain_task = asyncio.create_task(session.drain(30, on_event)) try: walk_log = await asyncio.wait_for(asyncio.shield(walk_task), timeout=45) except asyncio.TimeoutError: walk_log = {"error": "walk timed out"} except Exception as exc: # noqa: BLE001 - report, do not hide walk_log = {"error": f"{type(exc).__name__}: {exc}"} await drain_task module_version = await session.evaluate( "fetch('/WodifyClient/moduleservices/moduleversioninfo')" ".then(r => r.json()).then(j => j.versionToken)", await_promise=True, ) finally: await session.close() crashed = (" The page itself reported errors, so the app is failing to " "run rather than calling different endpoints: " + " | ".join(page_errors)) if page_errors else "" 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." + crashed ) if not found: # Never persist an empty capture: it would replace a cache that may # still answer queries with one that cannot answer any. raise RuntimeError( "captured none of the allowlisted data actions; the existing cache " "was left untouched." + (crashed or " The app made data-action calls, but none matched actions.ACTIONS " "-- Wodify has probably moved its endpoints. Dump every " "/screenservices/ path while clicking Home -> Schedule -> a class " "and compare.") ) 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, "page_errors": page_errors, } 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) page_errors = payload.pop("page_errors", []) 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, "page_errors": page_errors, }