metainspector 5.19.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 (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +21 -0
  3. data/Gemfile +1 -1
  4. data/README.md +214 -9
  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 +23 -4
  15. data/lib/meta_inspector/http_session.rb +75 -0
  16. data/lib/meta_inspector/image_downloader.rb +98 -0
  17. data/lib/meta_inspector/parser.rb +22 -2
  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 +196 -27
  21. data/lib/meta_inspector/parsers/texts.rb +2 -2
  22. data/lib/meta_inspector/request.rb +17 -39
  23. data/lib/meta_inspector/url_policy.rb +68 -0
  24. data/lib/meta_inspector/version.rb +1 -1
  25. data/lib/meta_inspector.rb +1 -0
  26. data/meta_inspector.gemspec +1 -2
  27. data/spec/document_spec.rb +139 -0
  28. data/spec/examples_spec.rb +206 -0
  29. data/spec/image_download_spec.rb +125 -0
  30. data/spec/image_metadata_spec.rb +110 -0
  31. data/spec/image_validity_spec.rb +195 -0
  32. data/spec/inline_images_spec.rb +75 -0
  33. data/spec/meta_inspector/head_links_spec.rb +69 -0
  34. data/spec/meta_inspector/iframes_spec.rb +50 -0
  35. data/spec/meta_inspector/images_spec.rb +130 -0
  36. data/spec/meta_inspector/meta_inspector_spec.rb +58 -7
  37. data/spec/meta_inspector/texts_spec.rb +50 -0
  38. data/spec/parser_spec.rb +10 -0
  39. data/spec/request_spec.rb +1 -1
  40. data/spec/unicode_image_urls_spec.rb +74 -0
  41. data/spec/url_filter_spec.rb +206 -0
  42. metadata +32 -36
  43. data/examples/redirect_web_server.rb +0 -5
@@ -0,0 +1,75 @@
1
+ require 'http/cookie'
2
+ require 'faraday'
3
+ require 'faraday-cookie_jar'
4
+ require 'faraday-http-cache'
5
+ require 'faraday/encoding'
6
+ require 'faraday/follow_redirects'
7
+ require 'faraday/gzip'
8
+ require 'faraday/retry'
9
+ require_relative 'url_policy'
10
+
11
+ module MetaInspector
12
+ # Builds page and binary image transports from the same caller configuration.
13
+ class HttpSession
14
+ def initialize(options = {})
15
+ @allow_redirections = options[:allow_redirections]
16
+ @retries = options[:retries]
17
+ @headers = options[:headers]
18
+ @url_filter = options[:url_filter]
19
+ if !@url_filter.nil? && !@url_filter.respond_to?(:call)
20
+ raise ArgumentError, 'url_filter must respond to call'
21
+ end
22
+ @cache = cache_option(options)
23
+ @faraday_options = (options[:faraday_options] || {}).except(:faraday_http_cache)
24
+ end
25
+
26
+ def build(url, image: false, origin: nil, protect_redirect_callback: false)
27
+ URLPolicy.validate!(url)
28
+ faraday_options = @faraday_options.merge(url: url)
29
+ redirects = (faraday_options.delete(:redirect) || {}).dup
30
+ if protect_redirect_callback && redirects[:callback]
31
+ callback = redirects[:callback]
32
+ redirects[:callback] = lambda do |*args|
33
+ begin
34
+ callback.call(*args)
35
+ rescue StandardError => error
36
+ raise URLPolicy::Failure.new(error)
37
+ end
38
+ end
39
+ end
40
+ Faraday.new(faraday_options) do |faraday|
41
+ unless image
42
+ faraday.request :retry, max: @retries
43
+ faraday.request :gzip
44
+ end
45
+ if @allow_redirections
46
+ redirects[:limit] ||= 10
47
+ faraday.use Faraday::FollowRedirects::Middleware, **redirects
48
+ faraday.use :cookie_jar
49
+ end
50
+ faraday.use URLPolicy, @url_filter, image ? origin : nil
51
+ if !image && @cache.is_a?(Hash)
52
+ cache_options = @cache.dup
53
+ cache_options[:serializer] ||= Marshal
54
+ faraday.use Faraday::HttpCache, **cache_options
55
+ end
56
+ faraday.headers.merge!(@headers || {})
57
+ faraday.response :encoding unless image
58
+ faraday.adapter :net_http
59
+ end
60
+ end
61
+
62
+ private
63
+
64
+ def cache_option(options)
65
+ nested = (options[:faraday_options] || {})[:faraday_http_cache]
66
+ top_level = options[:faraday_http_cache]
67
+ return nested if top_level.nil?
68
+ unless nested.nil?
69
+ raise ArgumentError, 'Pass faraday_http_cache inside faraday_options or as a top-level option, not both'
70
+ end
71
+ Request.warn_faraday_http_cache_deprecation
72
+ top_level
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,98 @@
1
+ require 'stringio'
2
+ require 'fastimage'
3
+ require 'timeout'
4
+ require 'base64'
5
+
6
+ module MetaInspector
7
+ class ImageDownloader
8
+ MAX_BYTES = 256 * 1024
9
+ TIMEOUT = 2
10
+
11
+ def initialize(session, origin, options = {})
12
+ @session = session
13
+ @origin = origin
14
+ @connection_timeout = [options[:connection_timeout] || TIMEOUT, TIMEOUT].min
15
+ @read_timeout = [options[:read_timeout] || TIMEOUT, TIMEOUT].min
16
+ end
17
+
18
+ def size(url, reject_invalid_url: false)
19
+ fetch(url, metadata: false, reject_invalid_url: reject_invalid_url)
20
+ end
21
+
22
+ def metadata(url, reject_invalid_url: false)
23
+ fetch(url, metadata: true, reject_invalid_url: reject_invalid_url)
24
+ end
25
+
26
+ def inline_metadata(url)
27
+ header, payload = url.split(',', 2)
28
+ return nil unless payload && !payload.match?(/%(?![0-9a-fA-F]{2})/)
29
+
30
+ bytes = payload.gsub(/%([0-9a-fA-F]{2})/) { [$1.to_i(16)].pack('C') }.b
31
+ bytes = Base64.strict_decode64(bytes) if header.match?(/;base64\z/i)
32
+ dimensions = FastImage.size(StringIO.new(bytes))
33
+ return nil unless dimensions
34
+
35
+ { dimensions: dimensions, type: FastImage.type(StringIO.new(bytes)), file_size: bytes.bytesize }
36
+ rescue ArgumentError
37
+ nil
38
+ end
39
+
40
+ private
41
+
42
+ def fetch(url, metadata:, reject_invalid_url:)
43
+ bytes = ''.b
44
+ received = 0
45
+ status = nil
46
+ headers = nil
47
+ completed = false
48
+ stop = Object.new
49
+ Timeout.timeout(TIMEOUT) do
50
+ session = @session.build(url, image: true, origin: @origin.url, protect_redirect_callback: reject_invalid_url)
51
+ catch(stop) do
52
+ session.get do |request|
53
+ request.headers['Range'] = "bytes=0-#{MAX_BYTES - 1}"
54
+ request.headers['Accept-Encoding'] = 'identity'
55
+ request.options.open_timeout = @connection_timeout
56
+ request.options.timeout = @read_timeout
57
+ request.options.on_data = proc do |chunk, _total, env|
58
+ status = env.status
59
+ headers = env.response_headers
60
+ remaining = MAX_BYTES - received
61
+ received += chunk.bytesize
62
+ # 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)
66
+ throw stop
67
+ end
68
+ throw stop if received >= MAX_BYTES
69
+ end
70
+ end
71
+ completed = true
72
+ end
73
+ 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
86
+ end
87
+
88
+ def file_size(status, headers, completed, bytesize)
89
+ value = if status == 206
90
+ headers['content-range'].to_s[/\Abytes \d+-\d+\/(\d+)\z/i, 1]
91
+ elsif status == 200 && (headers['content-encoding'].nil? || headers['content-encoding'] == 'identity')
92
+ length = headers['content-length']
93
+ length.nil? && completed ? bytesize.to_s : length.to_s[/\A\d+\z/]
94
+ end
95
+ value.to_i if value
96
+ end
97
+ end
98
+ end
@@ -10,12 +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
- max_image_downloads: options[:max_image_downloads])
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)
19
25
  @texts_parser = MetaInspector::Parsers::TextsParser.new(self)
