metainspector 5.20.0 → 5.21.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 (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +16 -0
  3. data/Gemfile +1 -1
  4. data/README.md +147 -6
  5. data/examples/basic_scraping.rb +4 -3
  6. data/examples/faraday_redirect_options.rb +23 -31
  7. data/examples/html_size_limit.rb +17 -0
  8. data/examples/iframes.rb +15 -0
  9. data/examples/image_details.rb +17 -0
  10. data/examples/image_validation.rb +25 -0
  11. data/examples/link_checker.rb +2 -2
  12. data/examples/responsive_images.rb +15 -0
  13. data/examples/spider.rb +2 -2
  14. data/lib/meta_inspector/document.rb +14 -1
  15. data/lib/meta_inspector/http_session.rb +11 -1
  16. data/lib/meta_inspector/image_downloader.rb +48 -3
  17. data/lib/meta_inspector/parser.rb +20 -1
  18. data/lib/meta_inspector/parsers/head_links.rb +18 -3
  19. data/lib/meta_inspector/parsers/iframes.rb +21 -0
  20. data/lib/meta_inspector/parsers/images.rb +194 -26
  21. data/lib/meta_inspector/parsers/texts.rb +2 -2
  22. data/lib/meta_inspector/url_policy.rb +12 -2
  23. data/lib/meta_inspector/version.rb +1 -1
  24. data/lib/meta_inspector.rb +1 -0
  25. data/meta_inspector.gemspec +1 -2
  26. data/spec/document_spec.rb +139 -0
  27. data/spec/examples_spec.rb +206 -0
  28. data/spec/image_download_spec.rb +11 -0
  29. data/spec/image_metadata_spec.rb +110 -0
  30. data/spec/image_validity_spec.rb +195 -0
  31. data/spec/inline_images_spec.rb +75 -0
  32. data/spec/meta_inspector/head_links_spec.rb +69 -0
  33. data/spec/meta_inspector/iframes_spec.rb +50 -0
  34. data/spec/meta_inspector/images_spec.rb +130 -0
  35. data/spec/meta_inspector/texts_spec.rb +50 -0
  36. data/spec/parser_spec.rb +10 -0
  37. data/spec/unicode_image_urls_spec.rb +74 -0
  38. data/spec/url_filter_spec.rb +1 -1
  39. metadata +27 -36
  40. data/examples/redirect_web_server.rb +0 -5
@@ -10,13 +10,18 @@ module MetaInspector
10
10
  class Parser
11
11
  def initialize(document, options = {})
12
12
  @document = document
13
+ @max_html_bytes = options[:max_html_bytes]
13
14
  @head_links_parser = MetaInspector::Parsers::HeadLinksParser.new(self)
14
15
  @meta_tag_parser = MetaInspector::Parsers::MetaTagsParser.new(self)
15
16
  @links_parser = MetaInspector::Parsers::LinksParser.new(self)
16
17
  @download_images = options[:download_images]
17
18
  @images_parser = MetaInspector::Parsers::ImagesParser.new(self, download_images: @download_images,
18
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],
19
23
  image_downloader: options[:image_downloader])
24
+ @iframes_parser = MetaInspector::Parsers::IframesParser.new(self)
20
25
  @texts_parser = MetaInspector::Parsers::TextsParser.new(self)
21
26
 
22
27
  parsed # parse early so we can fail early
@@ -28,12 +33,26 @@ module MetaInspector
28
33
  delegate [:head_links, :stylesheets, :canonicals, :feeds, :feed] => :@head_links_parser
29
34
  delegate [:links, :base_url] => :@links_parser
30
35
  delegate :images => :@images_parser
36
+ delegate [:iframes, :iframe_sources] => :@iframes_parser
31
37
  delegate [:language, :title, :best_title, :author, :best_author, :description, :best_description,
32
38
  :h1, :h2, :h3, :h4, :h5, :h6] => :@texts_parser
33
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
46
+
34
47
  # Returns the whole parsed document
