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