1 # frozen_string_literal: true
3 # The OSM module provides support functions for OSM.
6 require "rexml/parsers/sax2parser"
10 # The base class for API Errors.
11 class APIError < RuntimeError
12 def initialize(message = "Generic API Error")
17 :internal_server_error
21 # Raised when access is denied.
22 class APIAccessDenied < APIError
24 super("Access denied")
32 # Raised when an API object is not found.
33 class APINotFoundError < APIError
35 super("Object not found")
43 # Raised when a precondition to an API action fails sanity check.
44 class APIPreconditionFailedError < APIError
45 def initialize(message = "")
46 super("Precondition failed: #{message}")
54 # Raised when to delete an already-deleted object.
55 class APIAlreadyDeletedError < APIError
56 def initialize(type = "object", id = "")
60 super("The #{type} with the id #{id} has already been deleted")
63 attr_reader :type, :id
70 # Raised when the user logged in isn't the same as the changeset
71 class APIUserChangesetMismatchError < APIError
73 super("The user doesn't own that changeset")
81 # Raised when the changeset provided is already closed
82 class APIChangesetAlreadyClosedError < APIError
83 def initialize(changeset)
84 @changeset = changeset
86 super("The changeset #{changeset.id} was closed at #{changeset.closed_at}")
89 attr_reader :changeset
96 # Raised when the changeset provided is not yet closed
97 class APIChangesetNotYetClosedError < APIError
98 def initialize(changeset)
99 @changeset = changeset
101 super("The changeset #{changeset.id} is not yet closed.")
104 attr_reader :changeset
111 # Raised when a user is already subscribed to the changeset
112 class APIChangesetAlreadySubscribedError < APIError
113 def initialize(changeset)
114 @changeset = changeset
116 super("You are already subscribed to changeset #{changeset.id}.")
119 attr_reader :changeset
126 # Raised when a user is not subscribed to the changeset
127 class APIChangesetNotSubscribedError < APIError
128 def initialize(changeset)
129 @changeset = changeset
131 super("You are not subscribed to changeset #{changeset.id}.")
134 attr_reader :changeset
141 # Raised when a change is expecting a changeset, but the changeset doesn't exist
142 class APIChangesetMissingError < APIError
144 super("You need to supply a changeset to be able to make a change")
152 # Raised when a diff is uploaded containing many changeset IDs which don't match
153 # the changeset ID that the diff was uploaded to.
154 class APIChangesetMismatchError < APIError
155 def initialize(provided, allowed)
156 super("Changeset mismatch: Provided #{provided} but only #{allowed} is allowed")
164 # Raised when a diff upload has an unknown action. You can only have create,
166 class APIChangesetActionInvalid < APIError
167 def initialize(provided)
168 super("Unknown action #{provided}, choices are create, modify, delete")
176 # Raised when bad XML is encountered which stops things parsing as
178 class APIBadXMLError < APIError
179 def initialize(model, xml, message = "")
180 super("Cannot parse valid #{model} from xml string #{xml}. #{message}")
188 # Raised when the provided version is not equal to the latest in the db.
189 class APIVersionMismatchError < APIError
190 def initialize(id, type, provided, latest)
196 super("Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}")
199 attr_reader :provided, :latest, :id, :type
206 # raised when a two tags have a duplicate key string in an element.
207 # this is now forbidden by the API.
208 class APIDuplicateTagsError < APIError
209 def initialize(type, id, tag_key)
214 super("Element #{type}/#{id} has duplicate tags with key #{tag_key}")
217 attr_reader :type, :id, :tag_key
224 # Raised when a way has more than the configured number of way nodes.
225 # This prevents ways from being to long and difficult to work with
226 class APITooManyWayNodesError < APIError
227 def initialize(id, provided, max)
228 super("You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed")
235 attr_reader :id, :provided, :max
242 # Raised when a relation has more than the configured number of relation members.
243 # This prevents relations from being too complex and difficult to work with
244 class APITooManyRelationMembersError < APIError
245 def initialize(id, provided, max)
246 super("You tried to add #{provided} members to relation #{id}, however only #{max} are allowed")
253 attr_reader :id, :provided, :max
261 # raised when user input couldn't be parsed
262 class APIBadUserInput < APIError
269 # raised when bounding box is invalid
270 class APIBadBoundingBox < APIError
277 # raised when an API call is made using a method not supported on that URI
278 class APIBadMethodError < APIError
279 def initialize(supported_method)
280 super("Only method #{supported_method} is supported on this URI")
289 # raised when an API call takes too long
290 class APITimeoutError < APIError
292 super("Request timed out")
301 # raised when someone tries to redact a current version of
302 # an element - only historical versions can be redacted.
303 class APICannotRedactError < APIError
305 super("Cannot redact current version of element, only historical versions may be redacted.")
313 # Raised when the note provided is already closed
314 class APINoteAlreadyClosedError < APIError
318 super("The note #{note.id} was closed at #{note.closed_at}")
328 # Raised when the note provided is already open
329 class APINoteAlreadyOpenError < APIError
333 super("The note #{note.id} is already open")
343 # raised when a two preferences have a duplicate key string.
344 class APIDuplicatePreferenceError < APIError
348 super("Duplicate preferences with key #{key}")
358 # Raised when a rate limit is exceeded
359 class APIRateLimitExceeded < APIError
361 super("Rate limit exceeded")
369 # Raised when a size limit is exceeded
370 class APISizeLimitExceeded < APIError
372 super("Size limit exceeded")
380 # Helper methods for going to/from mercator and lat/lng.
384 # init me with your bounding box and the size of your image
385 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
386 xsize = xsheet(max_lon) - xsheet(min_lon)
387 ysize = ysheet(max_lat) - ysheet(min_lat)
388 xscale = xsize / width
389 yscale = ysize / height
390 scale = [xscale, yscale].max
392 xpad = (width * scale) - xsize
393 ypad = (height * scale) - ysize
398 @tx = xsheet(min_lon) - (xpad / 2)
399 @ty = ysheet(min_lat) - (ypad / 2)
401 @bx = xsheet(max_lon) + (xpad / 2)
402 @by = ysheet(max_lat) + (ypad / 2)
405 # the following two functions will give you the x/y on the entire sheet
408 log(tan((PI / 4) + (lat * PI / 180 / 2))) / (PI / 180)
415 # and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
416 # If the bbox has no extent, return the centre of the image to avoid dividing by zero.
419 return @height / 2 if (@by - @ty).zero?
421 @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
425 return @width / 2 if (@bx - @tx).zero?
427 ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
434 # initialise with a base position
435 def initialize(lat, lon)
436 @lat = lat * PI / 180
437 @lon = lon * PI / 180
440 # get the distance from the base position to a given position
441 def distance(lat, lon)
444 6372.795 * 2 * asin(sqrt((sin((lat - @lat) / 2)**2) + (cos(@lat) * cos(lat) * (sin((lon - @lon) / 2)**2))))
447 # get the worst case bounds for a given radius from the base position
449 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2))
452 lonradius = 2 * asin(sqrt((sin(radius / 6372.795 / 2)**2) / (cos(@lat)**2)))
453 rescue Errno::EDOM, Math::DomainError
457 minlat = [(@lat - latradius) * 180 / PI, -90].max
458 maxlat = [(@lat + latradius) * 180 / PI, 90].min
459 minlon = [(@lon - lonradius) * 180 / PI, -180].max
460 maxlon = [(@lon + lonradius) * 180 / PI, 180].min
462 BoundingBox.new(minlon, minlat, maxlon, maxlat)
465 # get the SQL to use to calculate distance
466 def sql_for_distance(lat_field, lon_field)
467 "6372.795 * 2 * asin(sqrt(power(sin((radians(#{lat_field}) - #{@lat}) / 2), 2) + cos(#{@lat}) * cos(radians(#{lat_field})) * power(sin((radians(#{lon_field}) - #{@lon})/2), 2)))"
473 doc = XML::Document.new
474 doc.encoding = XML::Encoding::UTF_8
475 root = XML::Node.new "osm"
476 xml_root_attributes.each do |k, v|
483 def xml_root_attributes
484 { "version" => Settings.api_version,
485 "generator" => Settings.generator,
486 "copyright" => Settings.copyright_owner,
487 "attribution" => Settings.attribution_url,
488 "license" => Settings.license_url }
492 def self.ip_to_country(ip_address)
493 ipinfo = maxmind_database.lookup(ip_address) if Settings.key?(:maxmind_database)
495 return ipinfo.country.iso_code if ipinfo&.found?
500 def self.ip_location(ip_address)
501 code = OSM.ip_to_country(ip_address)
503 if code && country = Country.find(code)
504 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
510 # Parse a float, raising a specified exception on failure
511 def self.parse_float(str, klass, *)
517 # Construct a random token of a given length
518 def self.make_token(length = 24)
519 SecureRandom.urlsafe_base64(length)
522 # Return an SQL fragment to select a given area of the globe
523 def self.sql_for_area(bbox, prefix = nil)
524 tilesql = QuadTile.sql_for_area(bbox, prefix)
525 bbox = bbox.to_scaled
527 "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " \
528 "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
531 # Return the terms and conditions text for a given country
532 def self.legal_text_for_country(country_code)
533 file_name = Rails.root.join("config", "legales", "#{country_code}.yml")
534 file_name = Rails.root.join("config", "legales", "#{Settings.default_legale}.yml") unless File.exist? file_name
535 YAML.load_file(file_name).transform_values!(&:html_safe)
538 # Return the HTTP client to use
540 @http_client ||= Faraday.new(:request => { :timeout => 15 },
541 :headers => { :user_agent => Settings.server_url })
544 # Return the MaxMindDB database handle
545 def self.maxmind_database
546 @maxmind_database ||= MaxMindDB.new(Settings.maxmind_database) if Settings.key?(:maxmind_database)