metainspector 5.22.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +9 -0
- data/README.md +26 -21
- data/lib/meta_inspector/document.rb +76 -66
- data/lib/meta_inspector/errors.rb +5 -1
- data/lib/meta_inspector/html_encoding.rb +7 -1
- data/lib/meta_inspector/http_session.rb +51 -44
- data/lib/meta_inspector/image_downloader.rb +37 -26
- data/lib/meta_inspector/parser.rb +49 -50
- data/lib/meta_inspector/parsers/base.rb +7 -2
- data/lib/meta_inspector/parsers/head_links.rb +12 -27
- data/lib/meta_inspector/parsers/iframes.rb +2 -3
- data/lib/meta_inspector/parsers/images.rb +119 -70
- data/lib/meta_inspector/parsers/links.rb +10 -6
- data/lib/meta_inspector/parsers/meta_tags.rb +16 -29
- data/lib/meta_inspector/parsers/texts.rb +43 -33
- data/lib/meta_inspector/request.rb +42 -45
- data/lib/meta_inspector/url.rb +13 -16
- data/lib/meta_inspector/url_policy.rb +17 -10
- data/lib/meta_inspector/version.rb +1 -1
- data/lib/meta_inspector.rb +14 -13
- data/lib/metainspector.rb +1 -1
- data/spec/document_spec.rb +48 -68
- data/spec/meta_inspector/images_spec.rb +82 -1
- data/spec/meta_inspector/meta_inspector_spec.rb +3 -25
- data/spec/meta_inspector/texts_spec.rb +67 -12
- data/spec/parser_spec.rb +0 -10
- data/spec/request_errors_spec.rb +1 -1
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 4b5d10a14ffef08c3fc9fd659e8b4ecdd5a5afab3b67f53cc553ce81f8ac3a2f
|
|
4
|
+
data.tar.gz: bb33246ce30dd3196176f56f4b94153d58dfd2e2c3459c70476579c8c9ef0db0
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: a6bc3242ca7ff77fa43b2038ea30a9e389bba55064bd948fbc31e640aa975aa6dc36b27297e9e5959d908a525c41159d629f3205c150ea4d5e19768818f63351
|
|
7
|
+
data.tar.gz: 1bb96d78211f2ed6e2b464c6e9eccf513a6bd42a4ba3be569a3954b1e1a879d067f0411b28cdd634b4bb3414254d8e3b5840f48e7ff02ee79ebbf4fa772d204e
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# MetaInspector Changelog
|
|
2
2
|
|
|
3
|
+
## [Changes in 6.0.0](https://github.com/jaimeiniesta/metainspector/compare/v5.22.0...v6.0.0)
|
|
4
|
+
|
|
5
|
+
* **Breaking:** `max_image_downloads` defaults to `20` instead of `nil` (unlimited), so a page with many images no longer decides how many requests `images.with_size`, `images.largest` and `images.best` make. Images past the limit that lack HTML dimensions get `[0, 0]` and can't win `largest`. Pass `max_image_downloads: nil` to keep downloading every image (#600).
|
|
6
|
+
* **Breaking:** raise `ArgumentError` for unknown options, naming them, instead of ignoring them. A misspelled option, or one with a String key as read from JSON or YAML, did nothing: `MetaInspector.new(url, 'document' => html)` fetched the page instead of parsing `html`. Option keys must be Symbols (#604).
|
|
7
|
+
* **Breaking:** `title` returns `nil` instead of `""` when the head has no `<title>` or it is blank, like `description`, `author` and the other readers, so `page.title || fallback` reaches the fallback. `title`, `description` and `best_description` trim surrounding whitespace, and `description` returns `nil` for a blank meta description; whitespace inside the text is kept as written. `to_hash['title']` and `to_hash['description']` change the same way (#604).
|
|
8
|
+
* **Breaking:** remove `page.feed` and `page.favicon`, which warn as deprecated since 5.21.0. Use `page.feeds` and `page.images.favicon` (#604).
|
|
9
|
+
* **Breaking:** remove the top-level `faraday_http_cache` option, deprecated in 5.20.0. Pass it inside `faraday_options`: `faraday_options: { faraday_http_cache: { store: cache } }`. The top-level option now raises `ArgumentError` (#604).
|
|
10
|
+
* **Breaking:** `images.with_size`, `images.largest` and `images.best` download one candidate per `<img>` or `<picture>` instead of every `srcset` candidate, which roughly tripled image downloads since 5.21.0. Each image is ranked by its largest candidate: the largest width descriptor if any, otherwise the highest density, with `src` as `1x`. A `src` with `width` and `height` in the HTML is still ranked without a download. **`with_size` changes**: it no longer lists the smaller candidates of each image. `to_a` and `with_details` still list every candidate (#600).
|
|
11
|
+
|
|
3
12
|
## [Changes in 5.22.0](https://github.com/jaimeiniesta/metainspector/compare/v5.21.2...v5.22.0)
|
|
4
13
|
|
|
5
14
|
* `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).
|
data/README.md
CHANGED
|
@@ -84,7 +84,7 @@ page = MetaInspector.new("https://github.com",
|
|
|
84
84
|
|
|
85
85
|
## Options reference
|
|
86
86
|
|
|
87
|
-
Pass these options as the second argument to `MetaInspector.new(url, options)
|
|
87
|
+
Pass these options as the second argument to `MetaInspector.new(url, options)`, with Symbol keys. Any other key, including a String key such as `'document'`, raises an `ArgumentError` that names it.
|
|
88
88
|
|
|
89
89
|
| Option | Default | Description |
|
|
90
90
|
| --- | --- | --- |
|
|
@@ -99,14 +99,13 @@ Pass these options as the second argument to `MetaInspector.new(url, options)`.
|
|
|
99
99
|
| `normalize_url` | `true` | Normalize URLs using Addressable. |
|
|
100
100
|
| `allow_non_html_content` | `false` | Allow non-HTML responses to be passed to the HTML parser. |
|
|
101
101
|
| `download_images` | `true` | Allow image downloads for dimensions, metadata and validation. |
|
|
102
|
-
| `max_image_downloads` | `
|
|
102
|
+
| `max_image_downloads` | `20` | Limit image lookup attempts; `nil` for unlimited, `0` disables image downloads. |
|
|
103
103
|
| `download_image_options` | `nil` | Set `reject_invalid_images: true` in a hash to discard images that fail validation. |
|
|
104
104
|
| `fetch_all_image_meta` | `nil` (disabled) | Enable validity lookups through `images.with_metadata`. |
|
|
105
105
|
| `inline_image_data` | `nil` (disabled) | Return full data URLs and allow inline images in `best` and `largest`. |
|
|
106
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
107
|
| `url_filter` | `nil` | Callable receiving a URI before each request; `false` or `nil` rejects the destination. |
|
|
108
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
109
|
|
|
111
110
|
## Accessing response
|
|
112
111
|
|
|
@@ -151,21 +150,16 @@ page.feeds # RSS, Atom or JSON feed links as an array of hashes: {
|
|
|
151
150
|
and ignoring parameters such as `; charset=utf-8`; `type` in the result is the
|
|
152
151
|
attribute as written.
|
|
153
152
|
|
|
154
|
-
`page.feed` is a deprecated compatibility method that returns the first RSS or
|
|
155
|
-
Atom feed's absolute URL, or `nil` if none is found. It skips JSON feeds. Each
|
|
156
|
-
call emits a deprecation warning. Use `page.feeds` instead; `page.feed` is
|
|
157
|
-
scheduled for removal in **6.0**.
|
|
158
|
-
|
|
159
153
|
### Texts
|
|
160
154
|
|
|
161
155
|
```ruby
|
|
162
156
|
page.language # declared language from the root <html lang="..."> attribute
|
|
163
|
-
page.title # title of the page from the head section,
|
|
157
|
+
page.title # title of the page from the head section, or nil
|
|
164
158
|
page.best_title # best title of the page, from a selection of candidates
|
|
165
159
|
page.author # author of the page from the meta author tag
|
|
166
160
|
page.best_author # best author of the page, from a selection of candidates
|
|
167
|
-
page.description # returns the meta description
|
|
168
|
-
page.best_description # returns the first non-empty description between the following candidates: standard meta description, og:description, twitter:description, the first long paragraph
|
|
161
|
+
page.description # returns the meta description, or nil
|
|
162
|
+
page.best_description # returns the first non-empty description between the following candidates: standard meta description, og:description, twitter:description, the first long paragraph; trims surrounding whitespace
|
|
169
163
|
page.h1 # returns h1 text array
|
|
170
164
|
page.h2 # returns h2 text array
|
|
171
165
|
page.h3 # returns h3 text array
|
|
@@ -180,6 +174,10 @@ attribute is missing, empty, or whitespace-only. It does not infer language from
|
|
|
180
174
|
the page content or other attributes. The value is also included in `to_hash`
|
|
181
175
|
under the `"language"` key.
|
|
182
176
|
|
|
177
|
+
`title` is the text of the first `<title>` in the head and `description` the
|
|
178
|
+
content of the meta description. Both trim surrounding whitespace and return
|
|
179
|
+
`nil` when missing or blank, so `page.title || fallback` works.
|
|
180
|
+
|
|
183
181
|
`best_title` selects the first non-empty value from the standard `title` meta tag,
|
|
184
182
|
`og:title`, the head `<title>`, a body `<title>`, the first `<h1>`, and finally
|
|
185
183
|
`parsely-title`.
|
|
@@ -212,17 +210,22 @@ page.images.best # Most relevant image from og:image, twitter:image, or
|
|
|
212
210
|
page.images.favicon # absolute URL to the favicon
|
|
213
211
|
```
|
|
214
212
|
|
|
215
|
-
`page.favicon` is a deprecated shortcut for `page.images.favicon`, returning the
|
|
216
|
-
same URL or `nil`. Each call emits a deprecation warning. Use
|
|
217
|
-
`page.images.favicon` instead; `page.favicon` is scheduled for removal in **6.0**.
|
|
218
|
-
|
|
219
213
|
The collection includes `img[src]`, `img[srcset]`, and `source[srcset]` inside
|
|
220
214
|
`picture`, resolved to absolute URLs and deduplicated. Elements appear in document
|
|
221
215
|
order; for each `img`, `src` comes before its `srcset` candidates, which retain
|
|
222
216
|
their listed order. All candidates are included regardless of media conditions or
|
|
223
|
-
device density.
|
|
224
|
-
|
|
225
|
-
|
|
217
|
+
device density. The `img` element's width and height apply only to its `src`
|
|
218
|
+
fallback. By default, non-HTTP responsive URLs remain in the collection but cannot
|
|
219
|
+
be downloaded for sizing.
|
|
220
|
+
|
|
221
|
+
`with_size`, `largest` and `best` treat the candidates of each `img` or `picture`
|
|
222
|
+
as one image at different sizes and rank only the largest one: the candidate with
|
|
223
|
+
the largest width descriptor (`800w`) if any has one, otherwise the highest density
|
|
224
|
+
(`2x`; `src` and candidates without a descriptor count as `1x`). That candidate is
|
|
225
|
+
downloaded for its dimensions, so each image costs at most one download. A `src`
|
|
226
|
+
with both `width` and `height` in the HTML is ranked as well, since it needs no
|
|
227
|
+
download. The other candidates are not in `with_size`; `to_a` and `with_details`
|
|
228
|
+
still list them all.
|
|
226
229
|
|
|
227
230
|
`images.owner_suggested` tries `og:image`, `twitter:image`, and `parsely-image-url`
|
|
228
231
|
in that order, skipping empty or whitespace-only values. Relative image URLs are
|
|
@@ -439,7 +442,7 @@ documents, set `max_html_bytes` to a non-negative integer:
|
|
|
439
442
|
page = MetaInspector.new(url, max_html_bytes: 2 * 1024 * 1024)
|
|
440
443
|
```
|
|
441
444
|
|
|
442
|
-
The default
|
|
445
|
+
The default is `nil` (no limit). Set a finite limit when fetching URLs you
|
|
443
446
|
do not control. Exceeding it raises `MetaInspector::ParserError` during
|
|
444
447
|
initialization. The limit applies separately to the bytes received for each
|
|
445
448
|
response (including redirect bodies), each stage of gzip/deflate decompression,
|
|
@@ -768,7 +771,7 @@ page = MetaInspector.new('http://example.com', max_image_downloads: 10)
|
|
|
768
771
|
page.images.with_size
|
|
769
772
|
```
|
|
770
773
|
|
|
771
|
-
The default is `nil`
|
|
774
|
+
The default is `20`; pass `nil` for no limit. The option accepts a non-negative integer or `nil`; `0` disables image downloads. `download_images: false` always disables downloads, regardless of the limit.
|
|
772
775
|
|
|
773
776
|
By default, the limit counts image size lookup attempts in HTML order, after excluding unparseable URLs and duplicates. Images with both HTML dimensions already present do not consume the limit, and those dimensions are preserved even after the limit is reached. Failed lookups count toward the limit. Images with incomplete dimensions that are not downloaded remain in `images.with_size` with dimensions `[0, 0]`, matching the behavior when downloads are disabled.
|
|
774
777
|
|
|
@@ -831,7 +834,7 @@ cache = ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache')
|
|
|
831
834
|
page = MetaInspector.new('http://example.com', faraday_options: { faraday_http_cache: { store: cache } })
|
|
832
835
|
```
|
|
833
836
|
|
|
834
|
-
The top-level `faraday_http_cache` option
|
|
837
|
+
The top-level `faraday_http_cache` option was removed in 6.0 and raises an `ArgumentError`.
|
|
835
838
|
|
|
836
839
|
## Exception Handling
|
|
837
840
|
|
|
@@ -852,6 +855,8 @@ page.title # => the title of the error page
|
|
|
852
855
|
|
|
853
856
|
## Examples
|
|
854
857
|
|
|
858
|
+
For a web demo, see [metainspectordemo](https://github.com/jaimeiniesta/metainspectordemo): a small Rack app where you enter a URL and explore what MetaInspector extracts from it, including metadata, images, links, headings, feeds and the full `to_hash` output. Run it locally with `bundle exec rackup`.
|
|
859
|
+
|
|
855
860
|
Runnable sample scripts live in `examples/`. From the repository root, pass the URL as an argument:
|
|
856
861
|
|
|
857
862
|
```sh
|
|
@@ -14,7 +14,7 @@ module MetaInspector
|
|
|
14
14
|
# * headers: object containing custom headers for the request
|
|
15
15
|
# * normalize_url: true by default
|
|
16
16
|
# * download_images: fetch missing image dimensions. Defaults to true
|
|
17
|
-
# * max_image_downloads: maximum image size lookups
|
|
17
|
+
# * max_image_downloads: maximum image size lookups. Defaults to 20; nil for unlimited
|
|
18
18
|
# * download_image_options: supports reject_invalid_images (default false)
|
|
19
19
|
# * inline_image_data: return full data URLs in image results (default false)
|
|
20
20
|
# * fetch_all_image_meta: enable image validity metadata (default false)
|
|
@@ -22,57 +22,46 @@ module MetaInspector
|
|
|
22
22
|
# * url_filter: callable receiving a URI before each request; false/nil rejects it
|
|
23
23
|
# * faraday_options: an optional hash of options to pass to Faraday on the request.
|
|
24
24
|
# Its faraday_http_cache key configures response caching with Faraday::HttpCache
|
|
25
|
-
#
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
25
|
+
#
|
|
26
|
+
# Raises ArgumentError for any other key, including String keys
|
|
27
|
+
OPTIONS = %i[
|
|
28
|
+
connection_timeout read_timeout retries encoding allow_redirections allow_non_html_content
|
|
29
|
+
head_first document headers normalize_url download_images max_image_downloads
|
|
30
|
+
download_image_options fetch_all_image_meta inline_image_data max_html_bytes url_filter
|
|
31
|
+
faraday_options
|
|
32
|
+
].freeze
|
|
33
|
+
|
|
34
|
+
# Options used by Request and by Parser. HttpSession and ImageDownloader
|
|
35
|
+
# pick their own options from the whole hash.
|
|
36
|
+
REQUEST_OPTIONS = %i[
|
|
37
|
+
allow_redirections head_first allow_non_html_content connection_timeout read_timeout encoding
|
|
38
|
+
].freeze
|
|
39
|
+
PARSER_OPTIONS = %i[
|
|
40
|
+
download_images max_html_bytes max_image_downloads download_image_options fetch_all_image_meta
|
|
41
|
+
inline_image_data
|
|
42
|
+
].freeze
|
|
43
|
+
private_constant :REQUEST_OPTIONS, :PARSER_OPTIONS
|
|
36
44
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
45
|
+
def initialize(initial_url, options = {})
|
|
46
|
+
validate_option_keys!(options)
|
|
47
|
+
options = defaults.merge(options)
|
|
48
|
+
validate_limit!(options, :max_html_bytes)
|
|
49
|
+
validate_limit!(options, :max_image_downloads)
|
|
41
50
|
|
|
42
51
|
@allow_redirections = options[:allow_redirections]
|
|
43
52
|
@allow_non_html_content = options[:allow_non_html_content]
|
|
44
|
-
|
|
45
|
-
@document
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
@
|
|
49
|
-
@
|
|
50
|
-
@
|
|
51
|
-
|
|
52
|
-
@url = MetaInspector::URL.new(initial_url, normalize: @normalize_url)
|
|
53
|
-
@request = MetaInspector::Request.new(@url, http_session: @http_session,
|
|
54
|
-
allow_redirections: @allow_redirections,
|
|
55
|
-
head_first: options[:head_first],
|
|
56
|
-
allow_non_html_content: @allow_non_html_content,
|
|
57
|
-
connection_timeout: @connection_timeout,
|
|
58
|
-
read_timeout: @read_timeout,
|
|
59
|
-
retries: @retries,
|
|
60
|
-
encoding: @encoding,
|
|
61
|
-
headers: @headers,
|
|
62
|
-
faraday_options: @faraday_options,
|
|
63
|
-
faraday_http_cache: @faraday_http_cache) unless @document
|
|
64
|
-
@parser = MetaInspector::Parser.new(self, download_images: @download_images,
|
|
65
|
-
max_html_bytes: max_html_bytes,
|
|
66
|
-
max_image_downloads: @max_image_downloads,
|
|
67
|
-
download_image_options: options[:download_image_options],
|
|
68
|
-
fetch_all_image_meta: options[:fetch_all_image_meta],
|
|
69
|
-
inline_image_data: options[:inline_image_data],
|
|
70
|
-
image_downloader: MetaInspector::ImageDownloader.new(@http_session, @url, options))
|
|
53
|
+
@headers = options[:headers]
|
|
54
|
+
@document = options[:document]
|
|
55
|
+
|
|
56
|
+
http_session = HttpSession.new(options)
|
|
57
|
+
@url = URL.new(initial_url, normalize: options[:normalize_url])
|
|
58
|
+
@request = Request.new(@url, http_session: http_session, **options.slice(*REQUEST_OPTIONS)) unless @document
|
|
59
|
+
@parser = Parser.new(self, image_downloader: ImageDownloader.new(http_session, @url, options),
|
|
60
|
+
**options.slice(*PARSER_OPTIONS))
|
|
71
61
|
end
|
|
72
62
|
|
|
73
63
|
extend Forwardable
|
|
74
|
-
delegate [
|
|
75
|
-
:tracked?, :untracked_url, :untrack!] => :@url
|
|
64
|
+
delegate %i[url scheme host root_url tracked? untracked_url untrack!] => :@url
|
|
76
65
|
|
|
77
66
|
# No request is made when the HTML is passed with the document: option,
|
|
78
67
|
# so these return nil in that case
|
|
@@ -84,11 +73,10 @@ module MetaInspector
|
|
|
84
73
|
@request&.response
|
|
85
74
|
end
|
|
86
75
|
|
|
87
|
-
delegate [
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
:head_links, :stylesheets, :canonicals] => :@parser
|
|
76
|
+
delegate %i[
|
|
77
|
+
parsed language title best_title author best_author h1 h2 h3 h4 h5 h6 description best_description
|
|
78
|
+
links images iframes iframe_sources feeds charset meta_tags meta_tag meta head_links stylesheets canonicals
|
|
79
|
+
] => :@parser
|
|
92
80
|
|
|
93
81
|
# Returns all document data as a nested Hash
|
|
94
82
|
def to_hash
|
|
@@ -130,6 +118,28 @@ module MetaInspector
|
|
|
130
118
|
|
|
131
119
|
private
|
|
132
120
|
|
|
121
|
+
# An option that is misspelled, or given with a String key (as when read from
|
|
122
|
+
# JSON or YAML), would otherwise be ignored: with 'document' => html, the page
|
|
123
|
+
# would be fetched instead of parsing the HTML.
|
|
124
|
+
def validate_option_keys!(options)
|
|
125
|
+
unknown = options.keys - OPTIONS
|
|
126
|
+
return if unknown.empty?
|
|
127
|
+
|
|
128
|
+
message = "Unknown option#{'s' if unknown.size > 1}: #{unknown.map(&:inspect).join(', ')}"
|
|
129
|
+
message += ' (option keys must be Symbols)' if unknown.any?(String)
|
|
130
|
+
if unknown.include?(:faraday_http_cache)
|
|
131
|
+
message += ' (pass it inside faraday_options: { faraday_http_cache: ... })'
|
|
132
|
+
end
|
|
133
|
+
raise ArgumentError, message
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def validate_limit!(options, name)
|
|
137
|
+
value = options[name]
|
|
138
|
+
return if value.nil? || (value.is_a?(Integer) && value >= 0)
|
|
139
|
+
|
|
140
|
+
raise ArgumentError, "#{name} must be a non-negative Integer or nil"
|
|
141
|
+
end
|
|
142
|
+
|
|
133
143
|
# Middleware can add headers that Net::HTTP would have normalized: faraday-gzip
|
|
134
144
|
# sets "Content-Length" to an Integer after decompressing. Downcase the names
|
|
135
145
|
# and re-encode only String values.
|
|
@@ -146,19 +156,18 @@ module MetaInspector
|
|
|
146
156
|
end
|
|
147
157
|
|
|
148
158
|
def defaults
|
|
149
|
-
{
|
|
150
|
-
:
|
|
151
|
-
:
|
|
152
|
-
:
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
:
|
|
157
|
-
:
|
|
158
|
-
:
|
|
159
|
-
:
|
|
160
|
-
|
|
161
|
-
:max_image_downloads => nil }
|
|
159
|
+
{
|
|
160
|
+
connection_timeout: 20,
|
|
161
|
+
read_timeout: 20,
|
|
162
|
+
retries: 3,
|
|
163
|
+
headers: { 'User-Agent' => default_user_agent, 'Accept-Encoding' => 'identity' },
|
|
164
|
+
allow_redirections: true,
|
|
165
|
+
allow_non_html_content: false,
|
|
166
|
+
head_first: false,
|
|
167
|
+
normalize_url: true,
|
|
168
|
+
download_images: true,
|
|
169
|
+
max_image_downloads: 20
|
|
170
|
+
}
|
|
162
171
|
end
|
|
163
172
|
|
|
164
173
|
def default_user_agent
|
|
@@ -166,9 +175,10 @@ module MetaInspector
|
|
|
166
175
|
end
|
|
167
176
|
|
|
168
177
|
def document
|
|
169
|
-
@document ||=
|
|
170
|
-
|
|
171
|
-
|
|
178
|
+
@document ||= begin
|
|
179
|
+
unless allow_non_html_content || Request.html_content_type?(content_type)
|
|
180
|
+
raise NonHtmlError.for(content_type)
|
|
181
|
+
end
|
|
172
182
|
@request.read
|
|
173
183
|
end
|
|
174
184
|
end
|
|
@@ -11,5 +11,9 @@ module MetaInspector
|
|
|
11
11
|
|
|
12
12
|
class ParserError < Error; end
|
|
13
13
|
|
|
14
|
-
class NonHtmlError < ParserError
|
|
14
|
+
class NonHtmlError < ParserError
|
|
15
|
+
def self.for(content_type)
|
|
16
|
+
new("The url provided contains #{content_type} content instead of text/html content")
|
|
17
|
+
end
|
|
18
|
+
end
|
|
15
19
|
end
|
|
@@ -67,6 +67,12 @@ module MetaInspector
|
|
|
67
67
|
'UTF-16LE' => %w[csunicode iso-10646-ucs-2 ucs-2 unicode unicodefeff utf-16 utf-16le]
|
|
68
68
|
}.flat_map { |encoding, labels| labels.map { |label| [label, encoding] } }.to_h.freeze
|
|
69
69
|
|
|
70
|
+
# Returns the charset label of a Content-Type value, such as
|
|
71
|
+
# "text/html; charset=utf-8", or nil if there is none.
|
|
72
|
+
def self.charset_param(content_type)
|
|
73
|
+
content_type.to_s[/(?:\A|;)\s*charset\s*=\s*["']?([^;\s"']+)/i, 1]
|
|
74
|
+
end
|
|
75
|
+
|
|
70
76
|
# Returns the encoding for a charset label, or nil if browsers don't know it.
|
|
71
77
|
def self.resolve(label)
|
|
72
78
|
LABELS[label.to_s.strip.downcase]
|
|
@@ -145,7 +151,7 @@ module MetaInspector
|
|
|
145
151
|
attributes = attributes.to_h
|
|
146
152
|
charset = attributes['charset']
|
|
147
153
|
if !charset && attributes['http-equiv'].to_s.casecmp?('content-type')
|
|
148
|
-
charset = attributes['content']
|
|
154
|
+
charset = HtmlEncoding.charset_param(attributes['content'])
|
|
149
155
|
end
|
|
150
156
|
return if charset.to_s.strip.empty?
|
|
151
157
|
|
|
@@ -28,61 +28,42 @@ module MetaInspector
|
|
|
28
28
|
|
|
29
29
|
def initialize(options = {})
|
|
30
30
|
@allow_redirections = options[:allow_redirections]
|
|
31
|
-
@retries
|
|
32
|
-
@attempt_timeout
|
|
33
|
-
@headers
|
|
34
|
-
@max_html_bytes
|
|
35
|
-
@url_filter
|
|
31
|
+
@retries = options[:retries]
|
|
32
|
+
@attempt_timeout = (options[:connection_timeout] || 0) + (options[:read_timeout] || 0) + 1
|
|
33
|
+
@headers = options[:headers]
|
|
34
|
+
@max_html_bytes = options[:max_html_bytes]
|
|
35
|
+
@url_filter = options[:url_filter]
|
|
36
36
|
if !@url_filter.nil? && !@url_filter.respond_to?(:call)
|
|
37
37
|
raise ArgumentError, 'url_filter must respond to call'
|
|
38
38
|
end
|
|
39
|
-
|
|
40
|
-
@
|
|
39
|
+
faraday_options = options[:faraday_options] || {}
|
|
40
|
+
@cache = faraday_options[:faraday_http_cache]
|
|
41
|
+
@faraday_options = faraday_options.except(:faraday_http_cache)
|
|
41
42
|
end
|
|
42
43
|
|
|
44
|
+
# Builds a connection for a page request or, with image: true, for an image
|
|
45
|
+
# lookup. Image lookups skip retries, the attempt deadline, decompression,
|
|
46
|
+
# the HTML size limit and the cache.
|
|
43
47
|
def build(url, image: false, origin: nil, protect_redirect_callback: false)
|
|
44
48
|
uri = URLPolicy.validate!(url)
|
|
45
49
|
# Image requests must keep trusting the initial origin after page redirects.
|
|
46
50
|
@page_origin ||= url.to_s unless image
|
|
47
51
|
# Faraday.new decodes a query in its URL with the default encoder, before
|
|
48
|
-
# any configured one applies, so the query is added to the params
|
|
52
|
+
# any configured one applies, so the query is added to the params after.
|
|
49
53
|
query = uri.query
|
|
50
54
|
uri.query = nil
|
|
51
55
|
faraday_options = @faraday_options.merge(url: uri.to_s)
|
|
52
56
|
faraday_options[:request] = { params_encoder: RawQuery }.merge(faraday_options[:request] || {})
|
|
53
|
-
redirects = (faraday_options.delete(:redirect)
|
|
54
|
-
|
|
55
|
-
callback = redirects[:callback]
|
|
56
|
-
redirects[:callback] = lambda do |*args|
|
|
57
|
-
begin
|
|
58
|
-
callback.call(*args)
|
|
59
|
-
rescue StandardError => error
|
|
60
|
-
raise URLPolicy::Failure.new(error)
|
|
61
|
-
end
|
|
62
|
-
end
|
|
63
|
-
end
|
|
57
|
+
redirects = redirect_options(faraday_options.delete(:redirect), protect_redirect_callback)
|
|
58
|
+
|
|
64
59
|
connection = Faraday.new(faraday_options) do |faraday|
|
|
65
|
-
unless image
|
|
66
|
-
faraday.request :retry, max: @retries
|
|
67
|
-
faraday.use AttemptTimeout, @attempt_timeout
|
|
68
|
-
# Responses run in reverse order: decompress before applying the charset.
|
|
69
|
-
faraday.response :encoding
|
|
70
|
-
faraday.request :gzip if @max_html_bytes.nil?
|
|
71
|
-
end
|
|
60
|
+
page_middleware(faraday) unless image
|
|
72
61
|
if @allow_redirections
|
|
73
|
-
redirects[:limit] ||= 10
|
|
74
62
|
faraday.use Faraday::FollowRedirects::Middleware, **redirects
|
|
75
63
|
faraday.use :cookie_jar
|
|
76
64
|
end
|
|
77
|
-
faraday.use URLPolicy, @url_filter, image ? origin : nil,
|
|
78
|
-
|
|
79
|
-
faraday.use LimitedResponse, @max_html_bytes if !image && @max_html_bytes
|
|
80
|
-
if !image && @cache.is_a?(Hash)
|
|
81
|
-
cache_options = @cache.dup
|
|
82
|
-
cache_options[:serializer] ||= Marshal
|
|
83
|
-
faraday.use Faraday::HttpCache, **cache_options
|
|
84
|
-
end
|
|
85
|
-
faraday.use LimitedResponse::Streaming, @max_html_bytes if !image && @max_html_bytes
|
|
65
|
+
faraday.use URLPolicy, @url_filter, image ? origin : nil, request_origin: @page_origin || origin
|
|
66
|
+
page_limit_and_cache_middleware(faraday) unless image
|
|
86
67
|
faraday.headers.merge!(@headers || {})
|
|
87
68
|
faraday.adapter :net_http
|
|
88
69
|
end
|
|
@@ -92,15 +73,41 @@ module MetaInspector
|
|
|
92
73
|
|
|
93
74
|
private
|
|
94
75
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
76
|
+
# With protect_callback, errors raised by the caller's redirect callback
|
|
77
|
+
# bypass the rescue clauses for network errors, and are re-raised as is.
|
|
78
|
+
def redirect_options(redirects, protect_callback)
|
|
79
|
+
redirects = (redirects || {}).dup
|
|
80
|
+
redirects[:limit] ||= 10
|
|
81
|
+
callback = redirects[:callback]
|
|
82
|
+
if protect_callback && callback
|
|
83
|
+
redirects[:callback] = lambda do |*args|
|
|
84
|
+
callback.call(*args)
|
|
85
|
+
rescue StandardError => error
|
|
86
|
+
raise URLPolicy::Failure.new(error)
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
redirects
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Outermost page middleware: each retry gets its own attempt deadline.
|
|
93
|
+
def page_middleware(faraday)
|
|
94
|
+
faraday.request :retry, max: @retries
|
|
95
|
+
faraday.use AttemptTimeout, @attempt_timeout
|
|
96
|
+
# Responses run in reverse order: decompress before applying the charset.
|
|
97
|
+
faraday.response :encoding
|
|
98
|
+
faraday.request :gzip if @max_html_bytes.nil?
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# LimitedResponse wraps the cache and Streaming runs inside it, so cached
|
|
102
|
+
# bodies are checked too and the cache stores the received bytes.
|
|
103
|
+
def page_limit_and_cache_middleware(faraday)
|
|
104
|
+
faraday.use LimitedResponse, @max_html_bytes if @max_html_bytes
|
|
105
|
+
if @cache.is_a?(Hash)
|
|
106
|
+
cache_options = @cache.dup
|
|
107
|
+
cache_options[:serializer] ||= Marshal
|
|
108
|
+
faraday.use Faraday::HttpCache, **cache_options
|
|
101
109
|
end
|
|
102
|
-
|
|
103
|
-
top_level
|
|
110
|
+
faraday.use LimitedResponse::Streaming, @max_html_bytes if @max_html_bytes
|
|
104
111
|
end
|
|
105
112
|
end
|
|
106
113
|
end
|
|
@@ -39,12 +39,33 @@ module MetaInspector
|
|
|
39
39
|
|
|
40
40
|
private
|
|
41
41
|
|
|
42
|
+
# The first MAX_BYTES bytes of a successful image response. complete is
|
|
43
|
+
# true when the whole body was read.
|
|
44
|
+
Download = Struct.new(:status, :headers, :bytes, :complete, keyword_init: true)
|
|
45
|
+
private_constant :Download
|
|
46
|
+
|
|
42
47
|
def fetch(url, metadata:, reject_invalid_url:)
|
|
43
|
-
|
|
48
|
+
download = download(url, reject_invalid_url)
|
|
49
|
+
return unless download.status && (200..299).cover?(download.status)
|
|
50
|
+
|
|
51
|
+
dimensions = FastImage.size(StringIO.new(download.bytes))
|
|
52
|
+
return dimensions unless metadata
|
|
53
|
+
|
|
54
|
+
{ dimensions: dimensions, type: FastImage.type(StringIO.new(download.bytes)), file_size: file_size(download) }
|
|
55
|
+
rescue URLPolicy::Failure => failure
|
|
56
|
+
raise failure.original
|
|
57
|
+
rescue URI::InvalidComponentError => error
|
|
58
|
+
raise MetaInspector::RequestError.new(error)
|
|
59
|
+
rescue Faraday::TimeoutError, Faraday::ConnectionFailed, Faraday::SSLError,
|
|
60
|
+
Faraday::FollowRedirects::RedirectLimitReached, URI::InvalidURIError, Timeout::Error
|
|
61
|
+
nil
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Streams the response and stops as soon as it has MAX_BYTES, gets an
|
|
65
|
+
# error status, or reaches TIMEOUT.
|
|
66
|
+
def download(url, reject_invalid_url)
|
|
67
|
+
download = Download.new(bytes: ''.b, complete: false)
|
|
44
68
|
received = 0
|
|
45
|
-
status = nil
|
|
46
|
-
headers = nil
|
|
47
|
-
completed = false
|
|
48
69
|
stop = Object.new
|
|
49
70
|
Timeout.timeout(TIMEOUT) do
|
|
50
71
|
session = @session.build(url, image: true, origin: @origin.url, protect_redirect_callback: reject_invalid_url)
|
|
@@ -55,44 +76,34 @@ module MetaInspector
|
|
|
55
76
|
request.options.open_timeout = @connection_timeout
|
|
56
77
|
request.options.timeout = @read_timeout
|
|
57
78
|
request.options.on_data = proc do |chunk, _total, env|
|
|
58
|
-
status = env.status
|
|
59
|
-
headers = env.response_headers
|
|
79
|
+
download.status = env.status
|
|
80
|
+
download.headers = env.response_headers
|
|
60
81
|
remaining = MAX_BYTES - received
|
|
61
82
|
received += chunk.bytesize
|
|
62
83
|
# 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)
|
|
84
|
+
if (200..299).cover?(env.status)
|
|
85
|
+
download.bytes << chunk.b.byteslice(0, remaining)
|
|
86
|
+
elsif !(300..399).cover?(env.status)
|
|
66
87
|
throw stop
|
|
67
88
|
end
|
|
68
89
|
throw stop if received >= MAX_BYTES
|
|
69
90
|
end
|
|
70
91
|
end
|
|
71
|
-
|
|
92
|
+
download.complete = true
|
|
72
93
|
end
|
|
73
94
|
end
|
|
74
|
-
|
|
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 URI::InvalidComponentError => error
|
|
84
|
-
raise MetaInspector::RequestError.new(error)
|
|
85
|
-
rescue Faraday::TimeoutError, Faraday::ConnectionFailed, Faraday::SSLError,
|
|
86
|
-
Faraday::FollowRedirects::RedirectLimitReached, URI::InvalidURIError, Timeout::Error
|
|
87
|
-
nil
|
|
95
|
+
download
|
|
88
96
|
end
|
|
89
97
|
|
|
90
|
-
|
|
98
|
+
# The full size of the image, from Content-Range for partial responses,
|
|
99
|
+
# or from Content-Length or the bytes read for complete ones.
|
|
100
|
+
def file_size(download)
|
|
101
|
+
status, headers = download.status, download.headers
|
|
91
102
|
value = if status == 206
|
|
92
103
|
headers['content-range'].to_s[/\Abytes \d+-\d+\/(\d+)\z/i, 1]
|
|
93
104
|
elsif status == 200 && (headers['content-encoding'].nil? || headers['content-encoding'] == 'identity')
|
|
94
105
|
length = headers['content-length']
|
|
95
|
-
length.nil? &&
|
|
106
|
+
length.nil? && download.complete ? download.bytes.bytesize.to_s : length.to_s[/\A\d+\z/]
|
|
96
107
|
end
|
|
97
108
|
value.to_i if value
|
|
98
109
|
end
|