Module: Zerobounce::GetFileHelper

Defined in:
lib/zerobounce/get_file_helper.rb

Overview

Bulk getfile response handling (v2): HTTP errors, JSON error bodies (including HTTP 200).

Class Method Summary collapse

Class Method Details

.format_error_message(body) ⇒ String

Parameters:

  • body (String)

Returns:

  • (String)


40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/zerobounce/get_file_helper.rb', line 40

def format_error_message(body)
  o = JSON.parse(body.to_s)
  return body.to_s unless o.is_a?(Hash)

  %w[message error error_message].each do |k|
    v = o[k]
    next if v.nil?
    return v.strip if v.is_a?(String) && !v.strip.empty?
    return v[0].strip if v.is_a?(Array) && v[0].is_a?(String)
  end
  body.to_s
rescue JSON::ParserError
  body.to_s.empty? ? 'Invalid getfile response' : body.to_s
end

.json_indicates_error?(body) ⇒ Boolean

Parameters:

  • body (String)

Returns:

  • (Boolean)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/zerobounce/get_file_helper.rb', line 13

def json_indicates_error?(body)
  t = body.to_s.lstrip
  return false if t.empty? || t[0] != '{'

  o = JSON.parse(t)
  return false unless o.is_a?(Hash)

  if o.key?('success')
    s = o['success']
    return true if s == false || s == 'False' || s == 'false'
  end

  %w[message error error_message].each do |k|
    v = o[k]
    next if v.nil?

    return true if v.is_a?(String) && !v.strip.empty?
    return true if v.is_a?(Array) && !v.empty?
  end

  o.key?('success')
rescue JSON::ParserError
  false
end

.process_getfile_response(response) ⇒ String

Returns CSV/text body on success.

Parameters:

  • response (RestClient::Response)

Returns:

  • (String)

    CSV/text body on success



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/zerobounce/get_file_helper.rb', line 67

def process_getfile_response(response)
  code = response.code.to_i
  body_str = response.body.to_s
  ct = (response.headers[:content_type] || response.headers['Content-Type'] || '').to_s

  if code > 299
    msg = if body_str.lstrip.start_with?('{')
            format_error_message(body_str)
          else
            body_str.empty? ? "HTTP #{code}" : body_str
          end
    raise msg
  end

  if should_treat_as_error?(body_str, ct)
    raise format_error_message(body_str)
  end

  io = StringIO.new(response.body)
  io.set_encoding_by_bom
  io.string
end

.should_treat_as_error?(body, content_type) ⇒ Boolean

Parameters:

  • body (String)
  • content_type (String)

Returns:

  • (Boolean)


58
59
60
61
62
63
# File 'lib/zerobounce/get_file_helper.rb', line 58

def should_treat_as_error?(body, content_type)
  ct = content_type.to_s.downcase
  return true if ct.include?('application/json')

  json_indicates_error?(body)
end