Give a Google place its free half back

This commit is contained in:
Maurice
2026-08-10 09:53:08 +02:00
committed by Maurice
parent 8f9af76204
commit 0c8788ce44
7 changed files with 872 additions and 45 deletions
+67
View File
@@ -40,6 +40,73 @@ export function toApiLang(lang: string | undefined, fallback = 'en'): string {
return API_LANG_OVERRIDES[code] ?? code;
}
/**
* A wiki subdomain out of a TREK language code.
*
* Not the same normalisation as `toApiLang`, and the difference bites: TREK
* calls Brazilian Portuguese `br`, but `br.wikipedia.org` exists and is the
* BRETON Wikipedia. Passing the raw code through would not fail — it would
* quietly return Breton articles. `pt-br.wikipedia.org` does not resolve at
* all, so the region subtag has to go as well.
*/
const WIKI_LANG_OVERRIDES: Record<string, string> = {
br: 'pt',
gr: 'el',
};
export function toWikiLang(lang: string | undefined, fallback = 'en'): string {
const raw = (lang || '').trim();
if (!raw) return fallback;
const mapped = WIKI_LANG_OVERRIDES[raw] ?? raw;
const base = mapped.split('-')[0].toLowerCase();
return /^[a-z]{2,3}$/.test(base) ? base : fallback;
}
/** Metres between two coordinates. Spherical earth is plenty at this scale. */
export function haversineMetres(aLat: number, aLng: number, bLat: number, bLng: number): number {
const toRad = (deg: number) => (deg * Math.PI) / 180;
const dLat = toRad(bLat - aLat);
const dLng = toRad(bLng - aLng);
const h =
Math.sin(dLat / 2) ** 2 + Math.cos(toRad(aLat)) * Math.cos(toRad(bLat)) * Math.sin(dLng / 2) ** 2;
return 2 * 6371000 * Math.asin(Math.min(1, Math.sqrt(h)));
}
/**
* Whether two place names plausibly refer to the same thing.
*
* The gate that keeps a coordinate-based lookup from confidently describing the
* wrong building. "Hamburg Airport" and "Flughafen Hamburg" pass on "hamburg";
* "Hamburg Airport" and "Bahnhof Ohlsdorf" do not.
*
* One shared word is enough only when it carries some weight — four letters or
* more. Otherwise two have to match. A single short word is almost always an
* article or a generic noun, and TREK speaks 23 languages, so "Der Kiosk" and
* "Der Bahnhof" would sail through a plain word-overlap test while a stopword
* list for all of them is its own maintenance problem. Anything the pair rule
* lets through has already survived the distance check.
*/
export function namesOverlap(a: string, b: string): boolean {
const words = (value: string): Set<string> =>
new Set(
value
.toLowerCase()
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.split(/[^a-z0-9]+/)
.filter((word) => word.length > 2),
);
const left = words(a);
if (left.size === 0) return false;
let shared = 0;
for (const word of words(b)) {
if (!left.has(word)) continue;
if (word.length >= 4) return true;
if (++shared >= 2) return true;
}
return false;
}
const GOOGLE_FTID_RE = /^0x[0-9a-f]+:0x[0-9a-f]+$/i;
// Extracts a Google Maps feature id (ftid, 0x..:0x..) from a URL's ?ftid= param.
+189 -25
View File
@@ -27,6 +27,9 @@ import {
resolveOverpassTimeoutMs,
stripWikiMarkup,
parseWikipediaTag,
toWikiLang,
haversineMetres,
namesOverlap,
type GoogleOpeningHours,
type OverpassPoi,
} from './maps.helpers';
@@ -275,6 +278,12 @@ interface GooglePlaceDetails extends GooglePlaceResult {
// a slow provider is dropped rather than waited out.
const WIKI_TIMEOUT_MS = 6000;
// Tighter than the wiki calls, because this one sits at the FRONT of a chain:
// identity, then sitelinks, then the extract. Nominatim answers a bounded
// search in 0.2-0.7s in practice, so anything past a couple of seconds is a bad
// day at the provider rather than a slow answer worth waiting for.
const IDENTITY_TIMEOUT_MS = 2500;
const MAX_CONCURRENT_PHOTO_FETCHES = 5;
let photoFetchActive = 0;
const photoFetchQueue: Array<() => void> = [];
@@ -552,6 +561,91 @@ export class MapsService {
});
}
/**
* Finds the OpenStreetMap record for a place we only know by name and
* coordinate, and hands back its tags.
*
* This is what gives a Google place a free identity. Google's payload has no
* `wikidata`, no `wikipedia` and no `wikimedia_commons` — it never had — so
* without this the entire free half of the enrichment column is unreachable
* for anyone who configured a Google key, which is the opposite of how this
* feature is meant to work. OSM knows these places perfectly well; nobody was
* asking it.
*
* Two gates keep it from describing the wrong building, because a confident
* description of somewhere else is worse than none:
* - the match has to be within `maxDistanceM` of where we are looking, and
* - it has to share a substantial word with the name we are looking for.
* Among what survives, Nominatim's own `importance` decides — that is what
* separates the Brandenburg Gate from the underground station named after it.
*/
async resolveOsmIdentity(
name: string,
lat: number,
lng: number,
opts: { lang?: string; maxDistanceM?: number; signal?: AbortSignal } = {},
): Promise<{ tags: Record<string, string>; osmUrl: string | null; matchedName: string } | null> {
const query = (name || '').trim();
if (!query || !Number.isFinite(lat) || !Number.isFinite(lng)) return null;
const maxDistanceM = opts.maxDistanceM ?? 2000;
// ~2km box around the point, so Nominatim ranks locally instead of handing
// back the most famous place on earth with this name.
const d = 0.02;
const params = new URLSearchParams({
q: query,
format: 'jsonv2',
extratags: '1',
limit: '5',
bounded: '1',
viewbox: `${lng - d},${lat - d},${lng + d},${lat + d}`,
'accept-language': toApiLang(opts.lang),
});
try {
const res = await fetch(`https://nominatim.openstreetmap.org/search?${params}`, {
headers: { 'User-Agent': UA },
signal: opts.signal ?? AbortSignal.timeout(IDENTITY_TIMEOUT_MS),
});
if (!res.ok) return null;
// Nominatim answers rate limiting in plain text, not JSON.
const data = (await res.json()) as (NominatimResult & { importance?: number })[];
if (!Array.isArray(data)) return null;
const best = data
.map((item) => ({
item,
lat: parseFloat(item.lat),
lng: parseFloat(item.lon),
}))
.filter(({ item, lat: hitLat, lng: hitLng }) => {
if (!Number.isFinite(hitLat) || !Number.isFinite(hitLng)) return false;
if (haversineMetres(lat, lng, hitLat, hitLng) > maxDistanceM) return false;
const label = item.name || item.display_name?.split(',')[0] || '';
return namesOverlap(query, label);
})
.sort((a, b) => {
const byImportance = (b.item.importance ?? 0) - (a.item.importance ?? 0);
if (byImportance !== 0) return byImportance;
return (
haversineMetres(lat, lng, a.lat, a.lng) - haversineMetres(lat, lng, b.lat, b.lng)
);
})[0];
if (!best) return null;
return {
tags: best.item.extratags ?? {},
osmUrl:
best.item.osm_type && best.item.osm_id
? `https://www.openstreetmap.org/${best.item.osm_type}/${best.item.osm_id}`
: null,
matchedName: best.item.name || best.item.display_name?.split(',')[0] || query,
};
} catch {
return null;
}
}
// ── Nominatim lookup (by OSM ID) ───────────────────────────────────────────
async lookupNominatim(
@@ -871,35 +965,105 @@ export class MapsService {
});
for (const host of ['wikivoyage', 'wikipedia'] as const) {
try {
const res = await fetch(`https://${parsed.lang}.${host}.org/w/api.php?${params}`, {
headers: { 'User-Agent': UA },
signal: AbortSignal.timeout(WIKI_TIMEOUT_MS),
});
if (!res.ok) continue;
const data = (await res.json()) as {
query?: { pages?: Record<string, { title?: string; extract?: string }> };
};
const pages = data.query?.pages;
if (!pages) continue;
for (const page of Object.values(pages)) {
const text = page.extract?.trim();
// A missing article comes back as a page with no extract, not a 404.
if (!text) continue;
const title = page.title ?? parsed.title;
return {
text,
sourceUrl: `https://${parsed.lang}.${host}.org/wiki/${encodeURIComponent(title)}`,
source: host,
};
}
} catch {
/* try the next wiki */
}
const hit = await this.fetchWikiExtractFor(host, parsed.lang, parsed.title);
if (hit) return hit;
}
return null;
}
/**
* The lead paragraph of one named article on one named wiki.
*
* Split out from `fetchWikiExtract` because the article is not always found
* through an OSM tag: a place can carry a Wikidata id and no `wikipedia` tag
* at all (Berlin Hauptbahnhof is exactly that), and then the title comes from
* the item's sitelinks instead.
*/
async fetchWikiExtractFor(
host: 'wikivoyage' | 'wikipedia',
lang: string,
title: string,
signal?: AbortSignal,
): Promise<{ text: string; sourceUrl: string; source: 'wikivoyage' | 'wikipedia' } | null> {
if (!lang || !title) return null;
// Two sentences, not three: this sits next to a form, and a fourth line of
// prose pushes the pictures out of view.
const params = new URLSearchParams({
action: 'query',
format: 'json',
titles: title,
prop: 'extracts',
exintro: '1',
explaintext: '1',
exsentences: '2',
redirects: '1',
});
try {
const res = await fetch(`https://${lang}.${host}.org/w/api.php?${params}`, {
headers: { 'User-Agent': UA },
signal: signal ?? AbortSignal.timeout(WIKI_TIMEOUT_MS),
});
if (!res.ok) return null;
const data = (await res.json()) as {
query?: { pages?: Record<string, { title?: string; extract?: string }> };
};
for (const page of Object.values(data.query?.pages ?? {})) {
const text = page.extract?.trim();
// A missing article comes back as a page with no extract, not a 404.
if (!text) continue;
const resolved = page.title ?? title;
return {
text,
sourceUrl: `https://${lang}.${host}.org/wiki/${encodeURIComponent(resolved)}`,
source: host,
};
}
return null;
} catch {
return null;
}
}
/**
* Which articles a Wikidata item is linked to, for the wikis we care about.
*
* The way to an article when a place has a Wikidata id but no `wikipedia`
* tag — which is most of them, because mappers add one or the other. One
* request, a few hundred bytes.
*/
async fetchWikidataSitelinks(
wikidataId: string,
sites: string[],
signal?: AbortSignal,
): Promise<Record<string, string>> {
const qid = wikidataId.trim();
if (!/^Q\d+$/.test(qid) || sites.length === 0) return {};
const params = new URLSearchParams({
action: 'wbgetentities',
props: 'sitelinks',
ids: qid,
sitefilter: sites.join('|'),
format: 'json',
});
try {
const res = await fetch(`https://www.wikidata.org/w/api.php?${params}`, {
headers: { 'User-Agent': UA },
signal: signal ?? AbortSignal.timeout(IDENTITY_TIMEOUT_MS),
});
if (!res.ok) return {};
const data = (await res.json()) as {
entities?: Record<string, { sitelinks?: Record<string, { title?: string }> }>;
};
const out: Record<string, string> = {};
for (const [site, link] of Object.entries(data.entities?.[qid]?.sitelinks ?? {})) {
if (link?.title) out[site] = link.title;
}
return out;
} catch {
return {};
}
}
/**
* The pictures Wikidata records for a place, best first.
*
@@ -9,8 +9,8 @@ import type {
} from '@trek/shared';
import { safeFetchFollow } from '../../utils/ssrfGuard';
import { DatabaseService } from '../database/database.service';
import { MapsService, withPhotoFetchSlot, type CommonsCandidate } from '../maps/maps.service';
import { isGooglePlaceId, rankCommonsCandidates } from '../maps/maps.helpers';
import { MapsService, readWikiIdentity, withPhotoFetchSlot, type CommonsCandidate, type WikiIdentity } from '../maps/maps.service';
import { isGooglePlaceId, parseWikipediaTag, rankCommonsCandidates, toWikiLang } from '../maps/maps.helpers';
import { PlacePhotoCacheService } from '../place-photos/place-photo-cache.service';
/**
@@ -59,6 +59,15 @@ export function candidateKey(placeId: string, identity: string): string {
return `${placeId}~p${digest}`;
}
/**
* What the free sources need to know about a place, kept apart from whatever
* the maps provider returned. See `resolveIdentity` for why they do not merge.
*/
interface PlaceIdentity extends WikiIdentity {
/** Full OSM tag set, when the identity came from a Nominatim lookup. */
osmTags: Record<string, string> | null;
}
/** A ranked Commons pick, tagged with the rung of the ladder it came from. */
type CommonsPick = CommonsCandidate & { rung: 'wikidata' | 'wikipedia' | 'category' | 'nearby' };
@@ -204,10 +213,11 @@ export class PlaceEnrichmentService {
// comes along with the request. Refetching cost 12.8 seconds on a large
// OSM relation, and it ran in parallel with the client's own lookup.
const details = req.details ?? (await this.readDetails(userId, placeId, lang));
const identity = await this.resolveIdentity(req, details);
const [photos, description] = await Promise.all([
this.collectPhotos(userId, placeId, req, details),
this.collectDescription(userId, placeId, req, details),
this.collectPhotos(userId, placeId, req, identity),
this.collectDescription(userId, placeId, req, details, identity),
]);
const result: CachedEnrichment = { photos, description, facts: collectFacts(details) };
@@ -226,20 +236,53 @@ export class PlaceEnrichmentService {
return { credit: this.photoCache.get(key)?.attribution ?? null };
}
/**
* Which encyclopaedia entry, Wikidata item and Commons category describe this
* place.
*
* Kept beside the provider payload rather than merged into it, and that is
* not tidiness. `collectFacts` and the OSM branch of `collectDescription`
* both gate on `details.source`, so OSM tags folded into a Google payload
* would be carried around and never read — or, worse, would make a Google
* place start claiming to be an OpenStreetMap one.
*
* The lookup only runs when the payload brought nothing, which is every
* Google place: Google's response has no wiki tags and never had, so before
* this a configured API key silently switched the free half of this feature
* off.
*/
private async resolveIdentity(
req: MapsPlaceEnrichmentRequest,
details: Record<string, unknown> | null,
): Promise<PlaceIdentity> {
const fromPayload = (key: string): string | null =>
typeof details?.[key] === 'string' && (details[key] as string).trim() ? (details[key] as string).trim() : null;
const carried: PlaceIdentity = {
wikipedia: fromPayload('wikipedia'),
wikidata: fromPayload('wikidata'),
wikimedia_commons: fromPayload('wikimedia_commons'),
osmTags: null,
};
if (carried.wikipedia || carried.wikidata || carried.wikimedia_commons) return carried;
const resolved = await this.maps.resolveOsmIdentity(req.name, req.lat, req.lng, { lang: req.lang });
if (!resolved) return carried;
return { ...readWikiIdentity(resolved.tags), osmTags: resolved.tags };
}
// ── Photos ─────────────────────────────────────────────────────────────────
private async collectPhotos(
userId: number,
placeId: string,
req: MapsPlaceEnrichmentRequest,
details: Record<string, unknown> | null,
identity: PlaceIdentity,
): Promise<PlacePhotoCandidate[]> {
const apiKey = this.maps.getMapsKey(userId);
const wantsGoogle = !!apiKey && !this.maps.photosDisabled() && isGooglePlaceId(placeId);
const tag = (key: string): string | null => (typeof details?.[key] === 'string' ? (details[key] as string) : null);
const wikidata = tag('wikidata');
const wikipedia = tag('wikipedia');
const { wikidata, wikipedia } = identity;
// Google's listing is one call for the whole strip and knows nothing about
// the free sources, so it runs alongside them rather than in the ladder.
@@ -258,7 +301,7 @@ export class PlaceEnrichmentService {
// gate by the underground station beneath it. It is the fallback, and it
// only runs when the ladder above came up short.
const commonsPool: CommonsPick[] = [];
let categoryName = tag('wikimedia_commons');
let categoryName = identity.wikimedia_commons;
if (wikidata) {
const fromWikidata = await this.maps.fetchWikidataCandidates(wikidata, COMMONS_CAP);
@@ -392,6 +435,7 @@ export class PlaceEnrichmentService {
placeId: string,
req: MapsPlaceEnrichmentRequest,
details: Record<string, unknown> | null,
identity: PlaceIdentity,
): Promise<PlaceDescription | null> {
// OpenStreetMap first: it costs nothing, it is already fetched, and a
// description someone wrote into the map data beats a generated blurb.
@@ -405,6 +449,16 @@ export class PlaceEnrichmentService {
};
}
// Then the encyclopaedias. This used to sit BELOW Google, which read as a
// detail and was in fact the whole problem: an instance with a key asked
// Google, got nothing back for most places, and stopped — while a perfectly
// good Wikivoyage article sat one call away. Free sources are the normal
// case here and Google is the addition, so the order says so.
const extract = await this.fetchWikiDescription(identity, req.lang);
if (extract) {
return { text: extract.text, source: extract.source, sourceUrl: extract.sourceUrl, license: 'CC BY-SA 4.0' };
}
const apiKey = this.maps.getMapsKey(userId);
if (apiKey && !this.maps.detailsDisabled() && isGooglePlaceId(placeId)) {
const summary = await this.maps.fetchEditorialSummary(placeId, apiKey, req.lang);
@@ -418,16 +472,56 @@ export class PlaceEnrichmentService {
}
}
// Wikipedia last, and only when the place carries a wiki tag. Looking the
// article up by name lands on the wrong one for anything ambiguous, and a
// confident description of somewhere else is worse than none.
const wikipediaTag = typeof details?.wikipedia === 'string' ? details.wikipedia : null;
const extract = await this.maps.fetchWikiExtract(wikipediaTag);
if (extract) {
return { text: extract.text, source: extract.source, sourceUrl: extract.sourceUrl, license: 'CC BY-SA 4.0' };
return null;
}
/**
* The article about this place, in the reader's language where one exists.
*
* Two ways in, and a place usually has only one of them: mappers tag either
* `wikipedia` or `wikidata`, rarely both. The Wikidata route goes through
* sitelinks, which is also what makes the language choice honest — asking
* `<userlang>.wikipedia.org` for a title taken from the German tag returns
* nothing, so without sitelinks a German article is all a Korean reader could
* ever get.
*
* Wikivoyage before Wikipedia at every step: it describes a place for someone
* about to go there, where Wikipedia opens with area in square kilometres.
*/
private async fetchWikiDescription(
identity: PlaceIdentity,
lang: string | undefined,
): Promise<{ text: string; sourceUrl: string; source: 'wikivoyage' | 'wikipedia' } | null> {
const userLang = toWikiLang(lang);
const tag = parseWikipediaTag(identity.wikipedia);
if (identity.wikidata) {
// The tag's own language is in the list because the place named that
// article specifically; it beats falling through to English.
const wanted: { site: string; host: 'wikivoyage' | 'wikipedia'; lang: string }[] = [
{ site: `${userLang}wikivoyage`, host: 'wikivoyage', lang: userLang },
{ site: `${userLang}wiki`, host: 'wikipedia', lang: userLang },
...(tag && tag.lang !== userLang
? [{ site: `${tag.lang}wiki`, host: 'wikipedia' as const, lang: tag.lang }]
: []),
{ site: 'enwikivoyage', host: 'wikivoyage', lang: 'en' },
{ site: 'enwiki', host: 'wikipedia', lang: 'en' },
];
const sitelinks = await this.maps.fetchWikidataSitelinks(
identity.wikidata,
wanted.map((w) => w.site),
);
for (const { site, host, lang: hostLang } of wanted) {
const title = sitelinks[site];
if (!title) continue;
const hit = await this.maps.fetchWikiExtractFor(host, hostLang, title);
if (hit) return hit;
}
}
return null;
// No Wikidata id, or its sitelinks led nowhere: fall back to the tag, which
// names an article directly.
return identity.wikipedia ? this.maps.fetchWikiExtract(identity.wikipedia) : null;
}
/**