1445 lines
61 KiB
Ruby
1445 lines
61 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/google_saved"
|
|
require_relative "lib/maptool/routing"
|
|
require_relative "lib/maptool/mqtt_client"
|
|
require_relative "lib/maptool/can"
|
|
require_relative "lib/maptool/can_discovery"
|
|
require_relative "lib/maptool/gnss_sim"
|
|
require_relative "lib/maptool/trip"
|
|
require_relative "lib/maptool/trip_log"
|
|
require_relative "lib/maptool/updater"
|
|
require_relative "lib/maptool/sync"
|
|
require "ipaddr"
|
|
require_relative "lib/maptool/live_store"
|
|
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")
|
|
# Revalidate every static file (a cheap 304 when unchanged): /js and
|
|
# /css are cache-busted by ASSET_VERSION below, but the /vendor modules
|
|
# they import (mdi.mjs, nps-symbols.mjs, ...) aren't versioned — with no
|
|
# Cache-Control a browser caches them heuristically for hours, and a
|
|
# deploy that adds an export there (mdi.mjs gaining a new icon) left a
|
|
# tablet with new icons.js + stale mdi.mjs: a failed import, a blank map.
|
|
set :static_cache_control, [:no_cache]
|
|
# 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.
|
|
# expire_after: without it the cookie is a browser-session one, which
|
|
# Android drops whenever it kills the browser/PWA — a fresh Gitea
|
|
# login + MFA every time on the tablet. Counted from login (only the
|
|
# login paths write the cookie, see SkipSessionWrite).
|
|
set :sessions, httponly: true, secure: production?, same_site: :lax,
|
|
expire_after: 90 * 24 * 3600,
|
|
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
|
|
# Google Maps saved lists from a scheduled Google Takeout (product
|
|
# "Saved"), synced into TAKEOUT_DIR (mounted read-only, see
|
|
# docker-compose.yaml): checked hourly, a new export is imported into
|
|
# Tracks & Points under "Google Maps/<list>" (GoogleSaved). Unset = off.
|
|
TAKEOUT_DIR = ENV.fetch("TAKEOUT_DIR", "")
|
|
unless TAKEOUT_DIR.empty? || test?
|
|
Thread.new do
|
|
loop do
|
|
count = GoogleSaved.import_takeout(TAKEOUT_DIR, library: LIBRARY, state_path: File.join(DATA_DIR, "takeout_imported"))
|
|
warn "takeout: imported #{count} saved places" if count
|
|
rescue StandardError => e
|
|
warn "takeout import failed: #{e.class}: #{e.message}"
|
|
ensure
|
|
sleep 3600
|
|
end
|
|
end
|
|
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", "")
|
|
# The home MQTT broker the car's ESPHome nodes publish to (empty = off):
|
|
# mqtt:// or mqtts://, with a read-only user. See LIVE below.
|
|
MQTT_URL = ENV.fetch("MQTT_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"
|
|
)
|
|
|
|
# The car's server (no internet, so no Gitea login): requests from
|
|
# these networks (comma-separated CIDRs) count as logged in. By the
|
|
# socket's own peer address, never X-Forwarded-For — and only for a
|
|
# server no reverse proxy sits in front of (behind one every request
|
|
# comes from the proxy's address). "connected" stands for the subnets
|
|
# the server's own interfaces are on right now (host networking: the
|
|
# Pi's LAN, whichever Wi-Fi it's on), looked up on each request.
|
|
TRUSTED_NETWORKS = ENV.fetch("TRUSTED_NETWORKS", "").split(",").map(&:strip).reject(&:empty?)
|
|
.map { |cidr| cidr == "connected" ? :connected : IPAddr.new(cidr) }
|
|
|
|
# The directly connected subnets: each interface address under its netmask.
|
|
def self.connected_networks
|
|
Socket.getifaddrs.filter_map do |i|
|
|
next unless i.addr&.ip? && i.netmask&.ip?
|
|
|
|
IPAddr.new("#{i.addr.ip_address.split('%').first}/#{i.netmask.ip_address}")
|
|
rescue IPAddr::Error
|
|
nil
|
|
end
|
|
end
|
|
|
|
# Library sync (Sync), OsmAnd-style: brick is the server, a client
|
|
# (the car's) has SYNC_SERVER_URL and syncs on its Sync button. The same
|
|
# SYNC_TOKEN on both: the server's /api/sync/* answer only to it.
|
|
SYNC_TOKEN = ENV.fetch("SYNC_TOKEN", "")
|
|
SYNC_SERVER_URL = ENV.fetch("SYNC_SERVER_URL", "")
|
|
SYNC_CLIENT = SYNC_TOKEN.empty? || SYNC_SERVER_URL.empty? ? nil : Sync.new(server: SYNC_SERVER_URL, token: SYNC_TOKEN, library: LIBRARY, state_path: File.join(DATA_DIR, "sync_state.json"))
|
|
SYNC_MUTEX = Mutex.new
|
|
# Map data the server hands its clients (GET /api/sync/maps, pulled by
|
|
# bin/pull-maps.sh — one way, the server builds it): these files and
|
|
# everything under these directories of DATA_DIR.
|
|
# Of kiwix/ only the ZIM kiwix-serve is given (other ZIMs lying there are GBs).
|
|
MAP_SYNC_FILES = %w[offline.pmtiles offline.pmtiles.meta.json terrain.pmtiles terrain.pmtiles.meta.json offline_regions.json
|
|
kiwix/wikipedia.zim].freeze
|
|
MAP_SYNC_DIRS = %w[routing places hiking_trails nps].freeze
|
|
|
|
# { "relative/path" => absolute path } of the map data there is now;
|
|
# hidden and temporary files (.rsync-partial, *.part, *.tmp) left out,
|
|
# and routing/service.sh (each server copies its own in at boot).
|
|
def self.map_sync_files
|
|
paths = MAP_SYNC_FILES.map { |f| File.join(DATA_DIR, f) } +
|
|
MAP_SYNC_DIRS.flat_map { |d| Dir.glob(File.join(DATA_DIR, d, "**", "*")) }
|
|
paths.select { |p| File.file?(p) }
|
|
.to_h { |p| [p.delete_prefix("#{DATA_DIR}/"), p] }
|
|
.reject { |rel, _| rel.split("/").any? { |part| part.start_with?(".") } || rel.match?(/\.(part|tmp)\z|[\t\n]/) || rel == "routing/service.sh" }
|
|
end
|
|
|
|
helpers do
|
|
def logged_in?
|
|
!!session[:user] || trusted_network?
|
|
end
|
|
|
|
def trusted_network?
|
|
return false if TRUSTED_NETWORKS.empty?
|
|
|
|
address = IPAddr.new(request.env["REMOTE_ADDR"].to_s.delete_prefix("::ffff:"))
|
|
TRUSTED_NETWORKS.flat_map { |n| n == :connected ? App.connected_networks : [n] }.any? { |network| network.include?(address) }
|
|
rescue IPAddr::Error
|
|
false
|
|
end
|
|
|
|
def require_sync_token!
|
|
given = request.env["HTTP_AUTHORIZATION"].to_s.delete_prefix("Bearer ")
|
|
halt 401, json(error: "sync token required") if SYNC_TOKEN.empty? || !Rack::Utils.secure_compare(given, SYNC_TOKEN)
|
|
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.
|
|
# No receiver feeds it for now: gpsd support was dropped, the car's
|
|
# GNSS is to come over CAN (TODO.adoc) and will fill GNSS_LATEST the
|
|
# same way. Polling instead of push (SSE/WebSocket) is deliberate — a
|
|
# receiver 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
|
|
COURSE_MIN_M = 5 # fixes closer than this: too noisy for a course
|
|
COURSE_MIN_SPEED = 1.5 # m/s: slower, the last course stays
|
|
|
|
# Where every GNSS fix lands (the node over CAN, the simulation): into
|
|
# GNSS_LATEST, with the course over ground (track, °) worked out from
|
|
# the fix COURSE_MIN_M back when the receiver sends none — following
|
|
# heading-up from behind (followPosition, gnss.js) turns by it.
|
|
def self.gnss_update(gnss, at: Time.now.to_f)
|
|
fix = GNSS_LATEST_MUTEX.synchronize do
|
|
GNSS_LATEST.merge!(gnss)
|
|
next unless gnss.key?(:lat) || gnss.key?(:lon)
|
|
|
|
GNSS_LATEST[:received_at] = at
|
|
unless gnss.key?(:track)
|
|
position = GNSS_LATEST.values_at(:lon, :lat)
|
|
from = GNSS_LATEST[:course_from]
|
|
if from.nil? || (GNSS_LATEST[:speed] || 0) < COURSE_MIN_SPEED
|
|
GNSS_LATEST[:course_from] = position
|
|
elsif GnssSim.meters(from, position) >= COURSE_MIN_M
|
|
GNSS_LATEST[:track] = GnssSim.bearing(from, position).round(1)
|
|
GNSS_LATEST[:course_from] = position
|
|
end
|
|
end
|
|
GNSS_LATEST.dup
|
|
end
|
|
return unless fix && fix[:lat] && fix[:lon]
|
|
|
|
# a fix's own time when it has one (the simulation's clock, sped up)
|
|
TRIP_LOG.record(fix[:lon], fix[:lat], fix[:alt], gnss[:time].is_a?(Numeric) ? gnss[:time] : at) if TRIP_LOG.active?
|
|
# off the shared trip's route: routed again from here (TripStore#follow)
|
|
|
|
TRIP_STORE.follow([fix[:lon], fix[:lat]], speed: fix[:speed], hdop: fix[:hdop]) do |locations, vehicle, avoid|
|
|
Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s))
|
|
end
|
|
end
|
|
|
|
# Native CAN (lib/maptool/can.rb), on when data/can.json exists: one
|
|
# reader thread per interface. Signals named gnss.<field> (lat, lon,
|
|
# alt, speed in m/s, track in degrees, mode) feed GNSS_LATEST; a fix
|
|
# counts from the frame that brings lat or lon.
|
|
CAN_CONFIG_PATH = File.join(DATA_DIR, "can.json")
|
|
CAN_STORE = Can::Store.new
|
|
# A broken can.json turns CAN off (logged) instead of the whole server.
|
|
CAN_CONFIG, CAN_DECODER = begin
|
|
config = JSON.parse(File.read(CAN_CONFIG_PATH)) if File.exist?(CAN_CONFIG_PATH)
|
|
[config, config && Can::Decoder.new(config.fetch("signals", []))]
|
|
rescue StandardError => e
|
|
warn "can: #{CAN_CONFIG_PATH}: #{e.message} — CAN off"
|
|
[nil, nil]
|
|
end
|
|
# Simulated driving (lib/maptool/gnss_sim.rb) in place of the GNSS node.
|
|
GNSS_SIM = GnssSim.new(VALHALLA_URL)
|
|
|
|
if CAN_CONFIG && !test?
|
|
decoder = CAN_DECODER
|
|
# Our esphome-canopen nodes describe themselves over SDO (can_discovery.rb);
|
|
# can.json's "aliases" name their signals ({"XIAO STM32C5 2.Latitude": "gnss.lat"}).
|
|
if CAN_CONFIG.fetch("discover", true) && (interface = CAN_CONFIG.fetch("interfaces", []).first)
|
|
Can::Discoverer.new(store: CAN_STORE, decoder: decoder, cache_dir: File.join(DATA_DIR, "can_nodes"),
|
|
aliases: CAN_CONFIG.fetch("aliases", {}), interface: interface).start
|
|
end
|
|
CAN_CONFIG.fetch("interfaces", []).each do |interface|
|
|
Thread.new do
|
|
Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"]) do |values|
|
|
gnss = values.filter_map { |name, value| [name.delete_prefix("gnss.").to_sym, value] if name.start_with?("gnss.") }.to_h
|
|
next if gnss.empty? || GNSS_SIM.running?
|
|
|
|
App.gnss_update(gnss)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
# Live data off the home MQTT broker (MQTT_URL), polled by the frontend
|
|
# from /api/live like GNSS above — the "Tracker" and "ITS-G5" overlays:
|
|
# the LTE GNSS tracker's position and USB power (+ its trail, optionally
|
|
# logged), and ITS-G5 stations heard by its receiver. See LiveStore.
|
|
TRACKER_TOPIC = "mcu-tracker/location"
|
|
TRACKER_POWER_TOPIC = "mcu-tracker/binary_sensor/usb_power/state"
|
|
ITS_TOPIC = "mcu-its-g5/decoded"
|
|
LIVE_STORE = LiveStore.new(File.join(DATA_DIR, "live"))
|
|
|
|
def self.record_live(topic, payload, at: Time.now.to_f)
|
|
case topic
|
|
when TRACKER_TOPIC then LIVE_STORE.record_tracker(JSON.parse(payload), at: at)
|
|
when TRACKER_POWER_TOPIC then LIVE_STORE.record_usb_power(payload)
|
|
when ITS_TOPIC then LIVE_STORE.record_its(JSON.parse(payload), at: at)
|
|
end
|
|
rescue JSON::ParserError
|
|
nil
|
|
end
|
|
|
|
unless MQTT_URL.empty?
|
|
Thread.new do
|
|
MqttClient.new(url: MQTT_URL, username: ENV.fetch("MQTT_USERNAME", ""), password: ENV.fetch("MQTT_PASSWORD", ""),
|
|
topics: [TRACKER_TOPIC, TRACKER_POWER_TOPIC, ITS_TOPIC]).each_message { |topic, payload| record_live(topic, payload) }
|
|
end
|
|
end
|
|
|
|
get "/" do
|
|
erb :index, locals: { logged_in: logged_in?, user: session[:user] || "local network", revision: REVISION, sync_client: !SYNC_CLIENT.nil? }
|
|
end
|
|
|
|
# Map legend + symbol browser. A view, not a static public/ page, so it
|
|
# gets the same versioned importmap as the map: as a static page it
|
|
# imported /js/icons.js and /vendor/mdi/mdi.mjs unversioned, and a
|
|
# browser still holding an older copy of either rendered no symbols.
|
|
get "/symbols.html" do
|
|
erb :symbols, layout: false
|
|
end
|
|
|
|
# The GNSS simulation's controls (its API below, login).
|
|
get "/sim.html" do
|
|
erb :sim, layout: false
|
|
end
|
|
|
|
# Every status endpoint on one full-screen page (they need the login).
|
|
get "/status.html" do
|
|
erb :status, layout: false
|
|
end
|
|
|
|
# CANopen diagnostics (polls GET /api/can, which needs the login).
|
|
get "/can.html" do
|
|
erb :can, layout: false
|
|
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
|
|
|
|
# Self-update (lib/maptool/updater.rb), on the car's server only
|
|
# (SELF_UPDATE=1): GET says whether main has a newer commit that passed
|
|
# CI, POST asks the host to install it (bin/update-maptool.sh).
|
|
SELF_UPDATE = ENV["SELF_UPDATE"] == "1"
|
|
UPDATE_REPO = ENV.fetch("UPDATE_REPO", "randy/maptool")
|
|
|
|
get "/api/update" do
|
|
require_login!
|
|
halt json(enabled: false) unless SELF_UPDATE
|
|
|
|
Updater.reset! if params[:fresh] # "Check now": past the 10 min cache
|
|
latest = Updater.latest(GITEA_URL, UPDATE_REPO)
|
|
available = !!latest && latest[:ci] == "success" && latest[:sha] && !latest[:sha].start_with?(REVISION)
|
|
json enabled: true, current: REVISION, latest: latest&.dig(:sha)&.slice(0, 7), ci: latest&.dig(:ci),
|
|
available: available, status: Updater.status(DATA_DIR)
|
|
end
|
|
|
|
post "/api/update" do
|
|
require_login!
|
|
halt 404, json(error: "self-update is off on this server") unless SELF_UPDATE
|
|
|
|
latest = Updater.latest(GITEA_URL, UPDATE_REPO)
|
|
halt 409, json(error: "no newer version that passed CI") unless latest && latest[:ci] == "success" && !latest[:sha].start_with?(REVISION)
|
|
|
|
Updater.request(DATA_DIR, latest[:sha])
|
|
json requested: latest[:sha][0, 7]
|
|
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 continents: PmtilesBuilder.continents, 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
|
|
|
|
# The shared trip (lib/maptool/trip.rb): every screen polls it
|
|
# (?version=N: 204 while it's still N) and edits it with PUT
|
|
# {points: [{lngLat, name, nav}], vehicle, avoid, editing}, routed here.
|
|
# Logged in only — it's this server's own itinerary.
|
|
TRIP_STORE = TripStore.new(File.join(DATA_DIR, "trip.json"))
|
|
# The trip recorded (lib/maptool/trip_log.rb): GET its state (?since=N:
|
|
# the line's coordinates from N on), POST {"name"} starts it — a
|
|
# Trips/<date> <name> folder with the planned route and its stops —
|
|
# DELETE ends it. Every fix goes in meanwhile (App.gnss_update).
|
|
TRIP_LOG = TripLog.new(File.join(DATA_DIR, "trip_log.json"), library: LIBRARY)
|
|
|
|
get "/api/trip/log" do
|
|
require_login!
|
|
json TRIP_LOG.status(since: params[:since])
|
|
end
|
|
|
|
post "/api/trip/log" do
|
|
require_login!
|
|
name = JSON.parse(request.body.read)["name"].to_s
|
|
trip = TRIP_STORE.get
|
|
json folder: TRIP_LOG.start(name, plan: trip[:route], stops: trip[:points])
|
|
rescue JSON::ParserError
|
|
halt 400, json(error: "invalid JSON")
|
|
rescue ArgumentError => e
|
|
halt 409, json(error: e.message)
|
|
end
|
|
|
|
delete "/api/trip/log" do
|
|
require_login!
|
|
json folder: TRIP_LOG.stop
|
|
end
|
|
|
|
get "/api/trip" do
|
|
require_login!
|
|
trip = TRIP_STORE.get
|
|
halt 204 if params[:version] && params[:version].to_i == trip[:version]
|
|
|
|
json trip
|
|
end
|
|
|
|
put "/api/trip" do
|
|
require_login!
|
|
body = JSON.parse(request.body.read, symbolize_names: true)
|
|
halt 400, json(error: "points must be a list of {lngLat: [lon, lat]}") unless body[:points].is_a?(Array) && body[:points].all? { |p| p.is_a?(Hash) && p[:lngLat].is_a?(Array) }
|
|
|
|
json(TRIP_STORE.update(points: body[:points], vehicle: body[:vehicle], avoid: body[:avoid], editing: body[:editing]) do |locations, vehicle, avoid|
|
|
Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s))
|
|
end)
|
|
rescue JSON::ParserError
|
|
halt 400, json(error: "invalid JSON")
|
|
rescue ArgumentError, TypeError, KeyError
|
|
halt 400, json(error: "invalid points")
|
|
end
|
|
|
|
# The road being driven ({"points": [[lon, lat], ...]}, the last few
|
|
# fixes): name and speed limit, for the dashboard. Open like /api/route.
|
|
post "/api/road" do
|
|
points = JSON.parse(request.body.read)["points"]
|
|
halt 400, json(error: "points must be a list of [lon, lat]") unless points.is_a?(Array) && points.all?(Array)
|
|
|
|
json Routing.road(VALHALLA_URL, points.last(10))
|
|
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, `bboxes` ([w, s, e, n] each) which are in view.
|
|
get "/api/hiking-trails" do
|
|
countries = PmtilesBuilder.hiking_trails_countries(DATA_DIR)
|
|
json countries: countries, bboxes: countries.to_h { |code| [code, PmtilesBuilder.country_bbox(code)] }.compact
|
|
end
|
|
|
|
# Fetched client-side only for a country the viewer actually ticks in
|
|
# the Hiking trails checklist, not on page load. :code must be one
|
|
# hiking_trails_countries actually lists — otherwise this would accept
|
|
# an arbitrary ".."-laden path segment.
|
|
get "/tiles/hiking_trails/:code.geojson" do
|
|
halt 404 unless PmtilesBuilder.hiking_trails_countries(DATA_DIR).include?(params[:code])
|
|
|
|
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 client's side of a sync (Sync): its pull (whole rows after
|
|
# ?since=<rev>, an item's source file) and its push (rows, then the
|
|
# source files we said we lack).
|
|
get "/api/sync/changes" do
|
|
require_sync_token!
|
|
json LIBRARY.sync_changes(params[:since] || 0)
|
|
rescue ArgumentError, TypeError
|
|
halt 400, json(error: "since must be a number")
|
|
end
|
|
|
|
get "/api/sync/source/:id" do
|
|
require_sync_token!
|
|
path = LIBRARY.item_source(params[:id])
|
|
halt 404 unless path && File.file?(path)
|
|
send_file path
|
|
end
|
|
|
|
post "/api/sync/apply" do
|
|
require_sync_token!
|
|
missing = LIBRARY.apply_sync(JSON.parse(request.body.read))
|
|
json missing: missing.map { |item| item["id"] }
|
|
rescue JSON::ParserError, Library::InvalidValue
|
|
halt 400, json(error: "bad changes")
|
|
end
|
|
|
|
put "/api/sync/source/:id" do
|
|
require_sync_token!
|
|
row = LIBRARY.source_row(params[:id]) or halt 404
|
|
# Source files never change: one already here stays.
|
|
LIBRARY.store_source(row, request.body.read) unless File.exist?(LIBRARY.source_file(row["type"], row["source_path"]))
|
|
json ok: true
|
|
rescue Library::InvalidValue
|
|
halt 400, json(error: "bad source path")
|
|
end
|
|
|
|
# Map data for bin/pull-maps.sh: one "size<TAB>mtime<TAB>path" line per
|
|
# file, then each file by its path (Range requests resume a cut-off one).
|
|
get "/api/sync/maps" do
|
|
require_sync_token!
|
|
content_type :text
|
|
App.map_sync_files.sort.map { |rel, path| [File.size(path), File.mtime(path).to_i, rel].join("\t") }.join("\n") + "\n"
|
|
end
|
|
|
|
get "/api/sync/maps/file" do
|
|
require_sync_token!
|
|
path = App.map_sync_files[params[:path].to_s] or halt 404
|
|
# Straight through brick's nginx: buffered, it spools the response to
|
|
# a temp file capped at 1 GB (proxy_max_temp_file_size) and a bigger
|
|
# file's download ended there.
|
|
headers "X-Accel-Buffering" => "no"
|
|
send_file path
|
|
end
|
|
|
|
# The Sync button (a client only): pull, then push, now.
|
|
post "/api/sync/run" do
|
|
require_login!
|
|
halt 404, json(error: "not a sync client") unless SYNC_CLIENT
|
|
halt 409, json(error: "a sync is already running") unless SYNC_MUTEX.try_lock
|
|
begin
|
|
json SYNC_CLIENT.run
|
|
rescue *Sync::NETWORK_ERRORS => e
|
|
halt 502, json(error: "sync with #{SYNC_SERVER_URL} failed: #{e.message}")
|
|
ensure
|
|
SYNC_MUTEX.unlock
|
|
end
|
|
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
|
|
|
|
# NPS park maps (the "NPS park maps" overlay, public/js/nps.js): Harpers
|
|
# Ferry Center brochure maps, public domain. data/nps/ holds nps.json (the
|
|
# index: parks with bboxes, maps with download links and, for the 289
|
|
# georeferenced ones, overlay corners) plus overlay/ (JPEGs), geotiff/ and
|
|
# pdf/ — built outside this app by ~/Projects/NPS_Maps/nps-maps.py. Absent
|
|
# = the overlay stays disabled.
|
|
NPS_DIR = File.join(DATA_DIR, "nps")
|
|
|
|
get "/api/nps" do
|
|
path = File.join(NPS_DIR, "nps.json")
|
|
halt 404, json(error: "no NPS data") unless File.exist?(path)
|
|
|
|
cache_control :public, max_age: 3600
|
|
send_file path, type: "application/json"
|
|
end
|
|
|
|
get %r{/nps/(overlay|geotiff|pdf)/([\w.@-]+)} do |kind, name|
|
|
path = File.join(NPS_DIR, kind, name)
|
|
halt 404 unless File.file?(path)
|
|
|
|
cache_control :public, max_age: 86_400
|
|
send_file path, disposition: kind == "geotiff" ? "attachment" : "inline"
|
|
end
|
|
|
|
# What the CAN bus last said: per interface (up, frames, error), per
|
|
# CANopen node (heartbeat state, last seen) and each configured signal.
|
|
get "/api/can" do
|
|
require_login!
|
|
snapshot = CAN_STORE.snapshot
|
|
units = CAN_DECODER ? CAN_DECODER.units : {}
|
|
snapshot[:signals] = snapshot[:signals].to_h { |name, signal| [name, units[name] ? signal.merge(unit: units[name]) : signal] }
|
|
# simulated: the GNSS simulation (/sim.html) stands in for gnss.*
|
|
json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?)
|
|
end
|
|
|
|
# The GNSS simulation: POST {"start": [lon, lat]} drives randomly from
|
|
# there, POST {} from a random place in the offline countries, DELETE
|
|
# stops it, GET says whether it's on (and why it stopped).
|
|
get "/api/sim/gnss" do
|
|
require_login!
|
|
json running: GNSS_SIM.running?, error: GNSS_SIM.error, speedup: GNSS_SIM.speedup, speedups: GnssSim::SPEEDUPS
|
|
end
|
|
|
|
# {"speedup": 1|2|5|10|20}: the simulation's time, faster (also while it runs).
|
|
put "/api/sim/gnss" do
|
|
require_login!
|
|
GNSS_SIM.speedup = JSON.parse(request.body.read)["speedup"]
|
|
json running: GNSS_SIM.running?, error: GNSS_SIM.error, speedup: GNSS_SIM.speedup, speedups: GnssSim::SPEEDUPS
|
|
rescue JSON::ParserError
|
|
halt 400, json(error: "invalid JSON")
|
|
end
|
|
|
|
post "/api/sim/gnss" do
|
|
require_login!
|
|
body = JSON.parse(request.body.read)
|
|
lon, lat = body["start"]
|
|
# {"trip": true}: along the shared trip's route (to try the navigation)
|
|
route = TRIP_STORE.get[:route] if body["trip"]
|
|
halt 422, json(error: "the trip has no route") if body["trip"] && !route
|
|
if route then nil
|
|
elsif lon.nil?
|
|
codes = (PmtilesBuilder.offline_meta(DATA_DIR) || {}).fetch("sources", []).map { |source| source["code"] }
|
|
bboxes = codes.filter_map { |code| PmtilesBuilder.country_bbox(code) }
|
|
halt 422, json(error: "no offline countries to start in") if bboxes.empty?
|
|
elsif !lon.is_a?(Numeric) || !lat.is_a?(Numeric)
|
|
halt 400, json(error: "start must be [lon, lat]")
|
|
end
|
|
|
|
CAN_STORE.override_prefix = "gnss."
|
|
GNSS_SIM.start(lon, lat, bboxes: bboxes, route: route) do |fix|
|
|
CAN_STORE.put(fix.except(:time).transform_keys { |key| "gnss.#{key}" })
|
|
App.gnss_update(fix)
|
|
end
|
|
json running: true
|
|
rescue JSON::ParserError
|
|
halt 400, json(error: "invalid JSON")
|
|
end
|
|
|
|
delete "/api/sim/gnss" do
|
|
require_login!
|
|
GNSS_SIM.stop
|
|
CAN_STORE.override_prefix = nil
|
|
json running: false
|
|
end
|
|
|
|
get "/api/live" do
|
|
require_login!
|
|
json LIVE_STORE.snapshot.merge(available: !MQTT_URL.empty?)
|
|
end
|
|
|
|
# The tracker's name, icon, color, trail logging and trail length.
|
|
put "/api/live/settings" do
|
|
require_login!
|
|
json LIVE_STORE.update_settings(params.slice("name", "icon", "color", "logging", "trail_hours"))
|
|
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.except(:course_from).merge(available: true) : { available: false })
|
|
end
|
|
end
|
|
end
|
|
end
|