metainspector 5.21.1 → 5.22.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 (36) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +32 -0
  3. data/README.md +207 -36
  4. data/lib/meta_inspector/attempt_timeout.rb +40 -0
  5. data/lib/meta_inspector/document.rb +27 -4
  6. data/lib/meta_inspector/html_encoding.rb +177 -0
  7. data/lib/meta_inspector/http_session.rb +33 -5
  8. data/lib/meta_inspector/image_downloader.rb +2 -0
  9. data/lib/meta_inspector/limited_response.rb +125 -0
  10. data/lib/meta_inspector/parser.rb +112 -1
  11. data/lib/meta_inspector/parsers/head_links.rb +10 -3
  12. data/lib/meta_inspector/parsers/links.rb +10 -4
  13. data/lib/meta_inspector/parsers/meta_tags.rb +6 -2
  14. data/lib/meta_inspector/parsers/texts.rb +2 -2
  15. data/lib/meta_inspector/request.rb +45 -30
  16. data/lib/meta_inspector/url.rb +32 -5
  17. data/lib/meta_inspector/url_policy.rb +1 -1
  18. data/lib/meta_inspector/version.rb +1 -1
  19. data/meta_inspector.gemspec +1 -1
  20. data/spec/document_spec.rb +118 -0
  21. data/spec/meta_inspector/content_type_spec.rb +47 -0
  22. data/spec/meta_inspector/head_links_spec.rb +3 -3
  23. data/spec/meta_inspector/links_spec.rb +98 -2
  24. data/spec/meta_inspector/meta_tags_spec.rb +53 -0
  25. data/spec/meta_inspector/texts_spec.rb +82 -0
  26. data/spec/meta_inspector/timeouts_spec.rb +107 -0
  27. data/spec/noscript_spec.rb +179 -0
  28. data/spec/parser_spec.rb +382 -2
  29. data/spec/query_string_spec.rb +125 -0
  30. data/spec/request_errors_spec.rb +91 -0
  31. data/spec/request_spec.rb +28 -10
  32. data/spec/response_encoding_spec.rb +487 -0
  33. data/spec/response_size_spec.rb +176 -0
  34. data/spec/url_filter_spec.rb +2 -1
  35. data/spec/url_spec.rb +37 -0
  36. metadata +12 -2
@@ -1,5 +1,5 @@
1
- require 'timeout'
2
1
  require_relative 'http_session'
2
+ require_relative 'html_encoding'
3
3
 
4
4
  module MetaInspector
5
5
 
@@ -27,9 +27,26 @@ module MetaInspector
27
27
  def read
28
28
  return unless response
29
29
  body = response.body
