pinterest-dl 2.3.0 → 2.4.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.
@@ -1,246 +1,99 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'net/http'
4
3
  require 'uri'
5
- require 'openssl'
4
+ require_relative 'transport'
5
+ require_relative 'cookie_jar'
6
6
 
7
7
  module PinterestDL
8
8
  class Client
9
- MAX_REDIRECTS = 5
10
- RETRYABLE_HTTP_CODES = %w[408 429 500 502 503 504].freeze
9
+ MAX_REDIRECTS = Transport::MAX_REDIRECTS
10
+ RETRYABLE_HTTP_CODES = Transport::RETRYABLE_HTTP_CODES
11
11
 
12
- attr_reader :last_url
12
+ attr_reader :config, :cookie_jar, :transport
13
13
 
14
- def initialize(config: PinterestDL.config)
15
- @config = config
14
+ def initialize(config: PinterestDL.config, transport: nil, cookie_jar: nil)
15
+ @config = config.dup
16
+ @cookie_jar = cookie_jar || @config.cookie_jar
17
+ @transport = transport || Transport.new(config: @config, cookie_jar: @cookie_jar)
16
18
  @cache = {}
17
- @cookies = Hash.new { |hash, key| hash[key] = {} }
18
- @last_request_at = nil
19
19
  @last_url = nil
20
20
  @mutex = Mutex.new
21
21
  end
22
22
 
23
+ def last_url
24
+ @mutex.synchronize { @last_url || @transport.last_url }
25
+ end
26
+
23
27
  def get(url, headers: {}, use_cache: true)
24
- cache_key = [url, headers].hash
28
+ cache_key = [url.to_s, headers].hash
25
29
  if use_cache
26
- cached = @mutex.synchronize { @cache[cache_key] }
30
+ cached = @mutex.synchronize do
31
+ if @cache.key?(cache_key)
32
+ val = @cache.delete(cache_key)
33
+ @cache[cache_key] = val
34
+ val
35
+ end
36
+ end
27
37
  if cached
28
- body, @last_url = cached
38
+ body, final_url = cached
39
+ @mutex.synchronize { @last_url = final_url }
29
40
  return body
30
41
  end
31
42
  end
32
43
 
33
- body = fetch(url, headers: headers).body
34
- store_cache(cache_key, [body, @last_url]) if use_cache
44
+ response = @transport.get(url, headers: headers)
45
+ final_url = @transport.last_url
46
+ @mutex.synchronize { @last_url = final_url }
47
+ body = response.body
48
+ store_cache(cache_key, [body, final_url]) if use_cache
35
49
  body
36
50
  end
37
51
 
38
52
  def raw_get(url, headers: {})
39
- fetch(url, headers: headers)
53
+ response = @transport.get(url, headers: headers)
54
+ @mutex.synchronize { @last_url = @transport.last_url }
55
+ response
40
56
  end
41
57
 
42
58
  def stream_get(url, headers: {}, &block)
43
59
  raise ArgumentError, 'stream_get requires a block' unless block_given?
44
60
 
45
- fetch(url, headers: headers, &block)
61
+ response = @transport.get(url, headers: headers) do |res|
62
+ if block.arity == 2
63
+ res.read_body { |chunk| block.call(chunk, res) }
64
+ else
65
+ res.read_body(&block)
66
+ end
67
+ end
68
+ @mutex.synchronize { @last_url = @transport.last_url }
69
+ response
46
70
  end
47
71
 
48
- def cookie(name, url = @last_url)
49
- target = url.to_s.empty? ? 'https://www.pinterest.com' : url.to_s
50
- key = site_key(URI(target))
51
- @mutex.synchronize { @cookies[key][name] }
52
- rescue URI::InvalidURIError
53
- nil
72
+ def cookie(name, url = nil)
73
+ target = url || last_url || 'https://www.pinterest.com'
74
+ allow_local = @config.respond_to?(:allow_local_network) ? @config.allow_local_network : true
75
+ @cookie_jar.value_for(name, target, allow_local: allow_local)
54
76
  end
55
77
 
56
78
  def clear_cache
57
79
  @mutex.synchronize { @cache.clear }
58
80
  end
59
81
 
82
+ def cache_size
83
+ @mutex.synchronize { @cache.size }
84
+ end
85
+
60
86
  private
61
87
 
62
88
  def store_cache(key, value)
63
89
  @mutex.synchronize do
64
90
  max = @config.respond_to?(:max_cache_entries) ? @config.max_cache_entries.to_i : 256
