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
@@ -1,4 +1,5 @@
1
1
  require 'nokogiri'
2
+ require_relative 'html_encoding'
2
3
 
3
4
  module MetaInspector
4
5
  ##
@@ -8,51 +9,160 @@ module MetaInspector
8
9
  # passing itself as a reference for coordination purposes
9
10
  #
10
11
  class Parser
12
+ # libxml2's limit for a single text node, attribute value or comment
13
+ # (XML_MAX_TEXT_LENGTH).
14
+ MAX_NODE_BYTES = 10_000_000
15
+
11
16
  def initialize(document, options = {})
12
- @document = document
13
- @max_html_bytes = options[:max_html_bytes]
14
- @head_links_parser = MetaInspector::Parsers::HeadLinksParser.new(self)
15
- @meta_tag_parser = MetaInspector::Parsers::MetaTagsParser.new(self)
16
- @links_parser = MetaInspector::Parsers::LinksParser.new(self)
17
- @download_images = options[:download_images]
18
- @images_parser = MetaInspector::Parsers::ImagesParser.new(self, download_images: @download_images,
19
- max_image_downloads: options[:max_image_downloads],
20
- download_image_options: options[:download_image_options],
21
- fetch_all_image_meta: options[:fetch_all_image_meta],
22
- inline_image_data: options[:inline_image_data],
23
- image_downloader: options[:image_downloader])
24
- @iframes_parser = MetaInspector::Parsers::IframesParser.new(self)
25
- @texts_parser = MetaInspector::Parsers::TextsParser.new(self)
26
-
27
- parsed # parse early so we can fail early
17
+ @document = document
18
+ @max_html_bytes = options[:max_html_bytes]
19
+ @head_links_parser = Parsers::HeadLinksParser.new(self)
20
+ @meta_tag_parser = Parsers::MetaTagsParser.new(self)
21
+ @links_parser = Parsers::LinksParser.new(self)
22
+ @images_parser = Parsers::ImagesParser.new(self, options)
23
+ @iframes_parser = Parsers::IframesParser.new(self)
24
+ @texts_parser = Parsers::TextsParser.new(self)
25
+
26
+ parsed # parse early so we can fail early
28
27
  end
29
28
 
30
29
  extend Forwardable
31
- delegate [:url, :scheme, :host] => :@document
32
- delegate [:meta_tags, :meta_tag, :meta, :charset] => :@meta_tag_parser
33
- delegate [:head_links, :stylesheets, :canonicals, :feeds, :feed] => :@head_links_parser
34
- delegate [:links, :base_url] => :@links_parser
35
- delegate :images => :@images_parser
36
- delegate [:iframes, :iframe_sources] => :@iframes_parser
37
- delegate [:language, :title, :best_title, :author, :best_author, :description, :best_description,
38
- :h1, :h2, :h3, :h4, :h5, :h6] => :@texts_parser
39
-
40
- # Deprecated compatibility shortcut; remove in 6.0.
41
- def favicon
42
- warn 'DEPRECATION WARNING: page.favicon is deprecated and will be removed in 6.0. ' \
43
- 'Use page.images.favicon instead.'
44
- images.favicon
45
- end
30
+ delegate %i[url scheme host] => :@document
31
+ delegate %i[meta_tags meta_tag meta charset] => :@meta_tag_parser
32
+ delegate %i[head_links stylesheets canonicals feeds] => :@head_links_parser
33
+ delegate %i[links base_url] => :@links_parser
34
+ delegate :images => :@images_parser
35
+ delegate %i[iframes iframe_sources] => :@iframes_parser
36
+ delegate %i[language title best_title author best_author description best_description
37
+ h1 h2 h3 h4 h5 h6] => :@texts_parser
46
38
 
47
39
  # Returns the whole parsed document
40
+ #
41
+ # libxml2 (HTML4) parses first: it detects the encoding and enforces its
42
+ # resource limits. The DOM is then built with HTML5 rules, unless the HTML
43
+ # can't be converted to UTF-8, in which case libxml2's tree is kept.
48
44
  def parsed
49
45
  @parsed ||= begin
50
46
  html = @document.to_s
