]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api_controller.rb
1af14845585ee6b39e387cf6a5ab7071c509625e
[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}, :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)
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)
157     end
158
159     visible_nodes = {}
160     user_display_name_cache = {}
161
162     @nodes.each do |node|
163       if node.visible?
164         doc.root << node.to_xml_node(user_display_name_cache)
165         visible_nodes[node.id] = node
166       end
167     end
168
169     way_ids = Array.new
170     ways.each do |way|
171       if way.visible?
172         doc.root << way.to_xml_node(visible_nodes, user_display_name_cache)
173         way_ids << way.id
174       end
175     end 
176
177     relations = Relation.find_for_nodes(visible_nodes.keys, :conditions => {:visible => true}) +
178                 Relation.find_for_ways(way_ids, :conditions => {:visible => true})
179
180     # we do not normally return the "other" partners referenced by an relation, 
181     # e.g. if we return a way A that is referenced by relation X, and there's 
182     # another way B also referenced, that is not returned. But we do make 
183     # an exception for cases where an relation references another *relation*; 
184     # in that case we return that as well (but we don't go recursive here)
185     relations += Relation.find_for_relations(relations.collect { |r| r.id }, :conditions => {:visible => true})
186
187     # this "uniq" may be slightly inefficient; it may be better to first collect and output
188     # all node-related relations, then find the *not yet covered* way-related ones etc.
189     relations.uniq.each do |relation|
190       doc.root << relation.to_xml_node(user_display_name_cache)
191     end
192
193     response.headers["Content-Disposition"] = "attachment; filename=\"map.osm\""
194
195     render :text => doc.to_s, :content_type => "text/xml"
196   end
197
198   # Get a list of the tiles that have changed within a specified time
199   # period
200   def changes
201     zoom = (params[:zoom] || '12').to_i
202
203     if params.include?(:start) and params.include?(:end)
204       starttime = Time.parse(params[:start])
205       endtime = Time.parse(params[:end])
206     else
207       hours = (params[:hours] || '1').to_i.hours
208       endtime = Time.now.getutc
209       starttime = endtime - hours
210     end
211
212     if zoom >= 1 and zoom <= 16 and
213        endtime > starttime and endtime - starttime <= 24.hours
214       mask = (1 << zoom) - 1
215
216       tiles = Node.count(:conditions => ["timestamp BETWEEN ? AND ?", starttime, endtime],
217                          :group => "maptile_for_point(latitude, longitude, #{zoom})")
218
219       doc = OSM::API.new.get_xml_doc
220       changes = XML::Node.new 'changes'
221       changes["starttime"] = starttime.xmlschema
222       changes["endtime"] = endtime.xmlschema
223
224       tiles.each do |tile, count|
225         x = (tile.to_i >> zoom) & mask
226         y = tile.to_i & mask
227
228         t = XML::Node.new 'tile'
229         t["x"] = x.to_s
230         t["y"] = y.to_s
231         t["z"] = zoom.to_s
232         t["changes"] = count.to_s
233
234         changes << t
235       end
236
237       doc.root << changes
238
239       render :text => doc.to_s, :content_type => "text/xml"
240     else
241       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
242     end
243   end
244
245   # External apps that use the api are able to query the api to find out some 
246   # parameters of the API. It currently returns: 
247   # * minimum and maximum API versions that can be used.
248   # * maximum area that can be requested in a bbox request in square degrees
249   # * number of tracepoints that are returned in each tracepoints page
250   def capabilities
251     doc = OSM::API.new.get_xml_doc
252
253     api = XML::Node.new 'api'
254     version = XML::Node.new 'version'
255     version['minimum'] = "#{API_VERSION}";
256     version['maximum'] = "#{API_VERSION}";
257     api << version
258     area = XML::Node.new 'area'
259     area['maximum'] = MAX_REQUEST_AREA.to_s;
260     api << area
261     tracepoints = XML::Node.new 'tracepoints'
262     tracepoints['per_page'] = APP_CONFIG['tracepoints_per_page'].to_s
263     api << tracepoints
264     waynodes = XML::Node.new 'waynodes'
265     waynodes['maximum'] = APP_CONFIG['max_number_of_way_nodes'].to_s
266     api << waynodes
267     changesets = XML::Node.new 'changesets'
268     changesets['maximum_elements'] = Changeset::MAX_ELEMENTS.to_s
269     api << changesets
270     
271     doc.root << api
272
273     render :text => doc.to_s, :content_type => "text/xml"
274   end
275 end