20
26
 
21
27
  parsed # parse early so we can fail early
@@ -27,12 +33,26 @@ module MetaInspector
27
33
  delegate [:head_links, :stylesheets, :canonicals, :feeds, :feed] => :@head_links_parser
28
34
  delegate [:links, :base_url] => :@links_parser
29
35
  delegate :images => :@images_parser
36
+ delegate [:iframes, :iframe_sources] => :@iframes_parser
30
37
  delegate [:language, :title, :best_title, :author, :best_author, :description, :best_description,
31
38
  :h1, :h2, :h3, :h4, :h5, :h6] => :@texts_parser
32
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
+
33
47
  # Returns the whole parsed document
34
48
  def parsed
35
- @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
36
56
  end
37
57
  end
38
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
- require 'fastimage'
1
+ require_relative '../image_downloader'
2
+ require 'strscan'
2
3
 
3
4
  module MetaInspector
4
5
  module Parsers
@@ -9,8 +10,15 @@ module MetaInspector
9
10
  include Enumerable
10
11
 
11
12
  def initialize(main_parser, options = {})
13
+ @image_downloader = options[:image_downloader]
12
14
  @download_images = options[:download_images]
13
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
14
22
  super(main_parser)
15
23
  end
16
24
 
@@ -21,7 +29,7 @@ module MetaInspector
21
29
  # Returns the Facebook Open Graph image, Twitter image, Parsely image or
