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:", drawn with its child points), and a # folder's loose points and shapes together are another # ("points:"). class Library class NotFound < StandardError; end class InvalidPath < StandardError; end class ParseError < StandardError; end class InvalidValue < 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 items_fingerprint ON items(folder_id, fingerprint); 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 IN ('layer', 'track', 'route') 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| props = JSON.parse(props) kinds = type == "layer" ? 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?, "layer" => type == "layer", "color" => props["color"] }.compact 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, properties FROM items WHERE id = ? AND deleted_at IS NULL", [id]) raise NotFound unless item return layer_geojson(item[1], JSON.parse(item[2])["color"]) 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// 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 # Rename and/or recolor a track, route or layer (nil leaves it as is, # an empty color goes back to the default). def update_node(key, name: nil, color: nil) kind, id = key.to_s.split(":", 2) raise NotFound unless kind == "item" raise InvalidValue if color && !color.empty? && !color.match?(/\A#\h{6}\z/) raise InvalidValue if name && name.strip.empty? write do |db, rev, now| row = db.get_first_row("SELECT name, properties FROM items WHERE id = ? AND type IN ('track', 'route', 'layer') AND deleted_at IS NULL", [id]) raise NotFound unless row props = JSON.parse(row[1]) props = color.empty? ? props.except("color") : props.merge("color" => color) if color db.execute("UPDATE items SET name = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ?", [name ? name.strip : row[0], JSON.generate(props), now, rev, id]) end end # A migrated layer → ordinary items in its folder (its notes included, # keeping their ids), the legacy file copied as their original. The # layer is tombstoned; data/gpx/ itself stays untouched. def split_layer(key) kind, id = key.to_s.split(":", 2) row = connect { |db| db.get_first_row("SELECT folder_id, source_path, properties FROM items WHERE id = ? AND type = 'layer' AND deleted_at IS NULL", [id]) } raise NotFound unless kind == "item" && row folder, legacy, props = row features = begin JSON.parse(layer_geojson(legacy, JSON.parse(props)["color"]))["features"] rescue Gpx::ParseError, Fit::ParseError, JSON::ParserError => e raise ParseError, e.message end relative = File.join(SecureRandom.uuid, File.basename(legacy)) FileUtils.mkdir_p(File.join(@sources_dir, File.dirname(relative))) FileUtils.cp(@gpx_store.resolve_file(legacy), File.join(@sources_dir, relative)) keys = add_features(features, folder, source: relative, by_id: true) write { |db, rev, now| tombstone(db, "id = ?", [id], rev, now) } keys 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 # Returns the folder's new path. def rename_folder(path, name) name = name.to_s.strip raise InvalidPath if name.empty? || name.include?("/") || %w[. ..].include?(name) id = folder_id(path, create: false) or raise NotFound write do |db, rev, now| parent = db.get_first_value("SELECT parent_id FROM folders WHERE id = ?", [id]) raise InvalidValue if sibling?(db, parent, name, id) db.execute("UPDATE folders SET name = ?, updated_at = ?, rev = ? WHERE id = ?", [name, now, rev, id]) end [*path.split("/")[0...-1], name].join("/") end # Into `to_folder` ("" = top level); returns the folder's new path. def move_folder(path, to_folder) id = folder_id(path, create: false) or raise NotFound target = folder_id(to_folder, create: true) write do |db, rev, now| ancestor = target while ancestor raise InvalidPath if ancestor == id # into itself or its own subfolder ancestor = db.get_first_value("SELECT parent_id FROM folders WHERE id = ?", [ancestor]) end name = db.get_first_value("SELECT name FROM folders WHERE id = ?", [id]) raise InvalidValue if sibling?(db, target, name, id) db.execute("UPDATE folders SET parent_id = ?, updated_at = ?, rev = ? WHERE id = ?", [target, now, rev, id]) end [*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:) 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 # 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 # A layer's legacy GeoJSON with its node color on the lines. def layer_geojson(source, color) body = @gpx_store.geojson(source) return body unless color data = JSON.parse(body) data["features"].each { |f| f["properties"] = (f["properties"] || {}).merge("color" => color) unless f.dig("geometry", "type") == "Point" } JSON.generate(data) 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 # `folder` is a path, or with by_id: true already an id (nil = top). def add_features(features, folder, source: nil, by_id: false) target = by_id ? folder : 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_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 == ".." 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