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,455 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'json'
5
+ require 'optparse'
6
+ require 'uri'
7
+ require_relative 'version'
8
+ require_relative 'errors'
9
+ require_relative 'progress_bar'
10
+ require_relative 'session'
11
+ require_relative 'api'
12
+ require_relative 'tui'
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 == 'tui' || (command.nil? && launch_tui_directly?)
37
+ return run_tui
38
+ end
39
+
40
+ if command.nil? || target.nil?
41
+ @out.puts usage
42
+ return command.nil? ? 0 : 1
43
+ end
44
+
45
+ session = build_session
46
+ dispatch(command, target, session)
47
+ rescue OptionParser::ParseError => e
48
+ print_error("Invalid option: #{e.message}", hint: 'Run `pinterest-dl --help` for usage instructions.')
49
+ 1
50
+ rescue Interrupt
51
+ @err.puts "\npinterest-dl: interrupted"
52
+ 130
53
+ rescue PinterestDL::Error, ArgumentError => e
54
+ handle_domain_error(e)
55
+ 1
56
+ end
57
+
58
+ def usage
59
+ <<~USAGE
60
+ pinterest-dl v#{PinterestDL::VERSION}
61
+
62
+ Usage:
63
+ pinterest-dl
64
+ pinterest-dl tui [-o DIR] [-c COOKIES] [--proxy URL]
65
+ pinterest-dl image URL [-q QUALITY] [-o PATH] [options]
66
+ pinterest-dl video URL [-o PATH] [options]
67
+ pinterest-dl media URL [-q QUALITY] [options]
68
+ pinterest-dl search QUERY [-n LIMIT] [-t TYPE] [-q QUALITY] [-j JOBS] [-o DIR] [options]
69
+ pinterest-dl board URL [-n LIMIT] [-t TYPE] [-q QUALITY] [-j JOBS] [-o DIR] [options]
70
+
71
+ Options:
72
+ -o, --output PATH File or directory to save downloaded media (omit to print direct URL)
73
+ -n, --limit N Max number of results or files to download (default 25)
74
+ -t, --type TYPE Filter media type: all, image, video, pin (default all)
75
+ --images-only Shortcut for --type image
76
+ --videos-only Shortcut for --type video
77
+ -q, --quality Q Image quality: originals, 1200x, 736x, 564x, 474x, 236x
78
+ -c, --cookies STR|FILE Cookie header string or Netscape cookies.txt file path
79
+ -j, --jobs N Parallel download workers for batch downloads (default 4)
80
+ -s, --skip-existing Skip files that already exist on disk
81
+ --resume Resume partially downloaded .part files (default true)
82
+ --no-resume Restart interrupted downloads from scratch
83
+ --max-size BYTES Maximum allowed file size (e.g. 100M, 500M)
84
+ --max-speed RATE Throttle download speed per worker (e.g. 500K, 2M)
85
+ --format FMT Output report format: text, json, csv, quiet (default text)
86
+ --json Output results and summary in JSON format
87
+ --no-progress Disable live progress bar output
88
+ --non-interactive Run without interactive terminal animations or prompts
89
+ --proxy URL HTTP/HTTPS proxy URL
90
+ --timeout SEC Network read/open timeout in seconds
91
+ --retries N Max retries on transient failures (default 3)
92
+ -v, --verbose Enable debug logging
93
+ --version Print version and exit
94
+ -h, --help Show this help
95
+ USAGE
96
+ end
97
+
98
+ private
99
+
100
+ def launch_tui_directly?
101
+ !@options[:non_interactive] && @out.respond_to?(:tty?) && @out.tty? && $stdin.respond_to?(:tty?) && $stdin.tty?
102
+ end
103
+
104
+ def run_tui
105
+ @options[:proxy] ||= PinterestDL::TUI.detect_proxy
106
+ @options[:cookies] ||= PinterestDL::TUI.detect_cookies_file
107
+ out_dir = @options[:output] || './downloads'
108
+ PinterestDL::TUI.start(session: build_session, output_dir: out_dir)
109
+ 0
110
+ end
111
+
112
+ def default_options
113
+ {
114
+ limit: 25,
115
+ quality: :originals,
116
+ type: :all,
117
+ jobs: 4,
118
+ skip_existing: false,
119
+ resume: true,
120
+ progress: true,
121
+ non_interactive: false,
122
+ format: :text,
123
+ verbose: false
124
+ }
125
+ end
126
+
127
+ def parse_options!
128
+ parser = OptionParser.new do |opts|
129
+ opts.on('-o PATH', '--output PATH') { |v| @options[:output] = v }
130
+ opts.on('-n N', '--limit N', Integer) { |v| @options[:limit] = v }
131
+ opts.on('-t T', '--type T') { |v| @options[:type] = v.to_sym }
132
+ opts.on('--images-only') { @options[:type] = :image }
133
+ opts.on('--videos-only') { @options[:type] = :video }
134
+ opts.on('-q Q', '--quality Q') { |v| @options[:quality] = v.to_sym }
135
+ opts.on('-c STR', '--cookies STR') { |v| @options[:cookies] = v }
136
+ opts.on('-j N', '--jobs N', Integer) { |v| @options[:jobs] = v }
137
+ opts.on('-s', '--skip-existing') { @options[:skip_existing] = true }
138
+ opts.on('--[no-]resume') { |v| @options[:resume] = v }
139
+ opts.on('--max-size SIZE') { |v| @options[:max_size] = parse_byte_size(v) }
140
+ opts.on('--max-speed RATE') { |v| @options[:max_speed] = v }
141
+ opts.on('--format FMT') { |v| @options[:format] = parse_format(v) }
142
+ opts.on('--json') { @options[:format] = :json }
143
+ opts.on('--quiet') { @options[:format] = :quiet }
144
+ opts.on('--no-progress') { @options[:progress] = false }
145
+ opts.on('--non-interactive') do
146
+ @options[:non_interactive] = true
147
+ @options[:progress] = false
148
+ end
149
+ opts.on('--proxy URL') { |v| @options[:proxy] = v }
150
+ opts.on('--timeout SEC', Integer) { |v| @options[:timeout] = v }
151
+ opts.on('--retries N', Integer) { |v| @options[:retries] = v }
152
+ opts.on('-v', '--verbose') { @options[:verbose] = true }
153
+ opts.on('--version') do
154
+ @out.puts PinterestDL::VERSION
155
+ @early_exit = true
156
+ end
157
+ opts.on('-h', '--help') do
158
+ @out.puts usage
159
+ @early_exit = true
160
+ end
161
+ end
162
+ parser.parse!(@argv)
163
+ end
164
+
165
+ def parse_format(val)
166
+ sym = val.to_s.strip.downcase.to_sym
167
+ raise OptionParser::InvalidArgument, "format must be one of: #{FORMATS.join(', ')}" unless FORMATS.include?(sym)
168
+
169
+ sym
170
+ end
171
+
172
+ def parse_byte_size(val)
173
+ str = val.to_s.strip.downcase
174
+ match = str.match(/\A(\d+(?:\.\d+)?)\s*(b|k|kb|m|mb|g|gb)?\z/)
175
+ raise OptionParser::InvalidArgument, "invalid size #{val.inspect}" unless match
176
+
177
+ mult = Downloader::SPEED_MULTIPLIERS.fetch(match[2].to_s, 1)
178
+ (match[1].to_f * mult).to_i
179
+ end
180
+
181
+ def build_session
182
+ Session.new do |c|
183
+ c.cookies = @options[:cookies] if @options[:cookies]
184
+ c.quality = @options[:quality] if @options[:quality]
185
+ c.concurrency = @options[:jobs] if @options[:jobs]
186
+ c.overwrite = !@options[:skip_existing]
187
+ c.resume = @options[:resume]
188
+ c.progress = show_progress?
189
+ c.max_file_size = @options[:max_size] if @options[:max_size]
190
+ c.max_speed = @options[:max_speed] if @options[:max_speed]
191
+ c.proxy = @options[:proxy] if @options[:proxy]
192
+ if @options[:timeout]
193
+ c.open_timeout = @options[:timeout]
194
+ c.read_timeout = @options[:timeout]
195
+ end
196
+ c.max_retries = @options[:retries] if @options[:retries]
197
+ c.logger.level = Logger::DEBUG if @options[:verbose]
198
+ end
199
+ end
200
+
201
+ def dispatch(command, target, session)
202
+ case command
203
+ when 'image'
204
+ run_single_media(session, target, media_kind: :image)
205
+ when 'video'
206
+ run_single_media(session, target, media_kind: :video)
207
+ when 'media'
208
+ media = session.get_media(target, quality: @options[:quality])
209
+ emit_media_info(media)
210
+ 0
211
+ when 'search'
212
+ pins = session.search(target, limit: @options[:limit], type: @options[:type])
213
+ handle_pins(session, pins)
214
+ when 'board'
215
+ pins = session.board(target, limit: @options[:limit], type: @options[:type])
216
+ handle_pins(session, pins)
217
+ else
218
+ print_error("Unknown command '#{command}'", hint: 'Valid commands are: image, video, media, search, board')
219
+ 1
220
+ end
221
+ end
222
+
223
+ def run_single_media(session, target, media_kind:)
224
+ url = media_kind == :image ? session.get_image_url(target, quality: @options[:quality]) : session.get_video_url(target)
225
+ unless @options[:output]
226
+ if @options[:format] == :json
227
+ @out.puts JSON.pretty_generate({ type: media_kind, url: url })
228
+ elsif @options[:format] != :quiet
229
+ @out.puts url
230
+ end
231
+ return 0
232
+ end
233
+
234
+ dest_path = resolve_single_output_path(url, @options[:output], media_kind: media_kind)
235
+ label = File.basename(dest_path)
236
+ bar = build_byte_progress_bar(label: label, media_type: media_kind)
237
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
238
+ session.download(
239
+ url,
240
+ path: dest_path,
241
+ overwrite: !@options[:skip_existing],
242
+ resume: @options[:resume],
243
+ progress_bar: bar
244
+ )
245
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
246
+ emit_single_download_result(url, dest_path, media_kind, elapsed: elapsed)
247
+ 0
248
+ end
249
+
250
+ def resolve_single_output_path(url, explicit_output, media_kind:)
251
+ default_ext = media_kind == :video ? '.mp4' : '.jpg'
252
+ basename = extract_url_basename(url)
253
+ basename = "pinterest_#{media_kind}#{default_ext}" if basename.empty? || !basename.include?('.')
254
+
255
+ out_str = explicit_output.to_s.strip
256
+ if File.directory?(out_str) || out_str.end_with?('/', '\\') || out_str == '.'
257
+ File.join(out_str, basename)
258
+ else
259
+ out_str
260
+ end
261
+ end
262
+
263
+ def handle_pins(session, pins)
264
+ if pins.empty?
265
+ if @options[:format] == :json
266
+ @out.puts JSON.pretty_generate({ pins: [], count: 0 })
267
+ else
268
+ @err.puts 'No matching pins found' unless @options[:format] == :quiet
269
+ end
270
+ return 0
271
+ end
272
+
273
+ if @options[:type] == :pin
274
+ handle_pin_links(pins)
275
+ elsif @options[:output]
276
+ handle_batch_download(session, pins)
277
+ else
278
+ emit_pins_output(pins)
279
+ end
280
+ end
281
+
282
+ def handle_pin_links(pins)
283
+ links = pins.map { |p| p[:pin_url] }
284
+ if @options[:output]
285
+ FileUtils.mkdir_p(@options[:output])
286
+ out_file = File.join(@options[:output], 'pins.txt')
287
+ File.write(out_file, "#{links.join("\n")}\n")
288
+ if @options[:format] == :json
289
+ @out.puts JSON.pretty_generate({ saved: links.size, path: out_file, links: links })
290
+ elsif @options[:format] != :quiet
291
+ @out.puts "Saved #{links.size} pin links to #{out_file}"
292
+ end
293
+ elsif @options[:format] == :json
294
+ @out.puts JSON.pretty_generate(links)
295
+ elsif @options[:format] != :quiet
296
+ @out.puts links
297
+ end
298
+ 0
299
+ end
300
+
301
+ def handle_batch_download(session, pins)
302
+ selected = pins.first(@options[:limit])
303
+ items = selected.select do |p|
304
+ @options[:type] == :image ? p[:image_url] : (p[:video_url] || p[:image_url])
305
+ end
306
+
307
+ bar = ProgressBar.new(total: items.size, out: @err, enabled: show_progress?)
308
+ report = session.download_batch(
309
+ items,
310
+ dir: @options[:output],
311
+ concurrency: @options[:jobs],
312
+ overwrite: !@options[:skip_existing],
313
+ resume: @options[:resume]
314
+ ) do |done, _total, url|
315
+ kind = url.to_s.include?('.mp4') ? :video : :image
316
+ name = extract_url_basename(url)
317
+ bar.update(done, label: name, media_type: kind)
318
+ end
319
+
320
+ emit_batch_summary(report, items.size)
321
+ report[:succeeded].empty? && report[:failed].any? ? 1 : 0
322
+ end
323
+
324
+ def emit_single_download_result(url, path, media_kind, elapsed: 0.0)
325
+ size = File.exist?(path) ? File.size(path) : 0
326
+ case @options[:format]
327
+ when :json
328
+ @out.puts JSON.pretty_generate({
329
+ status: 'saved',
330
+ type: media_kind,
331
+ url: url,
332
+ path: path,
333
+ bytes: size,
334
+ elapsed_seconds: elapsed.round(2)
335
+ })
336
+ when :csv
337
+ @out.puts csv_line([media_kind, url, path, size])
338
+ when :text
339
+ badge = "[#{media_kind.to_s.upcase}]"
340
+ @out.puts "#{badge} Saved to #{path} (#{ProgressBar.format_bytes(size)} in #{elapsed.round(2)}s)"
341
+ end
342
+ end
343
+
344
+ def emit_media_info(media)
345
+ case @options[:format]
346
+ when :csv
347
+ @out.puts csv_line(%w[image_url video_url])
348
+ @out.puts csv_line([media[:image_url], media[:video_url]])
349
+ when :quiet
350
+ nil
351
+ else
352
+ @out.puts JSON.pretty_generate(media)
353
+ end
354
+ end
355
+
356
+ def emit_pins_output(pins)
357
+ case @options[:format]
358
+ when :csv
359
+ @out.puts csv_line(%w[id pin_url title creator image_url video_url])
360
+ pins.each do |p|
361
+ @out.puts csv_line([p[:id], p[:pin_url], p[:title], p[:creator], p[:image_url], p[:video_url]])
362
+ end
363
+ when :quiet
364
+ nil
365
+ else
366
+ @out.puts JSON.pretty_generate(pins)
367
+ end
368
+ 0
369
+ end
370
+
371
+ def emit_batch_summary(report, total_requested)
372
+ case @options[:format]
373
+ when :json
374
+ @out.puts report.to_json
375
+ when :csv
376
+ @out.puts csv_line(%w[succeeded skipped failed bytes_downloaded elapsed_seconds])
377
+ row = [
378
+ report[:succeeded].size,
379
+ report[:skipped].size,
380
+ report[:failed].size,
381
+ report.bytes_downloaded,
382
+ report.elapsed_seconds.round(2)
383
+ ]
384
+ @out.puts csv_line(row)
385
+ when :text
386
+ skipped_msg = report[:skipped]&.any? ? " (#{report[:skipped].size} skipped)" : ''
387
+ failed_msg = report[:failed]&.any? ? ", #{report[:failed].size} failed" : ''
388
+ bytes_str = ProgressBar.format_bytes(report.bytes_downloaded)
389
+ size_msg = report.bytes_downloaded.positive? ? " [#{bytes_str} in #{report.elapsed_seconds.round(1)}s]" : ''
390
+ summary = "Downloaded #{report[:succeeded].size}/#{total_requested} files to #{@options[:output]}"
391
+ @out.puts "#{summary}#{skipped_msg}#{failed_msg}#{size_msg}"
392
+ end
393
+ end
394
+
395
+ def build_byte_progress_bar(label:, media_type:)
396
+ ProgressBar.new(
397
+ total: 0,
398
+ width: 20,
399
+ out: @err,
400
+ enabled: show_progress?,
401
+ label: label,
402
+ media_type: media_type,
403
+ byte_mode: true
404
+ )
405
+ end
406
+
407
+ def show_progress?
408
+ @options[:progress] && !@options[:non_interactive] && @options[:format] != :json && @options[:format] != :quiet
409
+ end
410
+
411
+ def csv_line(fields)
412
+ row = fields.map do |field|
413
+ str = field.to_s
414
+ str.match?(/[,"\r\n]/) ? "\"#{str.gsub('"', '""')}\"" : str
415
+ end.join(',')
416
+ "#{row}\n"
417
+ end
418
+
419
+ def extract_url_basename(url)
420
+ File.basename(URI(url.to_s).path.to_s)
421
+ rescue URI::InvalidURIError
422
+ ''
423
+ end
424
+
425
+ def handle_domain_error(err)
426
+ hint = case err
427
+ when AuthenticationError
428
+ 'Pass a logged-in session cookie with `-c cookies.txt` or `-c "sessionid=..."`.'
429
+ when ForbiddenError
430
+ 'Pinterest rejected the request (HTTP 403). Check your cookies or try a different IP/proxy.'
431
+ when RateLimitError
432
+ wait_hint = err.retry_after ? " Wait #{err.retry_after}s or" : ''
433
+ "Rate limit reached (HTTP 429).#{wait_hint} reduce `-j/--jobs`."
434
+ when TimeoutError
435
+ 'Increase timeout with `--timeout 30` or configure a proxy with `--proxy`.'
436
+ when SSRFError, InvalidURLError
437
+ 'Provide a valid public Pinterest URL (e.g. https://www.pinterest.com/pin/...).'
438
+ when FileTooLargeError
439
+ 'Increase the maximum allowed file size with `--max-size 1G`.'
440
+ when DiskSpaceError
441
+ 'Check available disk space and write permissions on the output path.'
442
+ end
443
+ print_error(err.message, hint: hint)
444
+ end
445
+
446
+ def print_error(message, hint: nil)
447
+ if @options[:format] == :json
448
+ @err.puts JSON.generate({ error: message, hint: hint }.compact)
449
+ else
450
+ @err.puts "pinterest-dl: #{message}"
451
+ @err.puts " Hint: #{hint}" if hint
452
+ end
453
+ end
454
+ end
455
+ end