]> git.openstreetmap.org Git - rails.git/blob - app/controllers/trace_controller.rb
[18163] commited by me yesterday (and reverted in [18165]) was
[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   around_filter :api_call_handle_error, :only => [:api_details, :api_data, :api_create]
15
16   # Counts and selects pages of GPX traces for various criteria (by user, tags, public etc.).
17   #  target_user - if set, specifies the user to fetch traces for.  if not set will fetch all traces
18   def list(target_user = nil, action = "list")
19     # from display name, pick up user id if one user's traces only
20     display_name = params[:display_name]
21     if target_user.nil? and !display_name.blank?
22       target_user = User.find(:first, :conditions => [ "visible = ? and display_name = ?", true, display_name])
23       if target_user.nil?
24         @title = t'trace.no_such_user.title'
25         @not_found_user = display_name
26         render :action => 'no_such_user', :status => :not_found
27         return
28       end
29     end
30
31     # set title
32     if target_user.nil?
33       @title = t 'trace.list.public_traces'
34     elsif @user and @user == target_user
35       @title = t 'trace.list.your_traces'
36     else
37       @title = t 'trace.list.public_traces_from', :user => target_user.display_name
38     end
39
40     @title += t 'trace.list.tagged_with', :tags => params[:tag] if params[:tag]
41
42     # four main cases:
43     # 1 - all traces, logged in = all public traces + all user's (i.e + all mine)
44     # 2 - all traces, not logged in = all public traces
45     # 3 - user's traces, logged in as same user = all user's traces 
46     # 4 - user's traces, not logged in as that user = all user's public traces
47     if target_user.nil? # all traces
48       if @user
49         conditions = ["(gpx_files.visibility in ('public', 'identifiable') OR gpx_files.user_id = ?)", @user.id] #1
50       else
51         conditions  = ["gpx_files.visibility in ('public', 'identifiable')"] #2
52       end
53     else
54       if @user and @user == target_user
55         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)
56       else
57         conditions = ["gpx_files.visibility in ('public', 'identifiable') AND gpx_files.user_id = ?", target_user.id] #4
58       end
59     end
60     
61     if params[:tag]
62       @tag = params[:tag]
63
64       files = Tracetag.find_all_by_tag(params[:tag]).collect { |tt| tt.gpx_id }
65
66       if files.length > 0
67         conditions[0] += " AND gpx_files.id IN (#{files.join(',')})"
68       else
69         conditions[0] += " AND 0 = 1"
70       end
71     end
72     
73     conditions[0] += " AND gpx_files.visible = ?"
74     conditions << true
75
76     @trace_pages, @traces = paginate(:traces,
77                                      :include => [:user, :tags],
78                                      :conditions => conditions,
79                                      :order => "gpx_files.timestamp DESC",
80                                      :per_page => 20)
81
82     # put together SET of tags across traces, for related links
83     tagset = Hash.new
84     if @traces
85       @traces.each do |trace|
86         trace.tags.reload if params[:tag] # if searched by tag, ActiveRecord won't bring back other tags, so do explicitly here
87         trace.tags.each do |tag|
88           tagset[tag.tag] = tag.tag
89         end
90       end
91     end
92     
93     # final helper vars for view
94     @action = action
95     @display_name = target_user.display_name if target_user
96     @all_tags = tagset.values
97   end
98
99   def mine
100     # Load the preference of whether the user set the trace public the last time
101     @trace = Trace.new
102     visibility = @user.preferences.find(:first, :conditions => {:k => "gps.trace.visibility"})
103     if visibility
104       @trace.visibility = visibility.v
105     elsif @user.preferences.find(:first, :conditions => {:k => "gps.trace.public", :v => "default"}).nil?
106       @trace.visibility = "private"
107     else 
108       @trace.visibility = "public"
109     end
110     list(@user, "mine")
111   end
112
113   def view
114     @trace = Trace.find(params[:id])
115
116     if @trace and @trace.visible? and
117        (@trace.public? or @trace.user == @user)
118       @title = t 'trace.view.title', :name => @trace.name
119     else
120       flash[:notice] = t 'trace.view.trace_not_found'
121       redirect_to :controller => 'trace', :action => 'list'
122     end
123   rescue ActiveRecord::RecordNotFound
124     flash[:notice] = t 'trace.view.trace_not_found'
125     redirect_to :controller => 'trace', :action => 'list'
126   end
127
128   def create
129     if params[:trace]
130       logger.info(params[:trace][:gpx_file].class.name)
131       if params[:trace][:gpx_file].respond_to?(:read)
132         begin
133           do_create(params[:trace][:gpx_file], params[:trace][:tagstring],
134                     params[:trace][:description], params[:trace][:visibility])
135         rescue
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 end