51
- if @max_html_bytes && html.bytesize > @max_html_bytes
52
- raise MetaInspector::ParserError, "HTML is #{html.bytesize} bytes, exceeding the limit of #{@max_html_bytes} bytes"
47
+ check_html_size!(html)
48
+ html, document = html4_document(html)
49
+
50
+ if (utf8 = html5_input(html, document))
51
+ # The HTML5 tree is the DOM and enforces its own depth limit, so
52
+ # libxml2's depth error doesn't apply: its HTML4 tree can be much
53
+ # deeper, as it leaves elements open that HTML5 closes (#612).
54
+ parsed = html5_document(utf8, document)
55
+ enforce_node_size_limit(parsed, utf8, document)
56
+ parsed
57
+ else
58
+ # libxml2's tree is the DOM, and past its depth limit it's truncated.
59
+ raise_limit_error(document, /Excessive depth in document/)
60
+ document
53
61
  end
54
- Nokogiri::HTML(html)
55
62
  end
63
+ rescue ArgumentError, EncodingError => error
64
+ raise MetaInspector::ParserError.new(error)
65
+ end
66
+
67
+ private
68
+
69
+ def check_html_size!(html)
70
+ return unless @max_html_bytes && html.bytesize > @max_html_bytes
71
+
72
+ raise MetaInspector::ParserError, "HTML is #{html.bytesize} bytes, exceeding the limit of #{@max_html_bytes} bytes"
73
+ end
74
+
75
+ # Returns the HTML, converted if its encoding was detected from its bytes,
76
+ # and libxml2's tree for it.
77
+ def html4_document(html)
78
+ html = HtmlEncoding.normalize(html).scrub
79
+ # Keep libxml2's resource-limit validation. HTML5 has different limits
80
+ # and would otherwise accept oversized text nodes.
81
+ document = Nokogiri::HTML(html, nil, HtmlEncoding.detect(html))
82
+ # For untagged bytes, use the selected declaration, then parse
83
+ # again after the same conversion used for tagged strings. libxml2's
84
+ # Windows-31J decoder still uses some strict Shift_JIS character mappings.
85
+ if html.encoding == Encoding::BINARY && HtmlEncoding.superset(document.encoding)
86
+ html = HtmlEncoding.normalize(html.dup.force_encoding(document.encoding))
87
+ document = Nokogiri::HTML(html)
88
+ end
89
+ raise_limit_error(document, /Resource limit exceeded|xmlSAX2Characters: huge text node/)
90
+ [html, document]
91
+ end
92
+
93
+ def raise_limit_error(document, pattern)
94
+ return if non_html_content?
95
+
96
+ limit_error = document.errors.find { |error| error.message.match?(pattern) }
97
+ raise MetaInspector::ParserError, limit_error.message.strip if limit_error
98
+ end
99
+
100
+ # libxml2 may stop reading at a fatal error, such as its depth limit, so it
101
+ # may not have checked the size of everything after that point. Then apply
102
+ # its limit to the HTML5 tree, which has none of its own. Skip inputs too
103
+ # small to hold an oversized node: HTML5 parsing turns a byte into at most
104
+ # 3 (NUL to U+FFFD).
105
+ def enforce_node_size_limit(parsed, html, document)
106
+ return if non_html_content? || html.bytesize * 3 <= MAX_NODE_BYTES
107
+ return unless document.errors.any?(&:fatal?)
108
+
109
+ kind = catch(:oversized) do
110
+ parsed.traverse do |node|
111
+ if node.element?
112
+ throw :oversized, 'attribute value' if node.attribute_nodes.any? { |a| a.value.bytesize > MAX_NODE_BYTES }
113
+ elsif node.comment?
114
+ throw :oversized, 'comment' if node.content.bytesize > MAX_NODE_BYTES
115
+ elsif node.text? || node.cdata?
116
+ throw :oversized, 'text node' if node.content.bytesize > MAX_NODE_BYTES
117
+ end
118
+ end
119
+ nil
120
+ end
121
+ raise MetaInspector::ParserError, "Resource limit exceeded: #{kind} longer than #{MAX_NODE_BYTES} bytes" if kind
122
+ end
123
+
124
+ def html5_document(html, fallback)
125
+ parsed = Nokogiri::HTML5(html, max_attributes: -1, parse_noscript_content_as_text: true)
126
+ restore_noscript_content(parsed)
127
+ parsed.errors.concat(fallback.errors)
128
+ parsed
129
+ rescue ArgumentError
130
+ raise unless non_html_content?
131
+
132
+ # Binary files and XML feeds can nest past the HTML5 tree depth limit.
133
+ # The caller accepted non-HTML content, so keep libxml2's tree, whose
134
+ # depth is already capped, as 5.21.0 did.
135
+ fallback
136
+ end
137
+
138
+ # The caller opted in with allow_non_html_content and the response is not
139
+ # HTML, so resource limits that guard against truncated HTML do not apply.
140
+ def non_html_content?
141
+ @document.allow_non_html_content && !Request.html_content_type?(@document.content_type)
142
+ end
143
+
144
+ def restore_noscript_content(document)
145
+ document.css('noscript').each do |node|
146
+ # Isolate fallback markup so it cannot close the head or consume the
147
+ # rest of the page, while keeping it available to all extractors.
148
+ node.children = Nokogiri::HTML5.fragment(node.text, max_attributes: -1)
149
+ end
150
+ end
151
+
152
+ def html5_input(html, document)
153
+ encoding = html.encoding == Encoding::BINARY ? document.encoding || 'UTF-8' : html.encoding.name
154
+ encoding = encoding.sub(/\AISO_/i, 'ISO-').sub(/:\d+\z/, '')
155
+ encoding = case encoding.downcase
156
+ when 'latin1', 'l1' then 'ISO-8859-1'
157
+ when 'gb_2312-80' then 'GB2312'
158
+ else encoding
159
+ end
160
+ encoding = HtmlEncoding.superset(encoding) || encoding
161
+ html.encode(Encoding::UTF_8, encoding, invalid: :replace, undef: :replace)
162
+ rescue ArgumentError, Encoding::ConverterNotFoundError
163
+ # libxml2 supports encodings (such as UTF-7) that Ruby cannot transcode.
164
+ # Preserve the existing parser for those documents rather than rejecting them.
165
+ nil
56
166
  end
