pinterest-dl 2.1.5 → 2.3.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: 51b7122dcca9ae653e0f63a70665fa8b5dfddd87a9d7e17eeef3462843ed90c1
4
- data.tar.gz: e82c0d139c5bf84dfd5e13fa96488d8013636f72ce7e2bdc5bc9a8efc49151cc
3
+ metadata.gz: 5479bf9ab2de703e527f4e9f9a4a4b3a1ec7dbb37557f52790c78ac66f863529
4
+ data.tar.gz: b70ccb0ef0dcf62d5b30abffe40a1433d122619b8ed66903b7d26c4e0e7e67c8
5
5
  SHA512:
6
- metadata.gz: 911490799bd9db4405781306091bbe06271413e25b834190d46394ad7b288be5ce3153ba25d9261122dbb4efe0be08188c49583751999d08e87be223a017300e
7
- data.tar.gz: f18ffdcc24defdbf6bb392f738ed6b6dc62047ccecacfb90eb90fb52a879b18dd84c7677288d538f8105ecae7e611faec6470a0dfeaedb07f8767d9e822c0e20
6
+ metadata.gz: 02c4758ce34f5f99e1d8040d21dd8486d1c9f0ee53e86954847202150cbf2c49a7f98c6b9e71483a3b3869730c25a66a0418a56edd8e935342ec728b2f3a8ec9
7
+ data.tar.gz: 410b3b760fe0f1e74651ea828b2164a90527f90a8a654448f260c2c0a2d4725e8e56bce04e7d8e56a867e057e46d16073d0f41da079ddc22fd3d15cfe9795a4d
data/CHANGELOG.md CHANGED
@@ -3,6 +3,35 @@
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.3.0]
7
+
8
+ ### Added
9
+ - `download_batch` now runs downloads in parallel using a thread pool (default 4 workers, configurable via `config.concurrency` or `-j/--jobs` on the CLI).
10
+ - `cookies` in `PinterestDL.configure` (and `-c/--cookies` on the CLI) now accepts a path to a Netscape `cookies.txt` file in addition to a raw `key=val; ...` cookie string.
11
+ - Added `1200x` and `564x` image quality buckets alongside `originals`, `736x`, `474x`, and `236x`.
12
+ - `overwrite: false` on `download` / `download_batch` and `-s/--skip-existing` on the CLI to skip files that are already on disk when resuming a big board or search dump.
13
+ - HTTP/HTTPS proxy support via `config.proxy` (defaults to `HTTPS_PROXY` / `HTTP_PROXY` env vars) and `--proxy` on the CLI, plus `--timeout` and `--retries` flags.
14
+ - `Client#stream_get` for streaming large video responses straight to disk instead of buffering the whole file in memory.
15
+
16
+ ### Fixed
17
+ - `search` and `board` had a hardcoded default of 5 and 10 pages, so passing `-n 200` on the CLI silently stopped around ~125 pins. Page count now scales automatically with `limit` unless `pages:` is passed explicitly.
18
+ - Downloads now write to a temporary `.part` file first and atomically rename on completion, so a dropped connection or `Ctrl-C` mid-download doesn't leave half-written corrupt files behind.
19
+ - `Client` only retried socket-level exceptions (`SocketError`, `Timeout::Error`, etc.) and immediately blew up on HTTP 429 or 502/503/504. Transient HTTP status codes are now retried too, respecting `Retry-After` when Pinterest sends one.
20
+ - `Extractors::Image` missed numbered CDN hosts like `i0.pinimg.com` and `i1.pinimg.com` and didn't rewrite non-standard dimension buckets (e.g. `600x315`) when switching quality.
21
+ - `Client` cache and cookie jar access are now guarded by a mutex so concurrent workers don't race each other, rate-limit throttling uses `CLOCK_MONOTONIC` instead of wall-clock `Time.now`, and the in-memory cache is capped (`max_cache_entries`, default 256) so long-running scripts don't leak memory.
22
+ - Logger and `ProgressBar` output on the CLI now go to `stderr` instead of `stdout`, so piping `pinterest-dl search ... | jq .` doesn't get polluted by warnings or progress bars.
23
+ - `Ctrl-C` (`SIGINT`) in the CLI now exits cleanly with code 130 instead of dumping a Ruby backtrace.
24
+
25
+ ## [2.2.0]
26
+
27
+ ### Fixed
28
+ - `Board` and `Search` API calls were getting rejected on some endpoints because `X-Pinterest-Source-Url` and `X-Pinterest-AppState` headers were missing. Both are sent now, board slugs are matched case-insensitively, duplicate pins across pages are filtered out, `config.quality` is applied to returned URLs, and both fall back to SSR pins embedded in the HTML if the API feed comes back empty.
29
+ - `Search` was hitting the search HTML page on every single pagination step to grab a session; it now establishes the session once per search call and also handles responses where `data` is a flat array instead of `{ results: [...] }`.
30
+ - `PinData` now reads `<script data-relay-response="true">` blocks in addition to `__PWS_*__` tags, and picks the best available image when `orig` isn't present.
31
+ - `Client` normalizes country subdomains (`de.pinterest.com`, `fr.pinterest.com`, etc.) in its cookie jar, guards `Client#cookie` when `@last_url` is nil, and raises `AuthenticationError` on HTTP 401.
32
+ - `get_media` now falls back to `PinResource` when the initial pin HTML doesn't have both media URLs.
33
+ - CLI: wired up `-v/--verbose`, `--version`, the `media` subcommand, and made `-q/--quality` apply globally.
34
+
6
35
  ## [2.1.5]