65
- @cache.shift if max.positive? && @cache.size >= max
66
- @cache[key] = value if max.positive?
67
- end
68
- end
69
-
70
- def fetch(url, headers: {}, &stream_block)
71
- (MAX_REDIRECTS + 1).times do
72
- response = request_with_retries(url, headers: headers, &stream_block)
73
- save_cookies(response, url)
74
- unless response.is_a?(Net::HTTPRedirection)
75
- check_response(response, url)
76
- @last_url = url
77
- return response
78
- end
79
-
80
- location = response['location']
81
- raise PinterestDL::NotFoundError, "Redirected without a location header (#{url})" unless location
82
-
83
- url = URI.join(url, location).to_s
84
- end
85
-
86
- raise PinterestDL::NetworkError, "Too many redirects for #{url}"
87
- end
88
-
89
- def request_with_retries(url, headers: {}, &stream_block)
90
- attempts = 0
91
- begin
92
- throttle!
93
- uri = URI(url)
94
- http = build_http(uri)
95
- req = Net::HTTP::Get.new(uri, default_headers(uri).merge(headers))
96
- response = perform_request(http, req, &stream_block)
97
-
98
- if retryable_response?(response) && attempts < @config.max_retries
99
- attempts += 1
100
- wait = retry_delay_for(response, attempts)
101
- @config.logger.warn("HTTP #{response.code} from #{url}, retrying in #{wait}s (#{attempts}/#{@config.max_retries})")
102
- sleep(wait) if wait.positive?
103
- raise RetryableResponseSignal
104
- end
105
-
106
- response
107
- rescue RetryableResponseSignal
108
- retry
109
- rescue Timeout::Error, Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::ETIMEDOUT,
110
- Errno::EHOSTUNREACH, SocketError, OpenSSL::SSL::SSLError, EOFError => e
111
- attempts += 1
112
- if attempts <= @config.max_retries
113
- @config.logger.warn("request to #{url} failed (#{e.class}), retrying (#{attempts}/#{@config.max_retries})")
114
- sleep(@config.retry_wait * attempts)
115
- retry
116
- end
117
- raise PinterestDL::NetworkError.new("Failed to reach #{url}: #{e.message}", cause_error: e)
118
- end
119
- end
120
-
121
- class RetryableResponseSignal < StandardError; end
122
- private_constant :RetryableResponseSignal
123
-
124
- def perform_request(http, req, &stream_block)
125
- return http.request(req) unless stream_block
126
-
127
- http.request(req) do |response|
128
- if response.is_a?(Net::HTTPSuccess)
129
- response.read_body(&stream_block)
130
- end
131
- return response
132
- end
133
- end
134
-
135
- def retryable_response?(response)
136
- RETRYABLE_HTTP_CODES.include?(response.code.to_s)
137
- end
91
+ return if max <= 0
138
92
 
139
- def retry_delay_for(response, attempts)
140
- header = response['Retry-After'].to_s.strip
141
- if header.match?(/\A\d+(\.\d+)?\z/)
142
- header.to_f
143
- else
144
- @config.retry_wait * attempts
93
+ @cache.delete(key)
94
+ @cache.shift while @cache.size >= max
95
+ @cache[key] = value
145
96
  end
146
97
  end
