web_request_concern.rb 4.7 KB

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