metainspector 5.21.2 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -0
  3. data/README.md +215 -48
  4. data/lib/meta_inspector/attempt_timeout.rb +40 -0
  5. data/lib/meta_inspector/document.rb +101 -68
  6. data/lib/meta_inspector/errors.rb +5 -1
  7. data/lib/meta_inspector/html_encoding.rb +183 -0
  8. data/lib/meta_inspector/http_session.rb +74 -45
  9. data/lib/meta_inspector/image_downloader.rb +37 -24
  10. data/lib/meta_inspector/parser.rb +144 -34
  11. data/lib/meta_inspector/parsers/base.rb +7 -2
  12. data/lib/meta_inspector/parsers/head_links.rb +20 -28
  13. data/lib/meta_inspector/parsers/iframes.rb +2 -3
  14. data/lib/meta_inspector/parsers/images.rb +119 -70
  15. data/lib/meta_inspector/parsers/links.rb +19 -9
  16. data/lib/meta_inspector/parsers/meta_tags.rb +22 -31
  17. data/lib/meta_inspector/parsers/texts.rb +43 -33
  18. data/lib/meta_inspector/request.rb +67 -55
  19. data/lib/meta_inspector/url.rb +43 -19
  20. data/lib/meta_inspector/url_policy.rb +18 -11
  21. data/lib/meta_inspector/version.rb +1 -1
  22. data/lib/meta_inspector.rb +14 -13
  23. data/lib/metainspector.rb +1 -1
  24. data/meta_inspector.gemspec +1 -1
  25. data/spec/document_spec.rb +154 -56
  26. data/spec/meta_inspector/content_type_spec.rb +47 -0
  27. data/spec/meta_inspector/head_links_spec.rb +3 -3
  28. data/spec/meta_inspector/images_spec.rb +82 -1
  29. data/spec/meta_inspector/links_spec.rb +98 -2
  30. data/spec/meta_inspector/meta_inspector_spec.rb +3 -25
  31. data/spec/meta_inspector/meta_tags_spec.rb +53 -0
  32. data/spec/meta_inspector/texts_spec.rb +140 -3
  33. data/spec/meta_inspector/timeouts_spec.rb +107 -0
  34. data/spec/noscript_spec.rb +179 -0
  35. data/spec/parser_spec.rb +380 -10
  36. data/spec/query_string_spec.rb +125 -0
  37. data/spec/request_errors_spec.rb +91 -0
  38. data/spec/request_spec.rb +28 -10
  39. data/spec/response_encoding_spec.rb +487 -0
  40. data/spec/url_filter_spec.rb +2 -1
  41. data/spec/url_spec.rb +37 -0
  42. metadata +10 -2
@@ -14,7 +14,7 @@ module MetaInspector
14
14
  # * headers: object containing custom headers for the request
15
15
  # * normalize_url: true by default
16
16
  # * download_images: fetch missing image dimensions. Defaults to true
17
- # * max_image_downloads: maximum image size lookups, or nil for unlimited
17
+ # * max_image_downloads: maximum image size lookups. Defaults to 20; nil for unlimited
18
18
  # * download_image_options: supports reject_invalid_images (default false)
19
19
  # * inline_image_data: return full data URLs in image results (default false)
20
20
  # * fetch_all_image_meta: enable image validity metadata (default false)
@@ -22,65 +22,61 @@ module MetaInspector
22
22
  # * url_filter: callable receiving a URI before each request; false/nil rejects it
23
23
  # * faraday_options: an optional hash of options to pass to Faraday on the request.
24
24
  # Its faraday_http_cache key configures response caching with Faraday::HttpCache
25
- # * faraday_http_cache: deprecated, use faraday_options: { faraday_http_cache: ... }
26
- def initialize(initial_url, options = {})
27
- options = defaults.merge(options)
28
- max_html_bytes = options[:max_html_bytes]
29
- unless max_html_bytes.nil? || (max_html_bytes.is_a?(Integer) && max_html_bytes >= 0)
30
- raise ArgumentError, 'max_html_bytes must be a non-negative Integer or nil'
31
- end
32
- @max_image_downloads = options[:max_image_downloads]
33
- unless @max_image_downloads.nil? || (@max_image_downloads.is_a?(Integer) && @max_image_downloads >= 0)
34
- raise ArgumentError, 'max_image_downloads must be a non-negative Integer or nil'
35
- end
25
+ #
26
+ # Raises ArgumentError for any other key, including String keys
27
+ OPTIONS = %i[
28
+ connection_timeout read_timeout retries encoding allow_redirections allow_non_html_content
29
+ head_first document headers normalize_url download_images max_image_downloads
30
+ download_image_options fetch_all_image_meta inline_image_data max_html_bytes url_filter
31
+ faraday_options
32
+ ].freeze
36
33
 
