pinterest-dl 2.4.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.
@@ -115,66 +115,59 @@ module PinterestDL
115
115
 
116
116
  def load_netscape_file(file_path)
117
117
  @mutex.synchronize do
118
- File.foreach(file_path) { |line| load_netscape_line_unlocked(line) }
119
- end
120
- end
121
-
122
- def load_netscape_line_unlocked(line)
123
- stripped = line.strip
124
- return if stripped.empty?
125
-
126
- http_only = stripped.start_with?('#HttpOnly_')
127
- return if stripped.start_with?('#') && !http_only
128
-
129
- stripped = stripped.sub(/\A#HttpOnly_/, '') if http_only
130
- fields = stripped.split("\t")
131
-
132
- if fields.size >= 7
133
- cookie = build_netscape_cookie(fields, http_only)
134
- upsert_unlocked(cookie) if cookie
135
- elsif stripped.include?('=') && !stripped.include?("\t")
136
- load_cookie_pairs_unlocked(stripped)
137
- end
138
- end
139
-
140
- def build_netscape_cookie(fields, http_only)
141
- domain, include_subdomains, path, secure_flag, expiry_raw, name, value = fields
142
- normalized_domain = domain.sub(/\A\./, '')
143
-
144
- return unless Security.pinterest_host?(normalized_domain)
145
-
146
- expiry = expiry_raw.to_i
147
- Cookie.new(
148
- name: name.strip,
149
- value: value.to_s.strip,
150
- domain: normalized_domain.downcase,
151
- host_only: include_subdomains.to_s.upcase != 'TRUE' && !domain.start_with?('.'),
152
- path: path.to_s.empty? ? '/' : path.strip,
153
- secure: secure_flag.to_s.upcase == 'TRUE',
154
- http_only: http_only,
155
- expires: expiry.positive? ? Time.at(expiry) : nil,
156
- same_site: nil
157
- )
158
- end
159
-
160
- def load_cookie_pairs_unlocked(raw_cookies)
161
- raw_cookies.split(';').each do |pair|
162
- name, value = pair.strip.split('=', 2)
163
- next if name.nil? || value.nil? || name.empty?
164
-
165
- upsert_unlocked(
166
- Cookie.new(
167
- name: name,
168
- value: value,
169
- domain: 'pinterest.com',
170
- host_only: false,
171
- path: '/',
172
- secure: false,
173
- http_only: false,
174
- expires: nil,
175
- same_site: nil
176
- )
177
- )
118
+ File.foreach(file_path) do |line|
119
+ stripped = line.strip
120
+ next if stripped.empty?
121
+
122
+ if stripped.start_with?('#HttpOnly_')
123
+ stripped = stripped.sub(/\A#HttpOnly_/, '')
124
+ http_only = true
125
+ elsif stripped.start_with?('#')
126
+ next
127
+ else
128
+ http_only = false
129
+ end
130
+
131
+ fields = stripped.split("\t")
132
+ if fields.size >= 7
133
+ domain, include_subdomains, path, secure_flag, expiry_raw, name, value = fields
134
+ next unless Security.pinterest_host?(domain.sub(/\A\./, ''))
135
+
136
+ exp_int = expiry_raw.to_i
137
+ expires = exp_int.positive? ? Time.at(exp_int) : nil
138
+ cookie = Cookie.new(
139
+ name: name.strip,
140
+ value: value.to_s.strip,
141
+ domain: domain.sub(/\A\./, '').downcase,
142
+ host_only: include_subdomains.to_s.upcase != 'TRUE' && !domain.start_with?('.'),
143
+ path: path.to_s.empty? ? '/' : path.strip,
144
+ secure: secure_flag.to_s.upcase == 'TRUE',
145
+ http_only: http_only,
146
+ expires: expires,
147
+ same_site: nil
148
+ )
149
+ upsert_unlocked(cookie)
150
+ elsif stripped.include?('=') && !stripped.include?("\t")
151
+ stripped.split(';').each do |pair|
152
+ k, v = pair.strip.split('=', 2)
153
+ next if k.nil? || v.nil? || k.empty?
154
+
155
+ upsert_unlocked(
156
+ Cookie.new(
157
+ name: k,
158
+ value: v,
159
+ domain: 'pinterest.com',
160
+ host_only: false,
161
+ path: '/',
162
+ secure: false,
163
+ http_only: false,
164
+ expires: nil,
165
+ same_site: nil
166
+ )
167
+ )
168
+ end
169
+ end
170
+ end
178
171
  end
179
172
  end
180
173
 
@@ -229,24 +222,12 @@ module PinterestDL
229
222
  segments = raw_line.to_s.split(';').map(&:strip).reject(&:empty?)
230
223
  return nil if segments.empty?
231
224
 
232
- name, value = segments.shift.split('=', 2)
225
+ first = segments.shift
226
+ name, value = first.split('=', 2)
233
227
  return nil if name.nil? || value.nil? || name.strip.empty?
234
228
 
235
229
  origin_host = Security.clean_host(uri.host)
236
- attrs = default_cookie_attributes(name, value, uri, origin_host)
237
- state = { max_age_seen: false }
238
-
239
- segments.each do |segment|
240
- key, raw_value = segment.split('=', 2)
241
- apply_cookie_attribute(attrs, key.to_s.strip.downcase, raw_value&.strip, origin_host, state)
242
- end
243
-
244
- normalize_pinterest_cookie_domain(attrs)
245
- Cookie.new(**attrs)
246
- end
247
-
248
- def default_cookie_attributes(name, value, uri, origin_host)
249
- {
230
+ attrs = {
250
231
  name: name.strip,
251
232
  value: value.strip,
252
233
  domain: origin_host,
@@ -257,54 +238,46 @@ module PinterestDL
257
238
  expires: nil,
258
239
  same_site: nil
259
240
  }
260
- end
261
241
 
262
- def apply_cookie_attribute(attrs, key, value, origin_host, state)
263
- case key
264
- when 'domain'
265
- apply_cookie_domain(attrs, value, origin_host)
266
- when 'path'
267
- attrs[:path] = value && value.start_with?('/') ? value : '/'
268
- when 'secure'
269
- attrs[:secure] = true
270
- when 'httponly'
271
- attrs[:http_only] = true
272
- when 'max-age'
273
- apply_cookie_max_age(attrs, value, state)
274
- when 'expires'
275
- attrs[:expires] = parse_expiry(value) unless state[:max_age_seen]
276
- when 'samesite'
277
- attrs[:same_site] = value&.downcase
242
+ segments.each do |seg|
243
+ attr_name, attr_val = seg.split('=', 2)
244
+ key = attr_name.to_s.strip.downcase
245
+ val = attr_val&.strip
246
+ case key
247
+ when 'domain'
248
+ next if val.nil? || val.empty?
249
+
250
+ normalized = val.downcase.sub(/\A\./, '').chomp('.')
251
+ next unless domain_allowed_for_origin?(normalized, origin_host)
252
+
253
+ attrs[:domain] = normalized
254
+ attrs[:host_only] = false
255
+ when 'path'
256
+ attrs[:path] = val && val.start_with?('/') ? val : '/'
257
+ when 'secure'
258
+ attrs[:secure] = true
259
+ when 'httponly'
260
+ attrs[:http_only] = true
261
+ when 'max-age'
262
+ seconds = val.to_i
263
+ attrs[:expires] = seconds <= 0 ? Time.at(0) : Time.now + seconds
264
+ when 'expires'
265
+ attrs[:expires] = parse_expiry(val)
266
+ when 'samesite'
267
+ attrs[:same_site] = val&.downcase
268
+ end
278
269
  end
279
- end
280
-
281
- def apply_cookie_domain(attrs, value, origin_host)
282
- return if value.nil? || value.empty?
283
-
284
- normalized = value.downcase.sub(/\A\./, '').chomp('.')
285
- return unless domain_allowed_for_origin?(normalized, origin_host)
286
-
287
- attrs[:domain] = normalized
288
- attrs[:host_only] = false
289
- end
290
270
 
291
- def apply_cookie_max_age(attrs, value, state)
292
- seconds = Integer(value, 10)
293
- attrs[:expires] = seconds <= 0 ? Time.at(0) : Time.now + seconds
294
- state[:max_age_seen] = true
295
- rescue ArgumentError, TypeError
296
- nil
297
- end
298
-
299
- def normalize_pinterest_cookie_domain(attrs)
300
- return unless Security.pinterest_host?(attrs[:domain]) && attrs[:host_only]
271
+ if Security.pinterest_host?(attrs[:domain]) && attrs[:host_only]
272
+ attrs[:domain] = 'pinterest.com'
273
+ attrs[:host_only] = false
274
+ end
301
275
 
302
- attrs[:domain] = 'pinterest.com'
303
- attrs[:host_only] = false
276
+ Cookie.new(**attrs)
304
277
  end
305
278
 
306
279
  def domain_allowed_for_origin?(cookie_domain, origin_host)
307
- return false if cookie_domain.empty? || (!cookie_domain.include?('.') && origin_host != cookie_domain)
280
+ return false if cookie_domain.empty? || !cookie_domain.include?('.') && origin_host != cookie_domain
308
281
  return true if origin_host == cookie_domain
309
282
  return true if cookie_domain == 'pinterest.com' && Security.pinterest_host?(origin_host)
310
283
 
@@ -7,8 +7,6 @@ require_relative 'models'
7
7
  require_relative 'media_validator'
8
8
  require_relative 'progress_bar'
9
9
  require_relative 'security'
10
- require_relative 'downloader/response_plan'
11
- require_relative 'downloader/part_file'
12
10
 
13
11
  module PinterestDL
14
12
  class Downloader
@@ -41,6 +39,7 @@ module PinterestDL
41
39
  fbclid gclid _ga mc_cid mc_eid
42
40
  ].freeze
43
41
 
42
+ CONTENT_RANGE_REGEX = %r{\Abytes\s+(\d+)-(\d+)/(\d+|\*)\z}i
44
43
  UNSATISFIED_RANGE_REGEX = %r{\Abytes\s+\*/(\d+)\z}i
45
44
 
46
45
  def initialize(client: PinterestDL::Client.new, config: PinterestDL.config)
@@ -74,8 +73,7 @@ module PinterestDL
74
73
  end
75
74
 
76
75
  ensure_writable_directory!(File.dirname(target_path))
77
- part_file = PartFile.new(target_path, resumable: should_resume)
78
- part_path = part_file.path
76
+ part_path = build_part_path(target_path, resumable: should_resume)
79
77
  resumed_offset = should_resume && File.exist?(part_path) ? File.size(part_path) : 0
80
78
 
81
79
  progress_bar&.start
@@ -85,33 +83,35 @@ module PinterestDL
85
83
  resumed_offset: resumed_offset,
86
84
  max_size: size_limit,
87
85
  max_speed: speed_limit,
88
- verify_content: should_verify,
86
+ verify_content: verify_content,
89
87
  progress_bar: progress_bar,
90
88
  &on_progress
91
89
  )
92
90
  progress_bar&.finish(final_bytes: bytes_written)
93
91
 
94
- MediaValidator.validate_file_content!(part_path, url: url) if should_verify && bytes_written.positive?
92
+ if should_verify && bytes_written.positive?
93
+ MediaValidator.validate_file_content!(part_path, url: url)
94
+ end
95
95
 
96
- part_file.finalize!(target_path)
96
+ atomic_move!(part_path, target_path)
97
97
  target_path
98
98
  rescue ArgumentError
99
- PartFile.cleanup(part_path)
99
+ cleanup_part(part_path)
100
100
  raise
101
101
  rescue IncompleteDownloadError
102
- PartFile.cleanup(part_path) unless should_resume
102
+ cleanup_part(part_path) unless should_resume
103
103
  raise
104
104
  rescue PinterestDL::Error
105
- PartFile.cleanup(part_path)
105
+ cleanup_part(part_path)
106
106
  raise
107
107
  rescue Errno::ENOSPC, Errno::EDQUOT => e
108
- PartFile.cleanup(part_path)
108
+ cleanup_part(part_path)
109
109
  raise DiskSpaceError.new("Insufficient disk space while saving #{target_path}: #{e.message}", url: url, cause_error: e)
110
110
  rescue Errno::EACCES, Errno::EROFS, Errno::EPERM => e
111
- PartFile.cleanup(part_path)
111
+ cleanup_part(part_path)
112
112
  raise DiskSpaceError.new("Permission or read-only storage error at #{target_path}: #{e.message}", url: url, cause_error: e)
113
113
  rescue StandardError => e
114
- PartFile.cleanup(part_path)
114
+ cleanup_part(part_path)
115
115
  raise PinterestDL::DownloadError.new("Could not download #{url} to #{target_path}: #{e.message}", url: url, cause_error: e)
116
116
  end
117
117
 
@@ -178,7 +178,9 @@ module PinterestDL
178
178
  return :skip if overwrite == false
179
179
  return :overwrite if overwrite == true
180
180
 
181
- return :skip if @config.respond_to?(:overwrite) && @config.overwrite == false
181
+ if @config.respond_to?(:overwrite) && @config.overwrite == false
182
+ return :skip
183
+ end
182
184
 
183
185
  configured = @config.respond_to?(:collision_strategy) ? @config.collision_strategy : :overwrite
184
186
  validate_collision_strategy!(configured || :overwrite)
@@ -199,6 +201,12 @@ module PinterestDL
199
201
  default
200
202
  end
201
203
 
204
+ def build_part_path(path, resumable: false)
205
+ return "#{path}.part" if resumable
206
+
207
+ "#{path}.part.#{Process.pid}.#{Thread.current.object_id}"
208
+ end
209
+
202
210
  def perform_download_with_416_recovery(url, part_path, resumed_offset:, max_size:, max_speed:,
203
211
  verify_content:, progress_bar:, &on_progress)
204
212
  perform_download_to_part(
@@ -207,7 +215,7 @@ module PinterestDL
207
215
  resumed_offset: resumed_offset,
208
216
  max_size: max_size,
209
217
  max_speed: max_speed,
210
- verify_content: should_verify = verify_content,
218
+ verify_content: verify_content,
211
219
  progress_bar: progress_bar,
212
220
  &on_progress
213
221
  )
@@ -224,18 +232,18 @@ module PinterestDL
224
232
  actual_size: resumed_offset
225
233
  )
