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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5479bf9ab2de703e527f4e9f9a4a4b3a1ec7dbb37557f52790c78ac66f863529
4
- data.tar.gz: b70ccb0ef0dcf62d5b30abffe40a1433d122619b8ed66903b7d26c4e0e7e67c8
3
+ metadata.gz: 7398ed88032d99ccf9ec27c2bf853984bf91033d985888eb2a1597eb27019558
4
+ data.tar.gz: 9e7ea146fc43ab2cebb4b909f3ba2b9f1852acfe4bb311b9c801e35a0c387581
5
5
  SHA512:
6
- metadata.gz: 02c4758ce34f5f99e1d8040d21dd8486d1c9f0ee53e86954847202150cbf2c49a7f98c6b9e71483a3b3869730c25a66a0418a56edd8e935342ec728b2f3a8ec9
7
- data.tar.gz: 410b3b760fe0f1e74651ea828b2164a90527f90a8a654448f260c2c0a2d4725e8e56bce04e7d8e56a867e057e46d16073d0f41da079ddc22fd3d15cfe9795a4d
6
+ metadata.gz: abdc20702fba9c5349231be78541fbb07607a66f40ef0a1a6bbec1dd7ed63ddc2217fe94a4d4b8c9b13a9290d7a9eb66d428cab407ddb375bbaa8a6f3aaa38df
7
+ data.tar.gz: 5b7adcb2e28adc9a7e35e6399bb730411e030bf636de331f87844754cb2668a720e99f8041f4d0661f70f0acad77b22b54b98cb6a9a41e420c9ddc06e9a4a069
data/CHANGELOG.md CHANGED
@@ -3,6 +3,32 @@
3
3
  All notable changes to this project are documented here.
