pinterest-dl 2.1.5 → 2.2.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: 471becb9c2f3cb595ad9ebabded3b3cf766b2fd09ca4f7f59b50b171da47e307
4
+ data.tar.gz: 26034c4391ec3ba04f8f712c2ebf7e2b90cf994c599a55eb52c499c49908bfc0
5
5
  SHA512:
6
- metadata.gz: 911490799bd9db4405781306091bbe06271413e25b834190d46394ad7b288be5ce3153ba25d9261122dbb4efe0be08188c49583751999d08e87be223a017300e
7
- data.tar.gz: f18ffdcc24defdbf6bb392f738ed6b6dc62047ccecacfb90eb90fb52a879b18dd84c7677288d538f8105ecae7e611faec6470a0dfeaedb07f8767d9e822c0e20
6
+ metadata.gz: ecb5c3cf457faa56ba8d3f275ff2952b2efed749646c7db2f7486a38c42651c2a300ad0b9eaadb0f165b4fac1adef59f9f0baa29b3155f87eca5e8ae5be35050
7
+ data.tar.gz: 75034d098152e53f0484cb59c17a25bdf6cbe7f10702e6311d1bfe69c9eff62e991522a0e07c2482b2009de7d589027a39006b6691457ddf83f66d2dcb5ef317
data/CHANGELOG.md CHANGED
@@ -3,6 +3,16 @@
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.2.0]
7
+
8
+ ### Fixed
9
+ - `Board` and `Search` requests now send `X-Pinterest-Source-Url` and `X-Pinterest-AppState`, match slugs case-insensitively, deduplicate pins, apply `config.quality`, and fall back to SSR HTML pins.
10
+ - `Search` creates a session once per search call instead of once per page and handles array `data` payloads.
11
+ - `PinData` reads `<script data-relay-response="true">` blocks and non-`orig` image buckets.
12
+ - `Client` normalizes country domains in its cookie jar, guards `cookie` when URL is nil, and raises `AuthenticationError` on HTTP 401.
13
+ - `get_media` falls back to `PinResource` when page HTML is incomplete.
14
+ - CLI supports `-v/--verbose`, `--version`, `media`, and applies `-q/--quality` globally.
15
+
6
16
  ## [2.1.5]
7
17
 
8
18
  ### Fixed
data/README.md CHANGED
@@ -166,7 +166,7 @@ pinterest-dl search "cats" -t pin -n 30
166
166
  pinterest-dl --help
