Compare commits
5 commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9962a6932d | |||
| fff8a8382b | |||
| 195c84106e | |||
| bd87587391 | |||
| b8ee4b4cc0 |
6 changed files with 339 additions and 113 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
|
@ -1590,7 +1590,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "rs_maps"
|
||||
version = "0.2.0"
|
||||
version = "0.3.4"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"argon2",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
# Cargo.toml
|
||||
[package]
|
||||
name = "rs_maps"
|
||||
version = "0.2.0"
|
||||
version = "0.3.4"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
190
README.md
190
README.md
|
|
@ -1,114 +1,132 @@
|
|||
<!-- README.md -->
|
||||
|
||||
# rs_maps — build and deploy
|
||||
# rs_maps
|
||||
|
||||
Single Rust binary + one rootless Postgres container. See `DESIGN.md` for the reasoning.
|
||||
A self-hosted replacement for the parts of Google Maps most people actually use:
|
||||
saving places you care about, and planning walking routes. It runs as a single
|
||||
Rust binary with one Postgres container behind it, and it's built for a handful
|
||||
of trusted users rather than the public.
|
||||
|
||||
> **This code has not been compiled.** It was written without a Rust toolchain available,
|
||||
> so treat the first `cargo build` as the real review. Expect to fix a handful of import
|
||||
> paths and trait-bound details, not the structure.
|
||||
It is not a Google Maps clone. There are no reviews, no photos, no live traffic
|
||||
and no turn-by-turn navigation, and there is no plan to add them.
|
||||
|
||||
## 1. Refresh dependency versions
|
||||
## What it does
|
||||
|
||||
`Cargo.toml` has plausible versions, but pin them properly:
|
||||
**Places.** Click the map to drop a tagged marker with a name, kind, colour and
|
||||
description. Markers are private by default; flip one to shared and everyone
|
||||
else with an account sees it too.
|
||||
|
||||
**Search.** Type a place or address and get up to eight matches with their type
|
||||
and full address, so two branches of the same chain are distinguishable. Picking
|
||||
one drops a pin and shows what was found. "More details" pulls opening hours,
|
||||
phone, website and similar from OpenStreetMap where they exist — and says so
|
||||
plainly where they don't. Any hit can be saved as a place in one click.
|
||||
|
||||
**Routes.** Draw a walking route by clicking waypoints on the map. The line
|
||||
snaps to real paths and tracks, updating as you drag points around, with the
|
||||
routed distance and total ascent shown. Save it and the GPX lands in a shared
|
||||
folder both users can see. Saved routes can be reopened and edited later.
|
||||
|
||||
**GPX files.** Open a `.gpx` from your device to view it without uploading
|
||||
anything, or save it to the shared folder if you want it on the server. Files in
|
||||
the shared folder can be rendered on the map by anyone logged in.
|
||||
|
||||
**Live location.** Toggle it on to see where you are while the map is open. It's
|
||||
a dot on a map, not navigation guidance.
|
||||
|
||||
## What it's built on
|
||||
|
||||
- **Rust binary** (`axum`) serving the API and the whole frontend, which is
|
||||
embedded into the executable at compile time. One file to deploy.
|
||||
- **Postgres** in a rootless podman container, holding users, sessions and
|
||||
markers.
|
||||
- **A plain directory** for GPX files. No database involvement, no metadata.
|
||||
- **Nothing else self-hosted.** Map tiles come from OpenStreetMap, search from
|
||||
Nominatim, route snapping from brouter.de, and place details from Overpass —
|
||||
called directly from the browser, or proxied through one endpoint. Hosting any
|
||||
of them would mean gigabytes of data for a tool used a few times a week.
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Linux server with systemd and podman
|
||||
- nginx (or equivalent) terminating TLS — **not optional**: browser geolocation
|
||||
refuses to run without HTTPS, and session cookies are `Secure`
|
||||
- A Rust toolchain to build, or a release binary
|
||||
- A domain
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cargo add axum -F multipart,macros
|
||||
cargo add tokio -F full
|
||||
cargo add sqlx --no-default-features -F runtime-tokio,tls-rustls,postgres,uuid,time,macros,migrate
|
||||
cargo add tower-sessions
|
||||
cargo add tower-sessions-sqlx-store -F postgres
|
||||
cargo add lettre --no-default-features -F tokio1-rustls,smtp-transport,builder,pool
|
||||
cargo add rust-embed -F debug-embed
|
||||
cargo build
|
||||
git clone <this repo> && cd rs_maps
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
Two version-sensitive spots to check first if it doesn't compile:
|
||||
|
||||
- **`tower-sessions` / `tower-sessions-sqlx-store` must be a matching pair.** The store crate
|
||||
tracks the main crate's version and they break in lockstep. Check the store's own README for
|
||||
which `tower-sessions` it expects.
|
||||
- **axum 0.8 changed path params from `:id` to `{id}`.** This code uses `{id}`. If you end up on
|
||||
0.7 for some reason, they all need changing back.
|
||||
|
||||
## 2. Database
|
||||
Database and directories:
|
||||
|
||||
```bash
|
||||
podman secret create mapserver-db-password - # type the password, then Ctrl-D
|
||||
mkdir -p ~/.config/containers/systemd
|
||||
mkdir -p ~/.config/containers/systemd ~/gpx
|
||||
cp deploy/postgres.container ~/.config/containers/systemd/
|
||||
|
||||
# Hex, not base64: / and + in a password break DATABASE_URL parsing.
|
||||
openssl rand -hex 32 | tr -d '\n' | podman secret create rs_maps-db-password -
|
||||
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user start postgres
|
||||
```
|
||||
|
||||
Migrations run automatically on startup — both `./migrations` and the session store's own.
|
||||
Copy `.env.example` to `.env` and fill in at least these:
|
||||
|
||||
## 3. Config
|
||||
| Key | Notes |
|
||||
|---|---|
|
||||
| `DATABASE_URL` | `postgres://rs_maps:PASSWORD@127.0.0.1:5432/rs_maps` |
|
||||
| `REG_TOKEN` | `openssl rand -hex 32`. Anyone with this can register — it is the only access control |
|
||||
| `PUBLIC_URL` | Origin only: `https://example.com`. No trailing slash, no subpath |
|
||||
| `BASE_PATH` | `/maps` if served under a subpath, empty for the domain root |
|
||||
| `GPX_DIR` | Absolute path to a directory the service can write to |
|
||||
| `BIND_ADDR` | `127.0.0.1:8080` — loopback only, nginx is the only client |
|
||||
|
||||
`PUBLIC_URL` must match the browser's `Origin` header exactly. A mismatch
|
||||
(`www.` versus bare, or a stray trailing slash) means every save fails with a
|
||||
403 while pages load normally — a confusing thing to debug.
|
||||
|
||||
Run it:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.config/mapserver ~/gpx
|
||||
cp .env.example ~/.config/mapserver/.env
|
||||
chmod 600 ~/.config/mapserver/.env
|
||||
$EDITOR ~/.config/mapserver/.env
|
||||
./target/release/rs_maps
|
||||
```
|
||||
|
||||
Must change: `DATABASE_URL`, `REG_TOKEN`, `PUBLIC_URL`, `BASE_PATH`, `GPX_DIR`.
|
||||
Migrations apply on startup. Point nginx at it using `deploy/nginx-snippet.conf`
|
||||
— note the `client_max_body_size 25m` on the upload path and the redirect for
|
||||
the bare subpath. Then open the site, register with your `REG_TOKEN`, and you're
|
||||
in. The first account isn't special: there are no roles and no admin UI.
|
||||
|
||||
Leave `SMTP_HOST` empty for now — reset links get logged instead of emailed, and the whole flow
|
||||
is testable without a provider.
|
||||
For the service unit, systemd hardening and the release/upgrade scripts, see
|
||||
`deploy/`. `DESIGN.md` covers why the architecture is the way it is.
|
||||
|
||||
## 4. Run
|
||||
## Passwords and email
|
||||
|
||||
Email is optional and used only for password resets. Give a bad address and the
|
||||
only thing you lose is your own ability to reset — nothing else depends on it.
|
||||
With `SMTP_HOST` empty, reset links are written to the log rather than sent,
|
||||
which is enough to test the flow without an email provider.
|
||||
|
||||
Changing a password affects future logins only. Sessions already active on other
|
||||
devices stay valid; clearing those means deleting the session rows directly.
|
||||
That's a deliberate trade for a two-person deployment.
|
||||
|
||||
## Being a good citizen
|
||||
|
||||
Tiles, search, routing and place details all come from volunteer-run
|
||||
infrastructure. The app is built to stay inside their usage policies: search
|
||||
runs on submit rather than as you type, route previews are debounced, and place
|
||||
details are fetched only when asked for. If you fork this and put it in front of
|
||||
a lot of users, read those policies before scaling up.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
cargo build --release
|
||||
mkdir -p ~/.local/bin && cp target/release/mapserver ~/.local/bin/
|
||||
cp deploy/mapserver.service ~/.config/systemd/user/
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now mapserver
|
||||
loginctl enable-linger "$USER" # or nothing starts at boot
|
||||
journalctl --user -u mapserver -f
|
||||
cargo test
|
||||
```
|
||||
|
||||
## 5. nginx
|
||||
|
||||
Merge `deploy/nginx-snippet.conf` into your existing TLS server block, then
|
||||
`nginx -t && systemctl reload nginx`.
|
||||
|
||||
## 6. First account
|
||||
|
||||
Visit `https://your-domain/maps/`, choose "Create an account", and enter the `REG_TOKEN` from
|
||||
`.env`.
|
||||
|
||||
---
|
||||
|
||||
## Testing the reset flow with real mail
|
||||
|
||||
`mailpit` gives you a local SMTP server and a web inbox with no signup:
|
||||
|
||||
```
|
||||
SMTP_HOST=127.0.0.1
|
||||
SMTP_PORT=1025
|
||||
SMTP_TLS=none
|
||||
SMTP_USERNAME=
|
||||
SMTP_PASSWORD=
|
||||
```
|
||||
|
||||
When you move to a real provider: use an app-specific password (any account with 2FA will reject
|
||||
the normal one over SMTP), check SMTP isn't disabled by default on the account, and make sure
|
||||
`SMTP_FROM` is an address that account may send as.
|
||||
|
||||
## Things worth checking by hand after the first deploy
|
||||
|
||||
- `curl -i https://your-domain/maps/api/gpx/file/../../etc/passwd` → 400 or 404, never a file
|
||||
- Live location works (needs HTTPS; it silently fails on plain HTTP)
|
||||
- Session survives `systemctl --user restart mapserver`
|
||||
- Upload a >2 MB GPX — catches both the axum and nginx body limits at once
|
||||
- Upload the same filename twice — second one should come back as `name-1.gpx`
|
||||
- Reboot the server, confirm both units come back (this is what `enable-linger` is for)
|
||||
|
||||
## Unit tests
|
||||
|
||||
cargo test
|
||||
|
||||
No database needed — every test is pure: base-path normalisation, bbox parsing,
|
||||
GPX filename safety, and the rate-limiter window.
|
||||
No database needed — the tests cover base-path handling, bbox parsing, GPX
|
||||
filename safety, waypoint embedding, coordinate ordering and the rate limiter.
|
||||
|
|
|
|||
125
frontend/app.js
125
frontend/app.js
|
|
@ -26,7 +26,20 @@ const NOMINATIM = 'https://nominatim.openstreetmap.org/search';
|
|||
// Nominatim's search endpoint doesn't return object tags, so opening hours,
|
||||
// phone and website need a second lookup by OSM id. Overpass is donated
|
||||
// infrastructure like Nominatim: fine on an explicit click, not per result.
|
||||
const OVERPASS = 'https://overpass-api.de/api/interpreter';
|
||||
//
|
||||
// Tried in order. The main overpass-api.de instance is by far the busiest and
|
||||
// returns 504 under load even for a trivial single-object query, so the mirrors
|
||||
// are a practical necessity rather than belt and braces.
|
||||
const OVERPASS_ENDPOINTS = [
|
||||
'https://overpass.kumi.systems/api/interpreter',
|
||||
'https://overpass-api.de/api/interpreter',
|
||||
'https://overpass.private.coffee/api/interpreter',
|
||||
];
|
||||
|
||||
// Overpass queues requests when busy — a trivial single-object lookup has been
|
||||
// observed taking over a minute before returning a perfectly good 200. 30s is
|
||||
// the most that's reasonable to make someone wait; past that, give up quietly.
|
||||
const OVERPASS_TIMEOUT_MS = 30000;
|
||||
|
||||
const COLOURS = ['#4E9C6B', '#D2467F', '#E2A93C', '#4E8FC9', '#B07BD4', '#D3574B'];
|
||||
const DEFAULT_COLOUR = COLOURS[0];
|
||||
|
|
@ -51,7 +64,7 @@ const state = {
|
|||
colour: DEFAULT_COLOUR,
|
||||
searchPin: null, // transient pin for the current search hit
|
||||
draw: { active: false, points: [], markers: [], line: null, guide: null,
|
||||
timer: null, seq: 0, snapped: null },
|
||||
timer: null, seq: 0, snapped: null, editing: null },
|
||||
};
|
||||
|
||||
/* ───────────────────────────── api ───────────────────────────── */
|
||||
|
|
@ -479,7 +492,7 @@ function drawReset() {
|
|||
if (state.draw.line) state.map.removeLayer(state.draw.line);
|
||||
if (state.draw.guide) state.map.removeLayer(state.draw.guide);
|
||||
state.draw = { active: false, points: [], markers: [], line: null, guide: null,
|
||||
timer: null, seq: 0, snapped: null };
|
||||
timer: null, seq: 0, snapped: null, editing: null };
|
||||
}
|
||||
|
||||
function drawSetActive(on) {
|
||||
|
|
@ -489,6 +502,7 @@ function drawSetActive(on) {
|
|||
$('#draw-panel').hidden = !on;
|
||||
$('#draw-start').textContent = on ? 'Drawing…' : 'New route';
|
||||
$('#draw-start').disabled = on;
|
||||
if (!on) $('#draw-hint').textContent = 'Snapped to paths for walking';
|
||||
state.map.getContainer().style.cursor = on ? 'crosshair' : '';
|
||||
if (on) drawUpdate();
|
||||
}
|
||||
|
|
@ -624,7 +638,10 @@ $('#draw-start').addEventListener('click', () => {
|
|||
toast('Click the map to add waypoints');
|
||||
});
|
||||
|
||||
$('#draw-cancel').addEventListener('click', () => drawSetActive(false));
|
||||
$('#draw-cancel').addEventListener('click', () => {
|
||||
if (state.draw.editing && !confirm('Discard changes to this route?')) return;
|
||||
drawSetActive(false);
|
||||
});
|
||||
$('#draw-undo').addEventListener('click', undoWaypoint);
|
||||
|
||||
$('#draw-save').addEventListener('click', async () => {
|
||||
|
|
@ -642,10 +659,18 @@ $('#draw-save').addEventListener('click', async () => {
|
|||
const body = {
|
||||
name,
|
||||
waypoints: points.map((p) => ({ lat: p.lat, lon: p.lng })),
|
||||
// The backend replaces in place only when this matches the new name.
|
||||
// Rename the file and the original is left alone, as a copy.
|
||||
replace: state.draw.editing || null,
|
||||
};
|
||||
const result = await api('api/routes/calculate', { method: 'POST', ...json(body) });
|
||||
|
||||
toast(`Saved as ${result.filename}`);
|
||||
const renamed = state.draw.editing && result.filename !== state.draw.editing;
|
||||
toast(
|
||||
!state.draw.editing ? `Saved as ${result.filename}`
|
||||
: renamed ? `Saved as ${result.filename} — ${state.draw.editing} kept`
|
||||
: `${result.filename} updated`
|
||||
);
|
||||
drawSetActive(false);
|
||||
await loadGpxList();
|
||||
} catch (err) {
|
||||
|
|
@ -681,16 +706,40 @@ async function fetchOsmTags(osmType, osmId) {
|
|||
const short = OSM_SHORT[osmType];
|
||||
if (!short) return null;
|
||||
|
||||
const query = `[out:json][timeout:20];${short}(${osmId});out tags;`;
|
||||
const res = await fetch(OVERPASS, {
|
||||
// Server-side budget matched to ours, so it sheds the request rather than
|
||||
// holding it in a queue we've already stopped waiting on.
|
||||
const query = `[out:json][timeout:30];${short}(${osmId});out tags;`;
|
||||
let lastError = null;
|
||||
|
||||
for (const endpoint of OVERPASS_ENDPOINTS) {
|
||||
// AbortController rather than relying on the server: a hung connection
|
||||
// would otherwise block the fallback for as long as the browser allows.
|
||||
const abort = new AbortController();
|
||||
const timer = setTimeout(() => abort.abort(), OVERPASS_TIMEOUT_MS);
|
||||
|
||||
try {
|
||||
const res = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: 'data=' + encodeURIComponent(query),
|
||||
signal: abort.signal,
|
||||
});
|
||||
|
||||
// 429 and 504 mean this mirror is busy, not that the object is missing —
|
||||
// worth asking someone else.
|
||||
if (!res.ok) throw new Error('overpass ' + res.status);
|
||||
|
||||
const body = await res.json();
|
||||
return (body.elements && body.elements[0] && body.elements[0].tags) || {};
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
console.warn('overpass mirror failed:', endpoint, err.message);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError || new Error('no overpass endpoint responded');
|
||||
}
|
||||
|
||||
/* Renders whatever came back. Deliberately raw values — no "open now", no
|
||||
|
|
@ -861,9 +910,11 @@ function showSearchHit(hit) {
|
|||
slot.replaceChildren(node);
|
||||
more.remove();
|
||||
} catch {
|
||||
// Overpass being busy is routine and not worth interrupting anyone
|
||||
// over. The button simply comes back so it can be pressed again;
|
||||
// the reason stays in the console.
|
||||
more.disabled = false;
|
||||
more.textContent = 'More details';
|
||||
toast('Could not load details right now', true);
|
||||
}
|
||||
popup.update(); // re-measure after the content grew
|
||||
});
|
||||
|
|
@ -1052,10 +1103,68 @@ async function loadGpxList() {
|
|||
}
|
||||
});
|
||||
li.appendChild(show);
|
||||
|
||||
const edit = document.createElement('button');
|
||||
edit.className = 'link';
|
||||
edit.textContent = 'Edit';
|
||||
edit.addEventListener('click', () => editRoute(f.name));
|
||||
li.appendChild(edit);
|
||||
|
||||
// A plain anchor rather than a fetch-and-blob: same-origin navigation
|
||||
// carries the session cookie, and the browser handles the save dialog,
|
||||
// resumability and large files without any of it passing through JS.
|
||||
const download = document.createElement('a');
|
||||
download.className = 'link';
|
||||
download.textContent = 'Download';
|
||||
download.href = 'api/gpx/file/' + encodeURIComponent(f.name);
|
||||
// Without an explicit filename the browser would name it after the URL's
|
||||
// last segment, which is percent-encoded.
|
||||
download.download = f.name;
|
||||
li.appendChild(download);
|
||||
|
||||
list.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
/* Reopens a saved route for editing. Only routes created here can be edited:
|
||||
they carry their original <wpt> waypoints alongside the dense snapped track.
|
||||
A GPX recorded on a device has no such waypoints, and a few thousand track
|
||||
points can't be reduced back to the handful someone actually clicked. */
|
||||
async function editRoute(filename) {
|
||||
try {
|
||||
const res = await fetch('api/gpx/file/' + encodeURIComponent(filename), {
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) throw new Error('Could not read that file.');
|
||||
|
||||
const doc = new DOMParser().parseFromString(await res.text(), 'application/xml');
|
||||
const wpts = [...doc.getElementsByTagName('wpt')]
|
||||
.map((w) => ({
|
||||
lat: parseFloat(w.getAttribute('lat')),
|
||||
lng: parseFloat(w.getAttribute('lon')),
|
||||
}))
|
||||
.filter((p) => Number.isFinite(p.lat) && Number.isFinite(p.lng));
|
||||
|
||||
if (wpts.length < 2) {
|
||||
toast('That file has no editable waypoints — only routes drawn here can be edited', true);
|
||||
return;
|
||||
}
|
||||
|
||||
drawSetActive(true);
|
||||
state.draw.editing = filename;
|
||||
// Strip the extension: it's re-added on save, and showing it invites
|
||||
// someone to delete it by accident.
|
||||
$('#draw-name').value = filename.replace(/\.gpx$/i, '');
|
||||
$('#draw-hint').textContent = `Editing ${filename}`;
|
||||
|
||||
wpts.forEach((p) => addWaypoint(L.latLng(p.lat, p.lng)));
|
||||
state.map.fitBounds(L.latLngBounds(wpts.map((p) => [p.lat, p.lng])), { padding: [40, 40] });
|
||||
toast('Drag points to adjust, then save');
|
||||
} catch (err) {
|
||||
toast(err.message || 'Could not open that route', true);
|
||||
}
|
||||
}
|
||||
|
||||
$('#gpx-local').addEventListener('change', async (e) => {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
|
|
|
|||
33
src/gpx.rs
33
src/gpx.rs
|
|
@ -107,6 +107,39 @@ pub fn reserve(dir: &StdPath, name: &str) -> AppResult<(std::fs::File, String)>
|
|||
))
|
||||
}
|
||||
|
||||
/// Replaces an existing file's contents atomically: write a sibling temp file,
|
||||
/// then rename over the target. A reader that opens the file mid-save sees
|
||||
/// either the old contents or the new, never a partial write.
|
||||
pub async fn overwrite(dir: &StdPath, name: &str, bytes: &[u8]) -> AppResult<()> {
|
||||
validate_filename(name)?;
|
||||
|
||||
// Must exist already — this path is for editing, not creating.
|
||||
let target = resolve_existing(dir, name)?;
|
||||
|
||||
// Same directory, so the rename stays on one filesystem and is atomic.
|
||||
let temp = dir.join(format!(".{name}.tmp"));
|
||||
|
||||
let write = async {
|
||||
let mut file = tokio::fs::File::create(&temp).await?;
|
||||
file.write_all(bytes).await?;
|
||||
file.flush().await?;
|
||||
// Durable before the rename, so a crash can't leave an empty file in place.
|
||||
file.sync_all().await?;
|
||||
Ok::<_, std::io::Error>(())
|
||||
};
|
||||
|
||||
if let Err(e) = write.await {
|
||||
let _ = tokio::fs::remove_file(&temp).await;
|
||||
return Err(e.into());
|
||||
}
|
||||
|
||||
if let Err(e) = tokio::fs::rename(&temp, &target).await {
|
||||
let _ = tokio::fs::remove_file(&temp).await;
|
||||
return Err(e.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- handlers
|
||||
|
||||
async fn list(
|
||||
|
|
|
|||
|
|
@ -52,6 +52,11 @@ pub struct CalculateRequest {
|
|||
pub waypoints: Vec<Waypoint>,
|
||||
/// Desired filename. ".gpx" is appended if absent.
|
||||
pub name: String,
|
||||
/// When editing: the file this route came from. If it matches the target
|
||||
/// name the file is replaced in place; if the user renamed it, a new file is
|
||||
/// written and the original left alone.
|
||||
#[serde(default)]
|
||||
pub replace: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -94,6 +99,38 @@ fn lonlats(waypoints: &[Waypoint]) -> String {
|
|||
.join("|")
|
||||
}
|
||||
|
||||
/// The stored GPX carries the clicked waypoints as `<wpt>` elements alongside
|
||||
/// the dense snapped `<trk>`. Without them a saved route can't be reopened for
|
||||
/// editing — several thousand track points can't be reduced back to the handful
|
||||
/// of points the user actually placed. `<wpt>` is standard GPX, so other tools
|
||||
/// simply show them as markers.
|
||||
fn embed_waypoints(gpx: &str, waypoints: &[Waypoint]) -> String {
|
||||
let block: String = waypoints
|
||||
.iter()
|
||||
.map(|p| {
|
||||
format!(
|
||||
" <wpt lat=\"{:.6}\" lon=\"{:.6}\"><type>rs_maps:via</type></wpt>\n",
|
||||
p.lat, p.lon
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Insert immediately after the opening <gpx …> tag; the schema requires
|
||||
// wpt elements to precede trk.
|
||||
match gpx.find("<gpx").and_then(|start| gpx[start..].find('>').map(|o| start + o + 1)) {
|
||||
Some(after_open) => {
|
||||
let mut out = String::with_capacity(gpx.len() + block.len() + 1);
|
||||
out.push_str(&gpx[..after_open]);
|
||||
out.push('\n');
|
||||
out.push_str(&block);
|
||||
out.push_str(&gpx[after_open..]);
|
||||
out
|
||||
}
|
||||
// Shouldn't happen — looks_like_gpx already ran — but never lose the route.
|
||||
None => gpx.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cheap sanity check on the response body. BRouter reports routing failures
|
||||
/// ("operation not supported", "position not mapped in existing datafile") as
|
||||
/// 200 with a plain-text body, so status alone isn't enough.
|
||||
|
|
@ -239,8 +276,24 @@ async fn calculate(
|
|||
return Err(routing_failure(&body));
|
||||
}
|
||||
|
||||
// Same atomic create_new reservation the upload path uses, so a name clash
|
||||
// becomes route-1.gpx rather than silently overwriting.
|
||||
let body = embed_waypoints(&body, &request.waypoints);
|
||||
|
||||
// Replacing in place only when the user kept the name. A rename leaves the
|
||||
// original untouched and takes the normal collision-avoiding path.
|
||||
let replacing = request
|
||||
.replace
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|original| !original.is_empty())
|
||||
.filter(|original| original.eq_ignore_ascii_case(&filename));
|
||||
|
||||
let written_name = if let Some(original) = replacing {
|
||||
gpx::validate_filename(original)?;
|
||||
gpx::overwrite(&state.config.gpx_dir, original, body.as_bytes()).await?;
|
||||
original.to_string()
|
||||
} else {
|
||||
// Same atomic create_new reservation the upload path uses, so a name
|
||||
// clash becomes route-1.gpx rather than silently overwriting.
|
||||
let (file, written_name) = gpx::reserve(&state.config.gpx_dir, &filename)?;
|
||||
let mut file = tokio::fs::File::from_std(file);
|
||||
|
||||
|
|
@ -250,6 +303,8 @@ async fn calculate(
|
|||
return Err(e.into());
|
||||
}
|
||||
file.flush().await?;
|
||||
written_name
|
||||
};
|
||||
|
||||
tracing::info!(file = %written_name, points = request.waypoints.len(), "route saved");
|
||||
|
||||
|
|
@ -298,6 +353,17 @@ mod tests {
|
|||
assert!(validate(&request).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waypoints_are_embedded_before_the_track() {
|
||||
let gpx = r#"<?xml version="1.0"?><gpx version="1.1"><trk><name>x</name></trk></gpx>"#;
|
||||
let out = embed_waypoints(gpx, &[wp(53.5, -2.2), wp(53.6, -2.3)]);
|
||||
|
||||
assert_eq!(out.matches("<wpt").count(), 2);
|
||||
// Schema requires wpt before trk.
|
||||
assert!(out.find("<wpt").unwrap() < out.find("<trk").unwrap());
|
||||
assert!(out.contains(r#"lat="53.500000""#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_geojson_and_flips_coordinate_order() {
|
||||
let body = r#"{"features":[{"geometry":{"coordinates":
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue