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