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