]> git.openstreetmap.org Git - rails.git/blob - app/controllers/trace_controller.rb
9addcbfec85b4ac34f664c145d084a7bc07097d1
[rails.git] / app / controllers / trace_controller.rb
1 class TraceController < ApplicationController
2   layout 'site'
3
4   before_filter :authorize_web
5   before_filter :set_locale
6   before_filter :require_user, :only => [:mine, :create, :edit, :delete]
7   before_filter :authorize, :only => [:api_details, :api_data, :api_create]
8   before_filter :check_database_readable, :except => [:api_details, :api_data, :api_create]
9   before_filter :check_database_writable, :only => [:create, :edit, :delete]
10   before_filter :check_api_readable, :only => [:api_details, :api_data]
11   before_filter :check_api_writable, :only => [:api_create]
12   before_filter :require_allow_read_gpx, :only => [:api_details, :api_data]
13   before_filter :require_allow_write_gpx, :only => [:api_create]
14   before_filter :offline_warning, :only => [:mine, :view]
15   before_filter :offline_redirect, :only => [:create, :edit, :delete, :data, :api_data, :api_create]
16   around_filter :api_call_handle_error, :only => [:api_details, :api_data, :api_create]
17
18   # Counts and selects pages of GPX traces for various criteria (by user, tags, public etc.).
19   #  target_user - if set, specifies the user to fetch traces for.  if not set will fetch all traces
20   def list(target_user = nil, action = "list")
21     # from display name, pick up user id if one user's traces only
22     display_name = params[:display_name]
23     if target_user.nil? and !display_name.blank?
24       target_user = User.find(:first, :conditions => [ "visible = ? and display_name = ?", true, display_name])
25       if target_user.nil?
26         @title = t'trace.no_such_user.title'
27         @not_found_user = display_name
28         render :action => 'no_such_user', :status => :not_found
29         return
30       end
31     end
32
33     # set title
34     if target_user.nil?
35       @title = t 'trace.list.public_traces'
36     elsif @user and @user == target_user
37       @title = t 'trace.list.your_traces'
38     else
39       @title = t 'trace.list.public_traces_from', :user => target_user.display_name
40     end
41
42     @title += t 'trace.list.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     if target_user.nil? # all traces
50       if @user
51         conditions = ["(gpx_files.visibility in ('public', 'identifiable') OR gpx_files.user_id = ?)", @user.id] #1
52       else
53         conditions  = ["gpx_files.visibility in ('public', 'identifiable')"] #2
54       end
55     else
56       if @user and @user == target_user
57         conditions = ["gpx_files.user_id = ?", @user.id] #3 (check vs user id, so no join + can't pick up non-public traces by changing name)
58       else
59         conditions = ["gpx_files.visibility in ('public', 'identifiable') AND gpx_files.user_id = ?", target_user.id] #4
60       end
61     end
62     
63     if params[:tag]
64       @tag = params[:tag]
65
66       files = Tracetag.find_all_by_tag(params[:tag]).collect { |tt| tt.gpx_id }
67
68       if files.length > 0
69         conditions[0] += " AND gpx_files.id IN (#{files.join(',')})"
70       else
71         conditions[0] += " AND 0 = 1"
72       end
73     end
74     
75     conditions[0] += " AND gpx_files.visible = ?"
76     conditions << true
77
78     @trace_pages, @traces = paginate(:traces,
79                                      :include => [:user, :tags],
80                                      :conditions => conditions,
81                                      :order => "gpx_files.timestamp DESC",
82                                      :per_page => 20)
83
84     # put together SET of tags across traces, for related links
85     tagset = Hash.new
86     if @traces
87       @traces.each do |trace|
88         trace.tags.reload if params[:tag] # if searched by tag, ActiveRecord won't bring back other tags, so do explicitly here
89         trace.tags.each do |tag|
90           tagset[tag.tag] = tag.tag
91         end
92       end
93     end
94     
95     # final helper vars for view
96     @action = action
97     @display_name = target_user.display_name if target_user
98     @all_tags = tagset.values
99   end
100
101   def mine
102     # Load the preference of whether the user set the trace public the last time
103     @trace = Trace.new
104     visibility = @user.preferences.find(:first, :conditions => {:k => "gps.trace.visibility"})
105     if visibility
106       @trace.visibility = visibility.v
107     elsif @user.preferences.find(:first, :conditions => {:k => "gps.trace.public", :v => "default"}).nil?
108       @trace.visibility = "private"
109     else 
110       @trace.visibility = "public"
111     end
112     list(@user, "mine")
113   end
114
115   def view
116     @trace = Trace.find(params[:id])
117
118     if @trace and @trace.visible? and
119        (@trace.public? or @trace.user == @user)
120       @title = t 'trace.view.title', :name => @trace.name
121     else
122       flash[:error] = t 'trace.view.trace_not_found'
123       redirect_to :controller => 'trace', :action => 'list'
124     end
125   rescue ActiveRecord::RecordNotFound
126     flash[:error] = t 'trace.view.trace_not_found'
127     redirect_to :controller => 'trace', :action => 'list'
128   end
129
130   def create
131     if params[:trace]
132       logger.info(params[:trace][:gpx_file].class.name)
133       if params[:trace][:gpx_file].respond_to?(:read)
134         begin
135           do_create(params[:trace][:gpx_file], params[:trace][:tagstring],
136                     params[:trace][:description], params[:trace][:visibility])
137         rescue
138         end
139
140         if @trace.id
141           logger.info("id is #{@trace.id}")
142           flash[:notice] = t 'trace.create.trace_uploaded'
143
144           redirect_to :action => 'mine'
145         end
146       else
147         @trace = Trace.new({:name => "Dummy",
148                             :tagstring => params[:trace][:tagstring],
149                             :description => params[:trace][:description],
150                             :visibility => params[:trace][:visibility],
151                             :inserted => false, :user => @user,
152                             :timestamp => Time.now.getutc})
153         @trace.valid?
154         @trace.errors.add(:gpx_file, "can't be blank")
155       end
156     end
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 request.format == Mime::XML
165         send_file(trace.xml_file, :filename => "#{trace.id}.xml", :type => Mime::XML.to_s, :disposition => 'attachment')
166       else
167         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
168       end
169     else
170       render :nothing => true, :status => :not_found
171     end
172   rescue ActiveRecord::RecordNotFound
173     render :nothing => true, :status => :not_found
174   end
175
176   def edit
177     @trace = Trace.find(params[:id])
178
179     if @user and @trace.user == @user
180       @title = t 'trace.edit.title', :name => @trace.name
181       if params[:trace]
182         @trace.description = params[:trace][:description]
183         @trace.tagstring = params[:trace][:tagstring]
184         @trace.visibility = params[:trace][:visibility]
185         if @trace.save
186           redirect_to :action => 'view'
187         end        
188       end
189     else
190       render :nothing => true, :status => :forbidden
191     end
192   rescue ActiveRecord::RecordNotFound
193     render :nothing => true, :status => :not_found
194   end
195
196   def delete
197     trace = Trace.find(params[:id])
198
199     if @user and trace.user == @user
200       if request.post? and trace.visible?
201         trace.visible = false
202         trace.save
203         flash[:notice] = t 'trace.delete.scheduled_for_deletion'
204         redirect_to :controller => 'traces', :action => 'mine'
205       else
206         render :nothing => true, :status => :bad_request
207       end
208     else
209       render :nothing => true, :status => :forbidden
210     end
211   rescue ActiveRecord::RecordNotFound
212     render :nothing => true, :status => :not_found
213   end
214
215   def georss
216     conditions = ["gpx_files.visibility in ('public', 'identifiable')"]
217
218     if params[:display_name]
219       conditions[0] += " AND users.display_name = ?"
220       conditions << params[:display_name]
221     end
222
223     if params[:tag]
224       conditions[0] += " AND EXISTS (SELECT * FROM gpx_file_tags AS gft WHERE gft.gpx_id = gpx_files.id AND gft.tag = ?)"
225       conditions << params[:tag]
226     end
227
228     traces = Trace.find(:all, :include => :user, :conditions => conditions, 
229                         :order => "timestamp DESC", :limit => 20)
230
231     rss = OSM::GeoRSS.new
232
233     traces.each do |trace|
234       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, :user_login => trace.user.display_name})}'> GPX file with #{trace.size} points from #{trace.user.display_name}", trace.timestamp)
235     end
236
237     render :text => rss.to_s, :content_type => "application/rss+xml"
238   end
239
240   def picture
241     trace = Trace.find(params[:id])
242
243     if trace.inserted?
244       if trace.public? or (@user and @user == trace.user)
245         expires_in 7.days, :private => !trace.public?, :public => trace.public?
246         send_file(trace.large_picture_name, :filename => "#{trace.id}.gif", :type => 'image/gif', :disposition => 'inline')
247       else
248         render :nothing => true, :status => :forbidden
249       end
250     else
251       render :nothing => true, :status => :not_found
252     end
253   rescue ActiveRecord::RecordNotFound
254     render :nothing => true, :status => :not_found
255   end
256
257   def icon
258     trace = Trace.find(params[:id])
259
260     if trace.inserted?
261       if trace.public? or (@user and @user == trace.user)
262         expires_in 7.days, :private => !trace.public?, :public => trace.public?
263         send_file(trace.icon_picture_name, :filename => "#{trace.id}_icon.gif", :type => 'image/gif', :disposition => 'inline')
264       else
265         render :nothing => true, :status => :forbidden
266       end
267     else
268       render :nothing => true, :status => :not_found
269     end
270   rescue ActiveRecord::RecordNotFound
271     render :nothing => true, :status => :not_found
272   end
273
274   def api_details
275     trace = Trace.find(params[:id])
276
277     if trace.public? or trace.user == @user
278       render :text => trace.to_xml.to_s, :content_type => "text/xml"
279     else
280       render :nothing => true, :status => :forbidden
281     end
282   rescue ActiveRecord::RecordNotFound
283     render :nothing => true, :status => :not_found
284   end
285
286   def api_data
287     trace = Trace.find(params[:id])
288
289     if trace.public? or trace.user == @user
290       send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
291     else
292       render :nothing => true, :status => :forbidden
293     end
294   rescue ActiveRecord::RecordNotFound
295     render :nothing => true, :status => :not_found
296   end
297
298   def api_create
299     if request.post?
300       tags = params[:tags] || ""
301       description = params[:description] || ""
302       visibility = params[:visibility]
303
304       if visibility.nil?
305         if params[:public] && params[:public].to_i.nonzero?
306           visibility = "public"
307         else
308           visibility = "private"
309         end
310       end
311
312       if params[:file].respond_to?(:read)
313         do_create(params[:file], tags, description, visibility)
314
315         if @trace.id
316           render :text => @trace.id.to_s, :content_type => "text/plain"
317         elsif @trace.valid?
318           render :nothing => true, :status => :internal_server_error
319         else
320           render :nothing => true, :status => :bad_request
321         end
322       else
323         render :nothing => true, :status => :bad_request
324       end
325     else
326       render :nothing => true, :status => :method_not_allowed
327     end
328   end
329
330 private
331
332   def do_create(file, tags, description, visibility)
333     # Sanitise the user's filename
334     name = file.original_filename.gsub(/[^a-zA-Z0-9.]/, '_')
335
336     # Get a temporary filename...
337     filename = "/tmp/#{rand}"
338
339     # ...and save the uploaded file to that location
340     File.open(filename, "w") { |f| f.write(file.read) }
341
342     # Create the trace object, falsely marked as already
343     # inserted to stop the import daemon trying to load it
344     @trace = Trace.new({
345       :name => name,
346       :tagstring => tags,
347       :description => description,
348       :visibility => visibility,
349       :inserted => true,
350       :user => @user,
351       :timestamp => Time.now.getutc
352     })
353
354     Trace.transaction do
355       begin
356         # Save the trace object
357         @trace.save!
358
359         # Rename the temporary file to the final name
360         FileUtils.mv(filename, @trace.trace_name)
361       rescue Exception => ex
362         # Remove the file as we have failed to update the database
363         FileUtils.rm_f(filename)
364
365         # Pass the exception on
366         raise
367       end
368
369       begin
370         # Clear the inserted flag to make the import daemon load the trace
371         @trace.inserted = false
372         @trace.save!
373       rescue Exception => ex
374         # Remove the file as we have failed to update the database
375         FileUtils.rm_f(@trace.trace_name)
376
377         # Pass the exception on
378         raise
379       end
380     end
381
382     # Finally save the user's preferred privacy level
383     if pref = @user.preferences.find(:first, :conditions => {:k => "gps.trace.visibility"})
384       pref.v = visibility
385       pref.save
386     else
387       @user.preferences.create(:k => "gps.trace.visibility", :v => visibility)
388     end
389     
390   end
391
392   def offline_warning
393     flash.now[:warning] = t 'trace.offline_warning.message' if OSM_STATUS == :gpx_offline
394   end
395
396   def offline_redirect
397     redirect_to :action => :offline if OSM_STATUS == :gpx_offline
398   end
399
400 end