pinterest-dl 2.3.0 → 2.5.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.
@@ -0,0 +1,208 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ipaddr'
4
+ require 'resolv'
5
+ require 'uri'
6
+
7
+ module PinterestDL
8
+ module Security
9
+ PINTEREST_DOMAIN_REGEX = /\A(?:[a-z0-9-]+\.)*pinterest\.(?:com|[a-z]{2,3}(?:\.[a-z]{2})?)\z/i
10
+ PINIMG_DOMAIN_REGEX = /\A(?:[a-z0-9-]+\.)*pinimg\.com\z/i
11
+ SHORTENER_DOMAIN_REGEX = /\Apin\.it\z/i
12
+
13
+ PRIVATE_CIDRS = [
14
+ IPAddr.new('0.0.0.0/8'),
15
+ IPAddr.new('10.0.0.0/8'),
16
+ IPAddr.new('100.64.0.0/10'),
17
+ IPAddr.new('127.0.0.0/8'),
18
+ IPAddr.new('169.254.0.0/16'),
19
+ IPAddr.new('172.16.0.0/12'),
20
+ IPAddr.new('192.0.0.0/24'),
21
+ IPAddr.new('192.0.2.0/24'),
22
+ IPAddr.new('192.168.0.0/16'),
23
+ IPAddr.new('198.18.0.0/15'),
24
+ IPAddr.new('198.51.100.0/24'),
25
+ IPAddr.new('203.0.113.0/24'),
26
+ IPAddr.new('224.0.0.0/4'),
27
+ IPAddr.new('240.0.0.0/4'),
28
+ IPAddr.new('::/128'),
29
+ IPAddr.new('::1/128'),
30
+ IPAddr.new('fc00::/7'),
31
+ IPAddr.new('fe80::/10'),
32
+ IPAddr.new('ff00::/8')
33
+ ].freeze
34
+
35
+ SENSITIVE_KEY_PATTERN = /
36
+ (cookie|set-cookie|csrftoken|x-csrftoken|sessionid|_pinterest_sess|_auth|authorization|token|password|secret)
37
+ (\s*[:=]\s*)
38
+ ([^\s,;'"&]+)
39
+ /ix
40
+
41
+ URL_CREDENTIAL_PATTERN = %r{(https?://[^/\s:@]+:)([^@\s/]+)(@)}i
42
+
43
+ module_function
44
+
45
+ def parse_and_validate_url!(raw_url, allow_local: false, allowed_hosts: nil, https_only: false)
46
+ str = raw_url.to_s.strip
47
+ raise InvalidURLError.new('URL must not be empty', url: raw_url) if str.empty?
48
+
49
+ uri = URI.parse(str)
50
+ validate_scheme!(uri, raw_url, https_only: https_only)
51
+ validate_host_presence!(uri, raw_url)
52
+ validate_no_credentials!(uri, raw_url)
53
+ validate_ssrf!(uri, raw_url, allow_local: allow_local)
54
+ validate_allowed_host!(uri, raw_url, allowed_hosts: allowed_hosts, allow_local: allow_local)
55
+ uri
56
+ rescue URI::InvalidURIError => e
57
+ raise InvalidURLError.new("Malformed URL: #{raw_url}", url: raw_url, cause_error: e)
58
+ end
59
+
60
+ def validate_scheme!(uri, raw_url, https_only: false)
61
+ schemes = https_only ? %w[https] : %w[http https]
62
+ return if schemes.include?(uri.scheme.to_s.downcase)
63
+
64
+ raise InvalidURLError.new("Unsupported URL scheme #{uri.scheme.inspect} for #{raw_url}", url: raw_url)
65
+ end
66
+
67
+ def validate_host_presence!(uri, raw_url)
68
+ host = uri.host.to_s.strip
69
+ raise InvalidURLError.new("Missing host in URL: #{raw_url}", url: raw_url) if host.empty?
70
+ raise InvalidURLError.new("Invalid host in URL: #{raw_url}", url: raw_url) if host.include?(' ')
71
+ end
72
+
73
+ def validate_no_credentials!(uri, raw_url)
74
+ return if uri.user.nil? && uri.password.nil?
75
+
76
+ raise InvalidURLError.new("Credentials in URL are not allowed: #{redact(raw_url.to_s)}", url: redact(raw_url.to_s))
77
+ end
78
+
79
+ def validate_ssrf!(uri, raw_url, allow_local: false)
80
+ return if allow_local
81
+
82
+ host = clean_host(uri.host)
83
+ if host == 'localhost' || host.end_with?('.localhost') || host.end_with?('.local') || host.end_with?('.internal')
84
+ raise SSRFError.new("Blocked internal host #{host}", url: raw_url)
85
+ end
86
+
87
+ ip = parse_ip(host)
88
+ if ip
89
+ raise SSRFError.new("Blocked internal IP address #{ip}", url: raw_url) if private_ip?(ip)
90
+
91
+ return
92
+ end
93
+
94
+ return if trusted_domain?(host)
95
+
96
+ resolve_ips(host).each do |resolved|
97
+ raise SSRFError.new("Host #{host} resolved to restricted address #{resolved}", url: raw_url) if private_ip?(resolved)
98
+ end
99
+ end
100
+
101
+ def validate_allowed_host!(uri, raw_url, allowed_hosts: nil, allow_local: false)
102
+ return if allowed_hosts.nil?
103
+
104
+ host = clean_host(uri.host)
105
+ return if allow_local && local_host?(host)
106
+
107
+ matched = Array(allowed_hosts).any? do |pattern|
108
+ pattern.is_a?(Regexp) ? pattern.match?(host) : host == pattern.to_s.downcase
109
+ end
110
+ return if matched
111
+
112
+ raise InvalidURLError.new("Host #{host.inspect} is not in the allowed host list", url: raw_url)
113
+ end
114
+
115
+ def pinterest_host?(host)
116
+ PINTEREST_DOMAIN_REGEX.match?(clean_host(host))
117
+ end
118
+
119
+ def pinimg_host?(host)
120
+ PINIMG_DOMAIN_REGEX.match?(clean_host(host))
121
+ end
122
+
123
+ def shortener_host?(host)
124
+ SHORTENER_DOMAIN_REGEX.match?(clean_host(host))
125
+ end
126
+
127
+ def trusted_domain?(host)
128
+ pinterest_host?(host) || pinimg_host?(host) || shortener_host?(host)
129
+ end
130
+
131
+ def cookie_eligible_host?(host, allow_local: false)
132
+ cleaned = clean_host(host)
133
+ return true if allow_local && local_host?(cleaned)
134
+
135
+ pinterest_host?(cleaned)
136
+ end
137
+
138
+ def same_security_domain?(source_uri, target_uri)
139
+ src_host = clean_host(source_uri.host)
140
+ dst_host = clean_host(target_uri.host)
141
+ return true if src_host == dst_host
142
+ return true if pinterest_host?(src_host) && pinterest_host?(dst_host)
143
+
144
+ false
145
+ end
146
+
147
+ def allowed_redirect_target?(source_uri, target_uri, allow_local: false)
148
+ dst_host = clean_host(target_uri.host)
149
+ return false if target_uri.scheme == 'http' && source_uri.scheme == 'https' && !allow_local
150
+ return true if allow_local && local_host?(dst_host)
151
+
152
+ trusted_domain?(dst_host) || clean_host(source_uri.host) == dst_host
153
+ end
154
+
155
+ def local_host?(host)
156
+ cleaned = clean_host(host)
157
+ return true if cleaned == 'localhost'
158
+
159
+ ip = parse_ip(cleaned)
160
+ !ip.nil? && private_ip?(ip)
161
+ end
162
+
163
+ def private_ip?(ip_addr)
164
+ addr = ip_addr.is_a?(IPAddr) ? ip_addr : parse_ip(ip_addr.to_s)
165
+ return false unless addr
166
+
167
+ addr = addr.native if addr.respond_to?(:ipv4_mapped?) && addr.ipv4_mapped?
168
+ PRIVATE_CIDRS.any? { |cidr| cidr.include?(addr) }
169
+ end
170
+
171
+ def parse_ip(str)
172
+ IPAddr.new(str)
173
+ rescue IPAddr::InvalidAddressError, IPAddr::AddressFamilyError
174
+ nil
175
+ end
176
+
177
+ def resolve_ips(host)
178
+ Resolv.getaddresses(host).filter_map { |addr| parse_ip(addr) }
179
+ rescue StandardError
180
+ []
181
+ end
182
+
183
+ def clean_host(host)
184
+ host.to_s.strip.downcase.sub(/\A\[(.*)\]\z/, '\1').chomp('.')
185
+ end
186
+
187
+ def redact(text)
188
+ return '' if text.nil?
189
+
190
+ sanitized = text.to_s.dup
191
+ sanitized.gsub!(URL_CREDENTIAL_PATTERN, '\1[REDACTED]\3')
192
+ sanitized.gsub!(SENSITIVE_KEY_PATTERN, '\1\2[REDACTED]')
193
+ sanitized
194
+ end
195
+
196
+ def redact_headers(headers)
197
+ return {} unless headers.is_a?(Hash)
198
+
199
+ headers.each_with_object({}) do |(key, value), out|
200
+ out[key] = if key.to_s.match?(/\A(cookie|set-cookie|authorization|x-csrftoken|proxy-authorization)\z/i)
201
+ '[REDACTED]'
202
+ else
203
+ redact(value.to_s)
204
+ end
205
+ end
206
+ end
207
+ end
208
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'configuration'
4
+ require_relative 'client'
5
+ require_relative 'downloader'
6
+ require_relative 'search'
7
+ require_relative 'board'
8
+ require_relative 'media_type'
9
+ require_relative 'extractors/image'
10
+ require_relative 'extractors/video'
11
+ require_relative 'extractors/pin_data'
12
+
13
+ module PinterestDL
14
+ class Session
15
+ attr_reader :config, :client
16
+
17
+ def initialize(config: nil, client: nil, **options)
18
+ base_config = config ? config.dup : PinterestDL.config.dup
19
+ @config = options.empty? ? base_config : base_config.merge(**options)
20
+ @client = client || Client.new(config: @config)
21
+ end
22
+
23
+ def configure
24
+ yield @config if block_given?
25
+ @client = Client.new(config: @config)
26
+ self
27
+ end
28
+
29
+ def get_image_url(pin_url, quality: @config.quality)
30
+ PinterestDL.get_image_url(pin_url, quality: quality, client: @client)
31
+ end
32
+
33
+ def get_video_url(pin_url)
34
+ PinterestDL.get_video_url(pin_url, client: @client)
35
+ end
36
+
37
+ def get_media(pin_url, quality: @config.quality)
38
+ PinterestDL.get_media(pin_url, quality: quality, client: @client)
39
+ end
40
+
41
+ def search(query, limit: 25, pages: nil, type: :all)
42
+ PinterestDL.search(query, limit: limit, pages: pages, type: type, client: @client, config: @config)
43
+ end
44
+
45
+ def search_images(query, limit: 25)
46
+ search(query, limit: limit, type: :image).filter_map { |p| p[:image_url] }
47
+ end
48
+
49
+ def search_videos(query, limit: 25)
50
+ search(query, limit: limit, type: :video).filter_map { |p| p[:video_url] }
51
+ end
52
+
53
+ def board(board_url, limit: 50, pages: nil, type: :all)
54
+ PinterestDL.board(board_url, limit: limit, pages: pages, type: type, client: @client, config: @config)
55
+ end
56
+
57
+ def download(url, path:, **options, &block)
58
+ Downloader.new(client: @client, config: @config).download(url, path: path, **options, &block)
59
+ end
60
+
61
+ def download_batch(urls, dir:, **options, &block)
62
+ Downloader.new(client: @client, config: @config).download_batch(urls, dir: dir, **options, &block)
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,326 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'net/http'
5
+ require 'openssl'
6
+ require 'time'
7
+ require 'uri'
8
+ require_relative 'errors'
9
+ require_relative 'security'
10
+ require_relative 'cookie_jar'
11
+
12
+ module PinterestDL
13
+ class Transport
14
+ MAX_REDIRECTS = 5
15
+ RETRYABLE_HTTP_CODES = %w[408 429 500 502 503 504].freeze
16
+ SENSITIVE_REDIRECT_HEADERS = %w[Cookie Authorization X-CSRFToken X-Pinterest-Source-Url].freeze
17
+
18
+ attr_reader :last_url, :cookie_jar, :config
19
+
20
+ def initialize(config: PinterestDL.config, cookie_jar: nil)
21
+ @config = config
22
+ @cookie_jar = cookie_jar || config.cookie_jar.dup
23
+ @last_request_at = nil
24
+ @last_url = nil
25
+ @mutex = Mutex.new
26
+ end
27
+
28
+ def get(url, headers: {}, &stream_block)
29
+ current_url = url.to_s
30
+ current_headers = headers.dup
31
+
32
+ (MAX_REDIRECTS + 1).times do
33
+ uri = validate_target_url!(current_url)
34
+ response = request_with_retries(uri, headers: current_headers, &stream_block)
35
+ @cookie_jar.set_from_header(response.get_fields('set-cookie'), uri.to_s)
36
+
37
+ unless response.is_a?(Net::HTTPRedirection)
38
+ check_response!(response, uri.to_s)
39
+ @last_url = uri.to_s
40
+ return response
41
+ end
42
+
43
+ location = response['location']
44
+ unless location
45
+ raise RedirectError.new("Redirected without a location header (#{uri})", url: uri.to_s, status_code: response.code.to_i)
46
+ end
47
+
48
+ next_uri = resolve_redirect_uri!(uri, location)
49
+ current_headers = sanitize_redirect_headers(uri, next_uri, current_headers)
50
+ current_url = next_uri.to_s
51
+ end
52
+
53
+ raise RedirectError.new("Too many redirects for #{current_url}", url: current_url)
54
+ end
55
+
56
+ def call_resource(host:, resource_name:, source_path:, options:, headers: {}, client: nil)
57
+ payload = { options: options, context: {} }.to_json
58
+ uri = URI("https://#{host}/resource/#{resource_name}/get/")
59
+ uri.query = URI.encode_www_form('source_url' => source_path, 'data' => payload)
60
+
61
+ raw_body = if client
62
+ client.get(uri.to_s, use_cache: false, headers: headers)
63
+ else
64
+ get(uri.to_s, headers: headers).body
65
+ end
66
+
67
+ parse_and_validate_resource_json!(raw_body, resource_name: resource_name, url: uri.to_s)
68
+ end
69
+
70
+ def parse_and_validate_resource_json!(raw_body, resource_name: 'Resource', url: nil)
71
+ if raw_body.nil? || raw_body.to_s.strip.empty?
72
+ raise InvalidResponseError.new("Empty response from Pinterest (#{resource_name})", url: url)
73
+ end
74
+
75
+ parsed = JSON.parse(raw_body.to_s)
76
+ raise InvalidResponseError.new("Expected JSON object from #{resource_name}", url: url) unless parsed.is_a?(Hash)
77
+
78
+ res = parsed['resource_response']
79
+ if res.is_a?(Hash) && res['error'].is_a?(Hash)
80
+ err_msg = res.dig('error', 'message') || res.dig('error', 'code') || 'API error'
81
+ http_code = res['http_status'].to_i
82
+ raise AuthenticationError.new(err_msg.to_s, url: url, status_code: 401) if http_code == 401
83
+ raise ForbiddenError.new(err_msg.to_s, url: url, status_code: 403) if http_code == 403
84
+ raise RateLimitError.new(err_msg.to_s, url: url, status_code: 429) if http_code == 429
85
+ end
86
+
87
+ parsed
88
+ rescue JSON::ParserError, TypeError => e
89
+ raise InvalidResponseError.new("Unexpected response from Pinterest (#{resource_name})", url: url, cause_error: e)
90
+ end
91
+
92
+ def backoff_delay(attempt, base_wait: @config.retry_wait, max_wait: @config.max_retry_wait, jitter_ratio: @config.retry_jitter)
93
+ exp = [attempt.to_i - 1, 0].max
94
+ raw = base_wait.to_f * (2**exp)
95
+ capped = max_wait ? [raw, max_wait.to_f].min : raw
96
+ jitter_max = capped * jitter_ratio.to_f
97
+ jitter = jitter_max.positive? ? rand(0.0..jitter_max) : 0.0
98
+ [capped + jitter, max_wait ? max_wait.to_f : (capped + jitter)].min
99
+ end
100
+
101
+ def parse_retry_after(header_value, now: Time.now)
102
+ str = header_value.to_s.strip
103
+ return nil if str.empty?
104
+
105
+ if str.match?(/\A\d+(\.\d+)?\z/)
106
+ val = str.to_f
107
+ return [val, 0.0].max
108
+ end
109
+
110
+ target_time = Time.httpdate(str)
111
+ [target_time - now, 0.0].max
112
+ rescue ArgumentError
113
+ nil
114
+ end
115
+
116
+ private
117
+
118
+ RetryableResponseSignal = Class.new(StandardError)
119
+ private_constant :RetryableResponseSignal
120
+
121
+ def validate_target_url!(raw_url)
122
+ allow_local = @config.respond_to?(:allow_local_network) ? @config.allow_local_network : false
123
+ https_only = @config.respond_to?(:https_only) ? @config.https_only : false
124
+ Security.parse_and_validate_url!(raw_url, allow_local: allow_local, https_only: https_only)
125
+ end
126
+
127
+ def resolve_redirect_uri!(source_uri, location)
128
+ target_str = URI.join(source_uri.to_s, location.to_s).to_s
129
+ allow_local = @config.respond_to?(:allow_local_network) ? @config.allow_local_network : false
130
+ https_only = @config.respond_to?(:https_only) ? @config.https_only : false
131
+ target_uri = Security.parse_and_validate_url!(target_str, allow_local: allow_local, https_only: https_only)
132
+
133
+ unless Security.allowed_redirect_target?(source_uri, target_uri, allow_local: allow_local)
134
+ raise RedirectError.new(
135
+ "Blocked cross-domain redirect from #{source_uri.host} to untrusted host #{target_uri.host}",
136
+ url: target_uri.to_s
137
+ )
138
+ end
139
+
140
+ target_uri
141
+ rescue URI::InvalidURIError => e
142
+ raise RedirectError.new("Invalid redirect location #{location.inspect}", url: source_uri.to_s, cause_error: e)
143
+ end
144
+
145
+ def sanitize_redirect_headers(source_uri, target_uri, headers)
146
+ return headers if Security.same_security_domain?(source_uri, target_uri)
147
+
148
+ headers.reject do |k, _|
149
+ SENSITIVE_REDIRECT_HEADERS.any? { |s| s.casecmp?(k.to_s) }
150
+ end
151
+ end
152
+
153
+ def request_with_retries(uri, headers: {}, &stream_block)
154
+ attempts = 0
155
+ max_retries = @config.max_retries.to_i
156
+ begin
157
+ throttle!
158
+ http = build_http(uri)
159
+ req = Net::HTTP::Get.new(uri, default_headers(uri).merge(headers))
160
+ response = perform_request(http, req, &stream_block)
161
+
162
+ if retryable_response?(response) && attempts < max_retries
163
+ attempts += 1
164
+ wait = retry_delay_for(response, attempts)
165
+ @config.logger.warn(
166
+ Security.redact("HTTP #{response.code} from #{uri}, retrying in #{wait.round(2)}s (#{attempts}/#{max_retries})")
167
+ )
168
+ sleep(wait) if wait.positive?
169
+ raise RetryableResponseSignal
170
+ end
171
+
172
+ response
173
+ rescue RetryableResponseSignal
174
+ retry
175
+ rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout, Timeout::Error, Errno::ETIMEDOUT => e
176
+ attempts += 1
177
+ if attempts <= max_retries
178
+ wait = backoff_delay(attempts)
179
+ msg = "Timeout requesting #{uri} (#{e.class}), retrying in #{wait.round(2)}s (#{attempts}/#{max_retries})"
180
+ @config.logger.warn(Security.redact(msg))
181
+ sleep(wait) if wait.positive?
182
+ retry
183
+ end
184
+ raise TimeoutError.new("Timed out requesting #{uri}: #{e.message}", url: uri.to_s, cause_error: e)
185
+ rescue OpenSSL::SSL::SSLError => e
186
+ attempts += 1
187
+ if attempts <= max_retries
188
+ wait = backoff_delay(attempts)
189
+ msg = "SSL error requesting #{uri} (#{e.class}), retrying in #{wait.round(2)}s (#{attempts}/#{max_retries})"
190
+ @config.logger.warn(Security.redact(msg))
191
+ sleep(wait) if wait.positive?
192
+ retry
193
+ end
194
+ raise SSLError.new("SSL error connecting to #{uri}: #{e.message}", url: uri.to_s, cause_error: e)
195
+ rescue Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH,
196
+ Errno::EPIPE, SocketError, EOFError => e
197
+ attempts += 1
198
+ if attempts <= max_retries
199
+ wait = backoff_delay(attempts)
200
+ msg = "Connection to #{uri} failed (#{e.class}), retrying in #{wait.round(2)}s (#{attempts}/#{max_retries})"
201
+ @config.logger.warn(Security.redact(msg))
202
+ sleep(wait) if wait.positive?
203
+ retry
204
+ end
205
+ raise ConnectionError.new("Failed to reach #{uri}: #{e.message}", url: uri.to_s, cause_error: e)
206
+ end
207
+ end
208
+
209
+ def perform_request(http, req, &stream_block)
210
+ return http.request(req) unless stream_block
211
+
212
+ captured = nil
213
+ http.request(req) do |response|
214
+ if response.is_a?(Net::HTTPSuccess) || response.is_a?(Net::HTTPPartialContent)
215
+ stream_block.call(response)
216
+ end
217
+ captured = response
218
+ end
219
+ captured
220
+ end
221
+
222
+ def retryable_response?(response)
223
+ RETRYABLE_HTTP_CODES.include?(response.code.to_s)
224
+ end
225
+
226
+ def retry_delay_for(response, attempts)
227
+ parsed = parse_retry_after(response['Retry-After'])
228
+ if parsed
229
+ max_wait = @config.respond_to?(:max_retry_wait) && @config.max_retry_wait ? @config.max_retry_wait.to_f : 60.0
230
+ [parsed, max_wait].min
231
+ else
232
+ backoff_delay(attempts)
233
+ end
234
+ end
235
+
236
+ def check_response!(response, url)
237
+ code = response.code.to_i
238
+ case response
239
+ when Net::HTTPSuccess, Net::HTTPPartialContent
240
+ response
241
+ when Net::HTTPRequestedRangeNotSatisfiable
242
+ raise RangeNotSatisfiableError.new(
243
+ "Range not satisfiable for #{url} (HTTP 416)",
244
+ url: url,
245
+ status_code: 416,
246
+ content_range: response['Content-Range'] || response['content-range']
247
+ )
248
+ when Net::HTTPTooManyRequests
249
+ raise RateLimitError.new(
250
+ "Rate limited while requesting #{url} (HTTP 429)",
251
+ url: url,
252
+ status_code: 429,
253
+ retry_after: response['Retry-After']
254
+ )
255
+ when Net::HTTPUnauthorized
256
+ raise AuthenticationError.new("Authentication required for #{url} (HTTP 401)", url: url, status_code: 401)
257
+ when Net::HTTPForbidden
258
+ raise ForbiddenError.new("Request to #{url} was forbidden (HTTP 403)", url: url, status_code: 403)
259
+ when Net::HTTPNotFound, Net::HTTPGone
260
+ raise NotFoundError.new("Nothing found at #{url} (HTTP #{code})", url: url, status_code: code)
261
+ when Net::HTTPServerError
262
+ raise ServerError.new("Pinterest server error #{code} from #{url}", url: url, status_code: code)
263
+ else
264
+ if code == 416
265
+ raise RangeNotSatisfiableError.new(
266
+ "Range not satisfiable for #{url} (HTTP 416)",
267
+ url: url,
268
+ status_code: 416,
269
+ content_range: response['Content-Range'] || response['content-range']
270
+ )
271
+ end
272
+ raise NetworkError.new("Unexpected HTTP response #{code} from #{url}", url: url, status_code: code)
273
+ end
274
+ end
275
+
276
+ def build_http(uri)
277
+ http = build_proxy_http(uri)
278
+ if uri.scheme == 'https'
279
+ http.use_ssl = true
280
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER
281
+ end
282
+ http.open_timeout = @config.open_timeout
283
+ http.read_timeout = @config.read_timeout
284
+ http.write_timeout = @config.write_timeout if http.respond_to?(:write_timeout=) && @config.respond_to?(:write_timeout)
285
+ http
286
+ end
287
+
288
+ def build_proxy_http(uri)
289
+ proxy_url = @config.respond_to?(:proxy) ? @config.proxy : nil
290
+ return Net::HTTP.new(uri.host, uri.port) if proxy_url.nil? || proxy_url.to_s.strip.empty?
291
+
292
+ p_uri = URI(proxy_url.to_s)
293
+ Net::HTTP.new(uri.host, uri.port, p_uri.host, p_uri.port, p_uri.user, p_uri.password)
294
+ rescue URI::InvalidURIError
295
+ Net::HTTP.new(uri.host, uri.port)
296
+ end
297
+
298
+ def default_headers(uri)
299
+ headers = {
300
+ 'User-Agent' => @config.user_agent,
301
+ 'Accept-Language' => 'en-US,en;q=0.9'
302
+ }
303
+ allow_local = @config.respond_to?(:allow_local_network) ? @config.allow_local_network : false
304
+ cookie_line = @cookie_jar.header_for(uri, allow_local: allow_local)
305
+ headers['Cookie'] = cookie_line unless cookie_line.empty?
306
+ headers
307
+ end
308
+
309
+ def throttle!
310
+ return if @config.rate_limit_interval.to_f <= 0
311
+
312
+ @mutex.synchronize do
313
+ if @last_request_at
314
+ elapsed = monotonic_now - @last_request_at
315
+ wait = @config.rate_limit_interval - elapsed
316
+ sleep(wait) if wait.positive?
317
+ end
318
+ @last_request_at = monotonic_now
319
+ end
320
+ end
321
+
322
+ def monotonic_now
323
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
324
+ end
325
+ end
326
+ end