22
30
  # the largest image in the image collection
23
31
  def best
24
- owner_suggested || largest
32
+ suggested_image(skip_inline: !@inline_image_data) || largest
25
33
  end
26
34
 
27
35
  # Returns the parsed image from Facebook's open graph property tags
@@ -29,36 +37,62 @@ module MetaInspector
29
37
  # See doc at http://developers.facebook.com/docs/opengraph/
30
38
  # If none found, tries with Twitter image, then Parsely image
31
39
  def owner_suggested
32
- suggested_img = content_of(meta['og:image']) || content_of(meta['twitter:image']) ||
33
- content_of(meta['parsely-image-url'])
34
- 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
35
48
  end
36
49
 
37
50
  # Returns an array of [img_url, width, height] sorted by image area (width * height)
38
51
  def with_size
39
52
  @with_size ||= begin
40
- img_nodes = parsed.search('//img').select{ |img_node| img_node['src'] }
41
- imgs_with_size = img_nodes.map do |img_node|
42
- [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 }
43
56
  end
44
- imgs_with_size.reject! { |url, width, height| url.nil? || url.empty? }
45
- imgs_with_size.uniq! { |url, width, height| url }
46
- download_attempts = 0
47
- imgs_with_size.map! do |url, width, height|
57
+ imgs_with_size.map! do |url, width, height, _responsive|
48
58
  if width.nil? || height.nil?
49
- if @download_images && (@max_image_downloads.nil? || download_attempts < @max_image_downloads)
50
- download_attempts += 1
51
- width, height = FastImage.size(url)
52
- else
53
- width, height = [0, 0]
54
- end
59
+ width, height = image_size(url) || [0, 0]
55
60
  end
56
- [url, width.to_i, height.to_i]
61
+ [result_url(url), width.to_i, height.to_i]
57
62
  end
58
63
  imgs_with_size.sort_by { |url, width, height| -(width.to_i * height.to_i) }
59
64
  end
60
65
  end
61
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
+
62
96
  # Returns the largest image from the image collection,
63
97
  # filtered for images that are more square than 10:1 or 1:10
64
98
  def largest
@@ -66,7 +100,7 @@ module MetaInspector
66
100
  imgs_with_size = with_size.dup
67
101
  imgs_with_size.keep_if do |url, width, height|
68
102
  ratio = width.to_f / height.to_f
69
- ratio > 0.1 && ratio < 10
103
+ (@inline_image_data || !data_image_url?(url)) && ratio > 0.1 && ratio < 10
70
104
  end
71
105
  url, width, height = imgs_with_size.first
72
106
  url
@@ -75,25 +109,160 @@ module MetaInspector
75
109
 
76
110
  # Return favicon url if exist
77
111
  def favicon
78
- query = '//link[@rel="icon" or contains(@rel, "shortcut")]'
79
- value = parsed.xpath(query)[0].attributes['href'].value
80
- @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))
81
118
  rescue
82
119
  nil
83
120
  end
84
121
 
85
122
  private