30
- body = body.encode!(@encoding, @encoding, :invalid => :replace) if @encoding
30
+ check_content_encoding!(body)
31
+ if body.encoding == Encoding::BINARY
32
+ # The adapter tags the body only with HTTP charsets Ruby knows.
33
+ label = response.headers['content-type'].to_s[/(?:\A|;)\s*charset\s*=\s*["']?([^;\s"']+)/i, 1]
34
+ charset = HtmlEncoding.resolve(label)
35
+ body = body.dup.force_encoding(charset) if charset
36
+ end
37
+ body = body.dup.force_encoding(@encoding) if @encoding
38
+ encoding = HtmlEncoding.byte_order_mark_encoding(body)
39
+ body = body.dup.force_encoding(encoding) if encoding && !Encoding.find(encoding).ascii_compatible?
40
+ body = HtmlEncoding.normalize(body)
41
+ # Replace invalid bytes with U+FFFD, as browsers do, so one bad byte
42
+ # doesn't make the whole page fail. Binary bodies are decoded later by the parser.
43
+ body = if body.encoding.ascii_compatible?
44
+ body.scrub
45
+ else
46
+ body.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
47
+ end
31
48
  body.tr("\000", '')
32
- rescue ArgumentError => e
49
+ rescue ArgumentError, EncodingError => e
33
50
  raise MetaInspector::RequestError.new(e)
34
51
  end
35
52
 
@@ -41,9 +58,10 @@ module MetaInspector
41
58
  @response ||= fetch
42
59
  rescue URLPolicy::Failure => failure
43
60
  raise failure.original
44
- rescue Faraday::TimeoutError => e
61
+ rescue Faraday::TimeoutError, AttemptTimeout::Expired => e
45
62
  raise MetaInspector::TimeoutError.new(e)
46
- rescue Faraday::ConnectionFailed, Faraday::SSLError, URI::InvalidURIError, Faraday::FollowRedirects::RedirectLimitReached => e
63
+ rescue Faraday::ConnectionFailed, Faraday::SSLError, URI::InvalidURIError, URI::InvalidComponentError,
64
+ Faraday::FollowRedirects::RedirectLimitReached, Zlib::Error => e
47
65
  raise MetaInspector::RequestError.new(e)
48
66
  end
49
67
 
@@ -61,20 +79,16 @@ module MetaInspector
61
79
  end
62
80
 
63
81
  def fetch
64
- Timeout::timeout(fatal_timeout) do
65
- session = @http_session.build(url)
66
-
67
- check_head_content_type(session) if @head_first
68
- response = perform_request(session, :get)
82
+ session = @http_session.build(url)
69
83
 
70
- if @allow_redirections
71
- @url.url = response.env.url.to_s
72
- end
84
+ check_head_content_type(session) if @head_first
85
+ response = perform_request(session, :get)
73
86
 
74
- response
87
+ if @allow_redirections
88
+ @url.url = response.env.url.to_s
75
89
  end
76
- rescue Timeout::Error => e
77
- raise MetaInspector::TimeoutError.new(e)
90
+
91
+ response
78
92
  end
79
93
 
80
94
  def check_head_content_type(session)
@@ -87,26 +101,27 @@ module MetaInspector
87
101
  end
88
102
  end
89
103
 
104
+ # The compression middleware removes Content-Encoding once it has decoded the
105
+ # body. If it's still there, the body is compressed bytes, not HTML (#597).
106
+ def check_content_encoding!(body)
107
+ return if body.empty?
108
+
109
+ header = response.headers['content-encoding'].to_s
110
+ encodings = header.split(',').map { |value| value.strip.downcase }.reject(&:empty?) - ['identity']
111
+ return if encodings.empty?
112
+
113
+ raise MetaInspector::RequestError, "Unsupported Content-Encoding: #{header.strip}"
114
+ end
115
+
90
116
  def response_content_type(response)
91
- response.headers['content-type']&.split(';')&.first
117
+ response.headers['content-type']&.split(';')&.first&.strip&.downcase
92
118
  end
93
119
 
94
120
  def perform_request(session, method)
95
121
  session.public_send(method) do |req|
96
- req.options.timeout = @connection_timeout
97
- req.options.open_timeout = @read_timeout
122
+ req.options.open_timeout = @connection_timeout
123
+ req.options.timeout = @read_timeout
98
124
  end
99
125
  end
100
-
101
- # Timeouts when connecting / reading a request are handled by Faraday, but in the
102
- # case of URLs that respond with streaming, Faraday will never return. In that case,
103
- # we'll resort to our own timeout
104
- #
105
- # https://github.com/jaimeiniesta/metainspector/issues/188
106
- # https://github.com/lostisland/faraday/issues/602
107
- #
108
- def fatal_timeout
109
- (@connection_timeout || 0) + (@read_timeout || 0) + 1
110
- end
111
126
  end
112
127
  end
@@ -33,11 +33,15 @@ module MetaInspector
33
33
  return found_tracking_params.any?
34
34
  end
35
35
 
36
+ # Removes only the tracking key=value pairs, keeping the rest of the
37
+ # query string as written: order, repeated keys and encoding.
36
38
  def untracked_url
37
39
  u = parsed(url)
38
- return url unless u.query_values
39
- query_values = u.query_values.delete_if { |key, _| WELL_KNOWN_TRACKING_PARAMS.include? key }
40
- u.query_values = query_values.length > 0 ? query_values : nil
40
+ return url unless u.query
41
+ params = u.query.split('&', -1)
42
+ kept = params.reject { |param| tracking_param?(param) }
43
+ return url if kept.length == params.length
44
+ u.query = kept.empty? ? nil : kept.join('&')
41
45
  u.to_s
42
46
  end
43
47
 
@@ -62,18 +66,41 @@ module MetaInspector
62
66
  MetaInspector::URL.new(url, options).url
63
67
  else
64
68
  uri = Addressable::URI.join(base_url, url)
65
- options[:normalize] ? uri.normalize.to_s : uri.to_s
69
+ options[:normalize] ? normalize(uri) : uri.to_s
66
70
  end
67
71
  rescue MetaInspector::ParserError, Addressable::URI::InvalidURIError, ArgumentError
68
72
  nil
69
73
  end
70
74
 
75
+ # Addressable's normalization, except for the query: reserved characters such
76
+ # as ";" or "[]" and existing escapes are kept as written, since changing them
77
+ # can change the resource (RFC 3986, 2.2). Only what can't be sent is escaped.
78
+ def self.normalize(uri)
79
+ normalized = uri.normalize
80
+ normalized.query = escape_query(uri.query) if uri.query
81
+ normalized.to_s
82
+ end
83
+
84
+ # Bytes allowed in a query by RFC 3986 (pchar, "/" and "?"), plus "[]" and
85
+ # "%" when it starts an escape. Browsers send "[]" unescaped too.
86
+ QUERY_UNSAFE = /%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$&'()*+,;=:@\/?\[\]%]/n
87
+ private_constant :QUERY_UNSAFE
88
+
89
+ def self.escape_query(query)
90
+ query.b.gsub(QUERY_UNSAFE) { |byte| format('%%%02X', byte.ord) }.force_encoding(Encoding::UTF_8)
91
+ end
92
+
71
93
  private
72
94
 
73
95
  def self.defaults
74
96
  { :normalize => true }
75
97
  end
76
98
 
99
+ def tracking_param?(param)
100
+ key = Addressable::URI.unencode_component(param.split('=', 2).first)
101
+ WELL_KNOWN_TRACKING_PARAMS.include?(key)
102
+ end
103
+
77
104
  # Adds 'http' as default scheme, if there is none
78
105
  def with_default_scheme(url)
79
106
  parsed(url) && parsed(url).scheme.nil? ? 'http://' + url : url
@@ -82,7 +109,7 @@ module MetaInspector
82
109
  # Normalize url to deal with characters that should be encoded,
83
110
  # add trailing slash, convert to downcase...
84
111
  def normalized(url)
85
- Addressable::URI.parse(url).normalize.to_s
112
+ self.class.normalize(Addressable::URI.parse(url))
86
113
  rescue Addressable::URI::InvalidURIError => e
87
114
  raise MetaInspector::ParserError.new(e)
88
115
  end
@@ -21,7 +21,7 @@ module MetaInspector
21
21
  raise InvalidURL, 'URL must be HTTP or HTTPS'
22
22
  end
23
23
  uri
24
- rescue URI::InvalidURIError => error
24
+ rescue URI::InvalidURIError, URI::InvalidComponentError => error
25
25
  raise InvalidURL.new(error)
26
26
  end
27
27
 
@@ -1,3 +1,3 @@
1
1
  module MetaInspector
2
- VERSION = '5.21.1'
2
+ VERSION = '5.22.0'
3
3
  end
@@ -8,7 +8,7 @@ Gem::Specification.new do |gem|
8
8
  gem.homepage = "https://github.com/jaimeiniesta/metainspector"
9
9
  gem.license = "MIT"
10
10
 
11
- gem.files = `git ls-files`.split("\n") - ["Gemfile.lock"]
11
+ gem.files = (`git ls-files`.split("\n") - ["Gemfile.lock"]).reject { |f| f.start_with?("assets/") }
12
12
  gem.test_files = `git ls-files -- {spec}/*`.split("\n")
13
13
  gem.name = "metainspector"
14
14
  gem.require_paths = ["lib"]
@@ -1,6 +1,76 @@
1
1
  require 'spec_helper'
2
+ require 'json'
2
3
 
3
4
  describe MetaInspector::Document do
5
+ describe '#to_hash response headers' do
6
+ let(:url) { 'https://headers.example/' }
7
+ let(:page) { MetaInspector.new(url, download_images: false) }
8
+
9
+ before do
10
+ stub_request(:get, url).to_return(
11
+ body: '<title>Example</title>',
12
+ headers: { 'Content-Type' => 'text/html', 'X-Olaf' => header_value }
13
+ )
14
+ end
15
+
16
+ {
17
+ 'ASCII text' => ['plain text'.b, 'plain text'],
18
+ 'UTF-8 text' => ["\u2603", "\u2603"],
19
+ 'text with a known encoding' => ["caf\xE9".force_encoding(Encoding::ISO_8859_1), 'café'],
20
+ 'UTF-8 bytes in a binary string' => ["\u2603".b, "\u2603"],
21
+ 'invalid UTF-8 bytes in a binary string' => ["snowman \xFF".b, "snowman \uFFFD"],
22
+ 'invalid bytes in a UTF-8 string' => ["snowman \xFF", "snowman \uFFFD"]
23
+ }.each do |description, (value, expected)|
24
+ context "with #{description}" do
25
+ let(:header_value) { value }
26
+
27
+ it 'serializes the headers as valid UTF-8 in JSON' do
28
+ serialized = JSON.pretty_generate(page.to_hash)
29
+
30
+ expect(JSON.parse(serialized)['response']['headers']['x-olaf']).to eq(expected)
31
+ expect(page.to_hash['response']['headers']['x-olaf'].encoding).to eq(Encoding::UTF_8)
32
+ end
33
+ end
34
+ end
35
+
36
+ context 'when preserving the original response' do
37
+ let(:header_value) { "\u2603".b }
38
+
39
+ it 'leaves the raw headers and their encoding unchanged' do
40
+ raw_headers = page.response.headers
41
+ raw_value = raw_headers['x-olaf']
42
+ raw_value.freeze
43
+ raw_headers.freeze
44
+
45
+ page.to_hash
46
+
47
+ expect(page.response.headers).to equal(raw_headers)
48
+ expect(raw_headers['x-olaf']).to equal(raw_value)
49
+ expect(raw_value.bytes).to eq([0xE2, 0x98, 0x83])
50
+ expect(raw_value.encoding).to eq(Encoding::BINARY)
51
+ end
52
+ end
53
+
54
+ context 'when the response was compressed' do
55
+ let(:header_value) { 'unused' }
56
+ let(:html) { '<html><head><title>Hello</title></head></html>' }
57
+
58
+ before do
59
+ stub_request(:get, url).to_return(
60
+ body: Zlib.gzip(html),
61
+ headers: { 'Content-Type' => 'text/html', 'Content-Encoding' => 'gzip' }
62
+ )
63
+ end
64
+
65
+ it 'keeps header values that are not strings, like the decompressed Content-Length' do
66
+ headers = page.to_hash['response']['headers']
67
+
68
+ expect(headers['content-length']).to eq(html.bytesize)
69
+ expect(JSON.parse(JSON.generate(page.to_hash))['response']['headers']['content-length']).to eq(html.bytesize)
70
+ end
71
+ end
72
+ end
73
+
4
74
  describe 'public API' do
5
75
  let(:html) do
6
76
  <<~HTML
@@ -22,6 +92,40 @@ describe MetaInspector::Document do
22
92
  ])
