]> git.openstreetmap.org Git - rails.git/blob - lib/osm.rb
Merge remote-tracking branch 'upstream/pull/4720'
[rails.git] / lib / osm.rb
1 # The OSM module provides support functions for OSM.
2 module OSM
3   require "time"
4   require "rexml/parsers/sax2parser"
5   require "rexml/text"
6   require "xml/libxml"
7
8   # The base class for API Errors.
9   class APIError < RuntimeError
10     def initialize(message = "Generic API Error")
11       super(message)
12     end
13
14     def status
15       :internal_server_error
16     end
17   end
18
19   # Raised when access is denied.
20   class APIAccessDenied < APIError
21     def initialize
22       super("Access denied")
23     end
24
25     def status
26       :forbidden
27     end
28   end
29
30   # Raised when an API object is not found.
31   class APINotFoundError < APIError
32     def initialize
33       super("Object not found")
34     end
35
36     def status
37       :not_found
38     end
39   end
40
41   # Raised when a precondition to an API action fails sanity check.
42   class APIPreconditionFailedError < APIError
43     def initialize(message = "")
44       super("Precondition failed: #{message}")
45     end
46
47     def status
48       :precondition_failed
49     end
50   end
51
52   # Raised when to delete an already-deleted object.
53   class APIAlreadyDeletedError < APIError
54     def initialize(object = "object", object_id = "")
55       @object = object
56       @object_id = object_id
57
58       super("The #{object} with the id #{object_id} has already been deleted")
59     end
60
61     attr_reader :object, :object_id
62
63     def status
64       :gone
65     end
66   end
67
68   # Raised when the user logged in isn't the same as the changeset
69   class APIUserChangesetMismatchError < APIError
70     def initialize
71       super("The user doesn't own that changeset")
72     end
73
74     def status
75       :conflict
76     end
77   end
78
79   # Raised when the changeset provided is already closed
80   class APIChangesetAlreadyClosedError < APIError
81     def initialize(changeset)
82       @changeset = changeset
83
84       super("The changeset #{changeset.id} was closed at #{changeset.closed_at}")
85     end
86
87     attr_reader :changeset
88
89     def status
90       :conflict
91     end
92   end
93
94   # Raised when the changeset provided is not yet closed
95   class APIChangesetNotYetClosedError < APIError
96     def initialize(changeset)
97       @changeset = changeset
98
99       super("The changeset #{changeset.id} is not yet closed.")
100     end
101
102     attr_reader :changeset
103
104     def status
105       :conflict
106     end
107   end
108
109   # Raised when a user is already subscribed to the changeset
110   class APIChangesetAlreadySubscribedError < APIError
111     def initialize(changeset)
112       @changeset = changeset
113
114       super("You are already subscribed to changeset #{changeset.id}.")
115     end
116
117     attr_reader :changeset
118
119     def status
120       :conflict
121     end
122   end
123
124   # Raised when a user is not subscribed to the changeset
125   class APIChangesetNotSubscribedError < APIError
126     def initialize(changeset)
127       @changeset = changeset
128
129       super("You are not subscribed to changeset #{changeset.id}.")
130     end
131
132     attr_reader :changeset
133
134     def status
135       :not_found
136     end
137   end
138
139   # Raised when a change is expecting a changeset, but the changeset doesn't exist
140   class APIChangesetMissingError < APIError
141     def initialize
142       super("You need to supply a changeset to be able to make a change")
143     end
144
145     def status
146       :conflict
147     end
148   end
149
150   # Raised when a diff is uploaded containing many changeset IDs which don't match
151   # the changeset ID that the diff was uploaded to.
152   class APIChangesetMismatchError < APIError
153     def initialize(provided, allowed)
154       super("Changeset mismatch: Provided #{provided} but only #{allowed} is allowed")
155     end
156
157     def status
158       :conflict
159     end
160   end
161
162   # Raised when a diff upload has an unknown action. You can only have create,
163   # modify, or delete
164   class APIChangesetActionInvalid < APIError
165     def initialize(provided)
166       super("Unknown action #{provided}, choices are create, modify, delete")
167     end
168
169     def status
170       :bad_request
171     end
172   end
173
174   # Raised when bad XML is encountered which stops things parsing as
175   # they should.
176   class APIBadXMLError < APIError
177     def initialize(model, xml, message = "")
178       super("Cannot parse valid #{model} from xml string #{xml}. #{message}")
179     end
180
181     def status
182       :bad_request
183     end
184   end
185
186   # Raised when the provided version is not equal to the latest in the db.
187   class APIVersionMismatchError < APIError
188     def initialize(id, type, provided, latest)
189       @id = id
190       @type = type
191       @provided = provided
192       @latest = latest
193
194       super("Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}")
195     end
196
197     attr_reader :provided, :latest, :id, :type
198
199     def status
200       :conflict
201     end
202   end
203
204   # raised when a two tags have a duplicate key string in an element.
205   # this is now forbidden by the API.
206   class APIDuplicateTagsError < APIError
207     def initialize(type, id, tag_key)
208       @type = type
209       @id = id
210       @tag_key = tag_key
211
212       super("Element #{type}/#{id} has duplicate tags with key #{tag_key}")
213     end
214
215     attr_reader :type, :id, :tag_key
216
217     def status
218       :bad_request
219     end
220   end
221
222   # Raised when a way has more than the configured number of way nodes.
223   # This prevents ways from being to long and difficult to work with
224   class APITooManyWayNodesError < APIError
225     def initialize(id, provided, max)
226       super("You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed")
227
228       @id = id
229       @provided = provided
230       @max = max
231     end
232
233     attr_reader :id, :provided, :max
234
235     def status
236       :bad_request
237     end
238   end
239
240   # Raised when a relation has more than the configured number of relation members.
241   # This prevents relations from being too complex and difficult to work with
242   class APITooManyRelationMembersError < APIError
243     def initialize(id, provided, max)
244       super("You tried to add #{provided} members to relation #{id}, however only #{max} are allowed")
245
246       @id = id
247       @provided = provided
248       @max = max
249     end
250
251     attr_reader :id, :provided, :max
252
253     def status
254       :bad_request
255     end
256   end
257
258   ##
259   # raised when user input couldn't be parsed
260   class APIBadUserInput < APIError
261     def status
262       :bad_request
263     end
264   end
265
266   ##
267   # raised when bounding box is invalid
268   class APIBadBoundingBox < APIError
269     def status
270       :bad_request
271     end
272   end
273
274   ##
275   # raised when an API call is made using a method not supported on that URI
276   class APIBadMethodError < APIError
277     def initialize(supported_method)
278       super("Only method #{supported_method} is supported on this URI")
279     end
280
281     def status
282       :method_not_allowed
283     end
284   end
285
286   ##
287   # raised when an API call takes too long
288   class APITimeoutError < APIError
289     def initialize
290       super("Request timed out")
291     end
292
293     def status
294       :request_timeout
295     end
296   end
297
298   ##
299   # raised when someone tries to redact a current version of
300   # an element - only historical versions can be redacted.
301   class APICannotRedactError < APIError
302     def initialize
303       super("Cannot redact current version of element, only historical versions may be redacted.")
304     end
305
306     def status
307       :bad_request
308     end
309   end
310
311   # Raised when the note provided is already closed
312   class APINoteAlreadyClosedError < APIError
313     def initialize(note)
314       @note = note
315
316       super("The note #{note.id} was closed at #{note.closed_at}")
317     end
318
319     attr_reader :note
320
321     def status
322       :conflict
323     end
324   end
325
326   # Raised when the note provided is already open
327   class APINoteAlreadyOpenError < APIError
328     def initialize(note)
329       @note = note
330
331       super("The note #{note.id} is already open")
332     end
333
334     attr_reader :note
335
336     def status
337       :conflict
338     end
339   end
340
341   # raised when a two preferences have a duplicate key string.
342   class APIDuplicatePreferenceError < APIError
343     def initialize(key)
344       @key = key
345
346       super("Duplicate preferences with key #{key}")
347     end
348
349     attr_reader :key
350
351     def status
352       :bad_request
353     end
354   end
355
356   # Raised when a rate limit is exceeded
357   class APIRateLimitExceeded < APIError
358     def initialize
359       super("Rate limit exceeded")
360     end
361
362     def status
363       :too_many_requests
364     end
365   end
366
367   # Helper methods for going to/from mercator and lat/lng.
368   class Mercator
369     include Math
370
371     # init me with your bounding box and the size of your image
372     def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
373       xsize = xsheet(max_lon) - xsheet(min_lon)
374       ysize = ysheet(max_lat) - ysheet(min_lat)
375       xscale = xsize / width
376       yscale = ysize / height
377       scale = [xscale, yscale].max
378
379       xpad = (width * scale) - xsize
380       ypad = (height * scale) - ysize
381
382       @width = width
383       @height = height
384
385       @tx = xsheet(min_lon) - (xpad / 2)
386       @ty = ysheet(min_lat) - (ypad / 2)
387
388       @bx = xsheet(max_lon) + (xpad / 2)
389       @by = ysheet(max_lat) + (ypad / 2)
390     end
391
392     # the following two functions will give you the x/y on the entire sheet
393
394     def ysheet(lat)
395       log(tan((PI / 4) + (lat * PI / 180 / 2))) / (PI / 180)
396     end
397
398     def xsheet(lon)
399       lon
400     end
401
402     # and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
403     # If the bbox has no extent, return the centre of the image to avoid dividing by zero.
404
405     def y(lat)
406       return @height / 2 if (@by - @ty).zero?
407
408       @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
409     end
410
411     def x(lon)
412       return @width / 2 if (@bx - @tx).zero?
413
414       ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
415     end
416   end
417
418   class GreatCircle
419     include Math
420
421     # initialise with a base position
422     def initialize(lat, lon)
423       @lat = lat * PI / 180
424       @lon = lon * PI / 180
425     end
426
427     # get the distance from the base position to a given position
428     def distance(lat, lon)
429       lat = lat * PI / 180
430       lon = lon * PI / 180
431       6372.795 * 2 * asin(sqrt((sin((lat - @lat) / 2)**2) + (cos(@lat) * cos(lat) * (sin((lon - @lon) / 2)**2))))
432     end
433
434     # get the worst case bounds for a given radius from the base position
435     def bounds(radius)
436       latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2))
437
438       begin
439         lonradius = 2 * asin(sqrt((sin(radius / 6372.795 / 2)**2) / (cos(@lat)**2)))
440       rescue Errno::EDOM, Math::DomainError
441         lonradius = PI
442       end
443
444       minlat = [(@lat - latradius) * 180 / PI, -90].max
445       maxlat = [(@lat + latradius) * 180 / PI, 90].min
446       minlon = [(@lon - lonradius) * 180 / PI, -180].max
447       maxlon = [(@lon + lonradius) * 180 / PI, 180].min
448
449       BoundingBox.new(minlon, minlat, maxlon, maxlat)
450     end
451
452     # get the SQL to use to calculate distance
453     def sql_for_distance(lat_field, lon_field)
454       "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)))"
455     end
456   end
457
458   class API
459     def xml_doc
460       doc = XML::Document.new
461       doc.encoding = XML::Encoding::UTF_8
462       root = XML::Node.new "osm"
463       xml_root_attributes.each do |k, v|
464         root[k] = v
465       end
466       doc.root = root
467       doc
468     end
469
470     def xml_root_attributes
471       { "version" => Settings.api_version,
472         "generator" => Settings.generator,
473         "copyright" => Settings.copyright_owner,
474         "attribution" => Settings.attribution_url,
475         "license" => Settings.license_url }
476     end
477   end
478
479   def self.ip_to_country(ip_address)
480     ipinfo = maxmind_database.lookup(ip_address) if Settings.key?(:maxmind_database)
481
482     return ipinfo.country.iso_code if ipinfo&.found?
483
484     nil
485   end
486
487   def self.ip_location(ip_address)
488     code = OSM.ip_to_country(ip_address)
489
490     if code && country = Country.find(code)
491       return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
492     end
493
494     nil
495   end
496
497   # Parse a float, raising a specified exception on failure
498   def self.parse_float(str, klass, *args)
499     Float(str)
500   rescue StandardError
501     raise klass.new(*args)
502   end
503
504   # Construct a random token of a given length
505   def self.make_token(length = 24)
506     SecureRandom.urlsafe_base64(length)
507   end
508
509   # Return an SQL fragment to select a given area of the globe
510   def self.sql_for_area(bbox, prefix = nil)
511     tilesql = QuadTile.sql_for_area(bbox, prefix)
512     bbox = bbox.to_scaled
513
514     "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " \
515       "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
516   end
517
518   # Return the terms and conditions text for a given country
519   def self.legal_text_for_country(country_code)
520     file_name = Rails.root.join("config", "legales", "#{country_code}.yml")
521     file_name = Rails.root.join("config", "legales", "#{Settings.default_legale}.yml") unless File.exist? file_name
522     YAML.load_file(file_name).transform_values!(&:html_safe)
523   end
524
525   # Return the HTTP client to use
526   def self.http_client
527     @http_client ||= Faraday.new(:request => { :timeout => 15 })
528   end
529
530   # Return the MaxMindDB database handle
531   def self.maxmind_database
532     @maxmind_database ||= MaxMindDB.new(Settings.maxmind_database) if Settings.key?(:maxmind_database)
533   end
534 end