35
48
  def parsed
36
- @parsed ||= Nokogiri::HTML(@document.to_s)
49
+ @parsed ||= begin
50
+ 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"
53
+ end
54
+ Nokogiri::HTML(html)
55
+ end
37
56
  end
38
57
  end
39
58
  end
@@ -21,16 +21,17 @@ module MetaInspector
21
21
  end
22
22
 
23
23
  def stylesheets
24
- @stylesheets ||= head_links.select { |hl| hl[:rel] == 'stylesheet' }
24
+ @stylesheets ||= head_links.select { |hl| rel_includes?(hl[:rel], 'stylesheet') }
25
25
  end
26
26
 
27
27
  def canonicals
28
- @canonicals ||= head_links.select { |hl| hl[:rel] == 'canonical' }
28
+ @canonicals ||= head_links.select { |hl| rel_includes?(hl[:rel], 'canonical') }
29
29
  end
30
30
 
31
31
  def feeds
32
32
  @feeds ||=
33
- parsed.search("//link[@rel='alternate']").map do |link|
33
+ parsed.search('//link[@rel]').map do |link|
34
+ next unless rel_includes?(link['rel'], 'alternate')
34
35
  next if !KNOWN_FEED_TYPES.include?(link["type"]) || link["href"].to_s.strip == ''
35
36
 
36
37
  {
@@ -40,6 +41,20 @@ module MetaInspector
40
41
  }
41
42
  end.compact
42
43
  end
44
+
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]
51
+ end
52
+
53
+ private
54
+
55
+ def rel_includes?(rel, keyword)
56
+ rel.to_s.downcase(:ascii).split(/[ \t\n\f\r]+/).include?(keyword)
57
+ end
43
58
  end
44
59
  end
45
60
  end
@@ -0,0 +1,21 @@
1
+ module MetaInspector
2
+ module Parsers
3
+ class IframesParser < Base
4
+ delegate [:parsed, :base_url] => :@main_parser
5
+ def iframes
6
+ @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
10
+ end
11
+ end
12
+
13
+ def iframe_sources
14
+ iframes.map do |attributes|
15
+ src = attributes[:src].to_s.strip
16
+ URL.absolutify(src, base_url, normalize: false) unless src.empty?
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -1,4 +1,5 @@
1
1
  require_relative '../image_downloader'
2
+ require 'strscan'
2
3
 
3
4
  module MetaInspector
4
5
  module Parsers
@@ -12,6 +13,12 @@ module MetaInspector
12
13
  @image_downloader = options[:image_downloader]
13
14
  @download_images = options[:download_images]
14
15
  @max_image_downloads = options[:max_image_downloads]
16
+ @reject_invalid_images = (options[:download_image_options] || {})[:reject_invalid_images]
17
+ @fetch_all_image_meta = options[:fetch_all_image_meta]
18
+ @inline_image_data = options[:inline_image_data]
19
+ @image_sizes = {}
20
+ @image_metadata = {}
21
+ @download_attempts = 0
15
22
  super(main_parser)
16
23
  end
17
24
 
@@ -22,7 +29,7 @@ module MetaInspector
22
29
  # Returns the Facebook Open Graph image, Twitter image, Parsely image or
23
30
  # the largest image in the image collection
24
31
  def best
25
- owner_suggested || largest
32
+ suggested_image(skip_inline: !@inline_image_data) || largest
26
33
  end
27
34
 
28
35
  # Returns the parsed image from Facebook's open graph property tags
@@ -30,36 +37,62 @@ module MetaInspector
30
37
  # See doc at http://developers.facebook.com/docs/opengraph/
31
38
  # If none found, tries with Twitter image, then Parsely image
32
39
  def owner_suggested
