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