37
- @connection_timeout = options[:connection_timeout]
38
- @read_timeout = options[:read_timeout]
39
- @retries = options[:retries]
40
- @encoding = options[:encoding]
34
+ # Options used by Request and by Parser. HttpSession and ImageDownloader
35
+ # pick their own options from the whole hash.
36
+ REQUEST_OPTIONS = %i[
37
+ allow_redirections head_first allow_non_html_content connection_timeout read_timeout encoding
38
+ ].freeze
39
+ PARSER_OPTIONS = %i[
40
+ download_images max_html_bytes max_image_downloads download_image_options fetch_all_image_meta
41
+ inline_image_data
42
+ ].freeze
43
+ private_constant :REQUEST_OPTIONS, :PARSER_OPTIONS
44
+
45
+ def initialize(initial_url, options = {})
46
+ validate_option_keys!(options)
47
+ options = defaults.merge(options)
48
+ validate_limit!(options, :max_html_bytes)
49
+ validate_limit!(options, :max_image_downloads)
41
50
 
42
51
  @allow_redirections = options[:allow_redirections]
43
52
  @allow_non_html_content = options[:allow_non_html_content]
53
+ @headers = options[:headers]
54
+ @document = options[:document]
44
55
 
45
- @document = options[:document]
46
- @download_images = options[:download_images]
47
- @headers = options[:headers]
48
- @normalize_url = options[:normalize_url]
49
- @faraday_options = options[:faraday_options]
50
- @faraday_http_cache = options[:faraday_http_cache]
51
- @http_session = MetaInspector::HttpSession.new(options)
52
- @url = MetaInspector::URL.new(initial_url, normalize: @normalize_url)
53
- @request = MetaInspector::Request.new(@url, http_session: @http_session,
54
- allow_redirections: @allow_redirections,
55
- head_first: options[:head_first],
56
- allow_non_html_content: @allow_non_html_content,
57
- connection_timeout: @connection_timeout,
58
- read_timeout: @read_timeout,
59
- retries: @retries,
60
- encoding: @encoding,
61
- headers: @headers,
62
- faraday_options: @faraday_options,
63
- faraday_http_cache: @faraday_http_cache) unless @document
64
- @parser = MetaInspector::Parser.new(self, download_images: @download_images,
65
- max_html_bytes: max_html_bytes,
66
- max_image_downloads: @max_image_downloads,
67
- download_image_options: options[:download_image_options],
68
- fetch_all_image_meta: options[:fetch_all_image_meta],
69
- inline_image_data: options[:inline_image_data],
70
- image_downloader: MetaInspector::ImageDownloader.new(@http_session, @url, options))
56
+ http_session = HttpSession.new(options)
57
+ @url = URL.new(initial_url, normalize: options[:normalize_url])
58
+ @request = Request.new(@url, http_session: http_session, **options.slice(*REQUEST_OPTIONS)) unless @document
59
+ @parser = Parser.new(self, image_downloader: ImageDownloader.new(http_session, @url, options),
60
+ **options.slice(*PARSER_OPTIONS))
71
61
  end
72
62
 
73
63
  extend Forwardable
74
- delegate [:url, :scheme, :host, :root_url,
75
- :tracked?, :untracked_url, :untrack!] => :@url
64
+ delegate %i[url scheme host root_url tracked? untracked_url untrack!] => :@url
76
65
 
77
- delegate [:content_type, :response] => :@request
66
+ # No request is made when the HTML is passed with the document: option,
67
+ # so these return nil in that case
68
+ def content_type
69
+ @request&.content_type
70
+ end
78
71
 
79
- delegate [:parsed, :language, :title, :best_title, :author, :best_author,
80
- :h1, :h2, :h3, :h4, :h5, :h6, :description, :best_description, :links,
81
- :images, :iframes, :iframe_sources, :feeds, :feed, :charset, :meta_tags,
82
- :meta_tag, :meta, :favicon,
83
- :head_links, :stylesheets, :canonicals] => :@parser
72
+ def response
73
+ @request&.response
74
+ end
75
+
76
+ delegate %i[
77
+ parsed language title best_title author best_author h1 h2 h3 h4 h5 h6 description best_description
78
+ links images iframes iframe_sources feeds charset meta_tags meta_tag meta head_links stylesheets canonicals
79
+ ] => :@parser
84
80
 
85
81
  # Returns all document data as a nested Hash
86
82
  def to_hash
