-
-
Notifications
You must be signed in to change notification settings - Fork 479
Expand file tree
/
Copy path__init__.py
More file actions
3205 lines (2682 loc) · 129 KB
/
Copy path__init__.py
File metadata and controls
3205 lines (2682 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Python 3 API wrapper for Garmin Connect."""
import contextlib
import functools
import logging
import numbers
import os
import random
import re
import shutil
import time
from collections.abc import Callable
from datetime import UTC, date, datetime, timedelta
from enum import Enum, auto
from pathlib import Path
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from .typed import TypedGarmin
import requests
from requests import HTTPError
from . import client
from .fit import FitEncoderWeight # type: ignore
logger = logging.getLogger(__name__)
# Regex used to extract an HTTP status code from the client's error messages.
# The underlying client raises GarminConnectConnectionError with a message of
# the form "API Error {status} - {detail}", so we parse it to decide whether
# a failure is retryable (5xx) or not (4xx, auth, etc.).
_STATUS_CODE_RE = re.compile(r"(?:API Error|Error|HTTP)\s*(\d{3})")
# Constants for validation
MAX_ACTIVITY_LIMIT = 1000
MAX_HYDRATION_ML = 10000 # 10 liters
DATE_FORMAT_REGEX = r"^\d{4}-\d{2}-\d{2}$"
DATE_FORMAT_STR = "%Y-%m-%d"
VALID_WEIGHT_UNITS = {"kg", "lbs"}
# Add validation utilities
def _validate_date_format(date_str: str, param_name: str = "date") -> str:
"""Validate date string format YYYY-MM-DD."""
if not isinstance(date_str, str):
raise ValueError(f"{param_name} must be a string")
# Remove any extra whitespace
date_str = date_str.strip()
if not re.fullmatch(DATE_FORMAT_REGEX, date_str):
raise ValueError(
f"{param_name} must be in format 'YYYY-MM-DD', got: {date_str}"
)
try:
# Validate that it's a real date
datetime.strptime(date_str, DATE_FORMAT_STR)
except ValueError as e:
raise ValueError(f"invalid {param_name}: {e}") from e
return date_str
def _validate_positive_number(
value: int | float, param_name: str = "value"
) -> int | float:
"""Validate that a number is positive."""
if not isinstance(value, numbers.Real):
raise ValueError(f"{param_name} must be a number")
if isinstance(value, bool):
raise ValueError(f"{param_name} must be a number, not bool")
if value <= 0:
raise ValueError(f"{param_name} must be positive, got: {value}")
return value
def _validate_non_negative_integer(value: int, param_name: str = "value") -> int:
"""Validate that a value is a non-negative integer."""
if not isinstance(value, int) or isinstance(value, bool):
raise ValueError(f"{param_name} must be an integer")
if value < 0:
raise ValueError(f"{param_name} must be non-negative, got: {value}")
return value
def _validate_positive_integer(value: int, param_name: str = "value") -> int:
"""Validate that a value is a positive integer."""
if not isinstance(value, int) or isinstance(value, bool):
raise ValueError(f"{param_name} must be an integer")
if value <= 0:
raise ValueError(f"{param_name} must be a positive integer, got: {value}")
return value
def _fmt_ts(dt: datetime) -> str:
# Use ms precision to match server expectations
return dt.replace(tzinfo=None).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]
def _validate_json_exists(response: requests.Response) -> dict[str, Any] | None:
if response.status_code == 204:
return None
return response.json()
def _extract_status_code(exc: BaseException) -> int | None:
"""Best-effort extraction of an HTTP status code from an exception.
Checks ``status_code`` and ``response.status_code`` attributes, then
parses ``"API Error NNN"`` / ``"HTTP NNN"`` patterns out of the message
(the client raises ``GarminConnectConnectionError`` with messages like
``"API Error 503 - ..."``).
"""
status = getattr(exc, "status_code", None)
if isinstance(status, int):
return status
resp = getattr(exc, "response", None)
status = getattr(resp, "status_code", None)
if isinstance(status, int):
return status
match = _STATUS_CODE_RE.search(str(exc))
return int(match.group(1)) if match else None
def _has_network_cause(exc: BaseException) -> bool:
"""Walk ``__cause__`` / ``__context__`` looking for a raw network error."""
seen: set[int] = set()
cur: BaseException | None = exc
while cur is not None and id(cur) not in seen:
seen.add(id(cur))
if isinstance(cur, requests.ConnectionError | requests.Timeout):
return True
cur = cur.__cause__ or cur.__context__
return False
def _is_retryable(exc: BaseException) -> bool:
"""Return True for transient errors worth retrying.
Retries 5xx server errors and genuine network failures. Never retries
401 (auth), 429 (rate-limit) or 4xx (client) errors — those are
deterministic and caller-actionable.
"""
if isinstance(
exc, GarminConnectAuthenticationError | GarminConnectTooManyRequestsError
):
return False
if isinstance(exc, GarminConnectConnectionError):
status = _extract_status_code(exc)
if status is None:
return _has_network_cause(exc)
return 500 <= status < 600
return isinstance(exc, requests.ConnectionError | requests.Timeout)
def _backoff_delay(attempt: int, obj: Any) -> float:
"""Exponential backoff with 50-100% jitter, bounded by ``retry_max_wait``."""
min_wait = getattr(obj, "retry_min_wait", 1.0)
max_wait = getattr(obj, "retry_max_wait", 10.0)
base = min(max_wait, min_wait * (2**attempt))
return base * (0.5 + random.random() * 0.5) # noqa: S311 jitter, not crypto
def _handle_api_errors(
label: str,
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
"""Decorator: uniform error translation + optional retry for Garmin API calls.
Translates transport-level exceptions to domain-specific
``GarminConnectAuthenticationError`` (401), ``GarminConnectTooManyRequestsError``
(429) or ``GarminConnectConnectionError`` (all other HTTP / network failures),
preserving the original ``.response`` where available so callers can still
introspect the underlying response.
Retries are controlled by ``self.retry_attempts`` (default ``3``; set to
``0`` to disable). When enabled, only 5xx server errors and raw connection
/ timeout failures are retried, with exponential backoff plus jitter
between ``retry_min_wait`` and ``retry_max_wait`` seconds. 401 / 429 / 4xx
always fail fast.
"""
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(func)
def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
path = args[0] if args else kwargs.get("path", "<unknown>")
attempts = max(0, getattr(self, "retry_attempts", 0))
for attempt in range(attempts + 1):
try:
return func(self, *args, **kwargs)
except (
GarminConnectAuthenticationError,
GarminConnectTooManyRequestsError,
):
# Already domain-specific and never retryable.
raise
except (HTTPError, GarminConnectConnectionError) as e:
status = _extract_status_code(e)
if status == 401:
raise GarminConnectAuthenticationError(
f"Authentication failed: {e}"
) from e
if status == 429:
raise GarminConnectTooManyRequestsError(
f"Rate limit exceeded: {e}"
) from e
if status and 400 <= status < 500:
new_exc = GarminConnectConnectionError(
f"{label} client error ({status}): {e}"
)
resp = getattr(e, "response", None)
if resp is not None:
new_exc.response = resp # type: ignore[attr-defined]
raise new_exc from e
# 5xx or no parseable status — retryable path.
if attempt < attempts:
delay = _backoff_delay(attempt, self)
logger.warning(
"%s attempt %d/%d failed (path=%s status=%s) — "
"retrying in %.1fs: %s",
label,
attempt + 1,
attempts + 1,
path,
status,
delay,
e,
)
time.sleep(delay)
continue
logger.exception(
"%s failed for path '%s' (status=%s)", label, path, status
)
new_exc = GarminConnectConnectionError(f"{label} HTTP error: {e}")
resp = getattr(e, "response", None)
if resp is not None:
new_exc.response = resp # type: ignore[attr-defined]
raise new_exc from e
except (requests.ConnectionError, requests.Timeout) as e:
if attempt < attempts:
delay = _backoff_delay(attempt, self)
logger.warning(
"%s network error attempt %d/%d (path=%s) — "
"retrying in %.1fs: %s",
label,
attempt + 1,
attempts + 1,
path,
delay,
e,
)
time.sleep(delay)
continue
logger.exception("Network error during %s path=%s", label, path)
raise GarminConnectConnectionError(f"Connection error: {e}") from e
except Exception as e:
logger.exception("Connection error during %s path=%s", label, path)
raise GarminConnectConnectionError(f"Connection error: {e}") from e
# Unreachable: loop returns, retries, or raises.
raise RuntimeError(f"{label} retry loop exited without a result")
return wrapper
return decorator
class Garmin:
"""Class for fetching data from Garmin Connect."""
def __init__(
self,
email: str | None = None,
password: str | None = None,
is_cn: bool = False,
prompt_mfa: Callable[[], str] | None = None,
return_on_mfa: bool = False,
retry_attempts: int = 3,
retry_min_wait: float = 1.0,
retry_max_wait: float = 10.0,
verify_login: bool = True,
) -> None:
"""Create a new class instance.
:param retry_attempts: Retries for transient 5xx / network errors on
``connectapi``, ``connectwebproxy`` and ``download``. Defaults to
``3``; set to ``0`` to disable. 401, 429 and 4xx always fail fast
regardless.
:param retry_min_wait: Initial backoff in seconds; grows exponentially
with jitter between attempts.
:param retry_max_wait: Upper bound on the backoff in seconds.
:param verify_login: When ``True`` (default), each login strategy's
token is validated against the API tier before the chain accepts
it, so a token the API rejects (401/403) is discarded and the next
strategy is tried. Set ``False`` for the legacy "first token wins"
behavior.
"""
# Validate input types
if email is not None and not isinstance(email, str):
raise ValueError("email must be a string or None")
if password is not None and not isinstance(password, str):
raise ValueError("password must be a string or None")
if not isinstance(is_cn, bool):
raise ValueError("is_cn must be a boolean")
if not isinstance(return_on_mfa, bool):
raise ValueError("return_on_mfa must be a boolean")
if isinstance(retry_attempts, bool) or not isinstance(retry_attempts, int):
raise ValueError("retry_attempts must be an int")
if retry_attempts < 0:
raise ValueError("retry_attempts must be non-negative")
if not isinstance(verify_login, bool):
raise ValueError("verify_login must be a boolean")
self.username = email
self.password = password
self.is_cn = is_cn
self.prompt_mfa = prompt_mfa
self.return_on_mfa = return_on_mfa
self.retry_attempts = retry_attempts
self.retry_min_wait = float(retry_min_wait)
self.retry_max_wait = float(retry_max_wait)
self.verify_login = verify_login
self.garmin_connect_user_settings_url = (
"/userprofile-service/userprofile/user-settings"
)
self.garmin_connect_userprofile_settings_url = (
"/userprofile-service/userprofile/settings"
)
self.garmin_connect_devices_url = "/device-service/deviceregistration/devices"
self.garmin_connect_device_url = "/device-service/deviceservice"
self.garmin_connect_primary_device_url = (
"/web-gateway/device-info/primary-training-device"
)
self.garmin_connect_solar_url = "/web-gateway/solar"
self.garmin_connect_weight_url = "/weight-service"
self.garmin_connect_daily_summary_url = "/usersummary-service/usersummary/daily"
self.garmin_connect_metrics_url = "/metrics-service/metrics/maxmet/daily"
self.garmin_connect_biometric_url = "/biometric-service/biometric"
self.garmin_connect_biometric_stats_url = "/biometric-service/stats"
self.garmin_connect_heart_rate_zones_url = "/biometric-service/heartRateZones"
self.garmin_connect_power_zones_url = "/biometric-service/powerZones"
self.garmin_connect_daily_hydration_url = (
"/usersummary-service/usersummary/hydration/daily"
)
self.garmin_connect_set_hydration_url = (
"/usersummary-service/usersummary/hydration/log"
)
self.garmin_connect_daily_stats_steps_url = (
"/usersummary-service/stats/steps/daily"
)
self.garmin_connect_weekly_stats_steps_url = (
"/usersummary-service/stats/steps/weekly"
)
self.garmin_connect_weekly_stats_stress_url = (
"/usersummary-service/stats/stress/weekly"
)
self.garmin_connect_weekly_stats_intensity_minutes_url = (
"/usersummary-service/stats/im/weekly"
)
self.garmin_connect_personal_record_url = (
"/personalrecord-service/personalrecord/prs"
)
self.garmin_connect_earned_badges_url = "/badge-service/badge/earned"
self.garmin_connect_available_badges_url = "/badge-service/badge/available"
self.garmin_connect_adhoc_challenges_url = (
"/adhocchallenge-service/adHocChallenge/historical"
)
self.garmin_connect_badge_challenges_url = (
"/badgechallenge-service/badgeChallenge/completed"
)
self.garmin_connect_available_badge_challenges_url = (
"/badgechallenge-service/badgeChallenge/available"
)
self.garmin_connect_non_completed_badge_challenges_url = (
"/badgechallenge-service/badgeChallenge/non-completed"
)
self.garmin_connect_inprogress_virtual_challenges_url = (
"/badgechallenge-service/virtualChallenge/inProgress"
)
self.garmin_connect_daily_sleep_url = (
"/wellness-service/wellness/dailySleepData"
)
self.garmin_connect_daily_stress_url = "/wellness-service/wellness/dailyStress"
self.garmin_connect_hill_score_url = "/metrics-service/metrics/hillscore"
self.garmin_connect_daily_body_battery_url = (
"/wellness-service/wellness/bodyBattery/reports/daily"
)
self.garmin_connect_body_battery_events_url = (
"/wellness-service/wellness/bodyBattery/events"
)
self.garmin_connect_blood_pressure_endpoint = (
"/bloodpressure-service/bloodpressure/range"
)
self.garmin_connect_set_blood_pressure_endpoint = (
"/bloodpressure-service/bloodpressure"
)
self.garmin_connect_endurance_score_url = (
"/metrics-service/metrics/endurancescore"
)
self.garmin_connect_running_tolerance_url = (
"/metrics-service/metrics/runningtolerance/stats"
)
self.garmin_connect_menstrual_calendar_url = (
"/periodichealth-service/menstrualcycle/calendar"
)
self.garmin_connect_menstrual_dayview_url = (
"/periodichealth-service/menstrualcycle/dayview"
)
self.garmin_connect_pregnancy_snapshot_url = (
"/periodichealth-service/menstrualcycle/pregnancysnapshot"
)
self.garmin_connect_goals_url = "/goal-service/goal/goals"
self.garmin_connect_rhr_url = "/userstats-service/wellness/daily"
self.garmin_connect_hrv_url = "/hrv-service/hrv"
self.garmin_connect_training_readiness_url = (
"/metrics-service/metrics/trainingreadiness"
)
self.garmin_connect_race_predictor_url = (
"/metrics-service/metrics/racepredictions"
)
self.garmin_connect_training_status_url = (
"/metrics-service/metrics/trainingstatus/aggregated"
)
self.garmin_connect_user_summary_chart = (
"/wellness-service/wellness/dailySummaryChart"
)
self.garmin_connect_floors_chart_daily_url = (
"/wellness-service/wellness/floorsChartData/daily"
)
self.garmin_connect_heartrates_daily_url = (
"/wellness-service/wellness/dailyHeartRate"
)
self.garmin_connect_daily_respiration_url = (
"/wellness-service/wellness/daily/respiration"
)
self.garmin_connect_daily_spo2_url = "/wellness-service/wellness/daily/spo2"
self.garmin_connect_daily_intensity_minutes = (
"/wellness-service/wellness/daily/im"
)
self.garmin_daily_events_url = "/wellness-service/wellness/dailyEvents"
self.garmin_connect_activities = (
"/activitylist-service/activities/search/activities"
)
self.garmin_connect_activities_count = "/activitylist-service/activities/count"
self.garmin_connect_activities_baseurl = "/activitylist-service/activities/"
self.garmin_connect_activity = "/activity-service/activity"
self.garmin_connect_activity_types = "/activity-service/activity/activityTypes"
self.garmin_connect_activity_fordate = "/mobile-gateway/heartRate/forDate"
self.garmin_connect_fitnessstats = "/fitnessstats-service/activity"
self.garmin_connect_fitnessage = "/fitnessage-service/fitnessage"
self.garmin_connect_fit_download = "/download-service/files/activity"
self.garmin_connect_tcx_download = "/download-service/export/tcx/activity"
self.garmin_connect_gpx_download = "/download-service/export/gpx/activity"
self.garmin_connect_kml_download = "/download-service/export/kml/activity"
self.garmin_connect_csv_download = "/download-service/export/csv/activity"
self.garmin_connect_upload = "/upload-service/upload"
self.garmin_connect_gear = "/gear-service/gear/filterGear"
self.garmin_connect_gear_baseurl = "/gear-service/gear"
self.garmin_request_reload_url = "/wellness-service/wellness/epoch/request"
self.garmin_workouts = "/workout-service"
self.garmin_workouts_schedule_url = f"{self.garmin_workouts}/schedule"
self.garmin_calendar = "/calendar-service"
self.garmin_scheduled_workouts_url = f"{self.garmin_calendar}"
self.garmin_nutrition = "/nutrition-service"
self.garmin_connect_nutrition_daily_food_logs = (
f"{self.garmin_nutrition}/food/logs"
)
self.garmin_connect_nutrition_daily_meals = f"{self.garmin_nutrition}/meals"
self.garmin_connect_nutrition_daily_settings = (
f"{self.garmin_nutrition}/settings"
)
self.garmin_golf = "/gcs-golfcommunity/api/v2"
self.garmin_golf_scorecard_summary = f"{self.garmin_golf}/scorecard/summary"
self.garmin_golf_scorecard_detail = f"{self.garmin_golf}/scorecard/detail"
self.garmin_golf_shot = f"{self.garmin_golf}/shot/scorecard"
self.garmin_connect_delete_activity_url = "/activity-service/activity"
self.garmin_graphql_endpoint = "graphql-gateway/graphql"
self.garmin_connect_training_plan_url = "/trainingplan-service/trainingplan"
self.garmin_connect_daily_lifestyle_logging_url = (
"/lifestylelogging-service/dailyLog"
)
self.client = client.Client(
domain="garmin.cn" if is_cn else "garmin.com",
pool_connections=20,
pool_maxsize=20,
verify_login=verify_login,
)
self.display_name: str | None = None
self.full_name: str | None = None
self.unit_system: str | None = None
@functools.cached_property
def typed(self) -> "TypedGarmin":
"""Return a typed namespace that wraps selected endpoints with Pydantic models.
Example::
g = Garmin(email, password)
g.login()
stats = g.typed.get_stats("2026-04-21") # DailyStats
Requires the optional ``typed`` extra::
pip install 'garminconnect[typed]'
See :mod:`garminconnect.typed` for the list of wrapped endpoints and
response models. **Experimental** — shapes may change between minor
releases.
"""
# Lazy import so pydantic stays an optional dep. The typed module
# raises a clear ImportError on its own if pydantic is missing.
from .typed import TypedGarmin
return TypedGarmin(self)
@_handle_api_errors("API call")
def connectapi(self, path: str, **kwargs: Any) -> Any:
"""Native connectapi call with error translation and optional retries."""
return self.client.connectapi(path, **kwargs)
@_handle_api_errors("Web proxy call")
def connectwebproxy(self, path: str, **kwargs: Any) -> Any:
"""Web proxy request with error translation and optional retries."""
return self.client.request("GET", "connect", path, **kwargs).json()
@_handle_api_errors("Download")
def download(self, path: str, **kwargs: Any) -> Any:
"""Native download call with error translation and optional retries."""
return self.client.download(path, **kwargs)
def login(self, /, tokenstore: str | None = None) -> tuple[str | None, str | None]:
"""Log in natively.
Returns:
Tuple[str | None, str | None]: (needs_mfa, None) when MFA is required;
(None, None) on clean successful login.
"""
tokenstore = tokenstore or os.getenv("GARMINTOKENS")
try:
mfa_status = None
_legacy_token = None
# Try to load tokens from tokenstore if provided
tokens_loaded = False
tokenstore_path = None
if tokenstore:
try:
if len(tokenstore) > 512:
# Token data is provided directly as string
self.client.loads(tokenstore)
else:
# Tokenstore is a path - normalize it for cross-platform compatibility
# This fixes Windows path issues where ~ expansion or path separators
# might cause token extraction to not find all token files correctly
tokenstore_path = str(Path(tokenstore).expanduser().resolve())
normalized_path = tokenstore_path
logger.debug(
f"Loading tokens from normalized path: {normalized_path}"
)
self.client.load(normalized_path)
tokens_loaded = True
# Proactively refresh DI token if it's expired or about to expire.
# This avoids hitting the SSO login endpoint (which may be
# Cloudflare-blocked) when a simple DI refresh would suffice.
if (
self.client.di_refresh_token
and self.client._token_expires_soon()
):
logger.debug("Token expiring soon, refreshing proactively")
self.client._refresh_session()
except Exception as e:
logger.debug(
f"Failed to cleanly load tokens from {tokenstore}: {e}"
)
tokens_loaded = False
# If tokens weren't loaded (or failed to load), use credentials
if not tokens_loaded:
# Validate credentials before attempting login
if not self.username or not self.password:
raise GarminConnectAuthenticationError(
"Username and password are required"
)
if self.return_on_mfa:
mfa_status, _legacy_token = self.client.login(
self.username,
self.password,
return_on_mfa=self.return_on_mfa,
)
# In MFA early-return mode, profile/settings are not loaded yet
return mfa_status, _legacy_token
if tokenstore_path is not None:
self.client._tokenstore_path = tokenstore_path
mfa_status, _legacy_token = self.client.login(
self.username,
self.password,
prompt_mfa=self.prompt_mfa,
)
# Persist tokens so next run restores without re-login/MFA
if tokenstore_path is not None:
with contextlib.suppress(Exception):
self.client.dump(tokenstore_path)
# Continue to load profile/settings below
# Ensure profile is loaded (tokenstore path may not populate it).
try:
self._load_profile_and_settings()
except GarminConnectAuthenticationError:
# If we resumed from cached tokens and the API rejects them,
# the cache is stale/poisoned (e.g. a token whose audience the
# API tier no longer accepts — see #369). Discard it and run a
# full credential login so the strategy chain can find a token
# the API accepts. Without this, a poisoned cache silently
# short-circuits the chain on every run.
username, password = self.username, self.password
if not (
tokens_loaded and username and password and not self.return_on_mfa
):
raise
logger.warning(
"Cached tokens were rejected by the API; discarding and "
"performing a fresh login."
)
self.client._clear_auth_state()
if tokenstore_path is not None:
self.client._tokenstore_path = tokenstore_path
mfa_status, _legacy_token = self.client.login(
username,
password,
prompt_mfa=self.prompt_mfa,
)
if tokenstore_path is not None:
with contextlib.suppress(Exception):
self.client.dump(tokenstore_path)
self._load_profile_and_settings()
return mfa_status, _legacy_token
except (
HTTPError,
requests.exceptions.HTTPError,
GarminConnectConnectionError,
) as e:
status = getattr(getattr(e, "response", None), "status_code", None)
error_str = str(e).lower()
# Re-raised below with a clean message; avoid logging a full
# traceback for expected failures (rate limits, bot challenges).
logger.debug("Login failed: %s (status=%s)", e, status)
if status == 429 or "429" in error_str:
raise GarminConnectTooManyRequestsError(
"Too many login attempts. Please wait a few minutes "
"before trying again."
) from e
if status == 401 or "401" in error_str or "unauthorized" in error_str:
raise GarminConnectAuthenticationError(
"Authentication failed (401 Unauthorized). "
"Possible causes:\n"
" • Incorrect email or password\n"
" • Account locked — check https://sso.garmin.com\n"
" • Garmin SSO service is temporarily unavailable\n"
f"Original error: {e}"
) from e
auth_indicators = ["unauthorized", "authentication failed"]
if any(indicator in error_str for indicator in auth_indicators):
raise GarminConnectAuthenticationError(
f"Authentication failed: {e}"
) from e
raise GarminConnectConnectionError(f"Login failed: {e}") from e
except FileNotFoundError:
raise
except (GarminConnectTooManyRequestsError, GarminConnectAuthenticationError):
raise
except Exception as e:
error_str = str(e).lower()
auth_indicators = ["401", "unauthorized", "authentication", "login failed"]
if any(indicator in error_str for indicator in auth_indicators):
raise GarminConnectAuthenticationError(
f"Authentication failed: {e}"
) from e
logger.debug("Login failed: %s", e)
raise GarminConnectConnectionError(f"Login failed: {e}") from e
def _load_profile_and_settings(self) -> None:
"""Fetch social profile and user settings, populating display name,
full name and unit system. Raises ``GarminConnectAuthenticationError``
if either cannot be retrieved (e.g. the token is rejected).
"""
prof = None
for attempt in range(3):
try:
prof = self.client.connectapi("/userprofile-service/socialProfile")
if isinstance(prof, dict):
break
except Exception as e:
if attempt == 2:
raise GarminConnectAuthenticationError(
"Failed to retrieve social profile"
) from e
logger.debug("Retrying social profile fetch: %s", e)
time.sleep(1)
else:
raise GarminConnectAuthenticationError("Invalid profile data found")
self.display_name = prof.get("displayName", self.username)
self.full_name = prof.get("fullName", "")
settings = None
for attempt in range(3):
try:
settings = self.client.connectapi(self.garmin_connect_user_settings_url)
if settings and isinstance(settings, dict) and "userData" in settings:
break
except Exception as e:
if attempt == 2:
raise GarminConnectAuthenticationError(
"Failed to retrieve user settings"
) from e
logger.debug("Retrying user settings fetch: %s", e)
time.sleep(1)
else:
raise GarminConnectAuthenticationError("Invalid user settings found")
self.unit_system = settings["userData"].get("measurementSystem")
def resume_login(
self, client_state: dict[str, Any], mfa_code: str
) -> tuple[Any, Any]:
"""Resume login interactively."""
mfa_status, _legacy_token = self.client.resume_login(client_state, mfa_code)
prof = None
for attempt in range(3):
try:
prof = self.client.connectapi("/userprofile-service/socialProfile")
if isinstance(prof, dict):
self.display_name = prof.get("displayName")
self.full_name = prof.get("fullName", "")
break
except Exception as e:
if attempt == 2:
logger.debug("Profile fetch failed during resume_login, continuing")
else:
logger.debug("Retrying profile fetch during resume_login: %s", e)
time.sleep(1)
settings = None
for attempt in range(3):
try:
settings = self.client.connectapi(self.garmin_connect_user_settings_url)
if settings and isinstance(settings, dict) and "userData" in settings:
self.unit_system = settings["userData"].get("measurementSystem")
break
except Exception as e:
if attempt == 2:
logger.debug(
"User settings fetch failed during resume_login, continuing: %s",
e,
)
else:
logger.debug(
"Retrying user settings fetch during resume_login: %s", e
)
time.sleep(1)
return mfa_status, _legacy_token
def _require_display_name(self) -> str:
"""Return display_name or raise if not set.
New/empty Garmin profiles may not have a displayName, which
would cause 'None' to be interpolated into API URLs and
result in 403 Forbidden errors.
"""
if not self.display_name:
raise GarminConnectConnectionError(
"Display name is not set. This usually means your "
"Garmin profile is incomplete (new account with no "
"display name configured). Please set a display name "
"at https://connect.garmin.com and try again."
)
return self.display_name
def get_full_name(self) -> str | None:
"""Return full name."""
return self.full_name
def get_unit_system(self) -> str | None:
"""Return unit system."""
return self.unit_system
def get_stats(self, cdate: str) -> dict[str, Any]:
"""Return user activity summary for 'cdate' format 'YYYY-MM-DD'
(compat for garminconnect).
"""
# Validate input
cdate = _validate_date_format(cdate, "cdate")
return self.get_user_summary(cdate)
def get_user_summary(self, cdate: str) -> dict[str, Any]:
"""Return user activity summary for 'cdate' format 'YYYY-MM-DD'."""
# Validate input
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_daily_summary_url}/{self._require_display_name()}"
params = {"calendarDate": cdate}
logger.debug("Requesting user summary")
response = self.connectapi(url, params=params)
if not response:
raise GarminConnectConnectionError("No data received from server")
if response.get("privacyProtected") is True:
raise GarminConnectAuthenticationError("Authentication error")
return response
def get_steps_data(self, cdate: str) -> list[dict[str, Any]]:
"""Fetch available steps data 'cDate' format 'YYYY-MM-DD'."""
# Validate input
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_user_summary_chart}/{self._require_display_name()}"
params = {"date": cdate}
logger.debug("Requesting steps data")
response = self.connectapi(url, params=params)
if response is None:
logger.warning("No steps data received")
return []
return response
def get_floors(self, cdate: str) -> dict[str, Any]:
"""Fetch available floors data 'cDate' format 'YYYY-MM-DD'."""
# Validate input
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_floors_chart_daily_url}/{cdate}"
logger.debug("Requesting floors data")
response = self.connectapi(url)
if response is None:
raise GarminConnectConnectionError("No floors data received")
return response
def get_daily_steps(self, start: str, end: str) -> list[dict[str, Any]]:
"""Fetch available steps data 'start' and 'end' format 'YYYY-MM-DD'.
Note: The Garmin Connect API has a 28-day limit per request. For date ranges
exceeding 28 days, this method automatically splits the range into chunks
and makes multiple API calls, then merges the results.
"""
# Validate inputs
start = _validate_date_format(start, "start")
end = _validate_date_format(end, "end")
# Validate date range
start_date = datetime.strptime(start, DATE_FORMAT_STR).date()
end_date = datetime.strptime(end, DATE_FORMAT_STR).date()
if start_date > end_date:
raise ValueError("start date cannot be after end date")
# Calculate date range (inclusive)
days_diff = (end_date - start_date).days + 1
# If range is 28 days or less, make single request
if days_diff <= 28:
url = f"{self.garmin_connect_daily_stats_steps_url}/{start}/{end}"
logger.debug("Requesting daily steps data")
return self.connectapi(url)
# For ranges > 28 days, split into chunks
logger.debug(
f"Date range ({days_diff} days) exceeds 28-day limit, chunking requests"
)
all_results = []
current_start = start_date
while current_start <= end_date:
# Calculate chunk end (max 28 days from current_start)
chunk_end = min(current_start + timedelta(days=27), end_date)
chunk_start_str = current_start.isoformat()
chunk_end_str = chunk_end.isoformat()
url = (
f"{self.garmin_connect_daily_stats_steps_url}/"
f"{chunk_start_str}/{chunk_end_str}"
)
logger.debug(
f"Requesting daily steps data for chunk: "
f"{chunk_start_str} to {chunk_end_str}"
)
chunk_results = self.connectapi(url)
if chunk_results:
all_results.extend(chunk_results)
# Move to next chunk
current_start = chunk_end + timedelta(days=1)
return all_results
def get_weekly_steps(self, end: str, weeks: int = 52) -> list[dict[str, Any]]:
"""Fetch weekly steps aggregates.
Args:
end: End date string in format 'YYYY-MM-DD'
weeks: Number of weeks to fetch (default 52 = 1 year)
Returns:
List of weekly step aggregates containing:
- totalSteps: Total steps for the week
- averageSteps: Average daily steps
- totalDistance: Total distance in meters
- averageDistance: Average daily distance
- wellnessDataDaysCount: Days with data
"""
end = _validate_date_format(end, "end")
weeks = _validate_positive_integer(weeks, "weeks")
url = f"{self.garmin_connect_weekly_stats_steps_url}/{end}/{weeks}"
logger.debug("Requesting weekly steps data for %d weeks ending %s", weeks, end)
return self.connectapi(url)
def get_weekly_stress(self, end: str, weeks: int = 52) -> list[dict[str, Any]]:
"""Fetch weekly stress aggregates.
Args:
end: End date string in format 'YYYY-MM-DD'
weeks: Number of weeks to fetch (default 52 = 1 year)
Returns:
List of weekly stress aggregates containing:
- value: Overall stress value for the week
- calendarDate: Week start date
"""
end = _validate_date_format(end, "end")
weeks = _validate_positive_integer(weeks, "weeks")
url = f"{self.garmin_connect_weekly_stats_stress_url}/{end}/{weeks}"
logger.debug("Requesting weekly stress data for %d weeks ending %s", weeks, end)
return self.connectapi(url)
def get_weekly_intensity_minutes(
self, start: str, end: str
) -> list[dict[str, Any]]:
"""Fetch weekly intensity minutes aggregates.