diff --git a/pyproject.toml b/pyproject.toml
index 22588d5..59884aa 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -13,16 +13,20 @@ dependencies = ["fitparse>=1.2", "timezonefinder>=6"]
[project.optional-dependencies]
api = ["garminconnect>=0.3.19", "curl_cffi"]
+app = ["pywebview>=6", "garminconnect>=0.3.19", "curl_cffi"]
dev = ["pytest"]
[project.scripts]
mygarmin = "mygarmin.cli:main"
+[project.gui-scripts]
+mygarmin-app = "mygarmin.app:main"
+
[tool.setuptools.packages.find]
where = ["src"]
[tool.setuptools.package-data]
-mygarmin = ["report/*.html"]
+mygarmin = ["report/*.html", "app/*.html"]
[tool.pytest.ini_options]
testpaths = ["tests"]
diff --git a/src/mygarmin/app/__init__.py b/src/mygarmin/app/__init__.py
new file mode 100644
index 0000000..fdaddc9
--- /dev/null
+++ b/src/mygarmin/app/__init__.py
@@ -0,0 +1,240 @@
+"""The myGarmin desktop window (pywebview): a single HTML page (ui.html) talking to Api below.
+Long jobs run one at a time in a worker thread and stream their log lines into the page."""
+import json, os, sys, threading, traceback
+from datetime import datetime, timedelta
+from zoneinfo import available_timezones, ZoneInfo
+from .. import __version__
+from ..library import Library
+
+STATE = os.path.join(os.environ.get('LOCALAPPDATA') or os.path.expanduser('~/.local/share'), 'myGarmin', 'app.json')
+POPULAR = ['Africa/Johannesburg', 'Europe/London', 'Europe/Amsterdam', 'Europe/Berlin', 'America/New_York', 'America/Chicago',
+ 'America/Los_Angeles', 'Australia/Sydney', 'Pacific/Auckland', 'Asia/Dubai', 'Asia/Singapore', 'UTC']
+
+def _app_state():
+ try: return json.load(open(STATE, encoding='utf-8'))
+ except (OSError, ValueError): return {}
+
+def _save_app_state(**kw):
+ s = {**_app_state(), **kw}; os.makedirs(os.path.dirname(STATE), exist_ok=True)
+ json.dump(s, open(STATE, 'w', encoding='utf-8'), indent=1)
+
+def guess_tz():
+ """An IANA zone with this PC's current UTC offset (Windows only reports its own zone names)."""
+ off = datetime.now().astimezone().utcoffset()
+ return next((z for z in POPULAR if datetime.now(ZoneInfo(z)).utcoffset() == off), 'UTC')
+
+
+class Api:
+ def __init__(self):
+ self._window = None; self._lib = None; self._busy = None
+ self._mfa = threading.Event(); self._mfa_code = None
+ last = _app_state().get('library')
+ if last and os.path.exists(os.path.join(last, 'settings.json')):
+ try: self._lib = Library(last)
+ except Exception: self._lib = None
+
+ # ---- helpers ----
+ def _js(self, fn, *args):
+ if self._window: self._window.evaluate_js(f'ui.{fn}(' + ','.join(json.dumps(a, default=str) for a in args) + ')')
+
+ def _log(self, *parts): self._js('log', ' '.join(str(p) for p in parts))
+
+ def _job(self, name, fn):
+ if self._busy: return {'ok': False, 'error': f'Busy with "{self._busy}"'}
+ if not self._lib and name != 'login': return {'ok': False, 'error': 'Open or create a library first'}
+ self._busy = name
+ def run():
+ ok = True
+ try: fn()
+ except SystemExit as e: ok = False; self._log('Stopped:', e)
+ except Exception as e: ok = False; self._log('Error:', type(e).__name__, e); self._log(traceback.format_exc(limit=3))
+ finally:
+ self._busy = None
+ self._js('done', name, ok, self.state())
+ threading.Thread(target=run, daemon=True).start()
+ return {'ok': True}
+
+ # ---- state ----
+ def state(self):
+ s = {'version': __version__, 'busy': self._busy, 'library': None, 'recent': _app_state().get('recent', []),
+ 'timezones': sorted(available_timezones()), 'tz_guess': guess_tz()}
+ if not self._lib: return s
+ lib = self._lib
+ from ..sources import garmin_api
+ rows = lib.db.execute("SELECT source, count(*) n, sum(dup_of IS NULL AND (flag IS NULL OR flag IN ('suspect GPS','summary only'))) shown, "
+ "max(start_local) last FROM activities GROUP BY source ORDER BY source").fetchall()
+ hd = lib.db.execute('SELECT count(*), min(date), max(date) FROM health_days').fetchone()
+ dash = lib.path('dashboard.html')
+ s['library'] = {'root': lib.root, 'settings': lib.settings,
+ 'sources': [dict(r) for r in rows], 'shown': sum(r['shown'] or 0 for r in rows),
+ 'last_activity': max((r['last'] for r in rows if r['last']), default=None),
+ 'health': {'days': hd[0], 'first': hd[1], 'last': hd[2]},
+ 'garmin_login': os.path.exists(os.path.join(garmin_api.token_dir(lib), 'garmin_tokens.json')),
+ 'dashboard': datetime.fromtimestamp(os.path.getmtime(dash)).strftime('%Y-%m-%d %H:%M') if os.path.exists(dash) else None,
+ 'exports': os.path.exists(lib.path('exports', 'tracks_trk.zip'))}
+ return s
+
+ # ---- library ----
+ def pick_folder(self):
+ import webview
+ r = self._window.create_file_dialog(webview.FileDialog.FOLDER)
+ return r[0] if r else None
+
+ def pick_files(self):
+ import webview
+ r = self._window.create_file_dialog(webview.FileDialog.OPEN, allow_multiple=True,
+ file_types=('Activity and export files (*.zip;*.fit;*.tcx;*.gpx;*.trk;*.gz)', 'All files (*.*)'))
+ return list(r) if r else []
+
+ def _use(self, lib):
+ self._lib = lib
+ recent = [lib.root] + [r for r in _app_state().get('recent', []) if r != lib.root]
+ _save_app_state(library=lib.root, recent=recent[:8])
+ return self.state()
+
+ def create_library(self, path, name, birth_year, sex, tz):
+ if not path: return {'error': 'Choose a folder for the library'}
+ ZoneInfo(tz)
+ return self._use(Library.create(path, name=name or None, birth_year=int(birth_year) if birth_year else None, sex=sex or None, home_tz=tz))
+
+ def open_library(self, path):
+ if not path or not os.path.exists(os.path.join(path, 'settings.json')):
+ return {'error': 'That folder is not a myGarmin library (no settings.json). Create a new library there instead.'}
+ return self._use(Library(path))
+
+ def close_library(self):
+ self._lib = None; _save_app_state(library=None); return self.state()
+
+ def save_settings(self, name, birth_year, sex, tz, copies):
+ ZoneInfo(tz)
+ lib = Library.create(self._lib.root, name=name or None, birth_year=int(birth_year) if birth_year else None, sex=sex or None, home_tz=tz)
+ p = lib.path('settings.json'); s = json.load(open(p, encoding='utf-8'))
+ s['copy_dashboard_to'] = [c.strip() for c in (copies or '').splitlines() if c.strip()]
+ json.dump(s, open(p, 'w', encoding='utf-8'), indent=1)
+ return self._use(Library(lib.root))
+
+ # ---- jobs ----
+ def import_paths(self, paths):
+ from .. import dedupe, sources
+ def run():
+ for p in paths:
+ self._log('Importing', p)
+ st = sources.import_path(self._lib, p, log=self._log)
+ for k, v in sorted(st.items()): self._log(f' {v:6d} {k}')
+ self._log(dedupe.run(self._lib), 'recordings marked as copies of the same outing from another source')
+ self._build()
+ return self._job('import', run)
+
+ def _build(self):
+ from .. import report
+ report.build(self._lib, log=self._log)
+
+ def watch(self):
+ import shutil
+ from .. import dedupe, sources
+ from ..sources import watch
+ def run():
+ d = watch.pull(log=self._log)
+ if not d: return
+ try:
+ for k, v in sorted(sources.import_path(self._lib, d, log=self._log).items()): self._log(f' {v:6d} {k}')
+ finally: shutil.rmtree(d, ignore_errors=True)
+ self._log(dedupe.run(self._lib), 'recordings marked as copies'); self._build()
+ return self._job('watch', run)
+
+ def sync(self):
+ from .. import dedupe
+ from ..sources import garmin_api
+ def run():
+ self._log('Garmin Connect: fetching new activities and daily health…')
+ garmin_api.sync(self._lib, log=self._log)
+ self._log(dedupe.run(self._lib), 'recordings marked as copies'); self._build()
+ return self._job('sync', run)
+
+ def build(self): return self._job('build', self._build)
+
+ def export(self):
+ from .. import export
+ return self._job('export', lambda: export.run(self._lib, log=self._log))
+
+ def update(self, use_watch=True, use_api=True):
+ import shutil
+ from .. import dedupe, export, sources
+ from ..sources import garmin_api, watch
+ def run():
+ if use_watch:
+ d = watch.pull(log=self._log)
+ if d:
+ try:
+ for k, v in sorted(sources.import_path(self._lib, d, log=self._log).items()): self._log(f' {v:6d} {k}')
+ finally: shutil.rmtree(d, ignore_errors=True)
+ if use_api and os.path.exists(os.path.join(garmin_api.token_dir(self._lib), 'garmin_tokens.json')):
+ self._log('Garmin Connect: fetching new activities and daily health…'); garmin_api.sync(self._lib, log=self._log)
+ elif use_api: self._log('Garmin Connect: not logged in, skipped')
+ self._log(dedupe.run(self._lib), 'recordings marked as copies'); self._build()
+ export.run(self._lib, log=self._log)
+ return self._job('update', run)
+
+ # ---- Garmin login (the MFA code is asked for in the page while the login waits) ----
+ def login(self, email, password):
+ from ..sources import garmin_api
+ def ask():
+ self._mfa.clear(); self._js('askMfa')
+ if not self._mfa.wait(300): raise SystemExit('no MFA code entered')
+ return self._mfa_code
+ def run():
+ self._log('Logged in to Garmin Connect as', garmin_api.login(self._lib, email, password, ask), '(token kept on this PC only)')
+ return self._job('login', run)
+
+ def mfa(self, code): self._mfa_code = (code or '').strip(); self._mfa.set()
+
+ def logout(self):
+ import shutil
+ from ..sources import garmin_api
+ shutil.rmtree(garmin_api.token_dir(self._lib), ignore_errors=True); return self.state()
+
+ # ---- open things ----
+ def open_dashboard(self):
+ p = self._lib.path('dashboard.html')
+ if os.path.exists(p): os.startfile(p) if sys.platform == 'win32' else __import__('webbrowser').open('file://' + p)
+
+ def open_folder(self, sub=''):
+ p = self._lib.path(sub) if sub else self._lib.root
+ if sys.platform == 'win32': os.startfile(p)
+ else: __import__('subprocess').run(['open' if sys.platform == 'darwin' else 'xdg-open', p])
+
+
+def main():
+ try:
+ import webview
+ from webview.dom import DOMEventHandler
+ except ImportError:
+ raise SystemExit('The app window needs pywebview: pip install "mygarmin[app]"')
+ if sys.platform == 'win32': # a second window would share (and block on) the same browser data folder
+ import ctypes
+ main._mutex = ctypes.windll.kernel32.CreateMutexW(None, False, 'Local\\myGarminApp')
+ if ctypes.windll.kernel32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
+ ctypes.windll.user32.MessageBoxW(None, 'myGarmin is already open.', 'myGarmin', 0x40)
+ return
+ api = Api()
+ win = webview.create_window(f'myGarmin {__version__}', os.path.join(os.path.dirname(__file__), 'ui.html'), js_api=api,
+ width=1180, height=860, min_size=(760, 600), background_color='#f7f7f4')
+ api._window = win
+
+ def on_drop(e):
+ paths = [f.get('pywebviewFullPath') for f in e['dataTransfer'].get('files', []) if f.get('pywebviewFullPath')]
+ if paths: api._js('dropped', paths)
+ def loaded():
+ el = win.dom.get_element('#drop')
+ if el:
+ el.events.dragover += DOMEventHandler(lambda e: None, prevent_default=True)
+ el.events.drop += DOMEventHandler(on_drop, prevent_default=True, stop_propagation=True)
+ win.events.loaded += loaded
+ if os.environ.get('MYGARMIN_SELFTEST'): # developer check: does the page render through the real bridge?
+ def selftest():
+ import time; time.sleep(6)
+ r = win.evaluate_js("[document.getElementById('home').className, document.getElementById('setup').className, "
+ "document.getElementById('tiles').innerText.replace(/\\s+/g, ' ').slice(0, 120)].join(' | ')")
+ open(os.environ['MYGARMIN_SELFTEST'], 'w', encoding='utf-8').write(str(r)); win.destroy()
+ threading.Thread(target=selftest, daemon=True).start()
+ webview.start(private_mode=False, storage_path=os.path.join(os.path.dirname(STATE), 'webview'))
diff --git a/src/mygarmin/app/ui.html b/src/mygarmin/app/ui.html
new file mode 100644
index 0000000..c6bcc91
--- /dev/null
+++ b/src/mygarmin/app/ui.html
@@ -0,0 +1,273 @@
+
+
+
+
+
+myGarmin
+
+
+
+
+
myGarmin
+
+
+
+
+
+
+
+
+
+
Welcome
+
myGarmin keeps your activity and health history in one library folder on this PC: the original files, a database and your dashboard. Nothing is uploaded anywhere.
+
+
+
+
Create a new library
+
+
+
+
+
+
+
+
Birth year and sex are used only to rate VO2max and show ages; leave them empty if you prefer.
+
+
+
+
Open an existing library
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Keep it up to date
+
Reads the watch if it is connected by USB, fetches new data from Garmin Connect, then rebuilds the dashboard and the track exports.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Add data
+
+ Drop files or folders here
+ Garmin or Strava export zips, a copied watch GARMIN folder, or .fit .tcx .gpx .trk files
+
+
+
+
+
+
+ Where do I get my data?
+
+
Garmin Connect
garmin.com → Account → Data Management → Export Your Data. Garmin e-mails a zip (can take days); drop it here as is. Gives all activities plus daily sleep, HRV, stress and more.
+
Strava
strava.com → Settings → My Account → Download or Delete Your Account → Request your archive. Drop the zip here as is.
+
AlpineQuest
Copy the .trk files from the phone (AlpineQuest folder) to the PC and drop them here.
+
Garmin watch
Connect it by USB and press Read watch. Newer watches only keep a few weeks of data, so do this regularly or use Garmin Connect.
+
Races
Optional: put a races.csv in the library folder with date,event,time and optionally km,age_grade,position,pb.
+
+
+
+
+
+
+
Garmin Connect
+
+
Logged in· the login token is kept on this PC only
+
+
+
+
Not logged in. Garmin has no official personal API; this logs in the way the Connect app does and may stop working when Garmin changes its login. Your password is not stored.
+
+
+
+
+
+
+
+
+
+
+
+
What is in the library
+
+
+
+
+
+
+
+
+ Settings
+
+
+
+
+
+
+
+
Rebuild the dashboard afterwards to apply.
+
+
+
+
+
Log
+
+
+
+
+
+
+
+
+
+
diff --git a/src/mygarmin/library.py b/src/mygarmin/library.py
index 9ecde32..37e9605 100644
--- a/src/mygarmin/library.py
+++ b/src/mygarmin/library.py
@@ -30,7 +30,7 @@ class Library:
p = os.path.join(self.root, 'settings.json')
if not os.path.exists(p): raise FileNotFoundError(f'{self.root} is not a myGarmin library (no settings.json); run "mygarmin init" first')
self.settings = {**DEFAULTS, **json.load(open(p, encoding='utf-8'))}
- self.db = sqlite3.connect(os.path.join(self.root, 'myGarmin.db'))
+ self.db = sqlite3.connect(os.path.join(self.root, 'myGarmin.db'), check_same_thread=False) # the app runs jobs in a worker thread, one at a time
self.db.row_factory = sqlite3.Row
self.db.executescript(SCHEMA)
diff --git a/src/mygarmin/report/__init__.py b/src/mygarmin/report/__init__.py
index c4b8bed..1f5b1c4 100644
--- a/src/mygarmin/report/__init__.py
+++ b/src/mygarmin/report/__init__.py
@@ -1,5 +1,5 @@
"""Build the self-contained dashboard (dashboard.html) and an all_activities.csv from the library."""
-import csv, json, os
+import csv, json, os, shutil
from datetime import datetime
from .. import __version__
@@ -56,4 +56,7 @@ def build(lib, out=None, log=print):
w.writerow(['' if a.get(c) is None else a[c] for c in CSV_COLS])
log(f"{len(d['acts'])} activities, {len(d['tracks'])} tracks, {len(d['health']['days']) if d['health'] else 0} health days, "
f"{len(d['races'])} races -> {out}")
+ for p in lib.settings.get('copy_dashboard_to') or []: # e.g. a synced folder; settings.json: "copy_dashboard_to": [...]
+ try: shutil.copyfile(out, p); log(f' copied to {p}')
+ except OSError as e: log(f' could not copy to {p}: {e}')
return out
diff --git a/tests/test_app_api.py b/tests/test_app_api.py
new file mode 100644
index 0000000..e253f62
--- /dev/null
+++ b/tests/test_app_api.py
@@ -0,0 +1,29 @@
+"""The app's Api without a window: library create/open, settings, and jobs running in the worker thread."""
+import time
+import pytest
+from mygarmin import app
+from test_pipeline import inbox # noqa: F401 (fixture)
+
+def wait(api):
+ for _ in range(600):
+ if not api._busy: return
+ time.sleep(0.05)
+ raise TimeoutError(api._busy)
+
+def test_app_api(tmp_path, inbox, monkeypatch):
+ monkeypatch.setattr(app, 'STATE', str(tmp_path / 'app.json'))
+ api = app.Api()
+ assert api.state()['library'] is None
+ s = api.create_library(str(tmp_path / 'lib'), 'Sam', '1990', 'F', 'Europe/London')
+ assert s['library']['settings']['name'] == 'Sam' and s['recent'] == [str(tmp_path / 'lib')]
+ assert api.import_paths([str(inbox)])['ok']
+ assert not api.build()['ok'] # one job at a time
+ wait(api)
+ st = api.state()['library']
+ assert st['shown'] == 4 and st['health']['days'] == 2 and st['dashboard']
+ assert api.export()['ok']; wait(api)
+ assert api.state()['library']['exports']
+ s = api.save_settings('Sam B', '1990', 'F', 'Europe/London', 'C:\\x\\a.html\n\n')
+ assert s['library']['settings']['copy_dashboard_to'] == ['C:\\x\\a.html']
+ assert app.Api().state()['library']['root'] == str(tmp_path / 'lib') # reopens the last library
+ assert api.open_library(str(tmp_path))['error']