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
+897
-499
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user