pinterest-dl 2.2.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +52 -8
- data/README.md +108 -113
- data/bin/pinterest-dl +1 -125
- data/lib/pinterest-dl.rb +8 -1
- data/lib/pinterest_dl/api.rb +59 -24
- data/lib/pinterest_dl/board.rb +31 -42
- data/lib/pinterest_dl/cli.rb +428 -0
- data/lib/pinterest_dl/client.rb +61 -125
- data/lib/pinterest_dl/configuration.rb +104 -11
- data/lib/pinterest_dl/cookie_jar.rb +345 -0
- data/lib/pinterest_dl/downloader/part_file.rb +25 -0
- data/lib/pinterest_dl/downloader/response_plan.rb +194 -0
- data/lib/pinterest_dl/downloader.rb +714 -19
- data/lib/pinterest_dl/errors.rb +129 -15
- data/lib/pinterest_dl/extractors/image.rb +63 -9
- data/lib/pinterest_dl/extractors/pin_data.rb +156 -31
- data/lib/pinterest_dl/extractors/video.rb +42 -10
- data/lib/pinterest_dl/media_validator.rb +110 -0
- data/lib/pinterest_dl/models.rb +169 -0
- data/lib/pinterest_dl/paginator.rb +80 -0
- data/lib/pinterest_dl/progress_bar.rb +193 -4
- data/lib/pinterest_dl/search.rb +26 -42
- data/lib/pinterest_dl/security.rb +208 -0
- data/lib/pinterest_dl/session.rb +65 -0
- data/lib/pinterest_dl/transport.rb +322 -0
- data/lib/pinterest_dl/version.rb +1 -1
- metadata +54 -4
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'csv'
|
|
4
|
+
require 'fileutils'
|
|
5
|
+
require 'json'
|
|
6
|
+
require 'optparse'
|
|
7
|
+
require 'uri'
|
|
8
|
+
require_relative 'version'
|
|
9
|
+
require_relative 'errors'
|
|
10
|
+
require_relative 'progress_bar'
|
|
11
|
+
require_relative 'session'
|
|
12
|
+
require_relative 'api'
|
|
13
|
+
|
|
14
|
+
module PinterestDL
|
|
15
|
+
class CLI
|
|
16
|
+
FORMATS = %i[text json csv quiet].freeze
|
|
17
|
+
|
|
18
|
+
def self.run(argv = ARGV, out: $stdout, err: $stderr)
|
|
19
|
+
new(argv, out: out, err: err).run
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def initialize(argv, out: $stdout, err: $stderr)
|
|
23
|
+
@argv = argv.dup
|
|
24
|
+
@out = out
|
|
25
|
+
@err = err
|
|
26
|
+
@options = default_options
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def run
|
|
30
|
+
parse_options!
|
|
31
|
+
return 0 if @early_exit
|
|
32
|
+
|
|
33
|
+
command = @argv.shift
|
|
34
|
+
target = @argv.shift
|
|
35
|
+
|
|
36
|
+
if command.nil? || target.nil?
|
|
37
|
+
@out.puts usage
|
|
38
|
+
return command.nil? ? 0 : 1
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
session = build_session
|
|
42
|
+
dispatch(command, target, session)
|
|
43
|
+
rescue OptionParser::ParseError => e
|
|
44
|
+
print_error("Invalid option: #{e.message}", hint: 'Run `pinterest-dl --help` for usage instructions.')
|
|
45
|
+
1
|
|
46
|
+
rescue Interrupt
|
|
47
|
+
@err.puts "\npinterest-dl: interrupted"
|
|
48
|
+
130
|
|
49
|
+
rescue PinterestDL::Error, ArgumentError => e
|
|
50
|
+
handle_domain_error(e)
|
|
51
|
+
1
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def usage
|
|
55
|
+
<<~USAGE
|
|
56
|
+
pinterest-dl v#{PinterestDL::VERSION}
|
|
57
|
+
|
|
58
|
+
Usage:
|
|
59
|
+
pinterest-dl image URL [-q QUALITY] [-o PATH] [options]
|
|
60
|
+
pinterest-dl video URL [-o PATH] [options]
|
|
61
|
+
pinterest-dl media URL [-q QUALITY] [options]
|
|
62
|
+
pinterest-dl search QUERY [-n LIMIT] [-t TYPE] [-q QUALITY] [-j JOBS] [-o DIR] [options]
|
|
63
|
+
pinterest-dl board URL [-n LIMIT] [-t TYPE] [-q QUALITY] [-j JOBS] [-o DIR] [options]
|
|
64
|
+
|
|
65
|
+
Options:
|
|
66
|
+
-o, --output PATH File or directory to save downloaded media (omit to print direct URL)
|
|
67
|
+
-n, --limit N Max number of results or files to download (default 25)
|
|
68
|
+
-t, --type TYPE Filter media type: all, image, video, pin (default all)
|
|
69
|
+
--images-only Shortcut for --type image
|
|
70
|
+
--videos-only Shortcut for --type video
|
|
71
|
+
-q, --quality Q Image quality: originals, 1200x, 736x, 564x, 474x, 236x
|
|
72
|
+
-c, --cookies STR|FILE Cookie header string or Netscape cookies.txt file path
|
|
73
|
+
-j, --jobs N Parallel download workers for batch downloads (default 4)
|
|
74
|
+
-s, --skip-existing Skip files that already exist on disk
|
|
75
|
+
--resume Resume partially downloaded .part files (default true)
|
|
76
|
+
--no-resume Restart interrupted downloads from scratch
|
|
77
|
+
--max-size BYTES Maximum allowed file size (e.g. 100M, 500M)
|
|
78
|
+
--max-speed RATE Throttle download speed per worker (e.g. 500K, 2M)
|
|
79
|
+
--format FMT Output report format: text, json, csv, quiet (default text)
|
|
80
|
+
--json Output results and summary in JSON format
|
|
81
|
+
--no-progress Disable live progress bar output
|
|
82
|
+
--non-interactive Run without interactive terminal animations or prompts
|
|
83
|
+
--proxy URL HTTP/HTTPS proxy URL
|
|
84
|
+
--timeout SEC Network read/open timeout in seconds
|
|
85
|
+
--retries N Max retries on transient failures (default 3)
|
|
86
|
+
-v, --verbose Enable debug logging
|
|
87
|
+
--version Print version and exit
|
|
88
|
+
-h, --help Show this help
|
|
89
|
+
USAGE
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
private
|
|
93
|
+
|
|
94
|
+
def default_options
|
|
95
|
+
{
|
|
96
|
+
limit: 25,
|
|
97
|
+
quality: :originals,
|
|
98
|
+
type: :all,
|
|
99
|
+
jobs: 4,
|
|
100
|
+
skip_existing: false,
|
|
101
|
+
resume: true,
|
|
102
|
+
progress: true,
|
|
103
|
+
non_interactive: false,
|
|
104
|
+
format: :text,
|
|
105
|
+
verbose: false
|
|
106
|
+
}
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def parse_options!
|
|
110
|
+
parser = OptionParser.new do |opts|
|
|
111
|
+
opts.on('-o PATH', '--output PATH') { |v| @options[:output] = v }
|
|
112
|
+
opts.on('-n N', '--limit N', Integer) { |v| @options[:limit] = v }
|
|
113
|
+
opts.on('-t T', '--type T') { |v| @options[:type] = v.to_sym }
|
|
114
|
+
opts.on('--images-only') { @options[:type] = :image }
|
|
115
|
+
opts.on('--videos-only') { @options[:type] = :video }
|
|
116
|
+
opts.on('-q Q', '--quality Q') { |v| @options[:quality] = v.to_sym }
|
|
117
|
+
opts.on('-c STR', '--cookies STR') { |v| @options[:cookies] = v }
|
|
118
|
+
opts.on('-j N', '--jobs N', Integer) { |v| @options[:jobs] = v }
|
|
119
|
+
opts.on('-s', '--skip-existing') { @options[:skip_existing] = true }
|
|
120
|
+
opts.on('--[no-]resume') { |v| @options[:resume] = v }
|
|
121
|
+
opts.on('--max-size SIZE') { |v| @options[:max_size] = parse_byte_size(v) }
|
|
122
|
+
opts.on('--max-speed RATE') { |v| @options[:max_speed] = v }
|
|
123
|
+
opts.on('--format FMT') { |v| @options[:format] = parse_format(v) }
|
|
124
|
+
opts.on('--json') { @options[:format] = :json }
|
|
125
|
+
opts.on('--quiet') { @options[:format] = :quiet }
|
|
126
|
+
opts.on('--no-progress') { @options[:progress] = false }
|
|
127
|
+
opts.on('--non-interactive') do
|
|
128
|
+
@options[:non_interactive] = true
|
|
129
|
+
@options[:progress] = false
|
|
130
|
+
end
|
|
131
|
+
opts.on('--proxy URL') { |v| @options[:proxy] = v }
|
|
132
|
+
opts.on('--timeout SEC', Integer) { |v| @options[:timeout] = v }
|
|
133
|
+
opts.on('--retries N', Integer) { |v| @options[:retries] = v }
|
|
134
|
+
opts.on('-v', '--verbose') { @options[:verbose] = true }
|
|
135
|
+
opts.on('--version') do
|
|
136
|
+
@out.puts PinterestDL::VERSION
|
|
137
|
+
@early_exit = true
|
|
138
|
+
end
|
|
139
|
+
opts.on('-h', '--help') do
|
|
140
|
+
@out.puts usage
|
|
141
|
+
@early_exit = true
|
|
142
|
+
end
|
|
143
|
+
end
|
|
144
|
+
parser.parse!(@argv)
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def parse_format(val)
|
|
148
|
+
sym = val.to_s.strip.downcase.to_sym
|
|
149
|
+
raise OptionParser::InvalidArgument, "format must be one of: #{FORMATS.join(', ')}" unless FORMATS.include?(sym)
|
|
150
|
+
|
|
151
|
+
sym
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def parse_byte_size(val)
|
|
155
|
+
str = val.to_s.strip.downcase
|
|
156
|
+
match = str.match(/\A(\d+(?:\.\d+)?)\s*(b|k|kb|m|mb|g|gb)?\z/)
|
|
157
|
+
raise OptionParser::InvalidArgument, "invalid size #{val.inspect}" unless match
|
|
158
|
+
|
|
159
|
+
mult = Downloader::SPEED_MULTIPLIERS.fetch(match[2].to_s, 1)
|
|
160
|
+
(match[1].to_f * mult).to_i
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
def build_session
|
|
164
|
+
Session.new do |c|
|
|
165
|
+
c.cookies = @options[:cookies] if @options[:cookies]
|
|
166
|
+
c.quality = @options[:quality] if @options[:quality]
|
|
167
|
+
c.concurrency = @options[:jobs] if @options[:jobs]
|
|
168
|
+
c.overwrite = !@options[:skip_existing]
|
|
169
|
+
c.resume = @options[:resume]
|
|
170
|
+
c.progress = show_progress?
|
|
171
|
+
c.max_file_size = @options[:max_size] if @options[:max_size]
|
|
172
|
+
c.max_speed = @options[:max_speed] if @options[:max_speed]
|
|
173
|
+
c.proxy = @options[:proxy] if @options[:proxy]
|
|
174
|
+
if @options[:timeout]
|
|
175
|
+
c.open_timeout = @options[:timeout]
|
|
176
|
+
c.read_timeout = @options[:timeout]
|
|
177
|
+
end
|
|
178
|
+
c.max_retries = @options[:retries] if @options[:retries]
|
|
179
|
+
c.logger.level = Logger::DEBUG if @options[:verbose]
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
def dispatch(command, target, session)
|
|
184
|
+
case command
|
|
185
|
+
when 'image'
|
|
186
|
+
run_single_media(session, target, media_kind: :image)
|
|
187
|
+
when 'video'
|
|
188
|
+
run_single_media(session, target, media_kind: :video)
|
|
189
|
+
when 'media'
|
|
190
|
+
media = session.get_media(target, quality: @options[:quality])
|
|
191
|
+
emit_media_info(media)
|
|
192
|
+
0
|
|
193
|
+
when 'search'
|
|
194
|
+
pins = session.search(target, limit: @options[:limit], type: @options[:type])
|
|
195
|
+
handle_pins(session, pins)
|
|
196
|
+
when 'board'
|
|
197
|
+
pins = session.board(target, limit: @options[:limit], type: @options[:type])
|
|
198
|
+
handle_pins(session, pins)
|
|
199
|
+
else
|
|
200
|
+
print_error("Unknown command '#{command}'", hint: 'Valid commands are: image, video, media, search, board')
|
|
201
|
+
1
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
def run_single_media(session, target, media_kind:)
|
|
206
|
+
url = media_kind == :image ? session.get_image_url(target, quality: @options[:quality]) : session.get_video_url(target)
|
|
207
|
+
unless @options[:output]
|
|
208
|
+
if @options[:format] == :json
|
|
209
|
+
@out.puts JSON.pretty_generate({ type: media_kind, url: url })
|
|
210
|
+
elsif @options[:format] != :quiet
|
|
211
|
+
@out.puts url
|
|
212
|
+
end
|
|
213
|
+
return 0
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
dest_path = resolve_single_output_path(url, @options[:output], media_kind: media_kind)
|
|
217
|
+
label = File.basename(dest_path)
|
|
218
|
+
bar = build_byte_progress_bar(label: label, media_type: media_kind)
|
|
219
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
220
|
+
session.download(
|
|
221
|
+
url,
|
|
222
|
+
path: dest_path,
|
|
223
|
+
overwrite: !@options[:skip_existing],
|
|
224
|
+
resume: @options[:resume],
|
|
225
|
+
progress_bar: bar
|
|
226
|
+
)
|
|
227
|
+
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
|
|
228
|
+
emit_single_download_result(url, dest_path, media_kind, elapsed: elapsed)
|
|
229
|
+
0
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
def resolve_single_output_path(url, explicit_output, media_kind:)
|
|
233
|
+
default_ext = media_kind == :video ? '.mp4' : '.jpg'
|
|
234
|
+
basename = extract_url_basename(url)
|
|
235
|
+
basename = "pinterest_#{media_kind}#{default_ext}" if basename.empty? || !basename.include?('.')
|
|
236
|
+
|
|
237
|
+
out_str = explicit_output.to_s.strip
|
|
238
|
+
if File.directory?(out_str) || out_str.end_with?('/', '\\') || out_str == '.'
|
|
239
|
+
File.join(out_str, basename)
|
|
240
|
+
else
|
|
241
|
+
out_str
|
|
242
|
+
end
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
def handle_pins(session, pins)
|
|
246
|
+
if pins.empty?
|
|
247
|
+
if @options[:format] == :json
|
|
248
|
+
@out.puts JSON.pretty_generate({ pins: [], count: 0 })
|
|
249
|
+
else
|
|
250
|
+
@err.puts 'No matching pins found' unless @options[:format] == :quiet
|
|
251
|
+
end
|
|
252
|
+
return 0
|
|
253
|
+
end
|
|
254
|
+
|
|
255
|
+
if @options[:type] == :pin
|
|
256
|
+
handle_pin_links(pins)
|
|
257
|
+
elsif @options[:output]
|
|
258
|
+
handle_batch_download(session, pins)
|
|
259
|
+
else
|
|
260
|
+
emit_pins_output(pins)
|
|
261
|
+
end
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
def handle_pin_links(pins)
|
|
265
|
+
links = pins.map { |p| p[:pin_url] }
|
|
266
|
+
if @options[:output]
|
|
267
|
+
FileUtils.mkdir_p(@options[:output])
|
|
268
|
+
out_file = File.join(@options[:output], 'pins.txt')
|
|
269
|
+
File.write(out_file, "#{links.join("\n")}\n")
|
|
270
|
+
if @options[:format] == :json
|
|
271
|
+
@out.puts JSON.pretty_generate({ saved: links.size, path: out_file, links: links })
|
|
272
|
+
elsif @options[:format] != :quiet
|
|
273
|
+
@out.puts "Saved #{links.size} pin links to #{out_file}"
|
|
274
|
+
end
|
|
275
|
+
elsif @options[:format] == :json
|
|
276
|
+
@out.puts JSON.pretty_generate(links)
|
|
277
|
+
elsif @options[:format] != :quiet
|
|
278
|
+
@out.puts links
|
|
279
|
+
end
|
|
280
|
+
0
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
def handle_batch_download(session, pins)
|
|
284
|
+
selected = pins.first(@options[:limit])
|
|
285
|
+
items = selected.select do |p|
|
|
286
|
+
@options[:type] == :image ? p[:image_url] : (p[:video_url] || p[:image_url])
|
|
287
|
+
end
|
|
288
|
+
|
|
289
|
+
bar = ProgressBar.new(total: items.size, out: @err, enabled: show_progress?)
|
|
290
|
+
report = session.download_batch(
|
|
291
|
+
items,
|
|
292
|
+
dir: @options[:output],
|
|
293
|
+
concurrency: @options[:jobs],
|
|
294
|
+
overwrite: !@options[:skip_existing],
|
|
295
|
+
resume: @options[:resume]
|
|
296
|
+
) do |done, _total, url|
|
|
297
|
+
kind = url.to_s.include?('.mp4') ? :video : :image
|
|
298
|
+
name = extract_url_basename(url)
|
|
299
|
+
bar.update(done, label: name, media_type: kind)
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
emit_batch_summary(report, items.size)
|
|
303
|
+
report[:succeeded].empty? && report[:failed].any? ? 1 : 0
|
|
304
|
+
end
|
|
305
|
+
|
|
306
|
+
def emit_single_download_result(url, path, media_kind, elapsed: 0.0)
|
|
307
|
+
size = File.exist?(path) ? File.size(path) : 0
|
|
308
|
+
case @options[:format]
|
|
309
|
+
when :json
|
|
310
|
+
@out.puts JSON.pretty_generate({
|
|
311
|
+
status: 'saved',
|
|
312
|
+
type: media_kind,
|
|
313
|
+
url: url,
|
|
314
|
+
path: path,
|
|
315
|
+
bytes: size,
|
|
316
|
+
elapsed_seconds: elapsed.round(2)
|
|
317
|
+
})
|
|
318
|
+
when :csv
|
|
319
|
+
@out.puts CSV.generate_line([media_kind, url, path, size])
|
|
320
|
+
when :text
|
|
321
|
+
badge = "[#{media_kind.to_s.upcase}]"
|
|
322
|
+
@out.puts "#{badge} Saved to #{path} (#{ProgressBar.format_bytes(size)} in #{elapsed.round(2)}s)"
|
|
323
|
+
end
|
|
324
|
+
end
|
|
325
|
+
|
|
326
|
+
def emit_media_info(media)
|
|
327
|
+
case @options[:format]
|
|
328
|
+
when :csv
|
|
329
|
+
@out.puts CSV.generate_line(%w[image_url video_url])
|
|
330
|
+
@out.puts CSV.generate_line([media[:image_url], media[:video_url]])
|
|
331
|
+
when :quiet
|
|
332
|
+
nil
|
|
333
|
+
else
|
|
334
|
+
@out.puts JSON.pretty_generate(media)
|
|
335
|
+
end
|
|
336
|
+
end
|
|
337
|
+
|
|
338
|
+
def emit_pins_output(pins)
|
|
339
|
+
case @options[:format]
|
|
340
|
+
when :csv
|
|
341
|
+
@out.puts CSV.generate_line(%w[id pin_url title creator image_url video_url])
|
|
342
|
+
pins.each do |p|
|
|
343
|
+
@out.puts CSV.generate_line([p[:id], p[:pin_url], p[:title], p[:creator], p[:image_url], p[:video_url]])
|
|
344
|
+
end
|
|
345
|
+
when :quiet
|
|
346
|
+
nil
|
|
347
|
+
else
|
|
348
|
+
@out.puts JSON.pretty_generate(pins)
|
|
349
|
+
end
|
|
350
|
+
0
|
|
351
|
+
end
|
|
352
|
+
|
|
353
|
+
def emit_batch_summary(report, total_requested)
|
|
354
|
+
case @options[:format]
|
|
355
|
+
when :json
|
|
356
|
+
@out.puts report.to_json
|
|
357
|
+
when :csv
|
|
358
|
+
@out.puts CSV.generate_line(%w[succeeded skipped failed bytes_downloaded elapsed_seconds])
|
|
359
|
+
@out.puts CSV.generate_line([
|
|
360
|
+
report[:succeeded].size,
|
|
361
|
+
report[:skipped].size,
|
|
362
|
+
report[:failed].size,
|
|
363
|
+
report.bytes_downloaded,
|
|
364
|
+
report.elapsed_seconds.round(2)
|
|
365
|
+
])
|
|
366
|
+
when :text
|
|
367
|
+
skipped_msg = report[:skipped]&.any? ? " (#{report[:skipped].size} skipped)" : ''
|
|
368
|
+
failed_msg = report[:failed]&.any? ? ", #{report[:failed].size} failed" : ''
|
|
369
|
+
bytes_str = ProgressBar.format_bytes(report.bytes_downloaded)
|
|
370
|
+
size_msg = report.bytes_downloaded.positive? ? " [#{bytes_str} in #{report.elapsed_seconds.round(1)}s]" : ''
|
|
371
|
+
summary = "Downloaded #{report[:succeeded].size}/#{total_requested} files to #{@options[:output]}"
|
|
372
|
+
@out.puts "#{summary}#{skipped_msg}#{failed_msg}#{size_msg}"
|
|
373
|
+
end
|
|
374
|
+
end
|
|
375
|
+
|
|
376
|
+
def build_byte_progress_bar(label:, media_type:)
|
|
377
|
+
ProgressBar.new(
|
|
378
|
+
total: 0,
|
|
379
|
+
width: 20,
|
|
380
|
+
out: @err,
|
|
381
|
+
enabled: show_progress?,
|
|
382
|
+
label: label,
|
|
383
|
+
media_type: media_type,
|
|
384
|
+
byte_mode: true
|
|
385
|
+
)
|
|
386
|
+
end
|
|
387
|
+
|
|
388
|
+
def show_progress?
|
|
389
|
+
@options[:progress] && !@options[:non_interactive] && @options[:format] != :json && @options[:format] != :quiet
|
|
390
|
+
end
|
|
391
|
+
|
|
392
|
+
def extract_url_basename(url)
|
|
393
|
+
File.basename(URI(url.to_s).path.to_s)
|
|
394
|
+
rescue URI::InvalidURIError
|
|
395
|
+
''
|
|
396
|
+
end
|
|
397
|
+
|
|
398
|
+
def handle_domain_error(err)
|
|
399
|
+
hint = case err
|
|
400
|
+
when AuthenticationError
|
|
401
|
+
'Pass a logged-in session cookie with `-c cookies.txt` or `-c "sessionid=..."`.'
|
|
402
|
+
when ForbiddenError
|
|
403
|
+
'Pinterest rejected the request (HTTP 403). Check your cookies or try a different IP/proxy.'
|
|
404
|
+
when RateLimitError
|
|
405
|
+
wait_hint = err.retry_after ? " Wait #{err.retry_after}s or" : ''
|
|
406
|
+
"Rate limit reached (HTTP 429).#{wait_hint} reduce `-j/--jobs`."
|
|
407
|
+
when TimeoutError
|
|
408
|
+
'Increase timeout with `--timeout 30` or configure a proxy with `--proxy`.'
|
|
409
|
+
when SSRFError, InvalidURLError
|
|
410
|
+
'Provide a valid public Pinterest URL (e.g. https://www.pinterest.com/pin/...).'
|
|
411
|
+
when FileTooLargeError
|
|
412
|
+
'Increase the maximum allowed file size with `--max-size 1G`.'
|
|
413
|
+
when DiskSpaceError
|
|
414
|
+
'Check available disk space and write permissions on the output path.'
|
|
415
|
+
end
|
|
416
|
+
print_error(err.message, hint: hint)
|
|
417
|
+
end
|
|
418
|
+
|
|
419
|
+
def print_error(message, hint: nil)
|
|
420
|
+
if @options[:format] == :json
|
|
421
|
+
@err.puts JSON.generate({ error: message, hint: hint }.compact)
|
|
422
|
+
else
|
|
423
|
+
@err.puts "pinterest-dl: #{message}"
|
|
424
|
+
@err.puts " Hint: #{hint}" if hint
|
|
425
|
+
end
|
|
426
|
+
end
|
|
427
|
+
end
|
|
428
|
+
end
|
data/lib/pinterest_dl/client.rb
CHANGED
|
@@ -1,163 +1,99 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
require 'net/http'
|
|
5
3
|
require 'uri'
|
|
6
|
-
|
|
4
|
+
require_relative 'transport'
|
|
5
|
+
require_relative 'cookie_jar'
|
|
7
6
|
|
|
8
7
|
module PinterestDL
|
|
9
8
|
class Client
|
|
10
|
-
MAX_REDIRECTS =
|
|
9
|
+
MAX_REDIRECTS = Transport::MAX_REDIRECTS
|
|
10
|
+
RETRYABLE_HTTP_CODES = Transport::RETRYABLE_HTTP_CODES
|
|
11
11
|
|
|
12
|
-
attr_reader :
|
|
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
|
+
@mutex = Mutex.new
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def last_url
|
|
24
|
+
@mutex.synchronize { @last_url || @transport.last_url }
|
|
20
25
|
end
|
|
21
26
|
|
|
22
27
|
def get(url, headers: {}, use_cache: true)
|
|
23
|
-
cache_key = [url, headers].hash
|
|
24
|
-
if use_cache
|
|
25
|
-
|
|
26
|
-
|
|
28
|
+
cache_key = [url.to_s, headers].hash
|
|
29
|
+
if use_cache
|
|
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
|
|
37
|
+
if cached
|
|
38
|
+
body, final_url = cached
|
|
39
|
+
@mutex.synchronize { @last_url = final_url }
|
|
40
|
+
return body
|
|
41
|
+
end
|
|
27
42
|
end
|
|
28
43
|
|
|
29
|
-
|
|
30
|
-
|
|
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
|
|
31
49
|
body
|
|
32
50
|
end
|
|
33
51
|
|
|
34
52
|
def raw_get(url, headers: {})
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
def cookie(name, url = @last_url)
|
|
39
|
-
target = url.to_s.empty? ? 'https://www.pinterest.com' : url.to_s
|
|
40
|
-
@cookies[site_key(URI(target))][name]
|
|
41
|
-
rescue URI::InvalidURIError
|
|
42
|
-
nil
|
|
53
|
+
response = @transport.get(url, headers: headers)
|
|
54
|
+
@mutex.synchronize { @last_url = @transport.last_url }
|
|
55
|
+
response
|
|
43
56
|
end
|
|
44
57
|
|
|
45
|
-
def
|
|
46
|
-
|
|
47
|
-
end
|
|
48
|
-
|
|
49
|
-
private
|
|
50
|
-
|
|
51
|
-
def fetch(url, headers: {})
|
|
52
|
-
(MAX_REDIRECTS + 1).times do
|
|
53
|
-
response = request_with_retries(url, headers: headers)
|
|
54
|
-
save_cookies(response, url)
|
|
55
|
-
|
|
56
|
-
unless response.is_a?(Net::HTTPRedirection)
|
|
57
|
-
check_response(response, url)
|
|
58
|
-
@last_url = url
|
|
59
|
-
return response
|
|
60
|
-
end
|
|
61
|
-
|
|
62
|
-
location = response['location']
|
|
63
|
-
raise PinterestDL::NotFoundError, "Redirected without a location header (#{url})" unless location
|
|
64
|
-
|
|
65
|
-
url = URI.join(url, location).to_s
|
|
66
|
-
end
|
|
67
|
-
raise PinterestDL::NetworkError, "Too many redirects for #{url}"
|
|
68
|
-
end
|
|
58
|
+
def stream_get(url, headers: {}, &block)
|
|
59
|
+
raise ArgumentError, 'stream_get requires a block' unless block_given?
|
|
69
60
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
http = build_http(uri)
|
|
76
|
-
req = Net::HTTP::Get.new(uri, default_headers(uri).merge(headers))
|
|
77
|
-
http.request(req)
|
|
78
|
-
rescue Timeout::Error, Errno::ECONNRESET, Errno::ECONNREFUSED,
|
|
79
|
-
SocketError, OpenSSL::SSL::SSLError, EOFError => e
|
|
80
|
-
attempts += 1
|
|
81
|
-
if attempts <= @config.max_retries
|
|
82
|
-
@config.logger.warn("request to #{url} failed (#{e.class}), retrying (#{attempts}/#{@config.max_retries})")
|
|
83
|
-
sleep(@config.retry_wait * attempts)
|
|
84
|
-
retry
|
|
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)
|
|
85
66
|
end
|
|
86
|
-
raise PinterestDL::NetworkError.new("Failed to reach #{url}: #{e.message}", cause_error: e)
|
|
87
67
|
end
|
|
68
|
+
@mutex.synchronize { @last_url = @transport.last_url }
|
|
69
|
+
response
|
|
88
70
|
end
|
|
89
71
|
|
|
90
|
-
def
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
when Net::HTTPTooManyRequests
|
|
95
|
-
raise PinterestDL::RateLimitError.new(
|
|
96
|
-
"Rate limited while requesting #{url}",
|
|
97
|
-
retry_after: response['Retry-After']
|
|
98
|
-
)
|
|
99
|
-
when Net::HTTPUnauthorized
|
|
100
|
-
raise PinterestDL::AuthenticationError, "Authentication required for #{url}"
|
|
101
|
-
when Net::HTTPNotFound
|
|
102
|
-
raise PinterestDL::NotFoundError, "Nothing found at #{url}"
|
|
103
|
-
when Net::HTTPForbidden
|
|
104
|
-
raise PinterestDL::RateLimitError, "Request to #{url} was blocked (HTTP 403)"
|
|
105
|
-
else
|
|
106
|
-
raise PinterestDL::NetworkError, "Unexpected response #{response.code} from #{url}"
|
|
107
|
-
end
|
|
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)
|
|
108
76
|
end
|
|
109
77
|
|
|
110
|
-
def
|
|
111
|
-
|
|
112
|
-
http.use_ssl = (uri.scheme == 'https')
|
|
113
|
-
http.open_timeout = @config.open_timeout
|
|
114
|
-
http.read_timeout = @config.read_timeout
|
|
115
|
-
http
|
|
78
|
+
def clear_cache
|
|
79
|
+
@mutex.synchronize { @cache.clear }
|
|
116
80
|
end
|
|
117
81
|
|
|
118
|
-
def
|
|
119
|
-
|
|
120
|
-
'User-Agent' => @config.user_agent,
|
|
121
|
-
'Accept-Language' => 'en-US,en;q=0.9'
|
|
122
|
-
}
|
|
123
|
-
cookie_line = cookie_header(uri)
|
|
124
|
-
headers['Cookie'] = cookie_line unless cookie_line.empty?
|
|
125
|
-
headers
|
|
82
|
+
def cache_size
|
|
83
|
+
@mutex.synchronize { @cache.size }
|
|
126
84
|
end
|
|
127
85
|
|
|
128
|
-
|
|
129
|
-
parts = []
|
|
130
|
-
parts << @config.cookies.to_s if @config.authenticated?
|
|
131
|
-
parts.concat(@cookies[site_key(uri)].map { |name, value| "#{name}=#{value}" })
|
|
132
|
-
parts.join('; ')
|
|
133
|
-
end
|
|
86
|
+
private
|
|
134
87
|
|
|
135
|
-
def
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
next if name.nil? || value.nil?
|
|
88
|
+
def store_cache(key, value)
|
|
89
|
+
@mutex.synchronize do
|
|
90
|
+
max = @config.respond_to?(:max_cache_entries) ? @config.max_cache_entries.to_i : 256
|
|
91
|
+
return if max <= 0
|
|
140
92
|
|
|
141
|
-
|
|
93
|
+
@cache.delete(key)
|
|
94
|
+
@cache.shift while @cache.size >= max
|
|
95
|
+
@cache[key] = value
|
|
142
96
|
end
|
|
143
97
|
end
|
|
144
|
-
|
|
145
|
-
def site_key(uri)
|
|
146
|
-
host = uri.host.to_s.downcase
|
|
147
|
-
return 'pinterest.com' if host.include?('pinterest.')
|
|
148
|
-
|
|
149
|
-
host.split('.').last(2).join('.')
|
|
150
|
-
end
|
|
151
|
-
|
|
152
|
-
def throttle!
|
|
153
|
-
return if @config.rate_limit_interval <= 0
|
|
154
|
-
return unless @last_request_at
|
|
155
|
-
|
|
156
|
-
elapsed = Time.now - @last_request_at
|
|
157
|
-
wait = @config.rate_limit_interval - elapsed
|
|
158
|
-
sleep(wait) if wait.positive?
|
|
159
|
-
ensure
|
|
160
|
-
@last_request_at = Time.now
|
|
161
|
-
end
|
|
162
98
|
end
|
|
163
99
|
end
|