otf-api 0.2.1__py3-none-any.whl → 0.3.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.
Files changed (49) hide show
  1. otf_api/__init__.py +12 -67
  2. otf_api/api.py +794 -36
  3. otf_api/cli/__init__.py +4 -0
  4. otf_api/cli/_utilities.py +60 -0
  5. otf_api/cli/app.py +177 -0
  6. otf_api/cli/bookings.py +231 -0
  7. otf_api/cli/prompts.py +162 -0
  8. otf_api/models/__init__.py +4 -8
  9. otf_api/models/auth.py +18 -12
  10. otf_api/models/base.py +205 -2
  11. otf_api/models/responses/__init__.py +6 -14
  12. otf_api/models/responses/body_composition_list.py +304 -0
  13. otf_api/models/responses/book_class.py +405 -0
  14. otf_api/models/responses/bookings.py +211 -37
  15. otf_api/models/responses/cancel_booking.py +93 -0
  16. otf_api/models/responses/challenge_tracker_content.py +6 -6
  17. otf_api/models/responses/challenge_tracker_detail.py +6 -6
  18. otf_api/models/responses/classes.py +205 -7
  19. otf_api/models/responses/enums.py +0 -35
  20. otf_api/models/responses/favorite_studios.py +5 -5
  21. otf_api/models/responses/latest_agreement.py +2 -2
  22. otf_api/models/responses/lifetime_stats.py +92 -0
  23. otf_api/models/responses/member_detail.py +17 -12
  24. otf_api/models/responses/member_membership.py +2 -2
  25. otf_api/models/responses/member_purchases.py +9 -9
  26. otf_api/models/responses/out_of_studio_workout_history.py +4 -4
  27. otf_api/models/responses/performance_summary_detail.py +1 -1
  28. otf_api/models/responses/performance_summary_list.py +13 -13
  29. otf_api/models/responses/studio_detail.py +10 -10
  30. otf_api/models/responses/studio_services.py +8 -8
  31. otf_api/models/responses/telemetry.py +6 -6
  32. otf_api/models/responses/telemetry_hr_history.py +6 -6
  33. otf_api/models/responses/telemetry_max_hr.py +3 -3
  34. otf_api/models/responses/total_classes.py +2 -2
  35. otf_api/models/responses/workouts.py +4 -4
  36. otf_api-0.3.0.dist-info/METADATA +55 -0
  37. otf_api-0.3.0.dist-info/RECORD +42 -0
  38. otf_api-0.3.0.dist-info/entry_points.txt +3 -0
  39. otf_api/__version__.py +0 -1
  40. otf_api/classes_api.py +0 -44
  41. otf_api/member_api.py +0 -380
  42. otf_api/performance_api.py +0 -54
  43. otf_api/studios_api.py +0 -96
  44. otf_api/telemetry_api.py +0 -95
  45. otf_api-0.2.1.dist-info/METADATA +0 -284
  46. otf_api-0.2.1.dist-info/RECORD +0 -38
  47. {otf_api-0.2.1.dist-info → otf_api-0.3.0.dist-info}/AUTHORS.md +0 -0
  48. {otf_api-0.2.1.dist-info → otf_api-0.3.0.dist-info}/LICENSE +0 -0
  49. {otf_api-0.2.1.dist-info → otf_api-0.3.0.dist-info}/WHEEL +0 -0
otf_api/api.py CHANGED
@@ -1,23 +1,54 @@
1
1
  import asyncio
2
+ import contextlib
3
+ import json
2
4
  import typing
5
+ from datetime import date, datetime
6
+ from math import ceil
3
7
  from typing import Any
4
8
 
5
9
  import aiohttp
6
10
  from loguru import logger
7
11
  from yarl import URL
8
12
 
9
- from otf_api.classes_api import ClassesApi
10
- from otf_api.member_api import MemberApi
11
13
  from otf_api.models.auth import User
12
- from otf_api.performance_api import PerformanceApi
13
- from otf_api.studios_api import StudiosApi
14
- from otf_api.telemetry_api import TelemtryApi
14
+ from otf_api.models.responses.body_composition_list import BodyCompositionList
15
+ from otf_api.models.responses.book_class import BookClass
16
+ from otf_api.models.responses.cancel_booking import CancelBooking
17
+ from otf_api.models.responses.classes import ClassType, DoW, OtfClassList
18
+ from otf_api.models.responses.favorite_studios import FavoriteStudioList
19
+ from otf_api.models.responses.lifetime_stats import StatsResponse, StatsTime
20
+ from otf_api.models.responses.performance_summary_detail import PerformanceSummaryDetail
21
+ from otf_api.models.responses.performance_summary_list import PerformanceSummaryList
22
+ from otf_api.models.responses.studio_detail import Pagination, StudioDetail, StudioDetailList
23
+ from otf_api.models.responses.telemetry import Telemetry
24
+ from otf_api.models.responses.telemetry_hr_history import TelemetryHrHistory
25
+ from otf_api.models.responses.telemetry_max_hr import TelemetryMaxHr
26
+
27
+ from .models import (
28
+ BookingList,
29
+ BookingStatus,
30
+ ChallengeTrackerContent,
31
+ ChallengeTrackerDetailList,
32
+ ChallengeType,
33
+ EquipmentType,
34
+ LatestAgreement,
35
+ MemberDetail,
36
+ MemberMembership,
37
+ MemberPurchaseList,
38
+ OutOfStudioWorkoutHistoryList,
39
+ StudioServiceList,
40
+ TotalClasses,
41
+ WorkoutList,
42
+ )
43
+
44
+
45
+ class AlreadyBookedError(Exception):
46
+ pass
47
+
15
48
 
