]> git.openstreetmap.org Git - rails.git/blob - app/controllers/traces_controller.rb
Refactored and added new test
[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 :require_user, :only => [:mine, :new, :create, :edit, :delete]
8   before_action :authorize, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
9   before_action :check_database_readable, :except => [:api_read, :api_data]
10   before_action :check_database_writable, :only => [:new, :create, :edit, :delete, :api_create, :api_update, :api_delete]
11   before_action :check_api_readable, :only => [:api_read, :api_data]
12   before_action :check_api_writable, :only => [:api_create, :api_update, :api_delete]
13   before_action :require_allow_read_gpx, :only => [:api_read, :api_data]
14   before_action :require_allow_write_gpx, :only => [:api_create, :api_update, :api_delete]
15   before_action :offline_warning, :only => [:mine, :view]
16   before_action :offline_redirect, :only => [:new, :create, :edit, :delete, :data, :api_create, :api_delete, :api_data]
17   around_action :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.present?
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     @title = if target_user.nil?
34                t ".public_traces"
35              elsif current_user && current_user == target_user
36                t ".my_traces"
37              else
38                t ".public_traces_from", :user => target_user.display_name
39              end
40
41     @title += t ".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     @traces = if target_user.nil? # all traces
49                 if current_user
50                   Trace.visible_to(current_user) # 1
51                 else
52                   Trace.visible_to_all # 2
53                 end
54               elsif current_user && current_user == target_user
55                 current_user.traces # 3 (check vs user id, so no join + can't pick up non-public traces by changing name)
56               else
57                 target_user.traces.visible_to_all # 4
58               end
59
60     @traces = @traces.tagged(params[:tag]) if params[:tag]
61
62     @params = params.permit(:display_name, :tag)
63
64     @page = (params[:page] || 1).to_i
65     @page_size = 20
66
67     @traces = @traces.visible
68     @traces = @traces.order(:id => :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 => current_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 == current_user)
97       @title = t ".title", :name => @trace.name
98     else
99       flash[:error] = t ".trace_not_found"
100       redirect_to :action => "list"
101     end
102   rescue ActiveRecord::RecordNotFound
103     flash[:error] = t ".trace_not_found"
104     redirect_to :action => "list"
105   end
106
107   def new
108     @title = t ".upload_trace"
109     @trace = Trace.new(:visibility => default_visibility)
110   end
111
112   def create
113     logger.info(params[:trace][:gpx_file].class.name)
114
115     if params[:trace][:gpx_file].respond_to?(:read)
116       begin
117         do_create(params[:trace][:gpx_file], params[:trace][:tagstring],
118                   params[:trace][:description], params[:trace][:visibility])
119       rescue StandardError => ex
120         if @trace.valid?
121           flash[:error] = t("traces.create.upload_failed")
122           logger.debug ex
123         end
124         render :action => "new"
125         return
126       end
127
128       if @trace.id
129         flash[:notice] = t ".trace_uploaded"
130         flash[:warning] = t ".traces_waiting", :count => current_user.traces.where(:inserted => false).count if current_user.traces.where(:inserted => false).count > 4
131
132         redirect_to :action => :list, :display_name => current_user.display_name
133       end
134     else
135       @trace = Trace.new(:name => "Dummy",
136                          :tagstring => params[:trace][:tagstring],
137                          :description => params[:trace][:description],
138                          :visibility => params[:trace][:visibility],
139                          :inserted => false, :user => current_user,
140                          :timestamp => Time.now.getutc)
141       @trace.valid?
142       @trace.errors.add(:gpx_file, "can't be blank")
143       @title = t ".upload_trace"
144       render :action => "new"
145     end
146   end
147
148   def data
149     trace = Trace.find(params[:id])
150
151     if trace.visible? && (trace.public? || (current_user && current_user == trace.user))
152       if Acl.no_trace_download(request.remote_ip)
153         head :forbidden
154       elsif request.format == Mime[:xml]
155         send_data(trace.xml_file.read, :filename => "#{trace.id}.xml", :type => request.format.to_s, :disposition => "attachment")
156       elsif request.format == Mime[:gpx]
157         send_data(trace.xml_file.read, :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       head :not_found
163     end
164   rescue ActiveRecord::RecordNotFound
165     head :not_found
166   end
167
168   def edit
169     @trace = Trace.find(params[:id])
170
171     if !@trace.visible?
172       head :not_found
173     elsif current_user.nil? || @trace.user != current_user
174       head :forbidden
175     else
176       @title = t ".title", :name => @trace.name
177
178       if request.post? && params[:trace]
179         @trace.description = params[:trace][:description]
180         @trace.tagstring = params[:trace][:tagstring]
181         @trace.visibility = params[:trace][:visibility]
182         redirect_to :action => "view", :display_name => current_user.display_name if @trace.save
183       end
184     end
185   rescue ActiveRecord::RecordNotFound
186     head :not_found
187   end
188
189   def delete
190     trace = Trace.find(params[:id])
191
192     if !trace.visible?
193       head :not_found
194     elsif current_user.nil? || (trace.user != current_user && !current_user.administrator? && !current_user.moderator?)
195       head :forbidden
196     else
197       trace.visible = false
198       trace.save
199       flash[:notice] = t ".scheduled_for_deletion"
200       redirect_to :action => :list, :display_name => trace.user.display_name
201     end
202   rescue ActiveRecord::RecordNotFound
203     head :not_found
204   end
205
206   def georss
207     @traces = Trace.visible_to_all.visible
208
209     @traces = @traces.joins(:user).where(:users => { :display_name => params[:display_name] }) if params[:display_name]
210
211     @traces = @traces.tagged(params[:tag]) if params[:tag]
212     @traces = @traces.order("timestamp DESC")
213     @traces = @traces.limit(20)
214     @traces = @traces.includes(:user)
215   end
216
217   def picture
218     trace = Trace.find(params[:id])
219
220     if trace.visible? && trace.inserted?
221       if trace.public? || (current_user && current_user == trace.user)
222         expires_in 7.days, :private => !trace.public?, :public => trace.public?
223         send_file(trace.large_picture_name, :filename => "#{trace.id}.gif", :type => "image/gif", :disposition => "inline")
224       else
225         head :forbidden
226       end
227     else
228       head :not_found
229     end
230   rescue ActiveRecord::RecordNotFound
231     head :not_found
232   end
233
234   def icon
235     trace = Trace.find(params[:id])
236
237     if trace.visible? && trace.inserted?
238       if trace.public? || (current_user && current_user == trace.user)
239         expires_in 7.days, :private => !trace.public?, :public => trace.public?
240         send_file(trace.icon_picture_name, :filename => "#{trace.id}_icon.gif", :type => "image/gif", :disposition => "inline")
241       else
242         head :forbidden
243       end
244     else
245       head :not_found
246     end
247   rescue ActiveRecord::RecordNotFound
248     head :not_found
249   end
250
251   def api_read
252     trace = Trace.visible.find(params[:id])
253
254     if trace.public? || trace.user == current_user
255       render :xml => trace.to_xml.to_s
256     else
257       head :forbidden
258     end
259   end
260
261   def api_update
262     trace = Trace.visible.find(params[:id])
263
264     if trace.user == current_user
265       trace.update_from_xml(request.raw_post)
266       trace.save!
267
268       head :ok
269     else
270       head :forbidden
271     end
272   end
273
274   def api_delete
275     trace = Trace.visible.find(params[:id])
276
277     if trace.user == current_user
278       trace.visible = false
279       trace.save!
280
281       head :ok
282     else
283       head :forbidden
284     end
285   end
286
287   def api_data
288     trace = Trace.visible.find(params[:id])
289
290     if trace.public? || trace.user == current_user
291       if request.format == Mime[:xml]
292         send_data(trace.xml_file.read, :filename => "#{trace.id}.xml", :type => request.format.to_s, :disposition => "attachment")
293       elsif request.format == Mime[:gpx]
294         send_data(trace.xml_file.read, :filename => "#{trace.id}.gpx", :type => request.format.to_s, :disposition => "attachment")
295       else
296         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => "attachment")
297       end
298     else
299       head :forbidden
300     end
301   end
302
303   def api_create
304     tags = params[:tags] || ""
305     description = params[:description] || ""
306     visibility = params[:visibility]
307
308     if visibility.nil?
309       visibility = if params[:public] && params[:public].to_i.nonzero?
310                      "public"
311                    else
312                      "private"
313                    end
314     end
315
316     if params[:file].respond_to?(:read)
317       do_create(params[:file], tags, description, visibility)
318
319       if @trace.id
320         render :plain => @trace.id.to_s
321       elsif @trace.valid?
322         head :internal_server_error
323       else
324         head :bad_request
325       end
326     else
327       head :bad_request
328     end
329   end
330
331   private
332
333   def do_create(file, tags, description, visibility)
334     # Sanitise the user's filename
335     name = file.original_filename.gsub(/[^a-zA-Z0-9.]/, "_")
336
337     # Get a temporary filename...
338     filename = "/tmp/#{rand}"
339
340     # ...and save the uploaded file to that location
341     File.open(filename, "wb") { |f| f.write(file.read) }
342
343     # Create the trace object, falsely marked as already
344     # inserted to stop the import daemon trying to load it
345     @trace = Trace.new(
346       :name => name,
347       :tagstring => tags,
348       :description => description,
349       :visibility => visibility,
350       :inserted => true,
351       :user => current_user,
352       :timestamp => Time.now.getutc
353     )
354
355     Trace.transaction do
356       begin
357         # Save the trace object
358         @trace.save!
359
360         # Rename the temporary file to the final name
361         FileUtils.mv(filename, @trace.trace_name)
362       rescue StandardError
363         # Remove the file as we have failed to update the database
364         FileUtils.rm_f(filename)
365
366         # Pass the exception on
367         raise
368       end
369
370       begin
371         # Clear the inserted flag to make the import daemon load the trace
372         @trace.inserted = false
373         @trace.save!
374       rescue StandardError
375         # Remove the file as we have failed to update the database
376         FileUtils.rm_f(@trace.trace_name)
377
378         # Pass the exception on
379         raise
380       end
381     end
382
383     # Finally save the user's preferred privacy level
384     if pref = current_user.preferences.where(:k => "gps.trace.visibility").first
385       pref.v = visibility
386       pref.save
387     else
388       current_user.preferences.create(:k => "gps.trace.visibility", :v => visibility)
389     end
390   end
391
392   def offline_warning
393     flash.now[:warning] = t "traces.offline_warning.message" if STATUS == :gpx_offline
394   end
395
396   def offline_redirect
397     redirect_to :action => :offline if STATUS == :gpx_offline
398   end
399
400   def default_visibility
401     visibility = current_user.preferences.where(:k => "gps.trace.visibility").first
402
403     if visibility
404       visibility.v
405     elsif current_user.preferences.where(:k => "gps.trace.public", :v => "default").first.nil?
406       "private"
407     else
408       "public"
409     end
410   end
411 end