mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
feat(places): import the stops of a shared Google Maps route
Pasting a /maps/dir/ link into the list-import box answered "could not extract list ID", which is the whole of the complaint: people share a drive far more often than they share a list, and it is the same gesture — somebody pressed Share in Google Maps. Which screen they were on is the URL's business, so the box takes both and the controller decides. No API key and no call to Google for the link itself: the stops are in the URL. Three shapes arrive — the path form with its data blob, the documented ?api=1&origin= form, and a short link that is one of those after a redirect — and a stop the link spells out in coordinates needs no geocoder at all. One that is only a name is geocoded, keeping the name from the link rather than the one the geocoder answers with: somebody who typed a nickname into Google should not find a street address on their trip. A name nobody can place is left out and counted rather than failing the import, because a route of six stops with five findable is five stops more than the traveller had. Coordinates are read as 1d/2d, longitude before latitude, which is the reverse of a place link and the one way to put Berlin in Somalia. A blob that does not line up with the stops is ignored entirely: half a link read confidently is worse than one read as names.
This commit is contained in:
@@ -367,7 +367,7 @@ interface GooglePlaceDetails extends GooglePlaceResult {
|
||||
// unbounded body out of memory.
|
||||
const MAX_MAPS_PAGE_BYTES = 2_000_000;
|
||||
|
||||
const GOOGLE_SHORT_HOSTS = ['goo.gl', 'maps.app.goo.gl'];
|
||||
export const GOOGLE_SHORT_HOSTS = ['goo.gl', 'maps.app.goo.gl'];
|
||||
|
||||
/**
|
||||
* Google Maps lives on every country domain — google.de, maps.google.co.uk,
|
||||
@@ -376,7 +376,7 @@ const GOOGLE_SHORT_HOSTS = ['goo.gl', 'maps.app.goo.gl'];
|
||||
* labels stay short (2-3 letters, optionally two of them) so that
|
||||
* `google.evil.com` is not a Google host.
|
||||
*/
|
||||
function isGoogleMapsHost(hostname: string): boolean {
|
||||
export function isGoogleMapsHost(hostname: string): boolean {
|
||||
return GOOGLE_SHORT_HOSTS.includes(hostname)
|
||||
|| /^(www\.|maps\.)?google\.[a-z]{2,3}(\.[a-z]{2})?$/.test(hostname);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Reading the stops out of a shared Google Maps directions link.
|
||||
*
|
||||
* A `/maps/dir/` URL is a route somebody already planned: the stops are in the link
|
||||
* itself, which is why this needs no API key and no call to Google. Three shapes reach
|
||||
* us, and all three are somebody pressing "share" on a different screen:
|
||||
*
|
||||
* - the path form, `…/maps/dir/Berlin/Dresden/Prague/@50.9,13.5,8z/data=!4m…`, where the
|
||||
* segments between `dir` and the viewport are the stops and the data blob usually
|
||||
* carries a coordinate pair for each of them;
|
||||
* - the documented form, `…/maps/dir/?api=1&origin=…&destination=…&waypoints=A|B`, which
|
||||
* is what the URL builder in Google's own docs produces;
|
||||
* - a `maps.app.goo.gl` short link, which is either of the above after one redirect —
|
||||
* followed by the caller, because following it is a network call and this file makes
|
||||
* none.
|
||||
*
|
||||
* Everything here is pure. What it cannot answer — a stop that is only a name — it says
|
||||
* so about, and the caller geocodes it.
|
||||
*/
|
||||
|
||||
/** A stop read off the link. Coordinates when the link carried them, a name otherwise. */
|
||||
export interface DirWaypoint {
|
||||
name: string | null;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The most stops taken from one link.
|
||||
*
|
||||
* Google's own limit is ten waypoints between the ends; the cap is well above that
|
||||
* because the URL is user input and the geocoding behind it costs a request each.
|
||||
*/
|
||||
export const MAX_DIR_WAYPOINTS = 30;
|
||||
|
||||
/** `52.52,13.405` as a whole segment — how a stop with no name is written. */
|
||||
const COORD_PAIR = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/;
|
||||
|
||||
/**
|
||||
* The coordinate pairs Google hides in the `data=` blob, in driving order.
|
||||
*
|
||||
* Directions encode a stop as `!1d<lng>!2d<lat>`, the reverse of the `!3d<lat>!4d<lng>`
|
||||
* a single-place link uses — the numbers are the same protobuf fields read by a
|
||||
* different message, and getting the two the wrong way round puts Berlin in Somalia.
|
||||
*/
|
||||
const DATA_LNG_LAT = /!1d(-?\d+(?:\.\d+)?)!2d(-?\d+(?:\.\d+)?)/g;
|
||||
|
||||
/** Is this a directions link at all, rather than a list or a single place? */
|
||||
export function isDirectionsUrl(raw: string): boolean {
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
return /\/maps\/dir\/?/.test(url.pathname) || /\/dir\/?$/.test(url.pathname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Somewhere on Earth, rather than a pair of numbers that happen to be next to a comma. */
|
||||
function onEarth(lat: number, lng: number): boolean {
|
||||
return Number.isFinite(lat) && Number.isFinite(lng) && Math.abs(lat) <= 90 && Math.abs(lng) <= 180;
|
||||
}
|
||||
|
||||
/** A decoded stop: a coordinate pair becomes one, anything else stays a name. */
|
||||
function asWaypoint(decoded: string): DirWaypoint | null {
|
||||
const text = decoded.trim();
|
||||
if (!text) return null;
|
||||
const coords = text.match(COORD_PAIR);
|
||||
if (coords) {
|
||||
const lat = Number.parseFloat(coords[1]);
|
||||
const lng = Number.parseFloat(coords[2]);
|
||||
if (onEarth(lat, lng)) return { name: null, lat, lng };
|
||||
}
|
||||
return { name: text, lat: null, lng: null };
|
||||
}
|
||||
|
||||
/** A path segment still carries its escapes, and spaces as plus signs. */
|
||||
function decodeSegment(raw: string): string {
|
||||
try {
|
||||
return decodeURIComponent(raw.replaceAll('+', ' '));
|
||||
} catch {
|
||||
// A stray percent is somebody else's malformed link, not a reason to fail the import.
|
||||
return raw.replaceAll('+', ' ');
|
||||
}
|
||||
}
|
||||
|
||||
/** The `?api=1&origin=…` form, which names its parts instead of ordering them. */
|
||||
function fromQuery(url: URL): DirWaypoint[] {
|
||||
const origin = url.searchParams.get('origin');
|
||||
const destination = url.searchParams.get('destination');
|
||||
if (!origin && !destination) return [];
|
||||
const between = url.searchParams.get('waypoints')?.split('|') ?? [];
|
||||
// Already decoded by URLSearchParams, so these go straight in.
|
||||
return [origin, ...between, destination]
|
||||
.filter((part): part is string => !!part && part.trim().length > 0)
|
||||
.map((part) => asWaypoint(part))
|
||||
.filter((wp): wp is DirWaypoint => wp !== null);
|
||||
}
|
||||
|
||||
/** The path form, where the stops are the segments and the blob holds their positions. */
|
||||
function fromPath(url: URL): DirWaypoint[] {
|
||||
const parts = url.pathname.split('/').filter(Boolean);
|
||||
const at = parts.indexOf('dir');
|
||||
if (at < 0) return [];
|
||||
|
||||
const names: DirWaypoint[] = [];
|
||||
let data = '';
|
||||
for (const part of parts.slice(at + 1)) {
|
||||
// The viewport and the blob end the list of stops; everything after them belongs to
|
||||
// how the map was framed, not to where the car goes.
|
||||
if (part.startsWith('@')) continue;
|
||||
if (part.startsWith('data=')) { data = part; continue; }
|
||||
if (data) continue;
|
||||
const wp = asWaypoint(decodeSegment(part));
|
||||
if (wp) names.push(wp);
|
||||
}
|
||||
if (!names.length) return [];
|
||||
|
||||
// Positions from the blob, but only when there is exactly one for each stop. A partial
|
||||
// match cannot be lined up — Google drops the pair for "your location" and adds pairs
|
||||
// of its own for a route through several countries — and half a link read confidently
|
||||
// is worse than a link read as names and geocoded.
|
||||
const pairs = [...(data.matchAll(DATA_LNG_LAT))]
|
||||
.map((m) => ({ lng: Number.parseFloat(m[1]), lat: Number.parseFloat(m[2]) }))
|
||||
.filter((p) => onEarth(p.lat, p.lng));
|
||||
if (pairs.length !== names.length) return names;
|
||||
|
||||
return names.map((wp, i) => (wp.lat !== null ? wp : { name: wp.name, lat: pairs[i].lat, lng: pairs[i].lng }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The stops of a shared directions link, in the order they are driven.
|
||||
*
|
||||
* 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[] {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const fromParams = fromQuery(url);
|
||||
const found = fromParams.length ? fromParams : fromPath(url);
|
||||
return found.length >= 2 ? found.slice(0, MAX_DIR_WAYPOINTS) : [];
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import { memoryStorage } from 'multer';
|
||||
import { hexColorSchema, placeImageUrlSchema, placeWebsiteSchema } from '@trek/shared';
|
||||
import type { User } from '../../types';
|
||||
import { PlacesService } from './places.service';
|
||||
import { isDirectionsUrl } from './maps-dir.helpers';
|
||||
import { isUpdateConflict } from '../common/conflictResult';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
@@ -274,9 +275,15 @@ export class PlacesController {
|
||||
const opts = { enrich: parseBool(enrich, false), userId: user.id };
|
||||
const label = provider === 'google' ? 'Google' : 'Naver';
|
||||
try {
|
||||
const result = provider === 'google'
|
||||
? await this.places.importGoogleList(tripId, url, opts)
|
||||
: await this.places.importNaverList(tripId, url, opts);
|
||||
// A directions link and a list link arrive through the same box because they are
|
||||
// the same gesture: somebody pressed Share in Google Maps. Which screen they were
|
||||
// on is the URL's business, not the traveller's, and answering a pasted route with
|
||||
// "could not extract list ID" was the whole of the complaint.
|
||||
const result = provider !== 'google'
|
||||
? await this.places.importNaverList(tripId, url, opts)
|
||||
: isDirectionsUrl(url)
|
||||
? await this.places.importGoogleDirections(tripId, url, opts)
|
||||
: await this.places.importGoogleList(tripId, url, opts);
|
||||
if ('error' in result) {
|
||||
throw new HttpException({ error: result.error }, result.status);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
import { PlacesService } from './places.service';
|
||||
import { isDirectionsUrl } from './maps-dir.helpers';
|
||||
|
||||
function parseId(value: string | string[]): number | null {
|
||||
const n = Number(Array.isArray(value) ? value[0] : value);
|
||||
@@ -317,7 +318,7 @@ export class PlacesMcp {
|
||||
description: 'Import places from a shared Google Maps or Naver Maps list URL. Returns the imported places and count. The list must be shared publicly.',
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
url: z.string().url().describe('Publicly shared Google Maps list URL (maps.app.goo.gl/...) or Naver Maps list URL'),
|
||||
url: z.string().url().describe('Publicly shared Google Maps list URL, a Google Maps directions link (/maps/dir/...), or a Naver Maps list URL. A directions link is read straight out of the URL: its stops become places in driving order, and the ones written as names are geocoded.'),
|
||||
source: z.enum(['google-list', 'naver-list']).describe('List source: "google-list" for Google Maps saved places, "naver-list" for Naver Maps'),
|
||||
enrich: placeImportListRequestSchema.shape.enrich.describe('Re-resolve every imported place through the Places API afterwards to fill in photo, address, website and phone (#886). Needs a Google Maps key on the instance, costs a lookup per place, and runs in the background: the tool returns the bare import and the places fill in over the websocket. Off by default'),
|
||||
},
|
||||
@@ -336,7 +337,9 @@ export class PlacesMcp {
|
||||
// user because it spends that user's Places credential.
|
||||
const opts = { enrich: enrich ?? false, userId: ctx.userId };
|
||||
const result = source === 'google-list'
|
||||
? await this.places.importGoogleList(String(tripId), url, opts)
|
||||
? (isDirectionsUrl(url)
|
||||
? await this.places.importGoogleDirections(String(tripId), url, opts)
|
||||
: await this.places.importGoogleList(String(tripId), url, opts))
|
||||
: await this.places.importNaverList(String(tripId), url, opts);
|
||||
|
||||
if ('error' in result) {
|
||||
|
||||
@@ -6,7 +6,8 @@ import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { DatabaseService, type TripAccess } from '../database/database.service';
|
||||
import type { PlaceWithTags } from '../database/database.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
import { MapsService, GOOGLE_SHORT_HOSTS, isGoogleMapsHost } from '../maps/maps.service';
|
||||
import { parseDirectionsUrl } from './maps-dir.helpers';
|
||||
import type { Place, User } from '../../types';
|
||||
import { QueryHelpersService } from '../query-helpers/query-helpers.service';
|
||||
import { ratingAggregate } from '../common/rowShape';
|
||||
@@ -1033,6 +1034,26 @@ export class PlacesService {
|
||||
return { error: 'No places with coordinates found in list', status: 400 };
|
||||
}
|
||||
|
||||
const { created, skipped } = this.storeGooglePlaces(tripId, places);
|
||||
|
||||
if (created.length) {
|
||||
void this.enrichImportedList(tripId, created as EnrichablePlace[], opts);
|
||||
}
|
||||
|
||||
return { places: created, listName, skipped };
|
||||
}
|
||||
|
||||
/**
|
||||
* The insert half every Google-shaped import shares: dedupe, write, collect.
|
||||
*
|
||||
* One implementation for the list and for the directions link, because the rules are
|
||||
* the same rules — a place already on the trip is skipped rather than doubled, and a
|
||||
* row that matches but carries no provider id is given the one this import knows.
|
||||
*/
|
||||
private storeGooglePlaces(
|
||||
tripId: string,
|
||||
places: { name: string; lat: number; lng: number; notes: string | null; googleFtid: string | null }[],
|
||||
): { created: PlaceWithTags[]; skipped: number } {
|
||||
const dedup = this.buildDedupSet(tripId);
|
||||
const insertStmt = this.dbs.prepare(`
|
||||
INSERT INTO places (trip_id, name, lat, lng, notes, google_ftid, transport_mode)
|
||||
@@ -1063,12 +1084,103 @@ export class PlacesService {
|
||||
trackInsertedInDedupSet(candidate, dedup);
|
||||
}
|
||||
});
|
||||
return { created, skipped };
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Import a shared Google Maps directions link
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The stops of a route somebody else planned.
|
||||
*
|
||||
* The other half of the request the list import answers: people share a drive far more
|
||||
* often than they share a list, and until now a pasted `/maps/dir/` link came back as a
|
||||
* cryptic "could not extract list ID". No API key is involved and no call is made to
|
||||
* Google for the link itself — the stops are in the URL, which is the whole reason
|
||||
* this is possible at all.
|
||||
*
|
||||
* A stop the link spells out in coordinates is taken as it stands; one that is only a
|
||||
* name is geocoded, one request each. A name nobody can place is left out rather than
|
||||
* failing the import, because a route of six stops with five findable is five stops
|
||||
* more than the traveller had.
|
||||
*/
|
||||
async importGoogleDirections(tripId: string, url: string, opts?: ListImportOptions): Promise<ListImportResult | ListImportError> {
|
||||
const ssrf = await checkSsrf(url);
|
||||
if (!ssrf.allowed) return { error: 'URL is not allowed', status: 400 };
|
||||
|
||||
let parsed: URL;
|
||||
try { parsed = new URL(url); } catch { return { error: 'Invalid URL', status: 400 }; }
|
||||
|
||||
// Short links are resolved hop by hop through the guard, exactly as the list import
|
||||
// does it: a maps.app.goo.gl that 302s to an internal address is still blocked.
|
||||
let resolvedUrl = url;
|
||||
if (GOOGLE_SHORT_HOSTS.includes(parsed.hostname)) {
|
||||
try {
|
||||
const redirectRes = await safeFetchFollow(url, { signal: AbortSignal.timeout(10000) });
|
||||
resolvedUrl = redirectRes.url;
|
||||
} catch (err) {
|
||||
if (err instanceof SsrfBlockedError) return { error: 'URL is not allowed', status: 400 };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Checked after resolving, not before: the host that counts is the one the link lands
|
||||
// on, and `/maps/dir/` is a path anybody could serve.
|
||||
let host = '';
|
||||
try { host = new URL(resolvedUrl).hostname; } catch { /* an unparseable hop fails the check below */ }
|
||||
if (!isGoogleMapsHost(host)) {
|
||||
return { error: 'That link is not a Google Maps link.', status: 400 };
|
||||
}
|
||||
|
||||
const waypoints = parseDirectionsUrl(resolvedUrl);
|
||||
if (waypoints.length < 2) {
|
||||
return { error: 'Could not read any stops from that directions link. Open the route in Google Maps and use its Share button.', status: 400 };
|
||||
}
|
||||
|
||||
const places: { name: string; lat: number; lng: number; notes: string | null; googleFtid: string | null }[] = [];
|
||||
let unplaceable = 0;
|
||||
for (const wp of waypoints) {
|
||||
if (wp.lat !== null && wp.lng !== null) {
|
||||
// A stop written as coordinates has no name of its own, and the coordinates are a
|
||||
// better label than "Stop 3": they are what the traveller can look up.
|
||||
places.push({
|
||||
name: wp.name || `${wp.lat.toFixed(5)}, ${wp.lng.toFixed(5)}`,
|
||||
lat: wp.lat,
|
||||
lng: wp.lng,
|
||||
notes: null,
|
||||
googleFtid: null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (!wp.name) continue;
|
||||
try {
|
||||
const hits = await this.maps.searchNominatim(wp.name);
|
||||
const hit = hits.find((h) => h.lat !== null && h.lng !== null);
|
||||
// The name from the link, not the one the geocoder answers with: somebody who
|
||||
// typed a nickname into Google should not find a street address on their trip.
|
||||
if (hit) places.push({ name: wp.name, lat: hit.lat!, lng: hit.lng!, notes: null, googleFtid: null });
|
||||
else unplaceable++;
|
||||
} catch {
|
||||
// A geocoder that is down or rate-limited costs this one stop, not the import.
|
||||
unplaceable++;
|
||||
}
|
||||
}
|
||||
|
||||
if (places.length < 2) {
|
||||
return { error: 'None of the stops in that link could be placed on the map.', status: 400 };
|
||||
}
|
||||
|
||||
const { created, skipped } = this.storeGooglePlaces(tripId, places);
|
||||
if (created.length) {
|
||||
void this.enrichImportedList(tripId, created as EnrichablePlace[], opts);
|
||||
}
|
||||
|
||||
return { places: created, listName, skipped };
|
||||
// The route reads as what it is in the toast: where it starts and where it ends.
|
||||
const listName = `${places[0].name} → ${places[places.length - 1].name}`;
|
||||
// Both kinds of "not added" under one number, because from the traveller's side they
|
||||
// are one thing: this many stops in the link are not on the trip.
|
||||
return { places: created, listName, skipped: skipped + unplaceable };
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user