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
@@ -67,9 +67,13 @@ export class JourneyRecordedDaysRepository extends TrekRepository<JourneyRecorde
]);
}
/** The days a journey keeps, earliest first. */
/** The days a journey keeps, earliest first, the sources of one day in the order of their names. */
async listForJourney(journeyId: number): Promise<JourneyRecordedDayRow[]> {
return await this.selectRows().where('d.journey_id', '=', journeyId).orderBy('d.local_date', 'asc').execute();
return await this.selectRows()
.where('d.journey_id', '=', journeyId)
.orderBy('d.local_date', 'asc')
.orderBy('d.source', 'asc')
.execute();
}
/** The version a journey keeps for one day of one source; undefined while it keeps none. */
@@ -112,6 +116,36 @@ export class JourneyRecordedDaysRepository extends TrekRepository<JourneyRecorde
return written.id;
}
/**
* Keeps several days in one statement, each replacing the version kept for
* its journey, day and source; a replaced day keeps its id and the time it
* was first taken over. Nothing is written for an empty list.
*/
async upsertDays(days: readonly JourneyRecordedDayWrite[]): Promise<void> {
if (days.length === 0) return;
const now = dbNow();
await this.db()
.insertInto('journey_recorded_days')
.values(days.map((day) => ({ ...day, created_at: now, updated_at: now })))
.onConflict((oc) =>
oc.columns(['journey_id', 'local_date', 'source']).doUpdateSet((eb) => ({
source_kind: eb.ref('excluded.source_kind'),
utc_offset_minutes: eb.ref('excluded.utc_offset_minutes'),
window_from: eb.ref('excluded.window_from'),
window_to: eb.ref('excluded.window_to'),
segments: eb.ref('excluded.segments'),
point_count: eb.ref('excluded.point_count'),
distance_m: eb.ref('excluded.distance_m'),
content_hash: eb.ref('excluded.content_hash'),
truncated: eb.ref('excluded.truncated'),
fetched_at: eb.ref('excluded.fetched_at'),
imported_by: eb.ref('excluded.imported_by'),
updated_at: now,
})),
)
.execute();
}
/**
* Keeps a day only while the journey keeps none for that day and source, and
* answers its id; undefined when another version was there first. Two takeovers
@@ -0,0 +1,185 @@
import { offsetMinutesAt, resolveTimeZone } from '../common/timezoneService';
import type { GpxTrackPoint, GpxTrackRead } from '../place-import/place-import.types';
import {
DAWARICH_TRACK_POINTS_PER_DAY,
RECORDING_GAP_METERS,
capLinePoints,
haversineMetres,
thinRecordedLine,
type DawarichTrackSegment,
} from '@trek/shared';
/**
* Cutting a GPX file into the local days a journey keeps (#3085), the way a
* day taken over from Dawarich is kept: its pieces apart where the recording
* has a gap, thinned for the map, each day in one zone.
*
* A point names its day by its own time in the zone of where it was recorded,
* so a trip across zones lands every evening on the right date, unless the
* caller fixes one zone for the whole file. A point without a time with a zone
* names no day and is counted, not guessed.
*/
/** A local day of a GPX file, ready to be kept. */
interface GpxDay {
date: string;
/** The zone the day is cut in: that of its first point. */
utcOffsetMinutes: number;
window: { from: string; to: string };
segments: DawarichTrackSegment[];
}
interface GpxDayCut {
days: GpxDay[];
/** Points that carry no time with a zone. */
untimedPoints: number;
/** Points that carry one, whether or not their day was kept. */
timedPoints: number;
}
/** Minutes east of UTC at a place and an instant. */
type OffsetAt = (lat: number, lng: number, at: number) => number;
/** Silence this long that also ends somewhere else is a gap in the recording, as for Dawarich. */
const GAP_MS = 15 * 60_000;
/** Simplification tolerance in degrees, roughly five metres. */
const EPSILON = 0.00005;
const DAY_MS = 86_400_000;
interface PlacedPoint {
lat: number;
lng: number;
at: number;
date: string;
offset: number;
}
/**
* The days a GPX file covers, earliest first. With `date`, only that local
* day; with `utcOffsetMinutes`, every point is placed in that one zone instead
* of the zone of where it was recorded.
*/
export function cutGpxDays(
read: GpxTrackRead,
options: { date?: string; utcOffsetMinutes?: number },
offsetAt: OffsetAt,
): GpxDayCut {
const runsByDate = new Map<string, PlacedPoint[][]>();
const keep = (run: PlacedPoint[]) => {
const first = run[0];
if (!first) return;
const runs = runsByDate.get(first.date);
if (runs) runs.push(run);
else runsByDate.set(first.date, [run]);
};
let untimedPoints = 0;
let timedPoints = 0;
for (const segment of read.segments) {
const timed = segment.filter((point): point is GpxTrackPoint & { at: number } => point.at !== null);
untimedPoints += segment.length - timed.length;
timedPoints += timed.length;
timed.sort((a, b) => a.at - b.at);
let run: PlacedPoint[] = [];
for (const point of timed) {
const offset = options.utcOffsetMinutes ?? offsetAt(point.lat, point.lng, point.at);
const placed = { ...point, offset, date: new Date(point.at + offset * 60_000).toISOString().slice(0, 10) };
const last = run[run.length - 1];
if (last && (last.date !== placed.date || isGap(last, placed))) {
keep(run);
run = [];
}
run.push(placed);
}
keep(run);
}
const dates = [...runsByDate.keys()]
.filter((date) => options.date === undefined || date === options.date)
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
const days: GpxDay[] = [];
for (const date of dates) {
const runs = (runsByDate.get(date) ?? []).sort((a, b) => (a[0]?.at ?? 0) - (b[0]?.at ?? 0));
const segments = segmentsOf(runs);
const offset = runs[0]?.[0]?.offset ?? 0;
if (segments.length === 0) continue;
const from = Date.parse(`${date}T00:00:00Z`) - offset * 60_000;
days.push({
date,
utcOffsetMinutes: offset,
window: { from: new Date(from).toISOString(), to: new Date(from + DAY_MS).toISOString() },
segments,
});
}
return { days, untimedPoints, timedPoints };
}
function isGap(a: PlacedPoint, b: PlacedPoint): boolean {
return b.at - a.at > GAP_MS && haversineMetres(a.lat, a.lng, b.lat, b.lng) > RECORDING_GAP_METERS;
}
/**
* The runs of one day as drawable pieces, the day's point budget shared out by
* how many points each run brought. A run that thins to one point is a fix,
* not a way, and is left out. A piece's distance is measured on the full run,
* before thinning shortens it.
*/
function segmentsOf(runs: PlacedPoint[][]): DawarichTrackSegment[] {
const total = runs.reduce((sum, run) => sum + run.length, 0);
const segments: DawarichTrackSegment[] = [];
for (const run of runs) {
const first = run[0];
const last = run[run.length - 1];
if (!first || !last || run.length < 2) continue;
const budget = Math.max(2, Math.floor((DAWARICH_TRACK_POINTS_PER_DAY * run.length) / total));
const line = capLinePoints(
thinRecordedLine(
run.map((point): [number, number] => [point.lat, point.lng]),
EPSILON,
),
budget,
);
if (line.length < 2) continue;
let distance = 0;
for (let i = 1; i < run.length; i++) {
const a = run[i - 1] as PlacedPoint;
const b = run[i] as PlacedPoint;
distance += haversineMetres(a.lat, a.lng, b.lat, b.lng);
}
segments.push({
points: line,
mode: null,
startedAt: new Date(first.at).toISOString(),
endedAt: new Date(last.at).toISOString(),
distanceMeters: Math.round(distance),
});
}
return segments;
}
/**
* The offset of where and when a point was recorded, read from the time zone
* map; UTC where the map names no zone. Zones are looked up per cell of about
* a kilometre and offsets per zone and hour, so a day of one-second tracking
* asks each only a few times.
*/
export function recordedZoneOffsets(): OffsetAt {
const zones = new Map<string, string | null>();
const offsets = new Map<string, number>();
return (lat, lng, at) => {
const cell = `${lat.toFixed(2)},${lng.toFixed(2)}`;
let zone = zones.get(cell);
if (zone === undefined) {
zone = resolveTimeZone(lat, lng);
zones.set(cell, zone);
}
if (!zone) return 0;
const key = `${zone}|${Math.floor(at / 3_600_000)}`;
let offset = offsets.get(key);
if (offset === undefined) {
offset = offsetMinutesAt(zone, at);
offsets.set(key, offset);
}
return offset;
};
}
@@ -0,0 +1,75 @@
import { DomainError } from '../common/domain-error';
import { JourneyDomainService } from '../journey/journey-domain.service';
import { JourneyRecordedDaysService } from '../journey/journey-recorded-days.service';
import { PlaceImportService } from '../place-import/place-import.service';
import { cutGpxDays, recordedZoneOffsets } from './journey-gpx-days.helpers';
import { JourneyRecordingsService } from './journey-recordings.service';
import { Injectable } from '@nestjs/common';
import { JOURNEY_GPX_MAX_DAYS, type JourneyGpxImportOptions, type JourneyGpxImportResult } from '@trek/shared';
/**
* Recorded days from a GPX file (#3085), the second source beside Dawarich: a
* car's or a watch's track, cut into the local days of the journey and kept
* like a day taken over from Dawarich, so the journey map draws it.
*
* Needs the right to edit the journey and no integration. A file read again
* replaces the GPX version of each day it covers and leaves every other day,
* and every day Dawarich keeps, as it was. Nothing is written before the
* whole file is read and cut, and the days are kept in one transaction.
*/
@Injectable()
export class JourneyGpxImportService {
constructor(
private readonly recordings: JourneyRecordingsService,
private readonly recordedDays: JourneyRecordedDaysService,
private readonly journeys: JourneyDomainService,
private readonly placeImport: PlaceImportService,
) {}
async importGpx(
userId: number,
journeyId: number,
file: Buffer,
options: JourneyGpxImportOptions,
socketId?: string,
): Promise<JourneyGpxImportResult> {
await this.recordings.requireEditable(journeyId, userId);
const read = this.placeImport.readGpxTrackPoints(file);
if (!read) throw gpxRefused('The file is not a GPX file', 'gpx_unreadable');
const cut = cutGpxDays(read, options, recordedZoneOffsets());
if (cut.timedPoints === 0) {
throw gpxRefused('The GPX file holds no track points with times', 'gpx_no_times');
}
if (cut.days.length === 0) throw gpxRefused('The GPX file recorded nothing on that day', 'recording_empty');
if (cut.days.length > JOURNEY_GPX_MAX_DAYS) {
throw gpxRefused(`A GPX file may cover at most ${JOURNEY_GPX_MAX_DAYS} days`, 'gpx_too_many_days');
}
const readAt = new Date().toISOString();
const days = await this.recordedDays.keepGpxDays(
journeyId,
userId,
cut.days.map((day) => ({
...day,
sourceKind: 'tracks' as const,
truncated: false,
fetchedAt: readAt,
contentHash: this.recordedDays.hashOf(day.segments, day.utcOffsetMinutes),
})),
);
// One ping per day that changed, after the commit; a reader reads the days again once for the burst.
await Promise.all(
days
.filter(({ outcome }) => outcome !== 'unchanged')
.map(({ day }) =>
this.journeys.broadcastJourneyEvent(journeyId, 'journey:recording:updated', { date: day.date }, socketId),
),
);
return { days, untimedPoints: cut.untimedPoints };
}
}
function gpxRefused(message: string, code: string): DomainError {
return new DomainError(422, message, { details: { code } });
}
@@ -6,7 +6,13 @@ import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { rowId } from '../common/row-id.pipe';
import { JourneyRecordingPreviewDto, JourneyRecordingSaveDto } from './journey-recordings.dto';
import { JourneyGpxImportService } from './journey-gpx-import.service';
import {
JourneyGpxImportDto,
JourneyRecordingDeleteQueryDto,
JourneyRecordingPreviewDto,
JourneyRecordingSaveDto,
} from './journey-recordings.dto';
import { JourneyRecordingsService } from './journey-recordings.service';
import {
Body,
@@ -19,9 +25,15 @@ import {
Param,
Post,
Put,
Query,
UploadedFile,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
JOURNEY_GPX_MAX_BYTES,
journeyGpxImportResultSchema,
journeyRecordedDaysResponseSchema,
journeyRecordingDateSchema,
journeyRecordingPrepSchema,
@@ -30,17 +42,26 @@ import {
successResponseSchema,
} from '@trek/shared';
import { memoryStorage } from 'multer';
// A GPX file is read and dropped, never stored: held in memory under its cap.
const GPX_UPLOAD = { storage: memoryStorage(), limits: { fileSize: JOURNEY_GPX_MAX_BYTES } };
/**
* The days of recorded route a journey keeps (JRN-01), at
* `/api/journeys/:id/recordings`. Reading them needs only access to the
* journey; previewing and keeping a day needs the right to edit it and the
* Dawarich addon, and reads the caller's own connection.
* Dawarich addon, and reads the caller's own connection. Reading days from a
* GPX file (#3085) needs the right to edit and nothing else.
*/
@Controller('api/journeys/:id/recordings')
@UseGuards(AddonGuard, JwtAuthGuard)
@RequireAddon(ADDON_IDS.JOURNEY, 'Journey')
export class JourneyRecordingsController {
constructor(private readonly recordings: JourneyRecordingsService) {}
constructor(
private readonly recordings: JourneyRecordingsService,
private readonly gpxImport: JourneyGpxImportService,
) {}
@Get()
@ResponseContract(journeyRecordedDaysResponseSchema)
@@ -66,6 +87,22 @@ export class JourneyRecordingsController {
return await this.recordings.preview(user.id, id, body);
}
/** The local days a GPX file covers, kept as the journey's GPX days; checked in the handler, never by a guard. */
@Post('import-gpx')
@HttpCode(200)
@UseInterceptors(FileInterceptor('file', GPX_UPLOAD))
@ResponseContract(journeyGpxImportResultSchema)
async importGpx(
@CurrentUser() user: User,
@Param('id', rowId('Journey not found')) id: number,
@UploadedFile() file: Express.Multer.File | undefined,
@Body() body: JourneyGpxImportDto,
@Headers('x-socket-id') socketId?: string,
) {
if (!file) throw new HttpException({ error: 'No file uploaded', code: 'no-file' }, 400);
return await this.gpxImport.importGpx(user.id, id, file.buffer, body, socketId);
}
@Put(':date')
@ResponseContract(journeyRecordingSaveResultSchema)
async save(
@@ -85,9 +122,10 @@ export class JourneyRecordingsController {
@CurrentUser() user: User,
@Param('id', rowId('Journey not found')) id: number,
@Param('date') date: string,
@Query() query: JourneyRecordingDeleteQueryDto,
@Headers('x-socket-id') socketId?: string,
) {
await this.recordings.remove(user.id, id, dateParam(date), socketId);
await this.recordings.remove(user.id, id, dateParam(date), socketId, query.source);
return { success: true as const };
}
}
@@ -1,5 +1,7 @@
import {
journeyDayImportRequestSchema,
journeyGpxImportRequestSchema,
journeyRecordingDeleteQuerySchema,
journeyRecordingPreviewRequestSchema,
journeyRecordingSaveRequestSchema,
} from '@trek/shared';
@@ -9,3 +11,5 @@ import { createZodDto } from 'nestjs-zod';
export class JourneyRecordingPreviewDto extends createZodDto(journeyRecordingPreviewRequestSchema) {}
export class JourneyRecordingSaveDto extends createZodDto(journeyRecordingSaveRequestSchema) {}
export class JourneyDayImportDto extends createZodDto(journeyDayImportRequestSchema) {}
export class JourneyGpxImportDto extends createZodDto(journeyGpxImportRequestSchema) {}
export class JourneyRecordingDeleteQueryDto extends createZodDto(journeyRecordingDeleteQuerySchema) {}
@@ -10,15 +10,21 @@ import {
} from '../../nest-mcp';
import { addonGate, type HasAddons } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { JourneyGpxImportService } from './journey-gpx-import.service';
import { JourneyRecordingsService } from './journey-recordings.service';
import {
idSchema,
journeyGpxImportOptionsSchema,
journeyGpxTextSchema,
journeyRecordingDateSchema,
journeyRecordingDeleteQuerySchema,
journeyRecordingPreviewRequestSchema,
journeyRecordingSaveRequestSchema,
type JourneyGpxImportOptions,
type JourneyRecordedDay,
type JourneyRecordingPreviewRequest,
type JourneyRecordingSaveRequest,
type JourneyRecordingSource,
} from '@trek/shared';
const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY);
@@ -37,13 +43,14 @@ const bothAddonsOn = async (ctx: McpContext, self: HasAddons): Promise<boolean>
export class JourneyRecordingsMcp {
constructor(
private readonly recordings: JourneyRecordingsService,
private readonly gpxImport: JourneyGpxImportService,
readonly addons: AddonsService,
) {}
@Tool({
name: 'list_journey_recorded_days',
description:
'The days of route recorded in Dawarich that a journey keeps, one per local day: the zone the day was cut in, what it covers (distance, pieces, gaps without recording, modes, first and last time), whether the source was incomplete or the day still running when it was taken over, and whose recording it is. Kept days stay readable when Dawarich is unreachable.',
'The days of recorded route a journey keeps, taken over from Dawarich (source dawarich) or read from a GPX file (source gpx), one per local day and source: the zone the day was cut in, what it covers (distance, pieces, gaps without recording, modes, first and last time), whether the source was incomplete or the day still running when it was taken over, and whose recording it is. Kept days stay readable when Dawarich is unreachable.',
inputSchema: { journeyId: idSchema },
annotations: TOOL_ANNOTATIONS_READONLY,
when: journeyAddonOn,
@@ -102,17 +109,42 @@ export class JourneyRecordingsMcp {
return ok({ outcome, day: summary(day) });
}
@Tool({
name: 'import_journey_gpx_days',
description:
"Read the recorded route of a GPX file (its track segments with times; waypoints and routes are left out) into a journey as recorded days with source gpx, one per local day the file covers, so the journey map draws them, also on days without an entry. Each point names its day in the zone of where it was recorded unless utcOffsetMinutes fixes one zone; date keeps only that one local day. A day the journey kept from a GPX file before is replaced, one kept exactly so is left as it is, and a day kept from Dawarich is never touched. Points without a time with a zone are counted as untimedPoints and left out. Never changes an entry or a text of the journey. Everyone who can open the journey sees the route on its map. Needs edit access to the journey.",
inputSchema: { journeyId: idSchema, gpx: journeyGpxTextSchema, ...journeyGpxImportOptionsSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: journeyAddonOn,
access: { group: 'journey', mode: 'write' },
})
async importGpxDays(
{ journeyId, gpx, ...options }: { journeyId: number; gpx: string } & JourneyGpxImportOptions,
ctx: McpContext,
) {
const { days, untimedPoints } = await this.gpxImport.importGpx(
ctx.userId,
journeyId,
Buffer.from(gpx, 'utf-8'),
options,
);
return ok({ days: days.map(({ day, outcome }) => ({ outcome, day: summary(day) })), untimedPoints });
}
@Tool({
name: 'delete_journey_recorded_day',
description:
'Drop the recorded route a journey keeps for one local day. Its entries and texts stay as they are, and Dawarich keeps its own recording. Needs edit access to the journey.',
inputSchema: { journeyId: idSchema, date: journeyRecordingDateSchema },
"Drop the recorded route a journey keeps for one local day from one source: dawarich when source is left out, gpx for a day read from a GPX file. The other source's version of the day, the entries and the texts stay as they are, and Dawarich keeps its own recording. Needs edit access to the journey.",
inputSchema: { journeyId: idSchema, date: journeyRecordingDateSchema, ...journeyRecordingDeleteQuerySchema.shape },
annotations: TOOL_ANNOTATIONS_DELETE,
when: journeyAddonOn,
access: { group: 'journey', mode: 'write' },
})
async deleteRecordedDay({ journeyId, date }: { journeyId: number; date: string }, ctx: McpContext) {
await this.recordings.remove(ctx.userId, journeyId, date);
async deleteRecordedDay(
{ journeyId, date, source }: { journeyId: number; date: string; source?: JourneyRecordingSource },
ctx: McpContext,
) {
await this.recordings.remove(ctx.userId, journeyId, date, undefined, source);
return ok({ success: true });
}
}
@@ -1,9 +1,11 @@
import { AddonsModule } from '../addons/addons.module';
import { DawarichModule } from '../integrations/dawarich.module';
import { JourneyDomainModule } from '../journey/journey-domain.module';
import { PlaceImportModule } from '../place-import/place-import.module';
import { JourneyDayImportController } from './journey-day-import.controller';
import { JourneyDayImportMcp } from './journey-day-import.mcp';
import { JourneyDayImportService } from './journey-day-import.service';
import { JourneyGpxImportService } from './journey-gpx-import.service';
import { JourneyRecordingsController } from './journey-recordings.controller';
import { JourneyRecordingsMcp } from './journey-recordings.mcp';
import { JourneyRecordingsService } from './journey-recordings.service';
@@ -14,11 +16,19 @@ import { Module } from '@nestjs/common';
* from the caller's Dawarich connection, its routes and its MCP tools. The
* days themselves belong to the journey domain; this module only brings them
* in from Dawarich, so neither of the two has to import the other. A day
* taken over with its stays as drafts (JRN-02) lives here for the same reason.
* taken over with its stays as drafts (JRN-02) lives here for the same reason,
* and so do the days read from a GPX file (#3085), through the place import's
* GPX reader.
*/
@Module({
imports: [JourneyDomainModule, DawarichModule, AddonsModule],
imports: [JourneyDomainModule, DawarichModule, AddonsModule, PlaceImportModule],
controllers: [JourneyRecordingsController, JourneyDayImportController],
providers: [JourneyRecordingsService, JourneyRecordingsMcp, JourneyDayImportService, JourneyDayImportMcp],
providers: [
JourneyRecordingsService,
JourneyRecordingsMcp,
JourneyDayImportService,
JourneyDayImportMcp,
JourneyGpxImportService,
],
})
export class JourneyRecordingsModule {}
@@ -15,6 +15,7 @@ import {
type JourneyRecordingPreviewRequest,
type JourneyRecordingSaveRequest,
type JourneyRecordingSaveResult,
type JourneyRecordingSource,
} from '@trek/shared';
/**
@@ -128,10 +129,20 @@ export class JourneyRecordingsService {
return { day: kept, outcome: stored ? 'replaced' : 'created' };
}
/** Drops the day a journey keeps. Needs no Dawarich: a kept day stays removable once the connection is gone. */
async remove(userId: number, journeyId: number, date: string, socketId?: string): Promise<void> {
/**
* Drops the day a journey keeps from one source, Dawarich's unless another is
* named; the other source's version of the day stays. Needs no Dawarich: a
* kept day stays removable once the connection is gone.
*/
async remove(
userId: number,
journeyId: number,
date: string,
socketId?: string,
source: JourneyRecordingSource = 'dawarich',
): Promise<void> {
await this.requireEditable(journeyId, userId);
if (!(await this.recordedDays.remove(journeyId, date))) throw notFound('No recording kept for that day');
if (!(await this.recordedDays.remove(journeyId, date, source))) throw notFound('No recording kept for that day');
await this.journeys.broadcastJourneyEvent(journeyId, 'journey:recording:updated', { date }, socketId);
}
+25 -19
View File
@@ -15,14 +15,15 @@ import { isValidGeoPoint, parseRouteGeometry } from './journey-geometry';
import { JourneyRecordedDaysService } from './journey-recorded-days.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type {
JourneyMapLayerResult,
JourneyMapLayersResponse,
JourneyMapPlace,
JourneyMapRecording,
JourneyMapStay,
JourneyPublicMapLayersResponse,
JourneyTrack,
import {
oneRecordingPerDay,
type JourneyMapLayerResult,
type JourneyMapLayersResponse,
type JourneyMapPlace,
type JourneyMapRecording,
type JourneyMapStay,
type JourneyPublicMapLayersResponse,
type JourneyTrack,
} from '@trek/shared';
/** The entries a map may tie its plan and its stays to: who can read them is decided by the caller. */
@@ -77,7 +78,9 @@ export class JourneyMapService {
/**
* The map layers a share link shows, null for a link that does not exist.
* Drafts never reach it: the entries it ties places and stays to are the
* published ones, and a recorded day shows only beside a published entry.
* published ones, and a day taken over from Dawarich shows only beside a
* published entry. A day read from a GPX file was uploaded to be shown and
* needs none.
*/
async publicMapLayers(token: string): Promise<JourneyPublicMapLayersResponse | null> {
const link = await this.shareTokensRepo.findByToken(token);
@@ -173,17 +176,20 @@ export class JourneyMapService {
);
}
/** The kept days that have one of the given entries on them, their pieces apart. */
/**
* The kept days, their pieces apart, one per date: a GPX day always, and in
* preference to a Dawarich one of the same date; a Dawarich day only with
* one of the given entries on it.
*/
private async recordings(journeyId: number, entries: EntryRef[]): Promise<JourneyMapRecording[]> {
const days = new Set(entries.map((entry) => entry.entry_date));
return (await this.recordedDays.list(journeyId))
.filter((day) => days.has(day.date))
.map((day) => ({
date: day.date,
pieces: day.segments
.map((segment) => segment.points.filter(([lat, lng]) => isValidGeoPoint(lat, lng)))
.filter((points) => points.length > 1),
distance_m: day.stats.distanceMeters,
}));
const shown = (await this.recordedDays.list(journeyId)).filter((day) => day.source === 'gpx' || days.has(day.date));
return oneRecordingPerDay(shown).map((day) => ({
date: day.date,
pieces: day.segments
.map((segment) => segment.points.filter(([lat, lng]) => isValidGeoPoint(lat, lng)))
.filter((points) => points.length > 1),
distance_m: day.stats.distanceMeters,
}));
}
}
@@ -8,9 +8,16 @@ import type {
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
import { parseDbTimestamp } from '../../db/types';
import { decodeJson } from '../../utils/json-column';
import { UnitOfWork } from '../database/unit-of-work';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import { recordingStats, type DawarichTrackSegment, type JourneyRecordedDay } from '@trek/shared';
import {
recordingStats,
type DawarichTrackSegment,
type JourneyGpxImportResult,
type JourneyRecordedDay,
type JourneyRecordingSource,
} from '@trek/shared';
import crypto from 'crypto';
@@ -26,18 +33,22 @@ interface RecordingToKeep {
contentHash: string;
}
const SOURCE = 'dawarich';
/** The source a day is read, kept and dropped for when the caller names none: the first there was. */
const DEFAULT_SOURCE: JourneyRecordingSource = 'dawarich';
/**
* The recorded days a journey keeps (JRN-01). The journey owns them, so its
* map can draw them without the integration they came from; taking a day
* over from Dawarich is `journey-recordings`' part.
* over from Dawarich or reading it from a GPX file is `journey-recordings`'
* part. A journey keeps one version of a day per source; each source reads,
* replaces and drops only its own.
*/
@Injectable()
export class JourneyRecordedDaysService {
constructor(
@InjectRepository(JourneyRecordedDays) private readonly days: JourneyRecordedDaysRepository,
@InjectRepository(Journeys) private readonly journeys: JourneysRepository,
private readonly uow: UnitOfWork,
) {}
/**
@@ -55,8 +66,12 @@ export class JourneyRecordedDaysService {
return (await this.days.listForJourney(journeyId)).map(toRecordedDay);
}
async find(journeyId: number, date: string): Promise<JourneyRecordedDay | null> {
const row = await this.days.findDay(journeyId, date, SOURCE);
async find(
journeyId: number,
date: string,
source: JourneyRecordingSource = DEFAULT_SOURCE,
): Promise<JourneyRecordedDay | null> {
const row = await this.days.findDay(journeyId, date, source);
return row ? toRecordedDay(row) : null;
}
@@ -71,23 +86,7 @@ export class JourneyRecordedDaysService {
recording: RecordingToKeep,
replace: boolean,
): Promise<JourneyRecordedDay | null> {
const stats = recordingStats(recording.segments);
const row = {
journey_id: journeyId,
local_date: recording.date,
source: SOURCE,
source_kind: recording.sourceKind,
utc_offset_minutes: recording.utcOffsetMinutes,
window_from: recording.window.from,
window_to: recording.window.to,
segments: JSON.stringify(recording.segments),
point_count: stats.pointCount,
distance_m: stats.distanceMeters,
content_hash: recording.contentHash,
truncated: recording.truncated ? 1 : 0,
fetched_at: recording.fetchedAt,
imported_by: userId,
};
const row = rowOf(journeyId, userId, DEFAULT_SOURCE, recording);
if (replace) await this.days.upsertDay(row);
else if ((await this.days.insertDayIfAbsent(row)) === undefined) return null;
const kept = await this.find(journeyId, recording.date);
@@ -95,8 +94,42 @@ export class JourneyRecordedDaysService {
return kept;
}
async remove(journeyId: number, date: string): Promise<boolean> {
return await this.days.deleteDay(journeyId, date, SOURCE);
/**
* Keeps the days read from one GPX file (#3085), all or none: each replaces
* the GPX version the journey kept for its date, a day kept already exactly
* so is left as it was, and a day another source keeps is never touched.
* Answers every day as kept, in the order given.
*/
async keepGpxDays(
journeyId: number,
userId: number,
recordings: RecordingToKeep[],
): Promise<JourneyGpxImportResult['days']> {
const outcomes = await this.uow.transactional(async () => {
const stored = new Map(
(await this.days.listForJourney(journeyId))
.filter((row) => row.source === 'gpx')
.map((row) => [row.local_date, row.content_hash]),
);
const changed = recordings.filter((recording) => stored.get(recording.date) !== recording.contentHash);
await this.days.upsertDays(changed.map((recording) => rowOf(journeyId, userId, 'gpx', recording)));
return recordings.map(({ date, contentHash }) => ({ date, outcome: outcomeOf(stored.get(date), contentHash) }));
});
const kept = new Map(
(await this.days.listForJourney(journeyId))
.filter((row) => row.source === 'gpx')
.map((row) => [row.local_date, toRecordedDay(row)]),
);
return outcomes.map(({ date, outcome }) => {
const day = kept.get(date);
if (!day) throw new Error(`Recorded day ${date} of journey ${journeyId} vanished after its write`);
return { day, outcome };
});
}
/** Drops the day a journey keeps from one source; false when it kept none. */
async remove(journeyId: number, date: string, source: JourneyRecordingSource = DEFAULT_SOURCE): Promise<boolean> {
return await this.days.deleteDay(journeyId, date, source);
}
/** How many people besides `userId` can open the journey, and so would see its map. */
@@ -105,12 +138,39 @@ export class JourneyRecordedDaysService {
}
}
/** What keeping a day did, given the hash the journey kept for its date and source before. */
function outcomeOf(storedHash: string | undefined, hash: string): JourneyGpxImportResult['days'][number]['outcome'] {
if (storedHash === undefined) return 'created';
return storedHash === hash ? 'unchanged' : 'replaced';
}
function rowOf(journeyId: number, userId: number, source: JourneyRecordingSource, recording: RecordingToKeep) {
const stats = recordingStats(recording.segments);
return {
journey_id: journeyId,
local_date: recording.date,
source,
source_kind: recording.sourceKind,
utc_offset_minutes: recording.utcOffsetMinutes,
window_from: recording.window.from,
window_to: recording.window.to,
segments: JSON.stringify(recording.segments),
point_count: stats.pointCount,
distance_m: stats.distanceMeters,
content_hash: recording.contentHash,
truncated: recording.truncated ? 1 : 0,
fetched_at: recording.fetchedAt,
imported_by: userId,
};
}
function toRecordedDay(row: JourneyRecordedDayRow): JourneyRecordedDay {
const segments = decodeJson(JOURNEY_RECORDED_DAY_SEGMENTS, row.segments, `recorded day ${row.id}`);
return {
id: row.id,
date: row.local_date,
source: SOURCE,
// A row of a source this build does not know reads as the first one, as every row did before there were two.
source: row.source === 'gpx' ? 'gpx' : DEFAULT_SOURCE,
sourceKind: row.source_kind === 'tracks' ? 'tracks' : 'points',
utcOffsetMinutes: row.utc_offset_minutes,
window: { from: row.window_from, to: row.window_to },
@@ -3,6 +3,7 @@ import type {
DirectionsRedirect,
GoogleListPlace,
GpxImportOptions,
GpxTrackRead,
KmlDocumentRead,
KmlTracksRead,
ListImportError,
@@ -81,6 +82,11 @@ export class PlaceImportService {
return this.gpx.read(fileBuffer, opts);
}
/** The recording a GPX file holds, track segment by track segment, or null for a file that is not GPX (#3085). */
readGpxTrackPoints(fileBuffer: Buffer): GpxTrackRead | null {
return this.gpx.readTrackPoints(fileBuffer);
}
/** A trip as a GPX document, or null when the selection yields nothing. */
writeTripGpx(input: GpxExportInput, opts: GpxExportOptions = {}): string | null {
return this.gpx.write(input, opts);
@@ -20,6 +20,18 @@ export interface PreparedGpxPlace {
trackTimes?: { startedAt: string; endedAt: string };
}
/** A recorded point of a GPX track: where, and when (ms since the epoch), null when it names no time with a zone. */
export interface GpxTrackPoint {
lat: number;
lng: number;
at: number | null;
}
/** The recording a GPX file holds: each track segment's points in file order, waypoints and routes left out. */
export interface GpxTrackRead {
segments: GpxTrackPoint[][];
}
export interface GpxImportOptions {
importWaypoints?: boolean;
importRoutes?: boolean;
@@ -1,6 +1,6 @@
import { createGeometryNamer } from '../geometry-names';
import { coord, gpxGeometryParser, writeGpx } from '../gpx.codec';
import type { GpxImportOptions, PreparedGpxPlace } from '../place-import.types';
import type { GpxImportOptions, GpxTrackPoint, GpxTrackRead, PreparedGpxPlace } from '../place-import.types';
import { Injectable } from '@nestjs/common';
/**
@@ -217,6 +217,13 @@ export function gpxFilename(tripTitle: string, fallback = 'trip'): string {
/** A time written with its zone (`Z` or an offset); one without is local to an unknown clock and reads as none. */
const ZONED_TIME = /(?:Z|[+-]\d{2}:?\d{2})$/i;
/** A point's `<time>` in ms since the epoch, only when it is written with its zone. */
function zonedInstant(raw: unknown): number | null {
const text = typeof raw === 'string' ? raw.trim() : '';
const at = ZONED_TIME.test(text) ? Date.parse(text) : Number.NaN;
return Number.isFinite(at) ? at : null;
}
/**
* ACT-01: when a track was recorded, from the times on its points: the first
* and the last, only when every point carries one with its zone and they never
@@ -227,9 +234,8 @@ export function trackTimeSpan(times: readonly unknown[]): { startedAt: string; e
let first: number | undefined;
let last = Number.NEGATIVE_INFINITY;
for (const raw of times) {
const text = typeof raw === 'string' ? raw.trim() : '';
const at = ZONED_TIME.test(text) ? Date.parse(text) : Number.NaN;
if (!Number.isFinite(at) || at < last) return undefined;
const at = zonedInstant(raw);
if (at === null || at < last) return undefined;
first ??= at;
last = at;
}
@@ -327,6 +333,40 @@ function prepareGpxRows(fileBuffer: Buffer, opts: GpxImportOptions = {}): Prepar
return waypoints;
}
/**
* The recording a GPX file holds (#3085): every `<trkseg>` of every `<trk>` as
* its points in file order, each with its time where it carries one with a
* zone. Waypoints and routes are planned, not recorded, and are left out.
* Null for a document that is not GPX, or that declares a DOCTYPE, whose
* entities are never expanded here.
*/
export function readGpxTrackPoints(fileBuffer: Buffer): GpxTrackRead | null {
const xml = fileBuffer.toString('utf-8');
if (/<!(?:DOCTYPE|ENTITY)/i.test(xml)) return null;
let parsed: { gpx?: { trk?: Array<{ trkseg?: Array<{ trkpt?: Array<Record<string, unknown>> }> }> } } | undefined;
try {
parsed = gpxGeometryParser.parse(xml);
} catch {
return null;
}
const gpx = parsed?.gpx;
if (!gpx || typeof gpx !== 'object') return null;
const segments: GpxTrackPoint[][] = [];
for (const trk of gpx.trk ?? []) {
for (const seg of trk?.trkseg ?? []) {
const points: GpxTrackPoint[] = [];
for (const pt of seg?.trkpt ?? []) {
const lat = Number.parseFloat(String(pt['@_lat']));
const lng = Number.parseFloat(String(pt['@_lon']));
if (!Number.isFinite(lat) || !Number.isFinite(lng) || Math.abs(lat) > 90 || Math.abs(lng) > 180) continue;
points.push({ lat, lng, at: zonedInstant(pt.time) });
}
if (points.length > 0) segments.push(points);
}
}
return { segments };
}
/** The times as a row carries them: left out, not undefined, when the track has none. */
function withTrackTimes(span: ReturnType<typeof trackTimeSpan>): Pick<PreparedGpxPlace, 'trackTimes'> {
return span ? { trackTimes: span } : {};
@@ -339,6 +379,11 @@ export class GpxProvider {
return prepareGpxRows(fileBuffer, opts);
}
/** The track points a journey cuts its recorded days from, or null for a file that is not GPX. */
readTrackPoints(fileBuffer: Buffer): GpxTrackRead | null {
return readGpxTrackPoints(fileBuffer);
}
write(input: GpxExportInput, opts: GpxExportOptions = {}): string | null {
return buildGpx(input, opts);
}
@@ -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,
@@ -1,7 +1,11 @@
import {
journeyGpxImportRequestSchema,
journeyRecordedDaySchema,
journeyRecordingDateSchema,
journeyRecordingDeleteQuerySchema,
journeyRecordingPreviewRequestSchema,
journeyRecordingSaveRequestSchema,
oneRecordingPerDay,
recordingStats,
} from './journey-recordings.schema';
@@ -117,3 +121,62 @@ describe('recordingStats', () => {
});
});
});
describe('journeyRecordedDaySchema', () => {
it('JRNREC-SCHEMA-006: reads a day kept from a GPX file, its pieces as tracks', () => {
const day = {
id: 1,
date: '2026-05-14',
source: 'gpx',
sourceKind: 'tracks',
utcOffsetMinutes: 120,
window: { from: '2026-05-13T22:00:00.000Z', to: '2026-05-14T22:00:00.000Z' },
segments: [],
stats: recordingStats([]),
truncated: false,
provisional: false,
fetchedAt: '2026-05-15T08:00:00.000Z',
contentHash: HASH,
importedBy: null,
savedAt: '2026-05-15T08:00:00.000Z',
};
expect(journeyRecordedDaySchema.safeParse(day).success).toBe(true);
expect(journeyRecordedDaySchema.safeParse({ ...day, source: 'strava' }).success).toBe(false);
});
});
describe('oneRecordingPerDay', () => {
it('JRNREC-SCHEMA-007: keeps one day per date, the GPX one where both sources kept it, earliest first', () => {
const days = [
{ date: '2026-05-15', source: 'dawarich' as const, id: 1 },
{ date: '2026-05-14', source: 'gpx' as const, id: 2 },
{ date: '2026-05-14', source: 'dawarich' as const, id: 3 },
{ date: '2026-05-16', source: 'gpx' as const, id: 4 },
{ date: '2026-05-16', source: 'dawarich' as const, id: 5 },
];
expect(oneRecordingPerDay(days).map((day) => day.id)).toEqual([2, 1, 4]);
expect(oneRecordingPerDay([])).toEqual([]);
});
});
describe('journeyGpxImportRequestSchema', () => {
it('JRNREC-SCHEMA-008: reads the multipart fields, the offset as whole minutes within the zones there are', () => {
expect(journeyGpxImportRequestSchema.parse({})).toEqual({});
expect(journeyGpxImportRequestSchema.parse({ date: '2026-05-14', utcOffsetMinutes: '-300' })).toEqual({
date: '2026-05-14',
utcOffsetMinutes: -300,
});
expect(journeyGpxImportRequestSchema.safeParse({ utcOffsetMinutes: '900' }).success).toBe(false);
expect(journeyGpxImportRequestSchema.safeParse({ utcOffsetMinutes: '1.5' }).success).toBe(false);
expect(journeyGpxImportRequestSchema.safeParse({ utcOffsetMinutes: 'abc' }).success).toBe(false);
expect(journeyGpxImportRequestSchema.safeParse({ date: '2026-02-30' }).success).toBe(false);
});
});
describe('journeyRecordingDeleteQuerySchema', () => {
it('JRNREC-SCHEMA-009: names a known source or none', () => {
expect(journeyRecordingDeleteQuerySchema.parse({})).toEqual({});
expect(journeyRecordingDeleteQuerySchema.parse({ source: 'gpx' })).toEqual({ source: 'gpx' });
expect(journeyRecordingDeleteQuerySchema.safeParse({ source: 'strava' }).success).toBe(false);
});
});
@@ -18,8 +18,13 @@ import { z } from 'zod';
* reveals one, else the one the traveller picks.
*/
/** Where a recorded day came from. One source today; the column is there for a second. */
export const JOURNEY_RECORDING_SOURCES = ['dawarich'] as const;
/**
* Where a recorded day came from: taken over from the caller's Dawarich, or
* read from a GPX file someone uploaded (#3085). A journey keeps at most one
* version of a day per source.
*/
export const JOURNEY_RECORDING_SOURCES = ['dawarich', 'gpx'] as const;
export type JourneyRecordingSource = (typeof JOURNEY_RECORDING_SOURCES)[number];
/** `YYYY-MM-DD`, a calendar day that exists. */
export const journeyRecordingDateSchema = z
@@ -60,7 +65,11 @@ export const journeyRecordedDaySchema = z.object({
id: z.number(),
date: z.string(),
source: z.enum(JOURNEY_RECORDING_SOURCES),
/** Which Dawarich endpoint answered: pre-segmented tracks or thinned points. */
/**
* Which Dawarich endpoint answered: pre-segmented tracks or thinned points. A
* day read from a GPX file is `tracks`, its pieces being the file's track
* segments, so a reader that knows only these two still reads it.
*/
sourceKind: z.enum(['tracks', 'points']),
utcOffsetMinutes: z.number(),
window: recordingWindowSchema,
@@ -191,3 +200,75 @@ export function recordingStats(segments: DawarichTrackSegment[]): JourneyRecordi
lastAt: segments[segments.length - 1]?.endedAt ?? null,
};
}
/**
* The days a map draws, one per local day: where a journey keeps a day from
* both sources, the GPX file wins, since someone uploaded it for that day on
* purpose. Earliest day first.
*/
export function oneRecordingPerDay<T extends { date: string; source: JourneyRecordingSource }>(
days: readonly T[],
): T[] {
const byDate = new Map<string, T>();
for (const day of days) {
const kept = byDate.get(day.date);
if (!kept || (kept.source !== 'gpx' && day.source === 'gpx')) byDate.set(day.date, day);
}
return [...byDate.values()].sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
}
// ── GPX as a source (#3085) ──────────────────────────────────────────────────
/** The largest GPX file a journey reads its recorded days from. */
export const JOURNEY_GPX_MAX_BYTES = 15 * 1024 * 1024;
/** The most local days one GPX file may put into a journey at once. */
export const JOURNEY_GPX_MAX_DAYS = 120;
/**
* How a GPX file is cut into days. Without `utcOffsetMinutes` every point is
* placed in the zone of where it was recorded; with it, every day is cut in
* that one zone. `date` keeps only that one local day of the file.
*/
export const journeyGpxImportOptionsSchema = z.object({
date: journeyRecordingDateSchema.optional(),
utcOffsetMinutes: utcOffsetMinutesSchema.optional(),
});
export type JourneyGpxImportOptions = z.infer<typeof journeyGpxImportOptionsSchema>;
/** A zone offset as a multipart field carries it: the digits of a whole number of minutes. */
const offsetFieldSchema = z
.string()
.regex(/^-?\d{1,3}$/)
.transform(Number)
.pipe(utcOffsetMinutesSchema);
/** The text fields beside the `file` of `POST /api/journeys/:id/recordings/import-gpx`. */
export const journeyGpxImportRequestSchema = z.object({
date: journeyRecordingDateSchema.optional(),
utcOffsetMinutes: offsetFieldSchema.optional(),
});
export type JourneyGpxImportRequest = z.input<typeof journeyGpxImportRequestSchema>;
/** A GPX document handed over as text (MCP), under the same cap as an upload. */
export const journeyGpxTextSchema = z.string().min(1).max(JOURNEY_GPX_MAX_BYTES);
export const journeyGpxImportResultSchema = z.object({
/** One per local day the file covers, earliest first. */
days: z.array(
z.object({
day: journeyRecordedDaySchema,
/** `unchanged`: the journey kept this very day from a GPX file already. */
outcome: z.enum(['created', 'replaced', 'unchanged']),
}),
),
/** Track points left out because they carry no time with a zone, so no day can be named for them. */
untimedPoints: z.number(),
});
export type JourneyGpxImportResult = z.infer<typeof journeyGpxImportResultSchema>;
/** Which source's day `DELETE /api/journeys/:id/recordings/:date` drops; Dawarich's when left out. */
export const journeyRecordingDeleteQuerySchema = z.object({
source: z.enum(JOURNEY_RECORDING_SOURCES).optional(),
});
export type JourneyRecordingDeleteQuery = z.infer<typeof journeyRecordingDeleteQuerySchema>;
+3 -2
View File
@@ -246,8 +246,9 @@ Requires `journey:read` or `journey:write` scope.
| `get_journey_share_link` | Get the current public share link for a journey. Requires `journey:share`. |
| `create_journey_share_link` | Create or update the public share link for a journey. `share_plan` adds the linked trips' planned places and GPX routes to the shared map, `share_recordings` the recorded days that have a published entry; both start off and show nothing while the map is not shared. Requires `journey:share`. |
| `delete_journey_share_link` | Revoke the public share link for a journey. Requires `journey:share`. |
| `list_journey_recorded_days` | The days of recorded route a journey keeps: zone, distance, pieces, gaps, modes, whether the day was still running, and whose recording it is, without the geometry. Readable without a Dawarich connection. |
| `delete_journey_recorded_day` | Drop the recorded route a journey keeps for one day. Entries and texts stay, and Dawarich keeps its own recording. Needs edit access. |
| `list_journey_recorded_days` | The days of recorded route a journey keeps, from Dawarich or from a GPX file: zone, distance, pieces, gaps, modes, whether the day was still running, and whose recording it is, without the geometry. Readable without a Dawarich connection. |
| `import_journey_gpx_days` | Read the recorded route of a GPX file into a journey as recorded days, one per local day the file covers, cut in the zone of where it was recorded (or one fixed zone) and drawn on the journey map also on days without an entry. Reading the same file again replaces only its GPX days; days taken over from Dawarich stay. Needs edit access, no Dawarich. |
| `delete_journey_recorded_day` | Drop the recorded route a journey keeps for one day from one source (Dawarich unless `source` is `gpx`). The other source's day, the entries and the texts stay, and Dawarich keeps its own recording. Needs edit access. |
| `get_book` | The journey's photo book from the Studio, without its document: version, title, page format and every page with its id, role, photos and first words. Page and element ids for the tools below come from here. Any member may read it. |
| `describe_book_page` | One page of the book in words: every element with its id, frame in millimetres and photo or text, then the findings (overlaps, content in the fold or past the trim, empty frames, low print resolution, words past their frame) and whether the page reads as designed: a flat cover, a page whose largest words do not lead, colours or typefaces outside the book's theme. `edit_book_page` answers with the same art checks for the pages it changed. |
| `list_book_layouts` | The layouts a page can take: templates for double spreads and single pages, the decorated templates (whole designed pages, each with its style, tags, photo frames and the roles its words go into), photo grids, and the book's own saved layouts, with what each does to what is on the page. |