pinterest-dl 2.3.0 → 2.4.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,80 @@
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
+ return if @limit && yielded >= @limit
44
+ end
45
+
46
+ next_bookmarks = normalize_bookmarks(page[:bookmarks])
47
+ pages_fetched += 1
48
+
49
+ break if stop?(next_bookmarks, seen_bookmarks, pages_fetched, raw_pins)
50
+
51
+ seen_bookmarks[bookmark_signature(next_bookmarks)] = true
52
+ bookmarks = next_bookmarks
53
+ end
54
+ end
55
+
56
+ def collect
57
+ to_a
58
+ end
59
+
60
+ private
61
+
62
+ def normalize_bookmarks(raw)
63
+ Array(raw).flatten.map { |b| b.to_s.strip }.reject(&:empty?)
64
+ end
65
+
66
+ def bookmark_signature(bookmarks)
67
+ bookmarks.join('|')
68
+ end
69
+
70
+ def stop?(bookmarks, seen_bookmarks, pages_fetched, raw_pins)
71
+ return true if pages_fetched >= @max_pages
72
+ return true if raw_pins.empty?
73
+ return true if bookmarks.empty?
74
+ return true if bookmarks.all? { |b| END_MARKERS.include?(b.downcase) }
75
+ return true if seen_bookmarks[bookmark_signature(bookmarks)]
76
+
77
+ false
78
+ end
79
+ end
80
+ end
@@ -1,20 +1,209 @@
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
+ render_byte_progress(0, @last_total_bytes, speed: 0.0, label: @label, media_type: @media_type) if @byte_mode && @last_total_bytes
44
+ end
45
+ end
46
+
47
+ def update(done, bytes_received: nil, total_bytes: nil, speed: nil, label: nil, media_type: nil)
48
+ return unless @enabled
49
+
50
+ @mutex.synchronize do
51
+ eff_label = label || @label
52
+ eff_type = media_type || @media_type
53
+ if @byte_mode || (bytes_received && total_bytes)
54
+ rec = bytes_received || done.to_i
55
+ tot = total_bytes || @last_total_bytes || (@known_total ? @total : nil)
56
+ @last_received = rec
57
+ @last_total_bytes = tot if tot&.positive?
58
+ render_byte_progress(rec, tot, speed: speed, label: eff_label, media_type: eff_type)
59
+ else
60
+ render_item_progress(done, label: eff_label, media_type: eff_type)
61
+ end
62
+ end
63
+ end
64
+
65
+ def finish(final_bytes: nil)
66
+ return unless @enabled
67
+
68
+ @mutex.synchronize do
69
+ if @byte_mode && !@finished_newline
70
+ rec = final_bytes || @last_received
71
+ tot = @last_total_bytes || (rec.positive? ? rec : nil)
72
+ render_byte_progress(rec, tot, speed: nil, label: @label, media_type: @media_type, force_complete: true)
73
+ end
74
+ unless @finished_newline
75
+ @out.print "\n"
76
+ @out.flush
77
+ @finished_newline = true
78
+ end
79
+ end
80
+ end
81
+
82
+ def self.format_bytes(bytes)
83
+ val = bytes.to_f
84
+ return '0 B' if val <= 0
85
+
86
+ idx = 0
87
+ while val >= 1024.0 && idx < UNITS.size - 1
88
+ val /= 1024.0
89
+ idx += 1
90
+ end
91
+ idx.zero? ? "#{val.to_i} #{UNITS[idx]}" : format('%<val>.1f %<unit>s', val: val, unit: UNITS[idx])
92
+ end
93
+
94
+ def self.format_eta(seconds)
95
+ return '--:--' if seconds.nil? || seconds.infinite? || seconds.nan? || seconds.negative?
96
+
97
+ sec = seconds.round
98
+ return '99:59+' if sec > 359_999
99
+
100
+ hours = sec / 3600
101
+ mins = (sec % 3600) / 60
102
+ rem = sec % 60
103
+ if hours.positive?
104
+ format('%<h>02d:%<m>02d:%<s>02d', h: hours, m: mins, s: rem)
105
+ else
106
+ format('%<m>02d:%<s>02d', m: mins, s: rem)
107
+ end
9
108
  end
10
109
 
11
- def update(done)
110
+ def self.truncate_label(text, max_len: MAX_LABEL_LENGTH)
111
+ str = text.to_s
112
+ return str if str.length <= max_len || max_len < 6
113
+
114
+ ext = File.extname(str)
115
+ if !ext.empty? && ext.length < max_len - 4
116
+ keep = max_len - ext.length - 2
117
+ head = [keep - 3, 3].max
118
+ tail = [keep - head, 1].max
119
+ stem = File.basename(str, ext)
120
+ "#{stem[0, head]}..#{stem[-tail, tail]}#{ext}"
121
+ else
122
+ "#{str[0, max_len - 2]}.."
123
+ end
124
+ end
125
+
126
+ private
127
+
128
+ def render_item_progress(done, label: nil, media_type: nil)
12
129
  ratio = [[done.to_f / @total, 0.0].max, 1.0].min