167
167
  ```
168
168
 
169
- Flags: `-o/--output`, `-n/--limit`, `-t/--type` (`all`, `image`, `video`, `pin`), `-q/--quality`, `-c/--cookies`, `-v/--verbose`.
169
+ Flags: `-o/--output`, `-n/--limit`, `-t/--type` (`all`, `image`, `video`, `pin`), `-q/--quality`, `-c/--cookies`, `-v/--verbose`, `--version`.
170
170
 
171
171
 
172
172
  ## Development
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
 
@@ -10,8 +11,9 @@ def usage
10
11
  Usage:
11
12
  pinterest-dl image URL [-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
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]
15
17
 
16
18
  Options:
17
19
  -o, --output PATH File (image/video) or directory (search/board) to save to
@@ -19,17 +21,24 @@ def usage
19
21
  -t, --type TYPE What to collect in search/board: all, image, video, pin (default all)
20
22
  -q, --quality Q Image quality: originals, 736x, 474x, 236x (default originals)
21
23
  -c, --cookies STR Cookie string for authenticated requests
24
+ -v, --verbose Enable debug logging
25
+ --version Print version and exit
22
26
  -h, --help Show this help
23
27
  USAGE
24
28
  end
25
29
 
26
- options = { limit: 25, quality: :originals, type: :all }
30
+ options = { limit: 25, quality: :originals, type: :all, verbose: false }
27
31
  parser = OptionParser.new do |opts|
28
32
  opts.on('-o PATH', '--output PATH') { |v| options[:output] = v }
29
33
  opts.on('-n N', '--limit N', Integer) { |v| options[:limit] = v }
30
34
  opts.on('-t T', '--type T') { |v| options[:type] = v.to_sym }
31
35
  opts.on('-q Q', '--quality Q') { |v| options[:quality] = v.to_sym }
32
36
  opts.on('-c STR', '--cookies STR') { |v| options[:cookies] = v }
37
+ opts.on('-v', '--verbose') { options[:verbose] = true }
38
+ opts.on('--version') do
39
+ puts PinterestDL::VERSION
40
+ exit 0
41
+ end
33
42
  opts.on('-h', '--help') do
34
43
  puts usage
35
44
  exit 0
@@ -51,11 +60,6 @@ if command.nil? || target.nil?
51
60
  exit(command.nil? ? 0 : 1)
52
61
  end
53
62
 
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
63
  def die(message)
60
64
  warn "pinterest-dl: #{message}"
61
65
  exit 1
@@ -77,7 +81,9 @@ def handle_pins(pins, options)
77
81
  puts links
78
82
  end
79
83
  elsif options[:output]
80
- urls = pins.filter_map { |p| p[:video_url] || p[:image_url] }
84
+ urls = pins.filter_map do |p|
85
+ options[:type] == :image ? p[:image_url] : (p[:video_url] || p[:image_url])
86
+ end
81
87
  bar = PinterestDL::ProgressBar.new(total: urls.size)
82
88
  result = PinterestDL.download_batch(urls, dir: options[:output]) { |done, _total, _| bar.update(done) }
83
89
  puts "Downloaded #{result[:succeeded].size}/#{urls.size} files to #{options[:output]}"
@@ -87,6 +93,12 @@ def handle_pins(pins, options)
87
93
  end
88
94
 
89
95
  begin
96
+ PinterestDL.configure do |c|
97
+ c.cookies = options[:cookies] if options[:cookies]
98
+ c.quality = options[:quality] if options[:quality]
99
+ c.logger.level = Logger::DEBUG if options[:verbose]
100
+ end
101
+
90
102
  case command
91
103
  when 'image'
92
104
  url = PinterestDL.get_image_url(target, quality: options[:quality])
@@ -104,6 +116,8 @@ begin
104
116
  else
105
117
  puts url
106
118
  end
119
+ when 'media'
120
+ puts JSON.pretty_generate(PinterestDL.get_media(target, quality: options[:quality]))
107
121
  when 'search'
108
122
  handle_pins(PinterestDL.search(target, limit: options[:limit], type: options[:type]), options)
109
123
  when 'board'
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,10 +43,14 @@ 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
56
  def download(url, path:)
@@ -58,10 +61,10 @@ module PinterestDL
58
61
  Downloader.new(config: config).download_batch(urls, dir: dir, filename: filename, &progress)
59
62
  end
60
63
 
61
- def search(query, limit: 25, pages: 5, type: :all)
64
+ def search(query, limit: 25, pages: 5, type: :all, client: Client.new(config: config))
62
65
  type = MediaType.parse(type)
63
66
  pages = [pages, 15].max unless type == :all
64
- Search.new(config: config).call(query, limit: limit, pages: pages, type: type)
67
+ Search.new(client: client, config: config).call(query, limit: limit, pages: pages, type: type)
65
68
  end
66
69
 
67
70
  def search_json(query, limit: 25)
@@ -76,10 +79,10 @@ module PinterestDL
76
79
  search(query, limit: limit, type: :video).filter_map { |p| p[:video_url] }
77
80
  end
78
81
 
79
- def board(board_url, limit: 50, pages: 10, type: :all)
82
+ def board(board_url, limit: 50, pages: 10, type: :all, client: Client.new(config: config))
80
83
  type = MediaType.parse(type)
81
84
  pages = [pages, 20].max unless type == :all
82
- Board.new(config: config).call(board_url, limit: limit, pages: pages, type: type)
85
+ Board.new(client: client, config: config).call(board_url, limit: limit, pages: pages, type: type)
83
86
  end
84
87
 
85
88
  private
@@ -100,6 +103,7 @@ module PinterestDL
100
103
  headers = {
101
104
  'Accept' => 'application/json, text/javascript, */*, q=0.01',
102
105
  'X-Requested-With' => 'XMLHttpRequest',
106
+ 'X-Pinterest-AppState' => 'active',
103
107
  'X-Pinterest-PWS-Handler' => 'www/pin/[id].js',
104
108
  'X-Pinterest-Source-Url' => "/pin/#{pin_id}/",
105
109
  'X-CSRFToken' => client.cookie('csrftoken') || 'undefined',
@@ -109,7 +113,10 @@ module PinterestDL
109
113
  pin = JSON.parse(client.get(uri.to_s, headers: headers, use_cache: false)).dig('resource_response', 'data')
110
114
  return nil unless pin.is_a?(Hash)
111
115
 
112
- { image_url: pin.dig('images', 'orig', 'url'), video_url: Extractors::PinData.first_video_url(pin) }
116
+ {
117
+ image_url: Extractors::PinData.best_image_url(pin),
118
+ video_url: Extractors::PinData.first_video_url(pin)
119
+ }
113
120
  rescue PinterestDL::Error, JSON::ParserError => e
114
121
  logger.debug("PinResource failed for pin #{pin_id}: #{e.message}")
115
122
  nil
@@ -6,6 +6,7 @@ require 'uri'
6
6
  module PinterestDL
7
7
  class Board
8
8
  PAGE_SIZE = 50
9
+ RESERVED_PATHS = %w[pin search ideas today settings business].freeze
9
10
 
10
11
  def initialize(client: PinterestDL::Client.new, config: PinterestDL.config)
11
12
  @client = client
@@ -17,27 +18,42 @@ module PinterestDL
17
18
  html = start_session(username, slug)
18
19
  board_id = board_id_from_page(html, slug) || find_board_id(username, slug)
19
20
  resource, options = feed_request(board_id, section)
21
+ results = collect_pins(resource, options, limit: limit, pages: pages, type: type)
22
+ if results.empty?
23
+ fallback = PinterestDL::Extractors::PinData.extract_pins(html, quality: @config.quality)
24
+ results = PinterestDL::MediaType.filter(fallback, type)
25
+ end
26
+ results.first(limit)
27
+ end
20
28
 
29
+ private
30
+
31
+ def collect_pins(resource, options, limit:, pages:, type:)
21
32
  results = []
33
+ seen = {}
22
34
  bookmarks = nil
23
35
  pages_fetched = 0
24
36
 
25
37
  loop do
26
38
  page = fetch_page(resource, options, bookmarks)
27
- results.concat(PinterestDL::MediaType.filter(page[:pins], type))
39
+ PinterestDL::MediaType.filter(page[:pins], type).each do |pin|
40
+ next if seen[pin[:id]]
41
+
42
+ seen[pin[:id]] = true
43
+ results << pin
44
+ end
28
45
  bookmarks = page[:bookmarks]
29
46
  pages_fetched += 1
30
47
 
31
- break if results.size >= limit
32
- break if bookmarks.empty? || bookmarks == ['-end-']
33
- break if pages_fetched >= pages
34
- break if page[:pins].empty?
48
+ break if results.size >= limit || stop_pagination?(bookmarks, pages_fetched, pages, page[:pins])
35
49
  end
36
50
 
37
- results.first(limit)
51
+ results
38
52
  end
39
53
 
40
- private
54
+ def stop_pagination?(bookmarks, pages_fetched, max_pages, pins)
55
+ bookmarks.empty? || bookmarks == ['-end-'] || pages_fetched >= max_pages || pins.empty?
56
+ end
41
57
 
42
58
  def parse_url(board_url)
43
59
  url = board_url.to_s
@@ -48,7 +64,8 @@ module PinterestDL
48
64
 
49
65
  uri = URI(url)
50
66
  parts = uri.path.to_s.split('/').reject(&:empty?)
51
- valid = uri.host.to_s.include?('pinterest') && [2, 3].include?(parts.size) && parts.first != 'pin'
67
+ valid = uri.host.to_s.include?('pinterest') && [2, 3].include?(parts.size) &&
68
+ !RESERVED_PATHS.include?(parts.first.to_s.downcase)
52
69
  raise PinterestDL::InvalidURLError, "Not a Pinterest board URL: #{board_url}" unless valid
53
70
 
54
71
  parts
@@ -57,10 +74,11 @@ module PinterestDL
57
74
  end
58
75
 
59
76
  def start_session(username, slug)
60
- response = @client.raw_get("https://www.pinterest.com/#{username}/#{slug}/")
61
- @page_url = @client.last_url
62
- @host = URI(@page_url).host
63
- @source_path = URI(@page_url).path
77
+ target = "https://www.pinterest.com/#{username}/#{slug}/"
78
+ response = @client.raw_get(target)
79
+ @page_url = @client.last_url || target
80
+ @host = URI(@page_url).host || 'www.pinterest.com'
81
+ @source_path = URI(@page_url).path || "/#{username}/#{slug}/"
64
82
  response.body
65
83
  end
66
84
 
@@ -80,11 +98,12 @@ module PinterestDL
80
98
  end
81
99
  end
82
100
  end
83
- nil
101
+ html.to_s[/"board_id"\s*:\s*"(\d+)"/, 1]
84
102
  end
85
103
 
86
104
  def board_node?(node, slug)
87
- node['type'] == 'board' && node['id'].to_s.match?(/\A\d+\z/) && node['url'].to_s.include?("/#{slug}/")
105
+ node['type'] == 'board' && node['id'].to_s.match?(/\A\d+\z/) &&
106
+ node['url'].to_s.downcase.include?("/#{slug.to_s.downcase}/")
88
107
  end
89
108
 
90
109
  def find_board_id(username, slug)
@@ -93,10 +112,11 @@ module PinterestDL
93
112
  id = data.is_a?(Hash) && data['id']
94
113
  raise PinterestDL::NotFoundError, "Board not found: #{username}/#{slug} (private boards need --cookies)" unless id
95
114
 
96
- id
115
+ id.to_s
97
116
  end
98
117
 
99
118
  def feed_request(board_id, section)
119
+ @section = section
100
120
  unless section
101
121
  options = {
102
122
  board_id: board_id,
@@ -116,7 +136,7 @@ module PinterestDL
116
136
  def find_section_id(board_id, slug)
117
137
  json = call_resource('BoardSectionsResource', board_id: board_id)
118
138
  data = json.dig('resource_response', 'data')
119
- found = data.is_a?(Array) && data.find { |s| s['slug'] == slug }
139
+ found = data.is_a?(Array) && data.find { |s| s['slug'].to_s.casecmp?(slug.to_s) }
120
140
  raise PinterestDL::NotFoundError, "Section not found: #{slug}" unless found
121
141
 
122
142
  found['id']
@@ -143,31 +163,20 @@ module PinterestDL
143
163
  end
144
164
 
145
165
  def api_headers
166
+ handler = @section ? 'www/[username]/[slug]/[section_slug].js' : 'www/[username]/[slug].js'
146
167
  {
147
168
  'Accept' => 'application/json, text/javascript, */*, q=0.01',
148
169
  'X-Requested-With' => 'XMLHttpRequest',
149
- 'X-Pinterest-PWS-Handler' => 'www/[username]/[slug].js',
170
+ 'X-Pinterest-AppState' => 'active',
171
+ 'X-Pinterest-Source-Url' => @source_path,
172
+ 'X-Pinterest-PWS-Handler' => handler,
150
173
  'X-CSRFToken' => @client.cookie('csrftoken', @page_url) || 'undefined',
151
174
  'Referer' => @page_url
152
175
  }
153
176
  end
154
177
 
155
178
  def build_pin(raw)
156
- return nil unless raw.is_a?(Hash)
157
- return nil if raw['type'] && raw['type'] != 'pin'
158
-
159
- id = raw['id']
160
- return nil unless id
161
-
162
- {
163
- id: id,
164
- pin_url: "https://www.pinterest.com/pin/#{id}/",
165
- title: raw['title'] || raw['grid_title'],
166
- description: raw['description'],
167
- creator: raw.dig('pinner', 'username') || raw.dig('pinner', 'full_name'),
168
- image_url: raw.dig('images', 'orig', 'url'),
169
- video_url: PinterestDL::Extractors::PinData.first_video_url(raw)
170
- }
179
+ PinterestDL::Extractors::PinData.build_pin_hash(raw, quality: @config.quality)
171
180
  end
172
181
  end
173
182
  end
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Monji024
3
+
4
4
  require 'net/http'
5
5
  require 'uri'
6
6
  require 'openssl'
@@ -36,7 +36,10 @@ module PinterestDL
36
36
  end
37
37
 
38
38
  def cookie(name, url = @last_url)
39
- @cookies[site_key(URI(url))][name]
39
+ target = url.to_s.empty? ? 'https://www.pinterest.com' : url.to_s
40
+ @cookies[site_key(URI(target))][name]
41
+ rescue URI::InvalidURIError
42
+ nil
40
43
  end
41
44
 
42
45
  def clear_cache
@@ -93,6 +96,8 @@ module PinterestDL
93
96
  "Rate limited while requesting #{url}",
94
97
  retry_after: response['Retry-After']
95
98
  )
99
+ when Net::HTTPUnauthorized
100
+ raise PinterestDL::AuthenticationError, "Authentication required for #{url}"
96
101
  when Net::HTTPNotFound
97
102
  raise PinterestDL::NotFoundError, "Nothing found at #{url}"
98
103
  when Net::HTTPForbidden
@@ -133,12 +138,15 @@ module PinterestDL
133
138
  name, value = line.split(';').first.to_s.split('=', 2)
134
139
  next if name.nil? || value.nil?
135
140
 
136
- value.empty? ? jar.delete(name.strip) : jar[name.strip] = value
141
+ value.strip.empty? ? jar.delete(name.strip) : jar[name.strip] = value.strip
137
142
  end
138
143
  end
139
144
 
140
145
  def site_key(uri)
141
- uri.host.to_s.split('.').last(2).join('.')
146
+ host = uri.host.to_s.downcase
147
+ return 'pinterest.com' if host.include?('pinterest.')
148
+
149
+ host.split('.').last(2).join('.')
142
150
  end
143
151
 
144
152
  def throttle!
@@ -6,7 +6,7 @@ module PinterestDL
6
6
  class Configuration
7
7
  DEFAULT_USER_AGENT =
8
8
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' \
9
- '(KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'
9
+ '(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
10
10
 
11
11
  VALID_QUALITIES = %i[originals 736x 474x 236x].freeze
12
12
 
@@ -17,6 +17,10 @@ module PinterestDL
17
17
  attr_reader :quality
18
18
 
19
19
  def initialize
20
+ reset!
21
+ end
22
+
23
+ def reset!
20
24
  @user_agent = DEFAULT_USER_AGENT
21
25
  @cookies = nil
22
26
  @open_timeout = 10
@@ -25,10 +29,8 @@ module PinterestDL
25
29
  @retry_wait = 1.0
26
30
  @quality = :originals
27
31
  @rate_limit_interval = 0.0
28
- @logger = Logger.new($stdout).tap do |log|
29
- log.level = Logger::WARN
30
- log.formatter = proc { |severity, _time, _progname, msg| "[pinterest-dl] #{severity}: #{msg}\n" }
31
- end
32
+ @logger = default_logger
33
+ self
32
34
  end
33
35
 
34
36
  def quality=(value)
@@ -40,7 +42,16 @@ module PinterestDL
40
42
  end
41
43
 
42
44
  def authenticated?
43
- !cookies.nil? && !cookies.to_s.empty?
45
+ !cookies.nil? && !cookies.to_s.strip.empty?
46
+ end
47
+
48
+ private
49
+
50
+ def default_logger
51
+ Logger.new($stdout).tap do |log|
52
+ log.level = Logger::WARN
53
+ log.formatter = proc { |severity, _time, _progname, msg| "[pinterest-dl] #{severity}: #{msg}\n" }
54
+ end
44
55
  end
45
56
  end
46
57
  end
@@ -10,7 +10,8 @@ module PinterestDL
10
10
  end
11
11
 
12
12
  def download(url, path:)
13
- raise ArgumentError, 'url must not be nil/empty' if url.to_s.empty?
13
+ raise ArgumentError, 'url must not be nil/empty' if url.to_s.strip.empty?
14
+ raise ArgumentError, 'path must not be nil/empty' if path.to_s.strip.empty?
14
15
 
15
16
  FileUtils.mkdir_p(File.dirname(path))
16
17
  response = @client.raw_get(url)
@@ -47,8 +48,8 @@ module PinterestDL
47
48
  private
48
49
 
49
50
  def default_filename(url, index)
50
- ext = File.extname(URI(url).path)
51
- ext = '.jpg' if ext.nil? || ext.empty?
51
+ ext = File.extname(URI(url).path.to_s)[/\A\.[A-Za-z0-9]{2,5}\z/]
52
+ ext ||= '.jpg'
52
53
  format('%<index>04d%<ext>s', index: index + 1, ext: ext)
53
54
  rescue URI::InvalidURIError
54
55
  format('%<index>04d.jpg', index: index + 1)
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Monji024
3
+
4
4
  module PinterestDL
5
5
  class Error < StandardError
6
6
  end
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Monji024
3
+
4
4
  module PinterestDL
5
5
  module Extractors
6
6
  module Image
@@ -29,14 +29,14 @@ module PinterestDL
29
29
  end
30
30
 
31
31
  def from_raw_pattern(html)
32
- match = html.match(
32
+ match = html.to_s.match(
33
33
  %r{https://i\.pinimg\.com/(?:originals|736x|474x|236x)/[A-Za-z0-9_\-/]+\.(?:jpg|jpeg|png|gif|webp)}i
34
34
  )
35
35
  match && match[0]
36
36
  end
37
37
 
38
38
  def apply_quality(url, quality)
39
- return url unless url.include?('i.pinimg.com')
39
+ return url unless url.to_s.include?('i.pinimg.com')
40
40
 
41
41
  target = QUALITY_PATH[quality.to_sym]
42
42
  return url unless target
@@ -5,7 +5,8 @@ require 'json'
5
5
  module PinterestDL
6
6
  module Extractors
7
7
  module PinData
8
- SCRIPT_PATTERN = %r{<script[^>]*id=["']__PWS_[A-Z_]+__["'][^>]*>(.*?)</script>}m.freeze
8
+ SCRIPT_PATTERN =
9
+ %r{<script[^>]*(?:id=["']__PWS_[A-Z_]+__["']|data-relay-response=["']true["'])[^>]*>(.*?)</script>}m.freeze
9
10
 
10
11
  module_function
11
12
 
@@ -24,15 +25,67 @@ module PinterestDL
24
25
  found
25
26
  end
26
27
 
28
+ def extract_pins(html, quality: :originals)
29
+ pins = []
30
+ html.to_s.scan(SCRIPT_PATTERN).each do |(raw)|
31
+ stack = [safe_parse(raw)]
32
+ until stack.empty?
33
+ node = stack.pop
34
+ case node
35
+ when Hash
36
+ pin = build_pin_hash(node, quality: quality)
37
+ pins << pin if pin
38
+ stack.concat(node.values)
39
+ when Array
40
+ stack.concat(node)
41
+ end
42
+ end
43
+ end
44
+ pins
45
+ end
46
+
47
+ def build_pin_hash(raw, quality: :originals)
48
+ return nil unless raw.is_a?(Hash)
49
+ return nil if raw['type'] && raw['type'] != 'pin'
50
+
51
+ id = raw['id']
52
+ img = best_image_url(raw)
53
+ video = first_video_url(raw)
54
+ return nil unless id && (img || video)
55
+
56
+ {
57
+ id: id.to_s,
58
+ pin_url: "https://www.pinterest.com/pin/#{id}/",
59
+ title: raw['title'] || raw['grid_title'],
60
+ description: raw['description'],
61
+ creator: raw.dig('pinner', 'username') || raw.dig('pinner', 'full_name'),
62
+ image_url: img && PinterestDL::Extractors::Image.apply_quality(img, quality),
63
+ video_url: video
64
+ }
65
+ end
66
+
27
67
  def build_result(pin)
28
68
  {
29
- image_url: pin.dig('images', 'orig', 'url'),
69
+ image_url: best_image_url(pin),
30
70
  video_url: first_video_url(pin),
31
71
  title: pin['title'] || pin['grid_title'],
32
- description: pin['description']
72
+ description: pin['description'],
73
+ creator: pin.dig('pinner', 'username') || pin.dig('pinner', 'full_name')
33
74
  }
34
75
  end
35
76
 
77
+ def best_image_url(pin)
78
+ return nil unless pin.is_a?(Hash)
79
+
80
+ orig = pin.dig('images', 'orig', 'url')
81
+ return orig if orig
82
+
83
+ images = pin['images']
84
+ return nil unless images.is_a?(Hash)
85
+
86
+ images.values.filter_map { |v| v['url'] if v.is_a?(Hash) }.last
87
+ end
88
+
36
89
  def parse_embedded_json(html)
37
90
  html.to_s.scan(SCRIPT_PATTERN).each do |(raw)|
38
91
  parsed = safe_parse(raw)
@@ -62,8 +115,7 @@ module PinterestDL
62
115
  end
63
116
 
64
117
  def pin_like?(node)
65
- images = node['images']
66
- images.is_a?(Hash) && images.dig('orig', 'url')
118
+ !best_image_url(node).nil?
67
119
  end
68
120
 
69
121
  def has_media?(node)
@@ -71,6 +123,8 @@ module PinterestDL
71
123
  end
72
124
 
73
125
  def first_video_url(pin)
126
+ return nil unless pin.is_a?(Hash)
127
+
74
128
  video_list = pin.dig('videos', 'video_list')
75
129
  video_list = deep_find(pin['story_pin_data'], 'video_list') unless video_list.is_a?(Hash)
76
130
  best_video(video_list)
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Monji024
4
3
  module PinterestDL
5
4
  module Extractors
6
5
  module Video
@@ -22,18 +21,18 @@ module PinterestDL
22
21
  end
23
22
 
24
23
  def from_content_url(html)
25
- match = html.match(/"contentUrl"\s*:\s*"([^"]+\.mp4[^"]*)"/)
24
+ match = html.to_s.match(/"contentUrl"\s*:\s*"([^"]+\.mp4[^"]*)"/)
26
25
  match && match[1]
27
26
  end
28
27
 
29
28
  def from_raw_pattern(html)
30
- clean = html.gsub('\\u002F', '/').gsub('\\/', '/')
29
+ clean = html.to_s.gsub('\\u002F', '/').gsub('\\/', '/')
31
30
  match = clean.match(%r{https://v\d*\.pinimg\.com/videos/[^"'\s\\<>]+?\.mp4})
32
31
  match && match[0]
33
32
  end
34
33
 
35
34
  def unescape(url)
36
- url.gsub('\\u002F', '/').gsub('\\', '')
35
+ url.to_s.gsub('\\u002F', '/').gsub('\\', '')
37
36
  end
38
37
  end
39
38
 
@@ -56,13 +55,24 @@ module PinterestDL
56
55
 
57
56
  def content_url(html, type)
58
57
  html.to_s.scan(%r{<script[^>]*type=["']application/ld\+json["'][^>]*>(.*?)</script>}m).each do |(raw)|
59
- data = safe_parse(raw)
60
- next unless data
61
-
62
- data = data[0] if data.is_a?(Array) && !data.empty?
63
- next unless data.is_a?(Hash)
58
+ found = find_type_url(safe_parse(raw), type)
59
+ return found if found
60
+ end
61
+ nil
62
+ end
64
63
 
65
- return data['contentUrl'] if data['@type'] == type && data['contentUrl']
64
+ def find_type_url(node, type)
65
+ stack = [node]
66
+ until stack.empty?
67
+ current = stack.pop
68
+ case current
69
+ when Hash
70
+ return current['contentUrl'] if current['@type'] == type && current['contentUrl']
71
+
72
+ stack.concat(current.values)
73
+ when Array
74
+ stack.concat(current)
75
+ end
66
76
  end
67
77
  nil
68
78
  end
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Monji024
4
3
  module PinterestDL
5
4
  module MediaType
6
5
  TYPES = %i[all image video pin].freeze
@@ -8,8 +7,8 @@ module PinterestDL
8
7
  module_function
9
8
 
10
9
  def parse(value)
11
- type = (value || :all).to_sym
12
- return type if TYPES.include?(type)
10
+ normalized = value.nil? || value.to_s.strip.empty? ? :all : value.to_s.strip.downcase.to_sym
11
+ return normalized if TYPES.include?(normalized)
13
12
 
14
13
  raise ArgumentError, "type must be one of: #{TYPES.join(', ')}"
15
14
  end
@@ -1,19 +1,18 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Monji024
4
3
  module PinterestDL
5
4
  class ProgressBar
6
5
  def initialize(total:, width: 30, out: $stdout)
7
- @total = total.zero? ? 1 : total
6
+ @total = total.to_i <= 0 ? 1 : total.to_i
8
7
  @width = width
9
8
  @out = out
10
9
  end
11
10
 
12
11
  def update(done)
13
- ratio = done.to_f / @total
12
+ ratio = [[done.to_f / @total, 0.0].max, 1.0].min
14
13
  filled = (@width * ratio).round
15
14
  bar = ('#' * filled) + ('-' * (@width - filled))
16
- @out.print "\r[#{bar}] #{done}/#{@total} (#{(ratio * 100).round}%)"
15
+ @out.print "\r[#{bar}] #{done}/#{@total} (#{((done.to_f / @total) * 100).round}%)"
17
16
  @out.print "\n" if done >= @total
18
17
  @out.flush
19
18
  end
@@ -14,30 +14,47 @@ module PinterestDL
14
14
  end
15
15
 
16
16
  def call(query, limit: 25, pages: 5, type: :all)
17
+ raise ArgumentError, 'query must not be empty' if query.to_s.strip.empty?
18
+
19
+ session = establish_session(query)
20
+ results = collect_pages(session, query, limit: limit, pages: pages, type: type)
21
+ if results.empty?
22
+ fallback = PinterestDL::Extractors::PinData.extract_pins(session[:html], quality: @config.quality)
23
+ results = PinterestDL::MediaType.filter(fallback, type)
24
+ end
25
+ results.first(limit)
26
+ end
27
+
28
+ private
29
+
30
+ def collect_pages(session, query, limit:, pages:, type:)
17
31
  results = []
32
+ seen = {}
18
33
  bookmarks = nil
19
34
  pages_fetched = 0
20
35
 
21
36
  loop do
22
- page = fetch_page(query, bookmarks: bookmarks)
23
- pins = page[:pins]
24
- results.concat(PinterestDL::MediaType.filter(pins, type))
37
+ page = fetch_page(session, query, bookmarks: bookmarks)
38
+ PinterestDL::MediaType.filter(page[:pins], type).each do |pin|
39
+ next if seen[pin[:id]]
40
+
41
+ seen[pin[:id]] = true
42
+ results << pin
43
+ end
25
44
  bookmarks = page[:bookmarks]
26
45
  pages_fetched += 1
27
46
 
28
- break if results.size >= limit
29
- break if bookmarks.nil? || bookmarks.empty? || bookmarks == ['-end-']
30
- break if pages_fetched >= pages
31
- break if pins.empty?
47
+ break if results.size >= limit || stop_pagination?(bookmarks, pages_fetched, pages, page[:pins])
32
48
  end
33
49
 
34
- results.first(limit)
50
+ results
35
51
  end
36
52
 
37
- private
53
+ def stop_pagination?(bookmarks, pages_fetched, max_pages, pins)
54
+ bookmarks.nil? || bookmarks.empty? || bookmarks == ['-end-'] || pages_fetched >= max_pages || pins.empty?
55
+ end
38
56
 
39
- def fetch_page(query, bookmarks: nil)
40
- session = establish_session(query)
57
+ def fetch_page(session, query, bookmarks: nil)
41
58
  body = @client.get(
42
59
  build_search_url(session[:source_path], query, bookmarks),
43
60
  use_cache: false,
@@ -49,13 +66,21 @@ module PinterestDL
49
66
 
50
67
  parse_search_response(json)
51
68
  end
69
+
52
70
  def establish_session(query)
53
71
  source_path = "/search/pins/?q=#{URI.encode_www_form_component(query)}"
54
72
  home_uri = URI("https://www.pinterest.com#{source_path}")
55
73
  home_response = @client.raw_get(home_uri.to_s)
56
74
  cookies = (home_response.get_fields('set-cookie') || []).map { |c| c.split(';').first }
75
+ csrf = @client.cookie('csrftoken', home_uri.to_s) || csrf_token(cookies)
57
76
 
58
- { source_path: source_path, home_uri: home_uri, cookies: cookies, csrf: csrf_token(cookies) }
77
+ {
78
+ source_path: source_path,
79
+ home_uri: home_uri,
80
+ cookies: cookies,
81
+ csrf: csrf,
82
+ html: home_response.body
83
+ }
59
84
  end
60
85
 
61
86
  def csrf_token(cookies)
@@ -75,58 +100,35 @@ module PinterestDL
75
100
 
76
101
  def search_headers(session)
77
102
  cookie_header = [@config.cookies, session[:cookies].join('; ')].compact.reject(&:empty?).join('; ')
78
-
79
- {
103
+ headers = {
80
104
  'Accept' => 'application/json, text/javascript, */*, q=0.01',
81
105
  'X-Requested-With' => 'XMLHttpRequest',
106
+ 'X-Pinterest-AppState' => 'active',
107
+ 'X-Pinterest-Source-Url' => session[:source_path],
82
108
  'X-Pinterest-PWS-Handler' => 'www/search/[scope].js',
83
109
  'X-CSRFToken' => session[:csrf],
84
- 'Referer' => session[:home_uri].to_s,
85
- 'Cookie' => cookie_header
110
+ 'Referer' => session[:home_uri].to_s
86
111
  }
112
+ headers['Cookie'] = cookie_header unless cookie_header.empty?
113
+ headers
87
114
  end
88
115
 
89
116
  def parse_search_response(json)
90
- data_node = json.dig('resource_response', 'data') || {}
91
- raw_results = data_node['results'] || []
117
+ data_node = json.dig('resource_response', 'data')
118
+ raw_results =
119
+ case data_node
120
+ when Array then data_node
121
+ when Hash then data_node['results'] || []
122
+ else []
123
+ end
92
124
  next_bookmarks = json.dig('resource_response', 'bookmark') ||
93
- json.dig('resource', 'options', 'bookmarks')
125
+ json.dig('resource', 'options', 'bookmarks')
94
126
 
95
127
  { pins: raw_results.filter_map { |r| build_pin(r) }, bookmarks: Array(next_bookmarks) }
96
128
  end
97
129
 
98
130
  def build_pin(raw)
99
- id = raw['id']
100
- return nil unless id
101
-
102
- {
103
- id: id,
104
- pin_url: "https://www.pinterest.com/pin/#{id}/",
105
- title: raw['title'] || raw['grid_title'],
106
- description: raw['description'],
107
- creator: pin_creator(raw),
108
- image_url: pin_image_url(raw),
109
- video_url: first_video_url(raw)
110
- }
111
- end
112
-
113
- def pin_creator(raw)
114
- raw.dig('pinner', 'username') || raw.dig('pinner', 'full_name')
115
- end
116
-
117
- def pin_image_url(raw)
118
- raw.dig('images', 'orig', 'url') || fallback_image_url(raw)
119
- end
120
-
121
- def fallback_image_url(raw)
122
- images = raw['images']
123
- return nil unless images
124
-
125
- images.values.filter_map { |v| v['url'] if v.is_a?(Hash) }.last
126
- end
127
-
128
- def first_video_url(raw)
129
- PinterestDL::Extractors::PinData.first_video_url(raw)
131
+ PinterestDL::Extractors::PinData.build_pin_hash(raw, quality: @config.quality)
130
132
  end
131
133
 
132
134
  def safe_parse(body)
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Monji024
4
3
  module PinterestDL
5
- VERSION = '2.1.5'
4
+ VERSION = '2.2.0'
6
5
  end
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.1.5
4
+ version: 2.2.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-10-14 00:00:00.000000000 Z
11
+ date: 2026-11-03 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