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