33
- suggested_img = content_of(meta['og:image']) || content_of(meta['twitter:image']) ||
34
- content_of(meta['parsely-image-url'])
35
- URL.absolutify(suggested_img, base_url, normalize: false) if suggested_img
40
+ result_url(suggested_image)
41
+ end
42
+
43
+ # Returns validity for each image URL; nil means no lookup was performed.
44
+ def with_metadata
45
+ absolutified_images.map do |url|
46
+ { url: result_url(url), valid: @fetch_all_image_meta && url ? image_validity(url) : nil }
47
+ end
36
48
  end
37
49
 
38
50
  # Returns an array of [img_url, width, height] sorted by image area (width * height)
39
51
  def with_size
40
52
  @with_size ||= begin
41
- img_nodes = parsed.search('//img').select{ |img_node| img_node['src'] }
42
- imgs_with_size = img_nodes.map do |img_node|
43
- [URL.absolutify(img_node['src'], base_url, normalize: false), img_node['width'], img_node['height']]
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 }
44
56
  end
45
- imgs_with_size.reject! { |url, width, height| url.nil? || url.empty? }
46
- imgs_with_size.uniq! { |url, width, height| url }
47
- download_attempts = 0
48
- imgs_with_size.map! do |url, width, height|
57
+ imgs_with_size.map! do |url, width, height, _responsive|
49
58
  if width.nil? || height.nil?
50
- if @download_images && (@max_image_downloads.nil? || download_attempts < @max_image_downloads)
51
- download_attempts += 1
52
- width, height = @image_downloader.size(url)
53
- else
54
- width, height = [0, 0]
55
- end
59
+ width, height = image_size(url) || [0, 0]
56
60
  end
57
- [url, width.to_i, height.to_i]
61
+ [result_url(url), width.to_i, height.to_i]
58
62
  end
59
63
  imgs_with_size.sort_by { |url, width, height| -(width.to_i * height.to_i) }
60
64
  end
61
65
  end
62
66
 
67
+ # Returns image details sorted by area. Metadata lookups are opt-in.
68
+ # With validation enabled, details reuse the validation lookups.
69
+ def with_details
70
+ @with_details ||= begin
71
+ attempts = 0
72
+ images = unique_image_candidates.filter_map do |url, width, height, _responsive|
73
+ metadata = nil
74
+ if validating_images?
75
+ next if @reject_invalid_images && image_validity(url) == false
76
+
77
+ metadata = image_metadata(url)
78
+ elsif @download_images
79
+ if data_image_url?(url)
80
+ metadata = image_metadata(url)
81
+ elsif http_image_url?(url) && (@max_image_downloads.nil? || attempts < @max_image_downloads)
82
+ attempts += 1
83
+ metadata = @image_downloader.metadata(encoded_url(url))
84
+ end
85
+ end
86
+ 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] }
91
+ end
92
+ images.sort_by { |image| -(image[:width] * image[:height]) }
93
+ end
94
+ end
95
+
63
96
  # Returns the largest image from the image collection,
64
97
  # filtered for images that are more square than 10:1 or 1:10
65
98
  def largest
@@ -67,7 +100,7 @@ module MetaInspector
67
100
  imgs_with_size = with_size.dup
68
101
  imgs_with_size.keep_if do |url, width, height|
69
102
  ratio = width.to_f / height.to_f
70
- ratio > 0.1 && ratio < 10
103
+ (@inline_image_data || !data_image_url?(url)) && ratio > 0.1 && ratio < 10
71
104
  end
72
105
  url, width, height = imgs_with_size.first
73
106
  url
@@ -76,25 +109,160 @@ module MetaInspector
76
109
 
77
110
  # Return favicon url if exist
78
111
  def favicon
79
- query = '//link[@rel="icon" or contains(@rel, "shortcut")]'
80
- value = parsed.xpath(query)[0].attributes['href'].value
81
- @favicon ||= URL.absolutify(value, base_url, normalize: false)
112
+ link = parsed.xpath('//link[@rel]').find do |node|
113
+ # 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' }
115
+ end
116
+ value = link.attributes['href'].value
117
+ @favicon ||= result_url(URL.absolutify(value, base_url, normalize: false))
82
118
  rescue
