1
0

web_request_concern.rb 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. require 'faraday'
  2. require 'faraday_middleware'
  3. module WebRequestConcern
  4. extend ActiveSupport::Concern
  5. def validate_web_request_options!
  6. if options['user_agent'].present?
  7. errors.add(:base, "user_agent must be a string") unless options['user_agent'].is_a?(String)
  8. end
  9. if options['disable_ssl_verification'].present? && boolify(options['disable_ssl_verification']).nil?
  10. errors.add(:base, "if provided, disable_ssl_verification must be true or false")
  11. end
  12. unless headers(options['headers']).is_a?(Hash)
  13. errors.add(:base, "if provided, headers must be a hash")
  14. end
  15. begin
  16. basic_auth_credentials(options['basic_auth'])
  17. rescue ArgumentError => e
  18. errors.add(:base, e.message)
  19. end
  20. end
  21. def faraday
  22. faraday_options = {
  23. ssl: {
  24. verify: !boolify(options['disable_ssl_verification'])
  25. }
  26. }
  27. @faraday ||= Faraday.new(faraday_options) { |builder|
  28. builder.headers = headers if headers.length > 0
  29. builder.headers[:user_agent] = user_agent
  30. builder.use FaradayMiddleware::FollowRedirects
  31. builder.request :url_encoded
  32. if userinfo = basic_auth_credentials
  33. builder.request :basic_auth, *userinfo
  34. end
  35. case backend = faraday_backend
  36. when :typhoeus
  37. require 'typhoeus/adapters/faraday'
  38. end
  39. builder.adapter backend
  40. }
  41. end
  42. def headers(value = interpolated['headers'])
  43. value.presence || {}
  44. end
  45. def basic_auth_credentials(value = interpolated['basic_auth'])
  46. case value
  47. when nil, ''
  48. return nil
  49. when Array
  50. return value if value.size == 2
  51. when /:/
  52. return value.split(/:/, 2)
  53. end
  54. raise ArgumentError.new("bad value for basic_auth: #{value.inspect}")
  55. end
  56. def faraday_backend
  57. ENV.fetch('FARADAY_HTTP_BACKEND', 'typhoeus').to_sym
  58. end
  59. def user_agent
  60. interpolated['user_agent'].presence || self.class.default_user_agent
  61. end
  62. module ClassMethods
  63. def default_user_agent
  64. ENV.fetch('DEFAULT_HTTP_USER_AGENT', "Huginn - https://github.com/cantino/huginn")
  65. end
  66. end
  67. end