web_request_concern.rb 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. require 'faraday'
  2. require 'faraday_middleware'
  3. module WebRequestConcern
  4. module DoNotEncoder
  5. def self.encode(params)
  6. params.map do |key, value|
  7. value.nil? ? "#{key}" : "#{key}=#{value}"
  8. end.join('&')
  9. end
  10. def self.decode(val)
  11. [val]
  12. end
  13. end
  14. class CharacterEncoding < Faraday::Middleware
  15. def initialize(app, force_encoding: nil, default_encoding: nil, unzip: nil)
  16. super(app)
  17. @force_encoding = force_encoding
  18. @default_encoding = default_encoding
  19. @unzip = unzip
  20. end
  21. def call(env)
  22. @app.call(env).on_complete do |env|
  23. body = env[:body]
  24. case @unzip
  25. when 'gzip'.freeze
  26. body.replace(ActiveSupport::Gzip.decompress(body))
  27. end
  28. case
  29. when @force_encoding
  30. encoding = @force_encoding
  31. when body.encoding == Encoding::ASCII_8BIT
  32. # Not all Faraday adapters support automatic charset
  33. # detection, so we do that.
  34. case env[:response_headers][:content_type]
  35. when /;\s*charset\s*=\s*([^()<>@,;:\\\"\/\[\]?={}\s]+)/i
  36. encoding = Encoding.find($1) rescue nil
  37. when /\A\s*(?:text\/[^\s;]+|application\/(?:[^\s;]+\+)?(?:xml|json))\s*(?:;|\z)/i
  38. encoding = @default_encoding
  39. else
  40. # Never try to transcode a binary content
  41. next
  42. end
  43. end
  44. body.encode!(Encoding::UTF_8, encoding) unless body.encoding == Encoding::UTF_8
  45. end
  46. end
  47. end
  48. Faraday::Response.register_middleware character_encoding: CharacterEncoding
  49. extend ActiveSupport::Concern
  50. def validate_web_request_options!
  51. if options['user_agent'].present?
  52. errors.add(:base, "user_agent must be a string") unless options['user_agent'].is_a?(String)
  53. end
  54. if options['disable_ssl_verification'].present? && boolify(options['disable_ssl_verification']).nil?
  55. errors.add(:base, "if provided, disable_ssl_verification must be true or false")
  56. end
  57. unless headers(options['headers']).is_a?(Hash)
  58. errors.add(:base, "if provided, headers must be a hash")
  59. end
  60. begin
  61. basic_auth_credentials(options['basic_auth'])
  62. rescue ArgumentError => e
  63. errors.add(:base, e.message)
  64. end
  65. if (encoding = options['force_encoding']).present?
  66. case encoding
  67. when String
  68. begin
  69. Encoding.find(encoding)
  70. rescue ArgumentError
  71. errors.add(:base, "Unknown encoding: #{encoding.inspect}")
  72. end
  73. else
  74. errors.add(:base, "force_encoding must be a string")
  75. end
  76. end
  77. end
  78. def default_encoding
  79. Encoding::UTF_8
  80. end
  81. def faraday
  82. faraday_options = {
  83. ssl: {
  84. verify: !boolify(options['disable_ssl_verification'])
  85. }
  86. }
  87. @faraday ||= Faraday.new(faraday_options) { |builder|
  88. builder.response :character_encoding,
  89. force_encoding: interpolated['force_encoding'].presence,
  90. default_encoding: default_encoding,
  91. unzip: interpolated['unzip'].presence
  92. builder.headers = headers if headers.length > 0
  93. builder.headers[:user_agent] = user_agent
  94. builder.use FaradayMiddleware::FollowRedirects
  95. builder.request :url_encoded
  96. if boolify(interpolated['disable_url_encoding'])
  97. builder.options.params_encoder = DoNotEncoder
  98. end
  99. if userinfo = basic_auth_credentials
  100. builder.request :basic_auth, *userinfo
  101. end
  102. builder.use FaradayMiddleware::Gzip
  103. case backend = faraday_backend
  104. when :typhoeus
  105. require 'typhoeus/adapters/faraday'
  106. end
  107. builder.adapter backend
  108. }
  109. end
  110. def headers(value = interpolated['headers'])
  111. value.presence || {}
  112. end
  113. def basic_auth_credentials(value = interpolated['basic_auth'])
  114. case value
  115. when nil, ''
  116. return nil
  117. when Array
  118. return value if value.size == 2
  119. when /:/
  120. return value.split(/:/, 2)
  121. end
  122. raise ArgumentError.new("bad value for basic_auth: #{value.inspect}")
  123. end
  124. def faraday_backend
  125. ENV.fetch('FARADAY_HTTP_BACKEND', 'typhoeus').to_sym
  126. end
  127. def user_agent
  128. interpolated['user_agent'].presence || self.class.default_user_agent
  129. end
  130. module ClassMethods
  131. def default_user_agent
  132. ENV.fetch('DEFAULT_HTTP_USER_AGENT', "Huginn - https://github.com/cantino/huginn")
  133. end
  134. end
  135. end