]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api_controller.rb
caa2df9d81f622e92c4b0f01656968e91579bb3b
[rails.git] / app / controllers / api_controller.rb
1 class ApiController < ApplicationController
2   skip_before_action :verify_authenticity_token
3   before_action :check_api_readable, :except => [:capabilities]
4   before_action :setup_user_auth, :only => [:permissions]
5   around_action :api_call_handle_error, :api_call_timeout
6
7   # Get an XML response containing a list of tracepoints that have been uploaded
8   # within the specified bounding box, and in the specified page.
9   def trackpoints
10     # retrieve the page number
11     page = params["page"].to_s.to_i
12
13     unless page >= 0
14       report_error("Page number must be greater than or equal to 0")
15       return
16     end
17
18     offset = page * TRACEPOINTS_PER_PAGE
19
20     # Figure out the bbox
21     # check boundary is sane and area within defined
22     # see /config/application.yml
23     begin
24       bbox = BoundingBox.from_bbox_params(params)
25       bbox.check_boundaries
26       bbox.check_size
27     rescue StandardError => err
28       report_error(err.message)
29       return
30     end
31
32     # get all the points
33     points = Tracepoint.bbox(bbox).offset(offset).limit(TRACEPOINTS_PER_PAGE).order("gpx_id DESC, trackid ASC, timestamp ASC")
34
35     doc = XML::Document.new
36     doc.encoding = XML::Encoding::UTF_8
37     root = XML::Node.new "gpx"
38     root["version"] = "1.0"
39     root["creator"] = "OpenStreetMap.org"
40     root["xmlns"] = "http://www.topografix.com/GPX/1/0"
41
42     doc.root = root
43
44     # initialise these variables outside of the loop so that they
45     # stay in scope and don't get free'd up by the GC during the
46     # loop.
47     gpx_id = -1
48     trackid = -1
49     track = nil
50     trkseg = nil
51     anon_track = nil
52     anon_trkseg = nil
53     gpx_file = nil
54     timestamps = false
55
56     points.each do |point|
57       if gpx_id != point.gpx_id
58         gpx_id = point.gpx_id
59         trackid = -1
60         gpx_file = Trace.find(gpx_id)
61
62         if gpx_file.trackable?
63           track = XML::Node.new "trk"
64           doc.root << track
65           timestamps = true
66
67           if gpx_file.identifiable?
68             track << (XML::Node.new("name") << gpx_file.name)
69             track << (XML::Node.new("desc") << gpx_file.description)
70             track << (XML::Node.new("url") << url_for(:controller => "trace", :action => "view", :display_name => gpx_file.user.display_name, :id => gpx_file.id))
71           end
72         else
73           # use the anonymous track segment if the user hasn't allowed
74           # their GPX points to be tracked.
75           timestamps = false
76           if anon_track.nil?
77             anon_track = XML::Node.new "trk"
78             doc.root << anon_track
79           end
80           track = anon_track
81         end
82       end
83
84       if trackid != point.trackid
85         if gpx_file.trackable?
86           trkseg = XML::Node.new "trkseg"
87           track << trkseg
88           trackid = point.trackid
89         else
90           if anon_trkseg.nil?
91             anon_trkseg = XML::Node.new "trkseg"
92             anon_track << anon_trkseg
93           end
94           trkseg = anon_trkseg
95         end
96       end
97
98       trkseg << point.to_xml_node(timestamps)
99     end
100
101     response.headers["Content-Disposition"] = "attachment; filename=\"tracks.gpx\""
102
103     render :text => doc.to_s, :content_type => "text/xml"
104   end
105
106   # This is probably the most common call of all. It is used for getting the
107   # OSM data for a specified bounding box, usually for editing. First the
108   # bounding box (bbox) is checked to make sure that it is sane. All nodes
109   # are searched, then all the ways that reference those nodes are found.
110   # All Nodes that are referenced by those ways are fetched and added to the list
111   # of nodes.
112   # Then all the relations that reference the already found nodes and ways are
113   # fetched. All the nodes and ways that are referenced by those ways are then
114   # fetched. Finally all the xml is returned.
115   def map
116     # Figure out the bbox
117     # check boundary is sane and area within defined
118     # see /config/application.yml
119     begin
120       bbox = BoundingBox.from_bbox_params(params)
121       bbox.check_boundaries
122       bbox.check_size
123     rescue StandardError => err
124       report_error(err.message)
125       return
126     end
127
128     @nodes = Node.bbox(bbox).where(:visible => true).includes(:node_tags).limit(MAX_NUMBER_OF_NODES + 1)
129
130     node_ids = @nodes.collect(&:id)
131     if node_ids.length > MAX_NUMBER_OF_NODES
132       report_error("You requested too many nodes (limit is #{MAX_NUMBER_OF_NODES}). Either request a smaller area, or use planet.osm")
133       return
134     end
135     if node_ids.length == 0
136       render :text => "<osm version='#{API_VERSION}' generator='#{GENERATOR}'></osm>", :content_type => "text/xml"
137       return
138     end
139
140     doc = OSM::API.new.get_xml_doc
141
142     # add bounds
143     doc.root << bbox.add_bounds_to(XML::Node.new "bounds")
144
145     # get ways
146     # find which ways are needed
147     ways = []
148     if node_ids.length > 0
149       way_nodes = WayNode.where(:node_id => node_ids)
150       way_ids = way_nodes.collect { |way_node| way_node.id[0] }
151       ways = Way.preload(:way_nodes, :way_tags).find(way_ids)
152
153       list_of_way_nodes = ways.collect do |way|
154         way.way_nodes.collect(&:node_id)
155       end
156       list_of_way_nodes.flatten!
157
158     else
159       list_of_way_nodes = []
160     end
161
162     # - [0] in case some thing links to node 0 which doesn't exist. Shouldn't actually ever happen but it does. FIXME: file a ticket for this
163     nodes_to_fetch = (list_of_way_nodes.uniq - node_ids) - [0]
164
165     if nodes_to_fetch.length > 0
166       @nodes += Node.includes(:node_tags).find(nodes_to_fetch)
167     end
168
169     visible_nodes = {}
170     changeset_cache = {}
171     user_display_name_cache = {}
172
173     @nodes.each do |node|
174       if node.visible?
175         doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
176         visible_nodes[node.id] = node
177       end
178     end
179
180     way_ids = []
181     ways.each do |way|
182       if way.visible?
183         doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
184         way_ids << way.id
185       end
186     end
187
188     relations = Relation.nodes(visible_nodes.keys).visible +
189                 Relation.ways(way_ids).visible
190
191     # we do not normally return the "other" partners referenced by an relation,
192     # e.g. if we return a way A that is referenced by relation X, and there's
193     # another way B also referenced, that is not returned. But we do make
194     # an exception for cases where an relation references another *relation*;
195     # in that case we return that as well (but we don't go recursive here)
196     relations += Relation.relations(relations.collect(&:id)).visible
197
198     # this "uniq" may be slightly inefficient; it may be better to first collect and output
199     # all node-related relations, then find the *not yet covered* way-related ones etc.
200     relations.uniq.each do |relation|
201       doc.root << relation.to_xml_node(nil, changeset_cache, user_display_name_cache)
202     end
203
204     response.headers["Content-Disposition"] = "attachment; filename=\"map.osm\""
205
206     render :text => doc.to_s, :content_type => "text/xml"
207   end
208
209   # Get a list of the tiles that have changed within a specified time
210   # period
211   def changes
212     zoom = (params[:zoom] || "12").to_i
213
214     if params.include?(:start) && params.include?(:end)
215       starttime = Time.parse(params[:start])
216       endtime = Time.parse(params[:end])
217     else
218       hours = (params[:hours] || "1").to_i.hours
219       endtime = Time.now.getutc
220       starttime = endtime - hours
221     end
222
223     if zoom >= 1 && zoom <= 16 &&
224        endtime > starttime && endtime - starttime <= 24.hours
225       mask = (1 << zoom) - 1
226
227       tiles = Node.where(:timestamp => starttime..endtime).group("maptile_for_point(latitude, longitude, #{zoom})").count
228
229       doc = OSM::API.new.get_xml_doc
230       changes = XML::Node.new "changes"
231       changes["starttime"] = starttime.xmlschema
232       changes["endtime"] = endtime.xmlschema
233
234       tiles.each do |tile, count|
235         x = (tile.to_i >> zoom) & mask
236         y = tile.to_i & mask
237
238         t = XML::Node.new "tile"
239         t["x"] = x.to_s
240         t["y"] = y.to_s
241         t["z"] = zoom.to_s
242         t["changes"] = count.to_s
243
244         changes << t
245       end
246
247       doc.root << changes
248
249       render :text => doc.to_s, :content_type => "text/xml"
250     else
251       render :text => "Requested zoom is invalid, or the supplied start is after the end time, or the start duration is more than 24 hours", :status => :bad_request
252     end
253   end
254
255   # External apps that use the api are able to query the api to find out some
256   # parameters of the API. It currently returns:
257   # * minimum and maximum API versions that can be used.
258   # * maximum area that can be requested in a bbox request in square degrees
259   # * number of tracepoints that are returned in each tracepoints page
260   def capabilities
261     doc = OSM::API.new.get_xml_doc
262
263     api = XML::Node.new "api"
264     version = XML::Node.new "version"
265     version["minimum"] = "#{API_VERSION}"
266     version["maximum"] = "#{API_VERSION}"
267     api << version
268     area = XML::Node.new "area"
269     area["maximum"] = MAX_REQUEST_AREA.to_s
270     api << area
271     tracepoints = XML::Node.new "tracepoints"
272     tracepoints["per_page"] = TRACEPOINTS_PER_PAGE.to_s
273     api << tracepoints
274     waynodes = XML::Node.new "waynodes"
275     waynodes["maximum"] = MAX_NUMBER_OF_WAY_NODES.to_s
276     api << waynodes
277     changesets = XML::Node.new "changesets"
278     changesets["maximum_elements"] = Changeset::MAX_ELEMENTS.to_s
279     api << changesets
280     timeout = XML::Node.new "timeout"
281     timeout["seconds"] = API_TIMEOUT.to_s
282     api << timeout
283     status = XML::Node.new "status"
284     status["database"] = database_status.to_s
285     status["api"] = api_status.to_s
286     status["gpx"] = gpx_status.to_s
287     api << status
288     doc.root << api
289     policy = XML::Node.new "policy"
290     blacklist = XML::Node.new "imagery"
291     IMAGERY_BLACKLIST.each do |url_regex|
292       xnd = XML::Node.new "blacklist"
293       xnd["regex"] = url_regex.to_s
294       blacklist << xnd
295     end
296     policy << blacklist
297     doc.root << policy
298
299     render :text => doc.to_s, :content_type => "text/xml"
300   end
301
302   # External apps that use the api are able to query which permissions
303   # they have. This currently returns a list of permissions granted to the current user:
304   # * if authenticated via OAuth, this list will contain all permissions granted by the user to the access_token.
305   # * if authenticated via basic auth all permissions are granted, so the list will contain all permissions.
306   # * unauthenticated users have no permissions, so the list will be empty.
307   def permissions
308     @permissions = case
309                    when current_token.present?
310                      ClientApplication.all_permissions.select { |p| current_token.read_attribute(p) }
311                    when @user
312                      ClientApplication.all_permissions
313                    else
314                      []
315                    end
316   end
317 end