57
167
  end
58
168
  end
@@ -13,18 +13,23 @@ module MetaInspector
13
13
  # which, in turn, delegates it to the LinksParser.
14
14
  #
15
15
  class Base
16
+ extend Forwardable
17
+
16
18
  def initialize(main_parser)
17
19
  @main_parser = main_parser
18
20
  end
19
21
 
20
- extend Forwardable
21
-
22
22
  private
23
23
 
24
24
  # Cleans up nokogiri search results
25
25
  def cleanup(results)
26
26
  results.map { |r| r.value.strip }.reject(&:empty?).uniq
27
27
  end
28
+
29
+ # Splits a rel attribute into its tokens, lowercased as HTML does: ASCII only.
30
+ def rel_tokens(rel)
31
+ rel.to_s.downcase(:ascii).split(/[ \t\n\f\r]+/)
32
+ end
28
33
  end
29
34
  end
30
35
  end
@@ -3,20 +3,18 @@ module MetaInspector
3
3
  class HeadLinksParser < Base
4
4
  delegate [:parsed, :base_url] => :@main_parser
5
5
 
6
+ # application/json is JSON Feed 1.0; application/feed+json is 1.1.
6
7
  KNOWN_FEED_TYPES = %w[
7
- application/rss+xml application/atom+xml application/json
8
+ application/rss+xml application/atom+xml application/json application/feed+json
8
9
  ].freeze
9
10
 
10
11
  def head_links
11
12
  @head_links ||= parsed.css('head link').map do |tag|
12
- Hash[
13
- tag.attributes.keys.map do |key|
14
- keysym = key.to_sym
15
- val = tag.attributes[key].value
16
- val = URL.absolutify(val, base_url) if keysym == :href
17
- [keysym, val]
18
- end
19
- ]
13
+ tag.attributes.to_h do |name, attribute|
14
+ value = attribute.value
15
+ value = URL.absolutify(value, base_url) if name == 'href'
16
+ [name.to_sym, value]
17
+ end
20
18
  end
21
19
  end
22
20
 
@@ -29,31 +27,25 @@ module MetaInspector
29
27
  end
30
28
 
31
29
  def feeds
