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