pinterest-dl 2.3.0 → 2.5.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.
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'errors'
4
+
5
+ module PinterestDL
6
+ module MediaValidator
7
+ ALLOWED_CONTENT_TYPES = %w[
8
+ image/jpeg
9
+ image/jpg
10
+ image/png
11
+ image/gif
12
+ image/webp
13
+ image/avif
14
+ image/bmp
15
+ video/mp4
16
+ video/quicktime
17
+ video/webm
18
+ application/octet-stream
19
+ binary/octet-stream
20
+ ].freeze
21
+
22
+ REJECTED_CONTENT_TYPES = %w[
23
+ text/html
24
+ application/xhtml+xml
25
+ application/json
26
+ text/plain
27
+ text/xml
28
+ application/xml
29
+ text/javascript
30
+ application/javascript
31
+ ].freeze
32
+
33
+ JPEG_MAGIC = "\xFF\xD8\xFF".b.freeze
34
+ PNG_MAGIC = "\x89PNG\r\n\x1A\n".b.freeze
35
+ GIF87_MAGIC = 'GIF87a'.b.freeze
36
+ GIF89_MAGIC = 'GIF89a'.b.freeze
37
+ RIFF_MAGIC = 'RIFF'.b.freeze
38
+ WEBP_MAGIC = 'WEBP'.b.freeze
39
+ BMP_MAGIC = 'BM'.b.freeze
40
+ FTYP_MAGIC = 'ftyp'.b.freeze
41
+ EBML_MAGIC = "\x1A\x45\xDF\xA3".b.freeze
42
+
43
+ module_function
44
+
45
+ def validate_content_type!(content_type, url: nil)
46
+ return true if content_type.nil? || content_type.to_s.strip.empty?
47
+
48
+ mime = content_type.to_s.split(';').first.to_s.strip.downcase
49
+ return true if mime.empty?
50
+
51
+ if REJECTED_CONTENT_TYPES.include?(mime)
52
+ raise InvalidMediaError.new(
53
+ "Rejected non-media Content-Type #{mime.inspect} from #{url}",
54
+ url: url,
55
+ content_type: mime
56
+ )
57
+ end
58
+
59
+ return true if ALLOWED_CONTENT_TYPES.include?(mime) || mime.start_with?('image/', 'video/')
60
+
61
+ raise InvalidMediaError.new(
62
+ "Unsupported Content-Type #{mime.inspect} from #{url}",
63
+ url: url,
64
+ content_type: mime
65
+ )
66
+ end
67
+
68
+ def detect_signature(bytes)
69
+ return nil if bytes.nil?
70
+
71
+ raw = bytes.b
72
+ return :jpeg if raw.start_with?(JPEG_MAGIC)
73
+ return :png if raw.start_with?(PNG_MAGIC)
74
+ return :gif if raw.start_with?(GIF87_MAGIC) || raw.start_with?(GIF89_MAGIC)
75
+ return :webp if raw.bytesize >= 12 && raw.start_with?(RIFF_MAGIC) && raw.byteslice(8, 4) == WEBP_MAGIC
76
+ return :bmp if raw.start_with?(BMP_MAGIC)
77
+ return :mp4 if raw.bytesize >= 8 && raw.byteslice(4, 4) == FTYP_MAGIC
78
+ return :webm if raw.start_with?(EBML_MAGIC)
79
+
80
+ nil
81
+ end
82
+
83
+ def looks_like_html_or_json?(bytes)
84
+ return false if bytes.nil?
85
+
86
+ head = bytes.b.byteslice(0, 256).to_s.lstrip
87
+ return false if head.empty?
88
+
89
+ head.start_with?('<!DOCTYPE', '<html', '<HTML', '<head', '<script', '{"error"', '{"status"')
90
+ end
91
+
92
+ def validate_file_content!(path, url: nil, strict_magic: false)
93
+ return false unless File.exist?(path)
94
+
95
+ size = File.size(path)
96
+ raise IncompleteDownloadError.new("Downloaded file at #{path} is empty (0 bytes)", url: url, received_bytes: 0) if size.zero?
97
+
98
+ header = File.binread(path, 256)
99
+ if looks_like_html_or_json?(header)
100
+ raise InvalidMediaError.new("Downloaded payload from #{url} appears to be HTML or JSON instead of media", url: url)
101
+ end
102
+
103
+ if strict_magic && detect_signature(header).nil?
104
+ raise InvalidMediaError.new("Unrecognized media file signature from #{url}", url: url)
105
+ end
106
+
107
+ true
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module PinterestDL
6
+ class Pin
7
+ ATTRIBUTES = %i[id pin_url title description creator image_url video_url width height].freeze
8
+
9
+ attr_reader(*ATTRIBUTES)
10
+
11
+ def initialize(id:, pin_url: nil, title: nil, description: nil, creator: nil,
12
+ image_url: nil, video_url: nil, width: nil, height: nil)
13
+ @id = id.to_s
14
+ @pin_url = pin_url || "https://www.pinterest.com/pin/#{@id}/"
15
+ @title = title
16
+ @description = description
17
+ @creator = creator
18
+ @image_url = image_url
19
+ @video_url = video_url
20
+ @width = width
21
+ @height = height
22
+ end
23
+
24
+ def [](key)
25
+ sym = key.to_sym
26
+ return nil unless ATTRIBUTES.include?(sym)
27
+
28
+ public_send(sym)
29
+ end
30
+
31
+ def dig(first_key, *rest)
32
+ val = self[first_key]
33
+ return val if rest.empty? || val.nil?
34
+
35
+ val.respond_to?(:dig) ? val.dig(*rest) : nil
36
+ end
37
+
38
+ def fetch(key, *default, &block)
39
+ sym = key.to_sym
40
+ return public_send(sym) if ATTRIBUTES.include?(sym)
41
+ return yield(key) if block
42
+ return default.first unless default.empty?
43
+
44
+ raise KeyError, "key not found: #{key.inspect}"
45
+ end
46
+
47
+ def key?(key)
48
+ ATTRIBUTES.include?(key.to_sym)
49
+ end
50
+ alias has_key? key?
51
+ alias include? key?
52
+
53
+ def video?
54
+ !@video_url.nil? && !@video_url.empty?
55
+ end
56
+
57
+ def image?
58
+ !@image_url.nil? && !@image_url.empty? && !video?
59
+ end
60
+
61
+ def media_type
62
+ video? ? :video : :image
63
+ end
64
+
65
+ def primary_media_url
66
+ @video_url || @image_url
67
+ end
68
+
69
+ def to_h
70
+ {
71
+ id: @id,
72
+ pin_url: @pin_url,
73
+ title: @title,
74
+ description: @description,
75
+ creator: @creator,
76
+ image_url: @image_url,
77
+ video_url: @video_url
78
+ }
79
+ end
80
+ alias to_hash to_h
81
+
82
+ def deconstruct_keys(_keys)
83
+ to_h
84
+ end
85
+
86
+ def to_json(*args)
87
+ to_h.to_json(*args)
88
+ end
89
+
90
+ def ==(other)
91
+ case other
92
+ when Pin then to_h == other.to_h
93
+ when Hash then to_h == other.transform_keys(&:to_sym).slice(*ATTRIBUTES)
94
+ else false
95
+ end
96
+ end
97
+ alias eql? ==
98
+
99
+ def hash
100
+ to_h.hash
101
+ end
102
+ end
103
+
104
+ class DownloadReport
105
+ attr_reader :succeeded, :failed, :skipped, :resumed, :duplicates,
106
+ :bytes_downloaded, :elapsed_seconds, :items
107
+
108
+ def initialize(succeeded: [], failed: [], skipped: [], resumed: [], duplicates: [],
109
+ bytes_downloaded: 0, elapsed_seconds: 0.0, items: [])
110
+ @succeeded = succeeded
111
+ @failed = failed
112
+ @skipped = skipped
113
+ @resumed = resumed
114
+ @duplicates = duplicates
115
+ @bytes_downloaded = bytes_downloaded.to_i
116
+ @elapsed_seconds = elapsed_seconds.to_f
117
+ @items = items
118
+ end
119
+
120
+ def [](key)
121
+ to_h[key.to_sym]
122
+ end
123
+
124
+ def dig(first_key, *rest)
125
+ to_h.dig(first_key.to_sym, *rest)
126
+ end
127
+
128
+ def total_count
129
+ @succeeded.size + @failed.size + @duplicates.size
130
+ end
131
+
132
+ def average_speed
133
+ return 0.0 if @elapsed_seconds <= 0.0
134
+
135
+ @bytes_downloaded / @elapsed_seconds
136
+ end
137
+
138
+ def success?
139
+ @failed.empty?
140
+ end
141
+
142
+ def to_h
143
+ {
144
+ succeeded: @succeeded,
145
+ failed: @failed,
146
+ skipped: @skipped,
147
+ resumed: @resumed,
148
+ duplicates: @duplicates,
149
+ bytes_downloaded: @bytes_downloaded,
150
+ elapsed_seconds: @elapsed_seconds.round(3),
151
+ average_speed: average_speed.round(2)
152
+ }
153
+ end
154
+ alias to_hash to_h
155
+
156
+ def to_json(*args)
157
+ serializable = to_h.merge(
158
+ failed: @failed.map do |entry|
159
+ {
160
+ url: entry[:url],
161
+ error: entry[:error].respond_to?(:message) ? entry[:error].message : entry[:error].to_s,
162
+ error_class: entry[:error].class.name
163
+ }
164
+ end
165
+ )
166
+ serializable.to_json(*args)
167
+ end
168
+ end
169
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'media_type'
4
+
5
+ module PinterestDL
6
+ class Paginator
7
+ include Enumerable
8
+
9
+ END_MARKERS = ['-end-', 'end', ''].freeze
10
+
11
+ def initialize(max_pages: 10, limit: nil, type: :all, &page_fetcher)
12
+ raise ArgumentError, 'Paginator requires a page_fetcher block' unless block_given?
13
+
14
+ @max_pages = [max_pages.to_i, 1].max
15
+ @limit = limit&.to_i
16
+ @type = MediaType.parse(type)
17
+ @page_fetcher = page_fetcher
18
+ end
19
+
20
+ def each
21
+ return enum_for(:each) unless block_given?
22
+
23
+ seen_pin_ids = {}
24
+ seen_bookmarks = {}
25
+ bookmarks = nil
26
+ pages_fetched = 0
27
+ yielded = 0
28
+
29
+ loop do
30
+ page = @page_fetcher.call(bookmarks, pages_fetched)
31
+ break unless page.is_a?(Hash)
32
+
33
+ raw_pins = Array(page[:pins])
34
+ filtered_pins = MediaType.filter(raw_pins, @type)
35
+
36
+ filtered_pins.each do |pin|
37
+ pin_id = pin[:id].to_s
38
+ next if !pin_id.empty? && seen_pin_ids[pin_id]
39
+
40
+ seen_pin_ids[pin_id] = true unless pin_id.empty?
41
+ yield pin
42
+ yielded += 1
43
+ break if @limit && yielded >= @limit
44
+ end
45
+ break if @limit && yielded >= @limit
46
+
47
+ next_bookmarks = normalize_bookmarks(page[:bookmarks])
48
+ pages_fetched += 1
49
+
50
+ break if stop?(next_bookmarks, seen_bookmarks, pages_fetched, raw_pins)
51
+
52
+ seen_bookmarks[bookmark_signature(next_bookmarks)] = true
53
+ bookmarks = next_bookmarks
54
+ end
55
+ end
56
+
57
+ def collect
58
+ to_a
59
+ end
60
+
61
+ private
62
+
63
+ def normalize_bookmarks(raw)
64
+ Array(raw).flatten.map { |b| b.to_s.strip }.reject(&:empty?)
65
+ end
66
+
67
+ def bookmark_signature(bookmarks)
68
+ bookmarks.join('|')
69
+ end
70
+
71
+ def stop?(bookmarks, seen_bookmarks, pages_fetched, raw_pins)
72
+ return true if pages_fetched >= @max_pages
73
+ return true if raw_pins.empty?
74
+ return true if bookmarks.empty?
75
+ return true if bookmarks.all? { |b| END_MARKERS.include?(b.downcase) }
76
+ return true if seen_bookmarks[bookmark_signature(bookmarks)]
77
+
78
+ false
79
+ end
80
+ end
81
+ end
@@ -1,20 +1,211 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ begin
4
+ require 'io/console'
5
+ rescue LoadError
6
+ nil
7
+ end
8
+
3
9
  module PinterestDL