32
- @feeds ||=
33
- parsed.search('//link[@rel]').map do |link|
34
- next unless rel_includes?(link['rel'], 'alternate')
35
- next if !KNOWN_FEED_TYPES.include?(link["type"]) || link["href"].to_s.strip == ''
36
-
37
- {
38
- title: link["title"],
39
- href: URL.absolutify(link["href"], base_url),
40
- type: link["type"]
41
- }
42
- end.compact
43
- end
30
+ @feeds ||= parsed.search('//link[@rel]').filter_map do |link|
31
+ next unless rel_includes?(link['rel'], 'alternate')
32
+ next unless KNOWN_FEED_TYPES.include?(media_type(link['type']))
33
+ next if link['href'].to_s.strip.empty?
44
34
 
45
- # Deprecated compatibility method; remove in 6.0.
46
- def feed
47
- warn 'DEPRECATION WARNING: page.feed is deprecated and will be removed in 6.0. ' \
48
- 'Use page.feeds instead.'
49
- first_feed = feeds.find { |link| %r{/(rss|atom)\+xml$}i.match?(link[:type]) }
50
- first_feed && first_feed[:href]
35
+ { title: link['title'], href: URL.absolutify(link['href'], base_url), type: link['type'] }
36
+ end
51
37
  end
52
38
 
53
39
  private
54
40
 
41
+ # Media types are case-insensitive and may carry parameters
42
+ # (https://mimesniff.spec.whatwg.org/#mime-type-essence).
43
+ def media_type(type)
44
+ type.to_s.split(';', 2).first.to_s.strip.downcase(:ascii)
45
+ end
46
+
55
47
  def rel_includes?(rel, keyword)
56
- rel.to_s.downcase(:ascii).split(/[ \t\n\f\r]+/).include?(keyword)
48
+ rel_tokens(rel).include?(keyword)
57
49
  end
58
50
  end
59
51
  end
@@ -2,11 +2,10 @@ module MetaInspector
2
2
  module Parsers
3
3
  class IframesParser < Base
4
4
  delegate [:parsed, :base_url] => :@main_parser
5
+
5
6
  def iframes
6
7
  @iframes ||= parsed.search('//iframe').map do |iframe|
7
- iframe.attributes.each_with_object({}) do |(name, attribute), result|
8
- result[name.to_sym] = attribute.value
9
- end
8
+ iframe.attributes.to_h { |name, attribute| [name.to_sym, attribute.value] }
10
9
  end
11
10
  end
12
11
 
@@ -9,6 +9,22 @@ module MetaInspector
9
9
 
10
10
  include Enumerable
11
11
 
12
+ # Meta tags that name the page's image, in order of preference.
13
+ SUGGESTED_IMAGE_META = %w[og:image twitter:image parsely-image-url].freeze
14
+
15
+ # A URL that an <img> or <picture> may show. group identifies that
16
+ # element, and descriptor is [:w, width] or [:x, density].
17
+ Candidate = Struct.new(:url, :width, :height, :group, :descriptor) do
18
+ def width_descriptor?
19
+ descriptor[0] == :w
20
+ end
21
+
22
+ def descriptor_value
23
+ descriptor[1]
24
+ end
25
+ end
26
+ private_constant :SUGGESTED_IMAGE_META, :Candidate
27
+
12
28
  def initialize(main_parser, options = {})
13
29
  @image_downloader = options[:image_downloader]
14
30
  @download_images = options[:download_images]
@@ -47,20 +63,18 @@ module MetaInspector
47
63
  end
48
64
  end
49
65
 
50
- # Returns an array of [img_url, width, height] sorted by image area (width * height)
66
+ # Returns an array of [img_url, width, height] sorted by image area (width * height),
67
+ # ranking one candidate per <img> or <picture> (see ranked_candidates).
51
68
  def with_size
52
69
  @with_size ||= begin
53
- imgs_with_size = unique_image_candidates
54
- if @download_images && @reject_invalid_images
55
- imgs_with_size.reject! { |url, width, height| image_validity(url) == false }
56
- end
57
- imgs_with_size.map! do |url, width, height, _responsive|
58
- if width.nil? || height.nil?
59
- width, height = image_size(url) || [0, 0]
60
- end
61
- [result_url(url), width.to_i, height.to_i]
70
+ candidates = unique_image_candidates(ranked_candidates)
71
+ candidates.reject! { |candidate| image_validity(candidate.url) == false } if rejecting_invalid_images?
72
+ images = candidates.map do |candidate|
73
+ width, height = candidate.width, candidate.height
74
+ width, height = image_size(candidate.url) || [0, 0] if width.nil? || height.nil?
75
+ [result_url(candidate.url), width.to_i, height.to_i]
62
76
  end
