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