811 lines
36 KiB
Ruby
811 lines
36 KiB
Ruby
require "digest"
|
|
require "fileutils"
|
|
require "json"
|
|
require "securerandom"
|
|
require "sqlite3"
|
|
require "time"
|
|
require_relative "gpx"
|
|
require_relative "fit"
|
|
require_relative "tcx"
|
|
require_relative "fit_course"
|
|
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
|
|
class InvalidValue < StandardError; end
|
|
|
|
ROOT = "root" # folder id in a node key for items with no folder
|
|
EXTENSIONS = %w[.gpx .fit .tcx .geojson].freeze
|
|
# Bumped when a parser starts reading more (power, temperature, ...):
|
|
# tracks imported before get their profile re-read once (reparse).
|
|
PARSER_VERSION = 3
|
|
|
|
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 (rev) 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
|
|
db.execute("ALTER TABLE meta ADD COLUMN parser INTEGER NOT NULL DEFAULT 0") unless db.execute("PRAGMA table_info(meta)").any? { |c| c[1] == "parser" }
|
|
end
|
|
migrate if fresh
|
|
end
|
|
|
|
# Re-reads every imported track's/route's profile from its source file
|
|
# (and drops migrated layers' cached GeoJSON) when PARSER_VERSION went
|
|
# up; name, color and the rest stay. Returns how many were updated.
|
|
def reparse
|
|
return 0 if connect { |db| db.get_first_value("SELECT parser FROM meta") } >= PARSER_VERSION
|
|
|
|
rows = connect { |db| db.execute("SELECT id, type, name, geometry, properties, source_path FROM items WHERE deleted_at IS NULL AND source_path IS NOT NULL AND type IN ('track', 'route', 'layer')") }
|
|
updated = 0
|
|
rows.each do |id, type, name, geometry, props, source|
|
|
if type == "layer"
|
|
@gpx_store.refresh(source)
|
|
next
|
|
end
|
|
path = File.join(@sources_dir, source)
|
|
next if !File.file?(path) || path.downcase.end_with?(".geojson")
|
|
|
|
geometry = round(JSON.parse(geometry))
|
|
feature = parse(path).find { |f| item_type(f) == type && round(f["geometry"]) == geometry }
|
|
next unless feature&.dig("properties", "profile")
|
|
|
|
name = default_name(source) if name.to_s.empty?
|
|
props = JSON.parse(props).merge(feature["properties"].slice("profile", "laps"))
|
|
props["name"] = name if props["name"].to_s.empty?
|
|
write do |db, rev, now|
|
|
db.execute("UPDATE items SET name = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ?",
|
|
[name, JSON.generate(props), now, rev, id])
|
|
end
|
|
updated += 1
|
|
rescue Gpx::ParseError, Fit::ParseError, Errno::ENOENT, JSON::ParserError, GpxStore::InvalidPath
|
|
next
|
|
end
|
|
connect { |db| db.execute("UPDATE meta SET parser = ?", [PARSER_VERSION]) }
|
|
updated
|
|
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,
|
|
CASE WHEN parent_id IS NOT NULL THEN geometry 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] }
|
|
children = items.select { |i| i[2] && i[3] == "point" }.group_by { |i| i[2] }
|
|
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)
|
|
points = (children[iid] || []).map { |pid, *, pname, _, _, geometry| { "id" => pid, "name" => pname.to_s.empty? ? "Point" : pname, "coordinates" => JSON.parse(geometry)["coordinates"] } }
|
|
kinds = type == "layer" ? props["kinds"] || [] : [type, *("waypoint" if points.any?)]
|
|
{ "type" => "file", "path" => "item:#{iid}", "name" => name.to_s.empty? ? type.capitalize : name,
|
|
"kinds" => kinds, "original" => !source.nil?, "layer" => type == "layer", "color" => props["color"],
|
|
"points" => (points if points.any?) }.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
|
|
|
|
source_file(type, 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
|
|
|
|
# Already-parsed features (GoogleSaved) into `folder`, same rules as an
|
|
# upload minus the stored source file.
|
|
def import_features(features, folder:)
|
|
add_features(features, folder)
|
|
end
|
|
|
|
# FIT (and many TCX/GPX) tracks carry no name of their own: those take
|
|
# the file's, so the tree doesn't fill up with "Track".
|
|
def default_name(source)
|
|
File.basename(source, ".*")
|
|
end
|
|
|
|
# A point into a track/route (`key` "item:<id>"), kept with it like a
|
|
# GPX's own waypoints: shown, moved, deleted and exported together.
|
|
def add_point(key, feature)
|
|
kind, id = key.to_s.split(":", 2)
|
|
raise NotFound unless kind == "item"
|
|
raise InvalidValue unless feature.dig("geometry", "type") == "Point"
|
|
|
|
props = (feature["properties"] || {}).except("id").compact
|
|
write do |db, rev, now|
|
|
folder = db.get_first_row("SELECT folder_id FROM items WHERE id = ? AND type IN ('track', 'route') AND deleted_at IS NULL", [id]) or raise NotFound
|
|
point = SecureRandom.uuid
|
|
db.execute("INSERT INTO items VALUES (?, ?, ?, 'point', ?, ?, ?, ?, NULL, ?, ?, NULL, ?)",
|
|
[point, folder[0], id, props["name"], JSON.generate(feature["geometry"]), JSON.generate(props), point, now, now, rev])
|
|
point
|
|
end
|
|
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|
|
|
# Moved by hand: an imported approximate position (GoogleSaved) is checked now.
|
|
old, old_props = db.get_first_row("SELECT geometry, properties FROM items WHERE id = ?", [id])
|
|
props.delete("approximate") if old && round(JSON.parse(old)) != round(feature["geometry"])
|
|
# What the last import said stays, whatever the popup sent back
|
|
# (upsert_by_source_id tells a hand edit from it).
|
|
imported = old_props && JSON.parse(old_props)["imported"]
|
|
props["imported"] = imported if imported
|
|
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
|
|
|
|
# --- server ⇄ server sync (home ⇄ car) -----------------------------------
|
|
|
|
SYNC_FOLDER_COLUMNS = %w[id parent_id name created_at updated_at deleted_at].freeze
|
|
SYNC_ITEM_COLUMNS = %w[id folder_id parent_id type name geometry properties fingerprint source_path created_at updated_at deleted_at].freeze
|
|
|
|
# Whole rows written after `since`, tombstones included, at most `limit`
|
|
# of each table; "next" is the rev to ask from next time (below "rev"
|
|
# while there's more).
|
|
def sync_changes(since, limit: 500)
|
|
since = Integer(since)
|
|
connect do |db|
|
|
db.transaction do
|
|
rev = db.get_first_value("SELECT rev FROM meta")
|
|
tables = { "folders" => SYNC_FOLDER_COLUMNS, "items" => SYNC_ITEM_COLUMNS }.to_h do |table, columns|
|
|
rows = db.execute("SELECT #{columns.join(', ')}, rev FROM #{table} WHERE rev > ? ORDER BY rev LIMIT ?", [since, limit])
|
|
[table, rows.map { |row| (columns + ["rev"]).zip(row).to_h }]
|
|
end
|
|
full = tables.values.select { |rows| rows.size == limit }.map { |rows| rows.last["rev"] - 1 }
|
|
tables.merge("rev" => rev, "next" => [rev, *full].min)
|
|
end
|
|
end
|
|
end
|
|
|
|
# Takes the other server's rows (sync_changes): one newer than ours —
|
|
# or not here yet — replaces ours, else ours stays (last writer wins by
|
|
# updated_at; an echo of our own change ties and is skipped). Returns
|
|
# the source files (items' source_path) not here yet.
|
|
# ponytail: the losing version isn't kept; a history table if a lost
|
|
# edit ever matters.
|
|
def apply_sync(changes)
|
|
missing = []
|
|
write do |db, rev, _now|
|
|
{ "folders" => SYNC_FOLDER_COLUMNS, "items" => SYNC_ITEM_COLUMNS }.each do |table, columns|
|
|
(changes[table] || []).each do |row|
|
|
ours = db.get_first_value("SELECT updated_at FROM #{table} WHERE id = ?", [row["id"]])
|
|
next if ours && ours >= row["updated_at"].to_s
|
|
|
|
db.execute("INSERT OR REPLACE INTO #{table} (#{columns.join(', ')}, rev) VALUES (#{(['?'] * (columns.size + 1)).join(', ')})",
|
|
[*row.values_at(*columns), rev])
|
|
missing << row if table == "items" && row["source_path"] && !row["deleted_at"] && !File.exist?(source_file(row["type"], row["source_path"]))
|
|
end
|
|
end
|
|
end
|
|
missing
|
|
end
|
|
|
|
# Where an item's source file lives: a legacy layer's in GpxStore,
|
|
# an upload's under sources/.
|
|
# The path comes from the other server too: never outside sources/.
|
|
def source_file(type, source_path)
|
|
return @gpx_store.resolve_file(source_path) if type == "layer"
|
|
|
|
root = File.expand_path(@sources_dir)
|
|
path = File.expand_path(File.join(root, source_path.to_s))
|
|
raise InvalidValue unless path.start_with?("#{root}/")
|
|
|
|
path
|
|
end
|
|
|
|
# An item's source file (tombstoned or not: the other server may still
|
|
# need it), nil without one.
|
|
def item_source(id)
|
|
type, source = connect { |db| db.get_first_row("SELECT type, source_path FROM items WHERE id = ?", [id]) }
|
|
source && source_file(type, source)
|
|
end
|
|
|
|
# An item's type and source_path (where its file belongs), nil without one.
|
|
def source_row(id)
|
|
type, source = connect { |db| db.get_first_row("SELECT type, source_path FROM items WHERE id = ?", [id]) }
|
|
source && { "type" => type, "source_path" => source }
|
|
end
|
|
|
|
# The other server's copy of a source file, written into place.
|
|
def store_source(item, bytes)
|
|
path = source_file(item["type"], item["source_path"])
|
|
FileUtils.mkdir_p(File.dirname(path))
|
|
File.binwrite("#{path}.part", bytes)
|
|
File.rename("#{path}.part", path)
|
|
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/<name>.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 ".tcx" then Tcx.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
|
|
props["name"] = default_name(source) if source && props["name"].to_s.empty? && %w[track route].include?(type)
|
|
fingerprint = Digest::SHA1.hexdigest(JSON.generate([type, props["name"], round(f["geometry"])]))
|
|
if props["source_id"]
|
|
id = upsert_by_source_id(db, target, props, f["geometry"], rev, now)
|
|
keys << "points:#{target || ROOT}" if id
|
|
next
|
|
end
|
|
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
|
|
|
|
# A feature that names where it came from (`source_id`, e.g. a Google
|
|
# saved place's id) is kept once per folder: importing the list again
|
|
# refreshes the point's name and Google's fields, keeping what was
|
|
# changed here (color, icon, a moved position — only an approximate
|
|
# position gives way to an exact one, a renamed or redescribed point
|
|
# keeps its own text). One deleted here stays deleted.
|
|
# Returns the id, nil when skipped.
|
|
IMPORTED_TEXT = %w[name description].freeze
|
|
|
|
def upsert_by_source_id(db, folder, props, geometry, rev, now)
|
|
props = props.merge("imported" => props.slice(*IMPORTED_TEXT))
|
|
row = db.get_first_row("SELECT id, geometry, properties, deleted_at FROM items WHERE folder_id IS ? AND json_extract(properties, '$.source_id') = ?",
|
|
[folder, props["source_id"]])
|
|
unless row
|
|
id = SecureRandom.uuid
|
|
db.execute("INSERT INTO items VALUES (?, ?, NULL, 'point', ?, ?, ?, NULL, NULL, ?, ?, NULL, ?)",
|
|
[id, folder, props["name"], JSON.generate(geometry), JSON.generate(props.except("id")), now, now, rev])
|
|
return id
|
|
end
|
|
id, old_geometry, old_props, deleted = row
|
|
return nil if deleted
|
|
|
|
old = JSON.parse(old_props)
|
|
merged = old.merge(props.except("id", "approximate"))
|
|
# A field differing from what the last import said was edited here.
|
|
# Points imported before "imported" was kept: any difference counts
|
|
# as an edit, the safe guess.
|
|
last = old["imported"] || {}
|
|
IMPORTED_TEXT.each { |f| merged[f] = old[f] if old.key?(f) && old[f] != last.fetch(f, props[f]) }
|
|
exact = old["approximate"] && !props["approximate"]
|
|
merged.delete("approximate") if exact
|
|
new_geometry = exact ? JSON.generate(geometry) : old_geometry
|
|
return id if merged == old && new_geometry == old_geometry
|
|
|
|
db.execute("UPDATE items SET name = ?, geometry = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ?",
|
|
[merged["name"], new_geometry, JSON.generate(merged), now, rev, id])
|
|
id
|
|
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
|