83
119
  nil
84
120
  end
85
121
 
86
122
  private
87
123
 
124
+ def result_url(url)
125
+ return url if url.nil? || @inline_image_data || !data_image_url?(url)
126
+
127
+ url.split(',', 2).first
128
+ end
129
+
130
+ 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
134
+
135
+ url = URL.absolutify(value, base_url, normalize: false)
136
+ next if url.nil? || (skip_inline && data_image_url?(url))
137
+ next if @download_images && @reject_invalid_images && image_validity(url) == false
138
+
139
+ return url
140
+ end
141
+ nil
142
+ end
143
+
144
+ def unique_image_candidates
145
+ candidates = {}
146
+ image_candidates.each do |url, width, height, responsive|
147
+ next if url.nil? || url.empty?
148
+
149
+ previous = candidates[url]
150
+ if previous.nil? || ((previous[1].nil? || previous[2].nil?) && width && height)
151
+ candidates[url] = [url, width, height, responsive]
152
+ end
153
+ end
154
+ candidates.values
155
+ end
156
+
88
157
  def images_collection
89
- @images_collection ||= absolutified_images
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) }
162
+ end
163
+ end
164
+
165
+ def image_size(url)
166
+ return @image_sizes[url] if @image_sizes.key?(url)
167
+ return nil unless @download_images
168
+
169
+ if data_image_url?(url)
170
+ metadata = @image_downloader.inline_metadata(url)
171
+ @image_metadata[url] = metadata
172
+ return @image_sizes[url] = metadata && metadata[:dimensions]
173
+ end
174
+ 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
181
+
182
+ request_url = encoded_url(url)
183
+ @download_attempts += 1
184
+ # Metadata comes from the same download and lets with_details reuse it.
185
+ metadata = @image_downloader.metadata(request_url, reject_invalid_url: true)
186
+ @image_metadata[url] = metadata
187
+ @image_sizes[url] = metadata && metadata[:dimensions]
188
+ end
189
+
190
+ def image_metadata(url)
191
+ image_size(url)
192
+ @image_metadata[url]
193
+ end
194
+
195
+ def validating_images?
196
+ @reject_invalid_images || @fetch_all_image_meta
197
+ end
198
+
199
+ # Normalizes non-ASCII URLs for the request; results keep the original.
200
+ # A URL that cannot be normalized is returned as is, so URL validation
201
+ # rejects it instead of Addressable raising.
202
+ def encoded_url(url)
203
+ url.ascii_only? ? url : URL.new(url).url
204
+ rescue StandardError
205
+ url
206
+ end
207
+
208
+ def image_validity(url)
209
+ image_size(url)
210
+ return nil unless @image_sizes.key?(url)
211
+
212
+ !@image_sizes[url].nil?
213
+ end
214
+
215
+ def data_image_url?(url)
216
+ url.match?(/\Adata:/i)
217
+ end
218
+
219
+ def http_image_url?(url)
220
+ URLPolicy.validate!(encoded_url(url))
221
+ true
222
+ rescue URLPolicy::InvalidURL
223
+ false
90
224
  end
91
225
 
92
226
  def absolutified_images
93
- parsed_images.map { |i| URL.absolutify(i, base_url, normalize: false) }
227
+ image_candidates.map(&:first).uniq
228
+ end
229
+
230
+ def image_candidates
231
+ @image_candidates ||= parsed.xpath('//img | //picture/source').flat_map do |node|
232
+ candidates = []
233
+ 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]
238
+ end
239
+ end
240
+ end
241
+
242
+ def srcset_urls(value)
243
+ scanner = StringScanner.new(value.to_s)
244
+ urls = []
245
+ until scanner.eos?
246
+ scanner.skip(/[\t\n\f\r ,]+/)
247
+ break if scanner.eos?
248
+
249
+ url = scanner.scan(/[^\t\n\f\r ]+/)
250
+ if url.end_with?(',')
251
+ url = url.sub(/,+\z/, '')
252
+ descriptor = ''
253
+ else
254
+ scanner.skip(/[\t\n\f\r ]+/)
255
+ descriptor = scanner.scan(/(?:[^,(]|\([^)]*(?:\)|\z))*/).strip
256
+ scanner.skip(/,/)
257
+ end
258
+ urls << url if !url.empty? && valid_srcset_descriptor?(descriptor)
259
+ end
260
+ urls
94
261
  end
