From 25b87b94fe20fd93d5fe157fd6c38507482c3024 Mon Sep 17 00:00:00 2001 From: Roman Priesol Date: Thu, 12 Nov 2026 13:42:04 +0100 Subject: [PATCH] Installable PWA with a share target; design for an item-based library Android's share sheet (OsmAnd, Locus, mapy.com, ...) can now send GPX/FIT/GeoJSON/ZIP files to the installed app: the service worker parks them and the page offers to import them into a Tracks & Points folder, waiting through a login if needed. Manifest, app icon, a server-side fallback for /share-target. docs/library-design.adoc proposes replacing the file-based GpxStore with folders and items (stable ids, timestamps, tombstones, a change feed) as the base for syncing with OsmAnd and Locus. --- TODO.adoc | 7 + app.rb | 11 ++ docs/library-design.adoc | 319 ++++++++++++++++++++++++++++++++++++ public/css/style.css | 57 +++++++ public/icons/icon-192.png | Bin 0 -> 3910 bytes public/icons/icon-512.png | Bin 0 -> 11405 bytes public/icons/icon.svg | 9 + public/js/gpx.js | 20 ++- public/js/map.js | 2 + public/js/share_import.js | 120 ++++++++++++++ public/manifest.webmanifest | 35 ++++ public/sw.js | 42 ++++- test/test_app.rb | 13 ++ views/layout.erb | 7 + 14 files changed, 637 insertions(+), 5 deletions(-) create mode 100644 docs/library-design.adoc create mode 100644 public/icons/icon-192.png create mode 100644 public/icons/icon-512.png create mode 100644 public/icons/icon.svg create mode 100644 public/js/share_import.js create mode 100644 public/manifest.webmanifest diff --git a/TODO.adoc b/TODO.adoc index 4ce059f..ddbb576 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -70,6 +70,13 @@ independence from connectivity. ** [x] Kiwix as a source — full-text search of the ZIM (`Kiwix.search`), each hit's coordinates read from its page like the Wikipedia layer does; clicking opens the article (and jumps to it when it has coordinates) ** [x] Nearest first — every result carries its distance from the map center and the list is sorted by it across all sources; settlements count as closer (city x0.01 … suburb x0.3, `Places::DISTANCE_WEIGHT`) so a town's name still finds the town. Nominatim gets the visible area as a (non-restricting) `viewbox` +== Sync with OsmAnd / Locus / mapy.com + +* [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) +* [ ] Item-based library replacing the file-based `GpxStore` — design in `docs/library-design.adoc` +* [ ] Change feed + GPX export flavors for OsmAnd/Locus +* [ ] Android sync client (MapTool → apps first; apps → MapTool only if their APIs can list data) + == Nice to have (later) Deprioritized for now — revisit after the sections above land. diff --git a/app.rb b/app.rb index 08bf27f..5163d54 100644 --- a/app.rb +++ b/app.rb @@ -52,6 +52,9 @@ module Maptool class App < Sinatra::Base set :public_folder, File.join(__dir__, "public") + # The PWA manifest (public/manifest.webmanifest) — Rack doesn't know + # this extension and would serve it as application/octet-stream. + mime_type :webmanifest, "application/manifest+json" set :views, File.join(__dir__, "views") # sinatra/json defaults to MultiJson, whose `encode` (what @@ -250,6 +253,14 @@ module Maptool erb :index, locals: { logged_in: logged_in?, user: session[:user], revision: REVISION } end + # A share to the installed app normally never reaches the server: the + # service worker (public/sw.js) takes the POST, parks the files and + # opens the app. Only lands here if no worker is running yet — back to + # the map rather than a 404, the share just has to be repeated. + post "/share-target" do + redirect "/", 303 + end + get "/api/health" do json status: "ok", revision: REVISION end diff --git a/docs/library-design.adoc b/docs/library-design.adoc new file mode 100644 index 0000000..40fe5cd --- /dev/null +++ b/docs/library-design.adoc @@ -0,0 +1,319 @@ += Library: data model for tracks, points and sync (design) +:toc: +:toclevels: 2 + +Status: *proposal, not implemented.* 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 `` 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// + 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/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=` +| 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) + +* `` → point; `` → track; `` → route. +* `` → `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. GeoJSON → items by geometry 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 `` 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/.gpx`), track color/width + in the GPX `` (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. + +== Open questions + +* Migration: one subfolder per old file, or the file's items flattened + into its directory's folder? +* Should a recorded track keep its own waypoints as children (GPX-style) + or as independent points in the same folder (Locus-style)? Proposed: + independent points. +* 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. diff --git a/public/css/style.css b/public/css/style.css index b47cc29..93a84f7 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -99,6 +99,63 @@ html, body { color: #fff; } +/* Files shared to the installed app (share_import.js), waiting to be + imported. */ +.share-import { + position: fixed; + bottom: 16px; + left: 50%; + transform: translateX(-50%); + z-index: 40; + width: 320px; + max-width: calc(100vw - 32px); + box-sizing: border-box; + padding: 12px; + background: #1a1a1a; + color: #ddd; + border-radius: 6px; + box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35); + font-size: 13px; +} + +.share-import__files { + margin: 6px 0; + padding-left: 18px; + max-height: 120px; + overflow-y: auto; + overflow-wrap: anywhere; +} + +.share-import__folder { + display: flex; + align-items: center; + gap: 8px; +} + +.share-import__folder input { + flex: 1; + min-width: 0; + padding: 4px 6px; + font: inherit; +} + +.share-import__actions { + display: flex; + justify-content: flex-end; + align-items: center; + gap: 12px; + margin-top: 10px; +} + +.share-import__actions a { + color: #8fb8ff; +} + +.share-import__status { + margin: 8px 0 0; + color: #f2a29a; +} + /* Horizon-style sun & moon chart, dropped down from the topbar's sun readout (sun.js sunChartHtml). */ .sun-chart { diff --git a/public/icons/icon-192.png b/public/icons/icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..d4c85c5e17449b86bc8f74e8d470e7fb0c90a1ed GIT binary patch literal 3910 zcmd5X-s9hpf(ON|t!Vev^L5-@S6???^8MSL~QHmO^R_#%%MJQS$h$2XI z8np#6s%D6qHQG0Qet*CJzR&x|9nU%Ux%b@jIiGXyd2DQ`%YIt$GynkXxAbn_qmP|` z8#9F7-<$Geq7N*-dY1kG!1(xY19`a>9MXjX0ooP;CO$3!!47`TKyYv{{Jyt`zmtQn zGu+3|HE%;r5CAxaZr#*Ch2&GG!+lXBXPIc5*SE*NCUZ%}sN^s(1ZoO}Y9|+HT+nHo@c!xTlVewv{V6mpYQNBbfcL`;S?!mWAOkco+@sl>?r>4e8T(vDNj59%g7PbPow ztPCB{x;eK-t$pT}2TMWNdus87Sf=m>_`~C@!onwQZE92g{pxjAZ?FxaKfVa?!eFHh z4ZMcsCK)Q)L|}RNj_P!r^XJUD4g4m@_;onCJ!N-o%xU|_SKk&J5cz2)KTyEJ%BmF= zb^S+Q0c-u0%j)Cl(ngMhCEAyxjzf(1UJOU>cF>nVIq5zTKM&-+Zqi7^@nS zm6nEC87lAoS8-EKNK z6npoA*H5vy3>0Zxkd@W6u*e>LwPT4w@v=d{va+%b@K=-&2-lacN34NYhzAD?PsI_4 zyK9PvsUR*rP0dpx5j2fApJ~Y>?!^2n{tfU_3O^9@C0ChsZf*{XTk~t7jhLg0vDnk) zh6P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3$_|HbvJjA;Wva{s z=y#d5l|rT>1Q6UQ5rc+$3ySffsyjUnxScAWu}g8b!KS&JhRHH76G(ZYUA2L_^_9O; ziiH|Z6<@h;LZ4`MTHrUKwc2sGPXNd%W0up`}_ z{;8&i{gbEjv7)-p^RcD+KV3zH1|J_=)4M)D$^E1`Psc|td-mOwsEVk_8Jzi}X!hAE zVe1td2Ayj75zA4H2zfUVSvhmjIEP=GH6D&S4^d9oG)Q^>w2`cH@#6PExl4O4u6KUM z+|X)_*Tki1_5WmDc%OFlbeY>yh`iA~t+79To{JqSQS>=CswRv}B8rZ^J1Uzfj=W*0 zLr$8Gy|^Jc`}>rt=ApoIvn6#0H#+eJhYRVr(zn0Li3V0w9H zD9?#g<}_CoCBD|4qs(Go;_9$@Chw-;(n}8P(x9@1-dq+-!Dx{5D-T8_rxI>1_bH-m zUM=%fuJn4_o;UhByNzEjJ-?$^YnBp4nlVLc)Q7-Pzjt|}uS@in7$=q}ibF0^v$a*W zNDvbjUi$C_a19m$kFt z;m&dq;oij|+$y7fk%SQB*#Roj@ZL z9Hru>Ds_U%llK!2ld7;GLVi)}C4YLTMDCKy)y z!X&3R7Mhm5zR|^nKof|xs>1IukX8i{kO=x)t^dCKZyf%=0>L_oj7o`IG5M76EI<@d NxvHsHsbCrQzW}_Z-2wmr literal 0 HcmV?d00001 diff --git a/public/icons/icon.svg b/public/icons/icon.svg new file mode 100644 index 0000000..af37895 --- /dev/null +++ b/public/icons/icon.svg @@ -0,0 +1,9 @@ + + + + + + + diff --git a/public/js/gpx.js b/public/js/gpx.js index dcd7f90..cfcb4e6 100644 --- a/public/js/gpx.js +++ b/public/js/gpx.js @@ -957,10 +957,11 @@ export class GpxPanelControl { // file already in this app's own shape (e.g. a previous /api/gpx/file // response, saved and re-uploaded) can skip GPX/FIT entirely. const files = [...fileList].filter((file) => /\.(gpx|fit|geojson|zip)$/i.test(file.name)); - if (files.length === 0) return; + if (files.length === 0) return []; let tree = null; let failed = 0; + const uploaded = []; for (const [index, file] of files.entries()) { this._setStatus(files.length === 1 ? "Uploading…" : `Uploading ${index + 1} of ${files.length}…`); @@ -978,10 +979,12 @@ export class GpxPanelControl { const xhr = await uploadFile(formData, () => this._setStatus("Converting…")); if (xhr.status === 401) { window.location.href = "/login"; - return; + return uploaded; } if (xhr.status < 200 || xhr.status >= 300) throw new Error("upload failed"); - ({ tree } = JSON.parse(xhr.responseText)); + let paths; + ({ tree, paths } = JSON.parse(xhr.responseText)); + uploaded.push(...paths); } catch (err) { failed += 1; } @@ -989,6 +992,17 @@ export class GpxPanelControl { if (tree) this._renderTree(tree); this._setStatus(failed > 0 ? `${failed} of ${files.length} uploads failed.` : "Uploaded."); + return uploaded; + } + + // Files shared to the installed app (share_import.js): uploaded like a + // drop onto the tree, then shown on the map straight away — whoever + // shared a track from OsmAnd/Locus wants to see it, not hunt for it. + async importFiles(files, folder) { + this._togglePanel(true); + const paths = await this._uploadFiles(files, folder); + await Promise.all(paths.map((path) => this.show(path))); + return paths; } async _deleteFile(path) { diff --git a/public/js/map.js b/public/js/map.js index ffbbf2f..90d7ae1 100644 --- a/public/js/map.js +++ b/public/js/map.js @@ -21,6 +21,7 @@ import { formatCoords, formatSunInfo, sunChartHtml } from "/js/sun.js"; import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js"; import { isLoggedIn } from "/js/auth.js"; import { DebugControl } from "/js/debug.js"; +import { offerSharedFiles } from "/js/share_import.js"; import HomeButton from "/vendor/npmap-home-button/home-button.esm.js"; import OverviewMap from "/vendor/npmap-overview/overview.esm.js"; import * as maplibregl from "/vendor/maplibre-gl/maplibre-gl.mjs"; @@ -570,6 +571,7 @@ const gpxPanel = new GpxPanelControl(map, profilePanel); gpxPanel.mount(sidebar); const overlaysControl = new OverlaysControl(map); overlaysControl.mount(sidebar); +offerSharedFiles(gpxPanel); searchControl.setLayerOpeners({ layers: (path, result) => gpxPanel.showFeature(path, result.bbox.slice(0, 2)), hiking_trails: (code) => overlaysControl.showHikingTrailsCountry(code), diff --git a/public/js/share_import.js b/public/js/share_import.js new file mode 100644 index 0000000..8e1a2fb --- /dev/null +++ b/public/js/share_import.js @@ -0,0 +1,120 @@ +import { isLoggedIn } from "/js/auth.js"; +import { escapeHtml } from "/js/gpx.js"; + +// Files shared to the installed app from Android's share sheet (OsmAnd, +// Locus, mapy.com, a file manager, ...): public/sw.js parks them in this +// cache and opens the app; this offers to import them into a folder of +// Tracks & Points. Checked on every page load, not just right after a +// share, so a share made while logged out is still waiting after login. +const SHARED_CACHE = "shared-files"; +const KNOWN_EXTENSION = /\.(gpx|fit|geojson|zip)$/i; +// Some apps share a bare name ("Track 12") — the upload only accepts +// these extensions, so one is added from the file's type. +const EXTENSION_BY_TYPE = { + "application/gpx+xml": ".gpx", + "application/xml": ".gpx", + "text/xml": ".gpx", + "application/geo+json": ".geojson", + "application/json": ".geojson", + "application/zip": ".zip", + "application/vnd.ant.fit": ".fit", +}; +const DEFAULT_FOLDER = "Shared"; + +export async function offerSharedFiles(gpxPanel) { + if (new URLSearchParams(window.location.search).has("shared")) window.history.replaceState(null, "", "/"); + if (!("caches" in window)) return; + + let cache; + let requests; + try { + cache = await caches.open(SHARED_CACHE); + requests = await cache.keys(); + } catch { + return; // storage blocked — nothing to offer + } + if (requests.length === 0) return; + + const files = await Promise.all( + requests.map(async (request) => { + const response = await cache.match(request); + const blob = await response.blob(); + return new File([blob], withExtension(decodeURIComponent(response.headers.get("x-filename") || "shared"), blob.type), { + type: blob.type, + }); + }), + ); + const discard = () => Promise.all(requests.map((request) => cache.delete(request))); + + const card = document.createElement("div"); + card.className = "share-import"; + card.innerHTML = ` + Shared to MapTool + + ${ + isLoggedIn() + ? ` + ` + : `