23
93
  end
24
94
 
95
+ describe 'feed types' do
96
+ let(:html) do
97
+ <<~HTML
98
+ <html><head>
99
+ <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">
100
+ <link rel="alternate" type="application/feed+json" title="JSON Feed" href="/feed.json">
101
+ <link rel="alternate" type="Application/Atom+XML" title="Atom" href="/atom.xml">
102
+ <link rel="alternate" type=" application/rss+xml ; charset=utf-8" title="RSS with parameter" href="/rss2.xml">
103
+ <link rel="alternate" type="application/rss+xml-ish" title="Unknown" href="/other.xml">
104
+ <link rel="alternate" type="text/html" title="Translation" href="/es/">
105
+ </head></html>
106
+ HTML
107
+ end
108
+
109
+ it 'matches JSON Feed 1.1 and types with any case, whitespace or parameters, keeping the type as written' do
110
+ expect(page.feeds).to eq([
111
+ { title: 'RSS', href: 'https://example.com/feed.xml', type: 'application/rss+xml' },
112
+ { title: 'JSON Feed', href: 'https://example.com/feed.json', type: 'application/feed+json' },
113
+ { title: 'Atom', href: 'https://example.com/atom.xml', type: 'Application/Atom+XML' },
114
+ { title: 'RSS with parameter', href: 'https://example.com/rss2.xml',
115
+ type: ' application/rss+xml ; charset=utf-8' }
116
+ ])
117
+ end
118
+
119
+ it 'returns RSS or Atom feeds with parameters from the deprecated feed method' do
120
+ page = MetaInspector.new('https://example.com/', document: <<~HTML)
121
+ <link rel="alternate" type="application/feed+json" href="/feed.json">
122
+ <link rel="alternate" type="application/atom+xml; charset=utf-8" href="/atom.xml">
123
+ HTML
124
+
125
+ expect { expect(page.feed).to eq('https://example.com/atom.xml') }.to output(/DEPRECATION/).to_stderr
126
+ end
127
+ end
128
+
25
129
  it 'exposes the favicon through the images API' do