16
49
  if typing.TYPE_CHECKING:
17
50
  from loguru import Logger
18
51
 
19
- from otf_api.models.responses.member_detail import MemberDetail
20
- from otf_api.models.responses.studio_detail import StudioDetail
21
52
 
22
53
  API_BASE_URL = "api.orangetheory.co"
23
54
  API_IO_BASE_URL = "api.orangetheory.io"
@@ -51,14 +82,22 @@ class Api:
51
82
  self.member: MemberDetail
52
83
  self.home_studio: StudioDetail
53
84
 
54
- self.user = User.load_from_disk(username, password)
55
- self.session = aiohttp.ClientSession()
85
+ self.user = User.login(username, password)
56
86
 
57
- self.member_api = MemberApi(self)
58
- self.classes_api = ClassesApi(self)
59
- self.studios_api = StudiosApi(self)
60
- self.telemetry_api = TelemtryApi(self)
61
- self.performance_api = PerformanceApi(self)
87
+ headers = {
88
+ "Authorization": f"Bearer {self.user.cognito.id_token}",
89
+ "Content-Type": "application/json",
90
+ "Accept": "application/json",
91
+ }
92
+ self.session = aiohttp.ClientSession(headers=headers)
93
+
94
+ # simplify access to member_id and member_uuid
95
+ self._member_id = self.user.member_id
96
+ self._member_uuid = self.user.member_uuid
97
+ self._perf_api_headers = {
98
+ "koji-member-id": self._member_id,
99
+ "koji-member-email": self.user.id_claims_data.email,
100
+ }
62
101
 
63
102
  @classmethod
64
103
  async def create(cls, username: str, password: str) -> "Api":
@@ -70,11 +109,13 @@ class Api:
70
109
  password (str): The password of the user.
