web_request_concern.rb 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 @default_encoding
  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. # Return body as binary if default_encoding is nil
  44. next if encoding.nil?
  45. end
  46. body.encode!(Encoding::UTF_8, encoding)
  47. end
  48. end
  49. end
  50. Faraday::Response.register_middleware character_encoding: CharacterEncoding
  51. extend ActiveSupport::Concern
  52. def validate_web_request_options!
  53. if options['user_agent'].present?
  54. errors.add(:base, "user_agent must be a string") unless options['user_agent'].is_a?(String)
  55. end
  56. if options['proxy'].present?
  57. errors.add(:base, "proxy must be a string") unless options['proxy'].is_a?(String)
  58. end
  59. if options['disable_ssl_verification'].present? && boolify(options['disable_ssl_verification']).nil?
  60. errors.add(:base, "if provided, disable_ssl_verification must be true or false")
  61. end
  62. unless headers(options['headers']).is_a?(Hash)
  63. errors.add(:base, "if provided, headers must be a hash")
  64. end
  65. begin
  66. basic_auth_credentials(options['basic_auth'])
  67. rescue ArgumentError => e
  68. errors.add(:base, e.message)
  69. end
  70. if (encoding = options['force_encoding']).present?
  71. case encoding
  72. when String
  73. begin
  74. Encoding.find(encoding)
  75. rescue ArgumentError
  76. errors.add(:base, "Unknown encoding: #{encoding.inspect}")
  77. end
  78. else
  79. errors.add(:base, "force_encoding must be a string")
  80. end
  81. end
  82. end
  83. # The default encoding for a text content with no `charset`
  84. # specified in the Content-Type header. Override this and make it
  85. # return nil if you want to detect the encoding on your own.
  86. def default_encoding
  87. Encoding::UTF_8
  88. end
  89. def faraday
  90. faraday_options = {
  91. ssl: {
  92. verify: !boolify(options['disable_ssl_verification'])
  93. }
  94. }
  95. @faraday ||= Faraday.new(faraday_options) { |builder|
  96. builder.response :character_encoding,
  97. force_encoding: interpolated['force_encoding'].presence,
  98. default_encoding: default_encoding,
  99. unzip: interpolated['unzip'].presence
  100. builder.headers = headers if headers.length > 0
  101. builder.headers[:user_agent] = user_agent
  102. builder.proxy interpolated['proxy'].presence
  103. unless boolify(interpolated['disable_redirect_follow'])
  104. builder.use FaradayMiddleware::FollowRedirects
  105. end
  106. builder.request :multipart
  107. builder.request :url_encoded
  108. if boolify(interpolated['disable_url_encoding'])
  109. builder.options.params_encoder = DoNotEncoder
  110. end
  111. if userinfo = basic_auth_credentials
  112. builder.request :basic_auth, *userinfo
  113. end
  114. builder.use FaradayMiddleware::Gzip
  115. case backend = faraday_backend
  116. when :typhoeus
  117. require 'typhoeus/adapters/faraday'
  118. end
  119. builder.adapter backend
  120. }
  121. end
  122. def headers(value = interpolated['headers'])
  123. value.presence || {}
  124. end
  125. def basic_auth_credentials(value = interpolated['basic_auth'])
  126. case value
  127. when nil, ''
  128. return nil
  129. when Array
  130. return value if value.size == 2
  131. when /:/
  132. return value.split(/:/, 2)
  133. end
  134. raise ArgumentError.new("bad value for basic_auth: #{value.inspect}")
  135. end
  136. def faraday_backend
  137. ENV.fetch('FARADAY_HTTP_BACKEND', 'typhoeus').to_sym
  138. end
  139. def user_agent
  140. interpolated['user_agent'].presence || self.class.default_user_agent
  141. end
  142. module ClassMethods
  143. def default_user_agent
  144. ENV.fetch('DEFAULT_HTTP_USER_AGENT', "Huginn - https://github.com/huginn/huginn")
  145. end
  146. end
  147. end