Phase 2 start: desktop window (pywebview)

Setup screen (create/open library), update buttons, drag-and-drop import, Garmin Connect
login with MFA prompt, sources overview, settings, live log. Jobs run one at a time in a
worker thread. Single instance on Windows. Dashboard can be copied to extra paths
(copy_dashboard_to). App API test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-17 12:56:32 +02:00
parent 8e7f13477d
commit 462d23ba9d
6 changed files with 552 additions and 3 deletions

View File

@@ -13,16 +13,20 @@ dependencies = ["fitparse>=1.2", "timezonefinder>=6"]
[project.optional-dependencies] [project.optional-dependencies]
api = ["garminconnect>=0.3.19", "curl_cffi"] api = ["garminconnect>=0.3.19", "curl_cffi"]
app = ["pywebview>=6", "garminconnect>=0.3.19", "curl_cffi"]
dev = ["pytest"] dev = ["pytest"]
[project.scripts] [project.scripts]
mygarmin = "mygarmin.cli:main" mygarmin = "mygarmin.cli:main"
[project.gui-scripts]
mygarmin-app = "mygarmin.app:main"
[tool.setuptools.packages.find] [tool.setuptools.packages.find]
where = ["src"] where = ["src"]
[tool.setuptools.package-data] [tool.setuptools.package-data]
mygarmin = ["report/*.html"] mygarmin = ["report/*.html", "app/*.html"]
[tool.pytest.ini_options] [tool.pytest.ini_options]
testpaths = ["tests"] testpaths = ["tests"]

View File

@@ -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'))

273
src/mygarmin/app/ui.html Normal file
View File

