metainspector 5.21.2 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1a32c7da227fe7a2fbf3f106e6eb03af652694e293e4ea47928ee3adb71f21e5
4
- data.tar.gz: 6777d770a847f417cfa20a8cf70667e22db82393e2f6d5a839ac7d22406094ff
3
+ metadata.gz: 67105a349e6634209d648df68a7d9b238ab4f341736b2c02561eac0d7a9a1a5d
4
+ data.tar.gz: d780254e81091989b3a29fedd1b34c4484a10d2f31bbe2c93afaa42c05b2fe3e
5
5
  SHA512:
6
- metadata.gz: 239049c807eaf8c178fe386be88b79fac5888934191f372ab3995fefe443026389e0b99d2f92f03e616eb93104acc24e6da15fa616da7172c2f067dc9da41aef
7
- data.tar.gz: 4676aaa3467c872f19db8b584eacf8cd66bfe9351adbe4f2fb882233043ba9aece759d93cb859f2aefaa41dca109becbaab25ca657bf66c6a37be6d7518b8606
6
+ metadata.gz: 3bd38f87c130efc470111853d81232e9ca558a35d57f48cc0059c6461cb221feba092ef4bb402bad1262e79aaedeaefb1153f56e00874a8e66e49d984aeaa50d
7
+ data.tar.gz: 3ff2dbd24f1e5b76539f16dc872110a0788b45ad24483a1f7d7d74b0f2a9931b87cc4889b2356a1ee9aaad2d4d87a4b924184c87c9d7e80fa432c53db625766e
data/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # MetaInspector Changelog
2
2
 
