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