]> git.openstreetmap.org Git - rails.git/blob - app/controllers/trace_controller.rb
Merge branch 'master' into notes
[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 #  caches_action :list, :unless => :logged_in?, :layout => false
20 #  caches_action :view, :layout => false
21   caches_action :georss, :layout => true
22   cache_sweeper :trace_sweeper, :only => [:create, :edit, :delete, :api_create, :api_update, :api_delete]
23   cache_sweeper :tracetag_sweeper, :only => [:create, :edit, :delete, :api_create, :api_update, :api_delete]
24
25   # Counts and selects pages of GPX traces for various criteria (by user, tags, public etc.).
26   #  target_user - if set, specifies the user to fetch traces for.  if not set will fetch all traces
27   def list
28     # from display name, pick up user id if one user's traces only
29     display_name = params[:display_name]
30     if !display_name.blank?
31       target_user = User.active.where(:display_name => display_name).first
32       if target_user.nil?
33         render_unknown_user display_name
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         @traces = Trace.visible_to(@user) #1
57       else
58         @traces = Trace.public #2
59       end
60     else
61       if @user and @user == target_user
62         @traces = @user.traces #3 (check vs user id, so no join + can't pick up non-public traces by changing name)
63       else
64         @traces = target_user.traces.public #4
65       end
66     end
67
68     if params[:tag]
69       @tag = params[:tag]
70
71       files = Tracetag.where(:tag => params[:tag]).select(:gpx_id).all
72
73       if files.length > 0
74         @traces = @traces.where(:id => files.collect { |tt| tt.gpx_id })
75       end
76     end
77
78     @page = (params[:page] || 1).to_i
79     @page_size = 20
80
81     @traces = @traces.visible
82     @traces = @traces.order("timestamp DESC")
83     @traces = @traces.offset((@page - 1) * @page_size)
84     @traces = @traces.limit(@page_size)
85     @traces = @traces.includes(:user, :tags)
86
87     # put together SET of tags across traces, for related links
88     tagset = Hash.new
89     @traces.each do |trace|
90       trace.tags.reload if params[:tag] # if searched by tag, ActiveRecord won't bring back other tags, so do explicitly here
91       trace.tags.each do |tag|
92         tagset[tag.tag] = tag.tag
93       end
94     end
95
96     # final helper vars for view
97     @target_user = target_user
98     @display_name = target_user.display_name if target_user
99     @all_tags = tagset.values
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
125       if params[:trace][:gpx_file].respond_to?(:read)
126         begin
127           do_create(params[:trace][:gpx_file], params[:trace][:tagstring],
128                     params[:trace][:description], params[:trace][:visibility])
129         rescue => ex
130           logger.debug ex
131         end
132
133         if @trace.id
134           logger.info("id is #{@trace.id}")
135           flash[:notice] = t 'trace.create.trace_uploaded'
136
137           if @user.traces.count(:conditions => { :inserted => false }) > 4
138             flash[:warning] = t 'trace.trace_header.traces_waiting', :count => @user.traces.count(:conditions => { :inserted => false })
139           end
140
141           redirect_to :action => :list, :display_name => @user.display_name
142         end
143       else
144         @trace = Trace.new({:name => "Dummy",
145                             :tagstring => params[:trace][:tagstring],
146                             :description => params[:trace][:description],
147                             :visibility => params[:trace][:visibility],
148                             :inserted => false, :user => @user,
149                             :timestamp => Time.now.getutc})
150         @trace.valid?
151         @trace.errors.add(:gpx_file, "can't be blank")
152       end
153     else
154       @trace = Trace.new({:visibility => default_visibility}, :without_protection => true)
155     end
156
157     @title = t 'trace.create.upload_trace'
158   end
159
160   def data
161     trace = Trace.find(params[:id])
162
163     if trace.visible? and (trace.public? or (@user and @user == trace.user))
164       if Acl.no_trace_download(request.remote_ip)
165         render :nothing => true, :status => :forbidden
166       elsif 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', :display_name => @user.display_name
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 trace.visible?
203         trace.visible = false
204         trace.save
205         flash[:notice] = t 'trace.delete.scheduled_for_deletion'
206         redirect_to :action => :list, :display_name => @user.display_name
207       else
208         render :nothing => true, :status => :not_found
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     traces = Trace.public
219
220     if params[:display_name]
221       traces = traces.joins(:user).where(:users => {:display_name => params[:display_name]})
222     end
223
224     if params[:tag]
225       traces = traces.where("EXISTS (SELECT * FROM gpx_file_tags AS gft WHERE gft.gpx_id = gpx_files.id AND gft.tag = ?)", params[:tag])
226     end
227
228     traces = traces.order("timestamp DESC")
229     traces = traces.limit(20)
230     traces = traces.includes(:user)
231
232     rss = OSM::GeoRSS.new
233
234     traces.each do |trace|
235       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)
236     end
237
238     render :text => rss.to_s, :content_type => "application/rss+xml"
239   end
240
241   def picture
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.large_picture_name, :filename => "#{trace.id}.gif", :type => 'image/gif', :disposition => 'inline')
248       else
249         render :nothing => true, :status => :forbidden
250       end
251     else
252       render :nothing => true, :status => :not_found
253     end
254   rescue ActiveRecord::RecordNotFound
255     render :nothing => true, :status => :not_found
256   end
257
258   def icon
259     trace = Trace.find(params[:id])
260
261     if trace.inserted?
262       if trace.public? or (@user and @user == trace.user)
263         expires_in 7.days, :private => !trace.public?, :public => trace.public?
264         send_file(trace.icon_picture_name, :filename => "#{trace.id}_icon.gif", :type => 'image/gif', :disposition => 'inline')
265       else
266         render :nothing => true, :status => :forbidden
267       end
268     else
269       render :nothing => true, :status => :not_found
270     end
271   rescue ActiveRecord::RecordNotFound
272     render :nothing => true, :status => :not_found
273   end
274
275   def api_read
276     trace = Trace.visible.find(params[:id])
277
278     if trace.public? or trace.user == @user
279       render :text => trace.to_xml.to_s, :content_type => "text/xml"
280     else
281       render :nothing => true, :status => :forbidden
282     end
283   end
284
285   def api_update
286     trace = Trace.visible.find(params[:id])
287
288     if trace.user == @user
289       new_trace = Trace.from_xml(request.raw_post)
290
291       unless new_trace and new_trace.id == trace.id
292         raise OSM::APIBadUserInput.new("The id in the url (#{trace.id}) is not the same as provided in the xml (#{new_trace.id})")
293       end
294
295       trace.description = new_trace.description
296       trace.tags = new_trace.tags
297       trace.visibility = new_trace.visibility
298       trace.save!
299
300       render :nothing => true, :status => :ok
301     else
302       render :nothing => true, :status => :forbidden
303     end
304   end
305
306   def api_delete
307     trace = Trace.visible.find(params[:id])
308
309     if trace.user == @user
310       trace.visible = false
311       trace.save!
312
313       render :nothing => true, :status => :ok
314     else
315       render :nothing => true, :status => :forbidden
316     end
317   end
318
319   def api_data
320     trace = Trace.find(params[:id])
321
322     if trace.public? or trace.user == @user
323       if request.format == Mime::XML
324         send_file(trace.xml_file, :filename => "#{trace.id}.xml", :type => Mime::XML.to_s, :disposition => 'attachment')
325       else
326         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
327       end
328     else
329       render :nothing => true, :status => :forbidden
330     end
331   end
332
333   def api_create
334     tags = params[:tags] || ""
335     description = params[:description] || ""
336     visibility = params[:visibility]
337
338     if visibility.nil?
339       if params[:public] && params[:public].to_i.nonzero?
340         visibility = "public"
341       else
342         visibility = "private"
343       end
344     end
345
346     if params[:file].respond_to?(:read)
347       do_create(params[:file], tags, description, visibility)
348
349       if @trace.id
350         render :text => @trace.id.to_s, :content_type => "text/plain"
351       elsif @trace.valid?
352         render :nothing => true, :status => :internal_server_error
353       else
354         render :nothing => true, :status => :bad_request
355       end
356     else
357       render :nothing => true, :status => :bad_request
358     end
359   end
360
361 private
362
363   def do_create(file, tags, description, visibility)
364     # Sanitise the user's filename
365     name = file.original_filename.gsub(/[^a-zA-Z0-9.]/, '_')
366
367     # Get a temporary filename...
368     filename = "/tmp/#{rand}"
369
370     # ...and save the uploaded file to that location
371     File.open(filename, "wb") { |f| f.write(file.read) }
372
373     # Create the trace object, falsely marked as already
374     # inserted to stop the import daemon trying to load it
375     @trace = Trace.new({
376       :name => name,
377       :tagstring => tags,
378       :description => description,
379       :visibility => visibility,
380       :inserted => true,
381       :user => @user,
382       :timestamp => Time.now.getutc
383     }, :without_protection => true)
384
385     Trace.transaction do
386       begin
387         # Save the trace object
388         @trace.save!
389
390         # Rename the temporary file to the final name
391         FileUtils.mv(filename, @trace.trace_name)
392       rescue Exception => ex
393         # Remove the file as we have failed to update the database
394         FileUtils.rm_f(filename)
395
396         # Pass the exception on
397         raise
398       end
399
400       begin
401         # Clear the inserted flag to make the import daemon load the trace
402         @trace.inserted = false
403         @trace.save!
404       rescue Exception => ex
405         # Remove the file as we have failed to update the database
406         FileUtils.rm_f(@trace.trace_name)
407
408         # Pass the exception on
409         raise
410       end
411     end
412
413     # Finally save the user's preferred privacy level
414     if pref = @user.preferences.where(:k => "gps.trace.visibility").first
415       pref.v = visibility
416       pref.save
417     else
418       @user.preferences.create(:k => "gps.trace.visibility", :v => visibility)
419     end
420
421   end
422
423   def offline_warning
424     flash.now[:warning] = t 'trace.offline_warning.message' if STATUS == :gpx_offline
425   end
426
427   def offline_redirect
428     redirect_to :action => :offline if STATUS == :gpx_offline
429   end
430
431   def default_visibility
432     visibility = @user.preferences.where(:k => "gps.trace.visibility").first
433
434     if visibility
435       visibility.v
436     elsif @user.preferences.where(:k => "gps.trace.public", :v => "default").first.nil?
437       "private"
438     else
439       "public"
440     end
441   end
442
443 end