Files
maptool/docs/library-design.adoc

405 lines
17 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
= Library: data model for tracks, points and sync (design)
:toc:
:toclevels: 2
Status: *phases 1–3 implemented* (`lib/maptool/library.rb`, see Decisions); phase 4 (the Android client) 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.
== Why
The same tracks and points live in three places — MapTool, OsmAnd+ and
Locus Map on the phone/tablet — each edited independently. Today the unit
of storage in MapTool is a *file* (a `.gpx`/`.fit`/`.geojson` in a folder),
and nothing inside a file has a stable identity, a change time, or a
record of having been deleted. That's fine for "upload and look at it",
but any sync needs to answer _which point changed, where, and since
when_ — impossible when the smallest thing we know about is a whole file.
Goals:
* One folder tree with points and tracks mixed in it (Locus-style
"project" folders).
* Every point and track an item with a stable id, timestamps and a
tombstone on delete.
* A change feed that a sync client (Android app, the PWA) can poll.
* Import/export to GPX that round-trips what OsmAnd and Locus care about
(folders, names, descriptions, colors, icons).
Non-goals (for now): real-time collaboration, merging concurrent edits
field by field, syncing hiking trails / offline map data (those are
derived, not user data), LiveTrack sessions.
== How the apps model their data
=== Locus Map 4
* One *library*: a tree of folders and subfolders in which tracks,
planned routes and points can be mixed. The separate points/tracks tabs
of Locus 3 are gone.
* Nesting: 3 levels free, 6 with Premium.
* Items can be filtered by type (only tracks / only points) for display.
* Exporting a folder exports all of its content into one file.
* Syncs every change to Locus' own web library (no public API known).
* App data (`waypoints.db`, `tracks.db`) is SQLite, but not a supported
integration point; the Locus API is mainly for *sending* points/tracks
into Locus.
Sources: https://docs.locusmap.app/doku.php/manual:user_guide:my_library[My Library],
https://www.locusmap.app/the-new-library-brings-major-improvements-to-your-data-management/[blog],
https://github.com/asamm/locus-api[locus-api].
=== OsmAnd+
* *Favorites* (points) in folders/groups, nested ("Travel / Italy /
Rome"); a name must be unique within its folder. Each has address,
description, icon, color and background shape, defaulting to the
folder's. Stored as GPX `<wpt>` with `osmand:icon`, `osmand:color`,
`osmand:background`, `osmand:address` extensions.
* *Tracks* are separate GPX files in track folders (plus "smart folders",
virtual filters). A track file can carry its own waypoints.
* Points and tracks are *not* mixed: a "project" maps to a favorites
folder plus a track folder of the same name.
* AIDL API: add/update/remove favorites and favorite groups, import/show
GPX. Whether it can *list* existing favorites/tracks is unverified —
check `osmand-api-demo` before relying on reading from OsmAnd.
Sources: https://docs.osmand.net/docs/user/personal/favorites[Favorites],
https://docs.osmand.net/docs/user/personal/tracks/[Tracks],
https://docs.osmand.net/docs/technical/osmand-api-sdk[API/SDK].
=== mapy.com
No API. Data arrives by exporting/sharing a GPX from the app — the PWA
share target (`public/sw.js`, `public/js/share_import.js`) covers that.
=== What that means for us
Locus' model is the most general: a folder tree with mixed items. OsmAnd
fits into it by splitting each folder into "its points" (a favorites
folder) and "its tracks" (a track folder). So MapTool adopts Locus' shape
and maps to OsmAnd on export/sync.
== Current model (GpxStore) and its gaps
* `data/gpx/` folder tree; each file is a `.gpx`, `.fit` or `.geojson`,
converted to a GeoJSON FeatureCollection (cached as `*.gpx.geojson`).
* A file mixes tracks/routes (`LineString`/`MultiLineString`) and
waypoints (`Point`), each with `properties`: `kind`, `name`,
`description`, `time`, `category`, `color`, `icon` (OsmAnd icon keys,
e.g. `amenity_parking`), `photos`, `activity_type`.
* Notes (`notes.js`) are Features appended to a `.geojson` "layer" file,
the only ones with an `id`.
* Plugin output and Overpass POIs land as `.geojson` files the same way.
Gaps: no per-item id (except notes), no `updated_at`, no tombstones, the
file is the unit of move/delete/visibility, folder styling doesn't exist,
a file's name is doubling as a "collection" name.
== Proposed model
Stored in SQLite, `data/library.sqlite` (the `sqlite3` gem is already a
dependency for the place index).
=== Folders
[source,sql]
----
CREATE TABLE folders (
id TEXT PRIMARY KEY, -- uuid
parent_id TEXT REFERENCES folders(id),
name TEXT NOT NULL,
color TEXT, -- default for items inside
icon TEXT, -- OsmAnd icon key
visible INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
UNIQUE (parent_id, name)
);
----
Depth capped at 6 so a tree always fits Locus Premium (warn above 3).
=== Items
[source,sql]
----
CREATE TABLE items (
id TEXT PRIMARY KEY, -- uuid
folder_id TEXT NOT NULL REFERENCES folders(id),
type TEXT NOT NULL, -- 'point' | 'track' | 'route'
name TEXT,
description TEXT,
geometry TEXT NOT NULL, -- GeoJSON geometry (Point / LineString / MultiLineString)
properties TEXT NOT NULL DEFAULT '{}', -- JSON: color, icon, width, category, time,
-- activity_type, photos, address, ...
bbox TEXT NOT NULL, -- [w,s,e,n], for search and the map
fingerprint TEXT NOT NULL, -- hash of type + rounded geometry, for dedupe
source_id TEXT REFERENCES sources(id), -- the uploaded file it came from, if any
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
rev INTEGER NOT NULL -- global change counter at last write
);
CREATE INDEX items_rev ON items(rev);
----
* `type`: `track` = recorded (has timestamps/elevation), `route` =
planned. Both lines; the split matters to Locus and for stats.
* A recorded track keeps per-point time/elevation inside `geometry`'s
coordinates (`[lng, lat, ele]`) plus a parallel `properties.times`
array — what the elevation profile needs today.
* `properties` stays an open JSON bag so a GPX extension we don't model
(Locus/OsmAnd specific) survives a round trip unchanged.
=== Sources (original files)
[source,sql]
----
CREATE TABLE sources (
id TEXT PRIMARY KEY,
filename TEXT NOT NULL,
path TEXT NOT NULL, -- data/library/sources/<id>/<filename>
imported_at TEXT NOT NULL
);
----
An upload is still kept as-is (for "download original"), but what the
app works with is the items extracted from it. Deleting items never
deletes the source; deleting a source is a separate admin action.
=== Links to other apps
[source,sql]
----
CREATE TABLE item_links (
item_id TEXT NOT NULL REFERENCES items(id),
app TEXT NOT NULL, -- 'osmand' | 'locus' | ...
device TEXT NOT NULL, -- one phone/tablet
external_ref TEXT NOT NULL, -- the app's id / favorite name+group / GPX path
synced_rev INTEGER NOT NULL, -- our rev when last pushed/pulled
PRIMARY KEY (item_id, app, device)
);
----
Neither app gives us our id back, so this table — kept by the sync
client, reported to the server — is how "this OsmAnd favorite" and "this
MapTool point" stay the same thing.
=== Change counter
A single `rev` sequence (a one-row table, incremented in the same
transaction as every write) stamped on each folder/item write. `rev` —
not wall-clock time — is what clients sync against, so clock skew on a
phone can't skip a change.
== API
[cols="1,2"]
|===
| Route | Purpose
| `GET /api/library/tree`
| Folders with item counts (replaces `/api/gpx/tree`).
| `GET /api/library/folders/:id/items.geojson`
| A folder's items as a FeatureCollection, `id`/`folder_id`/`updated_at`
in `properties` — what the map draws.
| `POST /api/library/import`
| Multipart upload (GPX/FIT/TCX/GeoJSON/ZIP) into a folder: stores the
source, extracts items, skips items whose `fingerprint` already exists
in that folder (re-sharing the same track from OsmAnd doesn't
duplicate it).
| `PUT /api/library/items/:id`, `DELETE ...`
| Edit (name, description, style, move to folder) / tombstone. `PUT`
carries the `rev` the client last saw; an older one gets `409` with
the current item.
| `GET /api/library/changes?since=<rev>`
| Folders and items (including tombstones) with `rev > since`, plus the
new high-water `rev`. The sync feed.
| `GET /api/library/folders/:id/export.gpx?flavor=locus\|osmand`
| GPX of a folder for an app (see mapping below).
|===
== Mapping to the apps
=== GPX in (import, share target)
* `<wpt>` → point; `<trk>` → track; `<rte>` → route.
* `<type>` → `properties.category`; `osmand:color`/`locus:` color and
`osmand:icon` → `color`/`icon` (already parsed by `Gpx.waypoint_style`).
* Folder: the one picked in the import dialog; a GPX's own waypoint
groups (OsmAnd's per-folder favorites export) become subfolders.
* FIT → one track; TCX → one track per `<Activity>` (`Tcx`).
GeoJSON → items by geometry type.
* Heart rate, cadence, speed and power (FIT field 7, GPX `power` /
`PowerInWatts`, TCX `Watts`) go into the profile; the profile panel
computes splits and best efforts (fastest distances, best power over
5 s–60 min, biggest climb) from it in the browser.
* Laps: `laps` holds each lap's first profile index (FIT lap
`start_time`, TCX `<Lap>`), only with two or more. The panel switches
splits between 1/5/10 km (default by activity: run/hike 1, bike 5,
car 10) and laps; the segments are shaded in the charts, listed in the
table and marked as numbered posts on the map.
=== Points in a track or route
A track/route is a container for points (`parent_id`), like a GPX's own
waypoints: shown, moved, deleted and exported with it. `POST
/api/library/node/:key/points` adds one (the popup's "Add to …" copies a
point into any shown track/route); the tree lists them under the
track, collapsed. In a FIT course they become course points, placed at
the nearest point of the line, the type (water, food, summit, danger,
first aid, valley) guessed from the name/category/icon.
Points get in three ways: "Add to …" in a point's popup (a copy), a new
note saved "Into a track / route", and the route planner's 📍 points
(on by default for named places): saving the route syncs those as
points marked `from_route`, leaving hand-added ones alone.
=== FIT course out
`GET /api/library/node/:key?download=fit` writes the node's first line
as a FIT course (`FitCourse`) for Garmin/Wahoo devices: one record per
point with distance and a timestamp spread over the line's duration (a
4 m/s guess without one); the sport comes from the route's bicycle/foot
profile or the track's activity type.
=== Locus
Folder ⇄ folder, 1:1. Export a folder as one GPX with tracks and points
together (Locus imports it into a folder). Locus-specific extensions
(`locus:icon`, track style) are kept in `properties` and written back.
=== OsmAnd
* A folder's *points* → favorites group with the folder path as its
name ("Van / Croatia 2026"), written as GPX `<wpt>` with `osmand:`
extensions. OsmAnd requires unique names per group → duplicates get
" (2)" appended on export only.
* A folder's *tracks/routes* → one GPX per item in a track folder with
the same path (`tracks/Van/Croatia 2026/<name>.gpx`), track color/width
in the GPX `<extensions>` (exact `osmand:` tag names to verify against
a file exported from OsmAnd).
== Sync (later phase)
* Direction 1 — MapTool → apps: the Android sync client polls
`/changes`, pushes new/changed items into OsmAnd (AIDL: favorites,
GPX import) and Locus (locus-api: points/tracks into a folder), and
records `item_links`. Deletes: remove via the API where it allows it.
* Direction 2 — apps → MapTool: for now, *sharing* from the app (PWA
share target) — fingerprint dedupe makes re-sharing safe. Automatic
reading from the apps only if their APIs turn out to allow listing
data (open question above).
* Conflicts: last writer by `rev` wins per item; the losing version goes
to an `item_history` table so nothing is silently lost.
== Migration from GpxStore
One-off rake task, idempotent, `data/gpx/` left untouched until verified:
. Each directory under `data/gpx/` → a folder (same path).
. Each file → a subfolder named after the file (without extension), its
features → items in it; the file → a `sources` row. (Alternative: put
items straight into the directory's folder — see open questions.)
. Notes' existing `properties.id` reused as the item id, so links to
them survive.
. Category/icon/color carried over in `properties`.
Then the app switches to the library; `GpxStore` and `/api/gpx/*` are
removed once nothing uses them.
== What changes in the code
* `lib/maptool/library.rb` (new): schema, import (reusing `Gpx`, `Fit`,
`Geojson` parsing), queries, change feed, GPX export.
* `app.rb`: `/api/library/*` instead of `/api/gpx/*`.
* `public/js/gpx.js`: tree of folders → items (visibility per folder
and per item, item rename/move/delete), map sources per folder.
* `public/js/notes.js`: create/edit items instead of appending to a
layer file.
* `lib/maptool/search.rb`: the "layers" source queries `items` (an FTS
table over name/description) instead of scanning files in memory.
* Plugins: output imported via the same import path.
* `share_import.js`: posts to `/api/library/import`.
== Phases
. Library schema + import + read-only map view, migration task, behind
the same UI (tree shows folders/items). Old store still present.
. Editing (rename, move, delete, style) + notes on the library; remove
`GpxStore`.
. Change feed + GPX export flavors for OsmAnd/Locus.
. Android sync client (one direction), then the other direction if the
app APIs allow it.
== Decisions (phase 1)
* Migration: each old file → a subfolder named after it, holding the
file as one `layer` item still drawn from its GeoJSON — not split into
points. Splitting a layer into items can come later if needed; new
imports are split right away.
* Track waypoints: independent points with an optional `parent_id` (the
GPX's single track). The tree draws them with their track; Locus can
get them loose in the folder, OsmAnd inside the track's GPX. Both apps
import a GPX with tracks and points together; neither exports GeoJSON
(Locus imports it, OsmAnd doesn't), so exports are GPX.
* Simplified against the schema above: no `sources` table (an item's
`source_path` points at the stored upload), no `description`/`bbox`
columns (in `properties` / computed when needed), folder styling and
`item_links` not yet.
* 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.
== Decisions (phase 3)
* `GET /api/library/changes?since=<rev>`: folders and items with
`rev > since`, tombstones as `"deleted": true`, plus the current `rev`,
read in one transaction. A layer comes without geometry; it's a legacy
file until split. Login-only for now. The Android client will need a
token instead of the browser session (phase 4).
* `GET /api/library/export?folder=<path>&flavor=locus|osmand`, from the
folder's own menu (and the panel header for the top level). It covers
the folder's own items, not its subfolders.
** Locus: one GPX with points, tracks and routes together.
** OsmAnd: a zip. `favourites.gpx` holds the loose points, with the
folder path as their `<type>` group ("Van / CZ") and duplicate names
made unique ("Gate (2)"). `tracks/<folder path>/<name>.gpx` holds
one file per track, route or layer, with that item's own points in
it.
* GPX writing (`Gpx.from_features`): colors as `<osmand:color>`, which is
what import reads back, and on lines also gpx_style `<line><color>`,
which Locus reads. Not verified yet against files the apps export
themselves; adjust the tags once a real OsmAnd/Locus export is at
hand.
== Open questions
* Folder depth over 3 — fine to require Locus Premium?
* Does OsmAnd's AIDL API list existing favorites/tracks? Does locus-api
read points/tracks by folder? Decides whether direction 2 can be
automatic.