4
10
  class ProgressBar
5
- def initialize(total:, width: 30, out: $stdout)
11
+ UNITS = %w[B KB MB GB TB].freeze
12
+ MAX_LABEL_LENGTH = 18
13
+
14
+ attr_reader :total, :width, :out, :enabled, :label, :media_type
15
+
16
+ def initialize(total: 0, width: 24, out: $stdout, enabled: true, label: nil, media_type: nil, byte_mode: false)
17
+ @byte_mode = byte_mode
18
+ @known_total = total.to_i.positive? && !byte_mode
6
19
  @total = total.to_i <= 0 ? 1 : total.to_i
7
20
  @width = width
8
21
  @out = out
22
+ @enabled = enabled
23
+ @label = label
24
+ @media_type = media_type
25
+ @started_at = monotonic_now
26
+ @last_received = 0
27
+ @last_total_bytes = nil
28
+ @last_line_len = 0
29
+ @finished_newline = false
30
+ @mutex = Mutex.new
31
+ end
32
+
33
+ def start(total_bytes: nil, label: nil, media_type: nil)
34
+ return unless @enabled
35
+
36
+ @mutex.synchronize do
37
+ @started_at = monotonic_now
38
+ @finished_newline = false
39
+ @last_line_len = 0
40
+ @label = label if label
41
+ @media_type = media_type if media_type
42
+ @last_total_bytes = total_bytes if total_bytes&.positive?
43
+ if @byte_mode && @last_total_bytes
44
+ render_byte_progress(0, @last_total_bytes, speed: 0.0, label: @label, media_type: @media_type)
45
+ end
46
+ end
47
+ end
48
+
49
+ def update(done, bytes_received: nil, total_bytes: nil, speed: nil, label: nil, media_type: nil)
50
+ return unless @enabled
51
+
52
+ @mutex.synchronize do
53
+ eff_label = label || @label
54
+ eff_type = media_type || @media_type
55
+ if @byte_mode || (bytes_received && total_bytes)
56
+ rec = bytes_received || done.to_i
57
+ tot = total_bytes || @last_total_bytes || (@known_total ? @total : nil)
58
+ @last_received = rec
59
+ @last_total_bytes = tot if tot&.positive?
60
+ render_byte_progress(rec, tot, speed: speed, label: eff_label, media_type: eff_type)
61
+ else
62
+ render_item_progress(done, label: eff_label, media_type: eff_type)
63
+ end
64
+ end
65
+ end
66
+
67
+ def finish(final_bytes: nil)
68
+ return unless @enabled
69
+
70
+ @mutex.synchronize do
71
+ if @byte_mode && !@finished_newline
72
+ rec = final_bytes || @last_received
73
+ tot = @last_total_bytes || (rec.positive? ? rec : nil)
74
+ render_byte_progress(rec, tot, speed: nil, label: @label, media_type: @media_type, force_complete: true)
75
+ end
76
+ unless @finished_newline
77
+ @out.print "\n"
78
+ @out.flush
79
+ @finished_newline = true
80
+ end
81
+ end
82
+ end
83
+
84
+ def self.format_bytes(bytes)
85
+ val = bytes.to_f
86
+ return '0 B' if val <= 0
87
+
88
+ idx = 0
89
+ while val >= 1024.0 && idx < UNITS.size - 1
90
+ val /= 1024.0
91
+ idx += 1
92
+ end
93
+ idx.zero? ? "#{val.to_i} #{UNITS[idx]}" : format('%<val>.1f %<unit>s', val: val, unit: UNITS[idx])
94
+ end
95
+
96
+ def self.format_eta(seconds)
97
+ return '--:--' if seconds.nil? || seconds.infinite? || seconds.nan? || seconds.negative?
98
+
99
+ sec = seconds.round
100
+ return '99:59+' if sec > 359_999
101
+
102
+ hours = sec / 3600
103
+ mins = (sec % 3600) / 60
104
+ rem = sec % 60
105
+ if hours.positive?
106
+ format('%<h>02d:%<m>02d:%<s>02d', h: hours, m: mins, s: rem)
107
+ else
108
+ format('%<m>02d:%<s>02d', m: mins, s: rem)
109
+ end
9
110
  end
