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