1 # The OSM module provides support functions for OSM.
4 require "rexml/parsers/sax2parser"
8 if defined?(SystemTimer)
15 # The base class for API Errors.
16 class APIError < RuntimeError
17 def initialize(message = "Generic API Error")
22 :internal_server_error
26 # Raised when access is denied.
27 class APIAccessDenied < APIError
37 # Raised when an API object is not found.
38 class APINotFoundError < APIError
40 super "Object not found"
48 # Raised when a precondition to an API action fails sanity check.
49 class APIPreconditionFailedError < APIError
50 def initialize(message = "")
51 super "Precondition failed: #{message}"
59 # Raised when to delete an already-deleted object.
60 class APIAlreadyDeletedError < APIError
61 def initialize(object = "object", object_id = "")
63 @object_id = object_id
65 super "The #{object} with the id #{object_id} has already been deleted"
68 attr_reader :object, :object_id
75 # Raised when the user logged in isn't the same as the changeset
76 class APIUserChangesetMismatchError < APIError
78 super "The user doesn't own that changeset"
86 # Raised when the changeset provided is already closed
87 class APIChangesetAlreadyClosedError < APIError
88 def initialize(changeset)
89 @changeset = changeset
91 super "The changeset #{changeset.id} was closed at #{changeset.closed_at}"
94 attr_reader :changeset
101 # Raised when the changeset provided is not yet closed
102 class APIChangesetNotYetClosedError < APIError
103 def initialize(changeset)
104 @changeset = changeset
106 super "The changeset #{changeset.id} is not yet closed."
109 attr_reader :changeset
116 # Raised when a user is already subscribed to the changeset
117 class APIChangesetAlreadySubscribedError < APIError
118 def initialize(changeset)
119 @changeset = changeset
121 super "You are already subscribed to changeset #{changeset.id}."
124 attr_reader :changeset
131 # Raised when a user is not subscribed to the changeset
132 class APIChangesetNotSubscribedError < APIError
133 def initialize(changeset)
134 @changeset = changeset
136 super "You are not subscribed to changeset #{changeset.id}."
139 attr_reader :changeset
146 # Raised when a change is expecting a changeset, but the changeset doesn't exist
147 class APIChangesetMissingError < APIError
149 super "You need to supply a changeset to be able to make a change"
157 # Raised when a diff is uploaded containing many changeset IDs which don't match
158 # the changeset ID that the diff was uploaded to.
159 class APIChangesetMismatchError < APIError
160 def initialize(provided, allowed)
161 super "Changeset mismatch: Provided #{provided} but only #{allowed} is allowed"
169 # Raised when a diff upload has an unknown action. You can only have create,
171 class APIChangesetActionInvalid < APIError
172 def initialize(provided)
173 super "Unknown action #{provided}, choices are create, modify, delete"
181 # Raised when bad XML is encountered which stops things parsing as
183 class APIBadXMLError < APIError
184 def initialize(model, xml, message = "")
185 super "Cannot parse valid #{model} from xml string #{xml}. #{message}"
193 # Raised when the provided version is not equal to the latest in the db.
194 class APIVersionMismatchError < APIError
195 def initialize(id, type, provided, latest)
201 super "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
204 attr_reader :provided, :latest, :id, :type
211 # raised when a two tags have a duplicate key string in an element.
212 # this is now forbidden by the API.
213 class APIDuplicateTagsError < APIError
214 def initialize(type, id, tag_key)
219 super "Element #{type}/#{id} has duplicate tags with key #{tag_key}"
222 attr_reader :type, :id, :tag_key
229 # Raised when a way has more than the configured number of way nodes.
230 # This prevents ways from being to long and difficult to work with
231 class APITooManyWayNodesError < APIError
232 def initialize(id, provided, max)
233 super "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
240 attr_reader :id, :provided, :max
248 # raised when user input couldn't be parsed
249 class APIBadUserInput < APIError
256 # raised when bounding box is invalid
257 class APIBadBoundingBox < APIError
264 # raised when an API call is made using a method not supported on that URI
265 class APIBadMethodError < APIError
266 def initialize(supported_method)
267 super "Only method #{supported_method} is supported on this URI"
276 # raised when an API call takes too long
277 class APITimeoutError < APIError
279 super "Request timed out"
288 # raised when someone tries to redact a current version of
289 # an element - only historical versions can be redacted.
290 class APICannotRedactError < APIError
292 super "Cannot redact current version of element, only historical versions may be redacted."
300 # Raised when the note provided is already closed
301 class APINoteAlreadyClosedError < APIError
305 super "The note #{note.id} was closed at #{note.closed_at}"
315 # Raised when the note provided is already open
316 class APINoteAlreadyOpenError < APIError
320 super "The note #{note.id} is already open"
330 # raised when a two preferences have a duplicate key string.
331 class APIDuplicatePreferenceError < APIError
335 super "Duplicate preferences with key #{key}"
345 # Helper methods for going to/from mercator and lat/lng.
349 # init me with your bounding box and the size of your image
350 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
351 xsize = xsheet(max_lon) - xsheet(min_lon)
352 ysize = ysheet(max_lat) - ysheet(min_lat)
353 xscale = xsize / width
354 yscale = ysize / height
355 scale = [xscale, yscale].max
357 xpad = width * scale - xsize
358 ypad = height * scale - ysize
363 @tx = xsheet(min_lon) - xpad / 2
364 @ty = ysheet(min_lat) - ypad / 2
366 @bx = xsheet(max_lon) + xpad / 2
367 @by = ysheet(max_lat) + ypad / 2
370 # the following two functions will give you the x/y on the entire sheet
373 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
380 # and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
383 @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
387 ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
394 # initialise with a base position
395 def initialize(lat, lon)
396 @lat = lat * PI / 180
397 @lon = lon * PI / 180
400 # get the distance from the base position to a given position
401 def distance(lat, lon)
404 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2)**2 + cos(@lat) * cos(lat) * sin((lon - @lon) / 2)**2))
407 # get the worst case bounds for a given radius from the base position
409 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2))
412 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2 / cos(@lat)**2))
413 rescue Errno::EDOM, Math::DomainError
417 minlat = [(@lat - latradius) * 180 / PI, -90].max
418 maxlat = [(@lat + latradius) * 180 / PI, 90].min
419 minlon = [(@lon - lonradius) * 180 / PI, -180].max
420 maxlon = [(@lon + lonradius) * 180 / PI, 180].min
422 BoundingBox.new(minlon, minlat, maxlon, maxlat)
425 # get the SQL to use to calculate distance
426 def sql_for_distance(lat_field, lon_field)
427 "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)))"
433 doc = XML::Document.new
434 doc.encoding = XML::Encoding::UTF_8
435 root = XML::Node.new "osm"
436 xml_root_attributes.each do |k, v|
443 def xml_root_attributes
444 { "version" => Settings.api_version,
445 "generator" => Settings.generator,
446 "copyright" => Settings.copyright_owner,
447 "attribution" => Settings.attribution_url,
448 "license" => Settings.license_url }
452 def self.ip_to_country(ip_address)
453 ipinfo = maxmind_database.lookup(ip_address) if Settings.key?(:maxmind_database)
455 return ipinfo.country.iso_code if ipinfo&.found?
460 def self.ip_location(ip_address)
461 code = OSM.ip_to_country(ip_address)
463 if code && country = Country.find(code)
464 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
470 # Parse a float, raising a specified exception on failure
471 def self.parse_float(str, klass, *args)
474 raise klass.new(*args)
477 # Construct a random token of a given length
478 def self.make_token(length = 30)
479 chars = "abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
483 token += chars[(rand * chars.length).to_i].chr
489 # Return an SQL fragment to select a given area of the globe
490 def self.sql_for_area(bbox, prefix = nil)
491 tilesql = QuadTile.sql_for_area(bbox, prefix)
492 bbox = bbox.to_scaled
494 "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " \
495 "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
498 # Return the terms and conditions text for a given country
499 def self.legal_text_for_country(country_code)
500 file_name = Rails.root.join("config", "legales", country_code.to_s + ".yml")
501 file_name = Rails.root.join("config", "legales", Settings.default_legale + ".yml") unless File.exist? file_name
502 YAML.load_file(file_name).transform_values!(&:html_safe)
505 # Return the HTTP client to use
507 @http_client ||= Faraday.new
510 # Return the MaxMindDB database handle
511 def self.maxmind_database
512 @maxmind_database ||= MaxMindDB.new(Settings.maxmind_database) if Settings.key?(:maxmind_database)