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 +4 -4
- data/CHANGELOG.md +30 -2
- data/README.md +77 -45
- data/bin/pinterest-dl +79 -28
- data/lib/pinterest-dl.rb +1 -1
- data/lib/pinterest_dl/api.rb +35 -18
- data/lib/pinterest_dl/board.rb +41 -32
- data/lib/pinterest_dl/client.rb +120 -29
- data/lib/pinterest_dl/configuration.rb +64 -13
- data/lib/pinterest_dl/downloader.rb +155 -17
- data/lib/pinterest_dl/errors.rb +1 -1
- data/lib/pinterest_dl/extractors/image.rb +9 -6
- data/lib/pinterest_dl/extractors/pin_data.rb +59 -5
- data/lib/pinterest_dl/extractors/video.rb +20 -10
- data/lib/pinterest_dl/media_type.rb +2 -3
- data/lib/pinterest_dl/progress_bar.rb +3 -4
- data/lib/pinterest_dl/search.rb +52 -50
- data/lib/pinterest_dl/version.rb +1 -2
- metadata +2 -2
|
@@ -1,39 +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:)
|
|
13
|
-
raise ArgumentError, 'url must not be nil/empty' if url.to_s.empty?
|
|
22
|
+
def download(url, path:, overwrite: nil)
|
|
23
|
+
raise ArgumentError, 'url must not be nil/empty' if url.to_s.strip.empty?
|
|
24
|
+
raise ArgumentError, 'path must not be nil/empty' if path.to_s.strip.empty?
|
|
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?
|
|
14
28
|
|
|
15
29
|
FileUtils.mkdir_p(File.dirname(path))
|
|
16
|
-
|
|
17
|
-
|
|
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)
|
|
18
34
|
path
|
|
19
35
|
rescue PinterestDL::Error
|
|
36
|
+
cleanup_part(part_path)
|
|
20
37
|
raise
|
|
21
38
|
rescue StandardError => e
|
|
39
|
+
cleanup_part(part_path)
|
|
22
40
|
raise PinterestDL::DownloadError, "Could not download #{url} to #{path}: #{e.message}"
|
|
23
41
|
end
|
|
24
42
|
|
|
25
|
-
def download_batch(urls, dir:, filename: nil, &progress)
|
|
43
|
+
def download_batch(urls, dir:, filename: nil, concurrency: nil, overwrite: nil, &progress)
|
|
26
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)
|
|
27
79
|
succeeded = []
|
|
28
80
|
failed = []
|
|
81
|
+
skipped = []
|
|
29
82
|
total = urls.size
|
|
83
|
+
should_overwrite = overwrite.nil? ? (@config.respond_to?(:overwrite) ? @config.overwrite : true) : overwrite
|
|
30
84
|
|
|
31
|
-
urls.each_with_index do |
|
|
32
|
-
|
|
33
|
-
path = File.join(dir, name)
|
|
85
|
+
urls.each_with_index do |item, index|
|
|
86
|
+
url, path = resolve_target(item, index, dir, filename)
|
|
34
87
|
begin
|
|
35
|
-
|
|
36
|
-
|
|
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
|
|
37
95
|
rescue PinterestDL::Error => e
|
|
38
96
|
@config.logger.warn("failed to download #{url}: #{e.message}")
|
|
39
97
|
failed << { url: url, error: e }
|
|
@@ -41,17 +99,97 @@ module PinterestDL
|
|
|
41
99
|
progress&.call(index + 1, total, url)
|
|
42
100
|
end
|
|
43
101
|
|
|
44
|
-
{ succeeded: succeeded, failed: failed }
|
|
102
|
+
{ succeeded: succeeded, failed: failed, skipped: skipped }
|
|
45
103
|
end
|
|
46
104
|
|
|
47
|
-
|
|
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
|
|
48
178
|
|
|
49
179
|
def default_filename(url, index)
|
|
50
|
-
ext
|
|
51
|
-
|
|
52
|
-
|
|
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'
|
|
53
186
|
rescue URI::InvalidURIError
|
|
54
|
-
|
|
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
|
|
55
193
|
end
|
|
56
194
|
end
|
|
57
|
-
end
|
|
195
|
+
end
|
data/lib/pinterest_dl/errors.rb
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
# Monji024
|
|
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)
|
|
@@ -29,20 +32,20 @@ module PinterestDL
|
|
|
29
32
|
end
|
|
30
33
|
|
|
31
34
|
def from_raw_pattern(html)
|
|
32
|
-
match = html.match(
|
|
33
|
-
%r{https://i
|
|
35
|
+
match = html.to_s.match(
|
|
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.
|
|
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
|
|
@@ -5,7 +5,8 @@ require 'json'
|
|
|
5
5
|
module PinterestDL
|
|
6
6
|
module Extractors
|
|
7
7
|
module PinData
|
|
8
|
-
SCRIPT_PATTERN =
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
58
|
+
found = find_type_url(safe_parse(raw), type)
|
|
59
|
+
return found if found
|
|
60
|
+
end
|
|
61
|
+
nil
|
|
62
|
+
end
|
|
64
63
|
|
|
65
|
-
|
|
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
|
-
|
|
12
|
-
return
|
|
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.
|
|
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} (#{(
|
|
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
|
data/lib/pinterest_dl/search.rb
CHANGED
|
@@ -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
|
-
|
|
24
|
-
|
|
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
|
|
50
|
+
results
|
|
35
51
|
end
|
|
36
52
|
|
|
37
|
-
|
|
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
|
-
{
|
|
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 =
|
|
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
|
-
|
|
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
|
-
|
|
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)
|
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
|
+
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
|