26
130
  expect(page.images.favicon).to eq('https://example.com/icon.png')
27
131
  end
@@ -161,6 +265,20 @@ describe MetaInspector::Document do
161
265
  it "should get the title" do
162
266
  expect(doc.title).to eq("Hello From Passed Html")
163
267
  end
268
+
269
+ it 'returns nil content type and response, since no request was made' do
270
+ expect do
271
+ expect(doc.content_type).to be_nil
272
+ expect(doc.response).to be_nil
273
+ end.not_to output.to_stderr
274
+ end
275
+
276
+ it 'serializes to_hash with nil content type and response' do
277
+ hash = doc.to_hash
278
+
279
+ expect(hash).to include('title' => 'Hello From Passed Html', 'content_type' => nil, 'response' => nil)
280
+ expect(hash['links']['internal']).to eq(['http://cnn.com/hello'])
281
+ end
164
282
  end
165
283
 
166
284
  it "should return a String as to_s" do
@@ -0,0 +1,47 @@
1
+ require 'spec_helper'
2
+
3
+ describe MetaInspector, 'content type normalization' do
4
+ let(:page_url) { 'http://example.com/content-type' }
5
+ let(:html) { '<html><head><title>Downloaded page</title></head></html>' }
6
+
7
+ [false, true].each do |head_first|
8
+ context "with head_first: #{head_first}" do
9
+ ['Text/HTML; charset=utf-8', 'text/html ; charset=utf-8', " \tTEXT/HTML\t; charset=utf-8"].each do |content_type|
10
+ it "parses HTML served as #{content_type.inspect}" do
11
+ stub_request(:head, page_url).to_return(headers: { 'Content-Type' => content_type }) if head_first
12
+ stub_request(:get, page_url).to_return(body: html, headers: { 'Content-Type' => content_type })
13
+
14
+ page = MetaInspector.new(page_url, head_first: head_first)
15
+
16
+ expect(page.title).to eq('Downloaded page')
17
+ expect(page.content_type).to eq('text/html')
18
+ expect(page.to_hash['content_type']).to eq('text/html')
19
+ expect(page.response.headers['content-type']).to eq(content_type)
20
+ end
21
+ end
22
+
23
+ it 'still rejects non-HTML content after normalization' do
24
+ stub_request(:head, page_url).to_return(headers: { 'Content-Type' => 'Application/PDF ; version=1.7' }) if head_first
25
+ get_request = stub_request(:get, page_url)
26
+ .to_return(body: 'PDF data', headers: { 'Content-Type' => 'Application/PDF ; version=1.7' })
27
+
28
+ expect do
29
+ MetaInspector.new(page_url, head_first: head_first)
30
+ end.to raise_error(MetaInspector::NonHtmlError,
31
+ 'The url provided contains application/pdf content instead of text/html content')
32
+
33
+ expect(get_request).not_to have_been_requested if head_first
34
+ end
35
+
36
+ it 'normalizes non-HTML content when explicitly allowed' do
37
+ stub_request(:head, page_url).to_return(headers: { 'Content-Type' => 'Text/Plain ; charset=utf-8' }) if head_first
38
+ stub_request(:get, page_url).to_return(body: 'Plain text', headers: { 'Content-Type' => 'Text/Plain ; charset=utf-8' })
39
+
40
+ page = MetaInspector.new(page_url, head_first: head_first, allow_non_html_content: true)
41
+
42
+ expect(page.to_s).to eq('Plain text')
43
+ expect(page.content_type).to eq('text/plain')
44
+ end
45
+ end
46
+ end
47
+ end
@@ -56,7 +56,7 @@ describe MetaInspector do
56
56
  let(:page) { MetaInspector.new('https://example.com/page', document: document) }