7
36
 
8
37
  ### Fixed
@@ -92,9 +121,8 @@ This project follows [Semantic Versioning](https://semver.org/).
92
121
  is now the single source of truth for the gem version.
93
122
 
94
123
  ### Fixed
95
- - The gem no longer prints anythign on `require`.
124
+ - The gem no longer prints anything on `require`.
96
125
 
97
126
  ## [1.0.3]
98
-
99
127
  - Initial public release: `get_image_url`, `get_video_url`, `search`,
100
128
  `search_json`, `search_images`, `search_videos`.
data/README.md CHANGED
@@ -1,15 +1,14 @@
1
-
2
1
  # pinterest-dl
2
+
3
3
  **Get direct image/video URLs from Pinterest, search pins, fetch board contents, and download media — as a Ruby library or a CLI.**
4
4
 
5
- [![Gem Version](https://img.shields.io/gem/v/pinterest-dl)](https://rubygems.org/gems/pinterest-dl)
6
- [![Gem Downloads](https://img.shields.io/gem/dt/pinterest-dl)](https://rubygems.org/gems/pinterest-dl)
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
- [![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/)
10
- <img src="https://img.icons8.com/color/96/000000/pinterest--v1.png" width="80">
5
+ [![Gem Version](https://img.shields.io/gem/v/pinterest-dl)](https://rubygems.org/gems/pinterest-dl)
6
+ [![Gem Downloads](https://img.shields.io/gem/dt/pinterest-dl)](https://rubygems.org/gems/pinterest-dl)
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
+ [![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/)
11
10
 
12
- ---
11
+ <img src="https://img.icons8.com/color/96/000000/pinterest--v1.png" width="80">
13
12
 
14
13
  > **Note:** Users in some regions (e.g. Iran) may need a fu*king VPN to reach Pinterest.
15
14
  > (Yeah, because even in 2026 Pinterest still gives you the middle finger on clean APIs.)
@@ -18,12 +17,12 @@ Pinterest doesn't give you a clean, official API for getting a direct media URL
18
17
 
19
18
  ## What it does
20
19
 
21
- - Pulls the **direct image or video URL** out of a single pin page.
22
- - **Searches** Pinterest and returns pin metadata (id, url, title, description, creator, image/video URL), with pagination.
23
- - Fetches all pins from a **board** (or a specific board section).
24
- - **Downloads** a URL — or a whole batch of them — straight to disk, with progress reporting and per-file error handling.
25
- - Supports **authenticated requests** via cookies, for boards/pins that require a logged-in session.
26
- - Raises **specific, catchable exceptions** (`NotFoundError`, `RateLimitError`, `NetworkError`, ...) instead of returning `nil` or printing to stdout.
20
+ - 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.
22
+ - 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.
27
26
  - Ships a **CLI** (`pinterest-dl`) for one-off use from the shell.
28
27
 
29
28
  ## Installation
@@ -42,10 +41,15 @@ gem 'pinterest-dl'
42
41
 
43
42
  ```ruby
44
43
  require 'pinterest-dl'
44
+
45
45
  # Direct image URL
46
- PinterestDL.get_image_url('https://www.pinterest.com/pin/1234567890123456789/') # => "https://i.pinimg.com/originals/aa/bb/cc/aabbcc...jpg"
46
+ PinterestDL.get_image_url('https://www.pinterest.com/pin/1234567890123456789/')
47
+ # => "https://i.pinimg.com/originals/aa/bb/cc/aabbcc...jpg"
48
+
47
49
  # Direct video URL (raises PinterestDL::NotFoundError if the pin has no video)
48
- PinterestDL.get_video_url('https://www.pinterest.com/pin/1234567890123456789/') # => "https://v.pinimg.com/videos/mc/720p/aa/bb/cc/aabbcc....mp4"
50
+ PinterestDL.get_video_url('https://www.pinterest.com/pin/1234567890123456789/')
51
+ # => "https://v.pinimg.com/videos/mc/720p/aa/bb/cc/aabbcc....mp4"
52
+
49
53
  # Download it
50
54
  PinterestDL.download(
51
55
  PinterestDL.get_image_url('https://www.pinterest.com/pin/1234567890123456789/'),
@@ -58,25 +62,35 @@ PinterestDL.download(
58
62
  ### Get image / video URLs
59
63
 
60
64
  ```ruby
61
- url = PinterestDL.get_image_url('https://www.pinterest.com/pin/example/') # Pick a specific size bucket
62
- url = PinterestDL.get_image_url('https://www.pinterest.com/pin/example/', quality: :"474x") # quality can be :originals, :"736x", :"474x", :"236x"
65
+ url = PinterestDL.get_image_url('https://www.pinterest.com/pin/example/')
66
+
67
+ # Pick a specific size bucket
68
+ url = PinterestDL.get_image_url('https://www.pinterest.com/pin/example/', quality: :"736x")
69
+ # quality can be :originals, :"1200x", :"736x", :"564x", :"474x", :"236x"
70
+
63
71
  url = PinterestDL.get_video_url('https://www.pinterest.com/pin/example/')
72
+
64
73
  # Both at once
65
- media = PinterestDL.get_media('https://www.pinterest.com/pin/example/') # => { image_url: "https://i.pinimg.com/...", video_url: nil }
74
+ media = PinterestDL.get_media('https://www.pinterest.com/pin/example/')
75
+ # => { image_url: "https://i.pinimg.com/...", video_url: nil }
66
76
  ```
67
77
 
68
78
  ### Search
69
79
 
70
80
  ```ruby
71
- # Search for pins with a specific query
72
- results = PinterestDL.search('nature landscape', limit: 10) # => [{ id: "...", pin_url: "...", title: "...", description: "...", creator: "...", image_url: "...", video_url: nil }, ...]
73
- # Fetch more than one page of results (25 pins/page from Pinterest)
74
- results = PinterestDL.search('nature landscape', limit: 100, pages: 10)
75
- # Get only image URLs from search results
76
- images = PinterestDL.search_images('sunset', limit: 5) # => ["https://i.pinimg.com/originals/...", ...]
77
- # Get only video URLs from search results
78
- videos = PinterestDL.search_videos('tutorial', limit: 3) # => ["https://v.pinimg.com/videos/...", ...]
79
- # Get search results as a JSON string
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)
86
+ video_pins = PinterestDL.search('motion graphics', limit: 20, type: :video)
87
+
88
+ images = PinterestDL.search_images('sunset', limit: 5)
89
+ # => ["https://i.pinimg.com/originals/...", ...]
90
+
91
+ videos = PinterestDL.search_videos('tutorial', limit: 3)
92
+ # => ["https://v.pinimg.com/videos/...", ...]
93
+
80
94
  json_results = PinterestDL.search_json('anime art', limit: 20)
81
95
  ```
82
96
 
@@ -84,7 +98,11 @@ json_results = PinterestDL.search_json('anime art', limit: 20)
84
98
 
85
99
  ```ruby
86
100
  # All pins on a board
87
- pins = PinterestDL.board('https://www.pinterest.com/username/board-name/', limit: 50)
101
+ 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
+
88
106
  # A specific section within a board
89
107
  pins = PinterestDL.board('https://www.pinterest.com/username/board-name/section-slug/', limit: 50)
90
108
  ```
@@ -94,11 +112,16 @@ pins = PinterestDL.board('https://www.pinterest.com/username/board-name/section-
94
112
  ```ruby
95
113
  # Single file
96
114
  PinterestDL.download('https://i.pinimg.com/originals/aa/bb/cc/img.jpg', path: 'out/img.jpg')
97
- # Batch download (returns { succeeded: [...], failed: [{ url:, error: }, ...] })
98
- urls = PinterestDL.search_images('mountains', limit: 20)
99
- result = PinterestDL.download_batch(urls, dir: './downloads')
115
+
116
+ # Skip if already on disk
117
+ PinterestDL.download(url, path: 'out/img.jpg', overwrite: false)
118
+
119
+ # Batch download (returns { succeeded: [...], failed: [{ url:, error: }, ...], skipped: [...] })
120
+ urls = PinterestDL.search_images('mountains', limit: 40)
121
+ result = PinterestDL.download_batch(urls, dir: './downloads', concurrency: 6, overwrite: false)
122
+
100
123
  # With progress reporting
101
- bar = PinterestDL::ProgressBar.new(total: urls.size)
124
+ bar = PinterestDL::ProgressBar.new(total: urls.size, out: $stderr)
102
125
  PinterestDL.download_batch(urls, dir: './downloads') do |done, total, url|
103
126
  bar.update(done)
104
127
  end
@@ -106,11 +129,12 @@ end
106
129
 
107
130
  ### Cookies / authenticated sessions
108
131
 
109
- Some boards and pins require a logged-in session to view. Pass your browser's Pinterest cookies through global configuration:
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:
110
133
 
111
134
  ```ruby
112
135
  PinterestDL.configure do |c|
113
136
  c.cookies = 'sessionid=...; csrftoken=...' # yeah, steal your own fucking session if you have to
137
+ # c.cookies = File.expand_path('~/cookies.txt')
114
138
  c.user_agent = 'Mozilla/5.0 ...' # optional override
115
139
  end
116
140
  ```
@@ -120,12 +144,17 @@ end
120
144
  ```ruby
121
145
  PinterestDL.configure do |c|
122
146
  c.open_timeout = 10 # seconds, connection open timeout
123
- c.read_timeout = 20 # seconds, response read timeout
124
- c.max_retries = 3 # retries on transient network failures
125
- c.retry_wait = 1.0 # base seconds between retries (backs off linearly)
126
- c.rate_limit_interval = 0.5 # minimum seconds between outgoing requests
127
- c.quality = :originals # default image quality for get_image_url
128
- c.logger.level = Logger::INFO # library uses this Logger instead of puts
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
129
158
  end
130
159
  ```
131
160
 
@@ -146,6 +175,8 @@ rescue PinterestDL::NetworkError => e
146
175
  # DNS/timeout/connection-level failure; e.cause_error has the original exception
147
176
  rescue PinterestDL::InvalidURLError
148
177
  # the given string isn't a Pinterest pin/board URL
178
+ rescue PinterestDL::DownloadError
179
+ # disk or stream failure while saving a file
149
180
  rescue PinterestDL::Error
150
181
  # catch-all for anything above
151
182
  end
@@ -157,17 +188,18 @@ end
157
188
  pinterest-dl image https://www.pinterest.com/pin/example/
158
189
  pinterest-dl image https://www.pinterest.com/pin/example/ -o pin.jpg
159
190
  pinterest-dl video https://www.pinterest.com/pin/example/ -o pin.mp4
191
+ pinterest-dl media https://www.pinterest.com/pin/example/
160
192
  pinterest-dl search "cyberpunk city" -n 20
161
- pinterest-dl search "cyberpunk city" -n 20 -o ./downloads
162
- pinterest-dl board https://www.pinterest.com/username/board-name/ -n 50 -o ./downloads
193
+ pinterest-dl search "cyberpunk city" -n 50 -j 8 -o ./downloads
194
+ pinterest-dl board https://www.pinterest.com/username/board-name/ -n 100 -j 6 -s -o ./downloads
163
195
  pinterest-dl board https://www.pinterest.com/username/board-name/ -t video -o ./videos
164
196
  pinterest-dl search "cats" -t image -n 30 -o ./images
165
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
166
199
  pinterest-dl --help
167
200
  ```
168
201
 
169
- Flags: `-o/--output`, `-n/--limit`, `-t/--type` (`all`, `image`, `video`, `pin`), `-q/--quality`, `-c/--cookies`, `-v/--verbose`.
170
-
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`.
171
203
 
172
204
  ## Development
173
205
 
@@ -187,4 +219,4 @@ bundle exec rake # both (default task)
187
219
 
188
220
  ## License
189
221
 
190
- WTFPL © [monji024](https://github.com/monji024)
222
+ WTFPL — [monji024](https://github.com/monji024)
data/bin/pinterest-dl CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env ruby
2
- # Monji024
2
+ # frozen_string_literal: true
3
+
3
4
  require_relative '../lib/pinterest-dl'
4
5
  require 'optparse'
5
6
 
@@ -8,28 +9,54 @@ def usage
8
9
  pinterest-dl v#{PinterestDL::VERSION}
9
10
 
10
11
  Usage:
11
- pinterest-dl image URL [-o FILE]
12
+ pinterest-dl image URL [-q QUALITY] [-o FILE]
12
13
  pinterest-dl video URL [-o FILE]
13
- pinterest-dl search QUERY [-n LIMIT] [-t TYPE] [-o DIR]
14
- pinterest-dl board URL [-n LIMIT] [-t TYPE] [-o DIR]
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]
15
17
 
16
18
  Options:
17
- -o, --output PATH File (image/video) or directory (search/board) to save to
18
- -n, --limit N Max number of results (search/board), default 25
19
- -t, --type TYPE What to collect in search/board: all, image, video, pin (default all)
20
- -q, --quality Q Image quality: originals, 736x, 474x, 236x (default originals)
21
- -c, --cookies STR Cookie string for authenticated requests
22
- -h, --help Show this help
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
23
32
  USAGE
24
33
  end
25
34
 
26
- options = { limit: 25, quality: :originals, type: :all }
35
+ options = {
36
+ limit: 25,
37
+ quality: :originals,
38
+ type: :all,
39
+ jobs: 4,
40
+ skip_existing: false,
41
+ verbose: false
42
+ }
43
+
27
44
  parser = OptionParser.new do |opts|
28
45
  opts.on('-o PATH', '--output PATH') { |v| options[:output] = v }
29
46
  opts.on('-n N', '--limit N', Integer) { |v| options[:limit] = v }
30
47
  opts.on('-t T', '--type T') { |v| options[:type] = v.to_sym }
31
48
  opts.on('-q Q', '--quality Q') { |v| options[:quality] = v.to_sym }
32
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
33
60
  opts.on('-h', '--help') do
34
61
  puts usage
35
62
  exit 0
@@ -51,19 +78,14 @@ if command.nil? || target.nil?
51
78
  exit(command.nil? ? 0 : 1)
52
79
  end
53
80
 
54
- PinterestDL.configure do |c|
55
- c.cookies = options[:cookies] if options[:cookies]
56
- c.logger.level = Logger::DEBUG if options[:verbose]
57
- end
58
-
59
- def die(message)
81
+ def die(message, code = 1)
60
82
  warn "pinterest-dl: #{message}"
61
- exit 1
83
+ exit code
62
84
  end
63
85
 
64
86
  def handle_pins(pins, options)
65
87
  if pins.empty?
66
- puts 'No matching pins found'
88
+ warn 'No matching pins found'
67
89
  return
68
90
  end
69
91
 
@@ -71,27 +93,51 @@ def handle_pins(pins, options)
71
93
  links = pins.map { |p| p[:pin_url] }
72
94
  if options[:output]
73
95
  FileUtils.mkdir_p(options[:output])
74
- File.write(File.join(options[:output], 'pins.txt'), "#{links.join("\n")}\n")
75
- puts "Saved #{links.size} pin links to #{options[:output]}/pins.txt"
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}"
76
99
  else
77
100
  puts links
78
101
  end
79
102
  elsif options[:output]
80
- urls = pins.filter_map { |p| p[:video_url] || p[:image_url] }
81
- bar = PinterestDL::ProgressBar.new(total: urls.size)
82
- result = PinterestDL.download_batch(urls, dir: options[:output]) { |done, _total, _| bar.update(done) }
83
- puts "Downloaded #{result[:succeeded].size}/#{urls.size} files to #{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?
84
116
  else
85
117
  puts JSON.pretty_generate(pins)
86
118
  end
87
119
  end
88
120
 
89
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
+
90
136
  case command
91
137
  when 'image'
92
138
  url = PinterestDL.get_image_url(target, quality: options[:quality])
93
139
  if options[:output]
94
- PinterestDL.download(url, path: options[:output])
140
+ PinterestDL.download(url, path: options[:output], overwrite: !options[:skip_existing])
95
141
  puts "Saved to #{options[:output]}"
96
142
  else
97
143
  puts url
@@ -99,11 +145,13 @@ begin
99
145
  when 'video'
100
146
  url = PinterestDL.get_video_url(target)
101
147
  if options[:output]
102
- PinterestDL.download(url, path: options[:output])
148
+ PinterestDL.download(url, path: options[:output], overwrite: !options[:skip_existing])
103
149
  puts "Saved to #{options[:output]}"
104
150
  else
105
151
  puts url
106
152
  end
153
+ when 'media'
154
+ puts JSON.pretty_generate(PinterestDL.get_media(target, quality: options[:quality]))
107
155
  when 'search'
108
156
  handle_pins(PinterestDL.search(target, limit: options[:limit], type: options[:type]), options)
109
157
  when 'board'
@@ -111,6 +159,9 @@ begin
111
159
  else
112
160
  die "unknown command '#{command}'\n\n#{usage}"
113
161
  end
162
+ rescue Interrupt
163
+ warn "\npinterest-dl: interrupted"
164
+ exit 130
114
165
  rescue PinterestDL::Error, ArgumentError => e
115
166
  die e.message
116
- end
167
+ end
data/lib/pinterest-dl.rb CHANGED
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Monji024
3
+
4
4
  require 'json'
5
5
  require_relative 'pinterest_dl/version'
6
6
  require_relative 'pinterest_dl/errors'
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Monji024
4
3
  module PinterestDL
5
4
  PIN_URL_PATTERN = %r{(pinterest\.[a-z.]+/pin/|pin\.it/)}i.freeze
6
5
 
@@ -44,24 +43,37 @@ module PinterestDL
44
43
 
45
44
  def get_media(pin_url, quality: config.quality, client: Client.new(config: config))
46
45
  html, pin_id = load_pin(pin_url, client)
47
- {
48
- image_url: extract_pin_image(html, pin_id, quality: quality),
49
- video_url: extract_pin_video(html, pin_id)
50
- }
46
+ image = extract_pin_image(html, pin_id, quality: quality)
47
+ video = extract_pin_video(html, pin_id)
48
+ if (!image || !video) && pin_id
49
+ api_pin = pin_from_api(pin_id, client)
50
+ image ||= api_pin && api_pin[:image_url] && Extractors::Image.apply_quality(api_pin[:image_url], quality)
51
+ video ||= api_pin && api_pin[:video_url]
52
+ end
53
+ { image_url: image, video_url: video }
51
54
  end
52
55
 
53
- def download(url, path:)
54
- Downloader.new(config: config).download(url, path: path)
56
+ def download(url, path:, overwrite: nil)
57
+ Downloader.new(config: config).download(url, path: path, overwrite: overwrite)
55
58
  end
56
59
 
57
- def download_batch(urls, dir:, filename: nil, &progress)
58
- Downloader.new(config: config).download_batch(urls, dir: dir, filename: filename, &progress)
60
+ def download_batch(urls, dir:, filename: nil, concurrency: nil, overwrite: nil, &progress)
61
+ Downloader.new(config: config).download_batch(
62
+ urls,
63
+ dir: dir,
64
+ filename: filename,
65
+ concurrency: concurrency,
66
+ overwrite: overwrite,
67
+ &progress
68
+ )
59
69
  end
60
70
 
61
- def search(query, limit: 25, pages: 5, type: :all)
71
+ def search(query, limit: 25, pages: nil, type: :all, client: Client.new(config: config))
62
72
  type = MediaType.parse(type)
63
- pages = [pages, 15].max unless type == :all
64
- Search.new(config: config).call(query, limit: limit, pages: pages, type: type)
73
+ needed_pages = (limit.to_f / 25).ceil + 2
74
+ effective_pages = pages || [needed_pages, 5].max
75
+ 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)
65
77
  end
66
78
 
67
79
  def search_json(query, limit: 25)
@@ -76,10 +88,12 @@ module PinterestDL
76
88
  search(query, limit: limit, type: :video).filter_map { |p| p[:video_url] }
77
89
  end
78
90
 
79
- def board(board_url, limit: 50, pages: 10, type: :all)
91
+ def board(board_url, limit: 50, pages: nil, type: :all, client: Client.new(config: config))
80
92
  type = MediaType.parse(type)
81
- pages = [pages, 20].max unless type == :all
82
- Board.new(config: config).call(board_url, limit: limit, pages: pages, type: type)
93
+ needed_pages = (limit.to_f / Board::PAGE_SIZE).ceil + 2
94
+ effective_pages = pages || [needed_pages, 10].max
95
+ 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)
83
97
  end
84
98
 
85
99
  private
@@ -100,16 +114,19 @@ module PinterestDL
100
114
  headers = {
101
115
  'Accept' => 'application/json, text/javascript, */*, q=0.01',
102
116
  'X-Requested-With' => 'XMLHttpRequest',
117
+ 'X-Pinterest-AppState' => 'active',
103
118
  'X-Pinterest-PWS-Handler' => 'www/pin/[id].js',
104
119
  'X-Pinterest-Source-Url' => "/pin/#{pin_id}/",
105
120
  'X-CSRFToken' => client.cookie('csrftoken') || 'undefined',
106
121
  'Referer' => "https://www.pinterest.com/pin/#{pin_id}/"
107
122
  }
108
-
109
123
  pin = JSON.parse(client.get(uri.to_s, headers: headers, use_cache: false)).dig('resource_response', 'data')
110
124
  return nil unless pin.is_a?(Hash)
111
125
 
112
- { image_url: pin.dig('images', 'orig', 'url'), video_url: Extractors::PinData.first_video_url(pin) }
126
+ {
127
+ image_url: Extractors::PinData.best_image_url(pin),
128
+ video_url: Extractors::PinData.first_video_url(pin)
129
+ }
113
130
  rescue PinterestDL::Error, JSON::ParserError => e
114
131
  logger.debug("PinResource failed for pin #{pin_id}: #{e.message}")
115
132
  nil
@@ -150,4 +167,4 @@ module PinterestDL
150
167
  raise InvalidURLError, "Not a Pinterest pin URL: #{pin_url.inspect}"
151
168
  end
152
169
  end
153
- end
170
+ end