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