Library phase 1: SQLite item library with folders, migration of old files as layers, import split into items

This commit is contained in:
randy committed 2026-11-13 09:03:22 +01:00
1 parent 4216211a20
commit ad8b72c3d3
16 files changed
+897 -499

No files matched your search

+119 -174
View File
@@ -7,6 +7,7 @@ require "stringio"
require_relative "lib/maptool/gpx"
require_relative "lib/maptool/fit"
require_relative "lib/maptool/gpx_store"
require_relative "lib/maptool/library"
require_relative "lib/maptool/gpsd_client"
require_relative "lib/maptool/livetrack_store"
require_relative "lib/maptool/livetrack_client"
@@ -101,7 +102,10 @@ module Maptool
OFFLINE_PMTILES_PATH = File.join(DATA_DIR, "offline.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"))
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"))
# 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.
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:)
paths = []
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
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
paths
@@ -452,7 +464,7 @@ module Maptool
sources = params[:sources].to_s.split(",")
sources = Search::SOURCES.keys if sources.empty?
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)
end
@@ -494,98 +506,134 @@ module Maptool
body response.body
end
get "/api/gpx/tree" do
json GPX_STORE.tree
# Tracks & Points (lib/maptool/library.rb). Reading is login-free like
# 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
# A .zip (Garmin's bulk/FIT export format) is expanded into its
# .gpx/.fit/.geojson entries instead of being stored itself — nothing
# downstream (tree listing, map rendering) knows what to do with a zip.
post "/api/gpx" do
# .gpx/.fit/.geojson entries, each imported like its own upload.
post "/api/library/import" do
require_login!
file = params[:file]
halt 400, json(error: "file is required") unless file && file[:tempfile]
begin
paths = if file[:filename].to_s.downcase.end_with?(".zip")
save_zip_entries(folder: params[:folder].to_s, io: file[:tempfile])
else
[GPX_STORE.save(folder: params[:folder].to_s, filename: file[:filename], io: file[:tempfile])]
end
rescue GpxStore::InvalidPath
keys = if file[:filename].to_s.downcase.end_with?(".zip")
save_zip_entries(folder: params[:folder].to_s, io: file[:tempfile])
else
LIBRARY.import(folder: params[:folder].to_s, filename: file[:filename], io: file[:tempfile])
end
rescue Library::InvalidPath
halt 400, json(error: "invalid folder")
rescue Library::ParseError
halt 422, json(error: "could not parse file")
rescue Zip::Error
halt 400, json(error: "invalid zip file")
end
json paths: paths, tree: GPX_STORE.tree
json paths: keys, tree: LIBRARY.tree
end
# A hand-drawn point/note (see notes.js) — unlike the upload above, this
# grows one existing/new .geojson "layer" file in place (GpxStore#
# append_feature) rather than always landing as its own new file.
post "/api/gpx/notes" do
require_login!
begin
feature = JSON.parse(params[:feature].to_s)
rescue JSON::ParserError
halt 400, json(error: "invalid feature")
end
halt 400, json(error: "invalid feature") unless feature.is_a?(Hash) && feature["geometry"]
# ?download=original sends the file the node came from, ?download=geojson
# the node's GeoJSON as an attachment — both login-only, like the other
# export/manage actions; plain viewing on the map isn't.
get "/api/library/node/:key" do
require_login! if params[:download]
key = params[:key]
begin
path = GPX_STORE.append_feature(
feature: feature,
path: params[:path],
folder: params[:folder].to_s,
name: params[:name].to_s
)
rescue GpxStore::InvalidPath
halt 400, json(error: "invalid path")
rescue Errno::ENOENT
halt 404, json(error: "file not found")
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
json path: path, tree: GPX_STORE.tree
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
# 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
delete "/api/library/node/:key" do
require_login!
begin
feature = JSON.parse(params[:feature].to_s)
rescue JSON::ParserError
halt 400, json(error: "invalid feature")
end
halt 400, json(error: "invalid feature") unless feature.is_a?(Hash) && feature["geometry"]
LIBRARY.delete_node(params[:key])
json tree: LIBRARY.tree
rescue Library::NotFound
halt 404
end
post "/api/library/move" do
require_login!
key = LIBRARY.move_node(params[:key].to_s, params[:to_folder].to_s)
json path: key, tree: LIBRARY.tree
rescue Library::InvalidPath
halt 400, json(error: "invalid folder")
rescue Library::NotFound
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")
end
delete "/api/library/folder/*" do
require_login!
LIBRARY.delete_folder(params[:splat].first)
json tree: LIBRARY.tree
rescue Library::InvalidPath
halt 400
rescue Library::NotFound
halt 404
end
# 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?
begin
GPX_STORE.update_feature(path: params[:path], id: params[:id], feature: feature)
rescue GpxStore::InvalidPath
halt 400, json(error: "invalid path")
rescue Errno::ENOENT
halt 404, json(error: "note not found")
end
LIBRARY.update_feature(params[:path], params[:id], feature)
json ok: true
rescue Library::NotFound, Errno::ENOENT
halt 404, json(error: "note not found")
rescue GpxStore::InvalidPath
halt 400, json(error: "invalid path")
end
delete "/api/gpx/notes" do
delete "/api/library/notes" do
require_login!
halt 400, json(error: "path and id are required") if params[:path].to_s.empty? || params[:id].to_s.empty?
begin
GPX_STORE.delete_feature(path: params[:path], id: params[:id])
rescue GpxStore::InvalidPath
halt 400, json(error: "invalid path")
rescue Errno::ENOENT
halt 404, json(error: "note not found")
end
LIBRARY.delete_feature(params[:path], params[:id])
json ok: true
rescue Library::NotFound, Errno::ENOENT
halt 404, json(error: "note not found")
rescue GpxStore::InvalidPath
halt 400, json(error: "invalid path")
end
# Lists whatever import plugins are on disk (see lib/maptool/plugins.rb
@@ -596,11 +644,9 @@ module Maptool
end
# Runs one plugin for the given bbox (the current map viewport, from
# the frontend's "Run for this area" button) and saves its GeoJSON
# output as a new file the same way an uploaded .geojson would be
# saved — reusing GpxStore#save rather than #append_feature since this
# writes a whole FeatureCollection at once, not one feature into an
# existing one.
# the frontend's "Run for this area" button) and imports its GeoJSON
# output into a folder of its own, named after the area's center and
# the run's time — so one run's POIs stay apart from another's.
post "/api/plugins/:name/run" do
require_login!
bbox = %w[south west north east].map { |key| params[key].to_s }
@@ -613,114 +659,13 @@ module Maptool
halt 502, json(error: e.message)
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_lon = format("%.2f", (west + east) / 2)
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)))
json path: path, tree: GPX_STORE.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
keys = LIBRARY.import(folder: name, filename: "#{name}.geojson", io: StringIO.new(JSON.generate(geojson)))
json path: keys.first, tree: LIBRARY.tree
end
# Called by the Apps Script watching Gmail for Garmin LiveTrack emails —