activy-checker 0.2.6__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.
- activy_checker/__init__.py +21 -0
- activy_checker/activy.py +238 -0
- activy_checker/cli.py +186 -0
- activy_checker/compare.py +62 -0
- activy_checker/garmin.py +165 -0
- activy_checker/models.py +48 -0
- activy_checker/progress.py +80 -0
- activy_checker/report.py +83 -0
- activy_checker-0.2.6.dist-info/METADATA +178 -0
- activy_checker-0.2.6.dist-info/RECORD +14 -0
- activy_checker-0.2.6.dist-info/WHEEL +5 -0
- activy_checker-0.2.6.dist-info/entry_points.txt +2 -0
- activy_checker-0.2.6.dist-info/licenses/LICENSE +21 -0
- activy_checker-0.2.6.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""activy-checker: audit Activy's activity sync."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .activy import ActivyClient
|
|
5
|
+
from .compare import CompareResult, Match, compare
|
|
6
|
+
from .garmin import GarminClient
|
|
7
|
+
from .models import Activity
|
|
8
|
+
from .report import render_comparison, render_summary, summarize
|
|
9
|
+
|
|
10
|
+
__version__ = "0.2.6"
|
|
11
|
+
__all__ = [
|
|
12
|
+
"ActivyClient",
|
|
13
|
+
"GarminClient",
|
|
14
|
+
"Activity",
|
|
15
|
+
"compare",
|
|
16
|
+
"CompareResult",
|
|
17
|
+
"Match",
|
|
18
|
+
"summarize",
|
|
19
|
+
"render_summary",
|
|
20
|
+
"render_comparison",
|
|
21
|
+
]
|
activy_checker/activy.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""Client for Activy's unofficial mobile API (OpenID Connect + CQRS queries).
|
|
2
|
+
|
|
3
|
+
Activy exposes no public API. This client talks to the same endpoints as the
|
|
4
|
+
mobile app, authenticating against YOUR account (grant_type=password).
|
|
5
|
+
Intended for use with your own account and your own data.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import ssl
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.parse
|
|
13
|
+
import urllib.request
|
|
14
|
+
from typing import Any, Callable
|
|
15
|
+
|
|
16
|
+
from .models import (
|
|
17
|
+
Activity,
|
|
18
|
+
KIND_BIKE,
|
|
19
|
+
KIND_EXERCISE,
|
|
20
|
+
KIND_OTHER,
|
|
21
|
+
KIND_RUN,
|
|
22
|
+
KIND_STEPS,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
AUTH_BASE = "https://players.v3.activy.pl/auth"
|
|
26
|
+
TOKEN_URL = AUTH_BASE + "/connect/token"
|
|
27
|
+
USERINFO_URL = AUTH_BASE + "/connect/userinfo"
|
|
28
|
+
CLIENT_ID = "activy.mobile"
|
|
29
|
+
SCOPE = (
|
|
30
|
+
"openid profile email offline_access "
|
|
31
|
+
"activy.rides activy.players activy.contests activy.rankings"
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
HOSTS = {
|
|
35
|
+
"players": "https://players.v3.activy.pl",
|
|
36
|
+
"rides": "https://rides.v3.activy.pl",
|
|
37
|
+
"contests": "https://contests.v3.activy.pl",
|
|
38
|
+
"rankings": "https://rankings.v3.activy.pl",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
MYCONTESTS = "Activy.Contests.Contracts.Mobile.Contests.MyContests"
|
|
42
|
+
USER_CONTEST_FEED = "Activy.Players.Contracts.Mobile.Newsfeed.UserContestFeed"
|
|
43
|
+
CONTEST_FEED = "Activy.Players.Contracts.Mobile.Newsfeed.ContestFeed"
|
|
44
|
+
|
|
45
|
+
# Activy ActivityType -> common category
|
|
46
|
+
_KIND_BY_TYPE = {0: KIND_BIKE, 1: KIND_RUN, 2: KIND_EXERCISE, 3: KIND_STEPS}
|
|
47
|
+
|
|
48
|
+
_CTX = ssl.create_default_context()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class ActivyError(RuntimeError):
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ActivyClient:
|
|
56
|
+
def __init__(self, timeout: int = 40):
|
|
57
|
+
self._token: str | None = None
|
|
58
|
+
self._user_id: str | None = None
|
|
59
|
+
self.timeout = timeout
|
|
60
|
+
|
|
61
|
+
# ---- authentication --------------------------------------------------
|
|
62
|
+
def login(self, email: str, password: str) -> None:
|
|
63
|
+
data = urllib.parse.urlencode({
|
|
64
|
+
"grant_type": "password",
|
|
65
|
+
"client_id": CLIENT_ID,
|
|
66
|
+
"username": email,
|
|
67
|
+
"password": password,
|
|
68
|
+
"scope": SCOPE,
|
|
69
|
+
}).encode()
|
|
70
|
+
req = urllib.request.Request(TOKEN_URL, data=data, method="POST")
|
|
71
|
+
req.add_header("Content-Type", "application/x-www-form-urlencoded")
|
|
72
|
+
req.add_header("Accept", "application/json")
|
|
73
|
+
try:
|
|
74
|
+
with urllib.request.urlopen(req, context=_CTX, timeout=self.timeout) as r:
|
|
75
|
+
body = json.loads(r.read().decode("utf-8", "replace"))
|
|
76
|
+
except urllib.error.HTTPError as e:
|
|
77
|
+
detail = e.read().decode("utf-8", "replace")
|
|
78
|
+
raise ActivyError(f"Activy login failed (HTTP {e.code}): {detail[:200]}")
|
|
79
|
+
token = body.get("access_token")
|
|
80
|
+
if not token:
|
|
81
|
+
raise ActivyError(f"No access_token in response: {body}")
|
|
82
|
+
self._token = token
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def user_id(self) -> str:
|
|
86
|
+
if self._user_id is None:
|
|
87
|
+
self._user_id = self._userinfo()["sub"]
|
|
88
|
+
return self._user_id
|
|
89
|
+
|
|
90
|
+
def _userinfo(self) -> dict[str, Any]:
|
|
91
|
+
return self._get(USERINFO_URL)
|
|
92
|
+
|
|
93
|
+
# ---- low-level calls -------------------------------------------------
|
|
94
|
+
def _headers(self) -> dict[str, str]:
|
|
95
|
+
if not self._token:
|
|
96
|
+
raise ActivyError("Not logged in: call client.login(email, password) first")
|
|
97
|
+
return {
|
|
98
|
+
"Authorization": "Bearer " + self._token,
|
|
99
|
+
"Accept": "application/json",
|
|
100
|
+
"Content-Type": "application/json",
|
|
101
|
+
"User-Agent": "activy-checker/1.0",
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
def _get(self, url: str) -> Any:
|
|
105
|
+
req = urllib.request.Request(url, method="GET")
|
|
106
|
+
for k, v in self._headers().items():
|
|
107
|
+
req.add_header(k, v)
|
|
108
|
+
with urllib.request.urlopen(req, context=_CTX, timeout=self.timeout) as r:
|
|
109
|
+
return json.loads(r.read().decode("utf-8", "replace"))
|
|
110
|
+
|
|
111
|
+
def query(self, service: str, namespace: str, payload: dict[str, Any]) -> tuple[int, Any]:
|
|
112
|
+
url = f"{HOSTS[service]}/api/query/{namespace}"
|
|
113
|
+
req = urllib.request.Request(url, data=json.dumps(payload).encode(), method="POST")
|
|
114
|
+
for k, v in self._headers().items():
|
|
115
|
+
req.add_header(k, v)
|
|
116
|
+
try:
|
|
117
|
+
with urllib.request.urlopen(req, context=_CTX, timeout=self.timeout) as r:
|
|
118
|
+
return r.status, json.loads(r.read().decode("utf-8", "replace"))
|
|
119
|
+
except urllib.error.HTTPError as e:
|
|
120
|
+
return e.code, None
|
|
121
|
+
|
|
122
|
+
# ---- high-level ------------------------------------------------------
|
|
123
|
+
def contest_ids(self) -> list[str]:
|
|
124
|
+
st, data = self.query("contests", MYCONTESTS, {})
|
|
125
|
+
if st != 200 or not isinstance(data, list):
|
|
126
|
+
return []
|
|
127
|
+
ids = []
|
|
128
|
+
for x in data:
|
|
129
|
+
cid = x.get("Id") or x.get("ContestId") or (x.get("Contest") or {}).get("Id")
|
|
130
|
+
if cid:
|
|
131
|
+
ids.append(cid)
|
|
132
|
+
return ids
|
|
133
|
+
|
|
134
|
+
def get_activities(
|
|
135
|
+
self,
|
|
136
|
+
since: str,
|
|
137
|
+
max_pages: int = 500,
|
|
138
|
+
progress: Callable[[dict[str, Any]], None] | None = None,
|
|
139
|
+
) -> list[Activity]:
|
|
140
|
+
"""Return your activities with date >= ``since`` (YYYY-MM-DD).
|
|
141
|
+
|
|
142
|
+
Activities are read from each contest's feed (there is no dedicated
|
|
143
|
+
list endpoint). The feed is reverse-chronological, so we paginate until
|
|
144
|
+
every event on a page is older than ``since``.
|
|
145
|
+
|
|
146
|
+
``progress``, if given, is called after every feed page with a dict:
|
|
147
|
+
``contest`` / ``contests`` (1-based index and total), ``page``
|
|
148
|
+
(1-based), ``found`` (your activities so far) and ``reached`` (the
|
|
149
|
+
oldest date seen on that page).
|
|
150
|
+
"""
|
|
151
|
+
me = self.user_id
|
|
152
|
+
found: dict[str, Activity] = {}
|
|
153
|
+
cids = self.contest_ids()
|
|
154
|
+
for n, cid in enumerate(cids, 1):
|
|
155
|
+
report = None
|
|
156
|
+
if progress:
|
|
157
|
+
def report(page, reached, n=n):
|
|
158
|
+
progress({"contest": n, "contests": len(cids), "page": page,
|
|
159
|
+
"found": len(found), "reached": reached})
|
|
160
|
+
self._collect_contest(cid, me, since, found, max_pages, report)
|
|
161
|
+
return sorted(found.values(), key=lambda a: a.start or "")
|
|
162
|
+
|
|
163
|
+
def _collect_contest(self, cid, me, since, found, max_pages, report=None) -> None:
|
|
164
|
+
# UserContestFeed requires both the contest and your user id; without
|
|
165
|
+
# UserId the API rejects the request.
|
|
166
|
+
base = {"ContestId": cid, "UserId": me}
|
|
167
|
+
feed = USER_CONTEST_FEED
|
|
168
|
+
st, arr = self.query("players", feed, dict(base, Page=0, PageSize=50))
|
|
169
|
+
if st != 200 or not isinstance(arr, list) or not arr:
|
|
170
|
+
feed = CONTEST_FEED
|
|
171
|
+
page = 0
|
|
172
|
+
previous = None
|
|
173
|
+
while page < max_pages:
|
|
174
|
+
st, arr = self.query("players", feed, dict(base, Page=page, PageSize=50))
|
|
175
|
+
if st != 200 or not isinstance(arr, list) or not arr:
|
|
176
|
+
break
|
|
177
|
+
# Guard against a feed that ignores paging and keeps returning the
|
|
178
|
+
# same page: stop instead of re-reading it until max_pages.
|
|
179
|
+
signature = json.dumps(arr, sort_keys=True, default=str)
|
|
180
|
+
if signature == previous:
|
|
181
|
+
break
|
|
182
|
+
previous = signature
|
|
183
|
+
page_dates = []
|
|
184
|
+
for ev in arr:
|
|
185
|
+
date = (ev.get("Date") or "")[:10]
|
|
186
|
+
page_dates.append(date)
|
|
187
|
+
ride = (ev.get("Content") or {}).get("Ride")
|
|
188
|
+
if not ride:
|
|
189
|
+
continue
|
|
190
|
+
if ride.get("UserId") not in (me, None):
|
|
191
|
+
continue
|
|
192
|
+
if date and date < since:
|
|
193
|
+
continue
|
|
194
|
+
act = _ride_to_activity(ride, ev.get("Date"))
|
|
195
|
+
if act and act.id not in found:
|
|
196
|
+
found[act.id] = act
|
|
197
|
+
if report:
|
|
198
|
+
report(page + 1, min((d for d in page_dates if d), default=""))
|
|
199
|
+
# early stop: whole page older than 'since'
|
|
200
|
+
if page_dates and max(page_dates) < since:
|
|
201
|
+
break
|
|
202
|
+
page += 1
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _duration_seconds(t: str | None) -> int:
|
|
206
|
+
"""Parse Activy duration 'd.hh:mm:ss.fff' or 'hh:mm:ss' into seconds."""
|
|
207
|
+
if not t:
|
|
208
|
+
return 0
|
|
209
|
+
try:
|
|
210
|
+
head = t.split(":")[0]
|
|
211
|
+
if "." in head:
|
|
212
|
+
days_s, hms = t.split(".", 1)
|
|
213
|
+
days = int(days_s)
|
|
214
|
+
else:
|
|
215
|
+
days, hms = 0, t
|
|
216
|
+
parts = hms.split(".")[0].split(":")
|
|
217
|
+
h, m, s = (list(map(int, parts)) + [0, 0, 0])[:3]
|
|
218
|
+
return days * 86400 + h * 3600 + m * 60 + s
|
|
219
|
+
except (ValueError, IndexError):
|
|
220
|
+
return 0
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _ride_to_activity(ride: dict[str, Any], date_iso: str | None) -> Activity | None:
|
|
224
|
+
aid = ride.get("ActivityId")
|
|
225
|
+
if not aid:
|
|
226
|
+
return None
|
|
227
|
+
atype = ride.get("ActivityType")
|
|
228
|
+
return Activity(
|
|
229
|
+
source="activy",
|
|
230
|
+
id=str(aid),
|
|
231
|
+
date=(date_iso or "")[:10],
|
|
232
|
+
start=date_iso or "",
|
|
233
|
+
kind=_KIND_BY_TYPE.get(atype, KIND_OTHER),
|
|
234
|
+
raw_type=str(atype),
|
|
235
|
+
distance_km=round(float(ride.get("Distance") or 0.0), 2),
|
|
236
|
+
duration_s=_duration_seconds(ride.get("Time")),
|
|
237
|
+
raw=ride,
|
|
238
|
+
)
|
activy_checker/cli.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Command-line entry point for activy-checker."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import datetime
|
|
6
|
+
import getpass
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .activy import ActivyClient, ActivyError
|
|
12
|
+
from .compare import compare
|
|
13
|
+
from .garmin import GarminClient
|
|
14
|
+
from .models import KIND_STEPS, Activity
|
|
15
|
+
from .progress import Spinner
|
|
16
|
+
from .report import render_comparison, render_summary, summarize
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
DEFAULT_SINCE = "2026-09-01"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _prompt(label: str, value: str | None) -> str:
|
|
23
|
+
"""Return ``value`` or ask for it. The prompt goes to stderr so stdout stays a clean report."""
|
|
24
|
+
if value:
|
|
25
|
+
return value
|
|
26
|
+
sys.stderr.write(label)
|
|
27
|
+
sys.stderr.flush()
|
|
28
|
+
return input().strip()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
32
|
+
p = argparse.ArgumentParser(
|
|
33
|
+
prog="activy-checker",
|
|
34
|
+
description="Audit Activy's activity sync: detect missing activities and incorrect distances.",
|
|
35
|
+
)
|
|
36
|
+
p.add_argument("--since", default=DEFAULT_SINCE,
|
|
37
|
+
help=f"Start date YYYY-MM-DD (default: {DEFAULT_SINCE})")
|
|
38
|
+
p.add_argument("--until", default=datetime.date.today().isoformat(),
|
|
39
|
+
help="End date YYYY-MM-DD (default: today)")
|
|
40
|
+
p.add_argument("--activy-email", default=None, help="Activy email (else prompted)")
|
|
41
|
+
p.add_argument("--garmin-email", default=None, help="Garmin email (else prompted)")
|
|
42
|
+
p.add_argument("--activy-only", action="store_true",
|
|
43
|
+
help="Only fetch and summarize Activy (skip Garmin and comparison)")
|
|
44
|
+
p.add_argument("--garmin-tokenstore", default=None,
|
|
45
|
+
help="Directory or .json file to cache the Garmin session (avoids repeated MFA)")
|
|
46
|
+
p.add_argument("--include-steps", action="store_true",
|
|
47
|
+
help="Keep Activy step-count entries (excluded by default: they have no Garmin activity)")
|
|
48
|
+
p.add_argument("--duration-tolerance", type=int, default=8, metavar="SECONDS",
|
|
49
|
+
help="Max duration difference for two activities to match (default: 8)")
|
|
50
|
+
p.add_argument("--distance-tolerance", type=float, default=0.5, metavar="KM",
|
|
51
|
+
help="Distance difference above which a match is reported as a mismatch (default: 0.5)")
|
|
52
|
+
p.add_argument("--json", dest="json_out", default=None,
|
|
53
|
+
help="Write the full result as JSON to this path")
|
|
54
|
+
p.add_argument("--verbose", action="store_true",
|
|
55
|
+
help="Show the Garmin library's sign-in messages (hidden by default)")
|
|
56
|
+
p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
57
|
+
return p
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
MFA_PROMPT = ("Garmin has sent you a verification code (check your email).\n"
|
|
61
|
+
"Enter the code to continue: ")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _activy_progress(p: dict, since: str) -> str:
|
|
65
|
+
contest = f" (contest {p['contest']}/{p['contests']})" if p["contests"] > 1 else ""
|
|
66
|
+
reached = f", reached {p['reached']}" if p["reached"] else ""
|
|
67
|
+
return (f"Scanning Activy feed{contest}: page {p['page']}, "
|
|
68
|
+
f"{p['found']} of yours so far{reached} (going back to {since}) ...")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _activity_dict(a: Activity) -> dict:
|
|
72
|
+
return {
|
|
73
|
+
"source": a.source, "id": a.id, "date": a.date, "start": a.start,
|
|
74
|
+
"kind": a.kind, "raw_type": a.raw_type,
|
|
75
|
+
"distance_km": a.distance_km, "duration_s": a.duration_s,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def main(argv: list[str] | None = None) -> int:
|
|
80
|
+
try:
|
|
81
|
+
return _run(argv)
|
|
82
|
+
except KeyboardInterrupt:
|
|
83
|
+
print("\nAborted.", file=sys.stderr)
|
|
84
|
+
return 130
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _run(argv: list[str] | None) -> int:
|
|
88
|
+
args = build_parser().parse_args(argv)
|
|
89
|
+
|
|
90
|
+
# --- Activy ---
|
|
91
|
+
print(f"Fetching Activy activities since {args.since}.", file=sys.stderr)
|
|
92
|
+
activy = ActivyClient()
|
|
93
|
+
try:
|
|
94
|
+
email = _prompt("Activy email: ", args.activy_email)
|
|
95
|
+
password = getpass.getpass("Activy password (hidden): ")
|
|
96
|
+
with Spinner("Signing in to Activy ...") as sp:
|
|
97
|
+
activy.login(email, password)
|
|
98
|
+
sp.update("Looking up your Activy contests ...")
|
|
99
|
+
activy_acts = activy.get_activities(
|
|
100
|
+
args.since, progress=lambda p: sp.update(_activy_progress(p, args.since)))
|
|
101
|
+
except (ActivyError, OSError, ValueError) as e: # OSError covers network errors
|
|
102
|
+
print(f"Activy error: {e}", file=sys.stderr)
|
|
103
|
+
return 2
|
|
104
|
+
activy_acts = [a for a in activy_acts if args.since <= a.date <= args.until]
|
|
105
|
+
if not args.include_steps:
|
|
106
|
+
activy_acts = [a for a in activy_acts if a.kind != KIND_STEPS]
|
|
107
|
+
if not activy_acts:
|
|
108
|
+
print("Warning: no Activy activities found in this date range. If you expected some, "
|
|
109
|
+
"see docs/troubleshooting.md#activy-returns-no-activities", file=sys.stderr)
|
|
110
|
+
print(render_summary("Activy", activy_acts))
|
|
111
|
+
|
|
112
|
+
if args.activy_only:
|
|
113
|
+
if args.json_out:
|
|
114
|
+
_write_json(args.json_out, activy_acts, None, None)
|
|
115
|
+
return 0
|
|
116
|
+
|
|
117
|
+
# --- Garmin ---
|
|
118
|
+
print(f"\nFetching Garmin activities since {args.since}.", file=sys.stderr)
|
|
119
|
+
garmin = GarminClient(tokenstore=args.garmin_tokenstore, quiet=not args.verbose)
|
|
120
|
+
try:
|
|
121
|
+
with Spinner("Checking for a saved Garmin session ..."):
|
|
122
|
+
resumed = garmin.try_resume()
|
|
123
|
+
if resumed:
|
|
124
|
+
print("Resumed saved Garmin session.", file=sys.stderr)
|
|
125
|
+
else:
|
|
126
|
+
gemail = _prompt("Garmin email: ", args.garmin_email)
|
|
127
|
+
gpass = getpass.getpass("Garmin password (hidden): ")
|
|
128
|
+
# No spinner here: garminconnect may ask for an MFA code and print
|
|
129
|
+
# its own messages, which an animated line would overwrite.
|
|
130
|
+
print("Signing in to Garmin (this can take a moment) ...", file=sys.stderr)
|
|
131
|
+
garmin.login(gemail, gpass, mfa_prompt=lambda: _prompt(MFA_PROMPT, None))
|
|
132
|
+
with Spinner(f"Fetching Garmin activities {args.since} .. {args.until} ..."):
|
|
133
|
+
garmin_acts = garmin.get_activities(args.since, args.until)
|
|
134
|
+
except Exception as e: # garminconnect raises its own exception types
|
|
135
|
+
print(f"Garmin error: {e}", file=sys.stderr)
|
|
136
|
+
if garmin.log and not args.verbose:
|
|
137
|
+
print("Garmin sign-in details:", file=sys.stderr)
|
|
138
|
+
for line in garmin.log[-5:]:
|
|
139
|
+
print(f" {line}", file=sys.stderr)
|
|
140
|
+
return 3
|
|
141
|
+
garmin_acts = [a for a in garmin_acts if args.since <= a.date <= args.until]
|
|
142
|
+
print()
|
|
143
|
+
print(render_summary("Garmin", garmin_acts))
|
|
144
|
+
|
|
145
|
+
# --- comparison ---
|
|
146
|
+
result = compare(activy_acts, garmin_acts,
|
|
147
|
+
duration_tolerance_s=args.duration_tolerance,
|
|
148
|
+
distance_tolerance_km=args.distance_tolerance)
|
|
149
|
+
print()
|
|
150
|
+
print(render_comparison(result))
|
|
151
|
+
|
|
152
|
+
if args.json_out:
|
|
153
|
+
_write_json(args.json_out, activy_acts, garmin_acts, result)
|
|
154
|
+
print(f"\nJSON written to {args.json_out}", file=sys.stderr)
|
|
155
|
+
return 0
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _write_json(path, activy_acts, garmin_acts, result) -> None:
|
|
159
|
+
out = {
|
|
160
|
+
"activy": {
|
|
161
|
+
"summary": summarize(activy_acts),
|
|
162
|
+
"activities": [_activity_dict(a) for a in activy_acts],
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if garmin_acts is not None:
|
|
166
|
+
out["garmin"] = {
|
|
167
|
+
"summary": summarize(garmin_acts),
|
|
168
|
+
"activities": [_activity_dict(a) for a in garmin_acts],
|
|
169
|
+
}
|
|
170
|
+
if result is not None:
|
|
171
|
+
out["comparison"] = {
|
|
172
|
+
"matched": len(result.matched),
|
|
173
|
+
"missing_in_activy": [_activity_dict(g) for g in result.only_garmin],
|
|
174
|
+
"missing_in_garmin": [_activity_dict(a) for a in result.only_activy],
|
|
175
|
+
"distance_mismatches": [
|
|
176
|
+
{"date": m.activy.date, "activy_km": m.activy.distance_km,
|
|
177
|
+
"garmin_km": m.garmin.distance_km, "delta_km": m.distance_delta_km}
|
|
178
|
+
for m in result.distance_mismatches
|
|
179
|
+
],
|
|
180
|
+
}
|
|
181
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
182
|
+
json.dump(out, f, ensure_ascii=False, indent=2)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
if __name__ == "__main__":
|
|
186
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Match Activy activities against Garmin and describe the differences.
|
|
2
|
+
|
|
3
|
+
The two services share start timestamps almost exactly (Activy copies the
|
|
4
|
+
duration from Garmin), so date + duration is the most reliable match key.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
from .models import Activity
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class Match:
|
|
15
|
+
activy: Activity
|
|
16
|
+
garmin: Activity
|
|
17
|
+
|
|
18
|
+
@property
|
|
19
|
+
def distance_delta_km(self) -> float:
|
|
20
|
+
return round(self.activy.distance_km - self.garmin.distance_km, 2)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class CompareResult:
|
|
25
|
+
matched: list[Match] = field(default_factory=list)
|
|
26
|
+
only_garmin: list[Activity] = field(default_factory=list) # missing in Activy
|
|
27
|
+
only_activy: list[Activity] = field(default_factory=list) # missing in Garmin
|
|
28
|
+
distance_mismatches: list[Match] = field(default_factory=list)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def compare(
|
|
32
|
+
activy: list[Activity],
|
|
33
|
+
garmin: list[Activity],
|
|
34
|
+
duration_tolerance_s: int = 8,
|
|
35
|
+
distance_tolerance_km: float = 0.5,
|
|
36
|
+
) -> CompareResult:
|
|
37
|
+
"""Match each Activy activity to the unused Garmin activity on the same date
|
|
38
|
+
whose duration is closest, provided the difference is within
|
|
39
|
+
``duration_tolerance_s``. Each Garmin activity is matched at most once.
|
|
40
|
+
"""
|
|
41
|
+
result = CompareResult()
|
|
42
|
+
used = [False] * len(garmin)
|
|
43
|
+
|
|
44
|
+
for a in activy:
|
|
45
|
+
best, best_diff = -1, None
|
|
46
|
+
for i, g in enumerate(garmin):
|
|
47
|
+
if used[i] or g.date != a.date:
|
|
48
|
+
continue
|
|
49
|
+
diff = abs(g.duration_s - a.duration_s)
|
|
50
|
+
if diff <= duration_tolerance_s and (best_diff is None or diff < best_diff):
|
|
51
|
+
best, best_diff = i, diff
|
|
52
|
+
if best >= 0:
|
|
53
|
+
used[best] = True
|
|
54
|
+
m = Match(activy=a, garmin=garmin[best])
|
|
55
|
+
result.matched.append(m)
|
|
56
|
+
if abs(m.distance_delta_km) > distance_tolerance_km:
|
|
57
|
+
result.distance_mismatches.append(m)
|
|
58
|
+
else:
|
|
59
|
+
result.only_activy.append(a)
|
|
60
|
+
|
|
61
|
+
result.only_garmin = [g for i, g in enumerate(garmin) if not used[i]]
|
|
62
|
+
return result
|
activy_checker/garmin.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Garmin Connect client (thin wrapper over the `garminconnect` library)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import contextlib
|
|
5
|
+
import datetime
|
|
6
|
+
import logging
|
|
7
|
+
from typing import Any, Callable, Iterator
|
|
8
|
+
|
|
9
|
+
from .models import (
|
|
10
|
+
Activity,
|
|
11
|
+
KIND_BIKE,
|
|
12
|
+
KIND_EXERCISE,
|
|
13
|
+
KIND_OTHER,
|
|
14
|
+
KIND_RUN,
|
|
15
|
+
KIND_SWIM,
|
|
16
|
+
KIND_WALK,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
# Garmin activityType.typeKey -> common category
|
|
20
|
+
_KIND_BY_TYPEKEY = {
|
|
21
|
+
"road_biking": KIND_BIKE,
|
|
22
|
+
"mountain_biking": KIND_BIKE,
|
|
23
|
+
"gravel_cycling": KIND_BIKE,
|
|
24
|
+
"cycling": KIND_BIKE,
|
|
25
|
+
"virtual_ride": KIND_BIKE,
|
|
26
|
+
"indoor_cycling": KIND_BIKE,
|
|
27
|
+
"running": KIND_RUN,
|
|
28
|
+
"trail_running": KIND_RUN,
|
|
29
|
+
"treadmill_running": KIND_RUN,
|
|
30
|
+
"track_running": KIND_RUN,
|
|
31
|
+
"walking": KIND_WALK,
|
|
32
|
+
"hiking": KIND_WALK,
|
|
33
|
+
"casual_walking": KIND_WALK,
|
|
34
|
+
"swimming": KIND_SWIM,
|
|
35
|
+
"open_water_swimming": KIND_SWIM,
|
|
36
|
+
"lap_swimming": KIND_SWIM,
|
|
37
|
+
"indoor_cardio": KIND_EXERCISE,
|
|
38
|
+
"strength_training": KIND_EXERCISE,
|
|
39
|
+
"yoga": KIND_EXERCISE,
|
|
40
|
+
"fitness_equipment": KIND_EXERCISE,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class GarminError(RuntimeError):
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _ListHandler(logging.Handler):
|
|
49
|
+
def __init__(self, sink: list[str]):
|
|
50
|
+
super().__init__(level=logging.DEBUG)
|
|
51
|
+
self.sink = sink
|
|
52
|
+
|
|
53
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
54
|
+
self.sink.append(f"{record.levelname}: {record.getMessage()}")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@contextlib.contextmanager
|
|
58
|
+
def _capture_library_logs(sink: list[str], enabled: bool = True) -> Iterator[None]:
|
|
59
|
+
"""Collect garminconnect's log output into ``sink`` instead of the terminal.
|
|
60
|
+
|
|
61
|
+
During sign-in garminconnect tries several strategies and logs a warning for
|
|
62
|
+
each one Garmin rejects (e.g. "mobile+cffi returned 429 ..."), even when a
|
|
63
|
+
later strategy succeeds. Those warnings are noise for end users.
|
|
64
|
+
"""
|
|
65
|
+
if not enabled:
|
|
66
|
+
yield
|
|
67
|
+
return
|
|
68
|
+
logger = logging.getLogger("garminconnect")
|
|
69
|
+
handler = _ListHandler(sink)
|
|
70
|
+
previous_propagate = logger.propagate
|
|
71
|
+
logger.addHandler(handler)
|
|
72
|
+
logger.propagate = False
|
|
73
|
+
try:
|
|
74
|
+
yield
|
|
75
|
+
finally:
|
|
76
|
+
logger.removeHandler(handler)
|
|
77
|
+
logger.propagate = previous_propagate
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _garmin_class():
|
|
81
|
+
try:
|
|
82
|
+
from garminconnect import Garmin
|
|
83
|
+
except ImportError as e: # pragma: no cover
|
|
84
|
+
raise GarminError(
|
|
85
|
+
"The 'garminconnect' package is required. Install with: pip install garminconnect"
|
|
86
|
+
) from e
|
|
87
|
+
return Garmin
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class GarminClient:
|
|
91
|
+
"""Wraps `garminconnect.Garmin`, normalizing results to `Activity`.
|
|
92
|
+
|
|
93
|
+
``tokenstore`` is an optional directory (tokens are kept in
|
|
94
|
+
``garmin_tokens.json`` inside it) or a path to a ``.json`` file. When set,
|
|
95
|
+
a saved session is reused and a fresh login is persisted there, so MFA is
|
|
96
|
+
only needed once.
|
|
97
|
+
|
|
98
|
+
With ``quiet=True`` (default) the library's sign-in warnings are kept in
|
|
99
|
+
``self.log`` instead of being printed.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
def __init__(self, tokenstore: str | None = None, quiet: bool = True):
|
|
103
|
+
self.tokenstore = tokenstore
|
|
104
|
+
self.quiet = quiet
|
|
105
|
+
self.log: list[str] = []
|
|
106
|
+
self._api = None
|
|
107
|
+
|
|
108
|
+
def try_resume(self) -> bool:
|
|
109
|
+
"""Resume a saved session from ``tokenstore``; return True on success."""
|
|
110
|
+
if not self.tokenstore:
|
|
111
|
+
return False
|
|
112
|
+
Garmin = _garmin_class()
|
|
113
|
+
try:
|
|
114
|
+
api = Garmin()
|
|
115
|
+
with _capture_library_logs(self.log, self.quiet):
|
|
116
|
+
api.login(self.tokenstore)
|
|
117
|
+
except Exception:
|
|
118
|
+
return False
|
|
119
|
+
self._api = api
|
|
120
|
+
return True
|
|
121
|
+
|
|
122
|
+
def login(
|
|
123
|
+
self,
|
|
124
|
+
email: str | None = None,
|
|
125
|
+
password: str | None = None,
|
|
126
|
+
mfa_prompt: Callable[[], str] | None = None,
|
|
127
|
+
) -> None:
|
|
128
|
+
"""Log in, reusing a saved session when possible (may prompt for MFA)."""
|
|
129
|
+
if self.try_resume():
|
|
130
|
+
return
|
|
131
|
+
if not email or not password:
|
|
132
|
+
raise GarminError("Garmin email and password are required for a fresh login")
|
|
133
|
+
Garmin = _garmin_class()
|
|
134
|
+
api = Garmin(email=email, password=password,
|
|
135
|
+
prompt_mfa=mfa_prompt or (lambda: input("Garmin MFA code: ").strip()))
|
|
136
|
+
try:
|
|
137
|
+
# With a tokenstore, garminconnect persists the new session itself.
|
|
138
|
+
with _capture_library_logs(self.log, self.quiet):
|
|
139
|
+
api.login(self.tokenstore)
|
|
140
|
+
except Exception as e:
|
|
141
|
+
raise GarminError(f"Garmin login failed: {e}") from e
|
|
142
|
+
self._api = api
|
|
143
|
+
|
|
144
|
+
def get_activities(self, since: str, until: str | None = None) -> list[Activity]:
|
|
145
|
+
if self._api is None:
|
|
146
|
+
raise GarminError("Not logged in: call client.login(...) first")
|
|
147
|
+
until = until or datetime.date.today().isoformat()
|
|
148
|
+
raw = self._api.get_activities_by_date(since, until)
|
|
149
|
+
return [_to_activity(a) for a in raw]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _to_activity(a: dict[str, Any]) -> Activity:
|
|
153
|
+
type_key = (a.get("activityType") or {}).get("typeKey", "") or ""
|
|
154
|
+
start = a.get("startTimeLocal") or ""
|
|
155
|
+
return Activity(
|
|
156
|
+
source="garmin",
|
|
157
|
+
id=str(a.get("activityId")),
|
|
158
|
+
date=start[:10],
|
|
159
|
+
start=start,
|
|
160
|
+
kind=_KIND_BY_TYPEKEY.get(type_key, KIND_OTHER),
|
|
161
|
+
raw_type=type_key,
|
|
162
|
+
distance_km=round(float(a.get("distance") or 0.0) / 1000.0, 2),
|
|
163
|
+
duration_s=int(a.get("duration") or 0),
|
|
164
|
+
raw=a,
|
|
165
|
+
)
|
activy_checker/models.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Shared, normalized activity model used for both sources (Activy, Garmin)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
# Common categories that both services' types are mapped to.
|
|
8
|
+
KIND_BIKE = "bike"
|
|
9
|
+
KIND_RUN = "run"
|
|
10
|
+
KIND_WALK = "walk"
|
|
11
|
+
KIND_SWIM = "swim"
|
|
12
|
+
KIND_EXERCISE = "exercise"
|
|
13
|
+
KIND_STEPS = "steps"
|
|
14
|
+
KIND_OTHER = "other"
|
|
15
|
+
|
|
16
|
+
KIND_LABEL = {
|
|
17
|
+
KIND_BIKE: "Bike",
|
|
18
|
+
KIND_RUN: "Run",
|
|
19
|
+
KIND_WALK: "Walk",
|
|
20
|
+
KIND_SWIM: "Swim",
|
|
21
|
+
KIND_EXERCISE: "Exercise",
|
|
22
|
+
KIND_STEPS: "Steps",
|
|
23
|
+
KIND_OTHER: "Other",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Activity:
|
|
29
|
+
"""A single activity reduced to a common shape."""
|
|
30
|
+
|
|
31
|
+
source: str # "activy" | "garmin"
|
|
32
|
+
id: str # identifier in the source system
|
|
33
|
+
date: str # "YYYY-MM-DD" (local start date)
|
|
34
|
+
start: str # full start timestamp (ISO) if available
|
|
35
|
+
kind: str # one of KIND_*
|
|
36
|
+
raw_type: str # original source type (e.g. "road_biking", "0")
|
|
37
|
+
distance_km: float
|
|
38
|
+
duration_s: int
|
|
39
|
+
raw: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def duration_hms(self) -> str:
|
|
43
|
+
return format_duration(self.duration_s)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def format_duration(seconds: int) -> str:
|
|
47
|
+
s = int(seconds or 0)
|
|
48
|
+
return f"{s // 3600}:{s % 3600 // 60:02d}:{s % 60:02d}"
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""A small terminal spinner for long-running steps.
|
|
2
|
+
|
|
3
|
+
It writes to stderr and only animates when stderr is a terminal, so piping or
|
|
4
|
+
redirecting the report (``activy-checker > report.txt``) stays clean.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
from typing import TextIO
|
|
12
|
+
|
|
13
|
+
FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Spinner:
|
|
17
|
+
"""Context manager showing ``<frame> <message>`` on one self-updating line.
|
|
18
|
+
|
|
19
|
+
>>> with Spinner("Working") as sp:
|
|
20
|
+
... sp.update("Still working")
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, message: str = "", stream: TextIO | None = None,
|
|
24
|
+
interval: float = 0.1, enabled: bool | None = None):
|
|
25
|
+
self.stream = stream or sys.stderr
|
|
26
|
+
if enabled is None:
|
|
27
|
+
isatty = getattr(self.stream, "isatty", None)
|
|
28
|
+
enabled = bool(isatty and isatty())
|
|
29
|
+
self.enabled = enabled
|
|
30
|
+
self.message = message
|
|
31
|
+
self.interval = interval
|
|
32
|
+
self._stop = threading.Event()
|
|
33
|
+
self._thread: threading.Thread | None = None
|
|
34
|
+
self._lock = threading.Lock()
|
|
35
|
+
self._frame = 0
|
|
36
|
+
|
|
37
|
+
def update(self, message: str) -> None:
|
|
38
|
+
self.message = message
|
|
39
|
+
|
|
40
|
+
def start(self) -> "Spinner":
|
|
41
|
+
if self.enabled and self._thread is None:
|
|
42
|
+
self._draw()
|
|
43
|
+
self._thread = threading.Thread(target=self._run, daemon=True)
|
|
44
|
+
self._thread.start()
|
|
45
|
+
return self
|
|
46
|
+
|
|
47
|
+
def stop(self, final: str | None = None) -> None:
|
|
48
|
+
"""Stop animating and clear the line; optionally print ``final`` instead."""
|
|
49
|
+
if self._thread is not None:
|
|
50
|
+
self._stop.set()
|
|
51
|
+
self._thread.join()
|
|
52
|
+
self._thread = None
|
|
53
|
+
with self._lock:
|
|
54
|
+
self.stream.write("\r" + " " * self._width() + "\r")
|
|
55
|
+
self.stream.flush()
|
|
56
|
+
if final is not None and self.enabled:
|
|
57
|
+
self.stream.write(final + "\n")
|
|
58
|
+
self.stream.flush()
|
|
59
|
+
|
|
60
|
+
def __enter__(self) -> "Spinner":
|
|
61
|
+
return self.start()
|
|
62
|
+
|
|
63
|
+
def __exit__(self, *exc) -> None:
|
|
64
|
+
self.stop()
|
|
65
|
+
|
|
66
|
+
# ---- internals -------------------------------------------------------
|
|
67
|
+
def _width(self) -> int:
|
|
68
|
+
return max(20, shutil.get_terminal_size((80, 20)).columns - 1)
|
|
69
|
+
|
|
70
|
+
def _draw(self) -> None:
|
|
71
|
+
with self._lock:
|
|
72
|
+
frame = FRAMES[self._frame % len(FRAMES)]
|
|
73
|
+
self._frame += 1
|
|
74
|
+
text = f"{frame} {self.message}"[: self._width()]
|
|
75
|
+
self.stream.write("\r" + text.ljust(self._width()))
|
|
76
|
+
self.stream.flush()
|
|
77
|
+
|
|
78
|
+
def _run(self) -> None:
|
|
79
|
+
while not self._stop.wait(self.interval):
|
|
80
|
+
self._draw()
|
activy_checker/report.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Human-readable summaries and comparison output."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
|
|
6
|
+
from .compare import CompareResult
|
|
7
|
+
from .models import Activity, KIND_LABEL, format_duration
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def summarize(activities: list[Activity]) -> dict:
|
|
11
|
+
"""Aggregate counts, distance and duration per kind, plus totals."""
|
|
12
|
+
by_kind: dict[str, dict] = defaultdict(lambda: {"count": 0, "distance_km": 0.0, "duration_s": 0})
|
|
13
|
+
for a in activities:
|
|
14
|
+
b = by_kind[a.kind]
|
|
15
|
+
b["count"] += 1
|
|
16
|
+
b["distance_km"] += a.distance_km
|
|
17
|
+
b["duration_s"] += a.duration_s
|
|
18
|
+
total = {
|
|
19
|
+
"count": len(activities),
|
|
20
|
+
"distance_km": round(sum(a.distance_km for a in activities), 2),
|
|
21
|
+
"duration_s": sum(a.duration_s for a in activities),
|
|
22
|
+
}
|
|
23
|
+
for b in by_kind.values():
|
|
24
|
+
b["distance_km"] = round(b["distance_km"], 2)
|
|
25
|
+
return {"by_kind": dict(by_kind), "total": total}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def render_summary(title: str, activities: list[Activity]) -> str:
|
|
29
|
+
s = summarize(activities)
|
|
30
|
+
lines = [f"== {title} ==", ""]
|
|
31
|
+
lines.append(f"{'Kind':<10} {'Count':>5} {'Distance':>12} {'Time':>10}")
|
|
32
|
+
lines.append("-" * 40)
|
|
33
|
+
for kind, b in sorted(s["by_kind"].items(), key=lambda kv: -kv[1]["count"]):
|
|
34
|
+
lines.append(
|
|
35
|
+
f"{KIND_LABEL.get(kind, kind):<10} {b['count']:>5} "
|
|
36
|
+
f"{b['distance_km']:>9.1f} km {format_duration(b['duration_s']):>10}"
|
|
37
|
+
)
|
|
38
|
+
lines.append("-" * 40)
|
|
39
|
+
t = s["total"]
|
|
40
|
+
lines.append(
|
|
41
|
+
f"{'TOTAL':<10} {t['count']:>5} {t['distance_km']:>9.1f} km "
|
|
42
|
+
f"{format_duration(t['duration_s']):>10}"
|
|
43
|
+
)
|
|
44
|
+
return "\n".join(lines)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def render_comparison(result: CompareResult) -> str:
|
|
48
|
+
lines = ["== Comparison: Activy vs Garmin ==", ""]
|
|
49
|
+
lines.append(
|
|
50
|
+
f"Matched: {len(result.matched)} | "
|
|
51
|
+
f"Missing in Activy: {len(result.only_garmin)} | "
|
|
52
|
+
f"Missing in Garmin: {len(result.only_activy)} | "
|
|
53
|
+
f"Distance mismatches: {len(result.distance_mismatches)}"
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
lines.append("")
|
|
57
|
+
lines.append(f"-- Missing in Activy (present in Garmin, not imported) [{len(result.only_garmin)}] --")
|
|
58
|
+
if result.only_garmin:
|
|
59
|
+
for g in sorted(result.only_garmin, key=lambda x: x.start or ""):
|
|
60
|
+
lines.append(f" {g.date} {g.raw_type:<18} {g.distance_km:>7.2f} km {g.duration_hms}")
|
|
61
|
+
else:
|
|
62
|
+
lines.append(" (none)")
|
|
63
|
+
|
|
64
|
+
lines.append("")
|
|
65
|
+
lines.append(f"-- Missing in Garmin (present in Activy only) [{len(result.only_activy)}] --")
|
|
66
|
+
if result.only_activy:
|
|
67
|
+
for a in sorted(result.only_activy, key=lambda x: x.start or ""):
|
|
68
|
+
lines.append(f" {a.date} {a.raw_type:<18} {a.distance_km:>7.2f} km {a.duration_hms}")
|
|
69
|
+
else:
|
|
70
|
+
lines.append(" (none)")
|
|
71
|
+
|
|
72
|
+
lines.append("")
|
|
73
|
+
lines.append(f"-- Distance mismatches (same activity, different distance) [{len(result.distance_mismatches)}] --")
|
|
74
|
+
if result.distance_mismatches:
|
|
75
|
+
for m in sorted(result.distance_mismatches, key=lambda x: x.activy.start or ""):
|
|
76
|
+
lines.append(
|
|
77
|
+
f" {m.activy.date} Activy {m.activy.distance_km:>7.2f} km "
|
|
78
|
+
f"vs Garmin {m.garmin.distance_km:>7.2f} km (Δ {m.distance_delta_km:+.2f} km)"
|
|
79
|
+
)
|
|
80
|
+
else:
|
|
81
|
+
lines.append(" (none)")
|
|
82
|
+
|
|
83
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: activy-checker
|
|
3
|
+
Version: 0.2.6
|
|
4
|
+
Summary: Audit Activy's activity sync: detect missing activities and incorrect distances.
|
|
5
|
+
Author: Michał Kaftański
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/kaftee/activy-checker
|
|
8
|
+
Project-URL: Documentation, https://github.com/kaftee/activy-checker/blob/main/docs/usage.md
|
|
9
|
+
Project-URL: Changelog, https://github.com/kaftee/activy-checker/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Issues, https://github.com/kaftee/activy-checker/issues
|
|
11
|
+
Keywords: activy,garmin,fitness,activities,sync
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Utilities
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: garminconnect>=0.3.0
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
28
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# activy-checker
|
|
32
|
+
|
|
33
|
+
[](https://github.com/kaftee/activy-checker/actions/workflows/tests.yml)
|
|
34
|
+
|
|
35
|
+
Audit [Activy](https://activy.app)'s activity sync: detect activities that
|
|
36
|
+
never arrived and activities recorded with incorrect distances — and get a
|
|
37
|
+
clean summary of your training. It currently compares Activy with
|
|
38
|
+
[Garmin Connect](https://connect.garmin.com); other sources can be
|
|
39
|
+
[requested](https://github.com/kaftee/activy-checker#other-integrations).
|
|
40
|
+
|
|
41
|
+
Activy imports workouts from Garmin, but the import is not always complete: a
|
|
42
|
+
ride can silently never appear, or show up with the wrong distance. If Activy
|
|
43
|
+
powers a company or charity challenge, those gaps cost you points.
|
|
44
|
+
`activy-checker` logs into **your** two accounts, pulls your activities for a
|
|
45
|
+
date range and tells you exactly what is different.
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
Matched: 5 | Missing in Activy: 1 | Missing in Garmin: 0 | Distance mismatches: 1
|
|
49
|
+
|
|
50
|
+
-- Missing in Activy (present in Garmin, not imported) [1] --
|
|
51
|
+
2026-05-10 road_biking 98.40 km 3:12:00
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Why I built this
|
|
55
|
+
|
|
56
|
+
Activy's import from Garmin is not 100% reliable. I found out by pure chance:
|
|
57
|
+
one day I noticed that an activity recorded on my Garmin had never appeared in
|
|
58
|
+
Activy. Nothing warned me — not the app, not Activy.
|
|
59
|
+
|
|
60
|
+
When I contacted Activy support, I was not told about any errors on their
|
|
61
|
+
side, and they were not willing to look at the history of my earlier
|
|
62
|
+
activities to check whether anything else was missing. I found that strange:
|
|
63
|
+
if one activity can silently go missing, others can too, and I had no way to
|
|
64
|
+
check.
|
|
65
|
+
|
|
66
|
+
That is why I wrote `activy-checker` — so that anyone can verify their own
|
|
67
|
+
Activy history against Garmin instead of relying on luck.
|
|
68
|
+
|
|
69
|
+
## Features
|
|
70
|
+
|
|
71
|
+
- **Missing in Activy** — activities recorded on Garmin that never reached Activy.
|
|
72
|
+
- **Missing in Garmin** — activities that exist only in Activy (e.g. manual entries).
|
|
73
|
+
- **Distance mismatches** — the same activity stored with a different distance.
|
|
74
|
+
- **Summaries** — count, distance and time per activity kind, for each source.
|
|
75
|
+
- **JSON export** of everything above, for your own scripts or a support ticket.
|
|
76
|
+
- Passwords are prompted with `getpass` and never stored; the Garmin session can
|
|
77
|
+
optionally be cached so MFA is needed only once.
|
|
78
|
+
|
|
79
|
+
## Disclaimer
|
|
80
|
+
|
|
81
|
+
This is an **unofficial** tool, not affiliated with or endorsed by Activy or
|
|
82
|
+
Garmin. Activy has no public API, so `activy-checker` talks to the same mobile
|
|
83
|
+
endpoints the Activy app uses, signing in with your own credentials. Use it only
|
|
84
|
+
with **your own account and your own data**, at your own risk. The Activy API
|
|
85
|
+
can change without notice and break the tool.
|
|
86
|
+
|
|
87
|
+
## Quick start
|
|
88
|
+
|
|
89
|
+
Requires **Python 3.12+**. The easiest way is [pipx](https://pipx.pypa.io),
|
|
90
|
+
which installs the command in its own environment:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
pipx install activy-checker
|
|
94
|
+
activy-checker --garmin-tokenstore ~/.garminconnect
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
or with pip: `pip install activy-checker`. To work on the code, see
|
|
98
|
+
[Contributing](https://github.com/kaftee/activy-checker/blob/main/CONTRIBUTING.md).
|
|
99
|
+
|
|
100
|
+
You will be asked for your Activy email and password, then your Garmin email
|
|
101
|
+
and password and — if your Garmin account uses two-step verification — the
|
|
102
|
+
code Garmin emails you.
|
|
103
|
+
|
|
104
|
+
## Common commands
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
activy-checker # from 2026-09-01 (default)
|
|
108
|
+
activy-checker --since 2026-09-01 --until 2026-09-30
|
|
109
|
+
activy-checker --activy-only # just summarize Activy
|
|
110
|
+
activy-checker --garmin-tokenstore ~/.garminconnect # cache Garmin session
|
|
111
|
+
activy-checker --since 2026-09-01 --json result.json # machine-readable output
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
All options are described in [docs/usage.md](https://github.com/kaftee/activy-checker/blob/main/docs/usage.md).
|
|
115
|
+
|
|
116
|
+
## Example output
|
|
117
|
+
|
|
118
|
+
```
|
|
119
|
+
== Activy ==
|
|
120
|
+
|
|
121
|
+
Kind Count Distance Time
|
|
122
|
+
----------------------------------------
|
|
123
|
+
Bike 2 103.5 km 3:31:00
|
|
124
|
+
Run 2 9.3 km 1:27:00
|
|
125
|
+
Exercise 1 0.0 km 0:25:00
|
|
126
|
+
----------------------------------------
|
|
127
|
+
TOTAL 5 112.8 km 5:23:00
|
|
128
|
+
|
|
129
|
+
== Garmin ==
|
|
130
|
+
|
|
131
|
+
Kind Count Distance Time
|
|
132
|
+
----------------------------------------
|
|
133
|
+
Bike 3 201.9 km 6:43:01
|
|
134
|
+
Run 1 5.2 km 0:32:01
|
|
135
|
+
Walk 1 9.9 km 0:55:01
|
|
136
|
+
Exercise 1 0.0 km 0:25:00
|
|
137
|
+
----------------------------------------
|
|
138
|
+
TOTAL 6 217.0 km 8:35:03
|
|
139
|
+
|
|
140
|
+
== Comparison: Activy vs Garmin ==
|
|
141
|
+
|
|
142
|
+
Matched: 5 | Missing in Activy: 1 | Missing in Garmin: 0 | Distance mismatches: 1
|
|
143
|
+
|
|
144
|
+
-- Missing in Activy (present in Garmin, not imported) [1] --
|
|
145
|
+
2026-05-10 road_biking 98.40 km 3:12:00
|
|
146
|
+
|
|
147
|
+
-- Missing in Garmin (present in Activy only) [0] --
|
|
148
|
+
(none)
|
|
149
|
+
|
|
150
|
+
-- Distance mismatches (same activity, different distance) [1] --
|
|
151
|
+
2026-05-05 Activy 4.10 km vs Garmin 9.87 km (Δ -5.77 km)
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
(Sample data.) Note that the two summaries use each service's own categories:
|
|
155
|
+
Activy files Garmin walks and hikes under **Run**, so kinds are not expected to
|
|
156
|
+
line up one-to-one — the comparison matches individual activities, not kinds.
|
|
157
|
+
|
|
158
|
+
## Documentation
|
|
159
|
+
|
|
160
|
+
- [Usage](https://github.com/kaftee/activy-checker/blob/main/docs/usage.md) — every option, exit codes, JSON format, using it as a library
|
|
161
|
+
- [How it works](https://github.com/kaftee/activy-checker/blob/main/docs/how-it-works.md) — the Activy API, fetching, matching rules, type mapping
|
|
162
|
+
- [Troubleshooting](https://github.com/kaftee/activy-checker/blob/main/docs/troubleshooting.md) — login problems, Garmin rate limits, reading the results
|
|
163
|
+
- [Contributing](https://github.com/kaftee/activy-checker/blob/main/CONTRIBUTING.md) — development setup, tests and releases
|
|
164
|
+
- [Changelog](https://github.com/kaftee/activy-checker/blob/main/CHANGELOG.md)
|
|
165
|
+
|
|
166
|
+
## Other integrations
|
|
167
|
+
|
|
168
|
+
`activy-checker` currently compares Activy with **Garmin Connect** only. If
|
|
169
|
+
you use Activy with **Strava**, **Polar**, **Suunto** or another service and
|
|
170
|
+
would like it supported, please
|
|
171
|
+
[open a feature request](https://github.com/kaftee/activy-checker/issues/new?template=feature_request.yml)
|
|
172
|
+
and tell us which service you use.
|
|
173
|
+
|
|
174
|
+
Found a bug? [Report it here](https://github.com/kaftee/activy-checker/issues/new?template=bug_report.yml).
|
|
175
|
+
|
|
176
|
+
## License
|
|
177
|
+
|
|
178
|
+
MIT — see [LICENSE](https://github.com/kaftee/activy-checker/blob/main/LICENSE).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
activy_checker/__init__.py,sha256=uzCj3yE72texo_eW_5MGxWfKP3Fv1fEJZhMBjThd7ss,505
|
|
2
|
+
activy_checker/activy.py,sha256=Qkc1sGAaWws_5NL-HSmKUQ_eCO8ltxBlXssS8-4bHgc,9006
|
|
3
|
+
activy_checker/cli.py,sha256=p8PJdK0kH3zaOAeozyPAaMbrrmqFjSZyOKaC1GeyZJs,7936
|
|
4
|
+
activy_checker/compare.py,sha256=w9lOWwoEcxmJNnK8FGomepm3-y1GSauqXOKLZISve9M,2068
|
|
5
|
+
activy_checker/garmin.py,sha256=_jHapLTU31Tu0FIXb8gfVwc36vrLmuWdUacGivGTk8E,5342
|
|
6
|
+
activy_checker/models.py,sha256=_MdEkXKRZ3Hm7OyPpMj1X9hKIGa_RA2p8J-_z2H8HOw,1288
|
|
7
|
+
activy_checker/progress.py,sha256=5a-gfa2J9l2c8AyObmHomCoV67MvpeId0ACqCTb5mBo,2650
|
|
8
|
+
activy_checker/report.py,sha256=PDyFN0PpNzbe120R04QyQOCFh5fp-Sd78kwXNHadJUY,3305
|
|
9
|
+
activy_checker-0.2.6.dist-info/licenses/LICENSE,sha256=Ej6HgNvmPzBw5UGC0B7u-LpmFG67sT3ftrqXux4B3FA,1075
|
|
10
|
+
activy_checker-0.2.6.dist-info/METADATA,sha256=FtHTBXREpbBn1ffSlahBuc27Oqbl1rmodcQ0w-eEoGM,7637
|
|
11
|
+
activy_checker-0.2.6.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
12
|
+
activy_checker-0.2.6.dist-info/entry_points.txt,sha256=5HRV3hcJ0XFeVbbhWwmZBFhpGdr0y9amLG-QeUb6jYA,59
|
|
13
|
+
activy_checker-0.2.6.dist-info/top_level.txt,sha256=JxTL-D8nbrUK1fI6KwW_CbYwZi-TlBDtCc990wB-Oac,15
|
|
14
|
+
activy_checker-0.2.6.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Michał Kaftański
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
activy_checker
|