147
-
148
- def check_response(response, url)
149
- case response
150
- when Net::HTTPSuccess
151
- response
152
- when Net::HTTPTooManyRequests
153
- raise PinterestDL::RateLimitError.new(
154
- "Rate limited while requesting #{url}",
155
- retry_after: response['Retry-After']
156
- )
157
- when Net::HTTPUnauthorized
158
- raise PinterestDL::AuthenticationError, "Authentication required for #{url}"
159
- when Net::HTTPNotFound
160
- raise PinterestDL::NotFoundError, "Nothing found at #{url}"
161
- when Net::HTTPForbidden
162
- raise PinterestDL::RateLimitError, "Request to #{url} was blocked (HTTP 403)"
163
- else
164
- raise PinterestDL::NetworkError, "Unexpected response #{response.code} from #{url}"
165
- end
166
- end
167
-
168
- def build_http(uri)
169
- http = build_proxy_http(uri)
170
- http.use_ssl = (uri.scheme == 'https')
171
- http.open_timeout = @config.open_timeout
172
- http.read_timeout = @config.read_timeout
173
- http.write_timeout = @config.write_timeout if http.respond_to?(:write_timeout=) && @config.respond_to?(:write_timeout)
174
- http
175
- end
176
-
177
- def build_proxy_http(uri)
178
- proxy_url = @config.respond_to?(:proxy) ? @config.proxy : nil
179
- return Net::HTTP.new(uri.host, uri.port) if proxy_url.nil? || proxy_url.to_s.strip.empty?
180
-
181
- p_uri = URI(proxy_url.to_s)
182
- Net::HTTP.new(uri.host, uri.port, p_uri.host, p_uri.port, p_uri.user, p_uri.password)
183
- rescue URI::InvalidURIError
184
- Net::HTTP.new(uri.host, uri.port)
185
- end
186
-
187
- def default_headers(uri)
188
- headers = {
189
- 'User-Agent' => @config.user_agent,
190
- 'Accept-Language' => 'en-US,en;q=0.9'
191
- }
192
- cookie_line = cookie_header(uri)
193
- headers['Cookie'] = cookie_line unless cookie_line.empty?
194
- headers
195
- end
196
-
197
- def cookie_header(uri)
198
- parts = []
199
- parts << @config.cookies.to_s if @config.authenticated?
200
- key = site_key(uri)
201
- jar_pairs = @mutex.synchronize { @cookies[key].map { |name, value| "#{name}=#{value}" } }
202
- parts.concat(jar_pairs)
203
- parts.join('; ')
204
- end
205
-
206
- def save_cookies(response, url)
207
- fields = response.get_fields('set-cookie')
208
- return if fields.nil? || fields.empty?
209
-
210
- key = site_key(URI(url))
211
- @mutex.synchronize do
212
- jar = @cookies[key]
213
- fields.each do |line|
214
- name, value = line.split(';').first.to_s.split('=', 2)
215
- next if name.nil? || value.nil?
216
-
217
- value.strip.empty? ? jar.delete(name.strip) : jar[name.strip] = value.strip
218
- end
219
- end
220
- end
221
-
222
- def site_key(uri)
223
- host = uri.host.to_s.downcase
224
- return 'pinterest.com' if host.include?('pinterest.')
225
-
226
- host.split('.').last(2).join('.')
227
- end
228
-
229
- def throttle!
230
- return if @config.rate_limit_interval <= 0
231
-
232
- @mutex.synchronize do
233
- if @last_request_at
234
- elapsed = monotonic_now - @last_request_at
235
- wait = @config.rate_limit_interval - elapsed
236
- sleep(wait) if wait.positive?
237
- end
238
- @last_request_at = monotonic_now
239
- end
240
- end
241
-
242
- def monotonic_now
243
- Process.clock_gettime(Process::CLOCK_MONOTONIC)
244
- end
245
98
  end
246
- end
99
+ end
@@ -1,6 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'logger'
4
+ require_relative 'errors'
5
+ require_relative 'security'
6
+ require_relative 'cookie_jar'
4
7
 
5
8
  module PinterestDL
6
9
  class Configuration
@@ -9,34 +12,64 @@ module PinterestDL
9
12
  '(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
10
13
 
11
14
  VALID_QUALITIES = %i[originals 1200x 736x 564x 474x 236x].freeze
15
+ DEFAULT_MAX_FILE_SIZE = 500 * 1024 * 1024
12
16
 
13
17
  attr_accessor :user_agent, :open_timeout, :read_timeout, :write_timeout,
14
- :max_retries, :retry_wait, :logger, :rate_limit_interval,
15
- :proxy, :max_cache_entries, :concurrency, :overwrite
16
- attr_reader :quality, :cookies
17
-
18
- def initialize
18
+ :max_retries, :retry_wait, :max_retry_wait, :retry_jitter,
19
+ :rate_limit_interval, :proxy, :max_cache_entries,
20
+ :overwrite, :max_file_size, :max_speed, :verify_content_type,
21
+ :progress, :resume, :deduplicate, :collision_strategy,
22
+ :allow_local_network, :https_only, :min_free_disk_space
23
+ attr_reader :quality, :cookies, :concurrency, :cookie_jar, :logger
24
+
25
+ def initialize(**options)
19
26
  reset!
27
+ apply_options(options)
28
+ end
29
+
30
+ def initialize_copy(other)
31
+ super
32
+ @cookie_jar = other.cookie_jar.dup
33
+ @cookies = other.cookies&.dup
34
+ @user_agent = other.user_agent&.dup
35
+ @proxy = other.proxy&.dup
20
36
  end
21
37
 
22
38
  def reset!
23
39
  @user_agent = DEFAULT_USER_AGENT
24
40
  @cookies = nil
41
+ @cookie_jar = CookieJar.new
25
42
  @open_timeout = 10
26
43
  @read_timeout = 20
27
44
  @write_timeout = 20
28
45
  @max_retries = 3
29
46
  @retry_wait = 1.0
47
+ @max_retry_wait = 30.0
48
+ @retry_jitter = 0.25
30
49
  @quality = :originals