86
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
+
87
157
  def images_collection
88
- @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
89
224
  end
90
225
 
91
226
  def absolutified_images
92
- 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
93
261
  end
94
262
 
95
- def parsed_images
96
- 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)
97
266
  end
98
267
 
99
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,12 +1,5 @@
1
- require 'http/cookie'
2
- require 'faraday'
3
- require 'faraday-cookie_jar'
4
- require 'faraday-http-cache'
5
- require 'faraday/encoding'
6
- require 'faraday/follow_redirects'
7
- require 'faraday/gzip'
8
- require 'faraday/retry'
9
1
  require 'timeout'
2
+ require_relative 'http_session'
10
3
 
11
4
  module MetaInspector
12
5
 
@@ -15,18 +8,15 @@ module MetaInspector
15
8
  def initialize(initial_url, options = {})
16
9
  @url = initial_url
17
10
 
18
- fail MetaInspector::RequestError.new('URL must be HTTP') unless @url.url =~ /http[s]?:\/\//i
11
+ URLPolicy.validate!(@url.url)
19
12
 
20
13
  @allow_redirections = options[:allow_redirections]
21
14
  @head_first = options[:head_first]
22
15
  @allow_non_html_content = options[:allow_non_html_content]
23
16
  @connection_timeout = options[:connection_timeout]
24
17
  @read_timeout = options[:read_timeout]
25
- @retries = options[:retries]
26
18
  @encoding = options[:encoding]
27
- @headers = options[:headers]
28
- @faraday_options = options[:faraday_options] || {}
29
- @faraday_http_cache = options[:faraday_http_cache]
19
+ @http_session = options[:http_session] || HttpSession.new(options)
30
20
 
31
21
  response # request early so we can fail early
32
22
  end
@@ -49,6 +39,8 @@ module MetaInspector
49
39
 
50
40
  def response
51
41
  @response ||= fetch
42
+ rescue URLPolicy::Failure => failure
43
+ raise failure.original
52
44
  rescue Faraday::TimeoutError => e
53
45
  raise MetaInspector::TimeoutError.new(e)
54
46
  rescue Faraday::ConnectionFailed, Faraday::SSLError, URI::InvalidURIError, Faraday::FollowRedirects::RedirectLimitReached => e
@@ -57,34 +49,20 @@ module MetaInspector
57
49
 
58
50
  private
59
51
 
52
+ # Once per process: apps fetch many pages with the same options, and a warning
53
+ # per request would flood their logs
54
+ def self.warn_faraday_http_cache_deprecation
55
+ return if @faraday_http_cache_deprecation_warned
56
+
57
+ @faraday_http_cache_deprecation_warned = true
58
+ warn 'DEPRECATION WARNING: the top-level faraday_http_cache option is deprecated and will be removed ' \
59
+ 'in the next major version. Pass it inside faraday_options instead: ' \
60
+ 'faraday_options: { faraday_http_cache: { store: cache } }'
61
+ end
62
+
60
63
  def fetch
61
64
  Timeout::timeout(fatal_timeout) do
62
- # Work on copies: the caller may reuse or freeze the hashes it passed in, and
63
- # losing :redirect would drop a callback that blocks redirects to private hosts
64
- faraday_options = @faraday_options.merge(:url => url)
65
- follow_redirects_options = (faraday_options.delete(:redirect) || {}).dup
66
-
67
- session = Faraday.new(faraday_options) do |faraday|
68
- faraday.request :retry, max: @retries
69
-
70
- faraday.request :gzip
71
-
72
- if @allow_redirections
73
- follow_redirects_options[:limit] ||= 10
74
- faraday.use Faraday::FollowRedirects::Middleware, **follow_redirects_options
75
- faraday.use :cookie_jar
76
- end
77
-
78
- if @faraday_http_cache.is_a?(Hash)
79
- cache_options = @faraday_http_cache.dup
80
- cache_options[:serializer] ||= Marshal
81
- faraday.use Faraday::HttpCache, **cache_options
82
- end
83
-
84
- faraday.headers.merge!(@headers || {})
85
- faraday.response :encoding
86
- faraday.adapter :net_http
87
- end
65
+ session = @http_session.build(url)
88
66
 
89
67
  check_head_content_type(session) if @head_first
90
68
  response = perform_request(session, :get)