feat(journey): keep recorded days from a GPX file beside Dawarich

A GPX file is a second source of a journey's recorded days (#3085). The
new route POST /api/journeys/:id/recordings/import-gpx (multipart, 15 MB,
edit access, no Dawarich needed) and the MCP tool import_journey_gpx_days
read the file's track segments through the place import's GPX reader,
place every timed point on its local day in the zone of where it was
recorded (or in one zone the caller fixes), cut the pieces at gaps, thin
them like a Dawarich day and keep one day per date with source gpx in one
transaction. Reading the file again replaces only its GPX days and leaves
an unchanged day and every Dawarich day alone; a day that changed pings
journey:recording:updated.

A GPX day is stored with source_kind tracks, so the existing contract
still reads it. DELETE :date and delete_journey_recorded_day take an
optional source, Dawarich's when left out. The shared map shows a GPX day
also without a published entry and prefers it over a Dawarich day of the
same date; the list of kept days carries both, ordered by date and source.
No migration: source and source_kind are text columns already.
This commit is contained in:
Maurice
2026-11-30 14:32:11 +01:00
parent cd20a0371f
commit 9f3722f459
26 changed files with 1458 additions and 75 deletions
@@ -11,7 +11,8 @@
* The walk: preview, keep, read the day back once the connection is gone,
* take the same day over again without a second copy, replace it on purpose,
* keep the version when Dawarich fails, and drop it. Then the preparation of
* the journey's days (JRN-03) as each caller sees it.
* the journey's days (JRN-03) as each caller sees it, and the days read from a
* GPX file (#3085) beside the ones Dawarich gave, each dropped by its source.
*/
import { DawarichConnections } from '../../src/db/entities/DawarichConnections.entity';
import { JourneyRecordedDays } from '../../src/db/entities/JourneyRecordedDays.entity';
@@ -329,4 +330,97 @@ describe('Journey recordings e2e (real guards + temp SQLite)', () => {
expect((await request(server).get(`${base()}/prep`).set(as(VIEWER))).status).toBe(403);
expect((await request(server).get(`${base()}/prep`).set(as(OUTSIDER))).status).toBe(404);
});
describe('days from a GPX file (#3085)', () => {
const TRACK = Buffer.from(
'<?xml version="1.0"?><gpx version="1.1"><trk><trkseg>' +
`<trkpt lat="45.43" lon="12.33"><time>${DAY}T08:00:00Z</time></trkpt>` +
`<trkpt lat="45.44" lon="12.34"><time>${DAY}T08:05:00Z</time></trkpt>` +
'<trkpt lat="45.5" lon="11.9"><time>2026-05-15T07:00:00Z</time></trkpt>' +
'<trkpt lat="45.51" lon="11.91"><time>2026-05-15T07:05:00Z</time></trkpt>' +
'</trkseg></trk></gpx>',
);
const upload = (userId: number, file: Buffer = TRACK) =>
request(server).post(`${base()}/import-gpx`).set(as(userId)).attach('file', file, 'drive.gpx');
it('keeps the days of the file beside the Dawarich day, with Dawarich off, and drops each by its source', async () => {
const shown = await preview();
await request(server)
.put(`${base()}/${DAY}`)
.set(as(OWNER))
.send({ utcOffsetMinutes: 120, expectedHash: shown.body.contentHash });
await setAddonEnabled(orm, 'dawarich', false);
const imported = await upload(EDITOR).set('X-Socket-Id', '12');
expect(imported.status).toBe(200);
expect(imported.body.untimedPoints).toBe(0);
type Kept = { day: { date: string }; outcome: string };
const outcomes = imported.body.days.map((d: Kept) => [d.day.date, d.outcome]);
expect(outcomes).toEqual([
[DAY, 'created'],
['2026-05-15', 'created'],
]);
expect(realtime.broadcastToUserMock).toHaveBeenCalledWith(
VIEWER,
{ type: 'journey:recording:updated', journeyId, date: '2026-05-15' },
'12',
);
const listed = await request(server).get(base()).set(as(VIEWER));
expect(listed.body.days.map((d: { date: string; source: string }) => [d.date, d.source])).toEqual([
[DAY, 'dawarich'],
[DAY, 'gpx'],
['2026-05-15', 'gpx'],
]);
const again = await upload(EDITOR);
expect(again.body.days.map((d: { outcome: string }) => d.outcome)).toEqual(['unchanged', 'unchanged']);
expect(await countRows(orm, JourneyRecordedDays)).toBe(3);
const dropped = await request(server).delete(`${base()}/${DAY}?source=gpx`).set(as(EDITOR));
expect(dropped.status).toBe(200);
const left = await request(server).get(base()).set(as(OWNER));
expect(left.body.days.map((d: { date: string; source: string }) => [d.date, d.source])).toEqual([
[DAY, 'dawarich'],
['2026-05-15', 'gpx'],
]);
expect((await request(server).delete(`${base()}/${DAY}?source=strava`).set(as(EDITOR))).status).toBe(400);
});
it('cuts one day in the zone asked for, and refuses what it cannot read before writing anything', async () => {
const one = await request(server)
.post(`${base()}/import-gpx`)
.set(as(OWNER))
.field('date', DAY)
.field('utcOffsetMinutes', '120')
.attach('file', TRACK, 'drive.gpx');
expect(one.status).toBe(200);
expect(one.body.days).toHaveLength(1);
expect(one.body.days[0].day).toMatchObject({
date: DAY,
source: 'gpx',
sourceKind: 'tracks',
utcOffsetMinutes: 120,
});
await deleteRows(orm, JourneyRecordedDays);
const notGpx = await upload(OWNER, Buffer.from('<kml/>'));
expect(notGpx.status).toBe(422);
expect(notGpx.body).toEqual({ error: 'The file is not a GPX file', code: 'gpx_unreadable' });
const badZone = await request(server)
.post(`${base()}/import-gpx`)
.set(as(OWNER))
.field('utcOffsetMinutes', '2000')
.attach('file', TRACK, 'drive.gpx');
expect(badZone.status).toBe(400);
const noFile = await request(server).post(`${base()}/import-gpx`).set(as(OWNER)).send({});
expect(noFile.status).toBe(400);
expect(noFile.body).toEqual({ error: 'No file uploaded', code: 'no-file' });
expect((await upload(VIEWER)).status).toBe(403);
expect((await upload(OUTSIDER)).status).toBe(404);
expect((await request(server).post(`${base()}/import-gpx`).attach('file', TRACK, 'drive.gpx')).status).toBe(401);
expect(await countRows(orm, JourneyRecordedDays)).toBe(0);
});
});
});
@@ -619,6 +619,20 @@ const journeyCases: ParityCase[] = [
rest: { method: 'delete', path: (s) => `/api/journeys/${s.journey.id}/recordings/${DAY}` },
expect: [{ event: 'journey:recording:updated', user: 'actor' }],
},
{
tool: 'import_journey_gpx_days',
needs: ['journey'],
args: (s) => ({
journeyId: s.journey.id,
gpx:
'<gpx><trk><trkseg>' +
`<trkpt lat="48.85" lon="2.35"><time>${DAY}T08:00:00Z</time></trkpt>` +
`<trkpt lat="48.86" lon="2.36"><time>${DAY}T08:10:00Z</time></trkpt>` +
'</trkseg></trk></gpx>',
}),
twin: 'POST /api/journeys/:id/recordings/import-gpx, a multipart upload of the same file',
expect: [{ event: 'journey:recording:updated', user: 'actor' }],
},
];
/** The scene's journey shown in its trip, as the link route writes it, without the event the route sends. */
@@ -165,4 +165,18 @@ describe('JourneyRecordedDaysRepository', () => {
expect(row?.created_at).toBe(longAgo);
expect(row?.updated_at).not.toBe(longAgo);
});
it('JRDAYS-008: one day of two sources is two rows, listed in the order of their names and each its own (#3085)', async () => {
const { user, journey: j } = await journey();
await days.upsertDay(day(j.id, user.id, { source: 'gpx', content_hash: 'g'.repeat(64) }));
await days.upsertDay(day(j.id, user.id));
await days.upsertDay(day(j.id, user.id, { source: 'gpx', content_hash: 'h'.repeat(64) }));
expect((await days.listForJourney(j.id)).map((row) => [row.source, row.content_hash])).toEqual([
['dawarich', 'a'.repeat(64)],
['gpx', 'h'.repeat(64)],
]);
expect(await days.deleteDay(j.id, '2026-05-14', 'gpx')).toBe(true);
expect(await days.findDay(j.id, '2026-05-14', 'dawarich')).toMatchObject({ source: 'dawarich' });
});
});
@@ -0,0 +1,149 @@
/**
* Cutting a GPX file into the local days a journey keeps (#3085): pure, no DB,
* no container. JRNGPX-CUT-001 to JRNGPX-CUT-007.
*/
import { cutGpxDays, recordedZoneOffsets } from '../../../src/nest/journey-recordings/journey-gpx-days.helpers';
import type { GpxTrackPoint } from '../../../src/nest/place-import/place-import.types';
import { describe, expect, it } from 'vitest';
const at = (iso: string) => Date.parse(iso);
const point = (lat: number, lng: number, time: string | null): GpxTrackPoint => ({
lat,
lng,
at: time === null ? null : at(time),
});
/** Venice in May: two hours east of UTC. */
const venice = () => 120;
describe('cutGpxDays', () => {
it('JRNGPX-CUT-001: a point names its day by its time in the zone of where it was recorded', () => {
const cut = cutGpxDays(
{
segments: [
[
point(45.43, 12.33, '2026-05-14T21:40:00Z'),
point(45.431, 12.331, '2026-05-14T21:50:00Z'),
// 00:05 on the 15th in Venice: the next day, though still the 14th in UTC.
point(45.432, 12.332, '2026-05-14T22:05:00Z'),
point(45.433, 12.333, '2026-05-14T22:15:00Z'),
],
],
},
{},
venice,
);
expect(cut.days.map((day) => day.date)).toEqual(['2026-05-14', '2026-05-15']);
expect(cut.days[0]).toMatchObject({
utcOffsetMinutes: 120,
window: { from: '2026-05-13T22:00:00.000Z', to: '2026-05-14T22:00:00.000Z' },
segments: [{ startedAt: '2026-05-14T21:40:00.000Z', endedAt: '2026-05-14T21:50:00.000Z', mode: null }],
});
expect(cut.days[1]?.window).toEqual({ from: '2026-05-14T22:00:00.000Z', to: '2026-05-15T22:00:00.000Z' });
expect(cut).toMatchObject({ untimedPoints: 0, timedPoints: 4 });
});
it('JRNGPX-CUT-002: one zone fixed by the caller cuts every day in it', () => {
const cut = cutGpxDays(
{
segments: [[point(45.43, 12.33, '2026-05-14T22:05:00Z'), point(45.431, 12.331, '2026-05-14T22:15:00Z')]],
},
{ utcOffsetMinutes: 0 },
venice,
);
expect(cut.days.map((day) => [day.date, day.utcOffsetMinutes])).toEqual([['2026-05-14', 0]]);
});
it('JRNGPX-CUT-003: silence that ends somewhere else is a gap, silence in one place is none', () => {
const cut = cutGpxDays(
{
segments: [
[
point(45.43, 12.33, '2026-05-14T08:00:00Z'),
point(45.431, 12.331, '2026-05-14T08:05:00Z'),
// An hour at the same café table: no gap.
point(45.431, 12.3313, '2026-05-14T09:05:00Z'),
// An hour later and kilometres away: a gap.
point(45.5, 12.4, '2026-05-14T10:05:00Z'),
point(45.501, 12.401, '2026-05-14T10:10:00Z'),
],
],
},
{},
venice,
);
expect(cut.days).toHaveLength(1);
expect(cut.days[0]?.segments.map((segment) => segment.points.length)).toEqual([3, 2]);
expect(cut.days[0]?.segments[0]?.distanceMeters).toBeGreaterThan(100);
});
it('JRNGPX-CUT-004: the track segments stay apart, earliest first, a lone fix is no line', () => {
const cut = cutGpxDays(
{
segments: [
[point(45.5, 12.4, '2026-05-14T12:00:00Z'), point(45.501, 12.401, '2026-05-14T12:05:00Z')],
[point(45.43, 12.33, '2026-05-14T08:00:00Z'), point(45.431, 12.331, '2026-05-14T08:05:00Z')],
[point(45.6, 12.5, '2026-05-14T14:00:00Z')],
],
},
{},
venice,
);
expect(cut.days[0]?.segments.map((segment) => segment.startedAt)).toEqual([
'2026-05-14T08:00:00.000Z',
'2026-05-14T12:00:00.000Z',
]);
});
it('JRNGPX-CUT-005: points without a time are counted and left out; points out of order are put in order', () => {
const cut = cutGpxDays(
{
segments: [
[
point(45.431, 12.331, '2026-05-14T08:05:00Z'),
point(45.43, 12.33, null),
point(45.43, 12.33, '2026-05-14T08:00:00Z'),
],
],
},
{},
venice,
);
expect(cut).toMatchObject({ untimedPoints: 1, timedPoints: 2 });
expect(cut.days[0]?.segments[0]?.points).toEqual([
[45.43, 12.33],
[45.431, 12.331],
]);
const untimed = cutGpxDays({ segments: [[point(45.43, 12.33, null)]] }, {}, venice);
expect(untimed).toEqual({ days: [], untimedPoints: 1, timedPoints: 0 });
});
it('JRNGPX-CUT-006: a date keeps that one day, and a long recording is thinned for the map', () => {
const long = Array.from({ length: 5000 }, (_, i) =>
point(
45.43 + i * 0.0001 * Math.sin(i),
12.33 + i * 0.0001,
new Date(at('2026-05-15T06:00:00Z') + i * 1000).toISOString(),
),
);
const short = [point(45.43, 12.33, '2026-05-14T08:00:00Z'), point(45.44, 12.34, '2026-05-14T08:05:00Z')];
const cut = cutGpxDays({ segments: [short, long] }, { date: '2026-05-15' }, venice);
expect(cut.days.map((day) => day.date)).toEqual(['2026-05-15']);
const points = cut.days[0]?.segments.reduce((sum, segment) => sum + segment.points.length, 0) ?? 0;
expect(points).toBeGreaterThan(1);
expect(points).toBeLessThanOrEqual(600);
});
});
describe('recordedZoneOffsets', () => {
it('JRNGPX-CUT-007: reads the offset of where and when a point was recorded', () => {
const offsetAt = recordedZoneOffsets();
expect(offsetAt(45.43, 12.33, at('2026-05-14T12:00:00Z'))).toBe(120);
expect(offsetAt(45.43, 12.33, at('2026-01-14T12:00:00Z'))).toBe(60);
expect(offsetAt(40.71, -74.0, at('2026-05-14T12:00:00Z'))).toBe(-240);
// Asked again, the same answer from what it read before.
expect(offsetAt(45.43, 12.33, at('2026-05-14T12:30:00Z'))).toBe(120);
});
});
@@ -0,0 +1,283 @@
/**
* JourneyGpxImportService (#3085): the days of a GPX file kept by a journey
* beside the ones taken over from Dawarich. The suite takes the service from
* its module over a snapshot test db, so the journey access, the GPX reader,
* the kept rows and the broadcasts are the real ones.
*
* What it pins: a file is cut into the local days of where it was recorded
* and kept with source gpx; read again it replaces only the GPX version of
* its days, leaves an unchanged day and every Dawarich day alone; nothing is
* written for a file that is not GPX, has no times or holds nothing on the
* asked day; only an editor may; dropping a day names its source.
*/
import { JourneyRecordedDays } from '../../../src/db/entities/JourneyRecordedDays.entity';
import { DomainError } from '../../../src/nest/common/domain-error';
import { JourneyGpxImportService } from '../../../src/nest/journey-recordings/journey-gpx-import.service';
import { JourneyRecordingsModule } from '../../../src/nest/journey-recordings/journey-recordings.module';
import { JourneyRecordingsService } from '../../../src/nest/journey-recordings/journey-recordings.service';
import { JourneyRecordedDaysService } from '../../../src/nest/journey/journey-recorded-days.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addJourneyContributor, makeJourney } from '../../helpers/factories/journeys';
import { countRows, findRows } from '../../helpers/factories/rows';
import { setAddonEnabled } from '../../helpers/factories/settings';
import { makeUser } from '../../helpers/factories/users';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let svc: JourneyGpxImportService;
let recordings: JourneyRecordingsService;
let kept: JourneyRecordedDaysService;
beforeAll(async () => {
t = await createTestModule({ db, imports: [JourneyRecordingsModule] });
svc = t.get(JourneyGpxImportService);
recordings = t.get(JourneyRecordingsService);
kept = t.get(JourneyRecordedDaysService);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
t.realtime.reset();
await setAddonEnabled(orm, 'journey', true);
// A GPX file needs no Dawarich at all.
await setAddonEnabled(orm, 'dawarich', false);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
type Pt = [number, number, string | null];
/** A GPX document of the given track segments, a point being `[lat, lng, time]`. */
function gpx(...segments: Pt[][]): Buffer {
const seg = (points: Pt[]) =>
`<trkseg>${points
.map(([lat, lng, time]) => `<trkpt lat="${lat}" lon="${lng}">${time ? `<time>${time}</time>` : ''}</trkpt>`)
.join('')}</trkseg>`;
return Buffer.from(`<?xml version="1.0"?><gpx version="1.1"><trk>${segments.map(seg).join('')}</trk></gpx>`);
}
/** A drive through the Veneto on the 14th and the 15th, in UTC; local time is two hours ahead. */
const TWO_DAYS = gpx(
[
[45.43, 12.33, '2026-05-14T08:00:00Z'],
[45.44, 12.34, '2026-05-14T08:05:00Z'],
[45.45, 12.35, '2026-05-14T08:10:00Z'],
],
[
[45.5, 11.9, '2026-05-15T07:00:00Z'],
[45.51, 11.91, '2026-05-15T07:05:00Z'],
[45.51, 11.92, null],
],
);
async function fixture() {
const { user: owner } = await makeUser(orm, { username: 'marta' });
const { user: editor } = await makeUser(orm, { username: 'jonas' });
const { user: viewer } = await makeUser(orm);
const { user: outsider } = await makeUser(orm);
const journey = await makeJourney(orm, owner.id, { title: 'Veneto' });
await addJourneyContributor(orm, journey.id, editor.id, 'editor');
await addJourneyContributor(orm, journey.id, viewer.id, 'viewer');
return { owner, editor, viewer, outsider, journey };
}
async function refusal(promise: Promise<unknown>): Promise<{ status: number; body: Record<string, unknown> }> {
const err = await promise.then(
() => null,
(e: unknown) => e,
);
expect(err).toBeInstanceOf(DomainError);
return { status: (err as DomainError).getStatus(), body: (err as DomainError).toBody() };
}
/** The day Dawarich kept for the 14th, to see that a GPX file never touches it. */
async function keepFromDawarich(journeyId: number, userId: number) {
await kept.keep(
journeyId,
userId,
{
date: '2026-05-14',
sourceKind: 'points',
utcOffsetMinutes: 120,
window: { from: '2026-05-13T22:00:00.000Z', to: '2026-05-14T22:00:00.000Z' },
segments: [
{
points: [
[45.434, 12.3388],
[45.4364, 12.3218],
],
mode: 'walking',
startedAt: '2026-05-14T09:00:00+02:00',
endedAt: '2026-05-14T09:40:00+02:00',
distanceMeters: 1500,
},
],
truncated: false,
fetchedAt: '2026-05-15T07:00:00.000Z',
contentHash: 'd'.repeat(64),
},
false,
);
}
describe('JourneyGpxImportService.importGpx', () => {
it('JRNGPX-SVC-001: keeps one GPX day per local day the file covers and tells everyone on the journey', async () => {
const f = await fixture();
const result = await svc.importGpx(f.editor.id, f.journey.id, TWO_DAYS, {}, 'sock-1');
expect(result.untimedPoints).toBe(1);
expect(result.days.map(({ day, outcome }) => [day.date, day.source, day.sourceKind, outcome])).toEqual([
['2026-05-14', 'gpx', 'tracks', 'created'],
['2026-05-15', 'gpx', 'tracks', 'created'],
]);
expect(result.days[0]?.day).toMatchObject({
utcOffsetMinutes: 120,
window: { from: '2026-05-13T22:00:00.000Z', to: '2026-05-14T22:00:00.000Z' },
stats: { segmentCount: 1, firstAt: '2026-05-14T08:00:00.000Z', lastAt: '2026-05-14T08:10:00.000Z' },
importedBy: { username: 'jonas' },
truncated: false,
provisional: false,
});
const rows = await findRows(orm, JourneyRecordedDays, { journey: f.journey.id }, { local_date: 'asc' });
expect(rows.map((row) => [row.local_date, row.source])).toEqual([
['2026-05-14', 'gpx'],
['2026-05-15', 'gpx'],
]);
const told = t.realtime.broadcastToUserMock.mock.calls.filter(([userId]) => userId === f.viewer.id);
expect(told.map(([, event]) => event)).toEqual(
expect.arrayContaining([
{ type: 'journey:recording:updated', journeyId: f.journey.id, date: '2026-05-14' },
{ type: 'journey:recording:updated', journeyId: f.journey.id, date: '2026-05-15' },
]),
);
expect(told).toHaveLength(2);
expect(told.every(([, , socket]) => socket === 'sock-1')).toBe(true);
});
it('JRNGPX-SVC-002: read again, a file replaces only the GPX version of its days and never a Dawarich day', async () => {
const f = await fixture();
await keepFromDawarich(f.journey.id, f.owner.id);
await svc.importGpx(f.owner.id, f.journey.id, TWO_DAYS, {});
t.realtime.reset();
const same = await svc.importGpx(f.owner.id, f.journey.id, TWO_DAYS, {});
expect(same.days.map(({ outcome }) => outcome)).toEqual(['unchanged', 'unchanged']);
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
const longer = gpx([
[45.43, 12.33, '2026-05-14T08:00:00Z'],
[45.44, 12.34, '2026-05-14T08:05:00Z'],
[45.46, 12.37, '2026-05-14T08:20:00Z'],
]);
const replaced = await svc.importGpx(f.owner.id, f.journey.id, longer, {});
expect(replaced.days.map(({ day, outcome }) => [day.date, outcome])).toEqual([['2026-05-14', 'replaced']]);
expect(await countRows(orm, JourneyRecordedDays, { journey: f.journey.id })).toBe(3);
const dawarich = await kept.find(f.journey.id, '2026-05-14');
expect(dawarich).toMatchObject({ source: 'dawarich', contentHash: 'd'.repeat(64), sourceKind: 'points' });
expect((await kept.find(f.journey.id, '2026-05-15', 'gpx'))?.stats.segmentCount).toBe(1);
});
it('JRNGPX-SVC-003: one day of the file with date, every day in one zone the caller fixes with utcOffsetMinutes', async () => {
const f = await fixture();
// Ten hours west of UTC, the file's mornings are the evenings before.
const fixed = await svc.importGpx(f.owner.id, f.journey.id, TWO_DAYS, { utcOffsetMinutes: -600 });
expect(fixed.days.map(({ day }) => [day.date, day.utcOffsetMinutes, day.window.from])).toEqual([
['2026-05-13', -600, '2026-05-13T10:00:00.000Z'],
['2026-05-14', -600, '2026-05-14T10:00:00.000Z'],
]);
const one = await svc.importGpx(f.owner.id, f.journey.id, TWO_DAYS, { date: '2026-05-15' });
expect(one.days.map(({ day, outcome }) => [day.date, day.utcOffsetMinutes, outcome])).toEqual([
['2026-05-15', 120, 'created'],
]);
});
it('JRNGPX-SVC-004: a day asked for that the file does not cover writes nothing', async () => {
const f = await fixture();
expect(await refusal(svc.importGpx(f.owner.id, f.journey.id, TWO_DAYS, { date: '2026-05-20' }))).toEqual({
status: 422,
body: { error: 'The GPX file recorded nothing on that day', code: 'recording_empty' },
});
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
});
it('JRNGPX-SVC-005: refuses a file that is not GPX, declares a DOCTYPE or has no times, writing nothing', async () => {
const f = await fixture();
const unreadable = { status: 422, body: { error: 'The file is not a GPX file', code: 'gpx_unreadable' } };
expect(await refusal(svc.importGpx(f.owner.id, f.journey.id, Buffer.from('<kml/>'), {}))).toEqual(unreadable);
const doctype = Buffer.from('<?xml version="1.0"?><!DOCTYPE gpx [<!ENTITY x "y">]><gpx><trk/></gpx>');
expect(await refusal(svc.importGpx(f.owner.id, f.journey.id, doctype, {}))).toEqual(unreadable);
const drawn = gpx([
[45.43, 12.33, null],
[45.44, 12.34, null],
]);
expect(await refusal(svc.importGpx(f.owner.id, f.journey.id, drawn, {}))).toEqual({
status: 422,
body: { error: 'The GPX file holds no track points with times', code: 'gpx_no_times' },
});
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
});
it('JRNGPX-SVC-006: refuses a stranger with 404 and a viewer with 403 before reading the file', async () => {
const f = await fixture();
expect(await refusal(svc.importGpx(f.outsider.id, f.journey.id, TWO_DAYS, {}))).toEqual({
status: 404,
body: { error: 'Journey not found' },
});
expect(await refusal(svc.importGpx(f.viewer.id, f.journey.id, TWO_DAYS, {}))).toEqual({
status: 403,
body: { error: 'Not allowed' },
});
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
});
it('JRNGPX-SVC-007: refuses a file that covers more days than a journey takes at once', async () => {
const f = await fixture();
const days = Array.from({ length: 121 }, (_, i) => {
const day = new Date(Date.UTC(2026, 0, 1 + i, 10)).toISOString();
const later = new Date(Date.UTC(2026, 0, 1 + i, 10, 5)).toISOString();
return [
[45.43, 12.33, day],
[45.44, 12.34, later],
] as Pt[];
});
expect(await refusal(svc.importGpx(f.owner.id, f.journey.id, gpx(...days), {}))).toEqual({
status: 422,
body: { error: 'A GPX file may cover at most 120 days', code: 'gpx_too_many_days' },
});
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
});
});
describe('JourneyRecordingsService.remove by source', () => {
it('JRNGPX-SVC-008: drops the GPX day and leaves the Dawarich one of the same date, and the other way round', async () => {
const f = await fixture();
await keepFromDawarich(f.journey.id, f.owner.id);
await svc.importGpx(f.owner.id, f.journey.id, TWO_DAYS, {});
await recordings.remove(f.editor.id, f.journey.id, '2026-05-14', undefined, 'gpx');
expect(await kept.find(f.journey.id, '2026-05-14', 'gpx')).toBeNull();
expect(await kept.find(f.journey.id, '2026-05-14')).not.toBeNull();
expect((await refusal(recordings.remove(f.editor.id, f.journey.id, '2026-05-14', undefined, 'gpx'))).status).toBe(
404,
);
await recordings.remove(f.editor.id, f.journey.id, '2026-05-15', undefined, 'gpx');
await recordings.remove(f.editor.id, f.journey.id, '2026-05-14');
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
});
});
@@ -342,4 +342,56 @@ describe('JourneyMapService.publicMapLayers', () => {
],
});
});
it('JRNMAP-013: a day read from a GPX file shows without an entry, and wins over a Dawarich day of its date', async () => {
const { token, journey, user } = await shared({ share_recordings: true });
await makeJourneyEntry(orm, journey.id, user.id, { entry_date: '2026-05-14' });
await keep(journey.id, user.id, '2026-05-14');
const gpxDay = (date: string, lng: number) => ({
date,
sourceKind: 'tracks' as const,
utcOffsetMinutes: 120,
window: { from: `${date}T00:00:00+02:00`, to: `${date}T23:59:59+02:00` },
segments: [
{
points: [
[45.43, 12.33],
[45.44, lng],
] as Array<[number, number]>,
mode: null,
startedAt: `${date}T08:00:00+02:00`,
endedAt: `${date}T08:30:00+02:00`,
distanceMeters: 1200,
},
],
truncated: false,
fetchedAt: `${date}T23:59:59+02:00`,
contentHash: 'b'.repeat(64),
});
await recorded.keepGpxDays(journey.id, user.id, [gpxDay('2026-05-14', 12.35), gpxDay('2026-05-16', 12.36)]);
const layers = await map.publicMapLayers(token);
const items = layers?.recordings.status === 'ok' ? layers.recordings.items : [];
expect(items.map((day) => [day.date, day.pieces])).toEqual([
[
'2026-05-14',
[
[
[45.43, 12.33],
[45.44, 12.35],
],
],
],
[
'2026-05-16',
[
[
[45.43, 12.33],
[45.44, 12.36],
],
],
],
]);
});
});
@@ -8,6 +8,7 @@ import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import type { JourneyGpxImportService } from '../../../src/nest/journey-recordings/journey-gpx-import.service';
import { JourneyRecordingsController } from '../../../src/nest/journey-recordings/journey-recordings.controller';
import type { JourneyRecordingsService } from '../../../src/nest/journey-recordings/journey-recordings.service';
import type { User } from '../../../src/types';
@@ -27,9 +28,14 @@ function controllerWith() {
remove: vi.fn(async () => undefined),
prepStatus: vi.fn(async () => ({ enabled: true })),
};
const gpx = { importGpx: vi.fn(async () => ({ days: [], untimedPoints: 0 })) };
return {
service,
controller: new JourneyRecordingsController(service as unknown as JourneyRecordingsService),
gpx,
controller: new JourneyRecordingsController(
service as unknown as JourneyRecordingsService,
gpx as unknown as JourneyGpxImportService,
),
};
}
@@ -45,6 +51,7 @@ describe('JourneyRecordingsController', () => {
['list', RequestMethod.GET, '/', undefined],
['prep', RequestMethod.GET, 'prep', undefined],
['preview', RequestMethod.POST, 'preview', 200],
['importGpx', RequestMethod.POST, 'import-gpx', 200],
['save', RequestMethod.PUT, ':date', undefined],
['remove', RequestMethod.DELETE, ':date', 200],
] as const;
@@ -70,15 +77,17 @@ describe('JourneyRecordingsController', () => {
expect(await controller.save(user, 9, '2026-05-14', save, 'sock-1')).toEqual({ outcome: 'created' });
expect(service.save).toHaveBeenCalledExactlyOnceWith(4, 9, '2026-05-14', save, 'sock-1');
expect(await controller.remove(user, 9, '2026-05-14', 'sock-1')).toEqual({ success: true });
expect(service.remove).toHaveBeenCalledExactlyOnceWith(4, 9, '2026-05-14', 'sock-1');
expect(await controller.remove(user, 9, '2026-05-14', {}, 'sock-1')).toEqual({ success: true });
expect(service.remove).toHaveBeenCalledExactlyOnceWith(4, 9, '2026-05-14', 'sock-1', undefined);
await controller.remove(user, 9, '2026-05-14', { source: 'gpx' });
expect(service.remove).toHaveBeenLastCalledWith(4, 9, '2026-05-14', undefined, 'gpx');
});
it('JRNREC-CTL-003: a day that is no calendar day is a 400 before the service is asked', async () => {
const { service, controller } = controllerWith();
const refusals = await Promise.all(
['2026-02-30', '14.05.2026', 'today'].map((date) =>
controller.remove(user, 9, date).catch((err: unknown) => err),
controller.remove(user, 9, date, {}).catch((err: unknown) => err),
),
);
for (const err of refusals) {
@@ -99,4 +108,21 @@ describe('JourneyRecordingsController', () => {
expect(await controller.prep(user, 9)).toEqual({ enabled: true });
expect(service.prepStatus).toHaveBeenCalledExactlyOnceWith(4, 9);
});
it('JRNREC-CTL-005: hands a GPX upload with its fields to the import, and refuses a request without a file (#3085)', async () => {
const { gpx, controller } = controllerWith();
const file = { buffer: Buffer.from('<gpx/>') } as Express.Multer.File;
expect(await controller.importGpx(user, 9, file, { date: '2026-05-14' }, 'sock-1')).toEqual({
days: [],
untimedPoints: 0,
});
expect(gpx.importGpx).toHaveBeenCalledExactlyOnceWith(4, 9, file.buffer, { date: '2026-05-14' }, 'sock-1');
const missing = await controller.importGpx(user, 9, undefined, {}).catch((err: unknown) => err);
expect(missing).toBeInstanceOf(HttpException);
expect((missing as HttpException).getStatus()).toBe(400);
expect((missing as HttpException).getResponse()).toEqual({ error: 'No file uploaded', code: 'no-file' });
expect(gpx.importGpx).toHaveBeenCalledTimes(1);
});
});
@@ -190,4 +190,37 @@ describe('JourneyRecordingsMcp', () => {
});
await expect(mcp.getRecordingPrep({ journeyId: f.journey.id }, ctx(f.viewer.id))).rejects.toThrow('Not allowed');
});
it('JRNREC-MCP-005: reads days from GPX text and drops a day of one source, as REST does (#3085)', async () => {
const f = await fixture();
const gpx =
'<gpx><trk><trkseg>' +
'<trkpt lat="45.43" lon="12.33"><time>2026-05-14T08:00:00Z</time></trkpt>' +
'<trkpt lat="45.44" lon="12.34"><time>2026-05-14T08:05:00Z</time></trkpt>' +
'<trkpt lat="45.45" lon="12.36"/>' +
'</trkseg></trk></gpx>';
const imported = read(await mcp.importGpxDays({ journeyId: f.journey.id, gpx }, ctx(f.owner.id)));
expect(imported.untimedPoints).toBe(1);
expect(imported.days).toHaveLength(1);
expect(imported.days[0]).toMatchObject({ outcome: 'created', day: { date: '2026-05-14', source: 'gpx' } });
expect(imported.days[0].day.segments).toBeUndefined();
await expect(mcp.importGpxDays({ journeyId: f.journey.id, gpx }, ctx(f.viewer.id))).rejects.toThrow('Not allowed');
// Without a source the Dawarich day is meant, and there is none.
const day = { journeyId: f.journey.id, date: '2026-05-14' };
await expect(mcp.deleteRecordedDay(day, ctx(f.owner.id))).rejects.toThrow('No recording kept for that day');
const dropped = await mcp.deleteRecordedDay({ ...day, source: 'gpx' }, ctx(f.owner.id));
expect(read(dropped)).toEqual({ success: true });
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
const entry = getEntry(JourneyRecordingsMcp as unknown as ClassRef, 'importGpxDays');
if (entry?.kind !== 'tool') throw new Error('importGpxDays is no tool');
expect(entry.options.access).toEqual({ group: 'journey', mode: 'write' });
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled');
enabled.mockImplementation(async (id: string) => id !== 'dawarich');
expect(await entry.options.when?.(ctx(1), mcp)).toBe(true);
enabled.mockImplementation(async (id: string) => id !== 'journey');
expect(await entry.options.when?.(ctx(1), mcp)).toBe(false);
});
});
@@ -9,6 +9,7 @@ import {
buildTourGpx,
GpxProvider,
gpxFilename,
readGpxTrackPoints,
trackTimeSpan,
type GpxExportPlace,
type GpxExportDay,
@@ -389,3 +390,47 @@ describe('track times (ACT-01)', () => {
expect(byName.get('Drawn')).not.toHaveProperty('trackTimes');
});
});
describe('recorded track points (#3085)', () => {
const doc = (body: string) => Buffer.from(`<?xml version="1.0"?><gpx version="1.1">${body}</gpx>`);
it('GPX-REC-001: every track segment apart, its points in file order with the times that carry a zone', () => {
const read = readGpxTrackPoints(
doc(
'<wpt lat="1" lon="1"><name>Pin</name></wpt>' +
'<rte><rtept lat="2" lon="2"/></rte>' +
'<trk><trkseg>' +
'<trkpt lat="45.43" lon="12.33"><time>2026-05-14T08:00:00Z</time></trkpt>' +
'<trkpt lat="45.44" lon="12.34"><time>2026-05-14T10:00:00+02:00</time></trkpt>' +
'<trkpt lat="45.45" lon="12.35"><time>2026-05-14T08:10:00</time></trkpt>' +
'<trkpt lat="45.46" lon="12.36"/>' +
'</trkseg><trkseg>' +
'<trkpt lat="45.47" lon="12.37"><time>2026-05-14T09:00:00Z</time></trkpt>' +
'<trkpt lat="95" lon="12.38"><time>2026-05-14T09:01:00Z</time></trkpt>' +
'<trkpt lat="x" lon="12.38"><time>2026-05-14T09:01:00Z</time></trkpt>' +
'</trkseg><trkseg/></trk>',
),
);
expect(read).toEqual({
segments: [
[
{ lat: 45.43, lng: 12.33, at: Date.parse('2026-05-14T08:00:00Z') },
{ lat: 45.44, lng: 12.34, at: Date.parse('2026-05-14T08:00:00Z') },
{ lat: 45.45, lng: 12.35, at: null },
{ lat: 45.46, lng: 12.36, at: null },
],
[{ lat: 45.47, lng: 12.37, at: Date.parse('2026-05-14T09:00:00Z') }],
],
});
});
it('GPX-REC-002: a file that is not GPX, or declares a DOCTYPE, reads as nothing; one without tracks as no segments', () => {
expect(readGpxTrackPoints(Buffer.from('<kml><Placemark/></kml>'))).toBeNull();
expect(readGpxTrackPoints(Buffer.from('not xml at all'))).toBeNull();
expect(
readGpxTrackPoints(Buffer.from('<?xml version="1.0"?><!DOCTYPE gpx [<!ENTITY a "b">]><gpx><trk/></gpx>')),
).toBeNull();
expect(readGpxTrackPoints(doc('<wpt lat="1" lon="1"/>'))).toEqual({ segments: [] });
expect(new GpxProvider().readTrackPoints(doc('<trk/>'))).toEqual({ segments: [] });
});
});
@@ -114,6 +114,16 @@ describe('PlaceImportService: files and lists', () => {
expect(svc.tripGpxFilename('My Trip')).toBe('My-Trip.gpx');
});
it('reads the recorded track points of a GPX file for a journey (#3085)', () => {
const gpx = Buffer.from(
'<gpx><trk><trkseg><trkpt lat="1" lon="2"><time>2026-05-14T08:00:00Z</time></trkpt></trkseg></trk></gpx>',
);
expect(svc.readGpxTrackPoints(gpx)).toEqual({
segments: [[{ lat: 1, lng: 2, at: Date.parse('2026-05-14T08:00:00Z') }]],
});
expect(svc.readGpxTrackPoints(Buffer.from('<kml/>'))).toBeNull();
});
it('writes a list as GPX and reads it back', () => {
const exported = svc.writeCollectionGpx({
format: COLLECTION_FILE_FORMAT,