+
+ def api_data
+ trace = Trace.find(params[:id])
+
+ if trace.public? or trace.user == @user
+ send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
+ else
+ render :nothing => true, :status => :forbidden
+ end
+ rescue ActiveRecord::RecordNotFound
+ render :nothing => true, :status => :not_found
+ end
+
+ def api_create
+ if request.post?
+ tags = params[:tags] || ""
+ description = params[:description] || ""
+ pub = params[:public] || false
+
+ if params[:file].respond_to?(:read)
+ do_create(params[:file], tags, description, pub)
+
+ if @trace.id
+ render :text => @trace.id.to_s, :content_type => "text/plain"
+ elsif @trace.valid?
+ render :nothing => true, :status => :internal_server_error
+ else
+ render :nothing => true, :status => :bad_request
+ end
+ else
+ render :nothing => true, :status => :bad_request
+ end
+ else
+ render :nothing => true, :status => :method_not_allowed
+ end
+ end
+
+private
+
+ def do_create(file, tags, description, public)
+ # Sanitise the user's filename
+ name = file.original_filename.gsub(/[^a-zA-Z0-9.]/, '_')
+
+ # Get a temporary filename...
+ filename = "/tmp/#{rand}"
+
+ # ...and save the uploaded file to that location
+ File.open(filename, "w") { |f| f.write(file.read) }
+
+ # Create the trace object, falsely marked as already
+ # inserted to stop the import daemon trying to load it
+ @trace = Trace.new({
+ :name => name,
+ :tagstring => tags,
+ :description => description,
+ :public => public,
+ :inserted => true,
+ :user => @user,
+ :timestamp => Time.now.getutc
+ })
+
+ # Save the trace object
+ if @trace.save
+ # Rename the temporary file to the final name
+ FileUtils.mv(filename, @trace.trace_name)
+
+ # Clear the inserted flag to make the import daemon load the trace
+ @trace.inserted = false
+ @trace.save!
+ else
+ # Remove the file as we have failed to update the database
+ FileUtils.rm_f(filename)
+ end
+
+ # Finally save whether the user marked the trace as being public
+ if @trace.public?
+ if @user.trace_public_default.nil?
+ @user.preferences.create(:k => "gps.trace.public", :v => "default")
+ end
+ else
+ pref = @user.trace_public_default
+ pref.destroy unless pref.nil?
+ end
+
+ end
+