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