10
111
 
11
- def update(done)
112
+ def self.truncate_label(text, max_len: MAX_LABEL_LENGTH)
113
+ str = text.to_s
114
+ return str if str.length <= max_len || max_len < 6
115
+
116
+ ext = File.extname(str)
117
+ if !ext.empty? && ext.length < max_len - 4
118
+ keep = max_len - ext.length - 2
119
+ head = [keep - 3, 3].max
120
+ tail = [keep - head, 1].max
121
+ stem = File.basename(str, ext)
122
+ "#{stem[0, head]}..#{stem[-tail, tail]}#{ext}"
123
+ else
124
+ "#{str[0, max_len - 2]}.."
125
+ end
126
+ end
127
+
128
+ private
129
+
130
+ def render_item_progress(done, label: nil, media_type: nil)
12
131
  ratio = [[done.to_f / @total, 0.0].max, 1.0].min
13
132
  filled = (@width * ratio).round
14
133
  bar = ('#' * filled) + ('-' * (@width - filled))
15
- @out.print "\r[#{bar}] #{done}/#{@total} (#{((done.to_f / @total) * 100).round}%)"
16
- @out.print "\n" if done >= @total
134
+ pct = ((done.to_f / @total) * 100).round
135
+ badge = media_type ? "[#{media_type.to_s.upcase}] " : ''
136
+ short_label = label && !label.empty? ? " #{self.class.truncate_label(label)}" : ''
137
+ line = "#{badge}[#{bar}] #{done}/#{@total} (#{pct}%)#{short_label}"
138
+ write_in_place(line, newline: done >= @total)
139
+ end
140
+
141
+ def render_byte_progress(received, total_bytes, speed: nil, label: nil, media_type: nil, force_complete: false)
142
+ return if @finished_newline && !force_complete
143
+
144
+ elapsed = [monotonic_now - @started_at, 0.001].max
145
+ current_speed = speed || (received.to_f / elapsed)
146
+ speed_str = "#{self.class.format_bytes(current_speed)}/s"
147
+ badge = media_type ? "[#{media_type.to_s.upcase}] " : ''
148
+ short_label = label && !label.empty? ? "#{self.class.truncate_label(label)} " : ''
149
+
150
+ if total_bytes&.positive?
151
+ ratio = force_complete ? 1.0 : [[received.to_f / total_bytes, 0.0].max, 1.0].min
152
+ pct = (ratio * 100).round
153
+ remaining = [total_bytes - received, 0].max
154
+ eta_sec = current_speed.positive? ? (remaining.to_f / current_speed) : nil
155
+ eta_str = ratio >= 1.0 ? '00:00' : self.class.format_eta(eta_sec)
156
+ size_str = "#{self.class.format_bytes(received)}/#{self.class.format_bytes(total_bytes)}"
157
+ tail = " #{pct}% #{size_str} #{speed_str} ETA #{eta_str}"
158
+ eff_width = adaptive_bar_width(badge.length + short_label.length + tail.length + 2)
159
+ filled = (eff_width * ratio).round
160
+ bar = ('#' * filled) + ('-' * (eff_width - filled))
161
+ line = "#{badge}#{short_label}[#{bar}]#{tail}"
162
+ write_in_place(line, newline: received >= total_bytes || force_complete)
163
+ else
164
+ size_str = self.class.format_bytes(received)
165
+ line = "#{badge}#{short_label}#{size_str} #{speed_str}"
166
+ write_in_place(line, newline: force_complete)
167
+ end
168
+ end
169
+
170
+ def adaptive_bar_width(non_bar_len)
171
+ cols = detect_terminal_columns
172
+ return @width unless cols&.positive?
173
+
174
+ available = cols - non_bar_len - 1
175
+ [[available, 6].max, @width].min
176
+ end
177
+
178
+ def detect_terminal_columns
179
+ if @out.respond_to?(:winsize)
180
+ cols = @out.winsize[1].to_i
181
+ return cols if cols.positive?
182
+ end
183
+ env_cols = ENV['COLUMNS'].to_i
184
+ return env_cols if env_cols.positive?
185
+
186
+ nil
187
+ rescue StandardError
188
+ nil
189
+ end
190
+
191
+ def write_in_place(line, newline: false)
192
+ cols = detect_terminal_columns
193
+ clipped = cols && cols > 10 && line.length >= cols ? line[0, cols - 1] : line
194
+ pad_count = [@last_line_len - clipped.length, 0].max
195
+ padded = pad_count.positive? ? "#{clipped}#{' ' * pad_count}" : clipped
196
+ @last_line_len = clipped.length
197
+
198
+ @out.print "\r#{padded}"
199
+ if newline
200
+ @out.print "\n"
201
+ @finished_newline = true
202
+ @last_line_len = 0
203
+ end
17
204
  @out.flush
