require "json" require_relative "gpx" require_relative "fit" require_relative "kiwix" require_relative "library" require_relative "places" require_relative "pmtiles_builder" module Maptool # Server-side half of the search box (public/js/search.js): every saved # layer (shown on the map or not), offline hiking trails, the offline # place-name index (Places) and the offline Wikipedia (Kiwix). Online # providers (Nominatim) are queried by the browser itself, so this route # keeps working with no uplink at all. # # A source is a name -> lambda(words, ctx) returning results, each capped # at LIMIT on its own so one busy source can't crowd out the rest — the # LIMIT nearest to the map center when there is one: every result then # carries distance_km (shown) and score (sorted by; distance, except a # settlement counts as closer, see Places::DISTANCE_WEIGHT). ctx # carries :text, :library, :data_dir, :center ([lat, lng] or nil) and # :kiwix_url. `ref` in a result is what the browser needs to act on it # (switch a layer on, open an article). module Search LIMIT = 50 KIWIX_LIMIT = 10 # each result costs kiwix-serve one more page fetch, see Kiwix.search SOURCES = { "layers" => lambda do |words, ctx| scan(words, "layers", ctx[:library].nodes) end, "hiking_trails" => lambda do |words, ctx| countries = PmtilesBuilder.hiking_trails_countries(ctx[:data_dir]).map do |code| path = PmtilesBuilder.hiking_trails_country_path(ctx[:data_dir], code) ["Hiking trails #{code}", code, File.mtime(path), -> { File.read(path) }] end scan(words, "hiking_trails", countries) end, "places" => lambda do |words, ctx| PmtilesBuilder.places_countries(ctx[:data_dir]).flat_map do |code| Places.search(PmtilesBuilder.places_country_path(ctx[:data_dir], code), words, center: ctx[:center], limit: LIMIT).map do |place| label = [place[:kind], "Offline map #{code}"].reject(&:empty?).join(" · ") place.merge(source: "places", source_label: label, ref: code) end end end, "kiwix" => lambda do |_words, ctx| Kiwix.search(ctx[:kiwix_url], ctx[:text], limit: KIWIX_LIMIT).map do |article| { name: article[:title], bbox: article[:position] && (article[:position] * 2), source: "kiwix", source_label: "Wikipedia", ref: article[:link] } end end, }.freeze # ref => [stamp, entries] — a country's hiking-trails file runs to tens # of MB, so it's parsed once per change (its mtime, a library node's # rev), not once per keystroke. # ponytail: unbounded in-memory cache, fine for a handful of layer files. @cache = {} def self.query(text, library:, data_dir:, sources: SOURCES.keys, center: nil, kiwix_url: "") words = normalize(text).split return [] if words.empty? ctx = { text: text.to_s.strip, library: library, data_dir: data_dir, center: center, kiwix_url: kiwix_url.to_s } (sources & SOURCES.keys).flat_map do |source| results = SOURCES[source].call(words, ctx) results = nearest_first(results, center) if center results.first(LIMIT).map { |result| result.except(:importance) } end end # Results without a position (a Wikipedia article with no coordinates) # go last. def self.nearest_first(results, center) results.each do |result| next unless (bbox = result[:bbox]) result[:distance_km] = haversine_km(center, [(bbox[1] + bbox[3]) / 2.0, (bbox[0] + bbox[2]) / 2.0]).round(1) result[:score] = result[:distance_km] * Places::DISTANCE_WEIGHT[result[:importance]] end results.sort_by { |result| result[:score] || Float::INFINITY } end def self.haversine_km((lat1, lng1), (lat2, lng2)) rad = Math::PI / 180 a = (Math.sin((lat2 - lat1) * rad / 2)**2) + (Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * (Math.sin((lng2 - lng1) * rad / 2)**2)) 2 * 6371.0 * Math.asin(Math.sqrt(a)) end # files: [label, ref, stamp, reader] — every matching feature of each, # found in memory (all of them, so query can pick the nearest). def self.scan(words, source, files) files.flat_map do |label, ref, stamp, read| entries(ref, stamp, label, read).filter_map do |entry| entry.except(:text).merge(source: source, source_label: label, ref: ref) if words.all? { |word| entry[:text].include?(word) } end end end # Lowercased, diacritics and apostrophes stripped — "kosice" finds # "Košice", "mcdonalds" finds "McDonald's" (see Places.row's extra). def self.normalize(text) text.to_s.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").delete(Places::APOSTROPHES).downcase end def self.entries(ref, stamp, label, read) cached = @cache[ref] return cached[1] if cached && cached[0] == stamp entries = begin JSON.parse(read.call).fetch("features", []).filter_map { |feature| entry(feature, label) } rescue JSON::ParserError, Gpx::ParseError, Fit::ParseError, Errno::ENOENT, Library::NotFound [] end @cache[ref] = [stamp, entries] entries end def self.entry(feature, fallback_name) coords = feature.dig("geometry", "coordinates") return nil unless coords.is_a?(Array) && !coords.empty? props = feature["properties"] || {} name = props["name"].to_s.strip name = fallback_name if name.empty? lngs, lats = Places.positions(coords).map { |p| p.first(2) }.transpose { name: name, kind: props["kind"] || feature.dig("geometry", "type"), bbox: [lngs.min, lats.min, lngs.max, lats.max], text: normalize("#{name} #{props["description"]}"), } end end end