makerundev-server 0.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- makerundev_server/__init__.py +3 -0
- makerundev_server/app.py +399 -0
- makerundev_server/charts.py +197 -0
- makerundev_server/config.py +26 -0
- makerundev_server/cross_site.py +33 -0
- makerundev_server/db.py +144 -0
- makerundev_server/garmin.py +148 -0
- makerundev_server/garmin_store.py +129 -0
- makerundev_server/garmin_sync.py +182 -0
- makerundev_server/main.py +12 -0
- makerundev_server/matching.py +35 -0
- makerundev_server/migrations/env.py +36 -0
- makerundev_server/migrations/script.py.mako +15 -0
- makerundev_server/migrations/versions/0001_activities.py +36 -0
- makerundev_server/migrations/versions/0002_athlete_settings.py +31 -0
- makerundev_server/migrations/versions/0003_activity_identity.py +36 -0
- makerundev_server/migrations/versions/0004_strava_connection.py +33 -0
- makerundev_server/migrations/versions/0005_activity_laps.py +17 -0
- makerundev_server/migrations/versions/0006_garmin_connection.py +32 -0
- makerundev_server/settings.py +129 -0
- makerundev_server/static/apple-touch-icon.png +0 -0
- makerundev_server/static/favicon-dark.png +0 -0
- makerundev_server/static/favicon-light.png +0 -0
- makerundev_server/static/style.css +198 -0
- makerundev_server/store.py +464 -0
- makerundev_server/strava.py +171 -0
- makerundev_server/sync.py +124 -0
- makerundev_server/sync_state.py +57 -0
- makerundev_server/templates/activity.html +111 -0
- makerundev_server/templates/base.html +22 -0
- makerundev_server/templates/garmin.html +76 -0
- makerundev_server/templates/index.html +48 -0
- makerundev_server/templates/load.html +81 -0
- makerundev_server/templates/settings.html +59 -0
- makerundev_server/templates/strava.html +75 -0
- makerundev_server/training.py +69 -0
- makerundev_server-0.6.0.dist-info/METADATA +146 -0
- makerundev_server-0.6.0.dist-info/RECORD +41 -0
- makerundev_server-0.6.0.dist-info/WHEEL +4 -0
- makerundev_server-0.6.0.dist-info/entry_points.txt +3 -0
- makerundev_server-0.6.0.dist-info/licenses/LICENSE +202 -0
makerundev_server/app.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import datetime as dt
|
|
3
|
+
import secrets
|
|
4
|
+
import threading
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Annotated, Any
|
|
8
|
+
from zoneinfo import ZoneInfo
|
|
9
|
+
|
|
10
|
+
import httpx2
|
|
11
|
+
from fastapi import FastAPI, File, HTTPException, Request, UploadFile
|
|
12
|
+
from fastapi.concurrency import run_in_threadpool
|
|
13
|
+
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
|
14
|
+
from fastapi.staticfiles import StaticFiles
|
|
15
|
+
from fastapi.templating import Jinja2Templates
|
|
16
|
+
from makerundev import ActivityFileError, Lap, format
|
|
17
|
+
from makerundev.metrics import best_efforts, splits, summarize, time_in_zones
|
|
18
|
+
|
|
19
|
+
from makerundev_server import charts, config, garmin
|
|
20
|
+
from makerundev_server.cross_site import CrossSiteGuard
|
|
21
|
+
from makerundev_server.db import ActivityRow, connect
|
|
22
|
+
from makerundev_server.garmin_sync import GarminSync
|
|
23
|
+
from makerundev_server.settings import FORM_FIELDS, ZONE_FIELDS, form_values, parse_form, timezones
|
|
24
|
+
from makerundev_server.store import Store
|
|
25
|
+
from makerundev_server.strava import ACTIVITY_URL, SCOPE, StravaClient, StravaError, credentials
|
|
26
|
+
from makerundev_server.sync import StravaSync
|
|
27
|
+
from makerundev_server.training import DEFAULT_RANGE, RANGES, load_view, today_in
|
|
28
|
+
|
|
29
|
+
MAX_UPLOAD_BYTES = 64 * 1024 * 1024
|
|
30
|
+
HERE = Path(__file__).parent
|
|
31
|
+
STRAVA_NOTICES = {
|
|
32
|
+
"connected": "Connected to Strava. Start a sync to bring your activities in.",
|
|
33
|
+
"denied": "Strava access was not granted, so nothing was connected.",
|
|
34
|
+
"state": "That Strava response did not match a connection started here. Try again.",
|
|
35
|
+
"scope": "makerundev needs permission to read your activities, private ones included."
|
|
36
|
+
" Connect again and leave that box ticked.",
|
|
37
|
+
"failed": "Strava did not complete the connection. Check the client id and secret.",
|
|
38
|
+
"disconnected": "Disconnected from Strava.",
|
|
39
|
+
}
|
|
40
|
+
GARMIN_NOTICES = {
|
|
41
|
+
"saved": "Key saved. Start a sync to bring your activities in.",
|
|
42
|
+
"empty": "Paste your Personal API key first.",
|
|
43
|
+
"rejected": "Garmin did not accept that key. Check it was copied whole and has not expired.",
|
|
44
|
+
"unreachable": "Garmin could not be reached to check the key. Try again later.",
|
|
45
|
+
"removed": "Key removed. Activities imported from Garmin stay.",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def create_app(
|
|
50
|
+
data_dir: Path | None = None,
|
|
51
|
+
strava_transport: httpx2.BaseTransport | None = None,
|
|
52
|
+
garmin_transport: httpx2.BaseTransport | None = None,
|
|
53
|
+
garmin_pause: float = garmin.PAUSE_S,
|
|
54
|
+
) -> FastAPI:
|
|
55
|
+
root = data_dir or config.data_dir()
|
|
56
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
store = Store(root, connect(root))
|
|
58
|
+
store.reset_syncs()
|
|
59
|
+
templates = Jinja2Templates(directory=HERE / "templates")
|
|
60
|
+
templates.env.filters.update(
|
|
61
|
+
km=format.distance,
|
|
62
|
+
duration=format.duration,
|
|
63
|
+
pace=format.pace,
|
|
64
|
+
distance_name=format.distance_name,
|
|
65
|
+
signed=_signed,
|
|
66
|
+
local=_local,
|
|
67
|
+
)
|
|
68
|
+
templates.env.globals.update(
|
|
69
|
+
format_pace=format.pace,
|
|
70
|
+
format_bpm=lambda value: f"{value:.0f} bpm",
|
|
71
|
+
format_metres=lambda value: f"{value:.0f} m",
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def timezone() -> str:
|
|
75
|
+
settings = store.athlete_settings()
|
|
76
|
+
return settings.timezone if settings else "UTC"
|
|
77
|
+
|
|
78
|
+
app = FastAPI(title="makerundev")
|
|
79
|
+
app.add_middleware(CrossSiteGuard)
|
|
80
|
+
app.mount("/static", StaticFiles(directory=HERE / "static"), name="static")
|
|
81
|
+
|
|
82
|
+
def index(request: Request, notices: list[str], status_code: int = 200) -> HTMLResponse:
|
|
83
|
+
return templates.TemplateResponse(
|
|
84
|
+
request,
|
|
85
|
+
"index.html",
|
|
86
|
+
{"activities": store.list(), "notices": notices, "timezone": timezone()},
|
|
87
|
+
status_code=status_code,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
@app.get("/", response_class=HTMLResponse)
|
|
91
|
+
def home(request: Request) -> HTMLResponse:
|
|
92
|
+
return index(request, [])
|
|
93
|
+
|
|
94
|
+
@app.post("/activities", response_class=HTMLResponse)
|
|
95
|
+
def upload(request: Request, files: Annotated[list[UploadFile], File()]) -> HTMLResponse:
|
|
96
|
+
notices: list[str] = []
|
|
97
|
+
imported = 0
|
|
98
|
+
for upload in files:
|
|
99
|
+
name = upload.filename or "upload"
|
|
100
|
+
data = upload.file.read(MAX_UPLOAD_BYTES + 1)
|
|
101
|
+
if len(data) > MAX_UPLOAD_BYTES:
|
|
102
|
+
notices.append(f"{name}: larger than 64 MB")
|
|
103
|
+
continue
|
|
104
|
+
try:
|
|
105
|
+
result = store.import_file(name, data)
|
|
106
|
+
except ActivityFileError as error:
|
|
107
|
+
notices.append(f"{name}: {error}")
|
|
108
|
+
continue
|
|
109
|
+
imported += 1
|
|
110
|
+
if not result.created:
|
|
111
|
+
notices.append(f"{name}: already imported")
|
|
112
|
+
return index(request, notices, status_code=200 if imported else 400)
|
|
113
|
+
|
|
114
|
+
@app.get("/activities/{activity_id}", response_class=HTMLResponse)
|
|
115
|
+
def detail(request: Request, activity_id: int) -> HTMLResponse:
|
|
116
|
+
row = _row(store, activity_id)
|
|
117
|
+
activity = store.activity(row)
|
|
118
|
+
records = activity.records
|
|
119
|
+
summary = summarize(activity)
|
|
120
|
+
settings = store.athlete_settings()
|
|
121
|
+
zones = []
|
|
122
|
+
if settings is not None:
|
|
123
|
+
boundaries = settings.zone_boundaries_bpm()
|
|
124
|
+
zones = charts.zone_bars(time_in_zones(activity, boundaries), boundaries)
|
|
125
|
+
return templates.TemplateResponse(
|
|
126
|
+
request,
|
|
127
|
+
"activity.html",
|
|
128
|
+
{
|
|
129
|
+
"activity": row,
|
|
130
|
+
"strava_url": ACTIVITY_URL.format(row.external_id)
|
|
131
|
+
if row.external_source == "strava"
|
|
132
|
+
else None,
|
|
133
|
+
"efforts": best_efforts(activity),
|
|
134
|
+
"splits": _unless_single(splits(activity)),
|
|
135
|
+
"laps": _lap_rows(store.laps(row)),
|
|
136
|
+
"ground_contact_time": summary.avg_ground_contact_time,
|
|
137
|
+
"vertical_oscillation": summary.avg_vertical_oscillation,
|
|
138
|
+
"step_length": summary.avg_step_length,
|
|
139
|
+
"settings_set": settings is not None,
|
|
140
|
+
"zones": zones,
|
|
141
|
+
"timezone": settings.timezone if settings else "UTC",
|
|
142
|
+
"route": charts.route(records),
|
|
143
|
+
"pace": charts.series(records, "pace", invert=True),
|
|
144
|
+
"heart_rate": charts.series(records, "heart_rate"),
|
|
145
|
+
"elevation": charts.series(records, "altitude"),
|
|
146
|
+
"chart": {"width": charts.WIDTH, "height": charts.HEIGHT},
|
|
147
|
+
},
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
def settings_page(
|
|
151
|
+
request: Request,
|
|
152
|
+
values: dict[str, str],
|
|
153
|
+
errors: dict[str, str],
|
|
154
|
+
notice: str | None = None,
|
|
155
|
+
status_code: int = 200,
|
|
156
|
+
) -> HTMLResponse:
|
|
157
|
+
return templates.TemplateResponse(
|
|
158
|
+
request,
|
|
159
|
+
"settings.html",
|
|
160
|
+
{
|
|
161
|
+
"values": values,
|
|
162
|
+
"errors": errors,
|
|
163
|
+
"notice": notice,
|
|
164
|
+
"zone_fields": ZONE_FIELDS,
|
|
165
|
+
"timezones": sorted(timezones()),
|
|
166
|
+
"highest_heart_rate": store.highest_heart_rate(),
|
|
167
|
+
},
|
|
168
|
+
status_code=status_code,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
@app.get("/settings", response_class=HTMLResponse)
|
|
172
|
+
def settings(request: Request, recomputed: str = "", unreadable: str = "") -> HTMLResponse:
|
|
173
|
+
notice = None
|
|
174
|
+
if recomputed.isdigit():
|
|
175
|
+
notice = "Settings saved." + _count(" TRIMP recomputed for {}.", int(recomputed))
|
|
176
|
+
if unreadable.isdigit():
|
|
177
|
+
notice += _count(" {} could not be read; see the server log.", int(unreadable))
|
|
178
|
+
return settings_page(request, form_values(store.athlete_settings()), {}, notice)
|
|
179
|
+
|
|
180
|
+
@app.post("/settings", response_class=HTMLResponse, response_model=None)
|
|
181
|
+
async def save_settings(request: Request) -> Response:
|
|
182
|
+
form = await request.form()
|
|
183
|
+
values = {name: str(form.get(name, "")) for name in FORM_FIELDS}
|
|
184
|
+
parsed, errors = parse_form(values)
|
|
185
|
+
if parsed is None:
|
|
186
|
+
return settings_page(request, values, errors, status_code=422)
|
|
187
|
+
result = await run_in_threadpool(store.save_athlete_settings, parsed)
|
|
188
|
+
query = f"recomputed={result.recomputed}&unreadable={result.unreadable}"
|
|
189
|
+
return RedirectResponse(f"/settings?{query}", status_code=303)
|
|
190
|
+
|
|
191
|
+
@app.get("/load", response_class=HTMLResponse)
|
|
192
|
+
def load(request: Request, days: str = DEFAULT_RANGE) -> HTMLResponse:
|
|
193
|
+
selected = days if days in RANGES else DEFAULT_RANGE
|
|
194
|
+
settings = store.athlete_settings()
|
|
195
|
+
view = None
|
|
196
|
+
if settings is not None:
|
|
197
|
+
today = today_in(settings.timezone)
|
|
198
|
+
view = load_view(store.list(), settings.timezone, today, RANGES[selected])
|
|
199
|
+
return templates.TemplateResponse(
|
|
200
|
+
request,
|
|
201
|
+
"load.html",
|
|
202
|
+
{
|
|
203
|
+
"settings_set": settings is not None,
|
|
204
|
+
"view": view,
|
|
205
|
+
"plot": charts.load_chart(view.days) if view else None,
|
|
206
|
+
"ranges": RANGES,
|
|
207
|
+
"selected": selected,
|
|
208
|
+
"chart": {"width": charts.WIDTH, "height": charts.HEIGHT},
|
|
209
|
+
},
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
def strava_client() -> StravaClient | None:
|
|
213
|
+
configured = credentials()
|
|
214
|
+
return StravaClient(configured, strava_transport) if configured else None
|
|
215
|
+
|
|
216
|
+
def to_strava(notice: str = "") -> RedirectResponse:
|
|
217
|
+
return RedirectResponse(f"/strava?notice={notice}" if notice else "/strava", 303)
|
|
218
|
+
|
|
219
|
+
@app.get("/strava", response_class=HTMLResponse)
|
|
220
|
+
def strava(request: Request, notice: str = "") -> HTMLResponse:
|
|
221
|
+
connection = store.strava_connection()
|
|
222
|
+
return templates.TemplateResponse(
|
|
223
|
+
request,
|
|
224
|
+
"strava.html",
|
|
225
|
+
{
|
|
226
|
+
"configured": credentials() is not None,
|
|
227
|
+
"connected": connection is not None and connection.access_token is not None,
|
|
228
|
+
"connection": connection,
|
|
229
|
+
"notice": STRAVA_NOTICES.get(notice),
|
|
230
|
+
"callback_domain": request.url.hostname,
|
|
231
|
+
"timezone": timezone(),
|
|
232
|
+
},
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
@app.post("/strava/connect", response_model=None)
|
|
236
|
+
def strava_connect(request: Request) -> Response:
|
|
237
|
+
client = strava_client()
|
|
238
|
+
if client is None:
|
|
239
|
+
return to_strava()
|
|
240
|
+
state = secrets.token_urlsafe(32)
|
|
241
|
+
store.begin_strava_oauth(state)
|
|
242
|
+
redirect_uri = str(request.url_for("strava_callback"))
|
|
243
|
+
return RedirectResponse(client.authorize_url(redirect_uri, state), status_code=303)
|
|
244
|
+
|
|
245
|
+
@app.get("/strava/callback", name="strava_callback", response_model=None)
|
|
246
|
+
def strava_callback(
|
|
247
|
+
code: str = "", state: str = "", scope: str = "", error: str = ""
|
|
248
|
+
) -> Response:
|
|
249
|
+
client = strava_client()
|
|
250
|
+
connection = store.strava_connection()
|
|
251
|
+
expected = connection.oauth_state if connection else None
|
|
252
|
+
if client is None or not expected or not secrets.compare_digest(expected, state):
|
|
253
|
+
return to_strava("state")
|
|
254
|
+
if error or not code:
|
|
255
|
+
return to_strava("denied")
|
|
256
|
+
if SCOPE not in scope.replace(" ", ",").split(","):
|
|
257
|
+
return to_strava("scope")
|
|
258
|
+
try:
|
|
259
|
+
tokens = client.exchange(code)
|
|
260
|
+
except (StravaError, httpx2.HTTPError, KeyError):
|
|
261
|
+
return to_strava("failed")
|
|
262
|
+
store.save_strava_tokens(tokens)
|
|
263
|
+
return to_strava("connected")
|
|
264
|
+
|
|
265
|
+
@app.post("/strava/sync", response_model=None)
|
|
266
|
+
def strava_sync() -> Response:
|
|
267
|
+
client = strava_client()
|
|
268
|
+
if client is not None and store.start_strava_sync():
|
|
269
|
+
worker = threading.Thread(target=StravaSync(store, client).run, daemon=True)
|
|
270
|
+
app.state.strava_sync = worker
|
|
271
|
+
worker.start()
|
|
272
|
+
return to_strava()
|
|
273
|
+
|
|
274
|
+
@app.post("/strava/disconnect", response_model=None)
|
|
275
|
+
def strava_disconnect() -> Response:
|
|
276
|
+
client = strava_client()
|
|
277
|
+
if client is not None:
|
|
278
|
+
with contextlib.suppress(StravaError, httpx2.HTTPError, KeyError):
|
|
279
|
+
client.revoke(StravaSync(store, client).access_token())
|
|
280
|
+
store.disconnect_strava()
|
|
281
|
+
return to_strava("disconnected")
|
|
282
|
+
|
|
283
|
+
def garmin_client() -> garmin.GarminClient:
|
|
284
|
+
return garmin.GarminClient(garmin_transport, pause=garmin_pause)
|
|
285
|
+
|
|
286
|
+
def to_garmin(notice: str = "") -> RedirectResponse:
|
|
287
|
+
return RedirectResponse(f"/garmin?notice={notice}" if notice else "/garmin", 303)
|
|
288
|
+
|
|
289
|
+
@app.get("/garmin", response_class=HTMLResponse)
|
|
290
|
+
def garmin_page(request: Request, notice: str = "") -> HTMLResponse:
|
|
291
|
+
return templates.TemplateResponse(
|
|
292
|
+
request,
|
|
293
|
+
"garmin.html",
|
|
294
|
+
{
|
|
295
|
+
"connection": store.garmin.connection(),
|
|
296
|
+
"notice": GARMIN_NOTICES.get(notice),
|
|
297
|
+
"activity_url": garmin.ACTIVITY_URL,
|
|
298
|
+
"timezone": timezone(),
|
|
299
|
+
},
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
@app.post("/garmin/key", response_model=None)
|
|
303
|
+
async def garmin_key(request: Request) -> Response:
|
|
304
|
+
key = str((await request.form()).get("key", "")).strip()
|
|
305
|
+
if not key:
|
|
306
|
+
return to_garmin("empty")
|
|
307
|
+
try:
|
|
308
|
+
token = await run_in_threadpool(garmin_client().token, key)
|
|
309
|
+
except garmin.Unauthorized:
|
|
310
|
+
return to_garmin("rejected")
|
|
311
|
+
except (garmin.GarminError, httpx2.HTTPError):
|
|
312
|
+
return to_garmin("unreachable")
|
|
313
|
+
await run_in_threadpool(store.garmin.save_key, key, token)
|
|
314
|
+
return to_garmin("saved")
|
|
315
|
+
|
|
316
|
+
@app.post("/garmin/sync", response_model=None)
|
|
317
|
+
def garmin_sync() -> Response:
|
|
318
|
+
running = getattr(app.state, "garmin_sync", None)
|
|
319
|
+
if running is not None and running.is_alive():
|
|
320
|
+
return to_garmin()
|
|
321
|
+
if store.garmin.start_sync():
|
|
322
|
+
worker = threading.Thread(target=GarminSync(store, garmin_client()).run, daemon=True)
|
|
323
|
+
app.state.garmin_sync = worker
|
|
324
|
+
worker.start()
|
|
325
|
+
return to_garmin()
|
|
326
|
+
|
|
327
|
+
@app.post("/garmin/remove", response_model=None)
|
|
328
|
+
def garmin_remove() -> Response:
|
|
329
|
+
store.garmin.remove_key()
|
|
330
|
+
return to_garmin("removed")
|
|
331
|
+
|
|
332
|
+
@app.get("/api/activities")
|
|
333
|
+
def api_activities() -> list[dict[str, Any]]:
|
|
334
|
+
return [_as_dict(row) for row in store.list()]
|
|
335
|
+
|
|
336
|
+
@app.get("/api/activities/{activity_id}/records")
|
|
337
|
+
def api_records(activity_id: int) -> list[dict[str, Any]]:
|
|
338
|
+
return store.records(_row(store, activity_id)).to_dicts()
|
|
339
|
+
|
|
340
|
+
return app
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _local(moment: dt.datetime, timezone: str, pattern: str = "%Y-%m-%d %H:%M") -> str:
|
|
344
|
+
return moment.astimezone(ZoneInfo(timezone)).strftime(pattern)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _signed(value: float) -> str:
|
|
348
|
+
rounded = round(value)
|
|
349
|
+
return f"{rounded:+d}" if rounded else "0"
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _count(template: str, count: int) -> str:
|
|
353
|
+
if not count:
|
|
354
|
+
return ""
|
|
355
|
+
return template.format(f"{count} {'activity' if count == 1 else 'activities'}")
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _unless_single[T](rows: Sequence[T]) -> list[T]:
|
|
359
|
+
return list(rows) if len(rows) >= 2 else []
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _lap_rows(laps: tuple[Lap, ...]) -> list[dict[str, Any]]:
|
|
363
|
+
return [
|
|
364
|
+
{
|
|
365
|
+
"number": number,
|
|
366
|
+
"elapsed_s": lap.elapsed_s,
|
|
367
|
+
"distance_m": lap.distance_m,
|
|
368
|
+
"pace_s_per_km": lap.pace_s_per_km,
|
|
369
|
+
}
|
|
370
|
+
for number, lap in enumerate(_unless_single(laps), start=1)
|
|
371
|
+
]
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _row(store: Store, activity_id: int) -> ActivityRow:
|
|
375
|
+
row = store.get(activity_id)
|
|
376
|
+
if row is None:
|
|
377
|
+
raise HTTPException(status_code=404, detail="activity not found")
|
|
378
|
+
return row
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _as_dict(row: ActivityRow) -> dict[str, Any]:
|
|
382
|
+
return {
|
|
383
|
+
"id": row.id,
|
|
384
|
+
"filename": row.filename,
|
|
385
|
+
"sport": row.sport,
|
|
386
|
+
"device": row.device,
|
|
387
|
+
"source_format": row.source_format,
|
|
388
|
+
"start_time": row.start_time.isoformat(),
|
|
389
|
+
"distance_m": row.distance_m,
|
|
390
|
+
"elapsed_s": row.elapsed_s,
|
|
391
|
+
"moving_s": row.moving_s,
|
|
392
|
+
"pace_s_per_km": row.pace_s_per_km,
|
|
393
|
+
"avg_heart_rate": row.avg_heart_rate,
|
|
394
|
+
"max_heart_rate": row.max_heart_rate,
|
|
395
|
+
"elevation_gain_m": row.elevation_gain_m,
|
|
396
|
+
"trimp": row.trimp,
|
|
397
|
+
"external_source": row.external_source,
|
|
398
|
+
"external_id": row.external_id,
|
|
399
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import itertools
|
|
2
|
+
import math
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
import polars as pl
|
|
7
|
+
from makerundev import format
|
|
8
|
+
|
|
9
|
+
from makerundev_server.training import Day
|
|
10
|
+
|
|
11
|
+
WIDTH = 720
|
|
12
|
+
HEIGHT = 160
|
|
13
|
+
INSET = 12
|
|
14
|
+
MAX_POINTS = 600
|
|
15
|
+
MIN_LOAD_TOP = 10.0
|
|
16
|
+
MIN_FORM_SPAN = 5.0
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True, slots=True)
|
|
20
|
+
class Series:
|
|
21
|
+
path: str
|
|
22
|
+
low: float
|
|
23
|
+
high: float
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def series(records: pl.DataFrame, column: str, invert: bool = False) -> Series | None:
|
|
27
|
+
if column == "pace":
|
|
28
|
+
frame = records.filter(pl.col("speed") > 0.5).select(
|
|
29
|
+
"distance", pace=1000 / pl.col("speed")
|
|
30
|
+
)
|
|
31
|
+
else:
|
|
32
|
+
frame = records.select("distance", column).drop_nulls()
|
|
33
|
+
if frame.height < 2:
|
|
34
|
+
return None
|
|
35
|
+
step = max(1, frame.height // MAX_POINTS)
|
|
36
|
+
frame = frame.gather_every(step)
|
|
37
|
+
x = frame["distance"].to_list()
|
|
38
|
+
y = frame[column].to_list()
|
|
39
|
+
x0, x1 = x[0], x[-1]
|
|
40
|
+
low, high = min(y), max(y)
|
|
41
|
+
span_x = (x1 - x0) or 1.0
|
|
42
|
+
span_y = (high - low) or 1.0
|
|
43
|
+
points = []
|
|
44
|
+
for xi, yi in zip(x, y, strict=True):
|
|
45
|
+
fraction = (yi - low) / span_y
|
|
46
|
+
top = fraction if invert else 1 - fraction
|
|
47
|
+
y_px = INSET + top * (HEIGHT - 2 * INSET)
|
|
48
|
+
points.append(f"{(xi - x0) / span_x * WIDTH:.1f},{y_px:.1f}")
|
|
49
|
+
return Series(path="M" + " L".join(points), low=low, high=high)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
ROUTE_SIZE = 1000.0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True, slots=True)
|
|
56
|
+
class Route:
|
|
57
|
+
points: str
|
|
58
|
+
width: float
|
|
59
|
+
height: float
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def route(records: pl.DataFrame) -> Route | None:
|
|
63
|
+
positions = records.select("latitude", "longitude").drop_nulls()
|
|
64
|
+
if positions.height < 2:
|
|
65
|
+
return None
|
|
66
|
+
step = max(1, positions.height // MAX_POINTS)
|
|
67
|
+
frame = positions.gather_every(step)
|
|
68
|
+
if (positions.height - 1) % step:
|
|
69
|
+
frame = pl.concat([frame, positions.tail(1)])
|
|
70
|
+
lat = frame["latitude"].to_list()
|
|
71
|
+
lon = frame["longitude"].to_list()
|
|
72
|
+
squash = math.cos(math.radians(sum(lat) / len(lat)))
|
|
73
|
+
x = [value * squash for value in lon]
|
|
74
|
+
left, right = min(x), max(x)
|
|
75
|
+
bottom, top = min(lat), max(lat)
|
|
76
|
+
scale = ROUTE_SIZE / (max(right - left, top - bottom) or 1.0)
|
|
77
|
+
points = " ".join(
|
|
78
|
+
f"{INSET + (xi - left) * scale:.1f},{INSET + (top - yi) * scale:.1f}"
|
|
79
|
+
for xi, yi in zip(x, lat, strict=True)
|
|
80
|
+
)
|
|
81
|
+
return Route(
|
|
82
|
+
points=points,
|
|
83
|
+
width=(right - left) * scale + 2 * INSET,
|
|
84
|
+
height=(top - bottom) * scale + 2 * INSET,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True, slots=True)
|
|
89
|
+
class ZoneBar:
|
|
90
|
+
name: str
|
|
91
|
+
bpm: str
|
|
92
|
+
seconds: float
|
|
93
|
+
share: float
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def zone_bars(seconds: Sequence[float], boundaries_bpm: Sequence[float]) -> list[ZoneBar]:
|
|
97
|
+
total = sum(seconds)
|
|
98
|
+
if not total:
|
|
99
|
+
return []
|
|
100
|
+
return [
|
|
101
|
+
ZoneBar(
|
|
102
|
+
f"Zone {zone + 1}",
|
|
103
|
+
format.zone_range(zone, boundaries_bpm),
|
|
104
|
+
zone_seconds,
|
|
105
|
+
zone_seconds / total,
|
|
106
|
+
)
|
|
107
|
+
for zone, zone_seconds in enumerate(seconds)
|
|
108
|
+
]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True, slots=True)
|
|
112
|
+
class Hit:
|
|
113
|
+
x: float
|
|
114
|
+
width: float
|
|
115
|
+
title: str
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(frozen=True, slots=True)
|
|
119
|
+
class Line:
|
|
120
|
+
path: str
|
|
121
|
+
end: float
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
LABEL_GAP = 12.0
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def spread_labels(ends: dict[str, float]) -> list[tuple[str, float]]:
|
|
128
|
+
placed: list[tuple[str, float]] = []
|
|
129
|
+
for name, top in sorted(ends.items(), key=lambda item: item[1]):
|
|
130
|
+
top = max(top, placed[-1][1] + LABEL_GAP if placed else LABEL_GAP)
|
|
131
|
+
placed.append((name, top))
|
|
132
|
+
overflow = placed[-1][1] - 100.0 if placed else 0.0
|
|
133
|
+
if overflow > 0:
|
|
134
|
+
placed = [(name, top - overflow) for name, top in placed]
|
|
135
|
+
return placed
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass(frozen=True, slots=True)
|
|
139
|
+
class LoadChart:
|
|
140
|
+
fitness: Line
|
|
141
|
+
fatigue: Line
|
|
142
|
+
form: Line
|
|
143
|
+
load_top: float
|
|
144
|
+
form_low: float
|
|
145
|
+
form_high: float
|
|
146
|
+
zero: float
|
|
147
|
+
hits: list[Hit]
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def end_labels(self) -> list[tuple[str, float]]:
|
|
151
|
+
return spread_labels({"Fitness": self.fitness.end, "Fatigue": self.fatigue.end})
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def load_chart(days: Sequence[Day]) -> LoadChart:
|
|
155
|
+
last = len(days) - 1
|
|
156
|
+
indices = list(range(0, len(days), max(1, len(days) // MAX_POINTS)))
|
|
157
|
+
if indices[-1] != last:
|
|
158
|
+
indices.append(last)
|
|
159
|
+
sampled = [days[index] for index in indices]
|
|
160
|
+
xs = [index / last * WIDTH for index in indices] if last else [WIDTH / 2]
|
|
161
|
+
load_top = max(MIN_LOAD_TOP, *(max(day.fitness, day.fatigue) for day in days))
|
|
162
|
+
form_low = min(-MIN_FORM_SPAN, *(day.form for day in days))
|
|
163
|
+
form_high = max(MIN_FORM_SPAN, *(day.form for day in days))
|
|
164
|
+
|
|
165
|
+
def y(value: float, low: float, high: float) -> float:
|
|
166
|
+
fraction = (value - low) / ((high - low) or 1.0)
|
|
167
|
+
return INSET + (1 - fraction) * (HEIGHT - 2 * INSET)
|
|
168
|
+
|
|
169
|
+
def line(key: str, low: float, high: float) -> Line:
|
|
170
|
+
values = [getattr(day, key) for day in sampled]
|
|
171
|
+
points = [f"{x:.1f},{y(v, low, high):.1f}" for x, v in zip(xs, values, strict=True)]
|
|
172
|
+
if len(points) == 1:
|
|
173
|
+
points = [f"0,{y(values[0], low, high):.1f}", f"{WIDTH},{y(values[0], low, high):.1f}"]
|
|
174
|
+
return Line(path="M" + " L".join(points), end=y(values[-1], low, high) / HEIGHT * 100)
|
|
175
|
+
|
|
176
|
+
edges = [0.0, *((a + b) / 2 for a, b in itertools.pairwise(xs)), float(WIDTH)]
|
|
177
|
+
hits = [
|
|
178
|
+
Hit(
|
|
179
|
+
x=edges[position],
|
|
180
|
+
width=edges[position + 1] - edges[position],
|
|
181
|
+
title=(
|
|
182
|
+
f"{day.date:%Y-%m-%d}: fitness {day.fitness:.0f}, fatigue {day.fatigue:.0f}, "
|
|
183
|
+
f"form {round(day.form):+d}, TRIMP {day.load:.0f}"
|
|
184
|
+
),
|
|
185
|
+
)
|
|
186
|
+
for position, day in enumerate(sampled)
|
|
187
|
+
]
|
|
188
|
+
return LoadChart(
|
|
189
|
+
fitness=line("fitness", 0.0, load_top),
|
|
190
|
+
fatigue=line("fatigue", 0.0, load_top),
|
|
191
|
+
form=line("form", form_low, form_high),
|
|
192
|
+
load_top=load_top,
|
|
193
|
+
form_low=form_low,
|
|
194
|
+
form_high=form_high,
|
|
195
|
+
zero=y(0.0, form_low, form_high),
|
|
196
|
+
hits=hits,
|
|
197
|
+
)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
PREFIXES = ("MAKERUNDEV_", "PACELAB_")
|
|
5
|
+
DATABASE = "makerundev.db"
|
|
6
|
+
LEGACY_DATABASE = "pacelab.db"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def env(name: str, default: str) -> str:
|
|
10
|
+
for prefix in PREFIXES:
|
|
11
|
+
value = os.environ.get(prefix + name)
|
|
12
|
+
if value is not None:
|
|
13
|
+
return value
|
|
14
|
+
return default
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def data_dir() -> Path:
|
|
18
|
+
return Path(env("DATA_DIR", "data"))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def database_path(data_dir: Path) -> Path:
|
|
22
|
+
current = data_dir / DATABASE
|
|
23
|
+
legacy = data_dir / LEGACY_DATABASE
|
|
24
|
+
if legacy.exists() and not current.exists():
|
|
25
|
+
return legacy
|
|
26
|
+
return current
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from urllib.parse import urlsplit
|
|
2
|
+
|
|
3
|
+
from starlette.datastructures import Headers
|
|
4
|
+
from starlette.responses import PlainTextResponse
|
|
5
|
+
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
6
|
+
|
|
7
|
+
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
|
8
|
+
ALLOWED_FETCH_SITES = frozenset({"same-origin", "none"})
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def is_cross_site_write(method: str, headers: Headers) -> bool:
|
|
12
|
+
if method in SAFE_METHODS:
|
|
13
|
+
return False
|
|
14
|
+
fetch_site = headers.get("sec-fetch-site")
|
|
15
|
+
if fetch_site is not None:
|
|
16
|
+
return fetch_site not in ALLOWED_FETCH_SITES
|
|
17
|
+
origin = headers.get("origin")
|
|
18
|
+
if origin is None:
|
|
19
|
+
return False
|
|
20
|
+
origin_host = urlsplit(origin).netloc
|
|
21
|
+
return not origin_host or origin_host != headers.get("host")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CrossSiteGuard:
|
|
25
|
+
def __init__(self, app: ASGIApp) -> None:
|
|
26
|
+
self.app = app
|
|
27
|
+
|
|
28
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
29
|
+
if scope["type"] == "http" and is_cross_site_write(scope["method"], Headers(scope=scope)):
|
|
30
|
+
response = PlainTextResponse("Cross-site request refused", status_code=403)
|
|
31
|
+
await response(scope, receive, send)
|
|
32
|
+
return
|
|
33
|
+
await self.app(scope, receive, send)
|