18
205
  end
206
+
207
+ def monotonic_now
208
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
209
+ end
19
210
  end
20
211
  end
@@ -3,10 +3,14 @@
3
3
  require 'json'
4
4
  require 'net/http'
5
5
  require 'uri'
6
+ require_relative 'paginator'
7
+ require_relative 'media_type'
8
+ require_relative 'extractors/pin_data'
6
9
 
7
10
  module PinterestDL
8
11
  class Search
9
12
  S_URL = 'https://www.pinterest.com/resource/BaseSearchResource/get/'
13
+ PAGE_SIZE = 25
10
14
 
11
15
  def initialize(client: PinterestDL::Client.new, config: PinterestDL.config)
12
16
  @client = client
@@ -16,54 +20,27 @@ module PinterestDL
16
20
  def call(query, limit: 25, pages: 5, type: :all)
17
21
  raise ArgumentError, 'query must not be empty' if query.to_s.strip.empty?
18
22
 
23
+ parsed_type = MediaType.parse(type)
19
24
  session = establish_session(query)
20
- results = collect_pages(session, query, limit: limit, pages: pages, type: type)
25
+ paginator = Paginator.new(max_pages: pages, limit: limit, type: parsed_type) do |bookmarks, _page_idx|
26
+ fetch_page(session, query, bookmarks: bookmarks)
27
+ end
28
+
29
+ results = paginator.to_a
21
30
  if results.empty?
