Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf912b96e5 | ||
|
|
6f5f11cb4d |
No files matched your search
@@ -36,6 +36,9 @@
|
||||
/data/library.sqlite*
|
||||
/data/library/
|
||||
|
||||
# Offline routing: Valhalla tiles and its status files (lib/maptool/routing.rb)
|
||||
/data/routing/
|
||||
|
||||
# Garmin LiveTrack session IDs received via webhook
|
||||
/data/livetrack.json
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ independence from connectivity.
|
||||
|
||||
* [x] Installable PWA with a share target — `public/manifest.webmanifest`, `public/sw.js` parks files shared from Android's share sheet (OsmAnd, Locus, mapy.com — the last has no API at all), `public/js/share_import.js` offers to import them into a Tracks & Points folder (login required, files wait until then)
|
||||
* [x] Item-based library replacing the file-based `GpxStore`, phase 1 — `lib/maptool/library.rb`, design in `docs/library-design.adoc`; old files migrated as layers in subfolders
|
||||
* [ ] Library phase 2 — rename/style items and folders, split a layer into items, notes inside layers as items
|
||||
* [x] Library phase 2 — rename/recolor tracks, routes and layers, rename and move (drag) folders, split a migrated layer into items (its notes become items, keeping their ids)
|
||||
* [ ] Change feed + GPX export flavors for OsmAnd/Locus
|
||||
* [ ] Android sync client (MapTool → apps first; apps → MapTool only if their APIs can list data)
|
||||
|
||||
@@ -84,7 +84,10 @@ Deprioritized for now — revisit after the sections above land.
|
||||
|
||||
=== Vanlife features
|
||||
|
||||
* [ ] Offline routing (Valhalla/OSRM) with vehicle parameters (height, weight, width)
|
||||
* [ ] Offline routing with vehicle parameters (height, weight, width) — Valhalla in its own container, design in `docs/routing-design.adoc`
|
||||
** [x] Phase 1: `valhalla` compose service (`bin/routing-service.sh`), builds from the offline map's extracts, "Offline routing" row in the Offline data panel
|
||||
** [ ] Phase 2: `/api/route`, vehicle profile, route panel, save a route to the library
|
||||
** [ ] Phase 3: elevation profile from terrain.pmtiles, isochrones
|
||||
* [ ] Solar calculator — sun path for location/date, shadows from surroundings, camper orientation
|
||||
|
||||
=== HW integration
|
||||
|
||||
@@ -8,6 +8,7 @@ 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"
|
||||
@@ -142,6 +143,9 @@ module Maptool
|
||||
# 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
|
||||
@@ -417,6 +421,32 @@ module Maptool
|
||||
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
|
||||
|
||||
# Same reasoning as DELETE /api/offline-tiles above.
|
||||
delete "/api/terrain-tiles" do
|
||||
require_login!
|
||||
@@ -571,6 +601,27 @@ module Maptool
|
||||
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 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
|
||||
|
||||
post "/api/library/move" do
|
||||
require_login!
|
||||
key = LIBRARY.move_node(params[:key].to_s, params[:to_folder].to_s)
|
||||
@@ -589,6 +640,21 @@ module Maptool
|
||||
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)
|
||||
|
||||
Executable
+103
@@ -0,0 +1,103 @@
|
||||
#!/bin/bash
|
||||
# Runs inside the valhalla container (docker-compose.yaml), which mounts the
|
||||
# whole data/ at /data. maptool copies this script to data/routing/ at boot
|
||||
# (Maptool::Routing.install_service_script), so the container always runs
|
||||
# the version that shipped with the app. See docs/routing-design.adoc.
|
||||
#
|
||||
# Serves data/routing/tiles.tar with valhalla_service, and polls for
|
||||
# data/routing/build-request.json ({"regions": ["SK", ...]}, written by
|
||||
# maptool). A build hard-links those countries' Geofabrik extracts, builds
|
||||
# into staging/ while the old tiles keep serving, then swaps tiles.tar in
|
||||
# and restarts the service. Progress goes to status.json, the build's
|
||||
# output to build.log.
|
||||
set -u
|
||||
|
||||
R=/data/routing
|
||||
S=$R/staging
|
||||
SERVICE_PID=
|
||||
|
||||
status() { # state step [message]
|
||||
local now
|
||||
now=$(date -u +%FT%TZ)
|
||||
python3 - "$R/status.json" "$1" "$2" "${3:-}" "$now" "${STARTED:-$now}" <<'PY'
|
||||
import json, os, sys
|
||||
path, state, step, message, now, started = sys.argv[1:]
|
||||
data = {"state": state, "started_at": started}
|
||||
if step: data["step"] = step
|
||||
if state != "running": data["finished_at"] = now
|
||||
if message: data["message"] = message
|
||||
with open(path + ".tmp", "w") as f: json.dump(data, f)
|
||||
os.replace(path + ".tmp", path)
|
||||
PY
|
||||
}
|
||||
|
||||
config() { # dir
|
||||
valhalla_build_config --mjolnir-tile-dir "$1/tiles" --mjolnir-tile-extract "$1/tiles.tar" \
|
||||
--mjolnir-admin "$1/admins.sqlite" --mjolnir-concurrency "${BUILD_THREADS:-$(( $(nproc) / 2 ))}" \
|
||||
> "$1/valhalla.json"
|
||||
}
|
||||
|
||||
stop_service() {
|
||||
[ -n "$SERVICE_PID" ] || return 0
|
||||
kill "$SERVICE_PID" 2>/dev/null
|
||||
# It can take a long time to exit on SIGTERM; it holds nothing to flush.
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$SERVICE_PID" 2>/dev/null || break; sleep 0.5; done
|
||||
kill -9 "$SERVICE_PID" 2>/dev/null
|
||||
wait "$SERVICE_PID" 2>/dev/null
|
||||
SERVICE_PID=
|
||||
}
|
||||
|
||||
serve() {
|
||||
stop_service
|
||||
[ -f "$R/tiles.tar" ] || return 0
|
||||
valhalla_service "$R/valhalla.json" "${SERVICE_THREADS:-4}" &
|
||||
SERVICE_PID=$!
|
||||
}
|
||||
|
||||
build() {
|
||||
STARTED=$(date -u +%FT%TZ)
|
||||
local regions code
|
||||
rm -rf "$S" "$R/pbf"
|
||||
mkdir -p "$S" "$R/pbf"
|
||||
mv "$R/build-request.json" "$S/request.json"
|
||||
regions=$(python3 -c 'import json,sys; print(" ".join(json.load(open(sys.argv[1]))["regions"]))' "$S/request.json")
|
||||
for code in $regions; do
|
||||
ln "/data/geofabrik_cache/$code.osm.pbf" "$R/pbf/" || { status error "" "no downloaded extract for $code"; return 1; }
|
||||
done
|
||||
: > "$R/build.log"
|
||||
run() { # step command...
|
||||
status running "$1"
|
||||
shift
|
||||
nice -n 10 "$@" >> "$R/build.log" 2>&1 || { status error "" "$(tail -c 2000 "$R/build.log")"; return 1; }
|
||||
}
|
||||
config "$S" &&
|
||||
run "admin areas" valhalla_build_admins -c "$S/valhalla.json" "$R"/pbf/*.osm.pbf &&
|
||||
run "routing graph ($regions)" valhalla_build_tiles -c "$S/valhalla.json" "$R"/pbf/*.osm.pbf &&
|
||||
run "packing tiles" valhalla_build_extract -c "$S/valhalla.json" -v || return 1
|
||||
|
||||
mv "$S/tiles.tar" "$R/tiles.tar"
|
||||
mv "$S/admins.sqlite" "$R/admins.sqlite"
|
||||
config "$R"
|
||||
mv "$S/request.json" "$R/built.json"
|
||||
rm -rf "$S" "$R/pbf"
|
||||
serve
|
||||
status done ""
|
||||
}
|
||||
|
||||
# bash as PID 1 ignores SIGTERM unless trapped: stop promptly on a redeploy.
|
||||
trap 'stop_service; exit 0' TERM INT
|
||||
|
||||
mkdir -p "$R"
|
||||
[ -f "$R/tiles.tar" ] && config "$R"
|
||||
# A build interrupted by a restart (every redeploy restarts the whole
|
||||
# compose project) starts over: its request is still in staging/.
|
||||
if [ -f "$S/request.json" ] && [ ! -f "$R/build-request.json" ]; then
|
||||
mv "$S/request.json" "$R/build-request.json"
|
||||
fi
|
||||
serve
|
||||
while true; do
|
||||
[ -f "$R/build-request.json" ] && build
|
||||
# valhalla_service died (or never started): start it again.
|
||||
if [ -n "$SERVICE_PID" ] && ! kill -0 "$SERVICE_PID" 2>/dev/null; then serve; fi
|
||||
sleep 10 & wait $! # interruptible, so the trap above runs right away
|
||||
done
|
||||
@@ -54,6 +54,8 @@ services:
|
||||
# that only forwards to maptool itself, so app.rb's GET /kiwix/*
|
||||
# proxies to this instead of handing the browser this address.
|
||||
KIWIX_URL: "http://kiwix:8080"
|
||||
# The valhalla service below, same story as KIWIX_URL.
|
||||
VALHALLA_URL: "http://valhalla:8002"
|
||||
volumes:
|
||||
# Uploaded GPX files and the offline PMTiles extract — kept outside
|
||||
# the image so a rebuild/redeploy doesn't wipe them (see
|
||||
@@ -128,6 +130,22 @@ services:
|
||||
# :z, shared for the same reason as maptool's own ./data mount above.
|
||||
- ./data/kiwix/wikipedia.zim:/data/wikipedia.zim:z
|
||||
|
||||
# Offline routing (docs/routing-design.adoc). Valhalla's own image (it
|
||||
# isn't packaged for Debian, so not in maptool's), running
|
||||
# data/routing/service.sh — bin/routing-service.sh, copied there by
|
||||
# maptool at boot so the two always match; the loop below waits for it
|
||||
# on a first start. Mounts the whole data/ (not just data/routing/) so it
|
||||
# can hard-link Geofabrik extracts from data/geofabrik_cache/ (a link
|
||||
# can't cross two bind mounts). Serves port 8002 on the compose network
|
||||
# only, maptool proxies to it.
|
||||
valhalla:
|
||||
image: ghcr.io/valhalla/valhalla:3.9.1
|
||||
restart: unless-stopped
|
||||
command: ["bash", "-c", "until [ -f /data/routing/service.sh ]; do sleep 5; done; exec bash /data/routing/service.sh"]
|
||||
volumes:
|
||||
# :z, shared for the same reason as maptool's own ./data mount above.
|
||||
- ./data:/data:z
|
||||
|
||||
networks:
|
||||
default:
|
||||
enable_ipv6: true
|
||||
@@ -58,7 +58,9 @@ expect this to flip the other way, `/srv/docker` symlinked to
|
||||
references it, and the sync step doesn't need to special-case it
|
||||
the way an earlier version of this layout did) — uploaded GPX
|
||||
files, `offline.pmtiles`, `terrain.pmtiles`, and
|
||||
`kiwix/wikipedia.zim` (see `docs/development.adoc` for each).
|
||||
`kiwix/wikipedia.zim` (see `docs/development.adoc` for each), and
|
||||
`routing/` (the offline routing graph, built and served by the
|
||||
`valhalla` compose service, see `docs/routing-design.adoc`).
|
||||
Persisted via that bind mount, so a redeploy never touches it.
|
||||
Also where a private import plugin belongs (`data/plugins/<name>/`,
|
||||
see `lib/maptool/plugins.rb`'s `PLUGINS_DIRS`) — `build/plugins/`
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
:toc:
|
||||
:toclevels: 2
|
||||
|
||||
Status: *phase 1 implemented* (`lib/maptool/library.rb`, see Decisions); phases 2–4 proposed. Replaces the file-based store behind
|
||||
Status: *phases 1–2 implemented* (`lib/maptool/library.rb`, see Decisions); phases 3–4 proposed. Replaces the file-based store behind
|
||||
Tracks & Points (`GpxStore`) with an item-based library that OsmAnd, Locus
|
||||
Map and the MapTool web app can all be synced against.
|
||||
|
||||
@@ -324,6 +324,23 @@ removed once nothing uses them.
|
||||
* Migration runs on first start (no `library.sqlite` yet); `rake
|
||||
library:migrate` re-runs it (idempotent).
|
||||
|
||||
== Decisions (phase 2)
|
||||
|
||||
* Rename and color apply to tracks, routes and layers (the node in the
|
||||
tree). Color is stored as `properties.color` and drawn as the line
|
||||
color. A layer's color is laid over its legacy GeoJSON when it's served.
|
||||
Single points keep their category color from the GPX.
|
||||
* Folders: rename, and move by dragging one onto another folder (or onto
|
||||
the tree's blank space for the top level). Moving into a folder's own
|
||||
subfolder, or next to a sibling of the same name, is refused.
|
||||
* "Split into items" turns a migrated layer into ordinary items in its
|
||||
folder. Its notes keep their ids, the legacy file is copied to
|
||||
`sources/` as their "original", and the layer is tombstoned.
|
||||
`data/gpx/` isn't touched. A note edited in an unsplit layer still
|
||||
goes to its legacy file.
|
||||
* `GpxStore` stays, since unsplit layers are still drawn from it. It goes
|
||||
away once nothing is a layer any more.
|
||||
|
||||
== Open questions
|
||||
|
||||
* Folder depth over 3 — fine to require Locus Premium?
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
= Offline routing — design
|
||||
:toc:
|
||||
:toclevels: 1
|
||||
|
||||
Status: *phase 1 implemented* (the container, builds, status in the Offline data panel); phases 2–3 proposed.
|
||||
|
||||
== Goal
|
||||
|
||||
Car/camper routing that works with no internet, from the same OSM
|
||||
extracts the offline map is built from, with the vehicle's dimensions
|
||||
(height, width, length, weight) respected, so the route doesn't go
|
||||
under a 3 m bridge or over a 3.5 t bridge. Later on the same engine:
|
||||
an elevation profile of the route and isochrones ("how far in 2 hours").
|
||||
|
||||
== How OsmAnd and Locus do it
|
||||
|
||||
Neither routes on raw OSM. Someone else builds a compact graph once and
|
||||
the phone just downloads it:
|
||||
|
||||
* *OsmAnd*: every `.obf` map file has a routing section (roads with only
|
||||
the tags routing needs) built on OsmAnd's servers. Since 4.6 it also
|
||||
carries precomputed "HH" (highway hierarchy) shortcuts for long
|
||||
routes. Vehicle height/weight/width are profile parameters checked
|
||||
against `maxheight`/`maxweight` at query time.
|
||||
* *Locus*: offline routing goes through BRouter: `.rd5` segment files
|
||||
(5°×5° tiles, built weekly by brouter.de) and profiles scripted at
|
||||
query time. Its lookup tables have no `maxheight`/`maxweight`, so it
|
||||
can't respect vehicle dimensions. It's built for cycling first.
|
||||
|
||||
Valhalla is the same idea: the build (hours, once per map refresh)
|
||||
produces compact tiles with only roads and their restrictions (a
|
||||
fraction of the OSM extract), and queries are A* over those tiles in
|
||||
milliseconds. The difference is only that we build the tiles ourselves
|
||||
from the extracts we already have, instead of downloading someone
|
||||
else's.
|
||||
|
||||
== Engine: Valhalla
|
||||
|
||||
[cols="1,3"]
|
||||
|===
|
||||
| Valhalla
|
||||
| `truck` costing takes height/width/length/weight/axle load per
|
||||
*request*, so one graph serves any vehicle. Has `/isochrone`,
|
||||
`/height` and `/optimized_route` built in. Tiles are a memory-mapped
|
||||
tar, so RAM stays modest even for many countries. Chosen.
|
||||
|
||||
| GraphHopper
|
||||
| Java is already in the image (Planetiler), and custom models can do
|
||||
dimensions too, but the import for ~16 GB of PBF wants a heap close
|
||||
to the server's 30 GB RAM.
|
||||
|
||||
| OSRM
|
||||
| Fastest queries, but restrictions are baked in at build time: one
|
||||
graph per vehicle profile, no dimension parameters per request.
|
||||
|===
|
||||
|
||||
== Data
|
||||
|
||||
The PBF files are already there: `data/geofabrik_cache/<CC>.osm.pbf`,
|
||||
one per country selected for the offline map (`data/offline_regions.json`,
|
||||
currently 14 countries, ~16 GB). Routing uses exactly that set, so
|
||||
there's no second region picker. The files are hard-linked into
|
||||
`data/routing/pbf/` (same file system, no copies, and Geofabrik refreshes
|
||||
don't change a build that's in progress).
|
||||
|
||||
Measured on the server: 16 cores, 30 GB RAM, 780 GB free. Rough
|
||||
expectation for this set: tiles 15–25 GB, a build of a few hours. The
|
||||
build runs at a low priority and the old tiles keep serving while it
|
||||
runs.
|
||||
|
||||
== Containers
|
||||
|
||||
Valhalla isn't packaged for Debian trixie, so it isn't in the maptool
|
||||
image but in its own compose service, `valhalla`, from Valhalla's image
|
||||
`ghcr.io/valhalla/valhalla` (Renovate bumps the tag). It runs
|
||||
`bin/routing-service.sh`, which maptool copies to
|
||||
`data/routing/service.sh` at boot, so the script always matches the
|
||||
deployed app. It mounts the whole `data/`, since a hard link from
|
||||
`data/geofabrik_cache/` can't cross two bind mounts.
|
||||
|
||||
The two sides talk through files in `data/routing/`:
|
||||
|
||||
[cols="1,1,2"]
|
||||
|===
|
||||
| File | Written by | Meaning
|
||||
|
||||
| `build-request.json`
|
||||
| maptool
|
||||
| `{"regions": [...]}`: build these countries.
|
||||
|
||||
| `status.json`
|
||||
| container
|
||||
| `state` (running/done/error), `step`, `started_at`, `message`.
|
||||
|
||||
| `tiles.tar`, `admins.sqlite`, `valhalla.json`
|
||||
| container
|
||||
| The served graph.
|
||||
|
||||
| `built.json`
|
||||
| container
|
||||
| The request the current tiles were built from.
|
||||
|
||||
| `build.log`
|
||||
| container
|
||||
| The last build's output.
|
||||
|===
|
||||
|
||||
The script serves `tiles.tar` with `valhalla_service`, polls for a
|
||||
request every 10 s, and builds into `staging/` while the old tiles keep
|
||||
serving. It runs `valhalla_build_admins`, then `valhalla_build_tiles`,
|
||||
then `valhalla_build_extract`, at `nice 10` with half the cores. When
|
||||
the build succeeds, it swaps the tiles in and restarts the service. A
|
||||
failure keeps the old tiles and puts the end of the log in
|
||||
`status.json`. Every redeploy restarts the whole compose project; a
|
||||
build cut off that way starts over on its own (its request is still in
|
||||
`staging/`).
|
||||
|
||||
No timezone database (`valhalla_build_timezones` downloads one): only
|
||||
time-dependent routing needs it.
|
||||
|
||||
Tested locally with Liechtenstein: the build takes 2 s, a rebuild while
|
||||
serving swaps the tiles in, and a truck route with dimensions comes back.
|
||||
|
||||
== maptool side
|
||||
|
||||
* "Offline routing" row in the Offline data panel, next to the offline
|
||||
map and terrain (`/api/routing-tiles`, same shape). Apply builds all
|
||||
three. A routing request made while the offline map is still
|
||||
downloading extracts waits for it (`Routing.offline_build_finished`).
|
||||
The row says whether the service answers.
|
||||
* `POST /api/route` proxies to Valhalla `/route` with `costing: truck`
|
||||
and the vehicle profile filled in. It's open to everyone, like the
|
||||
map. Login is required only to save the result.
|
||||
* Vehicle profile: height, width, length, weight. Stored server-side,
|
||||
one for now, editable in the route panel.
|
||||
* Route panel: start, end and via points (map click, search result, GPS
|
||||
position, a library point), the route drawn with distance, time and
|
||||
turn list. "Save to library" stores it as a `route` item, so the
|
||||
route goes to OsmAnd/Locus through the same export as everything
|
||||
else.
|
||||
|
||||
== Phases
|
||||
|
||||
. Container + build script + "Build routing" + status. Done when
|
||||
`curl valhalla:8002/route` answers on the server.
|
||||
. `/api/route`, the vehicle profile, the route panel, save to library.
|
||||
. Elevation profile of the route (sampled from `terrain.pmtiles`, which
|
||||
is already there, instead of Valhalla's own SRTM download), then
|
||||
isochrones.
|
||||
|
||||
== Open questions
|
||||
|
||||
* Trailer / several vehicle profiles: one profile until it's needed.
|
||||
* Build time and size for all 14 countries: measure on the first build
|
||||
on the server.
|
||||
@@ -145,6 +145,11 @@ similar); see
|
||||
https://download.mapterhorn.com/attribution.json[their own attribution
|
||||
list] for the full provenance.
|
||||
|
||||
Offline routing runs https://github.com/valhalla/valhalla[Valhalla]
|
||||
(MIT) in its own container from Valhalla's published image
|
||||
(`ghcr.io/valhalla/valhalla`, version pinned in `docker-compose.yaml`),
|
||||
over the same Geofabrik extracts (ODbL). See `docs/routing-design.adoc`.
|
||||
|
||||
Not a frontend asset like the above, but also baked into this app's own
|
||||
Docker image (not a separate container the way kiwix-serve/gpsd are —
|
||||
see `docs/deployment.adoc`/`docs/development.adoc`): three CLI tools
|
||||
|
||||
+100
-7
@@ -29,6 +29,7 @@ module Maptool
|
||||
class NotFound < StandardError; end
|
||||
class InvalidPath < StandardError; end
|
||||
class ParseError < StandardError; end
|
||||
class InvalidValue < StandardError; end
|
||||
|
||||
ROOT = "root" # folder id in a node key for items with no folder
|
||||
EXTENSIONS = %w[.gpx .fit .geojson].freeze
|
||||
@@ -56,6 +57,7 @@ module Maptool
|
||||
CREATE INDEX IF NOT EXISTS items_folder ON items(folder_id);
|
||||
CREATE INDEX IF NOT EXISTS items_parent ON items(parent_id);
|
||||
CREATE INDEX IF NOT EXISTS items_rev ON items(rev);
|
||||
CREATE INDEX IF NOT EXISTS items_fingerprint ON items(folder_id, fingerprint);
|
||||
CREATE INDEX IF NOT EXISTS folders_rev ON folders(rev);
|
||||
SQL
|
||||
end
|
||||
@@ -90,7 +92,7 @@ module Maptool
|
||||
[db.execute("SELECT id, parent_id, name FROM folders WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE"),
|
||||
db.execute(<<~SQL)]
|
||||
SELECT id, folder_id, parent_id, type, name, source_path,
|
||||
CASE WHEN type = 'layer' THEN properties END
|
||||
CASE WHEN type IN ('layer', 'track', 'route') THEN properties END
|
||||
FROM items WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE
|
||||
SQL
|
||||
end
|
||||
@@ -104,9 +106,10 @@ module Maptool
|
||||
end
|
||||
own = items_in[id] || []
|
||||
nodes = own.select { |i| %w[track route layer].include?(i[3]) }.map do |iid, _, _, type, name, source, props|
|
||||
kinds = type == "layer" ? JSON.parse(props)["kinds"] || [] : [type, *("waypoint" if has_children.include?(iid))]
|
||||
props = JSON.parse(props)
|
||||
kinds = type == "layer" ? props["kinds"] || [] : [type, *("waypoint" if has_children.include?(iid))]
|
||||
{ "type" => "file", "path" => "item:#{iid}", "name" => name.to_s.empty? ? type.capitalize : name,
|
||||
"kinds" => kinds, "original" => !source.nil? }
|
||||
"kinds" => kinds, "original" => !source.nil?, "layer" => type == "layer", "color" => props["color"] }.compact
|
||||
end
|
||||
loose = own.count { |i| %w[point shape].include?(i[3]) && i[2].nil? }
|
||||
if loose.positive?
|
||||
@@ -140,9 +143,9 @@ module Maptool
|
||||
rows = connect do |db|
|
||||
case kind
|
||||
when "item"
|
||||
item = db.get_first_row("SELECT type, source_path FROM items WHERE id = ? AND deleted_at IS NULL", [id])
|
||||
item = db.get_first_row("SELECT type, source_path, properties FROM items WHERE id = ? AND deleted_at IS NULL", [id])
|
||||
raise NotFound unless item
|
||||
return @gpx_store.geojson(item[1]) if item[0] == "layer"
|
||||
return layer_geojson(item[1], JSON.parse(item[2])["color"]) if item[0] == "layer"
|
||||
|
||||
db.execute("#{FEATURE_SQL} AND (id = ? OR parent_id = ?) ORDER BY parent_id IS NOT NULL", [id, id])
|
||||
when "points"
|
||||
@@ -192,6 +195,47 @@ module Maptool
|
||||
add_features([feature], folder).first
|
||||
end
|
||||
|
||||
# Rename and/or recolor a track, route or layer (nil leaves it as is,
|
||||
# an empty color goes back to the default).
|
||||
def update_node(key, name: nil, color: nil)
|
||||
kind, id = key.to_s.split(":", 2)
|
||||
raise NotFound unless kind == "item"
|
||||
raise InvalidValue if color && !color.empty? && !color.match?(/\A#\h{6}\z/)
|
||||
raise InvalidValue if name && name.strip.empty?
|
||||
|
||||
write do |db, rev, now|
|
||||
row = db.get_first_row("SELECT name, properties FROM items WHERE id = ? AND type IN ('track', 'route', 'layer') AND deleted_at IS NULL", [id])
|
||||
raise NotFound unless row
|
||||
|
||||
props = JSON.parse(row[1])
|
||||
props = color.empty? ? props.except("color") : props.merge("color" => color) if color
|
||||
db.execute("UPDATE items SET name = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ?",
|
||||
[name ? name.strip : row[0], JSON.generate(props), now, rev, id])
|
||||
end
|
||||
end
|
||||
|
||||
# A migrated layer → ordinary items in its folder (its notes included,
|
||||
# keeping their ids), the legacy file copied as their original. The
|
||||
# layer is tombstoned; data/gpx/ itself stays untouched.
|
||||
def split_layer(key)
|
||||
kind, id = key.to_s.split(":", 2)
|
||||
row = connect { |db| db.get_first_row("SELECT folder_id, source_path, properties FROM items WHERE id = ? AND type = 'layer' AND deleted_at IS NULL", [id]) }
|
||||
raise NotFound unless kind == "item" && row
|
||||
|
||||
folder, legacy, props = row
|
||||
features = begin
|
||||
JSON.parse(layer_geojson(legacy, JSON.parse(props)["color"]))["features"]
|
||||
rescue Gpx::ParseError, Fit::ParseError, JSON::ParserError => e
|
||||
raise ParseError, e.message
|
||||
end
|
||||
relative = File.join(SecureRandom.uuid, File.basename(legacy))
|
||||
FileUtils.mkdir_p(File.join(@sources_dir, File.dirname(relative)))
|
||||
FileUtils.cp(@gpx_store.resolve_file(legacy), File.join(@sources_dir, relative))
|
||||
keys = add_features(features, folder, source: relative, by_id: true)
|
||||
write { |db, rev, now| tombstone(db, "id = ?", [id], rev, now) }
|
||||
keys
|
||||
end
|
||||
|
||||
# Edit/delete one feature of a node (a note's popup). A layer's notes
|
||||
# still live in its legacy .geojson file, so those go to GpxStore.
|
||||
def update_feature(key, id, feature)
|
||||
@@ -275,6 +319,40 @@ module Maptool
|
||||
end
|
||||
end
|
||||
|
||||
# Returns the folder's new path.
|
||||
def rename_folder(path, name)
|
||||
name = name.to_s.strip
|
||||
raise InvalidPath if name.empty? || name.include?("/") || %w[. ..].include?(name)
|
||||
|
||||
id = folder_id(path, create: false) or raise NotFound
|
||||
write do |db, rev, now|
|
||||
parent = db.get_first_value("SELECT parent_id FROM folders WHERE id = ?", [id])
|
||||
raise InvalidValue if sibling?(db, parent, name, id)
|
||||
|
||||
db.execute("UPDATE folders SET name = ?, updated_at = ?, rev = ? WHERE id = ?", [name, now, rev, id])
|
||||
end
|
||||
[*path.split("/")[0...-1], name].join("/")
|
||||
end
|
||||
|
||||
# Into `to_folder` ("" = top level); returns the folder's new path.
|
||||
def move_folder(path, to_folder)
|
||||
id = folder_id(path, create: false) or raise NotFound
|
||||
target = folder_id(to_folder, create: true)
|
||||
write do |db, rev, now|
|
||||
ancestor = target
|
||||
while ancestor
|
||||
raise InvalidPath if ancestor == id # into itself or its own subfolder
|
||||
|
||||
ancestor = db.get_first_value("SELECT parent_id FROM folders WHERE id = ?", [ancestor])
|
||||
end
|
||||
name = db.get_first_value("SELECT name FROM folders WHERE id = ?", [id])
|
||||
raise InvalidValue if sibling?(db, target, name, id)
|
||||
|
||||
db.execute("UPDATE folders SET parent_id = ?, updated_at = ?, rev = ? WHERE id = ?", [target, now, rev, id])
|
||||
end
|
||||
[*to_folder.to_s.split("/").map(&:strip).reject(&:empty?), path.split("/").last].join("/")
|
||||
end
|
||||
|
||||
# "a/b" → folder id (nil for the top level), created along the way if
|
||||
# `create`; nil when it doesn't exist and isn't created.
|
||||
def folder_id(path, create:)
|
||||
@@ -307,6 +385,20 @@ module Maptool
|
||||
id == ROOT ? nil : id
|
||||
end
|
||||
|
||||
def sibling?(db, parent, name, except)
|
||||
db.get_first_value("SELECT 1 FROM folders WHERE parent_id IS ? AND name = ? AND id != ? AND deleted_at IS NULL", [parent, name, except])
|
||||
end
|
||||
|
||||
# A layer's legacy GeoJSON with its node color on the lines.
|
||||
def layer_geojson(source, color)
|
||||
body = @gpx_store.geojson(source)
|
||||
return body unless color
|
||||
|
||||
data = JSON.parse(body)
|
||||
data["features"].each { |f| f["properties"] = (f["properties"] || {}).merge("color" => color) unless f.dig("geometry", "type") == "Point" }
|
||||
JSON.generate(data)
|
||||
end
|
||||
|
||||
def layer_source(key)
|
||||
kind, id = key.to_s.split(":", 2)
|
||||
return nil unless kind == "item"
|
||||
@@ -338,8 +430,9 @@ module Maptool
|
||||
end
|
||||
end
|
||||
|
||||
def add_features(features, folder, source: nil)
|
||||
target = folder_id(folder, create: true)
|
||||
# `folder` is a path, or with by_id: true already an id (nil = top).
|
||||
def add_features(features, folder, source: nil, by_id: false)
|
||||
target = by_id ? folder : folder_id(folder, create: true)
|
||||
features = features.select { |f| f.is_a?(Hash) && f.dig("geometry", "coordinates").is_a?(Array) }
|
||||
lines = features.count { |f| %w[track route].include?(item_type(f)) }
|
||||
parent = nil
|
||||
|
||||
@@ -245,6 +245,8 @@ module Maptool
|
||||
run_job(OFFLINE_MUTEX, OFFLINE_STATUS, kind: "offline", data_dir: data_dir, regions: codes) do |report_step|
|
||||
extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step)
|
||||
end
|
||||
# A routing build requested meanwhile waited for these extracts.
|
||||
Routing.offline_build_finished(data_dir) if defined?(Routing)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
require "fileutils"
|
||||
require "json"
|
||||
require "net/http"
|
||||
require "time"
|
||||
require_relative "pmtiles_builder"
|
||||
|
||||
module Maptool
|
||||
# maptool's side of offline routing (docs/routing-design.adoc). Valhalla
|
||||
# runs in its own container (bin/routing-service.sh); the two talk
|
||||
# through files in data/routing/: maptool writes build-request.json, the
|
||||
# container writes status.json, built.json and tiles.tar.
|
||||
module Routing
|
||||
SERVICE_SCRIPT = File.expand_path("../../bin/routing-service.sh", __dir__)
|
||||
MUTEX = Mutex.new
|
||||
@pending = false
|
||||
|
||||
def self.dir(data_dir)
|
||||
File.join(data_dir, "routing")
|
||||
end
|
||||
|
||||
def self.tiles_path(data_dir)
|
||||
File.join(dir(data_dir), "tiles.tar")
|
||||
end
|
||||
|
||||
# At boot: the container runs whatever script is in data/routing/, so it
|
||||
# always matches the deployed app.
|
||||
def self.install_service_script(data_dir)
|
||||
FileUtils.mkdir_p(dir(data_dir))
|
||||
FileUtils.cp(SERVICE_SCRIPT, File.join(dir(data_dir), "service.sh"))
|
||||
end
|
||||
|
||||
# Routing covers the offline map's selected countries. While an offline
|
||||
# build is running (it may be downloading those very extracts), the
|
||||
# request waits for it — PmtilesBuilder calls offline_build_finished.
|
||||
def self.request_build(data_dir)
|
||||
codes = PmtilesBuilder.selected_regions(data_dir)
|
||||
raise PmtilesBuilder::BuildError, "select at least one region first" if codes.empty?
|
||||
|
||||
MUTEX.synchronize do
|
||||
if PmtilesBuilder.offline_status[:state] == "running"
|
||||
@pending = true
|
||||
return
|
||||
end
|
||||
missing = codes.reject { |code| File.exist?(extract_path(data_dir, code)) }
|
||||
raise PmtilesBuilder::BuildError, "no downloaded map data for #{missing.join(", ")}, build the offline map first" if missing.any?
|
||||
|
||||
write_json(File.join(dir(data_dir), "build-request.json"), regions: codes, requested_at: Time.now.utc.iso8601)
|
||||
end
|
||||
end
|
||||
|
||||
def self.offline_build_finished(data_dir)
|
||||
pending = MUTEX.synchronize { @pending.tap { @pending = false } }
|
||||
request_build(data_dir) if pending
|
||||
rescue PmtilesBuilder::BuildError
|
||||
nil # the offline build failed to download something; its own row shows that
|
||||
end
|
||||
|
||||
# The DataFileRow build-status shape (offline_data.js): state, step,
|
||||
# started_at, message.
|
||||
def self.build_status(data_dir)
|
||||
return { state: "running", step: "waiting for the offline map build" } if MUTEX.synchronize { @pending }
|
||||
return { state: "running", step: "waiting for the routing container" } if File.exist?(File.join(dir(data_dir), "build-request.json"))
|
||||
|
||||
read_json(File.join(dir(data_dir), "status.json")) || { state: "idle" }
|
||||
end
|
||||
|
||||
# The DataFileRow status shape, plus whether Valhalla answers.
|
||||
def self.tiles_status(data_dir, valhalla_url)
|
||||
path = tiles_path(data_dir)
|
||||
return { available: false } unless File.exist?(path)
|
||||
|
||||
built = read_json(File.join(dir(data_dir), "built.json")) || {}
|
||||
{ available: true, size: File.size(path), mtime: File.mtime(path).utc.iso8601,
|
||||
meta: { sources: (built[:regions] || []).map { |code| { code: code } }, serving: serving?(valhalla_url) } }
|
||||
end
|
||||
|
||||
# nil = never built, true = other countries selected or a newer
|
||||
# extract downloaded since, false = up to date.
|
||||
def self.update_available?(data_dir)
|
||||
path = tiles_path(data_dir)
|
||||
return nil unless File.exist?(path)
|
||||
|
||||
built = (read_json(File.join(dir(data_dir), "built.json")) || {})[:regions] || []
|
||||
codes = PmtilesBuilder.selected_regions(data_dir)
|
||||
return true unless built.sort == codes.sort
|
||||
|
||||
codes.any? { |code| File.exist?(extract_path(data_dir, code)) && File.mtime(extract_path(data_dir, code)) > File.mtime(path) }
|
||||
end
|
||||
|
||||
def self.serving?(valhalla_url)
|
||||
return false if valhalla_url.to_s.empty?
|
||||
|
||||
uri = URI("#{valhalla_url}/status")
|
||||
Net::HTTP.start(uri.host, uri.port, open_timeout: 1, read_timeout: 2) { |http| http.get(uri.path).is_a?(Net::HTTPSuccess) }
|
||||
rescue StandardError
|
||||
false
|
||||
end
|
||||
|
||||
def self.extract_path(data_dir, code)
|
||||
File.join(data_dir, "geofabrik_cache", "#{code}.osm.pbf")
|
||||
end
|
||||
private_class_method :extract_path
|
||||
|
||||
def self.read_json(path)
|
||||
JSON.parse(File.read(path), symbolize_names: true)
|
||||
rescue Errno::ENOENT, JSON::ParserError
|
||||
nil
|
||||
end
|
||||
private_class_method :read_json
|
||||
|
||||
def self.write_json(path, data)
|
||||
File.write("#{path}.tmp", JSON.generate(data))
|
||||
File.rename("#{path}.tmp", path)
|
||||
end
|
||||
private_class_method :write_json
|
||||
|
||||
def self.reset!
|
||||
MUTEX.synchronize { @pending = false }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -940,6 +940,10 @@ html, body {
|
||||
width: calc(100% - 18px);
|
||||
}
|
||||
|
||||
.gpx-tree__folder-row > :first-child {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.gpx-tree summary.gpx-drop-hover {
|
||||
background: #eef5fd;
|
||||
outline: 1px dashed #4a90d9;
|
||||
@@ -1022,6 +1026,7 @@ html, body {
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
||||
padding: 4px;
|
||||
font-size: 13px;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.gpx-tree__download-menu[hidden] {
|
||||
@@ -1030,6 +1035,11 @@ html, body {
|
||||
|
||||
.gpx-tree__download-menu-item {
|
||||
display: block;
|
||||
width: 100%;
|
||||
border: none;
|
||||
background: none;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
padding: 6px 10px;
|
||||
border-radius: 4px;
|
||||
color: inherit;
|
||||
|
||||
+129
-29
@@ -30,6 +30,7 @@ const BADGE_IMAGE_PREFIX = "badge-"; // one registered image per distinct badge
|
||||
// folders, as opposed to an OS file drag (type "Files") for uploading a new
|
||||
// one — both land on the same drop targets, told apart by this.
|
||||
const MOVE_MIME = "application/x-gpx-path";
|
||||
const FOLDER_DRAG_PREFIX = "folder:"; // a dragged folder's MOVE_MIME payload, vs. a node key
|
||||
|
||||
// A sidebar icon that opens a side panel for uploading GPX files (via
|
||||
// drag & drop, stored server-side in a folder hierarchy the user can add to
|
||||
@@ -278,7 +279,16 @@ export class GpxPanelControl {
|
||||
const name = document.createElement("span");
|
||||
name.textContent = folder.name;
|
||||
row.appendChild(name);
|
||||
if (isLoggedIn()) row.appendChild(this._deleteButton(() => this._deleteFolder(folder.path)));
|
||||
if (isLoggedIn()) {
|
||||
row.appendChild(this._menuButton("⋯", "Edit", [{ label: "Rename…", run: () => this._renameFolder(folder) }]));
|
||||
row.appendChild(this._deleteButton(() => this._deleteFolder(folder.path)));
|
||||
// Dragged onto another folder (or the tree's blank space) moves it.
|
||||
summary.draggable = true;
|
||||
summary.addEventListener("dragstart", (event) => {
|
||||
event.dataTransfer.setData(MOVE_MIME, `${FOLDER_DRAG_PREFIX}${folder.path}`);
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
});
|
||||
}
|
||||
summary.appendChild(row);
|
||||
this._wireFolderDropTarget(summary, folder.path);
|
||||
|
||||
@@ -314,6 +324,8 @@ export class GpxPanelControl {
|
||||
// rather than shown-but-failing-on-click.
|
||||
if (loggedIn) {
|
||||
row.appendChild(this._downloadButton(file));
|
||||
// A folder's "Points (N)" node has no name or color of its own.
|
||||
if (file.path.startsWith("item:")) row.appendChild(this._editButton(file));
|
||||
row.appendChild(this._deleteButton(() => this._deleteFile(file)));
|
||||
}
|
||||
|
||||
@@ -338,35 +350,60 @@ export class GpxPanelControl {
|
||||
|
||||
// One button, one obvious place for both download kinds — clicking it
|
||||
// opens a small menu (Original / GeoJSON) instead of splitting them
|
||||
// across two differently-shaped click targets (the file name used to be
|
||||
// a GeoJSON-only download link; easy to miss it was a link at all, and
|
||||
// it only ever covered half the story). Costs a click for the common
|
||||
// case of downloading several files in a row, in exchange for both
|
||||
// formats actually being reachable from one, discoverable place.
|
||||
// across two differently-shaped click targets.
|
||||
_downloadButton(file) {
|
||||
const geojsonUrl = `${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "geojson", name: file.name })}`;
|
||||
return this._menuButton(DOWNLOAD_ICON, "Download", [
|
||||
// A folder's loose points have no single file they came from.
|
||||
file.original && { label: "Original file", run: () => this._download(`${gpxFileUrl(file.path)}?download=original`, file.name) },
|
||||
{ label: "GeoJSON", run: () => this._download(geojsonUrl, `${file.name}.geojson`) },
|
||||
]);
|
||||
}
|
||||
|
||||
_editButton(file) {
|
||||
return this._menuButton("⋯", "Edit", [
|
||||
{ label: "Rename…", run: () => this._renameFile(file) },
|
||||
{ label: "Color…", run: () => this._pickColor(file) },
|
||||
file.color && { label: "Default color", run: () => this._patchNode(file.path, { color: "" }) },
|
||||
file.layer && { label: "Split into items", run: () => this._splitLayer(file) },
|
||||
]);
|
||||
}
|
||||
|
||||
// A button opening a small menu of `entries` ({ label, run }, falsy ones
|
||||
// skipped).
|
||||
_menuButton(content, title, entries) {
|
||||
const wrapper = document.createElement("span");
|
||||
wrapper.className = "gpx-tree__download-wrapper";
|
||||
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "gpx-tree__download";
|
||||
button.title = "Download";
|
||||
button.setAttribute("aria-label", "Download");
|
||||
button.innerHTML = DOWNLOAD_ICON;
|
||||
button.title = title;
|
||||
button.setAttribute("aria-label", title);
|
||||
button.innerHTML = content;
|
||||
|
||||
const menu = document.createElement("div");
|
||||
menu.className = "gpx-tree__download-menu";
|
||||
menu.hidden = true;
|
||||
// A folder's loose points have no single file they came from.
|
||||
if (file.original) menu.appendChild(this._downloadMenuItem("Original file", `${gpxFileUrl(file.path)}?download=original`, file.name));
|
||||
const geojsonUrl = `${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "geojson", name: file.name })}`;
|
||||
menu.appendChild(this._downloadMenuItem("GeoJSON", geojsonUrl, `${file.name}.geojson`));
|
||||
entries.filter(Boolean).forEach(({ label, run }) => {
|
||||
const item = document.createElement("button");
|
||||
item.type = "button";
|
||||
item.className = "gpx-tree__download-menu-item";
|
||||
item.textContent = label;
|
||||
item.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this._closeDownloadMenu();
|
||||
run();
|
||||
});
|
||||
menu.appendChild(item);
|
||||
});
|
||||
|
||||
// stopPropagation so this click doesn't immediately reach the
|
||||
// document-level listener (mount()) that closes whichever menu is
|
||||
// open on an outside click — otherwise it would close right back up
|
||||
// the instant it opened.
|
||||
// open on an outside click, nor toggle a folder's <details>.
|
||||
button.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this._toggleDownloadMenu(menu);
|
||||
});
|
||||
@@ -376,19 +413,6 @@ export class GpxPanelControl {
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
_downloadMenuItem(label, url, filename) {
|
||||
const item = document.createElement("a");
|
||||
item.className = "gpx-tree__download-menu-item";
|
||||
item.href = url;
|
||||
item.textContent = label;
|
||||
item.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
this._closeDownloadMenu();
|
||||
this._download(url, filename);
|
||||
});
|
||||
return item;
|
||||
}
|
||||
|
||||
// Only one menu open at a time — opening a second one closes whichever
|
||||
// was already open, same as onlyOneSidePanelOpen does for the sidebar's
|
||||
// own panels (panels.js), just scoped to this one control instead of
|
||||
@@ -557,7 +581,7 @@ export class GpxPanelControl {
|
||||
source: linesId,
|
||||
filter: ["any", ["!has", "category"], ["!=", ["get", "category"], "Note"]],
|
||||
layout: { "line-cap": "round", "line-join": "round" },
|
||||
paint: { "line-color": TRACK_COLOR, "line-width": 3 },
|
||||
paint: { "line-color": ["coalesce", ["get", "color"], TRACK_COLOR], "line-width": 3 },
|
||||
});
|
||||
this._registerLineInteractivity(`${linesId}-line`);
|
||||
|
||||
@@ -1025,6 +1049,10 @@ export class GpxPanelControl {
|
||||
}
|
||||
|
||||
async _moveFile(from, toFolder) {
|
||||
if (from.startsWith(FOLDER_DRAG_PREFIX)) {
|
||||
await this._patchFolder(from.slice(FOLDER_DRAG_PREFIX.length), { to_folder: toFolder });
|
||||
return;
|
||||
}
|
||||
const response = await fetch(MOVE_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
@@ -1043,6 +1071,78 @@ export class GpxPanelControl {
|
||||
this._renderTree(tree);
|
||||
}
|
||||
|
||||
async _renameFolder(folder) {
|
||||
const name = window.prompt("Rename folder:", folder.name);
|
||||
if (name && name.trim() && name.trim() !== folder.name) await this._patchFolder(folder.path, { name: name.trim() });
|
||||
}
|
||||
|
||||
// Node keys are ids, so nothing shown on the map changes with its folder.
|
||||
async _patchFolder(path, fields) {
|
||||
const response = await fetch(`${FOLDER_URL}/${path.split("/").map(encodeURIComponent).join("/")}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(fields),
|
||||
});
|
||||
if (redirectIfUnauthorized(response)) return;
|
||||
if (response.status === 409) window.alert("A folder with that name already exists there.");
|
||||
if (!response.ok) return;
|
||||
this._renderTree((await response.json()).tree);
|
||||
}
|
||||
|
||||
async _renameFile(file) {
|
||||
const name = window.prompt("Rename:", file.name);
|
||||
if (name && name.trim() && name.trim() !== file.name) await this._patchNode(file.path, { name: name.trim() });
|
||||
}
|
||||
|
||||
// The native color picker; one hidden input reused for every node.
|
||||
_pickColor(file) {
|
||||
if (!this._colorInput) {
|
||||
this._colorInput = document.createElement("input");
|
||||
this._colorInput.type = "color";
|
||||
this._colorInput.hidden = true;
|
||||
this._panel.appendChild(this._colorInput);
|
||||
this._colorInput.addEventListener("change", () => this._patchNode(this._colorInput.dataset.path, { color: this._colorInput.value }));
|
||||
}
|
||||
this._colorInput.dataset.path = file.path;
|
||||
this._colorInput.value = file.color || TRACK_COLOR;
|
||||
this._colorInput.click();
|
||||
}
|
||||
|
||||
async _patchNode(path, fields) {
|
||||
const response = await fetch(gpxFileUrl(path), {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(fields),
|
||||
});
|
||||
if (redirectIfUnauthorized(response)) return;
|
||||
if (!response.ok) return;
|
||||
this._renderTree((await response.json()).tree);
|
||||
if (this._visible.has(path)) {
|
||||
this._removeLayers(path);
|
||||
await this._addLayers(path);
|
||||
}
|
||||
}
|
||||
|
||||
async _splitLayer(file) {
|
||||
if (!window.confirm(`Split "${file.name}" into separate points and tracks? This can't be undone.`)) return;
|
||||
|
||||
this._setStatus("Splitting…");
|
||||
const response = await fetch(`${gpxFileUrl(file.path)}/split`, { method: "POST" });
|
||||
if (redirectIfUnauthorized(response)) return;
|
||||
if (!response.ok) {
|
||||
this._setStatus("Split failed.");
|
||||
return;
|
||||
}
|
||||
const { paths, tree } = await response.json();
|
||||
this._renderTree(tree);
|
||||
this._setStatus("Split.");
|
||||
if (this._visible.has(file.path)) {
|
||||
this._visible.delete(file.path);
|
||||
this._removeLayers(file.path);
|
||||
await Promise.all(paths.map((path) => this.show(path)));
|
||||
}
|
||||
}
|
||||
|
||||
_setStatus(text) {
|
||||
this._uploadStatus.hidden = false;
|
||||
this._uploadStatus.textContent = text;
|
||||
|
||||
@@ -48,6 +48,13 @@ function formatOfflineMeta(meta) {
|
||||
return ` · ${meta.sources.map((s) => s.code).join(", ")}`;
|
||||
}
|
||||
|
||||
// Routing tiles live in the valhalla container's hands (see
|
||||
// lib/maptool/routing.rb); "serving" says whether it actually answers.
|
||||
function formatRoutingMeta(meta) {
|
||||
if (!meta) return "";
|
||||
return `${formatOfflineMeta(meta)} · ${meta.serving ? "routing ready" : "routing service not running"}`;
|
||||
}
|
||||
|
||||
function formatTerrainMeta(meta) {
|
||||
if (!meta) return "";
|
||||
const count = meta.sources.length;
|
||||
@@ -204,6 +211,18 @@ class DataFileRow {
|
||||
this._deleteButton.addEventListener("click", () => this._delete());
|
||||
container.appendChild(row);
|
||||
this._refreshStatus();
|
||||
this._resumePolling();
|
||||
}
|
||||
|
||||
// A build started earlier (a routing build runs for hours) keeps showing
|
||||
// its progress after a page reload.
|
||||
async _resumePolling() {
|
||||
try {
|
||||
const status = await (await fetch(this._buildStatusUrl)).json();
|
||||
if (status.state === "running") this._poll();
|
||||
} catch {
|
||||
// status stays whatever _refreshStatus shows
|
||||
}
|
||||
}
|
||||
|
||||
// Single place that writes to _statusEl, so the error styling (pre-wrap,
|
||||
@@ -231,7 +250,7 @@ class DataFileRow {
|
||||
|
||||
const updated = new Date(data.mtime).toLocaleString([], { dateStyle: "short", timeStyle: "short" });
|
||||
this._setStatus(`${formatBytes(data.size)} · updated ${updated}${this._formatMeta(data.meta)}`);
|
||||
this._deleteButton.hidden = !isLoggedIn();
|
||||
this._deleteButton.hidden = !isLoggedIn() || !this._deleteUrl;
|
||||
this._checkUpdate();
|
||||
}
|
||||
|
||||
@@ -368,6 +387,15 @@ export class OfflineDataControl {
|
||||
checkUpdateUrl: "/api/terrain-tiles/check-update",
|
||||
formatMeta: formatTerrainMeta,
|
||||
}),
|
||||
// No delete: the tiles are in use by the routing container.
|
||||
new DataFileRow({
|
||||
label: "Offline routing",
|
||||
statusUrl: "/api/routing-tiles",
|
||||
buildUrl: "/api/routing-tiles/build",
|
||||
buildStatusUrl: "/api/routing-tiles/build-status",
|
||||
checkUpdateUrl: "/api/routing-tiles/check-update",
|
||||
formatMeta: formatRoutingMeta,
|
||||
}),
|
||||
];
|
||||
this._regionPicker = new RegionPicker(() => this._rows.forEach((row) => row.triggerBuild()));
|
||||
}
|
||||
|
||||
@@ -216,6 +216,20 @@ class AppTest < Minitest::Test
|
||||
assert_equal 404, request.get(node_url(key)).status
|
||||
end
|
||||
|
||||
def test_renaming_a_node_and_a_folder_needs_login
|
||||
key = json_body(upload("ride.gpx", File.read(fixture_path("sample.gpx")), folder: "trips"))["paths"].first
|
||||
assert_equal 401, request.patch(node_url(key), params: { name: "x" }).status
|
||||
|
||||
renamed = request.patch(node_url(key), params: { name: "Evening", color: "#123456" }, **logged_in_env)
|
||||
assert_equal [["Evening", "#123456"]], json_body(renamed)["tree"]["children"][0]["children"].map { |c| c.values_at("name", "color") }
|
||||
assert_equal 400, request.patch(node_url(key), params: { color: "red" }, **logged_in_env).status
|
||||
|
||||
folder = request.patch("/api/library/folder/trips", params: { name: "2026", to_folder: "Van" }, **logged_in_env)
|
||||
assert_equal "Van/2026", json_body(folder)["path"]
|
||||
request.post("/api/library/folder?path=Bus", **logged_in_env)
|
||||
assert_equal 409, request.patch("/api/library/folder/Van", params: { name: "Bus" }, **logged_in_env).status
|
||||
end
|
||||
|
||||
def test_invalid_folder_path_is_rejected
|
||||
assert_equal 400, request.post("/api/library/folder?path=..%2F..%2Fescape", **logged_in_env).status
|
||||
end
|
||||
|
||||
@@ -69,6 +69,7 @@ module AppTestHelper
|
||||
File.write(File.join(Maptool::App::DATA_DIR, "livetrack.json"), "[]")
|
||||
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "offline_regions.json"))
|
||||
Maptool::PmtilesBuilder.reset!
|
||||
Maptool::Routing.reset!
|
||||
super
|
||||
end
|
||||
|
||||
|
||||
@@ -85,6 +85,51 @@ class LibraryTest < Minitest::Test
|
||||
assert_raises(Maptool::Library::InvalidPath) { library.create_folder("../x") }
|
||||
end
|
||||
|
||||
def test_renaming_and_recoloring_a_track_and_a_layer
|
||||
@store.save(folder: "", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx")))
|
||||
library = open_library
|
||||
layer = library.tree["children"].first["children"].first["path"]
|
||||
track = library.import(folder: "t", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx"))).first
|
||||
|
||||
library.update_node(track, name: "Morning ride", color: "#00ff00")
|
||||
library.update_node(layer, color: "#0000ff")
|
||||
nodes = library.tree["children"].flat_map { |f| f["children"].flat_map { |c| c["children"] || [c] } }
|
||||
assert_includes nodes.map { |n| n.values_at("name", "color") }, ["Morning ride", "#00ff00"]
|
||||
lines = JSON.parse(library.geojson(layer))["features"].reject { |f| f["geometry"]["type"] == "Point" }
|
||||
assert_equal ["#0000ff"], lines.map { |f| f["properties"]["color"] }.uniq
|
||||
|
||||
library.update_node(track, color: "")
|
||||
assert_nil JSON.parse(library.geojson(track))["features"].first["properties"]["color"]
|
||||
assert_raises(Maptool::Library::InvalidValue) { library.update_node(track, color: "red") }
|
||||
end
|
||||
|
||||
def test_splitting_a_layer_turns_it_into_items_and_keeps_note_ids
|
||||
@store.append_feature(feature: note("Gate", "n1"), folder: "", name: "My Notes")
|
||||
library = open_library
|
||||
folder = library.tree["children"].first
|
||||
key = folder["children"].first["path"]
|
||||
|
||||
keys = library.split_layer(key)
|
||||
assert_equal ["Points (1)"], library.tree["children"].first["children"].map { |c| c["name"] }
|
||||
assert_equal ["n1"], JSON.parse(library.geojson(keys.first))["features"].map { |f| f["properties"]["id"] }
|
||||
assert_equal ["My Notes.geojson"], Dir.glob("*/*", base: File.join(@dir, "sources")).map { |f| File.basename(f) }
|
||||
assert_raises(Maptool::Library::NotFound) { library.geojson(key) }
|
||||
end
|
||||
|
||||
def test_renaming_and_moving_folders
|
||||
library = open_library
|
||||
key = library.add_note(note("Gate"), "a/b")
|
||||
library.create_folder("c")
|
||||
|
||||
assert_equal "a/x", library.rename_folder("a/b", "x")
|
||||
assert_equal "c/x", library.move_folder("a/x", "c")
|
||||
assert_equal ["a", "c"], library.tree["children"].map { |f| f["name"] }
|
||||
assert_equal ["Gate"], JSON.parse(library.geojson(key))["features"].map { |f| f["properties"]["name"] }
|
||||
assert_raises(Maptool::Library::InvalidPath) { library.move_folder("c", "c/x") }
|
||||
library.create_folder("a/x")
|
||||
assert_raises(Maptool::Library::InvalidValue) { library.move_folder("c/x", "a") }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def open_library
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
require_relative "test_helper"
|
||||
require "maptool/routing"
|
||||
|
||||
class RoutingTest < Minitest::Test
|
||||
def setup
|
||||
@data = Dir.mktmpdir
|
||||
@routing = File.join(@data, "routing")
|
||||
FileUtils.mkdir_p([@routing, File.join(@data, "geofabrik_cache")])
|
||||
Maptool::PmtilesBuilder.set_selected_regions(@data, %w[SK])
|
||||
end
|
||||
|
||||
def teardown
|
||||
FileUtils.remove_entry(@data)
|
||||
Maptool::PmtilesBuilder.reset!
|
||||
Maptool::Routing.reset!
|
||||
end
|
||||
|
||||
def test_a_build_needs_the_extracts_and_writes_a_request_for_the_container
|
||||
assert_raises(Maptool::PmtilesBuilder::BuildError) { Maptool::Routing.request_build(@data) }
|
||||
|
||||
File.write(File.join(@data, "geofabrik_cache", "SK.osm.pbf"), "pbf")
|
||||
Maptool::Routing.request_build(@data)
|
||||
assert_equal %w[SK], JSON.parse(File.read(File.join(@routing, "build-request.json")))["regions"]
|
||||
assert_equal "waiting for the routing container", Maptool::Routing.build_status(@data)[:step]
|
||||
end
|
||||
|
||||
def test_a_request_during_an_offline_build_waits_for_it
|
||||
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "running")
|
||||
Maptool::Routing.request_build(@data)
|
||||
assert_equal "waiting for the offline map build", Maptool::Routing.build_status(@data)[:step]
|
||||
refute File.exist?(File.join(@routing, "build-request.json"))
|
||||
|
||||
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "done")
|
||||
File.write(File.join(@data, "geofabrik_cache", "SK.osm.pbf"), "pbf")
|
||||
Maptool::Routing.offline_build_finished(@data)
|
||||
assert File.exist?(File.join(@routing, "build-request.json"))
|
||||
end
|
||||
|
||||
def test_update_check_compares_regions_and_extract_age
|
||||
assert_nil Maptool::Routing.update_available?(@data)
|
||||
|
||||
pbf = File.join(@data, "geofabrik_cache", "SK.osm.pbf")
|
||||
File.write(pbf, "pbf")
|
||||
File.utime(Time.now - 60, Time.now - 60, pbf)
|
||||
File.write(File.join(@routing, "tiles.tar"), "tiles")
|
||||
File.write(File.join(@routing, "built.json"), JSON.generate(regions: %w[SK]))
|
||||
refute Maptool::Routing.update_available?(@data)
|
||||
|
||||
File.utime(Time.now + 60, Time.now + 60, pbf)
|
||||
assert Maptool::Routing.update_available?(@data)
|
||||
Maptool::PmtilesBuilder.set_selected_regions(@data, %w[SK CZ])
|
||||
assert Maptool::Routing.update_available?(@data)
|
||||
assert_equal [{ code: "SK" }], Maptool::Routing.tiles_status(@data, "")[:meta][:sources]
|
||||
end
|
||||
|
||||
def test_the_container_status_file_is_passed_through
|
||||
assert_equal({ state: "idle" }, Maptool::Routing.build_status(@data))
|
||||
File.write(File.join(@routing, "status.json"), JSON.generate(state: "running", step: "packing tiles"))
|
||||
assert_equal "packing tiles", Maptool::Routing.build_status(@data)[:step]
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user