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