22
31
  fallback = PinterestDL::Extractors::PinData.extract_pins(session[:html], quality: @config.quality)
23
- results = PinterestDL::MediaType.filter(fallback, type)
32
+ results = PinterestDL::MediaType.filter(fallback, parsed_type)
24
33
  end
25
34
  results.first(limit)
26
35
  end
27
36
 
28
37
  private
29
38
 
30
- def collect_pages(session, query, limit:, pages:, type:)
31
- results = []
32
- seen = {}
33
- bookmarks = nil
34
- pages_fetched = 0
35
-
36
- loop do
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
44
- bookmarks = page[:bookmarks]
45
- pages_fetched += 1
46
-
47
- break if results.size >= limit || stop_pagination?(bookmarks, pages_fetched, pages, page[:pins])
48
- end
49
-
50
- results
51
- end
52
-
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
56
-
57
39
  def fetch_page(session, query, bookmarks: nil)
58
- body = @client.get(
59
- build_search_url(session[:source_path], query, bookmarks),
60
- use_cache: false,
61
- headers: search_headers(session)
62
- )
63
-
64
- json = safe_parse(body)
65
- raise PinterestDL::NotFoundError, "No search results for \"#{query}\"" unless json
40
+ url = build_search_url(session[:source_path], query, bookmarks)
41
+ body = @client.get(url, use_cache: false, headers: search_headers(session))
66
42
 