57
57
  let(:expected_link) do
58
58
  attributes = { title: 'Example', href: 'https://example.com/resource', type: 'application/rss+xml' }
59
- attributes[:rel] = rel unless method == :feeds
59
+ attributes[:rel] = rel.gsub(/\r\n?/, "\n") unless method == :feeds
60
60
  attributes
61
61
  end
62
62
 
@@ -68,9 +68,9 @@ describe MetaInspector do
68
68
  let(:rel) { value }
69
69
  let(:rel_attribute) { %(rel="#{rel}") }
70
70
 
71
- it "matches the complete token and preserves the link attributes" do
71
+ it "matches the complete token and preserves the parsed link attributes" do
72
72
  expect(page.public_send(method)).to eq([expected_link])
73
- expect(page.head_links.first[:rel]).to eq(rel)
73
+ expect(page.head_links.first[:rel]).to eq(rel.gsub(/\r\n?/, "\n"))
74
74
  end
75
75
  end
76
76
  end
@@ -58,7 +58,7 @@ describe MetaInspector do
58
58
  "http://international.com/faqs#cami%C3%83%C2%B3n",
59
59
  "http://international.com/search?q=cami%C3%83%C2%B3n",
60
60
  "http://international.com/search?q=espa%C3%83%C2%B1a#top",