4
4
  This project follows [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [2.4.0]
7
+
8
+ ### Security
9
+ - Added `PinterestDL::Security` with strict URL/host validation, SSRF protection against private, loopback, link-local, and metadata IP ranges (`SSRFError`), and rejection of embedded URL credentials.
10
+ - Added `PinterestDL::CookieJar` preserving `Domain`, `Path`, `Secure`, `HttpOnly`, and `Expires`/`Max-Age` attributes and strictly preventing cookies from being sent to CDN (`*.pinimg.com`), shortener (`pin.it`), or external hosts.
11
+ - Cross-domain redirects are now validated against trusted hosts (`RedirectError`) and strip sensitive headers (`Cookie`, `Authorization`, `X-CSRFToken`) when crossing security domains.
12
+ - Added `PinterestDL::MediaValidator` to verify HTTP `Content-Type` headers and binary file signatures (JPEG, PNG, GIF, WebP, MP4, WebM) and reject HTML/JSON error pages disguised as media (`InvalidMediaError`).
13
+ - Enforced configurable maximum download file size (`config.max_file_size`, default 500 MB, or `--max-size` on the CLI) with `FileTooLargeError`.
14
+ - Logger output automatically redacts cookies, CSRF tokens, session IDs, and proxy passwords.
15
+
16
+ ### Added
17
+ - `PinterestDL::Session` (`PinterestDL.session`) for fully isolated per-client configuration and cookie jars without global state interference.
18
+ - `PinterestDL::Transport` layer with exponential backoff and random jitter (`retry_jitter`, `max_retry_wait`), plus full support for both integer and HTTP-date `Retry-After` headers.
19
+ - `PinterestDL::Paginator` for unified cursor/bookmark pagination across `Search` and `Board`, with duplicate bookmark cycle detection and `Enumerable` support.
20
+ - `PinterestDL::Pin` and `PinterestDL::DownloadReport` models supporting both object-oriented methods and Hash `[]`/`dig` access.
21
+ - Resumable downloads (`Range: bytes=N-` with HTTP `206 Partial Content`) via `resume: true` and `--resume`/`--no-resume`.
22
+ - Download speed throttling (`max_speed:` / `--max-speed`, e.g. `500K`, `2M`), batch URL deduplication (`deduplicate: true`), smart filename collision handling (`collision_strategy: :rename`), and disk space / write-permission error handling (`DiskSpaceError`).
23
+ - Live byte-level `ProgressBar` showing percentage, received/total bytes, download speed, ETA, and media type badge (`[IMAGE]` / `[VIDEO]`), with `--no-progress` and `--non-interactive` flags.
24
+ - Extracted CLI logic into `PinterestDL::CLI` (`lib/pinterest_dl/cli.rb`) with `--format text|json|csv|quiet`, `--json`, `--images-only`, `--videos-only`, and actionable error hints.
25
+ - Expanded error hierarchy: `ForbiddenError` (distinct from `RateLimitError`), `TimeoutError`, `ConnectionError`, `SSLError`, `RedirectError`, `SSRFError`, `InvalidResponseError`, `FileTooLargeError`, `IncompleteDownloadError`, `InvalidMediaError`, and `DiskSpaceError`.
26
+
27
+ ### Fixed
28
+ - `Extractors::PinData.best_image_url` now ranks image variants by resolution area and bucket priority instead of relying on hash insertion order.
29
+ - Added support for `__NEXT_DATA__`, `window.__INITIAL_STATE__`, `srcset`, and `<video>`/`<source>` fallbacks when extracting media from HTML.
30
+ - Fixed race conditions and thread exception propagation in `Downloader#download_batch`, and verified `Content-Length` to detect truncated downloads (`IncompleteDownloadError`).
31
+
6
32
  ## [2.3.0]
7
33
 
8
34
  ### Added
data/README.md CHANGED
@@ -6,24 +6,23 @@
6
6
  [![Gem Downloads](https://img.shields.io/gem/dt/pinterest-dl)](https://rubygems.org/gems/pinterest-dl)
7
7
  [![CI](https://github.com/monji024/pinterest-dl/actions/workflows/ci.yml/badge.svg)](https://github.com/monji024/pinterest-dl/actions/workflows/ci.yml)
8
8
  [![License](https://img.shields.io/badge/License-WTFPL-blue)](LICENSE)
9
- [![Ruby](https://img.shields.io/badge/Ruby-2.7+-red)](https://www.ruby-lang.org/)
9
+ [![Ruby](https://img.shields.io/badge/Ruby-3.0+-red)](https://www.ruby-lang.org/)
10
10
 
11
11
  <img src="https://img.icons8.com/color/96/000000/pinterest--v1.png" width="80">
12
12
 
13
- > **Note:** Users in some regions (e.g. Iran) may need a fu*king VPN to reach Pinterest.
14
- > (Yeah, because even in 2026 Pinterest still gives you the middle finger on clean APIs.)
13
+ > **Note:** Users in some regions (e.g. Iran) may need a VPN or proxy (`--proxy`) to reach Pinterest.
15
14
 
16
- Pinterest doesn't give you a clean, official API for getting a direct media URL out of a pin, walking a board, or downloading a batch of images. `pinterest-dl` does that: point it at a pin, a search query, or a board, and get back real `i.pinimg.com` / `v.pinimg.com` URLs — or the fucking files themselves, already saved to disk.
15
+ Pinterest doesn't give you a clean, official API for getting a direct media URL out of a pin, walking a board, or downloading a batch of images. `pinterest-dl` does that: point it at a pin, a search query, or a board, and get back real `i.pinimg.com` / `v.pinimg.com` URLs — or save the files straight to disk.
17
16
 
18
17
  ## What it does
19
18
 
20
19
  - Pulls the **direct image or video URL** out of a single pin page (including `pin.it` short links and country domains).
21
- - **Searches** Pinterest and returns pin metadata (id, url, title, description, creator, image/video URL), with automatic pagination.
20
+ - **Searches** Pinterest and returns pin metadata (`id`, `pin_url`, `title`, `description`, `creator`, `image_url`, `video_url`), with automatic cursor pagination and duplicate detection.
22
21
  - Fetches all pins from a **board** (or a specific board section).
23
- - **Downloads** a URL or a whole batch in parallel (multi-threaded, written to `.part` files first so interrupted runs don't leave broken files on disk).
24
- - Supports **authenticated requests** via raw cookie strings or a Netscape `cookies.txt` file, for boards/pins that require a logged-in session.
25
- - Raises **specific, catchable exceptions** (`NotFoundError`, `RateLimitError`, `NetworkError`, ...) instead of returning `nil` or printing to stdout.
26
- - Ships a **CLI** (`pinterest-dl`) for one-off use from the shell.
22
+ - **Downloads** single files or parallel batches with live progress bars (percentage, bytes, speed, ETA), HTTP `Range` resume, bandwidth throttling, content-type/magic-byte verification, max file size limits, and automatic deduplication.
23
+ - Provides **isolated sessions** (`PinterestDL.session`) alongside global configuration, with domain-scoped `CookieJar` protection, cross-domain redirect guards, SSRF prevention, and automatic log redaction.
24
+ - Raises **specific, catchable exceptions** (`NotFoundError`, `ForbiddenError`, `RateLimitError`, `AuthenticationError`, `TimeoutError`, `SSRFError`, `FileTooLargeError`, `IncompleteDownloadError`, `InvalidMediaError`, ...) instead of returning `nil`.
25
+ - Ships a full-featured **CLI** (`pinterest-dl`) with `text`, `json`, `csv`, and `quiet` output modes.
27
26
 
28
27
  ## Installation
29
28
 
@@ -59,14 +58,29 @@ PinterestDL.download(
59
58
 
60
59
  ## Usage
61
60
 
61
+ ### Isolated Sessions
62
+
63
+ Create independent sessions with their own cookies, timeouts, and settings without mutating global state:
64
+
65
+ ```ruby
66
+ session = PinterestDL.session(
67
+ cookies: File.expand_path('~/cookies.txt'),
68
+ quality: :'1200x',
69
+ concurrency: 6,
70
+ max_speed: '2M'
71
+ )
72
+
73
+ pins = session.board('https://www.pinterest.com/username/board-name/', limit: 50)
74
+ report = session.download_batch(pins, dir: './downloads')
75
+ ```
76
+
62
77
  ### Get image / video URLs
63
78
 
64
79
  ```ruby
65
80
  url = PinterestDL.get_image_url('https://www.pinterest.com/pin/example/')
66
81
 
67
- # Pick a specific size bucket
82
+ # Pick a specific size bucket (:originals, :"1200x", :"736x", :"564x", :"474x", :"236x")
68
83
  url = PinterestDL.get_image_url('https://www.pinterest.com/pin/example/', quality: :"736x")
69
- # quality can be :originals, :"1200x", :"736x", :"564x", :"474x", :"236x"
70
84
 
71
85
  url = PinterestDL.get_video_url('https://www.pinterest.com/pin/example/')
72
86
 
@@ -75,148 +89,97 @@ media = PinterestDL.get_media('https://www.pinterest.com/pin/example/')
75
89
  # => { image_url: "https://i.pinimg.com/...", video_url: nil }
76
90
  ```
77
91
 
78
- ### Search
92
+ ### Search & Boards
79
93
 
80
94
  ```ruby
81
- results = PinterestDL.search('nature landscape', limit: 10)
82
- # => [{ id: "...", pin_url: "...", title: "...", description: "...", creator: "...", image_url: "...", video_url: nil }, ...]
83
-
84
- # Page count scales with limit, or cap it yourself with pages:
85
- results = PinterestDL.search('nature landscape', limit: 150)
95
+ results = PinterestDL.search('nature landscape', limit: 25)
86
96
  video_pins = PinterestDL.search('motion graphics', limit: 20, type: :video)
87
97
 
88
98
  images = PinterestDL.search_images('sunset', limit: 5)
89
- # => ["https://i.pinimg.com/originals/...", ...]
90
-
91
99
  videos = PinterestDL.search_videos('tutorial', limit: 3)
92
- # => ["https://v.pinimg.com/videos/...", ...]
93
100
 
94
- json_results = PinterestDL.search_json('anime art', limit: 20)
95
- ```
96
-
97
- ### Boards & sections
98
-
99
- ```ruby
100
- # All pins on a board
101
+ # Boards and board sections
101
102
  pins = PinterestDL.board('https://www.pinterest.com/username/board-name/', limit: 100)
102
-
103
- # Only videos from a board
104
- videos = PinterestDL.board('https://www.pinterest.com/username/board-name/', limit: 50, type: :video)
105
-
106
- # A specific section within a board
107
- pins = PinterestDL.board('https://www.pinterest.com/username/board-name/section-slug/', limit: 50)
103
+ section_pins = PinterestDL.board('https://www.pinterest.com/username/board-name/section-slug/', limit: 50)
108
104
  ```
109
105
 
110
106
  ### Downloading
111
107
 
112
108
  ```ruby
113
- # Single file
114
- PinterestDL.download('https://i.pinimg.com/originals/aa/bb/cc/img.jpg', path: 'out/img.jpg')
115
-
116
- # Skip if already on disk
117
- PinterestDL.download(url, path: 'out/img.jpg', overwrite: false)
109
+ # Single file with resume, max size, and speed limit
110
+ PinterestDL.download(
111
+ 'https://i.pinimg.com/originals/aa/bb/cc/img.jpg',
112
+ path: 'out/img.jpg',
113
+ resume: true,
114
+ max_size: 100 * 1024 * 1024,
115
+ max_speed: '1.5M'
116
+ )
118
117
 
119
- # Batch download (returns { succeeded: [...], failed: [{ url:, error: }, ...], skipped: [...] })
118
+ # Batch download (returns a PinterestDL::DownloadReport, compatible with Hash access)
120
119
  urls = PinterestDL.search_images('mountains', limit: 40)
121
- result = PinterestDL.download_batch(urls, dir: './downloads', concurrency: 6, overwrite: false)
122
-
123
- # With progress reporting
124
- bar = PinterestDL::ProgressBar.new(total: urls.size, out: $stderr)
125
- PinterestDL.download_batch(urls, dir: './downloads') do |done, total, url|
126
- bar.update(done)
127
- end
128
- ```
129
-
130
- ### Cookies / authenticated sessions
131
-
132
- Some boards and pins require a logged-in session to view. Pass your browser's Pinterest cookies (either a raw string or a Netscape `cookies.txt` path) through global configuration:
120
+ report = PinterestDL.download_batch(
121
+ urls,
122
+ dir: './downloads',
123
+ concurrency: 6,
124
+ overwrite: false,
125
+ resume: true,
126
+ deduplicate: true,
127
+ collision_strategy: :rename
128
+ )
133
129
 
134
- ```ruby
135
- PinterestDL.configure do |c|
136
- c.cookies = 'sessionid=...; csrftoken=...' # yeah, steal your own fucking session if you have to
137
- # c.cookies = File.expand_path('~/cookies.txt')
138
- c.user_agent = 'Mozilla/5.0 ...' # optional override
139
- end
130
+ puts "Downloaded: #{report.succeeded.size}, Failed: #{report.failed.size}, Bytes: #{report.bytes_downloaded}"
140
131
  ```
141
132
 
142
- ### Other configuration
133
+ ### Configuration
143
134
 
144
135
  ```ruby
145
136
  PinterestDL.configure do |c|
146
- c.open_timeout = 10 # seconds, connection open timeout
147
- c.read_timeout = 20 # seconds, response read timeout
148
- c.write_timeout = 20 # seconds, request write timeout
149
- c.max_retries = 3 # retries on transient network / 429 / 5xx failures
150
- c.retry_wait = 1.0 # base seconds between retries
151
- c.rate_limit_interval = 0.5 # minimum seconds between outgoing requests
152
- c.concurrency = 4 # parallel worker threads for download_batch
153
- c.overwrite = true # set false to skip existing files
154
- c.proxy = nil # HTTP/HTTPS proxy URL (defaults to ENV)
155
- c.quality = :originals # default image quality
156
- c.max_cache_entries = 256 # in-memory GET cache cap
157
- c.logger.level = Logger::INFO # library uses this Logger instead of puts
158
- end
159
- ```
160
-
161
- ### Error handling
162
-
163
- Every method raises a subclass of `PinterestDL::Error` instead of returning `nil` or printing to the console:
164
-
165
- ```ruby
166
- begin
167
- PinterestDL.get_image_url('https://www.pinterest.com/pin/does-not-exist/')
168
- rescue PinterestDL::NotFoundError
169
- # pin/board/search had nothing to extract
170
- rescue PinterestDL::RateLimitError => e
171
- # Pinterest throttled us; e.retry_after may hold a hint
172
- rescue PinterestDL::AuthenticationError
173
- # the resource needs c.cookies to be set
174
- rescue PinterestDL::NetworkError => e
175
- # DNS/timeout/connection-level failure; e.cause_error has the original exception
176
- rescue PinterestDL::InvalidURLError
177
- # the given string isn't a Pinterest pin/board URL
178
- rescue PinterestDL::DownloadError
179
- # disk or stream failure while saving a file
180
- rescue PinterestDL::Error
181
- # catch-all for anything above
137
+ c.cookies = File.expand_path('~/cookies.txt')
138
+ c.open_timeout = 10
139
+ c.read_timeout = 20
140
+ c.write_timeout = 20
141
+ c.max_retries = 3
142
+ c.retry_wait = 1.0
143
+ c.max_retry_wait = 30.0
144
+ c.retry_jitter = 0.25
145
+ c.rate_limit_interval = 0.5
146
+ c.concurrency = 4
147
+ c.overwrite = true
148
+ c.resume = true
149
+ c.deduplicate = true
150
+ c.collision_strategy = :rename
151
+ c.max_file_size = 500 * 1024 * 1024
152
+ c.max_speed = nil
153
+ c.verify_content_type = true
154
+ c.proxy = nil
155
+ c.quality = :originals
156
+ c.max_cache_entries = 256
182
157
  end
183
158
  ```
184
159
 
185
160
  ### CLI
186
161
 
187
162
  ```bash
188
- pinterest-dl image https://www.pinterest.com/pin/example/
189
163
  pinterest-dl image https://www.pinterest.com/pin/example/ -o pin.jpg
190
- pinterest-dl video https://www.pinterest.com/pin/example/ -o pin.mp4
191
- pinterest-dl media https://www.pinterest.com/pin/example/
192
- pinterest-dl search "cyberpunk city" -n 20
164
+ pinterest-dl video https://www.pinterest.com/pin/example/ -o pin.mp4 --max-speed 2M
165
+ pinterest-dl media https://www.pinterest.com/pin/example/ --json
193
166
  pinterest-dl search "cyberpunk city" -n 50 -j 8 -o ./downloads
194
167
  pinterest-dl board https://www.pinterest.com/username/board-name/ -n 100 -j 6 -s -o ./downloads
195
- pinterest-dl board https://www.pinterest.com/username/board-name/ -t video -o ./videos
196
- pinterest-dl search "cats" -t image -n 30 -o ./images
197
- pinterest-dl search "cats" -t pin -n 30
198
- pinterest-dl board https://www.pinterest.com/username/secret/ -c ~/cookies.txt --proxy http://127.0.0.1:10809 -o ./secret
199
- pinterest-dl --help
168
+ pinterest-dl board https://www.pinterest.com/username/board-name/ --videos-only -o ./videos
169
+ pinterest-dl search "cats" --images-only -n 30 --format json
170
+ pinterest-dl board https://www.pinterest.com/username/secret/ -c ~/cookies.txt --no-progress -o ./secret
200
171
  ```
201
172
 
202
- Flags: `-o/--output`, `-n/--limit`, `-t/--type` (`all`, `image`, `video`, `pin`), `-q/--quality`, `-c/--cookies`, `-j/--jobs`, `-s/--skip-existing`, `--proxy`, `--timeout`, `--retries`, `-v/--verbose`, `--version`.
203
-
204
173
  ## Development
205
174
 
206
175
  ```bash
207
176
  bundle install
208
- bundle exec rake test # run the test suite
209
- bundle exec rake rubocop # lint
210
- bundle exec rake # both (default task)
177
+ bundle exec rake test # run the test suite
178
+ bundle exec rake coverage # run tests with SimpleCov coverage
179
+ bundle exec rake rubocop # lint
180
+ bundle exec rake # test + rubocop
211
181
  ```
212
182
 
213
- ## Links
214
-
215
- - [RubyGems](https://rubygems.org/gems/pinterest-dl)
216
- - [GitHub](https://github.com/monji024/pinterest-dl)
217
- - [Changelog](CHANGELOG.md)
218
- - [Issue tracker](https://github.com/monji024/pinterest-dl/issues)
219
-
220
183
  ## License
221
184
 
222
185
  WTFPL — [monji024](https://github.com/monji024)
data/bin/pinterest-dl CHANGED
@@ -2,166 +2,5 @@
2
2
  # frozen_string_literal: true
3
3
 
4
4
  require_relative '../lib/pinterest-dl'
5
- require 'optparse'
6
5
 
7
- def usage
8
- <<~USAGE
9
- pinterest-dl v#{PinterestDL::VERSION}
10
-
11
- Usage:
12
- pinterest-dl image URL [-q QUALITY] [-o FILE]
13
- pinterest-dl video URL [-o FILE]
14
- pinterest-dl media URL [-q QUALITY]
15
- pinterest-dl search QUERY [-n LIMIT] [-t TYPE] [-q QUALITY] [-j JOBS] [-o DIR]
16
- pinterest-dl board URL [-n LIMIT] [-t TYPE] [-q QUALITY] [-j JOBS] [-o DIR]
17
-
18
- Options:
19
- -o, --output PATH File (image/video) or directory (search/board) to save to
20
- -n, --limit N Max number of results (search/board), default 25
21
- -t, --type TYPE What to collect in search/board: all, image, video, pin (default all)
22
- -q, --quality Q Image quality: originals, 1200x, 736x, 564x, 474x, 236x (default originals)
23
- -c, --cookies STR|FILE Cookie header string or Netscape cookies.txt file path
24
- -j, --jobs N Parallel download workers for batch downloads (default 4)
25
- -s, --skip-existing Skip files that already exist on disk
26
- --proxy URL HTTP/HTTPS proxy URL
27
- --timeout SEC Network read/open timeout in seconds
28
- --retries N Max retries on transient failures (default 3)
29
- -v, --verbose Enable debug logging
30
- --version Print version and exit
31
- -h, --help Show this help
32
- USAGE
33
- end
34
-
35
- options = {
36
- limit: 25,
37
- quality: :originals,
38
- type: :all,
39
- jobs: 4,
40
- skip_existing: false,
41
- verbose: false
42
- }
43
-
44
- parser = OptionParser.new do |opts|
45
- opts.on('-o PATH', '--output PATH') { |v| options[:output] = v }
46
- opts.on('-n N', '--limit N', Integer) { |v| options[:limit] = v }
47
- opts.on('-t T', '--type T') { |v| options[:type] = v.to_sym }
48
- opts.on('-q Q', '--quality Q') { |v| options[:quality] = v.to_sym }
49
- opts.on('-c STR', '--cookies STR') { |v| options[:cookies] = v }
50
- opts.on('-j N', '--jobs N', Integer) { |v| options[:jobs] = v }
51
- opts.on('-s', '--skip-existing') { options[:skip_existing] = true }
52
- opts.on('--proxy URL') { |v| options[:proxy] = v }
53
- opts.on('--timeout SEC', Integer) { |v| options[:timeout] = v }
54
- opts.on('--retries N', Integer) { |v| options[:retries] = v }
55
- opts.on('-v', '--verbose') { options[:verbose] = true }
56
- opts.on('--version') do
57
- puts PinterestDL::VERSION
58
- exit 0
59
- end
60
- opts.on('-h', '--help') do
61
- puts usage
62
- exit 0
63
- end
64
- end
65
-
66
- begin
67
- parser.parse!(ARGV)
68
- rescue OptionParser::ParseError => e
69
- warn "pinterest-dl: #{e.message}"
70
- exit 1
71
- end
72
-
73
- command = ARGV.shift
74
- target = ARGV.shift
75
-
76
- if command.nil? || target.nil?
77
- puts usage
78
- exit(command.nil? ? 0 : 1)
79
- end
80
-
81
- def die(message, code = 1)
82
- warn "pinterest-dl: #{message}"
83
- exit code
84
- end
85
-
86
- def handle_pins(pins, options)
87
- if pins.empty?
88
- warn 'No matching pins found'
89
- return
90
- end
91
-
92
- if options[:type] == :pin
93
- links = pins.map { |p| p[:pin_url] }
94
- if options[:output]
95
- FileUtils.mkdir_p(options[:output])
96
- out_file = File.join(options[:output], 'pins.txt')
97
- File.write(out_file, "#{links.join("\n")}\n")
98
- puts "Saved #{links.size} pin links to #{out_file}"
99
- else
100
- puts links
101
- end
102
- elsif options[:output]
103
- urls = pins.filter_map do |p|
104
- options[:type] == :image ? p[:image_url] : (p[:video_url] || p[:image_url])
105
- end
106
- bar = PinterestDL::ProgressBar.new(total: urls.size, out: $stderr)
107
- result = PinterestDL.download_batch(
108
- urls,
109
- dir: options[:output],
110
- concurrency: options[:jobs],
111
- overwrite: !options[:skip_existing]
112
- ) { |done, _total, _| bar.update(done) }
113
- skipped_msg = result[:skipped]&.any? ? " (#{result[:skipped].size} skipped)" : ''
114
- puts "Downloaded #{result[:succeeded].size}/#{urls.size} files to #{options[:output]}#{skipped_msg}"
115
- exit 1 if result[:succeeded].empty? && result[:failed].any?
116
- else
117
- puts JSON.pretty_generate(pins)
118
- end
119
- end
120
-
121
- begin
122
- PinterestDL.configure do |c|
123
- c.cookies = options[:cookies] if options[:cookies]
124
- c.quality = options[:quality] if options[:quality]
125
- c.concurrency = options[:jobs] if options[:jobs]
126
- c.overwrite = !options[:skip_existing]
127
- c.proxy = options[:proxy] if options[:proxy]
128
- if options[:timeout]
129
- c.open_timeout = options[:timeout]
130
- c.read_timeout = options[:timeout]
131
- end
132
- c.max_retries = options[:retries] if options[:retries]
133
- c.logger.level = Logger::DEBUG if options[:verbose]
134
- end
135
-
136
- case command
137
- when 'image'
138
- url = PinterestDL.get_image_url(target, quality: options[:quality])
139
- if options[:output]
140
- PinterestDL.download(url, path: options[:output], overwrite: !options[:skip_existing])
141
- puts "Saved to #{options[:output]}"
142
- else
143
- puts url
144
- end
145
- when 'video'
146
- url = PinterestDL.get_video_url(target)
147
- if options[:output]
148
- PinterestDL.download(url, path: options[:output], overwrite: !options[:skip_existing])
149
- puts "Saved to #{options[:output]}"
150
- else
151
- puts url
152
- end
153
- when 'media'
154
- puts JSON.pretty_generate(PinterestDL.get_media(target, quality: options[:quality]))
155
- when 'search'
156
- handle_pins(PinterestDL.search(target, limit: options[:limit], type: options[:type]), options)
157
- when 'board'
158
- handle_pins(PinterestDL.board(target, limit: options[:limit], type: options[:type]), options)
159
- else
160
- die "unknown command '#{command}'\n\n#{usage}"
161
- end
162
- rescue Interrupt
163
- warn "\npinterest-dl: interrupted"
164
- exit 130
165
- rescue PinterestDL::Error, ArgumentError => e
166
- die e.message
167
- end
6
+ exit(PinterestDL::CLI.run(ARGV))
data/lib/pinterest-dl.rb CHANGED
@@ -1,11 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
-
4
3
  require 'json'
5
4
  require_relative 'pinterest_dl/version'
6
5
  require_relative 'pinterest_dl/errors'
6
+ require_relative 'pinterest_dl/security'
7
+ require_relative 'pinterest_dl/cookie_jar'
7
8
  require_relative 'pinterest_dl/configuration'
9
+ require_relative 'pinterest_dl/models'
10
+ require_relative 'pinterest_dl/media_validator'
11
+ require_relative 'pinterest_dl/transport'
8
12
  require_relative 'pinterest_dl/client'
13
+ require_relative 'pinterest_dl/paginator'
9
14
  require_relative 'pinterest_dl/media_type'
10
15
  require_relative 'pinterest_dl/extractors/image'
11
16
  require_relative 'pinterest_dl/extractors/video'
@@ -14,7 +19,9 @@ require_relative 'pinterest_dl/search'
14
19
  require_relative 'pinterest_dl/board'
15
20
  require_relative 'pinterest_dl/downloader'
16
21
  require_relative 'pinterest_dl/progress_bar'
22
+ require_relative 'pinterest_dl/session'
17
23
  require_relative 'pinterest_dl/api'
24
+ require_relative 'pinterest_dl/cli'
18
25
 
19
26
  module PinterestDL
20
27
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PinterestDL
4
- PIN_URL_PATTERN = %r{(pinterest\.[a-z.]+/pin/|pin\.it/)}i.freeze
4
+ PIN_URL_PATTERN = %r{\Ahttps?://(?:[a-z0-9-]+\.)*(?:pinterest\.(?:com|[a-z]{2,3}(?:\.[a-z]{2})?)/pin/|pin\.it/)}i
5
5
 
6
6
  class << self
7
7
  def config
@@ -9,10 +9,20 @@ module PinterestDL
9
9
  end
10
10
 
11
11
  def configure
12
- yield config
12
+ yield config if block_given?
13
13
  config
14
14
  end
15
15
 
16
+ def reset_config!
17
+ config.reset!
18
+ end
19
+
20
+ def session(**options, &block)
21
+ sess = Session.new(**options)
22
+ sess.configure(&block) if block
23
+ sess
24
+ end
25
+
16
26
  def logger
17
27
  config.logger
18
28
  end
@@ -21,7 +31,7 @@ module PinterestDL
21
31
  html, pin_id = load_pin(pin_url, client)
22
32
  url = extract_pin_image(html, pin_id, quality: quality)
23
33
  url ||= api_image_url(pin_id, client, quality)
24
- raise NotFoundError, "No image found at #{pin_url}" unless url
34
+ raise NotFoundError.new("No image found at #{pin_url}", url: pin_url) unless url
25
35
 
26
36
  url
27
37
  end
@@ -38,7 +48,7 @@ module PinterestDL
38
48
  end
39
49
 
40
50
  hint = pin && pin[:image_url] ? ' (it looks like an image pin, try the image command)' : ''
41
- raise NotFoundError, "No video found at #{pin_url}#{hint}"
51
+ raise NotFoundError.new("No video found at #{pin_url}#{hint}", url: pin_url)
42
52
  end
43
53
 
44
54
  def get_media(pin_url, quality: config.quality, client: Client.new(config: config))
@@ -53,47 +63,58 @@ module PinterestDL
53
63
  { image_url: image, video_url: video }
54
64
  end
55
65
 
56
- def download(url, path:, overwrite: nil)
57
- Downloader.new(config: config).download(url, path: path, overwrite: overwrite)
66
+ def download(url, path:, overwrite: nil, client: nil, **options, &progress)
67
+ active_client = client || Client.new(config: config)
68
+ Downloader.new(client: active_client, config: config).download(
69
+ url,
70
+ path: path,
71
+ overwrite: overwrite,
72
+ **options,
73
+ &progress
74
+ )
58
75
  end
59
76
 
60
- def download_batch(urls, dir:, filename: nil, concurrency: nil, overwrite: nil, &progress)
61
- Downloader.new(config: config).download_batch(
77
+ def download_batch(urls, dir:, filename: nil, concurrency: nil, overwrite: nil, client: nil, **options, &progress)
78
+ active_client = client || Client.new(config: config)
79
+ Downloader.new(client: active_client, config: config).download_batch(
62
80
  urls,
63
81
  dir: dir,
64
82
  filename: filename,
65
83
  concurrency: concurrency,
66
84
  overwrite: overwrite,
85
+ **options,
67
86
  &progress
68
87
  )
69
88
  end
70
89
 
71
- def search(query, limit: 25, pages: nil, type: :all, client: Client.new(config: config))
90
+ def search(query, limit: 25, pages: nil, type: :all, client: nil, config: self.config)
72
91
  type = MediaType.parse(type)
92
+ active_client = client || Client.new(config: config)
73
93
  needed_pages = (limit.to_f / 25).ceil + 2
74
94
  effective_pages = pages || [needed_pages, 5].max
75
95
  effective_pages = [effective_pages, 15].max unless type == :all
76
- Search.new(client: client, config: config).call(query, limit: limit, pages: effective_pages, type: type)
96
+ Search.new(client: active_client, config: config).call(query, limit: limit, pages: effective_pages, type: type)
77
97
  end
78
98
 
79
- def search_json(query, limit: 25)
80
- JSON.pretty_generate(search(query, limit: limit))
99
+ def search_json(query, limit: 25, **options)
100
+ JSON.pretty_generate(search(query, limit: limit, **options))
81
101
  end
82
102
 
83
- def search_images(query, limit: 25)
84
- search(query, limit: limit, type: :image).filter_map { |p| p[:image_url] }
103
+ def search_images(query, limit: 25, **options)
104
+ search(query, limit: limit, type: :image, **options).filter_map { |p| p[:image_url] }
85
105
  end
86
106
 
87
- def search_videos(query, limit: 25)
88
- search(query, limit: limit, type: :video).filter_map { |p| p[:video_url] }
107
+ def search_videos(query, limit: 25, **options)
108
+ search(query, limit: limit, type: :video, **options).filter_map { |p| p[:video_url] }
89
109
  end
90
110
 
91
- def board(board_url, limit: 50, pages: nil, type: :all, client: Client.new(config: config))
111
+ def board(board_url, limit: 50, pages: nil, type: :all, client: nil, config: self.config)
92
112
  type = MediaType.parse(type)
113
+ active_client = client || Client.new(config: config)
93
114
  needed_pages = (limit.to_f / Board::PAGE_SIZE).ceil + 2
94
115
  effective_pages = pages || [needed_pages, 10].max
95
116
  effective_pages = [effective_pages, 20].max unless type == :all
96
- Board.new(client: client, config: config).call(board_url, limit: limit, pages: effective_pages, type: type)
117
+ Board.new(client: active_client, config: config).call(board_url, limit: limit, pages: effective_pages, type: type)
97
118
  end
98
119
 
99
120
  private
@@ -128,7 +149,7 @@ module PinterestDL
128
149
  video_url: Extractors::PinData.first_video_url(pin)
129
150
  }
130
151
  rescue PinterestDL::Error, JSON::ParserError => e
131
- logger.debug("PinResource failed for pin #{pin_id}: #{e.message}")
152
+ logger.debug(Security.redact("PinResource failed for pin #{pin_id}: #{e.message}"))
132
153
  nil
133
154
  end
134
155
 
@@ -162,9 +183,13 @@ module PinterestDL
162
183
  end
163
184
 
164
185
  def validate_pin_url!(pin_url)
165
- return if pin_url.to_s.match?(PIN_URL_PATTERN)
186
+ str = pin_url.to_s.strip
187
+ raise InvalidURLError.new("Not a Pinterest pin URL: #{pin_url.inspect}", url: pin_url) unless str.match?(PIN_URL_PATTERN)
166
188
 
167
- raise InvalidURLError, "Not a Pinterest pin URL: #{pin_url.inspect}"
189
+ uri = URI.parse(str)
190
+ raise InvalidURLError.new("Credentials not allowed in URL: #{pin_url.inspect}", url: pin_url) if uri.user || uri.password
191
+ rescue URI::InvalidURIError => e
192
+ raise InvalidURLError.new("Not a Pinterest pin URL: #{pin_url.inspect}", url: pin_url, cause_error: e)
168
193
  end
169
194
  end
170
- end
195
+ end