43
+ json = validate_search_json!(body, query: query, url: url)
67
44
  parse_search_response(json)
68
45
  end
69
46
 
@@ -89,7 +66,7 @@ module PinterestDL
89
66
  end
90
67
 
91
68
  def build_search_url(source_path, query, bookmarks)
92
- options = { query: query, scope: 'pins', page_size: 25 }
69
+ options = { query: query, scope: 'pins', page_size: PAGE_SIZE }
93
70
  options[:bookmarks] = bookmarks if bookmarks && !bookmarks.empty?
94
71
  data = { options: options, context: {} }.to_json
95
72
 
@@ -99,7 +76,6 @@ module PinterestDL
99
76
  end
100
77
 
101
78
  def search_headers(session)
102
- cookie_header = [@config.cookies, session[:cookies].join('; ')].compact.reject(&:empty?).join('; ')
103
79
  headers = {
104
80
  'Accept' => 'application/json, text/javascript, */*, q=0.01',
105
81
  'X-Requested-With' => 'XMLHttpRequest',
@@ -109,7 +85,10 @@ module PinterestDL
109
85
  'X-CSRFToken' => session[:csrf],
110
86
  'Referer' => session[:home_uri].to_s
111
87
  }
112
- headers['Cookie'] = cookie_header unless cookie_header.empty?
88
+ unless @client.respond_to?(:cookie_jar)
89
+ cookie_header = [@config.cookies, session[:cookies].join('; ')].compact.reject(&:empty?).join('; ')
90
+ headers['Cookie'] = cookie_header unless cookie_header.empty?
91
+ end
113
92
  headers
114
93
  end
115
94
 
@@ -131,10 +110,17 @@ module PinterestDL
131
110
  PinterestDL::Extractors::PinData.build_pin_hash(raw, quality: @config.quality)
132
111
  end
133
112
 
134
- def safe_parse(body)
135
- JSON.parse(body)
136
- rescue JSON::ParserError, TypeError
137
- nil
113
+ def validate_search_json!(body, query:, url:)
114
+ parsed = JSON.parse(body.to_s)
115
+ raise PinterestDL::NotFoundError.new("No search results for \"#{query}\"", url: url) unless parsed.is_a?(Hash)
116
+
117
+ if parsed['resource_response'] && !parsed['resource_response'].is_a?(Hash)
118
+ raise PinterestDL::InvalidResponseError.new("Malformed resource_response for \"#{query}\"", url: url)
119
+ end
120
+
121
+ parsed
122
+ rescue JSON::ParserError, TypeError => e
123
+ raise PinterestDL::NotFoundError.new("No search results for \"#{query}\"", url: url, cause_error: e)
138
124
  end
139
125
  end
140
126
  end