@@ -0,0 +1,273 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>myGarmin</title>
<style>
/* Same visual language as the dashboard; fonts fall back to system ones so the app works offline */
:root {
--bg: #f7f7f4; --surface: #ffffff; --fg: #171a17; --muted: #5d625c; --rule: #dfe1db; --accent: #1f6f5c; --accent-fg: #ffffff;
--warn: #b5560f; --bad: #b3261e; --good: #1f6f5c;
--display: "Fraunces", Georgia, serif; --body: "IBM Plex Sans", "Segoe UI", system-ui, sans-serif; --mono: "IBM Plex Mono", Consolas, ui-monospace, monospace;
color-scheme: light;
}
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) {
--bg: #141613; --surface: #1c1f1b; --fg: #eceee9; --muted: #a4a9a2; --rule: #2f332e; --accent: #5fc2a6; --accent-fg: #0d1f19;
--warn: #e39a52; --bad: #ef7b72; --good: #5fc2a6; color-scheme: dark } }
* { box-sizing: border-box }
body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.5 var(--body) }
header.top { display: flex; align-items: center; gap: 16px; padding: 14px 24px; border-bottom: 1px solid var(--rule); background: var(--surface); position: sticky; top: 0; z-index: 5 }
header.top h1 { font: 600 22px var(--display); margin: 0 }
header.top .lib { color: var(--muted); font: 12px var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0 }
main { max-width: 1180px; margin: 0 auto; padding: 24px; display: grid; gap: 20px }
h2 { font: 600 18px var(--display); margin: 0 0 8px }
h3 { font: 600 14px var(--body); margin: 0 0 6px }
p { margin: 0 0 8px }
.muted, .note { color: var(--muted) }
.note { font-size: 13px }
.card { background: var(--surface); border: 1px solid var(--rule); border-radius: 8px; padding: 16px 18px; min-width: 0 }
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr)); gap: 20px; align-items: start }
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px }
.tile { background: var(--surface); border: 1px solid var(--rule); border-radius: 8px; padding: 12px 16px }
.tile b { display: block; font: 600 24px var(--display); font-variant-numeric: tabular-nums }
.tile span { color: var(--muted); font-size: 12px }
button, .btn { font: 500 14px var(--body); border-radius: 6px; padding: 8px 14px; border: 1px solid var(--rule); background: var(--surface); color: var(--fg); cursor: pointer }
button.primary { background: var(--accent); color: var(--accent-fg); border-color: var(--accent); font-weight: 600 }
button.big { padding: 12px 22px; font-size: 15px }
button:disabled { opacity: .5; cursor: default }
button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px }
button.link { border: 0; background: none; color: var(--accent); padding: 0; text-decoration: underline }
.row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center }
label { display: grid; gap: 4px; font-size: 13px; color: var(--muted) }
input, select, textarea { font: 14px var(--body); background: var(--bg); color: var(--fg); border: 1px solid var(--rule); border-radius: 6px; padding: 7px 9px; width: 100% }
textarea { font: 12px var(--mono); min-height: 52px }
.form { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)) }
.form .wide { grid-column: 1 / -1 }
#drop { border: 2px dashed var(--rule); border-radius: 10px; padding: 26px 18px; text-align: center; transition: border-color .15s, background .15s }
#drop.over { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, transparent) }
#drop b { font: 600 16px var(--display); display: block; margin-bottom: 4px }
table { border-collapse: collapse; width: 100%; font-size: 13px; font-variant-numeric: tabular-nums }
th, td { padding: 5px 8px; text-align: right; border-bottom: 1px solid var(--rule) }
th:first-child, td:first-child { text-align: left }
#log { font: 12px/1.45 var(--mono); background: var(--bg); border: 1px solid var(--rule); border-radius: 6px; padding: 10px; height: 260px; overflow: auto; white-space: pre-wrap; margin: 0 }
.status { display: inline-flex; align-items: center; gap: 6px; font-size: 13px }
.dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; background: var(--muted) }
.dot.ok { background: var(--good) } .dot.off { background: var(--warn) }
.busy { color: var(--accent); font-weight: 600 }
details > summary { cursor: pointer; font: 600 14px var(--body); list-style-position: inside }
details[open] > summary { margin-bottom: 10px }
.help td, .help th { text-align: left; vertical-align: top }
.recent button { font: 12px var(--mono); text-align: left; width: 100% }
.hidden { display: none !important }
@media (prefers-reduced-motion: reduce) { * { transition: none !important } }
</style>
</head>
<body>
<header class="top">
<h1>myGarmin</h1>
<div class="lib" id="libPath"></div>
<span class="busy hidden" id="busy" role="status" aria-live="polite"></span>
<button id="switchLib" class="hidden" onclick="ui.call('close_library').then(ui.render)">Switch library</button>
</header>
<main>
<!-- no library yet -->
<section id="setup" class="hidden">
<div class="card">
<h2>Welcome</h2>
<p class="muted">myGarmin keeps your activity and health history in one <b>library folder</b> on this PC: the original files, a database and your dashboard. Nothing is uploaded anywhere.</p>
</div>
<div class="grid2" style="margin-top:20px">
<div class="card">
<h2>Create a new library</h2>
<div class="form">
<label class="wide">Folder<div class="row" style="flex-wrap:nowrap"><input id="newPath" placeholder="e.g. D:\myGarmin"><button onclick="ui.pick('newPath')">Browse…</button></div></label>
<label>Your name<input id="newName" placeholder="shown on the dashboard"></label>
<label>Birth year<input id="newBirth" type="number" min="1900" max="2030" placeholder="for age comparisons"></label>
<label>Sex<select id="newSex"><option value="">Not set</option><option value="M">Male</option><option value="F">Female</option></select></label>
<label>Home time zone<input id="newTz" list="tzList"></label>
</div>
<p class="note" style="margin-top:8px">Birth year and sex are used only to rate VO2max and show ages; leave them empty if you prefer.</p>
<button class="primary" onclick="ui.create()">Create library</button>
</div>
<div class="card">
<h2>Open an existing library</h2>
<div class="row" style="flex-wrap:nowrap"><input id="openPath" placeholder="library folder"><button onclick="ui.pick('openPath')">Browse…</button><button class="primary" onclick="ui.open()">Open</button></div>
<div id="recent" class="recent" style="margin-top:12px;display:grid;gap:6px"></div>
</div>
</div>
</section>
<!-- library open -->
<section id="home" class="hidden" style="display:grid;gap:20px">
<div class="tiles" id="tiles"></div>
<div class="card">
<div class="row" style="justify-content:space-between">
<div>
<h2 style="margin:0">Keep it up to date</h2>
<p class="note" style="margin:2px 0 0">Reads the watch if it is connected by USB, fetches new data from Garmin Connect, then rebuilds the dashboard and the track exports.</p>
</div>
<button class="primary big job" onclick="ui.job('update', true, true)">Update everything</button>
</div>
<div class="row" style="margin-top:12px">
<button class="job" onclick="ui.job('watch')">Read watch (USB)</button>
<button class="job" onclick="ui.job('sync')">Sync Garmin Connect</button>
<button class="job" onclick="ui.job('build')">Rebuild dashboard</button>
<button class="job" onclick="ui.job('export')">Export tracks (GPX + AlpineQuest)</button>
<span style="flex:1"></span>
<button onclick="ui.call('open_dashboard')" id="openDash">Open dashboard</button>
<button onclick="ui.call('open_folder', 'exports')">Open exports</button>
<button onclick="ui.call('open_folder')">Open library folder</button>
</div>
</div>
<div class="grid2">
<div class="card">
<h2>Add data</h2>
<div id="drop">
<b>Drop files or folders here</b>
<span class="muted">Garmin or Strava export zips, a copied watch <code>GARMIN</code> folder, or .fit .tcx .gpx .trk files</span>
<div class="row" style="justify-content:center;margin-top:12px">
<button class="job" onclick="ui.chooseFiles()">Choose files…</button>
<button class="job" onclick="ui.chooseFolder()">Choose a folder…</button>
</div>
</div>
<details style="margin-top:14px">
<summary>Where do I get my data?</summary>
<table class="help">
<tr><th>Garmin Connect</th><td>garmin.com → Account → Data Management → <b>Export Your Data</b>. Garmin e-mails a zip (can take days); drop it here as is. Gives all activities plus daily sleep, HRV, stress and more.</td></tr>
<tr><th>Strava</th><td>strava.com → Settings → My Account → <b>Download or Delete Your Account</b> → Request your archive. Drop the zip here as is.</td></tr>
<tr><th>AlpineQuest</th><td>Copy the <code>.trk</code> files from the phone (AlpineQuest folder) to the PC and drop them here.</td></tr>
<tr><th>Garmin watch</th><td>Connect it by USB and press <b>Read watch</b>. Newer watches only keep a few weeks of data, so do this regularly or use Garmin Connect.</td></tr>
<tr><th>Races</th><td>Optional: put a <code>races.csv</code> in the library folder with <code>date,event,time</code> and optionally <code>km,age_grade,position,pb</code>.</td></tr>
</table>
</details>
</div>
<div style="display:grid;gap:20px">
<div class="card">
<h2>Garmin Connect</h2>
<div id="gcIn" class="hidden">
<p><span class="status"><i class="dot ok"></i>Logged in</span> <span class="note">· the login token is kept on this PC only</span></p>
<button class="link" onclick="ui.call('logout').then(ui.render)">Log out</button>
</div>
<div id="gcOut" class="hidden">
<p class="note"><span class="status"><i class="dot off"></i>Not logged in.</span> 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.</p>
<div class="form">
<label>E-mail<input id="gcEmail" type="email" autocomplete="username"></label>
<label>Password<input id="gcPass" type="password" autocomplete="current-password"></label>
</div>
<div class="row" style="margin-top:10px"><button class="primary job" onclick="ui.login()">Log in</button></div>
</div>
<div id="gcMfa" class="hidden" style="margin-top:10px">
<label>Code from your authenticator app or e-mail<div class="row" style="flex-wrap:nowrap"><input id="mfaCode" inputmode="numeric" autocomplete="one-time-code"><button class="primary" onclick="ui.sendMfa()">Send</button></div></label>
</div>
</div>
<div class="card">
<h2>What is in the library</h2>
<table id="srcTable"></table>
<p class="note" id="healthLine" style="margin-top:8px"></p>
</div>
</div>
</div>
<div class="card">
<details id="settingsBox">
<summary>Settings</summary>
<div class="form">
<label>Name<input id="sName"></label>
<label>Birth year<input id="sBirth" type="number" min="1900" max="2030"></label>
<label>Sex<select id="sSex"><option value="">Not set</option><option value="M">Male</option><option value="F">Female</option></select></label>
<label>Home time zone<input id="sTz" list="tzList"></label>
<label class="wide">Also copy the dashboard to (one path per line, e.g. a OneDrive folder)<textarea id="sCopies"></textarea></label>
</div>
<div class="row" style="margin-top:10px"><button class="primary" onclick="ui.saveSettings()">Save settings</button><span class="note">Rebuild the dashboard afterwards to apply.</span></div>
</details>
</div>
<div class="card">
<div class="row" style="justify-content:space-between"><h2 style="margin:0">Log</h2><button class="link" onclick="document.getElementById('log').textContent=''">Clear</button></div>
<pre id="log" aria-live="polite"></pre>
</div>
</section>
<datalist id="tzList"></datalist>
<p class="note" id="foot"></p>
</main>
<script>
const $ = id => document.getElementById(id);
let S = null;
const ui = {
async call(fn, ...args) {
try { return await window.pywebview.api[fn](...args) } catch (e) { ui.log('Error: ' + (e.message || e)); return null }
},
log(line) { const l = $('log'); if (!l) return; l.textContent += line + '\n'; l.scrollTop = l.scrollHeight },
async render(state) {
S = state || await ui.call('state'); if (!S) return;
if (S.error) { alert(S.error); S = await ui.call('state') }
$('foot').textContent = `myGarmin ${S.version}`;
if (!$('tzList').children.length) $('tzList').innerHTML = S.timezones.map(z => `<option value="${z}">`).join('');
const L = S.library;
$('setup').classList.toggle('hidden', !!L); $('home').classList.toggle('hidden', !L); $('switchLib').classList.toggle('hidden', !L);
$('libPath').textContent = L ? L.root : '';
ui.busy(S.busy);
if (!L) {
if (!$('newTz').value) $('newTz').value = S.tz_guess;
$('recent').innerHTML = S.recent.length ? '<p class="note" style="margin:0">Recently used</p>' + S.recent.map(r => `<button data-p="${r.replace(/"/g, '&quot;')}">${r.replace(/</g, '&lt;')}</button>`).join('') : '';
$('recent').querySelectorAll('button').forEach(b => b.onclick = () => { $('openPath').value = b.dataset.p; ui.open() });
return;
}
const n = v => (v ?? 0).toLocaleString();
$('tiles').innerHTML = [[n(L.shown), 'activities on the dashboard'], [L.last_activity ? L.last_activity.slice(0, 10) : '—', 'latest activity'],
[n(L.health.days), 'days of health data'], [L.health.last || '—', 'latest health day'], [L.dashboard || 'not built yet', 'dashboard built']]
.map(([v, l]) => `<div class="tile"><b>${v}</b><span>${l}</span></div>`).join('');
const label = { fit: 'Garmin (FIT)', tcx: 'Garmin (TCX)', alpinequest: 'AlpineQuest', strava: 'Strava', gpx: 'GPX' };
$('srcTable').innerHTML = '<thead><tr><th>Source</th><th>Recordings</th><th>On dashboard</th><th>Latest</th></tr></thead><tbody>' +
(L.sources.length ? L.sources.map(r => `<tr><td>${label[r.source] || r.source}</td><td>${n(r.n)}</td><td>${n(r.shown)}</td><td>${(r.last || '').slice(0, 10)}</td></tr>`).join('')
: '<tr><td colspan="4" class="muted">Nothing yet: add some data.</td></tr>') + '</tbody>';
$('healthLine').textContent = L.health.days ? `Daily health ${L.health.first} to ${L.health.last}. Recordings left out of the dashboard are copies of an outing another source also recorded, transport, or too short.` : 'No daily health data yet: import a Garmin Connect export or log in to Garmin Connect.';
$('gcIn').classList.toggle('hidden', !L.garmin_login); $('gcOut').classList.toggle('hidden', L.garmin_login);
$('openDash').disabled = !L.dashboard;
const s = L.settings;
if (!$('settingsBox').open) { $('sName').value = s.name || ''; $('sBirth').value = s.birth_year || ''; $('sSex').value = s.sex || ''; $('sTz').value = s.home_tz || 'UTC';
$('sCopies').value = (s.copy_dashboard_to || []).join('\n') }
},
busy(name) {
$('busy').textContent = name ? `Working: ${name}…` : ''; $('busy').classList.toggle('hidden', !name);
document.querySelectorAll('button.job').forEach(b => b.disabled = !!name);
},
async job(fn, ...args) {
const r = await ui.call(fn, ...args);
if (r && !r.ok) { ui.log(r.error); return }
ui.busy(fn); ui.log(`— ${fn} started ${new Date().toLocaleTimeString()}`);
},
done(name, ok, state) { ui.log(`— ${name} ${ok ? 'finished' : 'stopped'} ${new Date().toLocaleTimeString()}`); $('gcMfa').classList.add('hidden'); ui.render(state) },
dropped(paths) { ui.log('Dropped: ' + paths.join(', ')); ui.job('import_paths', paths) },
async chooseFiles() { const p = await ui.call('pick_files'); if (p && p.length) ui.job('import_paths', p) },
async chooseFolder() { const p = await ui.call('pick_folder'); if (p) ui.job('import_paths', [p]) },
async pick(id) { const p = await ui.call('pick_folder'); if (p) $(id).value = p },
async create() {
ui.render(await ui.call('create_library', $('newPath').value.trim(), $('newName').value.trim(), $('newBirth').value, $('newSex').value, $('newTz').value.trim() || 'UTC'));
},
async open() { ui.render(await ui.call('open_library', $('openPath').value.trim())) },
async saveSettings() {
const st = await ui.call('save_settings', $('sName').value.trim(), $('sBirth').value, $('sSex').value, $('sTz').value.trim() || 'UTC', $('sCopies').value);
$('settingsBox').open = false; ui.render(st); ui.log('Settings saved.');
},
async login() {
const e = $('gcEmail').value.trim(), p = $('gcPass').value; if (!e || !p) return;
$('gcPass').value = ''; ui.job('login', e, p);
},
askMfa() { $('gcMfa').classList.remove('hidden'); $('mfaCode').focus(); ui.log('Garmin asks for a verification code.') },
sendMfa() { ui.call('mfa', $('mfaCode').value); $('mfaCode').value = ''; $('gcMfa').classList.add('hidden') },
};
// visual feedback while dragging (the drop itself is handled in Python, which sees the full paths)
const drop = $('drop');
['dragenter', 'dragover'].forEach(t => drop.addEventListener(t, e => { e.preventDefault(); drop.classList.add('over') }));
['dragleave', 'drop'].forEach(t => drop.addEventListener(t, () => drop.classList.remove('over')));
window.addEventListener('pywebviewready', () => ui.render());
</script>
</body>
</html>

View File

@@ -30,7 +30,7 @@ class Library:
p = os.path.join(self.root, 'settings.json') 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') 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.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.row_factory = sqlite3.Row
self.db.executescript(SCHEMA) self.db.executescript(SCHEMA)

View File

@@ -1,5 +1,5 @@
"""Build the self-contained dashboard (dashboard.html) and an all_activities.csv from the library.""" """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 datetime import datetime
from .. import __version__ 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]) 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, " 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}") 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 return out

29
tests/test_app_api.py Normal file
View File

@@ -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']