63
- imgs_with_size.sort_by { |url, width, height| -(width.to_i * height.to_i) }
77
+ images.sort_by { |_url, width, height| -(width * height) }
64
78
  end
65
79
  end
66
80
 
@@ -68,8 +82,9 @@ module MetaInspector
68
82
  # With validation enabled, details reuse the validation lookups.
69
83
  def with_details
70
84
  @with_details ||= begin
71
- attempts = 0
72
- images = unique_image_candidates.filter_map do |url, width, height, _responsive|
85
+ downloads = 0
86
+ images = unique_image_candidates(image_candidates).filter_map do |candidate|
87
+ url = candidate.url
73
88
  metadata = nil
74
89
  if validating_images?
75
90
  next if @reject_invalid_images && image_validity(url) == false
@@ -78,16 +93,17 @@ module MetaInspector
78
93
  elsif @download_images
79
94
  if data_image_url?(url)
80
95
  metadata = image_metadata(url)
81
- elsif http_image_url?(url) && (@max_image_downloads.nil? || attempts < @max_image_downloads)
82
- attempts += 1
96
+ elsif http_image_url?(url) && within_download_limit?(downloads)
97
+ downloads += 1
83
98
  metadata = @image_downloader.metadata(encoded_url(url))
84
99
  end
85
100
  end
86
101
  downloaded_width, downloaded_height = metadata && metadata[:dimensions]
87
- width ||= downloaded_width
88
- height ||= downloaded_height
89
- { url: result_url(url), width: width.to_i, height: height.to_i,
90
- type: metadata && metadata[:type], file_size: metadata && metadata[:file_size] }
102
+ { url: result_url(url),
103
+ width: (candidate.width || downloaded_width).to_i,
104
+ height: (candidate.height || downloaded_height).to_i,
105
+ type: metadata && metadata[:type],
106
+ file_size: metadata && metadata[:file_size] }
91
107
  end
92
108
  images.sort_by { |image| -(image[:width] * image[:height]) }
93
109
  end
@@ -96,26 +112,20 @@ module MetaInspector
96
112
  # Returns the largest image from the image collection,
97
113
  # filtered for images that are more square than 10:1 or 1:10
98
114
  def largest
99
- @largest_image ||= begin
100
- imgs_with_size = with_size.dup
101
- imgs_with_size.keep_if do |url, width, height|
102
- ratio = width.to_f / height.to_f
103
- (@inline_image_data || !data_image_url?(url)) && ratio > 0.1 && ratio < 10
104
- end
105
- url, width, height = imgs_with_size.first
106
- url
107
- end
115
+ @largest_image ||= with_size.find do |url, width, height|
116
+ ratio = width.to_f / height.to_f
117
+ (@inline_image_data || !data_image_url?(url)) && ratio > 0.1 && ratio < 10
118
+ end&.first
108
119
  end
109
120
 
110
- # Return favicon url if exist
121
+ # Return favicon url if exist. An href that can't be resolved returns nil.
111
122
  def favicon
112
123
  link = parsed.xpath('//link[@rel]').find do |node|
113
124
  # Keep legacy shortcut-only links while matching whole, ASCII-insensitive tokens.
114
- node['rel'].tr('A-Z', 'a-z').split(/[ \t\n\f\r]+/).any? { |rel| rel == 'icon' || rel == 'shortcut' }
125
+ rel_tokens(node['rel']).any? { |rel| rel == 'icon' || rel == 'shortcut' }
115
126
  end
116
- value = link.attributes['href'].value
117
- @favicon ||= result_url(URL.absolutify(value, base_url, normalize: false))
118
- rescue
127
+ result_url(URL.absolutify(link.attributes['href'].value, base_url, normalize: false))
128
+ rescue StandardError
119
129
  nil
120
130
  end
121
131
 
@@ -128,40 +138,68 @@ module MetaInspector
128
138
  end
129
139
 
130
140
  def suggested_image(skip_inline: false)