226
234
  end
227
- MediaValidator.validate_file_content!(part_path, url: url) if should_verify
235
+ MediaValidator.validate_file_content!(part_path, url: url) if verify_content
228
236
  return resumed_offset
229
237
  end
230
238
 
231
- PartFile.cleanup(part_path)
239
+ cleanup_part(part_path)
232
240
  perform_download_to_part(
233
241
  url,
234
242
  part_path,
235
243
  resumed_offset: 0,
236
244
  max_size: max_size,
237
245
  max_speed: max_speed,
238
- verify_content: should_verify,
246
+ verify_content: verify_content,
239
247
  progress_bar: progress_bar,
240
248
  &on_progress
241
249
  )
@@ -281,13 +289,118 @@ module PinterestDL
281
289
  end
282
290
 
283
291
  def prepare_response_plan!(response, url:, resumed_offset:, max_size:, verify_content:)
284
- ResponsePlan.build(
285
- response,
286
- url: url,
287
- resumed_offset: resumed_offset,
288
- max_size: max_size,
289
- verify_content: verify_content
290
- )
292
+ if response.nil?
293
+ return {
294
+ is_partial: false,
295
+ effective_offset: 0,
296
+ expected_body_bytes: nil,
297
+ final_total_size: nil,
298
+ write_mode: 'wb'
299
+ }
300
+ end
301
+
302
+ status_code = response.respond_to?(:code) && response.code ? response.code.to_i : 200
303
+ if status_code == 416 || response.is_a?(Net::HTTPRequestedRangeNotSatisfiable)
304
+ cr = extract_header(response, 'content-range')
305
+ raise RangeNotSatisfiableError.new("Range not satisfiable for #{url} (HTTP 416)", url: url, status_code: 416, content_range: cr)
306
+ end
307
+
308
+ content_type = extract_header(response, 'content-type')
309
+ MediaValidator.validate_content_type!(content_type, url: url) if verify_content
310
+
311
+ raw_len = extract_header(response, 'content-length')
312
+ content_length = raw_len && raw_len.to_s.strip.match?(/\A\d+\z/) ? raw_len.to_s.strip.to_i : nil
313
+
314
+ is_partial = response.is_a?(Net::HTTPPartialContent) || status_code == 206
315
+ if is_partial
316
+ unless resumed_offset.positive?
317
+ raise InvalidResponseError.new("Unexpected HTTP 206 without Range request for #{url}", url: url, status_code: 206)
318
+ end
319
+
320
+ range_info = parse_and_validate_content_range!(
321
+ extract_header(response, 'content-range'),
322
+ expected_offset: resumed_offset,
323
+ content_length: content_length,
324
+ url: url
325
+ )
326
+ effective_offset = resumed_offset
327
+ expected_body_bytes = range_info[:range_length]
328
+ final_total_size = range_info[:total_size] || (effective_offset + expected_body_bytes)
329
+ write_mode = 'ab'
330
+ else
331
+ effective_offset = 0
332
+ expected_body_bytes = content_length
333
+ final_total_size = content_length
334
+ write_mode = 'wb'
335
+ end
336
+
337
+ if max_size && final_total_size && final_total_size > max_size
338
+ raise FileTooLargeError.new(
339
+ "File at #{url} (#{final_total_size} bytes) exceeds max_file_size (#{max_size} bytes)",
340
+ url: url,
341
+ max_size: max_size,
342
+ actual_size: final_total_size
343
+ )
344
+ end
345
+
346
+ {
347
+ is_partial: is_partial,
348
+ effective_offset: effective_offset,
349
+ expected_body_bytes: expected_body_bytes,
350
+ final_total_size: final_total_size,
351
+ write_mode: write_mode
352
+ }
353
+ end
354
+
355
+ def parse_and_validate_content_range!(header_value, expected_offset:, content_length:, url:)
356
+ raw = header_value.to_s.strip
357
+ if raw.empty?
358
+ raise InvalidResponseError.new("Missing Content-Range header in HTTP 206 response from #{url}", url: url, status_code: 206)
359
+ end
360
+
361
+ match = raw.match(CONTENT_RANGE_REGEX)
362
+ unless match
363
+ raise InvalidResponseError.new("Malformed Content-Range header #{raw.inspect} from #{url}", url: url, status_code: 206)
364
+ end
365
+
366
+ range_start = match[1].to_i
367
+ range_end = match[2].to_i
368
+ total_token = match[3]
369
+ total_size = total_token == '*' ? nil : total_token.to_i
370
+
371
+ if range_start > range_end || (total_size && (total_size <= 0 || range_end >= total_size))
372
+ raise InvalidResponseError.new("Invalid byte range bounds in Content-Range #{raw.inspect} from #{url}", url: url, status_code: 206)
373
+ end
374
+
375
+ if range_start != expected_offset
376
+ raise InvalidResponseError.new(
377
+ "Content-Range start (#{range_start}) does not match requested offset (#{expected_offset}) from #{url}",
378
+ url: url,
379
+ status_code: 206
380
+ )
381
+ end
382
+
383
+ range_length = (range_end - range_start) + 1
384
+ if content_length && content_length != range_length
385
+ raise InvalidResponseError.new(
386
+ "Content-Length (#{content_length}) does not match Content-Range length (#{range_length}) from #{url}",
387
+ url: url,
388
+ status_code: 206
389
+ )
390
+ end
391
+
392
+ {
393
+ range_start: range_start,
394
+ range_end: range_end,
395
+ range_length: range_length,
396
+ total_size: total_size
397
+ }
398
+ end
399
+
400
+ def extract_header(response, name)
401
+ return nil unless response.respond_to?(:[])
402
+
403
+ response[name] || response[name.downcase] || response[name.split('-').map(&:capitalize).join('-')]
291
404
  end