61
- "http://international.com/index.php?q=espa%C3%83%C2%B1a&url=aHR0zZQ==&cntnt01pageid=21"
61
+ "http://international.com/index.php?q=espa%C3%83%C2%B1a&url=aHR0zZQ%3D%3D&cntnt01pageid=21"
62
62
  ])
63
63
 
64
64
  expect(m.links.external).to eq([
@@ -79,7 +79,7 @@ describe MetaInspector do
79
79
  "http://international.com/faqs#cami%C3%83%C2%B3n",
80
80
  "http://international.com/search?q=cami%C3%83%C2%B3n",
81
81
  "http://international.com/search?q=espa%C3%83%C2%B1a#top",
82
- "http://international.com/index.php?q=espa%C3%83%C2%B1a&url=aHR0zZQ==&cntnt01pageid=21"
82
+ "http://international.com/index.php?q=espa%C3%83%C2%B1a&url=aHR0zZQ%3D%3D&cntnt01pageid=21"
83
83
  ])
84
84
  end
85
85
 
@@ -215,6 +215,57 @@ describe MetaInspector do
215
215
  end
216
216
  end
217
217
 
218
+ describe 'Base element lookup' do
219
+ # Searching the whole document for <base> once per link, image, iframe or
220
+ # <link> made these methods take quadratic time on large pages (#573).
221
+ callers = {
222
+ 'links.all' => ->(page) { page.links.all },
223
+ 'images.to_a' => ->(page) { page.images.to_a },
224
+ 'iframe_sources' => ->(page) { page.iframe_sources },
225
+ 'head_links' => ->(page) { page.head_links },
226
+ 'feeds' => ->(page) { page.feeds }
227
+ }
228
+
229
+ { 'without a base element' => '', 'with a base element' => '<base href="/dir/">' }.each do |name, base|
230
+ context name do
231
+ let(:html) do
232
+ <<~HTML
233
+ <html><head>#{base}
234
+ <link rel="stylesheet" href="a.css"><link rel="stylesheet" href="b.css">
235
+ <link rel="alternate" type="application/rss+xml" href="a.xml">
236
+ <link rel="alternate" type="application/atom+xml" href="b.xml">
237
+ </head><body>
238
+ <a href="a">a</a><a href="b">b</a><a href="c">c</a>
239
+ <img src="a.png"><img src="b.png"><img srcset="c.png 1x, d.png 2x">
240
+ <iframe src="a.html"></iframe><iframe src="b.html"></iframe>
241
+ </body></html>
242
+ HTML
243
+ end
244
+ let(:page) { MetaInspector.new('http://example.com/', document: html) }
245
+
246
+ callers.each do |method, call|
247
+ it "searches the document for it only once for #{method}" do
248
+ allow(page.parsed).to receive(:search).and_call_original
249
+
250
+ call.call(page)
251
+
252
+ expect(page.parsed).to have_received(:search).with('base').once
253
+ end
254
+ end
255
+ end
256
+ end
257
+
258
+ it 'keeps following the page URL when there is no base element' do
259
+ page = MetaInspector.new('http://example.com/?utm_source=feed', document: '<html><body><a href="a">a</a></body></html>')
260
+
261
+ expect(page.links.base_url).to eq('http://example.com/?utm_source=feed')
262
+
263
+ page.untrack!
264
+
265
+ expect(page.links.base_url).to eq('http://example.com/')
266
+ end
267
+ end
268
+
218
269
  describe 'Non-HTTP links' do