13
130
  filled = (@width * ratio).round
14
131
  bar = ('#' * filled) + ('-' * (@width - filled))
15
- @out.print "\r[#{bar}] #{done}/#{@total} (#{((done.to_f / @total) * 100).round}%)"
16
- @out.print "\n" if done >= @total
132
+ pct = ((done.to_f / @total) * 100).round
133
+ badge = media_type ? "[#{media_type.to_s.upcase}] " : ''
134
+ short_label = label && !label.empty? ? " #{self.class.truncate_label(label)}" : ''
135
+ line = "#{badge}[#{bar}] #{done}/#{@total} (#{pct}%)#{short_label}"
136
+ write_in_place(line, newline: done >= @total)
137
+ end
138
+
139
+ def render_byte_progress(received, total_bytes, speed: nil, label: nil, media_type: nil, force_complete: false)
140
+ return if @finished_newline && !force_complete
141
+
142
+ elapsed = [monotonic_now - @started_at, 0.001].max
143
+ current_speed = speed || (received.to_f / elapsed)
144
+ speed_str = "#{self.class.format_bytes(current_speed)}/s"
145
+ badge = media_type ? "[#{media_type.to_s.upcase}] " : ''
146
+ short_label = label && !label.empty? ? "#{self.class.truncate_label(label)} " : ''
147
+
148
+ if total_bytes&.positive?
149
+ ratio = force_complete ? 1.0 : [[received.to_f / total_bytes, 0.0].max, 1.0].min
150
+ pct = (ratio * 100).round
151
+ remaining = [total_bytes - received, 0].max
152
+ eta_sec = current_speed.positive? ? (remaining.to_f / current_speed) : nil
153
+ eta_str = ratio >= 1.0 ? '00:00' : self.class.format_eta(eta_sec)
154
+ size_str = "#{self.class.format_bytes(received)}/#{self.class.format_bytes(total_bytes)}"
155
+ tail = " #{pct}% #{size_str} #{speed_str} ETA #{eta_str}"
156
+ eff_width = adaptive_bar_width(badge.length + short_label.length + tail.length + 2)
157
+ filled = (eff_width * ratio).round
158
+ bar = ('#' * filled) + ('-' * (eff_width - filled))
159
+ line = "#{badge}#{short_label}[#{bar}]#{tail}"
160
+ write_in_place(line, newline: received >= total_bytes || force_complete)
161
+ else
162
+ size_str = self.class.format_bytes(received)
163
+ line = "#{badge}#{short_label}#{size_str} #{speed_str}"
164
+ write_in_place(line, newline: force_complete)
165
+ end
166
+ end
167
+
168
+ def adaptive_bar_width(non_bar_len)
169
+ cols = detect_terminal_columns
170
+ return @width unless cols&.positive?
171
+
172
+ available = cols - non_bar_len - 1
173
+ [[available, 6].max, @width].min
174
+ end
175
+
176
+ def detect_terminal_columns
177
+ if @out.respond_to?(:winsize)
178
+ cols = @out.winsize[1].to_i
179
+ return cols if cols.positive?
180
+ end
181
+ env_cols = ENV['COLUMNS'].to_i
182
+ return env_cols if env_cols.positive?
183
+
184
+ nil
185
+ rescue StandardError
186
+ nil
187
+ end
188
+
189
+ def write_in_place(line, newline: false)
190
+ cols = detect_terminal_columns
191
+ clipped = cols && cols > 10 && line.length >= cols ? line[0, cols - 1] : line
192
+ pad_count = [@last_line_len - clipped.length, 0].max
193
+ padded = pad_count.positive? ? "#{clipped}#{' ' * pad_count}" : clipped
194
+ @last_line_len = clipped.length
195
+
196
+ @out.print "\r#{padded}"
197
+ if newline
198
+ @out.print "\n"
199
+ @finished_newline = true
200
+ @last_line_len = 0
201
+ end
17
202
  @out.flush
18
203
  end
204
+
205
+ def monotonic_now
206
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
207
+ end
19
208
  end
20
209
  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
 
@@ -131,10 +108,17 @@ module PinterestDL
131
108
  PinterestDL::Extractors::PinData.build_pin_hash(raw, quality: @config.quality)
132
109
  end
133
110
 
134
- def safe_parse(body)
135
- JSON.parse(body)
136
- rescue JSON::ParserError, TypeError
137
- nil
111
+ def validate_search_json!(body, query:, url:)
112
+ parsed = JSON.parse(body.to_s)
113
+ raise PinterestDL::NotFoundError.new("No search results for \"#{query}\"", url: url) unless parsed.is_a?(Hash)
114
+
115
+ if parsed['resource_response'] && !parsed['resource_response'].is_a?(Hash)
116
+ raise PinterestDL::InvalidResponseError.new("Malformed resource_response for \"#{query}\"", url: url)
117
+ end
118
+
119
+ parsed
120
+ rescue JSON::ParserError, TypeError => e
121
+ raise PinterestDL::NotFoundError.new("No search results for \"#{query}\"", url: url, cause_error: e)
138
122
  end
139
123
  end
140
124
  end