mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
feat(tours): download a saved tour as a GPX file (PR1-06A)
A saved tour can be handed over as a GPX file on purpose: its whole saved line as one track with the heights it has and none it lacks, its name, description and link, and the activity in <type>. The file is named after the tour. A tour without a line of two points is refused with 422 rather than written as a file that imports as nothing; the export changes nothing. GET /api/trips/:tripId/tours/:placeId/export.gpx, readable by anyone who sees the trip, and the MCP tool export_tour_gpx with the same rules. The tour detail gets a "GPX" action beside the navigation, the planner head a download button that waits while the tour has unsaved changes. The tours rail head now uses the same plain icon buttons as the editor.
This commit is contained in:
@@ -12,7 +12,7 @@ import type {
|
||||
import { CollectionGpxProvider, type ExportedCollectionFile } from './providers/collection-gpx.provider';
|
||||
import { GoogleDirectionsProvider } from './providers/google-directions.provider';
|
||||
import { GoogleListProvider } from './providers/google-list.provider';
|
||||
import { GpxProvider, type GpxExportInput, type GpxExportOptions } from './providers/gpx.provider';
|
||||
import { GpxProvider, type GpxExportInput, type GpxExportOptions, type GpxTourExport } from './providers/gpx.provider';
|
||||
import { KmlProvider } from './providers/kml.provider';
|
||||
import { NaverListProvider } from './providers/naver-list.provider';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
@@ -21,7 +21,13 @@ import type { CollectionGpxExport, CollectionGpxReadResult } from '@trek/shared'
|
||||
// The directions-link reading is also what the road trip planner reads a
|
||||
// shared route with, and what the import routes dispatch on.
|
||||
export { isDirectionsUrl, parseDirectionsUrl, MAX_DIR_WAYPOINTS } from './directions-url.helpers';
|
||||
export type { GpxExportDay, GpxExportInput, GpxExportOptions, GpxExportPlace } from './providers/gpx.provider';
|
||||
export type {
|
||||
GpxExportDay,
|
||||
GpxExportInput,
|
||||
GpxExportOptions,
|
||||
GpxExportPlace,
|
||||
GpxTourExport,
|
||||
} from './providers/gpx.provider';
|
||||
export type { ExportedCollectionFile } from './providers/collection-gpx.provider';
|
||||
|
||||
/** Places a name, or says nobody can. */
|
||||
@@ -64,6 +70,15 @@ export class PlaceImportService {
|
||||
return this.gpx.filename(tripTitle);
|
||||
}
|
||||
|
||||
/** One tour as a GPX document (PR1-06A), or null when it has no line to write. */
|
||||
writeTourGpx(tour: GpxTourExport): string | null {
|
||||
return this.gpx.writeTour(tour);
|
||||
}
|
||||
|
||||
tourGpxFilename(tourName: string): string {
|
||||
return this.gpx.tourFilename(tourName);
|
||||
}
|
||||
|
||||
/** A list file as GPX (#2301). */
|
||||
writeCollectionGpx(file: ExportedCollectionFile): CollectionGpxExport {
|
||||
return this.collectionGpx.write(file);
|
||||
|
||||
@@ -145,11 +145,58 @@ export function buildGpx(input: GpxExportInput, opts: GpxExportOptions = {}): st
|
||||
return writeGpx({ metadata: { name: input.tripTitle }, wpt, rte, trk });
|
||||
}
|
||||
|
||||
/** One tour as the exporter needs it (PR1-06A). */
|
||||
export interface GpxTourExport {
|
||||
name: string;
|
||||
description: string | null;
|
||||
/** The tour's own information link, written as the track's <link>. */
|
||||
website: string | null;
|
||||
/** The activity as GPX names it in <type>, e.g. `hiking`. */
|
||||
activity: string;
|
||||
/** JSON `[[lat, lng]]` or `[[lat, lng, ele]]`, the tour's saved line. */
|
||||
route_geometry: string | null;
|
||||
/** Named stops along the tour, written as waypoints in their order. */
|
||||
stops: Array<{ name: string; lat: number; lng: number }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One tour as a GPX document: its whole saved line as one track, with the
|
||||
* heights it has and none it lacks, and its named stops as waypoints. Null when
|
||||
* the tour has no line of at least two points, so the caller refuses instead
|
||||
* of handing over a file a device would read as nothing.
|
||||
*/
|
||||
export function buildTourGpx(tour: GpxTourExport): string | null {
|
||||
const geometry = parseGeometry(tour.route_geometry);
|
||||
if (geometry.length < 2) return null;
|
||||
const desc = tour.description?.trim() || undefined;
|
||||
const link = tour.website ? { '@_href': tour.website } : undefined;
|
||||
return writeGpx({
|
||||
metadata: { name: tour.name, ...(desc ? { desc } : {}), ...(link ? { link } : {}) },
|
||||
wpt: tour.stops.map((stop) => ({ '@_lat': coord(stop.lat), '@_lon': coord(stop.lng), name: stop.name })),
|
||||
trk: [
|
||||
{
|
||||
name: tour.name,
|
||||
desc,
|
||||
link,
|
||||
type: tour.activity,
|
||||
trkseg: {
|
||||
trkpt: geometry.map((p) => ({
|
||||
'@_lat': coord(p.lat),
|
||||
'@_lon': coord(p.lng),
|
||||
...(p.ele != null ? { ele: coord(p.ele) } : {}),
|
||||
})),
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
/** Filenames land on the receiving filesystem, so its reserved characters are
|
||||
* folded away rather than escaped. Header safety is contentDisposition()'s
|
||||
* job since #2165, which is why the title's own script survives here —
|
||||
* 沖縄 stays 沖縄 instead of being mangled into underscores. */
|
||||
export function gpxFilename(tripTitle: string): string {
|
||||
* 沖縄 stays 沖縄 instead of being mangled into underscores. `fallback`
|
||||
* names a file whose title folds away to nothing. */
|
||||
export function gpxFilename(tripTitle: string, fallback = 'trip'): string {
|
||||
const base = tripTitle
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/[\x00-\x1f\x7f"\\/:*?<>|]+/g, ' ')
|
||||
@@ -158,7 +205,7 @@ export function gpxFilename(tripTitle: string): string {
|
||||
.replaceAll(' ', '-');
|
||||
// Codepoints, not UTF-16 units: slice() would cut an emoji in half and the
|
||||
// lone surrogate is exactly what URI-encoding chokes on.
|
||||
return `${[...base].slice(0, 60).join('') || 'trip'}.gpx`;
|
||||
return `${[...base].slice(0, 60).join('') || fallback}.gpx`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,4 +321,12 @@ export class GpxProvider {
|
||||
filename(tripTitle: string): string {
|
||||
return gpxFilename(tripTitle);
|
||||
}
|
||||
|
||||
writeTour(tour: GpxTourExport): string | null {
|
||||
return buildTourGpx(tour);
|
||||
}
|
||||
|
||||
tourFilename(tourName: string): string {
|
||||
return gpxFilename(tourName, 'tour');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import { Tours } from '../../db/entities/Tours.entity';
|
||||
import type { PlacesRepository } from '../../db/repositories/Places.repository';
|
||||
import type { ToursRepository } from '../../db/repositories/Tours.repository';
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import { toRowId } from '../common/row-id';
|
||||
import { PlaceImportService } from '../place-import/place-import.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import type { PaddleBoatType } from '@trek/shared';
|
||||
|
||||
/** What GPX calls the activity in a track's <type>; a paddle tour says what it is paddled in. */
|
||||
const PADDLE_ACTIVITY: Record<PaddleBoatType, string> = {
|
||||
kayak: 'kayaking',
|
||||
canoe: 'canoeing',
|
||||
sup: 'stand_up_paddling',
|
||||
other: 'paddling',
|
||||
};
|
||||
|
||||
export function gpxActivityOf(type: string, boat: string | null): string {
|
||||
if (type === 'kayak') return PADDLE_ACTIVITY[(boat ?? 'other') as PaddleBoatType] ?? PADDLE_ACTIVITY.other;
|
||||
return type === 'hike' ? 'hiking' : type;
|
||||
}
|
||||
|
||||
/**
|
||||
* PR1-06A: one saved tour as a GPX file, its whole saved line with the heights
|
||||
* it has. A read: nothing about the tour, its days or where it came from
|
||||
* changes, and a tour without a line of its own is refused rather than written
|
||||
* as a file that imports as nothing.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TourGpxExportService {
|
||||
constructor(
|
||||
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
|
||||
@InjectRepository(Places) private readonly placesRepo: PlacesRepository,
|
||||
private readonly placeImport: PlaceImportService,
|
||||
) {}
|
||||
|
||||
async export(tripId: string, placeId: string): Promise<{ gpx: string; filename: string }> {
|
||||
const tid = toRowId(tripId);
|
||||
const pid = toRowId(placeId);
|
||||
const tour = tid !== null && pid !== null ? await this.toursRepo.findInTrip(tid, pid) : undefined;
|
||||
const place = tour && tid !== null ? await this.placesRepo.findInTrip(tour.place_id, tid) : undefined;
|
||||
if (!tour || !place) throw new NotFoundException('Tour not found');
|
||||
|
||||
const gpx = this.placeImport.writeTourGpx({
|
||||
name: tour.name,
|
||||
description: tour.description ?? null,
|
||||
website: tour.website ?? null,
|
||||
activity: gpxActivityOf(tour.tour_type, tour.boat_type),
|
||||
route_geometry: place.route_geometry ?? null,
|
||||
stops: [],
|
||||
});
|
||||
if (!gpx) {
|
||||
throw new DomainError(422, 'This tour has no route to export', { code: 'tour_without_route' });
|
||||
}
|
||||
return { gpx, filename: this.placeImport.tourGpxFilename(tour.name) };
|
||||
}
|
||||
}
|
||||
@@ -4,17 +4,21 @@ import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { contentDisposition } from '../common/content-disposition';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
|
||||
import { TourCopyDto, TourCreateDto } from './dto/tour-create.dto';
|
||||
import { TourObstacleReviewsDto } from './dto/tour-obstacle-reviews.dto';
|
||||
import { TourPaddlePlanDto } from './dto/tour-paddle-plan.dto';
|
||||
import { TourGpxExportService } from './tour-gpx-export.service';
|
||||
import { TourObstacleReviewsService } from './tour-obstacle-reviews.service';
|
||||
import { TourPaddlePlanService } from './tour-paddle-plan.service';
|
||||
import { ToursService } from './tours.service';
|
||||
import { Body, Controller, Get, Headers, HttpCode, Param, Post, Put, UseGuards } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Headers, HttpCode, Param, Post, Put, Res, UseGuards } from '@nestjs/common';
|
||||
import { tourCreateResponseSchema, tourDetailResponseSchema } from '@trek/shared';
|
||||
|
||||
import type { Response } from 'express';
|
||||
|
||||
/**
|
||||
* /api/trips/:tripId/tours: the Tours facet, read and route edits.
|
||||
* TripAccessGuard resolves
|
||||
@@ -30,6 +34,7 @@ export class ToursController {
|
||||
private readonly tours: ToursService,
|
||||
private readonly paddlePlans: TourPaddlePlanService,
|
||||
private readonly obstacleReviews: TourObstacleReviewsService,
|
||||
private readonly gpxExport: TourGpxExportService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@@ -37,6 +42,19 @@ export class ToursController {
|
||||
return { tours: await this.tours.listTours(tripId) };
|
||||
}
|
||||
|
||||
/**
|
||||
* PR1-06A: the saved tour as a GPX file, its whole line with the heights it
|
||||
* has. A read, so seeing the trip is enough; 422 when the tour has no line.
|
||||
* response-contract-exempt: a file download written through @Res(), not a JSON body.
|
||||
*/
|
||||
@Get(':placeId/export.gpx')
|
||||
async exportGpx(@Param('tripId') tripId: string, @Param('placeId') placeId: string, @Res() res: Response) {
|
||||
const { gpx, filename } = await this.gpxExport.export(tripId, placeId);
|
||||
res.setHeader('Content-Type', 'application/gpx+xml; charset=utf-8');
|
||||
res.setHeader('Content-Disposition', contentDisposition(filename, 'attachment'));
|
||||
res.send(gpx);
|
||||
}
|
||||
|
||||
@Get(':placeId')
|
||||
async detail(@Param('tripId') tripId: string, @Param('placeId') placeId: string) {
|
||||
return await this.tours.getTour(tripId, placeId);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type M
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { TourGpxExportService } from './tour-gpx-export.service';
|
||||
import { ToursService } from './tours.service';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { idSchema, type TourListItem } from '@trek/shared';
|
||||
@@ -30,6 +31,7 @@ export class ToursMcp {
|
||||
constructor(
|
||||
private readonly tours: ToursService,
|
||||
private readonly access: TripAccessService,
|
||||
private readonly gpxExport: TourGpxExportService,
|
||||
// Read by the addon gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
@@ -95,4 +97,24 @@ export class ToursMcp {
|
||||
const onDay = tours.filter((tour) => (days.get(tour.place_id) ?? []).some((day) => day.day_id === dayId));
|
||||
return ok({ tours: onDay.map((tour) => withDays(tour, days)) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'export_tour_gpx',
|
||||
description:
|
||||
'Export one saved tour of a trip as a GPX 1.1 document: its whole saved line as one track, with the heights it carries and none it lacks. Returns the GPX text and a file name. A tour without a line of at least two points cannot be exported. Nothing about the tour changes.',
|
||||
inputSchema: { tripId: idSchema, placeId: idSchema.describe('The place id of the tour, as list_tours gives it') },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
})
|
||||
async exportTourGpx({ tripId, placeId }: { tripId: number; placeId: number }, ctx: McpContext) {
|
||||
// A read, like the REST route: seeing the trip is enough.
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
try {
|
||||
return ok(await this.gpxExport.export(String(tripId), String(placeId)));
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof NotFoundException) return errorResult('Tour not found.');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { PlaceImportModule } from '../place-import/place-import.module';
|
||||
import { PlacesModule } from '../places/places.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { WandererModule } from '../wanderer/wanderer.module';
|
||||
import { TourGpxExportService } from './tour-gpx-export.service';
|
||||
import { TourObstacleReviewsService } from './tour-obstacle-reviews.service';
|
||||
import { PaddleCheckCache } from './tour-paddle-check.cache';
|
||||
import { TourPaddleCheckService } from './tour-paddle-check.service';
|
||||
@@ -52,6 +53,7 @@ import { Module } from '@nestjs/common';
|
||||
PaddleCheckCache,
|
||||
TourPaddleCheckService,
|
||||
TourObstacleReviewsService,
|
||||
TourGpxExportService,
|
||||
ToursWandererService,
|
||||
ToursMcp,
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user