Files
maptool/lib/maptool/google_saved.rb
T

151 lines
6.5 KiB
Ruby
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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