Google Maps saved lists from a scheduled Google Takeout: hourly check of TAKEOUT_DIR (brick's Drive backup, mounted read-only), the zip with Takeout/Saved/*.csv picked by its central directory (photo parts skipped), each list into Google Maps/<list>; positions decoded offline from the place's S2 feature id and refined by Nominatim, unresolved ones flagged approximate in the popup (cleared when moved by hand); points matched by Google id per folder, so a new export updates them (own color/icon/position kept, deleted stay deleted)
CI / check (push) Successful in 8m56s
CI / deploy (push) Successful in 38s

This commit is contained in:
randy committed 2026-11-25 15:10:30 +01:00
1 parent 261b4c053e
commit 0aee739ac3
9 files changed
+306 -1

No files matched your search

+2
View File
@@ -18,3 +18,5 @@ group :test do
end end
gem "faraday-cookie_jar", "~> 0.0.8" gem "faraday-cookie_jar", "~> 0.0.8"
gem "csv", "~> 3.3"
+3
View File
@@ -7,6 +7,7 @@ GEM
version_gem (~> 1.1, >= 1.1.16) version_gem (~> 1.1, >= 1.1.16)
base64 (0.3.0) base64 (0.3.0)
bigdecimal (4.1.3) bigdecimal (4.1.3)
csv (3.3.7)
domain_name (0.6.20260902) domain_name (0.6.20260902)
drb (2.2.3) drb (2.2.3)
faraday (2.15.1) faraday (2.15.1)
@@ -126,6 +127,7 @@ PLATFORMS
x86_64-linux-musl x86_64-linux-musl
DEPENDENCIES DEPENDENCIES
csv (~> 3.3)
faraday-cookie_jar (~> 0.0.8) faraday-cookie_jar (~> 0.0.8)
minitest (~> 6.0) minitest (~> 6.0)
oauth2 (~> 2.0) oauth2 (~> 2.0)
@@ -144,6 +146,7 @@ CHECKSUMS
base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b
bigdecimal (4.1.3) sha256=61ebe1e5e559bdc3cc6f2c0ee7f427321fc838f59611c294356eb04d6e21cf66 bigdecimal (4.1.3) sha256=61ebe1e5e559bdc3cc6f2c0ee7f427321fc838f59611c294356eb04d6e21cf66
bundler (4.0.20) sha256=7978a8ac648767f5e635bc522445b79e80a52b907a39a36c2d8085ed6bc762ae bundler (4.0.20) sha256=7978a8ac648767f5e635bc522445b79e80a52b907a39a36c2d8085ed6bc762ae
csv (3.3.7) sha256=15a3f16f6628da8664d455eb634e7f22031bcf53044923caf56975109e71b9f8
domain_name (0.6.20260902) sha256=4fac7f8e0a77dc85ec02f6534fdeff38e143d434ab8a86528fe68ca5bc45a042 domain_name (0.6.20260902) sha256=4fac7f8e0a77dc85ec02f6534fdeff38e143d434ab8a86528fe68ca5bc45a042
drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373 drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373
faraday (2.15.1) sha256=8708154deda739c5e86cc42b74960e23e8491fce0eba9e11639a6a34b1ac288f faraday (2.15.1) sha256=8708154deda739c5e86cc42b74960e23e8491fce0eba9e11639a6a34b1ac288f
+18
View File
@@ -8,6 +8,7 @@ require_relative "lib/maptool/gpx"
require_relative "lib/maptool/fit" require_relative "lib/maptool/fit"
require_relative "lib/maptool/gpx_store" require_relative "lib/maptool/gpx_store"
require_relative "lib/maptool/library" require_relative "lib/maptool/library"
require_relative "lib/maptool/google_saved"
require_relative "lib/maptool/routing" require_relative "lib/maptool/routing"
require_relative "lib/maptool/gpsd_client" require_relative "lib/maptool/gpsd_client"
require_relative "lib/maptool/mqtt_client" require_relative "lib/maptool/mqtt_client"
@@ -127,6 +128,23 @@ module Maptool
rescue StandardError => e rescue StandardError => e
warn "library reparse failed: #{e.message}" warn "library reparse failed: #{e.message}"
end end
# Google Maps saved lists from a scheduled Google Takeout (product
# "Saved"), synced into TAKEOUT_DIR (mounted read-only, see
# docker-compose.yaml): checked hourly, a new export is imported into
# Tracks & Points under "Google Maps/<list>" (GoogleSaved). Unset = off.
TAKEOUT_DIR = ENV.fetch("TAKEOUT_DIR", "")
unless TAKEOUT_DIR.empty? || test?
Thread.new do
loop do
count = GoogleSaved.import_takeout(TAKEOUT_DIR, library: LIBRARY, state_path: File.join(DATA_DIR, "takeout_imported"))
warn "takeout: imported #{count} saved places" if count
rescue StandardError => e
warn "takeout import failed: #{e.class}: #{e.message}"
ensure
sleep 3600
end
end
end
LIVETRACK_STORE = LiveTrackStore.new(File.join(DATA_DIR, "livetrack.json")) LIVETRACK_STORE = LiveTrackStore.new(File.join(DATA_DIR, "livetrack.json"))
# Not under DATA_DIR: unlike everything else there (uploads, PMTiles, # Not under DATA_DIR: unlike everything else there (uploads, PMTiles,
+10
View File
@@ -61,6 +61,9 @@ services:
KIWIX_URL: "http://kiwix:8080" KIWIX_URL: "http://kiwix:8080"
# The valhalla service below, same story as KIWIX_URL. # The valhalla service below, same story as KIWIX_URL.
VALHALLA_URL: "http://valhalla:8002" VALHALLA_URL: "http://valhalla:8002"
# Google Takeout exports (the "Saved" lists), mounted below; app.rb
# imports a new one hourly. Remove both lines to turn it off.
TAKEOUT_DIR: /app/takeout
volumes: volumes:
# Uploaded GPX files and the offline PMTiles extract — kept outside # Uploaded GPX files and the offline PMTiles extract — kept outside
# the image so a rebuild/redeploy doesn't wipe them (see # the image so a rebuild/redeploy doesn't wipe them (see
@@ -80,6 +83,13 @@ services:
# recursively relabels that file to maptool's own private label, # recursively relabels that file to maptool's own private label,
# locking kiwix out of it (and kiwix's :Z would do the same back). # locking kiwix out of it (and kiwix's :Z would do the same back).
- ./data:/app/data:z - ./data:/app/data:z
# Where the Google Drive backup syncs the scheduled Takeout (a plain
# directory; changed files get moved to ../../old/, so the bind stays
# valid). Read-only. Shared :z like data/ above: brick enforces
# SELinux and the backup tree is unlabeled_t, unreadable for a
# container; the root sync job is unaffected by the relabel and new
# files inherit the directory's label.
- /srv/backup/gdrive/my-drive/current/Takeout:/app/takeout:ro,z
# Fakes a GNSS fix (a loop around Bratislava, see # Fakes a GNSS fix (a loop around Bratislava, see
# bin/gnss_simulator.rb/docs/development.adoc) since there's no real # bin/gnss_simulator.rb/docs/development.adoc) since there's no real
+150
View File
@@ -0,0 +1,150 @@
require "csv"
require "json"
require "net/http"
require "uri"
require "zip"
module Maptool
# Google Maps saved lists ("Want to go", "Norway 2026", …) from a Google
# Takeout export: product "Saved", one Takeout/Saved/<list>.csv each with
# Title,Note,URL,Tags,Comment. The URL carries no coordinates, only the
# place's feature id (…/data=!4m2!3m1!1s0x45de3cbf60603ce7:0x82f2b236d153558f),
# whose first half is an S2 cell id around the place: decoded offline it's
# within a few hundred metres to a few km (the low bits look hashed), then
# refined by a Nominatim name search around it. A place Nominatim can't
# find keeps the decoded spot and `approximate: true`.
module GoogleSaved
FEATURE_ID = /!1s(0x\h+):(0x\h+)/
SAVED_ENTRY = %r{\ATakeout/Saved/[^/]+\.csv\z}
NOMINATIM = "https://nominatim.openstreetmap.org/search"
# Search box around the decoded spot, degrees (~10 km).
REFINE_RADIUS = 0.1
# A CSV Google wrote (header Title,…,URL)? Other Takeout CSVs aren't lists.
def self.saved_list?(text)
text.sub(/\A/, "").start_with?("Title,Note,URL")
end
# CSV text → GeoJSON point features, unrefined. `source_id` is Google's
# feature id: Library updates a point with the same one in the same
# folder instead of adding it again.
def self.features(text)
CSV.parse(text.sub(/\A/, ""), headers: true).filter_map do |row|
url = row["URL"].to_s
match = url.match(FEATURE_ID)
coords = url[%r{/maps/search/(-?\d+\.\d+),[+\s]*(-?\d+\.\d+)}] && [Regexp.last_match(2).to_f, Regexp.last_match(1).to_f]
approximate = coords.nil?
coords ||= match && s2_lng_lat(match[1].to_i(16))
next unless coords
name = row["Title"].to_s.strip
name = "Saved place" if name.empty?
# One text the point popup shows and linkifies: the list's note and
# comment, then the way back to the place in Google Maps.
description = [row["Note"], row["Comment"], "Google Maps: #{url}"].map { |t| t.to_s.strip }.reject(&:empty?).join("\n\n")
props = { "name" => name, "description" => description,
"source_id" => (match ? "google:#{match[1]}:#{match[2]}" : "google:#{url}"),
"approximate" => (true if approximate) }.compact
{ "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => coords.map { |c| c.round(6) } }, "properties" => props }
end
end
# Moves each approximate feature onto `lookup.(name, lng, lat)` → [lng,
# lat] or nil; one that isn't found stays approximate.
def self.refine!(features, lookup: method(:nominatim))
features.each do |feature|
props = feature["properties"]
next unless props["approximate"]
found = lookup.call(props["name"], *feature["geometry"]["coordinates"])
next unless found
feature["geometry"]["coordinates"] = found.map { |c| c.round(6) }
props.delete("approximate")
end
end
# Nominatim's usage policy: at most 1 request a second, an identifying
# User-Agent.
def self.nominatim(name, lng, lat)
sleep 1
r = REFINE_RADIUS
uri = URI(NOMINATIM)
uri.query = URI.encode_www_form(q: name, format: "jsonv2", limit: 1, bounded: 1,
viewbox: [lng - r, lat + r, lng + r, lat - r].join(","))
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 20) do |http|
http.request(Net::HTTP::Get.new(uri, "User-Agent" => "maptool (Google saved lists import)"))
end
hit = response.is_a?(Net::HTTPSuccess) && JSON.parse(response.body).first
hit && [hit["lon"].to_f, hit["lat"].to_f]
rescue JSON::ParserError, Net::OpenTimeout, Net::ReadTimeout, SocketError, SystemCallError, OpenSSL::SSL::SSLError
nil
end
# Each Takeout zip in `dir` holding saved lists, newest first: only the
# zip's central directory is read, so the multi-GB photo parts of the
# same export are cheap to skip.
def self.takeout_zips(dir)
Dir.glob(File.join(dir, "*.zip")).select do |path|
Zip::File.open(path) { |zip| zip.entries.any? { |e| e.name.match?(SAVED_ENTRY) } }
rescue Zip::Error
false
end.sort_by { |path| -File.mtime(path).to_f }
end
# { "<list name>" => csv text } for the zip's saved lists.
def self.lists(zip_path)
Zip::File.open(zip_path) do |zip|
zip.entries.select { |e| e.name.match?(SAVED_ENTRY) }
.to_h { |e| [File.basename(e.name, ".csv"), e.get_input_stream.read.force_encoding("UTF-8")] }
.select { |_, text| saved_list?(text) }
end
end
# Imports the newest Takeout zip in `dir` with saved lists, once (its
# name, size and mtime are remembered in `state_path`), each list into
# "<folder>/<list name>". Returns the number of places, nil if nothing new.
def self.import_takeout(dir, library:, state_path:, folder: "Google Maps", lookup: method(:nominatim))
zip = takeout_zips(dir).first or return nil
stamp = [File.basename(zip), File.size(zip), File.mtime(zip).to_i].join(" ")
return nil if File.exist?(state_path) && File.read(state_path) == stamp
count = lists(zip).sum do |list, text|
places = features(text)
next 0 if places.empty? # Images / Saved for later: no places, no folder
refine!(places, lookup: lookup)
library.import_features(places, folder: "#{folder}/#{list.tr('/', '_')}")
places.size
end
File.write(state_path, stamp)
count
end
# S2 cell id → [lng, lat] of the cell's center (the S2 library's
# face/Hilbert-curve decoding, quadratic projection).
POS_TO_IJ = [[0, 1, 3, 2], [0, 2, 3, 1], [3, 2, 0, 1], [3, 1, 0, 2]].freeze
POS_TO_ORIENTATION = [1, 0, 0, 3].freeze
def self.s2_lng_lat(id)
face = id >> 61
i = j = 0
orientation = face & 1
30.times do |k|
bits = (id >> (59 - 2 * k)) & 3
ij = POS_TO_IJ[orientation][bits]
i = (i << 1) | (ij >> 1)
j = (j << 1) | (ij & 1)
orientation ^= POS_TO_ORIENTATION[bits]
end
uv = lambda do |n|
s = (n + 0.5) / (1 << 30)
s >= 0.5 ? (4 * s * s - 1) / 3.0 : (1 - 4 * (1 - s) * (1 - s)) / 3.0
end
u = uv.call(i)
v = uv.call(j)
x, y, z = [[1, u, v], [-u, 1, v], [-u, -v, 1], [-1, -v, -u], [v, -1, -u], [v, u, -1]][face]
[Math.atan2(y, x) * 180 / Math::PI, Math.atan2(z, Math.hypot(x, y)) * 180 / Math::PI]
end
end
end
+44
View File
@@ -234,6 +234,12 @@ module Maptool
add_features(features, folder, source: relative) add_features(features, folder, source: relative)
end 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 # 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". # the file's, so the tree doesn't fill up with "Track".
def default_name(source) def default_name(source)
@@ -312,6 +318,9 @@ module Maptool
props = (feature["properties"] || {}).except("id") props = (feature["properties"] || {}).except("id")
write do |db, rev, now| write do |db, rev, now|
# Moved by hand: an imported approximate position (GoogleSaved) is checked now.
old = db.get_first_value("SELECT geometry FROM items WHERE id = ?", [id])
props.delete("approximate") if old && round(JSON.parse(old)) != round(feature["geometry"])
db.execute("UPDATE items SET name = ?, geometry = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ? AND deleted_at IS NULL", 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]) [props["name"], JSON.generate(feature["geometry"]), JSON.generate(props), now, rev, id])
raise NotFound if db.changes.zero? raise NotFound if db.changes.zero?
@@ -598,6 +607,11 @@ module Maptool
props = (f["properties"] || {}).compact props = (f["properties"] || {}).compact
props["name"] = default_name(source) if source && props["name"].to_s.empty? && %w[track route].include?(type) 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"])])) 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]) existing = db.get_first_value("SELECT id FROM items WHERE folder_id IS ? AND fingerprint = ? AND deleted_at IS NULL", [target, fingerprint])
id = existing id = existing
unless existing unless existing
@@ -615,6 +629,36 @@ module Maptool
keys.uniq keys.uniq
end 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). One deleted here stays deleted.
# Returns the id, nil when skipped.
def upsert_by_source_id(db, folder, props, geometry, rev, now)
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"))
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 = ?",
[props["name"], new_geometry, JSON.generate(merged), now, rev, id])
id
end
def item_type(feature) def item_type(feature)
geometry = feature.dig("geometry", "type").to_s geometry = feature.dig("geometry", "type").to_s
props = feature["properties"] || {} props = feature["properties"] || {}
+6
View File
@@ -1966,6 +1966,12 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr
height: 100%; height: 100%;
} }
.gpx-popup__approximate {
margin: 4px 0;
font-size: 12px;
color: #a35d00;
}
.gpx-popup__time { .gpx-popup__time {
color: #888; color: #888;
font-size: 12px; font-size: 12px;
+3 -1
View File
@@ -1505,7 +1505,7 @@ function nodeKeys(node) {
// for — see _registerPointInteractivity) adds Edit/Delete buttons; the // for — see _registerPointInteractivity) adds Edit/Delete buttons; the
// click handling for them lives in _wireNoteActions, not here, since this // click handling for them lives in _wireNoteActions, not here, since this
// only builds markup, it has no map/store access of its own. // only builds markup, it has no map/store access of its own.
function popupHtml({ name, description, time, category, photos, icon }, { editable = false, movable = false } = {}) { function popupHtml({ name, description, time, category, photos, icon, approximate }, { editable = false, movable = false } = {}) {
const parts = []; const parts = [];
if (name) { if (name) {
const glyph = icon && POI_ICONS[icon] ? `<span class="gpx-popup__header-icon">${POI_ICONS[icon]}</span>` : ""; const glyph = icon && POI_ICONS[icon] ? `<span class="gpx-popup__header-icon">${POI_ICONS[icon]}</span>` : "";
@@ -1513,6 +1513,8 @@ function popupHtml({ name, description, time, category, photos, icon }, { editab
} }
if (category) parts.push(`<p class="gpx-popup__category">${escapeHtml(category)}</p>`); if (category) parts.push(`<p class="gpx-popup__category">${escapeHtml(category)}</p>`);
if (photos?.length > 0) parts.push(formatPhotos(photos)); if (photos?.length > 0) parts.push(formatPhotos(photos));
// Google saved places Nominatim couldn't pin down (GoogleSaved).
if (approximate) parts.push(`<p class="gpx-popup__approximate">≈ Approximate position, check it</p>`);
// A Note's description is self-authored by the (logged-in) viewer, not // A Note's description is self-authored by the (logged-in) viewer, not
// uploaded/untrusted like every other description here — formatDescription // uploaded/untrusted like every other description here — formatDescription
// is deliberately left alone for that untrusted case (see // is deliberately left alone for that untrusted case (see
+70
View File
@@ -0,0 +1,70 @@
require_relative "test_helper"
require "maptool/library"
require "maptool/google_saved"
require "zip"
class GoogleSavedTest < Minitest::Test
CSV_TEXT = <<~CSV
Title,Note,URL,Tags,Comment
,,,,
Reine,"Fishing village, red huts",https://www.google.com/maps/place/Reine/data=!4m2!3m1!1s0x45de3cbf60603ce7:0x82f2b236d153558f,,
Somewhere,,"https://www.google.com/maps/search/48.1486,+17.1077",,
CSV
def setup
@dir = Dir.mktmpdir
end
def teardown
FileUtils.remove_entry(@dir)
end
def test_the_place_id_decodes_near_the_place
lng, lat = Maptool::GoogleSaved.s2_lng_lat(0x45de3cbf60603ce7)
assert_in_delta 67.932, lat, 0.02 # Reine, Lofoten
assert_in_delta 13.089, lng, 0.02
end
def test_a_list_becomes_points_with_their_google_id
reine, spot = Maptool::GoogleSaved.features(CSV_TEXT)
assert_equal "Reine", reine["properties"]["name"]
assert_match(/\AFishing village, red huts\n\nGoogle Maps: https:/, reine["properties"]["description"])
assert_equal "google:0x45de3cbf60603ce7:0x82f2b236d153558f", reine["properties"]["source_id"]
assert reine["properties"]["approximate"]
assert_equal [17.1077, 48.1486], spot["geometry"]["coordinates"]
refute spot["properties"].key?("approximate")
end
def test_importing_a_takeout_again_updates_instead_of_duplicating
library = Maptool::Library.new(File.join(@dir, "library.sqlite"), gpx_store: Maptool::GpxStore.new(File.join(@dir, "gpx")),
sources_dir: File.join(@dir, "sources"))
takeout = File.join(@dir, "takeout")
FileUtils.mkdir_p(takeout)
write_zip = lambda do |name, text|
Zip::File.open(File.join(takeout, name), create: true) { |zip| zip.get_output_stream("Takeout/Saved/Norway 2026.csv") { |io| io.write(text) } }
end
state = File.join(@dir, "state")
not_found = ->(*) {}
write_zip.call("takeout-1.zip", CSV_TEXT)
assert_equal 2, Maptool::GoogleSaved.import_takeout(takeout, library: library, state_path: state, lookup: not_found)
assert_nil Maptool::GoogleSaved.import_takeout(takeout, library: library, state_path: state, lookup: not_found), "same zip twice"
points = -> { JSON.parse(library.geojson(library.tree["children"][0]["children"][0]["children"][0]["path"]))["features"] }
reine = points.call.find { |f| f["properties"]["name"] == "Reine" }
reine["properties"]["color"] = "#ff0000"
library.update_feature("points:x", reine["properties"]["id"], reine)
sleep 1.1 # a newer export (mtime) with a changed note, now found by name
write_zip.call("takeout-2.zip", CSV_TEXT.sub("red huts", "rorbuer"))
Maptool::GoogleSaved.import_takeout(takeout, library: library, state_path: state, lookup: ->(*) { [13.0897, 67.9322] })
features = points.call
assert_equal 2, features.size
reine = features.find { |f| f["properties"]["name"] == "Reine" }
assert_match(/\AFishing village, rorbuer/, reine["properties"]["description"])
assert_equal "#ff0000", reine["properties"]["color"], "own changes kept"
assert_equal [13.0897, 67.9322], reine["geometry"]["coordinates"], "approximate spot replaced by the exact one"
refute reine["properties"].key?("approximate")
end
end