]> git.openstreetmap.org Git - rails.git/blob - app/controllers/trace_controller.rb
Generate cache paths in the same way as the normal expire_action routine
[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_details, :api_data, :api_create]
8   before_filter :check_database_readable, :except => [:api_details, :api_data, :api_create]
9   before_filter :check_database_writable, :only => [:create, :edit, :delete]
10   before_filter :check_api_readable, :only => [:api_details, :api_data]
11   before_filter :check_api_writable, :only => [:api_create]
12   before_filter :require_allow_read_gpx, :only => [:api_details, :api_data]
13   before_filter :require_allow_write_gpx, :only => [:api_create]
14   before_filter :offline_warning, :only => [:mine, :view]
15   before_filter :offline_redirect, :only => [:create, :edit, :delete, :data, :api_data, :api_create]
16   around_filter :api_call_handle_error, :only => [:api_details, :api_data, :api_create]
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]
22   cache_sweeper :tracetag_sweeper, :only => [:create, :edit, :delete, :api_create]
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(target_user = nil, action = "list")
27     # from display name, pick up user id if one user's traces only
28     display_name = params[:display_name]
29     if target_user.nil? and !display_name.blank?
30       target_user = User.find(:first, :conditions => [ "visible = ? and display_name = ?", true, 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     @trace_pages, @traces = paginate(:traces,
85                                      :include => [:user, :tags],
86                                      :conditions => conditions,
87                                      :order => "gpx_files.timestamp DESC",
88                                      :per_page => 20)
89
90     # put together SET of tags across traces, for related links
91     tagset = Hash.new
92     if @traces
93       @traces.each do |trace|
94         trace.tags.reload if params[:tag] # if searched by tag, ActiveRecord won't bring back other tags, so do explicitly here
95         trace.tags.each do |tag|
96           tagset[tag.tag] = tag.tag
97         end
98       end
99     end
100
101     # final helper vars for view
102     @action = action
103     @display_name = target_user.display_name if target_user
104     @all_tags = tagset.values
105     @trace = Trace.new(:visibility => default_visibility) if @user
106   end
107
108   def mine
109     redirect_to :action => :list, :display_name => @user.display_name
110   end
111
112   def view
113     @trace = Trace.find(params[:id])
114
115     if @trace and @trace.visible? and
116        (@trace.public? or @trace.user == @user)
117       @title = t 'trace.view.title', :name => @trace.name
118     else
119       flash[:error] = t 'trace.view.trace_not_found'
120       redirect_to :controller => 'trace', :action => 'list'
121     end
122   rescue ActiveRecord::RecordNotFound
123     flash[:error] = t 'trace.view.trace_not_found'
124     redirect_to :controller => 'trace', :action => 'list'
125   end
126
127   def create
128     if params[:trace]
129       logger.info(params[:trace][:gpx_file].class.name)
130       if params[:trace][:gpx_file].respond_to?(:read)
131         begin
132           do_create(params[:trace][:gpx_file], params[:trace][:tagstring],
133                     params[:trace][:description], params[:trace][:visibility])
134         rescue => ex
135           logger.debug ex
136         end
137
138         if @trace.id
139           logger.info("id is #{@trace.id}")
140           flash[:notice] = t 'trace.create.trace_uploaded'
141
142           redirect_to :action => 'mine'
143         end
144       else
145         @trace = Trace.new({:name => "Dummy",
146                             :tagstring => params[:trace][:tagstring],
147                             :description => params[:trace][:description],
148                             :visibility => params[:trace][:visibility],
149                             :inserted => false, :user => @user,
150                             :timestamp => Time.now.getutc})
151         @trace.valid?
152         @trace.errors.add(:gpx_file, "can't be blank")
153       end
154     end
155     @title = t 'trace.create.upload_trace'
156   end
157
158   def data
159     trace = Trace.find(params[:id])
160
161     if trace.visible? and (trace.public? or (@user and @user == trace.user))
162       if request.format == Mime::XML
163         send_file(trace.xml_file, :filename => "#{trace.id}.xml", :type => Mime::XML.to_s, :disposition => 'attachment')
164       else
165         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
166       end
167     else
168       render :nothing => true, :status => :not_found
169     end
170   rescue ActiveRecord::RecordNotFound
171     render :nothing => true, :status => :not_found
172   end
173
174   def edit
175     @trace = Trace.find(params[:id])
176
177     if @user and @trace.user == @user
178       @title = t 'trace.edit.title', :name => @trace.name
179       if params[:trace]
180         @trace.description = params[:trace][:description]
181         @trace.tagstring = params[:trace][:tagstring]
182         @trace.visibility = params[:trace][:visibility]
183         if @trace.save
184           redirect_to :action => 'view'
185         end
186       end
187     else
188       render :nothing => true, :status => :forbidden
189     end
190   rescue ActiveRecord::RecordNotFound
191     render :nothing => true, :status => :not_found
192   end
193
194   def delete
195     trace = Trace.find(params[:id])
196
197     if @user and trace.user == @user
198       if request.post? and trace.visible?
199         trace.visible = false
200         trace.save
201         flash[:notice] = t 'trace.delete.scheduled_for_deletion'
202         redirect_to :controller => 'traces', :action => 'mine'
203       else
204         render :nothing => true, :status => :bad_request
205       end
206     else
207       render :nothing => true, :status => :forbidden
208     end
209   rescue ActiveRecord::RecordNotFound
210     render :nothing => true, :status => :not_found
211   end
212
213   def georss
214     conditions = ["gpx_files.visibility in ('public', 'identifiable')"]
215
216     if params[:display_name]
217       conditions[0] += " AND users.display_name = ?"
218       conditions << params[:display_name]
219     end
220
221     if params[:tag]
222       conditions[0] += " AND EXISTS (SELECT * FROM gpx_file_tags AS gft WHERE gft.gpx_id = gpx_files.id AND gft.tag = ?)"
223       conditions << params[:tag]
224     end
225
226     traces = Trace.find(:all, :include => :user, :conditions => conditions,
227                         :order => "timestamp DESC", :limit => 20)
228
229     rss = OSM::GeoRSS.new
230
231     traces.each do |trace|
232       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, :user_login => trace.user.display_name})}'> GPX file with #{trace.size} points from #{trace.user.display_name}", trace.timestamp)
233     end
234
235     render :text => rss.to_s, :content_type => "application/rss+xml"
236   end
237
238   def picture
239     trace = Trace.find(params[:id])
240
241     if trace.inserted?
242       if trace.public? or (@user and @user == trace.user)
243         expires_in 7.days, :private => !trace.public?, :public => trace.public?
244         send_file(trace.large_picture_name, :filename => "#{trace.id}.gif", :type => 'image/gif', :disposition => 'inline')
245       else
246         render :nothing => true, :status => :forbidden
247       end
248     else
249       render :nothing => true, :status => :not_found
250     end
251   rescue ActiveRecord::RecordNotFound
252     render :nothing => true, :status => :not_found
253   end
254
255   def icon
256     trace = Trace.find(params[:id])
257
258     if trace.inserted?
259       if trace.public? or (@user and @user == trace.user)
260         expires_in 7.days, :private => !trace.public?, :public => trace.public?
261         send_file(trace.icon_picture_name, :filename => "#{trace.id}_icon.gif", :type => 'image/gif', :disposition => 'inline')
262       else
263         render :nothing => true, :status => :forbidden
264       end
265     else
266       render :nothing => true, :status => :not_found
267     end
268   rescue ActiveRecord::RecordNotFound
269     render :nothing => true, :status => :not_found
270   end
271
272   def api_details
273     trace = Trace.find(params[:id])
274
275     if trace.public? or trace.user == @user
276       render :text => trace.to_xml.to_s, :content_type => "text/xml"
277     else
278       render :nothing => true, :status => :forbidden
279     end
280   rescue ActiveRecord::RecordNotFound
281     render :nothing => true, :status => :not_found
282   end
283
284   def api_data
285     trace = Trace.find(params[:id])
286
287     if trace.public? or trace.user == @user
288       send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
289     else
290       render :nothing => true, :status => :forbidden
291     end
292   rescue ActiveRecord::RecordNotFound
293     render :nothing => true, :status => :not_found
294   end
295
296   def api_create
297     if request.post?
298       tags = params[:tags] || ""
299       description = params[:description] || ""
300       visibility = params[:visibility]
301
302       if visibility.nil?
303         if params[:public] && params[:public].to_i.nonzero?
304           visibility = "public"
305         else
306           visibility = "private"
307         end
308       end
309
310       if params[:file].respond_to?(:read)
311         do_create(params[:file], tags, description, visibility)
312
313         if @trace.id
314           render :text => @trace.id.to_s, :content_type => "text/plain"
315         elsif @trace.valid?
316           render :nothing => true, :status => :internal_server_error
317         else
318           render :nothing => true, :status => :bad_request
319         end
320       else
321         render :nothing => true, :status => :bad_request
322       end
323     else
324       render :nothing => true, :status => :method_not_allowed
325     end
326   end
327
328 private
329
330   def do_create(file, tags, description, visibility)
331     # Sanitise the user's filename
332     name = file.original_filename.gsub(/[^a-zA-Z0-9.]/, '_')
333
334     # Get a temporary filename...
335     filename = "/tmp/#{rand}"
336
337     # ...and save the uploaded file to that location
338     File.open(filename, "w") { |f| f.write(file.read) }
339
340     # Create the trace object, falsely marked as already
341     # inserted to stop the import daemon trying to load it
342     @trace = Trace.new({
343       :name => name,
344       :tagstring => tags,
345       :description => description,
346       :visibility => visibility,
347       :inserted => true,
348       :user => @user,
349       :timestamp => Time.now.getutc
350     })
351
352     Trace.transaction do
353       begin
354         # Save the trace object
355         @trace.save!
356
357         # Rename the temporary file to the final name
358         FileUtils.mv(filename, @trace.trace_name)
359       rescue Exception => ex
360         # Remove the file as we have failed to update the database
361         FileUtils.rm_f(filename)
362
363         # Pass the exception on
364         raise
365       end
366
367       begin
368         # Clear the inserted flag to make the import daemon load the trace
369         @trace.inserted = false
370         @trace.save!
371       rescue Exception => ex
372         # Remove the file as we have failed to update the database
373         FileUtils.rm_f(@trace.trace_name)
374
375         # Pass the exception on
376         raise
377       end
378     end
379
380     # Finally save the user's preferred privacy level
381     if pref = @user.preferences.find(:first, :conditions => {:k => "gps.trace.visibility"})
382       pref.v = visibility
383       pref.save
384     else
385       @user.preferences.create(:k => "gps.trace.visibility", :v => visibility)
386     end
387
388   end
389
390   def offline_warning
391     flash.now[:warning] = t 'trace.offline_warning.message' if OSM_STATUS == :gpx_offline
392   end
393
394   def offline_redirect
395     redirect_to :action => :offline if OSM_STATUS == :gpx_offline
396   end
397
398   def default_visibility
399     visibility = @user.preferences.find(:first, :conditions => {:k => "gps.trace.visibility"})
400
401     if visibility
402       visibility.v
403     elsif @user.preferences.find(:first, :conditions => {:k => "gps.trace.public", :v => "default"}).nil?
404       "private"
405     else
406       "public"
407     end
408   end
409
410 end