95
262
 
96
- def parsed_images
97
- cleanup(parsed.search('//img/@src'))
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)
98
266
  end
99
267
 
100
268
  def content_of(content)
@@ -64,7 +64,7 @@ module MetaInspector
64
64
  @description ||= meta['description']
65
65
  end
66
66
 
67
- # A description getter that returns the first non-nill description
67
+ # A description getter that returns the first non-blank description
68
68
  # from the following candidates:
69
69
  # - the standard meta description
70
70
  # - the og:description meta tag
@@ -119,7 +119,7 @@ module MetaInspector
119
119
  meta['twitter:description'],
120
120
  secondary_description
121
121
  ]
122
- candidates.find { |x| !x.to_s.empty? }
122
+ candidates.find { |x| !x.to_s.strip.empty? }
123
123
  end
124
124
 
125
125
  # Look for the first <p> block with 120 characters or more
@@ -1,6 +1,8 @@
1
1
  module MetaInspector
2
2
  # Runs inside redirect handling, before cache access or the network adapter.
3
3
  class URLPolicy < Faraday::Middleware
4
+ class InvalidURL < MetaInspector::RequestError; end
5
+
4
6
  class Failure < StandardError
5
7
  attr_reader :original
6
8
 
@@ -15,11 +17,11 @@ module MetaInspector
15
17
  def self.validate!(value)
16
18
  uri = URI.parse(value.to_s)
17
19
  unless uri.is_a?(URI::HTTP) && uri.hostname && !uri.hostname.empty?
18
- raise MetaInspector::RequestError, 'URL must be HTTP or HTTPS'
20
+ raise InvalidURL, 'URL must be HTTP or HTTPS'
19
21
  end
20
22
  uri
21
23
  rescue URI::InvalidURIError => error
22
- raise MetaInspector::RequestError.new(error)
24
+ raise InvalidURL.new(error)
23
25
  end
24
26
 
25
27
  def initialize(app, filter, image_origin = nil)
@@ -32,6 +34,14 @@ module MetaInspector
32
34
  uri = self.class.validate!(env.url)
33
35
  if @image_origin && origin(uri) != origin(@image_origin)
34
36
  env.request_headers.delete_if { |key, _| !IMAGE_HEADERS.include?(key.downcase) }
37
+ unless @image_origin.scheme == 'https' && uri.scheme == 'http'
38
+ referer = @image_origin.dup
39
+ referer.userinfo = nil
40
+ referer.path = '/'
41
+ referer.query = nil
42
+ referer.fragment = nil
43
+ env.request_headers['Referer'] = referer.to_s
44
+ end
35
45
  end
36
46
  check_filter(uri) if @filter
37
47
  @app.call(env)
@@ -1,3 +1,3 @@
1
1
  module MetaInspector
2
- VERSION = '5.20.0'
2
+ VERSION = '5.21.0'
3
3
  end
@@ -5,6 +5,7 @@ require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/url')
5
5
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parser'))
6
6
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/base'))
7
7
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/images'))
8
+ require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/iframes'))
8
9
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/links'))
9
10
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/head_links'))
10
11
  require File.expand_path(File.join(File.dirname(__FILE__), 'meta_inspector/parsers/meta_tags'))
@@ -24,6 +24,7 @@ Gem::Specification.new do |gem|
24
24
  gem.add_dependency 'faraday-http-cache', '>= 2.8', '< 4.0'
25
25
  gem.add_dependency 'faraday-retry', '~> 2.0'
26
26
  gem.add_dependency 'addressable', '~> 2.9.1'