131
- ['og:image', 'twitter:image', 'parsely-image-url'].each do |key|
132
- value = content_of(meta[key])
133
- next unless value
141
+ SUGGESTED_IMAGE_META.each do |key|
142
+ value = meta[key]
143
+ next if value.nil? || value.strip.empty?
134
144
 
135
145
  url = URL.absolutify(value, base_url, normalize: false)
136
146
  next if url.nil? || (skip_inline && data_image_url?(url))
137
- next if @download_images && @reject_invalid_images && image_validity(url) == false
147
+ next if rejecting_invalid_images? && image_validity(url) == false
138
148
 
139
149
  return url
140
150
  end
141
151
  nil
142
152
  end
143
153
 
144
- def unique_image_candidates
145
- candidates = {}
146
- image_candidates.each do |url, width, height, responsive|
154
+ # Keeps one candidate per URL: the first one, unless a later one has both
155
+ # dimensions in the HTML and the first doesn't.
156
+ def unique_image_candidates(candidates)
157
+ unique = {}
158
+ candidates.each do |candidate|
159
+ url = candidate.url
147
160
  next if url.nil? || url.empty?
148
161
 
149
- previous = candidates[url]
150
- if previous.nil? || ((previous[1].nil? || previous[2].nil?) && width && height)
151
- candidates[url] = [url, width, height, responsive]
162
+ previous = unique[url]
163
+ if previous.nil? || ((previous.width.nil? || previous.height.nil?) && candidate.width && candidate.height)
164
+ unique[url] = candidate
152
165
  end
153
166
  end
154
- candidates.values
167
+ unique.values
168
+ end
169
+
170
+ # The candidates of one <img> or <picture> are the same picture at different
171
+ # sizes, so only the largest one is downloaded for ranking: the largest width
172
+ # descriptor if any candidate has one, otherwise the highest density (src
173
+ # counts as 1x). Candidates that can't be measured are skipped while others
174
+ # remain. A src with both dimensions in the HTML is kept too, as it costs no
175
+ # download.
176
+ def ranked_candidates
177
+ image_candidates.group_by(&:group).flat_map do |_group, candidates|
178
+ candidates = candidates.reject { |candidate| candidate.url.nil? || candidate.url.empty? }
179
+ sized = candidates.select { |candidate| candidate.width && candidate.height }
180
+ pool = candidates.select { |candidate| measurable_image_url?(candidate.url) }
181
+ pool = candidates if pool.empty?
182
+ with_width = pool.select(&:width_descriptor?)
183
+ pool = with_width unless with_width.empty?
184
+ largest = pool.each_with_index.max_by { |candidate, index| [candidate.descriptor_value, -index] }&.first
185
+ largest ? [largest] + (sized - [largest]) : sized
186
+ end
187
+ end
188
+
189
+ def measurable_image_url?(url)
190
+ data_image_url?(url) ? @inline_image_data : http_image_url?(url)
155
191
  end
156
192
 
157
193
  def images_collection
158
- @images_collection ||= if @download_images && @reject_invalid_images
159
- absolutified_images.reject { |url| url && image_validity(url) == false }.map { |url| result_url(url) }
160
- else
161
- absolutified_images.map { |url| result_url(url) }
194
+ @images_collection ||= begin
195
+ urls = absolutified_images
196
+ urls = urls.reject { |url| url && image_validity(url) == false } if rejecting_invalid_images?
197
+ urls.map { |url| result_url(url) }
162
198
  end
163
199
  end
164
200
 
201
+ # Returns [width, height], or nil if unknown. Each URL is looked up once,
202
+ # and only max_image_downloads HTTP lookups are made.
165
203
  def image_size(url)
166
204
  return @image_sizes[url] if @image_sizes.key?(url)
167
205
  return nil unless @download_images
@@ -172,15 +210,12 @@ module MetaInspector
172
210
  return @image_sizes[url] = metadata && metadata[:dimensions]
173
211
  end
174
212
  return @image_sizes[url] = nil unless http_image_url?(url)
175
- return nil unless @max_image_downloads.nil? || @download_attempts < @max_image_downloads
176
-
177
- unless validating_images?
178
- @download_attempts += 1
179
- return @image_sizes[url] = @image_downloader.size(encoded_url(url))
180
- end
213
+ return nil unless within_download_limit?(@download_attempts)
181
214
 