31
50
  @rate_limit_interval = 0.0
32
- @proxy = ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV['HTTP_PROXY'] || ENV['http_proxy']
51
+ @proxy = ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV['HTTP_PROXY'] || ENV.fetch('http_proxy', nil)
33
52
  @max_cache_entries = 256
34
53
  @concurrency = 4
35
54
  @overwrite = true
36
- @logger = default_logger
55
+ @max_file_size = DEFAULT_MAX_FILE_SIZE
56
+ @max_speed = nil
57
+ @verify_content_type = true
58
+ @progress = true
59
+ @resume = true
60
+ @deduplicate = true
61
+ @collision_strategy = :rename
62
+ @allow_local_network = false
63
+ @https_only = false
64
+ @min_free_disk_space = 1024 * 1024
65
+ self.logger = default_logger
37
66
  self
38
67
  end
39
68
 
69
+ def merge(**options)
70
+ dup.tap { |copy| copy.send(:apply_options, options) }
71
+ end
72
+
40
73
  def quality=(value)
41
74
  value = value.to_sym
42
75
  valid = VALID_QUALITIES.join(', ')
@@ -46,13 +79,16 @@ module PinterestDL
46
79
  end
47
80
 
48
81
  def cookies=(value)
82
+ @cookie_jar = CookieJar.new
49
83
  if value.nil? || value.to_s.strip.empty?
50
84
  @cookies = nil
51
85
  return
52
86
  end
53
87
 
54
88
  raw = value.to_s.strip
55
- @cookies = File.file?(raw) ? parse_cookie_file(raw) : raw
89
+ @cookie_jar.load_raw(raw)
90
+ @cookies = @cookie_jar.to_cookie_string
91
+ @cookies = nil if @cookies.empty?
56
92
  end
57
93
 
58
94
  def concurrency=(value)
@@ -62,36 +98,53 @@ module PinterestDL
62
98
  @concurrency = num
63
99
  end
64
100
 
101
+ def logger=(custom_logger)
102
+ @logger = wrap_redacting_logger(custom_logger || default_logger)
103
+ end
104
+
65
105
  def authenticated?
66
106
  !@cookies.nil? && !@cookies.empty?
67
107
  end
68
108
 
69
- private
109
+ def validate!
110
+ raise ConfigurationError, 'open_timeout must be positive' if @open_timeout.to_f <= 0
111
+ raise ConfigurationError, 'read_timeout must be positive' if @read_timeout.to_f <= 0
112
+ raise ConfigurationError, 'max_retries must be >= 0' if @max_retries.to_i.negative?
113
+ raise ConfigurationError, 'max_file_size must be positive' if @max_file_size && @max_file_size.to_i <= 0
70
114
 
71
- def parse_cookie_file(path)
72
- pairs = []
73
- File.foreach(path) do |line|
74
- stripped = line.strip
75
- next if stripped.empty? || stripped.start_with?('#')
115
+ true
116
+ end
76
117
 
77
- fields = stripped.split("\t")
78
- if fields.size >= 7
79
- domain, _flag, _path, _secure, _expiry, name, val = fields
80
- next unless domain.include?('pinterest.')
118
+ private
81
119
 
82
- pairs << "#{name}=#{val}"
83
- elsif stripped.include?('=') && !stripped.include?("\t")
84
- pairs << stripped
85
- end
120
+ def apply_options(options)
121
+ options.each do |key, value|
122
+ setter = :"#{key}="
123
+ raise ConfigurationError, "Unknown configuration option: #{key}" unless respond_to?(setter)
124
+
125
+ public_send(setter, value)
86
126
  end
87
- pairs.join('; ')
88
127
  end
89
128
 
90
129
  def default_logger
91
130
  Logger.new($stderr).tap do |log|
92
131
  log.level = Logger::WARN
93
- log.formatter = proc { |severity, _time, _progname, msg| "[pinterest-dl] #{severity}: #{msg}\n" }
94
132
  end
95
133
  end
134
+
135
+ def wrap_redacting_logger(base_logger)
136
+ return base_logger unless base_logger.respond_to?(:formatter=)
137
+
138
+ original_formatter = base_logger.formatter
139
+ base_logger.formatter = proc do |severity, time, progname, msg|
140
+ safe_msg = Security.redact(msg.to_s)
141
+ if original_formatter
142
+ Security.redact(original_formatter.call(severity, time, progname, safe_msg).to_s)
143
+ else
144
+ "[pinterest-dl] #{severity}: #{safe_msg}\n"
145
+ end
146
+ end
147
+ base_logger
148
+ end
96
149
  end
97
- end
150
+ end