]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api_controller.rb
Display the image of the user who made the diary entry, not that of
[rails.git] / app / controllers / api_controller.rb
1 class ApiController < ApplicationController
2
3   session :off
4   before_filter :check_read_availability, :except => [:capabilities]
5   after_filter :compress_output
6
7   # Help methods for checking boundary sanity and area size
8   include MapBoundary
9
10   #COUNT is the number of map requests to allow before exiting and starting a new process
11   @@count = COUNT
12
13   # The maximum area you're allowed to request, in square degrees
14   MAX_REQUEST_AREA = 0.25
15
16   # Number of GPS trace/trackpoints returned per-page
17   TRACEPOINTS_PER_PAGE = 5000
18
19   
20   def trackpoints
21     @@count+=1
22     #retrieve the page number
23     page = params['page'].to_i
24     unless page
25         page = 0;
26     end
27
28     unless page >= 0
29         report_error("Page number must be greater than or equal to 0")
30         return
31     end
32
33     offset = page * TRACEPOINTS_PER_PAGE
34
35     # Figure out the bbox
36     bbox = params['bbox']
37     unless bbox and bbox.count(',') == 3
38       report_error("The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
39       return
40     end
41
42     bbox = bbox.split(',')
43     min_lon, min_lat, max_lon, max_lat = sanitise_boundaries(bbox)
44     # check boundary is sane and area within defined
45     # see /config/application.yml
46     begin
47       check_boundaries(min_lon, min_lat, max_lon, max_lat)
48     rescue Exception => err
49       report_error(err.message)
50       return
51     end
52
53     # get all the points
54     points = Tracepoint.find_by_area(min_lat, min_lon, max_lat, max_lon, :offset => offset, :limit => TRACEPOINTS_PER_PAGE, :order => "timestamp DESC" )
55
56     doc = XML::Document.new
57     doc.encoding = 'UTF-8'
58     root = XML::Node.new 'gpx'
59     root['version'] = '1.0'
60     root['creator'] = 'OpenStreetMap.org'
61     root['xmlns'] = "http://www.topografix.com/GPX/1/0/"
62     
63     doc.root = root
64
65     track = XML::Node.new 'trk'
66     doc.root << track
67
68     trkseg = XML::Node.new 'trkseg'
69     track << trkseg
70
71     points.each do |point|
72       trkseg << point.to_xml_node()
73     end
74
75     #exit when we have too many requests
76     if @@count > MAX_COUNT
77       render :text => doc.to_s, :content_type => "text/xml"
78       @@count = COUNT
79       exit!
80     end
81
82     render :text => doc.to_s, :content_type => "text/xml"
83
84   end
85
86   def map
87     GC.start
88     @@count+=1
89     # Figure out the bbox
90     bbox = params['bbox']
91
92     unless bbox and bbox.count(',') == 3
93       # alternatively: report_error(TEXT['boundary_parameter_required']
94       report_error("The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
95       return
96     end
97
98     bbox = bbox.split(',')
99
100     min_lon, min_lat, max_lon, max_lat = sanitise_boundaries(bbox)
101
102     # check boundary is sane and area within defined
103     # see /config/application.yml
104     begin
105       check_boundaries(min_lon, min_lat, max_lon, max_lat)
106     rescue Exception => err
107       report_error(err.message)
108       return
109     end
110
111     @nodes = Node.find_by_area(min_lat, min_lon, max_lat, max_lon, :conditions => "visible = 1", :limit => APP_CONFIG['max_number_of_nodes']+1)
112     # get all the nodes, by tag not yet working, waiting for change from NickB
113     # need to be @nodes (instance var) so tests in /spec can be performed
114     #@nodes = Node.search(bbox, params[:tag])
115
116     node_ids = @nodes.collect(&:id)
117     if node_ids.length > APP_CONFIG['max_number_of_nodes']
118       report_error("You requested too many nodes (limit is 50,000). Either request a smaller area, or use planet.osm")
119       return
120     end
121     if node_ids.length == 0
122       render :text => "<osm version='0.5'></osm>", :content_type => "text/xml"
123       return
124     end
125
126     relations = Array.new
127
128     doc = OSM::API.new.get_xml_doc
129
130     # get ways
131     # find which ways are needed
132     ways = Array.new
133     if node_ids.length > 0
134       way_nodes = WayNode.find_all_by_node_id(node_ids)
135       way_ids = way_nodes.collect { |way_node| way_node.id[0] }
136       ways = Way.find(way_ids)
137
138       list_of_way_nodes = ways.collect { |way|
139         way.way_nodes.collect { |way_node| way_node.node_id }
140       }
141       list_of_way_nodes.flatten!
142
143     else
144       list_of_way_nodes = Array.new
145     end
146
147     # - [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
148     nodes_to_fetch = (list_of_way_nodes.uniq - node_ids) - [0]
149
150     if nodes_to_fetch.length > 0
151       @nodes += Node.find(nodes_to_fetch)
152     end
153
154     visible_nodes = {}
155     user_display_name_cache = {}
156
157     @nodes.each do |node|
158       if node.visible?
159         doc.root << node.to_xml_node(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, user_display_name_cache)
168         way_ids << way.id
169       end
170     end 
171
172     # collect relationships. currently done in one big block at the end;
173     # may need to move this upwards if people want automatic completion of
174     # relationships, i.e. deliver referenced objects like we do with ways...
175     relations = Array.new
176     if visible_nodes.length > 0
177         relations += Relation.find_by_sql("select e.* from current_relations e,current_relation_members em where " +
178             "e.visible=1 and " +
179             "em.id = e.id and em.member_type='node' and em.member_id in (#{visible_nodes.keys.join(',')})")
180     end
181     if way_ids.length > 0
182         relations += Relation.find_by_sql("select e.* from current_relations e,current_relation_members em where " +
183             "e.visible=1 and " +
184             "em.id = e.id and em.member_type='way' and em.member_id in (#{way_ids.join(',')})")
185     end
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     relation_ids = relations.collect { |relation| relation.id }
192     if relation_ids.length > 0
193         relations += Relation.find_by_sql("select e.* from current_relations e,current_relation_members em where " +
194             "e.visible=1 and " +
195             "em.id = e.id and em.member_type='relation' and em.member_id in (#{relation_ids.join(',')})")
196     end
197
198     # this "uniq" may be slightly inefficient; it may be better to first collect and output
199     # all node-related relations, then find the *not yet covered* way-related ones etc.
200     relations.uniq.each do |relation|
201       doc.root << relation.to_xml_node(user_display_name_cache)
202     end
203
204     render :text => doc.to_s, :content_type => "text/xml"
205     
206     #exit when we have too many requests
207     if @@count > MAX_COUNT
208       @@count = COUNT
209       
210       exit!
211     end
212   end
213
214   def changes
215     zoom = (params[:zoom] || '12').to_i
216
217     if params.include?(:start) and params.include?(:end)
218       starttime = Time.parse(params[:start])
219       endtime = Time.parse(params[:end])
220     else
221       hours = (params[:hours] || '1').to_i.hours
222       endtime = Time.now
223       starttime = endtime - hours
224     end
225
226     if zoom >= 1 and zoom <= 16 and
227        endtime >= starttime and endtime - starttime <= 24.hours
228       mask = (1 << zoom) - 1
229
230       tiles = Node.count(:conditions => ["timestamp BETWEEN ? AND ?", starttime, endtime],
231                          :group => "maptile_for_point(latitude, longitude, #{zoom})")
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 :nothing => true, :status => :bad_request
256     end
257   end
258
259   def capabilities
260     doc = OSM::API.new.get_xml_doc
261
262     api = XML::Node.new 'api'
263     version = XML::Node.new 'version'
264     version['minimum'] = '0.5';
265     version['maximum'] = '0.5';
266     api << version
267     area = XML::Node.new 'area'
268     area['maximum'] = MAX_REQUEST_AREA.to_s;
269     api << area
270     
271     doc.root << api
272
273     render :text => doc.to_s, :content_type => "text/xml"
274   end
275 end