3
+ ## [Changes in 5.22.0](https://github.com/jaimeiniesta/metainspector/compare/v5.21.2...v5.22.0)
4
+
5
+ * `feeds` returns [JSON Feed 1.1](https://www.jsonfeed.org/version/1.1/) links (`application/feed+json`), and matches feed types case-insensitively and ignoring parameters, so `Application/Atom+XML` and `application/rss+xml; charset=utf-8` are found too. `type` keeps the attribute as written. The deprecated `feed` method still returns only RSS and Atom feeds, now also with parameters (#599).
6
+ * Raise `MetaInspector::TimeoutError` instead of `MetaInspector::RequestError` when connecting times out, and retry connection timeouts like read timeouts. **The error class changes**: if you rescue only `MetaInspector::RequestError`, rescue `MetaInspector::TimeoutError` too. Refused connections, DNS failures and other connection errors still raise `RequestError` and are not retried. The `connection_timeout + read_timeout + 1` deadline now applies to each attempt instead of the whole fetch, so `retries` gets all its attempts: before, `retries: 3` stopped after two or three. An attempt that reaches the deadline, such as one to a server that streams forever, is not retried, so it still raises `TimeoutError` after 41 seconds with the defaults. A page whose connection or read times out on every attempt now takes up to 4 × 40 seconds to fail, instead of 41 (#598).
7
+ * Raise `MetaInspector::RequestError` when a response is still compressed with an encoding MetaInspector doesn't decode, such as `br` or `zstd`, instead of parsing the compressed bytes as HTML and returning an empty page. Servers can send these even when asked for `Accept-Encoding: identity`. Adding the `brotli` gem enables `br` (#597).
8
+ * Replace invalid byte sequences in fetched pages with U+FFFD, as browsers do, instead of raising `MetaInspector::RequestError` when the charset comes from the `Content-Type` header. Before, they were only replaced with the `encoding:` option (#596).
9
+ * Resolve charset labels with the [Encoding Standard](https://encoding.spec.whatwg.org/#names-and-labels) table, as browsers do. Labels such as `ks_c_5601-1987`, `x-sjis`, `x-gbk` or `unicode-1-1-utf-8` no longer leave the page empty or garbled. `us-ascii` and `ascii` decode as Windows-1252 instead of raising `MetaInspector::RequestError`, and `iso-8859-9` and `iso-8859-11` as Windows-1254 and Windows-874. A UTF-16 label in a meta tag is read as UTF-8. A meta label that neither the table nor Ruby knows is ignored instead of cutting the document at the meta tag (#595).
10
+ * Return links inside inline `<svg>` and `<math>` again in `links`, as in 5.21.0. With the HTML5 parser those `<a>` elements are in another namespace, and the `//a/@href` lookup skipped them (#593).
11
+ * Return a page again for PDFs, binary files and deeply nested feeds with `allow_non_html_content: true`, instead of raising `MetaInspector::ParserError`. When the response is not `text/html`, parser resource limits no longer raise; if the HTML5 parser gives up, `parsed` falls back to the depth-capped HTML4 tree, as in 5.21.0. HTML responses and `max_html_bytes` are still enforced (#592).
12
+ * Fix `to_hash` raising `NoMethodError` on compressed responses. Header values that are not Strings, such as the Integer `Content-Length` set by faraday-gzip after decompressing, are kept as they are, and header names are downcased so `content-length` can be looked up as before (#591).
13
+ * Decode fetched UTF-16 and UTF-32 pages with a byte-order mark before removing NUL characters, even when the HTTP header has no charset. Preserve the raw response body and prefer the mark over conflicting meta declarations (#601).
14
+ * Preserve titles, head links and page content after tracking snippets in `<noscript>`, including unclosed or self-closing iframes. Parse each fallback separately so its links, images, stylesheets and iframes remain available (#602).
15
+ * Use the first meta charset declaration for binary HTML bodies, so a later conflicting declaration no longer garbles text or truncates the page. Preserve HTTP and string encodings, and prefer a byte-order mark over meta declarations (#575).
16
+ * Parse the DOM with HTML5 rules so paragraphs inside `h1`–`h6` retain their text, including the `best_title` heading fallback (#566). `parsed` now returns `Nokogiri::HTML5::Document`; malformed markup can produce a different tree, and literal CR/CRLF line endings in text and attributes normalize to LF. Preserve HTML4 encoding detection and text-size limits before HTML5 parsing, and wrap HTML5 depth-limit failures in `MetaInspector::ParserError`. Retain HTML4 parsing for legacy charsets that Ruby cannot transcode to UTF-8.
17
+ * Parse responses declared as UTF-16, UTF-32 or ISO-2022-JP by converting non-ASCII-compatible bodies to UTF-8 before removing NUL characters. Preserve the raw response body during conversion, replace invalid bytes with U+FFFD (#596) and wrap unsupported encoding conversions, such as UTF-7, in `MetaInspector::RequestError` (#568).
18
+ * Raise `MetaInspector::ParserError` during initialization when Nokogiri truncates HTML at its nesting or content resource limits, instead of silently returning incomplete links, headings and other metadata. Other recoverable HTML and encoding errors remain tolerated (#565). The nesting limit is the HTML5 parser's (400 levels), so pages that libxml2 truncated at 256 levels in 5.21.0 are now parsed in full. These include pages that only nest that deep in libxml2's HTML4 tree, such as unclosed `<div>`s inside `<section>`s; legacy charsets that Ruby cannot transcode keep the 256 limit. The 10 MB limit on text, attribute values and comments still applies past libxml2's nesting limit (#612).
19
+ * Convert response header values in `to_hash` to UTF-8, replacing invalid bytes, so non-ASCII headers no longer prevent JSON serialization. The original `response.headers` values are preserved (#563).
20
+ * Replace invalid byte sequences before parsing HTML passed with `document:`, so extracted text and `to_hash` no longer raise encoding errors. The original string returned by `to_s` is preserved (#569).
21
+ * Wrap malformed gzip/deflate responses and invalid `mailto:` page URLs or redirect destinations in `MetaInspector::RequestError`. Invalid `mailto:` image URLs return unknown dimensions instead of raising (#567).
22
+ * Return only the first `<title>` in the head for `title` and `to_hash['title']`, instead of concatenating all titles (#564).
23
+ * Fix `charset` returning `nil` for lowercase or mixed-case `http-equiv="content-type"` declarations. Read the `charset` parameter by name regardless of parameter order, spacing or case, and remove surrounding quotes (#562).
24
+ * Fix swapped `connection_timeout` and `read_timeout` options for GET and HEAD requests (#561). The connection timeout now limits opening the connection, and the read timeout limits waiting for the response.
25
+ * Fix garbled titles, descriptions and other text on compressed pages whose charset is declared only in the `Content-Type` header, including when custom headers enable compression (#572). Apply the charset after decompressing the response body.
26
+ * `untracked_url` and `untrack!` remove only the `utm_*` tracking parameters and keep the rest of the query string as written, instead of sorting keys, dropping repeated keys and re-encoding values (#557). **The returned URL changes** for any query with more than one parameter, or with `+` in a value: `?b=2&a=1` used to come back as `?a=1&b=2` and `?q=a+b` as `?q=a%20b`. If you store `untracked_url` values to spot duplicate pages, new results may not match the ones you saved before, so normalize both sides yourself or re-generate the stored values.
27
+ * Request page and image URLs with the query string as given, instead of sorting keys, keeping only the last value of a repeated key (`?tag=x&tag=y` was requested as `?tag=y`) and re-escaping values. URLs with non-UTF-8 escapes such as `?q=caf%E9` no longer raise `ArgumentError` (#594). **`url` changes too**: it reports the query that was requested, so, as with `untracked_url` above, stored values for queries with more than one parameter may not match new ones. With `normalize_url: true`, the default, normalization now escapes only what can't be sent (spaces, non-ASCII characters, `|`, `{`, `}`, a `%` that doesn't start an escape) and keeps reserved characters such as `;` and `[]` and existing escapes such as `%2F` or `%3D` as written, instead of escaping or decoding them (#613). **`links` and `head_links` change too** for queries with those characters, so stored link URLs may not match new ones either. Pass `normalize_url: false` to send the page URL unchanged.
28
+ * Fix `to_hash`, `content_type` and `response` raising `NoMethodError` when the HTML is passed with the `document` option. No request is made in that case, so `content_type` and `response` return `nil`, and `to_hash` includes `'content_type' => nil` and `'response' => nil` (#559).
29
+ * Fix `links`, `images`, `iframe_sources`, `head_links` and `feeds` taking quadratic time on pages with thousands of links, images, iframes or `<link>` elements. The whole document was searched for a `<base>` element once per element found; now it's searched once per page. Getting the links of a 700 KB page with 32,000 of them goes from 21 seconds to about 1, and results don't change (#573).
30
+
3
31
  ## [Changes in 5.21.2](https://github.com/jaimeiniesta/metainspector/compare/v5.21.1...v5.21.2)
4
32
 
5
33
  * Security: apply `max_html_bytes` while downloading page and redirect responses and during gzip/deflate decompression, before charset conversion and parsing. Oversized responses raise `MetaInspector::ParserError`; cached responses are checked as well. The 5.x default remains `nil` (unlimited); set a finite limit for untrusted URLs. Other content encodings are rejected with a finite limit ([GHSA-36j3-rh89-4gm2](https://github.com/jaimeiniesta/metainspector/security/advisories/GHSA-36j3-rh89-4gm2)).
data/README.md CHANGED
@@ -27,6 +27,40 @@ MetaInspector has been downloaded more than 4 million times via RubyGems.org and
27
27
 
28
28
  If you're using MetaInspector, please consider giving back to help ensure its continued development. You can support the project by becoming a sponsor on [GitHub Sponsors](https://github.com/sponsors/jaimeiniesta): pick the tier that suits you, either as an individual or on behalf of your company.
29
29
 
30
+ ### Gold Sponsors
31
+
32
+ <div style="display: flex; gap: 10px;">
33
+
34
+ <a href="https://github.com/sponsors/jaimeiniesta/sponsorships?sponsor=jaimeiniesta&tier_id=507665">
35
+ <img height="175" src="assets/sponsor_logo_placeholder.gif" alt="Become a Gold Sponsor">
36
+ </a>
37
+
38
+ </div>
39
+
40
+ ### Silver Sponsors
41
+
42
+ <div style="display: flex; gap: 10px;">
43
+
44
+ <a href="https://rocketvalidator.com">
45
+ <img height="150" src="assets/sponsor_logo_rocket_validator.png" alt="Rocket Validator - accessibility and HTML site-wide validator">
46
+ </a>
47
+
48
+ <a href="https://github.com/sponsors/jaimeiniesta/sponsorships?sponsor=jaimeiniesta&tier_id=63404">
49
+ <img height="150" src="assets/sponsor_logo_placeholder.gif" alt="Become a Silver Sponsor">
50
+ </a>
51
+
52
+ </div>
53
+
54
+ ### Bronze Sponsors
55
+
56
+ <div style="display: flex; gap: 10px;">
57
+
58
+ <a href="https://github.com/sponsors/jaimeiniesta/sponsorships?sponsor=jaimeiniesta&tier_id=63403">
59
+ <img height="125" src="assets/sponsor_logo_placeholder.gif" alt="Become a Bronze Sponsor">
60
+ </a>
61
+
62
+ </div>
63
+
30
64
  ## Usage
31
65
 
32
66
  Initialize a MetaInspector instance for an URL, like this:
@@ -48,6 +82,32 @@ page = MetaInspector.new("https://github.com",
48
82
  :document => "<html>...</html>")
49
83
  ```
50
84
 
85
+ ## Options reference
86
+
87
+ Pass these options as the second argument to `MetaInspector.new(url, options)`.
88
+
89
+ | Option | Default | Description |
90
+ | --- | --- | --- |
91
+ | `connection_timeout` | `20` | Maximum seconds to wait for a connection. |
92
+ | `read_timeout` | `20` | Maximum seconds to wait for a read once connected. |
93
+ | `retries` | `3` | Maximum additional attempts after a timeout. See [Timeout & Retries](#timeout--retries). |
94
+ | `allow_redirections` | `true` | Follow redirects, up to 10 by default; customize with `faraday_options[:redirect]`. |
95
+ | `head_first` | `false` | Check content type with HEAD before downloading with GET. |
96
+ | `document` | `nil` | HTML string to parse instead of fetching the page. |
97
+ | `headers` | User-Agent and Accept-Encoding | Request headers; a custom hash replaces the [default headers](#headers). |
98
+ | `encoding` | `nil` | Force the fetched body's encoding instead of relying on automatic detection. |
99
+ | `normalize_url` | `true` | Normalize URLs using Addressable. |
100
+ | `allow_non_html_content` | `false` | Allow non-HTML responses to be passed to the HTML parser. |
101
+ | `download_images` | `true` | Allow image downloads for dimensions, metadata and validation. |
102
+ | `max_image_downloads` | `nil` (unlimited) | Limit image lookup attempts; `0` disables image downloads. |
103
+ | `download_image_options` | `nil` | Set `reject_invalid_images: true` in a hash to discard images that fail validation. |
104
+ | `fetch_all_image_meta` | `nil` (disabled) | Enable validity lookups through `images.with_metadata`. |
105
+ | `inline_image_data` | `nil` (disabled) | Return full data URLs and allow inline images in `best` and `largest`. |
106
+ | `max_html_bytes` | `nil` (unlimited) | Byte limit for each response body, decompression stage and processed HTML; exceeding it raises `ParserError`. See [Timeout & Retries](#timeout--retries). |
107
+ | `url_filter` | `nil` | Callable receiving a URI before each request; `false` or `nil` rejects the destination. |
108
+ | `faraday_options` | `nil` | Faraday configuration, including `redirect` and `faraday_http_cache` settings. |
109
+ | `faraday_http_cache` (deprecated) | `nil` | Legacy cache configuration; use `faraday_options[:faraday_http_cache]` instead. |
110
+
51
111
  ## Accessing response
52
112
 
53
113
  You can check the status and headers from the response like this:
@@ -58,6 +118,10 @@ page.response.headers # { "server"=>"nginx", "content-type"=>"text/html; charset
58
118
  # "cache-control"=>"must-revalidate, private, max-age=0", ... }
59
119
  ```
60
120
 
121
+ When the HTML is passed with the `document` option, no request is made, so
122
+ `page.response` and `page.content_type` return `nil`, and so do the `response`
123
+ and `content_type` keys of `to_hash`.
124
+
61
125
  ## Accessing scraped data
62
126
 
63
127
  ### URL
@@ -78,9 +142,15 @@ page.root_url # Root url (scheme + host, like https://github.com/)
78
142
  page.head_links # an array of hashes of all head/links
79
143
  page.stylesheets # an array of hashes of all head/links where rel='stylesheet'
80
144
  page.canonicals # an array of hashes of all head/links where rel='canonical'
81
- page.feeds # Get rss or atom links in meta data fields as array of hash in the form { href: "...", title: "...", type: "..." }
145
+ page.feeds # RSS, Atom or JSON feed links as an array of hashes: { href: "...", title: "...", type: "..." }
82
146
  ```
83
147
 
148
+ `feeds` returns `<link rel="alternate">` elements whose `type` is
149
+ `application/rss+xml`, `application/atom+xml`, `application/feed+json` (JSON Feed
150
+ 1.1) or `application/json` (JSON Feed 1.0). The type is matched case-insensitively
151
+ and ignoring parameters such as `; charset=utf-8`; `type` in the result is the
152
+ attribute as written.
153
+
84
154
  `page.feed` is a deprecated compatibility method that returns the first RSS or
85
155
  Atom feed's absolute URL, or `nil` if none is found. It skips JSON feeds. Each
86
156
  call emits a deprecation warning. Use `page.feeds` instead; `page.feed` is
@@ -135,6 +205,9 @@ page.links.external # every external link found on the page as an absolute
135
205
  page.images # enumerable collection of image URLs found on the page
136
206
  page.images.with_size # a sorted array (by descending area) of [image_url, width, height]
137
207
  page.images.with_details # image hashes with dimensions, type and file size (downloads images)
208
+ page.images.with_metadata # image hashes with URL and validity (enable lookups with fetch_all_image_meta: true)
209
+ page.images.largest # largest image, excluding aspect ratios of 10:1 or wider and 1:10 or taller
210
+ page.images.owner_suggested # first image from og:image, twitter:image, or parsely-image-url
138
211
  page.images.best # Most relevant image from og:image, twitter:image, or parsely-image-url; falls back to page.images.largest
139
212
  page.images.favicon # absolute URL to the favicon
140
213
  ```
@@ -289,7 +362,7 @@ Please be aware that all keys are converted to downcase, so it's `'dc.date.issue
289
362
 
290
363
  ```ruby
291
364
  page.charset # UTF-8
292
- page.content_type # content-type returned by the server when the url was requested
365
+ page.content_type # content-type returned by the server when the url was requested, or nil with the document option
293
366
  ```
294
367
 
295
368
  ## Other representations
@@ -310,25 +383,52 @@ page.to_s # A String with the contents of the HTML document
310
383
  And the full scraped document is accessible from:
311
384
 
312
385
  ```ruby
313
- page.parsed # Nokogiri doc that you can use it to get any element from the page
386
+ page.parsed # Nokogiri::HTML5::Document that you can use to get any element from the page
314
387
  ```
315
388
 
389
+ The DOM follows HTML5 parsing rules, including keeping paragraphs inside headings
390
+ produced by CMS editors. Malformed markup may produce a different tree than the
391
+ previous HTML4 parser. HTML5 also normalizes literal CR and CRLF line endings to
392
+ LF, including in attribute values; `to_s` still returns the original document.
393
+ For legacy charsets that Ruby cannot convert to UTF-8 (such as UTF-7),
394
+ MetaInspector retains the HTML4 document and its parsing behavior.
395
+
316
396
  ## Options
317
397
 
318
398
  ### Forced encoding
319
399
 
320
- If you get a `MetaInspector::RequestError, "invalid byte sequence in UTF-8"` or similar error, you can try forcing the encoding like this:
400
+ Invalid byte sequences in the page's encoding are replaced with U+FFFD before
401
+ parsing, as browsers do, so one bad byte doesn't stop the rest of the page from
402
+ being read. If a page declares the wrong charset, you can force the right one:
321
403
 
322
404
  ```ruby
323
- page = MetaInspector.new(url, :encoding => 'UTF-8')
405
+ page = MetaInspector.new(url, :encoding => 'Windows-1252')
324
406
  ```
325
407
 
408
+ For HTML passed with `document:`, the original string is still available through `page.to_s`.
409
+
410
+ Legacy HTML charsets use browser-compatible supersets: GB2312 uses GBK,
411
+ Shift_JIS uses Windows-31J, EUC-KR uses CP949, Big5 uses Big5-HKSCS, and
412
+ ISO-8859-1 uses Windows-1252. This applies to HTTP charset declarations, HTML
413
+ meta declarations and the encoding of supplied strings, preserving characters
414
+ outside the strict legacy charset and the rest of the document. Declared meta
415
+ charsets and raw response bytes are preserved. Strings tagged with one of these
416
+ legacy encodings are converted to UTF-8 before cleanup; `page.to_s` returns the
417
+ converted text for downloaded pages.
418
+
419
+ Fetched bodies with non-ASCII-compatible encodings, such as UTF-16, UTF-32 and
420
+ ISO-2022-JP, are converted to UTF-8 before NUL characters are removed and the HTML
421
+ is parsed. `page.to_s` returns that UTF-8 text; the conversion preserves the raw
422
+ `page.response.body`. Invalid bytes are replaced with U+FFFD; conversions Ruby
423
+ doesn't support, such as UTF-7, raise `MetaInspector::RequestError` with the
424
+ original encoding error as the cause.
425
+
326
426
  ### Timeout & Retries
327
427
 
328
428
  You can specify 2 different timeouts when requesting a page:
329
429
 
330
430
  * `connection_timeout` sets the maximum number of seconds to wait to get a connection to the page.
331
- * `read_timeout` sets the maximum number of seconds to wait to read the page, once connected.
431
+ * `read_timeout` sets the maximum number of seconds to wait for a read, once connected.
332
432
 
333
433
  Both timeouts default to 20 seconds each.
334
434
 
@@ -356,23 +456,43 @@ parsing deadline: even a small document can be
356
456
  slow to parse. Ruby's `Timeout.timeout` cannot reliably interrupt Nokogiri's
357
457
  native parser; use a separately supervised process if a hard deadline is needed.
358
458
 
359
- You can also specify the number of `retries`, which defaults to 3.
459
+ Nokogiri also enforces limits on nesting depth and the size of individual text
460
+ nodes, attribute values and comments. If one of these limits truncates the HTML,
461
+ MetaInspector raises `MetaInspector::ParserError` during initialization, with the
462
+ parser's diagnostic in the message. These limits apply even when `max_html_bytes`
463
+ is `nil`. MetaInspector retains an HTML4 pass for the size limits and encoding
464
+ detection before building the HTML5 DOM. The nesting limit is HTML5's, 400
465
+ levels; for legacy charsets that Ruby cannot transcode, where the HTML4 tree is
466
+ the DOM, it is HTML4's, 256 levels. Ordinary HTML errors and recoverable
467
+ encoding errors are still tolerated.
468
+
469
+ You can also specify the maximum number of additional attempts with `retries`,
470
+ which defaults to 3. Connection timeouts and read timeouts are retried. Other
471
+ connection failures, such as a refused connection or a DNS failure, are not.
472
+
473
+ Each attempt also has a deadline of `connection_timeout + read_timeout + 1`
474
+ seconds, which covers its redirects. It stops servers that keep sending data
475
+ slowly enough that the read timeout never fires. With the defaults, this is 41
476
+ seconds. An attempt that reaches the deadline is not retried, so such a server
477
+ holds the fetch for 41 seconds, not 41 for each retry. With `head_first: true`,
478
+ the HEAD and GET requests each get their own attempts.
360
479
 
361
- For example, this will time out after 10 seconds waiting for a connection, or after 5 seconds waiting
362
- to read its contents, and will retry 4 times:
480
+ For example, this allows up to 10 seconds to connect and 5 seconds per read, with
481
+ up to 4 additional attempts after a timeout, each within a 16-second deadline:
363
482
 
364
483
  ```ruby
365
- page = MetaInspector.new('www.google', :connection_timeout => 10, :read_timeout => 5, :retries => 4)
484
+ page = MetaInspector.new('https://example.com', connection_timeout: 10, read_timeout: 5, retries: 4)
366
485
  ```
367
486
 
368
- If MetaInspector fails to fetch the page after it has exhausted its retries,
369
- it will raise `MetaInspector::TimeoutError`, which you can rescue in your
370
- application code.
487
+ If the last attempt times out, or any attempt reaches the deadline, MetaInspector
488
+ raises `MetaInspector::TimeoutError`; other connection failures raise
489
+ `MetaInspector::RequestError`. Rescue both if your application handles them the
490
+ same way:
371
491
 
372
492
  ```ruby
373
493
  begin
374
494
  page = MetaInspector.new(url)
375
- rescue MetaInspector::TimeoutError
495
+ rescue MetaInspector::TimeoutError, MetaInspector::RequestError
376
496
  enqueue_for_future_fetch_attempt(url)
377
497
  render_simple(url)
378
498
  else
@@ -415,8 +535,8 @@ page = MetaInspector.new(url, faraday_options: { redirect: { callback: callback
415
535
  ```
416
536
 
417
537
 
418
- The `faraday_options[:redirect]` hash is passed to the `FollowRedirects` middleware used by `Faraday`, so that we can use all available options.
419
- Check them [here](https://github.com/lostisland/faraday_middleware/blob/main/lib/faraday_middleware/response/follow_redirects.rb#L44).
538
+ The `faraday_options[:redirect]` hash is passed to the `faraday-follow_redirects`
539
+ middleware. See its [available options](https://github.com/tisba/faraday-follow-redirects#usage).
420
540
  The origin header policy also applies after your redirect callback runs and when
421
541
  `clear_authorization_header: false` is set.
422
542
 
@@ -488,7 +608,13 @@ By default, the following headers are set:
488
608
  }
489
609
  ```
490
610
 
491
- The `Accept-Encoding` is set to `identity` to avoid exceptions being raised on servers that return malformed compressed responses, [as explained here](https://github.com/lostisland/faraday/issues/337).
611
+ `Accept-Encoding: identity` requests uncompressed responses to reduce problems with
612
+ malformed compressed data. Servers may still send compressed responses. gzip and
613
+ deflate are decoded, and malformed gzip or deflate data raises
614
+ `MetaInspector::RequestError`. Other encodings, such as `br` or `zstd`, also raise
615
+ `MetaInspector::RequestError` instead of being parsed as HTML. To decode `br`, add
616
+ the [`brotli`](https://rubygems.org/gems/brotli) gem to your Gemfile; this doesn't
617
+ apply with `max_html_bytes`, which only decodes gzip and deflate.
492
618
 
493
619
  If you want to override the default headers then use the `headers` option:
494
620
 
@@ -497,6 +623,10 @@ If you want to override the default headers then use the `headers` option:
497
623
  page = MetaInspector.new('example.com', :headers => {'User-Agent' => 'My custom User-Agent'})
498
624
  ```
499
625
 
626
+ The `headers` option replaces all default headers. To keep requesting uncompressed
627
+ responses with a custom User-Agent, also pass `'Accept-Encoding' => 'identity'`.
628
+ Otherwise, the compression middleware requests compressed responses automatically.
629
+
500
630
  ### Disabling SSL verification (or any other Faraday options)
501
631
 
502
632
  Faraday can be passed options via `:faraday_options`.
@@ -514,20 +644,24 @@ MetaInspector.new('https://example.com', faraday_options: { ssl: { verify: false
514
644
 
515
645
  ### Allow non-HTML content type
516
646
 
517
- MetaInspector will by default raise an exception when trying to parse a non-HTML URL (one that has a content-type different than text/html). You can disable this behaviour with:
647
+ MetaInspector fetches and parses the document during initialization. By default,
648
+ `MetaInspector.new` raises `MetaInspector::NonHtmlError` if the response declares a
649
+ content type other than `text/html`. You can disable this behaviour with:
518
650
 
519
651
  ```ruby
520
652
  page = MetaInspector.new('github.com', :allow_non_html_content => true)
521
653
  ```
522
654
 
523
655
  ```ruby
524
- page = MetaInspector.new('http://example.com/image.png')
525
- page.content_type # "image/png"
526
- page.description # will raise an exception
656
+ begin
657
+ page = MetaInspector.new('http://example.com/image.png')
658
+ rescue MetaInspector::NonHtmlError => error
659
+ warn error.message # The url provided contains image/png content instead of text/html content
660
+ end
527
661
 
528
662
  page = MetaInspector.new('http://example.com/image.png', :allow_non_html_content => true)
529
663
  page.content_type # "image/png"
530
- page.description # will return a garbled string
664
+ page.description # usually nil; non-HTML data is still passed to the HTML parser
531
665
  ```
532
666
 
533
667
  ### Check content type before downloading
@@ -557,15 +691,31 @@ redirect settings. Passing a `document` directly makes no HTTP requests.
557
691
  By default, URLs are normalized using the Addressable gem. For example:
558
692
 
559
693
  ```ruby
560
- # Normalization will add a default scheme and a trailing slash...
561
- page = MetaInspector.new('github.com')
562
- page.url # https://github.com/
694
+ # Normalization adds the default http scheme and a trailing slash.
695
+ # Supplying HTML avoids a request, so redirects cannot change the URL.
696
+ page = MetaInspector.new('example.com', document: '<html></html>')
697
+ page.url # http://example.com/
563
698
 
564
699
  # ...and it will also convert international characters
565
700
  page = MetaInspector.new('http://www.詹姆斯.com')
566
701
  page.url # http://www.xn--8ws00zhy3a.com/
567
702
  ```
568
703
 
704
+ When a page is fetched with redirects enabled, `page.url` is updated to the final
705
+ URL. For example, an HTTPS URL after requesting `github.com` reflects GitHub's
706
+ redirect from HTTP, rather than a default HTTPS scheme.
707
+
708
+ Normalization leaves the query string as written, except for characters that
709
+ can't be sent in a URL, such as spaces, non-ASCII characters, `|`, `{`, `}` or a
710
+ `%` that doesn't start an escape. Reserved characters such as `;` and `[]`, and
711
+ existing escapes such as `%2F`, are kept, because changing them can change the
712
+ page the server returns. The same applies to the URLs in `links` and `head_links`:
713
+
714
+ ```ruby
715
+ page = MetaInspector.new('http://example.com/?a[]=1;b=café')
716
+ page.url # http://example.com/?a[]=1;b=caf%C3%A9
717
+ ```
718
+
569
719
  While this is generally useful, it can be [tricky](https://github.com/sporkmonger/addressable/issues/182) [sometimes](https://github.com/sporkmonger/addressable/issues/160).
570
720
 
571
721
  You can disable URL normalization by passing the `normalize_url: false` option.
@@ -674,7 +824,7 @@ Unsupported image URL schemes get `nil` metadata instead of raising; redirects t
674
824
 
675
825
  ### Caching responses
676
826
 
677
- MetaInspector can be configured to use [Faraday::HttpCache](https://github.com/plataformatec/faraday-http-cache) to cache page responses. For that you should pass the `faraday_http_cache` option inside `faraday_options`, with at least the `:store` key, for example:
827
+ MetaInspector can be configured to use [Faraday::HttpCache](https://github.com/sourcelevel/faraday-http-cache) to cache page responses. For that you should pass the `faraday_http_cache` option inside `faraday_options`, with at least the `:store` key, for example:
678
828
 
679
829
  ```ruby
680
830
  cache = ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache')
@@ -687,11 +837,19 @@ The top-level `faraday_http_cache` option still works, but it is deprecated and
687
837
 
688
838
  Web page scraping is tricky, you can expect to find different exceptions during the request of the page or the parsing of its contents. MetaInspector will encapsulate these exceptions on these main errors:
689
839
 
690
- * `MetaInspector::TimeoutError`. When fetching a web page has taken too long.
691
- * `MetaInspector::RequestError`. When there has been an error on the request phase. Examples: page not found, SSL failure, invalid URI.
840
+ * `MetaInspector::TimeoutError`. When connecting or reading times out and no retries are left, or an attempt reaches its deadline. See [Timeout & Retries](#timeout--retries).
841
+ * `MetaInspector::RequestError`. When there has been an error on the request phase. Examples: DNS failure, refused connection, SSL failure, invalid URI, malformed compressed response.
692
842
  * `MetaInspector::ParserError`. When there has been an error parsing the contents of the page.
693
843
  * `MetaInspector::NonHtmlError`. When the contents of the page was not HTML. See also the `allow_non_html_content` option
694
844
 
845
+ HTTP error statuses such as 403, 404 and 500 do not raise `MetaInspector::RequestError`. Their response bodies are processed like any other page, and you can check the status through `page.response.status`:
846
+
847
+ ```ruby
848
+ page = MetaInspector.new(url) # a URL that returns an HTML error page
849
+ page.response.status # => 404
850
+ page.title # => the title of the error page
851
+ ```
852
+
695
853
  ## Examples
696
854
 
697
855
  Runnable sample scripts live in `examples/`. From the repository root, pass the URL as an argument:
@@ -712,15 +870,19 @@ You can also run them from inside `examples/`, for example `bundle exec ruby bas
712
870
  * `iframes.rb`: lists iframe attributes and resolved source URLs without downloading embedded documents.
713
871
  * `html_size_limit.rb <url> [max_bytes]`: skips HTML over the byte limit (default: 2 MiB). The limit applies after download and does not bound parse time.
714
872
 
715
- What follows is an example of use from irb:
873
+ What follows is an example of use from irb. The `; nil` suppresses the document's
874
+ lengthy inspection output:
716
875
 
717
876
  ```ruby
718
877
  $ irb
719
878
  >> require 'metainspector'
720
879
  => true
721
880
 
722
- >> page = MetaInspector.new('http://github.com')
723
- => #<MetaInspector:0x11330c0 @url="http://github.com">
881
+ >> page = MetaInspector.new('http://github.com'); nil
882
+ => nil
883
+
884
+ >> page.class
885
+ => MetaInspector::Document
724
886
 
725
887
  >> page.title
726
888
  => "GitHub"
@@ -0,0 +1,40 @@
1
+ require 'timeout'
2
+ require 'net/http'
3
+ require 'faraday'
4
+
5
+ module MetaInspector
6
+ # Runs inside the retry middleware, so it applies to each attempt of a page
7
+ # request, redirects included, and every retry gets the full time.
8
+ class AttemptTimeout < Faraday::Middleware
9
+ # Not a Faraday::TimeoutError or Timeout::Error, so the retry middleware
10
+ # doesn't retry it. Request raises it as MetaInspector::TimeoutError.
11
+ class Expired < Faraday::Error; end
12
+
13
+ def initialize(app, seconds)
14
+ super(app)
15
+ @seconds = seconds
16
+ end
17
+
18
+ # Faraday's timeouts don't fire while a server keeps streaming, so each
19
+ # attempt also has its own deadline. An attempt that reaches it isn't
20
+ # retried: a server that keeps one busy that long would keep the next ones
21
+ # busy too.
22
+ #
23
+ # https://github.com/jaimeiniesta/metainspector/issues/188
24
+ # https://github.com/lostisland/faraday/issues/602
25
+ #
26
+ # The Net::HTTP adapter raises Faraday::ConnectionFailed for a connection
27
+ # timeout, as for a refused connection. Raising Faraday::TimeoutError instead
28
+ # lets the retry middleware retry it, and it reaches the caller as
29
+ # MetaInspector::TimeoutError (#598).
30
+ def call(env)
31
+ Timeout.timeout(@seconds) { @app.call(env) }
32
+ rescue Timeout::Error => error
33
+ raise Expired, error
34
+ rescue Faraday::ConnectionFailed => error
35
+ raise unless error.wrapped_exception.is_a?(Net::OpenTimeout)
36
+
37
+ raise Faraday::TimeoutError, error.wrapped_exception
38
+ end
39
+ end
40
+ end
@@ -74,7 +74,15 @@ module MetaInspector
74
74
  delegate [:url, :scheme, :host, :root_url,
75
75
  :tracked?, :untracked_url, :untrack!] => :@url
76
76
 
77
- delegate [:content_type, :response] => :@request
77
+ # No request is made when the HTML is passed with the document: option,
78
+ # so these return nil in that case
79
+ def content_type
80
+ @request&.content_type
81
+ end
82
+
83
+ def response
84
+ @request&.response
85
+ end
78
86
 
79
87
  delegate [:parsed, :language, :title, :best_title, :author, :best_author,
80
88
  :h1, :h2, :h3, :h4, :h5, :h6, :description, :best_description, :links,
@@ -110,8 +118,8 @@ module MetaInspector
110
118
  'content_type' => content_type,
111
119
  'meta_tags' => meta_tags,
112
120
  'favicon' => images.favicon,
113
- 'response' => { 'status' => response.status,
114
- 'headers' => response.headers }
121
+ 'response' => response && { 'status' => response.status,
122
+ 'headers' => serialized_response_headers }
115
123
  }
116
124
  end
117
125
 
@@ -122,6 +130,21 @@ module MetaInspector
122
130
 
123
131
  private
124
132
 
133
+ # Middleware can add headers that Net::HTTP would have normalized: faraday-gzip
134
+ # sets "Content-Length" to an Integer after decompressing. Downcase the names
135
+ # and re-encode only String values.
136
+ def serialized_response_headers
137
+ response.headers.to_h do |name, value|
138
+ [name.to_s.downcase, value.is_a?(String) ? utf8_header_value(value) : value]
139
+ end
140
+ end
141
+
142
+ # Net::HTTP returns binary strings, even when the bytes are valid UTF-8.
143
+ def utf8_header_value(value)
144
+ source_encoding = value.encoding == Encoding::BINARY ? Encoding::UTF_8 : value.encoding
145
+ value.encode(Encoding::UTF_8, source_encoding, invalid: :replace, undef: :replace)
146
+ end
147
+
125
148
  def defaults
126
149
  { :connection_timeout => 20,
127
150
  :read_timeout => 20,