pinterest-dl 2.2.0 → 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 +4 -4
- data/CHANGELOG.md +26 -8
- data/README.md +77 -45
- data/bin/pinterest-dl +61 -24
- data/lib/pinterest_dl/api.rb +22 -12
- data/lib/pinterest_dl/client.rb +111 -28
- data/lib/pinterest_dl/configuration.rb +49 -9
- data/lib/pinterest_dl/downloader.rb +153 -16
- data/lib/pinterest_dl/extractors/image.rb +8 -5
- data/lib/pinterest_dl/version.rb +1 -1
- metadata +2 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 5479bf9ab2de703e527f4e9f9a4a4b3a1ec7dbb37557f52790c78ac66f863529
|
|
4
|
+
data.tar.gz: b70ccb0ef0dcf62d5b30abffe40a1433d122619b8ed66903b7d26c4e0e7e67c8
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 02c4758ce34f5f99e1d8040d21dd8486d1c9f0ee53e86954847202150cbf2c49a7f98c6b9e71483a3b3869730c25a66a0418a56edd8e935342ec728b2f3a8ec9
|
|
7
|
+
data.tar.gz: 410b3b760fe0f1e74651ea828b2164a90527f90a8a654448f260c2c0a2d4725e8e56bce04e7d8e56a867e057e46d16073d0f41da079ddc22fd3d15cfe9795a4d
|
data/CHANGELOG.md
CHANGED
|
@@ -3,15 +3,34 @@
|
|
|
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
|
+
|
|
6
25
|
## [2.2.0]
|
|
7
26
|
|
|
8
27
|
### Fixed
|
|
9
|
-
- `Board` and `Search`
|
|
10
|
-
- `Search`
|
|
11
|
-
- `PinData` reads `<script data-relay-response="true">` blocks and
|
|
12
|
-
- `Client` normalizes country
|
|
13
|
-
- `get_media` falls back to `PinResource` when
|
|
14
|
-
- CLI
|
|
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.
|
|
15
34
|
|
|
16
35
|
## [2.1.5]
|
|
17
36
|
|
|
@@ -102,9 +121,8 @@ This project follows [Semantic Versioning](https://semver.org/).
|
|
|
102
121
|
is now the single source of truth for the gem version.
|
|
103
122
|
|
|
104
123
|
### Fixed
|
|
105
|
-
- The gem no longer prints
|
|
124
|
+
- The gem no longer prints anything on `require`.
|
|
106
125
|
|
|
107
126
|
## [1.0.3]
|
|
108
|
-
|
|
109
127
|
- Initial public release: `get_image_url`, `get_video_url`, `search`,
|
|
110
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
|
-
[](https://rubygems.org/gems/pinterest-dl)
|
|
6
|
-
[](https://rubygems.org/gems/pinterest-dl)
|
|
7
|
-
[](https://github.com/monji024/pinterest-dl/actions/workflows/ci.yml)
|
|
8
|
-
[](LICENSE)
|
|
9
|
-
[](https://www.ruby-lang.org/)
|
|
10
|
-
<img src="https://img.icons8.com/color/96/000000/pinterest--v1.png" width="80">
|
|
5
|
+
[](https://rubygems.org/gems/pinterest-dl)
|
|
6
|
+
[](https://rubygems.org/gems/pinterest-dl)
|
|
7
|
+
[](https://github.com/monji024/pinterest-dl/actions/workflows/ci.yml)
|
|
8
|
+
[](LICENSE)
|
|
9
|
+
[](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
|
|
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/')
|
|
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/')
|
|
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/')
|
|
62
|
-
|
|
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/')
|
|
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
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
#
|
|
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:
|
|
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
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
|
124
|
-
c.
|
|
125
|
-
c.
|
|
126
|
-
c.
|
|
127
|
-
c.
|
|
128
|
-
c.
|
|
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
|
|
162
|
-
pinterest-dl board https://www.pinterest.com/username/board-name/ -n
|
|
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`, `--version`.
|
|
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
|
|
222
|
+
WTFPL — [monji024](https://github.com/monji024)
|
data/bin/pinterest-dl
CHANGED
|
@@ -9,31 +9,49 @@ def usage
|
|
|
9
9
|
pinterest-dl v#{PinterestDL::VERSION}
|
|
10
10
|
|
|
11
11
|
Usage:
|
|
12
|
-
pinterest-dl image URL [-o FILE]
|
|
12
|
+
pinterest-dl image URL [-q QUALITY] [-o FILE]
|
|
13
13
|
pinterest-dl video URL [-o FILE]
|
|
14
|
-
pinterest-dl media URL
|
|
15
|
-
pinterest-dl search QUERY [-n LIMIT] [-t TYPE] [-q QUALITY] [-o DIR]
|
|
16
|
-
pinterest-dl board URL [-n LIMIT] [-t TYPE] [-q QUALITY] [-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]
|
|
17
17
|
|
|
18
18
|
Options:
|
|
19
|
-
-o, --output PATH
|
|
20
|
-
-n, --limit N
|
|
21
|
-
-t, --type TYPE
|
|
22
|
-
-q, --quality Q
|
|
23
|
-
-c, --cookies STR
|
|
24
|
-
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
|
27
32
|
USAGE
|
|
28
33
|
end
|
|
29
34
|
|
|
30
|
-
options = {
|
|
35
|
+
options = {
|
|
36
|
+
limit: 25,
|
|
37
|
+
quality: :originals,
|
|
38
|
+
type: :all,
|
|
39
|
+
jobs: 4,
|
|
40
|
+
skip_existing: false,
|
|
41
|
+
verbose: false
|
|
42
|
+
}
|
|
43
|
+
|
|
31
44
|
parser = OptionParser.new do |opts|
|
|
32
45
|
opts.on('-o PATH', '--output PATH') { |v| options[:output] = v }
|
|
33
46
|
opts.on('-n N', '--limit N', Integer) { |v| options[:limit] = v }
|
|
34
47
|
opts.on('-t T', '--type T') { |v| options[:type] = v.to_sym }
|
|
35
48
|
opts.on('-q Q', '--quality Q') { |v| options[:quality] = v.to_sym }
|
|
36
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 }
|
|
37
55
|
opts.on('-v', '--verbose') { options[:verbose] = true }
|
|
38
56
|
opts.on('--version') do
|
|
39
57
|
puts PinterestDL::VERSION
|
|
@@ -60,14 +78,14 @@ if command.nil? || target.nil?
|
|
|
60
78
|
exit(command.nil? ? 0 : 1)
|
|
61
79
|
end
|
|
62
80
|
|
|
63
|
-
def die(message)
|
|
81
|
+
def die(message, code = 1)
|
|
64
82
|
warn "pinterest-dl: #{message}"
|
|
65
|
-
exit
|
|
83
|
+
exit code
|
|
66
84
|
end
|
|
67
85
|
|
|
68
86
|
def handle_pins(pins, options)
|
|
69
87
|
if pins.empty?
|
|
70
|
-
|
|
88
|
+
warn 'No matching pins found'
|
|
71
89
|
return
|
|
72
90
|
end
|
|
73
91
|
|
|
@@ -75,8 +93,9 @@ def handle_pins(pins, options)
|
|
|
75
93
|
links = pins.map { |p| p[:pin_url] }
|
|
76
94
|
if options[:output]
|
|
77
95
|
FileUtils.mkdir_p(options[:output])
|
|
78
|
-
File.
|
|
79
|
-
|
|
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}"
|
|
80
99
|
else
|
|
81
100
|
puts links
|
|
82
101
|
end
|
|
@@ -84,9 +103,16 @@ def handle_pins(pins, options)
|
|
|
84
103
|
urls = pins.filter_map do |p|
|
|
85
104
|
options[:type] == :image ? p[:image_url] : (p[:video_url] || p[:image_url])
|
|
86
105
|
end
|
|
87
|
-
bar = PinterestDL::ProgressBar.new(total: urls.size)
|
|
88
|
-
result = PinterestDL.download_batch(
|
|
89
|
-
|
|
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?
|
|
90
116
|
else
|
|
91
117
|
puts JSON.pretty_generate(pins)
|
|
92
118
|
end
|
|
@@ -96,6 +122,14 @@ begin
|
|
|
96
122
|
PinterestDL.configure do |c|
|
|
97
123
|
c.cookies = options[:cookies] if options[:cookies]
|
|
98
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]
|
|
99
133
|
c.logger.level = Logger::DEBUG if options[:verbose]
|
|
100
134
|
end
|
|
101
135
|
|
|
@@ -103,7 +137,7 @@ begin
|
|
|
103
137
|
when 'image'
|
|
104
138
|
url = PinterestDL.get_image_url(target, quality: options[:quality])
|
|
105
139
|
if options[:output]
|
|
106
|
-
PinterestDL.download(url, path: options[:output])
|
|
140
|
+
PinterestDL.download(url, path: options[:output], overwrite: !options[:skip_existing])
|
|
107
141
|
puts "Saved to #{options[:output]}"
|
|
108
142
|
else
|
|
109
143
|
puts url
|
|
@@ -111,7 +145,7 @@ begin
|
|
|
111
145
|
when 'video'
|
|
112
146
|
url = PinterestDL.get_video_url(target)
|
|
113
147
|
if options[:output]
|
|
114
|
-
PinterestDL.download(url, path: options[:output])
|
|
148
|
+
PinterestDL.download(url, path: options[:output], overwrite: !options[:skip_existing])
|
|
115
149
|
puts "Saved to #{options[:output]}"
|
|
116
150
|
else
|
|
117
151
|
puts url
|
|
@@ -125,6 +159,9 @@ begin
|
|
|
125
159
|
else
|
|
126
160
|
die "unknown command '#{command}'\n\n#{usage}"
|
|
127
161
|
end
|
|
162
|
+
rescue Interrupt
|
|
163
|
+
warn "\npinterest-dl: interrupted"
|
|
164
|
+
exit 130
|
|
128
165
|
rescue PinterestDL::Error, ArgumentError => e
|
|
129
166
|
die e.message
|
|
130
|
-
end
|
|
167
|
+
end
|
data/lib/pinterest_dl/api.rb
CHANGED
|
@@ -53,18 +53,27 @@ module PinterestDL
|
|
|
53
53
|
{ image_url: image, video_url: video }
|
|
54
54
|
end
|
|
55
55
|
|
|
56
|
-
def download(url, path:)
|
|
57
|
-
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)
|
|
58
58
|
end
|
|
59
59
|
|
|
60
|
-
def download_batch(urls, dir:, filename: nil, &progress)
|
|
61
|
-
Downloader.new(config: config).download_batch(
|
|
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
|
+
)
|
|
62
69
|
end
|
|
63
70
|
|
|
64
|
-
def search(query, limit: 25, pages:
|
|
71
|
+
def search(query, limit: 25, pages: nil, type: :all, client: Client.new(config: config))
|
|
65
72
|
type = MediaType.parse(type)
|
|
66
|
-
|
|
67
|
-
|
|
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)
|
|
68
77
|
end
|
|
69
78
|
|
|
70
79
|
def search_json(query, limit: 25)
|
|
@@ -79,10 +88,12 @@ module PinterestDL
|
|
|
79
88
|
search(query, limit: limit, type: :video).filter_map { |p| p[:video_url] }
|
|
80
89
|
end
|
|
81
90
|
|
|
82
|
-
def board(board_url, limit: 50, pages:
|
|
91
|
+
def board(board_url, limit: 50, pages: nil, type: :all, client: Client.new(config: config))
|
|
83
92
|
type = MediaType.parse(type)
|
|
84
|
-
|
|
85
|
-
|
|
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)
|
|
86
97
|
end
|
|
87
98
|
|
|
88
99
|
private
|
|
@@ -109,7 +120,6 @@ module PinterestDL
|
|
|
109
120
|
'X-CSRFToken' => client.cookie('csrftoken') || 'undefined',
|
|
110
121
|
'Referer' => "https://www.pinterest.com/pin/#{pin_id}/"
|
|
111
122
|
}
|
|
112
|
-
|
|
113
123
|
pin = JSON.parse(client.get(uri.to_s, headers: headers, use_cache: false)).dig('resource_response', 'data')
|
|
114
124
|
return nil unless pin.is_a?(Hash)
|
|
115
125
|
|
|
@@ -157,4 +167,4 @@ module PinterestDL
|
|
|
157
167
|
raise InvalidURLError, "Not a Pinterest pin URL: #{pin_url.inspect}"
|
|
158
168
|
end
|
|
159
169
|
end
|
|
160
|
-
end
|
|
170
|
+
end
|
data/lib/pinterest_dl/client.rb
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
|
|
4
3
|
require 'net/http'
|
|
5
4
|
require 'uri'
|
|
6
5
|
require 'openssl'
|
|
@@ -8,6 +7,7 @@ require 'openssl'
|
|
|
8
7
|
module PinterestDL
|
|
9
8
|
class Client
|
|
10
9
|
MAX_REDIRECTS = 5
|
|
10
|
+
RETRYABLE_HTTP_CODES = %w[408 429 500 502 503 504].freeze
|
|
11
11
|
|
|
12
12
|
attr_reader :last_url
|
|
13
13
|
|
|
@@ -17,17 +17,21 @@ module PinterestDL
|
|
|
17
17
|
@cookies = Hash.new { |hash, key| hash[key] = {} }
|
|
18
18
|
@last_request_at = nil
|
|
19
19
|
@last_url = nil
|
|
20
|
+
@mutex = Mutex.new
|
|
20
21
|
end
|
|
21
22
|
|
|
22
23
|
def get(url, headers: {}, use_cache: true)
|
|
23
24
|
cache_key = [url, headers].hash
|
|
24
|
-
if use_cache
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
if use_cache
|
|
26
|
+
cached = @mutex.synchronize { @cache[cache_key] }
|
|
27
|
+
if cached
|
|
28
|
+
body, @last_url = cached
|
|
29
|
+
return body
|
|
30
|
+
end
|
|
27
31
|
end
|
|
28
32
|
|
|
29
33
|
body = fetch(url, headers: headers).body
|
|
30
|
-
|
|
34
|
+
store_cache(cache_key, [body, @last_url]) if use_cache
|
|
31
35
|
body
|
|
32
36
|
end
|
|
33
37
|
|
|
@@ -35,24 +39,38 @@ module PinterestDL
|
|
|
35
39
|
fetch(url, headers: headers)
|
|
36
40
|
end
|
|
37
41
|
|
|
42
|
+
def stream_get(url, headers: {}, &block)
|
|
43
|
+
raise ArgumentError, 'stream_get requires a block' unless block_given?
|
|
44
|
+
|
|
45
|
+
fetch(url, headers: headers, &block)
|
|
46
|
+
end
|
|
47
|
+
|
|
38
48
|
def cookie(name, url = @last_url)
|
|
39
49
|
target = url.to_s.empty? ? 'https://www.pinterest.com' : url.to_s
|
|
40
|
-
|
|
50
|
+
key = site_key(URI(target))
|
|
51
|
+
@mutex.synchronize { @cookies[key][name] }
|
|
41
52
|
rescue URI::InvalidURIError
|
|
42
53
|
nil
|
|
43
54
|
end
|
|
44
55
|
|
|
45
56
|
def clear_cache
|
|
46
|
-
@cache.clear
|
|
57
|
+
@mutex.synchronize { @cache.clear }
|
|
47
58
|
end
|
|
48
59
|
|
|
49
60
|
private
|
|
50
61
|
|
|
51
|
-
def
|
|
62
|
+
def store_cache(key, value)
|
|
63
|
+
@mutex.synchronize do
|
|
64
|
+
max = @config.respond_to?(:max_cache_entries) ? @config.max_cache_entries.to_i : 256
|
|
65
|
+
@cache.shift if max.positive? && @cache.size >= max
|
|
66
|
+
@cache[key] = value if max.positive?
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def fetch(url, headers: {}, &stream_block)
|
|
52
71
|
(MAX_REDIRECTS + 1).times do
|
|
53
|
-
response = request_with_retries(url, headers: headers)
|
|
72
|
+
response = request_with_retries(url, headers: headers, &stream_block)
|
|
54
73
|
save_cookies(response, url)
|
|
55
|
-
|
|
56
74
|
unless response.is_a?(Net::HTTPRedirection)
|
|
57
75
|
check_response(response, url)
|
|
58
76
|
@last_url = url
|
|
@@ -64,19 +82,32 @@ module PinterestDL
|
|
|
64
82
|
|
|
65
83
|
url = URI.join(url, location).to_s
|
|
66
84
|
end
|
|
85
|
+
|
|
67
86
|
raise PinterestDL::NetworkError, "Too many redirects for #{url}"
|
|
68
87
|
end
|
|
69
88
|
|
|
70
|
-
def request_with_retries(url, headers: {})
|
|
89
|
+
def request_with_retries(url, headers: {}, &stream_block)
|
|
71
90
|
attempts = 0
|
|
72
91
|
begin
|
|
73
92
|
throttle!
|
|
74
93
|
uri = URI(url)
|
|
75
94
|
http = build_http(uri)
|
|
76
95
|
req = Net::HTTP::Get.new(uri, default_headers(uri).merge(headers))
|
|
77
|
-
http
|
|
78
|
-
|
|
79
|
-
|
|
96
|
+
response = perform_request(http, req, &stream_block)
|
|
97
|
+
|
|
98
|
+
if retryable_response?(response) && attempts < @config.max_retries
|
|
99
|
+
attempts += 1
|
|
100
|
+
wait = retry_delay_for(response, attempts)
|
|
101
|
+
@config.logger.warn("HTTP #{response.code} from #{url}, retrying in #{wait}s (#{attempts}/#{@config.max_retries})")
|
|
102
|
+
sleep(wait) if wait.positive?
|
|
103
|
+
raise RetryableResponseSignal
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
response
|
|
107
|
+
rescue RetryableResponseSignal
|
|
108
|
+
retry
|
|
109
|
+
rescue Timeout::Error, Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::ETIMEDOUT,
|
|
110
|
+
Errno::EHOSTUNREACH, SocketError, OpenSSL::SSL::SSLError, EOFError => e
|
|
80
111
|
attempts += 1
|
|
81
112
|
if attempts <= @config.max_retries
|
|
82
113
|
@config.logger.warn("request to #{url} failed (#{e.class}), retrying (#{attempts}/#{@config.max_retries})")
|
|
@@ -87,6 +118,33 @@ module PinterestDL
|
|
|
87
118
|
end
|
|
88
119
|
end
|
|
89
120
|
|
|
121
|
+
class RetryableResponseSignal < StandardError; end
|
|
122
|
+
private_constant :RetryableResponseSignal
|
|
123
|
+
|
|
124
|
+
def perform_request(http, req, &stream_block)
|
|
125
|
+
return http.request(req) unless stream_block
|
|
126
|
+
|
|
127
|
+
http.request(req) do |response|
|
|
128
|
+
if response.is_a?(Net::HTTPSuccess)
|
|
129
|
+
response.read_body(&stream_block)
|
|
130
|
+
end
|
|
131
|
+
return response
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def retryable_response?(response)
|
|
136
|
+
RETRYABLE_HTTP_CODES.include?(response.code.to_s)
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def retry_delay_for(response, attempts)
|
|
140
|
+
header = response['Retry-After'].to_s.strip
|
|
141
|
+
if header.match?(/\A\d+(\.\d+)?\z/)
|
|
142
|
+
header.to_f
|
|
143
|
+
else
|
|
144
|
+
@config.retry_wait * attempts
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
|
|
90
148
|
def check_response(response, url)
|
|
91
149
|
case response
|
|
92
150
|
when Net::HTTPSuccess
|
|
@@ -108,13 +166,24 @@ module PinterestDL
|
|
|
108
166
|
end
|
|
109
167
|
|
|
110
168
|
def build_http(uri)
|
|
111
|
-
http =
|
|
169
|
+
http = build_proxy_http(uri)
|
|
112
170
|
http.use_ssl = (uri.scheme == 'https')
|
|
113
171
|
http.open_timeout = @config.open_timeout
|
|
114
172
|
http.read_timeout = @config.read_timeout
|
|
173
|
+
http.write_timeout = @config.write_timeout if http.respond_to?(:write_timeout=) && @config.respond_to?(:write_timeout)
|
|
115
174
|
http
|
|
116
175
|
end
|
|
117
176
|
|
|
177
|
+
def build_proxy_http(uri)
|
|
178
|
+
proxy_url = @config.respond_to?(:proxy) ? @config.proxy : nil
|
|
179
|
+
return Net::HTTP.new(uri.host, uri.port) if proxy_url.nil? || proxy_url.to_s.strip.empty?
|
|
180
|
+
|
|
181
|
+
p_uri = URI(proxy_url.to_s)
|
|
182
|
+
Net::HTTP.new(uri.host, uri.port, p_uri.host, p_uri.port, p_uri.user, p_uri.password)
|
|
183
|
+
rescue URI::InvalidURIError
|
|
184
|
+
Net::HTTP.new(uri.host, uri.port)
|
|
185
|
+
end
|
|
186
|
+
|
|
118
187
|
def default_headers(uri)
|
|
119
188
|
headers = {
|
|
120
189
|
'User-Agent' => @config.user_agent,
|
|
@@ -128,17 +197,25 @@ module PinterestDL
|
|
|
128
197
|
def cookie_header(uri)
|
|
129
198
|
parts = []
|
|
130
199
|
parts << @config.cookies.to_s if @config.authenticated?
|
|
131
|
-
|
|
200
|
+
key = site_key(uri)
|
|
201
|
+
jar_pairs = @mutex.synchronize { @cookies[key].map { |name, value| "#{name}=#{value}" } }
|
|
202
|
+
parts.concat(jar_pairs)
|
|
132
203
|
parts.join('; ')
|
|
133
204
|
end
|
|
134
205
|
|
|
135
206
|
def save_cookies(response, url)
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
name, value = line.split(';').first.to_s.split('=', 2)
|
|
139
|
-
next if name.nil? || value.nil?
|
|
207
|
+
fields = response.get_fields('set-cookie')
|
|
208
|
+
return if fields.nil? || fields.empty?
|
|
140
209
|
|
|
141
|
-
|
|
210
|
+
key = site_key(URI(url))
|
|
211
|
+
@mutex.synchronize do
|
|
212
|
+
jar = @cookies[key]
|
|
213
|
+
fields.each do |line|
|
|
214
|
+
name, value = line.split(';').first.to_s.split('=', 2)
|
|
215
|
+
next if name.nil? || value.nil?
|
|
216
|
+
|
|
217
|
+
value.strip.empty? ? jar.delete(name.strip) : jar[name.strip] = value.strip
|
|
218
|
+
end
|
|
142
219
|
end
|
|
143
220
|
end
|
|
144
221
|
|
|
@@ -151,13 +228,19 @@ module PinterestDL
|
|
|
151
228
|
|
|
152
229
|
def throttle!
|
|
153
230
|
return if @config.rate_limit_interval <= 0
|
|
154
|
-
return unless @last_request_at
|
|
155
231
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
232
|
+
@mutex.synchronize do
|
|
233
|
+
if @last_request_at
|
|
234
|
+
elapsed = monotonic_now - @last_request_at
|
|
235
|
+
wait = @config.rate_limit_interval - elapsed
|
|
236
|
+
sleep(wait) if wait.positive?
|
|
237
|
+
end
|
|
238
|
+
@last_request_at = monotonic_now
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
def monotonic_now
|
|
243
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
161
244
|
end
|
|
162
245
|
end
|
|
163
|
-
end
|
|
246
|
+
end
|
|
@@ -8,13 +8,12 @@ module PinterestDL
|
|
|
8
8
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' \
|
|
9
9
|
'(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
|
|
10
10
|
|
|
11
|
-
VALID_QUALITIES = %i[originals 736x 474x 236x].freeze
|
|
11
|
+
VALID_QUALITIES = %i[originals 1200x 736x 564x 474x 236x].freeze
|
|
12
12
|
|
|
13
|
-
attr_accessor :
|
|
14
|
-
:max_retries, :retry_wait, :logger,
|
|
15
|
-
:
|
|
16
|
-
|
|
17
|
-
attr_reader :quality
|
|
13
|
+
attr_accessor :user_agent, :open_timeout, :read_timeout, :write_timeout,
|
|
14
|
+
:max_retries, :retry_wait, :logger, :rate_limit_interval,
|
|
15
|
+
:proxy, :max_cache_entries, :concurrency, :overwrite
|
|
16
|
+
attr_reader :quality, :cookies
|
|
18
17
|
|
|
19
18
|
def initialize
|
|
20
19
|
reset!
|
|
@@ -25,10 +24,15 @@ module PinterestDL
|
|
|
25
24
|
@cookies = nil
|
|
26
25
|
@open_timeout = 10
|
|
27
26
|
@read_timeout = 20
|
|
27
|
+
@write_timeout = 20
|
|
28
28
|
@max_retries = 3
|
|
29
29
|
@retry_wait = 1.0
|
|
30
30
|
@quality = :originals
|
|
31
31
|
@rate_limit_interval = 0.0
|
|
32
|
+
@proxy = ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV['HTTP_PROXY'] || ENV['http_proxy']
|
|
33
|
+
@max_cache_entries = 256
|
|
34
|
+
@concurrency = 4
|
|
35
|
+
@overwrite = true
|
|
32
36
|
@logger = default_logger
|
|
33
37
|
self
|
|
34
38
|
end
|
|
@@ -41,17 +45,53 @@ module PinterestDL
|
|
|
41
45
|
@quality = value
|
|
42
46
|
end
|
|
43
47
|
|
|
48
|
+
def cookies=(value)
|
|
49
|
+
if value.nil? || value.to_s.strip.empty?
|
|
50
|
+
@cookies = nil
|
|
51
|
+
return
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
raw = value.to_s.strip
|
|
55
|
+
@cookies = File.file?(raw) ? parse_cookie_file(raw) : raw
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def concurrency=(value)
|
|
59
|
+
num = value.to_i
|
|
60
|
+
raise ArgumentError, 'concurrency must be at least 1' if num < 1
|
|
61
|
+
|
|
62
|
+
@concurrency = num
|
|
63
|
+
end
|
|
64
|
+
|
|
44
65
|
def authenticated?
|
|
45
|
-
|
|
66
|
+
!@cookies.nil? && !@cookies.empty?
|
|
46
67
|
end
|
|
47
68
|
|
|
48
69
|
private
|
|
49
70
|
|
|
71
|
+
def parse_cookie_file(path)
|
|
72
|
+
pairs = []
|
|
73
|
+
File.foreach(path) do |line|
|
|
74
|
+
stripped = line.strip
|
|
75
|
+
next if stripped.empty? || stripped.start_with?('#')
|
|
76
|
+
|
|
77
|
+
fields = stripped.split("\t")
|
|
78
|
+
if fields.size >= 7
|
|
79
|
+
domain, _flag, _path, _secure, _expiry, name, val = fields
|
|
80
|
+
next unless domain.include?('pinterest.')
|
|
81
|
+
|
|
82
|
+
pairs << "#{name}=#{val}"
|
|
83
|
+
elsif stripped.include?('=') && !stripped.include?("\t")
|
|
84
|
+
pairs << stripped
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
pairs.join('; ')
|
|
88
|
+
end
|
|
89
|
+
|
|
50
90
|
def default_logger
|
|
51
|
-
Logger.new($
|
|
91
|
+
Logger.new($stderr).tap do |log|
|
|
52
92
|
log.level = Logger::WARN
|
|
53
93
|
log.formatter = proc { |severity, _time, _progname, msg| "[pinterest-dl] #{severity}: #{msg}\n" }
|
|
54
94
|
end
|
|
55
95
|
end
|
|
56
96
|
end
|
|
57
|
-
end
|
|
97
|
+
end
|
|
@@ -1,40 +1,97 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require 'fileutils'
|
|
4
|
+
require 'uri'
|
|
4
5
|
|
|
5
6
|
module PinterestDL
|
|
6
7
|
class Downloader
|
|
8
|
+
CONTENT_TYPE_EXT = {
|
|
9
|
+
'image/jpeg' => '.jpg',
|
|
10
|
+
'image/png' => '.png',
|
|
11
|
+
'image/gif' => '.gif',
|
|
12
|
+
'image/webp' => '.webp',
|
|
13
|
+
'video/mp4' => '.mp4',
|
|
14
|
+
'video/quicktime' => '.mov'
|
|
15
|
+
}.freeze
|
|
16
|
+
|
|
7
17
|
def initialize(client: PinterestDL::Client.new, config: PinterestDL.config)
|
|
8
18
|
@client = client
|
|
9
19
|
@config = config
|
|
10
20
|
end
|
|
11
21
|
|
|
12
|
-
def download(url, path:)
|
|
22
|
+
def download(url, path:, overwrite: nil)
|
|
13
23
|
raise ArgumentError, 'url must not be nil/empty' if url.to_s.strip.empty?
|
|
14
24
|
raise ArgumentError, 'path must not be nil/empty' if path.to_s.strip.empty?
|
|
15
25
|
|
|
26
|
+
should_overwrite = overwrite.nil? ? (@config.respond_to?(:overwrite) ? @config.overwrite : true) : overwrite
|
|
27
|
+
return path if !should_overwrite && File.exist?(path) && File.size(path).positive?
|
|
28
|
+
|
|
16
29
|
FileUtils.mkdir_p(File.dirname(path))
|
|
17
|
-
|
|
18
|
-
|
|
30
|
+
part_path = "#{path}.part.#{Process.pid}.#{Thread.current.object_id}"
|
|
31
|
+
|
|
32
|
+
write_to_part(url, part_path)
|
|
33
|
+
File.rename(part_path, path)
|
|
19
34
|
path
|
|
20
35
|
rescue PinterestDL::Error
|
|
36
|
+
cleanup_part(part_path)
|
|
21
37
|
raise
|
|
22
38
|
rescue StandardError => e
|
|
39
|
+
cleanup_part(part_path)
|
|
23
40
|
raise PinterestDL::DownloadError, "Could not download #{url} to #{path}: #{e.message}"
|
|
24
41
|
end
|
|
25
42
|
|
|
26
|
-
def download_batch(urls, dir:, filename: nil, &progress)
|
|
43
|
+
def download_batch(urls, dir:, filename: nil, concurrency: nil, overwrite: nil, &progress)
|
|
27
44
|
FileUtils.mkdir_p(dir)
|
|
45
|
+
total = urls.size
|
|
46
|
+
return { succeeded: [], failed: [], skipped: [] } if total.zero?
|
|
47
|
+
|
|
48
|
+
workers = resolve_concurrency(concurrency, total)
|
|
49
|
+
return sequential_batch(urls, dir: dir, filename: filename, overwrite: overwrite, &progress) if workers <= 1
|
|
50
|
+
|
|
51
|
+
concurrent_batch(urls, dir: dir, filename: filename, workers: workers, overwrite: overwrite, &progress)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
private
|
|
55
|
+
|
|
56
|
+
def write_to_part(url, part_path)
|
|
57
|
+
if @client.respond_to?(:stream_get)
|
|
58
|
+
File.open(part_path, 'wb') do |file|
|
|
59
|
+
@client.stream_get(url) { |chunk| file.write(chunk) }
|
|
60
|
+
end
|
|
61
|
+
else
|
|
62
|
+
response = @client.raw_get(url)
|
|
63
|
+
File.binwrite(part_path, response.body)
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def cleanup_part(part_path)
|
|
68
|
+
FileUtils.rm_f(part_path) if part_path && File.exist?(part_path)
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def resolve_concurrency(concurrency, total)
|
|
72
|
+
return 1 unless @client.is_a?(PinterestDL::Client)
|
|
73
|
+
|
|
74
|
+
configured = concurrency || (@config.respond_to?(:concurrency) ? @config.concurrency : 1)
|
|
75
|
+
[[configured.to_i, 1].max, total].min
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def sequential_batch(urls, dir:, filename:, overwrite:, &progress)
|
|
28
79
|
succeeded = []
|
|
29
80
|
failed = []
|
|
81
|
+
skipped = []
|
|
30
82
|
total = urls.size
|
|
83
|
+
should_overwrite = overwrite.nil? ? (@config.respond_to?(:overwrite) ? @config.overwrite : true) : overwrite
|
|
31
84
|
|
|
32
|
-
urls.each_with_index do |
|
|
33
|
-
|
|
34
|
-
path = File.join(dir, name)
|
|
85
|
+
urls.each_with_index do |item, index|
|
|
86
|
+
url, path = resolve_target(item, index, dir, filename)
|
|
35
87
|
begin
|
|
36
|
-
|
|
37
|
-
|
|
88
|
+
if !should_overwrite && File.exist?(path) && File.size(path).positive?
|
|
89
|
+
skipped << path
|
|
90
|
+
succeeded << path
|
|
91
|
+
else
|
|
92
|
+
download(url, path: path, overwrite: true)
|
|
93
|
+
succeeded << path
|
|
94
|
+
end
|
|
38
95
|
rescue PinterestDL::Error => e
|
|
39
96
|
@config.logger.warn("failed to download #{url}: #{e.message}")
|
|
40
97
|
failed << { url: url, error: e }
|
|
@@ -42,17 +99,97 @@ module PinterestDL
|
|
|
42
99
|
progress&.call(index + 1, total, url)
|
|
43
100
|
end
|
|
44
101
|
|
|
45
|
-
{ succeeded: succeeded, failed: failed }
|
|
102
|
+
{ succeeded: succeeded, failed: failed, skipped: skipped }
|
|
46
103
|
end
|
|
47
104
|
|
|
48
|
-
|
|
105
|
+
def concurrent_batch(urls, dir:, filename:, workers:, overwrite:, &progress)
|
|
106
|
+
queue = Queue.new
|
|
107
|
+
urls.each_with_index { |item, index| queue << [item, index] }
|
|
108
|
+
workers.times { queue << nil }
|
|
109
|
+
|
|
110
|
+
succeeded = []
|
|
111
|
+
failed = []
|
|
112
|
+
skipped = []
|
|
113
|
+
done_count = 0
|
|
114
|
+
total = urls.size
|
|
115
|
+
mutex = Mutex.new
|
|
116
|
+
should_overwrite = overwrite.nil? ? (@config.respond_to?(:overwrite) ? @config.overwrite : true) : overwrite
|
|
117
|
+
|
|
118
|
+
threads = Array.new(workers) do
|
|
119
|
+
Thread.new do
|
|
120
|
+
while (work = queue.pop)
|
|
121
|
+
item, index = work
|
|
122
|
+
url, path = resolve_target(item, index, dir, filename)
|
|
123
|
+
outcome = nil
|
|
124
|
+
err = nil
|
|
125
|
+
|
|
126
|
+
begin
|
|
127
|
+
if !should_overwrite && File.exist?(path) && File.size(path).positive?
|
|
128
|
+
outcome = :skipped
|
|
129
|
+
else
|
|
130
|
+
download(url, path: path, overwrite: true)
|
|
131
|
+
outcome = :succeeded
|
|
132
|
+
end
|
|
133
|
+
rescue PinterestDL::Error => e
|
|
134
|
+
err = e
|
|
135
|
+
outcome = :failed
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
mutex.synchronize do
|
|
139
|
+
case outcome
|
|
140
|
+
when :skipped
|
|
141
|
+
skipped << path
|
|
142
|
+
succeeded << path
|
|
143
|
+
when :succeeded
|
|
144
|
+
succeeded << path
|
|
145
|
+
when :failed
|
|
146
|
+
@config.logger.warn("failed to download #{url}: #{err.message}")
|
|
147
|
+
failed << { url: url, error: err }
|
|
148
|
+
end
|
|
149
|
+
done_count += 1
|
|
150
|
+
progress&.call(done_count, total, url)
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
threads.each(&:join)
|
|
157
|
+
{ succeeded: succeeded, failed: failed, skipped: skipped }
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
def resolve_target(item, index, dir, filename)
|
|
161
|
+
if item.is_a?(Hash)
|
|
162
|
+
url = item[:video_url] || item[:image_url] || item[:url]
|
|
163
|
+
name = filename ? filename.call(url, index) : pin_filename(item, url, index)
|
|
164
|
+
else
|
|
165
|
+
url = item
|
|
166
|
+
name = filename ? filename.call(url, index) : default_filename(url, index)
|
|
167
|
+
end
|
|
168
|
+
[url, File.join(dir, sanitize_filename(name))]
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def pin_filename(pin, url, index)
|
|
172
|
+
ext = extract_ext(url)
|
|
173
|
+
id = pin[:id].to_s.strip
|
|
174
|
+
return default_filename(url, index) if id.empty?
|
|
175
|
+
|
|
176
|
+
format('%<index>04d_%<id>s%<ext>s', index: index + 1, id: id, ext: ext)
|
|
177
|
+
end
|
|
49
178
|
|
|
50
179
|
def default_filename(url, index)
|
|
51
|
-
ext
|
|
52
|
-
|
|
53
|
-
|
|
180
|
+
format('%<index>04d%<ext>s', index: index + 1, ext: extract_ext(url))
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
def extract_ext(url)
|
|
184
|
+
ext = File.extname(URI(url.to_s).path.to_s)[/\A\.[A-Za-z0-9]{2,5}\z/]
|
|
185
|
+
ext || '.jpg'
|
|
54
186
|
rescue URI::InvalidURIError
|
|
55
|
-
|
|
187
|
+
'.jpg'
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
def sanitize_filename(name)
|
|
191
|
+
clean = File.basename(name.to_s.strip).gsub(/[\x00\/\\:*?"<>|]/, '_')
|
|
192
|
+
clean.empty? ? 'download.jpg' : clean
|
|
56
193
|
end
|
|
57
194
|
end
|
|
58
|
-
end
|
|
195
|
+
end
|
|
@@ -1,16 +1,19 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
|
|
4
3
|
module PinterestDL
|
|
5
4
|
module Extractors
|
|
6
5
|
module Image
|
|
7
6
|
QUALITY_PATH = {
|
|
8
7
|
originals: 'originals',
|
|
8
|
+
'1200x': '1200x',
|
|
9
9
|
'736x': '736x',
|
|
10
|
+
'564x': '564x',
|
|
10
11
|
'474x': '474x',
|
|
11
12
|
'236x': '236x'
|
|
12
13
|
}.freeze
|
|
13
14
|
|
|
15
|
+
BUCKET_REGEX = /(?:originals|1200x|736x|564x|474x|236x|\d+x\d*)/i.freeze
|
|
16
|
+
|
|
14
17
|
module_function
|
|
15
18
|
|
|
16
19
|
def extract(html, quality: :originals)
|
|
@@ -30,19 +33,19 @@ module PinterestDL
|
|
|
30
33
|
|
|
31
34
|
def from_raw_pattern(html)
|
|
32
35
|
match = html.to_s.match(
|
|
33
|
-
%r{https://i
|
|
36
|
+
%r{https://i\d*\.pinimg\.com/(?:originals|1200x|736x|564x|474x|236x)/[A-Za-z0-9_\-/]+\.(?:jpg|jpeg|png|gif|webp)}i
|
|
34
37
|
)
|
|
35
38
|
match && match[0]
|
|
36
39
|
end
|
|
37
40
|
|
|
38
41
|
def apply_quality(url, quality)
|
|
39
|
-
return url unless url.to_s.
|
|
42
|
+
return url unless url.to_s.match?(%r{i\d*\.pinimg\.com}i)
|
|
40
43
|
|
|
41
44
|
target = QUALITY_PATH[quality.to_sym]
|
|
42
45
|
return url unless target
|
|
43
46
|
|
|
44
|
-
url.sub(%r{/
|
|
47
|
+
url.sub(%r{/#{BUCKET_REGEX}/}, "/#{target}/")
|
|
45
48
|
end
|
|
46
49
|
end
|
|
47
50
|
end
|
|
48
|
-
end
|
|
51
|
+
end
|
data/lib/pinterest_dl/version.rb
CHANGED
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: pinterest-dl
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 2.
|
|
4
|
+
version: 2.3.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Monji
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: bin
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2026-11-
|
|
11
|
+
date: 2026-11-08 00:00:00.000000000 Z
|
|
12
12
|
dependencies: []
|
|
13
13
|
description: A Ruby toolkit for getting direct image and video URLs from Pinterest
|
|
14
14
|
pins, searching pins, fetching board contents, and downloading media to disk — as
|