71
110
  """
72
111
  self = cls(username, password)
73
- self.member = await self.member_api.get_member_detail()
74
- self.home_studio = await self.studios_api.get_studio_detail(self.member.home_studio.studio_uuid)
112
+ self.member = await self.get_member_detail()
113
+ self.home_studio = await self.get_studio_detail(self.member.home_studio.studio_uuid)
75
114
  return self
76
115
 
77
116
  def __del__(self) -> None:
117
+ if not hasattr(self, "session"):
118
+ return
78
119
  try:
79
120
  loop = asyncio.get_event_loop()
80
121
  asyncio.create_task(self._close_session()) # noqa
@@ -86,18 +127,6 @@ class Api:
86
127
  if not self.session.closed:
87
128
  await self.session.close()
88
129
 
89
- @property
90
- def _base_headers(self) -> dict[str, str]:
91
- """Get the base headers for the API."""
92
- if not self.user:
93
- raise ValueError("No user is logged in.")
94
-
95
- return {
96
- "Authorization": f"Bearer {self.user.cognito.id_token}",
97
- "Content-Type": "application/json",
98
- "Accept": "application/json",
99
- }
100
-
101
130
  async def _do(
102
131
  self,
103
132
  method: str,
@@ -105,6 +134,7 @@ class Api:
105
134
  url: str,
106
135
  params: dict[str, Any] | None = None,
107
136
  headers: dict[str, str] | None = None,
137
+ **kwargs: Any,
108
138
  ) -> Any:
109
139
  """Perform an API request."""
110
140
 
@@ -115,22 +145,30 @@ class Api:
115
145
 
116
146
  logger.debug(f"Making {method!r} request to {full_url}, params: {params}")
117
147
 
118
- if headers:
119
- headers.update(self._base_headers)
120
- else:
121
- headers = self._base_headers
148
+ text = None
149
+ async with self.session.request(method, full_url, headers=headers, params=params, **kwargs) as response:
150
+ with contextlib.suppress(Exception):
151
+ text = await response.text()
152
+
153
+ try:
154
+ response.raise_for_status()
155
+ except aiohttp.ClientResponseError as e:
156
+ logger.exception(f"Error making request: {e}")
157
+ logger.exception(f"Response: {text}")
158
+ # raise
159
+ except Exception as e:
160
+ logger.exception(f"Error making request: {e}")
161
+ # raise
122
162
 
123
- async with self.session.request(method, full_url, headers=headers, params=params) as response:
124
- response.raise_for_status()
125
163
  return await response.json()
126
164
 
127
165
  async def _classes_request(self, method: str, url: str, params: dict[str, Any] | None = None) -> Any:
128
166
  """Perform an API request to the classes API."""
129
167
  return await self._do(method, API_IO_BASE_URL, url, params)
130
168
 
131
- async def _default_request(self, method: str, url: str, params: dict[str, Any] | None = None) -> Any:
169
+ async def _default_request(self, method: str, url: str, params: dict[str, Any] | None = None, **kwargs: Any) -> Any:
132
170
  """Perform an API request to the default API."""
133
- return await self._do(method, API_BASE_URL, url, params)
171
+ return await self._do(method, API_BASE_URL, url, params, **kwargs)
134
172
 
135
173
  async def _telemetry_request(self, method: str, url: str, params: dict[str, Any] | None = None) -> Any:
136
174
  """Perform an API request to the Telemetry API."""
@@ -141,3 +179,723 @@ class Api:
141
179
  ) -> Any:
142
180
  """Perform an API request to the performance summary API."""
143
181
  return await self._do(method, API_IO_BASE_URL, url, params, headers)
182
+
183
+ async def get_workouts(self) -> WorkoutList:
184
+ """Get the list of workouts from OT Live.
185
+
186
+ Returns:
187
+ WorkoutList: The list of workouts.
188
+
189
+ Info:
190
+ ---
191
+ This returns data from the same api the [OT Live website](https://otlive.orangetheory.com/) uses.
192
+ It is quite a bit of data, and all workouts going back to ~2019. The data includes the class history
193
+ UUID, which can be used to get telemetry data for a specific workout.
194
+ """
195
+
196
+ res = await self._default_request("GET", "/virtual-class/in-studio-workouts")
197
+
198
+ return WorkoutList(workouts=res["data"])
199
+
200
+ async def get_total_classes(self) -> TotalClasses:
201
+ """Get the member's total classes. This is a simple object reflecting the total number of classes attended,
202
+ both in-studio and OT Live.
203
+
204
+ Returns:
205
+ TotalClasses: The member's total classes.
206
+ """
207
+ data = await self._default_request("GET", "/mobile/v1/members/classes/summary")
208
+ return TotalClasses(**data["data"])
209
+
210
+ async def get_classes(
211
+ self,
212
+ studio_uuids: list[str] | None = None,
213
+ include_home_studio: bool = True,
214
+ start_date: str | None = None,
215
+ end_date: str | None = None,
216
+ limit: int | None = None,
217
+ class_type: ClassType | list[ClassType] | None = None,
218
+ exclude_cancelled: bool = False,
219
+ day_of_week: list[DoW] | None = None,
220
+ start_time: list[str] | None = None,
221
+ ) -> OtfClassList:
222
+ """Get the classes for the user.
223
+
224
+ Returns a list of classes that are available for the user, based on the studio UUIDs provided. If no studio
225
+ UUIDs are provided, it will default to the user's home studio.
226
+
227
+ Args:
228
+ studio_uuids (list[str] | None): The studio UUIDs to get the classes for. Default is None, which will\
229
+ default to the user's home studio only.
230
+ include_home_studio (bool): Whether to include the home studio in the classes. Default is True.
231
+ start_date (str | None): The start date to get classes for, in the format "YYYY-MM-DD". Default is None.
232
+ end_date (str | None): The end date to get classes for, in the format "YYYY-MM-DD". Default is None.
233
+ limit (int | None): Limit the number of classes returned. Default is None.
234
+ class_type (ClassType | list[ClassType] | None): The class type to filter by. Default is None. Multiple
235
+ class types can be provided, if there are multiple there will be a call per class type.
236
+ exclude_cancelled (bool): Whether to exclude cancelled classes. Default is False.
237
+ day_of_week (list[DoW] | None): The days of the week to filter by. Default is None.
238
+ start_time (list[str] | None): The start time to filter by. Default is None.
239
+
240
+ Returns:
241
+ OtfClassList: The classes for the user.
242
+ """
243
+
244
+ if not studio_uuids:
245
+ studio_uuids = [self.home_studio.studio_uuid]
246
+ elif include_home_studio and self.home_studio.studio_uuid not in studio_uuids:
247
+ studio_uuids.append(self.home_studio.studio_uuid)
248
+
249
+ path = "/v1/classes"
250
+
251
+ params = {"studio_ids": studio_uuids}
252
+
253
+ classes_resp = await self._classes_request("GET", path, params=params)
254
+ classes_list = OtfClassList(classes=classes_resp["items"])
255
+
256
+ if start_date:
257
+ start_dtme = datetime.strptime(start_date, "%Y-%m-%d") # noqa
258
+ classes_list.classes = [c for c in classes_list.classes if c.starts_at_local >= start_dtme]
259
+
260
+ if end_date:
261
+ end_dtme = datetime.strptime(end_date, "%Y-%m-%d") # noqa
262
+ classes_list.classes = [c for c in classes_list.classes if c.ends_at_local <= end_dtme]
263
+
264
+ if limit:
265
+ classes_list.classes = classes_list.classes[:limit]
266
+
267
+ if class_type and isinstance(class_type, str):
268
+ class_type = [class_type]
269
+
270
+ if day_of_week and not isinstance(day_of_week, list):
271
+ day_of_week = [day_of_week]
272
+
273
+ if start_time and not isinstance(start_time, list):
274
+ start_time = [start_time]
275
+
276
+ if class_type:
277
+ classes_list.classes = [c for c in classes_list.classes if c.class_type in class_type]
278
+
279
+ if exclude_cancelled:
280
+ classes_list.classes = [c for c in classes_list.classes if not c.canceled]
281
+
282
+ for otf_class in classes_list.classes:
283
+ otf_class.is_home_studio = otf_class.studio.id == self.home_studio.studio_uuid
284
+
285
+ if day_of_week:
286
+ classes_list.classes = [c for c in classes_list.classes if c.day_of_week_enum in day_of_week]
287
+
288
+ if start_time:
289
+ classes_list.classes = [
290
+ c for c in classes_list.classes if any(c.time.strip().startswith(t) for t in start_time)
291
+ ]
292
+
293
+ classes_list.classes = list(filter(lambda c: not c.canceled, classes_list.classes))
294
+
295
+ booking_resp = await self.get_bookings(start_date, end_date, status=BookingStatus.Booked)
296
+ booked_classes = {b.otf_class.class_uuid for b in booking_resp.bookings}
297
+
298
+ for otf_class in classes_list.classes:
299
+ otf_class.is_booked = otf_class.ot_class_uuid in booked_classes
300
+
301
+ return classes_list
302
+
303
+ async def book_class(self, class_uuid: str) -> BookClass | typing.Any:
304
+ """Book a class by class_uuid.
305
+
306
+ Args:
307
+ class_uuid (str): The class UUID to book.
308
+
309
+ Returns:
310
+ None: The response is empty.
311
+ """
312
+
313
+ bookings = await self.get_bookings()
314
+
315
+ for booking in bookings.bookings:
316
+ if booking.otf_class.class_uuid == class_uuid:
317
+ raise AlreadyBookedError(f"Class {class_uuid} is already booked.")
318
+
319
+ body = {"classUUId": class_uuid, "confirmed": False, "waitlist": False}
320
+
321
+ resp = await self._default_request("PUT", f"/member/members/{self._member_id}/bookings", json=body)
322
+
323
+ if resp["code"] == "ERROR":
324
+ if resp["data"]["errorCode"] == "603":
325
+ raise AlreadyBookedError(f"Class {class_uuid} is already booked.")
326
+ raise Exception(f"Error booking class {class_uuid}: {json.dumps(resp)}")
327
+
328
+ data = BookClass(**resp["data"])
329
+ return data
330
+
331
+ async def cancel_booking(self, booking_uuid: str) -> CancelBooking:
332
+ """Cancel a class by booking_uuid.
333
+
334
+ Args:
335
+ booking_uuid (str): The booking UUID to cancel.
336
+
337
+ Returns:
338
+ None: The response is empty.
339
+ """
340
+
341
+ params = {"confirmed": "true"}
342
+ resp = await self._default_request(
343
+ "DELETE", f"/member/members/{self._member_id}/bookings/{booking_uuid}", params=params
344
+ )
345
+ return CancelBooking(**resp["data"])
346
+
347
+ async def get_bookings(
348
+ self,
349
+ start_date: date | str | None = None,
350
+ end_date: date | str | None = None,
351
+ status: BookingStatus | None = None,
352
+ limit: int | None = None,
353
+ exclude_cancelled: bool = True,
354
+ exclude_checkedin: bool = True,
355
+ ) -> BookingList:
356
+ """Get the member's bookings.
357
+
358
+ Args:
359
+ start_date (date | str | None): The start date for the bookings. Default is None.
360
+ end_date (date | str | None): The end date for the bookings. Default is None.
361
+ status (BookingStatus | None): The status of the bookings to get. Default is None, which includes\
362
+ all statuses. Only a single status can be provided.
363
+ limit (int | None): The maximum number of bookings to return. Default is None, which returns all\
364
+ bookings.
365
+ exclude_cancelled (bool): Whether to exclude cancelled bookings. Default is True.
366
+ exclude_checkedin (bool): Whether to exclude checked-in bookings. Default is True.
367
+
368
+ Returns:
369
+ BookingList: The member's bookings.
370
+
371
+ Warning:
372
+ ---
373
+ Incorrect statuses do not cause any bad status code, they just return no results.
374
+
375
+ Tip:
376
+ ---
377
+ `CheckedIn` - you must provide dates if you want to get bookings with a status of CheckedIn. If you do not
378
+ provide dates, the endpoint will return no results for this status.
379
+
380
+ Dates Notes:
381
+ ---
382
+ If dates are provided, the endpoint will return bookings where the class date is within the provided
383
+ date range. If no dates are provided, it will go back 45 days and forward about 30 days.
384
+
385
+ Developer Notes:
386
+ ---
387
+ Looking at the code in the app, it appears that this endpoint accepts multiple statuses. Indeed,
388
+ it does not throw an error if you include a list of statuses. However, only the last status in the list is
389
+ used. I'm not sure if this is a bug or if the API is supposed to work this way.
390
+ """
391
+
392
+ if exclude_cancelled and status == BookingStatus.Cancelled:
393
+ logger.warning(
394
+ "Cannot exclude cancelled bookings when status is Cancelled. Setting exclude_cancelled to False."
395
+ )
396
+ exclude_cancelled = False
397
+
398
+ if isinstance(start_date, date):
399
+ start_date = start_date.isoformat()
400
+
401
+ if isinstance(end_date, date):
402
+ end_date = end_date.isoformat()
403
+
404
+ status_value = status.value if status else None
405
+
406
+ params = {"startDate": start_date, "endDate": end_date, "statuses": status_value}
407
+
408
+ res = await self._default_request("GET", f"/member/members/{self._member_id}/bookings", params=params)
409
+
410
+ bookings = res["data"][:limit] if limit else res["data"]
411
+
412
+ data = BookingList(bookings=bookings)
413
+ data.bookings = sorted(data.bookings, key=lambda x: x.otf_class.starts_at_local)
414
+
415
+ for booking in data.bookings:
416
+ if not booking.otf_class:
417
+ continue
418
+ if booking.otf_class.studio.studio_uuid == self.home_studio.studio_uuid:
419
+ booking.is_home_studio = True
420
+ else:
421
+ booking.is_home_studio = False
422
+
423
+ if exclude_cancelled:
424
+ data.bookings = [b for b in data.bookings if b.status != BookingStatus.Cancelled]
425
+
426
+ if exclude_checkedin:
427
+ data.bookings = [b for b in data.bookings if b.status != BookingStatus.CheckedIn]
428
+
429
+ return data
430
+
431
+ async def _get_bookings_old(self, status: BookingStatus | None = None) -> BookingList:
432
+ """Get the member's bookings.
433
+
434
+ Args:
435
+ status (BookingStatus | None): The status of the bookings to get. Default is None, which includes
436
+ all statuses. Only a single status can be provided.
437
+
438
+ Returns:
439
+ BookingList: The member's bookings.
440
+
441
+ Raises:
442
+ ValueError: If an unaccepted status is provided.
443
+
444
+ Notes:
445
+ ---
446
+ This one is called with the param named 'status'. Dates cannot be provided, because if the endpoint
447
+ receives a date, it will return as if the param name was 'statuses'.
448
+
449
+ Note: This seems to only work for Cancelled, Booked, CheckedIn, and Waitlisted statuses. If you provide
450
+ a different status, it will return all bookings, not filtered by status. The results in this scenario do
451
+ not line up with the `get_bookings` with no status provided, as that returns fewer records. Likely the
452
+ filtered dates are different on the backend.
453
+
454
+ My guess: the endpoint called with dates and 'statuses' is a "v2" kind of thing, where they upgraded without
455
+ changing the version of the api. Calling it with no dates and a singular (limited) status is probably v1.
456
+
457
+ I'm leaving this in here for reference, but marking it private. I just don't want to have to puzzle over
458
+ this again if I remove it and forget about it.
459
+
460
+ """
461
+
462
+ if status and status not in [
463
+ BookingStatus.Cancelled,
464
+ BookingStatus.Booked,
465
+ BookingStatus.CheckedIn,
466
+ BookingStatus.Waitlisted,
467
+ ]:
468
+ raise ValueError(
469
+ "Invalid status provided. Only Cancelled, Booked, CheckedIn, Waitlisted, and None are supported."
470
+ )
471
+
472
+ status_value = status.value if status else None
473
+
474
+ params = {"status": status_value}
475
+
476
+ res = await self._default_request("GET", f"/member/members/{self._member_id}/bookings", params=params)
477
+
478
+ return BookingList(bookings=res["data"])
479
+
480
+ async def get_challenge_tracker_content(self) -> ChallengeTrackerContent:
481
+ """Get the member's challenge tracker content.
482
+
483
+ Returns:
484
+ ChallengeTrackerContent: The member's challenge tracker content.
485
+ """
486
+ data = await self._default_request("GET", f"/challenges/v3.1/member/{self._member_id}")
487
+ return ChallengeTrackerContent(**data["Dto"])
488
+
489
+ async def get_challenge_tracker_detail(
490
+ self, equipment_id: EquipmentType, challenge_type_id: ChallengeType, challenge_sub_type_id: int = 0
491
+ ) -> ChallengeTrackerDetailList:
492
+ """Get the member's challenge tracker details.
493
+
494
+ Args:
495
+ equipment_id (EquipmentType): The equipment ID.
496
+ challenge_type_id (ChallengeType): The challenge type ID.
497
+ challenge_sub_type_id (int): The challenge sub type ID. Default is 0.
498
+
499
+ Returns:
500
+ ChallengeTrackerDetailList: The member's challenge tracker details.
501
+
502
+ Notes:
503
+ ---
504
+ I'm not sure what the challenge_sub_type_id is supposed to be, so it defaults to 0.
505
+
506
+ """
507
+ params = {
508
+ "equipmentId": equipment_id.value,
509
+ "challengeTypeId": challenge_type_id.value,
510
+ "challengeSubTypeId": challenge_sub_type_id,
511
+ }
512
+
513
+ data = await self._default_request("GET", f"/challenges/v3/member/{self._member_id}/benchmarks", params=params)
514
+
515
+ return ChallengeTrackerDetailList(details=data["Dto"])
516
+
517
+ async def get_challenge_tracker_participation(self, challenge_type_id: ChallengeType) -> typing.Any:
518
+ """Get the member's participation in a challenge.
519
+
520
+ Args:
521
+ challenge_type_id (ChallengeType): The challenge type ID.
522
+
523
+ Returns:
524
+ Any: The member's participation in the challenge.
525
+
526
+ Notes:
527
+ ---
528
+ I've never gotten this to return anything other than invalid response. I'm not sure if it's a bug
529
+ in my code or the API.
530
+
531
+ """
532
+ params = {"challengeTypeId": challenge_type_id.value}
533
+
534
+ data = await self._default_request(
535
+ "GET", f"/challenges/v1/member/{self._member_id}/participation", params=params
536
+ )
537
+ return data
538
+
539
+ async def get_member_detail(
540
+ self, include_addresses: bool = True, include_class_summary: bool = True, include_credit_card: bool = False
541
+ ) -> MemberDetail:
542
+ """Get the member details.
543
+
544
+ Args:
545
+ include_addresses (bool): Whether to include the member's addresses in the response.
546
+ include_class_summary (bool): Whether to include the member's class summary in the response.
547
+ include_credit_card (bool): Whether to include the member's credit card information in the response.
548
+
549
+ Returns:
550
+ MemberDetail: The member details.
551
+
552
+
553
+ Notes:
554
+ ---
555
+ The include_addresses, include_class_summary, and include_credit_card parameters are optional and determine
556
+ what additional information is included in the response. By default, all additional information is included,
557
+ with the exception of the credit card information.
558
+
559
+ The base member details include the last four of a credit card regardless of the include_credit_card,
560
+ although this is not always the same details as what is in the member_credit_card field. There doesn't seem
561
+ to be a way to exclude this information, and I do not know which is which or why they differ.
562
+ """
563
+
564
+ include: list[str] = []
565
+ if include_addresses:
566
+ include.append("memberAddresses")
567
+
568
+ if include_class_summary:
569
+ include.append("memberClassSummary")
570
+
571
+ if include_credit_card:
572
+ include.append("memberCreditCard")
573
+
574
+ params = {"include": ",".join(include)} if include else None
575
+
576
+ data = await self._default_request("GET", f"/member/members/{self._member_id}", params=params)
577
+ return MemberDetail(**data["data"])
578
+
579
+ async def get_member_membership(self) -> MemberMembership:
580
+ """Get the member's membership details.
581
+
582
+ Returns:
583
+ MemberMembership: The member's membership details.
584
+ """
585
+
586
+ data = await self._default_request("GET", f"/member/members/{self._member_id}/memberships")
587
+ return MemberMembership(**data["data"])
588
+
589
+ async def get_member_purchases(self) -> MemberPurchaseList:
590
+ """Get the member's purchases, including monthly subscriptions and class packs.
591
+
592
+ Returns:
593
+ MemberPurchaseList: The member's purchases.
594
+ """
595
+ data = await self._default_request("GET", f"/member/members/{self._member_id}/purchases")
596
+ return MemberPurchaseList(data=data["data"])
597
+
598
+ async def get_member_lifetime_stats(self, select_time: StatsTime = StatsTime.AllTime) -> StatsResponse:
599
+ """Get the member's lifetime stats.
600
+
601
+ Args:
602
+ select_time (StatsTime): The time period to get stats for. Default is StatsTime.AllTime.
603
+
604
+ Notes:
605
+ ---
606
+ The time period provided in the path does not do anything, and the endpoint always returns the same data.
607
+ It is being provided anyway, in case this changes in the future.
608
+
609
+ Returns:
610
+ Any: The member's lifetime stats.
611
+ """
612
+
613
+ data = await self._default_request("GET", f"/performance/v2/{self._member_id}/over-time/{select_time.value}")
614
+
615
+ stats = StatsResponse(**data["data"])
616
+ return stats
617
+
618
+ async def get_out_of_studio_workout_history(self) -> OutOfStudioWorkoutHistoryList:
619
+ """Get the member's out of studio workout history.
620
+
621
+ Returns:
622
+ OutOfStudioWorkoutHistoryList: The member's out of studio workout history.
623
+ """
624
+ data = await self._default_request("GET", f"/member/members/{self._member_id}/out-of-studio-workout")
625
+
626
+ return OutOfStudioWorkoutHistoryList(data=data["data"])
627
+
628
+ async def get_favorite_studios(self) -> FavoriteStudioList:
629
+ """Get the member's favorite studios.
630
+
631
+ Returns:
632
+ FavoriteStudioList: The member's favorite studios.
633
+ """
634
+ data = await self._default_request("GET", f"/member/members/{self._member_id}/favorite-studios")
635
+
636
+ return FavoriteStudioList(studios=data["data"])
637
+
638
+ async def get_latest_agreement(self) -> LatestAgreement:
639
+ """Get the latest agreement for the member.
640
+
641
+ Returns:
642
+ LatestAgreement: The agreement.
643
+
644
+ Notes:
645
+ ---
646
+ In this context, "latest" means the most recent agreement with a specific ID, not the most recent agreement
647
+ in general. The agreement ID is hardcoded in the endpoint, so it will always return the same agreement.
648
+ """
649
+ data = await self._default_request("GET", "/member/agreements/9d98fb27-0f00-4598-ad08-5b1655a59af6")
650
+ return LatestAgreement(**data["data"])
651
+
652
+ async def get_studio_services(self, studio_uuid: str | None = None) -> StudioServiceList:
653
+ """Get the services available at a specific studio. If no studio UUID is provided, the member's home studio
654
+ will be used.
655
+
656
+ Args:
657
+ studio_uuid (str): The studio UUID to get services for. Default is None, which will use the member's home\
658
+ studio.
659
+
660
+ Returns:
661
+ StudioServiceList: The services available at the studio.
662
+ """
663
+ studio_uuid = studio_uuid or self.home_studio.studio_uuid
664
+ data = await self._default_request("GET", f"/member/studios/{studio_uuid}/services")
665
+ return StudioServiceList(data=data["data"])
666
+
667
+ async def get_performance_summaries(self, limit: int = 30) -> PerformanceSummaryList:
668
+ """Get a list of performance summaries for the authenticated user.
669
+
670
+ Args:
671
+ limit (int): The maximum number of performance summaries to return. Defaults to 30.
672
+
673
+ Returns:
674
+ PerformanceSummaryList: A list of performance summaries.
675
+
676
+ Developer Notes:
677
+ ---
678
+ In the app, this is referred to as 'getInStudioWorkoutHistory'.
679
+
680
+ """
681
+
682
+ path = "/v1/performance-summaries"
683
+ params = {"limit": limit}
684
+ res = await self._performance_summary_request("GET", path, headers=self._perf_api_headers, params=params)
685
+ retval = PerformanceSummaryList(summaries=res["items"])
686
+ return retval
687
+
688
+ async def get_performance_summary(self, performance_summary_id: str) -> PerformanceSummaryDetail:
689
+ """Get a detailed performance summary for a given workout.
690
+
691
+ Args:
692
+ performance_summary_id (str): The ID of the performance summary to retrieve.
693
+
694
+ Returns:
695
+ PerformanceSummaryDetail: A detailed performance summary.
696
+ """
697
+
698
+ path = f"/v1/performance-summaries/{performance_summary_id}"
699
+ res = await self._performance_summary_request("GET", path, headers=self._perf_api_headers)
700
+ retval = PerformanceSummaryDetail(**res)
701
+ return retval
702
+
703
+ async def get_studio_detail(self, studio_uuid: str | None = None) -> StudioDetail:
704
+ """Get detailed information about a specific studio. If no studio UUID is provided, it will default to the
705
+ user's home studio.
706
+
707
+ Args:
708
+ studio_uuid (str): Studio UUID to get details for. Defaults to None, which will default to the user's home\
709
+ studio.
710
+
711
+ Returns:
712
+ StudioDetail: Detailed information about the studio.
713
+ """
714
+ studio_uuid = studio_uuid or self.home_studio.studio_uuid
715
+
716
+ path = f"/mobile/v1/studios/{studio_uuid}"
717
+ params = {"include": "locations"}
718
+
719
+ res = await self._default_request("GET", path, params=params)
720
+ return StudioDetail(**res["data"])
721
+
722
+ async def search_studios_by_geo(
723
+ self,
724
+ latitude: float | None = None,
725
+ longitude: float | None = None,
726
+ distance: float = 50,
727
+ page_index: int = 1,
728
+ page_size: int = 50,
729
+ ) -> StudioDetailList:
730
+ """Search for studios by geographic location.
731
+
732
+ Args:
733
+ latitude (float, optional): Latitude of the location to search around, if None uses home studio latitude.
734
+ longitude (float, optional): Longitude of the location to search around, if None uses home studio longitude.
735
+ distance (float, optional): Distance in miles to search around the location. Defaults to 50.
736
+ page_index (int, optional): Page index to start at. Defaults to 1.
737
+ page_size (int, optional): Number of results per page. Defaults to 50.
738
+
739
+ Returns:
740
+ StudioDetailList: List of studios that match the search criteria.
741
+
742
+ Notes:
743
+ ---
744
+ There does not seem to be a limit to the number of results that can be requested total or per page, the
745
+ library enforces a limit of 50 results per page to avoid potential rate limiting issues.
746
+
747
+ """
748
+ path = "/mobile/v1/studios"
749
+
750
+ latitude = latitude or self.home_studio.studio_location.latitude
751
+ longitude = longitude or self.home_studio.studio_location.longitude
752
+
753
+ if page_size > 50:
754
+ self.logger.warning("The API does not support more than 50 results per page, limiting to 50.")
755
+ page_size = 50
756
+
757
+ if page_index < 1:
758
+ self.logger.warning("Page index must be greater than 0, setting to 1.")
759
+ page_index = 1
760
+
761
+ params = {
762
+ "pageIndex": page_index,
763
+ "pageSize": page_size,
764
+ "latitude": latitude,
765
+ "longitude": longitude,
766
+ "distance": distance,
767
+ }
768
+
769
+ all_results: list[StudioDetail] = []
770
+
771
+ while True:
772
+ res = await self._default_request("GET", path, params=params)
773
+ pagination = Pagination(**res["data"].pop("pagination"))
774
+ all_results.extend([StudioDetail(**studio) for studio in res["data"]["studios"]])
775
+
776
+ if len(all_results) == pagination.total_count:
777
+ break
778
+
779
+ params["pageIndex"] += 1
780
+
781
+ return StudioDetailList(studios=all_results)
782
+
783
+ async def get_hr_history(self) -> TelemetryHrHistory:
784
+ """Get the heartrate history for the user.
785
+
786
+ Returns a list of history items that contain the max heartrate, start/end bpm for each zone,
787
+ the change from the previous, the change bucket, and the assigned at time.
788
+
789
+ Returns:
790
+ TelemetryHrHistory: The heartrate history for the user.
791
+
792
+ """
793
+ path = "/v1/physVars/maxHr/history"
794
+
795
+ params = {"memberUuid": self._member_id}
796
+ res = await self._telemetry_request("GET", path, params=params)
797
+ return TelemetryHrHistory(**res)
798
+
799
+ async def get_max_hr(self) -> TelemetryMaxHr:
800
+ """Get the max heartrate for the user.
801
+
802
+ Returns a simple object that has the member_uuid and the max_hr.
803
+
804
+ Returns:
805
+ TelemetryMaxHr: The max heartrate for the user.
806
+ """
807
+ path = "/v1/physVars/maxHr"
808
+
809
+ params = {"memberUuid": self._member_id}
810
+
811
+ res = await self._telemetry_request("GET", path, params=params)
812
+ return TelemetryMaxHr(**res)
813
+
814
+ async def get_telemetry(self, class_history_uuid: str, max_data_points: int = 0) -> Telemetry:
815
+ """Get the telemetry for a class history.
816
+
817
+ This returns an object that contains the max heartrate, start/end bpm for each zone,
818
+ and a list of telemetry items that contain the heartrate, splat points, calories, and timestamp.
819
+
820
+ Args:
821
+ class_history_uuid (str): The class history UUID.
822
+ max_data_points (int): The max data points to use for the telemetry. Default is 0, which will attempt to\
823
+ get the max data points from the workout. If the workout is not found, it will default to 120 data points.
824
+
825
+ Returns:
826
+ TelemetryItem: The telemetry for the class history.
827
+
828
+ """
829
+ path = "/v1/performance/summary"
830
+
831
+ max_data_points = max_data_points or await self._get_max_data_points(class_history_uuid)
832
+
833
+ params = {"classHistoryUuid": class_history_uuid, "maxDataPoints": max_data_points}
834
+ res = await self._telemetry_request("GET", path, params=params)
835
+ return Telemetry(**res)
836
+
837
+ async def _get_max_data_points(self, class_history_uuid: str) -> int:
838
+ """Get the max data points to use for the telemetry.
839
+
840
+ Attempts to get the amount of active time for the workout from the OT Live API. If the workout is not found,
841
+ it will default to 120 data points. If it is found, it will calculate the amount of data points needed based on
842
+ the active time. This should amount to a data point per 30 seconds, roughly.
843
+
844
+ Args:
845
+ class_history_uuid (str): The class history UUID.
846
+
847
+ Returns:
848
+ int: The max data points to use.
849
+ """
850
+ workouts = await self.get_workouts()
851
+ workout = workouts.by_class_history_uuid.get(class_history_uuid)
852
+ max_data_points = 120 if workout is None else ceil(active_time_to_data_points(workout.active_time))
853
+ return max_data_points
854
+
855
+ # the below do not return any data for me, so I can't test them
856
+
857
+ async def _get_member_services(self, active_only: bool = True) -> typing.Any:
858
+ """Get the member's services.
859
+
860
+ Args:
861
+ active_only (bool): Whether to only include active services. Default is True.
862
+
863
+ Returns:
864
+ Any: The member's service
865
+ ."""
866
+ active_only_str = "true" if active_only else "false"
867
+ data = await self._default_request(
868
+ "GET", f"/member/members/{self._member_id}/services", params={"activeOnly": active_only_str}
869
+ )
870
+ return data
871
+
872
+ async def _get_aspire_data(self, datetime: str | None = None, unit: str | None = None) -> typing.Any:
873
+ """Get data from the member's aspire wearable.
874
+
875
+ Note: I don't have an aspire wearable, so I can't test this.
876
+
877
+ Args:
878
+ datetime (str | None): The date and time to get data for. Default is None.
879
+ unit (str | None): The measurement unit. Default is None.
880
+
881
+ Returns:
882
+ Any: The member's aspire data.
883
+ """
884
+ params = {"datetime": datetime, "unit": unit}
885
+
886
+ data = self._default_request("GET", f"/member/wearables/{self._member_id}/wearable-daily", params=params)
887
+ return data
888
+
889
+ async def get_body_composition_list(self) -> BodyCompositionList:
890
+ """Get the member's body composition list.
891
+
892
+ Returns:
893
+ Any: The member's body composition list.
894
+ """
895
+ data = await self._default_request("GET", f"/member/members/{self._member_uuid}/body-composition")
896
+
897
+ return BodyCompositionList(data=data["data"])
898
+
899
+
900
+ def active_time_to_data_points(active_time: int) -> float:
901
+ return active_time / 60 * 2