feat(clients): maps: Places, Address Validation, Solar, Pollen, Air Quality, Area Insights, Routes, web services, Street View, key handling
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,248 @@
|
||||
# Google Maps Platform - Specification
|
||||
|
||||
Owned directory: `src/google/maps/`. Namespace `molo::google::maps`. Depends on
|
||||
the `src/google` foundation only (`GoogleClient`, `Service`, `GoogleError`,
|
||||
`Credentials`, `valid_segment`, `endpoints::custom`). Tests:
|
||||
`tests/src/google/maps/`. Demo: `example/app/google/MapsDemo.cpp`, routes under
|
||||
`/google/maps`, page script `example/assets/google_maps.js`, route tests
|
||||
`tests/example/google/maps/`.
|
||||
|
||||
## 1. Scope
|
||||
|
||||
Typed classes for twelve Maps Platform surfaces:
|
||||
|
||||
| Surface | Class | Calls |
|
||||
|---|---|---|
|
||||
| Places API (New) | `Places` | autocomplete, searchText, searchNearby, get, photo media (URI only) |
|
||||
| Address Validation | `AddressValidation` | validateAddress, provideValidationFeedback |
|
||||
| Solar | `Solar` | buildingInsights, dataLayers, geoTiff (path only) |
|
||||
| Pollen | `Pollen` | forecast, heatmap tile (path only) |
|
||||
| Air Quality | `AirQuality` | currentConditions, forecast, history, heatmap tile (path only) |
|
||||
| Area Insights | `AreaInsights` | computeInsights |
|
||||
| Routes API v2 | `Routes` | computeRoutes, computeRouteMatrix |
|
||||
| Geocoding | `Geocoding` | forward, reverse, by place id |
|
||||
| Time Zone | `TimeZone` | lookup |
|
||||
| Elevation | `Elevation` | at points, along a path |
|
||||
| Street View Publish | `StreetViewPublish` | all 14 Discovery methods (reads, writes, explicit deletes) |
|
||||
| API-key handling | `MapsKey`, `KeyRestrictions`, `ApiKeys` | key shape and redaction, restriction model and lint, read-only key list and get |
|
||||
|
||||
Out of scope on purpose: the JavaScript / Android / iOS map renderers, Static
|
||||
Maps / Street View Static / Map Tiles / Embed (URL products with image
|
||||
bodies), Route Optimization and Maps Datasets (own APIs, not in the plan row),
|
||||
Places Aggregate, Geolocation, Roads. API Keys mutations (create, patch,
|
||||
delete, getKeyString) are deliberately absent: they change or reveal secrets
|
||||
and belong to the ops package.
|
||||
|
||||
## 2. Module map (one class or concern per file)
|
||||
|
||||
| File | Concern |
|
||||
|---|---|
|
||||
| `caps.h` | Static ceilings |
|
||||
| `calls.h/.cpp` | The one call table (`CALLS-BEGIN` ... `CALLS-END`), `render`, `endpoint_of` |
|
||||
| `types.h/.cpp` | `LatLng`, `FieldMask`, `Query` (percent-encoding), text and code validators |
|
||||
| `maps_service.h/.cpp` | `MapsService : Service`: runs a table row, validates query parameters and body fields against it, dry run, `check_web_status` |
|
||||
| `places.h/.cpp` | Places (New) requests, `Place`, `Places` |
|
||||
| `address_validation.h/.cpp` | `PostalAddress`, requests, `AddressVerdict`, `AddressValidation` |
|
||||
| `environment.h/.cpp` | `Solar`, `Pollen`, `AirQuality`, `InsightsFilter`, `AreaInsights` |
|
||||
| `routes.h/.cpp` | `Waypoint`, route and matrix requests, `RouteSummary`, `Routes` |
|
||||
| `web_services.h/.cpp` | `Geocoding`, `TimeZone`, `Elevation` and their result types |
|
||||
| `street_view.h/.cpp` | `StreetViewPublish` |
|
||||
| `maps_key.h/.cpp` | `MapsKey`, `KeyRestrictions`, `ApiKeys` |
|
||||
| `tools/check_discovery.py` | Checks the table against the Discovery documents |
|
||||
|
||||
## 3. Static caps (see caps.h)
|
||||
|
||||
| Knob | Value |
|
||||
|---|---|
|
||||
| Field mask | 1..64 entries, 1024 chars, `[A-Za-z0-9_.]`; `*` only via `FieldMask::all()` |
|
||||
| Free text (query, address, input) | 512 chars |
|
||||
| Address lines | 30 |
|
||||
| Place types per filter | 50 |
|
||||
| Places per search page | 20 |
|
||||
| Route intermediates | 25 (documented) |
|
||||
| Route matrix | 25 origins, 25 destinations, 625 elements |
|
||||
| Elevation points | 512 (documented) |
|
||||
| Query value / rendered path | 2048 / 4096 chars |
|
||||
| Photo ids per batch | 100 |
|
||||
| Page size | 100 |
|
||||
| Pollen days | 5; air history hours 720 |
|
||||
| Places radius | 50000 m; solar data-layer radius 1000 m |
|
||||
| Tile zoom | 20 |
|
||||
| Photo size | 4800 px |
|
||||
|
||||
## 4. Contracts
|
||||
|
||||
- Every URL comes from the call table. A query parameter or a top-level body
|
||||
field not declared in the row, or a call used on the wrong API class, throws
|
||||
`GoogleError::invalid` before any traffic. Path variables are validated
|
||||
per segment (`[A-Za-z0-9._-]`, at most 512, no `..`, no empty segment).
|
||||
- Credentials: Maps endpoints have `prefer_key = true`, so a configured API key
|
||||
is used (header `x-goog-api-key`, never in the URL), else the OAuth
|
||||
credential. Street View Publish and API Keys are OAuth only. No credential:
|
||||
`NotConfiguredError` (503) before any traffic. A Vertex express key
|
||||
(`AQ.`) is not a Maps key; `MapsKey::looks_like_maps_key` says so.
|
||||
- Field masks: Places (New) and Routes refuse a request without a response
|
||||
field mask, and bill by it. It is a required, validated `FieldMask` argument
|
||||
sent as the `fields` system parameter (documented by Google as equivalent to
|
||||
the `X-Goog-FieldMask` header, because `GoogleClient` cannot set headers).
|
||||
- Geocoding, Time Zone and Elevation answer HTTP 200 with a `status` member on
|
||||
failure. `check_web_status` turns every status except `OK`, `ZERO_RESULTS`
|
||||
and `DATA_NOT_AVAILABLE` into `GoogleError` (REQUEST_DENIED and
|
||||
OVER_DAILY_LIMIT 403, OVER_QUERY_LIMIT 429, UNKNOWN_ERROR 502, else 400).
|
||||
- Dry run: `set_dry_run(true)` makes every call validate fully and return
|
||||
`{"dry_run":true,"method","host","path","body"}` instead of sending. The
|
||||
demo uses it for every route (all Maps requests are billed); tests use it to
|
||||
assert exact request shapes with no network and no credential.
|
||||
- Binary rows (GeoTIFF, heatmap tiles) return image bytes that the JSON client
|
||||
cannot carry; the classes expose the validated request path only. Photo
|
||||
media is requested with `skipHttpRedirect=true` and returns the `photoUri`.
|
||||
- Writes and deletes (Street View) are explicit methods with no defaults; the
|
||||
demo route is a dry run unless `?confirm=true`.
|
||||
- `KeyRestrictions` models Cloud API-key restrictions (one application
|
||||
restriction kind plus API targets) against the API Keys v2 `V2Restrictions`
|
||||
schema. `lint()` reports unrestricted keys, wildcard referrers and
|
||||
`0.0.0.0/0`. `ApiKeys` never reads `keyString`.
|
||||
|
||||
## 5. Example routes (`/google/maps`)
|
||||
|
||||
GET (2xx without a credential): `/google/maps` page, `/status`, `/calls`.
|
||||
POST (422 bad input, 503 `google_not_configured`, dry run unless
|
||||
`"confirm":"true"`): `/places/search`, `/places/nearby`, `/places/autocomplete`,
|
||||
`/places/details`, `/address/validate`, `/solar`, `/pollen`, `/air`, `/area`,
|
||||
`/routes`, `/geocode`, `/timezone`, `/elevation`, `/streetview/list`.
|
||||
DELETE `/streetview/photo/{id}` (dry run unless `?confirm=true`). POST
|
||||
`/keys/lint` is local (no credential, no Google call). Matrix row:
|
||||
`google-maps` (GET page only). Excluded from locust.
|
||||
|
||||
## Required APIs
|
||||
|
||||
Enable these on the project (placeholder project `example-214512124`). A disabled API answers 403 `SERVICE_DISABLED`. All bill per request except as noted by Google's pricing.
|
||||
|
||||
- `places.googleapis.com` (Places API (New)): https://console.developers.google.com/apis/api/places.googleapis.com/overview?project=example-214512124
|
||||
- `addressvalidation.googleapis.com`: https://console.developers.google.com/apis/api/addressvalidation.googleapis.com/overview?project=example-214512124
|
||||
- `solar.googleapis.com`: https://console.developers.google.com/apis/api/solar.googleapis.com/overview?project=example-214512124
|
||||
- `pollen.googleapis.com`: https://console.developers.google.com/apis/api/pollen.googleapis.com/overview?project=example-214512124
|
||||
- `airquality.googleapis.com`: https://console.developers.google.com/apis/api/airquality.googleapis.com/overview?project=example-214512124
|
||||
- `areainsights.googleapis.com`: https://console.developers.google.com/apis/api/areainsights.googleapis.com/overview?project=example-214512124
|
||||
- `routes.googleapis.com`: https://console.developers.google.com/apis/api/routes.googleapis.com/overview?project=example-214512124
|
||||
- `geocoding-backend.googleapis.com` (Geocoding API): https://console.developers.google.com/apis/api/geocoding-backend.googleapis.com/overview?project=example-214512124
|
||||
- `timezone-backend.googleapis.com` (Time Zone API): https://console.developers.google.com/apis/api/timezone-backend.googleapis.com/overview?project=example-214512124
|
||||
- `elevation-backend.googleapis.com` (Elevation API): https://console.developers.google.com/apis/api/elevation-backend.googleapis.com/overview?project=example-214512124
|
||||
- `streetviewpublish.googleapis.com`: https://console.developers.google.com/apis/api/streetviewpublish.googleapis.com/overview?project=example-214512124
|
||||
- `apikeys.googleapis.com` (API Keys, read-only listing; no billing): https://console.developers.google.com/apis/api/apikeys.googleapis.com/overview?project=example-214512124
|
||||
|
||||
Credential notes: Geocoding, Time Zone and Elevation need a real Maps API key
|
||||
(OAuth is refused, see Verified live). Street View Publish needs the OAuth
|
||||
scope `https://www.googleapis.com/auth/streetviewpublish`, which the
|
||||
`cloud-platform` service-account token does not carry. Service-account
|
||||
tokens work for the new-generation APIs (Places New, Routes, Address
|
||||
Validation, Solar, Pollen, Air Quality, Area Insights).
|
||||
|
||||
## Sources
|
||||
|
||||
Discovery documents (fetched 2026-10-25, no auth), which the call table is
|
||||
derived from and `tools/check_discovery.py` checks:
|
||||
|
||||
- `https://places.googleapis.com/$discovery/rest?version=v1`
|
||||
- `https://addressvalidation.googleapis.com/$discovery/rest?version=v1`
|
||||
- `https://solar.googleapis.com/$discovery/rest?version=v1`
|
||||
- `https://pollen.googleapis.com/$discovery/rest?version=v1`
|
||||
- `https://airquality.googleapis.com/$discovery/rest?version=v1`
|
||||
- `https://areainsights.googleapis.com/$discovery/rest?version=v1`
|
||||
- `https://streetviewpublish.googleapis.com/$discovery/rest?version=v1`
|
||||
- `https://apikeys.googleapis.com/$discovery/rest?version=v2`
|
||||
|
||||
No Discovery document exists (404 / 403 for `routes`, `geocode`,
|
||||
`geocoding-backend`, `timezone-backend`, `elevation-backend`,
|
||||
`mapsplatformdatasets`, `routeoptimization` on 2026-10-25), so these use the
|
||||
official reference, as read on 2026-10-25:
|
||||
|
||||
- Routes: `https://developers.google.com/maps/documentation/routes/reference/rest/v2/TopLevel/computeRoutes`
|
||||
(POST `https://routes.googleapis.com/directions/v2:computeRoutes`, request
|
||||
fields, field mask via `X-Goog-FieldMask` / `$fields` / `fields`) and the
|
||||
proto `https://raw.githubusercontent.com/googleapis/googleapis/master/google/maps/routing/v2/routes_service.proto`
|
||||
(`/directions/v2:computeRoutes`, `/distanceMatrix/v2:computeRouteMatrix`,
|
||||
`ComputeRouteMatrixRequest` fields).
|
||||
- Geocoding: `https://developers.google.com/maps/documentation/geocoding/requests-geocoding`
|
||||
(GET `https://maps.googleapis.com/maps/api/geocode/json`).
|
||||
- Time Zone: `https://developers.google.com/maps/documentation/timezone/requests-timezone`
|
||||
(GET `https://maps.googleapis.com/maps/api/timezone/json`).
|
||||
- Elevation: `https://developers.google.com/maps/documentation/elevation/requests-elevation`
|
||||
(GET `https://maps.googleapis.com/maps/api/elevation/json`, 512 points).
|
||||
- Semantics (enums, ranges, caps) of the Discovery APIs from the field
|
||||
descriptions inside the Discovery documents.
|
||||
|
||||
## Verified against discovery
|
||||
|
||||
2026-10-25: `python3 -I src/google/maps/tools/check_discovery.py` checks 33
|
||||
Discovery rows: rpc id, HTTP method, path, path variables, every query
|
||||
parameter (method or global system parameter such as `fields`), every top-level
|
||||
request field, and the API Keys restriction schemas. It also fails when a
|
||||
Discovery method of a covered API has no row (7 API Keys methods are excluded
|
||||
on purpose, listed in the script). Result: OK. 5 reference rows (Routes x2,
|
||||
Geocoding, Time Zone, Elevation) cannot be checked this way.
|
||||
|
||||
## Verified live
|
||||
|
||||
Project `lisa-448004`, service-account token (`cloud-platform`), 2026-10-25,
|
||||
`MOLO_LIVE_NET=1 MOLO_LIVE_PAID=1` (`tests/src/google/maps/test_maps_live.cpp`).
|
||||
Replies are Google's own:
|
||||
|
||||
- Service Usage state of all 12 Maps services: every one is `DISABLED` on the
|
||||
project (reported as `API NOT ENABLED`). `apikeys.googleapis.com` is also
|
||||
disabled (403 `SERVICE_DISABLED`).
|
||||
- One request per API with the OAuth token: Places (New) `searchText`,
|
||||
Address Validation, Solar, Pollen, Air Quality, Area Insights and Routes
|
||||
each answered 403 `PERMISSION_DENIED` "... API has not been used in project
|
||||
... or it is disabled". That proves route, host, OAuth acceptance and error
|
||||
mapping; it proves nothing about success response shapes. Nothing was
|
||||
enabled, created or billed.
|
||||
- Geocoding, Time Zone, Elevation with only an OAuth token: HTTP 200 with
|
||||
status `REQUEST_DENIED` "You must use an API key", mapped to `GoogleError` 403.
|
||||
So these three need a Maps key (none is available: the Vertex express key
|
||||
is not a Maps key).
|
||||
- Street View Publish `photos.list` with the `cloud-platform` token: 403
|
||||
"insufficient authentication scopes".
|
||||
|
||||
## Unverified
|
||||
|
||||
- Every success response shape of every API (`Place` parsing, `AddressVerdict`,
|
||||
`RouteSummary`, geocode / time zone / elevation parsing, matrix elements):
|
||||
no enabled API and no Maps key were available, so they are read from the
|
||||
Discovery schemas and the reference pages only. Parsers are tolerant and
|
||||
keep the raw document.
|
||||
- Routes: request and response shapes come from the reference page and proto,
|
||||
not Discovery (no document). `computeRouteMatrix` waypoint wrapping
|
||||
(`{"waypoint":{...}}`) is from the proto.
|
||||
- Geocoding / Time Zone / Elevation: the reference pages show the key as a
|
||||
`key` query parameter. This package sends it in the `x-goog-api-key`
|
||||
header; whether these legacy endpoints accept the header is unverified
|
||||
(no Maps key). If they do not, a key-in-query option is needed (gap).
|
||||
- The `fields` system parameter in place of the `X-Goog-FieldMask` header is
|
||||
documented for Places and Routes but was not seen to succeed (APIs disabled).
|
||||
- `routingPreference` only with DRIVE / TWO_WHEELER and `computeAlternativeRoutes`
|
||||
not with intermediates are rules taken from the reference descriptions.
|
||||
- Enum value lists for Routes (`travelMode`, `extraComputations`, `units`) are
|
||||
from the reference, not Discovery.
|
||||
- Street View Publish and API Keys calls other than the auth failure above.
|
||||
|
||||
## Gaps
|
||||
|
||||
- Binary downloads (GeoTIFF, heatmap tiles, Street View byte upload to
|
||||
`uploadUrl`, photo bytes) are not implemented: `GoogleClient` is JSON only.
|
||||
Owner: `src/google/client.*` (a raw-bytes call) plus a follow-up here.
|
||||
- No custom headers in `GoogleClient`: the field mask goes as `fields`, and a
|
||||
key-in-query mode for the legacy web services is not available. Owner:
|
||||
`src/google/client.*`.
|
||||
- No `X-Goog-User-Project` handling for OAuth calls.
|
||||
- Places: no Place Photos beyond `photo_uri`, no autocomplete session-token
|
||||
generator, no typed model for opening hours, reviews or EV data (raw Json is
|
||||
returned). Routes: no typed steps, tolls or traffic-on-polyline.
|
||||
- Not covered: Maps Static / Street View Static / Map Tiles, Geolocation,
|
||||
Roads, Route Optimization, Maps Datasets, Places Aggregate, API Keys
|
||||
mutations (see Scope).
|
||||
- The newer Geocoding v4 (`geocode.googleapis.com`) and Elevation v1 REST
|
||||
surfaces are not documented in the pages read; only the classic web service
|
||||
forms are implemented.
|
||||
- `api_catalog.*` and `APIS.md` do not list the 12 services above yet
|
||||
(integration step, see Required APIs).
|
||||
@@ -0,0 +1,92 @@
|
||||
#include "google/maps/address_validation.h"
|
||||
|
||||
#include "google/errors.h"
|
||||
#include "google/maps/caps.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
void PostalAddress::validate() const {
|
||||
if (region_code.size() != 2 && region_code.size() != 3)
|
||||
throw GoogleError::invalid("regionCode is required (CLDR, e.g. NL)");
|
||||
check_code(region_code, "regionCode");
|
||||
check_code(language_code, "languageCode");
|
||||
if (address_lines.empty()) throw GoogleError::invalid("at least one address line is required");
|
||||
check_count(address_lines.size(), MapsCaps::kMaxAddressLines, "address lines");
|
||||
for (const auto& l : address_lines) check_text(l, "address line");
|
||||
check_text(postal_code, "postalCode", false);
|
||||
check_text(administrative_area, "administrativeArea", false);
|
||||
check_text(locality, "locality", false);
|
||||
}
|
||||
|
||||
Json PostalAddress::to_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
o.set("regionCode", Json(region_code));
|
||||
if (!language_code.empty()) o.set("languageCode", Json(language_code));
|
||||
if (!postal_code.empty()) o.set("postalCode", Json(postal_code));
|
||||
if (!administrative_area.empty()) o.set("administrativeArea", Json(administrative_area));
|
||||
if (!locality.empty()) o.set("locality", Json(locality));
|
||||
Json lines = Json::array();
|
||||
for (const auto& l : address_lines) lines.push(Json(l));
|
||||
o.set("addressLines", lines);
|
||||
return o;
|
||||
}
|
||||
|
||||
void ValidateAddressRequest::validate() const {
|
||||
address.validate();
|
||||
check_text(previous_response_id, "previousResponseId", false);
|
||||
if (enable_usps_cass && address.region_code != "US" && address.region_code != "PR")
|
||||
throw GoogleError::invalid("enableUspsCass is for US and PR addresses only");
|
||||
}
|
||||
|
||||
Json ValidateAddressRequest::to_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
o.set("address", address.to_json());
|
||||
if (!previous_response_id.empty()) o.set("previousResponseId", Json(previous_response_id));
|
||||
if (enable_usps_cass) o.set("enableUspsCass", Json(true));
|
||||
return o;
|
||||
}
|
||||
|
||||
AddressVerdict AddressVerdict::from_json(const Json& doc) {
|
||||
AddressVerdict v;
|
||||
v.raw = doc;
|
||||
if (!doc.is_object()) return v;
|
||||
if (const Json* id = doc.find("responseId"); id && id->is_string()) v.response_id = id->as_string();
|
||||
const Json* r = doc.find("result");
|
||||
if (!r || !r->is_object()) return v;
|
||||
if (const Json* a = r->find("address"); a && a->is_object())
|
||||
if (const Json* f = a->find("formattedAddress"); f && f->is_string()) v.formatted_address = f->as_string();
|
||||
if (const Json* d = r->find("verdict"); d && d->is_object()) {
|
||||
if (const Json* c = d->find("addressComplete"); c && c->is_bool()) v.address_complete = c->as_bool();
|
||||
if (const Json* u = d->find("hasUnconfirmedComponents"); u && u->is_bool())
|
||||
v.has_unconfirmed_components = u->as_bool();
|
||||
if (const Json* g = d->find("validationGranularity"); g && g->is_string())
|
||||
v.validation_granularity = g->as_string();
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
AddressValidation::AddressValidation(std::shared_ptr<GoogleClient> client)
|
||||
: MapsService(std::move(client), Api::kAddressValidation) {}
|
||||
|
||||
Json AddressValidation::validate(const ValidateAddressRequest& r) const {
|
||||
Json body = r.to_json();
|
||||
return invoke(Call::kAddressValidate, {}, Query(), &body);
|
||||
}
|
||||
|
||||
Json AddressValidation::provide_feedback(const std::string& conclusion,
|
||||
const std::string& response_id) const {
|
||||
if (conclusion != "VALIDATED_VERSION_USED" && conclusion != "USER_VERSION_USED" &&
|
||||
conclusion != "UNVALIDATED_VERSION_USED" && conclusion != "UNUSED")
|
||||
throw GoogleError::invalid("unknown conclusion");
|
||||
check_text(response_id, "responseId");
|
||||
Json body = Json::object();
|
||||
body.set("conclusion", Json(conclusion));
|
||||
body.set("responseId", Json(response_id));
|
||||
return invoke(Call::kAddressFeedback, {}, Query(), &body);
|
||||
}
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
// Address Validation API: validateAddress and provideValidationFeedback.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "google/maps/maps_service.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
// A postal address (google.type.PostalAddress subset).
|
||||
struct PostalAddress {
|
||||
std::string region_code; // CLDR, required ("NL", "US")
|
||||
std::string language_code;
|
||||
std::string postal_code;
|
||||
std::string administrative_area;
|
||||
std::string locality;
|
||||
std::vector<std::string> address_lines; // at least one, <= 30
|
||||
void validate() const;
|
||||
clients::body::Json to_json() const;
|
||||
};
|
||||
|
||||
struct ValidateAddressRequest {
|
||||
PostalAddress address;
|
||||
std::string previous_response_id; // set when re-validating after a user fix
|
||||
bool enable_usps_cass = false; // US and PR only
|
||||
void validate() const;
|
||||
clients::body::Json to_json() const;
|
||||
};
|
||||
|
||||
// Tolerant view of the verdict.
|
||||
struct AddressVerdict {
|
||||
std::string response_id;
|
||||
std::string formatted_address;
|
||||
bool address_complete = false;
|
||||
bool has_unconfirmed_components = false;
|
||||
std::string validation_granularity;
|
||||
clients::body::Json raw;
|
||||
static AddressVerdict from_json(const clients::body::Json& doc);
|
||||
};
|
||||
|
||||
class AddressValidation : public MapsService {
|
||||
public:
|
||||
explicit AddressValidation(std::shared_ptr<GoogleClient> client);
|
||||
clients::body::Json validate(const ValidateAddressRequest& r) const;
|
||||
// conclusion: VALIDATED_VERSION_USED, USER_VERSION_USED,
|
||||
// UNVALIDATED_VERSION_USED or UNUSED. responseId is the first response id of
|
||||
// the session.
|
||||
clients::body::Json provide_feedback(const std::string& conclusion,
|
||||
const std::string& response_id) const;
|
||||
};
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,157 @@
|
||||
#include "google/maps/calls.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include "google/errors.h"
|
||||
#include "google/maps/caps.h"
|
||||
#include "google/resource.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
// CALLS-BEGIN (parsed by tools/check_discovery.py; one row per line)
|
||||
static const CallSpec kCalls[] = {
|
||||
{Call::kPlacesAutocomplete, Api::kPlaces, "POST", "v1/places:autocomplete", "places.places.autocomplete", "input,sessionToken,locationBias,locationRestriction,includedPrimaryTypes,includedRegionCodes,languageCode,regionCode,origin,inputOffset,includeQueryPredictions", "fields", "discovery"},
|
||||
{Call::kPlacesGet, Api::kPlaces, "GET", "v1/{+name}", "places.places.get", "", "languageCode,regionCode,sessionToken,fields", "discovery"},
|
||||
{Call::kPlacesSearchNearby, Api::kPlaces, "POST", "v1/places:searchNearby", "places.places.searchNearby", "locationRestriction,includedTypes,excludedTypes,includedPrimaryTypes,excludedPrimaryTypes,maxResultCount,languageCode,regionCode,rankPreference", "fields", "discovery"},
|
||||
{Call::kPlacesSearchText, Api::kPlaces, "POST", "v1/places:searchText", "places.places.searchText", "textQuery,includedType,strictTypeFiltering,openNow,minRating,priceLevels,locationBias,locationRestriction,pageSize,pageToken,languageCode,regionCode,rankPreference", "fields", "discovery"},
|
||||
{Call::kPlacesPhotoMedia, Api::kPlaces, "GET", "v1/{+name}", "places.places.photos.getMedia", "", "maxHeightPx,maxWidthPx,skipHttpRedirect", "discovery"},
|
||||
{Call::kAddressValidate, Api::kAddressValidation, "POST", "v1:validateAddress", "addressvalidation.validateAddress", "address,previousResponseId,enableUspsCass,languageOptions,sessionToken", "", "discovery"},
|
||||
{Call::kAddressFeedback, Api::kAddressValidation, "POST", "v1:provideValidationFeedback", "addressvalidation.provideValidationFeedback", "conclusion,responseId", "", "discovery"},
|
||||
{Call::kSolarBuildingInsights, Api::kSolar, "GET", "v1/buildingInsights:findClosest", "solar.buildingInsights.findClosest", "", "location.latitude,location.longitude,requiredQuality,exactQualityRequired", "discovery"},
|
||||
{Call::kSolarDataLayers, Api::kSolar, "GET", "v1/dataLayers:get", "solar.dataLayers.get", "", "location.latitude,location.longitude,radiusMeters,view,requiredQuality,pixelSizeMeters,exactQualityRequired", "discovery"},
|
||||
{Call::kSolarGeoTiff, Api::kSolar, "GET", "v1/geoTiff:get", "solar.geoTiff.get", "", "id", "discovery"},
|
||||
{Call::kPollenForecast, Api::kPollen, "GET", "v1/forecast:lookup", "pollen.forecast.lookup", "", "location.latitude,location.longitude,days,languageCode,pageSize,pageToken,plantsDescription", "discovery"},
|
||||
{Call::kPollenHeatmapTile, Api::kPollen, "GET", "v1/mapTypes/{mapType}/heatmapTiles/{zoom}/{x}/{y}", "pollen.mapTypes.heatmapTiles.lookupHeatmapTile", "", "", "discovery"},
|
||||
{Call::kAirForecast, Api::kAirQuality, "POST", "v1/forecast:lookup", "airquality.forecast.lookup", "location,dateTime,period,pageSize,pageToken,universalAqi,extraComputations,uaqiColorPalette,customLocalAqis,languageCode", "", "discovery"},
|
||||
{Call::kAirHeatmapTile, Api::kAirQuality, "GET", "v1/mapTypes/{mapType}/heatmapTiles/{zoom}/{x}/{y}", "airquality.mapTypes.heatmapTiles.lookupHeatmapTile", "", "", "discovery"},
|
||||
{Call::kAirHistory, Api::kAirQuality, "POST", "v1/history:lookup", "airquality.history.lookup", "location,hours,period,dateTime,pageSize,pageToken,universalAqi,extraComputations,uaqiColorPalette,customLocalAqis,languageCode", "", "discovery"},
|
||||
{Call::kAirCurrent, Api::kAirQuality, "POST", "v1/currentConditions:lookup", "airquality.currentConditions.lookup", "location,universalAqi,extraComputations,uaqiColorPalette,customLocalAqis,languageCode", "", "discovery"},
|
||||
{Call::kAreaComputeInsights, Api::kAreaInsights, "POST", "v1:computeInsights", "areainsights.computeInsights", "insights,filter", "", "discovery"},
|
||||
{Call::kRoutesCompute, Api::kRoutes, "POST", "directions/v2:computeRoutes", "ref:routes.computeRoutes", "origin,destination,intermediates,travelMode,routingPreference,polylineQuality,polylineEncoding,departureTime,arrivalTime,computeAlternativeRoutes,routeModifiers,languageCode,regionCode,units,optimizeWaypointOrder,requestedReferenceRoutes,extraComputations,trafficModel,transitPreferences", "fields", "reference"},
|
||||
{Call::kRoutesMatrix, Api::kRoutes, "POST", "distanceMatrix/v2:computeRouteMatrix", "ref:routes.computeRouteMatrix", "origins,destinations,travelMode,routingPreference,departureTime,arrivalTime,languageCode,regionCode,units,extraComputations,trafficModel,transitPreferences", "fields", "reference"},
|
||||
{Call::kGeocode, Api::kWebServices, "GET", "maps/api/geocode/json", "ref:geocoding.json", "", "address,components,bounds,language,region,latlng,place_id,result_type,location_type", "reference"},
|
||||
{Call::kTimeZone, Api::kWebServices, "GET", "maps/api/timezone/json", "ref:timezone.json", "", "location,timestamp,language", "reference"},
|
||||
{Call::kElevation, Api::kWebServices, "GET", "maps/api/elevation/json", "ref:elevation.json", "", "locations,path,samples", "reference"},
|
||||
{Call::kStreetPhotoSequences, Api::kStreetViewPublish, "GET", "v1/photoSequences", "streetviewpublish.photoSequences.list", "", "filter,pageSize,pageToken", "discovery"},
|
||||
{Call::kStreetPhotoStartUpload, Api::kStreetViewPublish, "POST", "v1/photo:startUpload", "streetviewpublish.photo.startUpload", "", "", "discovery"},
|
||||
{Call::kStreetPhotoGet, Api::kStreetViewPublish, "GET", "v1/photo/{photoId}", "streetviewpublish.photo.get", "", "view,languageCode", "discovery"},
|
||||
{Call::kStreetPhotoCreate, Api::kStreetViewPublish, "POST", "v1/photo", "streetviewpublish.photo.create", "uploadReference,pose,captureTime,places,connections", "", "discovery"},
|
||||
{Call::kStreetPhotoUpdate, Api::kStreetViewPublish, "PUT", "v1/photo/{id}", "streetviewpublish.photo.update", "photoId,pose,captureTime,places,connections", "updateMask", "discovery"},
|
||||
{Call::kStreetPhotoDelete, Api::kStreetViewPublish, "DELETE", "v1/photo/{photoId}", "streetviewpublish.photo.delete", "", "", "discovery"},
|
||||
{Call::kStreetSequenceGet, Api::kStreetViewPublish, "GET", "v1/photoSequence/{sequenceId}", "streetviewpublish.photoSequence.get", "", "view,filter", "discovery"},
|
||||
{Call::kStreetSequenceDelete, Api::kStreetViewPublish, "DELETE", "v1/photoSequence/{sequenceId}", "streetviewpublish.photoSequence.delete", "", "", "discovery"},
|
||||
{Call::kStreetSequenceCreate, Api::kStreetViewPublish, "POST", "v1/photoSequence", "streetviewpublish.photoSequence.create", "uploadReference,captureTimeOverride,filename", "inputType", "discovery"},
|
||||
{Call::kStreetSequenceStartUpload, Api::kStreetViewPublish, "POST", "v1/photoSequence:startUpload", "streetviewpublish.photoSequence.startUpload", "", "", "discovery"},
|
||||
{Call::kStreetPhotosBatchUpdate, Api::kStreetViewPublish, "POST", "v1/photos:batchUpdate", "streetviewpublish.photos.batchUpdate", "updatePhotoRequests", "", "discovery"},
|
||||
{Call::kStreetPhotosBatchDelete, Api::kStreetViewPublish, "POST", "v1/photos:batchDelete", "streetviewpublish.photos.batchDelete", "photoIds", "", "discovery"},
|
||||
{Call::kStreetPhotosList, Api::kStreetViewPublish, "GET", "v1/photos", "streetviewpublish.photos.list", "", "view,filter,pageSize,pageToken,languageCode", "discovery"},
|
||||
{Call::kStreetPhotosBatchGet, Api::kStreetViewPublish, "GET", "v1/photos:batchGet", "streetviewpublish.photos.batchGet", "", "photoIds,view,languageCode", "discovery"},
|
||||
{Call::kApiKeysList, Api::kApiKeys, "GET", "v2/{+parent}/keys", "apikeys.projects.locations.keys.list", "", "pageSize,pageToken,showDeleted", "discovery"},
|
||||
{Call::kApiKeysGet, Api::kApiKeys, "GET", "v2/{+name}", "apikeys.projects.locations.keys.get", "", "", "discovery"},
|
||||
};
|
||||
// CALLS-END
|
||||
|
||||
const CallSpec& spec_of(Call call) {
|
||||
for (const auto& s : kCalls)
|
||||
if (s.call == call) return s;
|
||||
throw GoogleError::invalid("unknown call");
|
||||
}
|
||||
|
||||
clients::Method method_of(Call call) {
|
||||
const char* m = spec_of(call).http_method;
|
||||
if (!std::strcmp(m, "GET")) return clients::Method::kGet;
|
||||
if (!std::strcmp(m, "POST")) return clients::Method::kPost;
|
||||
if (!std::strcmp(m, "PUT")) return clients::Method::kPut;
|
||||
if (!std::strcmp(m, "DELETE")) return clients::Method::kDelete;
|
||||
throw GoogleError::invalid("unknown http method");
|
||||
}
|
||||
|
||||
std::size_t call_count() { return sizeof(kCalls) / sizeof(kCalls[0]); }
|
||||
const CallSpec& spec_at(std::size_t index) {
|
||||
if (index >= call_count()) throw GoogleError::invalid("call index out of range");
|
||||
return kCalls[index];
|
||||
}
|
||||
|
||||
ServiceEndpoint endpoint_of(Api api) {
|
||||
switch (api) {
|
||||
case Api::kPlaces: return {"places", "https://places.googleapis.com", true};
|
||||
case Api::kAddressValidation:
|
||||
return {"addressvalidation", "https://addressvalidation.googleapis.com", true};
|
||||
case Api::kSolar: return {"solar", "https://solar.googleapis.com", true};
|
||||
case Api::kPollen: return {"pollen", "https://pollen.googleapis.com", true};
|
||||
case Api::kAirQuality: return {"airquality", "https://airquality.googleapis.com", true};
|
||||
case Api::kAreaInsights: return {"areainsights", "https://areainsights.googleapis.com", true};
|
||||
case Api::kRoutes: return {"routes", "https://routes.googleapis.com", true};
|
||||
case Api::kWebServices: return {"maps", "https://maps.googleapis.com", true};
|
||||
case Api::kStreetViewPublish:
|
||||
return {"streetviewpublish", "https://streetviewpublish.googleapis.com", false};
|
||||
case Api::kApiKeys: return {"apikeys", "https://apikeys.googleapis.com", false};
|
||||
}
|
||||
throw GoogleError::invalid("unknown api");
|
||||
}
|
||||
|
||||
bool in_list(const char* list, const std::string& name) {
|
||||
std::string cur;
|
||||
for (const char* p = list;; ++p) {
|
||||
if (*p == ',' || *p == '\0') {
|
||||
if (cur == name) return true;
|
||||
cur.clear();
|
||||
if (*p == '\0') return false;
|
||||
} else {
|
||||
cur += *p;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
// Photo references are longer than valid_segment's 128; same alphabet.
|
||||
bool long_segment(const std::string& id) {
|
||||
if (id.empty() || id.size() > 512 || id == "." || id == "..") return false;
|
||||
for (char c : id)
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||
c == '-' || c == '_' || c == '.'))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
bool valid_path_segment(const std::string& s, bool plus) {
|
||||
if (!plus) return valid_segment(s);
|
||||
// A resource name: "places/ChIJ..", "projects/p/locations/global/keys/k".
|
||||
if (s.empty() || s.size() > 512) return false;
|
||||
std::size_t start = 0;
|
||||
while (true) {
|
||||
std::size_t slash = s.find('/', start);
|
||||
std::string part = s.substr(start, slash == std::string::npos ? std::string::npos : slash - start);
|
||||
if (!long_segment(part)) return false;
|
||||
if (slash == std::string::npos) return true;
|
||||
start = slash + 1;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string render(Call call, const std::map<std::string, std::string>& vars) {
|
||||
std::string out = "/";
|
||||
const std::string path = spec_of(call).path;
|
||||
std::size_t used = 0;
|
||||
for (std::size_t i = 0; i < path.size();) {
|
||||
if (path[i] != '{') {
|
||||
out += path[i++];
|
||||
continue;
|
||||
}
|
||||
std::size_t close = path.find('}', i);
|
||||
std::string name = path.substr(i + 1, close - i - 1);
|
||||
bool plus = !name.empty() && name[0] == '+';
|
||||
if (plus) name = name.substr(1);
|
||||
auto it = vars.find(name);
|
||||
if (it == vars.end()) throw GoogleError::invalid("missing path variable " + name);
|
||||
if (!valid_path_segment(it->second, plus))
|
||||
throw GoogleError::invalid("bad value for path variable " + name);
|
||||
out += it->second;
|
||||
++used;
|
||||
i = close + 1;
|
||||
}
|
||||
if (used != vars.size()) throw GoogleError::invalid("unexpected path variable");
|
||||
if (out.size() > MapsCaps::kMaxPathChars) throw GoogleError::invalid("path too long");
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
|
||||
// The ONE table of REST calls this package makes. Rows with source
|
||||
// "discovery" are checked against Google's Discovery documents by
|
||||
// tools/check_discovery.py. Rows with source "reference" (Routes, Geocoding,
|
||||
// Time Zone, Elevation) have no Discovery document; they follow the official
|
||||
// reference pages / protos recorded in SPEC.md and are exercised live only.
|
||||
// Code builds every URL from this table, never from a literal.
|
||||
|
||||
#include <cstddef>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
#include "clients/request.h"
|
||||
#include "google/endpoints.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
enum class Api {
|
||||
kPlaces, kAddressValidation, kSolar, kPollen, kAirQuality, kAreaInsights,
|
||||
kRoutes, kWebServices, kStreetViewPublish, kApiKeys,
|
||||
};
|
||||
|
||||
enum class Call {
|
||||
kPlacesAutocomplete, kPlacesGet, kPlacesSearchNearby, kPlacesSearchText, kPlacesPhotoMedia,
|
||||
kAddressValidate, kAddressFeedback,
|
||||
kSolarBuildingInsights, kSolarDataLayers, kSolarGeoTiff,
|
||||
kPollenForecast, kPollenHeatmapTile,
|
||||
kAirForecast, kAirHeatmapTile, kAirHistory, kAirCurrent,
|
||||
kAreaComputeInsights,
|
||||
kRoutesCompute, kRoutesMatrix,
|
||||
kGeocode, kTimeZone, kElevation,
|
||||
kStreetPhotoSequences, kStreetPhotoStartUpload, kStreetPhotoGet, kStreetPhotoCreate,
|
||||
kStreetPhotoUpdate, kStreetPhotoDelete, kStreetSequenceGet, kStreetSequenceDelete,
|
||||
kStreetSequenceCreate, kStreetSequenceStartUpload, kStreetPhotosBatchUpdate,
|
||||
kStreetPhotosBatchDelete, kStreetPhotosList, kStreetPhotosBatchGet,
|
||||
kApiKeysList, kApiKeysGet,
|
||||
};
|
||||
|
||||
struct CallSpec {
|
||||
Call call;
|
||||
Api api;
|
||||
const char* http_method; // GET POST PUT DELETE
|
||||
const char* path; // "v1/{+name}" style, no leading slash
|
||||
const char* rpc_id; // discovery method id, or "ref:<name>" for reference rows
|
||||
const char* body_fields; // comma list: request body fields we send
|
||||
const char* query_params; // comma list: query parameters we send
|
||||
const char* source; // "discovery" or "reference"
|
||||
};
|
||||
|
||||
const CallSpec& spec_of(Call call);
|
||||
clients::Method method_of(Call call);
|
||||
std::size_t call_count();
|
||||
const CallSpec& spec_at(std::size_t index);
|
||||
|
||||
// Host and name of an API; a Service is built on it. Maps keys are the
|
||||
// documented credential, so every endpoint but the OAuth-only ones (Street
|
||||
// View Publish, API Keys) prefers the key.
|
||||
ServiceEndpoint endpoint_of(Api api);
|
||||
|
||||
// "/v1/places/ChIJ..": placeholders `{+x}` take a slash separated path of
|
||||
// segments, `{x}` a single segment; every segment is validated (valid_segment,
|
||||
// no ".."), every placeholder must be supplied and none may be extra.
|
||||
std::string render(Call call, const std::map<std::string, std::string>& vars = {});
|
||||
|
||||
// True when `name` is in the comma list.
|
||||
bool in_list(const char* list, const std::string& name);
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
// Static ceilings for the Maps Platform package. Never autotuned.
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
struct MapsCaps {
|
||||
static constexpr std::size_t kMaxFieldMaskChars = 1024;
|
||||
static constexpr std::size_t kMaxFieldMaskEntries = 64;
|
||||
static constexpr std::size_t kMaxTextChars = 512; // queries, addresses, inputs
|
||||
static constexpr std::size_t kMaxAddressLines = 30; // postal address lines
|
||||
static constexpr std::size_t kMaxTypes = 50; // place types per filter
|
||||
static constexpr std::size_t kMaxResultCount = 20; // places per search page
|
||||
static constexpr std::size_t kMaxPoints = 512; // elevation points, documented limit
|
||||
static constexpr std::size_t kMaxIntermediates = 25; // route waypoints, documented limit
|
||||
static constexpr std::size_t kMaxMatrixElements = 625; // origins x destinations per request
|
||||
static constexpr std::size_t kMaxMatrixSide = 25; // origins or destinations
|
||||
static constexpr std::size_t kMaxQueryValueChars = 2048; // one query value before encoding
|
||||
static constexpr std::size_t kMaxPathChars = 4096; // rendered request path
|
||||
static constexpr std::size_t kMaxIds = 100; // photo ids per batch
|
||||
static constexpr int kMaxPageSize = 100;
|
||||
static constexpr int kMaxForecastDays = 5; // pollen
|
||||
static constexpr int kMaxHistoryHours = 720; // air quality history
|
||||
static constexpr int kMaxRadiusMeters = 50000; // places radius
|
||||
static constexpr int kMaxSolarRadiusMeters = 1000; // data layers
|
||||
static constexpr int kMaxTileZoom = 20;
|
||||
static constexpr std::size_t kMaxKeys = 300; // API keys listed per project
|
||||
};
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,207 @@
|
||||
#include "google/maps/environment.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "google/errors.h"
|
||||
#include "google/maps/caps.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
namespace {
|
||||
void check_enum(const std::string& v, std::initializer_list<const char*> allowed, const char* what,
|
||||
bool allow_empty = true) {
|
||||
if (v.empty() && allow_empty) return;
|
||||
for (const char* a : allowed)
|
||||
if (v == a) return;
|
||||
throw GoogleError::invalid(std::string("unknown ") + what + ": " + v);
|
||||
}
|
||||
|
||||
Json string_array(const std::vector<std::string>& v, std::size_t max, const char* what) {
|
||||
check_count(v.size(), max, what);
|
||||
Json a = Json::array();
|
||||
for (const auto& s : v) {
|
||||
check_text(s, what);
|
||||
a.push(Json(s));
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
void check_extra(const std::vector<std::string>& extra) {
|
||||
for (const auto& e : extra)
|
||||
check_enum(e, {"LOCAL_AQI", "HEALTH_RECOMMENDATIONS", "POLLUTANT_ADDITIONAL_INFO",
|
||||
"DOMINANT_POLLUTANT_CONCENTRATION", "POLLUTANT_CONCENTRATION"},
|
||||
"extraComputation", false);
|
||||
check_count(extra.size(), 5, "extraComputations");
|
||||
}
|
||||
|
||||
Json air_body(const LatLng& at, const std::vector<std::string>& extra, const std::string& language) {
|
||||
check_extra(extra);
|
||||
check_code(language, "languageCode");
|
||||
Json b = Json::object();
|
||||
b.set("location", at.to_json());
|
||||
if (!extra.empty()) b.set("extraComputations", string_array(extra, 5, "extraComputations"));
|
||||
if (!language.empty()) b.set("languageCode", Json(language));
|
||||
return b;
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> tile_vars(const std::string& map_type, int zoom, int x, int y) {
|
||||
if (zoom < 0 || zoom > MapsCaps::kMaxTileZoom) throw GoogleError::invalid("zoom must be 0..20");
|
||||
long n = 1L << zoom;
|
||||
if (x < 0 || y < 0 || x >= n || y >= n) throw GoogleError::invalid("tile x / y outside the zoom grid");
|
||||
return {{"mapType", map_type}, {"zoom", std::to_string(zoom)}, {"x", std::to_string(x)},
|
||||
{"y", std::to_string(y)}};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Solar::Solar(std::shared_ptr<GoogleClient> client) : MapsService(std::move(client), Api::kSolar) {}
|
||||
|
||||
Json Solar::building_insights(const LatLng& at, const std::string& q) const {
|
||||
at.validate();
|
||||
check_enum(q, {"HIGH", "MEDIUM", "LOW", "BASE"}, "requiredQuality");
|
||||
Query query;
|
||||
query.add("location.latitude", at.lat).add("location.longitude", at.lng);
|
||||
if (!q.empty()) query.add("requiredQuality", q);
|
||||
return invoke(Call::kSolarBuildingInsights, {}, query);
|
||||
}
|
||||
|
||||
Json Solar::data_layers(const LatLng& at, int radius, const std::string& view, const std::string& q,
|
||||
double pixel) const {
|
||||
at.validate();
|
||||
if (radius < 1 || radius > MapsCaps::kMaxSolarRadiusMeters)
|
||||
throw GoogleError::invalid("radiusMeters must be 1..1000");
|
||||
check_enum(view, {"DSM_LAYER", "IMAGERY_LAYERS", "IMAGERY_AND_ANNUAL_FLUX_LAYERS",
|
||||
"IMAGERY_AND_ALL_FLUX_LAYERS", "FULL_LAYERS"}, "view");
|
||||
check_enum(q, {"HIGH", "MEDIUM", "LOW", "BASE"}, "requiredQuality");
|
||||
if (pixel != 0 && (pixel < 0.1 || pixel > 1.0)) throw GoogleError::invalid("pixelSizeMeters must be 0.1..1");
|
||||
Query query;
|
||||
query.add("location.latitude", at.lat).add("location.longitude", at.lng);
|
||||
query.add("radiusMeters", static_cast<double>(radius));
|
||||
if (!view.empty()) query.add("view", view);
|
||||
if (!q.empty()) query.add("requiredQuality", q);
|
||||
if (pixel != 0) query.add("pixelSizeMeters", pixel);
|
||||
return invoke(Call::kSolarDataLayers, {}, query);
|
||||
}
|
||||
|
||||
std::string Solar::geotiff_path(const std::string& id) const {
|
||||
check_text(id, "id");
|
||||
return path_for(Call::kSolarGeoTiff, {}, Query().add("id", id));
|
||||
}
|
||||
|
||||
Pollen::Pollen(std::shared_ptr<GoogleClient> client) : MapsService(std::move(client), Api::kPollen) {}
|
||||
|
||||
Json Pollen::forecast(const LatLng& at, int days, const std::string& language, bool plants) const {
|
||||
at.validate();
|
||||
if (days < 1 || days > MapsCaps::kMaxForecastDays) throw GoogleError::invalid("days must be 1..5");
|
||||
check_code(language, "languageCode");
|
||||
Query q;
|
||||
q.add("location.latitude", at.lat).add("location.longitude", at.lng).add("days", static_cast<long>(days));
|
||||
if (!language.empty()) q.add("languageCode", language);
|
||||
if (plants) q.add("plantsDescription", true);
|
||||
return invoke(Call::kPollenForecast, {}, q);
|
||||
}
|
||||
|
||||
std::string Pollen::heatmap_tile_path(const std::string& t, int zoom, int x, int y) const {
|
||||
check_enum(t, {"TREE_UPI", "GRASS_UPI", "WEED_UPI"}, "mapType", false);
|
||||
return path_for(Call::kPollenHeatmapTile, tile_vars(t, zoom, x, y), Query());
|
||||
}
|
||||
|
||||
AirQuality::AirQuality(std::shared_ptr<GoogleClient> client)
|
||||
: MapsService(std::move(client), Api::kAirQuality) {}
|
||||
|
||||
Json AirQuality::current(const LatLng& at, const std::vector<std::string>& extra,
|
||||
const std::string& language) const {
|
||||
Json b = air_body(at, extra, language);
|
||||
return invoke(Call::kAirCurrent, {}, Query(), &b);
|
||||
}
|
||||
|
||||
Json AirQuality::forecast(const LatLng& at, const std::string& date_time,
|
||||
const std::vector<std::string>& extra, const std::string& language,
|
||||
int page_size) const {
|
||||
check_text(date_time, "dateTime");
|
||||
if (page_size < 0 || page_size > MapsCaps::kMaxPageSize) throw GoogleError::invalid("pageSize must be 0..100");
|
||||
Json b = air_body(at, extra, language);
|
||||
b.set("dateTime", Json(date_time));
|
||||
if (page_size) b.set("pageSize", Json(page_size));
|
||||
return invoke(Call::kAirForecast, {}, Query(), &b);
|
||||
}
|
||||
|
||||
Json AirQuality::history(const LatLng& at, int hours, const std::vector<std::string>& extra,
|
||||
const std::string& language, int page_size) const {
|
||||
if (hours < 1 || hours > MapsCaps::kMaxHistoryHours) throw GoogleError::invalid("hours must be 1..720");
|
||||
if (page_size < 0 || page_size > MapsCaps::kMaxPageSize) throw GoogleError::invalid("pageSize must be 0..100");
|
||||
Json b = air_body(at, extra, language);
|
||||
b.set("hours", Json(hours));
|
||||
if (page_size) b.set("pageSize", Json(page_size));
|
||||
return invoke(Call::kAirHistory, {}, Query(), &b);
|
||||
}
|
||||
|
||||
std::string AirQuality::heatmap_tile_path(const std::string& t, int zoom, int x, int y) const {
|
||||
return path_for(Call::kAirHeatmapTile, tile_vars(t, zoom, x, y), Query());
|
||||
}
|
||||
|
||||
void InsightsFilter::validate() const {
|
||||
if (circle_center) {
|
||||
circle_center->validate();
|
||||
if (circle_radius_meters < 1 || circle_radius_meters > MapsCaps::kMaxRadiusMeters)
|
||||
throw GoogleError::invalid("radius must be 1..50000");
|
||||
if (!region_place.empty()) throw GoogleError::invalid("circle and region are exclusive");
|
||||
} else if (region_place.empty()) {
|
||||
throw GoogleError::invalid("a circle or a region is required");
|
||||
} else if (region_place.rfind("places/", 0) != 0) {
|
||||
throw GoogleError::invalid("region must be places/{id}");
|
||||
}
|
||||
check_count(included_types.size() + excluded_types.size(), MapsCaps::kMaxTypes, "types");
|
||||
if (min_rating < 0 || max_rating < 0 || min_rating > 5 || max_rating > 5 ||
|
||||
(max_rating > 0 && min_rating > max_rating))
|
||||
throw GoogleError::invalid("bad rating range");
|
||||
for (const auto& s : operating_status)
|
||||
check_enum(s, {"OPERATING_STATUS_OPERATIONAL", "OPERATING_STATUS_PERMANENTLY_CLOSED",
|
||||
"OPERATING_STATUS_TEMPORARILY_CLOSED"}, "operatingStatus", false);
|
||||
}
|
||||
|
||||
Json InsightsFilter::to_json() const {
|
||||
validate();
|
||||
Json f = Json::object();
|
||||
Json loc = Json::object();
|
||||
if (circle_center) {
|
||||
Json c = Json::object();
|
||||
c.set("latLng", circle_center->to_json());
|
||||
c.set("radius", Json(circle_radius_meters));
|
||||
loc.set("circle", c);
|
||||
} else {
|
||||
Json r = Json::object();
|
||||
r.set("place", Json(region_place));
|
||||
loc.set("region", r);
|
||||
}
|
||||
f.set("locationFilter", loc);
|
||||
if (!included_types.empty() || !excluded_types.empty()) {
|
||||
Json t = Json::object();
|
||||
if (!included_types.empty()) t.set("includedTypes", string_array(included_types, MapsCaps::kMaxTypes, "types"));
|
||||
if (!excluded_types.empty()) t.set("excludedTypes", string_array(excluded_types, MapsCaps::kMaxTypes, "types"));
|
||||
f.set("typeFilter", t);
|
||||
}
|
||||
if (!operating_status.empty()) f.set("operatingStatus", string_array(operating_status, 3, "operatingStatus"));
|
||||
if (min_rating > 0 || max_rating > 0) {
|
||||
Json r = Json::object();
|
||||
if (min_rating > 0) r.set("minRating", Json(min_rating));
|
||||
if (max_rating > 0) r.set("maxRating", Json(max_rating));
|
||||
f.set("ratingFilter", r);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
AreaInsights::AreaInsights(std::shared_ptr<GoogleClient> client)
|
||||
: MapsService(std::move(client), Api::kAreaInsights) {}
|
||||
|
||||
Json AreaInsights::compute(const std::vector<std::string>& insights, const InsightsFilter& filter) const {
|
||||
if (insights.empty()) throw GoogleError::invalid("at least one insight is required");
|
||||
for (const auto& i : insights) check_enum(i, {"INSIGHT_COUNT", "INSIGHT_PLACES"}, "insight", false);
|
||||
Json b = Json::object();
|
||||
b.set("insights", string_array(insights, 2, "insights"));
|
||||
b.set("filter", filter.to_json());
|
||||
return invoke(Call::kAreaComputeInsights, {}, Query(), &b);
|
||||
}
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
// Environment and location-insight APIs: Solar, Pollen, Air Quality, Area
|
||||
// Insights. Media rows (GeoTIFF, heatmap tiles) return binary bodies that
|
||||
// GoogleClient (JSON only) cannot carry, so those expose the validated
|
||||
// request path only (`*_path`); fetching the bytes is a gap listed in SPEC.
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "google/maps/maps_service.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
class Solar : public MapsService {
|
||||
public:
|
||||
explicit Solar(std::shared_ptr<GoogleClient> client);
|
||||
// quality: "", HIGH, MEDIUM, LOW, BASE (a lower floor widens coverage).
|
||||
clients::body::Json building_insights(const LatLng& at, const std::string& required_quality = "") const;
|
||||
// view: "" or DSM_LAYER, IMAGERY_LAYERS, IMAGERY_AND_ANNUAL_FLUX_LAYERS,
|
||||
// IMAGERY_AND_ALL_FLUX_LAYERS, FULL_LAYERS. radius 1..1000 m, pixel size
|
||||
// 0.1 (default) .. 1 m. Response lists GeoTIFF URLs; bytes are not fetched.
|
||||
clients::body::Json data_layers(const LatLng& at, int radius_meters, const std::string& view = "",
|
||||
const std::string& required_quality = "",
|
||||
double pixel_size_meters = 0) const;
|
||||
std::string geotiff_path(const std::string& id) const;
|
||||
};
|
||||
|
||||
class Pollen : public MapsService {
|
||||
public:
|
||||
explicit Pollen(std::shared_ptr<GoogleClient> client);
|
||||
clients::body::Json forecast(const LatLng& at, int days, const std::string& language = "",
|
||||
bool plants_description = false) const;
|
||||
// map_type TREE_UPI, GRASS_UPI, WEED_UPI.
|
||||
std::string heatmap_tile_path(const std::string& map_type, int zoom, int x, int y) const;
|
||||
};
|
||||
|
||||
class AirQuality : public MapsService {
|
||||
public:
|
||||
explicit AirQuality(std::shared_ptr<GoogleClient> client);
|
||||
// extra: LOCAL_AQI, HEALTH_RECOMMENDATIONS, POLLUTANT_ADDITIONAL_INFO,
|
||||
// DOMINANT_POLLUTANT_CONCENTRATION, POLLUTANT_CONCENTRATION.
|
||||
clients::body::Json current(const LatLng& at, const std::vector<std::string>& extra = {},
|
||||
const std::string& language = "") const;
|
||||
// date_time RFC 3339 ("2026-10-26T12:00:00Z"); hourly forecast up to 96 h ahead.
|
||||
clients::body::Json forecast(const LatLng& at, const std::string& date_time,
|
||||
const std::vector<std::string>& extra = {},
|
||||
const std::string& language = "", int page_size = 0) const;
|
||||
// hours 1..720 back from now.
|
||||
clients::body::Json history(const LatLng& at, int hours, const std::vector<std::string>& extra = {},
|
||||
const std::string& language = "", int page_size = 0) const;
|
||||
// map_type like US_AQI, UAQI_RED_GREEN, ... (validated as a segment).
|
||||
std::string heatmap_tile_path(const std::string& map_type, int zoom, int x, int y) const;
|
||||
};
|
||||
|
||||
struct InsightsFilter {
|
||||
std::optional<LatLng> circle_center;
|
||||
int circle_radius_meters = 0; // with center, 1..50000
|
||||
std::string region_place; // "places/ChIJ..." (alternative area)
|
||||
std::vector<std::string> included_types, excluded_types;
|
||||
std::vector<std::string> operating_status; // OPERATING_STATUS_OPERATIONAL, ...
|
||||
double min_rating = 0, max_rating = 0; // 0: unset
|
||||
void validate() const;
|
||||
clients::body::Json to_json() const;
|
||||
};
|
||||
|
||||
class AreaInsights : public MapsService {
|
||||
public:
|
||||
explicit AreaInsights(std::shared_ptr<GoogleClient> client);
|
||||
// insights: INSIGHT_COUNT and/or INSIGHT_PLACES.
|
||||
clients::body::Json compute(const std::vector<std::string>& insights, const InsightsFilter& filter) const;
|
||||
};
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,181 @@
|
||||
#include "google/maps/maps_key.h"
|
||||
|
||||
#include "clients/transports/http_transport.h"
|
||||
#include "google/credentials.h"
|
||||
#include "google/errors.h"
|
||||
#include "google/maps/caps.h"
|
||||
#include "google/resource.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
MapsKey::MapsKey(std::string key) : key_(std::move(key)) {}
|
||||
|
||||
MapsKey MapsKey::from_env() {
|
||||
std::string k = Credentials::env("GOOGLE_MAPS_API_KEY");
|
||||
if (k.empty()) k = Credentials::env("GOOGLE_API_KEY");
|
||||
return MapsKey(k);
|
||||
}
|
||||
|
||||
bool MapsKey::looks_like_maps_key() const {
|
||||
if (key_.size() != 39 || key_.compare(0, 4, "AIza") != 0) return false;
|
||||
for (char c : key_)
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_'))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string MapsKey::redacted() const {
|
||||
if (key_.empty()) return "";
|
||||
if (key_.size() <= 12) return "****";
|
||||
return key_.substr(0, 4) + "..." + key_.substr(key_.size() - 4);
|
||||
}
|
||||
|
||||
std::shared_ptr<GoogleClient> MapsKey::make_client() const {
|
||||
if (key_.empty()) return std::make_shared<GoogleClient>(std::make_unique<clients::transports::HttpTransport>(), nullptr);
|
||||
return std::make_shared<GoogleClient>(std::make_unique<clients::transports::HttpTransport>(),
|
||||
Credentials::api_key(key_), nullptr);
|
||||
}
|
||||
|
||||
namespace {
|
||||
Json strings(const std::vector<std::string>& v) {
|
||||
Json a = Json::array();
|
||||
for (const auto& s : v) a.push(Json(s));
|
||||
return a;
|
||||
}
|
||||
void check_list(const std::vector<std::string>& v, const char* what) {
|
||||
check_count(v.size(), 50, what);
|
||||
for (const auto& s : v) check_text(s, what);
|
||||
}
|
||||
std::vector<std::string> read_strings(const Json* a) {
|
||||
std::vector<std::string> out;
|
||||
if (a && a->is_array())
|
||||
for (const auto& e : a->as_array())
|
||||
if (e.is_string()) out.push_back(e.as_string());
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void KeyRestrictions::validate() const {
|
||||
int kinds = (allowed_referrers.empty() ? 0 : 1) + (allowed_ips.empty() ? 0 : 1) +
|
||||
(allowed_bundle_ids.empty() ? 0 : 1) + (android_apps.empty() ? 0 : 1);
|
||||
if (kinds > 1) throw GoogleError::invalid("only one application restriction kind per key");
|
||||
check_list(allowed_referrers, "referrer");
|
||||
check_list(allowed_ips, "ip");
|
||||
check_list(allowed_bundle_ids, "bundle id");
|
||||
check_list(api_services, "api service");
|
||||
check_count(android_apps.size(), 50, "android apps");
|
||||
for (const auto& [pkg, sha] : android_apps) {
|
||||
check_text(pkg, "android package");
|
||||
check_text(sha, "android sha1 fingerprint");
|
||||
}
|
||||
for (const auto& s : api_services)
|
||||
if (s.size() < 4 || s.find(".googleapis.com") == std::string::npos)
|
||||
throw GoogleError::invalid("api service must be a *.googleapis.com name: " + s);
|
||||
}
|
||||
|
||||
Json KeyRestrictions::to_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
if (!allowed_referrers.empty()) {
|
||||
Json b = Json::object();
|
||||
b.set("allowedReferrers", strings(allowed_referrers));
|
||||
o.set("browserKeyRestrictions", b);
|
||||
}
|
||||
if (!allowed_ips.empty()) {
|
||||
Json s = Json::object();
|
||||
s.set("allowedIps", strings(allowed_ips));
|
||||
o.set("serverKeyRestrictions", s);
|
||||
}
|
||||
if (!allowed_bundle_ids.empty()) {
|
||||
Json i = Json::object();
|
||||
i.set("allowedBundleIds", strings(allowed_bundle_ids));
|
||||
o.set("iosKeyRestrictions", i);
|
||||
}
|
||||
if (!android_apps.empty()) {
|
||||
Json apps = Json::array();
|
||||
for (const auto& [pkg, sha] : android_apps) {
|
||||
Json a = Json::object();
|
||||
a.set("packageName", Json(pkg));
|
||||
a.set("sha1Fingerprint", Json(sha));
|
||||
apps.push(a);
|
||||
}
|
||||
Json a = Json::object();
|
||||
a.set("allowedApplications", apps);
|
||||
o.set("androidKeyRestrictions", a);
|
||||
}
|
||||
if (!api_services.empty()) {
|
||||
Json targets = Json::array();
|
||||
for (const auto& s : api_services) {
|
||||
Json t = Json::object();
|
||||
t.set("service", Json(s));
|
||||
targets.push(t);
|
||||
}
|
||||
o.set("apiTargets", targets);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
std::vector<std::string> KeyRestrictions::lint() const {
|
||||
std::vector<std::string> f;
|
||||
if (allowed_referrers.empty() && allowed_ips.empty() && allowed_bundle_ids.empty() && android_apps.empty())
|
||||
f.push_back("no application restriction: anyone holding the key can use it");
|
||||
if (api_services.empty()) f.push_back("no API restriction: the key works for every enabled API");
|
||||
for (const auto& r : allowed_referrers)
|
||||
if (r == "*" || r == "*/*") f.push_back("referrer '" + r + "' allows every website");
|
||||
for (const auto& ip : allowed_ips)
|
||||
if (ip == "0.0.0.0/0" || ip == "::/0") f.push_back("ip '" + ip + "' allows every address");
|
||||
return f;
|
||||
}
|
||||
|
||||
KeyRestrictions KeyRestrictions::from_json(const Json& r) {
|
||||
KeyRestrictions k;
|
||||
if (!r.is_object()) return k;
|
||||
if (const Json* b = r.find("browserKeyRestrictions")) k.allowed_referrers = read_strings(b->find("allowedReferrers"));
|
||||
if (const Json* s = r.find("serverKeyRestrictions")) k.allowed_ips = read_strings(s->find("allowedIps"));
|
||||
if (const Json* i = r.find("iosKeyRestrictions")) k.allowed_bundle_ids = read_strings(i->find("allowedBundleIds"));
|
||||
if (const Json* a = r.find("androidKeyRestrictions"))
|
||||
if (const Json* apps = a->find("allowedApplications"); apps && apps->is_array())
|
||||
for (const auto& e : apps->as_array()) {
|
||||
const Json* p = e.find("packageName");
|
||||
const Json* s = e.find("sha1Fingerprint");
|
||||
k.android_apps.emplace_back(p && p->is_string() ? p->as_string() : "",
|
||||
s && s->is_string() ? s->as_string() : "");
|
||||
}
|
||||
if (const Json* t = r.find("apiTargets"); t && t->is_array())
|
||||
for (const auto& e : t->as_array())
|
||||
if (const Json* s = e.find("service"); s && s->is_string()) k.api_services.push_back(s->as_string());
|
||||
return k;
|
||||
}
|
||||
|
||||
ApiKeys::ApiKeys(std::shared_ptr<GoogleClient> client) : MapsService(std::move(client), Api::kApiKeys) {}
|
||||
|
||||
Json ApiKeys::list(const std::string& project, int page_size, const std::string& page_token) const {
|
||||
if (page_size < 0 || page_size > MapsCaps::kMaxPageSize) throw GoogleError::invalid("pageSize must be 0..100");
|
||||
if (!valid_segment(project)) throw GoogleError::invalid("project is empty or has invalid characters");
|
||||
Query q;
|
||||
if (page_size) q.add("pageSize", static_cast<long>(page_size));
|
||||
if (!page_token.empty()) q.add("pageToken", page_token);
|
||||
return invoke(Call::kApiKeysList, {{"parent", "projects/" + project + "/locations/global"}}, q);
|
||||
}
|
||||
|
||||
Json ApiKeys::get(const std::string& key_name) const {
|
||||
if (key_name.rfind("projects/", 0) != 0 || key_name.find("/locations/global/keys/") == std::string::npos)
|
||||
throw GoogleError::invalid("key name must be projects/{p}/locations/global/keys/{uid}");
|
||||
return invoke(Call::kApiKeysGet, {{"name", key_name}}, Query());
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, KeyRestrictions>> ApiKeys::restrictions_of(const Json& list) {
|
||||
std::vector<std::pair<std::string, KeyRestrictions>> out;
|
||||
const Json* keys = list.is_object() ? list.find("keys") : nullptr;
|
||||
if (!keys || !keys->is_array()) return out;
|
||||
for (const auto& k : keys->as_array()) {
|
||||
const Json* n = k.find("name");
|
||||
const Json* r = k.find("restrictions");
|
||||
out.emplace_back(n && n->is_string() ? n->as_string() : "", r ? KeyRestrictions::from_json(*r) : KeyRestrictions());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
// Maps Platform API-key handling. A Maps key is a Cloud API key restricted by
|
||||
// application (referrer / IP / Android / iOS) and by API target.
|
||||
// - MapsKey: env lookup (GOOGLE_MAPS_API_KEY, else GOOGLE_API_KEY), shape
|
||||
// check, redaction, and a GoogleClient that sends it in x-goog-api-key.
|
||||
// - KeyRestrictions: a local description of a key's restrictions, validated
|
||||
// against the API Keys v2 schema (V2Restrictions), with a safety lint
|
||||
// (an unrestricted key is reported).
|
||||
// - ApiKeys: read-only list and get through the API Keys API (OAuth). The
|
||||
// secret key string is never read: getKeyString is deliberately absent.
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
#include "google/maps/maps_service.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
class MapsKey {
|
||||
public:
|
||||
explicit MapsKey(std::string key = "");
|
||||
// GOOGLE_MAPS_API_KEY, else GOOGLE_API_KEY (process env, .env.json.local, .env.json).
|
||||
static MapsKey from_env();
|
||||
bool present() const { return !key_.empty(); }
|
||||
// Classic Cloud API keys are "AIza" + 35 URL-safe characters. Vertex express
|
||||
// keys ("AQ.") are a different credential and are NOT Maps keys.
|
||||
bool looks_like_maps_key() const;
|
||||
// "AIza...wxyz" style: first 4 and last 4 only; "" when absent.
|
||||
std::string redacted() const;
|
||||
// Never exposes the key; a client that sends it as x-goog-api-key.
|
||||
std::shared_ptr<GoogleClient> make_client() const;
|
||||
|
||||
private:
|
||||
std::string key_;
|
||||
};
|
||||
|
||||
struct KeyRestrictions {
|
||||
std::vector<std::string> allowed_referrers; // browser keys, e.g. "https://*.example.com/*"
|
||||
std::vector<std::string> allowed_ips; // server keys, IPv4/IPv6/CIDR
|
||||
std::vector<std::string> allowed_bundle_ids; // iOS
|
||||
std::vector<std::pair<std::string, std::string>> android_apps; // Android: (package, sha1 fingerprint)
|
||||
std::vector<std::string> api_services; // apiTargets[].service, e.g. "places.googleapis.com"
|
||||
void validate() const;
|
||||
// V2Restrictions document. Only one application restriction kind is allowed.
|
||||
clients::body::Json to_json() const;
|
||||
// Findings that make a key unsafe to ship ("no application restriction", ...).
|
||||
std::vector<std::string> lint() const;
|
||||
static KeyRestrictions from_json(const clients::body::Json& restrictions);
|
||||
};
|
||||
|
||||
class ApiKeys : public MapsService {
|
||||
public:
|
||||
explicit ApiKeys(std::shared_ptr<GoogleClient> client);
|
||||
// project like "my-project" or "123456"; location is always global.
|
||||
clients::body::Json list(const std::string& project, int page_size = 0,
|
||||
const std::string& page_token = "") const;
|
||||
// Key resource name "projects/{p}/locations/global/keys/{uid}".
|
||||
clients::body::Json get(const std::string& key_name) const;
|
||||
// The restrictions of a listed key, as local value.
|
||||
static std::vector<std::pair<std::string, KeyRestrictions>> restrictions_of(const clients::body::Json& list);
|
||||
};
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,66 @@
|
||||
#include "google/maps/maps_service.h"
|
||||
|
||||
#include "google/errors.h"
|
||||
#include "google/maps/caps.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
MapsService::MapsService(std::shared_ptr<GoogleClient> client, Api api)
|
||||
: Service(std::move(client), endpoint_of(api)), api_(api) {}
|
||||
|
||||
std::string MapsService::path_for(Call call, const std::map<std::string, std::string>& vars,
|
||||
const Query& query, const Json* body) const {
|
||||
const CallSpec& spec = spec_of(call);
|
||||
if (spec.api != api_) throw GoogleError::invalid("call does not belong to this API");
|
||||
for (const auto& [name, value] : query.items()) {
|
||||
(void)value;
|
||||
if (!in_list(spec.query_params, name))
|
||||
throw GoogleError::invalid("query parameter not declared for this call: " + name);
|
||||
}
|
||||
if (body) {
|
||||
if (!body->is_object()) throw GoogleError::invalid("request body must be an object");
|
||||
for (const auto& [name, value] : body->as_object()) {
|
||||
(void)value;
|
||||
if (!in_list(spec.body_fields, name))
|
||||
throw GoogleError::invalid("request field not declared for this call: " + name);
|
||||
}
|
||||
}
|
||||
std::string path = render(call, vars) + query.encode();
|
||||
if (path.size() > MapsCaps::kMaxPathChars) throw GoogleError::invalid("request path too long");
|
||||
return path;
|
||||
}
|
||||
|
||||
Json MapsService::invoke(Call call, const std::map<std::string, std::string>& vars,
|
||||
const Query& query, const Json* body) const {
|
||||
std::string path = path_for(call, vars, query, body);
|
||||
if (dry_run_) {
|
||||
Json d = Json::object();
|
||||
d.set("dry_run", Json(true));
|
||||
d.set("method", Json(spec_of(call).http_method));
|
||||
d.set("host", Json(endpoint_.base_url));
|
||||
d.set("path", Json(path));
|
||||
d.set("body", body ? *body : Json());
|
||||
return d;
|
||||
}
|
||||
return client_->request(method_of(call), endpoint_, path, body);
|
||||
}
|
||||
|
||||
void MapsService::check_web_status(const Json& doc, const std::string& service) {
|
||||
if (doc.is_object() && doc.has("dry_run")) return;
|
||||
const Json* st = doc.is_object() ? doc.find("status") : nullptr;
|
||||
if (!st || !st->is_string()) throw GoogleError(502, "BAD_RESPONSE", "missing status member", service);
|
||||
const std::string& s = st->as_string();
|
||||
if (s == "OK" || s == "ZERO_RESULTS" || s == "DATA_NOT_AVAILABLE") return;
|
||||
std::string msg = s;
|
||||
for (const char* key : {"error_message", "errorMessage"})
|
||||
if (const Json* m = doc.find(key); m && m->is_string()) msg += ": " + m->as_string();
|
||||
int http = 400;
|
||||
if (s == "REQUEST_DENIED" || s == "OVER_DAILY_LIMIT") http = 403;
|
||||
else if (s == "OVER_QUERY_LIMIT") http = 429;
|
||||
else if (s == "UNKNOWN_ERROR") http = 502;
|
||||
throw GoogleError(http, s, msg, service);
|
||||
}
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
// Base of every Maps API class: runs one row of the call table. Validates the
|
||||
// call belongs to the API, the query parameters and the top-level body fields
|
||||
// against the row, and renders the path, all before any network traffic.
|
||||
// Reference-only web services (Geocoding, Time Zone, Elevation) answer HTTP
|
||||
// 200 with a "status" member on failure; check_web_status() turns that into a
|
||||
// GoogleError so failures are loud.
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
#include "google/maps/calls.h"
|
||||
#include "google/maps/types.h"
|
||||
#include "google/service.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
class MapsService : public Service {
|
||||
public:
|
||||
MapsService(std::shared_ptr<GoogleClient> client, Api api);
|
||||
Api api() const { return api_; }
|
||||
// Dry run: invoke() validates everything, then returns
|
||||
// {"dry_run":true,"method","path","body"} instead of sending. Used by the
|
||||
// demo for paid calls and by tests to see the exact request without any
|
||||
// network traffic or credential.
|
||||
void set_dry_run(bool on) { dry_run_ = on; }
|
||||
bool dry_run() const { return dry_run_; }
|
||||
|
||||
protected:
|
||||
// vars: path variables. query: validated against the row. body: null for
|
||||
// none, else an object whose keys must be declared in the row.
|
||||
clients::body::Json invoke(Call call, const std::map<std::string, std::string>& vars,
|
||||
const Query& query, const clients::body::Json* body = nullptr) const;
|
||||
// The request path (with query) without sending; used by tests and media rows.
|
||||
std::string path_for(Call call, const std::map<std::string, std::string>& vars,
|
||||
const Query& query, const clients::body::Json* body = nullptr) const;
|
||||
|
||||
// Geocoding / Time Zone / Elevation: status OK passes; ZERO_RESULTS and
|
||||
// DATA_NOT_AVAILABLE pass (an answer); everything else throws.
|
||||
static void check_web_status(const clients::body::Json& doc, const std::string& service);
|
||||
|
||||
private:
|
||||
Api api_;
|
||||
bool dry_run_ = false;
|
||||
};
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,217 @@
|
||||
#include "google/maps/places.h"
|
||||
|
||||
#include "google/errors.h"
|
||||
#include "google/maps/caps.h"
|
||||
#include "google/resource.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
namespace {
|
||||
Json strings(const std::vector<std::string>& v, std::size_t max, const char* what) {
|
||||
check_count(v.size(), max, what);
|
||||
Json a = Json::array();
|
||||
for (const auto& s : v) {
|
||||
check_text(s, what);
|
||||
a.push(Json(s));
|
||||
}
|
||||
return a;
|
||||
}
|
||||
void put(Json& o, const char* key, const std::string& v) {
|
||||
if (!v.empty()) o.set(key, Json(v));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void LocationArea::validate(bool restriction) const {
|
||||
if (center) {
|
||||
center->validate();
|
||||
if (!(radius_meters > 0) || radius_meters > MapsCaps::kMaxRadiusMeters)
|
||||
throw GoogleError::invalid("radius must be in (0, 50000]");
|
||||
if (low || high) throw GoogleError::invalid("circle and rectangle are exclusive");
|
||||
return;
|
||||
}
|
||||
if (!low || !high) throw GoogleError::invalid("area needs a circle or a rectangle");
|
||||
low->validate();
|
||||
high->validate();
|
||||
(void)restriction;
|
||||
}
|
||||
|
||||
Json LocationArea::to_json(bool restriction) const {
|
||||
validate(restriction);
|
||||
Json o = Json::object();
|
||||
if (center) {
|
||||
Json c = Json::object();
|
||||
c.set("center", center->to_json());
|
||||
c.set("radius", Json(radius_meters));
|
||||
o.set("circle", c);
|
||||
} else {
|
||||
Json r = Json::object();
|
||||
r.set("low", low->to_json());
|
||||
r.set("high", high->to_json());
|
||||
o.set("rectangle", r);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
void AutocompleteRequest::validate() const {
|
||||
check_text(input, "input");
|
||||
check_text(session_token, "sessionToken", false);
|
||||
check_code(language_code, "languageCode");
|
||||
check_code(region_code, "regionCode");
|
||||
if (bias) bias->validate(false);
|
||||
}
|
||||
|
||||
Json AutocompleteRequest::to_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
o.set("input", Json(input));
|
||||
put(o, "sessionToken", session_token);
|
||||
if (bias) o.set("locationBias", bias->to_json(false));
|
||||
if (!included_primary_types.empty())
|
||||
o.set("includedPrimaryTypes", strings(included_primary_types, 5, "primary types"));
|
||||
if (!included_region_codes.empty())
|
||||
o.set("includedRegionCodes", strings(included_region_codes, 15, "region codes"));
|
||||
put(o, "languageCode", language_code);
|
||||
put(o, "regionCode", region_code);
|
||||
if (include_query_predictions) o.set("includeQueryPredictions", Json(true));
|
||||
return o;
|
||||
}
|
||||
|
||||
void SearchTextRequest::validate() const {
|
||||
check_text(text_query, "textQuery");
|
||||
check_text(included_type, "includedType", false);
|
||||
check_text(page_token, "pageToken", false);
|
||||
if (min_rating < 0 || min_rating > 5) throw GoogleError::invalid("minRating must be in [0, 5]");
|
||||
if (page_size < 0 || page_size > static_cast<int>(MapsCaps::kMaxResultCount))
|
||||
throw GoogleError::invalid("pageSize must be 0..20");
|
||||
if (bias && restriction) throw GoogleError::invalid("bias and restriction are exclusive");
|
||||
if (bias) bias->validate(false);
|
||||
if (restriction) {
|
||||
restriction->validate(true);
|
||||
if (restriction->center) throw GoogleError::invalid("text search restriction must be a rectangle");
|
||||
}
|
||||
check_code(language_code, "languageCode");
|
||||
check_code(region_code, "regionCode");
|
||||
}
|
||||
|
||||
Json SearchTextRequest::to_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
o.set("textQuery", Json(text_query));
|
||||
put(o, "includedType", included_type);
|
||||
if (open_now) o.set("openNow", Json(true));
|
||||
if (min_rating > 0) o.set("minRating", Json(min_rating));
|
||||
if (page_size > 0) o.set("pageSize", Json(page_size));
|
||||
put(o, "pageToken", page_token);
|
||||
if (bias) o.set("locationBias", bias->to_json(false));
|
||||
if (restriction) o.set("locationRestriction", restriction->to_json(true));
|
||||
put(o, "languageCode", language_code);
|
||||
put(o, "regionCode", region_code);
|
||||
return o;
|
||||
}
|
||||
|
||||
void SearchNearbyRequest::validate() const {
|
||||
restriction.validate(true);
|
||||
if (!restriction.center) throw GoogleError::invalid("nearby search restriction must be a circle");
|
||||
if (max_result_count < 0 || max_result_count > static_cast<int>(MapsCaps::kMaxResultCount))
|
||||
throw GoogleError::invalid("maxResultCount must be 0..20");
|
||||
if (!rank_preference.empty() && rank_preference != "POPULARITY" && rank_preference != "DISTANCE")
|
||||
throw GoogleError::invalid("rankPreference must be POPULARITY or DISTANCE");
|
||||
check_code(language_code, "languageCode");
|
||||
check_code(region_code, "regionCode");
|
||||
}
|
||||
|
||||
Json SearchNearbyRequest::to_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
o.set("locationRestriction", restriction.to_json(true));
|
||||
if (!included_types.empty()) o.set("includedTypes", strings(included_types, MapsCaps::kMaxTypes, "types"));
|
||||
if (!excluded_types.empty()) o.set("excludedTypes", strings(excluded_types, MapsCaps::kMaxTypes, "types"));
|
||||
if (max_result_count > 0) o.set("maxResultCount", Json(max_result_count));
|
||||
put(o, "languageCode", language_code);
|
||||
put(o, "regionCode", region_code);
|
||||
put(o, "rankPreference", rank_preference);
|
||||
return o;
|
||||
}
|
||||
|
||||
Place Place::from_json(const Json& doc) {
|
||||
Place p;
|
||||
p.raw = doc;
|
||||
if (!doc.is_object()) return p;
|
||||
auto str = [&](const char* k) {
|
||||
const Json* v = doc.find(k);
|
||||
return v && v->is_string() ? v->as_string() : std::string();
|
||||
};
|
||||
p.id = str("id");
|
||||
p.name = str("name");
|
||||
p.formatted_address = str("formattedAddress");
|
||||
if (const Json* d = doc.find("displayName"); d && d->is_object())
|
||||
if (const Json* t = d->find("text"); t && t->is_string()) p.display_name = t->as_string();
|
||||
if (const Json* l = doc.find("location"); l && l->is_object()) {
|
||||
const Json* la = l->find("latitude");
|
||||
const Json* lo = l->find("longitude");
|
||||
if (la && lo && la->is_number() && lo->is_number()) p.location = LatLng{la->as_number(), lo->as_number()};
|
||||
}
|
||||
if (const Json* t = doc.find("types"); t && t->is_array())
|
||||
for (const auto& e : t->as_array())
|
||||
if (e.is_string()) p.types.push_back(e.as_string());
|
||||
return p;
|
||||
}
|
||||
|
||||
Places::Places(std::shared_ptr<GoogleClient> client) : MapsService(std::move(client), Api::kPlaces) {}
|
||||
|
||||
std::string Places::resource_name(const std::string& place_id) {
|
||||
if (place_id.rfind("places/", 0) == 0) return place_id;
|
||||
return "places/" + place_id;
|
||||
}
|
||||
|
||||
Json Places::autocomplete(const AutocompleteRequest& r) const {
|
||||
Json body = r.to_json();
|
||||
return invoke(Call::kPlacesAutocomplete, {}, Query(), &body);
|
||||
}
|
||||
|
||||
Json Places::search_text(const SearchTextRequest& r, const FieldMask& mask) const {
|
||||
Json body = r.to_json();
|
||||
return invoke(Call::kPlacesSearchText, {}, Query().add("fields", mask.str()), &body);
|
||||
}
|
||||
|
||||
Json Places::search_nearby(const SearchNearbyRequest& r, const FieldMask& mask) const {
|
||||
Json body = r.to_json();
|
||||
return invoke(Call::kPlacesSearchNearby, {}, Query().add("fields", mask.str()), &body);
|
||||
}
|
||||
|
||||
Json Places::get(const std::string& place_id, const FieldMask& mask, const std::string& language,
|
||||
const std::string& region, const std::string& session_token) const {
|
||||
check_code(language, "languageCode");
|
||||
check_code(region, "regionCode");
|
||||
Query q;
|
||||
q.add("fields", mask.str());
|
||||
if (!language.empty()) q.add("languageCode", language);
|
||||
if (!region.empty()) q.add("regionCode", region);
|
||||
if (!session_token.empty()) q.add("sessionToken", session_token);
|
||||
return invoke(Call::kPlacesGet, {{"name", resource_name(place_id)}}, q);
|
||||
}
|
||||
|
||||
Json Places::photo_uri(const std::string& photo_name, int max_width_px, int max_height_px) const {
|
||||
if (photo_name.find("/photos/") == std::string::npos || photo_name.rfind("places/", 0) != 0)
|
||||
throw GoogleError::invalid("photo name must be places/{id}/photos/{ref}");
|
||||
if (max_width_px < 0 || max_width_px > 4800 || max_height_px < 0 || max_height_px > 4800 ||
|
||||
(max_width_px == 0 && max_height_px == 0))
|
||||
throw GoogleError::invalid("maxWidthPx / maxHeightPx must be 1..4800, at least one set");
|
||||
Query q;
|
||||
if (max_width_px) q.add("maxWidthPx", static_cast<long>(max_width_px));
|
||||
if (max_height_px) q.add("maxHeightPx", static_cast<long>(max_height_px));
|
||||
q.add("skipHttpRedirect", true);
|
||||
return invoke(Call::kPlacesPhotoMedia, {{"name", photo_name + "/media"}}, q);
|
||||
}
|
||||
|
||||
std::vector<Place> Places::places_of(const Json& response) {
|
||||
std::vector<Place> out;
|
||||
const Json* p = response.is_object() ? response.find("places") : nullptr;
|
||||
if (p && p->is_array())
|
||||
for (const auto& e : p->as_array()) out.push_back(Place::from_json(e));
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,88 @@
|
||||
#pragma once
|
||||
|
||||
// Places API (New): autocomplete, text search, nearby search, place details,
|
||||
// photo media. Every call that returns places needs a FieldMask (sent as the
|
||||
// `fields` system parameter); the mask decides the billed SKU.
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "google/maps/maps_service.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
// Circle or rectangle area, used as bias or restriction.
|
||||
struct LocationArea {
|
||||
std::optional<LatLng> center;
|
||||
double radius_meters = 0; // with center: circle, (0, 50000]
|
||||
std::optional<LatLng> low; // rectangle corners (alternative to the circle)
|
||||
std::optional<LatLng> high;
|
||||
void validate(bool restriction) const;
|
||||
clients::body::Json to_json(bool restriction) const;
|
||||
};
|
||||
|
||||
struct AutocompleteRequest {
|
||||
std::string input; // required
|
||||
std::string session_token;
|
||||
std::optional<LocationArea> bias;
|
||||
std::vector<std::string> included_primary_types;
|
||||
std::vector<std::string> included_region_codes;
|
||||
std::string language_code, region_code;
|
||||
bool include_query_predictions = false;
|
||||
void validate() const;
|
||||
clients::body::Json to_json() const;
|
||||
};
|
||||
|
||||
struct SearchTextRequest {
|
||||
std::string text_query; // required
|
||||
std::string included_type;
|
||||
bool open_now = false;
|
||||
double min_rating = 0; // 0: unset, else (0, 5]
|
||||
int page_size = 0; // 0: unset, else 1..20
|
||||
std::string page_token;
|
||||
std::optional<LocationArea> bias;
|
||||
std::optional<LocationArea> restriction; // rectangle only (Google rule)
|
||||
std::string language_code, region_code;
|
||||
void validate() const;
|
||||
clients::body::Json to_json() const;
|
||||
};
|
||||
|
||||
struct SearchNearbyRequest {
|
||||
LocationArea restriction; // required circle
|
||||
std::vector<std::string> included_types, excluded_types;
|
||||
int max_result_count = 0; // 0: unset, else 1..20
|
||||
std::string language_code, region_code;
|
||||
std::string rank_preference; // "", POPULARITY, DISTANCE
|
||||
void validate() const;
|
||||
clients::body::Json to_json() const;
|
||||
};
|
||||
|
||||
// Tolerant view of one place in a response.
|
||||
struct Place {
|
||||
std::string id, name, display_name, formatted_address;
|
||||
std::optional<LatLng> location;
|
||||
std::vector<std::string> types;
|
||||
clients::body::Json raw;
|
||||
static Place from_json(const clients::body::Json& doc);
|
||||
};
|
||||
|
||||
class Places : public MapsService {
|
||||
public:
|
||||
explicit Places(std::shared_ptr<GoogleClient> client);
|
||||
clients::body::Json autocomplete(const AutocompleteRequest& r) const;
|
||||
clients::body::Json search_text(const SearchTextRequest& r, const FieldMask& mask) const;
|
||||
clients::body::Json search_nearby(const SearchNearbyRequest& r, const FieldMask& mask) const;
|
||||
// place_id like "ChIJ..." or the resource name "places/ChIJ...".
|
||||
clients::body::Json get(const std::string& place_id, const FieldMask& mask,
|
||||
const std::string& language = "", const std::string& region = "",
|
||||
const std::string& session_token = "") const;
|
||||
// Photo name "places/{id}/photos/{ref}". Returns {"name","photoUri"}; never
|
||||
// follows the redirect (skipHttpRedirect=true), so no image bytes are held.
|
||||
clients::body::Json photo_uri(const std::string& photo_name, int max_width_px,
|
||||
int max_height_px) const;
|
||||
static std::vector<Place> places_of(const clients::body::Json& response);
|
||||
static std::string resource_name(const std::string& place_id);
|
||||
};
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,164 @@
|
||||
#include "google/maps/routes.h"
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
#include "google/errors.h"
|
||||
#include "google/maps/caps.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
namespace {
|
||||
void check_enum(const std::string& v, std::initializer_list<const char*> allowed, const char* what) {
|
||||
if (v.empty()) return;
|
||||
for (const char* a : allowed)
|
||||
if (v == a) return;
|
||||
throw GoogleError::invalid(std::string("unknown ") + what + ": " + v);
|
||||
}
|
||||
|
||||
void check_common(const std::string& mode, const std::string& pref, const std::string& units,
|
||||
const std::string& departure, const std::string& lang, const std::string& region) {
|
||||
check_enum(mode, {"DRIVE", "BICYCLE", "WALK", "TWO_WHEELER", "TRANSIT"}, "travelMode");
|
||||
check_enum(pref, {"TRAFFIC_UNAWARE", "TRAFFIC_AWARE", "TRAFFIC_AWARE_OPTIMAL"}, "routingPreference");
|
||||
check_enum(units, {"METRIC", "IMPERIAL"}, "units");
|
||||
if (!pref.empty() && !mode.empty() && mode != "DRIVE" && mode != "TWO_WHEELER")
|
||||
throw GoogleError::invalid("routingPreference applies to DRIVE and TWO_WHEELER only");
|
||||
check_text(departure, "departureTime", false);
|
||||
check_code(lang, "languageCode");
|
||||
check_code(region, "regionCode");
|
||||
}
|
||||
|
||||
void put(Json& o, const char* key, const std::string& v) {
|
||||
if (!v.empty()) o.set(key, Json(v));
|
||||
}
|
||||
|
||||
Json waypoints(const std::vector<Waypoint>& v, std::size_t max, const char* what) {
|
||||
check_count(v.size(), max, what);
|
||||
Json a = Json::array();
|
||||
for (const auto& w : v) a.push(w.to_json());
|
||||
return a;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void Waypoint::validate() const {
|
||||
int set = (location ? 1 : 0) + (address.empty() ? 0 : 1) + (place_id.empty() ? 0 : 1);
|
||||
if (set != 1) throw GoogleError::invalid("a waypoint needs exactly one of location, address, placeId");
|
||||
if (location) location->validate();
|
||||
check_text(address, "address", false);
|
||||
check_text(place_id, "placeId", false);
|
||||
}
|
||||
|
||||
Json Waypoint::to_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
if (location) {
|
||||
Json ll = Json::object();
|
||||
ll.set("latLng", location->to_json());
|
||||
o.set("location", ll);
|
||||
} else if (!address.empty()) {
|
||||
o.set("address", Json(address));
|
||||
} else {
|
||||
o.set("placeId", Json(place_id));
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
void ComputeRoutesRequest::validate() const {
|
||||
origin.validate();
|
||||
destination.validate();
|
||||
check_count(intermediates.size(), MapsCaps::kMaxIntermediates, "intermediates");
|
||||
for (const auto& w : intermediates) w.validate();
|
||||
check_common(travel_mode, routing_preference, units, departure_time, language_code, region_code);
|
||||
if (compute_alternatives && !intermediates.empty())
|
||||
throw GoogleError::invalid("alternative routes are not available with intermediates");
|
||||
check_count(extra_computations.size(), 8, "extraComputations");
|
||||
for (const auto& e : extra_computations)
|
||||
check_enum(e, {"TOLLS", "FUEL_CONSUMPTION", "TRAFFIC_ON_POLYLINE",
|
||||
"HTML_FORMATTED_NAVIGATION_INSTRUCTIONS", "FLYOVER_INFO_ON_POLYLINE",
|
||||
"NARROW_ROAD_INFO_ON_POLYLINE"}, "extraComputation");
|
||||
}
|
||||
|
||||
Json ComputeRoutesRequest::to_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
o.set("origin", origin.to_json());
|
||||
o.set("destination", destination.to_json());
|
||||
if (!intermediates.empty()) o.set("intermediates", waypoints(intermediates, MapsCaps::kMaxIntermediates, "intermediates"));
|
||||
put(o, "travelMode", travel_mode);
|
||||
put(o, "routingPreference", routing_preference);
|
||||
put(o, "departureTime", departure_time);
|
||||
if (compute_alternatives) o.set("computeAlternativeRoutes", Json(true));
|
||||
put(o, "languageCode", language_code);
|
||||
put(o, "regionCode", region_code);
|
||||
put(o, "units", units);
|
||||
if (!extra_computations.empty()) {
|
||||
Json a = Json::array();
|
||||
for (const auto& e : extra_computations) a.push(Json(e));
|
||||
o.set("extraComputations", a);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
void RouteMatrixRequest::validate() const {
|
||||
if (origins.empty() || destinations.empty()) throw GoogleError::invalid("origins and destinations are required");
|
||||
check_count(origins.size(), MapsCaps::kMaxMatrixSide, "origins");
|
||||
check_count(destinations.size(), MapsCaps::kMaxMatrixSide, "destinations");
|
||||
check_count(origins.size() * destinations.size(), MapsCaps::kMaxMatrixElements, "matrix elements");
|
||||
for (const auto& w : origins) w.validate();
|
||||
for (const auto& w : destinations) w.validate();
|
||||
check_common(travel_mode, routing_preference, units, departure_time, language_code, region_code);
|
||||
}
|
||||
|
||||
Json RouteMatrixRequest::to_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
// The matrix wraps each waypoint: {"waypoint": {...}}.
|
||||
auto wrap = [](const std::vector<Waypoint>& v) {
|
||||
Json a = Json::array();
|
||||
for (const auto& w : v) {
|
||||
Json e = Json::object();
|
||||
e.set("waypoint", w.to_json());
|
||||
a.push(e);
|
||||
}
|
||||
return a;
|
||||
};
|
||||
o.set("origins", wrap(origins));
|
||||
o.set("destinations", wrap(destinations));
|
||||
put(o, "travelMode", travel_mode);
|
||||
put(o, "routingPreference", routing_preference);
|
||||
put(o, "departureTime", departure_time);
|
||||
put(o, "languageCode", language_code);
|
||||
put(o, "regionCode", region_code);
|
||||
put(o, "units", units);
|
||||
return o;
|
||||
}
|
||||
|
||||
std::optional<RouteSummary> RouteSummary::first_of(const Json& response) {
|
||||
const Json* routes = response.is_object() ? response.find("routes") : nullptr;
|
||||
if (!routes || !routes->is_array() || routes->as_array().empty()) return std::nullopt;
|
||||
const Json& r = routes->as_array().front();
|
||||
RouteSummary s;
|
||||
if (const Json* d = r.find("distanceMeters"); d && d->is_number()) s.distance_meters = d->as_int();
|
||||
if (const Json* d = r.find("duration"); d && d->is_string()) {
|
||||
s.duration = d->as_string();
|
||||
s.duration_seconds = std::strtol(s.duration.c_str(), nullptr, 10);
|
||||
}
|
||||
if (const Json* p = r.find("polyline"); p && p->is_object())
|
||||
if (const Json* e = p->find("encodedPolyline"); e && e->is_string()) s.encoded_polyline = e->as_string();
|
||||
return s;
|
||||
}
|
||||
|
||||
Routes::Routes(std::shared_ptr<GoogleClient> client) : MapsService(std::move(client), Api::kRoutes) {}
|
||||
|
||||
Json Routes::compute_routes(const ComputeRoutesRequest& r, const FieldMask& mask) const {
|
||||
Json body = r.to_json();
|
||||
return invoke(Call::kRoutesCompute, {}, Query().add("fields", mask.str()), &body);
|
||||
}
|
||||
|
||||
Json Routes::compute_route_matrix(const RouteMatrixRequest& r, const FieldMask& mask) const {
|
||||
Json body = r.to_json();
|
||||
return invoke(Call::kRoutesMatrix, {}, Query().add("fields", mask.str()), &body);
|
||||
}
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
|
||||
// Routes API v2: computeRoutes and computeRouteMatrix. No Discovery document
|
||||
// exists; shapes follow the official reference page and the proto
|
||||
// google/maps/routing/v2/routes_service.proto (see SPEC Sources). The
|
||||
// response field mask is required (sent as the `fields` system parameter).
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "google/maps/maps_service.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
// A route endpoint: exactly one of coordinates, address or place id.
|
||||
struct Waypoint {
|
||||
std::optional<LatLng> location;
|
||||
std::string address;
|
||||
std::string place_id;
|
||||
static Waypoint at(LatLng p) { Waypoint w; w.location = p; return w; }
|
||||
static Waypoint of_address(std::string a) { Waypoint w; w.address = std::move(a); return w; }
|
||||
static Waypoint of_place(std::string id) { Waypoint w; w.place_id = std::move(id); return w; }
|
||||
void validate() const;
|
||||
clients::body::Json to_json() const; // {"location":{"latLng":..}} | {"address":..} | {"placeId":..}
|
||||
};
|
||||
|
||||
struct ComputeRoutesRequest {
|
||||
Waypoint origin, destination;
|
||||
std::vector<Waypoint> intermediates; // <= 25
|
||||
std::string travel_mode; // "", DRIVE, BICYCLE, WALK, TWO_WHEELER, TRANSIT
|
||||
std::string routing_preference; // "", TRAFFIC_UNAWARE, TRAFFIC_AWARE, TRAFFIC_AWARE_OPTIMAL
|
||||
std::string departure_time; // RFC 3339, optional
|
||||
bool compute_alternatives = false;
|
||||
std::string language_code, region_code;
|
||||
std::string units; // "", METRIC, IMPERIAL
|
||||
std::vector<std::string> extra_computations; // TOLLS, FUEL_CONSUMPTION, ...
|
||||
void validate() const;
|
||||
clients::body::Json to_json() const;
|
||||
};
|
||||
|
||||
struct RouteMatrixRequest {
|
||||
std::vector<Waypoint> origins, destinations; // each <= 25, product <= 625
|
||||
std::string travel_mode, routing_preference, departure_time, language_code, region_code, units;
|
||||
void validate() const;
|
||||
clients::body::Json to_json() const;
|
||||
};
|
||||
|
||||
// Tolerant summary of the first route of a response.
|
||||
struct RouteSummary {
|
||||
long distance_meters = 0;
|
||||
std::string duration; // "1234s" as Google sends it
|
||||
long duration_seconds = 0;
|
||||
std::string encoded_polyline;
|
||||
static std::optional<RouteSummary> first_of(const clients::body::Json& response);
|
||||
};
|
||||
|
||||
class Routes : public MapsService {
|
||||
public:
|
||||
explicit Routes(std::shared_ptr<GoogleClient> client);
|
||||
clients::body::Json compute_routes(const ComputeRoutesRequest& r, const FieldMask& mask) const;
|
||||
// Google answers an array of elements, one per origin/destination pair.
|
||||
clients::body::Json compute_route_matrix(const RouteMatrixRequest& r, const FieldMask& mask) const;
|
||||
};
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,151 @@
|
||||
#include "google/maps/street_view.h"
|
||||
|
||||
#include "google/errors.h"
|
||||
#include "google/maps/caps.h"
|
||||
#include "google/resource.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
namespace {
|
||||
void check_view(const std::string& v) {
|
||||
if (!v.empty() && v != "BASIC" && v != "INCLUDE_DOWNLOAD_URL")
|
||||
throw GoogleError::invalid("view must be BASIC or INCLUDE_DOWNLOAD_URL");
|
||||
}
|
||||
void check_page(int n) {
|
||||
if (n < 0 || n > MapsCaps::kMaxPageSize) throw GoogleError::invalid("pageSize must be 0..100");
|
||||
}
|
||||
void check_mask(const std::string& m) {
|
||||
if (m.empty()) throw GoogleError::invalid("updateMask is required");
|
||||
FieldMask checked(m); // same alphabet and caps as a field mask
|
||||
(void)checked;
|
||||
}
|
||||
Json id_array(const std::vector<std::string>& ids) {
|
||||
if (ids.empty()) throw GoogleError::invalid("at least one photo id is required");
|
||||
check_count(ids.size(), MapsCaps::kMaxIds, "photo ids");
|
||||
Json a = Json::array();
|
||||
for (const auto& id : ids) {
|
||||
if (!valid_segment(id)) throw GoogleError::invalid("bad photo id");
|
||||
a.push(Json(id));
|
||||
}
|
||||
return a;
|
||||
}
|
||||
void check_object(const Json& j, const char* what) {
|
||||
if (!j.is_object()) throw GoogleError::invalid(std::string(what) + " must be an object");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
StreetViewPublish::StreetViewPublish(std::shared_ptr<GoogleClient> client)
|
||||
: MapsService(std::move(client), Api::kStreetViewPublish) {}
|
||||
|
||||
Json StreetViewPublish::get_photo(const std::string& id, const std::string& view, const std::string& lang) const {
|
||||
check_view(view);
|
||||
check_code(lang, "languageCode");
|
||||
Query q;
|
||||
if (!view.empty()) q.add("view", view);
|
||||
if (!lang.empty()) q.add("languageCode", lang);
|
||||
return invoke(Call::kStreetPhotoGet, {{"photoId", id}}, q);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::batch_get_photos(const std::vector<std::string>& ids, const std::string& view,
|
||||
const std::string& lang) const {
|
||||
check_view(view);
|
||||
check_code(lang, "languageCode");
|
||||
Json checked = id_array(ids);
|
||||
(void)checked;
|
||||
Query q;
|
||||
for (const auto& id : ids) q.add("photoIds", id); // repeated parameter
|
||||
if (!view.empty()) q.add("view", view);
|
||||
if (!lang.empty()) q.add("languageCode", lang);
|
||||
return invoke(Call::kStreetPhotosBatchGet, {}, q);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::list_photos(const std::string& view, const std::string& filter, int page_size,
|
||||
const std::string& token) const {
|
||||
check_view(view);
|
||||
check_page(page_size);
|
||||
check_text(filter, "filter", false);
|
||||
Query q;
|
||||
if (!view.empty()) q.add("view", view);
|
||||
if (!filter.empty()) q.add("filter", filter);
|
||||
if (page_size) q.add("pageSize", static_cast<long>(page_size));
|
||||
if (!token.empty()) q.add("pageToken", token);
|
||||
return invoke(Call::kStreetPhotosList, {}, q);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::list_photo_sequences(const std::string& filter, int page_size,
|
||||
const std::string& token) const {
|
||||
check_page(page_size);
|
||||
check_text(filter, "filter", false);
|
||||
Query q;
|
||||
if (!filter.empty()) q.add("filter", filter);
|
||||
if (page_size) q.add("pageSize", static_cast<long>(page_size));
|
||||
if (!token.empty()) q.add("pageToken", token);
|
||||
return invoke(Call::kStreetPhotoSequences, {}, q);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::get_photo_sequence(const std::string& id, const std::string& view,
|
||||
const std::string& filter) const {
|
||||
check_view(view);
|
||||
check_text(filter, "filter", false);
|
||||
Query q;
|
||||
if (!view.empty()) q.add("view", view);
|
||||
if (!filter.empty()) q.add("filter", filter);
|
||||
return invoke(Call::kStreetSequenceGet, {{"sequenceId", id}}, q);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::start_upload_photo() const {
|
||||
Json empty = Json::object();
|
||||
return invoke(Call::kStreetPhotoStartUpload, {}, Query(), &empty);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::start_upload_sequence() const {
|
||||
Json empty = Json::object();
|
||||
return invoke(Call::kStreetSequenceStartUpload, {}, Query(), &empty);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::create_photo(const Json& photo) const {
|
||||
check_object(photo, "photo");
|
||||
const Json* ref = photo.find("uploadReference");
|
||||
if (!ref || !ref->is_object()) throw GoogleError::invalid("photo.uploadReference is required");
|
||||
return invoke(Call::kStreetPhotoCreate, {}, Query(), &photo);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::update_photo(const std::string& id, const Json& photo, const std::string& mask) const {
|
||||
check_object(photo, "photo");
|
||||
check_mask(mask);
|
||||
return invoke(Call::kStreetPhotoUpdate, {{"id", id}}, Query().add("updateMask", mask), &photo);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::batch_update_photos(const Json& requests) const {
|
||||
if (!requests.is_array() || requests.as_array().empty())
|
||||
throw GoogleError::invalid("updatePhotoRequests must be a non-empty array");
|
||||
check_count(requests.as_array().size(), MapsCaps::kMaxIds, "update requests");
|
||||
Json body = Json::object();
|
||||
body.set("updatePhotoRequests", requests);
|
||||
return invoke(Call::kStreetPhotosBatchUpdate, {}, Query(), &body);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::create_photo_sequence(const Json& sequence, const std::string& input_type) const {
|
||||
check_object(sequence, "sequence");
|
||||
if (input_type != "VIDEO" && input_type != "XDM")
|
||||
throw GoogleError::invalid("inputType must be VIDEO or XDM");
|
||||
return invoke(Call::kStreetSequenceCreate, {}, Query().add("inputType", input_type), &sequence);
|
||||
}
|
||||
|
||||
Json StreetViewPublish::delete_photo(const std::string& id) const {
|
||||
return invoke(Call::kStreetPhotoDelete, {{"photoId", id}}, Query());
|
||||
}
|
||||
|
||||
Json StreetViewPublish::delete_photo_sequence(const std::string& id) const {
|
||||
return invoke(Call::kStreetSequenceDelete, {{"sequenceId", id}}, Query());
|
||||
}
|
||||
|
||||
Json StreetViewPublish::batch_delete_photos(const std::vector<std::string>& ids) const {
|
||||
Json body = Json::object();
|
||||
body.set("photoIds", id_array(ids));
|
||||
return invoke(Call::kStreetPhotosBatchDelete, {}, Query(), &body);
|
||||
}
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,48 @@
|
||||
#pragma once
|
||||
|
||||
// Street View Publish API: list, get, batchGet (read) and the write calls.
|
||||
// OAuth only (scope https://www.googleapis.com/auth/streetviewpublish); a key
|
||||
// does not work. Write and delete calls are explicit methods with no defaults;
|
||||
// the byte upload to the uploadUrl returned by start_upload_* is not part of
|
||||
// this class (JSON client; listed in SPEC Gaps).
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "google/maps/maps_service.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
class StreetViewPublish : public MapsService {
|
||||
public:
|
||||
explicit StreetViewPublish(std::shared_ptr<GoogleClient> client);
|
||||
|
||||
// view: "" (BASIC) or INCLUDE_DOWNLOAD_URL.
|
||||
clients::body::Json get_photo(const std::string& photo_id, const std::string& view = "",
|
||||
const std::string& language = "") const;
|
||||
clients::body::Json batch_get_photos(const std::vector<std::string>& photo_ids, const std::string& view = "",
|
||||
const std::string& language = "") const;
|
||||
// filter e.g. "placeId=ChIJ..". Single page; token continues.
|
||||
clients::body::Json list_photos(const std::string& view = "", const std::string& filter = "",
|
||||
int page_size = 0, const std::string& page_token = "") const;
|
||||
clients::body::Json list_photo_sequences(const std::string& filter = "", int page_size = 0,
|
||||
const std::string& page_token = "") const;
|
||||
clients::body::Json get_photo_sequence(const std::string& sequence_id, const std::string& view = "",
|
||||
const std::string& filter = "") const;
|
||||
|
||||
// Writes (explicit; the demo runs them as dry runs).
|
||||
clients::body::Json start_upload_photo() const;
|
||||
clients::body::Json start_upload_sequence() const;
|
||||
clients::body::Json create_photo(const clients::body::Json& photo) const;
|
||||
clients::body::Json update_photo(const std::string& photo_id, const clients::body::Json& photo,
|
||||
const std::string& update_mask) const;
|
||||
clients::body::Json batch_update_photos(const clients::body::Json& update_photo_requests) const;
|
||||
clients::body::Json create_photo_sequence(const clients::body::Json& sequence,
|
||||
const std::string& input_type) const;
|
||||
// Destructive, no defaults.
|
||||
clients::body::Json delete_photo(const std::string& photo_id) const;
|
||||
clients::body::Json delete_photo_sequence(const std::string& sequence_id) const;
|
||||
clients::body::Json batch_delete_photos(const std::vector<std::string>& photo_ids) const;
|
||||
};
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check src/google/maps/calls.cpp against Google's Discovery documents.
|
||||
|
||||
Fails (exit 1) when a "discovery" row is absent, its HTTP method or path
|
||||
differs, or a request body field or query parameter is not in the document;
|
||||
also when a Discovery method of a covered API has no row (new methods must be
|
||||
wrapped on purpose). Rows with source "reference" (Routes, Geocoding, Time
|
||||
Zone, Elevation) have no Discovery document; they are counted and listed so
|
||||
the SPEC `## Unverified` section stays honest.
|
||||
|
||||
python3 -I src/google/maps/tools/check_discovery.py
|
||||
|
||||
Python 3 stdlib only, no credentials needed.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
CALLS = os.path.join(HERE, "..", "calls.cpp")
|
||||
DOCS = {
|
||||
"places": ("places.googleapis.com", "v1"),
|
||||
"addressvalidation": ("addressvalidation.googleapis.com", "v1"),
|
||||
"solar": ("solar.googleapis.com", "v1"),
|
||||
"pollen": ("pollen.googleapis.com", "v1"),
|
||||
"airquality": ("airquality.googleapis.com", "v1"),
|
||||
"areainsights": ("areainsights.googleapis.com", "v1"),
|
||||
"streetviewpublish": ("streetviewpublish.googleapis.com", "v1"),
|
||||
"apikeys": ("apikeys.googleapis.com", "v2"),
|
||||
}
|
||||
# API Keys is only read here (list, get). The rest mutates keys or returns the
|
||||
# secret key string and belongs to the ops package (IAM / key management) or
|
||||
# is deliberately absent (getKeyString, lookupKey).
|
||||
EXCLUDED = {"apikeys.projects.locations.keys.getKeyString", "apikeys.projects.locations.keys.patch",
|
||||
"apikeys.projects.locations.keys.undelete", "apikeys.projects.locations.keys.create",
|
||||
"apikeys.projects.locations.keys.delete", "apikeys.keys.lookupKey", "apikeys.operations.get"}
|
||||
ROW = re.compile(r'^\s*\{Call::\w+, Api::\w+, (.*)\},?\s*$')
|
||||
STR = re.compile(r'"([^"]*)"')
|
||||
|
||||
|
||||
def fetch(host, version):
|
||||
url = "https://%s/$discovery/rest?version=%s" % (host, version)
|
||||
with urllib.request.urlopen(url, timeout=60) as r:
|
||||
return json.load(r)
|
||||
|
||||
|
||||
def methods(node, out):
|
||||
for m in node.get("methods", {}).values():
|
||||
out[m["id"]] = m
|
||||
for child in node.get("resources", {}).values():
|
||||
methods(child, out)
|
||||
|
||||
|
||||
def main():
|
||||
text = open(CALLS).read()
|
||||
a = text.index("// CALLS-BEGIN")
|
||||
b = text.index("// CALLS-END")
|
||||
rows = []
|
||||
for line in text[a:b].splitlines()[1:]:
|
||||
m = ROW.match(line)
|
||||
if m:
|
||||
rows.append(STR.findall(m.group(1)))
|
||||
index, docs, bad, reference = {}, {}, [], []
|
||||
for name, (host, ver) in DOCS.items():
|
||||
docs[name] = fetch(host, ver)
|
||||
index[name] = {}
|
||||
methods(docs[name], index[name])
|
||||
covered = set()
|
||||
for http, path, rpc, body, query, source in rows:
|
||||
if source == "reference":
|
||||
reference.append(rpc)
|
||||
continue
|
||||
service = rpc.split(".")[0]
|
||||
if service not in index:
|
||||
bad.append("no discovery doc for " + rpc)
|
||||
continue
|
||||
m = index[service].get(rpc)
|
||||
if not m:
|
||||
bad.append("missing rpc " + rpc)
|
||||
continue
|
||||
covered.add(rpc)
|
||||
if m["httpMethod"] != http:
|
||||
bad.append("%s: http %s != %s" % (rpc, http, m["httpMethod"]))
|
||||
if m["path"] != path:
|
||||
bad.append("%s: path %s != %s" % (rpc, path, m["path"]))
|
||||
params = dict(docs[service].get("parameters", {})) # global: fields, key, ...
|
||||
glob = set(params)
|
||||
params.update(m.get("parameters", {}))
|
||||
for q in filter(None, query.split(",")):
|
||||
if q not in params:
|
||||
bad.append("%s: query param %s absent" % (rpc, q))
|
||||
elif q not in glob and params[q].get("location") != "query":
|
||||
bad.append("%s: %s is not a query parameter" % (rpc, q))
|
||||
fields = [f for f in body.split(",") if f]
|
||||
if fields:
|
||||
ref = m.get("request", {}).get("$ref")
|
||||
props = docs[service]["schemas"].get(ref, {}).get("properties", {})
|
||||
for f in fields:
|
||||
if f not in props:
|
||||
bad.append("%s: body field %s absent in %s" % (rpc, f, ref))
|
||||
# path placeholders must exist as path parameters
|
||||
for ph in re.findall(r"\{\+?(\w+)\}", path):
|
||||
if ph not in m.get("parameters", {}):
|
||||
bad.append("%s: path variable %s absent" % (rpc, ph))
|
||||
# coverage: every Discovery method of the covered APIs is a row
|
||||
for service, idx in index.items():
|
||||
for rpc in idx:
|
||||
if rpc not in covered and rpc not in EXCLUDED:
|
||||
bad.append("coverage: %s has no row" % rpc)
|
||||
# key restriction schema used by KeyRestrictions
|
||||
s = docs["apikeys"]["schemas"]
|
||||
want = {"V2Restrictions": ["apiTargets", "browserKeyRestrictions", "iosKeyRestrictions",
|
||||
"serverKeyRestrictions", "androidKeyRestrictions"],
|
||||
"V2BrowserKeyRestrictions": ["allowedReferrers"],
|
||||
"V2ServerKeyRestrictions": ["allowedIps"],
|
||||
"V2IosKeyRestrictions": ["allowedBundleIds"],
|
||||
"V2AndroidKeyRestrictions": ["allowedApplications"],
|
||||
"V2AndroidApplication": ["packageName", "sha1Fingerprint"],
|
||||
"V2ApiTarget": ["service"]}
|
||||
for schema, fields in want.items():
|
||||
props = s.get(schema, {}).get("properties")
|
||||
if props is None:
|
||||
bad.append("missing schema " + schema)
|
||||
continue
|
||||
for f in fields:
|
||||
if f not in props:
|
||||
bad.append("schema %s.%s absent" % (schema, f))
|
||||
for r in bad:
|
||||
print("FAIL", r)
|
||||
print("discovery rows checked: %d, reference rows (not checkable): %d (%s)" % (
|
||||
len(covered), len(reference), ", ".join(reference)))
|
||||
print("result:", "FAIL (%d)" % len(bad) if bad else "OK")
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,139 @@
|
||||
#include "google/maps/types.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
#include "google/errors.h"
|
||||
#include "google/maps/caps.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
void LatLng::validate() const {
|
||||
if (!std::isfinite(lat) || !std::isfinite(lng) || lat < -90 || lat > 90 || lng < -180 || lng > 180)
|
||||
throw GoogleError::invalid("coordinates out of range");
|
||||
}
|
||||
|
||||
Json LatLng::to_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
o.set("latitude", Json(lat));
|
||||
o.set("longitude", Json(lng));
|
||||
return o;
|
||||
}
|
||||
|
||||
Json LatLng::to_lat_lng_json() const {
|
||||
validate();
|
||||
Json o = Json::object();
|
||||
o.set("lat", Json(lat));
|
||||
o.set("lng", Json(lng));
|
||||
return o;
|
||||
}
|
||||
|
||||
std::string LatLng::to_string() const {
|
||||
validate();
|
||||
char buf[64];
|
||||
std::snprintf(buf, sizeof buf, "%.7f,%.7f", lat, lng);
|
||||
return buf;
|
||||
}
|
||||
|
||||
LatLng LatLng::parse(const std::string& text) {
|
||||
std::size_t comma = text.find(',');
|
||||
if (comma == std::string::npos || text.size() > 64) throw GoogleError::invalid("expected lat,lng");
|
||||
char* end = nullptr;
|
||||
std::string a = text.substr(0, comma), b = text.substr(comma + 1);
|
||||
LatLng p;
|
||||
p.lat = std::strtod(a.c_str(), &end);
|
||||
if (a.empty() || *end) throw GoogleError::invalid("bad latitude");
|
||||
p.lng = std::strtod(b.c_str(), &end);
|
||||
if (b.empty() || *end) throw GoogleError::invalid("bad longitude");
|
||||
p.validate();
|
||||
return p;
|
||||
}
|
||||
|
||||
FieldMask::FieldMask(std::string mask) : mask_(std::move(mask)) {
|
||||
if (mask_.empty()) throw GoogleError::invalid("field mask is required");
|
||||
if (mask_.size() > MapsCaps::kMaxFieldMaskChars) throw GoogleError::invalid("field mask too long");
|
||||
if (mask_ == "*") throw GoogleError::invalid("field mask '*' must be requested with FieldMask::all()");
|
||||
std::size_t entries = 1;
|
||||
bool empty_entry = true;
|
||||
for (char c : mask_) {
|
||||
if (c == ',') {
|
||||
if (empty_entry) throw GoogleError::invalid("empty field mask entry");
|
||||
++entries;
|
||||
empty_entry = true;
|
||||
continue;
|
||||
}
|
||||
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||
c == '_' || c == '.';
|
||||
if (!ok) throw GoogleError::invalid("bad character in field mask");
|
||||
empty_entry = false;
|
||||
}
|
||||
if (empty_entry) throw GoogleError::invalid("empty field mask entry");
|
||||
if (entries > MapsCaps::kMaxFieldMaskEntries) throw GoogleError::invalid("too many field mask entries");
|
||||
}
|
||||
|
||||
FieldMask FieldMask::all() {
|
||||
FieldMask m("x");
|
||||
m.mask_ = "*";
|
||||
return m;
|
||||
}
|
||||
|
||||
std::string percent_encode(const std::string& text) {
|
||||
static const char* hex = "0123456789ABCDEF";
|
||||
std::string out;
|
||||
for (unsigned char c : text) {
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' ||
|
||||
c == '_' || c == '.' || c == '~') {
|
||||
out += static_cast<char>(c);
|
||||
} else {
|
||||
out += '%';
|
||||
out += hex[c >> 4];
|
||||
out += hex[c & 15];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Query& Query::add(const std::string& name, const std::string& value) {
|
||||
if (value.size() > MapsCaps::kMaxQueryValueChars) throw GoogleError::invalid("query value too long: " + name);
|
||||
items_.emplace_back(name, value);
|
||||
return *this;
|
||||
}
|
||||
Query& Query::add(const std::string& name, double value) {
|
||||
char buf[64];
|
||||
std::snprintf(buf, sizeof buf, "%.10g", value);
|
||||
return add(name, std::string(buf));
|
||||
}
|
||||
Query& Query::add(const std::string& name, long value) { return add(name, std::to_string(value)); }
|
||||
Query& Query::add(const std::string& name, bool value) { return add(name, std::string(value ? "true" : "false")); }
|
||||
|
||||
std::string Query::encode() const {
|
||||
std::string out;
|
||||
for (const auto& [k, v] : items_) {
|
||||
out += out.empty() ? '?' : '&';
|
||||
out += percent_encode(k) + "=" + percent_encode(v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void check_text(const std::string& text, const char* what, bool required) {
|
||||
if (required && text.empty()) throw GoogleError::invalid(std::string(what) + " is required");
|
||||
if (text.size() > MapsCaps::kMaxTextChars) throw GoogleError::invalid(std::string(what) + " too long");
|
||||
}
|
||||
|
||||
void check_code(const std::string& code, const char* what) {
|
||||
if (code.empty()) return;
|
||||
if (code.size() > 12) throw GoogleError::invalid(std::string(what) + " malformed");
|
||||
for (char c : code)
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-'))
|
||||
throw GoogleError::invalid(std::string(what) + " malformed");
|
||||
}
|
||||
|
||||
void check_count(std::size_t n, std::size_t max, const char* what) {
|
||||
if (n > max) throw GoogleError::invalid(std::string("too many ") + what);
|
||||
}
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
|
||||
// Small validated value types shared by every Maps API: coordinates, field
|
||||
// masks, query strings. Each validates on construction or on use, before any
|
||||
// network traffic.
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
struct LatLng {
|
||||
double lat = 0;
|
||||
double lng = 0;
|
||||
|
||||
void validate() const; // lat in [-90,90], lng in [-180,180]
|
||||
clients::body::Json to_json() const; // {"latitude":..,"longitude":..}
|
||||
clients::body::Json to_lat_lng_json() const; // {"lat":..,"lng":..} (legacy)
|
||||
std::string to_string() const; // "lat,lng" with 7 decimals
|
||||
static LatLng parse(const std::string& text); // "lat,lng"
|
||||
};
|
||||
|
||||
// Response field selection. Places and Routes bill by the fields asked for and
|
||||
// refuse a request without a mask, so the mask is a required, validated
|
||||
// object: 1..64 entries of [A-Za-z0-9_.], and `*` (everything, the most
|
||||
// expensive SKU) only through all().
|
||||
class FieldMask {
|
||||
public:
|
||||
explicit FieldMask(std::string mask);
|
||||
static FieldMask all();
|
||||
const std::string& str() const { return mask_; }
|
||||
bool is_all() const { return mask_ == "*"; }
|
||||
|
||||
private:
|
||||
std::string mask_;
|
||||
};
|
||||
|
||||
// Ordered query parameters. add() skips nothing; values are percent-encoded
|
||||
// by encode() and capped.
|
||||
class Query {
|
||||
public:
|
||||
Query& add(const std::string& name, const std::string& value);
|
||||
Query& add(const std::string& name, const char* value) { return add(name, std::string(value)); }
|
||||
Query& add(const std::string& name, double value);
|
||||
Query& add(const std::string& name, long value);
|
||||
Query& add(const std::string& name, bool value);
|
||||
const std::vector<std::pair<std::string, std::string>>& items() const { return items_; }
|
||||
bool empty() const { return items_.empty(); }
|
||||
// "?a=b&c=d" with percent-encoding, or "" when empty.
|
||||
std::string encode() const;
|
||||
|
||||
private:
|
||||
std::vector<std::pair<std::string, std::string>> items_;
|
||||
};
|
||||
|
||||
std::string percent_encode(const std::string& text);
|
||||
|
||||
// Validators that throw GoogleError::invalid.
|
||||
void check_text(const std::string& text, const char* what, bool required = true);
|
||||
void check_code(const std::string& code, const char* what); // language / region "en", "nl-NL", "NL"
|
||||
void check_count(std::size_t n, std::size_t max, const char* what);
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,172 @@
|
||||
#include "google/maps/web_services.h"
|
||||
|
||||
#include "google/errors.h"
|
||||
#include "google/maps/caps.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
namespace {
|
||||
std::string str(const Json& d, const char* k) {
|
||||
const Json* v = d.is_object() ? d.find(k) : nullptr;
|
||||
return v && v->is_string() ? v->as_string() : "";
|
||||
}
|
||||
std::optional<LatLng> latlng(const Json& d, const char* a, const char* b) {
|
||||
const Json* la = d.is_object() ? d.find(a) : nullptr;
|
||||
const Json* lo = d.is_object() ? d.find(b) : nullptr;
|
||||
if (la && lo && la->is_number() && lo->is_number()) return LatLng{la->as_number(), lo->as_number()};
|
||||
return std::nullopt;
|
||||
}
|
||||
std::string join(const std::vector<LatLng>& pts) {
|
||||
std::string s;
|
||||
for (const auto& p : pts) {
|
||||
if (!s.empty()) s += "|";
|
||||
s += p.to_string();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
std::vector<GeocodeResult> results_of(const Json& doc) {
|
||||
std::vector<GeocodeResult> out;
|
||||
const Json* r = doc.find("results");
|
||||
if (r && r->is_array())
|
||||
for (const auto& e : r->as_array()) out.push_back(GeocodeResult::from_json(e));
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
GeocodeResult GeocodeResult::from_json(const Json& doc) {
|
||||
GeocodeResult g;
|
||||
g.formatted_address = str(doc, "formatted_address");
|
||||
g.place_id = str(doc, "place_id");
|
||||
if (const Json* pm = doc.is_object() ? doc.find("partial_match") : nullptr; pm && pm->is_bool())
|
||||
g.partial_match = pm->as_bool();
|
||||
if (const Json* t = doc.is_object() ? doc.find("types") : nullptr; t && t->is_array())
|
||||
for (const auto& e : t->as_array())
|
||||
if (e.is_string()) g.types.push_back(e.as_string());
|
||||
if (const Json* geo = doc.is_object() ? doc.find("geometry") : nullptr; geo && geo->is_object()) {
|
||||
g.location_type = str(*geo, "location_type");
|
||||
if (const Json* l = geo->find("location")) g.location = latlng(*l, "lat", "lng");
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
Geocoding::Geocoding(std::shared_ptr<GoogleClient> client)
|
||||
: MapsService(std::move(client), Api::kWebServices) {}
|
||||
|
||||
Json Geocoding::raw(const Query& q) const {
|
||||
Json doc = invoke(Call::kGeocode, {}, q);
|
||||
check_web_status(doc, "geocoding");
|
||||
return doc;
|
||||
}
|
||||
|
||||
std::vector<GeocodeResult> Geocoding::geocode(const std::string& address, const std::string& components,
|
||||
const std::string& region, const std::string& language) const {
|
||||
if (address.empty() && components.empty()) throw GoogleError::invalid("address or components is required");
|
||||
check_text(address, "address", false);
|
||||
check_text(components, "components", false);
|
||||
check_code(region, "region");
|
||||
check_code(language, "language");
|
||||
Query q;
|
||||
if (!address.empty()) q.add("address", address);
|
||||
if (!components.empty()) q.add("components", components);
|
||||
if (!region.empty()) q.add("region", region);
|
||||
if (!language.empty()) q.add("language", language);
|
||||
return results_of(raw(q));
|
||||
}
|
||||
|
||||
std::vector<GeocodeResult> Geocoding::reverse(const LatLng& at, const std::string& result_type,
|
||||
const std::string& location_type,
|
||||
const std::string& language) const {
|
||||
check_text(result_type, "result_type", false);
|
||||
check_text(location_type, "location_type", false);
|
||||
check_code(language, "language");
|
||||
Query q;
|
||||
q.add("latlng", at.to_string());
|
||||
if (!result_type.empty()) q.add("result_type", result_type);
|
||||
if (!location_type.empty()) q.add("location_type", location_type);
|
||||
if (!language.empty()) q.add("language", language);
|
||||
return results_of(raw(q));
|
||||
}
|
||||
|
||||
std::vector<GeocodeResult> Geocoding::by_place_id(const std::string& place_id, const std::string& language) const {
|
||||
check_text(place_id, "place_id");
|
||||
check_code(language, "language");
|
||||
Query q;
|
||||
q.add("place_id", place_id);
|
||||
if (!language.empty()) q.add("language", language);
|
||||
return results_of(raw(q));
|
||||
}
|
||||
|
||||
TimeZone::TimeZone(std::shared_ptr<GoogleClient> client)
|
||||
: MapsService(std::move(client), Api::kWebServices) {}
|
||||
|
||||
Json TimeZone::raw(const LatLng& at, long timestamp, const std::string& language) const {
|
||||
if (timestamp < 0) throw GoogleError::invalid("timestamp must be seconds since 1970 UTC, >= 0");
|
||||
check_code(language, "language");
|
||||
Query q;
|
||||
q.add("location", at.to_string()).add("timestamp", timestamp);
|
||||
if (!language.empty()) q.add("language", language);
|
||||
Json doc = invoke(Call::kTimeZone, {}, q);
|
||||
check_web_status(doc, "timezone");
|
||||
return doc;
|
||||
}
|
||||
|
||||
TimeZoneInfo TimeZone::lookup(const LatLng& at, long timestamp, const std::string& language) const {
|
||||
Json doc = raw(at, timestamp, language);
|
||||
TimeZoneInfo t;
|
||||
t.status = str(doc, "status");
|
||||
t.time_zone_id = str(doc, "timeZoneId");
|
||||
t.time_zone_name = str(doc, "timeZoneName");
|
||||
if (const Json* v = doc.find("rawOffset"); v && v->is_number()) t.raw_offset = v->as_int();
|
||||
if (const Json* v = doc.find("dstOffset"); v && v->is_number()) t.dst_offset = v->as_int();
|
||||
return t;
|
||||
}
|
||||
|
||||
Elevation::Elevation(std::shared_ptr<GoogleClient> client)
|
||||
: MapsService(std::move(client), Api::kWebServices) {}
|
||||
|
||||
namespace {
|
||||
std::vector<ElevationPoint> parse_elevation(const Json& doc) {
|
||||
std::vector<ElevationPoint> out;
|
||||
const Json* r = doc.find("results");
|
||||
if (!r || !r->is_array()) return out;
|
||||
for (const auto& e : r->as_array()) {
|
||||
ElevationPoint p;
|
||||
if (const Json* v = e.find("elevation"); v && v->is_number()) p.elevation = v->as_number();
|
||||
if (const Json* v = e.find("resolution"); v && v->is_number()) p.resolution = v->as_number();
|
||||
if (const Json* l = e.find("location"))
|
||||
if (auto ll = latlng(*l, "lat", "lng")) p.location = *ll;
|
||||
out.push_back(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Json Elevation::raw_at(const std::vector<LatLng>& points) const {
|
||||
if (points.empty()) throw GoogleError::invalid("at least one location is required");
|
||||
check_count(points.size(), MapsCaps::kMaxPoints, "locations");
|
||||
Json doc = invoke(Call::kElevation, {}, Query().add("locations", join(points)));
|
||||
check_web_status(doc, "elevation");
|
||||
return doc;
|
||||
}
|
||||
|
||||
std::vector<ElevationPoint> Elevation::at(const std::vector<LatLng>& points) const {
|
||||
return parse_elevation(raw_at(points));
|
||||
}
|
||||
|
||||
Json Elevation::raw_along(const std::vector<LatLng>& path, int samples) const {
|
||||
if (path.size() < 2) throw GoogleError::invalid("a path needs at least two points");
|
||||
check_count(path.size(), MapsCaps::kMaxPoints, "path points");
|
||||
if (samples < 2 || samples > static_cast<int>(MapsCaps::kMaxPoints))
|
||||
throw GoogleError::invalid("samples must be 2..512");
|
||||
Json doc = invoke(Call::kElevation, {}, Query().add("path", join(path)).add("samples", static_cast<long>(samples)));
|
||||
check_web_status(doc, "elevation");
|
||||
return doc;
|
||||
}
|
||||
|
||||
std::vector<ElevationPoint> Elevation::along(const std::vector<LatLng>& path, int samples) const {
|
||||
return parse_elevation(raw_along(path, samples));
|
||||
}
|
||||
|
||||
} // namespace molo::google::maps
|
||||
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
|
||||
// The classic Maps web services: Geocoding, Time Zone, Elevation. No
|
||||
// Discovery document; shapes follow the official reference pages (SPEC
|
||||
// Sources). They answer HTTP 200 with a "status" member; any status other
|
||||
// than OK / ZERO_RESULTS / DATA_NOT_AVAILABLE becomes a GoogleError.
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "google/maps/maps_service.h"
|
||||
|
||||
namespace molo::google::maps {
|
||||
|
||||
struct GeocodeResult {
|
||||
std::string formatted_address, place_id, location_type;
|
||||
std::optional<LatLng> location;
|
||||
std::vector<std::string> types;
|
||||
bool partial_match = false;
|
||||
static GeocodeResult from_json(const clients::body::Json& doc);
|
||||
};
|
||||
|
||||
class Geocoding : public MapsService {
|
||||
public:
|
||||
explicit Geocoding(std::shared_ptr<GoogleClient> client);
|
||||
// address and/or components ("country:NL|postal_code:1011"); at least one.
|
||||
std::vector<GeocodeResult> geocode(const std::string& address, const std::string& components = "",
|
||||
const std::string& region = "", const std::string& language = "") const;
|
||||
std::vector<GeocodeResult> reverse(const LatLng& at, const std::string& result_type = "",
|
||||
const std::string& location_type = "",
|
||||
const std::string& language = "") const;
|
||||
std::vector<GeocodeResult> by_place_id(const std::string& place_id, const std::string& language = "") const;
|
||||
// Raw document (status, results), already status-checked.
|
||||
clients::body::Json raw(const Query& q) const;
|
||||
};
|
||||
|
||||
struct TimeZoneInfo {
|
||||
std::string time_zone_id, time_zone_name, status;
|
||||
long raw_offset = 0, dst_offset = 0;
|
||||
// Local epoch seconds for `timestamp`: timestamp + rawOffset + dstOffset.
|
||||
long local_time(long timestamp) const { return timestamp + raw_offset + dst_offset; }
|
||||
};
|
||||
|
||||
class TimeZone : public MapsService {
|
||||
public:
|
||||
explicit TimeZone(std::shared_ptr<GoogleClient> client);
|
||||
// Status ZERO_RESULTS (over water) returns info with that status and empty id.
|
||||
TimeZoneInfo lookup(const LatLng& at, long timestamp, const std::string& language = "") const;
|
||||
// The status-checked document (or the dry-run preview).
|
||||
clients::body::Json raw(const LatLng& at, long timestamp, const std::string& language = "") const;
|
||||
};
|
||||
|
||||
struct ElevationPoint {
|
||||
LatLng location;
|
||||
double elevation = 0; // meters
|
||||
double resolution = -1; // meters, -1: omitted by Google
|
||||
};
|
||||
|
||||
class Elevation : public MapsService {
|
||||
public:
|
||||
explicit Elevation(std::shared_ptr<GoogleClient> client);
|
||||
std::vector<ElevationPoint> at(const std::vector<LatLng>& points) const;
|
||||
// 2..512 path points, samples 2..512 equidistant points along it.
|
||||
std::vector<ElevationPoint> along(const std::vector<LatLng>& path, int samples) const;
|
||||
// Status-checked documents (or dry-run previews).
|
||||
clients::body::Json raw_at(const std::vector<LatLng>& points) const;
|
||||
clients::body::Json raw_along(const std::vector<LatLng>& path, int samples) const;
|
||||
};
|
||||
|
||||
} // namespace molo::google::maps
|
||||
Reference in New Issue
Block a user