@@ -110,8 +106,8 @@ module MetaInspector
110
106
  'content_type' => content_type,
111
107
  'meta_tags' => meta_tags,
112
108
  'favicon' => images.favicon,
113
- 'response' => { 'status' => response.status,
114
- 'headers' => response.headers }
109
+ 'response' => response && { 'status' => response.status,
110
+ 'headers' => serialized_response_headers }
115
111
  }
116
112
  end
117
113
 
@@ -122,20 +118,56 @@ module MetaInspector
122
118
 
123
119
  private
124
120
 
121
+ # An option that is misspelled, or given with a String key (as when read from
122
+ # JSON or YAML), would otherwise be ignored: with 'document' => html, the page
123
+ # would be fetched instead of parsing the HTML.
124
+ def validate_option_keys!(options)
125
+ unknown = options.keys - OPTIONS
126
+ return if unknown.empty?
127
+
128
+ message = "Unknown option#{'s' if unknown.size > 1}: #{unknown.map(&:inspect).join(', ')}"
129
+ message += ' (option keys must be Symbols)' if unknown.any?(String)
130
+ if unknown.include?(:faraday_http_cache)
131
+ message += ' (pass it inside faraday_options: { faraday_http_cache: ... })'
132
+ end
133
+ raise ArgumentError, message
134
+ end
135
+
136
+ def validate_limit!(options, name)
137
+ value = options[name]
138
+ return if value.nil? || (value.is_a?(Integer) && value >= 0)
139
+
140
+ raise ArgumentError, "#{name} must be a non-negative Integer or nil"
141
+ end
142
+
143
+ # Middleware can add headers that Net::HTTP would have normalized: faraday-gzip
144
+ # sets "Content-Length" to an Integer after decompressing. Downcase the names
145
+ # and re-encode only String values.
146
+ def serialized_response_headers
147
+ response.headers.to_h do |name, value|
148
+ [name.to_s.downcase, value.is_a?(String) ? utf8_header_value(value) : value]
149
+ end
150
+ end
151
+
152
+ # Net::HTTP returns binary strings, even when the bytes are valid UTF-8.
153
+ def utf8_header_value(value)
154
+ source_encoding = value.encoding == Encoding::BINARY ? Encoding::UTF_8 : value.encoding
155
+ value.encode(Encoding::UTF_8, source_encoding, invalid: :replace, undef: :replace)
156
+ end
157
+
125
158
  def defaults
126
- { :connection_timeout => 20,
127
- :read_timeout => 20,
128
- :retries => 3,
129
- :headers => {
130
- 'User-Agent' => default_user_agent,
131
- 'Accept-Encoding' => 'identity'
132
- },
133
- :allow_redirections => true,
134
- :allow_non_html_content => false,
135
- :head_first => false,
136
- :normalize_url => true,
137
- :download_images => true,
138
- :max_image_downloads => nil }
159
+ {
160
+ connection_timeout: 20,
161
+ read_timeout: 20,
162
+ retries: 3,
163
+ headers: { 'User-Agent' => default_user_agent, 'Accept-Encoding' => 'identity' },
164
+ allow_redirections: true,
165
+ allow_non_html_content: false,
166
+ head_first: false,
167
+ normalize_url: true,
168
+ download_images: true,
169
+ max_image_downloads: 20
170
+ }
139
171
  end
140
172
 
141
173
  def default_user_agent
@@ -143,9 +175,10 @@ module MetaInspector
143
175
  end
144
176
 
145
177
  def document
146
- @document ||= if !allow_non_html_content && !content_type.nil? && content_type != 'text/html'
147
- fail MetaInspector::NonHtmlError.new "The url provided contains #{content_type} content instead of text/html content"
148
- else
178
+ @document ||= begin
179
+ unless allow_non_html_content || Request.html_content_type?(content_type)
180
+ raise NonHtmlError.for(content_type)
181
+ end
149
182
  @request.read
150
183
  end
151
184
  end
@@ -11,5 +11,9 @@ module MetaInspector
11
11
 
12
12
  class ParserError < Error; end
13
13
 
14
- class NonHtmlError < ParserError; end
14
+ class NonHtmlError < ParserError
15
+ def self.for(content_type)
16
+ new("The url provided contains #{content_type} content instead of text/html content")
17
+ end
18
+ end
15
19
  end
