Files
maptool/app.rb
T

968 lines
40 KiB
Ruby

require "sinatra/base"
require "sinatra/json"
require "oauth2"
require "securerandom"
require "zip"
require "stringio"
require_relative "lib/maptool/gpx"
require_relative "lib/maptool/fit"
require_relative "lib/maptool/gpx_store"
require_relative "lib/maptool/library"
require_relative "lib/maptool/routing"
require_relative "lib/maptool/gpsd_client"
require_relative "lib/maptool/livetrack_store"
require_relative "lib/maptool/livetrack_client"
require_relative "lib/maptool/kiwix"
require_relative "lib/maptool/plugins"
require_relative "lib/maptool/pmtiles_builder"
require_relative "lib/maptool/search"
module Maptool
# Only /login, /auth/callback and /logout ever write to session
# (oauth_state, user, session.clear) — everything else only ever reads
# it, if it touches session at all. That still matters:
# Rack::Session::Cookie re-serializes and re-sets the cookie on *every*
# response that so much as read session (Rack::Protection's own CSRF
# check does, on nearly every request) — reflecting whatever cookie
# that particular request happened to arrive with, whether or not
# anything changed. A HAR capture caught the actual failure mode this
# caused: seconds after a successful login, a background poll fired the
# instant the page loads was still carrying the browser's pre-login
# cookie (a client-side timing race across the OAuth redirect chain,
# not something this server controls), and its own re-issued Set-Cookie
# landed *after* the login's, silently overwriting session[:user] with
# nothing logged anywhere to explain it.
#
# A plain Rack middleware, not a Sinatra `before` filter: static assets
# (public_folder — every JS/CSS/font/vendor file) are served by
# Sinatra's own built-in static-file shortcut, which bypasses route and
# filter dispatch entirely but is still wrapped by this, same as every
# other response — each one was independently capable of winning the
# clobbering race a `before` filter alone left uncovered.
class SkipSessionWrite
WRITE_PATHS = %w[/login /auth/callback /logout].freeze
def initialize(app)
@app = app
end
def call(env)
env["rack.session.options"][:skip] = true unless WRITE_PATHS.include?(env["PATH_INFO"])
@app.call(env)
end
end
class App < Sinatra::Base
set :public_folder, File.join(__dir__, "public")
# The PWA manifest (public/manifest.webmanifest) — Rack doesn't know
# this extension and would serve it as application/octet-stream.
mime_type :webmanifest, "application/manifest+json"
set :views, File.join(__dir__, "views")
# sinatra/json defaults to MultiJson, whose `encode` (what
# sinatra-contrib 4.2.1 actually calls) is deprecated in newer
# multi_json versions in favor of a constant this app has no other use
# for — stdlib JSON already does the same job and every use of the
# `json` helper below is a plain hash/array, nothing MultiJson-specific.
set :json_encoder, JSON
# A persistent secret across restarts/redeploys — otherwise every deploy
# would invalidate every logged-in session's cookie (see
# docs/deployment.adoc). Falls back to a random one so the app still
# loads locally/in CI without it set; that fallback just means sessions
# don't survive a restart there, which is fine outside production.
set :sessions, httponly: true, secure: production?, same_site: :lax,
secret: ENV.fetch("SESSION_SECRET") { SecureRandom.hex(32) }
use SkipSessionWrite
# Cache-busts /js and /css requests: browsers (and a caching proxy in
# front of production, see docs/deployment.adoc) hang onto static
# assets for hours, so without this a deploy that changes app.js/css
# can go unnoticed by an already-open tab until that cache expires.
# A fresh value every process start (i.e. every deploy, which restarts
# the container) is enough — it doesn't need to survive restarts.
ASSET_VERSION = Time.now.to_i
# Written by the CI deploy job (.gitea/workflows/ci.yml) right before it
# drops .git from the deployed copy, so this is the only way to tell
# which commit is actually live short of asking the deploy job itself —
# handy for exactly the kind of "did my push actually deploy, or am I
# looking at a stale browser cache" confusion ASSET_VERSION above can't
# answer by itself (that only proves *a* deploy happened recently, not
# *which* one). Absent outside a real deploy (local dev, CI's own
# `check` job), hence the fallback.
REVISION = begin
File.read(File.join(__dir__, "REVISION")).strip
rescue Errno::ENOENT
"dev"
end
# Overridable so the test suite can point this at a throwaway directory
# instead of the real data/ — nothing else needs to set this.
DATA_DIR = ENV.fetch("MAPTOOL_DATA_DIR") { File.join(__dir__, "data") }
OFFLINE_PMTILES_PATH = File.join(DATA_DIR, "offline.pmtiles")
TERRAIN_PMTILES_PATH = File.join(DATA_DIR, "terrain.pmtiles")
# Pre-library uploads (data/gpx/), still read for migrated layers.
GPX_STORE = GpxStore.new(File.join(DATA_DIR, "gpx"))
LIBRARY = Library.new(File.join(DATA_DIR, "library.sqlite"), gpx_store: GPX_STORE,
sources_dir: File.join(DATA_DIR, "library", "sources"))
# Once per parser upgrade, in the background so boot isn't held up.
Thread.new do
warn "library: re-read #{LIBRARY.reparse} track profiles"
rescue StandardError => e
warn "library reparse failed: #{e.message}"
end
LIVETRACK_STORE = LiveTrackStore.new(File.join(DATA_DIR, "livetrack.json"))
# Not under DATA_DIR: unlike everything else there (uploads, PMTiles,
# the kiwix ZIM), a plugin is code, not local data — plugins/overpass-pois
# ships checked into this repo as the reference example of the
# contract. Overridable so tests can point it at a throwaway fixture
# directory. In production this whole directory is baked into the
# image (see Dockerfile's `COPY . .`) and wiped/replaced on every
# deploy along with the rest of the checkout (docs/deployment.adoc) —
# fine for a plugin checked into this repo, not for a private one.
PLUGINS_DIR = ENV.fetch("MAPTOOL_PLUGINS_DIR") { File.join(__dir__, "plugins") }
# A second, optional plugin directory under DATA_DIR — the same
# persistent bind mount as gpx/kiwix (docs/deployment.adoc), so a
# private/scraper plugin (one whose ToS forbids living in this public
# repo) dropped in data/plugins/ survives a redeploy the way PLUGINS_DIR
# above can't. Checked after PLUGINS_DIR (see Plugins.list/run), so a
# same-named private plugin never shadows the built-in one.
PLUGINS_DIRS = [PLUGINS_DIR, File.join(DATA_DIR, "plugins")].freeze
# Shared secret for the Garmin LiveTrack webhook (a Google Apps Script
# watching Gmail for LiveTrack emails, see docs/deployment.adoc) — not a
# Gitea-authenticated user, so it can't use the OAuth2 login flow above.
# Blank means the endpoint is disabled, same fallback story as the
# OAuth2 secrets: fine outside production, nothing works without it set.
LIVETRACK_WEBHOOK_SECRET = ENV.fetch("LIVETRACK_WEBHOOK_SECRET", "")
# An external kiwix-serve instance (see docs/development.adoc), not
# something this app runs itself — blank disables the "Nearby on
# Wikipedia" popup link the same way the other optional-integration
# blanks above do. Only ever reached server-side (the Docker-network
# service name in production, e.g. "http://kiwix:8080") — production
# sits behind a reverse proxy (map.priesol.net) that only forwards to
# this app, so a browser can't reach kiwix-serve directly by any
# hostname/port of its own. GET /kiwix/* below proxies to it instead.
KIWIX_URL = ENV.fetch("KIWIX_URL", "")
# The valhalla container (docker-compose.yaml), reached server side only.
VALHALLA_URL = ENV.fetch("VALHALLA_URL", "")
Routing.install_service_script(DATA_DIR)
# Login delegates to the Gitea instance the user already has an account
# on, rather than maintaining a local username/password — see
# docs/architecture.adoc. Only users listed in ALLOWED_GITEA_USERS may
# write; anyone else can authenticate against Gitea but is still
# refused. No defaults for the OAuth2 client id/secret/user list: blank
# values just mean login (and thus writing) doesn't work, which is fine
# outside production — nothing here is eagerly validated at load time.
GITEA_URL = ENV.fetch("GITEA_URL", "https://git.priesol.net")
ALLOWED_GITEA_USERS = ENV.fetch("MAPTOOL_ALLOWED_GITEA_USER", "").split(",").map(&:strip)
OAUTH_CLIENT = OAuth2::Client.new(
ENV.fetch("GITEA_OAUTH_CLIENT_ID", ""),
ENV.fetch("GITEA_OAUTH_CLIENT_SECRET", ""),
site: GITEA_URL,
authorize_url: "/login/oauth/authorize",
token_url: "/login/oauth/access_token"
)
helpers do
def logged_in?
!!session[:user]
end
def require_login!
halt 401, json(error: "login required", login_url: "/login") unless logged_in?
end
def pmtiles_file_status(path, meta)
return { available: false } unless File.exist?(path)
status = { available: true, size: File.size(path), mtime: File.mtime(path).utc.iso8601 }
meta ? status.merge(meta: meta) : status
end
def callback_url
"#{request.base_url}/auth/callback"
end
# Zip-bomb guard: the entries' *declared* uncompressed sizes are summed
# before anything is extracted, and rubyzip itself (validate_entry_sizes,
# on by default) raises Zip::EntrySizeError if an entry inflates past
# what it declared — so a lying header can't sneak past this either.
MAX_ZIP_UNCOMPRESSED = 500 * 1024 * 1024
def parse_feature
feature = JSON.parse(params[:feature].to_s)
halt 400, json(error: "invalid feature") unless feature.is_a?(Hash) && feature["geometry"]
feature
rescue JSON::ParserError
halt 400, json(error: "invalid feature")
end
# The node's first line as a FIT course (FitCourse), or nil. A route
# planned for a bicycle/foot profile keeps that sport.
def fit_course(geojson, name)
feature = JSON.parse(geojson)["features"].find { |f| f.dig("geometry", "type").to_s.end_with?("LineString") }
return unless feature
props = feature["properties"] || {}
coordinates = feature["geometry"]["type"] == "LineString" ? feature["geometry"]["coordinates"] : feature["geometry"]["coordinates"].flatten(1)
vehicle = props["vehicle"].is_a?(Hash) ? props["vehicle"] : {}
sport = case vehicle["type"]
when "bicycle" then "cycling"
when "foot" then vehicle["speed"].to_f >= 7 ? "running" : "hiking"
else props["activity_type"]
end
points = JSON.parse(geojson)["features"].select { |f| f.dig("geometry", "type") == "Point" }.map do |f|
p = f["properties"] || {}
{ coordinate: f["geometry"]["coordinates"], name: p["name"], hint: [p["name"], p["category"], p["icon"]].compact.join(" ") }
end
FitCourse.encode(coordinates, name: props["name"] || name, sport: sport, duration: props["duration_secs"], points: points)
rescue ArgumentError
nil
end
def save_zip_entries(folder:, io:)
paths = []
Zip::File.open_buffer(io) do |zip|
entries = zip.select { |entry| entry.file? && Library::EXTENSIONS.any? { |ext| entry.name.downcase.end_with?(ext) } }
halt 413, json(error: "zip contents too large") if entries.sum(&:size) > MAX_ZIP_UNCOMPRESSED
entries.each do |entry|
paths.concat(LIBRARY.import(folder: folder, filename: File.basename(entry.name), io: StringIO.new(entry.get_input_stream.read)))
end
end
paths
end
end
get "/login" do
session[:oauth_state] = SecureRandom.hex(16)
redirect OAUTH_CLIENT.auth_code.authorize_url(
redirect_uri: callback_url,
state: session[:oauth_state],
scope: "read:user"
)
end
get "/auth/callback" do
halt 400, "invalid state" unless params[:state] && params[:state] == session.delete(:oauth_state)
token = OAUTH_CLIENT.auth_code.get_token(params[:code], redirect_uri: callback_url)
user = token.get("/api/v1/user").parsed
halt 403, "not authorized" unless ALLOWED_GITEA_USERS.include?(user["login"])
session[:user] = user["login"]
redirect "/"
end
get "/logout" do
session.clear
redirect "/"
end
# Live GNSS position, polled by the frontend from /api/gnss/position. A
# single background thread reads gpsd (if it's running — harmless retry
# loop if not, see GpsdClient) and keeps this updated; polling instead
# of push (SSE/WebSocket) is deliberate — gpsd itself only reports at
# ~1Hz, so there is nothing to gain from a push channel, and it avoids
# Sinatra's `stream(:keep_open)` helper, which — absent an EventMachine
# reactor (i.e. under plain threaded Puma, as here) — busy-loops calling
# its block repeatedly instead of waiting for external writes; fine for
# a single blocking per-message write, not for "register once, get
# pushed to later" like this.
# A fix is only reported back as "available" for this long after it
# last arrived — otherwise a receiver that's lost its fix, or been
# unplugged, would keep showing its last position forever as if it
# were still live.
GNSS_STALE_AFTER = 10 # seconds
GNSS_LATEST = {}
GNSS_LATEST_MUTEX = Mutex.new
Thread.new do
GpsdClient.new.each_position do |position|
GNSS_LATEST_MUTEX.synchronize do
GNSS_LATEST.replace(position)
GNSS_LATEST[:received_at] = Time.now.to_f
end
end
end
get "/" do
erb :index, locals: { logged_in: logged_in?, user: session[:user], revision: REVISION }
end
# A share to the installed app normally never reaches the server: the
# service worker (public/sw.js) takes the POST, parks the files and
# opens the app. Only lands here if no worker is running yet — back to
# the map rather than a 404, the share just has to be repeated.
post "/share-target" do
redirect "/", 303
end
get "/api/health" do
json status: "ok", revision: REVISION
end
get "/api/offline-tiles" do
json pmtiles_file_status(OFFLINE_PMTILES_PATH, PmtilesBuilder.offline_meta(DATA_DIR))
end
# Served as a plain range-request-capable file, not decoded server-side:
# pmtiles.js reads the archive's directory and fetches only the byte
# ranges it needs for the tiles currently on screen.
get "/tiles/offline.pmtiles" do
halt 404 unless File.exist?(OFFLINE_PMTILES_PATH)
send_file OFFLINE_PMTILES_PATH, type: "application/octet-stream"
end
# Compares the recorded build (offline.pmtiles.meta.json) against the
# current latest Protomaps build without rebuilding anything —
# update_available is null (not true/false) if there's no local build
# yet, or the live index couldn't be reached, so the frontend can tell
# "don't know" apart from "no, up to date". Not folded into GET
# /api/offline-tiles above: that route is on the hot path (map.js's own
# topbar-dot check on every page load), this one only gets called when
# the Offline data panel is actually opened.
get "/api/offline-tiles/check-update" do
json update_available: PmtilesBuilder.offline_update_available?(DATA_DIR)
end
# Lists the selectable countries and which of them are currently
# selected (data/offline_regions.json) — read-only, no login needed,
# same tier as the plain availability checks above.
get "/api/offline-regions" do
json available: PmtilesBuilder.available_regions, selected: PmtilesBuilder.selected_regions(DATA_DIR)
end
# Just updates the selection — does not itself start a build, so
# ticking several countries doesn't fire off several rebuilds. The
# frontend follows this with the two build routes below once the user
# is done choosing.
post "/api/offline-regions" do
require_login!
codes = Array(params[:codes])
begin
PmtilesBuilder.set_selected_regions(DATA_DIR, codes)
rescue PmtilesBuilder::BuildError => e
halt 400, json(error: e.message)
end
json ok: true
end
# Regenerates offline.pmtiles for the currently selected regions (see
# POST /api/offline-regions above) by downloading each from Geofabrik
# and tiling them with Planetiler — see lib/maptool/pmtiles_builder.rb.
# Runs in the background; poll build-status below for progress.
post "/api/offline-tiles/build" do
require_login!
begin
PmtilesBuilder.build_offline(data_dir: DATA_DIR)
rescue PmtilesBuilder::BuildError => e
halt 409, json(error: e.message)
end
json status: "started"
end
get "/api/offline-tiles/build-status" do
json PmtilesBuilder.offline_status
end
# Per-step timings of past offline/terrain builds, newest first — the
# "benchmark" to compare a later build against (debug panel).
get "/api/build-history" do
json PmtilesBuilder.build_history(DATA_DIR)
end
# Deletes offline.pmtiles plus its whole per-country download cache —
# a manual "reclaim the space"/"start over" action, distinct from
# unticking countries in the region picker (which only changes what a
# future build covers, doesn't free anything already on disk).
delete "/api/offline-tiles" do
require_login!
begin
PmtilesBuilder.delete_offline_data(DATA_DIR)
rescue PmtilesBuilder::BuildError => e
halt 409, json(error: e.message)
end
json ok: true
end
# What's actually in the per-country download cache right now (not the
# same as offline.pmtiles' own meta.sources — see cached_extracts) —
# read-only, same tier as GET /api/offline-regions above, so the region
# picker can show a size + delete affordance next to each cached
# country regardless of whether it's still selected or already built.
get "/api/offline-tiles/cache" do
json extracts: PmtilesBuilder.cached_extracts(DATA_DIR)
end
# Deletes one country's cached Geofabrik extract only — e.g. to force a
# clean re-download of just that one, or reclaim space for a country
# that's no longer selected (the cache otherwise keeps it indefinitely).
delete "/api/offline-tiles/cache/:code" do
require_login!
begin
PmtilesBuilder.delete_cached_extract(DATA_DIR, params[:code])
rescue PmtilesBuilder::BuildError => e
halt 409, json(error: e.message)
end
json ok: true
end
# Same optional-local-file story as offline.pmtiles above — see
# docs/development.adoc for how to generate one, until then hillshade
# just stays unavailable while the offline basemap is active.
get "/api/terrain-tiles" do
json pmtiles_file_status(TERRAIN_PMTILES_PATH, PmtilesBuilder.terrain_meta(DATA_DIR))
end
get "/tiles/terrain.pmtiles" do
halt 404 unless File.exist?(TERRAIN_PMTILES_PATH)
send_file TERRAIN_PMTILES_PATH, type: "application/octet-stream"
end
# Same reasoning as GET /api/offline-tiles/check-update above.
get "/api/terrain-tiles/check-update" do
json update_available: PmtilesBuilder.terrain_update_available?(DATA_DIR)
end
post "/api/terrain-tiles/build" do
require_login!
begin
PmtilesBuilder.build_terrain(data_dir: DATA_DIR)
rescue PmtilesBuilder::BuildError => e
halt 409, json(error: e.message)
end
json status: "started"
end
get "/api/terrain-tiles/build-status" do
json PmtilesBuilder.terrain_status
end
# Offline routing (lib/maptool/routing.rb): the same status/build/
# build-status/check-update shape as the two rows above, so the Offline
# data panel shows it the same way. Valhalla builds in its own
# container; these only hand it requests and read its status files.
get "/api/routing-tiles" do
json Routing.tiles_status(DATA_DIR, VALHALLA_URL)
end
get "/api/routing-tiles/check-update" do
json update_available: Routing.update_available?(DATA_DIR)
end
post "/api/routing-tiles/build" do
require_login!
begin
Routing.request_build(DATA_DIR)
rescue PmtilesBuilder::BuildError => e
halt 409, json(error: e.message)
end
json status: "started"
end
get "/api/routing-tiles/build-status" do
json Routing.build_status(DATA_DIR)
end
# A route through the posted points ({"locations": [[lon, lat], ...]})
# for the vehicle profile "vehicle" (an id, default the first). Open to anyone, like viewing the map; only
# saving it to the library needs a login.
post "/api/route" do
body = JSON.parse(request.body.read)
locations = body["locations"]
halt 400, json(error: "locations must be a list of [lon, lat]") unless locations.is_a?(Array) && locations.all?(Array)
json Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, body["vehicle"]), body["avoid"])
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
rescue Routing::RouteError => e
halt 422, json(error: e.message)
rescue Routing::Unavailable => e
halt 503, json(error: e.message)
end
# Where the vehicle profile gets in each of `minutes` from `center`
# ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route.
post "/api/isochrone" do
body = JSON.parse(request.body.read)
json Routing.isochrone(VALHALLA_URL, body["center"], body["minutes"], Routing.vehicle(DATA_DIR, body["vehicle"]), body["avoid"])
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
rescue Routing::RouteError => e
halt 422, json(error: e.message)
rescue Routing::Unavailable => e
halt 503, json(error: e.message)
end
get "/api/vehicles" do
json Routing.vehicles(DATA_DIR)
end
put "/api/vehicles" do
require_login!
json Routing.save_vehicles(DATA_DIR, JSON.parse(request.body.read))
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
rescue ArgumentError => e
halt 400, json(error: e.message)
end
# Same reasoning as DELETE /api/offline-tiles above.
delete "/api/terrain-tiles" do
require_login!
begin
PmtilesBuilder.delete_terrain_data(DATA_DIR)
rescue PmtilesBuilder::BuildError => e
halt 409, json(error: e.message)
end
json ok: true
end
# Generated as a step inside POST /api/offline-tiles/build (see
# PmtilesBuilder.extract_hiking_trails) rather than its own separate
# build — it's derived from the exact same per-country .osm.pbf cache
# offline.pmtiles itself already downloads, so there's nothing of its
# own to trigger; DELETE /api/offline-tiles removes it too. One file
# per country (not one combined file) so a viewer only ever fetches
# the country they actually pick in the Hiking trails overlay's own
# checklist (public/js/hiking_trails.js), not every selected country's
# trails at once — `countries` lists which ones exist to build that
# checklist from.
get "/api/hiking-trails" do
json countries: PmtilesBuilder.hiking_trails_countries(DATA_DIR)
end
# Fetched client-side only for a country the viewer actually ticks in
# the Hiking trails checklist, not on page load. :code is constrained
# to exactly what hiking_trails_countries can ever return (two
# uppercase letters) — otherwise this would accept an arbitrary
# ".."-laden path segment.
get "/tiles/hiking_trails/:code.geojson" do
halt 404 unless params[:code].match?(/\A[A-Z]{2}\z/)
path = PmtilesBuilder.hiking_trails_country_path(DATA_DIR, params[:code])
halt 404 unless File.exist?(path)
send_file path, type: "application/geo+json"
end
# The search box's local half (public/js/search.js) — saved layers
# (shown or not), offline hiking trails, the offline place index and
# Kiwix; lat/lng (the map center) puts nearer places first. Read-only
# and login-free like the tree listing: viewing needs no account.
get "/api/search" do
sources = params[:sources].to_s.split(",")
sources = Search::SOURCES.keys if sources.empty?
center = params[:lat] && params[:lng] ? [params[:lat].to_f, params[:lng].to_f] : nil
json results: Search.query(params[:q], library: LIBRARY, data_dir: DATA_DIR, sources: sources,
center: center, kiwix_url: KIWIX_URL)
end
# Pinged once per page load (public/js/map.js) — url is a same-origin
# path (not kiwix-serve's own address, which the browser can't reach
# directly behind the reverse proxy in front of this app), proxied by
# GET /kiwix/* below.
get "/api/kiwix" do
reachable = Kiwix.reachable?(KIWIX_URL)
json available: reachable, url: (reachable ? "/kiwix" : "")
end
# Backs the "Wikipedia" map layer (public/js/gpx.js) — replaces the old
# per-popup "Nearby on Wikipedia" link, which only ever pointed at one
# POI at a time. Read-only and login-free, same as the tree/plugin
# listing routes below: viewing the map needs no account, only writing
# to it does.
get "/api/kiwix/nearby" do
halt 404 if KIWIX_URL.empty?
bbox = %w[south west north east].map { |key| params[key].to_s }
halt 400, json(error: "south, west, north, east are required") if bbox.any?(&:empty?)
json Kiwix.nearby(KIWIX_URL, bbox.map(&:to_f))
end
# Proxies kiwix-serve's own search UI and content pages through this
# app instead of linking the browser to it directly (see KIWIX_URL) —
# kiwix-serve is started with --urlRootLocation=/kiwix
# (docker-compose.yaml), so every link/asset it emits already carries
# this same /kiwix prefix and Just Works through this passthrough. GET
# only: browsing a read-only ZIM archive never needs to write anything.
get "/kiwix/*" do
halt 404 if KIWIX_URL.empty?
response = Kiwix.proxy(KIWIX_URL, "/kiwix/#{params[:splat].first}", request.query_string)
halt 502 unless response
content_type response["content-type"] || "application/octet-stream"
status response.code.to_i
body response.body
end
# Tracks & Points (lib/maptool/library.rb). Reading is login-free like
# the rest of the map; every write needs a login. A node `key` is
# "item:<id>" or "points:<folder id>" (see Library).
get "/api/library/tree" do
json LIBRARY.tree
end
# A .zip (Garmin's bulk/FIT export format) is expanded into its
# .gpx/.fit/.geojson entries, each imported like its own upload.
post "/api/library/import" do
require_login!
file = params[:file]
halt 400, json(error: "file is required") unless file && file[:tempfile]
begin
keys = if file[:filename].to_s.downcase.end_with?(".zip")
save_zip_entries(folder: params[:folder].to_s, io: file[:tempfile])
else
LIBRARY.import(folder: params[:folder].to_s, filename: file[:filename], io: file[:tempfile])
end
rescue Library::InvalidPath
halt 400, json(error: "invalid folder")
rescue Library::ParseError
halt 422, json(error: "could not parse file")
rescue Zip::Error
halt 400, json(error: "invalid zip file")
end
json paths: keys, tree: LIBRARY.tree
end
# ?download=original sends the file the node came from, ?download=geojson
# the node's GeoJSON as an attachment — both login-only, like the other
# export/manage actions; plain viewing on the map isn't.
get "/api/library/node/:key" do
require_login! if params[:download]
key = params[:key]
if params[:download] == "original"
path = LIBRARY.original(key)
halt 404 unless path && File.file?(path)
return send_file(path, filename: File.basename(path), disposition: "attachment")
end
begin
body = LIBRARY.geojson(key)
rescue Library::NotFound, Errno::ENOENT
halt 404
rescue Gpx::ParseError, Fit::ParseError
halt 422, json(error: "could not parse file")
end
name = params[:name].to_s.empty? ? "export" : File.basename(params[:name].to_s)
if params[:download] == "fit"
fit = fit_course(body, name)
halt 422, json(error: "not a track or route") unless fit
content_type "application/vnd.ant.fit"
attachment "#{name}.fit"
return fit
end
content_type :json
attachment "#{name}.geojson" if params[:download]
body
end
delete "/api/library/node/:key" do
require_login!
LIBRARY.delete_node(params[:key])
json tree: LIBRARY.tree
rescue Library::NotFound
halt 404
end
# Rename/recolor a track, route or layer.
patch "/api/library/node/:key" do
require_login!
LIBRARY.update_node(params[:key], name: params[:name], color: params[:color])
json tree: LIBRARY.tree
rescue Library::InvalidValue
halt 400, json(error: "invalid name or color")
rescue Library::NotFound
halt 404
end
# A point into a track/route (body: a GeoJSON Point Feature, as for notes).
post "/api/library/node/:key/points" do
require_login!
id = LIBRARY.add_point(params[:key], parse_feature)
json id: id, tree: LIBRARY.tree
rescue Library::InvalidValue
halt 400, json(error: "a Point feature is required")
rescue Library::NotFound
halt 404
end
# A migrated layer → ordinary items (Library#split_layer).
post "/api/library/node/:key/split" do
require_login!
json paths: LIBRARY.split_layer(params[:key]), tree: LIBRARY.tree
rescue Library::ParseError
halt 422, json(error: "could not parse file")
rescue Library::NotFound
halt 404
end
# The sync feed (Library#changes): everything after ?since=<rev>.
# Login-only, like the other exports.
get "/api/library/changes" do
require_login!
json LIBRARY.changes(params[:since])
rescue Library::InvalidValue
halt 400, json(error: "since must be a number")
end
# A folder (?folder=a/b, "" = top level) for an app: ?flavor=locus is
# one GPX, ?flavor=osmand a zip of favourites.gpx + tracks/.
get "/api/library/export" do
require_login!
folder = params[:folder].to_s
name = folder.split("/").last || "MapTool"
case params[:flavor]
when "locus"
content_type "application/gpx+xml" # before attachment, which doesn't know .gpx
attachment "#{name}.gpx"
LIBRARY.export_gpx(folder)
when "osmand"
files = LIBRARY.export_osmand(folder)
halt 404, json(error: "nothing to export") if files.empty?
content_type "application/zip"
attachment "#{name}-osmand.zip"
Zip::OutputStream.write_buffer do |zip|
files.each do |path, gpx|
zip.put_next_entry(path)
zip.write(gpx)
end
end.string
else
halt 400, json(error: "flavor must be locus or osmand")
end
rescue Library::InvalidPath
halt 400, json(error: "invalid folder")
rescue Library::NotFound
halt 404
end
post "/api/library/move" do
require_login!
key = LIBRARY.move_node(params[:key].to_s, params[:to_folder].to_s)
json path: key, tree: LIBRARY.tree
rescue Library::InvalidPath
halt 400, json(error: "invalid folder")
rescue Library::NotFound
halt 404
end
post "/api/library/folder" do
require_login!
LIBRARY.create_folder(params[:path].to_s)
json tree: LIBRARY.tree
rescue Library::InvalidPath
halt 400, json(error: "invalid path")
end
# Rename (`name`) and/or move (`to_folder`, "" = top level) a folder.
patch "/api/library/folder/*" do
require_login!
path = params[:splat].first
path = LIBRARY.rename_folder(path, params[:name]) if params[:name]
path = LIBRARY.move_folder(path, params[:to_folder].to_s) if params.key?("to_folder")
json path: path, tree: LIBRARY.tree
rescue Library::InvalidPath
halt 400, json(error: "invalid folder")
rescue Library::InvalidValue
halt 409, json(error: "a folder with that name already exists there")
rescue Library::NotFound
halt 404
end
delete "/api/library/folder/*" do
require_login!
LIBRARY.delete_folder(params[:splat].first)
json tree: LIBRARY.tree
rescue Library::InvalidPath
halt 400
rescue Library::NotFound
halt 404
end
# A hand-drawn point/shape (notes.js, measure.js) into a folder.
post "/api/library/notes" do
require_login!
feature = parse_feature
key = LIBRARY.add_note(feature, params[:folder].to_s)
json path: key, tree: LIBRARY.tree
rescue Library::InvalidPath
halt 400, json(error: "invalid folder")
end
# Edit/delete one note from its popup: `path` is the node it's drawn
# in, `id` its properties.id.
put "/api/library/notes" do
require_login!
feature = parse_feature
halt 400, json(error: "path and id are required") if params[:path].to_s.empty? || params[:id].to_s.empty?
LIBRARY.update_feature(params[:path], params[:id], feature)
json ok: true
rescue Library::NotFound, Errno::ENOENT
halt 404, json(error: "note not found")
rescue GpxStore::InvalidPath
halt 400, json(error: "invalid path")
end
delete "/api/library/notes" do
require_login!
halt 400, json(error: "path and id are required") if params[:path].to_s.empty? || params[:id].to_s.empty?
LIBRARY.delete_feature(params[:path], params[:id])
json ok: true
rescue Library::NotFound, Errno::ENOENT
halt 404, json(error: "note not found")
rescue GpxStore::InvalidPath
halt 400, json(error: "invalid path")
end
# Lists whatever import plugins are on disk (see lib/maptool/plugins.rb
# for the contract) — read-only, doesn't need require_login! the way
# actually running one does below.
get "/api/plugins" do
json Plugins.list(PLUGINS_DIRS)
end
# Runs one plugin for the given bbox (the current map viewport, from
# the frontend's "Run for this area" button) and imports its GeoJSON
# output into a folder of its own, named after the area's center and
# the run's time — so one run's POIs stay apart from another's.
post "/api/plugins/:name/run" do
require_login!
bbox = %w[south west north east].map { |key| params[key].to_s }
halt 400, json(error: "south, west, north, east are required") if bbox.any?(&:empty?)
south, west, north, east = bbox.map(&:to_f)
begin
geojson = Plugins.run(PLUGINS_DIRS, params[:name], [south, west, north, east])
rescue Plugins::RunError => e
halt 502, json(error: e.message)
end
center_lat = format("%.2f", (south + north) / 2)
center_lon = format("%.2f", (west + east) / 2)
timestamp = Time.now.strftime("%y%m%d_%H%M")
name = "#{params[:name]}_#{center_lat}_#{center_lon}_#{timestamp}"
keys = LIBRARY.import(folder: name, filename: "#{name}.geojson", io: StringIO.new(JSON.generate(geojson)))
json path: keys.first, tree: LIBRARY.tree
end
# Called by the Apps Script watching Gmail for Garmin LiveTrack emails —
# it only extracts and forwards the session id/token, nothing else.
post "/api/livetrack/session" do
halt 403 if LIVETRACK_WEBHOOK_SECRET.empty? || params[:secret] != LIVETRACK_WEBHOOK_SECRET
session_id = params[:session_id].to_s.strip
session_token = params[:session_token].to_s.strip
halt 400, json(error: "session_id is required") if session_id.empty?
LIVETRACK_STORE.add(session_id, session_token)
json ok: true
end
get "/api/livetrack/sessions" do
json sessions: LIVETRACK_STORE.list
end
# Garmin stops serving a session's live-track page some while after the
# activity ends (its own session/token URL, not the API — see
# LiveTrackClient) — the exact cutoff isn't documented, ~24h is what's
# been observed. Ended sessions old enough to likely be past that are
# verified once at startup (LiveTrackStore#stale_ended already skips
# ones already flagged, so this doesn't re-hit Garmin for the same
# dead session on every restart), so the panel can grey them out up
# front instead of only failing after a user clicks one and waits on
# a fetch.
LIVETRACK_MAP_STALE_AFTER = 24 * 60 * 60 # seconds
Thread.new do
LIVETRACK_STORE.stale_ended(LIVETRACK_MAP_STALE_AFTER).each do |session|
LiveTrackClient.fetch(session["id"], session["token"])
rescue LiveTrackClient::FetchError
LIVETRACK_STORE.mark_unavailable(session["id"])
end
end
# Garmin's own API (livetrack.garmin.com/api/v2/...) 403s a plain server
# request no matter what headers it gets — see LiveTrackClient — so this
# fetches the session page itself and pulls the track out of that.
get "/api/livetrack/sessions/:id/track" do
session = LIVETRACK_STORE.find(params[:id])
halt 404, json(error: "unknown session") unless session
halt 404, json(error: "session has no token") if session["token"].to_s.empty?
begin
result = LiveTrackClient.fetch(session["id"], session["token"])
rescue LiveTrackClient::FetchError => e
halt 502, json(error: "could not fetch track: #{e.message}")
end
summary = LiveTrackClient.summarize(result)
LIVETRACK_STORE.set_summary(session["id"], summary)
points = result.points
coordinates = points.filter_map { |p| p.dig("position", "lon") && p.dig("position", "lat") && [p["position"]["lon"], p["position"]["lat"]] }
halt 502, json(error: "track has no positions") if coordinates.empty?
last = points.last
features = [
{ type: "Feature", geometry: { type: "LineString", coordinates: coordinates }, properties: { "kind" => "actual" } },
{
type: "Feature",
geometry: { type: "Point", coordinates: coordinates.last },
# Merges the session summary in too — the point layer's hover
# popup (public/js/livetrack.js) reads it straight off here
# rather than needing a second fetch against /sessions.
properties: summary.merge(
"time" => last["dateTime"],
"speed_meters_per_sec" => last["speedMetersPerSec"],
"heart_rate_beats_per_min" => last["heartRateBeatsPerMin"]
),
},
]
# Only present when the activity was started from a saved Garmin
# course (see LiveTrackClient#fetch) — plotted separately from the
# actual track ("kind" distinguishes the two LineStrings) since it's
# the planned route, not where the person has actually been.
course_coordinates = result.course&.[]("geoPoints")&.filter_map { |p| p.dig("position", "lon") && p.dig("position", "lat") && [p["position"]["lon"], p["position"]["lat"]] }
if course_coordinates&.any?
features << {
type: "Feature",
geometry: { type: "LineString", coordinates: course_coordinates },
properties: { "kind" => "planned", "name" => result.course["name"] },
}
end
json(type: "FeatureCollection", features: features)
end
get "/api/gnss/position" do
require_login!
GNSS_LATEST_MUTEX.synchronize do
received_at = GNSS_LATEST[:received_at]
fresh = received_at && (Time.now.to_f - received_at) < GNSS_STALE_AFTER
json(fresh ? GNSS_LATEST.merge(available: true) : { available: false })
end
end
end
end