27
+ gem.add_dependency 'base64', '~> 0.3'
27
28
  gem.add_dependency 'fastimage', '~> 2.2'
28
29
  gem.add_dependency 'nesty', '~> 1.0'
29
30
 
@@ -31,8 +32,6 @@ Gem::Specification.new do |gem|
31
32
  gem.add_development_dependency 'webmock', '~> 3.17'
32
33
  gem.add_development_dependency 'rake', '~> 13.0'
33
34
  gem.add_development_dependency 'pry', '~> 0.14'
34
- gem.add_development_dependency 'puma', '~> 8.0', '>= 8.0.2'
35
35
  gem.add_development_dependency 'rubocop', '~> 1.34'
36
36
  gem.add_development_dependency 'resolv', '~> 0.8'
37
- gem.add_development_dependency 'sinatra', '~> 4.2'
38
37
  end
@@ -1,6 +1,144 @@
1
1
  require 'spec_helper'
2
2
 
3
3
  describe MetaInspector::Document do
4
+ describe 'public API' do
5
+ let(:html) do
6
+ <<~HTML
7
+ <html><head>
8
+ <link rel="icon" href="/icon.png">
9
+ <link rel="alternate" type="application/rss+xml" title="News" href="/feed.xml">
10
+ </head><body></body></html>
11
+ HTML
12
+ end
13
+ let(:page) { MetaInspector.new('https://example.com/', document: html) }
14
+
15
+ it 'retains the deprecated feed and favicon methods' do
16
+ expect(page).to respond_to(:feed, :favicon)
17
+ end
18
+
19
+ it 'exposes feeds through the plural API' do
20
+ expect(page.feeds).to eq([
21
+ { title: 'News', href: 'https://example.com/feed.xml', type: 'application/rss+xml' }
22
+ ])
23
+ end
24
+
25
+ it 'exposes the favicon through the images API' do
26
+ expect(page.images.favicon).to eq('https://example.com/icon.png')
27
+ end
28
+
29
+ { feed: 'feeds', favicon: 'images.favicon' }.each do |method, replacement|
30
+ it "warns on each call to ##{method}, naming its replacement and removal version" do
31
+ 2.times do
32
+ expect { page.public_send(method) }.to output(
33
+ "DEPRECATION WARNING: page.#{method} is deprecated and will be removed in 6.0. Use page.#{replacement} instead.\n"
34
+ ).to_stderr
35
+ end
36
+ end
37
+
38
+ it "returns nil from ##{method} when the document has no matching metadata" do
39
+ empty_page = MetaInspector.new('https://example.com/', document: '<html></html>')
40
+
41
+ expect { expect(empty_page.public_send(method)).to be_nil }.to output(/DEPRECATION/).to_stderr
42
+ end
43
+ end
44
+
45
+ it 'returns the favicon URL from the deprecated shortcut' do
46
+ expect { expect(page.favicon).to eq(page.images.favicon) }.to output(/DEPRECATION/).to_stderr
47
+ end
48
+
49
+ it 'keeps the supported APIs and serialization free of deprecation warnings' do
50
+ stub_request(:get, 'https://example.com/').to_return(body: html)
51
+ fetched_page = MetaInspector.new('https://example.com/', download_images: false)
52
+
53
+ expect do
54
+ fetched_page.feeds
55
+ fetched_page.images.favicon
56
+ fetched_page.to_hash
57
+ end.not_to output.to_stderr
58
+ end
59
+
60
+ describe '#feed' do
61
+ let(:html) do
62
+ <<~HTML
63
+ <html><head>
64
+ <base href="https://example.com/blog/">
65
+ <link rel="alternate" type="application/json" href="feed.json">
66
+ <link rel="alternate" type="#{first_type}" href="first.xml">
67
+ <link rel="alternate" type="application/rss+xml" href="second.xml">
68
+ </head></html>
69
+ HTML
70
+ end
71
+
72
+ ['application/rss+xml', 'application/atom+xml'].each do |type|
73
+ context "with #{type} first" do
74
+ let(:first_type) { type }
75
+
76
+ it 'returns the first RSS or Atom URL, skipping JSON and resolving the base URL' do
77
+ expect { expect(page.feed).to eq('https://example.com/blog/first.xml') }
78
+ .to output(/DEPRECATION/).to_stderr
79
+ end
80
+ end
81
+ end
82
+
83
+ context 'with only JSON feeds' do
84
+ let(:html) { '<link rel="alternate" type="application/json" href="/feed.json">' }
85
+
86
+ it 'returns nil' do
87
+ expect { expect(page.feed).to be_nil }.to output(/DEPRECATION/).to_stderr
88
+ end
89
+ end
90
+ end
91
+
92
+ ['<html></html>', nil].each do |document|
93
+ context "with #{document ? 'empty' : 'populated'} HTML" do
94
+ before do
95
+ stub_request(:get, 'https://example.com/').to_return(
96
+ body: document || html, headers: { 'Content-Type' => 'text/html' }
97
+ )
98
+ end
99
+
100
+ MetaInspector::Document.public_instance_methods(false).sort.each do |method|
101
+ it "can call ##{method}" do
102
+ fetched_page = MetaInspector.new('https://example.com/', download_images: false)
103
+
104
+ if [:feed, :favicon].include?(method)
105
+ expect { fetched_page.public_send(method) }.to output(/DEPRECATION/).to_stderr
106
+ else
107
+ expect { fetched_page.public_send(method) }.not_to raise_error
108
+ end
109
+ end
110
+ end
111
+ end
112
+ end
113
+ end
114
+
115
+ describe 'max_html_bytes option' do
116
+ it 'rejects oversized supplied HTML before parsing' do
117
+ expect do
118
+ MetaInspector.new('http://example.com/', document: '<p>é</p>', max_html_bytes: 8)
119
+ end.to raise_error(MetaInspector::ParserError, /HTML.*9 bytes.*8 bytes/)
120
+ end
121
+
122
+ it 'accepts HTML at the byte limit and without a limit' do
123
+ html = '<title>é</title>'
124
+ expect(MetaInspector.new('http://example.com/', document: html, max_html_bytes: html.bytesize).title).to eq('é')
125
+ expect(MetaInspector.new('http://example.com/', document: html).title).to eq('é')
126
+ end
127
+
128
+ it 'rejects oversized fetched HTML' do
129
+ stub_request(:get, 'http://example.com/').to_return(body: '<p>hello</p>', headers: { 'Content-Type' => 'text/html' })
130
+ expect { MetaInspector.new('http://example.com/', max_html_bytes: 5) }.to raise_error(MetaInspector::ParserError)
131
+ end
132
+
133
+ [-1, 1.5, '1', true, false].each do |limit|
134
+ it "rejects invalid limit #{limit.inspect} before fetching" do
135
+ expect { MetaInspector.new('http://example.com/', max_html_bytes: limit) }
136
+ .to raise_error(ArgumentError, 'max_html_bytes must be a non-negative Integer or nil')
137
+ expect(WebMock).not_to have_requested(:get, 'http://example.com/')
138
+ end
139
+ end
140
+ end
141
+
4
142
  describe 'max_image_downloads option' do
5
143
  [-1, 1.5, '1', true, false].each do |limit|
6
144
  it "should reject #{limit.inspect} before fetching the document" do
@@ -62,6 +200,7 @@ describe MetaInspector::Document do
62
200
  'non_http' => ["mailto:pagerankalert@gmail.com"]
63
201
  },
64
202
  "images" => ["http://pagerankalert.com/images/pagerank_alert.png?1305794559"],
203
+ "iframes" => [],
65
204
  "charset" => "utf-8",
66
205
  "feeds" => [{href: "http://feeds.feedburner.com/PageRankAlert", title: "PageRankAlert.com blog", type: "application/rss+xml"}],
67
206
  "h1" => [],