feat(fitness): download GPX from history detail

Export each cardio exercise's stored GPS track from the history
detail page. Cadence is emitted per-point via Garmin's
TrackPointExtension v1 so Strava/Garmin Connect preserve it.
Filename: YYYY-MM-DD-<workout> <mins>min <Activity>.gpx.
This commit is contained in:
2026-04-21 18:52:01 +02:00
parent c99442b54b
commit cf5ac96fc3
5 changed files with 155 additions and 2 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "homepage",
"version": "1.43.1",
"version": "1.44.0",
"private": true,
"type": "module",
"scripts": {
+1
View File
@@ -104,6 +104,7 @@ const translations: Translations = {
pace: { en: 'PACE', de: 'TEMPO' },
upload_gpx: { en: 'Upload GPX', de: 'GPX hochladen' },
uploading: { en: 'Uploading...', de: 'Hochladen...' },
download_gpx: { en: 'Download GPX', de: 'GPX herunterladen' },
elevation: { en: 'Elevation', de: 'Höhenprofil' },
elevation_unit: { en: 'm', de: 'm' },
elevation_gain: { en: 'Gain', de: 'Anstieg' },
+68
View File
@@ -0,0 +1,68 @@
import type { IGpsPoint } from '$models/WorkoutSession';
function escapeXml(s: string): string {
return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
/** Generate a GPX 1.1 document from an array of GPS points.
* Cadence is emitted via Garmin's TrackPointExtension v1 (<gpxtpx:cad>). */
export function generateGpx(track: IGpsPoint[], name: string): string {
const hasCadence = track.some(p => typeof p.cadence === 'number');
const nsExt = hasCadence
? ' xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1"'
: '';
const pts = track.map(p => {
const ele = typeof p.altitude === 'number' ? ` <ele>${p.altitude}</ele>\n` : '';
const time = ` <time>${new Date(p.timestamp).toISOString()}</time>\n`;
const cad = typeof p.cadence === 'number'
? ` <extensions><gpxtpx:TrackPointExtension><gpxtpx:cad>${Math.round(p.cadence)}</gpxtpx:cad></gpxtpx:TrackPointExtension></extensions>\n`
: '';
return ` <trkpt lat="${p.lat}" lon="${p.lng}">\n${ele}${time}${cad} </trkpt>`;
}).join('\n');
return `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Bocken Homepage" xmlns="http://www.topografix.com/GPX/1/1"${nsExt}>
<trk>
<name>${escapeXml(name)}</name>
<trkseg>
${pts}
</trkseg>
</trk>
</gpx>
`;
}
/** Sanitize a string for use as a filename. Preserves spaces; strips path/control chars. */
export function safeFilename(s: string): string {
return s.replace(/[\\/\x00-\x1f:*?"<>|]+/g, '').replace(/\s+/g, ' ').trim().slice(0, 120);
}
const ACTIVITY_LABEL: Record<string, string> = {
running: 'Run',
walking: 'Walk',
cycling: 'Cycle',
hiking: 'Hike'
};
/** Build a GPX filename: "YYYY-MM-DD-<workout> <duration>min <Activity>.gpx". */
export function buildGpxFilename(opts: {
startTime: Date | string | number;
workoutName: string;
durationMin: number;
activityType?: string;
fallbackActivity?: string;
}): string {
const date = new Date(opts.startTime).toISOString().slice(0, 10);
const name = safeFilename(opts.workoutName) || 'Workout';
const mins = Math.max(0, Math.round(opts.durationMin));
const activity = opts.activityType && ACTIVITY_LABEL[opts.activityType]
? ACTIVITY_LABEL[opts.activityType]
: safeFilename(opts.fallbackActivity ?? '') || 'Cardio';
return `${date}-${name} ${mins}min ${activity}.gpx`;
}
@@ -5,6 +5,7 @@ import { WorkoutSession } from '$models/WorkoutSession';
import type { IGpsPoint } from '$models/WorkoutSession';
import { simplifyTrack } from '$lib/server/simplifyTrack';
import { computeSessionKcal } from '$lib/server/computeSessionKcal';
import { generateGpx, buildGpxFilename } from '$lib/server/gpxExport';
import mongoose from 'mongoose';
/** Haversine distance in km between two points */
@@ -56,6 +57,62 @@ function parseGpx(xml: string): IGpsPoint[] {
return points;
}
// GET /api/fitness/sessions/[id]/gpx?exerciseIdx=N — download GPX export of the track
export const GET: RequestHandler = async ({ params, url, locals }) => {
const session = await locals.auth();
if (!session || !session.user?.nickname) {
return json({ error: 'Unauthorized' }, { status: 401 });
}
if (!mongoose.Types.ObjectId.isValid(params.id)) {
return json({ error: 'Invalid session ID' }, { status: 400 });
}
const exerciseIdx = parseInt(url.searchParams.get('exerciseIdx') ?? '', 10);
if (isNaN(exerciseIdx) || exerciseIdx < 0) {
return json({ error: 'Invalid exercise index' }, { status: 400 });
}
await dbConnect();
const workoutSession = await WorkoutSession.findOne({
_id: params.id,
createdBy: session.user.nickname
}).lean();
if (!workoutSession) {
return json({ error: 'Session not found' }, { status: 404 });
}
const ex = workoutSession.exercises[exerciseIdx];
if (!ex) {
return json({ error: 'Exercise index out of range' }, { status: 400 });
}
if (!ex.gpsTrack || ex.gpsTrack.length === 0) {
return json({ error: 'No GPS track on this exercise' }, { status: 404 });
}
const trackName = `${workoutSession.name}${ex.name}`;
const trackMs = ex.gpsTrack[ex.gpsTrack.length - 1].timestamp - ex.gpsTrack[0].timestamp;
const durationMin = trackMs > 0 ? trackMs / 60000 : (workoutSession.duration ?? 0);
const filename = buildGpxFilename({
startTime: workoutSession.startTime,
workoutName: workoutSession.name,
durationMin,
activityType: workoutSession.activityType,
fallbackActivity: ex.name
});
const xml = generateGpx(ex.gpsTrack, trackName);
return new Response(xml, {
status: 200,
headers: {
'Content-Type': 'application/gpx+xml; charset=utf-8',
'Content-Disposition': `attachment; filename="${filename}"; filename*=UTF-8''${encodeURIComponent(filename)}`
}
});
};
// POST /api/fitness/sessions/[id]/gpx — upload GPX file for an exercise
export const POST: RequestHandler = async ({ params, request, locals }) => {
const session = await locals.auth();
@@ -1,7 +1,7 @@
<script>
import { goto, invalidateAll } from '$app/navigation';
import { page } from '$app/stores';
import { Clock, Weight, Trophy, Trash2, Pencil, Plus, Upload, Route, X, RefreshCw, Gauge, Flame, Info, Mountain } from '@lucide/svelte';
import { Clock, Weight, Trophy, Trash2, Pencil, Plus, Upload, Download, Route, X, RefreshCw, Gauge, Flame, Info, Mountain } from '@lucide/svelte';
import { detectFitnessLang, fitnessSlugs, t } from '$lib/js/fitnessI18n';
import { confirm } from '$lib/js/confirmDialog.svelte';
import { toast } from '$lib/js/toast.svelte';
@@ -543,6 +543,11 @@
input.click();
}
/** @param {number} exIdx */
function downloadGpx(exIdx) {
window.location.href = `/api/fitness/sessions/${session._id}/gpx?exerciseIdx=${exIdx}`;
}
/** @param {number} exIdx */
async function removeGpx(exIdx) {
if (!await confirm(t('remove_gps_confirm', lang))) return;
@@ -836,6 +841,10 @@
</div>
{/if}
{/if}
<button class="gpx-download-btn" onclick={() => downloadGpx(exIdx)}>
<Download size={14} />
{t('download_gpx', lang)}
</button>
</div>
{:else if isCardio(ex.exerciseId)}
<button class="gpx-upload-btn" onclick={() => uploadGpx(exIdx)} disabled={uploading === exIdx}>
@@ -1345,6 +1354,24 @@
opacity: 0.5;
cursor: not-allowed;
}
.gpx-download-btn {
display: inline-flex;
align-items: center;
gap: 0.4rem;
margin-top: 0.75rem;
padding: 0.4rem 0.75rem;
background: transparent;
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
color: var(--color-text-secondary);
font-size: 0.8rem;
cursor: pointer;
transition: border-color 0.15s, color 0.15s;
}
.gpx-download-btn:hover {
border-color: var(--color-primary);
color: var(--color-primary);
}
/* GPS charts */
.chart-section {