219
270
  before(:each) do
220
271
  @m = MetaInspector.new('http://example.com/nonhttp')
@@ -231,6 +282,51 @@ describe MetaInspector do
231
282
  end
232
283
  end
233
284
 
285
+ describe 'Links inside inline SVG and MathML' do
286
+ let(:page) do
287
+ MetaInspector.new('http://example.com/', document: <<~HTML)
288
+ <html><body>
289
+ <a href="/before">text</a>
290
+ <svg viewBox="0 0 10 10"><a href="/svg-link"><circle r="5"/></a></svg>
291
+ <math><a href="/math-link">x</a></math>
292
+ <a href="/after">text</a>
293
+ </body></html>
294
+ HTML
295
+ end
296
+
297
+ it 'returns them with the HTML links, in document order' do
298
+ expect(page.links.raw).to eq(['/before', '/svg-link', '/math-link', '/after'])
299
+ end
300
+
301
+ it 'resolves them like any other link' do
302
+ expect(page.links.internal).to eq(['http://example.com/before',
303
+ 'http://example.com/svg-link',
304
+ 'http://example.com/math-link',
305
+ 'http://example.com/after'])
306
+ end
307
+ end
308
+
309
+ describe 'Query strings in links' do
310
+ let(:page) do
311
+ MetaInspector.new('http://example.com/dir/', document: <<~HTML)
312
+ <a href="/a?x=1;y=2&b[]=1&c=a%2fb&%61=1">relative</a>
313
+ <a href="http://other.com/a?x=1;y=2&b[]=1&c=a%2fb&%61=1">absolute</a>
314
+ <a href="b?q=café&r=a|b&s=50%">needs escaping</a>
315
+ <link rel="alternate" type="application/rss+xml" href="/feed?x=1;y=2">
316
+ HTML
317
+ end
318
+
319
+ it 'keeps reserved characters and escapes as written (#613)' do
320
+ expect(page.links.all).to eq(['http://example.com/a?x=1;y=2&b[]=1&c=a%2fb&%61=1',
321
+ 'http://other.com/a?x=1;y=2&b[]=1&c=a%2fb&%61=1',
322
+ 'http://example.com/dir/b?q=caf%C3%A9&r=a%7Cb&s=50%25'])
323
+ end
324
+
325
+ it 'applies the same rule to head links' do
326
+ expect(page.feeds.map { |feed| feed[:href] }).to eq(['http://example.com/feed?x=1;y=2'])
327
+ end
328
+ end
329
+
234
330
  describe 'Protocol-relative URLs' do
