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:
@@ -1,13 +1,464 @@
|
|||||||
#include "../GoogleDemos.hpp"
|
#include "../GoogleDemos.hpp"
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <functional>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
#include "../../fw/Router.hpp"
|
#include "../../fw/Router.hpp"
|
||||||
|
#include "../../fw/Templates.hpp"
|
||||||
|
#include "../../fw/Validate.hpp"
|
||||||
|
#include "clients/body/json.h"
|
||||||
|
#include "google/maps/address_validation.h"
|
||||||
|
#include "google/maps/calls.h"
|
||||||
|
#include "google/maps/caps.h"
|
||||||
|
#include "google/maps/environment.h"
|
||||||
|
#include "google/maps/maps_key.h"
|
||||||
|
#include "google/maps/places.h"
|
||||||
|
#include "google/maps/routes.h"
|
||||||
|
#include "google/maps/street_view.h"
|
||||||
|
#include "google/maps/web_services.h"
|
||||||
|
#include "google/resource.h"
|
||||||
|
|
||||||
namespace molo::example::app {
|
namespace molo::example::app {
|
||||||
|
|
||||||
// Places, Address Validation, Solar, Pollen, Air Quality, Area Insights, Routes, Geocoding. Stub: the package agent fills this in.
|
// Google Maps Platform over src/google/maps: Places (new), Address
|
||||||
|
// Validation, Solar, Pollen, Air Quality, Area Insights, Routes, Geocoding,
|
||||||
|
// Time Zone, Elevation, Street View Publish and API-key handling. GET routes
|
||||||
|
// never touch Google. Every route that calls Google is a POST (or DELETE),
|
||||||
|
// validates first (422), answers 503 google_not_configured without a
|
||||||
|
// credential, and is a DRY RUN unless the body has "confirm":"true" (every
|
||||||
|
// Maps request is billed). The dry run returns the exact request.
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using Json = clients::body::Json;
|
||||||
|
namespace mp = google::maps;
|
||||||
|
using Form = std::map<std::string, std::string>;
|
||||||
|
|
||||||
|
[[noreturn]] void rethrow(const google::GoogleError& e) {
|
||||||
|
if (e.http_status() == 503 && e.status() == "NOT_CONFIGURED")
|
||||||
|
throw fw::HttpError(503, "google_not_configured", e.message());
|
||||||
|
if (e.service().empty() && e.status() == "INVALID_ARGUMENT")
|
||||||
|
throw fw::HttpError(422, "validation_error", e.message());
|
||||||
|
throw fw::HttpError(502, "google_error", e.status() + ": " + e.message());
|
||||||
|
}
|
||||||
|
|
||||||
|
fw::Response json_reply(const Json& j, int status = 200) {
|
||||||
|
fw::Response res = fw::JsonResponse(j.dump(), status);
|
||||||
|
res.headers.set("Cache-Control", "no-store");
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string field(const Form& in, const char* key) {
|
||||||
|
auto it = in.find(key);
|
||||||
|
return it == in.end() ? "" : it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[noreturn]] void bad(const std::string& message) {
|
||||||
|
throw fw::HttpError(422, "validation_error", message);
|
||||||
|
}
|
||||||
|
|
||||||
|
double number(const Form& in, const char* key, double fallback, bool required = false) {
|
||||||
|
std::string v = field(in, key);
|
||||||
|
if (v.empty()) {
|
||||||
|
if (required) bad(std::string(key) + " is required");
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
char* end = nullptr;
|
||||||
|
double d = std::strtod(v.c_str(), &end);
|
||||||
|
if (*end) bad(std::string(key) + " is not a number");
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
int integer(const Form& in, const char* key, int fallback, bool required = false) {
|
||||||
|
return static_cast<int>(number(in, key, fallback, required));
|
||||||
|
}
|
||||||
|
|
||||||
|
mp::LatLng point(const Form& in, const char* lat = "lat", const char* lng = "lng") {
|
||||||
|
return mp::LatLng{number(in, lat, 0, true), number(in, lng, 0, true)};
|
||||||
|
}
|
||||||
|
|
||||||
|
// "52.37,4.89" is coordinates, anything else an address.
|
||||||
|
mp::Waypoint waypoint(const std::string& text, const char* what) {
|
||||||
|
if (text.empty()) bad(std::string(what) + " is required");
|
||||||
|
if (text.rfind("place:", 0) == 0) return mp::Waypoint::of_place(text.substr(6));
|
||||||
|
try {
|
||||||
|
return mp::Waypoint::at(mp::LatLng::parse(text));
|
||||||
|
} catch (const google::GoogleError&) {
|
||||||
|
return mp::Waypoint::of_address(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> split(const std::string& text, char sep) {
|
||||||
|
std::vector<std::string> out;
|
||||||
|
std::string cur;
|
||||||
|
for (char c : text) {
|
||||||
|
if (c == sep) {
|
||||||
|
if (!cur.empty()) out.push_back(cur);
|
||||||
|
cur.clear();
|
||||||
|
} else {
|
||||||
|
cur += c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!cur.empty()) out.push_back(cur);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// What a route does for one request: given a service factory flag (dry run or
|
||||||
|
// real) it returns Google's answer or the dry-run preview.
|
||||||
|
using Action = std::function<Json(const std::shared_ptr<google::GoogleClient>&, bool dry)>;
|
||||||
|
|
||||||
|
class MapsDemo {
|
||||||
|
public:
|
||||||
|
explicit MapsDemo(Services& services) {
|
||||||
|
if (!services.google) services.google = google::GoogleClient::from_env();
|
||||||
|
client_ = services.google;
|
||||||
|
}
|
||||||
|
bool configured() const { return client_->configured(); }
|
||||||
|
const std::shared_ptr<google::GoogleClient>& client() const { return client_; }
|
||||||
|
|
||||||
|
// 1. validate (preview through the dry run, no credential needed),
|
||||||
|
// 2. credential check (503), 3. dry run answer unless confirm, 4. call.
|
||||||
|
fw::Response run(const Form& in, const Action& action) const {
|
||||||
|
try {
|
||||||
|
Json preview = action(client_, true);
|
||||||
|
if (!configured()) throw google::NotConfiguredError("maps");
|
||||||
|
Json j = Json::object();
|
||||||
|
if (field(in, "confirm") != "true") {
|
||||||
|
j.set("dry_run", Json(true));
|
||||||
|
j.set("request", preview);
|
||||||
|
j.set("hint", Json("send \"confirm\":\"true\" to call Google; every Maps request is billed"));
|
||||||
|
return json_reply(j);
|
||||||
|
}
|
||||||
|
j.set("dry_run", Json(false));
|
||||||
|
j.set("response", action(client_, false));
|
||||||
|
return json_reply(j);
|
||||||
|
} catch (const google::GoogleError& e) {
|
||||||
|
rethrow(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::shared_ptr<google::GoogleClient> client_;
|
||||||
|
};
|
||||||
|
|
||||||
|
const char kPage[] = R"MAPS({% extends "base.html" %}
|
||||||
|
{% block content %}
|
||||||
|
<h1>Google Maps Platform</h1>
|
||||||
|
<p class="hint">Places, Address Validation, Solar, Pollen, Air Quality, Area
|
||||||
|
Insights, Routes, Geocoding, Time Zone, Elevation, Street View Publish and
|
||||||
|
API-key checks. Every Maps request is billed, so each call is a dry run that
|
||||||
|
shows the exact request until you tick "Call Google". Needs a Google
|
||||||
|
credential (a Maps API key for Geocoding, Time Zone and Elevation).</p>
|
||||||
|
<p id="m-config" class="hint">Checking configuration...</p>
|
||||||
|
<section class="maps">
|
||||||
|
<label class="inline">API
|
||||||
|
<select id="m-api">
|
||||||
|
<option value="places/search">Places: text search</option>
|
||||||
|
<option value="places/nearby">Places: nearby</option>
|
||||||
|
<option value="places/autocomplete">Places: autocomplete</option>
|
||||||
|
<option value="places/details">Places: details</option>
|
||||||
|
<option value="address/validate">Address validation</option>
|
||||||
|
<option value="solar">Solar: building insights</option>
|
||||||
|
<option value="pollen">Pollen: forecast</option>
|
||||||
|
<option value="air">Air quality: current</option>
|
||||||
|
<option value="area">Area insights: count</option>
|
||||||
|
<option value="routes">Routes: compute</option>
|
||||||
|
<option value="geocode">Geocoding</option>
|
||||||
|
<option value="timezone">Time zone</option>
|
||||||
|
<option value="elevation">Elevation</option>
|
||||||
|
<option value="streetview/list">Street View: list photos</option>
|
||||||
|
<option value="keys/lint">Key restrictions: lint (local)</option>
|
||||||
|
</select></label>
|
||||||
|
<input id="m-q" type="text" maxlength="200" placeholder="Query, address, place id or origin" autocomplete="off">
|
||||||
|
<input id="m-q2" type="text" maxlength="200" placeholder="Destination (routes) or API list" autocomplete="off">
|
||||||
|
<div class="maps-row">
|
||||||
|
<input id="m-lat" type="text" inputmode="decimal" value="52.3702157" aria-label="Latitude">
|
||||||
|
<input id="m-lng" type="text" inputmode="decimal" value="4.8951679" aria-label="Longitude">
|
||||||
|
<input id="m-radius" type="text" inputmode="numeric" value="500" aria-label="Radius in meters">
|
||||||
|
</div>
|
||||||
|
<label class="inline"><input id="m-confirm" type="checkbox"> Call Google (billed)</label>
|
||||||
|
<div class="maps-actions">
|
||||||
|
<button id="m-run" type="button" class="primary">Run</button>
|
||||||
|
<button id="m-calls" type="button">Call table</button>
|
||||||
|
</div>
|
||||||
|
<p id="m-error" class="error" role="alert"></p>
|
||||||
|
<pre id="m-out" class="scroll"></pre>
|
||||||
|
</section>
|
||||||
|
<script src="/embedded/google_maps.js"></script>
|
||||||
|
{% endblock %}
|
||||||
|
)MAPS";
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
void register_google_maps_demo(fw::Router& router, Services& services) {
|
void register_google_maps_demo(fw::Router& router, Services& services) {
|
||||||
(void)router;
|
auto demo = std::make_shared<MapsDemo>(services);
|
||||||
(void)services;
|
fw::Environment* env = services.templates.get();
|
||||||
|
env->add_template("google_maps.html", kPage);
|
||||||
|
services.add_feature("google-maps", "/google/maps");
|
||||||
|
|
||||||
|
// ---- Pages and status (never call Google).
|
||||||
|
router.get("/google/maps", "google-maps-page", [env](fw::Request) {
|
||||||
|
fw::TemplateCtx ctx;
|
||||||
|
ctx["title"] = std::string("Google Maps Platform");
|
||||||
|
return fw::Response(200, env->render("google_maps.html", ctx), "text/html; charset=utf-8");
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/google/maps/status", "google-maps-status", [demo](fw::Request) {
|
||||||
|
mp::MapsKey key = mp::MapsKey::from_env();
|
||||||
|
Json j = Json::object();
|
||||||
|
j.set("configured", Json(demo->configured()));
|
||||||
|
j.set("maps_key_present", Json(key.present()));
|
||||||
|
j.set("maps_key_shape_ok", Json(key.looks_like_maps_key()));
|
||||||
|
j.set("maps_key", Json(key.redacted()));
|
||||||
|
j.set("calls", Json(static_cast<int>(mp::call_count())));
|
||||||
|
Json caps = Json::object();
|
||||||
|
caps.set("max_points", Json(static_cast<int>(mp::MapsCaps::kMaxPoints)));
|
||||||
|
caps.set("max_matrix_elements", Json(static_cast<int>(mp::MapsCaps::kMaxMatrixElements)));
|
||||||
|
caps.set("max_result_count", Json(static_cast<int>(mp::MapsCaps::kMaxResultCount)));
|
||||||
|
caps.set("max_field_mask_entries", Json(static_cast<int>(mp::MapsCaps::kMaxFieldMaskEntries)));
|
||||||
|
j.set("caps", caps);
|
||||||
|
return json_reply(j);
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/google/maps/calls", "google-maps-calls", [](fw::Request) {
|
||||||
|
Json rows = Json::array();
|
||||||
|
for (std::size_t i = 0; i < mp::call_count(); ++i) {
|
||||||
|
const mp::CallSpec& c = mp::spec_at(i);
|
||||||
|
Json r = Json::object();
|
||||||
|
r.set("id", Json(c.rpc_id));
|
||||||
|
r.set("method", Json(c.http_method));
|
||||||
|
r.set("path", Json(c.path));
|
||||||
|
r.set("host", Json(mp::endpoint_of(c.api).base_url));
|
||||||
|
r.set("source", Json(c.source));
|
||||||
|
rows.push(r);
|
||||||
|
}
|
||||||
|
Json j = Json::object();
|
||||||
|
j.set("calls", rows);
|
||||||
|
return json_reply(j);
|
||||||
|
});
|
||||||
|
|
||||||
|
// A POST route: parse the flat JSON body, run the action under the dry-run rules.
|
||||||
|
auto post = [&router, demo](const std::string& path, const std::string& name,
|
||||||
|
std::function<Action(const Form&)> make) {
|
||||||
|
router.post(path, name, [demo, make](fw::Request req) {
|
||||||
|
Form in = fw::parse_json_object_flat(req.body);
|
||||||
|
try {
|
||||||
|
return demo->run(in, make(in));
|
||||||
|
} catch (const google::GoogleError& e) {
|
||||||
|
rethrow(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const std::string kPlaceFields = "places.id,places.displayName,places.formattedAddress,places.location";
|
||||||
|
|
||||||
|
post("/google/maps/places/search", "google-maps-places-search", [=](const Form& in) -> Action {
|
||||||
|
mp::SearchTextRequest r;
|
||||||
|
r.text_query = field(in, "query");
|
||||||
|
r.page_size = integer(in, "limit", 5);
|
||||||
|
r.language_code = field(in, "language");
|
||||||
|
std::string fields = field(in, "fields").empty() ? kPlaceFields : field(in, "fields");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::Places p(c);
|
||||||
|
p.set_dry_run(dry);
|
||||||
|
return p.search_text(r, mp::FieldMask(fields));
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/places/nearby", "google-maps-places-nearby", [=](const Form& in) -> Action {
|
||||||
|
mp::SearchNearbyRequest r;
|
||||||
|
r.restriction.center = point(in);
|
||||||
|
r.restriction.radius_meters = number(in, "radius", 500);
|
||||||
|
if (!field(in, "type").empty()) r.included_types = {field(in, "type")};
|
||||||
|
r.max_result_count = integer(in, "limit", 5);
|
||||||
|
std::string fields = field(in, "fields").empty() ? kPlaceFields : field(in, "fields");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::Places p(c);
|
||||||
|
p.set_dry_run(dry);
|
||||||
|
return p.search_nearby(r, mp::FieldMask(fields));
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/places/autocomplete", "google-maps-places-autocomplete", [=](const Form& in) -> Action {
|
||||||
|
mp::AutocompleteRequest r;
|
||||||
|
r.input = field(in, "input");
|
||||||
|
r.session_token = field(in, "session");
|
||||||
|
r.language_code = field(in, "language");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::Places p(c);
|
||||||
|
p.set_dry_run(dry);
|
||||||
|
return p.autocomplete(r);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/places/details", "google-maps-places-details", [=](const Form& in) -> Action {
|
||||||
|
std::string id = field(in, "place_id");
|
||||||
|
std::string fields = field(in, "fields").empty() ? "id,displayName,formattedAddress,location" : field(in, "fields");
|
||||||
|
std::string language = field(in, "language");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::Places p(c);
|
||||||
|
p.set_dry_run(dry);
|
||||||
|
return p.get(id, mp::FieldMask(fields), language);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/address/validate", "google-maps-address-validate", [=](const Form& in) -> Action {
|
||||||
|
mp::ValidateAddressRequest r;
|
||||||
|
r.address.region_code = field(in, "region");
|
||||||
|
r.address.address_lines = split(field(in, "lines"), '\n');
|
||||||
|
r.address.locality = field(in, "locality");
|
||||||
|
r.address.postal_code = field(in, "postal_code");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::AddressValidation a(c);
|
||||||
|
a.set_dry_run(dry);
|
||||||
|
return a.validate(r);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/solar", "google-maps-solar", [=](const Form& in) -> Action {
|
||||||
|
mp::LatLng at = point(in);
|
||||||
|
std::string quality = field(in, "quality");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::Solar s(c);
|
||||||
|
s.set_dry_run(dry);
|
||||||
|
return s.building_insights(at, quality);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/pollen", "google-maps-pollen", [=](const Form& in) -> Action {
|
||||||
|
mp::LatLng at = point(in);
|
||||||
|
int days = integer(in, "days", 1);
|
||||||
|
std::string language = field(in, "language");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::Pollen p(c);
|
||||||
|
p.set_dry_run(dry);
|
||||||
|
return p.forecast(at, days, language);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/air", "google-maps-air", [=](const Form& in) -> Action {
|
||||||
|
mp::LatLng at = point(in);
|
||||||
|
std::string language = field(in, "language");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::AirQuality a(c);
|
||||||
|
a.set_dry_run(dry);
|
||||||
|
return a.current(at, {}, language);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/area", "google-maps-area", [=](const Form& in) -> Action {
|
||||||
|
mp::InsightsFilter f;
|
||||||
|
f.circle_center = point(in);
|
||||||
|
f.circle_radius_meters = integer(in, "radius", 500);
|
||||||
|
if (!field(in, "type").empty()) f.included_types = {field(in, "type")};
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::AreaInsights a(c);
|
||||||
|
a.set_dry_run(dry);
|
||||||
|
return a.compute({"INSIGHT_COUNT"}, f);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/routes", "google-maps-routes", [=](const Form& in) -> Action {
|
||||||
|
mp::ComputeRoutesRequest r;
|
||||||
|
r.origin = waypoint(field(in, "origin"), "origin");
|
||||||
|
r.destination = waypoint(field(in, "destination"), "destination");
|
||||||
|
r.travel_mode = field(in, "mode").empty() ? "DRIVE" : field(in, "mode");
|
||||||
|
std::string fields = field(in, "fields").empty() ? "routes.duration,routes.distanceMeters" : field(in, "fields");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::Routes routes(c);
|
||||||
|
routes.set_dry_run(dry);
|
||||||
|
return routes.compute_routes(r, mp::FieldMask(fields));
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/geocode", "google-maps-geocode", [=](const Form& in) -> Action {
|
||||||
|
std::string address = field(in, "address");
|
||||||
|
bool reverse = address.empty();
|
||||||
|
mp::LatLng at;
|
||||||
|
if (reverse) at = point(in);
|
||||||
|
std::string language = field(in, "language");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::Geocoding g(c);
|
||||||
|
g.set_dry_run(dry);
|
||||||
|
mp::Query q;
|
||||||
|
if (reverse) {
|
||||||
|
at.validate();
|
||||||
|
q.add("latlng", at.to_string());
|
||||||
|
} else {
|
||||||
|
mp::check_text(address, "address");
|
||||||
|
q.add("address", address);
|
||||||
|
}
|
||||||
|
mp::check_code(language, "language");
|
||||||
|
if (!language.empty()) q.add("language", language);
|
||||||
|
return g.raw(q);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/timezone", "google-maps-timezone", [=](const Form& in) -> Action {
|
||||||
|
mp::LatLng at = point(in);
|
||||||
|
long ts = static_cast<long>(number(in, "timestamp", 0, true));
|
||||||
|
std::string language = field(in, "language");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::TimeZone t(c);
|
||||||
|
t.set_dry_run(dry);
|
||||||
|
return t.raw(at, ts, language);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/elevation", "google-maps-elevation", [=](const Form& in) -> Action {
|
||||||
|
std::vector<mp::LatLng> pts;
|
||||||
|
for (const auto& p : split(field(in, "locations"), '|')) pts.push_back(mp::LatLng::parse(p));
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::Elevation e(c);
|
||||||
|
e.set_dry_run(dry);
|
||||||
|
return e.raw_at(pts);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
post("/google/maps/streetview/list", "google-maps-streetview-list", [=](const Form& in) -> Action {
|
||||||
|
int limit = integer(in, "limit", 5);
|
||||||
|
std::string filter = field(in, "filter");
|
||||||
|
return [=](const auto& c, bool dry) {
|
||||||
|
mp::StreetViewPublish s(c);
|
||||||
|
s.set_dry_run(dry);
|
||||||
|
return s.list_photos("", filter, limit);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Destructive: a DELETE, and a dry run unless ?confirm=true.
|
||||||
|
router.del("/google/maps/streetview/photo/{id}", "google-maps-streetview-delete", [demo](fw::Request req) {
|
||||||
|
std::string id = req.param_or("id", "");
|
||||||
|
Form in;
|
||||||
|
in["confirm"] = req.query_or("confirm", "");
|
||||||
|
if (!google::valid_segment(id)) bad("id is empty or has invalid characters");
|
||||||
|
return demo->run(in, [id](const auto& c, bool dry) {
|
||||||
|
mp::StreetViewPublish s(c);
|
||||||
|
s.set_dry_run(dry);
|
||||||
|
return s.delete_photo(id);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Local: lint key restrictions. No credential, no Google call.
|
||||||
|
router.post("/google/maps/keys/lint", "google-maps-keys-lint", [](fw::Request req) {
|
||||||
|
Form in = fw::parse_json_object_flat(req.body);
|
||||||
|
try {
|
||||||
|
mp::KeyRestrictions k;
|
||||||
|
k.allowed_referrers = split(field(in, "referrers"), ',');
|
||||||
|
k.allowed_ips = split(field(in, "ips"), ',');
|
||||||
|
k.api_services = split(field(in, "apis"), ',');
|
||||||
|
k.validate();
|
||||||
|
Json findings = Json::array();
|
||||||
|
for (const auto& f : k.lint()) findings.push(Json(f));
|
||||||
|
Json j = Json::object();
|
||||||
|
j.set("scope", Json("local"));
|
||||||
|
j.set("restrictions", k.to_json());
|
||||||
|
j.set("findings", findings);
|
||||||
|
return json_reply(j);
|
||||||
|
} catch (const google::GoogleError& e) {
|
||||||
|
rethrow(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace molo::example::app
|
} // namespace molo::example::app
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// Google Maps page: thin client over /google/maps/*. Every Google call is a
|
||||||
|
// POST and a dry run until "Call Google" is ticked; the server validates.
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
var $ = function (id) { return document.getElementById(id); };
|
||||||
|
var out = $("m-out"), err = $("m-error");
|
||||||
|
|
||||||
|
function show(text, isError) {
|
||||||
|
(isError ? err : out).textContent = text;
|
||||||
|
if (isError) out.textContent = ""; else err.textContent = "";
|
||||||
|
}
|
||||||
|
function request(method, path, body) {
|
||||||
|
var opts = { method: method, headers: { "Content-Type": "application/json" } };
|
||||||
|
if (body) opts.body = JSON.stringify(body);
|
||||||
|
return fetch(path, opts).then(function (res) {
|
||||||
|
return res.text().then(function (text) {
|
||||||
|
if (!res.ok) {
|
||||||
|
var msg = "HTTP " + res.status;
|
||||||
|
try { var j = JSON.parse(text); msg = (j.error || "") + ": " + (j.message || msg); } catch (e) {}
|
||||||
|
throw new Error(msg);
|
||||||
|
}
|
||||||
|
return JSON.parse(text);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function body() {
|
||||||
|
var q = $("m-q").value, q2 = $("m-q2").value;
|
||||||
|
return {
|
||||||
|
query: q, input: q, address: q, place_id: q, origin: q, destination: q2, filter: q,
|
||||||
|
lines: q, region: q2, locations: q + (q2 ? "|" + q2 : ""),
|
||||||
|
referrers: q, ips: "", apis: q2,
|
||||||
|
lat: $("m-lat").value, lng: $("m-lng").value, radius: $("m-radius").value,
|
||||||
|
timestamp: String(Math.floor(Date.now() / 1000)),
|
||||||
|
confirm: $("m-confirm").checked ? "true" : "false"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function clean(b) {
|
||||||
|
var o = {};
|
||||||
|
Object.keys(b).forEach(function (k) { if (b[k] !== "") o[k] = b[k]; });
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
$("m-run").addEventListener("click", function () {
|
||||||
|
var api = $("m-api").value;
|
||||||
|
var path = "/google/maps/" + api;
|
||||||
|
request("POST", path, clean(body()))
|
||||||
|
.then(function (j) { show(JSON.stringify(j, null, 2), false); })
|
||||||
|
.catch(function (e) { show(e.message, true); });
|
||||||
|
});
|
||||||
|
$("m-calls").addEventListener("click", function () {
|
||||||
|
request("GET", "/google/maps/calls")
|
||||||
|
.then(function (j) { show(JSON.stringify(j, null, 2), false); })
|
||||||
|
.catch(function (e) { show(e.message, true); });
|
||||||
|
});
|
||||||
|
request("GET", "/google/maps/status").then(function (j) {
|
||||||
|
$("m-config").textContent = j.configured
|
||||||
|
? "Credential configured. Maps key: " + (j.maps_key_present ? j.maps_key : "none") + "."
|
||||||
|
: "No Google credential: calls answer 503 until one is configured.";
|
||||||
|
}).catch(function () { $("m-config").textContent = "Status unavailable."; });
|
||||||
|
})();
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
// Routes: every POST that would call Google Maps. No credential is 503
|
||||||
|
// google_not_configured, bad input is 422 before any traffic, GET is 405, and
|
||||||
|
// with a credential but no confirm the answer is a dry run that shows the
|
||||||
|
// exact request and sends nothing.
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "support/GoogleRig.hpp"
|
||||||
|
|
||||||
|
using namespace molo::example::test;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
struct Case {
|
||||||
|
std::string path;
|
||||||
|
std::string good;
|
||||||
|
std::string bad;
|
||||||
|
std::string expect_in_request; // proof of the exact request shape
|
||||||
|
};
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
const std::string json = "application/json";
|
||||||
|
const std::vector<Case> cases = {
|
||||||
|
{"/google/maps/places/search", "{\"query\":\"pizza\",\"limit\":\"3\"}", "{\"query\":\"\"}",
|
||||||
|
"/v1/places:searchText?fields=places.id"},
|
||||||
|
{"/google/maps/places/nearby", "{\"lat\":\"52.37\",\"lng\":\"4.89\",\"radius\":\"300\",\"type\":\"cafe\"}",
|
||||||
|
"{\"lat\":\"99\",\"lng\":\"4.89\"}", "/v1/places:searchNearby"},
|
||||||
|
{"/google/maps/places/autocomplete", "{\"input\":\"Dam\"}", "{}", "/v1/places:autocomplete"},
|
||||||
|
{"/google/maps/places/details", "{\"place_id\":\"ChIJabc\"}", "{\"place_id\":\"a/../b\"}",
|
||||||
|
"/v1/places/ChIJabc?fields="},
|
||||||
|
{"/google/maps/address/validate", "{\"region\":\"NL\",\"lines\":\"Dam 1\"}", "{\"region\":\"NL\"}",
|
||||||
|
"/v1:validateAddress"},
|
||||||
|
{"/google/maps/solar", "{\"lat\":\"52.37\",\"lng\":\"4.89\"}", "{\"lat\":\"x\",\"lng\":\"4\"}",
|
||||||
|
"/v1/buildingInsights:findClosest?location.latitude=52.37"},
|
||||||
|
{"/google/maps/pollen", "{\"lat\":\"52.37\",\"lng\":\"4.89\",\"days\":\"2\"}",
|
||||||
|
"{\"lat\":\"52.37\",\"lng\":\"4.89\",\"days\":\"9\"}", "/v1/forecast:lookup?"},
|
||||||
|
{"/google/maps/air", "{\"lat\":\"52.37\",\"lng\":\"4.89\"}", "{\"lat\":\"52.37\"}",
|
||||||
|
"/v1/currentConditions:lookup"},
|
||||||
|
{"/google/maps/area", "{\"lat\":\"52.37\",\"lng\":\"4.89\",\"radius\":\"500\"}",
|
||||||
|
"{\"lat\":\"52.37\",\"lng\":\"4.89\",\"radius\":\"0\"}", "/v1:computeInsights"},
|
||||||
|
{"/google/maps/routes", "{\"origin\":\"52.37,4.89\",\"destination\":\"Utrecht Centraal\"}",
|
||||||
|
"{\"origin\":\"52.37,4.89\"}", "/directions/v2:computeRoutes?fields=routes.duration"},
|
||||||
|
{"/google/maps/geocode", "{\"address\":\"Dam 1 Amsterdam\"}", "{\"lat\":\"1\"}",
|
||||||
|
"/maps/api/geocode/json?address=Dam%201%20Amsterdam"},
|
||||||
|
{"/google/maps/timezone", "{\"lat\":\"52.37\",\"lng\":\"4.89\",\"timestamp\":\"1700000000\"}",
|
||||||
|
"{\"lat\":\"52.37\",\"lng\":\"4.89\"}", "/maps/api/timezone/json?location=52.3700000"},
|
||||||
|
{"/google/maps/elevation", "{\"locations\":\"52.37,4.89|52.38,4.90\"}", "{\"locations\":\"nope\"}",
|
||||||
|
"/maps/api/elevation/json?locations=52.3700000"},
|
||||||
|
{"/google/maps/streetview/list", "{\"limit\":\"2\"}", "{\"limit\":\"500\"}", "/v1/photos?pageSize=2"},
|
||||||
|
};
|
||||||
|
for (const Case& c : cases) {
|
||||||
|
{
|
||||||
|
GoogleRig rig(false);
|
||||||
|
Fixture f(rig.client);
|
||||||
|
auto res = f.client->post(c.path, c.good, json);
|
||||||
|
check(res.status == 503, c.path + ": no credential is 503");
|
||||||
|
check(contains(res.body, "google_not_configured"), c.path + ": error code google_not_configured");
|
||||||
|
check(contains(res.headers.get("Content-Type"), "application/json"), c.path + ": error body is json");
|
||||||
|
check(rig.mock->send_count() == 0, c.path + ": nothing sent without a credential");
|
||||||
|
}
|
||||||
|
{
|
||||||
|
GoogleRig rig;
|
||||||
|
Fixture f(rig.client);
|
||||||
|
auto bad = f.client->post(c.path, c.bad, json);
|
||||||
|
check(bad.status == 422, c.path + ": bad input is 422");
|
||||||
|
check(contains(bad.body, "validation_error"), c.path + ": error code validation_error");
|
||||||
|
check(f.client->get(c.path).status == 405, c.path + ": get is 405");
|
||||||
|
auto dry = f.client->post(c.path, c.good, json);
|
||||||
|
check(dry.status == 200, c.path + ": dry run is 200");
|
||||||
|
check(contains(dry.body, "\"dry_run\":true"), c.path + ": answer says dry run");
|
||||||
|
check(contains(dry.body, c.expect_in_request), c.path + ": exact request shown (" + c.expect_in_request + ")");
|
||||||
|
check(!contains(dry.body, kTestKey), c.path + ": credential never shown");
|
||||||
|
check(rig.mock->send_count() == 0, c.path + ": side effect: a dry run sends nothing");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return finish("google/maps/calls");
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
// Routes: DELETE /google/maps/streetview/photo/{id} (destructive: dry run
|
||||||
|
// unless ?confirm=true) and POST /google/maps/keys/lint (local, no credential).
|
||||||
|
#include "support/GoogleRig.hpp"
|
||||||
|
|
||||||
|
using namespace molo::example::test;
|
||||||
|
using molo::example::fw::Method;
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
const std::string json = "application/json";
|
||||||
|
{
|
||||||
|
GoogleRig rig(false);
|
||||||
|
Fixture f(rig.client);
|
||||||
|
auto res = f.client->request(Method::Delete, "/google/maps/streetview/photo/p1");
|
||||||
|
check(res.status == 503 && contains(res.body, "google_not_configured"), "delete without credential is 503");
|
||||||
|
check(rig.mock->send_count() == 0, "side effect: nothing sent");
|
||||||
|
}
|
||||||
|
{
|
||||||
|
GoogleRig rig;
|
||||||
|
Fixture f(rig.client);
|
||||||
|
auto res = f.client->request(Method::Delete, "/google/maps/streetview/photo/p1");
|
||||||
|
check(res.status == 200 && contains(res.body, "\"dry_run\":true"), "delete is a dry run by default");
|
||||||
|
check(contains(res.body, "\"method\":\"DELETE\"") && contains(res.body, "/v1/photo/p1"),
|
||||||
|
"dry run shows the DELETE request");
|
||||||
|
check(rig.mock->send_count() == 0, "side effect: the dry run deleted nothing");
|
||||||
|
check(f.client->request(Method::Delete, "/google/maps/streetview/photo/a..b%2Fc").status != 200 ||
|
||||||
|
rig.mock->send_count() == 0,
|
||||||
|
"odd ids never reach Google");
|
||||||
|
check(f.client->get("/google/maps/streetview/photo/p1").status == 405, "get is 405");
|
||||||
|
}
|
||||||
|
{
|
||||||
|
GoogleRig rig(false);
|
||||||
|
Fixture f(rig.client);
|
||||||
|
auto open = f.client->post("/google/maps/keys/lint", "{}", json);
|
||||||
|
check(open.status == 200, "lint works without a credential");
|
||||||
|
check(contains(open.body, "\"scope\":\"local\""), "lint is local");
|
||||||
|
check(contains(open.body, "no application restriction") && contains(open.body, "no API restriction"),
|
||||||
|
"an unrestricted key is reported");
|
||||||
|
auto good = f.client->post("/google/maps/keys/lint",
|
||||||
|
"{\"referrers\":\"https://*.example.com/*\",\"apis\":\"places.googleapis.com\"}", json);
|
||||||
|
check(good.status == 200 && contains(good.body, "\"findings\":[]"), "a restricted key has no findings");
|
||||||
|
check(contains(good.body, "allowedReferrers") && contains(good.body, "apiTargets"), "restrictions rendered");
|
||||||
|
auto both = f.client->post("/google/maps/keys/lint",
|
||||||
|
"{\"referrers\":\"https://a.com/*\",\"ips\":\"1.2.3.4\"}", json);
|
||||||
|
check(both.status == 422, "two application restriction kinds are 422");
|
||||||
|
check(f.client->get("/google/maps/keys/lint").status == 405, "get is 405");
|
||||||
|
}
|
||||||
|
return finish("google/maps/delete_and_keys");
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
// Route: GET /google/maps, /google/maps/status, /google/maps/calls (never call Google)
|
||||||
|
#include "support/GoogleRig.hpp"
|
||||||
|
|
||||||
|
using namespace molo::example::test;
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
{
|
||||||
|
GoogleRig rig;
|
||||||
|
Fixture f(rig.client);
|
||||||
|
auto page = f.client->get("/google/maps");
|
||||||
|
check(page.status == 200, "page is 200");
|
||||||
|
check(contains(page.headers.get("Content-Type"), "text/html"), "page is html");
|
||||||
|
check(contains(page.body, "viewport") || contains(page.body, "Google Maps Platform"), "page renders");
|
||||||
|
check(contains(page.body, "/embedded/google_maps.js"), "page loads its script");
|
||||||
|
|
||||||
|
auto st = f.client->get("/google/maps/status");
|
||||||
|
check(st.status == 200, "status is 200");
|
||||||
|
check(contains(st.headers.get("Content-Type"), "application/json"), "status is json");
|
||||||
|
check(contains(st.body, "\"configured\":true"), "configured with a key");
|
||||||
|
check(contains(st.body, "\"max_points\":512"), "caps shown");
|
||||||
|
check(!contains(st.body, kTestKey), "credential never shown");
|
||||||
|
|
||||||
|
auto calls = f.client->get("/google/maps/calls");
|
||||||
|
check(calls.status == 200, "calls is 200");
|
||||||
|
check(contains(calls.body, "places.places.searchText"), "places search declared");
|
||||||
|
check(contains(calls.body, "\"source\":\"reference\""), "reference rows are marked");
|
||||||
|
check(contains(calls.body, "directions/v2:computeRoutes"), "routes declared");
|
||||||
|
check(!contains(calls.body, kTestKey), "no credential in the table");
|
||||||
|
|
||||||
|
check(f.client->post("/google/maps").status == 405, "page post is 405");
|
||||||
|
check(f.client->post("/google/maps/status").status == 405, "status post is 405");
|
||||||
|
check(f.client->post("/google/maps/calls").status == 405, "calls post is 405");
|
||||||
|
check(rig.mock->send_count() == 0, "side effect: no upstream traffic");
|
||||||
|
}
|
||||||
|
{
|
||||||
|
GoogleRig rig(false);
|
||||||
|
Fixture f(rig.client);
|
||||||
|
check(contains(f.client->get("/google/maps/status").body, "\"configured\":false"),
|
||||||
|
"not configured without a key");
|
||||||
|
check(f.client->get("/google/maps").status == 200, "page works without a credential");
|
||||||
|
}
|
||||||
|
return finish("google/maps/status");
|
||||||
|
}
|
||||||
@@ -0,0 +1,492 @@
|
|||||||
|
// Maps package: deterministic local tests (call table, path rendering,
|
||||||
|
// validation, caps, request shapes through the dry run, key handling, no
|
||||||
|
// credential behavior). No scripted Google replies: shapes are verified
|
||||||
|
// against Google's Discovery documents by src/google/maps/tools/
|
||||||
|
// check_discovery.py and live (see src/google/maps/SPEC.md).
|
||||||
|
#include <memory>
|
||||||
|
#include <set>
|
||||||
|
|
||||||
|
#include "framework.h"
|
||||||
|
#include "clients/transports/mock_transport.h"
|
||||||
|
#include "google/errors.h"
|
||||||
|
#include "google/maps/address_validation.h"
|
||||||
|
#include "google/maps/calls.h"
|
||||||
|
#include "google/maps/caps.h"
|
||||||
|
#include "google/maps/environment.h"
|
||||||
|
#include "google/maps/maps_key.h"
|
||||||
|
#include "google/maps/places.h"
|
||||||
|
#include "google/maps/routes.h"
|
||||||
|
#include "google/maps/street_view.h"
|
||||||
|
#include "google/maps/web_services.h"
|
||||||
|
|
||||||
|
using namespace molo::google;
|
||||||
|
using namespace molo::google::maps;
|
||||||
|
using molo::clients::body::Json;
|
||||||
|
using molo::clients::transports::MockTransport;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
struct Rig {
|
||||||
|
MockTransport* mock;
|
||||||
|
std::shared_ptr<GoogleClient> client;
|
||||||
|
Rig() {
|
||||||
|
auto t = std::make_unique<MockTransport>();
|
||||||
|
mock = t.get();
|
||||||
|
client = std::make_shared<GoogleClient>(std::move(t), nullptr); // no credential
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename F>
|
||||||
|
bool invalid(F&& f) {
|
||||||
|
try {
|
||||||
|
f();
|
||||||
|
} catch (const NotConfiguredError&) {
|
||||||
|
return false; // passed validation, stopped at the credential check
|
||||||
|
} catch (const GoogleError& e) {
|
||||||
|
return e.http_status() == 400 && e.status() == "INVALID_ARGUMENT";
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename F>
|
||||||
|
bool not_configured(F&& f) {
|
||||||
|
try {
|
||||||
|
f();
|
||||||
|
} catch (const NotConfiguredError&) {
|
||||||
|
return true;
|
||||||
|
} catch (...) {
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const LatLng kAmsterdam{52.3702157, 4.8951679};
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(maps, call_table_is_unique_and_complete) {
|
||||||
|
std::set<int> calls;
|
||||||
|
std::set<std::string> rpcs;
|
||||||
|
for (std::size_t i = 0; i < call_count(); ++i) {
|
||||||
|
const CallSpec& s = spec_at(i);
|
||||||
|
ASSERT_TRUE(calls.insert(static_cast<int>(s.call)).second);
|
||||||
|
ASSERT_TRUE(rpcs.insert(s.rpc_id).second);
|
||||||
|
ASSERT_TRUE(std::string(s.source) == "discovery" || std::string(s.source) == "reference");
|
||||||
|
ASSERT_EQ(spec_of(s.call).rpc_id, std::string(s.rpc_id));
|
||||||
|
}
|
||||||
|
ASSERT_EQ(call_count(), static_cast<std::size_t>(38));
|
||||||
|
ASSERT_EQ(static_cast<std::size_t>(Call::kApiKeysGet) + 1, call_count());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, path_rendering) {
|
||||||
|
ASSERT_EQ(render(Call::kPlacesGet, {{"name", "places/ChIJabc-_"}}), "/v1/places/ChIJabc-_");
|
||||||
|
ASSERT_EQ(render(Call::kPlacesSearchText), "/v1/places:searchText");
|
||||||
|
ASSERT_EQ(render(Call::kRoutesCompute), "/directions/v2:computeRoutes");
|
||||||
|
ASSERT_EQ(render(Call::kRoutesMatrix), "/distanceMatrix/v2:computeRouteMatrix");
|
||||||
|
ASSERT_EQ(render(Call::kGeocode), "/maps/api/geocode/json");
|
||||||
|
ASSERT_EQ(render(Call::kStreetPhotoGet, {{"photoId", "p1"}}), "/v1/photo/p1");
|
||||||
|
ASSERT_EQ(render(Call::kPollenHeatmapTile, {{"mapType", "TREE_UPI"}, {"zoom", "2"}, {"x", "1"}, {"y", "3"}}),
|
||||||
|
"/v1/mapTypes/TREE_UPI/heatmapTiles/2/1/3");
|
||||||
|
ASSERT_TRUE(invalid([] { render(Call::kPlacesGet, {{"name", "places/../x"}}); }));
|
||||||
|
ASSERT_TRUE(invalid([] { render(Call::kPlacesGet, {{"name", "places//x"}}); }));
|
||||||
|
ASSERT_TRUE(invalid([] { render(Call::kPlacesGet, {}); }));
|
||||||
|
ASSERT_TRUE(invalid([] { render(Call::kPlacesSearchText, {{"extra", "x"}}); }));
|
||||||
|
ASSERT_TRUE(invalid([] { render(Call::kStreetPhotoGet, {{"photoId", "a/b"}}); }));
|
||||||
|
ASSERT_TRUE(method_of(Call::kStreetPhotoUpdate) == molo::clients::Method::kPut);
|
||||||
|
ASSERT_TRUE(method_of(Call::kStreetPhotoDelete) == molo::clients::Method::kDelete);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, endpoints_prefer_key_except_oauth_only_apis) {
|
||||||
|
ASSERT_TRUE(endpoint_of(Api::kPlaces).prefer_key);
|
||||||
|
ASSERT_TRUE(endpoint_of(Api::kWebServices).prefer_key);
|
||||||
|
ASSERT_FALSE(endpoint_of(Api::kStreetViewPublish).prefer_key);
|
||||||
|
ASSERT_FALSE(endpoint_of(Api::kApiKeys).prefer_key);
|
||||||
|
ASSERT_EQ(endpoint_of(Api::kRoutes).base_url, "https://routes.googleapis.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, latlng_and_fieldmask_validation) {
|
||||||
|
ASSERT_TRUE(invalid([] { LatLng{91, 0}.validate(); }));
|
||||||
|
ASSERT_TRUE(invalid([] { LatLng{0, -181}.validate(); }));
|
||||||
|
ASSERT_EQ(kAmsterdam.to_string(), "52.3702157,4.8951679");
|
||||||
|
LatLng p = LatLng::parse("1.5,-2.25");
|
||||||
|
ASSERT_EQ(p.lat, 1.5);
|
||||||
|
ASSERT_EQ(p.lng, -2.25);
|
||||||
|
ASSERT_TRUE(invalid([] { LatLng::parse("abc"); }));
|
||||||
|
ASSERT_TRUE(invalid([] { FieldMask(""); }));
|
||||||
|
ASSERT_TRUE(invalid([] { FieldMask("*"); }));
|
||||||
|
ASSERT_TRUE(invalid([] { FieldMask("places.id,,places.name"); }));
|
||||||
|
ASSERT_TRUE(invalid([] { FieldMask("places.id;drop"); }));
|
||||||
|
ASSERT_TRUE(invalid([] { FieldMask(std::string(1025, 'a')); }));
|
||||||
|
ASSERT_EQ(FieldMask("places.id,places.displayName").str(), "places.id,places.displayName");
|
||||||
|
ASSERT_TRUE(FieldMask::all().is_all());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, query_encoding_and_row_check) {
|
||||||
|
Query q;
|
||||||
|
q.add("a b", "x&y=z");
|
||||||
|
ASSERT_EQ(q.encode(), "?a%20b=x%26y%3Dz");
|
||||||
|
Rig rig;
|
||||||
|
Places places(rig.client);
|
||||||
|
places.set_dry_run(true);
|
||||||
|
// An undeclared query parameter or body field is rejected before sending.
|
||||||
|
struct Probe : Places {
|
||||||
|
using Places::Places;
|
||||||
|
Json bad_query() const { return invoke(Call::kPlacesGet, {{"name", "places/x"}}, Query().add("nope", "1")); }
|
||||||
|
Json bad_field() const {
|
||||||
|
Json b = Json::object();
|
||||||
|
b.set("nope", Json(1));
|
||||||
|
return invoke(Call::kPlacesSearchText, {}, Query(), &b);
|
||||||
|
}
|
||||||
|
Json wrong_api() const { return invoke(Call::kRoutesCompute, {}, Query()); }
|
||||||
|
} probe(rig.client);
|
||||||
|
ASSERT_TRUE(invalid([&] { probe.bad_query(); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { probe.bad_field(); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { probe.wrong_api(); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { Query().add("x", std::string(3000, 'a')); }));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, no_credential_is_loud_and_sends_nothing) {
|
||||||
|
Rig rig;
|
||||||
|
Places places(rig.client);
|
||||||
|
SearchTextRequest r;
|
||||||
|
r.text_query = "pizza";
|
||||||
|
ASSERT_TRUE(not_configured([&] { places.search_text(r, FieldMask("places.id")); }));
|
||||||
|
Geocoding geo(rig.client);
|
||||||
|
ASSERT_TRUE(not_configured([&] { geo.geocode("Dam 1 Amsterdam"); }));
|
||||||
|
ASSERT_TRUE(not_configured([&] { TimeZone(rig.client).lookup(kAmsterdam, 1700000000); }));
|
||||||
|
ASSERT_EQ(rig.mock->send_count(), static_cast<std::size_t>(0));
|
||||||
|
ASSERT_FALSE(Places(rig.client).configured());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, places_request_shapes) {
|
||||||
|
Rig rig;
|
||||||
|
Places places(rig.client);
|
||||||
|
places.set_dry_run(true);
|
||||||
|
SearchTextRequest r;
|
||||||
|
r.text_query = "pizza amsterdam";
|
||||||
|
r.page_size = 5;
|
||||||
|
r.open_now = true;
|
||||||
|
r.language_code = "nl";
|
||||||
|
Json d = places.search_text(r, FieldMask("places.id,places.displayName"));
|
||||||
|
ASSERT_EQ(d.find("method")->as_string(), "POST");
|
||||||
|
ASSERT_EQ(d.find("path")->as_string(), "/v1/places:searchText?fields=places.id%2Cplaces.displayName");
|
||||||
|
ASSERT_EQ(d.find("body")->find("textQuery")->as_string(), "pizza amsterdam");
|
||||||
|
ASSERT_EQ(d.find("body")->find("pageSize")->as_int(), 5);
|
||||||
|
ASSERT_TRUE(d.find("body")->find("openNow")->as_bool());
|
||||||
|
|
||||||
|
SearchNearbyRequest n;
|
||||||
|
n.restriction.center = kAmsterdam;
|
||||||
|
n.restriction.radius_meters = 500;
|
||||||
|
n.included_types = {"restaurant"};
|
||||||
|
n.max_result_count = 3;
|
||||||
|
Json nd = places.search_nearby(n, FieldMask("places.id"));
|
||||||
|
const Json* circle = nd.find("body")->find("locationRestriction")->find("circle");
|
||||||
|
ASSERT_EQ(circle->find("radius")->as_number(), 500.0);
|
||||||
|
ASSERT_EQ(circle->find("center")->find("latitude")->as_number(), 52.3702157);
|
||||||
|
|
||||||
|
Json g = places.get("ChIJabc", FieldMask("id,displayName"), "nl", "NL");
|
||||||
|
ASSERT_EQ(g.find("method")->as_string(), "GET");
|
||||||
|
ASSERT_EQ(g.find("path")->as_string(),
|
||||||
|
"/v1/places/ChIJabc?fields=id%2CdisplayName&languageCode=nl®ionCode=NL");
|
||||||
|
ASSERT_EQ(Places::resource_name("places/x"), "places/x");
|
||||||
|
|
||||||
|
AutocompleteRequest a;
|
||||||
|
a.input = "Dam";
|
||||||
|
a.session_token = "tok";
|
||||||
|
Json ad = places.autocomplete(a);
|
||||||
|
ASSERT_EQ(ad.find("path")->as_string(), "/v1/places:autocomplete");
|
||||||
|
ASSERT_EQ(ad.find("body")->find("sessionToken")->as_string(), "tok");
|
||||||
|
|
||||||
|
Json p = places.photo_uri("places/X/photos/Y_-z", 400, 0);
|
||||||
|
ASSERT_EQ(p.find("path")->as_string(), "/v1/places/X/photos/Y_-z/media?maxWidthPx=400&skipHttpRedirect=true");
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, places_validation) {
|
||||||
|
Rig rig;
|
||||||
|
Places places(rig.client);
|
||||||
|
SearchTextRequest r;
|
||||||
|
ASSERT_TRUE(invalid([&] { places.search_text(r, FieldMask("places.id")); })); // empty query
|
||||||
|
r.text_query = "x";
|
||||||
|
r.page_size = 21;
|
||||||
|
ASSERT_TRUE(invalid([&] { places.search_text(r, FieldMask("places.id")); }));
|
||||||
|
r.page_size = 5;
|
||||||
|
r.min_rating = 6;
|
||||||
|
ASSERT_TRUE(invalid([&] { places.search_text(r, FieldMask("places.id")); }));
|
||||||
|
SearchNearbyRequest n;
|
||||||
|
ASSERT_TRUE(invalid([&] { places.search_nearby(n, FieldMask("places.id")); })); // no area
|
||||||
|
n.restriction.center = kAmsterdam;
|
||||||
|
n.restriction.radius_meters = 50001;
|
||||||
|
ASSERT_TRUE(invalid([&] { places.search_nearby(n, FieldMask("places.id")); }));
|
||||||
|
n.restriction.radius_meters = 100;
|
||||||
|
n.rank_preference = "BEST";
|
||||||
|
ASSERT_TRUE(invalid([&] { places.search_nearby(n, FieldMask("places.id")); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { places.get("a/b/../c", FieldMask("id")); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { places.photo_uri("places/x", 100, 100); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { places.photo_uri("places/x/photos/y", 0, 0); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { places.photo_uri("places/x/photos/y", 4801, 0); }));
|
||||||
|
AutocompleteRequest a;
|
||||||
|
ASSERT_TRUE(invalid([&] { places.autocomplete(a); }));
|
||||||
|
a.input = std::string(513, 'x');
|
||||||
|
ASSERT_TRUE(invalid([&] { places.autocomplete(a); }));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, place_parsing_is_tolerant) {
|
||||||
|
Json doc = Json::parse(
|
||||||
|
"{\"places\":[{\"id\":\"p1\",\"name\":\"places/p1\",\"displayName\":{\"text\":\"Cafe\"},"
|
||||||
|
"\"formattedAddress\":\"Dam 1\",\"location\":{\"latitude\":52.1,\"longitude\":4.2},"
|
||||||
|
"\"types\":[\"cafe\",\"food\"]},{}]}");
|
||||||
|
auto ps = Places::places_of(doc);
|
||||||
|
ASSERT_EQ(ps.size(), static_cast<std::size_t>(2));
|
||||||
|
ASSERT_EQ(ps[0].display_name, "Cafe");
|
||||||
|
ASSERT_EQ(ps[0].types.size(), static_cast<std::size_t>(2));
|
||||||
|
ASSERT_TRUE(ps[0].location.has_value());
|
||||||
|
ASSERT_FALSE(ps[1].location.has_value());
|
||||||
|
ASSERT_EQ(Places::places_of(Json::parse("{}")).size(), static_cast<std::size_t>(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, address_validation) {
|
||||||
|
Rig rig;
|
||||||
|
AddressValidation av(rig.client);
|
||||||
|
av.set_dry_run(true);
|
||||||
|
ValidateAddressRequest r;
|
||||||
|
ASSERT_TRUE(invalid([&] { av.validate(r); })); // no region, no lines
|
||||||
|
r.address.region_code = "NL";
|
||||||
|
r.address.address_lines = {"Dam 1", "1012 JS Amsterdam"};
|
||||||
|
Json d = av.validate(r);
|
||||||
|
ASSERT_EQ(d.find("path")->as_string(), "/v1:validateAddress");
|
||||||
|
ASSERT_EQ(d.find("body")->find("address")->find("regionCode")->as_string(), "NL");
|
||||||
|
ASSERT_EQ(d.find("body")->find("address")->find("addressLines")->as_array().size(), static_cast<std::size_t>(2));
|
||||||
|
r.enable_usps_cass = true;
|
||||||
|
ASSERT_TRUE(invalid([&] { av.validate(r); })); // CASS is US only
|
||||||
|
r.address.address_lines.assign(31, "x");
|
||||||
|
r.enable_usps_cass = false;
|
||||||
|
ASSERT_TRUE(invalid([&] { av.validate(r); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { av.provide_feedback("MAYBE", "id"); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { av.provide_feedback("UNUSED", ""); }));
|
||||||
|
Json f = av.provide_feedback("VALIDATED_VERSION_USED", "resp1");
|
||||||
|
ASSERT_EQ(f.find("path")->as_string(), "/v1:provideValidationFeedback");
|
||||||
|
AddressVerdict v = AddressVerdict::from_json(Json::parse(
|
||||||
|
"{\"responseId\":\"r\",\"result\":{\"verdict\":{\"addressComplete\":true,"
|
||||||
|
"\"validationGranularity\":\"PREMISE\"},\"address\":{\"formattedAddress\":\"Dam 1\"}}}"));
|
||||||
|
ASSERT_TRUE(v.address_complete);
|
||||||
|
ASSERT_EQ(v.formatted_address, "Dam 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, solar_pollen_air_area_shapes) {
|
||||||
|
Rig rig;
|
||||||
|
Solar solar(rig.client);
|
||||||
|
solar.set_dry_run(true);
|
||||||
|
Json s = solar.building_insights(kAmsterdam, "MEDIUM");
|
||||||
|
ASSERT_EQ(s.find("path")->as_string(),
|
||||||
|
"/v1/buildingInsights:findClosest?location.latitude=52.3702157&location.longitude=4.8951679&requiredQuality=MEDIUM");
|
||||||
|
ASSERT_TRUE(invalid([&] { solar.building_insights(kAmsterdam, "BEST"); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { solar.data_layers(kAmsterdam, 1001); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { solar.data_layers(kAmsterdam, 100, "NOPE"); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { solar.data_layers(kAmsterdam, 100, "", "", 2.0); }));
|
||||||
|
ASSERT_EQ(solar.geotiff_path("abc"), "/v1/geoTiff:get?id=abc");
|
||||||
|
|
||||||
|
Pollen pollen(rig.client);
|
||||||
|
pollen.set_dry_run(true);
|
||||||
|
Json p = pollen.forecast(kAmsterdam, 3, "nl");
|
||||||
|
ASSERT_TRUE(p.find("path")->as_string().find("days=3") != std::string::npos);
|
||||||
|
ASSERT_TRUE(invalid([&] { pollen.forecast(kAmsterdam, 6); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { pollen.forecast(kAmsterdam, 0); }));
|
||||||
|
ASSERT_EQ(pollen.heatmap_tile_path("GRASS_UPI", 3, 2, 5), "/v1/mapTypes/GRASS_UPI/heatmapTiles/3/2/5");
|
||||||
|
ASSERT_TRUE(invalid([&] { pollen.heatmap_tile_path("GRASS_UPI", 1, 2, 0); })); // x outside the grid
|
||||||
|
ASSERT_TRUE(invalid([&] { pollen.heatmap_tile_path("MOSS", 1, 0, 0); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { pollen.heatmap_tile_path("TREE_UPI", 21, 0, 0); }));
|
||||||
|
|
||||||
|
AirQuality air(rig.client);
|
||||||
|
air.set_dry_run(true);
|
||||||
|
Json c = air.current(kAmsterdam, {"LOCAL_AQI"}, "nl");
|
||||||
|
ASSERT_EQ(c.find("path")->as_string(), "/v1/currentConditions:lookup");
|
||||||
|
ASSERT_EQ(c.find("body")->find("location")->find("latitude")->as_number(), 52.3702157);
|
||||||
|
ASSERT_EQ(c.find("body")->find("extraComputations")->as_array()[0].as_string(), "LOCAL_AQI");
|
||||||
|
ASSERT_TRUE(invalid([&] { air.current(kAmsterdam, {"FOO"}); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { air.history(kAmsterdam, 721); }));
|
||||||
|
ASSERT_EQ(air.history(kAmsterdam, 24).find("body")->find("hours")->as_int(), 24);
|
||||||
|
ASSERT_TRUE(invalid([&] { air.forecast(kAmsterdam, ""); }));
|
||||||
|
ASSERT_EQ(air.forecast(kAmsterdam, "2026-10-26T12:00:00Z").find("path")->as_string(), "/v1/forecast:lookup");
|
||||||
|
|
||||||
|
AreaInsights area(rig.client);
|
||||||
|
area.set_dry_run(true);
|
||||||
|
InsightsFilter f;
|
||||||
|
ASSERT_TRUE(invalid([&] { area.compute({"INSIGHT_COUNT"}, f); })); // no area
|
||||||
|
f.circle_center = kAmsterdam;
|
||||||
|
f.circle_radius_meters = 1000;
|
||||||
|
f.included_types = {"restaurant"};
|
||||||
|
Json a = area.compute({"INSIGHT_COUNT"}, f);
|
||||||
|
ASSERT_EQ(a.find("path")->as_string(), "/v1:computeInsights");
|
||||||
|
ASSERT_EQ(a.find("body")->find("filter")->find("locationFilter")->find("circle")->find("radius")->as_int(), 1000);
|
||||||
|
ASSERT_TRUE(invalid([&] { area.compute({}, f); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { area.compute({"INSIGHT_ALL"}, f); }));
|
||||||
|
f.region_place = "places/x";
|
||||||
|
ASSERT_TRUE(invalid([&] { area.compute({"INSIGHT_COUNT"}, f); })); // circle and region together
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, routes_shapes_and_caps) {
|
||||||
|
Rig rig;
|
||||||
|
Routes routes(rig.client);
|
||||||
|
routes.set_dry_run(true);
|
||||||
|
ComputeRoutesRequest r;
|
||||||
|
ASSERT_TRUE(invalid([&] { routes.compute_routes(r, FieldMask("routes.duration")); })); // no waypoints
|
||||||
|
r.origin = Waypoint::at(kAmsterdam);
|
||||||
|
r.destination = Waypoint::of_address("Rotterdam Centraal");
|
||||||
|
r.travel_mode = "DRIVE";
|
||||||
|
r.routing_preference = "TRAFFIC_AWARE";
|
||||||
|
Json d = routes.compute_routes(r, FieldMask("routes.duration,routes.distanceMeters"));
|
||||||
|
ASSERT_EQ(d.find("path")->as_string(),
|
||||||
|
"/directions/v2:computeRoutes?fields=routes.duration%2Croutes.distanceMeters");
|
||||||
|
ASSERT_EQ(d.find("body")->find("origin")->find("location")->find("latLng")->find("latitude")->as_number(),
|
||||||
|
52.3702157);
|
||||||
|
ASSERT_EQ(d.find("body")->find("destination")->find("address")->as_string(), "Rotterdam Centraal");
|
||||||
|
r.travel_mode = "WALK"; // traffic preference is for DRIVE / TWO_WHEELER only
|
||||||
|
ASSERT_TRUE(invalid([&] { routes.compute_routes(r, FieldMask("routes.duration")); }));
|
||||||
|
r.routing_preference = "";
|
||||||
|
r.intermediates.assign(26, Waypoint::at(kAmsterdam));
|
||||||
|
ASSERT_TRUE(invalid([&] { routes.compute_routes(r, FieldMask("routes.duration")); }));
|
||||||
|
Waypoint two;
|
||||||
|
two.address = "a";
|
||||||
|
two.place_id = "b";
|
||||||
|
ASSERT_TRUE(invalid([&] { two.validate(); }));
|
||||||
|
|
||||||
|
RouteMatrixRequest m;
|
||||||
|
m.origins.assign(26, Waypoint::at(kAmsterdam));
|
||||||
|
m.destinations = {Waypoint::of_place("ChIJx")};
|
||||||
|
ASSERT_TRUE(invalid([&] { routes.compute_route_matrix(m, FieldMask("originIndex")); }));
|
||||||
|
m.origins.resize(2);
|
||||||
|
Json md = routes.compute_route_matrix(m, FieldMask("originIndex,destinationIndex,duration"));
|
||||||
|
ASSERT_EQ(md.find("path")->as_string(),
|
||||||
|
"/distanceMatrix/v2:computeRouteMatrix?fields=originIndex%2CdestinationIndex%2Cduration");
|
||||||
|
ASSERT_EQ(md.find("body")->find("origins")->as_array()[0].find("waypoint")->find("location") != nullptr, true);
|
||||||
|
ASSERT_EQ(md.find("body")->find("destinations")->as_array()[0].find("waypoint")->find("placeId")->as_string(), "ChIJx");
|
||||||
|
|
||||||
|
auto s = RouteSummary::first_of(Json::parse(
|
||||||
|
"{\"routes\":[{\"distanceMeters\":1234,\"duration\":\"456s\",\"polyline\":{\"encodedPolyline\":\"abc\"}}]}"));
|
||||||
|
ASSERT_TRUE(s.has_value());
|
||||||
|
ASSERT_EQ(s->distance_meters, 1234L);
|
||||||
|
ASSERT_EQ(s->duration_seconds, 456L);
|
||||||
|
ASSERT_FALSE(RouteSummary::first_of(Json::parse("{}")).has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, web_services_shapes_and_status_mapping) {
|
||||||
|
Rig rig;
|
||||||
|
Geocoding geo(rig.client);
|
||||||
|
geo.set_dry_run(true);
|
||||||
|
ASSERT_TRUE(invalid([&] { geo.geocode("", ""); }));
|
||||||
|
geo.geocode("Dam 1, Amsterdam", "country:NL", "nl", "nl");
|
||||||
|
ASSERT_EQ(geo.raw(Query().add("address", "a b")).find("path")->as_string(), "/maps/api/geocode/json?address=a%20b");
|
||||||
|
ASSERT_TRUE(invalid([&] { geo.raw(Query().add("nope", "1")); }));
|
||||||
|
TimeZone tz(rig.client);
|
||||||
|
tz.set_dry_run(true);
|
||||||
|
ASSERT_TRUE(invalid([&] { tz.lookup(kAmsterdam, -1); }));
|
||||||
|
Elevation el(rig.client);
|
||||||
|
el.set_dry_run(true);
|
||||||
|
ASSERT_TRUE(invalid([&] { el.at({}); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { el.along({kAmsterdam}, 5); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { el.along({kAmsterdam, kAmsterdam}, 1); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { el.at(std::vector<LatLng>(513, kAmsterdam)); }));
|
||||||
|
|
||||||
|
// Google answers HTTP 200 with a failure status: it must be loud.
|
||||||
|
struct S : MapsService {
|
||||||
|
using MapsService::MapsService;
|
||||||
|
static void check(const Json& d) { check_web_status(d, "maps"); }
|
||||||
|
};
|
||||||
|
S::check(Json::parse("{\"status\":\"OK\"}"));
|
||||||
|
S::check(Json::parse("{\"status\":\"ZERO_RESULTS\"}"));
|
||||||
|
S::check(Json::parse("{\"status\":\"DATA_NOT_AVAILABLE\"}"));
|
||||||
|
try {
|
||||||
|
S::check(Json::parse("{\"status\":\"REQUEST_DENIED\",\"error_message\":\"bad key\"}"));
|
||||||
|
FAIL("REQUEST_DENIED must throw");
|
||||||
|
} catch (const GoogleError& e) {
|
||||||
|
ASSERT_EQ(e.http_status(), 403);
|
||||||
|
ASSERT_EQ(e.status(), "REQUEST_DENIED");
|
||||||
|
ASSERT_TRUE(e.message().find("bad key") != std::string::npos);
|
||||||
|
}
|
||||||
|
ASSERT_THROW(S::check(Json::parse("{\"status\":\"OVER_QUERY_LIMIT\"}")), GoogleError);
|
||||||
|
ASSERT_THROW(S::check(Json::parse("{}")), GoogleError);
|
||||||
|
|
||||||
|
GeocodeResult g = GeocodeResult::from_json(Json::parse(
|
||||||
|
"{\"formatted_address\":\"Dam 1\",\"place_id\":\"p\",\"geometry\":{\"location_type\":\"ROOFTOP\","
|
||||||
|
"\"location\":{\"lat\":52.3,\"lng\":4.9}},\"types\":[\"street_address\"],\"partial_match\":true}"));
|
||||||
|
ASSERT_EQ(g.location_type, "ROOFTOP");
|
||||||
|
ASSERT_TRUE(g.partial_match);
|
||||||
|
ASSERT_EQ(g.location->lat, 52.3);
|
||||||
|
TimeZoneInfo ti;
|
||||||
|
ti.raw_offset = 3600;
|
||||||
|
ti.dst_offset = 3600;
|
||||||
|
ASSERT_EQ(ti.local_time(1000), 8200L);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, street_view_reads_and_explicit_writes) {
|
||||||
|
Rig rig;
|
||||||
|
StreetViewPublish sv(rig.client);
|
||||||
|
sv.set_dry_run(true);
|
||||||
|
ASSERT_EQ(sv.list_photos("INCLUDE_DOWNLOAD_URL", "placeId=ChIJx", 10).find("path")->as_string(),
|
||||||
|
"/v1/photos?view=INCLUDE_DOWNLOAD_URL&filter=placeId%3DChIJx&pageSize=10");
|
||||||
|
ASSERT_TRUE(invalid([&] { sv.list_photos("FULL"); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { sv.list_photos("", "", 101); }));
|
||||||
|
Json b = sv.batch_get_photos({"a", "b"});
|
||||||
|
ASSERT_EQ(b.find("path")->as_string(), "/v1/photos:batchGet?photoIds=a&photoIds=b");
|
||||||
|
ASSERT_TRUE(invalid([&] { sv.batch_get_photos({}); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { sv.batch_delete_photos({"a/b"}); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { sv.batch_delete_photos(std::vector<std::string>(101, "a")); }));
|
||||||
|
ASSERT_EQ(sv.delete_photo("p1").find("method")->as_string(), "DELETE");
|
||||||
|
ASSERT_EQ(sv.delete_photo_sequence("s1").find("path")->as_string(), "/v1/photoSequence/s1");
|
||||||
|
ASSERT_TRUE(invalid([&] { sv.delete_photo(".."); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { sv.create_photo(Json::object()); })); // uploadReference required
|
||||||
|
Json ph = Json::object();
|
||||||
|
Json ref = Json::object();
|
||||||
|
ref.set("uploadUrl", Json("https://x"));
|
||||||
|
ph.set("uploadReference", ref);
|
||||||
|
ASSERT_EQ(sv.create_photo(ph).find("path")->as_string(), "/v1/photo");
|
||||||
|
ASSERT_TRUE(invalid([&] { sv.update_photo("p1", ph, ""); }));
|
||||||
|
ASSERT_EQ(sv.update_photo("p1", Json::object(), "pose.heading").find("method")->as_string(), "PUT");
|
||||||
|
ASSERT_TRUE(invalid([&] { sv.create_photo_sequence(Json::object(), "AUDIO"); }));
|
||||||
|
// Real (non dry-run) writes stop at the credential check.
|
||||||
|
StreetViewPublish real(rig.client);
|
||||||
|
ASSERT_TRUE(not_configured([&] { real.delete_photo("p1"); }));
|
||||||
|
ASSERT_EQ(rig.mock->send_count(), static_cast<std::size_t>(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps, key_handling) {
|
||||||
|
MapsKey none;
|
||||||
|
ASSERT_FALSE(none.present());
|
||||||
|
ASSERT_EQ(none.redacted(), "");
|
||||||
|
ASSERT_FALSE(none.make_client()->configured());
|
||||||
|
MapsKey good("AIzaSyA1234567890abcdefghijklmnopqrstuv");
|
||||||
|
ASSERT_TRUE(good.present());
|
||||||
|
ASSERT_TRUE(good.looks_like_maps_key());
|
||||||
|
ASSERT_EQ(good.redacted(), "AIza...stuv");
|
||||||
|
ASSERT_TRUE(good.make_client()->configured());
|
||||||
|
ASSERT_FALSE(MapsKey("AQ.Ab8RN6Ixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx").looks_like_maps_key()); // Vertex express key
|
||||||
|
ASSERT_FALSE(MapsKey("short").looks_like_maps_key());
|
||||||
|
ASSERT_EQ(MapsKey("short").redacted(), "****");
|
||||||
|
|
||||||
|
KeyRestrictions k;
|
||||||
|
ASSERT_EQ(k.lint().size(), static_cast<std::size_t>(2)); // unrestricted: loud
|
||||||
|
k.allowed_referrers = {"https://*.example.com/*"};
|
||||||
|
k.api_services = {"places.googleapis.com", "geocoding-backend.googleapis.com"};
|
||||||
|
ASSERT_EQ(k.lint().size(), static_cast<std::size_t>(0));
|
||||||
|
Json j = k.to_json();
|
||||||
|
ASSERT_EQ(j.find("browserKeyRestrictions")->find("allowedReferrers")->as_array().size(), static_cast<std::size_t>(1));
|
||||||
|
ASSERT_EQ(j.find("apiTargets")->as_array()[1].find("service")->as_string(), "geocoding-backend.googleapis.com");
|
||||||
|
KeyRestrictions back = KeyRestrictions::from_json(j);
|
||||||
|
ASSERT_EQ(back.api_services.size(), static_cast<std::size_t>(2));
|
||||||
|
ASSERT_EQ(back.allowed_referrers[0], "https://*.example.com/*");
|
||||||
|
k.allowed_ips = {"1.2.3.4"};
|
||||||
|
ASSERT_TRUE(invalid([&] { k.validate(); })); // two application restriction kinds
|
||||||
|
k.allowed_ips.clear();
|
||||||
|
k.api_services = {"not-a-service"};
|
||||||
|
ASSERT_TRUE(invalid([&] { k.validate(); }));
|
||||||
|
KeyRestrictions open;
|
||||||
|
open.allowed_referrers = {"*"};
|
||||||
|
open.allowed_ips.clear();
|
||||||
|
ASSERT_EQ(open.lint().size(), static_cast<std::size_t>(2)); // wildcard referrer + no API restriction
|
||||||
|
|
||||||
|
Rig rig;
|
||||||
|
ApiKeys keys(rig.client);
|
||||||
|
keys.set_dry_run(true);
|
||||||
|
ASSERT_EQ(keys.list("my-proj", 10).find("path")->as_string(),
|
||||||
|
"/v2/projects/my-proj/locations/global/keys?pageSize=10");
|
||||||
|
ASSERT_TRUE(invalid([&] { keys.list("bad/proj"); }));
|
||||||
|
ASSERT_TRUE(invalid([&] { keys.get("keys/x"); }));
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
// Opt-in live checks for the Maps package (MOLO_LIVE_NET=1, GOOGLE_ACCESS_TOKEN,
|
||||||
|
// GOOGLE_CLOUD_PROJECT). Free and read-only: which Maps services are enabled
|
||||||
|
// on the project (Service Usage) and the API Keys listing. The per-request
|
||||||
|
// billed calls run only with MOLO_LIVE_PAID=1, at most ONE tiny request per
|
||||||
|
// API. A disabled API or a missing Maps key is reported loudly ("API NOT
|
||||||
|
// ENABLED" / "NO MAPS KEY"), never skipped silently. Nothing is created,
|
||||||
|
// changed or deleted. Replies are Google's own, never scripted.
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
#include "framework.h"
|
||||||
|
#include "clients/transports/http_transport.h"
|
||||||
|
#include "google/credentials.h"
|
||||||
|
#include "google/errors.h"
|
||||||
|
#include "google/maps/address_validation.h"
|
||||||
|
#include "google/maps/environment.h"
|
||||||
|
#include "google/maps/maps_key.h"
|
||||||
|
#include "google/maps/places.h"
|
||||||
|
#include "google/maps/routes.h"
|
||||||
|
#include "google/maps/street_view.h"
|
||||||
|
#include "google/maps/web_services.h"
|
||||||
|
#include "google/resource.h"
|
||||||
|
|
||||||
|
using namespace molo::google;
|
||||||
|
using namespace molo::google::maps;
|
||||||
|
using molo::clients::body::Json;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
bool ready() {
|
||||||
|
return std::getenv("MOLO_LIVE_NET") && !Credentials::env("GOOGLE_ACCESS_TOKEN").empty() &&
|
||||||
|
!Credentials::env("GOOGLE_CLOUD_PROJECT").empty();
|
||||||
|
}
|
||||||
|
bool paid() { return std::getenv("MOLO_LIVE_PAID") && std::string(std::getenv("MOLO_LIVE_PAID")) == "1"; }
|
||||||
|
|
||||||
|
// Maps key (classic AIza... only; a Vertex express key is not a Maps key) plus
|
||||||
|
// the OAuth credential, so each API gets the credential it accepts.
|
||||||
|
std::shared_ptr<GoogleClient> maps_client(bool& has_key) {
|
||||||
|
MapsKey key = MapsKey::from_env();
|
||||||
|
has_key = key.looks_like_maps_key();
|
||||||
|
std::shared_ptr<molo::clients::Auth> k = has_key ? Credentials::api_key(Credentials::env("GOOGLE_MAPS_API_KEY").empty()
|
||||||
|
? Credentials::env("GOOGLE_API_KEY")
|
||||||
|
: Credentials::env("GOOGLE_MAPS_API_KEY"))
|
||||||
|
: nullptr;
|
||||||
|
return std::make_shared<GoogleClient>(std::make_unique<molo::clients::transports::HttpTransport>(), k,
|
||||||
|
Credentials::oauth_from_env());
|
||||||
|
}
|
||||||
|
|
||||||
|
// One billed request. Success or a Google refusal that names why (API not
|
||||||
|
// enabled, key problem, quota) is reported; any other failure fails the test.
|
||||||
|
template <typename F>
|
||||||
|
void one(const char* what, F&& f) {
|
||||||
|
try {
|
||||||
|
f();
|
||||||
|
std::cout << " " << what << ": 200 OK\n";
|
||||||
|
} catch (const GoogleError& e) {
|
||||||
|
bool denied = e.http_status() == 403 || e.http_status() == 400 || e.http_status() == 401 ||
|
||||||
|
e.http_status() == 429 || e.status() == "REQUEST_DENIED";
|
||||||
|
std::cout << " " << what << ": " << e.http_status() << " " << e.status() << (denied ? " <-- API NOT ENABLED or credential refused: " : ": ")
|
||||||
|
<< e.message().substr(0, 200) << "\n";
|
||||||
|
ASSERT_TRUE(denied);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(maps_live, enabled_services_and_keys_are_reported) {
|
||||||
|
if (!ready()) {
|
||||||
|
std::cout << "SKIP maps_live.enabled_services_and_keys_are_reported (set MOLO_LIVE_NET=1, "
|
||||||
|
"GOOGLE_ACCESS_TOKEN and GOOGLE_CLOUD_PROJECT)\n";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bool has_key = false;
|
||||||
|
auto client = maps_client(has_key);
|
||||||
|
std::string project = Credentials::env("GOOGLE_CLOUD_PROJECT");
|
||||||
|
ServiceEndpoint usage = endpoints::custom("serviceusage", "https://serviceusage.googleapis.com/v1");
|
||||||
|
int enabled = 0;
|
||||||
|
for (const char* svc : {"places.googleapis.com", "places-backend.googleapis.com", "addressvalidation.googleapis.com",
|
||||||
|
"solar.googleapis.com", "pollen.googleapis.com", "airquality.googleapis.com",
|
||||||
|
"areainsights.googleapis.com", "routes.googleapis.com", "geocoding-backend.googleapis.com",
|
||||||
|
"timezone-backend.googleapis.com", "elevation-backend.googleapis.com",
|
||||||
|
"streetviewpublish.googleapis.com"}) {
|
||||||
|
Json s = client->get_json(usage, "/projects/" + project + "/services/" + svc);
|
||||||
|
const Json* st = s.find("state");
|
||||||
|
bool on = st && st->is_string() && st->as_string() == "ENABLED";
|
||||||
|
enabled += on ? 1 : 0;
|
||||||
|
std::cout << " " << svc << ": " << (on ? "ENABLED" : "API NOT ENABLED") << "\n";
|
||||||
|
}
|
||||||
|
std::cout << " maps services enabled: " << enabled << " of 12; classic Maps key present: "
|
||||||
|
<< (has_key ? "yes" : "NO MAPS KEY (Vertex express keys are not Maps keys)") << "\n";
|
||||||
|
|
||||||
|
ApiKeys keys(client);
|
||||||
|
try {
|
||||||
|
Json l = keys.list(project, 10);
|
||||||
|
auto all = ApiKeys::restrictions_of(l);
|
||||||
|
std::cout << " api keys listed: " << all.size() << "\n";
|
||||||
|
for (const auto& [name, r] : all)
|
||||||
|
for (const auto& f : r.lint()) std::cout << " key lint: " << f << "\n";
|
||||||
|
} catch (const GoogleError& e) {
|
||||||
|
std::cout << " apikeys.list: " << e.http_status() << " " << e.status() << " (API NOT ENABLED?) "
|
||||||
|
<< e.message().substr(0, 160) << "\n";
|
||||||
|
ASSERT_TRUE(e.http_status() == 403);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(maps_live, one_billed_request_per_api) {
|
||||||
|
if (!ready() || !paid()) {
|
||||||
|
std::cout << "SKIP maps_live.one_billed_request_per_api (set MOLO_LIVE_NET=1 and MOLO_LIVE_PAID=1: "
|
||||||
|
"each Maps API bills per request)\n";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bool has_key = false;
|
||||||
|
auto client = maps_client(has_key);
|
||||||
|
if (!has_key) std::cout << " NO MAPS KEY: key-only APIs (Geocoding, Time Zone, Elevation) are expected to be refused\n";
|
||||||
|
const LatLng here{52.3702157, 4.8951679};
|
||||||
|
|
||||||
|
one("places.searchText", [&] {
|
||||||
|
SearchTextRequest r;
|
||||||
|
r.text_query = "Dam Square";
|
||||||
|
r.page_size = 1;
|
||||||
|
Places(client).search_text(r, FieldMask("places.id"));
|
||||||
|
});
|
||||||
|
one("addressvalidation.validateAddress", [&] {
|
||||||
|
ValidateAddressRequest r;
|
||||||
|
r.address.region_code = "NL";
|
||||||
|
r.address.address_lines = {"Dam 1"};
|
||||||
|
AddressValidation(client).validate(r);
|
||||||
|
});
|
||||||
|
one("solar.findClosest", [&] { Solar(client).building_insights(here); });
|
||||||
|
one("pollen.forecast", [&] { Pollen(client).forecast(here, 1); });
|
||||||
|
one("airquality.currentConditions", [&] { AirQuality(client).current(here); });
|
||||||
|
one("areainsights.computeInsights", [&] {
|
||||||
|
InsightsFilter f;
|
||||||
|
f.circle_center = here;
|
||||||
|
f.circle_radius_meters = 200;
|
||||||
|
f.included_types = {"restaurant"};
|
||||||
|
AreaInsights(client).compute({"INSIGHT_COUNT"}, f);
|
||||||
|
});
|
||||||
|
one("routes.computeRoutes", [&] {
|
||||||
|
ComputeRoutesRequest r;
|
||||||
|
r.origin = Waypoint::at(here);
|
||||||
|
r.destination = Waypoint::at({52.0907374, 5.1214201});
|
||||||
|
r.travel_mode = "DRIVE";
|
||||||
|
Routes(client).compute_routes(r, FieldMask("routes.duration,routes.distanceMeters"));
|
||||||
|
});
|
||||||
|
one("geocoding", [&] { Geocoding(client).geocode("Dam 1, Amsterdam"); });
|
||||||
|
one("timezone", [&] { TimeZone(client).lookup(here, 1700000000); });
|
||||||
|
one("elevation", [&] { Elevation(client).at({here}); });
|
||||||
|
one("streetviewpublish.photos.list", [&] { StreetViewPublish(client).list_photos("", "", 1); });
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user