108 lines
4.5 KiB
Ruby
108 lines
4.5 KiB
Ruby
require "net/http"
|
|
require "uri"
|
|
require "ipaddr"
|
|
require "resolv"
|
|
require "cgi"
|
|
|
|
module Maptool
|
|
# A link pasted into the search (the Design canvas' Plan) → a place:
|
|
# { name:, lat:, lng:, url: }, or nil. The coordinates come from the URL
|
|
# itself (Google Maps' @lat,lng / !3d!4d / ?q=, geo:), else from the page
|
|
# it leads to (redirects followed: maps.app.goo.gl): its geo meta tags,
|
|
# JSON-LD, or a map link in it — the way a chat app unfurls a link, one
|
|
# page the user pasted. Only public addresses are fetched (never this
|
|
# server's LAN).
|
|
module LinkPlace
|
|
MAX_BYTES = 2_000_000
|
|
MAX_REDIRECTS = 5
|
|
TIMEOUT_S = 10
|
|
LAT_LNG = /(-?\d{1,2}\.\d+)\s*[,;]\s*(-?\d{1,3}\.\d+)/
|
|
|
|
class Error < StandardError; end
|
|
|
|
def self.resolve(url)
|
|
place = from_url(url)
|
|
return place if place
|
|
|
|
html, final = fetch(url)
|
|
from_url(final) || from_html(html)&.then { |p| p.merge(url: final) }
|
|
end
|
|
|
|
# Coordinates in the link itself.
|
|
def self.from_url(url)
|
|
text = CGI.unescape(url.to_s)
|
|
lat, lng = text.match(/!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)/)&.captures ||
|
|
text.match(/[?&](?:q|query|ll|destination|daddr|center)=(?:loc:)?#{LAT_LNG}/)&.captures ||
|
|
text.match(/@#{LAT_LNG}/)&.captures ||
|
|
text.match(/\Ageo:#{LAT_LNG}/)&.captures ||
|
|
text.match(%r{/place/#{LAT_LNG}})&.captures
|
|
return nil unless lat
|
|
|
|
name = text[%r{/place/([^/@]+)/}, 1]&.tr("+", " ")
|
|
place(name, lat, lng, url)
|
|
end
|
|
|
|
# Coordinates in the page: meta tags, JSON-LD, then a map link.
|
|
def self.from_html(html)
|
|
meta = ->(key) { html[/<meta[^>]+(?:property|name)=["']#{Regexp.escape(key)}["'][^>]*content=["']([^"']+)/i, 1] || html[/<meta[^>]+content=["']([^"']+)["'][^>]*(?:property|name)=["']#{Regexp.escape(key)}["']/i, 1] }
|
|
name = meta.("og:title") || html[%r{<title[^>]*>([^<]+)</title>}i, 1]
|
|
name = CGI.unescapeHTML(name.strip) if name
|
|
lat, lng = [meta.("place:location:latitude") || meta.("og:latitude"), meta.("place:location:longitude") || meta.("og:longitude")]
|
|
lat, lng = (meta.("geo.position") || meta.("ICBM"))&.match(LAT_LNG)&.captures unless lat && lng
|
|
lat, lng = html.match(/"latitude"\s*:\s*"?(-?\d+\.\d+)"?\s*,\s*"longitude"\s*:\s*"?(-?\d+\.\d+)/)&.captures unless lat && lng
|
|
lat, lng = html.scan(%r{https?://(?:www\.)?google\.[a-z.]+/maps[^"'\s<>]*}).lazy.filter_map { |u| from_url(CGI.unescapeHTML(u)) }.first&.values_at(:lat, :lng) unless lat && lng
|
|
lat && lng ? place(name, lat, lng, nil) : nil
|
|
end
|
|
|
|
def self.place(name, lat, lng, url)
|
|
lat = Float(lat)
|
|
lng = Float(lng)
|
|
return nil unless lat.between?(-90, 90) && lng.between?(-180, 180)
|
|
|
|
{ name: name&.strip&.then { |n| n.empty? ? nil : n[0, 160] }, lat: lat, lng: lng, url: url }.compact
|
|
end
|
|
|
|
# [body, final url]; raises Error.
|
|
def self.fetch(url, redirects = MAX_REDIRECTS)
|
|
uri = URI.parse(url)
|
|
raise Error, "only http(s) links" unless %w[http https].include?(uri.scheme) && uri.host
|
|
ip = public_ip(uri.host)
|
|
http = Net::HTTP.new(uri.host, uri.port)
|
|
http.ipaddr = ip # the address checked, not a second lookup
|
|
http.use_ssl = uri.scheme == "https"
|
|
http.open_timeout = http.read_timeout = TIMEOUT_S
|
|
request = Net::HTTP::Get.new(uri, "User-Agent" => "Mozilla/5.0 (maptool link preview)", "Accept" => "text/html")
|
|
http.request(request) do |response|
|
|
case response
|
|
when Net::HTTPRedirection
|
|
raise Error, "too many redirects" if redirects.zero?
|
|
|
|
return fetch(URI.join(url, response["location"]).to_s, redirects - 1)
|
|
when Net::HTTPSuccess
|
|
body = +""
|
|
response.read_body do |chunk|
|
|
body << chunk
|
|
break if body.bytesize > MAX_BYTES
|
|
end
|
|
return [body.force_encoding("UTF-8").scrub, url]
|
|
else
|
|
raise Error, "the page answered #{response.code}"
|
|
end
|
|
end
|
|
rescue URI::InvalidURIError, SocketError, Timeout::Error, SystemCallError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse => e
|
|
raise Error, e.message
|
|
end
|
|
|
|
def self.public_ip(host)
|
|
address = Resolv.getaddress(host)
|
|
ip = IPAddr.new(address)
|
|
raise Error, "not a public address" if ip.private? || ip.loopback? || ip.link_local? || address.start_with?("0.") || ip == IPAddr.new("::") ||
|
|
IPAddr.new("100.64.0.0/10").include?(ip) # CGNAT: Tailscale
|
|
|
|
address
|
|
rescue Resolv::ResolvError
|
|
raise Error, "unknown host #{host}"
|
|
end
|
|
end
|
|
end
|