235
331
  before(:each) do
236
332
  @m_http = MetaInspector.new('http://protocol-relative.com')
@@ -103,5 +103,58 @@ describe MetaInspector do
103
103
 
104
104
  expect(page.charset).to eq(nil)
105
105
  end
106
+
107
+ ['Content-Type', 'content-type', 'Content-type', 'CONTENT-TYPE'].each do |http_equiv|
108
+ it "gets the charset when http-equiv is #{http_equiv}" do
109
+ html = %(<meta http-equiv="#{http_equiv}" content="text/html; charset=utf-8">)
110
+ page = MetaInspector.new('http://example.com', document: html)
111
+
112
+ expect(page.charset).to eq('utf-8')
113
+ end
114
+ end
115
+
116
+ {
117
+ 'text/html; foo=bar; charset=utf-8' => 'utf-8',
118
+ 'text/html; charset=utf-8; foo=bar' => 'utf-8',
119
+ 'text/html; charset = utf-8 ' => 'utf-8',
120
+ "text/html;\tCHARSET\t=\tUTF-8" => 'UTF-8',
121
+ 'text/html; charset="utf-8"' => 'utf-8',
122
+ "text/html; charset='utf-8'" => 'utf-8',
123
+ 'text/html; foo=bar' => nil,
124
+ 'text/html; othercharset=utf-8' => nil,
125
+ 'text/html; charset' => nil,
126
+ 'text/html; charset=' => nil,
127
+ 'text/html' => nil
128
+ }.each do |content, charset|
129
+ it "gets #{charset.inspect} from the content #{content.inspect}" do
130
+ html = %(<meta http-equiv="Content-Type" content="#{content.gsub('"', '&quot;')}">)
131
+ page = MetaInspector.new('http://example.com', document: html)
132
+
133
+ expect(page.charset).to eq(charset)
134
+ end
135
+ end
136
+
137
+ it 'returns nil when the content-type meta tag has no content attribute' do
138
+ page = MetaInspector.new('http://example.com', document: '<meta http-equiv="content-type">')
139
+
140
+ expect(page.charset).to be_nil
141
+ end
142
+
143
+ it 'prefers a meta charset attribute over a content-type declaration' do
144
+ html = '<meta http-equiv="content-type" content="text/html; charset=windows-1252">' \
145
+ '<meta charset="utf-8">'
146
+ page = MetaInspector.new('http://example.com', document: html)
147
+
148
+ expect(page.charset).to eq('utf-8')
149
+ end
150
+
151
+ it 'uses the first content-type declaration and ignores other http-equiv values' do
152
+ html = '<meta http-equiv="refresh" content="0; charset=windows-1252">' \
153
+ '<meta http-equiv="content-type" content="text/html; charset=utf-8">' \
154
+ '<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">'
155
+ page = MetaInspector.new('http://example.com', document: html)
156
+
157
+ expect(page.charset).to eq('utf-8')
158
+ end
106
159
  end
107
160
  end