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