Library phase 1: SQLite item library with folders, migration of old files as layers, import split into items
This commit is contained in:
1 parent
4216211a20
commit
ad8b72c3d3
16 files changed
+890
-492
No files matched your search
@@ -32,6 +32,10 @@
|
|||||||
/data/gpx/*
|
/data/gpx/*
|
||||||
!/data/gpx/.gitkeep
|
!/data/gpx/.gitkeep
|
||||||
|
|
||||||
|
# Tracks & Points library (lib/maptool/library.rb) and its stored uploads
|
||||||
|
/data/library.sqlite*
|
||||||
|
/data/library/
|
||||||
|
|
||||||
# Garmin LiveTrack session IDs received via webhook
|
# Garmin LiveTrack session IDs received via webhook
|
||||||
/data/livetrack.json
|
/data/livetrack.json
|
||||||
|
|
||||||
|
|||||||
@@ -54,6 +54,20 @@ namespace :places do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
namespace :library do
|
||||||
|
desc "Migrate data/gpx/ files into the library (runs on first start anyway; idempotent)"
|
||||||
|
task :migrate do
|
||||||
|
require_relative "lib/maptool/library"
|
||||||
|
|
||||||
|
data_dir = ENV.fetch("MAPTOOL_DATA_DIR") { File.join(__dir__, "data") }
|
||||||
|
library = Maptool::Library.new(File.join(data_dir, "library.sqlite"),
|
||||||
|
gpx_store: Maptool::GpxStore.new(File.join(data_dir, "gpx")),
|
||||||
|
sources_dir: File.join(data_dir, "library", "sources"))
|
||||||
|
library.migrate
|
||||||
|
puts "Library at rev #{library.rev}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
namespace :gpx do
|
namespace :gpx do
|
||||||
desc "Backfill properties.id on Note-category features saved before edit/delete (and its id targeting) existed"
|
desc "Backfill properties.id on Note-category features saved before edit/delete (and its id targeting) existed"
|
||||||
task :backfill_note_ids do
|
task :backfill_note_ids do
|
||||||
|
|||||||
@@ -73,7 +73,8 @@ independence from connectivity.
|
|||||||
== Sync with OsmAnd / Locus / mapy.com
|
== 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)
|
* [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`
|
* [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
|
||||||
* [ ] Change feed + GPX export flavors for OsmAnd/Locus
|
* [ ] Change feed + GPX export flavors for OsmAnd/Locus
|
||||||
* [ ] Android sync client (MapTool → apps first; apps → MapTool only if their APIs can list data)
|
* [ ] Android sync client (MapTool → apps first; apps → MapTool only if their APIs can list data)
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ require "stringio"
|
|||||||
require_relative "lib/maptool/gpx"
|
require_relative "lib/maptool/gpx"
|
||||||
require_relative "lib/maptool/fit"
|
require_relative "lib/maptool/fit"
|
||||||
require_relative "lib/maptool/gpx_store"
|
require_relative "lib/maptool/gpx_store"
|
||||||
|
require_relative "lib/maptool/library"
|
||||||
require_relative "lib/maptool/gpsd_client"
|
require_relative "lib/maptool/gpsd_client"
|
||||||
require_relative "lib/maptool/livetrack_store"
|
require_relative "lib/maptool/livetrack_store"
|
||||||
require_relative "lib/maptool/livetrack_client"
|
require_relative "lib/maptool/livetrack_client"
|
||||||
@@ -101,7 +102,10 @@ module Maptool
|
|||||||
|
|
||||||
OFFLINE_PMTILES_PATH = File.join(DATA_DIR, "offline.pmtiles")
|
OFFLINE_PMTILES_PATH = File.join(DATA_DIR, "offline.pmtiles")
|
||||||
TERRAIN_PMTILES_PATH = File.join(DATA_DIR, "terrain.pmtiles")
|
TERRAIN_PMTILES_PATH = File.join(DATA_DIR, "terrain.pmtiles")
|
||||||
|
# Pre-library uploads (data/gpx/), still read for migrated layers.
|
||||||
GPX_STORE = GpxStore.new(File.join(DATA_DIR, "gpx"))
|
GPX_STORE = GpxStore.new(File.join(DATA_DIR, "gpx"))
|
||||||
|
LIBRARY = Library.new(File.join(DATA_DIR, "library.sqlite"), gpx_store: GPX_STORE,
|
||||||
|
sources_dir: File.join(DATA_DIR, "library", "sources"))
|
||||||
LIVETRACK_STORE = LiveTrackStore.new(File.join(DATA_DIR, "livetrack.json"))
|
LIVETRACK_STORE = LiveTrackStore.new(File.join(DATA_DIR, "livetrack.json"))
|
||||||
|
|
||||||
# Not under DATA_DIR: unlike everything else there (uploads, PMTiles,
|
# Not under DATA_DIR: unlike everything else there (uploads, PMTiles,
|
||||||
@@ -182,14 +186,22 @@ module Maptool
|
|||||||
# what it declared — so a lying header can't sneak past this either.
|
# what it declared — so a lying header can't sneak past this either.
|
||||||
MAX_ZIP_UNCOMPRESSED = 500 * 1024 * 1024
|
MAX_ZIP_UNCOMPRESSED = 500 * 1024 * 1024
|
||||||
|
|
||||||
|
def parse_feature
|
||||||
|
feature = JSON.parse(params[:feature].to_s)
|
||||||
|
halt 400, json(error: "invalid feature") unless feature.is_a?(Hash) && feature["geometry"]
|
||||||
|
feature
|
||||||
|
rescue JSON::ParserError
|
||||||
|
halt 400, json(error: "invalid feature")
|
||||||
|
end
|
||||||
|
|
||||||
def save_zip_entries(folder:, io:)
|
def save_zip_entries(folder:, io:)
|
||||||
paths = []
|
paths = []
|
||||||
Zip::File.open_buffer(io) do |zip|
|
Zip::File.open_buffer(io) do |zip|
|
||||||
entries = zip.select { |entry| entry.file? && GpxStore::TRACK_EXTENSIONS.any? { |ext| entry.name.downcase.end_with?(ext) } }
|
entries = zip.select { |entry| entry.file? && Library::EXTENSIONS.any? { |ext| entry.name.downcase.end_with?(ext) } }
|
||||||
halt 413, json(error: "zip contents too large") if entries.sum(&:size) > MAX_ZIP_UNCOMPRESSED
|
halt 413, json(error: "zip contents too large") if entries.sum(&:size) > MAX_ZIP_UNCOMPRESSED
|
||||||
|
|
||||||
entries.each do |entry|
|
entries.each do |entry|
|
||||||
paths << GPX_STORE.save(folder: folder, filename: File.basename(entry.name), io: StringIO.new(entry.get_input_stream.read))
|
paths.concat(LIBRARY.import(folder: folder, filename: File.basename(entry.name), io: StringIO.new(entry.get_input_stream.read)))
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
paths
|
paths
|
||||||
@@ -452,7 +464,7 @@ module Maptool
|
|||||||
sources = params[:sources].to_s.split(",")
|
sources = params[:sources].to_s.split(",")
|
||||||
sources = Search::SOURCES.keys if sources.empty?
|
sources = Search::SOURCES.keys if sources.empty?
|
||||||
center = params[:lat] && params[:lng] ? [params[:lat].to_f, params[:lng].to_f] : nil
|
center = params[:lat] && params[:lng] ? [params[:lat].to_f, params[:lng].to_f] : nil
|
||||||
json results: Search.query(params[:q], gpx_store: GPX_STORE, data_dir: DATA_DIR, sources: sources,
|
json results: Search.query(params[:q], library: LIBRARY, data_dir: DATA_DIR, sources: sources,
|
||||||
center: center, kiwix_url: KIWIX_URL)
|
center: center, kiwix_url: KIWIX_URL)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -494,98 +506,134 @@ module Maptool
|
|||||||
body response.body
|
body response.body
|
||||||
end
|
end
|
||||||
|
|
||||||
get "/api/gpx/tree" do
|
# Tracks & Points (lib/maptool/library.rb). Reading is login-free like
|
||||||
json GPX_STORE.tree
|
# the rest of the map; every write needs a login. A node `key` is
|
||||||
|
# "item:<id>" or "points:<folder id>" (see Library).
|
||||||
|
get "/api/library/tree" do
|
||||||
|
json LIBRARY.tree
|
||||||
end
|
end
|
||||||
|
|
||||||
# A .zip (Garmin's bulk/FIT export format) is expanded into its
|
# A .zip (Garmin's bulk/FIT export format) is expanded into its
|
||||||
# .gpx/.fit/.geojson entries instead of being stored itself — nothing
|
# .gpx/.fit/.geojson entries, each imported like its own upload.
|
||||||
# downstream (tree listing, map rendering) knows what to do with a zip.
|
post "/api/library/import" do
|
||||||
post "/api/gpx" do
|
|
||||||
require_login!
|
require_login!
|
||||||
file = params[:file]
|
file = params[:file]
|
||||||
halt 400, json(error: "file is required") unless file && file[:tempfile]
|
halt 400, json(error: "file is required") unless file && file[:tempfile]
|
||||||
|
|
||||||
begin
|
begin
|
||||||
paths = if file[:filename].to_s.downcase.end_with?(".zip")
|
keys = if file[:filename].to_s.downcase.end_with?(".zip")
|
||||||
save_zip_entries(folder: params[:folder].to_s, io: file[:tempfile])
|
save_zip_entries(folder: params[:folder].to_s, io: file[:tempfile])
|
||||||
else
|
else
|
||||||
[GPX_STORE.save(folder: params[:folder].to_s, filename: file[:filename], io: file[:tempfile])]
|
LIBRARY.import(folder: params[:folder].to_s, filename: file[:filename], io: file[:tempfile])
|
||||||
end
|
end
|
||||||
rescue GpxStore::InvalidPath
|
rescue Library::InvalidPath
|
||||||
halt 400, json(error: "invalid folder")
|
halt 400, json(error: "invalid folder")
|
||||||
|
rescue Library::ParseError
|
||||||
|
halt 422, json(error: "could not parse file")
|
||||||
rescue Zip::Error
|
rescue Zip::Error
|
||||||
halt 400, json(error: "invalid zip file")
|
halt 400, json(error: "invalid zip file")
|
||||||
end
|
end
|
||||||
|
|
||||||
json paths: paths, tree: GPX_STORE.tree
|
json paths: keys, tree: LIBRARY.tree
|
||||||
end
|
end
|
||||||
|
|
||||||
# A hand-drawn point/note (see notes.js) — unlike the upload above, this
|
# ?download=original sends the file the node came from, ?download=geojson
|
||||||
# grows one existing/new .geojson "layer" file in place (GpxStore#
|
# the node's GeoJSON as an attachment — both login-only, like the other
|
||||||
# append_feature) rather than always landing as its own new file.
|
# export/manage actions; plain viewing on the map isn't.
|
||||||
post "/api/gpx/notes" do
|
get "/api/library/node/:key" do
|
||||||
|
require_login! if params[:download]
|
||||||
|
key = params[:key]
|
||||||
|
|
||||||
|
if params[:download] == "original"
|
||||||
|
path = LIBRARY.original(key)
|
||||||
|
halt 404 unless path && File.file?(path)
|
||||||
|
return send_file(path, filename: File.basename(path), disposition: "attachment")
|
||||||
|
end
|
||||||
|
|
||||||
|
begin
|
||||||
|
body = LIBRARY.geojson(key)
|
||||||
|
rescue Library::NotFound, Errno::ENOENT
|
||||||
|
halt 404
|
||||||
|
rescue Gpx::ParseError, Fit::ParseError
|
||||||
|
halt 422, json(error: "could not parse file")
|
||||||
|
end
|
||||||
|
|
||||||
|
content_type :json
|
||||||
|
attachment "#{params[:name].to_s.empty? ? "export" : File.basename(params[:name].to_s)}.geojson" if params[:download]
|
||||||
|
body
|
||||||
|
end
|
||||||
|
|
||||||
|
delete "/api/library/node/:key" do
|
||||||
require_login!
|
require_login!
|
||||||
begin
|
LIBRARY.delete_node(params[:key])
|
||||||
feature = JSON.parse(params[:feature].to_s)
|
json tree: LIBRARY.tree
|
||||||
rescue JSON::ParserError
|
rescue Library::NotFound
|
||||||
halt 400, json(error: "invalid feature")
|
halt 404
|
||||||
end
|
end
|
||||||
halt 400, json(error: "invalid feature") unless feature.is_a?(Hash) && feature["geometry"]
|
|
||||||
|
|
||||||
begin
|
post "/api/library/move" do
|
||||||
path = GPX_STORE.append_feature(
|
require_login!
|
||||||
feature: feature,
|
key = LIBRARY.move_node(params[:key].to_s, params[:to_folder].to_s)
|
||||||
path: params[:path],
|
json path: key, tree: LIBRARY.tree
|
||||||
folder: params[:folder].to_s,
|
rescue Library::InvalidPath
|
||||||
name: params[:name].to_s
|
halt 400, json(error: "invalid folder")
|
||||||
)
|
rescue Library::NotFound
|
||||||
rescue GpxStore::InvalidPath
|
halt 404
|
||||||
|
end
|
||||||
|
|
||||||
|
post "/api/library/folder" do
|
||||||
|
require_login!
|
||||||
|
LIBRARY.create_folder(params[:path].to_s)
|
||||||
|
json tree: LIBRARY.tree
|
||||||
|
rescue Library::InvalidPath
|
||||||
halt 400, json(error: "invalid path")
|
halt 400, json(error: "invalid path")
|
||||||
rescue Errno::ENOENT
|
|
||||||
halt 404, json(error: "file not found")
|
|
||||||
end
|
end
|
||||||
|
|
||||||
json path: path, tree: GPX_STORE.tree
|
delete "/api/library/folder/*" do
|
||||||
end
|
|
||||||
|
|
||||||
# Editing/deleting one note (see the popup's Edit/Delete actions,
|
|
||||||
# gpx.js) — targets a feature by properties["id"], not array position
|
|
||||||
# (see GpxStore#update_feature/#delete_feature for why).
|
|
||||||
put "/api/gpx/notes" do
|
|
||||||
require_login!
|
require_login!
|
||||||
begin
|
LIBRARY.delete_folder(params[:splat].first)
|
||||||
feature = JSON.parse(params[:feature].to_s)
|
json tree: LIBRARY.tree
|
||||||
rescue JSON::ParserError
|
rescue Library::InvalidPath
|
||||||
halt 400, json(error: "invalid feature")
|
halt 400
|
||||||
|
rescue Library::NotFound
|
||||||
|
halt 404
|
||||||
end
|
end
|
||||||
halt 400, json(error: "invalid feature") unless feature.is_a?(Hash) && feature["geometry"]
|
|
||||||
|
# A hand-drawn point/shape (notes.js, measure.js) into a folder.
|
||||||
|
post "/api/library/notes" do
|
||||||
|
require_login!
|
||||||
|
feature = parse_feature
|
||||||
|
key = LIBRARY.add_note(feature, params[:folder].to_s)
|
||||||
|
json path: key, tree: LIBRARY.tree
|
||||||
|
rescue Library::InvalidPath
|
||||||
|
halt 400, json(error: "invalid folder")
|
||||||
|
end
|
||||||
|
|
||||||
|
# Edit/delete one note from its popup: `path` is the node it's drawn
|
||||||
|
# in, `id` its properties.id.
|
||||||
|
put "/api/library/notes" do
|
||||||
|
require_login!
|
||||||
|
feature = parse_feature
|
||||||
halt 400, json(error: "path and id are required") if params[:path].to_s.empty? || params[:id].to_s.empty?
|
halt 400, json(error: "path and id are required") if params[:path].to_s.empty? || params[:id].to_s.empty?
|
||||||
|
|
||||||
begin
|
LIBRARY.update_feature(params[:path], params[:id], feature)
|
||||||
GPX_STORE.update_feature(path: params[:path], id: params[:id], feature: feature)
|
json ok: true
|
||||||
|
rescue Library::NotFound, Errno::ENOENT
|
||||||
|
halt 404, json(error: "note not found")
|
||||||
rescue GpxStore::InvalidPath
|
rescue GpxStore::InvalidPath
|
||||||
halt 400, json(error: "invalid path")
|
halt 400, json(error: "invalid path")
|
||||||
rescue Errno::ENOENT
|
|
||||||
halt 404, json(error: "note not found")
|
|
||||||
end
|
end
|
||||||
|
|
||||||
json ok: true
|
delete "/api/library/notes" do
|
||||||
end
|
|
||||||
|
|
||||||
delete "/api/gpx/notes" do
|
|
||||||
require_login!
|
require_login!
|
||||||
halt 400, json(error: "path and id are required") if params[:path].to_s.empty? || params[:id].to_s.empty?
|
halt 400, json(error: "path and id are required") if params[:path].to_s.empty? || params[:id].to_s.empty?
|
||||||
|
|
||||||
begin
|
LIBRARY.delete_feature(params[:path], params[:id])
|
||||||
GPX_STORE.delete_feature(path: params[:path], id: params[:id])
|
json ok: true
|
||||||
|
rescue Library::NotFound, Errno::ENOENT
|
||||||
|
halt 404, json(error: "note not found")
|
||||||
rescue GpxStore::InvalidPath
|
rescue GpxStore::InvalidPath
|
||||||
halt 400, json(error: "invalid path")
|
halt 400, json(error: "invalid path")
|
||||||
rescue Errno::ENOENT
|
|
||||||
halt 404, json(error: "note not found")
|
|
||||||
end
|
|
||||||
|
|
||||||
json ok: true
|
|
||||||
end
|
end
|
||||||
|
|
||||||
# Lists whatever import plugins are on disk (see lib/maptool/plugins.rb
|
# Lists whatever import plugins are on disk (see lib/maptool/plugins.rb
|
||||||
@@ -596,11 +644,9 @@ module Maptool
|
|||||||
end
|
end
|
||||||
|
|
||||||
# Runs one plugin for the given bbox (the current map viewport, from
|
# Runs one plugin for the given bbox (the current map viewport, from
|
||||||
# the frontend's "Run for this area" button) and saves its GeoJSON
|
# the frontend's "Run for this area" button) and imports its GeoJSON
|
||||||
# output as a new file the same way an uploaded .geojson would be
|
# output into a folder of its own, named after the area's center and
|
||||||
# saved — reusing GpxStore#save rather than #append_feature since this
|
# the run's time — so one run's POIs stay apart from another's.
|
||||||
# writes a whole FeatureCollection at once, not one feature into an
|
|
||||||
# existing one.
|
|
||||||
post "/api/plugins/:name/run" do
|
post "/api/plugins/:name/run" do
|
||||||
require_login!
|
require_login!
|
||||||
bbox = %w[south west north east].map { |key| params[key].to_s }
|
bbox = %w[south west north east].map { |key| params[key].to_s }
|
||||||
@@ -613,114 +659,13 @@ module Maptool
|
|||||||
halt 502, json(error: e.message)
|
halt 502, json(error: e.message)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Filename carries the area's center and the run's timestamp (same
|
|
||||||
# idea as a p4n2gpx export's own "p4n_area_<lat>_<lon>_<date>_<time>"
|
|
||||||
# naming) — without it, running this again for a different area just
|
|
||||||
# overwrote/renamed-with-a-counter the same "overpass-pois.geojson",
|
|
||||||
# with nothing in the file tree to tell one run's POIs from another's.
|
|
||||||
center_lat = format("%.2f", (south + north) / 2)
|
center_lat = format("%.2f", (south + north) / 2)
|
||||||
center_lon = format("%.2f", (west + east) / 2)
|
center_lon = format("%.2f", (west + east) / 2)
|
||||||
timestamp = Time.now.strftime("%y%m%d_%H%M")
|
timestamp = Time.now.strftime("%y%m%d_%H%M")
|
||||||
filename = "#{params[:name]}_#{center_lat}_#{center_lon}_#{timestamp}.geojson"
|
name = "#{params[:name]}_#{center_lat}_#{center_lon}_#{timestamp}"
|
||||||
|
|
||||||
path = GPX_STORE.save(folder: "", filename: filename, io: StringIO.new(JSON.generate(geojson)))
|
keys = LIBRARY.import(folder: name, filename: "#{name}.geojson", io: StringIO.new(JSON.generate(geojson)))
|
||||||
json path: path, tree: GPX_STORE.tree
|
json path: keys.first, tree: LIBRARY.tree
|
||||||
end
|
|
||||||
|
|
||||||
# ?download=geojson exports the file's GeoJSON as an attachment instead
|
|
||||||
# of rendering it on the map — the only way to get a .gpx/.fit's
|
|
||||||
# converted form out of the app, since GpxStore#geojson's cache is
|
|
||||||
# otherwise an internal implementation detail with no filename of its
|
|
||||||
# own to expose. ?download=original exports the untouched, as-uploaded
|
|
||||||
# file instead (a .geojson source's "original" is that same file, so
|
|
||||||
# the two downloads are identical there — harmless, not special-cased).
|
|
||||||
# Both gated the same as the other write/manage actions below (upload,
|
|
||||||
# move, create folder) — viewing a file on the map stays open to
|
|
||||||
# anyone, exporting it as a file does not.
|
|
||||||
get "/api/gpx/file/*" do
|
|
||||||
require_login! if params[:download]
|
|
||||||
|
|
||||||
if params[:download] == "original"
|
|
||||||
begin
|
|
||||||
path = GPX_STORE.resolve_file(params[:splat].first)
|
|
||||||
rescue GpxStore::InvalidPath
|
|
||||||
halt 400
|
|
||||||
end
|
|
||||||
halt 404 unless File.file?(path)
|
|
||||||
return send_file(path, filename: File.basename(path), disposition: "attachment")
|
|
||||||
end
|
|
||||||
|
|
||||||
begin
|
|
||||||
body = GPX_STORE.geojson(params[:splat].first)
|
|
||||||
rescue GpxStore::InvalidPath
|
|
||||||
halt 400
|
|
||||||
rescue Errno::ENOENT
|
|
||||||
halt 404
|
|
||||||
rescue Gpx::ParseError, Fit::ParseError
|
|
||||||
halt 422, json(error: "could not parse file")
|
|
||||||
end
|
|
||||||
|
|
||||||
content_type :json
|
|
||||||
if params[:download]
|
|
||||||
# Matches the tree's own display name for a cached .gpx/.fit
|
|
||||||
# (public/js/gpx.js's _renderFile) — "ride.gpx" downloads as
|
|
||||||
# "ride.gpx.geojson", not "ride.geojson", so the two never disagree.
|
|
||||||
# A .geojson source is already named right and is left alone.
|
|
||||||
original_name = File.basename(params[:splat].first)
|
|
||||||
download_name = original_name.downcase.end_with?(".geojson") ? original_name : "#{original_name}.geojson"
|
|
||||||
attachment download_name
|
|
||||||
end
|
|
||||||
body
|
|
||||||
end
|
|
||||||
|
|
||||||
post "/api/gpx/folder" do
|
|
||||||
require_login!
|
|
||||||
begin
|
|
||||||
GPX_STORE.create_folder(params[:path].to_s)
|
|
||||||
rescue GpxStore::InvalidPath
|
|
||||||
halt 400, json(error: "invalid path")
|
|
||||||
end
|
|
||||||
|
|
||||||
json tree: GPX_STORE.tree
|
|
||||||
end
|
|
||||||
|
|
||||||
delete "/api/gpx/file/*" do
|
|
||||||
require_login!
|
|
||||||
begin
|
|
||||||
GPX_STORE.delete_file(params[:splat].first)
|
|
||||||
rescue GpxStore::InvalidPath
|
|
||||||
halt 400
|
|
||||||
rescue Errno::ENOENT
|
|
||||||
halt 404
|
|
||||||
end
|
|
||||||
|
|
||||||
json tree: GPX_STORE.tree
|
|
||||||
end
|
|
||||||
|
|
||||||
delete "/api/gpx/folder/*" do
|
|
||||||
require_login!
|
|
||||||
begin
|
|
||||||
GPX_STORE.delete_folder(params[:splat].first)
|
|
||||||
rescue GpxStore::InvalidPath
|
|
||||||
halt 400
|
|
||||||
rescue Errno::ENOENT
|
|
||||||
halt 404
|
|
||||||
end
|
|
||||||
|
|
||||||
json tree: GPX_STORE.tree
|
|
||||||
end
|
|
||||||
|
|
||||||
post "/api/gpx/move" do
|
|
||||||
require_login!
|
|
||||||
begin
|
|
||||||
path = GPX_STORE.move(from: params[:from].to_s, to_folder: params[:to_folder].to_s)
|
|
||||||
rescue GpxStore::InvalidPath
|
|
||||||
halt 400, json(error: "invalid path")
|
|
||||||
rescue Errno::ENOENT
|
|
||||||
halt 404
|
|
||||||
end
|
|
||||||
|
|
||||||
json path: path, tree: GPX_STORE.tree
|
|
||||||
end
|
end
|
||||||
|
|
||||||
# Called by the Apps Script watching Gmail for Garmin LiveTrack emails —
|
# Called by the Apps Script watching Gmail for Garmin LiveTrack emails —
|
||||||
|
|||||||
+36
-45
@@ -31,7 +31,7 @@ opened in a browser.
|
|||||||
|
|
||||||
| `data/`
|
| `data/`
|
||||||
| Local, gitignored data files, e.g. `offline.pmtiles` and uploaded
|
| Local, gitignored data files, e.g. `offline.pmtiles` and uploaded
|
||||||
GPX/FIT files under `data/gpx/`.
|
tracks and points (`library.sqlite`, `library/`, older `gpx/`).
|
||||||
|
|
||||||
| `lib/maptool/`
|
| `lib/maptool/`
|
||||||
| Application code beyond routing: the GPX/FIT parsers and file store.
|
| Application code beyond routing: the GPX/FIT parsers and file store.
|
||||||
@@ -341,35 +341,39 @@ upload GPX, FIT or GeoJSON files by dragging them in, organize them
|
|||||||
into folders (also by dragging), and toggle each one on the map
|
into folders (also by dragging), and toggle each one on the map
|
||||||
individually.
|
individually.
|
||||||
|
|
||||||
Storage:: Files are stored as-is under `data/gpx/`, in a
|
Storage:: An item-based library in `data/library.sqlite`
|
||||||
folder hierarchy the user manages directly — `Maptool::GpxStore`
|
(`Maptool::Library`, `lib/maptool/library.rb`; full design and the
|
||||||
(`lib/maptool/gpx_store.rb`) provides `save`, `create_folder`,
|
later phases in `docs/library-design.adoc`): folders, and in them
|
||||||
`delete_file`, `delete_folder` and `move`. Every path coming from the
|
points, tracks, routes and shapes, each with a stable id, timestamps,
|
||||||
client (a folder to create/upload/move into, a file path in a URL) is
|
a tombstone on delete and a global change counter (`rev`) for sync.
|
||||||
resolved with `File.expand_path` and checked against the store root
|
An upload is kept as-is under `data/library/sources/<uuid>/` and split
|
||||||
before touching the filesystem, so `../..`-style path traversal can't
|
into items; a feature already in the target folder (same fingerprint)
|
||||||
escape `data/gpx/`; `delete_folder` additionally refuses an empty path
|
isn't added twice. Points from a GPX holding exactly one track carry
|
||||||
or one that resolves to the store root itself, so it can never `rm
|
that track as `parent_id`. Files from before the library (`data/gpx/`,
|
||||||
-rf` the whole store.
|
still `GpxStore`) were migrated on first start, each into a subfolder
|
||||||
`GET /api/gpx/tree` returns the resulting folder/file tree as JSON,
|
named after it as one `layer` item still drawn from that file —
|
||||||
which the panel renders recursively (folders as `<details>`, files as
|
`data/gpx/` itself is never written to any more except to edit notes
|
||||||
a checkbox, both with a delete button).
|
inside such a layer. Folder paths from the client are split on `/`
|
||||||
|
and `.`/`..` rejected; nothing from the client is a filesystem path.
|
||||||
|
`GET /api/library/tree` returns folders and *nodes* — one checkbox
|
||||||
|
each: a track/route/layer (`item:<id>`, drawn with its child points)
|
||||||
|
or a folder's loose points and shapes (`points:<folder id>`).
|
||||||
|
|
||||||
Drag & drop:: The dropzone at the top of the panel accepts one or more
|
Drag & drop:: The dropzone at the top of the panel accepts one or more
|
||||||
`.gpx`/`.fit`/`.geojson` files, or a `.zip` (`POST /api/gpx`,
|
`.gpx`/`.fit`/`.geojson` files, or a `.zip` (`POST /api/library/import`,
|
||||||
multipart) into the top level, or click it to browse instead. A
|
multipart) into the top level, or click it to browse instead. A
|
||||||
`.geojson` file needs no format conversion — it's already the shape
|
`.geojson` file needs no format conversion — it's already the shape
|
||||||
`gpx.js` expects — so `GpxStore#geojson` just serves it straight from
|
`gpx.js` expects — so `GpxStore#geojson` just serves it straight from
|
||||||
disk (see "Rendering" below); useful for a file already in this app's
|
disk (see "Rendering" below); useful for a file already in this app's
|
||||||
own schema, e.g. one exported elsewhere in that shape, or a previous
|
own schema, e.g. one exported elsewhere in that shape, or a previous
|
||||||
`GET /api/gpx/file` response saved and re-uploaded. A `.zip` —
|
`GET /api/library/node` response saved and re-uploaded. A `.zip` —
|
||||||
Garmin's bulk/FIT export format — isn't stored itself:
|
Garmin's bulk/FIT export format — isn't stored itself:
|
||||||
`save_zip_entries` (`app.rb`) expands it with `rubyzip` and saves each
|
`save_zip_entries` (`app.rb`) expands it with `rubyzip` and saves each
|
||||||
`.gpx`/`.fit`/`.geojson` entry it contains individually (flattened —
|
`.gpx`/`.fit`/`.geojson` entry it contains individually (flattened —
|
||||||
any folder structure inside the zip is discarded), skipping anything
|
any folder structure inside the zip is discarded), skipping anything
|
||||||
else (readme files, etc.) it might hold. An already-uploaded file (a
|
else (readme files, etc.) it might hold. An already-uploaded file (a
|
||||||
`.gpx-tree__file` row, `draggable`) can be dragged onto a folder to
|
`.gpx-tree__file` row, `draggable`) can be dragged onto a folder to
|
||||||
move it there (`POST /api/gpx/move`), or dropped anywhere else in the
|
move it there (`POST /api/library/move`), or dropped anywhere else in the
|
||||||
tree to move it back to the top level; an OS file can also be dropped
|
tree to move it back to the top level; an OS file can also be dropped
|
||||||
directly onto a folder to upload straight into it. Both drag sources
|
directly onto a folder to upload straight into it. Both drag sources
|
||||||
land on the same drop targets and are told apart by a custom
|
land on the same drop targets and are told apart by a custom
|
||||||
@@ -379,29 +383,15 @@ map) gets moved, its map layers are re-added under the new path so it
|
|||||||
stays visible; if it (or its containing folder) gets deleted, its
|
stays visible; if it (or its containing folder) gets deleted, its
|
||||||
layers are removed instead.
|
layers are removed instead.
|
||||||
|
|
||||||
Rendering:: Checking a file fetches `GET /api/gpx/file/<path>`, routed
|
Rendering:: Checking a node fetches `GET /api/library/node/<key>`:
|
||||||
by extension to `Maptool::Gpx` or `Maptool::Fit`
|
its items as one GeoJSON `FeatureCollection` (each feature's
|
||||||
(`lib/maptool/gpx.rb`/`fit.rb`) for parsing, and both convert to the
|
`properties.id` is its item id), or for a migrated layer its old file
|
||||||
same GeoJSON `FeatureCollection` shape so the frontend doesn't need to
|
converted by `Maptool::Gpx`/`Maptool::Fit` through `GpxStore#geojson`,
|
||||||
know which format it got. `GpxStore#geojson` caches that conversion
|
which caches that conversion next to the file (`<path>.geojson`,
|
||||||
alongside the source file (`<path>.geojson`, invalidated by mtime) —
|
invalidated by mtime) — REXML parsing a several-thousand-waypoint POI
|
||||||
REXML parsing a several-thousand-waypoint POI export (a park4night
|
export can take tens of seconds. An import pays that parse once, at
|
||||||
area export, say) can take tens of seconds, and without a cache that
|
upload time, under the frontend's "Uploading…" status. A file that
|
||||||
cost repeats on every single toggle. `GpxStore#save` also calls
|
fails to parse is rejected at import (422).
|
||||||
`geojson` itself right after writing the file, so that cost is paid
|
|
||||||
once during the upload (covered by the frontend's own "Uploading…"
|
|
||||||
status) instead of on whichever toggle happens to be first — a silent
|
|
||||||
multi-second hang on a checkbox click reads as broken in a way the
|
|
||||||
same wait during an upload doesn't. A file that fails to parse still
|
|
||||||
saves fine either way; the error just surfaces on first view instead.
|
|
||||||
A `.geojson` upload skips this path entirely — `geojson` reads and
|
|
||||||
returns it directly, no cache file, no `Gpx`/`Fit` involved.
|
|
||||||
`GpxStore#save` converting eagerly means `cached` is `true` for
|
|
||||||
almost everything in the tree — the one exception is a `.gpx`/`.fit`
|
|
||||||
dropped straight into `data/gpx/` on the filesystem, bypassing the
|
|
||||||
app, and not yet opened. Badging the common case would just be noise,
|
|
||||||
so the file tree's icon (`PENDING_ICON`, `public/js/icons.js`) marks
|
|
||||||
that exception instead of the (near-universal) ready state.
|
|
||||||
+
|
+
|
||||||
The tree always shows a `.gpx`/`.fit` file under its real, as-uploaded
|
The tree always shows a `.gpx`/`.fit` file under its real, as-uploaded
|
||||||
name, even once cached — it briefly grew a `.geojson` suffix there
|
name, even once cached — it briefly grew a `.geojson` suffix there
|
||||||
@@ -421,11 +411,11 @@ document-level click listener the same way an outside click closes a
|
|||||||
threaded through `onlyOneSidePanelOpen`. A directly-uploaded `.geojson`
|
threaded through `onlyOneSidePanelOpen`. A directly-uploaded `.geojson`
|
||||||
keeps its own name and both menu items download the same (identical)
|
keeps its own name and both menu items download the same (identical)
|
||||||
content — redundant there, not wrong. Both downloads (`GET
|
content — redundant there, not wrong. Both downloads (`GET
|
||||||
/api/gpx/file/<path>?download=original`/`?download=geojson`) require
|
/api/library/node/<key>?download=original`/`?download=geojson`) require
|
||||||
login, same as upload/move/delete/create-folder, so the whole button —
|
login, same as upload/move/delete/create-folder, so the whole button —
|
||||||
not just its menu items — is left out of the DOM when logged out
|
not just its menu items — is left out of the DOM when logged out
|
||||||
rather than shown and failing on click (see "Authentication" below);
|
rather than shown and failing on click (see "Authentication" below);
|
||||||
`GET /api/gpx/file` itself stays open to anyone otherwise (viewing a
|
`GET /api/library/node` itself stays open to anyone otherwise (viewing a
|
||||||
file on the map isn't a write action), just not `?download=...` on it.
|
file on the map isn't a write action), just not `?download=...` on it.
|
||||||
Each menu item is a real `<a href>` (so right-click/middle-click still
|
Each menu item is a real `<a href>` (so right-click/middle-click still
|
||||||
do something sensible), but a plain navigation would land a logged-out
|
do something sensible), but a plain navigation would land a logged-out
|
||||||
@@ -754,10 +744,11 @@ exposed via Docker/nginx as `map.priesol.net`.
|
|||||||
|
|
||||||
The GPX store's read endpoints (viewing the map, the folder tree,
|
The GPX store's read endpoints (viewing the map, the folder tree,
|
||||||
individual files) are public — anyone with the URL can look. Its write
|
individual files) are public — anyone with the URL can look. Its write
|
||||||
endpoints (`POST /api/gpx`, `POST /api/gpx/folder`, `DELETE
|
endpoints (`POST /api/library/import`, `POST /api/library/folder`,
|
||||||
/api/gpx/file/*`, `DELETE /api/gpx/folder/*`, `POST /api/gpx/move`)
|
`DELETE /api/library/node/:key`, `DELETE /api/library/folder/*`,
|
||||||
|
`POST /api/library/move`, `/api/library/notes`)
|
||||||
require login, guarded by `require_login!` in `app.rb` — and so does
|
require login, guarded by `require_login!` in `app.rb` — and so does
|
||||||
exporting a file (`GET /api/gpx/file/*?download=...`), even though
|
exporting a node (`GET /api/library/node/:key?download=...`), even though
|
||||||
plain viewing of that same URL (no `?download`) doesn't; not a write
|
plain viewing of that same URL (no `?download`) doesn't; not a write
|
||||||
exactly, but treated the same as the others rather than left open.
|
exactly, but treated the same as the others rather than left open.
|
||||||
The tree UI (`public/js/gpx.js`) mirrors this: every control for a
|
The tree UI (`public/js/gpx.js`) mirrors this: every control for a
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
:toc:
|
:toc:
|
||||||
:toclevels: 2
|
:toclevels: 2
|
||||||
|
|
||||||
Status: *proposal, not implemented.* Replaces the file-based store behind
|
Status: *phase 1 implemented* (`lib/maptool/library.rb`, see Decisions); phases 2–4 proposed. Replaces the file-based store behind
|
||||||
Tracks & Points (`GpxStore`) with an item-based library that OsmAnd, Locus
|
Tracks & Points (`GpxStore`) with an item-based library that OsmAnd, Locus
|
||||||
Map and the MapTool web app can all be synced against.
|
Map and the MapTool web app can all be synced against.
|
||||||
|
|
||||||
@@ -306,13 +306,26 @@ removed once nothing uses them.
|
|||||||
. Android sync client (one direction), then the other direction if the
|
. Android sync client (one direction), then the other direction if the
|
||||||
app APIs allow it.
|
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).
|
||||||
|
|
||||||
== Open questions
|
== 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?
|
* Folder depth over 3 — fine to require Locus Premium?
|
||||||
* Does OsmAnd's AIDL API list existing favorites/tracks? Does locus-api
|
* Does OsmAnd's AIDL API list existing favorites/tracks? Does locus-api
|
||||||
read points/tracks by folder? Decides whether direction 2 can be
|
read points/tracks by folder? Decides whether direction 2 can be
|
||||||
|
|||||||
@@ -0,0 +1,420 @@
|
|||||||
|
require "digest"
|
||||||
|
require "fileutils"
|
||||||
|
require "json"
|
||||||
|
require "securerandom"
|
||||||
|
require "sqlite3"
|
||||||
|
require "time"
|
||||||
|
require_relative "gpx"
|
||||||
|
require_relative "fit"
|
||||||
|
require_relative "gpx_store"
|
||||||
|
|
||||||
|
module Maptool
|
||||||
|
# Tracks & Points as items in a folder tree (docs/library-design.adoc,
|
||||||
|
# phase 1): data/library.sqlite holds folders and items, each with a
|
||||||
|
# stable id, timestamps, a tombstone on delete and the global change
|
||||||
|
# counter (`rev`) a sync client will poll.
|
||||||
|
#
|
||||||
|
# Item types: point, track, route, shape (polygon / measured line note)
|
||||||
|
# and layer — a pre-library file from GpxStore (data/gpx/), migrated as a
|
||||||
|
# whole into a subfolder named after it and still drawn from that file.
|
||||||
|
# Points carry parent_id when they came in the same GPX as a single
|
||||||
|
# track (OsmAnd keeps those inside the track, Locus loose in the folder;
|
||||||
|
# this keeps both possible on export).
|
||||||
|
#
|
||||||
|
# The tree UI deals in "nodes", one checkbox each: every track/route/
|
||||||
|
# layer is one ("item:<id>", drawn with its child points), and a
|
||||||
|
# folder's loose points and shapes together are another
|
||||||
|
# ("points:<folder id>").
|
||||||
|
class Library
|
||||||
|
class NotFound < StandardError; end
|
||||||
|
class InvalidPath < StandardError; end
|
||||||
|
class ParseError < StandardError; end
|
||||||
|
|
||||||
|
ROOT = "root" # folder id in a node key for items with no folder
|
||||||
|
EXTENSIONS = %w[.gpx .fit .geojson].freeze
|
||||||
|
|
||||||
|
def initialize(db_path, gpx_store:, sources_dir:)
|
||||||
|
@path = db_path
|
||||||
|
@gpx_store = gpx_store
|
||||||
|
@sources_dir = sources_dir
|
||||||
|
fresh = !File.exist?(db_path)
|
||||||
|
FileUtils.mkdir_p(File.dirname(db_path))
|
||||||
|
connect do |db|
|
||||||
|
db.execute("PRAGMA journal_mode = WAL")
|
||||||
|
db.execute_batch(<<~SQL)
|
||||||
|
CREATE TABLE IF NOT EXISTS meta (rev INTEGER NOT NULL);
|
||||||
|
INSERT INTO meta SELECT 0 WHERE NOT EXISTS (SELECT 1 FROM meta);
|
||||||
|
CREATE TABLE IF NOT EXISTS folders (
|
||||||
|
id TEXT PRIMARY KEY, parent_id TEXT, name TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT, rev INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS items (
|
||||||
|
id TEXT PRIMARY KEY, folder_id TEXT, parent_id TEXT, type TEXT NOT NULL, name TEXT,
|
||||||
|
geometry TEXT, properties TEXT NOT NULL DEFAULT '{}', fingerprint TEXT, source_path TEXT,
|
||||||
|
created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT, rev INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
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 folders_rev ON folders(rev);
|
||||||
|
SQL
|
||||||
|
end
|
||||||
|
migrate if fresh
|
||||||
|
end
|
||||||
|
|
||||||
|
def rev
|
||||||
|
connect { |db| db.get_first_value("SELECT rev FROM meta") }
|
||||||
|
end
|
||||||
|
|
||||||
|
# GpxStore's tree → folders, each file → a subfolder named after it
|
||||||
|
# holding one layer item. Idempotent (a file already migrated, even if
|
||||||
|
# deleted since, is skipped); data/gpx/ itself is never touched.
|
||||||
|
def migrate
|
||||||
|
walk = lambda do |node, folder|
|
||||||
|
node["children"].each do |child|
|
||||||
|
if child["type"] == "folder"
|
||||||
|
walk.call(child, child["path"])
|
||||||
|
else
|
||||||
|
add_layer(child, [folder, File.basename(child["name"], ".*")].reject(&:empty?).join("/"))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
create_folder(folder) unless folder.empty?
|
||||||
|
end
|
||||||
|
walk.call(@gpx_store.tree, "")
|
||||||
|
end
|
||||||
|
|
||||||
|
# --- tree ---------------------------------------------------------------
|
||||||
|
|
||||||
|
def tree
|
||||||
|
folders, items = connect do |db|
|
||||||
|
[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
|
||||||
|
FROM items WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE
|
||||||
|
SQL
|
||||||
|
end
|
||||||
|
children_of = folders.group_by { |f| f[1] }
|
||||||
|
items_in = items.group_by { |i| i[1] }
|
||||||
|
has_children = items.filter_map { |i| i[2] }.to_set
|
||||||
|
build = lambda do |id, path|
|
||||||
|
subfolders = (children_of[id] || []).map do |fid, _, name|
|
||||||
|
sub = path.empty? ? name : "#{path}/#{name}"
|
||||||
|
{ "type" => "folder", "id" => fid, "name" => name, "path" => sub, "children" => build.call(fid, sub) }
|
||||||
|
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))]
|
||||||
|
{ "type" => "file", "path" => "item:#{iid}", "name" => name.to_s.empty? ? type.capitalize : name,
|
||||||
|
"kinds" => kinds, "original" => !source.nil? }
|
||||||
|
end
|
||||||
|
loose = own.count { |i| %w[point shape].include?(i[3]) && i[2].nil? }
|
||||||
|
if loose.positive?
|
||||||
|
nodes << { "type" => "file", "path" => "points:#{id || ROOT}", "name" => "Points (#{loose})",
|
||||||
|
"kinds" => ["waypoint"], "original" => false }
|
||||||
|
end
|
||||||
|
subfolders + nodes
|
||||||
|
end
|
||||||
|
{ "type" => "folder", "name" => "root", "path" => "", "children" => build.call(nil, "") }
|
||||||
|
end
|
||||||
|
|
||||||
|
# Every node as [label, key, stamp, reader] — Search's "layers" source.
|
||||||
|
# ponytail: stamp is the global rev, so any write re-reads every node on
|
||||||
|
# the next search; per-node revs if that ever gets slow.
|
||||||
|
def nodes
|
||||||
|
current = rev
|
||||||
|
flatten = lambda do |node, folder|
|
||||||
|
node["children"].flat_map do |child|
|
||||||
|
next flatten.call(child, child["path"]) if child["type"] == "folder"
|
||||||
|
|
||||||
|
[[[folder, child["name"]].reject(&:empty?).join(" / "), child["path"], current, -> { geojson(child["path"]) }]]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
flatten.call(tree, "")
|
||||||
|
end
|
||||||
|
|
||||||
|
# A node's FeatureCollection as a JSON string, every feature's
|
||||||
|
# properties carrying its item id.
|
||||||
|
def geojson(key)
|
||||||
|
kind, id = key.to_s.split(":", 2)
|
||||||
|
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])
|
||||||
|
raise NotFound unless item
|
||||||
|
return @gpx_store.geojson(item[1]) if item[0] == "layer"
|
||||||
|
|
||||||
|
db.execute("#{FEATURE_SQL} AND (id = ? OR parent_id = ?) ORDER BY parent_id IS NOT NULL", [id, id])
|
||||||
|
when "points"
|
||||||
|
db.execute("#{FEATURE_SQL} AND folder_id IS ? AND parent_id IS NULL AND type IN ('point', 'shape')", [folder_param(id)])
|
||||||
|
else raise NotFound
|
||||||
|
end
|
||||||
|
end
|
||||||
|
JSON.generate("type" => "FeatureCollection", "features" => rows.map { |row| feature(*row) })
|
||||||
|
end
|
||||||
|
|
||||||
|
# The file a node came from, for "download original": the legacy file
|
||||||
|
# or the stored upload. nil when there is none (a folder's points).
|
||||||
|
def original(key)
|
||||||
|
kind, id = key.to_s.split(":", 2)
|
||||||
|
return nil unless kind == "item"
|
||||||
|
|
||||||
|
type, source = connect { |db| db.get_first_row("SELECT type, source_path FROM items WHERE id = ? AND deleted_at IS NULL", [id]) }
|
||||||
|
return nil unless source
|
||||||
|
|
||||||
|
type == "layer" ? @gpx_store.resolve_file(source) : File.join(@sources_dir, source)
|
||||||
|
end
|
||||||
|
|
||||||
|
# --- writes -------------------------------------------------------------
|
||||||
|
|
||||||
|
# Stores the upload under sources/<uuid>/ and adds its features as
|
||||||
|
# items in `folder` (a "a/b" path, created if needed). Returns the node
|
||||||
|
# keys they show up under. A feature already in that folder (same
|
||||||
|
# fingerprint) isn't added twice — re-sharing a track from OsmAnd is a
|
||||||
|
# no-op — but its node is still returned.
|
||||||
|
def import(folder:, filename:, io:)
|
||||||
|
name = safe_filename(filename)
|
||||||
|
relative = File.join(SecureRandom.uuid, name)
|
||||||
|
path = File.join(@sources_dir, relative)
|
||||||
|
FileUtils.mkdir_p(File.dirname(path))
|
||||||
|
File.binwrite(path, io.read)
|
||||||
|
features = begin
|
||||||
|
parse(path)
|
||||||
|
rescue Gpx::ParseError, Fit::ParseError, JSON::ParserError => e
|
||||||
|
FileUtils.rm_rf(File.dirname(path))
|
||||||
|
raise ParseError, e.message
|
||||||
|
end
|
||||||
|
add_features(features, folder, source: relative)
|
||||||
|
end
|
||||||
|
|
||||||
|
# One hand-drawn note (notes.js) into `folder`; returns its node key.
|
||||||
|
def add_note(feature, folder)
|
||||||
|
add_features([feature], folder).first
|
||||||
|
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)
|
||||||
|
if (source = layer_source(key))
|
||||||
|
return @gpx_store.update_feature(path: source, id: id, feature: feature)
|
||||||
|
end
|
||||||
|
|
||||||
|
props = (feature["properties"] || {}).except("id")
|
||||||
|
write do |db, rev, now|
|
||||||
|
db.execute("UPDATE items SET name = ?, geometry = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ? AND deleted_at IS NULL",
|
||||||
|
[props["name"], JSON.generate(feature["geometry"]), JSON.generate(props), now, rev, id])
|
||||||
|
raise NotFound if db.changes.zero?
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def delete_feature(key, id)
|
||||||
|
if (source = layer_source(key))
|
||||||
|
return @gpx_store.delete_feature(path: source, id: id)
|
||||||
|
end
|
||||||
|
|
||||||
|
write do |db, rev, now|
|
||||||
|
tombstone(db, "id = ? OR parent_id = ?", [id, id], rev, now)
|
||||||
|
raise NotFound if db.changes.zero?
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# A whole node: a track with its points, a layer, or a folder's loose points.
|
||||||
|
def delete_node(key)
|
||||||
|
kind, id = key.to_s.split(":", 2)
|
||||||
|
write do |db, rev, now|
|
||||||
|
case kind
|
||||||
|
when "item" then tombstone(db, "id = ? OR parent_id = ?", [id, id], rev, now)
|
||||||
|
when "points" then tombstone(db, "folder_id IS ? AND parent_id IS NULL AND type IN ('point', 'shape')", [folder_param(id)], rev, now)
|
||||||
|
else raise NotFound
|
||||||
|
end
|
||||||
|
raise NotFound if db.changes.zero?
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Returns the node's key afterwards (a folder's points get a new one).
|
||||||
|
def move_node(key, to_folder)
|
||||||
|
kind, id = key.to_s.split(":", 2)
|
||||||
|
target = folder_id(to_folder, create: true)
|
||||||
|
write do |db, rev, now|
|
||||||
|
case kind
|
||||||
|
when "item"
|
||||||
|
db.execute("UPDATE items SET folder_id = ?, updated_at = ?, rev = ? WHERE (id = ? OR parent_id = ?) AND deleted_at IS NULL",
|
||||||
|
[target, now, rev, id, id])
|
||||||
|
when "points"
|
||||||
|
db.execute(<<~SQL, [target, now, rev, folder_param(id)])
|
||||||
|
UPDATE items SET folder_id = ?, updated_at = ?, rev = ?
|
||||||
|
WHERE folder_id IS ? AND parent_id IS NULL AND type IN ('point', 'shape') AND deleted_at IS NULL
|
||||||
|
SQL
|
||||||
|
end
|
||||||
|
raise NotFound if db.changes.zero?
|
||||||
|
end
|
||||||
|
kind == "points" ? "points:#{target || ROOT}" : key
|
||||||
|
end
|
||||||
|
|
||||||
|
def create_folder(path)
|
||||||
|
raise InvalidPath if path.to_s.strip.empty?
|
||||||
|
|
||||||
|
folder_id(path, create: true)
|
||||||
|
end
|
||||||
|
|
||||||
|
# Tombstones the folder, everything under it and all their items.
|
||||||
|
def delete_folder(path)
|
||||||
|
id = folder_id(path, create: false)
|
||||||
|
raise NotFound unless id
|
||||||
|
|
||||||
|
write do |db, rev, now|
|
||||||
|
ids = [id]
|
||||||
|
frontier = [id]
|
||||||
|
until frontier.empty?
|
||||||
|
frontier = db.execute("SELECT id FROM folders WHERE parent_id IN (#{(['?'] * frontier.size).join(',')}) AND deleted_at IS NULL", frontier).flatten
|
||||||
|
ids.concat(frontier)
|
||||||
|
end
|
||||||
|
marks = (["?"] * ids.size).join(",")
|
||||||
|
db.execute("UPDATE folders SET deleted_at = ?, updated_at = ?, rev = ? WHERE id IN (#{marks})", [now, now, rev, *ids])
|
||||||
|
tombstone(db, "folder_id IN (#{marks})", ids, rev, now)
|
||||||
|
end
|
||||||
|
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:)
|
||||||
|
parts = path.to_s.split("/").map(&:strip).reject(&:empty?)
|
||||||
|
raise InvalidPath if parts.any? { |part| %w[. ..].include?(part) }
|
||||||
|
|
||||||
|
parts.reduce(nil) do |parent, name|
|
||||||
|
found = connect { |db| db.get_first_value("SELECT id FROM folders WHERE parent_id IS ? AND name = ? AND deleted_at IS NULL", [parent, name]) }
|
||||||
|
next found if found
|
||||||
|
return nil unless create
|
||||||
|
|
||||||
|
id = SecureRandom.uuid
|
||||||
|
write do |db, rev, now|
|
||||||
|
db.execute("INSERT INTO folders VALUES (?, ?, ?, ?, ?, NULL, ?)", [id, parent, name, now, now, rev])
|
||||||
|
end
|
||||||
|
id
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
FEATURE_SQL = "SELECT id, name, geometry, properties FROM items WHERE deleted_at IS NULL AND type != 'layer'".freeze
|
||||||
|
|
||||||
|
def feature(id, name, geometry, properties)
|
||||||
|
{ "type" => "Feature", "geometry" => JSON.parse(geometry),
|
||||||
|
"properties" => JSON.parse(properties).merge("id" => id, "name" => name) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def folder_param(id)
|
||||||
|
id == ROOT ? nil : id
|
||||||
|
end
|
||||||
|
|
||||||
|
def layer_source(key)
|
||||||
|
kind, id = key.to_s.split(":", 2)
|
||||||
|
return nil unless kind == "item"
|
||||||
|
|
||||||
|
connect { |db| db.get_first_value("SELECT source_path FROM items WHERE id = ? AND type = 'layer'", [id]) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def add_layer(node, folder)
|
||||||
|
exists = connect { |db| db.get_first_value("SELECT 1 FROM items WHERE type = 'layer' AND source_path = ?", [node["path"]]) }
|
||||||
|
return if exists
|
||||||
|
|
||||||
|
target = folder_id(folder, create: true)
|
||||||
|
begin
|
||||||
|
@gpx_store.geojson(node["path"]) # warm GpxStore's conversion cache once, not on first view
|
||||||
|
rescue Gpx::ParseError, Fit::ParseError
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
write do |db, rev, now|
|
||||||
|
db.execute("INSERT INTO items (id, folder_id, type, name, properties, source_path, created_at, updated_at, rev) VALUES (?, ?, 'layer', ?, ?, ?, ?, ?, ?)",
|
||||||
|
[SecureRandom.uuid, target, node["name"], JSON.generate("kinds" => node["kinds"]), node["path"], now, now, rev])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def parse(path)
|
||||||
|
case File.extname(path).downcase
|
||||||
|
when ".fit" then Fit.to_geojson(path)["features"]
|
||||||
|
when ".geojson" then JSON.parse(File.read(path)).fetch("features", [])
|
||||||
|
else Gpx.to_geojson(path)["features"]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def add_features(features, folder, source: nil)
|
||||||
|
target = 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
|
||||||
|
keys = []
|
||||||
|
write do |db, rev, now|
|
||||||
|
# Lines first, so a GPX's waypoints can point at its one track.
|
||||||
|
features.sort_by { |f| f.dig("geometry", "type") == "Point" ? 1 : 0 }.each do |f|
|
||||||
|
type = item_type(f)
|
||||||
|
props = (f["properties"] || {}).compact
|
||||||
|
fingerprint = Digest::SHA1.hexdigest(JSON.generate([type, props["name"], round(f["geometry"])]))
|
||||||
|
existing = db.get_first_value("SELECT id FROM items WHERE folder_id IS ? AND fingerprint = ? AND deleted_at IS NULL", [target, fingerprint])
|
||||||
|
id = existing
|
||||||
|
unless existing
|
||||||
|
id = props["id"].to_s
|
||||||
|
id = SecureRandom.uuid if id.empty? || db.get_first_value("SELECT 1 FROM items WHERE id = ?", [id])
|
||||||
|
point_parent = parent if lines == 1 && %w[point shape].include?(type)
|
||||||
|
db.execute("INSERT INTO items VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
|
||||||
|
[id, target, point_parent, type, props["name"], JSON.generate(f["geometry"]),
|
||||||
|
JSON.generate(props.except("id")), fingerprint, source, now, now, rev])
|
||||||
|
end
|
||||||
|
parent = id if %w[track route].include?(type)
|
||||||
|
keys << (%w[track route].include?(type) ? "item:#{id}" : "points:#{target || ROOT}") unless lines == 1 && %w[point shape].include?(type)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
keys.uniq
|
||||||
|
end
|
||||||
|
|
||||||
|
def item_type(feature)
|
||||||
|
geometry = feature.dig("geometry", "type").to_s
|
||||||
|
props = feature["properties"] || {}
|
||||||
|
return "point" if geometry == "Point"
|
||||||
|
return "shape" if geometry.include?("Polygon") || props["category"] == "Note"
|
||||||
|
|
||||||
|
props["kind"] == "route" ? "route" : "track"
|
||||||
|
end
|
||||||
|
|
||||||
|
def round(value)
|
||||||
|
case value
|
||||||
|
when Hash then value.transform_values { |v| round(v) }
|
||||||
|
when Array then value.map { |v| round(v) }
|
||||||
|
when Float then value.round(6)
|
||||||
|
else value
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def tombstone(db, where, params, rev, now)
|
||||||
|
db.execute("UPDATE items SET deleted_at = ?, updated_at = ?, rev = ? WHERE (#{where}) AND deleted_at IS NULL", [now, now, rev, *params])
|
||||||
|
end
|
||||||
|
|
||||||
|
def safe_filename(filename)
|
||||||
|
base = File.basename(filename.to_s)
|
||||||
|
base = "upload.gpx" if base.empty? || base == "." || base == ".."
|
||||||
|
base = "#{base}.gpx" unless EXTENSIONS.include?(File.extname(base).downcase)
|
||||||
|
base
|
||||||
|
end
|
||||||
|
|
||||||
|
# One write transaction: bumps the change counter and hands every row
|
||||||
|
# written in it the same rev.
|
||||||
|
def write
|
||||||
|
connect do |db|
|
||||||
|
db.transaction(:immediate) do
|
||||||
|
rev = db.get_first_value("UPDATE meta SET rev = rev + 1 RETURNING rev")
|
||||||
|
yield db, rev, Time.now.utc.iso8601
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# ponytail: a connection per call — simple and thread-safe under Puma;
|
||||||
|
# a per-thread connection if opening ever shows up in a profile.
|
||||||
|
def connect
|
||||||
|
db = SQLite3::Database.new(@path)
|
||||||
|
db.busy_timeout = 5000
|
||||||
|
yield db
|
||||||
|
ensure
|
||||||
|
db&.close
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
+19
-25
@@ -2,6 +2,7 @@ require "json"
|
|||||||
require_relative "gpx"
|
require_relative "gpx"
|
||||||
require_relative "fit"
|
require_relative "fit"
|
||||||
require_relative "kiwix"
|
require_relative "kiwix"
|
||||||
|
require_relative "library"
|
||||||
require_relative "places"
|
require_relative "places"
|
||||||
require_relative "pmtiles_builder"
|
require_relative "pmtiles_builder"
|
||||||
|
|
||||||
@@ -17,7 +18,7 @@ module Maptool
|
|||||||
# LIMIT nearest to the map center when there is one: every result then
|
# LIMIT nearest to the map center when there is one: every result then
|
||||||
# carries distance_km (shown) and score (sorted by; distance, except a
|
# carries distance_km (shown) and score (sorted by; distance, except a
|
||||||
# settlement counts as closer, see Places::DISTANCE_WEIGHT). ctx
|
# settlement counts as closer, see Places::DISTANCE_WEIGHT). ctx
|
||||||
# carries :text, :gpx_store, :data_dir, :center ([lat, lng] or nil) and
|
# carries :text, :library, :data_dir, :center ([lat, lng] or nil) and
|
||||||
# :kiwix_url. `ref` in a result is what the browser needs to act on it
|
# :kiwix_url. `ref` in a result is what the browser needs to act on it
|
||||||
# (switch a layer on, open an article).
|
# (switch a layer on, open an article).
|
||||||
module Search
|
module Search
|
||||||
@@ -26,13 +27,12 @@ module Maptool
|
|||||||
|
|
||||||
SOURCES = {
|
SOURCES = {
|
||||||
"layers" => lambda do |words, ctx|
|
"layers" => lambda do |words, ctx|
|
||||||
store = ctx[:gpx_store]
|
scan(words, "layers", ctx[:library].nodes)
|
||||||
scan(words, "layers", files(store.tree).map { |path| [path, path, store.resolve_file(path), -> { store.geojson(path) }] })
|
|
||||||
end,
|
end,
|
||||||
"hiking_trails" => lambda do |words, ctx|
|
"hiking_trails" => lambda do |words, ctx|
|
||||||
countries = PmtilesBuilder.hiking_trails_countries(ctx[:data_dir]).map do |code|
|
countries = PmtilesBuilder.hiking_trails_countries(ctx[:data_dir]).map do |code|
|
||||||
path = PmtilesBuilder.hiking_trails_country_path(ctx[:data_dir], code)
|
path = PmtilesBuilder.hiking_trails_country_path(ctx[:data_dir], code)
|
||||||
["Hiking trails #{code}", code, path, -> { File.read(path) }]
|
["Hiking trails #{code}", code, File.mtime(path), -> { File.read(path) }]
|
||||||
end
|
end
|
||||||
scan(words, "hiking_trails", countries)
|
scan(words, "hiking_trails", countries)
|
||||||
end,
|
end,
|
||||||
@@ -52,16 +52,17 @@ module Maptool
|
|||||||
end,
|
end,
|
||||||
}.freeze
|
}.freeze
|
||||||
|
|
||||||
# path => [mtime, entries] — a country's hiking-trails file runs to tens
|
# ref => [stamp, entries] — a country's hiking-trails file runs to tens
|
||||||
# of MB, so it's parsed once per change, not once per keystroke.
|
# of MB, so it's parsed once per change (its mtime, a library node's
|
||||||
|
# rev), not once per keystroke.
|
||||||
# ponytail: unbounded in-memory cache, fine for a handful of layer files.
|
# ponytail: unbounded in-memory cache, fine for a handful of layer files.
|
||||||
@cache = {}
|
@cache = {}
|
||||||
|
|
||||||
def self.query(text, gpx_store:, data_dir:, sources: SOURCES.keys, center: nil, kiwix_url: "")
|
def self.query(text, library:, data_dir:, sources: SOURCES.keys, center: nil, kiwix_url: "")
|
||||||
words = normalize(text).split
|
words = normalize(text).split
|
||||||
return [] if words.empty?
|
return [] if words.empty?
|
||||||
|
|
||||||
ctx = { text: text.to_s.strip, gpx_store: gpx_store, data_dir: data_dir, center: center, kiwix_url: kiwix_url.to_s }
|
ctx = { text: text.to_s.strip, library: library, data_dir: data_dir, center: center, kiwix_url: kiwix_url.to_s }
|
||||||
(sources & SOURCES.keys).flat_map do |source|
|
(sources & SOURCES.keys).flat_map do |source|
|
||||||
results = SOURCES[source].call(words, ctx)
|
results = SOURCES[source].call(words, ctx)
|
||||||
results = nearest_first(results, center) if center
|
results = nearest_first(results, center) if center
|
||||||
@@ -87,11 +88,11 @@ module Maptool
|
|||||||
2 * 6371.0 * Math.asin(Math.sqrt(a))
|
2 * 6371.0 * Math.asin(Math.sqrt(a))
|
||||||
end
|
end
|
||||||
|
|
||||||
# files: [label, ref, file on disk, reader] — every matching feature
|
# files: [label, ref, stamp, reader] — every matching feature of each,
|
||||||
# of each, found in memory (all of them, so query can pick the nearest).
|
# found in memory (all of them, so query can pick the nearest).
|
||||||
def self.scan(words, source, files)
|
def self.scan(words, source, files)
|
||||||
files.flat_map do |label, ref, disk_path, read|
|
files.flat_map do |label, ref, stamp, read|
|
||||||
entries(disk_path, read).filter_map do |entry|
|
entries(ref, stamp, label, read).filter_map do |entry|
|
||||||
entry.except(:text).merge(source: source, source_label: label, ref: ref) if words.all? { |word| entry[:text].include?(word) }
|
entry.except(:text).merge(source: source, source_label: label, ref: ref) if words.all? { |word| entry[:text].include?(word) }
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -103,17 +104,16 @@ module Maptool
|
|||||||
text.to_s.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").delete(Places::APOSTROPHES).downcase
|
text.to_s.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").delete(Places::APOSTROPHES).downcase
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.entries(path, read)
|
def self.entries(ref, stamp, label, read)
|
||||||
mtime = File.mtime(path)
|
cached = @cache[ref]
|
||||||
cached = @cache[path]
|
return cached[1] if cached && cached[0] == stamp
|
||||||
return cached[1] if cached && cached[0] == mtime
|
|
||||||
|
|
||||||
entries = begin
|
entries = begin
|
||||||
JSON.parse(read.call).fetch("features", []).filter_map { |feature| entry(feature, File.basename(path)) }
|
JSON.parse(read.call).fetch("features", []).filter_map { |feature| entry(feature, label) }
|
||||||
rescue JSON::ParserError, Gpx::ParseError, Fit::ParseError, Errno::ENOENT
|
rescue JSON::ParserError, Gpx::ParseError, Fit::ParseError, Errno::ENOENT, Library::NotFound
|
||||||
[]
|
[]
|
||||||
end
|
end
|
||||||
@cache[path] = [mtime, entries]
|
@cache[ref] = [stamp, entries]
|
||||||
entries
|
entries
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -132,11 +132,5 @@ module Maptool
|
|||||||
text: normalize("#{name} #{props["description"]}"),
|
text: normalize("#{name} #{props["description"]}"),
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.files(node)
|
|
||||||
(node["children"] || []).flat_map do |child|
|
|
||||||
child["type"] == "folder" ? files(child) : [child["path"]]
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
+32
-46
@@ -6,7 +6,6 @@ import {
|
|||||||
WAYPOINT_ICON,
|
WAYPOINT_ICON,
|
||||||
TRACK_ICON,
|
TRACK_ICON,
|
||||||
ROUTE_ICON,
|
ROUTE_ICON,
|
||||||
PENDING_ICON,
|
|
||||||
DOWNLOAD_ICON,
|
DOWNLOAD_ICON,
|
||||||
MAP_MARKER_ICON,
|
MAP_MARKER_ICON,
|
||||||
POI_ICONS,
|
POI_ICONS,
|
||||||
@@ -16,10 +15,10 @@ import { notifySidePanelOpen, onlyOneSidePanelOpen, onGpxStoreChanged, notifyGpx
|
|||||||
import { formatActivityType } from "/js/track_profile.js";
|
import { formatActivityType } from "/js/track_profile.js";
|
||||||
import { isLoggedIn } from "/js/auth.js";
|
import { isLoggedIn } from "/js/auth.js";
|
||||||
|
|
||||||
const TREE_URL = "/api/gpx/tree";
|
const TREE_URL = "/api/library/tree";
|
||||||
const UPLOAD_URL = "/api/gpx";
|
const UPLOAD_URL = "/api/library/import";
|
||||||
const FOLDER_URL = "/api/gpx/folder";
|
const FOLDER_URL = "/api/library/folder";
|
||||||
const MOVE_URL = "/api/gpx/move";
|
const MOVE_URL = "/api/library/move";
|
||||||
const TRACK_COLOR = "#e63946";
|
const TRACK_COLOR = "#e63946";
|
||||||
const POI_ICON_KEYS = Object.keys(POI_ICONS);
|
const POI_ICON_KEYS = Object.keys(POI_ICONS);
|
||||||
const POI_ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
|
const POI_ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
|
||||||
@@ -303,26 +302,19 @@ export class GpxPanelControl {
|
|||||||
checkbox.checked = this._visible.has(file.path);
|
checkbox.checked = this._visible.has(file.path);
|
||||||
checkbox.dataset.path = file.path;
|
checkbox.dataset.path = file.path;
|
||||||
checkbox.addEventListener("change", () => this._toggleFile(file.path, checkbox.checked, checkbox));
|
checkbox.addEventListener("change", () => this._toggleFile(file.path, checkbox.checked, checkbox));
|
||||||
// Just the real, as-uploaded name — it used to grow a ".geojson" suffix
|
|
||||||
// once cached (matching the real "<path>.geojson" cache file on disk),
|
|
||||||
// back when the name doubled as a GeoJSON-only download link and the
|
|
||||||
// suffix explained what clicking it would get you. Now that downloading
|
|
||||||
// is the download button's job (see below), that suffix was just
|
|
||||||
// confusing: the file is still named "ride.gpx", not "ride.gpx.geojson".
|
|
||||||
const loggedIn = isLoggedIn();
|
const loggedIn = isLoggedIn();
|
||||||
const name = document.createElement("span");
|
const name = document.createElement("span");
|
||||||
name.className = "gpx-tree__file-name";
|
name.className = "gpx-tree__file-name";
|
||||||
name.textContent = file.name;
|
name.textContent = file.name;
|
||||||
label.appendChild(checkbox);
|
label.appendChild(checkbox);
|
||||||
(file.kinds || []).forEach((kind) => label.appendChild(this._kindIcon(kind)));
|
(file.kinds || []).forEach((kind) => label.appendChild(this._kindIcon(kind)));
|
||||||
if (!file.cached) label.appendChild(this._pendingIcon());
|
|
||||||
label.appendChild(name);
|
label.appendChild(name);
|
||||||
row.appendChild(label);
|
row.appendChild(label);
|
||||||
// Delete/download require login (app.rb); shown only once logged in
|
// Delete/download require login (app.rb); shown only once logged in
|
||||||
// rather than shown-but-failing-on-click.
|
// rather than shown-but-failing-on-click.
|
||||||
if (loggedIn) {
|
if (loggedIn) {
|
||||||
row.appendChild(this._downloadButton(file));
|
row.appendChild(this._downloadButton(file));
|
||||||
row.appendChild(this._deleteButton(() => this._deleteFile(file.path)));
|
row.appendChild(this._deleteButton(() => this._deleteFile(file)));
|
||||||
}
|
}
|
||||||
|
|
||||||
return row;
|
return row;
|
||||||
@@ -344,14 +336,6 @@ export class GpxPanelControl {
|
|||||||
return icon;
|
return icon;
|
||||||
}
|
}
|
||||||
|
|
||||||
_pendingIcon() {
|
|
||||||
const icon = document.createElement("span");
|
|
||||||
icon.className = "gpx-tree__kind-icon";
|
|
||||||
icon.innerHTML = PENDING_ICON;
|
|
||||||
icon.title = "Not yet converted — dropped straight into data/gpx/, not uploaded through the app";
|
|
||||||
return icon;
|
|
||||||
}
|
|
||||||
|
|
||||||
// One button, one obvious place for both download kinds — clicking it
|
// One button, one obvious place for both download kinds — clicking it
|
||||||
// opens a small menu (Original / GeoJSON) instead of splitting them
|
// opens a small menu (Original / GeoJSON) instead of splitting them
|
||||||
// across two differently-shaped click targets (the file name used to be
|
// across two differently-shaped click targets (the file name used to be
|
||||||
@@ -373,9 +357,10 @@ export class GpxPanelControl {
|
|||||||
const menu = document.createElement("div");
|
const menu = document.createElement("div");
|
||||||
menu.className = "gpx-tree__download-menu";
|
menu.className = "gpx-tree__download-menu";
|
||||||
menu.hidden = true;
|
menu.hidden = true;
|
||||||
const geojsonName = file.cached && !file.name.toLowerCase().endsWith(".geojson") ? `${file.name}.geojson` : file.name;
|
// A folder's loose points have no single file they came from.
|
||||||
menu.appendChild(this._downloadMenuItem("Original file", `${gpxFileUrl(file.path)}?download=original`, file.name));
|
if (file.original) menu.appendChild(this._downloadMenuItem("Original file", `${gpxFileUrl(file.path)}?download=original`, file.name));
|
||||||
menu.appendChild(this._downloadMenuItem("GeoJSON", `${gpxFileUrl(file.path)}?download=geojson`, geojsonName));
|
const geojsonUrl = `${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "geojson", name: file.name })}`;
|
||||||
|
menu.appendChild(this._downloadMenuItem("GeoJSON", geojsonUrl, `${file.name}.geojson`));
|
||||||
|
|
||||||
// stopPropagation so this click doesn't immediately reach the
|
// stopPropagation so this click doesn't immediately reach the
|
||||||
// document-level listener (mount()) that closes whichever menu is
|
// document-level listener (mount()) that closes whichever menu is
|
||||||
@@ -764,7 +749,7 @@ export class GpxPanelControl {
|
|||||||
element.querySelector(".gpx-popup__delete")?.addEventListener("click", async () => {
|
element.querySelector(".gpx-popup__delete")?.addEventListener("click", async () => {
|
||||||
if (!window.confirm("Delete this note?")) return;
|
if (!window.confirm("Delete this note?")) return;
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/gpx/notes?${new URLSearchParams({ path, id })}`, { method: "DELETE" });
|
const response = await fetch(`/api/library/notes?${new URLSearchParams({ path, id })}`, { method: "DELETE" });
|
||||||
if (!response.ok) throw new Error(`delete failed: ${response.status}`);
|
if (!response.ok) throw new Error(`delete failed: ${response.status}`);
|
||||||
popup.remove();
|
popup.remove();
|
||||||
notifyGpxStoreChanged();
|
notifyGpxStoreChanged();
|
||||||
@@ -803,7 +788,7 @@ export class GpxPanelControl {
|
|||||||
const updated = { ...feature, properties };
|
const updated = { ...feature, properties };
|
||||||
try {
|
try {
|
||||||
const body = new URLSearchParams({ path, id, feature: JSON.stringify(updated) });
|
const body = new URLSearchParams({ path, id, feature: JSON.stringify(updated) });
|
||||||
const response = await fetch("/api/gpx/notes", { method: "PUT", body });
|
const response = await fetch("/api/library/notes", { method: "PUT", body });
|
||||||
if (!response.ok) throw new Error(`save failed: ${response.status}`);
|
if (!response.ok) throw new Error(`save failed: ${response.status}`);
|
||||||
popup.remove();
|
popup.remove();
|
||||||
notifyGpxStoreChanged();
|
notifyGpxStoreChanged();
|
||||||
@@ -952,10 +937,8 @@ export class GpxPanelControl {
|
|||||||
async _uploadFiles(fileList, folder) {
|
async _uploadFiles(fileList, folder) {
|
||||||
// .zip: Garmin's bulk/FIT export format — the server expands it into
|
// .zip: Garmin's bulk/FIT export format — the server expands it into
|
||||||
// its .gpx/.fit/.geojson entries, so it's accepted here even though the
|
// its .gpx/.fit/.geojson entries, so it's accepted here even though the
|
||||||
// tree never shows a .zip itself. .geojson needs no server-side
|
// tree never shows a .zip itself. .geojson: e.g. a node's GeoJSON
|
||||||
// conversion (GpxStore#geojson serves it as-is) — accepted here so a
|
// download, re-imported.
|
||||||
// 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));
|
const files = [...fileList].filter((file) => /\.(gpx|fit|geojson|zip)$/i.test(file.name));
|
||||||
if (files.length === 0) return [];
|
if (files.length === 0) return [];
|
||||||
|
|
||||||
@@ -1005,8 +988,8 @@ export class GpxPanelControl {
|
|||||||
return paths;
|
return paths;
|
||||||
}
|
}
|
||||||
|
|
||||||
async _deleteFile(path) {
|
async _deleteFile({ path, name }) {
|
||||||
if (!window.confirm(`Delete "${path}"?`)) return;
|
if (!window.confirm(`Delete "${name}"?`)) return;
|
||||||
|
|
||||||
const response = await fetch(gpxFileUrl(path), { method: "DELETE" });
|
const response = await fetch(gpxFileUrl(path), { method: "DELETE" });
|
||||||
if (redirectIfUnauthorized(response)) return;
|
if (redirectIfUnauthorized(response)) return;
|
||||||
@@ -1023,37 +1006,35 @@ export class GpxPanelControl {
|
|||||||
async _deleteFolder(path) {
|
async _deleteFolder(path) {
|
||||||
if (!window.confirm(`Delete "${path}" and everything in it?`)) return;
|
if (!window.confirm(`Delete "${path}" and everything in it?`)) return;
|
||||||
|
|
||||||
const response = await fetch(`/api/gpx/folder/${path.split("/").map(encodeURIComponent).join("/")}`, {
|
const response = await fetch(`/api/library/folder/${path.split("/").map(encodeURIComponent).join("/")}`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
});
|
});
|
||||||
if (redirectIfUnauthorized(response)) return;
|
if (redirectIfUnauthorized(response)) return;
|
||||||
if (!response.ok) return;
|
if (!response.ok) return;
|
||||||
|
|
||||||
const prefix = `${path}/`;
|
// Node keys don't carry their folder's path — whatever's no longer in
|
||||||
[...this._visible].forEach((visiblePath) => {
|
// the tree was in the deleted folder.
|
||||||
if (visiblePath === path || visiblePath.startsWith(prefix)) {
|
|
||||||
this._visible.delete(visiblePath);
|
|
||||||
this._removeLayers(visiblePath);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const { tree } = await response.json();
|
const { tree } = await response.json();
|
||||||
|
const remaining = new Set(nodeKeys(tree));
|
||||||
|
[...this._visible].forEach((key) => {
|
||||||
|
if (remaining.has(key)) return;
|
||||||
|
this._visible.delete(key);
|
||||||
|
this._removeLayers(key);
|
||||||
|
});
|
||||||
this._renderTree(tree);
|
this._renderTree(tree);
|
||||||
}
|
}
|
||||||
|
|
||||||
async _moveFile(from, toFolder) {
|
async _moveFile(from, toFolder) {
|
||||||
if (from === toFolder) return;
|
|
||||||
|
|
||||||
const response = await fetch(MOVE_URL, {
|
const response = await fetch(MOVE_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
body: `from=${encodeURIComponent(from)}&to_folder=${encodeURIComponent(toFolder)}`,
|
body: `key=${encodeURIComponent(from)}&to_folder=${encodeURIComponent(toFolder)}`,
|
||||||
});
|
});
|
||||||
if (redirectIfUnauthorized(response)) return;
|
if (redirectIfUnauthorized(response)) return;
|
||||||
if (!response.ok) return;
|
if (!response.ok) return;
|
||||||
|
|
||||||
const { path: newPath, tree } = await response.json();
|
const { path: newPath, tree } = await response.json();
|
||||||
if (this._visible.has(from)) {
|
if (this._visible.has(from) && newPath !== from) {
|
||||||
this._visible.delete(from);
|
this._visible.delete(from);
|
||||||
this._removeLayers(from);
|
this._removeLayers(from);
|
||||||
this._visible.add(newPath);
|
this._visible.add(newPath);
|
||||||
@@ -1138,8 +1119,13 @@ function pointsSourceId(path) {
|
|||||||
return `gpx-${path}-points`;
|
return `gpx-${path}-points`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// path: a node key from the tree ("item:<id>" / "points:<folder id>").
|
||||||
function gpxFileUrl(path) {
|
function gpxFileUrl(path) {
|
||||||
return `/api/gpx/file/${path.split("/").map(encodeURIComponent).join("/")}`;
|
return `/api/library/node/${encodeURIComponent(path)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function nodeKeys(node) {
|
||||||
|
return (node.children || []).flatMap((child) => (child.type === "folder" ? nodeKeys(child) : [child.path]));
|
||||||
}
|
}
|
||||||
|
|
||||||
// properties come straight from an uploaded GPX file — untrusted input —
|
// properties come straight from an uploaded GPX file — untrusted input —
|
||||||
|
|||||||
+1
-1
@@ -456,7 +456,7 @@ map.addControl(new ZoomLevelControl(), "top-left");
|
|||||||
const pitchToggle = new PitchToggleControl();
|
const pitchToggle = new PitchToggleControl();
|
||||||
map.addControl(pitchToggle, "top-left");
|
map.addControl(pitchToggle, "top-left");
|
||||||
map.addControl(new MeasureControl(), "top-left");
|
map.addControl(new MeasureControl(), "top-left");
|
||||||
// Writing a note needs a login (POST /api/gpx/notes) — no point adding a
|
// Writing a note needs a login (POST /api/library/notes) — no point adding a
|
||||||
// button that can only ever end in a 401 for a logged-out viewer, same
|
// button that can only ever end in a 401 for a logged-out viewer, same
|
||||||
// "hide the write-only affordance" story as GpxPanelControl's own
|
// "hide the write-only affordance" story as GpxPanelControl's own
|
||||||
// upload/new-folder buttons.
|
// upload/new-folder buttons.
|
||||||
|
|||||||
+20
-26
@@ -28,7 +28,7 @@ const ICON_LABELS = {
|
|||||||
shop_convenience: "Convenience store",
|
shop_convenience: "Convenience store",
|
||||||
};
|
};
|
||||||
|
|
||||||
const NEW_LAYER_VALUE = "__new__";
|
const NEW_FOLDER_VALUE = "__new__";
|
||||||
|
|
||||||
// Every hand-drawn note (from here or measure.js's "Save as note") gets one
|
// Every hand-drawn note (from here or measure.js's "Save as note") gets one
|
||||||
// of these — the only stable way to find a specific feature again for
|
// of these — the only stable way to find a specific feature again for
|
||||||
@@ -68,7 +68,7 @@ export class NoteSaveForm {
|
|||||||
</div>
|
</div>
|
||||||
<textarea class="notes-panel__body" rows="3" placeholder="Details (optional) — **bold**, *italic*, links"></textarea>
|
<textarea class="notes-panel__body" rows="3" placeholder="Details (optional) — **bold**, *italic*, links"></textarea>
|
||||||
<select class="notes-panel__target"></select>
|
<select class="notes-panel__target"></select>
|
||||||
<input type="text" class="notes-panel__new-name" placeholder="Layer name" hidden>
|
<input type="text" class="notes-panel__new-name" placeholder="Folder name" hidden>
|
||||||
<div class="notes-panel__actions">
|
<div class="notes-panel__actions">
|
||||||
<button type="button" class="notes-panel__save">Save</button>
|
<button type="button" class="notes-panel__save">Save</button>
|
||||||
<button type="button" class="notes-panel__cancel">Cancel</button>
|
<button type="button" class="notes-panel__cancel">Cancel</button>
|
||||||
@@ -92,7 +92,7 @@ export class NoteSaveForm {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
this._target.addEventListener("change", () => {
|
this._target.addEventListener("change", () => {
|
||||||
this._newName.hidden = this._target.value !== NEW_LAYER_VALUE;
|
this._newName.hidden = this._target.value !== NEW_FOLDER_VALUE;
|
||||||
if (!this._newName.hidden) this._newName.focus();
|
if (!this._newName.hidden) this._newName.focus();
|
||||||
});
|
});
|
||||||
this._saveButton.addEventListener("click", () => this._save());
|
this._saveButton.addEventListener("click", () => this._save());
|
||||||
@@ -129,20 +129,20 @@ export class NoteSaveForm {
|
|||||||
|
|
||||||
async _populateTargets() {
|
async _populateTargets() {
|
||||||
const previousValue = this._target.value;
|
const previousValue = this._target.value;
|
||||||
let files = [];
|
let folders = [];
|
||||||
try {
|
try {
|
||||||
const tree = await (await fetch("/api/gpx/tree")).json();
|
const tree = await (await fetch("/api/library/tree")).json();
|
||||||
files = geojsonFiles(tree);
|
folders = folderPaths(tree);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Tree fetch failed — target select just falls back to "new layer"
|
// Tree fetch failed — still usable with the top level or a new folder.
|
||||||
// only, still usable.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this._target.innerHTML =
|
this._target.innerHTML =
|
||||||
files.map((file) => `<option value="${escapeAttr(file.path)}">${escapeText(file.path)}</option>`).join("") +
|
`<option value="">Top level</option>` +
|
||||||
`<option value="${NEW_LAYER_VALUE}">+ New layer…</option>`;
|
folders.map((path) => `<option value="${escapeAttr(path)}">${escapeText(path)}</option>`).join("") +
|
||||||
this._target.value = files.some((file) => file.path === previousValue) ? previousValue : NEW_LAYER_VALUE;
|
`<option value="${NEW_FOLDER_VALUE}">+ New folder…</option>`;
|
||||||
this._newName.hidden = this._target.value !== NEW_LAYER_VALUE;
|
this._target.value = folders.includes(previousValue) || previousValue === NEW_FOLDER_VALUE ? previousValue : "";
|
||||||
|
this._newName.hidden = this._target.value !== NEW_FOLDER_VALUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
async _save() {
|
async _save() {
|
||||||
@@ -150,9 +150,9 @@ export class NoteSaveForm {
|
|||||||
const details = this._body.value.trim();
|
const details = this._body.value.trim();
|
||||||
if (!title || !this._geometry) return;
|
if (!title || !this._geometry) return;
|
||||||
|
|
||||||
const isNewLayer = this._target.value === NEW_LAYER_VALUE;
|
const isNewFolder = this._target.value === NEW_FOLDER_VALUE;
|
||||||
const name = isNewLayer ? this._newName.value.trim() : "";
|
const folder = isNewFolder ? this._newName.value.trim() : this._target.value;
|
||||||
if (isNewLayer && !name) {
|
if (isNewFolder && !folder) {
|
||||||
this._newName.focus();
|
this._newName.focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -170,13 +170,11 @@ export class NoteSaveForm {
|
|||||||
geometry: this._geometry,
|
geometry: this._geometry,
|
||||||
};
|
};
|
||||||
|
|
||||||
const requestBody = new URLSearchParams({ feature: JSON.stringify(feature) });
|
const requestBody = new URLSearchParams({ feature: JSON.stringify(feature), folder });
|
||||||
if (isNewLayer) requestBody.set("name", name);
|
|
||||||
else requestBody.set("path", this._target.value);
|
|
||||||
|
|
||||||
this._saveButton.disabled = true;
|
this._saveButton.disabled = true;
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/gpx/notes", { method: "POST", body: requestBody });
|
const response = await fetch("/api/library/notes", { method: "POST", body: requestBody });
|
||||||
if (!response.ok) throw new Error(`save failed: ${response.status}`);
|
if (!response.ok) throw new Error(`save failed: ${response.status}`);
|
||||||
const { path } = await response.json();
|
const { path } = await response.json();
|
||||||
notifyGpxStoreChanged(path);
|
notifyGpxStoreChanged(path);
|
||||||
@@ -191,7 +189,7 @@ export class NoteSaveForm {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A quick "pin it with a note" tool — click the map, write a short note,
|
// A quick "pin it with a note" tool — click the map, write a short note,
|
||||||
// pick which .geojson "layer" file it joins (or start a new one). Point
|
// pick which folder it goes into (or start a new one). Point
|
||||||
// only: for a distance/area shape, draw it with the Measure tool and use
|
// only: for a distance/area shape, draw it with the Measure tool and use
|
||||||
// its own "Save as note" button instead of duplicating that click-to-place
|
// its own "Save as note" button instead of duplicating that click-to-place
|
||||||
// UX here — see measure.js.
|
// UX here — see measure.js.
|
||||||
@@ -274,12 +272,8 @@ export class NotesControl {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function geojsonFiles(node, results = []) {
|
function folderPaths(node) {
|
||||||
if (node.type === "file" && node.path.toLowerCase().endsWith(".geojson")) {
|
return (node.children || []).filter((child) => child.type === "folder").flatMap((child) => [child.path, ...folderPaths(child)]);
|
||||||
results.push({ path: node.path });
|
|
||||||
}
|
|
||||||
(node.children || []).forEach((child) => geojsonFiles(child, results));
|
|
||||||
return results;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function escapeAttr(value) {
|
function escapeAttr(value) {
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ function withExtension(name, type) {
|
|||||||
|
|
||||||
async function fillFolderSuggestions(datalist) {
|
async function fillFolderSuggestions(datalist) {
|
||||||
try {
|
try {
|
||||||
const tree = await (await fetch("/api/gpx/tree")).json();
|
const tree = await (await fetch("/api/library/tree")).json();
|
||||||
const folders = [];
|
const folders = [];
|
||||||
const walk = (node) =>
|
const walk = (node) =>
|
||||||
(node.children || []).forEach((child) => {
|
(node.children || []).forEach((child) => {
|
||||||
|
|||||||
+100
-167
@@ -77,11 +77,11 @@ class AppTest < Minitest::Test
|
|||||||
# --- auth guard ---
|
# --- auth guard ---
|
||||||
|
|
||||||
def test_write_routes_require_login
|
def test_write_routes_require_login
|
||||||
assert_equal 401, request.post("/api/gpx").status
|
assert_equal 401, request.post("/api/library/import").status
|
||||||
assert_equal 401, request.post("/api/gpx/folder").status
|
assert_equal 401, request.post("/api/library/folder").status
|
||||||
assert_equal 401, request.delete("/api/gpx/file/x.gpx").status
|
assert_equal 401, request.delete("/api/library/node/item:x").status
|
||||||
assert_equal 401, request.delete("/api/gpx/folder/x").status
|
assert_equal 401, request.delete("/api/library/folder/x").status
|
||||||
assert_equal 401, request.post("/api/gpx/move").status
|
assert_equal 401, request.post("/api/library/move").status
|
||||||
assert_equal 401, request.post("/api/plugins/test-plugin/run").status
|
assert_equal 401, request.post("/api/plugins/test-plugin/run").status
|
||||||
assert_equal 401, request.post("/api/offline-tiles/build").status
|
assert_equal 401, request.post("/api/offline-tiles/build").status
|
||||||
assert_equal 401, request.post("/api/terrain-tiles/build").status
|
assert_equal 401, request.post("/api/terrain-tiles/build").status
|
||||||
@@ -90,112 +90,83 @@ class AppTest < Minitest::Test
|
|||||||
assert_equal 401, request.delete("/api/terrain-tiles").status
|
assert_equal 401, request.delete("/api/terrain-tiles").status
|
||||||
end
|
end
|
||||||
|
|
||||||
# --- GPX/FIT upload and the tree ---
|
# --- Tracks & Points library (lib/maptool/library.rb) ---
|
||||||
|
|
||||||
def test_gpx_upload_and_tree
|
def test_gpx_import_makes_one_track_node_carrying_its_waypoint
|
||||||
content = File.read(fixture_path("sample.gpx"))
|
response = upload("ride.gpx", File.read(fixture_path("sample.gpx")))
|
||||||
response = post_file("/api/gpx", filename: "ride.gpx", content: content, env: logged_in_env)
|
|
||||||
|
|
||||||
assert_equal 200, response.status
|
assert_equal 200, response.status
|
||||||
body = json_body(response)
|
body = json_body(response)
|
||||||
assert_equal ["ride.gpx"], body["paths"]
|
assert_equal 1, body["paths"].size
|
||||||
assert_equal ["ride.gpx"], body["tree"]["children"].map { |c| c["name"] }
|
assert_match(/\Aitem:/, body["paths"].first)
|
||||||
|
node = body["tree"]["children"].first
|
||||||
|
assert_equal ["Morning Loop", %w[track waypoint]], node.values_at("name", "kinds")
|
||||||
|
|
||||||
|
features = json_body(request.get(node_url(node["path"])))["features"]
|
||||||
|
assert_equal %w[track waypoint], features.map { |f| f["properties"]["kind"] }
|
||||||
|
assert_operator features.first["properties"]["distance_meters"], :>, 0
|
||||||
|
assert(features.all? { |f| f["properties"]["id"] })
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_gpx_file_returns_geojson_with_track_properties
|
def test_importing_the_same_file_again_adds_nothing
|
||||||
content = File.read(fixture_path("sample.gpx"))
|
first = json_body(upload("ride.gpx", File.read(fixture_path("sample.gpx"))))
|
||||||
post_file("/api/gpx", filename: "ride.gpx", content: content, env: logged_in_env)
|
second = json_body(upload("ride (1).gpx", File.read(fixture_path("sample.gpx"))))
|
||||||
|
|
||||||
response = request.get("/api/gpx/file/ride.gpx")
|
assert_equal first["paths"], second["paths"]
|
||||||
assert_equal 200, response.status
|
assert_equal 1, second["tree"]["children"].size
|
||||||
track = json_body(response)["features"].find { |f| f["properties"]["kind"] == "track" }
|
|
||||||
assert_operator track["properties"]["distance_meters"], :>, 0
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_geojson_upload_is_served_back_unchanged
|
def test_geojson_points_land_in_the_folders_points_node
|
||||||
content = '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"kind":"waypoint","name":"Spot"},"geometry":{"type":"Point","coordinates":[17.1,48.1]}}]}'
|
content = '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"kind":"waypoint","name":"Spot"},"geometry":{"type":"Point","coordinates":[17.1,48.1]}}]}'
|
||||||
response = post_file("/api/gpx", filename: "spots.geojson", content: content, env: logged_in_env)
|
response = upload("spots.geojson", content, folder: "trips")
|
||||||
|
|
||||||
assert_equal 200, response.status
|
assert_equal 200, response.status
|
||||||
assert_equal ["spots.geojson"], json_body(response)["paths"]
|
key = json_body(response)["paths"].first
|
||||||
|
assert_match(/\Apoints:/, key)
|
||||||
file_response = request.get("/api/gpx/file/spots.geojson")
|
trips = json_body(response)["tree"]["children"].find { |c| c["name"] == "trips" }
|
||||||
assert_equal 200, file_response.status
|
assert_equal ["Points (1)"], trips["children"].map { |c| c["name"] }
|
||||||
assert_equal "Spot", json_body(file_response)["features"][0]["properties"]["name"]
|
assert_equal "Spot", json_body(request.get(node_url(key)))["features"][0]["properties"]["name"]
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_download_of_a_converted_gpx_names_it_gpx_geojson
|
def test_downloads_need_login_and_serve_the_original_or_geojson
|
||||||
content = File.read(fixture_path("sample.gpx"))
|
content = File.read(fixture_path("sample.gpx"))
|
||||||
post_file("/api/gpx", filename: "ride.gpx", content: content, env: logged_in_env)
|
key = json_body(upload("ride.gpx", content))["paths"].first
|
||||||
|
|
||||||
response = request.get("/api/gpx/file/ride.gpx?download=geojson", **logged_in_env)
|
assert_equal 401, request.get("#{node_url(key)}?download=original").status
|
||||||
assert_equal 200, response.status
|
assert_equal 401, request.get("#{node_url(key)}?download=geojson").status
|
||||||
assert_includes response.headers["Content-Disposition"], 'filename="ride.gpx.geojson"'
|
|
||||||
|
original = request.get("#{node_url(key)}?download=original", **logged_in_env)
|
||||||
|
assert_equal content, original.body
|
||||||
|
assert_includes original.headers["Content-Disposition"], 'filename="ride.gpx"'
|
||||||
|
geojson = request.get("#{node_url(key)}?download=geojson&name=Morning+Loop", **logged_in_env)
|
||||||
|
assert_includes geojson.headers["Content-Disposition"], 'filename="Morning Loop.geojson"'
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_download_of_a_native_geojson_keeps_its_own_name
|
def test_unparseable_gpx_is_rejected_at_import
|
||||||
content = '{"type":"FeatureCollection","features":[]}'
|
assert_equal 422, upload("bad.gpx", "<gpx><trk unclosed>").status
|
||||||
post_file("/api/gpx", filename: "spots.geojson", content: content, env: logged_in_env)
|
assert_empty json_body(request.get("/api/library/tree"))["children"]
|
||||||
|
|
||||||
response = request.get("/api/gpx/file/spots.geojson?download=geojson", **logged_in_env)
|
|
||||||
assert_equal 200, response.status
|
|
||||||
assert_includes response.headers["Content-Disposition"], 'filename="spots.geojson"'
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_download_of_the_original_file_serves_it_unconverted
|
|
||||||
content = File.read(fixture_path("sample.gpx"))
|
|
||||||
post_file("/api/gpx", filename: "ride.gpx", content: content, env: logged_in_env)
|
|
||||||
|
|
||||||
response = request.get("/api/gpx/file/ride.gpx?download=original", **logged_in_env)
|
|
||||||
assert_equal 200, response.status
|
|
||||||
assert_includes response.headers["Content-Disposition"], 'filename="ride.gpx"'
|
|
||||||
assert_equal content, response.body
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_download_requires_login
|
|
||||||
content = File.read(fixture_path("sample.gpx"))
|
|
||||||
post_file("/api/gpx", filename: "ride.gpx", content: content, env: logged_in_env)
|
|
||||||
|
|
||||||
assert_equal 401, request.get("/api/gpx/file/ride.gpx?download=geojson").status
|
|
||||||
assert_equal 401, request.get("/api/gpx/file/ride.gpx?download=original").status
|
|
||||||
# Plain viewing (no ?download) stays open to anyone.
|
|
||||||
assert_equal 200, request.get("/api/gpx/file/ride.gpx").status
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_unparseable_gpx_returns_422
|
|
||||||
post_file("/api/gpx", filename: "bad.gpx", content: "<gpx><trk unclosed>", env: logged_in_env)
|
|
||||||
|
|
||||||
response = request.get("/api/gpx/file/bad.gpx")
|
|
||||||
assert_equal 422, response.status
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_fit_upload_is_parsed_the_same_as_gpx
|
def test_fit_upload_is_parsed_the_same_as_gpx
|
||||||
fit_bytes = build_fit_file([[100_000_000, 200_000_000], [100_000_100, 200_000_100]])
|
fit_bytes = build_fit_file([[100_000_000, 200_000_000], [100_000_100, 200_000_100]])
|
||||||
response = post_file("/api/gpx", filename: "activity.fit", content: fit_bytes, env: logged_in_env)
|
key = json_body(upload("activity.fit", fit_bytes))["paths"].first
|
||||||
|
|
||||||
assert_equal 200, response.status
|
geojson = json_body(request.get(node_url(key)))
|
||||||
assert_equal ["activity.fit"], json_body(response)["paths"]
|
|
||||||
|
|
||||||
geojson = json_body(request.get("/api/gpx/file/activity.fit"))
|
|
||||||
assert_equal 2, geojson["features"][0]["geometry"]["coordinates"][0].size
|
assert_equal 2, geojson["features"][0]["geometry"]["coordinates"][0].size
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_zip_upload_expands_into_its_track_entries_and_skips_the_rest
|
def test_zip_upload_expands_into_its_track_entries_and_skips_the_rest
|
||||||
zip_bytes = build_zip(
|
zip_bytes = build_zip(
|
||||||
"one.gpx" => File.read(fixture_path("sample.gpx")),
|
"one.gpx" => File.read(fixture_path("sample.gpx")),
|
||||||
"two.fit" => build_fit_file([[100_000_000, 200_000_000]]),
|
"two.fit" => build_fit_file([[100_000_000, 200_000_000], [100_000_100, 200_000_100]]),
|
||||||
"readme.txt" => "not a track file",
|
"readme.txt" => "not a track file",
|
||||||
)
|
)
|
||||||
response = post_file("/api/gpx?folder=imported", filename: "export.zip", content: zip_bytes,
|
response = upload("export.zip", zip_bytes, folder: "imported", content_type: "application/zip")
|
||||||
content_type: "application/zip", env: logged_in_env)
|
|
||||||
|
|
||||||
assert_equal 200, response.status
|
assert_equal 200, response.status
|
||||||
paths = json_body(response)["paths"]
|
assert_equal 2, json_body(response)["paths"].size
|
||||||
assert_equal ["imported/one.gpx", "imported/two.fit"].sort, paths.sort
|
imported = json_body(response)["tree"]["children"].find { |c| c["name"] == "imported" }
|
||||||
|
assert_equal 2, imported["children"].size
|
||||||
names = json_body(request.get("/api/gpx/tree"))["children"]
|
|
||||||
.find { |c| c["name"] == "imported" }["children"].map { |c| c["name"] }
|
|
||||||
refute_includes names, "readme.txt"
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_zip_whose_contents_exceed_the_size_limit_is_rejected_before_saving_anything
|
def test_zip_whose_contents_exceed_the_size_limit_is_rejected_before_saving_anything
|
||||||
@@ -203,10 +174,10 @@ class AppTest < Minitest::Test
|
|||||||
original = Maptool::App::MAX_ZIP_UNCOMPRESSED
|
original = Maptool::App::MAX_ZIP_UNCOMPRESSED
|
||||||
Maptool::App.send(:remove_const, :MAX_ZIP_UNCOMPRESSED)
|
Maptool::App.send(:remove_const, :MAX_ZIP_UNCOMPRESSED)
|
||||||
Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, 1024)
|
Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, 1024)
|
||||||
response = post_file("/api/gpx", filename: "bomb.zip", content: zip_bytes, content_type: "application/zip", env: logged_in_env)
|
response = upload("bomb.zip", zip_bytes, content_type: "application/zip")
|
||||||
|
|
||||||
assert_equal 413, response.status
|
assert_equal 413, response.status
|
||||||
assert_empty json_body(request.get("/api/gpx/tree"))["children"]
|
assert_empty json_body(request.get("/api/library/tree"))["children"]
|
||||||
ensure
|
ensure
|
||||||
Maptool::App.send(:remove_const, :MAX_ZIP_UNCOMPRESSED)
|
Maptool::App.send(:remove_const, :MAX_ZIP_UNCOMPRESSED)
|
||||||
Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, original)
|
Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, original)
|
||||||
@@ -226,29 +197,27 @@ class AppTest < Minitest::Test
|
|||||||
end
|
end
|
||||||
|
|
||||||
def test_corrupt_zip_is_rejected
|
def test_corrupt_zip_is_rejected
|
||||||
response = post_file("/api/gpx", filename: "bad.zip", content: "not a zip", content_type: "application/zip", env: logged_in_env)
|
assert_equal 400, upload("bad.zip", "not a zip", content_type: "application/zip").status
|
||||||
assert_equal 400, response.status
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_folder_create_move_and_delete
|
def test_folder_create_move_and_delete
|
||||||
content = File.read(fixture_path("sample.gpx"))
|
key = json_body(upload("ride.gpx", File.read(fixture_path("sample.gpx"))))["paths"].first
|
||||||
post_file("/api/gpx", filename: "ride.gpx", content: content, env: logged_in_env)
|
|
||||||
|
|
||||||
create = request.post("/api/gpx/folder?path=trips", **logged_in_env)
|
assert_equal 200, request.post("/api/library/folder?path=trips", **logged_in_env).status
|
||||||
assert_equal 200, create.status
|
|
||||||
|
|
||||||
move = request.post("/api/gpx/move?from=ride.gpx&to_folder=trips", **logged_in_env)
|
move = request.post("/api/library/move", params: { key: key, to_folder: "trips" }, **logged_in_env)
|
||||||
assert_equal 200, move.status
|
assert_equal key, json_body(move)["path"]
|
||||||
assert_equal "trips/ride.gpx", json_body(move)["path"]
|
trips = json_body(move)["tree"]["children"].find { |c| c["name"] == "trips" }
|
||||||
|
assert_equal ["Morning Loop"], trips["children"].map { |c| c["name"] }
|
||||||
|
|
||||||
delete = request.delete("/api/gpx/file/trips/ride.gpx", **logged_in_env)
|
delete = request.delete("/api/library/folder/trips", **logged_in_env)
|
||||||
assert_equal 200, delete.status
|
assert_equal 200, delete.status
|
||||||
assert_empty json_body(delete)["tree"]["children"].find { |c| c["name"] == "trips" }["children"]
|
assert_empty json_body(delete)["tree"]["children"]
|
||||||
|
assert_equal 404, request.get(node_url(key)).status
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_invalid_folder_path_is_rejected
|
def test_invalid_folder_path_is_rejected
|
||||||
response = request.post("/api/gpx/folder?path=..%2F..%2Fescape", **logged_in_env)
|
assert_equal 400, request.post("/api/library/folder?path=..%2F..%2Fescape", **logged_in_env).status
|
||||||
assert_equal 400, response.status
|
|
||||||
end
|
end
|
||||||
|
|
||||||
# --- Notes (hand-drawn points/areas, notes.js) ---
|
# --- Notes (hand-drawn points/areas, notes.js) ---
|
||||||
@@ -259,101 +228,56 @@ class AppTest < Minitest::Test
|
|||||||
"properties" => { "name" => "Turning area", "category" => "Note" },
|
"properties" => { "name" => "Turning area", "category" => "Note" },
|
||||||
"geometry" => { "type" => "Polygon", "coordinates" => [[[17.1, 48.1], [17.2, 48.1], [17.2, 48.2], [17.1, 48.1]]] },
|
"geometry" => { "type" => "Polygon", "coordinates" => [[[17.1, 48.1], [17.2, 48.1], [17.2, 48.2], [17.1, 48.1]]] },
|
||||||
)
|
)
|
||||||
response = request.post("/api/gpx/notes", params: { feature: polygon, name: "Areas" }, **logged_in_env)
|
response = request.post("/api/library/notes", params: { feature: polygon, folder: "Areas" }, **logged_in_env)
|
||||||
|
|
||||||
assert_equal 200, response.status
|
assert_equal 200, response.status
|
||||||
geometry = json_body(request.get("/api/gpx/file/Areas.geojson"))["features"][0]["geometry"]
|
geometry = json_body(request.get(node_url(json_body(response)["path"])))["features"][0]["geometry"]
|
||||||
assert_equal "Polygon", geometry["type"]
|
assert_equal "Polygon", geometry["type"]
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_notes_requires_login
|
def test_notes_requires_login
|
||||||
assert_equal 401, request.post("/api/gpx/notes", params: { feature: sample_note_feature, name: "Notes" }).status
|
assert_equal 401, request.post("/api/library/notes", params: { feature: sample_note_feature, folder: "Notes" }).status
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_notes_creates_a_new_layer_file
|
def test_notes_go_into_one_points_node_per_folder
|
||||||
response = request.post("/api/gpx/notes", params: { feature: sample_note_feature, name: "My Notes" }, **logged_in_env)
|
first = json_body(request.post("/api/library/notes", params: { feature: sample_note_feature("Turning spot"), folder: "My Notes" }, **logged_in_env))
|
||||||
|
second = json_body(request.post("/api/library/notes", params: { feature: sample_note_feature("Narrow gate"), folder: "My Notes" }, **logged_in_env))
|
||||||
|
|
||||||
assert_equal 200, response.status
|
assert_equal first["path"], second["path"]
|
||||||
body = json_body(response)
|
features = json_body(request.get(node_url(first["path"])))["features"]
|
||||||
assert_equal "My Notes.geojson", body["path"]
|
assert_equal ["Narrow gate", "Turning spot"], features.map { |f| f["properties"]["name"] }.sort
|
||||||
assert_equal ["My Notes.geojson"], body["tree"]["children"].map { |c| c["name"] }
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_notes_appends_to_an_existing_layer_file_instead_of_disambiguating
|
def test_notes_rejects_malformed_or_geometryless_features
|
||||||
first = json_body(request.post("/api/gpx/notes", params: { feature: sample_note_feature("Turning spot"), name: "My Notes" }, **logged_in_env))
|
assert_equal 400, request.post("/api/library/notes", params: { feature: "not json" }, **logged_in_env).status
|
||||||
|
assert_equal 400, request.post("/api/library/notes", params: { feature: '{"type":"Feature","properties":{}}' }, **logged_in_env).status
|
||||||
second = request.post("/api/gpx/notes", params: { feature: sample_note_feature("Narrow gate"), path: first["path"] }, **logged_in_env)
|
|
||||||
assert_equal 200, second.status
|
|
||||||
assert_equal first["path"], json_body(second)["path"]
|
|
||||||
|
|
||||||
features = json_body(request.get("/api/gpx/file/#{Rack::Utils.escape_path(first["path"])}"))["features"]
|
|
||||||
assert_equal ["Turning spot", "Narrow gate"], features.map { |f| f["properties"]["name"] }
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_notes_rejects_malformed_feature_json
|
def test_notes_update_and_delete_need_login
|
||||||
response = request.post("/api/gpx/notes", params: { feature: "not json", name: "Notes" }, **logged_in_env)
|
assert_equal 401, request.put("/api/library/notes", params: { feature: sample_note_feature, path: "points:root", id: "a" }).status
|
||||||
assert_equal 400, response.status
|
assert_equal 401, request.delete("/api/library/notes", params: { path: "points:root", id: "a" }).status
|
||||||
end
|
|
||||||
|
|
||||||
def test_notes_rejects_a_feature_with_no_geometry
|
|
||||||
response = request.post("/api/gpx/notes", params: { feature: '{"type":"Feature","properties":{}}', name: "Notes" }, **logged_in_env)
|
|
||||||
assert_equal 400, response.status
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_notes_to_a_missing_path_is_404
|
|
||||||
response = request.post("/api/gpx/notes", params: { feature: sample_note_feature, path: "nope.geojson" }, **logged_in_env)
|
|
||||||
assert_equal 404, response.status
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_notes_update_requires_login
|
|
||||||
assert_equal 401, request.put("/api/gpx/notes", params: { feature: sample_note_feature, path: "x.geojson", id: "a" }).status
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_notes_update_edits_the_matching_note
|
def test_notes_update_edits_the_matching_note
|
||||||
created = json_body(request.post("/api/gpx/notes", params: { feature: sample_note_feature("Original", id: "a"), name: "My Notes" }, **logged_in_env))
|
created = json_body(request.post("/api/library/notes", params: { feature: sample_note_feature("Original", id: "a") }, **logged_in_env))
|
||||||
|
|
||||||
response = request.put(
|
response = request.put("/api/library/notes", params: { feature: sample_note_feature("Edited", id: "a"), path: created["path"], id: "a" }, **logged_in_env)
|
||||||
"/api/gpx/notes",
|
|
||||||
params: { feature: sample_note_feature("Edited", id: "a"), path: created["path"], id: "a" },
|
|
||||||
**logged_in_env,
|
|
||||||
)
|
|
||||||
assert_equal 200, response.status
|
assert_equal 200, response.status
|
||||||
|
features = json_body(request.get(node_url(created["path"])))["features"]
|
||||||
|
assert_equal [%w[Edited a]], features.map { |f| f["properties"].values_at("name", "id") }
|
||||||
|
|
||||||
features = json_body(request.get("/api/gpx/file/#{Rack::Utils.escape_path(created["path"])}"))["features"]
|
missing = request.put("/api/library/notes", params: { feature: sample_note_feature, path: created["path"], id: "nope" }, **logged_in_env)
|
||||||
assert_equal ["Edited"], features.map { |f| f["properties"]["name"] }
|
assert_equal 404, missing.status
|
||||||
end
|
|
||||||
|
|
||||||
def test_notes_update_missing_note_is_404
|
|
||||||
created = json_body(request.post("/api/gpx/notes", params: { feature: sample_note_feature("Original", id: "a"), name: "My Notes" }, **logged_in_env))
|
|
||||||
|
|
||||||
response = request.put(
|
|
||||||
"/api/gpx/notes",
|
|
||||||
params: { feature: sample_note_feature("Edited", id: "nope"), path: created["path"], id: "nope" },
|
|
||||||
**logged_in_env,
|
|
||||||
)
|
|
||||||
assert_equal 404, response.status
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_notes_delete_requires_login
|
|
||||||
assert_equal 401, request.delete("/api/gpx/notes", params: { path: "x.geojson", id: "a" }).status
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_notes_delete_removes_the_matching_note
|
def test_notes_delete_removes_the_matching_note
|
||||||
created = json_body(request.post("/api/gpx/notes", params: { feature: sample_note_feature("Turning spot", id: "a"), name: "My Notes" }, **logged_in_env))
|
created = json_body(request.post("/api/library/notes", params: { feature: sample_note_feature("Turning spot", id: "a") }, **logged_in_env))
|
||||||
request.post("/api/gpx/notes", params: { feature: sample_note_feature("Narrow gate", id: "b"), path: created["path"] }, **logged_in_env)
|
request.post("/api/library/notes", params: { feature: sample_note_feature("Narrow gate", id: "b") }, **logged_in_env)
|
||||||
|
|
||||||
response = request.delete("/api/gpx/notes", params: { path: created["path"], id: "a" }, **logged_in_env)
|
assert_equal 200, request.delete("/api/library/notes", params: { path: created["path"], id: "a" }, **logged_in_env).status
|
||||||
assert_equal 200, response.status
|
features = json_body(request.get(node_url(created["path"])))["features"]
|
||||||
|
|
||||||
features = json_body(request.get("/api/gpx/file/#{Rack::Utils.escape_path(created["path"])}"))["features"]
|
|
||||||
assert_equal ["Narrow gate"], features.map { |f| f["properties"]["name"] }
|
assert_equal ["Narrow gate"], features.map { |f| f["properties"]["name"] }
|
||||||
end
|
assert_equal 404, request.delete("/api/library/notes", params: { path: created["path"], id: "a" }, **logged_in_env).status
|
||||||
|
|
||||||
def test_notes_delete_missing_note_is_404
|
|
||||||
created = json_body(request.post("/api/gpx/notes", params: { feature: sample_note_feature("Turning spot", id: "a"), name: "My Notes" }, **logged_in_env))
|
|
||||||
|
|
||||||
response = request.delete("/api/gpx/notes", params: { path: created["path"], id: "nope" }, **logged_in_env)
|
|
||||||
assert_equal 404, response.status
|
|
||||||
end
|
end
|
||||||
|
|
||||||
# --- Import plugins (lib/maptool/plugins.rb) ---
|
# --- Import plugins (lib/maptool/plugins.rb) ---
|
||||||
@@ -364,7 +288,7 @@ class AppTest < Minitest::Test
|
|||||||
assert_equal [{ "name" => "test-plugin", "label" => "Test plugin" }], json_body(response)
|
assert_equal [{ "name" => "test-plugin", "label" => "Test plugin" }], json_body(response)
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_plugins_run_saves_the_output_as_a_new_geojson_file
|
def test_plugins_run_imports_the_output_into_a_folder_of_its_own
|
||||||
response = request.post(
|
response = request.post(
|
||||||
"/api/plugins/test-plugin/run",
|
"/api/plugins/test-plugin/run",
|
||||||
params: { south: "48.0", west: "17.0", north: "48.1", east: "17.1" },
|
params: { south: "48.0", west: "17.0", north: "48.1", east: "17.1" },
|
||||||
@@ -372,9 +296,9 @@ class AppTest < Minitest::Test
|
|||||||
)
|
)
|
||||||
assert_equal 200, response.status
|
assert_equal 200, response.status
|
||||||
body = json_body(response)
|
body = json_body(response)
|
||||||
assert_match(/\Atest-plugin_48\.05_17\.05_\d{6}_\d{4}\.geojson\z/, body["path"])
|
assert_match(/\Atest-plugin_48\.05_17\.05_\d{6}_\d{4}\z/, body["tree"]["children"].first["name"])
|
||||||
|
|
||||||
saved = json_body(request.get("/api/gpx/file/#{body["path"]}"))
|
saved = json_body(request.get(node_url(body["path"])))
|
||||||
assert_equal "Test POI", saved["features"][0]["properties"]["name"]
|
assert_equal "Test POI", saved["features"][0]["properties"]["name"]
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -542,6 +466,15 @@ class AppTest < Minitest::Test
|
|||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
|
def upload(filename, content, folder: "", content_type: "application/octet-stream")
|
||||||
|
post_file("/api/library/import?#{URI.encode_www_form(folder: folder)}", filename: filename, content: content,
|
||||||
|
content_type: content_type, env: logged_in_env)
|
||||||
|
end
|
||||||
|
|
||||||
|
def node_url(key)
|
||||||
|
"/api/library/node/#{Rack::Utils.escape_path(key)}"
|
||||||
|
end
|
||||||
|
|
||||||
def sample_note_feature(name = "Turning spot", id: nil)
|
def sample_note_feature(name = "Turning spot", id: nil)
|
||||||
JSON.generate(
|
JSON.generate(
|
||||||
"type" => "Feature",
|
"type" => "Feature",
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ module AppTestHelper
|
|||||||
# the next one, since minitest runs a class's tests in one process.
|
# the next one, since minitest runs a class's tests in one process.
|
||||||
def teardown
|
def teardown
|
||||||
FileUtils.rm_rf(Dir.glob(File.join(Maptool::App::DATA_DIR, "gpx", "*")))
|
FileUtils.rm_rf(Dir.glob(File.join(Maptool::App::DATA_DIR, "gpx", "*")))
|
||||||
|
Maptool::App::LIBRARY.send(:connect) { |db| db.execute_batch("DELETE FROM items; DELETE FROM folders") }
|
||||||
File.write(File.join(Maptool::App::DATA_DIR, "livetrack.json"), "[]")
|
File.write(File.join(Maptool::App::DATA_DIR, "livetrack.json"), "[]")
|
||||||
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "offline_regions.json"))
|
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "offline_regions.json"))
|
||||||
Maptool::PmtilesBuilder.reset!
|
Maptool::PmtilesBuilder.reset!
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
require_relative "test_helper"
|
||||||
|
require "maptool/library"
|
||||||
|
require "stringio"
|
||||||
|
|
||||||
|
class LibraryTest < Minitest::Test
|
||||||
|
def setup
|
||||||
|
@dir = Dir.mktmpdir
|
||||||
|
@store = Maptool::GpxStore.new(File.join(@dir, "gpx"))
|
||||||
|
end
|
||||||
|
|
||||||
|
def teardown
|
||||||
|
FileUtils.remove_entry(@dir)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_a_fresh_library_migrates_each_old_file_into_a_subfolder_of_its_own
|
||||||
|
@store.save(folder: "logs", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx")))
|
||||||
|
@store.append_feature(feature: note("Gate", "n1"), folder: "", name: "My Notes")
|
||||||
|
library = open_library
|
||||||
|
|
||||||
|
tree = library.tree
|
||||||
|
assert_equal ["logs", "My Notes"], tree["children"].map { |c| c["name"] }
|
||||||
|
ride = tree["children"][0]["children"].first
|
||||||
|
assert_equal ["ride", "folder"], ride.values_at("name", "type")
|
||||||
|
layer = ride["children"].first
|
||||||
|
assert_equal ["ride.gpx", %w[waypoint track]], layer.values_at("name", "kinds")
|
||||||
|
assert_equal %w[waypoint track], JSON.parse(library.geojson(layer["path"]))["features"].map { |f| f["properties"]["kind"] }
|
||||||
|
|
||||||
|
# Running it again (or reopening) doesn't duplicate anything.
|
||||||
|
library.migrate
|
||||||
|
assert_equal tree, open_library.tree
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_a_layers_notes_are_still_edited_in_its_old_file
|
||||||
|
@store.append_feature(feature: note("Gate", "n1"), folder: "", name: "My Notes")
|
||||||
|
library = open_library
|
||||||
|
key = library.tree["children"].first["children"].first["path"]
|
||||||
|
|
||||||
|
library.update_feature(key, "n1", note("Wide gate", "n1"))
|
||||||
|
assert_equal ["Wide gate"], JSON.parse(library.geojson(key))["features"].map { |f| f["properties"]["name"] }
|
||||||
|
library.delete_feature(key, "n1")
|
||||||
|
assert_empty JSON.parse(library.geojson(key))["features"]
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_every_write_bumps_rev_and_deletes_are_tombstones
|
||||||
|
library = open_library
|
||||||
|
before = library.rev
|
||||||
|
key = library.add_note(note("Gate"), "Van")
|
||||||
|
id = JSON.parse(library.geojson(key))["features"].first["properties"]["id"]
|
||||||
|
library.delete_feature(key, id)
|
||||||
|
|
||||||
|
assert_operator library.rev, :>, before
|
||||||
|
row = library.send(:connect) { |db| db.get_first_row("SELECT deleted_at, rev FROM items WHERE id = ?", [id]) }
|
||||||
|
refute_nil row[0]
|
||||||
|
assert_equal library.rev, row[1]
|
||||||
|
assert_empty JSON.parse(library.geojson(key))["features"]
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_the_same_feature_is_deduped_per_folder_only
|
||||||
|
library = open_library
|
||||||
|
library.add_note(note("Gate"), "a")
|
||||||
|
library.add_note(note("Gate"), "a")
|
||||||
|
library.add_note(note("Gate"), "b")
|
||||||
|
|
||||||
|
counts = library.tree["children"].map { |folder| folder["children"].first["name"] }
|
||||||
|
assert_equal ["Points (1)", "Points (1)"], counts
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_moving_a_folders_points_returns_their_new_key
|
||||||
|
library = open_library
|
||||||
|
key = library.add_note(note("Gate"), "a")
|
||||||
|
moved = library.move_node(key, "b/c")
|
||||||
|
|
||||||
|
refute_equal key, moved
|
||||||
|
assert_equal ["Gate"], JSON.parse(library.geojson(moved))["features"].map { |f| f["properties"]["name"] }
|
||||||
|
assert_raises(Maptool::Library::NotFound) { library.move_node(key, "b") }
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_deleting_a_folder_takes_its_subfolders_and_items
|
||||||
|
library = open_library
|
||||||
|
key = library.add_note(note("Gate"), "a/b")
|
||||||
|
library.delete_folder("a")
|
||||||
|
|
||||||
|
assert_empty library.tree["children"]
|
||||||
|
assert_empty JSON.parse(library.geojson(key))["features"]
|
||||||
|
assert_raises(Maptool::Library::InvalidPath) { library.create_folder("../x") }
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def open_library
|
||||||
|
Maptool::Library.new(File.join(@dir, "library.sqlite"), gpx_store: @store, sources_dir: File.join(@dir, "sources"))
|
||||||
|
end
|
||||||
|
|
||||||
|
def note(name, id = nil)
|
||||||
|
{ "type" => "Feature", "properties" => { "name" => name, "category" => "Note", "id" => id }.compact,
|
||||||
|
"geometry" => { "type" => "Point", "coordinates" => [17.1, 48.1] } }
|
||||||
|
end
|
||||||
|
end
|
||||||
+11
-7
@@ -1,18 +1,21 @@
|
|||||||
require_relative "test_helper"
|
require_relative "test_helper"
|
||||||
require "maptool/gpx_store"
|
require "maptool/gpx_store"
|
||||||
|
require "maptool/library"
|
||||||
require "maptool/search"
|
require "maptool/search"
|
||||||
require "stringio"
|
require "stringio"
|
||||||
|
|
||||||
class SearchTest < Minitest::Test
|
class SearchTest < Minitest::Test
|
||||||
def setup
|
def setup
|
||||||
@data_dir = Dir.mktmpdir
|
@data_dir = Dir.mktmpdir
|
||||||
@store = Maptool::GpxStore.new(File.join(@data_dir, "gpx"))
|
@library = Maptool::Library.new(File.join(@data_dir, "library.sqlite"),
|
||||||
|
gpx_store: Maptool::GpxStore.new(File.join(@data_dir, "gpx")),
|
||||||
|
sources_dir: File.join(@data_dir, "sources"))
|
||||||
camp = { "type" => "FeatureCollection", "features" => [
|
camp = { "type" => "FeatureCollection", "features" => [
|
||||||
point("Kemp Košice", 21.26, 48.72, "pitná voda"),
|
point("Kemp Košice", 21.26, 48.72, "pitná voda"),
|
||||||
{ "type" => "Feature", "properties" => { "kind" => "track" },
|
{ "type" => "Feature", "properties" => { "kind" => "track" },
|
||||||
"geometry" => { "type" => "LineString", "coordinates" => [[17.0, 48.0, 150], [18.0, 49.0, 300]] } },
|
"geometry" => { "type" => "LineString", "coordinates" => [[17.0, 48.0, 150], [18.0, 49.0, 300]] } },
|
||||||
] }
|
] }
|
||||||
@store.save(folder: "trips", filename: "camps.geojson", io: StringIO.new(JSON.generate(camp)))
|
@library.import(folder: "trips", filename: "camps.geojson", io: StringIO.new(JSON.generate(camp)))
|
||||||
|
|
||||||
trails = File.join(@data_dir, "hiking_trails")
|
trails = File.join(@data_dir, "hiking_trails")
|
||||||
FileUtils.mkdir_p(trails)
|
FileUtils.mkdir_p(trails)
|
||||||
@@ -22,16 +25,17 @@ class SearchTest < Minitest::Test
|
|||||||
|
|
||||||
def test_finds_across_sources_ignoring_case_and_diacritics_and_says_where
|
def test_finds_across_sources_ignoring_case_and_diacritics_and_says_where
|
||||||
layer = search("kosice")
|
layer = search("kosice")
|
||||||
assert_equal [["Kemp Košice", "layers", "trips/camps.geojson"]], layer.map { |r| r.values_at(:name, :source, :ref) }
|
assert_equal [["Kemp Košice", "layers", "trips / Track"]], layer.map { |r| r.values_at(:name, :source, :source_label) }
|
||||||
|
assert_match(/\Aitem:/, layer.first[:ref])
|
||||||
|
|
||||||
trail = search("snp hrdinov").first
|
trail = search("snp hrdinov").first
|
||||||
assert_equal ["hiking_trails", "SK", "Hiking trails SK"], trail.values_at(:source, :ref, :source_label)
|
assert_equal ["hiking_trails", "SK", "Hiking trails SK"], trail.values_at(:source, :ref, :source_label)
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_matches_description_and_falls_back_to_file_name_with_bbox
|
def test_matches_description_and_falls_back_to_node_label_with_bbox
|
||||||
assert_equal ["Kemp Košice"], search("voda").map { |r| r[:name] }
|
assert_equal ["Kemp Košice"], search("voda").map { |r| r[:name] }
|
||||||
|
|
||||||
track = search("camps").first
|
track = search("trips track").first
|
||||||
assert_equal [17.0, 48.0, 18.0, 49.0], track[:bbox]
|
assert_equal [17.0, 48.0, 18.0, 49.0], track[:bbox]
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -39,7 +43,7 @@ class SearchTest < Minitest::Test
|
|||||||
camps = { "type" => "FeatureCollection", "features" => [
|
camps = { "type" => "FeatureCollection", "features" => [
|
||||||
point("Kemp far", 21.0, 48.7), point("Kemp near", 17.1, 48.15),
|
point("Kemp far", 21.0, 48.7), point("Kemp near", 17.1, 48.15),
|
||||||
] }
|
] }
|
||||||
@store.save(folder: "", filename: "more.geojson", io: StringIO.new(JSON.generate(camps)))
|
@library.import(folder: "", filename: "more.geojson", io: StringIO.new(JSON.generate(camps)))
|
||||||
|
|
||||||
results = search("kemp", center: [48.14, 17.10])
|
results = search("kemp", center: [48.14, 17.10])
|
||||||
assert_equal ["Kemp near", "Kemp far", "Kemp Košice"], results.map { |r| r[:name] }
|
assert_equal ["Kemp near", "Kemp far", "Kemp Košice"], results.map { |r| r[:name] }
|
||||||
@@ -54,7 +58,7 @@ class SearchTest < Minitest::Test
|
|||||||
private
|
private
|
||||||
|
|
||||||
def search(text, **opts)
|
def search(text, **opts)
|
||||||
Maptool::Search.query(text, gpx_store: @store, data_dir: @data_dir, **opts)
|
Maptool::Search.query(text, library: @library, data_dir: @data_dir, **opts)
|
||||||
end
|
end
|
||||||
|
|
||||||
def point(name, lng, lat, description = nil)
|
def point(name, lng, lat, description = nil)
|
||||||
|
|||||||
Reference in new issue
Block a user