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