app.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. require 'yaml'
  2. require 'securerandom'
  3. Bundler.require
  4. Encoding.default_internal = 'binary'
  5. Encoding.default_external = 'binary'
  6. DIR_ROOT = File.expand_path File.dirname(__FILE__)
  7. $config = YAML.load_file(File.join(DIR_ROOT, 'config.yml'))
  8. SIGNAL_CODES = {
  9. 0 => 'success',
  10. 1 => 'missingargs',
  11. 2 => 'slowjs',
  12. 3 => 'openfailed',
  13. 4 => 'resourcetimeout',
  14. 5 => 'maxtimeout'
  15. }
  16. HARD_TIMEOUT = 30
  17. SCREENSHOTS_TMPDIR = '/tmp/screenshots'
  18. FileUtils.mkdir_p SCREENSHOTS_TMPDIR
  19. use Rack::Auth::Basic, "Restricted Area" do |username, password|
  20. username == 'screenshots' and password == $config['api_key']
  21. end
  22. get '/' do
  23. line = Cocaine::CommandLine.new(
  24. "DISPLAY=:0 timeout #{HARD_TIMEOUT} slimerjs screenshot.js", ":url :file_path :wait_time",
  25. expected_outcodes: [0]
  26. )
  27. file_tmp_path = File.join SCREENSHOTS_TMPDIR, "#{SecureRandom.uuid}.jpg"
  28. begin
  29. output = line.run url: params[:url], file_path: file_tmp_path, wait_time: (params[:wait_time] || 0)
  30. rescue Cocaine::ExitStatusError => e
  31. halt 500, SIGNAL_CODES[line.exit_status.to_i]
  32. end
  33. image_data = File.read file_tmp_path
  34. FileUtils.rm file_tmp_path
  35. content_type :jpg
  36. image_data
  37. end