182
- request_url = encoded_url(url)
183
215
  @download_attempts += 1
216
+ request_url = encoded_url(url)
217
+ return @image_sizes[url] = @image_downloader.size(request_url) unless validating_images?
218
+
184
219
  # Metadata comes from the same download and lets with_details reuse it.
185
220
  metadata = @image_downloader.metadata(request_url, reject_invalid_url: true)
186
221
  @image_metadata[url] = metadata
@@ -192,10 +227,18 @@ module MetaInspector
192
227
  @image_metadata[url]
193
228
  end
194
229
 
230
+ def within_download_limit?(downloads)
231
+ @max_image_downloads.nil? || downloads < @max_image_downloads
232
+ end
233
+
195
234
  def validating_images?
196
235
  @reject_invalid_images || @fetch_all_image_meta
197
236
  end
198
237
 
238
+ def rejecting_invalid_images?
239
+ @download_images && @reject_invalid_images
240
+ end
241
+
199
242
  # Normalizes non-ASCII URLs for the request; results keep the original.
200
243
  # A URL that cannot be normalized is returned as is, so URL validation
201
244
  # rejects it instead of Addressable raising.
@@ -224,17 +267,20 @@ module MetaInspector
224
267
  end
225
268
 
226
269
  def absolutified_images
227
- image_candidates.map(&:first).uniq
270
+ image_candidates.map(&:url).uniq
228
271
  end
229
272
 
273
+ # The src of each <img>, as 1x, and the srcset candidates of each <img>
274
+ # and <picture> source, in document order.
230
275
  def image_candidates
231
276
  @image_candidates ||= parsed.xpath('//img | //picture/source').flat_map do |node|
232
- candidates = []
277
+ sources = []
233
278
  src = node['src'].to_s.strip if node.name == 'img'
234
- candidates << [src, node['width'], node['height']] if src && !src.empty?
235
- srcset_urls(node['srcset']).each { |url| candidates << [url, nil, nil, true] }
236
- candidates.map do |url, width, height, responsive|
237
- [URL.absolutify(url, base_url, normalize: false), width, height, responsive]
279
+ sources << [src, node['width'], node['height'], [:x, 1.0]] if src && !src.empty?
280
+ srcset_urls(node['srcset']).each { |url, descriptor| sources << [url, nil, nil, descriptor] }
281
+ group = node.parent&.name == 'picture' ? node.parent.pointer_id : node.pointer_id
282
+ sources.map do |url, width, height, descriptor|
283
+ Candidate.new(URL.absolutify(url, base_url, normalize: false), width, height, group, descriptor)
238
284
  end
239
285
  end
240
286
  end
@@ -255,19 +301,22 @@ module MetaInspector
255
301
  descriptor = scanner.scan(/(?:[^,(]|\([^)]*(?:\)|\z))*/).strip
256
302
  scanner.skip(/,/)
257
303
  end
258
- urls << url if !url.empty? && valid_srcset_descriptor?(descriptor)
304
+ parsed_descriptor = parse_srcset_descriptor(descriptor)
305
+ urls << [url, parsed_descriptor] if !url.empty? && parsed_descriptor
259
306
  end
260
307
  urls
261
308
  end
262
309
 
263
- def valid_srcset_descriptor?(descriptor)
264
- descriptor.empty? || (descriptor.match?(/\A\d+w\z/) && descriptor.to_i > 0) ||
265
- (descriptor.match?(/\A(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?x\z/) && descriptor.to_f >= 0)
266
- end
267
-
268
- def content_of(content)
269
- return nil if content.nil? || content.strip.empty?
270
- content
310
+ # Returns [:w, width] or [:x, density], or nil for an invalid descriptor.
311
+ # A candidate without a descriptor is 1x.
312
+ def parse_srcset_descriptor(descriptor)
313
+ if descriptor.empty?
314
+ [:x, 1.0]
315
+ elsif descriptor.match?(/\A\d+w\z/) && descriptor.to_i > 0
316
+ [:w, descriptor.to_i]
317
+ elsif descriptor.match?(/\A(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?x\z/) && descriptor.to_f >= 0
318
+ [:x, descriptor.to_f]
319
+ end
271
320
  end
272
321
  end
273
322
  end