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 +20 -0
- openstride/__main__.py +5 -0
- openstride/_browser.py +225 -0
- openstride/_parse.py +353 -0
- openstride/cli.py +59 -0
- openstride/client.py +107 -0
- openstride/errors.py +21 -0
- openstride/models.py +171 -0
- openstride/py.typed +0 -0
- openstride/scraper.py +455 -0
- openstride-0.1.0.dist-info/METADATA +229 -0
- openstride-0.1.0.dist-info/RECORD +15 -0
- openstride-0.1.0.dist-info/WHEEL +4 -0
- openstride-0.1.0.dist-info/entry_points.txt +2 -0
- openstride-0.1.0.dist-info/licenses/LICENSE +21 -0
openstride/scraper.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
"""ClubScraper: Strava's removed club endpoints, read from the club pages a logged-in member sees."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from datetime import date, datetime, timedelta
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from zoneinfo import ZoneInfo
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, ValidationError
|
|
11
|
+
|
|
12
|
+
from . import _parse
|
|
13
|
+
from ._browser import DEFAULT_LOCALE, DEFAULT_SESSION_FILE, SESSION_EXPIRED_MSG, Browser
|
|
14
|
+
from .errors import MarkupChanged, SessionExpired
|
|
15
|
+
from .models import AthleteWeek, ClubActivity, ClubAdmin, ClubAthlete, ClubRoster, LeaderboardEntry
|
|
16
|
+
|
|
17
|
+
FEED_PAGES_MAX = 50 # circuit breaker: the feed only keeps about a day, a page or two
|
|
18
|
+
MEMBER_PAGES_MAX = 400 # circuit breaker: 12,000 members at 30 a page
|
|
19
|
+
FEED_PAGE_SIZE = 100
|
|
20
|
+
LEADERBOARD_SETTLE_MS = 1000 # after switching to last week, let the table re-render
|
|
21
|
+
WEEKS_WORKERS = 4
|
|
22
|
+
WEEKS_BATCH_SIZE = 24
|
|
23
|
+
HOME_PATH = "/dashboard"
|
|
24
|
+
WEEK_URL = "/athletes/{athlete_id}/interval?interval={week}&interval_type=week&chart_type=miles&year_offset=0"
|
|
25
|
+
|
|
26
|
+
# Leaderboard rank-table rows: the athlete id comes from the profile link, the rest are cell texts.
|
|
27
|
+
LEADERBOARD_JS = """() => [...document.querySelectorAll('.leaderboard tbody tr')].map(tr => {
|
|
28
|
+
const c = [...tr.children].map(td => td.innerText.trim());
|
|
29
|
+
const a = tr.querySelector('a.athlete-name');
|
|
30
|
+
return a && {id: a.getAttribute('href').split('/').pop(), name: a.innerText.trim(),
|
|
31
|
+
rank: c[0], dist: c[2], acts: c[3], elev: c[4], time: c[5]};
|
|
32
|
+
}).filter(Boolean)"""
|
|
33
|
+
|
|
34
|
+
# Fetch a batch of profile-week URLs with `workers` concurrent requests inside the logged-in page. Each response
|
|
35
|
+
# is JavaScript; the week's activity list is the HTML string passed to jQuery('#interval-rides').html(...), whose
|
|
36
|
+
# feed component carries the entries in data-react-props.appContext.preFetchedEntries. The string literal is
|
|
37
|
+
# handed to the JS engine to unescape (its escapes aren't JSON).
|
|
38
|
+
# Per URL: {entries: [...]} | {entries: null} (private: no list) | {expired} | {error} | {limited} | null.
|
|
39
|
+
# The first 429 stops every worker (unfetched URLs stay null): retrying in parallel only deepens Strava's block.
|
|
40
|
+
WEEKS_JS = r"""async ({urls, workers}) => {
|
|
41
|
+
const ATTEMPTS = 4, BACKOFF_MS = 2000, JITTER_MS = 1000, GAP_MS = 150, GAP_JITTER_MS = 350;
|
|
42
|
+
const sleep = (ms) => new Promise(res => setTimeout(res, ms));
|
|
43
|
+
const parse = (t) => {
|
|
44
|
+
const marker = "jQuery('#interval-rides').html(";
|
|
45
|
+
const start = t.indexOf(marker);
|
|
46
|
+
// Only a "..." literal is evaluated: the scan below stops at its closing quote, so no code can follow.
|
|
47
|
+
if (start < 0 || t[start + marker.length] !== '"') return null;
|
|
48
|
+
let i = start + marker.length + 1;
|
|
49
|
+
while (i < t.length && t[i] !== '"') i += t[i] === '\\' ? 2 : 1;
|
|
50
|
+
const html = Function('return ' + t.slice(start + marker.length, i + 1))();
|
|
51
|
+
const el = new DOMParser().parseFromString(html, 'text/html').querySelector('[data-react-props]');
|
|
52
|
+
return el ? (JSON.parse(el.getAttribute('data-react-props')).appContext.preFetchedEntries || []) : null;
|
|
53
|
+
};
|
|
54
|
+
const one = async (url) => {
|
|
55
|
+
let last = '';
|
|
56
|
+
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
|
|
57
|
+
if (attempt) await sleep(BACKOFF_MS * 2 ** attempt + Math.random() * JITTER_MS);
|
|
58
|
+
try {
|
|
59
|
+
const r = await fetch(url, {credentials: 'include', headers: {'X-Requested-With': 'XMLHttpRequest'}});
|
|
60
|
+
if (r.url.includes('/login') || r.status === 401) return {expired: true, status: r.status};
|
|
61
|
+
if (r.status === 429) { limited = true; return {limited: true}; }
|
|
62
|
+
if (r.status >= 500) { last = 'HTTP ' + r.status; continue; }
|
|
63
|
+
if (!r.ok) return {error: 'HTTP ' + r.status};
|
|
64
|
+
return {entries: parse(await r.text())};
|
|
65
|
+
} catch (e) { last = String(e); }
|
|
66
|
+
}
|
|
67
|
+
return {error: last};
|
|
68
|
+
};
|
|
69
|
+
const out = new Array(urls.length).fill(null);
|
|
70
|
+
let next = 0, limited = false;
|
|
71
|
+
const worker = async () => {
|
|
72
|
+
while (next < urls.length && !limited) {
|
|
73
|
+
const i = next++;
|
|
74
|
+
out[i] = await one(urls[i]);
|
|
75
|
+
await sleep(GAP_MS + Math.random() * GAP_JITTER_MS);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
await Promise.all(Array.from({length: Math.min(workers, urls.length)}, worker));
|
|
79
|
+
return out;
|
|
80
|
+
}"""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def monday_of(d: date) -> date:
|
|
84
|
+
"""Find the Monday of a date's week.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
d: Any date.
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
The Monday on or before d.
|
|
91
|
+
"""
|
|
92
|
+
return d - timedelta(days=d.weekday())
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def week_id(monday: date) -> str:
|
|
96
|
+
"""Build Strava's interval id for a week: ISO year + ISO week, e.g. 2026-09-14 -> '202638'.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
monday: The week's Monday.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
The six-digit interval id.
|
|
103
|
+
"""
|
|
104
|
+
y, w, _ = monday.isocalendar()
|
|
105
|
+
return f"{y}{w:02d}"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _activities(rows: Iterable[dict]) -> list[ClubActivity]:
|
|
109
|
+
"""Build ClubActivity models from flat feed rows.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
rows: _parse.feed_page() rows.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
The models.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
MarkupChanged: A row doesn't fit the model.
|
|
119
|
+
"""
|
|
120
|
+
try:
|
|
121
|
+
return [ClubActivity.from_feed(r) for r in rows]
|
|
122
|
+
except ValidationError as e:
|
|
123
|
+
raise MarkupChanged(f"An activity didn't have the expected shape: {e}") from e
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _member_count(page_html: str) -> int:
|
|
127
|
+
"""Read a members page's headline count.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
page_html: A members page.
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
The member count.
|
|
134
|
+
|
|
135
|
+
Raises:
|
|
136
|
+
MarkupChanged: The headline is missing.
|
|
137
|
+
"""
|
|
138
|
+
count = _parse.parse_member_count(page_html)
|
|
139
|
+
if count is None:
|
|
140
|
+
raise MarkupChanged("No member count on the club's members page; Strava may have changed it.")
|
|
141
|
+
return count
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class AthleteWeeks(BaseModel):
|
|
145
|
+
"""Result of ClubScraper.get_athlete_weeks: what was fetched, and what wasn't.
|
|
146
|
+
`rate_limited` means Strava answered 429 and the remaining requests were not sent (they are in `unfetched`)."""
|
|
147
|
+
|
|
148
|
+
weeks: list[AthleteWeek]
|
|
149
|
+
errors: int = 0
|
|
150
|
+
rate_limited: bool = False
|
|
151
|
+
unfetched: list[tuple[int, date]] = []
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class ClubScraper:
|
|
155
|
+
"""Reads Strava club data from the website with a saved login session (see `openstride login`).
|
|
156
|
+
|
|
157
|
+
Use it as a context manager so the browser is closed::
|
|
158
|
+
|
|
159
|
+
with ClubScraper("auth_state.json") as s:
|
|
160
|
+
acts = s.get_club_activities(123456)
|
|
161
|
+
|
|
162
|
+
Every call opens pages as the logged-in account, so it sees what that account sees: activities visible to it,
|
|
163
|
+
and the full roster only if the account may view the club's members. Not thread-safe; one per thread.
|
|
164
|
+
"""
|
|
165
|
+
|
|
166
|
+
def __init__(self, session_file: str | Path = DEFAULT_SESSION_FILE, *, headless: bool = True,
|
|
167
|
+
browser_channel: str | None = None, timezone: str | None = None, locale: str = DEFAULT_LOCALE):
|
|
168
|
+
"""Set up the scraper; the browser opens on the first request.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
session_file: Saved login from `openstride login` (Playwright storage state JSON).
|
|
172
|
+
headless: Run Chromium without a window.
|
|
173
|
+
browser_channel: "" / None for Playwright's Chromium, or "chrome" / "msedge" for an installed browser.
|
|
174
|
+
timezone: IANA zone the club's weeks are counted in (default: this machine's local zone).
|
|
175
|
+
locale: Browser locale. Strava's own language setting must be English either way.
|
|
176
|
+
"""
|
|
177
|
+
self.timezone = timezone
|
|
178
|
+
self._browser = Browser(session_file, headless=headless, channel=browser_channel, locale=locale,
|
|
179
|
+
timezone_id=timezone)
|
|
180
|
+
|
|
181
|
+
def __enter__(self) -> ClubScraper:
|
|
182
|
+
"""Enter the context.
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
This scraper.
|
|
186
|
+
"""
|
|
187
|
+
return self
|
|
188
|
+
|
|
189
|
+
def __exit__(self, *exc) -> None:
|
|
190
|
+
"""Close the browser on leaving the context.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
*exc: Exception info, ignored.
|
|
194
|
+
"""
|
|
195
|
+
self.close()
|
|
196
|
+
|
|
197
|
+
def close(self) -> None:
|
|
198
|
+
"""Close the browser. Safe to call twice; the next call reopens it."""
|
|
199
|
+
self._browser.close()
|
|
200
|
+
|
|
201
|
+
def _today(self) -> date:
|
|
202
|
+
"""Today's date in the scraper's timezone.
|
|
203
|
+
|
|
204
|
+
Returns:
|
|
205
|
+
Today's date.
|
|
206
|
+
"""
|
|
207
|
+
return datetime.now(ZoneInfo(self.timezone) if self.timezone else None).date()
|
|
208
|
+
|
|
209
|
+
# --- activities ----------------------------------------------------------------------------------------
|
|
210
|
+
|
|
211
|
+
def get_club_activities(self, club_id: int, limit: int | None = None) -> list[ClubActivity]:
|
|
212
|
+
"""Recent activities of the club's members, newest upload first (replaces GET /clubs/{id}/activities).
|
|
213
|
+
|
|
214
|
+
Strava's club feed keeps roughly the last 26 hours, whatever is asked for. Any sport. Each activity
|
|
215
|
+
appears once, even when it is also part of a group activity card.
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
club_id: Strava club id.
|
|
219
|
+
limit: Stop after this many activities; None for all.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
The activities.
|
|
223
|
+
|
|
224
|
+
Raises:
|
|
225
|
+
MarkupChanged: The feed is not JSON or its paging cursor is missing.
|
|
226
|
+
"""
|
|
227
|
+
b = self._browser
|
|
228
|
+
b.goto(f"/clubs/{club_id}/recent_activity")
|
|
229
|
+
base = f"/clubs/{club_id}/feed?feed_type=club&num_entries={FEED_PAGE_SIZE}"
|
|
230
|
+
url, out, seen = base, [], set()
|
|
231
|
+
for _ in range(FEED_PAGES_MAX):
|
|
232
|
+
text = b.fetch(url)
|
|
233
|
+
try:
|
|
234
|
+
data = json.loads(text)
|
|
235
|
+
except ValueError as e:
|
|
236
|
+
raise MarkupChanged(f"The club feed was not JSON: {text[:120]!r}") from e
|
|
237
|
+
entries = data.get("entries") or []
|
|
238
|
+
for act in _activities(_parse.feed_page(entries)):
|
|
239
|
+
if act.id not in seen:
|
|
240
|
+
seen.add(act.id)
|
|
241
|
+
out.append(act)
|
|
242
|
+
if limit is not None and len(out) >= limit:
|
|
243
|
+
return out
|
|
244
|
+
if not entries or not (data.get("pagination") or {}).get("hasMore"):
|
|
245
|
+
break
|
|
246
|
+
cursor = entries[-1].get("cursorData") or {}
|
|
247
|
+
if "updated_at" not in cursor or "rank" not in cursor:
|
|
248
|
+
raise MarkupChanged("The club feed's paging cursor is missing.")
|
|
249
|
+
url = f"{base}&before={cursor['updated_at']}&cursor={cursor['rank']}"
|
|
250
|
+
b.pause()
|
|
251
|
+
return out
|
|
252
|
+
|
|
253
|
+
# --- members -------------------------------------------------------------------------------------------
|
|
254
|
+
|
|
255
|
+
def _members_page(self, club_id: int, page: int) -> str:
|
|
256
|
+
"""Fetch one members page.
|
|
257
|
+
|
|
258
|
+
Args:
|
|
259
|
+
club_id: Strava club id.
|
|
260
|
+
page: 1-based page number.
|
|
261
|
+
|
|
262
|
+
Returns:
|
|
263
|
+
The page HTML.
|
|
264
|
+
"""
|
|
265
|
+
return self._browser.fetch(f"/clubs/{club_id}/members?page={page}")
|
|
266
|
+
|
|
267
|
+
def _open_members(self, club_id: int) -> str:
|
|
268
|
+
"""Open the club's members page in the browser, then fetch its first page.
|
|
269
|
+
|
|
270
|
+
Args:
|
|
271
|
+
club_id: Strava club id.
|
|
272
|
+
|
|
273
|
+
Returns:
|
|
274
|
+
Page 1's HTML.
|
|
275
|
+
"""
|
|
276
|
+
self._browser.goto(f"/clubs/{club_id}/members")
|
|
277
|
+
return self._members_page(club_id, 1)
|
|
278
|
+
|
|
279
|
+
def _walk_roster(self, club_id: int, first: str) -> ClubRoster:
|
|
280
|
+
"""Read every members page once.
|
|
281
|
+
|
|
282
|
+
Args:
|
|
283
|
+
club_id: Strava club id.
|
|
284
|
+
first: Page 1's HTML, already fetched.
|
|
285
|
+
|
|
286
|
+
Returns:
|
|
287
|
+
The headline count and every member seen.
|
|
288
|
+
|
|
289
|
+
Raises:
|
|
290
|
+
MarkupChanged: Page 1 has no member count.
|
|
291
|
+
"""
|
|
292
|
+
count = _member_count(first)
|
|
293
|
+
members: dict[int, ClubAthlete] = {}
|
|
294
|
+
|
|
295
|
+
def add(rows) -> int:
|
|
296
|
+
"""Merge roster rows into `members`.
|
|
297
|
+
|
|
298
|
+
Args:
|
|
299
|
+
rows: _parse.parse_roster() tuples.
|
|
300
|
+
|
|
301
|
+
Returns:
|
|
302
|
+
How many athletes were new.
|
|
303
|
+
"""
|
|
304
|
+
new = 0
|
|
305
|
+
for aid, name, is_admin in rows:
|
|
306
|
+
if aid not in members:
|
|
307
|
+
members[aid] = ClubAthlete.from_roster(aid, name, is_admin)
|
|
308
|
+
new += 1
|
|
309
|
+
elif is_admin: # admins are listed on every page; any listing as admin counts
|
|
310
|
+
members[aid].admin = True
|
|
311
|
+
return new
|
|
312
|
+
|
|
313
|
+
add(_parse.parse_roster(first))
|
|
314
|
+
for n in range(2, MEMBER_PAGES_MAX + 1):
|
|
315
|
+
self._browser.pause()
|
|
316
|
+
if not add(_parse.parse_roster(self._members_page(club_id, n))):
|
|
317
|
+
break # past the end: nobody new on this page
|
|
318
|
+
return ClubRoster(member_count=count, members=list(members.values()))
|
|
319
|
+
|
|
320
|
+
def get_club_roster(self, club_id: int) -> ClubRoster:
|
|
321
|
+
"""The headline member count and every member, from one walk of the members pages.
|
|
322
|
+
|
|
323
|
+
Walked twice if the first walk doesn't tally with the count, since a join or leave mid-walk shifts
|
|
324
|
+
the pages.
|
|
325
|
+
|
|
326
|
+
Args:
|
|
327
|
+
club_id: Strava club id.
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
The roster; check `complete` before trusting absences.
|
|
331
|
+
"""
|
|
332
|
+
roster = self._walk_roster(club_id, self._open_members(club_id))
|
|
333
|
+
if not roster.complete:
|
|
334
|
+
roster = self._walk_roster(club_id, self._members_page(club_id, 1))
|
|
335
|
+
return roster
|
|
336
|
+
|
|
337
|
+
def get_club_members(self, club_id: int, limit: int | None = None) -> list[ClubAthlete]:
|
|
338
|
+
"""The club's members, admins first (replaces GET /clubs/{id}/members). `admin` marks administrators.
|
|
339
|
+
|
|
340
|
+
Args:
|
|
341
|
+
club_id: Strava club id.
|
|
342
|
+
limit: Return at most this many; None for all.
|
|
343
|
+
|
|
344
|
+
Returns:
|
|
345
|
+
The members.
|
|
346
|
+
"""
|
|
347
|
+
return self.get_club_roster(club_id).members[:limit]
|
|
348
|
+
|
|
349
|
+
def get_club_admins(self, club_id: int, limit: int | None = None) -> list[ClubAdmin]:
|
|
350
|
+
"""The club's administrators (replaces GET /clubs/{id}/admins).
|
|
351
|
+
|
|
352
|
+
Args:
|
|
353
|
+
club_id: Strava club id.
|
|
354
|
+
limit: Return at most this many; None for all.
|
|
355
|
+
|
|
356
|
+
Returns:
|
|
357
|
+
The admins.
|
|
358
|
+
|
|
359
|
+
Raises:
|
|
360
|
+
MarkupChanged: The members page no longer marks admins.
|
|
361
|
+
"""
|
|
362
|
+
rows = _parse.parse_roster(self._open_members(club_id))
|
|
363
|
+
if rows and all(is_admin is None for _, _, is_admin in rows):
|
|
364
|
+
raise MarkupChanged("The members page no longer says who is an admin.")
|
|
365
|
+
admins = {aid: name for aid, name, is_admin in rows if is_admin} # every page lists all the admins
|
|
366
|
+
return [ClubAdmin.from_member(ClubAthlete.from_roster(aid, name, True))
|
|
367
|
+
for aid, name in admins.items()][:limit]
|
|
368
|
+
|
|
369
|
+
def get_club_member_count(self, club_id: int) -> int:
|
|
370
|
+
"""The member count Strava shows on the club page.
|
|
371
|
+
|
|
372
|
+
Args:
|
|
373
|
+
club_id: Strava club id.
|
|
374
|
+
|
|
375
|
+
Returns:
|
|
376
|
+
The member count.
|
|
377
|
+
|
|
378
|
+
Raises:
|
|
379
|
+
MarkupChanged: The headline is missing.
|
|
380
|
+
"""
|
|
381
|
+
return _member_count(self._open_members(club_id))
|
|
382
|
+
|
|
383
|
+
# --- leaderboard ---------------------------------------------------------------------------------------
|
|
384
|
+
|
|
385
|
+
def get_club_leaderboard(self, club_id: int, week: str = "this") -> list[LeaderboardEntry]:
|
|
386
|
+
"""The club's weekly leaderboard: about the top 100 athletes, club sport only.
|
|
387
|
+
|
|
388
|
+
Figures are Strava's own weekly totals (moving time).
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
club_id: Strava club id.
|
|
392
|
+
week: "this" or "last".
|
|
393
|
+
|
|
394
|
+
Returns:
|
|
395
|
+
The leaderboard rows.
|
|
396
|
+
|
|
397
|
+
Raises:
|
|
398
|
+
ValueError: week is not "this" or "last".
|
|
399
|
+
MarkupChanged: A row can't be read.
|
|
400
|
+
"""
|
|
401
|
+
if week not in ("this", "last"):
|
|
402
|
+
raise ValueError('week must be "this" or "last"')
|
|
403
|
+
page = self._browser.goto(f"/clubs/{club_id}/leaderboard")
|
|
404
|
+
if week == "last":
|
|
405
|
+
page.locator("span.button.last-week").click()
|
|
406
|
+
page.wait_for_load_state("networkidle")
|
|
407
|
+
page.wait_for_timeout(LEADERBOARD_SETTLE_MS)
|
|
408
|
+
rows = _parse.leaderboard_rows(page.evaluate(LEADERBOARD_JS))
|
|
409
|
+
start = monday_of(self._today()) - timedelta(weeks=1 if week == "last" else 0)
|
|
410
|
+
return [LeaderboardEntry(week=week, week_start=start, **r) for r in rows]
|
|
411
|
+
|
|
412
|
+
# --- athlete weeks -------------------------------------------------------------------------------------
|
|
413
|
+
|
|
414
|
+
def get_athlete_weeks(self, requests: Iterable[tuple[int, date]], workers: int = WEEKS_WORKERS,
|
|
415
|
+
batch_size: int = WEEKS_BATCH_SIZE) -> AthleteWeeks:
|
|
416
|
+
"""Many (athlete_id, week_start) profile weeks, `workers` at a time.
|
|
417
|
+
|
|
418
|
+
Stops at Strava's first HTTP 429 and returns what it fetched (rate_limited=True, the rest in `unfetched`).
|
|
419
|
+
|
|
420
|
+
Args:
|
|
421
|
+
requests: (athlete_id, any day of the week) pairs.
|
|
422
|
+
workers: Concurrent requests inside the page.
|
|
423
|
+
batch_size: URLs per page.evaluate round trip.
|
|
424
|
+
|
|
425
|
+
Returns:
|
|
426
|
+
The weeks read, the error count, and what was left unfetched.
|
|
427
|
+
|
|
428
|
+
Raises:
|
|
429
|
+
SessionExpired: Immediately, when the session has expired.
|
|
430
|
+
"""
|
|
431
|
+
jobs = [(int(a), monday_of(w)) for a, w in requests]
|
|
432
|
+
weeks, errors = [], 0
|
|
433
|
+
page = self._browser.ensure_on_site(HOME_PATH)
|
|
434
|
+
for b in range(0, len(jobs), batch_size):
|
|
435
|
+
batch = jobs[b:b + batch_size]
|
|
436
|
+
urls = [WEEK_URL.format(athlete_id=a, week=week_id(m)) for a, m in batch]
|
|
437
|
+
results = page.evaluate(WEEKS_JS, {"urls": urls, "workers": workers})
|
|
438
|
+
unfetched = []
|
|
439
|
+
for (aid, monday), res in zip(batch, results, strict=True):
|
|
440
|
+
if res is None or res.get("limited"): # never sent: a 429 stopped the batch
|
|
441
|
+
unfetched.append((aid, monday))
|
|
442
|
+
continue
|
|
443
|
+
if res.get("expired"):
|
|
444
|
+
raise SessionExpired(SESSION_EXPIRED_MSG)
|
|
445
|
+
if "error" in res:
|
|
446
|
+
errors += 1
|
|
447
|
+
continue
|
|
448
|
+
entries = res.get("entries")
|
|
449
|
+
own = [a for a in _activities(_parse.feed_page(entries or [])) if a.athlete_id == aid]
|
|
450
|
+
weeks.append(AthleteWeek(athlete_id=aid, week_start=monday, visible=entries is not None,
|
|
451
|
+
activities=own))
|
|
452
|
+
if unfetched:
|
|
453
|
+
return AthleteWeeks(weeks=weeks, errors=errors, rate_limited=True,
|
|
454
|
+
unfetched=unfetched + jobs[b + len(batch):])
|
|
455
|
+
return AthleteWeeks(weeks=weeks, errors=errors)
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: openstride
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Compatible with Strava: club activities, members and admins for Python, plus stravalib's full API client. Unofficial.
|
|
5
|
+
Project-URL: Source, https://github.com/choonyongchan/OpenStride
|
|
6
|
+
Author: choonyongchan
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: club,cycling,fitness,running,strava,stravalib
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Requires-Dist: playwright>=1.45
|
|
18
|
+
Requires-Dist: pydantic<3,>=2.0
|
|
19
|
+
Requires-Dist: stravalib<3,>=2.6
|
|
20
|
+
Provides-Extra: test
|
|
21
|
+
Requires-Dist: pytest-cov>=5; extra == 'test'
|
|
22
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# OpenStride
|
|
26
|
+
|
|
27
|
+
**OpenStride: compatible with Strava. A Python library for club activities, members and admins, plus a self-hosted club dashboard.**
|
|
28
|
+
|
|
29
|
+
On 1 September 2026 Strava removed three API endpoints:
|
|
30
|
+
`GET /clubs/{id}/activities`, `GET /clubs/{id}/members` and `GET /clubs/{id}/admins`.
|
|
31
|
+
OpenStride provides these three methods again, with the same arguments and return types,
|
|
32
|
+
using your own logged-in Strava session. Everything else in the official API is served by
|
|
33
|
+
[stravalib](https://github.com/stravalib/stravalib), which OpenStride builds on.
|
|
34
|
+
|
|
35
|
+
> **Unofficial. For educational purposes only.**
|
|
36
|
+
> OpenStride is not affiliated with, endorsed by or sponsored by Strava, Inc. "Strava" is a
|
|
37
|
+
> trademark of Strava, Inc. Review Strava's Terms of Service before use: using OpenStride
|
|
38
|
+
> may get the account you log in with restricted or banned. You are responsible for how you
|
|
39
|
+
> use OpenStride and for the club members' data it returns. Only use it with clubs you
|
|
40
|
+
> belong to, keep the request rate low, and respect members' privacy choices.
|
|
41
|
+
|
|
42
|
+
This repository has three parts:
|
|
43
|
+
|
|
44
|
+
| Part | What it is | Where |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| **Library** | `pip install openstride`: `ClubScraper`, and `Client` (a drop-in `stravalib.Client`) | `src/` |
|
|
47
|
+
| **Dashboard** | FastAPI backend + static frontend: leaderboard, awards, history, trend, and Strava-shaped `/api/v3/clubs/...` endpoints | `dashboard/` |
|
|
48
|
+
| **Docker image** | the dashboard with Chromium, one command to run | `Dockerfile`, `docker-compose.yml` |
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## 1. The library
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install openstride
|
|
56
|
+
python -m playwright install chromium
|
|
57
|
+
openstride login # log in to Strava in the window that opens; saves auth_state.json
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Drop-in for stravalib
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from openstride import Client
|
|
64
|
+
|
|
65
|
+
with Client(access_token="...", session_file="auth_state.json") as client:
|
|
66
|
+
me = client.get_athlete() # official API, via stravalib
|
|
67
|
+
for a in client.get_club_activities(123456): # removed endpoint, restored
|
|
68
|
+
print(a.athlete.firstname, a.sport_type, a.distance, a.moving_time)
|
|
69
|
+
members = client.get_club_members(123456)
|
|
70
|
+
admins = client.get_club_admins(123456)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`Client` subclasses `stravalib.Client`, so every other method is stravalib's. The three
|
|
74
|
+
club methods take the same arguments (`club_id`, `limit`) and return the same model types
|
|
75
|
+
(`isinstance(a, stravalib.model.ClubActivity)` holds), as lists instead of lazy iterators.
|
|
76
|
+
`access_token` is optional if you only use the club methods.
|
|
77
|
+
|
|
78
|
+
### Without an API token
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from datetime import date
|
|
82
|
+
from openstride import ClubScraper
|
|
83
|
+
|
|
84
|
+
with ClubScraper("auth_state.json", timezone="Asia/Singapore") as s:
|
|
85
|
+
activities = s.get_club_activities(123456) # about the last 26 hours, newest first
|
|
86
|
+
roster = s.get_club_roster(123456) # .member_count, .members, .complete
|
|
87
|
+
admins = s.get_club_admins(123456)
|
|
88
|
+
count = s.get_club_member_count(123456)
|
|
89
|
+
board = s.get_club_leaderboard(123456, "last") # Strava's weekly club leaderboard, ~top 100
|
|
90
|
+
many = s.get_athlete_weeks([(987654, date(2026, 9, 14)), ...]) # stops cleanly at HTTP 429
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
From the command line: `openstride activities 123456`, `openstride members 123456`,
|
|
94
|
+
`openstride admins 123456`, `openstride count 123456` (JSON on stdout).
|
|
95
|
+
|
|
96
|
+
### What you get, compared with the old endpoints
|
|
97
|
+
|
|
98
|
+
| Removed endpoint | Old API returned | OpenStride returns |
|
|
99
|
+
|---|---|---|
|
|
100
|
+
| `get_club_activities` | athlete first name + last initial, name, distance, moving/elapsed time, elevation, type, sport_type, workout_type. **No activity id, date or athlete id.** | all of those, plus `id`, `athlete_id`, full name, `start_date`, `start_date_local`, device, kudos, comments, description, location, visibility, steps, pace. `raw_type` keeps sports stravalib doesn't know yet. |
|
|
101
|
+
| `get_club_members` | first name, last initial, member/admin/owner flags. **No athlete id.** | `id`, full `name`, `firstname`, `lastname`, `admin`, `member="accepted"`. `owner` is always `None` (Strava doesn't expose it). |
|
|
102
|
+
| `get_club_admins` | summary athletes | `id`, full `name`, `firstname`, `lastname` |
|
|
103
|
+
|
|
104
|
+
### Accuracy: read this before relying on the numbers
|
|
105
|
+
|
|
106
|
+
- **Numbers match what Strava displays**, so they are rounded the way Strava
|
|
107
|
+
rounds them on screen: distance to 0.01 km or 0.01 mi (about 10 m), elevation to 1 m or 1 ft,
|
|
108
|
+
and durations over an hour shown without seconds lose them. Imperial accounts are
|
|
109
|
+
supported and converted to metres.
|
|
110
|
+
- **The account's Strava language must be English.** Labels and number formats are
|
|
111
|
+
localised; a non-English account raises `UnsupportedLocale` rather than returning wrong
|
|
112
|
+
numbers. Change it at strava.com/settings/display.
|
|
113
|
+
- **The club feed keeps limited entries.** Poll frequently (hourly), or use the profile weeks
|
|
114
|
+
(`get_athlete_weeks`) to backfill. Strava rate-limits those; the call stops at the first
|
|
115
|
+
HTTP 429 and tells you what it didn't fetch.
|
|
116
|
+
- **You see what the logged-in account sees.** Private activities and private profiles are
|
|
117
|
+
invisible; the full member list needs an account that may view the club's members.
|
|
118
|
+
- **Strava can change its service at any time.** OpenStride raises `MarkupChanged` instead of
|
|
119
|
+
returning wrong data. All errors subclass `OpenStrideError`:
|
|
120
|
+
`SessionExpired` (run `openstride login` again), `RateLimited`, `MarkupChanged`, `UnsupportedLocale`.
|
|
121
|
+
|
|
122
|
+
One `ClubScraper` drives one Chromium and is not thread-safe; use one per thread.
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## 2. The dashboard
|
|
127
|
+
|
|
128
|
+
A club challenge dashboard: totals, awards, a sortable leaderboard (every member, active
|
|
129
|
+
or not), history by day and trend charts. It syncs on a schedule and keeps its data as
|
|
130
|
+
CSV files you can open in any spreadsheet.
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
git clone <this repo> && cd OpenStride
|
|
134
|
+
python -m venv .venv && . .venv/bin/activate # Windows: .venv\Scripts\activate
|
|
135
|
+
pip install -e . -r requirements-dashboard.txt
|
|
136
|
+
python -m playwright install chromium
|
|
137
|
+
cp .env.example .env # set OPENSTRIDE_CLUB_ID and OPENSTRIDE_CHALLENGE_START
|
|
138
|
+
set -a; . ./.env; set +a # or export the variables your own way
|
|
139
|
+
python -m dashboard login # saves data/auth_state.json
|
|
140
|
+
python -m dashboard serve # http://localhost:8000
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
| Command | Does |
|
|
144
|
+
|---|---|
|
|
145
|
+
| `python -m dashboard serve` | API + dashboard; syncs every `OPENSTRIDE_SYNC_MINUTES`, profile scan at `OPENSTRIDE_SCAN_HOUR` |
|
|
146
|
+
| `python -m dashboard sync` | one light sync now (members, feed, leaderboard) |
|
|
147
|
+
| `python -m dashboard sync --scan` | ...plus the profile scan (fills gaps the feed missed) |
|
|
148
|
+
| `python -m dashboard sync --setup` | rescan every week since the start, for everyone |
|
|
149
|
+
| `python -m dashboard login` | log in again when the session expires |
|
|
150
|
+
|
|
151
|
+
### Where the numbers come from
|
|
152
|
+
|
|
153
|
+
Each sync reads the roster (and the headline member count), the club feed and the weekly
|
|
154
|
+
leaderboard; the nightly scan reads every current member's last two profile weeks (every
|
|
155
|
+
week since the start for newcomers). Per athlete and day, `statistics.csv` keeps cumulative
|
|
156
|
+
totals from the best source available: Strava's leaderboard figure, else the profile week,
|
|
157
|
+
else the feed. Set `OPENSTRIDE_SPORTS` to the club's sport so the three agree; the default is
|
|
158
|
+
foot sports (Run, TrailRun, VirtualRun, Walk, Hike).
|
|
159
|
+
|
|
160
|
+
| File in `data/` | Holds |
|
|
161
|
+
|---|---|
|
|
162
|
+
| `activities.csv` | every activity seen, any sport, one row each, never rewritten |
|
|
163
|
+
| `members.csv` | everyone ever on the roster, with `admin`, `ingest_at`, `left_at` |
|
|
164
|
+
| `member_count.csv` | the headline member count at each sync |
|
|
165
|
+
| `statistics.csv` | cumulative totals per athlete per day, with `source` |
|
|
166
|
+
| `status.json` | the last sync's outcome (shown on the dashboard when it failed) |
|
|
167
|
+
| `auth_state.json` | the Strava session. **Secret: never commit or share it.** |
|
|
168
|
+
|
|
169
|
+
### API
|
|
170
|
+
|
|
171
|
+
| Endpoint | |
|
|
172
|
+
|---|---|
|
|
173
|
+
| `GET /api/club` | name, settings, last sync |
|
|
174
|
+
| `GET /api/report?date=YYYY-MM-DD` | totals, awards, leaderboard as of a day |
|
|
175
|
+
| `GET /api/dates`, `GET /api/trend` | days with history; cumulative totals per day |
|
|
176
|
+
| `GET /api/v3/clubs/{id}/activities` | **the removed endpoints, same paths and JSON**, from the synced data (all history, not just 26 h), `?page=&per_page=` (max 200) |
|
|
177
|
+
| `GET /api/v3/clubs/{id}/members` | |
|
|
178
|
+
| `GET /api/v3/clubs/{id}/admins` | |
|
|
179
|
+
| `POST /api/sync?scan=&setup=` | run a sync now |
|
|
180
|
+
|
|
181
|
+
`/api/v3/*` and `POST /api/sync` need `Authorization: Bearer $OPENSTRIDE_API_TOKEN`; they are
|
|
182
|
+
off until you set the token. They expose more than the dashboard does (descriptions,
|
|
183
|
+
locations), so keep the token private.
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
curl -H "Authorization: Bearer $OPENSTRIDE_API_TOKEN" localhost:8000/api/v3/clubs/123456/activities?per_page=5
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
---
|
|
190
|
+
|
|
191
|
+
## 3. Docker
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
cp .env.example .env # fill in OPENSTRIDE_CLUB_ID, OPENSTRIDE_CHALLENGE_START, ...
|
|
195
|
+
mkdir -p data
|
|
196
|
+
# Log in once on a machine with a screen (the container has none), then copy the session in:
|
|
197
|
+
pip install openstride && python -m playwright install chromium && openstride login --session-file data/auth_state.json
|
|
198
|
+
docker compose up -d # http://localhost:8000
|
|
199
|
+
docker compose run --rm dashboard python -m dashboard sync --setup # optional: backfill since the start
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
The image runs as an unprivileged user with everything in the `/data` volume. When the
|
|
203
|
+
dashboard shows "SessionExpired", run `openstride login --session-file data/auth_state.json`
|
|
204
|
+
again; nothing else needs restarting.
|
|
205
|
+
|
|
206
|
+
---
|
|
207
|
+
|
|
208
|
+
## Development
|
|
209
|
+
|
|
210
|
+
Tests come in three layers, each run and coverage-gated in CI: `tests/library` (unit), `tests/dashboard`
|
|
211
|
+
(integration), and `tests/e2e` (headless Chromium against a local fake site).
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
pip install -e ".[test]" -r requirements-dashboard.txt httpx
|
|
215
|
+
python -m playwright install chromium
|
|
216
|
+
python -m pytest -q --cov # unit + integration + e2e, offline: never contacts Strava
|
|
217
|
+
OPENSTRIDE_TEST_CLUB_ID=123456 python -m pytest tests/live --live # vs live Strava: roster tallies, profile weeks = leaderboard
|
|
218
|
+
python -m build && twine check dist/* # the PyPI package (library only)
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
The library lives in `src/` (`_parse.py` is pure functions, unit-tested). The dashboard
|
|
222
|
+
calls the library. To publish: bump `version` in `pyproject.toml` and `__version__`, then
|
|
223
|
+
`twine upload dist/*`.
|
|
224
|
+
|
|
225
|
+
## Licence
|
|
226
|
+
|
|
227
|
+
MIT. Builds on [stravalib](https://github.com/stravalib/stravalib) (Apache-2.0) and
|
|
228
|
+
[Playwright](https://playwright.dev/). Dashboard originally based on
|
|
229
|
+
[DatabenderSK/strava-club-dashboard](https://github.com/DatabenderSK/strava-club-dashboard).
|