]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api_controller.rb
Another approach, but this time without scattering stuff all over the methods
[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 * 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 => 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=\"tracks.gpx\""
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     # FIXME um why is this area using a different order for the lat/lon from above???
148     @nodes = Node.find_by_area(min_lat, min_lon, max_lat, max_lon, :conditions => {:visible => true}, :include => :node_tags, :limit => MAX_NUMBER_OF_NODES+1)
149     # get all the nodes, by tag not yet working, waiting for change from NickB
150     # need to be @nodes (instance var) so tests in /spec can be performed
151     #@nodes = Node.search(bbox, params[:tag])
152
153     node_ids = @nodes.collect(&:id)
154     if node_ids.length > MAX_NUMBER_OF_NODES
155       report_error("You requested too many nodes (limit is #{MAX_NUMBER_OF_NODES}). Either request a smaller area, or use planet.osm")
156       return
157     end
158     if node_ids.length == 0
159       render :text => "<osm version='#{API_VERSION}' generator='#{GENERATOR}'></osm>", :content_type => "text/xml"
160       return
161     end
162
163     doc = OSM::API.new.get_xml_doc
164
165     # add bounds
166     bounds = XML::Node.new 'bounds'
167     bounds['minlat'] = min_lat.to_s
168     bounds['minlon'] = min_lon.to_s
169     bounds['maxlat'] = max_lat.to_s
170     bounds['maxlon'] = max_lon.to_s
171     doc.root << bounds
172
173     # get ways
174     # find which ways are needed
175     ways = Array.new
176     if node_ids.length > 0
177       way_nodes = WayNode.find_all_by_node_id(node_ids)
178       way_ids = way_nodes.collect { |way_node| way_node.id[0] }
179       ways = Way.find(way_ids, :include => [:way_nodes, :way_tags])
180
181       list_of_way_nodes = ways.collect { |way|
182         way.way_nodes.collect { |way_node| way_node.node_id }
183       }
184       list_of_way_nodes.flatten!
185
186     else
187       list_of_way_nodes = Array.new
188     end
189
190     # - [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
191     nodes_to_fetch = (list_of_way_nodes.uniq - node_ids) - [0]
192
193     if nodes_to_fetch.length > 0
194       @nodes += Node.find(nodes_to_fetch, :include => :node_tags)
195     end
196
197     visible_nodes = {}
198     changeset_cache = {}
199     user_display_name_cache = {}
200
201     @nodes.each do |node|
202       if node.visible?
203         doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
204         visible_nodes[node.id] = node
205       end
206     end
207
208     way_ids = Array.new
209     ways.each do |way|
210       if way.visible?
211         doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
212         way_ids << way.id
213       end
214     end 
215
216     relations = Relation.find_for_nodes(visible_nodes.keys, :conditions => {:visible => true}) +
217                 Relation.find_for_ways(way_ids, :conditions => {:visible => true})
218
219     # we do not normally return the "other" partners referenced by an relation, 
220     # e.g. if we return a way A that is referenced by relation X, and there's 
221     # another way B also referenced, that is not returned. But we do make 
222     # an exception for cases where an relation references another *relation*; 
223     # in that case we return that as well (but we don't go recursive here)
224     relations += Relation.find_for_relations(relations.collect { |r| r.id }, :conditions => {:visible => true})
225
226     # this "uniq" may be slightly inefficient; it may be better to first collect and output
227     # all node-related relations, then find the *not yet covered* way-related ones etc.
228     relations.uniq.each do |relation|
229       doc.root << relation.to_xml_node(nil, changeset_cache, user_display_name_cache)
230     end
231
232     response.headers["Content-Disposition"] = "attachment; filename=\"map.osm\""
233
234     render :text => doc.to_s, :content_type => "text/xml"
235   end
236
237   # Get a list of the tiles that have changed within a specified time
238   # period
239   def changes
240     zoom = (params[:zoom] || '12').to_i
241
242     if params.include?(:start) and params.include?(:end)
243       starttime = Time.parse(params[:start])
244       endtime = Time.parse(params[:end])
245     else
246       hours = (params[:hours] || '1').to_i.hours
247       endtime = Time.now.getutc
248       starttime = endtime - hours
249     end
250
251     if zoom >= 1 and zoom <= 16 and
252        endtime > starttime and endtime - starttime <= 24.hours
253       mask = (1 << zoom) - 1
254
255       tiles = Node.count(:conditions => ["timestamp BETWEEN ? AND ?", starttime, endtime],
256                          :group => "maptile_for_point(latitude, longitude, #{zoom})")
257
258       doc = OSM::API.new.get_xml_doc
259       changes = XML::Node.new 'changes'
260       changes["starttime"] = starttime.xmlschema
261       changes["endtime"] = endtime.xmlschema
262
263       tiles.each do |tile, count|
264         x = (tile.to_i >> zoom) & mask
265         y = tile.to_i & mask
266
267         t = XML::Node.new 'tile'
268         t["x"] = x.to_s
269         t["y"] = y.to_s
270         t["z"] = zoom.to_s
271         t["changes"] = count.to_s
272
273         changes << t
274       end
275
276       doc.root << changes
277
278       render :text => doc.to_s, :content_type => "text/xml"
279     else
280       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
281     end
282   end
283
284   # External apps that use the api are able to query the api to find out some 
285   # parameters of the API. It currently returns: 
286   # * minimum and maximum API versions that can be used.
287   # * maximum area that can be requested in a bbox request in square degrees
288   # * number of tracepoints that are returned in each tracepoints page
289   def capabilities
290     doc = OSM::API.new.get_xml_doc
291
292     api = XML::Node.new 'api'
293     version = XML::Node.new 'version'
294     version['minimum'] = "#{API_VERSION}";
295     version['maximum'] = "#{API_VERSION}";
296     api << version
297     area = XML::Node.new 'area'
298     area['maximum'] = MAX_REQUEST_AREA.to_s;
299     api << area
300     tracepoints = XML::Node.new 'tracepoints'
301     tracepoints['per_page'] = TRACEPOINTS_PER_PAGE.to_s
302     api << tracepoints
303     waynodes = XML::Node.new 'waynodes'
304     waynodes['maximum'] = MAX_NUMBER_OF_WAY_NODES.to_s
305     api << waynodes
306     changesets = XML::Node.new 'changesets'
307     changesets['maximum_elements'] = Changeset::MAX_ELEMENTS.to_s
308     api << changesets
309     timeout = XML::Node.new 'timeout'
310     timeout['seconds'] = API_TIMEOUT.to_s
311     api << timeout
312     
313     doc.root << api
314
315     render :text => doc.to_s, :content_type => "text/xml"
316   end
317 end