Module: HTTPX::Utils

Included in:
Transcoder::Multipart::Decoder
Defined in:
lib/httpx/utils.rb

Constant Summary collapse

TOKEN =
%r{[^\s()<>,;:\\"/\[\]?=]+}.freeze
VALUE =
/"(?:\\"|[^"])*"|#{TOKEN}/.freeze
FILENAME_REGEX =
/\s*filename=(#{VALUE})/.freeze
FILENAME_EXTENSION_REGEX =
/\s*filename\*=(#{VALUE})/.freeze
URIParser =
URI::RFC2396_Parser.new

Class Method Summary collapse

Class Method Details

.elapsed_time(monotonic_timestamp) ⇒ Object



18
19
20
# File 'lib/httpx/utils.rb', line 18

def elapsed_time(monotonic_timestamp)
  Process.clock_gettime(Process::CLOCK_MONOTONIC) - monotonic_timestamp
end

.get_filename(header, _prefix_regex = nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/httpx/utils.rb', line 33

def get_filename(header, _prefix_regex = nil)
  filename = nil
  case header
  when FILENAME_REGEX
    filename = Regexp.last_match(1)
    filename = Regexp.last_match(1) if filename =~ /^"(.*)"$/
  when FILENAME_EXTENSION_REGEX
    filename = Regexp.last_match(1)
    encoding, _, filename = filename.split("'", 3)
  end

  return unless filename

  filename = URI::DEFAULT_PARSER.unescape(filename) if filename.scan(/%.?.?/).all? { |s| /%[0-9a-fA-F]{2}/.match?(s) }

  filename.scrub!

  filename = filename.gsub(/\\(.)/, '\1') unless /\\[^\\"]/.match?(filename)

  filename.force_encoding ::Encoding.find(encoding) if encoding

  filename
end

.nowObject



14
15
16
# File 'lib/httpx/utils.rb', line 14

def now
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
end

.parse_retry_after(retry_after) ⇒ Object

The value of this field can be either an HTTP-date or a number of seconds to delay after the response is received.



24
25
26
27
28
29
30
31
# File 'lib/httpx/utils.rb', line 24

def parse_retry_after(retry_after)
  # first: bet on it being an integer
  Integer(retry_after)
rescue ArgumentError
  # Then it's a datetime
  time = Time.httpdate(retry_after)
  time - Time.now
end

.to_uri(uri) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/httpx/utils.rb', line 59

def to_uri(uri)
  return URI(uri) unless uri.is_a?(String) && !uri.ascii_only?

  uri = URI(URIParser.escape(uri))

  non_ascii_hostname = URIParser.unescape(uri.host)

  non_ascii_hostname.force_encoding(Encoding::UTF_8)

  idna_hostname = Punycode.encode_hostname(non_ascii_hostname)

  uri.host = idna_hostname
  uri.non_ascii_hostname = non_ascii_hostname
  uri
end