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/client.py ADDED
@@ -0,0 +1,107 @@
1
+ """Client: stravalib's full Strava API client, with the three removed club endpoints served by ClubScraper."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+
6
+ import stravalib
7
+
8
+ from ._browser import DEFAULT_SESSION_FILE
9
+ from .models import ClubActivity, ClubAdmin, ClubAthlete
10
+ from .scraper import ClubScraper
11
+
12
+
13
+ class Client(stravalib.Client):
14
+ """A drop-in stravalib.Client. Every official API method (OAuth, athlete, activities, streams, segments,
15
+ routes, uploads...) is stravalib's own; get_club_activities, get_club_members and get_club_admins, whose
16
+ endpoints Strava removed on 2026-09-01, read the club's web pages instead with a saved login session.
17
+
18
+ client = Client(access_token="...", session_file="auth_state.json")
19
+ me = client.get_athlete() # official API
20
+ for a in client.get_club_activities(123456): # web pages
21
+ print(a.athlete.firstname, a.distance)
22
+ client.close()
23
+
24
+ The club methods return lists (not stravalib's lazy BatchedResultsIterator); iterate them the same way.
25
+ """
26
+
27
+ def __init__(self, access_token: str | None = None, *args, session_file: str | Path = DEFAULT_SESSION_FILE,
28
+ scraper: ClubScraper | None = None, **kwargs):
29
+ """Make the client; the scraper is created on first club call.
30
+
31
+ Args:
32
+ access_token: OAuth token for the official API (optional if you only use the club methods).
33
+ session_file: Saved web login for the club methods (`openstride login`). Ignored if scraper is given.
34
+ scraper: A ClubScraper to use for the club methods instead of making one.
35
+ *args, **kwargs: Passed to stravalib.Client.
36
+ """
37
+ super().__init__(access_token, *args, **kwargs)
38
+ self._session_file = session_file
39
+ self._scraper = scraper
40
+
41
+ @property
42
+ def scraper(self) -> ClubScraper:
43
+ """The ClubScraper behind the club methods (made on first use).
44
+
45
+ Returns:
46
+ The scraper.
47
+ """
48
+ if self._scraper is None:
49
+ self._scraper = ClubScraper(self._session_file)
50
+ return self._scraper
51
+
52
+ def close(self) -> None:
53
+ """Close the scraper's browser, if one was opened."""
54
+ if self._scraper is not None:
55
+ self._scraper.close()
56
+
57
+ def __enter__(self) -> Client:
58
+ """Enter the context.
59
+
60
+ Returns:
61
+ This client.
62
+ """
63
+ return self
64
+
65
+ def __exit__(self, *exc) -> None:
66
+ """Close the scraper on leaving the context.
67
+
68
+ Args:
69
+ *exc: Exception info, ignored.
70
+ """
71
+ self.close()
72
+
73
+ def get_club_activities(self, club_id: int, limit: int | None = None) -> list[ClubActivity]:
74
+ """Recent club activities (about the last 26 hours), newest first. See ClubScraper.get_club_activities.
75
+
76
+ Args:
77
+ club_id: Strava club id.
78
+ limit: Return at most this many; None for all.
79
+
80
+ Returns:
81
+ The activities.
82
+ """
83
+ return self.scraper.get_club_activities(club_id, limit)
84
+
85
+ def get_club_members(self, club_id: int, limit: int | None = None) -> list[ClubAthlete]:
86
+ """The club's members, admins first. See ClubScraper.get_club_members.
87
+
88
+ Args:
89
+ club_id: Strava club id.
90
+ limit: Return at most this many; None for all.
91
+
92
+ Returns:
93
+ The members.
94
+ """
95
+ return self.scraper.get_club_members(club_id, limit)
96
+
97
+ def get_club_admins(self, club_id: int, limit: int | None = None) -> list[ClubAdmin]:
98
+ """The club's administrators. See ClubScraper.get_club_admins.
99
+
100
+ Args:
101
+ club_id: Strava club id.
102
+ limit: Return at most this many; None for all.
103
+
104
+ Returns:
105
+ The admins.
106
+ """
107
+ return self.scraper.get_club_admins(club_id, limit)
openstride/errors.py ADDED
@@ -0,0 +1,21 @@
1
+ """Exceptions raised by openstride. Catch OpenStrideError to handle them all."""
2
+
3
+
4
+ class OpenStrideError(RuntimeError):
5
+ """Base class: a Strava page could not be read."""
6
+
7
+
8
+ class SessionExpired(OpenStrideError):
9
+ """No saved session, or Strava sent the request to the login page. Run `openstride login` again."""
10
+
11
+
12
+ class RateLimited(OpenStrideError):
13
+ """Strava answered HTTP 429. Wait (15 minutes or more) before trying again."""
14
+
15
+
16
+ class MarkupChanged(OpenStrideError):
17
+ """A page no longer looks the way openstride expects: Strava changed it, or blocked the request."""
18
+
19
+
20
+ class UnsupportedLocale(OpenStrideError):
21
+ """The account shows Strava in a language other than English, so numbers can't be parsed safely."""
openstride/models.py ADDED
@@ -0,0 +1,171 @@
1
+ """Return types. The three club models subclass stravalib's, so code written against
2
+ stravalib.Client.get_club_activities / get_club_members / get_club_admins keeps working (isinstance checks,
3
+ attribute names, units). They add the fields Strava's web pages expose but the old API never returned
4
+ (activity id, athlete id, start date, full name, ...).
5
+
6
+ Units follow the Strava API: metres, seconds, sport types as Strava's enum strings.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from datetime import date, datetime
11
+ from typing import Literal, get_args
12
+
13
+ from pydantic import BaseModel
14
+ from stravalib import model as _m
15
+ from stravalib import strava_model as _sm
16
+
17
+ from ._parse import split_name
18
+
19
+ _SPORT_TYPES = frozenset(get_args(_sm.SportType.model_fields["root"].annotation))
20
+ _ACTIVITY_TYPES = frozenset(get_args(_sm.ActivityType.model_fields["root"].annotation))
21
+ # sport_type -> the deprecated `type` Strava's API reported alongside it. Only mappings Strava documents;
22
+ # any other sport_type that is not itself an ActivityType gets type=None.
23
+ _LEGACY_TYPE = {"TrailRun": "Run", "MountainBikeRide": "Ride", "GravelRide": "Ride",
24
+ "EMountainBikeRide": "EBikeRide"}
25
+ SUMMARY_STATE = 2 # stravalib resource_state for summary-level objects
26
+ MEMBER_ACCEPTED = "accepted" # ClubAthlete.member for everyone on the roster
27
+
28
+
29
+ def sport_and_type(raw: str | None) -> tuple[str | None, str | None]:
30
+ """Map a sport string from Strava's pages to stravalib's sport_type and legacy type.
31
+
32
+ Args:
33
+ raw: Sport as Strava sent it, e.g. "TrailRun".
34
+
35
+ Returns:
36
+ (sport_type, type), each None when stravalib doesn't know it.
37
+ """
38
+ sport = raw if raw in _SPORT_TYPES else None
39
+ legacy = raw if raw in _ACTIVITY_TYPES else _LEGACY_TYPE.get(raw or "")
40
+ return sport, legacy
41
+
42
+
43
+ class ClubAthlete(_sm.ClubAthlete):
44
+ """A club member (the removed GET /clubs/{id}/members). Adds `id` and the full display `name`.
45
+
46
+ Unlike the old API, `lastname` is the full last name, not an initial. `member` is "accepted" for everyone
47
+ on the roster; `admin` is None when the page didn't say; `owner` is always None (the page doesn't show it).
48
+ """
49
+
50
+ id: int | None = None
51
+ name: str | None = None
52
+
53
+ @classmethod
54
+ def from_roster(cls, athlete_id: int, name: str, is_admin: bool | None) -> ClubAthlete:
55
+ """Build from one members-page row.
56
+
57
+ Args:
58
+ athlete_id: Strava athlete id.
59
+ name: Display name.
60
+ is_admin: Whether the row was under the Admins heading; None if unknown.
61
+
62
+ Returns:
63
+ The member.
64
+ """
65
+ first, last = split_name(name)
66
+ return cls(id=athlete_id, name=name, firstname=first, lastname=last, member=MEMBER_ACCEPTED,
67
+ admin=is_admin, owner=None, resource_state=SUMMARY_STATE)
68
+
69
+
70
+ class ClubAdmin(_m.SummaryAthlete):
71
+ """A club administrator (the removed GET /clubs/{id}/admins returned SummaryAthlete). Adds the full `name`."""
72
+
73
+ name: str | None = None
74
+
75
+ @classmethod
76
+ def from_member(cls, member: ClubAthlete) -> ClubAdmin:
77
+ """Build from a member known to be an admin.
78
+
79
+ Args:
80
+ member: The member.
81
+
82
+ Returns:
83
+ The admin.
84
+ """
85
+ return cls(id=member.id, name=member.name, firstname=member.firstname, lastname=member.lastname,
86
+ resource_state=SUMMARY_STATE)
87
+
88
+
89
+ class ClubActivity(_m.ClubActivity):
90
+ """A club activity (the removed GET /clubs/{id}/activities), with the fields the old API left out.
91
+
92
+ `distance`, `moving_time` and `total_elevation_gain` are parsed from the numbers Strava displays, so they are
93
+ rounded the way the page rounds them (distance to 10 m, elevation to 1 m or 1 ft). `raw_type` is the sport
94
+ exactly as Strava sent it, kept even when stravalib's SportType doesn't know it yet.
95
+ """
96
+
97
+ athlete: ClubAthlete | None = None
98
+ id: int
99
+ athlete_id: int
100
+ raw_type: str | None = None
101
+ start_date: datetime | None = None
102
+ start_date_local: datetime | None = None
103
+ steps: int | None = None
104
+ pace: str | None = None
105
+ device_name: str | None = None
106
+ is_virtual: bool | None = None
107
+ is_commute: bool | None = None
108
+ visibility: str | None = None
109
+ location: str | None = None
110
+ description: str | None = None
111
+ kudos_count: int | None = None
112
+ comment_count: int | None = None
113
+ entity: str | None = None # "Activity" or "GroupActivity": which kind of feed card it came from
114
+
115
+ @classmethod
116
+ def from_feed(cls, row: dict) -> ClubActivity:
117
+ """Build from one flat feed row.
118
+
119
+ Args:
120
+ row: One _parse.feed_entry_activities() dict.
121
+
122
+ Returns:
123
+ The activity, with a summary athlete and stravalib sport/type set where known.
124
+ """
125
+ sport, legacy = sport_and_type(row.get("sport_type"))
126
+ first, last = split_name(row.get("athlete_name") or "")
127
+ athlete = ClubAthlete(id=row["athlete_id"], name=row.get("athlete_name"),
128
+ firstname=row.get("athlete_firstname") or first, lastname=last, resource_state=SUMMARY_STATE)
129
+ fields = {k: v for k, v in row.items() if k in cls.model_fields and k != "sport_type"}
130
+ return cls(**fields, athlete=athlete, sport_type=sport, type=legacy, raw_type=row.get("sport_type"))
131
+
132
+
133
+ class ClubRoster(BaseModel):
134
+ """One walk of a club's members pages. `complete` is False when the roster didn't tally with the headline
135
+ count (someone joined or left mid-walk, or a page failed); treat absences as unreliable then."""
136
+
137
+ member_count: int
138
+ members: list[ClubAthlete]
139
+
140
+ @property
141
+ def complete(self) -> bool:
142
+ """Whether the roster tallies with the headline count.
143
+
144
+ Returns:
145
+ True when len(members) == member_count.
146
+ """
147
+ return len(self.members) == self.member_count
148
+
149
+
150
+ class LeaderboardEntry(BaseModel):
151
+ """One row of a club's weekly leaderboard (the club's sport only, about the top 100 athletes)."""
152
+
153
+ week: Literal["this", "last"]
154
+ week_start: date
155
+ rank: int | None
156
+ athlete_id: int
157
+ athlete_name: str
158
+ distance: float # metres
159
+ activities: int
160
+ total_elevation_gain: float # metres
161
+ moving_time: int # seconds
162
+
163
+
164
+ class AthleteWeek(BaseModel):
165
+ """One athlete's own activities in one Monday-Sunday week, from their profile.
166
+ `visible` is False when the profile is private to the logged-in account (then `activities` is empty)."""
167
+
168
+ athlete_id: int
169
+ week_start: date
170
+ visible: bool
171
+ activities: list[ClubActivity]
openstride/py.typed ADDED
File without changes