]> git.openstreetmap.org Git - rails.git/blob - app/controllers/trace_controller.rb
Merge the gpx_bugs action into the main get_bugs action
[rails.git] / app / controllers / trace_controller.rb
1 class TraceController < ApplicationController
2   layout 'site'
3
4   before_filter :authorize_web
5   before_filter :set_locale
6   before_filter :require_user, :only => [:mine, :create, :edit, :delete]
7   before_filter :authorize, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
8   before_filter :check_database_readable, :except => [:api_read, :api_data]
9   before_filter :check_database_writable, :only => [:create, :edit, :delete, :api_create, :api_update, :api_delete]
10   before_filter :check_api_readable, :only => [:api_read, :api_data]
11   before_filter :check_api_writable, :only => [:api_create, :api_update, :api_delete]
12   before_filter :require_allow_read_gpx, :only => [:api_read, :api_data]
13   before_filter :require_allow_write_gpx, :only => [:api_create, :api_update, :api_delete]
14   before_filter :offline_warning, :only => [:mine, :view]
15   before_filter :offline_redirect, :only => [:create, :edit, :delete, :data, :api_create, :api_delete, :api_data]
16   around_filter :api_call_handle_error, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
17
18   caches_action :list, :unless => :logged_in?, :layout => false
19   caches_action :view, :layout => false
20   caches_action :georss, :layout => true
21   cache_sweeper :trace_sweeper, :only => [:create, :edit, :delete, :api_create, :api_update, :api_delete], :unless => STATUS == :database_offline
22   cache_sweeper :tracetag_sweeper, :only => [:create, :edit, :delete, :api_create, :api_update, :api_delete], :unless => STATUS == :database_offline
23
24   # Counts and selects pages of GPX traces for various criteria (by user, tags, public etc.).
25   #  target_user - if set, specifies the user to fetch traces for.  if not set will fetch all traces
26   def list
27     # from display name, pick up user id if one user's traces only
28     display_name = params[:display_name]
29     if !display_name.blank?
30       target_user = User.find(:first, :conditions => { :status => ["active", "confirmed"], :display_name => display_name })
31       if target_user.nil?
32         @title = t'trace.no_such_user.title'
33         @not_found_user = display_name
34         render :action => 'no_such_user', :status => :not_found
35         return
36       end
37     end
38
39     # set title
40     if target_user.nil?
41       @title = t 'trace.list.public_traces'
42     elsif @user and @user == target_user
43       @title = t 'trace.list.your_traces'
44     else
45       @title = t 'trace.list.public_traces_from', :user => target_user.display_name
46     end
47
48     @title += t 'trace.list.tagged_with', :tags => params[:tag] if params[:tag]
49
50     # four main cases:
51     # 1 - all traces, logged in = all public traces + all user's (i.e + all mine)
52     # 2 - all traces, not logged in = all public traces
53     # 3 - user's traces, logged in as same user = all user's traces
54     # 4 - user's traces, not logged in as that user = all user's public traces
55     if target_user.nil? # all traces
56       if @user
57         conditions = ["(gpx_files.visibility in ('public', 'identifiable') OR gpx_files.user_id = ?)", @user.id] #1
58       else
59         conditions  = ["gpx_files.visibility in ('public', 'identifiable')"] #2
60       end
61     else
62       if @user and @user == target_user
63         conditions = ["gpx_files.user_id = ?", @user.id] #3 (check vs user id, so no join + can't pick up non-public traces by changing name)
64       else
65         conditions = ["gpx_files.visibility in ('public', 'identifiable') AND gpx_files.user_id = ?", target_user.id] #4
66       end
67     end
68
69     if params[:tag]
70       @tag = params[:tag]
71
72       files = Tracetag.find_all_by_tag(params[:tag]).collect { |tt| tt.gpx_id }
73
74       if files.length > 0
75         conditions[0] += " AND gpx_files.id IN (#{files.join(',')})"
76       else
77         conditions[0] += " AND 0 = 1"
78       end
79     end
80
81     conditions[0] += " AND gpx_files.visible = ?"
82     conditions << true
83
84     @page = (params[:page] || 1).to_i
85     @page_size = 20
86
87     @traces = Trace.find(:all,
88                          :include => [:user, :tags],
89                          :conditions => conditions,
90                          :order => "gpx_files.timestamp DESC",
91                          :offset => (@page - 1) * @page_size,
92                          :limit => @page_size)
93
94     # put together SET of tags across traces, for related links
95     tagset = Hash.new
96     if @traces
97       @traces.each do |trace|
98         trace.tags.reload if params[:tag] # if searched by tag, ActiveRecord won't bring back other tags, so do explicitly here
99         trace.tags.each do |tag|
100           tagset[tag.tag] = tag.tag
101         end
102       end
103     end
104
105     # final helper vars for view
106     @target_user = target_user
107     @display_name = target_user.display_name if target_user
108     @all_tags = tagset.values
109   end
110
111   def mine
112     redirect_to :action => :list, :display_name => @user.display_name
113   end
114
115   def view
116     @trace = Trace.find(params[:id])
117
118     if @trace and @trace.visible? and
119        (@trace.public? or @trace.user == @user)
120       @title = t 'trace.view.title', :name => @trace.name
121     else
122       flash[:error] = t 'trace.view.trace_not_found'
123       redirect_to :controller => 'trace', :action => 'list'
124     end
125   rescue ActiveRecord::RecordNotFound
126     flash[:error] = t 'trace.view.trace_not_found'
127     redirect_to :controller => 'trace', :action => 'list'
128   end
129
130   def create
131     if params[:trace]
132       logger.info(params[:trace][:gpx_file].class.name)
133
134       if params[:trace][:gpx_file].respond_to?(:read)
135         begin
136           do_create(params[:trace][:gpx_file], params[:trace][:tagstring],
137                     params[:trace][:description], params[:trace][:visibility])
138         rescue => ex
139           logger.debug ex
140         end
141
142         if @trace.id
143           logger.info("id is #{@trace.id}")
144           flash[:notice] = t 'trace.create.trace_uploaded'
145
146           if @user.traces.count(:conditions => { :inserted => false }) > 4
147             flash[:warning] = t 'trace.trace_header.traces_waiting', :count => @user.traces.count(:conditions => { :inserted => false })
148           end
149
150           redirect_to :action => :list, :display_name => @user.display_name
151         end
152       else
153         @trace = Trace.new({:name => "Dummy",
154                             :tagstring => params[:trace][:tagstring],
155                             :description => params[:trace][:description],
156                             :visibility => params[:trace][:visibility],
157                             :inserted => false, :user => @user,
158                             :timestamp => Time.now.getutc})
159         @trace.valid?
160         @trace.errors.add(:gpx_file, "can't be blank")
161       end
162     else
163       @trace = Trace.new(:visibility => default_visibility)
164     end
165
166     @title = t 'trace.create.upload_trace'
167   end
168
169   def data
170     trace = Trace.find(params[:id])
171
172     if trace.visible? and (trace.public? or (@user and @user == trace.user))
173       if request.format == Mime::XML
174         send_file(trace.xml_file, :filename => "#{trace.id}.xml", :type => Mime::XML.to_s, :disposition => 'attachment')
175       else
176         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
177       end
178     else
179       render :nothing => true, :status => :not_found
180     end
181   rescue ActiveRecord::RecordNotFound
182     render :nothing => true, :status => :not_found
183   end
184
185   def edit
186     @trace = Trace.find(params[:id])
187
188     if @user and @trace.user == @user
189       @title = t 'trace.edit.title', :name => @trace.name
190       if params[:trace]
191         @trace.description = params[:trace][:description]
192         @trace.tagstring = params[:trace][:tagstring]
193         @trace.visibility = params[:trace][:visibility]
194         if @trace.save
195           redirect_to :action => 'view'
196         end
197       end
198     else
199       render :nothing => true, :status => :forbidden
200     end
201   rescue ActiveRecord::RecordNotFound
202     render :nothing => true, :status => :not_found
203   end
204
205   def delete
206     trace = Trace.find(params[:id])
207
208     if @user and trace.user == @user
209       if request.post? and trace.visible?
210         trace.visible = false
211         trace.save
212         flash[:notice] = t 'trace.delete.scheduled_for_deletion'
213         redirect_to :action => :list, :display_name => @user.display_name
214       else
215         render :nothing => true, :status => :bad_request
216       end
217     else
218       render :nothing => true, :status => :forbidden
219     end
220   rescue ActiveRecord::RecordNotFound
221     render :nothing => true, :status => :not_found
222   end
223
224   def georss
225     conditions = ["gpx_files.visibility in ('public', 'identifiable')"]
226
227     if params[:display_name]
228       conditions[0] += " AND users.display_name = ?"
229       conditions << params[:display_name]
230     end
231
232     if params[:tag]
233       conditions[0] += " AND EXISTS (SELECT * FROM gpx_file_tags AS gft WHERE gft.gpx_id = gpx_files.id AND gft.tag = ?)"
234       conditions << params[:tag]
235     end
236
237     traces = Trace.find(:all, :include => :user, :conditions => conditions,
238                         :order => "timestamp DESC", :limit => 20)
239
240     rss = OSM::GeoRSS.new
241
242     traces.each do |trace|
243       rss.add(trace.latitude, trace.longitude, trace.name, trace.user.display_name, url_for({:controller => 'trace', :action => 'view', :id => trace.id, :display_name => trace.user.display_name}), "<img src='#{url_for({:controller => 'trace', :action => 'icon', :id => trace.id, :display_name => trace.user.display_name})}'> GPX file with #{trace.size} points from #{trace.user.display_name}", trace.timestamp)
244     end
245
246     render :text => rss.to_s, :content_type => "application/rss+xml"
247   end
248
249   def picture
250     trace = Trace.find(params[:id])
251
252     if trace.inserted?
253       if trace.public? or (@user and @user == trace.user)
254         expires_in 7.days, :private => !trace.public?, :public => trace.public?
255         send_file(trace.large_picture_name, :filename => "#{trace.id}.gif", :type => 'image/gif', :disposition => 'inline')
256       else
257         render :nothing => true, :status => :forbidden
258       end
259     else
260       render :nothing => true, :status => :not_found
261     end
262   rescue ActiveRecord::RecordNotFound
263     render :nothing => true, :status => :not_found
264   end
265
266   def icon
267     trace = Trace.find(params[:id])
268
269     if trace.inserted?
270       if trace.public? or (@user and @user == trace.user)
271         expires_in 7.days, :private => !trace.public?, :public => trace.public?
272         send_file(trace.icon_picture_name, :filename => "#{trace.id}_icon.gif", :type => 'image/gif', :disposition => 'inline')
273       else
274         render :nothing => true, :status => :forbidden
275       end
276     else
277       render :nothing => true, :status => :not_found
278     end
279   rescue ActiveRecord::RecordNotFound
280     render :nothing => true, :status => :not_found
281   end
282
283   def api_read
284     trace = Trace.find(params[:id], :conditions => { :visible => true })
285
286     if trace.public? or trace.user == @user
287       render :text => trace.to_xml.to_s, :content_type => "text/xml"
288     else
289       render :nothing => true, :status => :forbidden
290     end
291   end
292
293   def api_update
294     trace = Trace.find(params[:id], :conditions => { :visible => true })
295
296     if trace.user == @user
297       new_trace = Trace.from_xml(request.raw_post)
298
299       unless new_trace and new_trace.id == trace.id
300         raise OSM::APIBadUserInput.new("The id in the url (#{trace.id}) is not the same as provided in the xml (#{new_trace.id})")
301       end
302
303       trace.description = new_trace.description
304       trace.tags = new_trace.tags
305       trace.visibility = new_trace.visibility
306       trace.save!
307
308       render :nothing => true, :status => :ok
309     else
310       render :nothing => true, :status => :forbidden
311     end
312   end
313
314   def api_delete
315     trace = Trace.find(params[:id], :conditions => { :visible => true })
316
317     if trace.user == @user
318       trace.visible = false
319       trace.save!
320
321       render :nothing => true, :status => :ok
322     else
323       render :nothing => true, :status => :forbidden
324     end
325   end
326
327   def api_data
328     trace = Trace.find(params[:id])
329
330     if trace.public? or trace.user == @user
331       if request.format == Mime::XML
332         send_file(trace.xml_file, :filename => "#{trace.id}.xml", :type => Mime::XML.to_s, :disposition => 'attachment')
333       else
334         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
335       end
336     else
337       render :nothing => true, :status => :forbidden
338     end
339   end
340
341   def api_create
342     if request.post?
343       tags = params[:tags] || ""
344       description = params[:description] || ""
345       visibility = params[:visibility]
346
347       if visibility.nil?
348         if params[:public] && params[:public].to_i.nonzero?
349           visibility = "public"
350         else
351           visibility = "private"
352         end
353       end
354
355       if params[:file].respond_to?(:read)
356         do_create(params[:file], tags, description, visibility)
357
358         if @trace.id
359           render :text => @trace.id.to_s, :content_type => "text/plain"
360         elsif @trace.valid?
361           render :nothing => true, :status => :internal_server_error
362         else
363           render :nothing => true, :status => :bad_request
364         end
365       else
366         render :nothing => true, :status => :bad_request
367       end
368     else
369       render :nothing => true, :status => :method_not_allowed
370     end
371   end
372
373 private
374
375   def do_create(file, tags, description, visibility)
376     # Sanitise the user's filename
377     name = file.original_filename.gsub(/[^a-zA-Z0-9.]/, '_')
378
379     # Get a temporary filename...
380     filename = "/tmp/#{rand}"
381
382     # ...and save the uploaded file to that location
383     File.open(filename, "w") { |f| f.write(file.read) }
384
385     # Create the trace object, falsely marked as already
386     # inserted to stop the import daemon trying to load it
387     @trace = Trace.new({
388       :name => name,
389       :tagstring => tags,
390       :description => description,
391       :visibility => visibility,
392       :inserted => true,
393       :user => @user,
394       :timestamp => Time.now.getutc
395     })
396
397     Trace.transaction do
398       begin
399         # Save the trace object
400         @trace.save!
401
402         # Rename the temporary file to the final name
403         FileUtils.mv(filename, @trace.trace_name)
404       rescue Exception => ex
405         # Remove the file as we have failed to update the database
406         FileUtils.rm_f(filename)
407
408         # Pass the exception on
409         raise
410       end
411
412       begin
413         # Clear the inserted flag to make the import daemon load the trace
414         @trace.inserted = false
415         @trace.save!
416       rescue Exception => ex
417         # Remove the file as we have failed to update the database
418         FileUtils.rm_f(@trace.trace_name)
419
420         # Pass the exception on
421         raise
422       end
423     end
424
425     # Finally save the user's preferred privacy level
426     if pref = @user.preferences.find(:first, :conditions => {:k => "gps.trace.visibility"})
427       pref.v = visibility
428       pref.save
429     else
430       @user.preferences.create(:k => "gps.trace.visibility", :v => visibility)
431     end
432
433   end
434
435   def offline_warning
436     flash.now[:warning] = t 'trace.offline_warning.message' if STATUS == :gpx_offline
437   end
438
439   def offline_redirect
440     redirect_to :action => :offline if STATUS == :gpx_offline
441   end
442
443   def default_visibility
444     visibility = @user.preferences.find(:first, :conditions => {:k => "gps.trace.visibility"})
445
446     if visibility
447       visibility.v
448     elsif @user.preferences.find(:first, :conditions => {:k => "gps.trace.public", :v => "default"}).nil?
449       "private"
450     else
451       "public"
452     end
453   end
454
455 end