diff --git a/TODO.adoc b/TODO.adoc index 9116ff9..2d19b73 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -75,7 +75,7 @@ independence from connectivity. * [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] 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 * [x] Library phase 2 — rename/recolor tracks, routes and layers, rename and move (drag) folders, split a migrated layer into items (its notes become items, keeping their ids) -* [ ] Change feed + GPX export flavors for OsmAnd/Locus +* [x] Change feed + GPX export flavors for OsmAnd/Locus — `/api/library/changes`, folder menu → Export for Locus (GPX) / OsmAnd (zip) * [ ] Android sync client (MapTool → apps first; apps → MapTool only if their APIs can list data) == Nice to have (later) diff --git a/app.rb b/app.rb index f34b16c..bd31d51 100644 --- a/app.rb +++ b/app.rb @@ -662,6 +662,46 @@ module Maptool halt 404 end + # The sync feed (Library#changes): everything after ?since=. + # Login-only, like the other exports. + get "/api/library/changes" do + require_login! + json LIBRARY.changes(params[:since]) + rescue Library::InvalidValue + halt 400, json(error: "since must be a number") + end + + # A folder (?folder=a/b, "" = top level) for an app: ?flavor=locus is + # one GPX, ?flavor=osmand a zip of favourites.gpx + tracks/. + get "/api/library/export" do + require_login! + folder = params[:folder].to_s + name = folder.split("/").last || "MapTool" + case params[:flavor] + when "locus" + content_type "application/gpx+xml" # before attachment, which doesn't know .gpx + attachment "#{name}.gpx" + LIBRARY.export_gpx(folder) + when "osmand" + files = LIBRARY.export_osmand(folder) + halt 404, json(error: "nothing to export") if files.empty? + content_type "application/zip" + attachment "#{name}-osmand.zip" + Zip::OutputStream.write_buffer do |zip| + files.each do |path, gpx| + zip.put_next_entry(path) + zip.write(gpx) + end + end.string + else + halt 400, json(error: "flavor must be locus or osmand") + end + rescue Library::InvalidPath + halt 400, json(error: "invalid folder") + 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) diff --git a/docs/library-design.adoc b/docs/library-design.adoc index f57d9f3..a0d46a2 100644 --- a/docs/library-design.adoc +++ b/docs/library-design.adoc @@ -2,7 +2,7 @@ :toc: :toclevels: 2 -Status: *phases 1–2 implemented* (`lib/maptool/library.rb`, see Decisions); phases 3–4 proposed. Replaces the file-based store behind +Status: *phases 1–3 implemented* (`lib/maptool/library.rb`, see Decisions); phase 4 (the Android client) proposed. Replaces the file-based store behind Tracks & Points (`GpxStore`) with an item-based library that OsmAnd, Locus Map and the MapTool web app can all be synced against. @@ -341,6 +341,28 @@ removed once nothing uses them. * `GpxStore` stays, since unsplit layers are still drawn from it. It goes away once nothing is a layer any more. +== Decisions (phase 3) + +* `GET /api/library/changes?since=`: folders and items with + `rev > since`, tombstones as `"deleted": true`, plus the current `rev`, + read in one transaction. A layer comes without geometry; it's a legacy + file until split. Login-only for now. The Android client will need a + token instead of the browser session (phase 4). +* `GET /api/library/export?folder=&flavor=locus|osmand`, from the + folder's own menu (and the panel header for the top level). It covers + the folder's own items, not its subfolders. + ** Locus: one GPX with points, tracks and routes together. + ** OsmAnd: a zip. `favourites.gpx` holds the loose points, with the + folder path as their `` group ("Van / CZ") and duplicate names + made unique ("Gate (2)"). `tracks//.gpx` holds + one file per track, route or layer, with that item's own points in + it. +* GPX writing (`Gpx.from_features`): colors as ``, which is + what import reads back, and on lines also gpx_style ``, + which Locus reads. Not verified yet against files the apps export + themselves; adjust the tags once a real OsmAnd/Locus export is at + hand. + == Open questions * Folder depth over 3 — fine to require Locus Premium? diff --git a/lib/maptool/gpx.rb b/lib/maptool/gpx.rb index d63942e..dbb3800 100644 --- a/lib/maptool/gpx.rb +++ b/lib/maptool/gpx.rb @@ -57,6 +57,84 @@ module Maptool end private_class_method :waypoint_feature + # The other direction, for exporting to OsmAnd/Locus (Library#export): + # Point features → , kind "route" lines → , every other line + # or polygon ring → . `group` replaces every waypoint's + # (OsmAnd reads it as the favourites group); without it the point's own + # category is kept. Colors go out as (what import reads + # back) and, on lines, gpx_style's , which Locus reads. + def self.from_features(features, group: nil) + doc = REXML::Document.new + doc << REXML::XMLDecl.new("1.0", "UTF-8") + gpx = doc.add_element("gpx", "version" => "1.1", "creator" => "MapTool", "xmlns" => "http://www.topografix.com/GPX/1/1", + "xmlns:osmand" => OSMAND_NAMESPACE, "xmlns:gpx_style" => GPX_STYLE_NAMESPACE) + points, lines = features.partition { |f| f.dig("geometry", "type") == "Point" } + points.each { |f| write_waypoint(gpx, f, group) } + lines.each { |f| write_line(gpx, f) } + out = +"" + doc.write(output: out) + out + end + + GPX_STYLE_NAMESPACE = "http://www.topografix.com/GPX/gpx_style/0/2" + private_constant :GPX_STYLE_NAMESPACE + + def self.write_waypoint(gpx, feature, group) + props = feature["properties"] || {} + wpt = gpx.add_element("wpt", position_attributes(feature["geometry"]["coordinates"])) + add_text(wpt, "ele", feature["geometry"]["coordinates"][2]) + add_text(wpt, "time", props["time"]) + add_text(wpt, "name", props["name"]) + add_text(wpt, "desc", props["description"]) + add_text(wpt, "type", group || props["category"]) + return unless props["color"] || props["icon"] + + extensions = wpt.add_element("extensions") + add_text(extensions, "osmand:color", props["color"]) + add_text(extensions, "osmand:icon", props["icon"]) + end + private_class_method :write_waypoint + + def self.write_line(gpx, feature) + props = feature["properties"] || {} + geometry = feature["geometry"] + segments = case geometry["type"] + when "LineString" then [geometry["coordinates"]] + when "MultiLineString", "Polygon" then geometry["coordinates"] + when "MultiPolygon" then geometry["coordinates"].flatten(1) + else return + end + route = props["kind"] == "route" + element = gpx.add_element(route ? "rte" : "trk") + add_text(element, "name", props["name"]) + add_text(element, "desc", props["description"]) + add_text(element, "type", props["activity_type"]) + if props["color"] + extensions = element.add_element("extensions") + add_text(extensions, "osmand:color", props["color"]) + add_text(extensions.add_element("gpx_style:line"), "gpx_style:color", props["color"].delete("#")) + end + if route + segments.flatten(1).each { |c| add_text(element.add_element("rtept", position_attributes(c)), "ele", c[2]) } + else + segments.each do |segment| + trkseg = element.add_element("trkseg") + segment.each { |c| add_text(trkseg.add_element("trkpt", position_attributes(c)), "ele", c[2]) } + end + end + end + private_class_method :write_line + + def self.position_attributes(coordinates) + { "lat" => coordinates[1].to_s, "lon" => coordinates[0].to_s } + end + private_class_method :position_attributes + + def self.add_text(parent, name, value) + parent.add_element(name).text = value.to_s unless value.nil? || value.to_s.empty? + end + private_class_method :add_text + # is plain GPX 1.1 (a wpt/trk/rte can carry any number of them), # not a vendor extension like waypoint_style's — a newer # p4n2gpx export started emitting one per park4night listing photo. A diff --git a/lib/maptool/library.rb b/lib/maptool/library.rb index 4a4fb4d..68716d8 100644 --- a/lib/maptool/library.rb +++ b/lib/maptool/library.rb @@ -353,6 +353,63 @@ module Maptool [*to_folder.to_s.split("/").map(&:strip).reject(&:empty?), path.split("/").last].join("/") end + # --- sync / export ------------------------------------------------------ + + # Everything written after `since` (tombstones included) and the + # current rev: the feed a sync client polls (docs/library-design.adoc). + # A layer has no geometry of its own here (it's a legacy file). + def changes(since) + since = Integer(since || 0) + connect do |db| + db.transaction do + folders = db.execute("SELECT id, parent_id, name, updated_at, deleted_at, rev FROM folders WHERE rev > ? ORDER BY rev", [since]) + items = db.execute("SELECT id, folder_id, parent_id, type, name, geometry, properties, updated_at, deleted_at, rev FROM items WHERE rev > ? ORDER BY rev", [since]) + { "rev" => db.get_first_value("SELECT rev FROM meta"), + "folders" => folders.map { |id, parent, name, updated, deleted, rev| { "id" => id, "parent_id" => parent, "name" => name, "updated_at" => updated, "deleted" => !deleted.nil?, "rev" => rev } }, + "items" => items.map do |id, folder, parent, type, name, geometry, props, updated, deleted, rev| + { "id" => id, "folder_id" => folder, "parent_id" => parent, "type" => type, "name" => name, + "geometry" => geometry && JSON.parse(geometry), "properties" => JSON.parse(props), + "updated_at" => updated, "deleted" => !deleted.nil?, "rev" => rev } + end } + end + end + rescue ArgumentError, TypeError + raise InvalidValue + end + + # A folder's own items (not its subfolders') as one GPX with points and + # tracks together — what Locus imports into one folder. + def export_gpx(path) + Gpx.from_features(export_entries(path).map { |e| e[:feature] }) + end + + # The same folder the way OsmAnd keeps things: { filename => GPX }. + # Loose points → favourites.gpx in a group named after the folder path + # (names made unique, OsmAnd needs that per group); each track, route + # or layer → its own tracks/.gpx with its own points. + def export_osmand(path) + group = path.to_s.split("/").reject(&:empty?).join(" / ") + group = "MapTool" if group.empty? + files = export_entries(path).group_by { |e| e[:file] } + favourites = (files.delete(nil) || []).map { |e| e[:feature] } + seen = Hash.new(0) + favourites = favourites.map do |f| + name = f["properties"]["name"].to_s.empty? ? "Point" : f["properties"]["name"] + seen[name] += 1 + f.merge("properties" => f["properties"].merge("name" => seen[name] > 1 ? "#{name} (#{seen[name]})" : name)) + end + out = {} + out["favourites.gpx"] = Gpx.from_features(favourites, group: group) if favourites.any? + dir = ["tracks", *group.split(" / ").map { |part| safe_name(part) }].join("/") + names = Hash.new(0) + files.each_value do |entries| + base = safe_name(File.basename(entries.first[:file_name].to_s, ".*")) + names[base] += 1 + out["#{dir}/#{names[base] > 1 ? "#{base} (#{names[base]})" : base}.gpx"] = Gpx.from_features(entries.map { |e| e[:feature] }) + end + out + 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:) @@ -385,6 +442,35 @@ module Maptool id == ROOT ? nil : id end + # Each feature in a folder (layers expanded) with the OsmAnd file it + # goes into: nil = favourites, else the id of the track/route/layer it + # belongs with (a polygon or a measured line gets a file of its own). + def export_entries(path) + id = path.to_s.empty? ? nil : (folder_id(path, create: false) or raise NotFound) + rows = connect do |db| + db.execute("SELECT id, parent_id, type, name, geometry, properties, source_path FROM items WHERE folder_id IS ? AND deleted_at IS NULL ORDER BY name COLLATE NOCASE", [id]) + end + rows.flat_map do |iid, parent, type, name, geometry, props, source| + if type == "layer" + features = begin + JSON.parse(layer_geojson(source, JSON.parse(props)["color"]))["features"] + rescue Gpx::ParseError, Fit::ParseError, Errno::ENOENT + [] # an unreadable legacy file doesn't sink the whole folder + end + lines = features.any? { |f| f.dig("geometry", "type") != "Point" } + features.map { |f| { feature: f, file: lines ? iid : nil, file_name: name } } + else + f = feature(iid, name, geometry, props) + file = parent || (type == "point" ? nil : iid) + [{ feature: f, file: file, file_name: file && (file == iid ? name : nil) }] + end + end.then do |entries| + # A track's points name their file after the track. + names = entries.filter_map { |e| [e[:file], e[:file_name]] if e[:file_name] }.to_h + entries.each { |e| e[:file_name] ||= names[e[:file]] } + end + end + def sibling?(db, parent, name, except) db.get_first_value("SELECT 1 FROM folders WHERE parent_id IS ? AND name = ? AND id != ? AND deleted_at IS NULL", [parent, name, except]) end @@ -482,6 +568,11 @@ module Maptool db.execute("UPDATE items SET deleted_at = ?, updated_at = ?, rev = ? WHERE (#{where}) AND deleted_at IS NULL", [now, now, rev, *params]) end + def safe_name(name) + name = name.to_s.gsub(%r{[/\\:*?"<>|]}, "_").strip + name.empty? || %w[. ..].include?(name) ? "track" : name + end + def safe_filename(filename) base = File.basename(filename.to_s) base = "upload.gpx" if base.empty? || base == "." || base == ".." diff --git a/public/js/gpx.js b/public/js/gpx.js index c1aec55..77299a8 100644 --- a/public/js/gpx.js +++ b/public/js/gpx.js @@ -130,6 +130,10 @@ export class GpxPanelControl { if (!isLoggedIn()) { this._panel.querySelector('[data-action="new-folder"]').hidden = true; this._panel.querySelector('[data-action="upload"]').hidden = true; + } else { + // The top level's own items have no folder row with a menu of its own. + const close = this._panel.querySelector(".gpx-panel__close"); + close.before(this._menuButton(DOWNLOAD_ICON, "Export the top level", this._exportEntries("", "MapTool"))); } this._panel .querySelector(".gpx-panel__close") @@ -280,7 +284,12 @@ export class GpxPanelControl { name.textContent = folder.name; row.appendChild(name); if (isLoggedIn()) { - row.appendChild(this._menuButton("⋯", "Edit", [{ label: "Rename…", run: () => this._renameFolder(folder) }])); + row.appendChild( + this._menuButton("⋯", "Edit", [ + { label: "Rename…", run: () => this._renameFolder(folder) }, + ...this._exportEntries(folder.path, folder.name), + ]), + ); row.appendChild(this._deleteButton(() => this._deleteFolder(folder.path))); // Dragged onto another folder (or the tree's blank space) moves it. summary.draggable = true; @@ -1083,6 +1092,15 @@ export class GpxPanelControl { this._renderTree(tree); } + // A folder (or "" for the top level) as files for the phone apps. + _exportEntries(path, name) { + const url = (flavor) => `/api/library/export?${new URLSearchParams({ folder: path, flavor })}`; + return [ + { label: "Export for Locus (GPX)", run: () => this._download(url("locus"), `${name}.gpx`) }, + { label: "Export for OsmAnd (zip)", run: () => this._download(url("osmand"), `${name}-osmand.zip`) }, + ]; + } + async _renameFolder(folder) { const name = window.prompt("Rename folder:", folder.name); if (name && name.trim() && name.trim() !== folder.name) await this._patchFolder(folder.path, { name: name.trim() }); diff --git a/test/test_app.rb b/test/test_app.rb index 8cc1716..94f69f4 100644 --- a/test/test_app.rb +++ b/test/test_app.rb @@ -247,6 +247,23 @@ class AppTest < Minitest::Test FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "vehicle.json")) end + def test_changes_and_exports_need_login + upload("ride.gpx", File.read(fixture_path("sample.gpx")), folder: "trips") + assert_equal 401, request.get("/api/library/changes").status + assert_equal 401, request.get("/api/library/export?folder=trips&flavor=locus").status + + changes = json_body(request.get("/api/library/changes?since=0", **logged_in_env)) + assert_equal ["Morning Loop", "Start"], changes["items"].map { |i| i["name"] }.sort + + locus = request.get("/api/library/export?folder=trips&flavor=locus", **logged_in_env) + assert_includes locus.body, "Morning Loop" + osmand = request.get("/api/library/export?folder=trips&flavor=osmand", **logged_in_env) + entries = nil + Zip::File.open_buffer(StringIO.new(osmand.body)) { |zip| entries = zip.map(&:name) } + assert_equal ["tracks/trips/Morning Loop.gpx"], entries + assert_equal 400, request.get("/api/library/export?folder=trips&flavor=x", **logged_in_env).status + end + def test_invalid_folder_path_is_rejected assert_equal 400, request.post("/api/library/folder?path=..%2F..%2Fescape", **logged_in_env).status end diff --git a/test/test_library.rb b/test/test_library.rb index 7c52b4d..8e04fce 100644 --- a/test/test_library.rb +++ b/test/test_library.rb @@ -145,8 +145,44 @@ class LibraryTest < Minitest::Test assert_equal [["Lake, scenic", 3]], features.map { |f| [f["properties"]["name"], f["properties"]["via"].size] } end + def test_changes_lists_everything_after_a_rev_tombstones_included + library = open_library + start = library.rev + key = library.add_note(note("Gate"), "Van") + id = JSON.parse(library.geojson(key))["features"].first["properties"]["id"] + library.delete_feature(key, id) + + changes = library.changes(start) + assert_equal library.rev, changes["rev"] + assert_equal ["Van"], changes["folders"].map { |f| f["name"] } + assert_equal [[id, true, "Point"]], changes["items"].map { |i| [i["id"], i["deleted"], i["geometry"]["type"]] } + assert_empty library.changes(library.rev)["items"] + assert_raises(Maptool::Library::InvalidValue) { library.changes("x") } + end + + def test_export_for_locus_and_osmand + library = open_library + library.import(folder: "Van/CZ", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx"))) + library.add_note(note("Gate"), "Van/CZ") + library.add_note(note("Gate", nil).tap { |f| f["geometry"]["coordinates"] = [17.3, 48.3] }, "Van/CZ") + + locus = Maptool::Gpx.to_geojson(write_tmp(library.export_gpx("Van/CZ")))["features"] + assert_equal 2, locus.count { |f| f["properties"]["name"] == "Gate" } + assert(locus.any? { |f| f["properties"]["kind"] == "track" }) + + files = library.export_osmand("Van/CZ") + assert_equal ["favourites.gpx", "tracks/Van/CZ/Morning Loop.gpx"], files.keys.sort + favourites = Maptool::Gpx.to_geojson(write_tmp(files["favourites.gpx"]))["features"] + assert_equal [["Gate", "Van / CZ"], ["Gate (2)", "Van / CZ"]], favourites.map { |f| f["properties"].values_at("name", "category") }.sort + assert_raises(Maptool::Library::NotFound) { library.export_gpx("nope") } + end + private + def write_tmp(content) + File.join(@dir, "export-#{SecureRandom.hex(4)}.gpx").tap { |path| File.write(path, content) } + end + def open_library Maptool::Library.new(File.join(@dir, "library.sqlite"), gpx_store: @store, sources_dir: File.join(@dir, "sources")) end