292
405
 
293
406
  def stream_to_part(url, part_path, headers:, resumed_offset:, max_size:, max_speed:, verify_content:, progress_bar:, &on_progress)
@@ -297,7 +410,7 @@ module PinterestDL
297
410
  file_handle = nil
298
411
  started_at = monotonic_now
299
412
 
300
- @client.stream_get(url, headers: headers) do |chunk, response|
413
+ final_response = @client.stream_get(url, headers: headers) do |chunk, response|
301
414
  if file_handle.nil?
302
415
  plan = prepare_response_plan!(
303
416
  response,
@@ -337,7 +450,17 @@ module PinterestDL
337
450
  end
338
451
 
339
452
  if file_handle.nil?
340
- File.binwrite(part_path, '')
453
+ if final_response
454
+ plan = prepare_response_plan!(
455
+ final_response,
456
+ url: url,
457
+ resumed_offset: resumed_offset,
458
+ max_size: max_size,
459
+ verify_content: verify_content
460
+ )
461
+ total_written = plan[:effective_offset]
462
+ end
463
+ File.binwrite(part_path, '') unless resumed_offset.positive? && plan && plan[:is_partial]
341
464
  else
342
465
  file_handle.flush
343
466
  file_handle.close
@@ -430,6 +553,14 @@ module PinterestDL
430
553
  end
431
554
  end
432
555
 
556
+ def atomic_move!(part_path, path)
557
+ File.rename(part_path, path)
558
+ end
559
+
560
+ def cleanup_part(part_path)
561
+ FileUtils.rm_f(part_path) if part_path && File.exist?(part_path)
562
+ end
563
+
433
564
  def ensure_writable_directory!(dir)
434
565
  FileUtils.mkdir_p(dir)
435
566
  return if File.writable?(dir)
@@ -184,16 +184,7 @@ module PinterestDL
184
184
  current = stack.pop
185
185
  case current
186
186
  when Hash
187
- if current['images'].is_a?(Hash)
188
- url = best_image_url(current)
189
- if url
190
- score = Image.score_url_quality(url)
191
- if score > best_score
192
- best = url
193
- best_score = score
194
- end
195
- end
196
- end
187
+ best, best_score = pick_better_story_image(current, best, best_score)
197
188
  stack.concat(current.values)
198
189
  when Array
199
190
  stack.concat(current)
@@ -202,6 +193,16 @@ module PinterestDL
202
193
  best
203
194
  end
204
195
 
196
+ def pick_better_story_image(node, best, best_score)
197
+ return [best, best_score] unless node['images'].is_a?(Hash)
198
+
199
+ url = best_image_url(node)
200
+ return [best, best_score] unless url
201
+
202
+ score = Image.score_url_quality(url)
203
+ score > best_score ? [url, score] : [best, best_score]
204
+ end
205
+
205
206
  def parse_embedded_json(html)
206
207
  each_script_payload(html).first
207
208
  end
@@ -215,7 +216,7 @@ module PinterestDL
215
216
  when Hash
216
217
  if pin_id
217
218
  node_id = (node['id'] || node['pin_id']).to_s
218
- matches << node if node_id == pin_id.to_s && has_media?(node)
219
+ matches << node if node_id == pin_id.to_s && media?(node)
219
220
  elsif pin_like?(node)
220
221
  return node
221
222
  end
@@ -231,7 +232,7 @@ module PinterestDL
231
232
  !best_image_url(node).nil?
232
233
  end
233
234
 
234
- def has_media?(node)
235
+ def media?(node)
235
236
  node['images'].is_a?(Hash) ||
236
237
  node['images'].is_a?(Array) ||
237
238
  node['videos'].is_a?(Hash) ||
@@ -40,8 +40,9 @@ module PinterestDL
40
40
  seen_pin_ids[pin_id] = true unless pin_id.empty?
41
41
  yield pin
42
42
  yielded += 1
43
- return if @limit && yielded >= @limit
43
+ break if @limit && yielded >= @limit
44
44
  end
45
+ break if @limit && yielded >= @limit
45
46
 
46
47
  next_bookmarks = normalize_bookmarks(page[:bookmarks])
47
48
  pages_fetched += 1
@@ -40,7 +40,9 @@ module PinterestDL
40
40
  @label = label if label
41
41
  @media_type = media_type if media_type
42
42
  @last_total_bytes = total_bytes if total_bytes&.positive?
43
- render_byte_progress(0, @last_total_bytes, speed: 0.0, label: @label, media_type: @media_type) if @byte_mode && @last_total_bytes
43
+ if @byte_mode && @last_total_bytes
44
+ render_byte_progress(0, @last_total_bytes, speed: 0.0, label: @label, media_type: @media_type)
45
+ end
44
46
  end
45
47
  end
46
48
 
@@ -76,7 +76,6 @@ module PinterestDL
76
76
  end
77
77
 
78
78
  def search_headers(session)
79
- cookie_header = [@config.cookies, session[:cookies].join('; ')].compact.reject(&:empty?).join('; ')
80
79
  headers = {
81
80
  'Accept' => 'application/json, text/javascript, */*, q=0.01',
82
81
  'X-Requested-With' => 'XMLHttpRequest',
@@ -86,7 +85,10 @@ module PinterestDL
86
85
  'X-CSRFToken' => session[:csrf],
87
86
  'Referer' => session[:home_uri].to_s
88
87
  }
89
- headers['Cookie'] = cookie_header unless cookie_header.empty?
88
+ unless @client.respond_to?(:cookie_jar)
89
+ cookie_header = [@config.cookies, session[:cookies].join('; ')].compact.reject(&:empty?).join('; ')
90
+ headers['Cookie'] = cookie_header unless cookie_header.empty?
91
+ end
90
92
  headers
91
93
  end
92
94
 
@@ -176,7 +176,7 @@ module PinterestDL
176
176
 
177
177
  def resolve_ips(host)
178
178
  Resolv.getaddresses(host).filter_map { |addr| parse_ip(addr) }
179
- rescue Resolv::ResolvError, SocketError, StandardError
179
+ rescue StandardError
180
180
  []
181
181
  end
182
182
 
@@ -115,7 +115,7 @@ module PinterestDL
115
115
 
116
116
  private
117
117
 
118
- class RetryableResponseSignal < StandardError; end
118
+ RetryableResponseSignal = Class.new(StandardError)
119
119
  private_constant :RetryableResponseSignal
120
120
 
121
121
  def validate_target_url!(raw_url)
@@ -209,10 +209,14 @@ module PinterestDL
209
209
  def perform_request(http, req, &stream_block)
210
210
  return http.request(req) unless stream_block
211
211
 
212
+ captured = nil
212
213
  http.request(req) do |response|
213
- stream_block.call(response) if response.is_a?(Net::HTTPSuccess) || response.is_a?(Net::HTTPPartialContent)
214
- return response
214
+ if response.is_a?(Net::HTTPSuccess) || response.is_a?(Net::HTTPPartialContent)
215
+ stream_block.call(response)
216
+ end
217
+ captured = response
215
218
  end
219
+ captured
216
220
  end
217
221
 
218
222
  def retryable_response?(response)