Log in to import — they'll wait here until then.

+ ` + } + + `; + document.body.appendChild(card); + + card.querySelector('[data-action="discard"]').addEventListener("click", async () => { + await discard(); + card.remove(); + }); + + const importButton = card.querySelector('[data-action="import"]'); + if (!importButton) return; + + fillFolderSuggestions(card.querySelector("datalist")); + importButton.addEventListener("click", async () => { + const folder = card.querySelector(".share-import__folder input").value.trim(); + card.querySelectorAll("button").forEach((button) => (button.disabled = true)); + const paths = await gpxPanel.importFiles(files, folder); + if (paths.length > 0) { + await discard(); + card.remove(); + return; + } + // Nothing made it in (wrong file type, server error) — keep them + // parked so another try or a discard is still possible. + const status = card.querySelector(".share-import__status"); + status.hidden = false; + status.textContent = "Import failed — only GPX, FIT, GeoJSON and ZIP files can be imported."; + card.querySelectorAll("button").forEach((button) => (button.disabled = false)); + }); +} + +function withExtension(name, type) { + return KNOWN_EXTENSION.test(name) ? name : `${name}${EXTENSION_BY_TYPE[type] || ".gpx"}`; +} + +async function fillFolderSuggestions(datalist) { + try { + const tree = await (await fetch("/api/gpx/tree")).json(); + const folders = []; + const walk = (node) => + (node.children || []).forEach((child) => { + if (child.type !== "folder") return; + folders.push(child.path); + walk(child); + }); + walk(tree); + datalist.innerHTML = folders.map((path) => `