mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
feat(journey): keep the route recorded on a journey day from Dawarich, previewed first, with its gaps
A day header in the journey timeline now carries the Dawarich mark for an editor whose Dawarich answers (dimmed with the reason while offline). It opens a dialog that names the journey and the day and reads that one local day from the caller's own connection: a sketch of the route, distance, first and last time, pieces, gaps without recording, modes and whether tracks or thinned points answered. The day is cut in the zone Dawarich records in where its answer shows one, else in this device's, and a picker cuts it in any other. Nothing is kept before "Keep route". On a phone the same sheet opens from the journey's More options for the day of the card shown. What is kept is the preview that was seen: the save reads the day again and refuses with recording_changed when its hash moved, and the dialog shows the new version. The same day taken over twice keeps one version and announces nothing; a different version is replaced only on "Replace", never touching an entry or text. A failed read throws before any write, so the kept version stays. Gaps stay gaps: points are split where silence ends elsewhere, and no day is joined to the one before. The dialog says how many other people will see the route; editors may keep their own recording. Kept days show in the day header (distance, whose recording, since when, still running) and on the desktop and phone journey maps in the colour of their day's pins, winning over the live trail of their date, and stay drawn without Dawarich. A trip's GPX track is now drawn dashed as the plan, recorded routes solid. Shared links do not show recorded days. Remove route asks first and works without a connection. Server: migration 046160 adds journey_recorded_days (one row per journey, local day and source, segments as JSON, zone, window, fetch time, hash, importer kept past their account). The journey domain owns the rows through JourneyRecordedDaysService; the new journey-recordings domain takes a day over through DawarichTracksService.fetchDay, which reads past the cache, asks a window wide enough for every zone and refuses with DomainErrors. REST under /api/journeys/:id/recordings (list, preview, PUT and DELETE /:date) with @trek/shared contracts, and MCP list_journey_recorded_days, preview_journey_recorded_day, save_journey_recorded_day and delete_journey_recorded_day on the same service and access. A new user event journey:recording:updated keeps every open map current. JourneyTrack gains an optional kind. All 27 locales carry the strings; the Journey and Dawarich wiki pages and the MCP tool list say what it does.
This commit is contained in:
@@ -1,19 +1,38 @@
|
||||
import { Trips } from '../../db/entities/Trips.entity';
|
||||
import { TripsRepository } from '../../db/repositories/Trips.repository';
|
||||
import { DawarichClient, type DawarichCreds } from './dawarich.client';
|
||||
import { bucketPointsByDay, bucketTracksByDay, countPoints, offsetMinutesOf } from './dawarich.helpers';
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import { DawarichClient, DawarichError, type DawarichCreds } from './dawarich.client';
|
||||
import { RECORDING_GAP, bucketPointsByDay, bucketTracksByDay, countPoints, offsetMinutesOf } from './dawarich.helpers';
|
||||
import { DawarichService } from './dawarich.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DAWARICH_TRACK_POINTS_PER_DAY, type DawarichTrack } from '@trek/shared';
|
||||
import { DAWARICH_TRACK_POINTS_PER_DAY, type DawarichTrack, type DawarichTrackSegment } from '@trek/shared';
|
||||
|
||||
/** One local day of recording, read for a journey to keep (JRN-01). */
|
||||
export interface RecordedDayFetch {
|
||||
segments: DawarichTrackSegment[];
|
||||
sourceKind: 'tracks' | 'points';
|
||||
/** The zone the day was cut in, minutes east of UTC. */
|
||||
utcOffsetMinutes: number;
|
||||
offsetSource: 'source' | 'chosen';
|
||||
/** The zone Dawarich records in, where its answer shows one. */
|
||||
sourceOffsetMinutes: number | null;
|
||||
window: { from: string; to: string };
|
||||
fetchedAt: string;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
const HOUR_MS = 3_600_000;
|
||||
|
||||
/**
|
||||
* The recorded route for a window, fetched on demand and never stored.
|
||||
* The recorded route for a window, fetched on demand and never stored here.
|
||||
*
|
||||
* That is the point of the whole feature and the one rule it must not break:
|
||||
* Dawarich owns the location archive. TREK draws the part of it somebody is
|
||||
* looking at right now and forgets it again. There is no table here, no
|
||||
* `route_geometry` written to a place, no background import.
|
||||
* `route_geometry` written to a place, no background import. The one copy is
|
||||
* a day a traveller takes over into a journey on purpose (`fetchDay`, JRN-01),
|
||||
* and the journey keeps that, not this service.
|
||||
*
|
||||
* What there is instead is a short in-memory cache, because "update the line
|
||||
* while the map is open" and "ask an instance for a month of GPS every few
|
||||
@@ -161,6 +180,65 @@ export class DawarichTracksService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One local day of recording, read fresh past the cache: what a journey keeps
|
||||
* has to be what the instance says now, not what the map saw a minute ago.
|
||||
*
|
||||
* The day is cut in Dawarich's own zone when `useSourceOffset` asks for it and
|
||||
* the answer reveals one (track times carry it, points do not), else in the
|
||||
* zone given. The request spans every zone there is around the date, so the
|
||||
* day is the same day whichever zone cuts it. A gap in the recording stays a
|
||||
* gap. Refuses with a DomainError the controller and the MCP tool pass on:
|
||||
* 409 `not_connected`, or the instance's own reason.
|
||||
*/
|
||||
async fetchDay(
|
||||
userId: number,
|
||||
date: string,
|
||||
zone: { offsetMinutes: number; useSourceOffset: boolean },
|
||||
): Promise<RecordedDayFetch> {
|
||||
const creds = await this.dawarich.getCredentials(userId);
|
||||
if (!creds) throw new DomainError(409, 'Dawarich is not connected', { details: { code: 'not_connected' } });
|
||||
|
||||
const dayStart = Date.parse(`${date}T00:00:00Z`);
|
||||
const from = new Date(dayStart - 14 * HOUR_MS);
|
||||
const to = new Date(dayStart + 36 * HOUR_MS);
|
||||
const capabilities = await this.dawarich.getCapabilities(userId);
|
||||
|
||||
if (capabilities?.tracks !== false) {
|
||||
try {
|
||||
const { features, truncated } = await this.client.listTracks(creds, from, to);
|
||||
const sourceOffset = sourceOffsetOf(features[0]?.properties?.start_at);
|
||||
const offset = zoneOf(zone, sourceOffset);
|
||||
const day = bucketTracksByDay(features, {
|
||||
maxPointsPerDay: DAWARICH_TRACK_POINTS_PER_DAY,
|
||||
offsetMinutes: offset.minutes,
|
||||
}).find((d) => d.date === date);
|
||||
if (day && day.segments.length > 0) {
|
||||
return recordedDay(date, day.segments, 'tracks', offset, sourceOffset, truncated);
|
||||
}
|
||||
} catch {
|
||||
// Points next, as for the overlay: an instance that cannot serve tracks
|
||||
// can usually still serve what they are built from.
|
||||
}
|
||||
}
|
||||
|
||||
const offset = zoneOf(zone, null);
|
||||
try {
|
||||
const { points, truncated } = await this.client.listPoints(creds, from, to);
|
||||
const day = bucketPointsByDay(points, offset.minutes, {
|
||||
maxPointsPerDay: DAWARICH_TRACK_POINTS_PER_DAY,
|
||||
gaps: RECORDING_GAP,
|
||||
}).find((d) => d.date === date);
|
||||
return recordedDay(date, day?.segments ?? [], 'points', offset, null, truncated);
|
||||
} catch (err) {
|
||||
if (err instanceof DawarichError) {
|
||||
const status = err.code === 'unauthorized' || err.code === 'forbidden' ? 400 : 502;
|
||||
throw new DomainError(status, err.message, { details: { code: err.code } });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private remember(key: string, value: DawarichTrack): void {
|
||||
if (this.cache.size >= DawarichTracksService.MAX_ENTRIES) {
|
||||
const oldest = this.cache.keys().next().value;
|
||||
@@ -177,6 +255,42 @@ export class DawarichTracksService {
|
||||
}
|
||||
}
|
||||
|
||||
/** The zone a Dawarich time names; null when it names none. */
|
||||
function sourceOffsetOf(value: unknown): number | null {
|
||||
if (typeof value !== 'string' || !/(Z|[+-]\d{2}:?\d{2})$/.test(value)) return null;
|
||||
return offsetMinutesOf(value);
|
||||
}
|
||||
|
||||
function zoneOf(
|
||||
zone: { offsetMinutes: number; useSourceOffset: boolean },
|
||||
sourceOffset: number | null,
|
||||
): { minutes: number; source: 'source' | 'chosen' } {
|
||||
return zone.useSourceOffset && sourceOffset !== null
|
||||
? { minutes: sourceOffset, source: 'source' }
|
||||
: { minutes: zone.offsetMinutes, source: 'chosen' };
|
||||
}
|
||||
|
||||
function recordedDay(
|
||||
date: string,
|
||||
segments: DawarichTrackSegment[],
|
||||
sourceKind: 'tracks' | 'points',
|
||||
offset: { minutes: number; source: 'source' | 'chosen' },
|
||||
sourceOffsetMinutes: number | null,
|
||||
truncated: boolean,
|
||||
): RecordedDayFetch {
|
||||
const from = Date.parse(`${date}T00:00:00Z`) - offset.minutes * 60_000;
|
||||
return {
|
||||
segments,
|
||||
sourceKind,
|
||||
utcOffsetMinutes: offset.minutes,
|
||||
offsetSource: offset.source,
|
||||
sourceOffsetMinutes,
|
||||
window: { from: new Date(from).toISOString(), to: new Date(from + 24 * HOUR_MS).toISOString() },
|
||||
fetchedAt: new Date().toISOString(),
|
||||
truncated,
|
||||
};
|
||||
}
|
||||
|
||||
function emptyTrack(): DawarichTrack {
|
||||
return {
|
||||
days: [],
|
||||
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
DawarichVisitRaw,
|
||||
DawarichVisitedCountry,
|
||||
} from './dawarich.client';
|
||||
import type { DawarichTrackDay, DawarichTrackSegment } from '@trek/shared';
|
||||
import { RECORDING_GAP_METERS, type DawarichTrackDay, type DawarichTrackSegment } from '@trek/shared';
|
||||
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
@@ -41,9 +41,9 @@ export function offsetMinutesOf(iso: string): number {
|
||||
return sign * (Number(match[2]) * 60 + Number(match[3]));
|
||||
}
|
||||
|
||||
/** Local wall-clock milliseconds — the instant shifted into the string's own offset. */
|
||||
function localMs(iso: string): number {
|
||||
return Date.parse(iso) + offsetMinutesOf(iso) * 60_000;
|
||||
/** Local wall-clock milliseconds — the instant shifted into the string's own offset, or into `offset` when given. */
|
||||
function localMs(iso: string, offset?: number): number {
|
||||
return Date.parse(iso) + (offset ?? offsetMinutesOf(iso)) * 60_000;
|
||||
}
|
||||
|
||||
/** `YYYY-MM-DD` of a local wall-clock millisecond value. */
|
||||
@@ -307,10 +307,61 @@ interface BucketOptions {
|
||||
maxPointsPerDay: number;
|
||||
/** Simplification tolerance in degrees. ~5e-5 is roughly five metres. */
|
||||
epsilon: number;
|
||||
/**
|
||||
* Cut a day where the recording has a gap instead of drawing across it, and
|
||||
* never join a day to the one before. Off for the live overlay, which has
|
||||
* always joined its points up; on for a day a journey keeps (JRN-01).
|
||||
*/
|
||||
gaps?: GapRule;
|
||||
/**
|
||||
* Cut tracks at midnight in this zone (minutes east of UTC) rather than in
|
||||
* the one their own times carry.
|
||||
*/
|
||||
offsetMinutes?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_BUCKET: BucketOptions = { maxPointsPerDay: 600, epsilon: 0.00005 };
|
||||
|
||||
/** When two recorded points are too far apart, in time and in space, to have been one movement. */
|
||||
interface GapRule {
|
||||
seconds: number;
|
||||
meters: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Silence on its own is no gap: a phone that records only when it moves sends
|
||||
* nothing for an hour at a café table and then goes on from the same spot.
|
||||
* Silence that ends somewhere else is one, and the line between the two ends
|
||||
* would be a way nobody can say was travelled.
|
||||
*/
|
||||
export const RECORDING_GAP: GapRule = { seconds: 15 * 60, meters: RECORDING_GAP_METERS };
|
||||
|
||||
interface TimedPoint {
|
||||
lat: number;
|
||||
lng: number;
|
||||
ts: number;
|
||||
}
|
||||
|
||||
/** Points in time order → the runs between the gaps of the recording. */
|
||||
export function splitAtGaps<T extends TimedPoint>(points: T[], rule: GapRule): T[][] {
|
||||
const runs: T[][] = [];
|
||||
let run: T[] = [];
|
||||
for (const point of points) {
|
||||
const last = run[run.length - 1];
|
||||
if (
|
||||
last &&
|
||||
point.ts - last.ts > rule.seconds &&
|
||||
distanceMeters(last.lat, last.lng, point.lat, point.lng) > rule.meters
|
||||
) {
|
||||
runs.push(run);
|
||||
run = [];
|
||||
}
|
||||
run.push(point);
|
||||
}
|
||||
if (run.length > 0) runs.push(run);
|
||||
return runs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recorded points → one entry per local calendar day.
|
||||
*
|
||||
@@ -324,8 +375,8 @@ export function bucketPointsByDay(
|
||||
offsetMinutes: number,
|
||||
options: Partial<BucketOptions> = {},
|
||||
): DawarichTrackDay[] {
|
||||
const { maxPointsPerDay, epsilon } = { ...DEFAULT_BUCKET, ...options };
|
||||
const byDay = new Map<string, Array<{ lat: number; lng: number; ts: number }>>();
|
||||
const { maxPointsPerDay, epsilon, gaps } = { ...DEFAULT_BUCKET, ...options };
|
||||
const byDay = new Map<string, TimedPoint[]>();
|
||||
|
||||
for (const point of points) {
|
||||
const lat = toNumber(point.latitude);
|
||||
@@ -346,6 +397,11 @@ export function bucketPointsByDay(
|
||||
for (let d = 0; d < dates.length; d++) {
|
||||
const date = dates[d]!;
|
||||
const own = byDay.get(date)!.sort((a, b) => a.ts - b.ts);
|
||||
if (gaps) {
|
||||
const segments = runsAsSegments(splitAtGaps(own, gaps), own.length, { maxPointsPerDay, epsilon });
|
||||
if (segments.length > 0) days.push({ date, segments });
|
||||
continue;
|
||||
}
|
||||
// Stitch the previous day's last point on, so consecutive days join up
|
||||
// rather than showing a jump the traveller never made.
|
||||
const previous = d > 0 ? byDay.get(dates[d - 1]!) : undefined;
|
||||
@@ -377,6 +433,40 @@ export function bucketPointsByDay(
|
||||
return days;
|
||||
}
|
||||
|
||||
/**
|
||||
* The runs of one day as drawable segments, the day's point budget shared out
|
||||
* by how many points each run brought. A run that thins to a single point is
|
||||
* a fix, not a way, and is left out.
|
||||
*/
|
||||
function runsAsSegments(
|
||||
runs: TimedPoint[][],
|
||||
total: number,
|
||||
{ maxPointsPerDay, epsilon }: Pick<BucketOptions, 'maxPointsPerDay' | 'epsilon'>,
|
||||
): DawarichTrackSegment[] {
|
||||
const segments: DawarichTrackSegment[] = [];
|
||||
for (const run of runs) {
|
||||
const budget = Math.max(2, Math.floor((maxPointsPerDay * run.length) / total));
|
||||
const line = capPoints(
|
||||
simplify(
|
||||
run.map((p): [number, number] => [p.lat, p.lng]),
|
||||
epsilon,
|
||||
),
|
||||
budget,
|
||||
);
|
||||
const first = run[0];
|
||||
const last = run[run.length - 1];
|
||||
if (line.length < 2 || !first || !last) continue;
|
||||
segments.push({
|
||||
points: line,
|
||||
mode: null,
|
||||
startedAt: new Date(first.ts * 1000).toISOString(),
|
||||
endedAt: new Date(last.ts * 1000).toISOString(),
|
||||
distanceMeters: null,
|
||||
});
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dawarich tracks → one entry per local calendar day.
|
||||
*
|
||||
@@ -391,7 +481,7 @@ export function bucketTracksByDay(
|
||||
features: DawarichTrackFeature[],
|
||||
options: Partial<BucketOptions> = {},
|
||||
): DawarichTrackDay[] {
|
||||
const { maxPointsPerDay, epsilon } = { ...DEFAULT_BUCKET, ...options };
|
||||
const { maxPointsPerDay, epsilon, offsetMinutes } = { ...DEFAULT_BUCKET, ...options };
|
||||
const byDay = new Map<string, DawarichTrackSegment[]>();
|
||||
|
||||
for (const feature of features) {
|
||||
@@ -406,7 +496,7 @@ export function bucketTracksByDay(
|
||||
const mode = typeof props?.dominant_mode === 'string' ? props.dominant_mode : null;
|
||||
const distance = toNumber(props?.distance);
|
||||
|
||||
for (const piece of splitAtLocalMidnight(points, startedAt, endedAt)) {
|
||||
for (const piece of splitAtLocalMidnight(points, startedAt, endedAt, offsetMinutes)) {
|
||||
const line = capPoints(simplify(piece.points, epsilon), maxPointsPerDay);
|
||||
if (line.length < 2) continue;
|
||||
const segment: DawarichTrackSegment = {
|
||||
@@ -442,9 +532,14 @@ interface TrackPiece {
|
||||
whole: boolean;
|
||||
}
|
||||
|
||||
function splitAtLocalMidnight(points: Array<[number, number]>, startedAt: string, endedAt: string): TrackPiece[] {
|
||||
const startLocal = localMs(startedAt);
|
||||
const endLocal = localMs(endedAt);
|
||||
function splitAtLocalMidnight(
|
||||
points: Array<[number, number]>,
|
||||
startedAt: string,
|
||||
endedAt: string,
|
||||
zone?: number,
|
||||
): TrackPiece[] {
|
||||
const startLocal = localMs(startedAt, zone);
|
||||
const endLocal = localMs(endedAt, zone);
|
||||
const startDate = dateOfLocalMs(startLocal);
|
||||
const endDate = dateOfLocalMs(endLocal);
|
||||
|
||||
@@ -468,7 +563,7 @@ function splitAtLocalMidnight(points: Array<[number, number]>, startedAt: string
|
||||
return [{ date: startDate, points, startedAt, endedAt, whole: true }];
|
||||
}
|
||||
|
||||
const offset = offsetMinutesOf(startedAt) * 60_000;
|
||||
const offset = (zone ?? offsetMinutesOf(startedAt)) * 60_000;
|
||||
const span = endLocal - startLocal;
|
||||
const pieces: TrackPiece[] = [];
|
||||
let cutIndex = 0;
|
||||
|
||||
@@ -202,7 +202,7 @@ export class DawarichMcp {
|
||||
@Tool({
|
||||
name: 'get_dawarich_trip_track',
|
||||
description:
|
||||
"Fetch the route actually recorded during a trip, grouped by local day, straight from the caller's Dawarich instance. Each day carries its segments with start and end times and, where Dawarich classified it, how it was travelled. Use it to answer what route someone really took, or how a day's movement compares with what was planned. Nothing is stored in TREK — this is a live read of the recording.",
|
||||
"Fetch the route actually recorded during a trip, grouped by local day, straight from the caller's Dawarich instance. Each day carries its segments with start and end times and, where Dawarich classified it, how it was travelled. Use it to answer what route someone really took, or how a day's movement compares with what was planned. This is a live read of the recording and stores nothing; a day is kept in a journey only when the traveller confirms it through save_journey_recorded_day.",
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
from: z
|
||||
|
||||
Reference in New Issue
Block a user