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