class OmniFiles::ProtectedApp

Protected app for POST request

Public Instance Methods

format_time_str(time) click to toggle source
# File lib/omnifiles/protectedapp.rb, line 57
def format_time_str time
  if time
    time.localtime.to_s
  else
    '<i>Not yet</i>'
  end
end
make_haml_data_from_doc(doc) click to toggle source
# File lib/omnifiles/protectedapp.rb, line 65
def make_haml_data_from_doc doc
  {
    shortened: doc['shortened'],
    url: url('/f/' + doc['shortened']),
    original_filename: make_visible_filename(doc['original_filename']),
    mime: doc['mime'],
    access_time: format_time_str(doc['accessed']['time']),
    created_time: format_time_str(doc['created']['time']),
    access_count: doc['accessed']['count']
  }
end
make_visible_filename(filename) click to toggle source
# File lib/omnifiles/protectedapp.rb, line 53
def make_visible_filename filename
    filename ? URI.unescape(filename) : "<i>Not provided</i>"
end
store_file() click to toggle source

POST handler with form/body handling

# File lib/omnifiles/protectedapp.rb, line 126
def store_file
  logger.info "Route POST store"
  begin
    req = Rack::Request.new(env)
    if !req.POST || req.POST == {}
      logger.info "Saving POST body to temp file"

      original_filename = nil

      # Make a temp file with body content
      temp_file = Tempfile.new("omnifiles-post-")
      File.open(temp_file.path, 'wb') do |ftemp|
        IO.copy_stream(req.body, ftemp)
      end
    else
      logger.info "Using POST form"

      # Use a Rack provided file with content
      post_file = req.POST['file']
      original_filename = URI.escape(File.basename(post_file[:filename]))

      temp_file = post_file[:tempfile]
    end

    store_with_file temp_file.path, original_filename

  ensure
    if temp_file
      temp_file.close
      temp_file.unlink
    end
  end
end
store_with_file(path, original_filename) click to toggle source

Save temporary file to storage

# File lib/omnifiles/protectedapp.rb, line 161
def store_with_file path, original_filename
  # Take a sample of file
  sample = Digest::MD5.hexdigest(IO.binread(path, 0x100))

  # Determine file mime and desired url
  mime = FileMagic.mime.file path

  # Short URL is composed from escaped filename from form, mime type and leading file bytes
  shortened = @storage.shorten_file sample, original_filename, mime

  # Save file to storage
  target_path = File.join(Settings.storage_dir, shortened)
  raise "Not so unique id #{shortened}" if File.exists? target_path
  FileUtils.cp path, target_path

  # Put record to storage
  @storage.put_file shortened, original_filename, mime
  short_url = url('/f/'+shortened)

  logger.info "Stored file #{target_path} to shortened #{shortened}, magic '#{mime}'"

  short_url
end