openstride 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
openstride/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """openstride: Strava's removed club endpoints (club activities, members, admins), read from the club web pages,
2
+ plus stravalib's full API client.
3
+
4
+ Unofficial. Not affiliated with, endorsed or sponsored by Strava, Inc. For educational purposes only: using it
5
+ may breach Strava's Terms of Service, and you are responsible for how you use it.
6
+ """
7
+ from ._browser import login
8
+ from .client import Client
9
+ from .errors import MarkupChanged, RateLimited, SessionExpired, OpenStrideError, UnsupportedLocale
10
+ from .models import AthleteWeek, ClubActivity, ClubAdmin, ClubAthlete, ClubRoster, LeaderboardEntry
11
+ from .scraper import AthleteWeeks, ClubScraper, monday_of, week_id
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = [
16
+ "Client", "ClubScraper", "login",
17
+ "ClubActivity", "ClubAthlete", "ClubAdmin", "ClubRoster", "LeaderboardEntry", "AthleteWeek", "AthleteWeeks",
18
+ "OpenStrideError", "SessionExpired", "RateLimited", "MarkupChanged", "UnsupportedLocale",
19
+ "monday_of", "week_id", "__version__",
20
+ ]
openstride/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
openstride/_browser.py ADDED
@@ -0,0 +1,225 @@
1
+ """The logged-in browser every scrape runs in. Requests are fetch()es made from inside a strava.com page, so they
2
+ carry that page's cookies and headers exactly as the website's own requests do."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import random
8
+ from contextlib import suppress
9
+ from pathlib import Path
10
+
11
+ from .errors import MarkupChanged, RateLimited, SessionExpired
12
+
13
+ BASE_URL = "https://www.strava.com"
14
+ LOGIN_URL = f"{BASE_URL}/login"
15
+ DEFAULT_SESSION_FILE = "auth_state.json"
16
+ DEFAULT_LOCALE = "en-US"
17
+ SESSION_EXPIRED_MSG = "The saved Strava session has expired. Run: openstride login"
18
+
19
+ # Paths Strava redirects to when the session is not logged in.
20
+ LOGIN_PATHS = ("/login", "/session", "/register", "/oauth")
21
+ # The URL Strava lands on after a successful interactive login.
22
+ LOGIN_DONE_GLOB = "**/dashboard**"
23
+ LOGIN_TIMEOUT_S = 300
24
+
25
+ LAUNCH_ARGS = ["--disable-blink-features=AutomationControlled"]
26
+ VIEWPORT = {"width": 1512, "height": 856}
27
+ DEFAULT_DELAY_S = (0.4, 0.9) # random wait between requests, seconds
28
+
29
+ # Session cookies are credentials: owner-only file and directory.
30
+ SESSION_FILE_MODE = 0o600
31
+ SESSION_DIR_MODE = 0o700
32
+
33
+ HTTP_UNAUTHORIZED = 401
34
+ HTTP_TOO_MANY_REQUESTS = 429
35
+
36
+ # GET a same-site URL from inside a logged-in page; report where it ended up so a login redirect is visible.
37
+ FETCH_JS = """async (url) => {
38
+ const r = await fetch(url, {credentials: 'include'});
39
+ return {ok: r.ok, status: r.status, url: r.url, text: await r.text()};
40
+ }"""
41
+
42
+
43
+ def _is_login(url: str) -> bool:
44
+ """Tell whether a URL is one of Strava's login pages.
45
+
46
+ Args:
47
+ url: Absolute or site-relative URL.
48
+
49
+ Returns:
50
+ True when the path after "strava.com" starts with a login path.
51
+ """
52
+ return url.split("strava.com", 1)[-1].startswith(LOGIN_PATHS)
53
+
54
+
55
+ def _launch(pw, headless: bool, channel: str | None, session_file: Path | None, locale: str, timezone_id: str | None):
56
+ """Launch Chromium and a context set up like ordinary desktop browsing.
57
+
58
+ Args:
59
+ pw: A started Playwright instance.
60
+ headless: Run without a window.
61
+ channel: Installed browser channel ("chrome", "msedge"), or None for Playwright's Chromium.
62
+ session_file: Storage-state JSON to load, if it exists.
63
+ locale: Browser locale.
64
+ timezone_id: IANA timezone for the context, or None for the machine's.
65
+
66
+ Returns:
67
+ (browser, context) tuple.
68
+ """
69
+ browser = pw.chromium.launch(headless=headless, channel=channel or None, args=LAUNCH_ARGS)
70
+ # Headless Chromium otherwise advertises "HeadlessChrome/..."; real Chromium reports <major>.0.0.0.
71
+ ver = f"{browser.version.split('.')[0]}.0.0.0"
72
+ ctx = browser.new_context(
73
+ storage_state=str(session_file) if session_file and session_file.exists() else None,
74
+ user_agent=("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
75
+ f"(KHTML, like Gecko) Chrome/{ver} Safari/537.36 Edg/{ver}"),
76
+ locale=locale, timezone_id=timezone_id, viewport=VIEWPORT,
77
+ )
78
+ return browser, ctx
79
+
80
+
81
+ class Browser:
82
+ """One Chromium with the saved session; opened lazily, closed by close(). Not thread-safe (Playwright's sync
83
+ API binds to the thread that started it): use one Browser per thread."""
84
+
85
+ def __init__(self, session_file: str | Path = DEFAULT_SESSION_FILE, *, headless: bool = True,
86
+ channel: str | None = None, locale: str = DEFAULT_LOCALE, timezone_id: str | None = None,
87
+ delay: tuple[float, float] = DEFAULT_DELAY_S):
88
+ """Store settings; nothing is launched until the first request.
89
+
90
+ Args:
91
+ session_file: Saved login (Playwright storage state JSON).
92
+ headless: Run Chromium without a window.
93
+ channel: Installed browser channel, or None for Playwright's Chromium.
94
+ locale: Browser locale.
95
+ timezone_id: IANA timezone for the context, or None for the machine's.
96
+ delay: (min, max) seconds to wait between requests; max 0 disables waiting.
97
+ """
98
+ self.session_file = Path(session_file)
99
+ self.headless, self.channel, self.locale, self.timezone_id = headless, channel, locale, timezone_id
100
+ self.delay = delay
101
+ self._pw = self._browser = self._ctx = self._page = None
102
+
103
+ def _open(self):
104
+ """Launch the browser on first use.
105
+
106
+ Returns:
107
+ The single Playwright page every request runs in.
108
+
109
+ Raises:
110
+ SessionExpired: No saved session file.
111
+ """
112
+ if self._page is not None:
113
+ return self._page
114
+ if not self.session_file.exists():
115
+ raise SessionExpired(f"No saved Strava session at {self.session_file}. Run: openstride login")
116
+ from playwright.sync_api import sync_playwright # imported here so parsing never needs Playwright
117
+ self._pw = sync_playwright().start()
118
+ try:
119
+ self._browser, self._ctx = _launch(self._pw, self.headless, self.channel, self.session_file,
120
+ self.locale, self.timezone_id)
121
+ self._page = self._ctx.new_page()
122
+ except Exception:
123
+ self.close()
124
+ raise
125
+ return self._page
126
+
127
+ def goto(self, path: str):
128
+ """Navigate to BASE_URL + path.
129
+
130
+ Args:
131
+ path: Site-relative path.
132
+
133
+ Returns:
134
+ The page, after a short pause.
135
+
136
+ Raises:
137
+ SessionExpired: Strava redirected to its login page.
138
+ """
139
+ page = self._open()
140
+ page.goto(BASE_URL + path, wait_until="domcontentloaded")
141
+ if _is_login(page.url):
142
+ raise SessionExpired(SESSION_EXPIRED_MSG)
143
+ self.pause()
144
+ return page
145
+
146
+ def ensure_on_site(self, path: str):
147
+ """Be on some strava.com page so fetches are same-origin.
148
+
149
+ Args:
150
+ path: Where to navigate if not already on the site.
151
+
152
+ Returns:
153
+ The page.
154
+ """
155
+ page = self._open()
156
+ return page if page.url.startswith(BASE_URL) else self.goto(path)
157
+
158
+ def fetch(self, path: str) -> str:
159
+ """GET path from inside the page.
160
+
161
+ Args:
162
+ path: Site-relative path.
163
+
164
+ Returns:
165
+ The response text.
166
+
167
+ Raises:
168
+ SessionExpired: HTTP 401 or redirected to login.
169
+ RateLimited: HTTP 429.
170
+ MarkupChanged: Any other non-2xx status.
171
+ """
172
+ r = self._page.evaluate(FETCH_JS, path)
173
+ if r["status"] == HTTP_UNAUTHORIZED or _is_login(r["url"]):
174
+ raise SessionExpired(SESSION_EXPIRED_MSG)
175
+ if r["status"] == HTTP_TOO_MANY_REQUESTS:
176
+ raise RateLimited(f"Strava rate-limited {path} (HTTP 429); wait before retrying.")
177
+ if not r["ok"]:
178
+ raise MarkupChanged(f"{path} returned HTTP {r['status']}.")
179
+ return r["text"]
180
+
181
+ def pause(self) -> None:
182
+ """Wait a short, random, human-sized time between requests (no-op before the browser opens)."""
183
+ if self._page is not None and self.delay[1] > 0:
184
+ self._page.wait_for_timeout(int(random.uniform(*self.delay) * 1000))
185
+
186
+ def close(self) -> None:
187
+ """Close the browser and stop Playwright. Safe to call twice; the next request reopens it."""
188
+ with suppress(Exception): # already gone; nothing left to release
189
+ if self._browser is not None:
190
+ self._browser.close()
191
+ with suppress(Exception):
192
+ if self._pw is not None:
193
+ self._pw.stop()
194
+ self._pw = self._browser = self._ctx = self._page = None
195
+
196
+
197
+ def login(session_file: str | Path = DEFAULT_SESSION_FILE, *, channel: str | None = None,
198
+ timeout_s: int = LOGIN_TIMEOUT_S) -> Path:
199
+ """Open a visible browser on Strava's login page, wait for the user to log in, and save the session.
200
+
201
+ Args:
202
+ session_file: Where to write the storage state JSON.
203
+ channel: Installed browser channel, or None for Playwright's Chromium.
204
+ timeout_s: How long to wait for the login to finish.
205
+
206
+ Returns:
207
+ Path of the saved session file.
208
+ """
209
+ from playwright.sync_api import sync_playwright
210
+ path = Path(session_file)
211
+ with sync_playwright() as pw:
212
+ browser, ctx = _launch(pw, False, channel, None, DEFAULT_LOCALE, None)
213
+ page = ctx.new_page()
214
+ page.goto(LOGIN_URL)
215
+ print(f"Log in to Strava in the browser window (waiting up to {timeout_s // 60} minutes)...")
216
+ page.wait_for_url(LOGIN_DONE_GLOB, timeout=timeout_s * 1000)
217
+ path.parent.mkdir(parents=True, exist_ok=True, mode=SESSION_DIR_MODE)
218
+ state = ctx.storage_state()
219
+ # Owner-only file, tightened even if an older copy exists.
220
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, SESSION_FILE_MODE)
221
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
222
+ json.dump(state, f)
223
+ os.chmod(path, SESSION_FILE_MODE)
224
+ browser.close()
225
+ return path
openstride/_parse.py ADDED
@@ -0,0 +1,353 @@
1
+ """Pure parsers for what Strava's web pages return. No I/O, no Playwright: everything here is unit-tested.
2
+
3
+ Strava's web pages show numbers as display text in the logged-in account's units ("5.23 km", "3.1 mi",
4
+ "394 ft", "1h 5m"). These parsers accept metric and imperial units but only English labels and
5
+ English number formatting ("1,234.5"). A page in another language raises UnsupportedLocale instead of
6
+ returning wrong numbers.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import html
11
+ import re
12
+ from collections.abc import Iterable
13
+
14
+ from .errors import MarkupChanged, UnsupportedLocale
15
+
16
+ # Metres per unit. Longer suffixes first so "mi" never matches as "m".
17
+ _LENGTH_UNITS = {"km": 1000.0, "mi": 1609.344, "ft": 0.3048, "yd": 0.9144, "m": 1.0}
18
+ _HMS_SECONDS = {"h": 3600, "m": 60, "s": 1}
19
+ _LENGTH_RE = re.compile(r"\s*(\d[\d,]*(?:\.\d+)?|\.\d+)\s*(km|mi|ft|yd|m)\s*", re.IGNORECASE)
20
+ _HMS_RE = re.compile(r"(\d+)\s*(h|m|s)(?![a-z])", re.IGNORECASE)
21
+ _CLOCK_RE = re.compile(r"^\s*(?:(\d+):)?(\d{1,2}):(\d{2})\s*$")
22
+ _INT_RE = re.compile(r"\d[\d,]*")
23
+ _TAG_RE = re.compile(r"<[^>]+>")
24
+
25
+ # Stat labels Strava shows on activity cards in English. Used to tell an English page from a translated one.
26
+ ENGLISH_STAT_LABELS = frozenset({
27
+ "Distance", "Time", "Elev Gain", "Pace", "Speed", "Steps", "Calories", "Avg HR", "Elevation",
28
+ "Moving Time", "Elapsed Time", "Avg Speed", "Avg Pace", "Max Speed", "Energy Output", "Avg Power",
29
+ })
30
+
31
+ # "Activity" entries (camelCase) -> the snake_case keys "GroupActivity" activities already use.
32
+ _ACTIVITY_KEYS = {
33
+ "activity_id": "id", "start_date": "startDate", "name": "activityName", "type": "type",
34
+ "elapsed_time": "elapsedTime", "device_name": "deviceName", "workout_type": "workoutType",
35
+ "is_virtual": "isVirtual", "is_commute": "isCommute", "visibility": "visibility",
36
+ "description": "description", "stats": "stats",
37
+ }
38
+
39
+
40
+ def strip_markup(value) -> str:
41
+ """Strip Strava's markup (<abbr> units, <p>/<br> in descriptions) and HTML entities.
42
+
43
+ Args:
44
+ value: Any value; None becomes ''.
45
+
46
+ Returns:
47
+ Plain, trimmed text.
48
+ """
49
+ return html.unescape(_TAG_RE.sub("", str(value if value is not None else ""))).strip()
50
+
51
+
52
+ def to_meters(text: str | None) -> float | None:
53
+ """Parse a displayed length ('5.23 km', '3.1 mi', '394 ft', '1,234 m').
54
+
55
+ The whole text must be one number and one unit, so '1h 5m' is not read as 5 metres.
56
+
57
+ Args:
58
+ text: Display text.
59
+
60
+ Returns:
61
+ Metres rounded to 0.1, or None if the text is not a length.
62
+ """
63
+ m = _LENGTH_RE.fullmatch(text or "")
64
+ if not m:
65
+ return None
66
+ return round(float(m.group(1).replace(",", "")) * _LENGTH_UNITS[m.group(2).lower()], 1)
67
+
68
+
69
+ def to_seconds(text: str | None) -> int | None:
70
+ """Parse a displayed duration: '1h 5m 3s', '45m 10s', '1h5m', '25:30' (mm:ss), '1:02:03' (h:mm:ss).
71
+
72
+ Args:
73
+ text: Display text.
74
+
75
+ Returns:
76
+ Whole seconds, or None if the text is not a duration.
77
+ """
78
+ s = text or ""
79
+ clock = _CLOCK_RE.match(s)
80
+ if clock:
81
+ h, m, sec = clock.groups()
82
+ return int(h or 0) * _HMS_SECONDS["h"] + int(m) * _HMS_SECONDS["m"] + int(sec)
83
+ parts = _HMS_RE.findall(s)
84
+ if not parts:
85
+ return None
86
+ return sum(int(n) * _HMS_SECONDS[u.lower()] for n, u in parts)
87
+
88
+
89
+ def to_int(text: str | None) -> int | None:
90
+ """Parse the first integer in a string ('1,234 steps' -> 1234).
91
+
92
+ Args:
93
+ text: Display text.
94
+
95
+ Returns:
96
+ The integer, or None if there is none.
97
+ """
98
+ m = _INT_RE.search(text or "")
99
+ return int(m.group(0).replace(",", "")) if m else None
100
+
101
+
102
+ def parse_stats(stats: Iterable[dict] | None) -> dict[str, str]:
103
+ """Turn Strava's stat_one / stat_one_subtitle pairs into {label: value}.
104
+
105
+ Labels vary by sport, so callers look up by label ('Distance', 'Pace'), never by position.
106
+
107
+ Args:
108
+ stats: Strava's [{"key": ..., "value": ...}] list.
109
+
110
+ Returns:
111
+ Plain-text values keyed by plain-text label.
112
+ """
113
+ raw = {s.get("key"): s.get("value") for s in (stats or [])}
114
+ out = {}
115
+ for key, value in raw.items():
116
+ if key and not key.endswith("_subtitle"):
117
+ label = strip_markup(raw.get(f"{key}_subtitle"))
118
+ if label:
119
+ out[label] = strip_markup(value)
120
+ return out
121
+
122
+
123
+ def check_english(stat_dicts: Iterable[dict[str, str]]) -> None:
124
+ """Check that activity stat labels are English.
125
+
126
+ Args:
127
+ stat_dicts: parse_stats() results.
128
+
129
+ Raises:
130
+ UnsupportedLocale: There are labels and none of them is an English label.
131
+ """
132
+ labels = {label for d in stat_dicts for label in d}
133
+ if labels and not labels & ENGLISH_STAT_LABELS:
134
+ raise UnsupportedLocale(
135
+ f"Strava is showing stat labels {sorted(labels)[:5]}; set the account's language to English "
136
+ "(strava.com/settings/display) so numbers can be parsed correctly.")
137
+
138
+
139
+ def _bool(value) -> bool | None:
140
+ """Read a JSON or string boolean.
141
+
142
+ Args:
143
+ value: True/False, "true"/"false", None or "".
144
+
145
+ Returns:
146
+ The boolean, or None when absent.
147
+ """
148
+ if value is None or value == "":
149
+ return None
150
+ if isinstance(value, str):
151
+ return value.strip().lower() == "true"
152
+ return bool(value)
153
+
154
+
155
+ def _int(value) -> int | None:
156
+ """Convert to int.
157
+
158
+ Args:
159
+ value: Anything.
160
+
161
+ Returns:
162
+ int(value), or None when it can't be converted.
163
+ """
164
+ try:
165
+ return int(value)
166
+ except (TypeError, ValueError):
167
+ return None
168
+
169
+
170
+ def _figures(stats: dict[str, str]) -> dict:
171
+ """Read the numeric figures from a stats dict.
172
+
173
+ Args:
174
+ stats: parse_stats() result.
175
+
176
+ Returns:
177
+ distance, moving_time, total_elevation_gain, steps (numbers or None) and pace (text or None).
178
+ """
179
+ return {
180
+ "distance": to_meters(stats.get("Distance")),
181
+ "moving_time": to_seconds(stats.get("Time") or stats.get("Moving Time")),
182
+ "total_elevation_gain": to_meters(stats.get("Elev Gain") or stats.get("Elevation")),
183
+ "steps": to_int(stats.get("Steps")),
184
+ "pace": stats.get("Pace") or None,
185
+ }
186
+
187
+
188
+ def _activity_row(entity: str, a: dict) -> dict:
189
+ """Build one flat activity dict from snake_case activity data (GroupActivity's shape).
190
+
191
+ Args:
192
+ entity: "Activity" or "GroupActivity".
193
+ a: Activity data with GroupActivity's snake_case keys.
194
+
195
+ Returns:
196
+ The flat dict described in feed_entry_activities.
197
+ """
198
+ stats = parse_stats(a.get("stats"))
199
+ return {
200
+ "entity": entity, "_stats": stats, **_figures(stats),
201
+ "id": _int(a.get("activity_id")), "athlete_id": _int(a.get("athlete_id")),
202
+ "athlete_name": strip_markup(a.get("athlete_name")) or None,
203
+ "athlete_firstname": strip_markup(a.get("athlete_firstname")) or None,
204
+ "start_date": a.get("start_date") or None, "start_date_local": a.get("start_date_local") or None,
205
+ "name": strip_markup(a.get("name")) or None, "sport_type": a.get("type") or None,
206
+ "elapsed_time": _int(a.get("elapsed_time")), "device_name": a.get("device_name") or None,
207
+ "workout_type": _int(a.get("workout_type")), "is_virtual": _bool(a.get("is_virtual")),
208
+ "is_commute": _bool(a.get("is_commute")), "visibility": a.get("visibility") or None,
209
+ "description": strip_markup(a.get("description")) or None, "location": a.get("location") or None,
210
+ "kudos_count": _int(a.get("kudos_count")), "comment_count": _int(a.get("num_comments")),
211
+ }
212
+
213
+
214
+ def feed_entry_activities(entry: dict) -> list[dict]:
215
+ """Turn one club-feed / profile-week entry into zero or more flat activity dicts with numeric fields.
216
+
217
+ "Activity" entries are camelCase at entry["activity"]; "GroupActivity" entries nest snake_case activities
218
+ in entry["rowData"]["activities"] (one per athlete in the group). Other entities (posts, challenges) -> [].
219
+
220
+ Args:
221
+ entry: One feed entry.
222
+
223
+ Returns:
224
+ Dicts with keys id, athlete_id, athlete_name, athlete_firstname, start_date, start_date_local, name,
225
+ sport_type, distance, moving_time, elapsed_time, total_elevation_gain, steps, pace, device_name,
226
+ workout_type, is_virtual, is_commute, visibility, location, description, kudos_count, comment_count,
227
+ entity, _stats.
228
+ """
229
+ entity = entry.get("entity")
230
+ if entity == "Activity":
231
+ a = entry.get("activity") or {}
232
+ ath = a.get("athlete") or {}
233
+ kc = a.get("kudosAndComments") or {}
234
+ return [_activity_row(entity, {
235
+ **{k: a.get(v) for k, v in _ACTIVITY_KEYS.items()},
236
+ "athlete_id": ath.get("athleteId"), "athlete_name": ath.get("athleteName"),
237
+ "athlete_firstname": ath.get("firstName"),
238
+ "location": (a.get("timeAndLocation") or {}).get("location"),
239
+ "kudos_count": kc.get("kudosCount"), "num_comments": len(kc.get("comments") or []),
240
+ })]
241
+ if entity == "GroupActivity":
242
+ return [_activity_row(entity, a) for a in (entry.get("rowData") or {}).get("activities") or []]
243
+ return []
244
+
245
+
246
+ def feed_page(entries: list[dict]) -> list[dict]:
247
+ """Collect every activity in a page of feed entries, after checking the page is in English.
248
+
249
+ Args:
250
+ entries: Feed entries.
251
+
252
+ Returns:
253
+ Flat activity dicts that have both an id and an athlete_id.
254
+
255
+ Raises:
256
+ UnsupportedLocale: The page is not in English.
257
+ """
258
+ rows = [r for e in entries for r in feed_entry_activities(e)]
259
+ check_english(r["_stats"] for r in rows)
260
+ return [r for r in rows if r["id"] and r["athlete_id"]]
261
+
262
+
263
+ # --- members page -------------------------------------------------------------------------------------------
264
+
265
+ _COUNT_RE = re.compile(r"""class=['"]membership-count['"][^>]*>\s*([\d,]+)\s+members?\b""")
266
+ _LIST_RE = re.compile(r"""<ul[^>]*class=['"]list-athletes['"][^>]*>""")
267
+ _ROW_RE = re.compile(r"""class=['"]text-headline['"]>\s*<a href=['"]/athletes/(\d+)['"]>([^<]*)</a>""")
268
+ _HEADING_RE = re.compile(r"<h\d[^>]*>([^<]*)</h\d>", re.IGNORECASE)
269
+
270
+
271
+ def parse_member_count(page_html: str) -> int | None:
272
+ """Read the headline from <span class='membership-count'>1,055 members</span>.
273
+
274
+ Args:
275
+ page_html: A members page.
276
+
277
+ Returns:
278
+ The member count, or None if the headline is missing.
279
+ """
280
+ m = _COUNT_RE.search(page_html or "")
281
+ return to_int(m.group(1)) if m else None
282
+
283
+
284
+ def parse_roster(page_html: str) -> list[tuple[int, str, bool | None]]:
285
+ """Read each row of a members page's ul.list-athletes lists.
286
+
287
+ is_admin comes from the heading right before each list ('Admins' / 'Members'); None when there is no
288
+ heading to tell. Rows outside those lists (nav, sidebar) are ignored.
289
+
290
+ Args:
291
+ page_html: A members page.
292
+
293
+ Returns:
294
+ (athlete_id, display name, is_admin) tuples in page order.
295
+ """
296
+ out: list[tuple[int, str, bool | None]] = []
297
+ text = page_html or ""
298
+ prev_end = 0
299
+ for m in _LIST_RE.finditer(text):
300
+ headings = _HEADING_RE.findall(text[prev_end:m.start()])
301
+ heading = strip_markup(headings[-1]).lower() if headings else ""
302
+ is_admin = True if "admin" in heading else False if "member" in heading else None
303
+ block = text[m.end():].split("</ul>", 1)[0]
304
+ for aid, name in _ROW_RE.findall(block):
305
+ out.append((int(aid), html.unescape(name).strip(), is_admin))
306
+ prev_end = m.end() + len(block)
307
+ return out
308
+
309
+
310
+ def split_name(display_name: str) -> tuple[str | None, str | None]:
311
+ """Split a display name at the first space: 'Ada Lovelace King' -> ('Ada', 'Lovelace King').
312
+
313
+ Args:
314
+ display_name: Full name as shown.
315
+
316
+ Returns:
317
+ (first, rest); rest is None for a single word, both None for an empty name.
318
+ """
319
+ parts = (display_name or "").split(None, 1)
320
+ if not parts:
321
+ return None, None
322
+ return parts[0], (parts[1] if len(parts) > 1 else None)
323
+
324
+
325
+ # --- leaderboard --------------------------------------------------------------------------------------------
326
+
327
+ def leaderboard_rows(rows: list[dict]) -> list[dict]:
328
+ """Turn rank-table cell texts (from the DOM) into numeric rows.
329
+
330
+ Args:
331
+ rows: {id, name, rank, dist, acts, elev, time} cell texts per row.
332
+
333
+ Returns:
334
+ Dicts with rank, athlete_id, athlete_name, distance, activities, total_elevation_gain, moving_time.
335
+
336
+ Raises:
337
+ MarkupChanged: A row can't be read.
338
+ """
339
+ out = []
340
+ for r in rows:
341
+ try:
342
+ out.append({
343
+ "rank": to_int(r.get("rank")),
344
+ "athlete_id": int(r["id"]),
345
+ "athlete_name": (r.get("name") or "").strip(),
346
+ "distance": to_meters(r.get("dist")) or 0.0,
347
+ "activities": to_int(r.get("acts")) or 0,
348
+ "total_elevation_gain": to_meters(r.get("elev")) or 0.0,
349
+ "moving_time": to_seconds(r.get("time")) or 0,
350
+ })
351
+ except (KeyError, TypeError, ValueError) as e:
352
+ raise MarkupChanged(f"Unreadable leaderboard row {r!r}: {e}") from e
353
+ return out
openstride/cli.py ADDED
@@ -0,0 +1,59 @@
1
+ """Command line: `openstride login` saves a session; `openstride activities|members|admins|count CLUB_ID` print JSON.
2
+
3
+ openstride login [--session-file auth_state.json] [--channel chrome]
4
+ openstride activities 123456 [--limit 20] [--session-file ...]
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ import sys
11
+
12
+ from . import __version__
13
+ from ._browser import DEFAULT_SESSION_FILE, login
14
+ from .errors import OpenStrideError
15
+ from .scraper import ClubScraper
16
+
17
+
18
+ def main(argv: list[str] | None = None) -> int:
19
+ """Run the command line.
20
+
21
+ Args:
22
+ argv: Arguments without the program name; None reads sys.argv.
23
+
24
+ Returns:
25
+ Exit code: 0 on success, 1 on an OpenStrideError.
26
+ """
27
+ p = argparse.ArgumentParser(prog="openstride", description="Strava club data from the website (unofficial).")
28
+ p.add_argument("--version", action="version", version=f"openstride {__version__}")
29
+ sub = p.add_subparsers(dest="command", required=True)
30
+
31
+ lg = sub.add_parser("login", help="log in in a browser window and save the session")
32
+ lg.add_argument("--session-file", default=DEFAULT_SESSION_FILE)
33
+ lg.add_argument("--channel", default=None, help='installed browser to use, e.g. "chrome" or "msedge"')
34
+
35
+ for name, help_ in (("activities", "recent club activities"), ("members", "club members"),
36
+ ("admins", "club admins"), ("count", "club member count")):
37
+ c = sub.add_parser(name, help=help_)
38
+ c.add_argument("club_id", type=int)
39
+ c.add_argument("--session-file", default=DEFAULT_SESSION_FILE)
40
+ if name != "count":
41
+ c.add_argument("--limit", type=int, default=None)
42
+
43
+ args = p.parse_args(argv)
44
+ try:
45
+ if args.command == "login":
46
+ print(f"Session saved to {login(args.session_file, channel=args.channel)}")
47
+ return 0
48
+ with ClubScraper(args.session_file) as s:
49
+ if args.command == "count":
50
+ print(s.get_club_member_count(args.club_id))
51
+ return 0
52
+ fetch = {"activities": s.get_club_activities, "members": s.get_club_members,
53
+ "admins": s.get_club_admins}[args.command]
54
+ items = fetch(args.club_id, args.limit)
55
+ print(json.dumps([i.model_dump(mode="json", exclude_none=True) for i in items], indent=2))
56
+ return 0
57
+ except OpenStrideError as e:
58
+ print(f"error: {e}", file=sys.stderr)
59
+ return 1