@@ -0,0 +1,183 @@
1
+ require 'nokogiri'
2
+
3
+ module MetaInspector
4
+ # HTML uses browser-compatible supersets of several legacy encodings.
5
+ # https://encoding.spec.whatwg.org/#names-and-labels
6
+ module HtmlEncoding
7
+ SUPERSETS = {
8
+ Encoding.find('GB2312') => 'GBK',
9
+ Encoding.find('Shift_JIS') => 'Windows-31J',
10
+ Encoding.find('EUC-KR') => 'CP949',
11
+ Encoding.find('Big5') => 'Big5-HKSCS',
12
+ Encoding.find('ISO-8859-1') => 'Windows-1252',
13
+ Encoding.find('US-ASCII') => 'Windows-1252',
14
+ Encoding.find('ISO-8859-9') => 'Windows-1254',
15
+ Encoding.find('ISO-8859-11') => 'Windows-874',
16
+ Encoding.find('TIS-620') => 'Windows-874'
17
+ }.freeze
18
+
19
+ # Labels browsers accept, keyed by the Ruby name of their encoding.
20
+ # The replacement and x-user-defined encodings are left out: their labels
21
+ # are ignored like unknown ones.
22
+ LABELS = {
23
+ 'UTF-8' => %w[unicode-1-1-utf-8 unicode11utf8 unicode20utf8 utf-8 utf8 x-unicode20utf8],
24
+ 'IBM866' => %w[866 cp866 csibm866 ibm866],
25
+ 'ISO-8859-2' => %w[csisolatin2 iso-8859-2 iso-ir-101 iso8859-2 iso88592 iso_8859-2 iso_8859-2:1987 l2 latin2],
26
+ 'ISO-8859-3' => %w[csisolatin3 iso-8859-3 iso-ir-109 iso8859-3 iso88593 iso_8859-3 iso_8859-3:1988 l3 latin3],
27
+ 'ISO-8859-4' => %w[csisolatin4 iso-8859-4 iso-ir-110 iso8859-4 iso88594 iso_8859-4 iso_8859-4:1988 l4 latin4],
28
+ 'ISO-8859-5' => %w[csisolatincyrillic cyrillic iso-8859-5 iso-ir-144 iso8859-5 iso88595 iso_8859-5
29
+ iso_8859-5:1988],
30
+ 'ISO-8859-6' => %w[arabic asmo-708 csiso88596e csiso88596i csisolatinarabic ecma-114 iso-8859-6 iso-8859-6-e
31
+ iso-8859-6-i iso-ir-127 iso8859-6 iso88596 iso_8859-6 iso_8859-6:1987],
32
+ 'ISO-8859-7' => %w[csisolatingreek ecma-118 elot_928 greek greek8 iso-8859-7 iso-ir-126 iso8859-7 iso88597
33
+ iso_8859-7 iso_8859-7:1987 sun_eu_greek],
34
+ # Includes the ISO-8859-8-I labels, which only differ in text direction.
35
+ 'ISO-8859-8' => %w[csiso88598e csisolatinhebrew hebrew iso-8859-8 iso-8859-8-e iso-ir-138 iso8859-8 iso88598
36
+ iso_8859-8 iso_8859-8:1988 visual csiso88598i iso-8859-8-i logical],
37
+ 'ISO-8859-10' => %w[csisolatin6 iso-8859-10 iso-ir-157 iso8859-10 iso885910 l6 latin6],
38
+ 'ISO-8859-13' => %w[iso-8859-13 iso8859-13 iso885913],
39
+ 'ISO-8859-14' => %w[iso-8859-14 iso8859-14 iso885914],
40
+ 'ISO-8859-15' => %w[csisolatin9 iso-8859-15 iso8859-15 iso885915 iso_8859-15 l9],
41
+ 'ISO-8859-16' => %w[iso-8859-16],
42
+ 'KOI8-R' => %w[cskoi8r koi koi8 koi8-r koi8_r],
43
+ 'KOI8-U' => %w[koi8-ru koi8-u],
44
+ 'macRoman' => %w[csmacintosh mac macintosh x-mac-roman],
45
+ 'Windows-874' => %w[dos-874 iso-8859-11 iso8859-11 iso885911 tis-620 windows-874],
46
+ 'Windows-1250' => %w[cp1250 windows-1250 x-cp1250],
47
+ 'Windows-1251' => %w[cp1251 windows-1251 x-cp1251],
48
+ 'Windows-1252' => %w[ansi_x3.4-1968 ascii cp1252 cp819 csisolatin1 ibm819 iso-8859-1 iso-ir-100 iso8859-1
49
+ iso88591 iso_8859-1 iso_8859-1:1987 l1 latin1 us-ascii windows-1252 x-cp1252],
50
+ 'Windows-1253' => %w[cp1253 windows-1253 x-cp1253],
51
+ 'Windows-1254' => %w[cp1254 csisolatin5 iso-8859-9 iso-ir-148 iso8859-9 iso88599 iso_8859-9 iso_8859-9:1989
52
+ l5 latin5 windows-1254 x-cp1254],
53
+ 'Windows-1255' => %w[cp1255 windows-1255 x-cp1255],
54
+ 'Windows-1256' => %w[cp1256 windows-1256 x-cp1256],
55
+ 'Windows-1257' => %w[cp1257 windows-1257 x-cp1257],
56
+ 'Windows-1258' => %w[cp1258 windows-1258 x-cp1258],
57
+ 'macCyrillic' => %w[x-mac-cyrillic x-mac-ukrainian],
58
+ 'GBK' => %w[chinese csgb2312 csiso58gb231280 gb2312 gb_2312 gb_2312-80 gbk iso-ir-58 x-gbk],
59
+ 'GB18030' => %w[gb18030],
60
+ 'Big5' => %w[big5 big5-hkscs cn-big5 csbig5 x-x-big5],
61
+ 'EUC-JP' => %w[cseucpkdfmtjapanese euc-jp x-euc-jp],
62
+ 'ISO-2022-JP' => %w[csiso2022jp iso-2022-jp],
63
+ 'Shift_JIS' => %w[csshiftjis ms932 ms_kanji shift-jis shift_jis sjis windows-31j x-sjis],
64
+ 'EUC-KR' => %w[cseuckr csksc56011987 euc-kr iso-ir-149 korean ks_c_5601-1987 ks_c_5601-1989 ksc5601
65
+ ksc_5601 windows-949],
66
+ 'UTF-16BE' => %w[unicodefffe utf-16be],
67
+ 'UTF-16LE' => %w[csunicode iso-10646-ucs-2 ucs-2 unicode unicodefeff utf-16 utf-16le]
68
+ }.flat_map { |encoding, labels| labels.map { |label| [label, encoding] } }.to_h.freeze
69
+
70
+ # Returns the charset label of a Content-Type value, such as
71
+ # "text/html; charset=utf-8", or nil if there is none.
72
+ def self.charset_param(content_type)
73
+ content_type.to_s[/(?:\A|;)\s*charset\s*=\s*["']?([^;\s"']+)/i, 1]
74
+ end
75
+
76
+ # Returns the encoding for a charset label, or nil if browsers don't know it.
77
+ def self.resolve(label)
78
+ LABELS[label.to_s.strip.downcase]
79
+ end
80
+
81
+ def self.ruby_encoding?(label)
82
+ Encoding.find(label)
83
+ true
84
+ rescue ArgumentError
85
+ false
86
+ end
87
+
88
+ def self.superset(label)
89
+ SUPERSETS[Encoding.find(label)] if label
90
+ rescue ArgumentError
91
+ nil
92
+ end
93
+
94
+ def self.normalize(html)
95
+ encoding = superset(html.encoding)
96
+ return html unless encoding
97
+
98
+ # Ruby's Big5-HKSCS byte validation rejects some sequences its transcoder
99
+ # supports. Convert before scrub/tr can reject or replace those bytes.
100
+ html.dup.force_encoding(encoding).encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
101
+ end
102
+
103
+ # Resolve binary HTML before Nokogiri can choose a later meta tag.
104
+ class Detector < Nokogiri::XML::SAX::Document
105
+ BYTE_ORDER_MARKS = {
106
+ "\x00\x00\xFE\xFF".b => 'UTF-32BE',
107
+ "\xFF\xFE\x00\x00".b => 'UTF-32LE',
108
+ "\xEF\xBB\xBF".b => 'UTF-8',
109
+ "\xFE\xFF".b => 'UTF-16BE',
110
+ "\xFF\xFE".b => 'UTF-16LE'
111
+ }.freeze
112
+ TEXT_ELEMENTS = %w[script style title textarea xmp iframe noembed noframes plaintext].freeze
113
+ private_constant :BYTE_ORDER_MARKS, :TEXT_ELEMENTS
114
+
115
+ def self.detect(html)
116
+ # HTTP charsets and the encoding: option already tag the body string.
117
+ return html.encoding.name unless html.encoding == Encoding::BINARY
118
+
119
+ encoding = byte_order_mark_encoding(html)
120
+ return encoding if encoding
121
+
122
+ detector = new
123
+ catch(:metainspector_charset) do
124
+ # Every byte is valid in Latin-1. Only markup matters during this scan;
125
+ # using SAX avoids mistaking comments or script contents for meta tags.
126
+ Nokogiri::HTML4::SAX::Parser.new(detector, 'ISO-8859-1').parse(html) unless html.empty?
127
+ # Name the default rather than return nil, or libxml2 would read the
128
+ # unknown label from the meta tag and stop parsing there.
129
+ 'Windows-1252' if detector.unknown_label
130
+ end
131
+ end
132
+
133
+ attr_reader :unknown_label
134
+
135
+ def self.byte_order_mark_encoding(html)
136
+ BYTE_ORDER_MARKS.each do |mark, encoding|
137
+ return encoding if html.start_with?(mark)
138
+ end
139
+ nil
140
+ end
141
+
142
+ def start_element(name, attributes = [])
143
+ return if @text_element
144
+
145
+ if TEXT_ELEMENTS.include?(name)
146
+ @text_element = name
147
+ return
148
+ end
149
+ return unless name == 'meta'
150
+
151
+ attributes = attributes.to_h
152
+ charset = attributes['charset']
153
+ if !charset && attributes['http-equiv'].to_s.casecmp?('content-type')
154
+ charset = HtmlEncoding.charset_param(attributes['content'])
155
+ end
156
+ return if charset.to_s.strip.empty?
157
+
158
+ encoding = HtmlEncoding.resolve(charset)
159
+ # A page whose meta tag can be read as ASCII isn't UTF-16.
160
+ # https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encoding
161
+ encoding = 'UTF-8' if encoding&.start_with?('UTF-16')
162
+ # Keep labels that only Ruby and libxml2 know, such as UTF-7.
163
+ encoding ||= charset.strip if HtmlEncoding.ruby_encoding?(charset.strip)
164
+ throw :metainspector_charset, encoding if encoding
165
+
166
+ @unknown_label = true
167
+ end
168
+
169
+ def end_element(name)
170
+ @text_element = nil if name == @text_element
171
+ end
172
+ end
173
+ private_constant :Detector
174
+
175
+ def self.detect(html)
176
+ Detector.detect(html)
177
+ end
178
+
179
+ def self.byte_order_mark_encoding(html)
180
+ Detector.byte_order_mark_encoding(html) if html.encoding == Encoding::BINARY
181
+ end
182
+ end
183
+ end
@@ -8,77 +8,106 @@ require 'faraday/gzip'
8
8
  require 'faraday/retry'
9
9
  require_relative 'url_policy'
10
10
  require_relative 'limited_response'
11
+ require_relative 'attempt_timeout'
11
12
 
12
13
  module MetaInspector
13
14
  # Builds page and binary image transports from the same caller configuration.
14
15
  class HttpSession
16
+ # Faraday stores the query as a params hash and rebuilds it for the request,
17
+ # which sorts keys, drops repeated ones and re-escapes values. This encoder
18
+ # keeps the whole query as a single key, so it is sent as written.
19
+ module RawQuery
20
+ def self.decode(query)
21
+ query.to_s.empty? ? {} : { query => nil }
22
+ end
23
+
24
+ def self.encode(params)
25
+ params.keys.join('&')
26
+ end
27
+ end
28
+
15
29
  def initialize(options = {})
16
30
  @allow_redirections = options[:allow_redirections]
17
- @retries = options[:retries]
18
- @headers = options[:headers]
19
- @max_html_bytes = options[:max_html_bytes]
20
- @url_filter = options[:url_filter]
31
+ @retries = options[:retries]
32
+ @attempt_timeout = (options[:connection_timeout] || 0) + (options[:read_timeout] || 0) + 1
33
+ @headers = options[:headers]
34
+ @max_html_bytes = options[:max_html_bytes]
35
+ @url_filter = options[:url_filter]
21
36
  if !@url_filter.nil? && !@url_filter.respond_to?(:call)
22
37
  raise ArgumentError, 'url_filter must respond to call'
23
38
  end
24
- @cache = cache_option(options)
25
- @faraday_options = (options[:faraday_options] || {}).except(:faraday_http_cache)
39
+ faraday_options = options[:faraday_options] || {}
40
+ @cache = faraday_options[:faraday_http_cache]
41
+ @faraday_options = faraday_options.except(:faraday_http_cache)
26
42
  end
27
43
 
44
+ # Builds a connection for a page request or, with image: true, for an image
45
+ # lookup. Image lookups skip retries, the attempt deadline, decompression,
46
+ # the HTML size limit and the cache.
28
47
  def build(url, image: false, origin: nil, protect_redirect_callback: false)
29
- URLPolicy.validate!(url)
48
+ uri = URLPolicy.validate!(url)
30
49
  # Image requests must keep trusting the initial origin after page redirects.
31
50
  @page_origin ||= url.to_s unless image
32
- faraday_options = @faraday_options.merge(url: url)
33
- redirects = (faraday_options.delete(:redirect) || {}).dup
34
- if protect_redirect_callback && redirects[:callback]
35
- callback = redirects[:callback]
36
- redirects[:callback] = lambda do |*args|
37
- begin
38
- callback.call(*args)
39
- rescue StandardError => error
40
- raise URLPolicy::Failure.new(error)
41
- end
42
- end
43
- end
44
- Faraday.new(faraday_options) do |faraday|
45
- unless image
46
- faraday.request :retry, max: @retries
47
- # Responses run in reverse order: decompress before applying the charset.
48
- faraday.response :encoding if @max_html_bytes
49
- faraday.request :gzip if @max_html_bytes.nil?
50
- end
51
+ # Faraday.new decodes a query in its URL with the default encoder, before
52
+ # any configured one applies, so the query is added to the params after.
53
+ query = uri.query
54
+ uri.query = nil
55
+ faraday_options = @faraday_options.merge(url: uri.to_s)
56
+ faraday_options[:request] = { params_encoder: RawQuery }.merge(faraday_options[:request] || {})
57
+ redirects = redirect_options(faraday_options.delete(:redirect), protect_redirect_callback)
58
+
59
+ connection = Faraday.new(faraday_options) do |faraday|
60
+ page_middleware(faraday) unless image
51
61
  if @allow_redirections
52
- redirects[:limit] ||= 10
53
62
  faraday.use Faraday::FollowRedirects::Middleware, **redirects
54
63
  faraday.use :cookie_jar
55
64
  end
56
- faraday.use URLPolicy, @url_filter, image ? origin : nil,
57
- request_origin: @page_origin || origin
58
- faraday.use LimitedResponse, @max_html_bytes if !image && @max_html_bytes
59
- if !image && @cache.is_a?(Hash)
60
- cache_options = @cache.dup
61
- cache_options[:serializer] ||= Marshal
62
- faraday.use Faraday::HttpCache, **cache_options
63
- end
64
- faraday.use LimitedResponse::Streaming, @max_html_bytes if !image && @max_html_bytes
65
+ faraday.use URLPolicy, @url_filter, image ? origin : nil, request_origin: @page_origin || origin
66
+ page_limit_and_cache_middleware(faraday) unless image
65
67
  faraday.headers.merge!(@headers || {})
66
- faraday.response :encoding unless image || @max_html_bytes
67
68
  faraday.adapter :net_http
68
69
  end
70
+ connection.params.merge_query(query, connection.options.params_encoder)
71
+ connection
69
72
  end
70
73
 
71
74
  private
72
75
 
73
- def cache_option(options)
74
- nested = (options[:faraday_options] || {})[:faraday_http_cache]
75
- top_level = options[:faraday_http_cache]
76
- return nested if top_level.nil?
77
- unless nested.nil?
78
- raise ArgumentError, 'Pass faraday_http_cache inside faraday_options or as a top-level option, not both'
76
+ # With protect_callback, errors raised by the caller's redirect callback
77
+ # bypass the rescue clauses for network errors, and are re-raised as is.
78
+ def redirect_options(redirects, protect_callback)
79
+ redirects = (redirects || {}).dup
80
+ redirects[:limit] ||= 10
81
+ callback = redirects[:callback]
82
+ if protect_callback && callback
83
+ redirects[:callback] = lambda do |*args|
84
+ callback.call(*args)
85
+ rescue StandardError => error
86
+ raise URLPolicy::Failure.new(error)
87
+ end
88
+ end
89
+ redirects
90
+ end
91
+
92
+ # Outermost page middleware: each retry gets its own attempt deadline.
93
+ def page_middleware(faraday)
94
+ faraday.request :retry, max: @retries
95
+ faraday.use AttemptTimeout, @attempt_timeout
96
+ # Responses run in reverse order: decompress before applying the charset.
97
+ faraday.response :encoding
98
+ faraday.request :gzip if @max_html_bytes.nil?
99
+ end
100
+
101
+ # LimitedResponse wraps the cache and Streaming runs inside it, so cached
102
+ # bodies are checked too and the cache stores the received bytes.
103
+ def page_limit_and_cache_middleware(faraday)
104
+ faraday.use LimitedResponse, @max_html_bytes if @max_html_bytes
105
+ if @cache.is_a?(Hash)
106
+ cache_options = @cache.dup
107
+ cache_options[:serializer] ||= Marshal
108
+ faraday.use Faraday::HttpCache, **cache_options
79
109
  end
80
- Request.warn_faraday_http_cache_deprecation
81
- top_level
110
+ faraday.use LimitedResponse::Streaming, @max_html_bytes if @max_html_bytes
82
111
  end
83
112
  end
84
113
  end
@@ -39,12 +39,33 @@ module MetaInspector
39
39
 
40
40
  private
41
41
 
42
+ # The first MAX_BYTES bytes of a successful image response. complete is
43
+ # true when the whole body was read.
44
+ Download = Struct.new(:status, :headers, :bytes, :complete, keyword_init: true)
45
+ private_constant :Download
46
+
42
47
  def fetch(url, metadata:, reject_invalid_url:)
43
- bytes = ''.b
48
+ download = download(url, reject_invalid_url)
49
+ return unless download.status && (200..299).cover?(download.status)
50
+
51
+ dimensions = FastImage.size(StringIO.new(download.bytes))
52
+ return dimensions unless metadata
53
+
54
+ { dimensions: dimensions, type: FastImage.type(StringIO.new(download.bytes)), file_size: file_size(download) }
55
+ rescue URLPolicy::Failure => failure
56
+ raise failure.original
57
+ rescue URI::InvalidComponentError => error
58
+ raise MetaInspector::RequestError.new(error)
59
+ rescue Faraday::TimeoutError, Faraday::ConnectionFailed, Faraday::SSLError,
60
+ Faraday::FollowRedirects::RedirectLimitReached, URI::InvalidURIError, Timeout::Error
61
+ nil
62
+ end
63
+
64
+ # Streams the response and stops as soon as it has MAX_BYTES, gets an
65
+ # error status, or reaches TIMEOUT.
66
+ def download(url, reject_invalid_url)
67
+ download = Download.new(bytes: ''.b, complete: false)
44
68
  received = 0
45
- status = nil
46
- headers = nil
47
- completed = false
48
69
  stop = Object.new
49
70
  Timeout.timeout(TIMEOUT) do
50
71
  session = @session.build(url, image: true, origin: @origin.url, protect_redirect_callback: reject_invalid_url)
@@ -55,42 +76,34 @@ module MetaInspector
55
76
  request.options.open_timeout = @connection_timeout
56
77
  request.options.timeout = @read_timeout
57
78
  request.options.on_data = proc do |chunk, _total, env|
58
- status = env.status
59
- headers = env.response_headers
79
+ download.status = env.status
80
+ download.headers = env.response_headers
60
81
  remaining = MAX_BYTES - received
61
82
  received += chunk.bytesize
62
83
  # Count redirect bodies too, across the entire lookup.
63
- if (200..299).cover?(status)
64
- bytes << chunk.b.byteslice(0, remaining)
65
- elsif !(300..399).cover?(status)
84
+ if (200..299).cover?(env.status)
85
+ download.bytes << chunk.b.byteslice(0, remaining)
86
+ elsif !(300..399).cover?(env.status)
66
87
  throw stop
67
88
  end
68
89
  throw stop if received >= MAX_BYTES
69
90
  end
70
91
  end
71
- completed = true
92
+ download.complete = true
72
93
  end
73
94
  end
74
- return unless status && (200..299).cover?(status)
75
-
76
- dimensions = FastImage.size(StringIO.new(bytes))
77
- return dimensions unless metadata
78
-
79
- { dimensions: dimensions, type: FastImage.type(StringIO.new(bytes)),
80
- file_size: file_size(status, headers, completed, bytes.bytesize) }
81
- rescue URLPolicy::Failure => failure
82
- raise failure.original
83
- rescue Faraday::TimeoutError, Faraday::ConnectionFailed, Faraday::SSLError,
84
- Faraday::FollowRedirects::RedirectLimitReached, URI::InvalidURIError, Timeout::Error
85
- nil
95
+ download
86
96
  end
87
97
 
88
- def file_size(status, headers, completed, bytesize)
98
+ # The full size of the image, from Content-Range for partial responses,
99
+ # or from Content-Length or the bytes read for complete ones.
100
+ def file_size(download)
101
+ status, headers = download.status, download.headers
89
102
  value = if status == 206
90
103
  headers['content-range'].to_s[/\Abytes \d+-\d+\/(\d+)\z/i, 1]
91
104
  elsif status == 200 && (headers['content-encoding'].nil? || headers['content-encoding'] == 'identity')
92
105
  length = headers['content-length']
93
- length.nil? && completed ? bytesize.to_s : length.to_s[/\A\d+\z/]
106
+ length.nil? && download.complete ? download.bytes.bytesize.to_s : length.to_s[/\A\d+\z/]
94
107
  end
95
108
  value.to_i if value
96
109
  end