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