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