diff --git a/server/src/db/repositories/JourneyRecordedDays.repository.ts b/server/src/db/repositories/JourneyRecordedDays.repository.ts index 94e1a0cef..d48e24505 100644 --- a/server/src/db/repositories/JourneyRecordedDays.repository.ts +++ b/server/src/db/repositories/JourneyRecordedDays.repository.ts @@ -67,9 +67,13 @@ export class JourneyRecordedDaysRepository extends TrekRepository { - 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 { + 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 diff --git a/server/src/nest/journey-recordings/journey-gpx-days.helpers.ts b/server/src/nest/journey-recordings/journey-gpx-days.helpers.ts new file mode 100644 index 000000000..058386dc6 --- /dev/null +++ b/server/src/nest/journey-recordings/journey-gpx-days.helpers.ts @@ -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(); + 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(); + const offsets = new Map(); + 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; + }; +} diff --git a/server/src/nest/journey-recordings/journey-gpx-import.service.ts b/server/src/nest/journey-recordings/journey-gpx-import.service.ts new file mode 100644 index 000000000..f3782e54e --- /dev/null +++ b/server/src/nest/journey-recordings/journey-gpx-import.service.ts @@ -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 { + 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 } }); +} diff --git a/server/src/nest/journey-recordings/journey-recordings.controller.ts b/server/src/nest/journey-recordings/journey-recordings.controller.ts index b35f871af..95f7ae101 100644 --- a/server/src/nest/journey-recordings/journey-recordings.controller.ts +++ b/server/src/nest/journey-recordings/journey-recordings.controller.ts @@ -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 }; } } diff --git a/server/src/nest/journey-recordings/journey-recordings.dto.ts b/server/src/nest/journey-recordings/journey-recordings.dto.ts index a6312581f..41dfae70f 100644 --- a/server/src/nest/journey-recordings/journey-recordings.dto.ts +++ b/server/src/nest/journey-recordings/journey-recordings.dto.ts @@ -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) {} diff --git a/server/src/nest/journey-recordings/journey-recordings.mcp.ts b/server/src/nest/journey-recordings/journey-recordings.mcp.ts index e0c9ad45f..30971b873 100644 --- a/server/src/nest/journey-recordings/journey-recordings.mcp.ts +++ b/server/src/nest/journey-recordings/journey-recordings.mcp.ts @@ -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 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 }); } } diff --git a/server/src/nest/journey-recordings/journey-recordings.module.ts b/server/src/nest/journey-recordings/journey-recordings.module.ts index 96b500904..f907be863 100644 --- a/server/src/nest/journey-recordings/journey-recordings.module.ts +++ b/server/src/nest/journey-recordings/journey-recordings.module.ts @@ -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 {} diff --git a/server/src/nest/journey-recordings/journey-recordings.service.ts b/server/src/nest/journey-recordings/journey-recordings.service.ts index 48c7c4533..f474a627b 100644 --- a/server/src/nest/journey-recordings/journey-recordings.service.ts +++ b/server/src/nest/journey-recordings/journey-recordings.service.ts @@ -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 { + /** + * 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 { 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); } diff --git a/server/src/nest/journey/journey-map.service.ts b/server/src/nest/journey/journey-map.service.ts index 080aa2c3b..df8273d36 100644 --- a/server/src/nest/journey/journey-map.service.ts +++ b/server/src/nest/journey/journey-map.service.ts @@ -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 { 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 { 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, + })); } } diff --git a/server/src/nest/journey/journey-recorded-days.service.ts b/server/src/nest/journey/journey-recorded-days.service.ts index 4795406aa..5c71c6777 100644 --- a/server/src/nest/journey/journey-recorded-days.service.ts +++ b/server/src/nest/journey/journey-recorded-days.service.ts @@ -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 { - const row = await this.days.findDay(journeyId, date, SOURCE); + async find( + journeyId: number, + date: string, + source: JourneyRecordingSource = DEFAULT_SOURCE, + ): Promise { + 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 { - 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 { - 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 { + 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 { + 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 }, diff --git a/server/src/nest/place-import/place-import.service.ts b/server/src/nest/place-import/place-import.service.ts index 237e69bd7..fc382afaa 100644 --- a/server/src/nest/place-import/place-import.service.ts +++ b/server/src/nest/place-import/place-import.service.ts @@ -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); diff --git a/server/src/nest/place-import/place-import.types.ts b/server/src/nest/place-import/place-import.types.ts index 69fa7deff..5af51b234 100644 --- a/server/src/nest/place-import/place-import.types.ts +++ b/server/src/nest/place-import/place-import.types.ts @@ -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; diff --git a/server/src/nest/place-import/providers/gpx.provider.ts b/server/src/nest/place-import/providers/gpx.provider.ts index a7fa22150..7fa432c18 100644 --- a/server/src/nest/place-import/providers/gpx.provider.ts +++ b/server/src/nest/place-import/providers/gpx.provider.ts @@ -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 `