Files
moloapp/example/app/google/MapsDemo.cpp
T

465 lines
17 KiB
C++

#include "../GoogleDemos.hpp"
#include <cstdlib>
#include <functional>
#include <memory>
#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 {
// 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) {
auto demo = std::make_shared<MapsDemo>(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