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