mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
add Google Maps route import and plugin corridor search
This commit is contained in:
@@ -2645,21 +2645,23 @@ export class MapsService {
|
||||
lat: string,
|
||||
lng: string,
|
||||
lang?: string,
|
||||
opts?: { lane?: GeoLane; timeoutMs?: number },
|
||||
opts?: { lane?: GeoLane; timeoutMs?: number; locality?: boolean },
|
||||
): Promise<{ name: string | null; address: string | null }> {
|
||||
const params = new URLSearchParams({
|
||||
lat,
|
||||
lon: lng,
|
||||
format: 'json',
|
||||
addressdetails: '1',
|
||||
zoom: '18',
|
||||
zoom: opts?.locality ? '10' : '18',
|
||||
'accept-language': toApiLang(lang),
|
||||
});
|
||||
const response = await nominatimFetch('reverse', params, opts);
|
||||
if (!response.ok) return { name: null, address: null };
|
||||
const data = (await response.json()) as { name?: string; display_name?: string; address?: Record<string, string> };
|
||||
const addr = data.address || {};
|
||||
const name = data.name || addr.tourism || addr.amenity || addr.shop || addr.building || addr.road || null;
|
||||
const name = opts?.locality
|
||||
? addr.city || addr.town || addr.village || addr.municipality || data.name || null
|
||||
: data.name || addr.tourism || addr.amenity || addr.shop || addr.building || addr.road || null;
|
||||
return { name, address: data.display_name || null };
|
||||
}
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ function fromPath(url: URL): DirWaypoint[] {
|
||||
* Empty when the link is not a route, or holds fewer than two stops — one stop is a
|
||||
* place, and the place search box already takes those.
|
||||
*/
|
||||
export function parseDirectionsUrl(raw: string): DirWaypoint[] {
|
||||
export function parseDirectionsUrl(raw: string, limit = MAX_DIR_WAYPOINTS): DirWaypoint[] {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
@@ -142,5 +142,5 @@ export function parseDirectionsUrl(raw: string): DirWaypoint[] {
|
||||
}
|
||||
const fromParams = fromQuery(url);
|
||||
const found = fromParams.length ? fromParams : fromPath(url);
|
||||
return found.length >= 2 ? found.slice(0, MAX_DIR_WAYPOINTS) : [];
|
||||
return found.length >= 2 ? found.slice(0, limit) : [];
|
||||
}
|
||||
|
||||
@@ -31,6 +31,9 @@ export interface HookSearchRequest {
|
||||
/** The caller's language tag, for providers that return localized names. */
|
||||
lang?: string;
|
||||
near?: { lat: number; lng: number };
|
||||
/** Category search within a Roadtrip search rectangle. Older hosts omit these fields. */
|
||||
category?: string;
|
||||
bounds?: { south: number; west: number; north: number; east: number };
|
||||
}
|
||||
|
||||
/** The waypoint request a route provider is asked to solve. */
|
||||
|
||||
@@ -443,6 +443,9 @@ export interface SearchRequest {
|
||||
lang?: string;
|
||||
/** Where the person is looking, when there is somewhere to bias toward. */
|
||||
near?: { lat: number; lng: number };
|
||||
/** Category search within a Roadtrip search rectangle. Older hosts omit these fields. */
|
||||
category?: string;
|
||||
bounds?: { south: number; west: number; north: number; east: number };
|
||||
}
|
||||
export interface SearchProvider {
|
||||
search(request: SearchRequest, ctx: PluginContext): Promise<SearchResultPlace[]>;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Body, Controller, Headers, HttpCode, Param, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
import type { Request } from 'express';
|
||||
import { googleRouteImportSchema, googleRoutePreviewRequestSchema } from '@trek/shared';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { TripAccessGuard } from '../permissions/trip-access.guard';
|
||||
import { GoogleRouteService } from './google-route.service';
|
||||
|
||||
class PreviewDto extends createZodDto(googleRoutePreviewRequestSchema) {}
|
||||
class ImportDto extends createZodDto(googleRouteImportSchema) {}
|
||||
|
||||
@Controller('api')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')
|
||||
export class GoogleRouteController {
|
||||
constructor(private readonly routes: GoogleRouteService) {}
|
||||
@Post('roadtrip/google-maps-preview')
|
||||
@HttpCode(200)
|
||||
preview(@Body() input: PreviewDto) { return this.routes.preview(input.url); }
|
||||
|
||||
@Post('trips/:tripId/roadtrip/google-maps-import')
|
||||
@HttpCode(200)
|
||||
@UseGuards(TripAccessGuard)
|
||||
import(@Param('tripId') tripId: string, @Body() input: ImportDto,
|
||||
@Req() req: Request & { user: { id: number } }, @Headers('x-socket-id') socketId?: string) {
|
||||
return this.routes.import(Number(tripId), req.user.id, input, socketId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { z } from 'zod';
|
||||
import { googleRouteImportSchema, googleRoutePreviewRequestSchema, type GoogleRouteImport } from '@trek/shared';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { GoogleRouteService } from './google-route.service';
|
||||
|
||||
@McpController()
|
||||
export class GoogleRouteMcp {
|
||||
constructor(private readonly routes: GoogleRouteService, readonly addons: AddonsService) {}
|
||||
@Tool({ name: 'preview_google_maps_route', description: 'Read ordered stops from a Google Maps directions link. No changes are saved. Review geocoded positions and unresolved stops before importing. The exact Google road geometry is not imported.',
|
||||
inputSchema: googleRoutePreviewRequestSchema.shape, annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'trips', mode: 'read' }, when: addonGate(ADDON_IDS.ROADTRIP) })
|
||||
async preview({ url }: { url: string }) { return ok(await this.routes.preview(url)); }
|
||||
|
||||
@Tool({ name: 'import_google_maps_route', description: 'Append reviewed Google Maps stops to an existing trip day in supplied order. Creates places and visits atomically. Requires place and day editing permissions. Existing visits remain. TREK calculates the road geometry; no Google route geometry is preserved.',
|
||||
inputSchema: { tripId: z.number().int().positive(), ...googleRouteImportSchema.shape },
|
||||
access: { group: 'trips', mode: 'write' }, when: addonGate(ADDON_IDS.ROADTRIP) })
|
||||
import(input: GoogleRouteImport & { tripId: number }, ctx: McpContext) { return ok(this.routes.import(input.tripId, ctx.userId, input)); }
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { HttpException, Injectable } from '@nestjs/common';
|
||||
import type { GoogleRouteImport, GoogleRoutePreview } from '@trek/shared';
|
||||
import { MapsService, GOOGLE_SHORT_HOSTS, isGoogleMapsHost } from '../maps/maps.service';
|
||||
import { isDirectionsUrl, parseDirectionsUrl, MAX_DIR_WAYPOINTS } from '../places/maps-dir.helpers';
|
||||
import { safeFetchFollow } from '../../utils/ssrfGuard';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { AssignmentsService } from '../assignments/assignments.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
|
||||
@Injectable()
|
||||
export class GoogleRouteService {
|
||||
constructor(private readonly maps: MapsService, private readonly db: DatabaseService,
|
||||
private readonly places: PlacesService, private readonly assignments: AssignmentsService,
|
||||
private readonly permissions: PermissionsService) {}
|
||||
|
||||
async preview(raw: string): Promise<GoogleRoutePreview> {
|
||||
let url = new URL(raw);
|
||||
if (url.protocol !== 'https:' || url.username || url.password || url.port ||
|
||||
!isGoogleMapsHost(url.hostname) && !GOOGLE_SHORT_HOSTS.includes(url.hostname))
|
||||
throw new HttpException({ error: 'Use a Google Maps directions link.' }, 400);
|
||||
if (GOOGLE_SHORT_HOSTS.includes(url.hostname)) {
|
||||
const reply = await safeFetchFollow(url.href, { signal: AbortSignal.timeout(10000) });
|
||||
url = new URL(reply.url);
|
||||
await reply.body?.cancel();
|
||||
if (!isGoogleMapsHost(url.hostname)) throw new HttpException({ error: 'Use a Google Maps directions link.' }, 400);
|
||||
}
|
||||
if (url.protocol !== 'https:' || !isDirectionsUrl(url.href))
|
||||
throw new HttpException({ error: 'Use a Google Maps directions link.' }, 400);
|
||||
const waypoints = parseDirectionsUrl(url.href, MAX_DIR_WAYPOINTS + 1);
|
||||
if (waypoints.length < 2 || waypoints.length > MAX_DIR_WAYPOINTS)
|
||||
throw new HttpException({ error: 'The link must contain between 2 and 30 readable stops.' }, 400);
|
||||
const stops: GoogleRoutePreview['stops'] = [];
|
||||
for (const waypoint of waypoints) {
|
||||
let name = (waypoint.name || `${waypoint.lat}, ${waypoint.lng}`).slice(0, 200);
|
||||
if (waypoint.lat !== null && waypoint.lng !== null) {
|
||||
if (!waypoint.name) {
|
||||
try {
|
||||
const place = await this.maps.reverseGeocode(String(waypoint.lat), String(waypoint.lng), undefined, { lane: 'background', timeoutMs: 5000, locality: true });
|
||||
name = (place.name || place.address || name).slice(0, 200);
|
||||
} catch { /* Keep the supplied position when its name cannot be resolved. */ }
|
||||
}
|
||||
stops.push({ name, lat: waypoint.lat, lng: waypoint.lng });
|
||||
continue;
|
||||
}
|
||||
let position: { lat: number; lng: number } | null = null;
|
||||
if (!/^(your location|my location|dein standort|mein standort|current location)$/i.test(name)) {
|
||||
try { position = await this.maps.geocodeQuery(name); } catch { position = null; }
|
||||
}
|
||||
if (position && (!Number.isFinite(position.lat) || !Number.isFinite(position.lng) || Math.abs(position.lat) > 90 || Math.abs(position.lng) > 180)) position = null;
|
||||
stops.push({ name, lat: position?.lat ?? null, lng: position?.lng ?? null });
|
||||
}
|
||||
return { stops };
|
||||
}
|
||||
|
||||
import(tripId: number, userId: number, input: GoogleRouteImport, socketId?: string) {
|
||||
const access = this.db.canAccessTrip(tripId, userId);
|
||||
if (!access) throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
const role = this.db.get<{ role: string }>('SELECT role FROM users WHERE id = ?', userId)?.role ?? 'user';
|
||||
if (!['place_edit', 'day_edit'].every(action => this.permissions.checkPermission(action, role, access.user_id, userId, access.user_id !== userId)))
|
||||
throw new HttpException({ error: 'Permission denied' }, 403);
|
||||
if (!this.assignments.dayExists(String(input.dayId), String(tripId))) throw new HttpException({ error: 'Day not found' }, 404);
|
||||
const imported = this.db.transaction(() => input.stops.map(stop => {
|
||||
const place = this.places.create(String(tripId), { ...stop, transport_mode: 'car', duration_minutes: 0 });
|
||||
const assignment = this.assignments.createAssignment(input.dayId, place.id);
|
||||
return { place, assignment };
|
||||
}));
|
||||
for (const { place, assignment } of imported) {
|
||||
this.places.broadcast(String(tripId), 'place:created', { place }, socketId);
|
||||
this.assignments.broadcast(String(tripId), 'assignment:created', { assignment }, socketId);
|
||||
}
|
||||
this.assignments.reconcile(tripId, socketId);
|
||||
return { imported: imported.length };
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { ADDON_IDS } from '../../addons';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, errorResult, type McpContext } from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
import { RoadtripSearchService } from './roadtrip-search.service';
|
||||
import { RoadtripPlanService } from './roadtrip-plan.service';
|
||||
import {
|
||||
roadtripPlanRequestSchema,
|
||||
@@ -20,7 +20,7 @@ const when = addonGate(ADDON_IDS.ROADTRIP);
|
||||
export class RoadtripPlanningMcp {
|
||||
constructor(
|
||||
private readonly plans: RoadtripPlanService,
|
||||
private readonly maps: MapsService,
|
||||
private readonly maps: RoadtripSearchService,
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@@ -104,16 +104,18 @@ export class RoadtripPlanningMcp {
|
||||
const tiles = corridorTiles(line, input.widthKm);
|
||||
const hits = new Map<
|
||||
string,
|
||||
{ poi: Awaited<ReturnType<MapsService['pois']>>['pois'][number]; alongKm: number; distanceKm: number }
|
||||
{ poi: Awaited<ReturnType<RoadtripSearchService['search']>>['pois'][number]; alongKm: number; distanceKm: number }
|
||||
>();
|
||||
const page = tiles.slice(input.offset, input.offset + 6);
|
||||
const failedAreas: number[] = [];
|
||||
let truncatedAreas = 0;
|
||||
const sources = new Set<string>();
|
||||
const failedSources = new Set<string>();
|
||||
for (const bbox of page) {
|
||||
try {
|
||||
const found = await this.maps.pois(input.category, bbox);
|
||||
sources.add(found.source);
|
||||
const found = await this.maps.search({ categories: [input.category], bbox }, ctx.userId);
|
||||
found.sources.forEach(source => sources.add(source));
|
||||
found.failedSources.forEach(source => failedSources.add(source));
|
||||
if (found.truncated || found.clamped) truncatedAreas++;
|
||||
for (const poi of found.pois) {
|
||||
const projection = projectOntoRoute(poi, line);
|
||||
@@ -146,7 +148,8 @@ export class RoadtripPlanningMcp {
|
||||
return ok({
|
||||
dayNumber: day.dayNumber,
|
||||
sources: [...sources],
|
||||
complete: !failedAreas.length && !truncatedAreas && input.offset + page.length >= tiles.length,
|
||||
failedSources: [...failedSources],
|
||||
complete: !failedSources.size && !failedAreas.length && !truncatedAreas && input.offset + page.length >= tiles.length,
|
||||
failedAreas,
|
||||
truncatedAreas,
|
||||
totalAreas: tiles.length,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Body, Controller, HttpCode, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { roadtripSearchAreaSchema } from '@trek/shared';
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RoadtripSearchService } from './roadtrip-search.service';
|
||||
|
||||
class SearchAreaDto extends createZodDto(roadtripSearchAreaSchema) {}
|
||||
|
||||
@Controller('api/roadtrip/search-area')
|
||||
@UseGuards(JwtAuthGuard, AddonGuard)
|
||||
@RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')
|
||||
export class RoadtripSearchController {
|
||||
constructor(private readonly search: RoadtripSearchService) {}
|
||||
@Post()
|
||||
@HttpCode(200)
|
||||
read(@Body() input: SearchAreaDto, @Req() req: Request & { user: { id: number } }) {
|
||||
return this.search.search(input, req.user.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { RoadtripSearchArea, RoadtripSearchAreaResponse } from '@trek/shared';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
import { PluginHooks } from '../plugins/plugin-hooks.service';
|
||||
import { pluginsEnabled } from '../plugins/kill-switch';
|
||||
import { normalizeSearchHits, MAX_HITS } from '../plugins/contributions/plugin-search.helpers';
|
||||
|
||||
const queries: Record<string, string> = {
|
||||
fuel: 'fuel station', charging: 'EV charging station', rest_area: 'rest area',
|
||||
campsite: 'campsite', restaurant: 'restaurant', sights: 'tourist attraction', hotel: 'hotel',
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class RoadtripSearchService {
|
||||
constructor(private readonly maps: MapsService, private readonly hooks: PluginHooks) {}
|
||||
|
||||
async search(input: RoadtripSearchArea, userId: number): Promise<RoadtripSearchAreaResponse> {
|
||||
const { bbox, lang } = input;
|
||||
const categories = [...new Set(input.categories)];
|
||||
const providers = pluginsEnabled() ? this.hooks.providersOf('searchProvider') : [];
|
||||
const core = this.maps.pois(categories.join(','), bbox, lang);
|
||||
const tasks = providers.flatMap(pluginId => categories.map(async category => {
|
||||
const raw = await this.hooks.searchPlaces(pluginId, {
|
||||
query: queries[category], category, bounds: bbox, lang, limit: MAX_HITS,
|
||||
near: { lat: (bbox.south + bbox.north) / 2, lng: (bbox.west + bbox.east) / 2 },
|
||||
}, userId);
|
||||
if (!Array.isArray(raw)) throw new Error('Invalid plugin search answer');
|
||||
const normalized = normalizeSearchHits(pluginId, raw);
|
||||
const pois = normalized.filter(p => p.lat >= bbox.south && p.lat <= bbox.north && p.lng >= bbox.west && p.lng <= bbox.east)
|
||||
.filter(p => !p.category || !(p.category in queries) || p.category === category)
|
||||
.map(p => ({ ...p, category, poi_type: category, opening_hours: null, cuisine: null, charging: null }));
|
||||
return { pois, source: `plugin:${pluginId}`, truncated: raw.length >= MAX_HITS || normalized.length < raw.length };
|
||||
}));
|
||||
const settled = await Promise.allSettled([core, ...tasks]);
|
||||
const sources = new Set<string>();
|
||||
const failedSources = new Set<string>();
|
||||
const pois = new Map<string, RoadtripSearchAreaResponse['pois'][number]>();
|
||||
let truncated = false;
|
||||
let clamped = false;
|
||||
settled.forEach((entry, index) => {
|
||||
if (entry.status === 'rejected') {
|
||||
failedSources.add(index === 0 ? 'TREK' : `plugin:${providers[Math.floor((index - 1) / categories.length)]}`);
|
||||
return;
|
||||
}
|
||||
sources.add(entry.value.source);
|
||||
truncated ||= entry.value.truncated;
|
||||
if ('clamped' in entry.value) clamped ||= entry.value.clamped;
|
||||
for (const poi of entry.value.pois) pois.set(poi.osm_id, poi);
|
||||
});
|
||||
return { pois: [...pois.values()], sources: [...sources], failedSources: [...failedSources], truncated, clamped };
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,8 @@
|
||||
import { GoogleRouteService } from './google-route.service';
|
||||
import { GoogleRouteController } from './google-route.controller';
|
||||
import { GoogleRouteMcp } from './google-route.mcp';
|
||||
import { PlacesModule } from '../places/places.module';
|
||||
import { AssignmentsModule } from '../assignments/assignments.module';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
@@ -18,6 +23,8 @@ import { RoadtripRouterService } from './roadtrip-router.service';
|
||||
import { RoadtripController } from './roadtrip.controller';
|
||||
import { RoadtripMcp } from './roadtrip.mcp';
|
||||
import { RoadtripService } from './roadtrip.service';
|
||||
import { RoadtripSearchService } from './roadtrip-search.service';
|
||||
import { RoadtripSearchController } from './roadtrip-search.controller';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RoadtripHazardsController } from './roadtrip-hazards.controller';
|
||||
import { RoadtripHazardsService } from './roadtrip-hazards.service';
|
||||
@@ -35,10 +42,11 @@ import { RoadtripHazardsMcp } from './roadtrip-hazards.mcp';
|
||||
RealtimeModule,
|
||||
SettingsModule,
|
||||
PluginsRuntimeModule,
|
||||
MapsModule,
|
||||
MapsModule, PlacesModule, AssignmentsModule,
|
||||
],
|
||||
controllers: [RoadtripPreferencesController, RoadtripController, DayBoundariesController, RoadtripHazardsController],
|
||||
providers: [
|
||||
controllers: [GoogleRouteController, RoadtripSearchController, RoadtripPreferencesController, RoadtripController, DayBoundariesController, RoadtripHazardsController],
|
||||
providers: [GoogleRouteService, GoogleRouteMcp,
|
||||
RoadtripSearchService,
|
||||
RoadtripHazardsService,
|
||||
RoadtripHazardsMcp,
|
||||
RoadtripService,
|
||||
|
||||
Reference in New Issue
Block a user