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.
@@ -1,48 +1,162 @@
1
1
  # frozen_string_literal: true
2
2
 
3
-
4
3
  module PinterestDL
5
4
  class Error < StandardError
5
+ attr_reader :url, :status_code, :cause_error
6
+
7
+ def initialize(message = nil, url: nil, status_code: nil, cause_error: nil)
8
+ @url = url
9
+ @status_code = status_code
10
+ @cause_error = cause_error
11
+ super(message)
12
+ end
13
+ end
14
+
15
+ class ConfigurationError < Error
16
+ def initialize(message = 'Invalid configuration', **kwargs)
17
+ super
18
+ end
6
19
  end
7
20
 
8
21
  class NetworkError < Error
9
- attr_reader :cause_error
22
+ def initialize(message = 'A network error occurred', **kwargs)
23
+ super
24
+ end
25
+ end
10
26
 
11
- def initialize(message = 'A network error occurred', cause_error: nil)
12
- @cause_error = cause_error
13
- super(message)
27
+ class TimeoutError < NetworkError
28
+ def initialize(message = 'Request timed out', **kwargs)
29
+ super
14
30
  end
15
31
  end
16
32
 
17
- class NotFoundError < Error
18
- def initialize(message = 'The requested resource was not found')
33
+ class ConnectionError < NetworkError
34
+ def initialize(message = 'Connection failed or closed unexpectedly', **kwargs)
19
35
  super
20
36
  end
21
37
  end
22
38
 
23
- class RateLimitError < Error
39
+ class SSLError < NetworkError
40
+ def initialize(message = 'SSL/TLS handshake or verification failed', **kwargs)
41
+ super
42
+ end
43
+ end
44
+
45
+ class RedirectError < NetworkError
46
+ def initialize(message = 'Redirect error', **kwargs)
47
+ super
48
+ end
49
+ end
50
+
51
+ class HTTPError < Error
52
+ def initialize(message = 'HTTP request failed', **kwargs)
53
+ super
54
+ end
55
+ end
56
+
57
+ class NotFoundError < HTTPError
58
+ def initialize(message = 'The requested resource was not found', **kwargs)
59
+ super(message, status_code: kwargs.fetch(:status_code, 404), **kwargs.except(:status_code))
60
+ end
61
+ end
62
+
63
+ class AuthenticationError < HTTPError
64
+ def initialize(message = 'Authentication required (set PinterestDL.configure { |c| c.cookies = ... })', **kwargs)
65
+ super(message, status_code: kwargs.fetch(:status_code, 401), **kwargs.except(:status_code))
66
+ end
67
+ end
68
+
69
+ class ForbiddenError < HTTPError
70
+ def initialize(message = 'Access to the requested resource was forbidden (HTTP 403)', **kwargs)
71
+ super(message, status_code: kwargs.fetch(:status_code, 403), **kwargs.except(:status_code))
72
+ end
73
+ end
74
+
75
+ class RateLimitError < HTTPError
24
76
  attr_reader :retry_after
25
77
 
26
- def initialize(message = 'Rate limited by Pinterest', retry_after: nil)
78
+ def initialize(message = 'Rate limited by Pinterest', retry_after: nil, **kwargs)
27
79
  @retry_after = retry_after
28
- super(message)
80
+ super(message, status_code: kwargs.fetch(:status_code, 429), **kwargs.except(:status_code))
81
+ end
82
+ end
83
+
84
+ class RangeNotSatisfiableError < HTTPError
85
+ attr_reader :content_range
86
+
87
+ def initialize(message = 'Requested byte range is not satisfiable (HTTP 416)', content_range: nil, **kwargs)
88
+ @content_range = content_range
89
+ super(message, status_code: kwargs.fetch(:status_code, 416), **kwargs.except(:status_code))
90
+ end
91
+ end
92
+
93
+ class ServerError < HTTPError
94
+ def initialize(message = 'Pinterest server returned an error', **kwargs)
95
+ super
96
+ end
97
+ end
98
+
99
+ class ValidationError < Error
100
+ def initialize(message = 'Validation failed', **kwargs)
101
+ super
102
+ end
103
+ end
104
+
105
+ class InvalidURLError < ValidationError
106
+ def initialize(message = 'The given URL does not look like a valid Pinterest URL', **kwargs)
107
+ super
29
108
  end
30
109
  end
31
110
 
32
- class AuthenticationError < Error
33
- def initialize(message = 'Authentication required (set PinterestDL.configure { |c| c.cookies = ... })')
111
+ class SSRFError < InvalidURLError
112
+ def initialize(message = 'Access to private, loopback, or internal network addresses is blocked', **kwargs)
34
113
  super
35
114
  end
36
115
  end
37
116
 
38
- class InvalidURLError < Error
39
- def initialize(message = 'The given URL does not look like a valid Pinterest URL')
117
+ class InvalidResponseError < ValidationError
118
+ def initialize(message = 'Unexpected or malformed response payload from Pinterest', **kwargs)
40
119
  super
41
120
  end
42
121
  end
43
122
 
44
123
  class DownloadError < Error
45
- def initialize(message = 'Failed to download file')
124
+ def initialize(message = 'Failed to download file', **kwargs)
125
+ super
126
+ end
127
+ end
128
+
129
+ class FileTooLargeError < DownloadError
130
+ attr_reader :max_size, :actual_size
131
+
132
+ def initialize(message = 'File size exceeds the configured maximum limit', max_size: nil, actual_size: nil, **kwargs)
133
+ @max_size = max_size
134
+ @actual_size = actual_size
135
+ super(message, **kwargs)
136
+ end
137
+ end
138
+
139
+ class IncompleteDownloadError < DownloadError
140
+ attr_reader :expected_bytes, :received_bytes
141
+
142
+ def initialize(message = 'Download ended before all bytes were received', expected_bytes: nil, received_bytes: nil, **kwargs)
143
+ @expected_bytes = expected_bytes
144
+ @received_bytes = received_bytes
145
+ super(message, **kwargs)
146
+ end
147
+ end
148
+
149
+ class InvalidMediaError < DownloadError
150
+ attr_reader :content_type
151
+
152
+ def initialize(message = 'Downloaded content is not a valid image or video', content_type: nil, **kwargs)
153
+ @content_type = content_type
154
+ super(message, **kwargs)
155
+ end
156
+ end
157
+
158
+ class DiskSpaceError < DownloadError
159
+ def initialize(message = 'Insufficient disk space or storage write failure', **kwargs)
46
160
  super
47
161
  end
48
162
  end
@@ -12,12 +12,32 @@ module PinterestDL
12
12
  '236x': '236x'
13
13
  }.freeze
14
14
 
15
- BUCKET_REGEX = /(?:originals|1200x|736x|564x|474x|236x|\d+x\d*)/i.freeze
15
+ QUALITY_RANK = {
16
+ 'orig' => 100,
17
+ 'originals' => 100,
18
+ '1200x' => 80,
19
+ '736x' => 60,
20
+ '600x315' => 50,
21
+ '564x' => 45,
22
+ '474x' => 35,
23
+ '236x' => 20,
24
+ '170x' => 15,
25
+ '136x136' => 10,
26
+ '60x60' => 5
27
+ }.freeze
28
+
29
+ BUCKET_REGEX = /(?:originals|1200x|736x|564x|474x|236x|\d+x\d*)/i
30
+
31
+ PINIMG_URL_REGEX = %r{
32
+ https://i\d*\.pinimg\.com/
33
+ (?:originals|1200x|736x|564x|474x|236x|\d+x\d*)/
34
+ [A-Za-z0-9_\-/]+\.(?:jpg|jpeg|png|gif|webp)
35
+ }ix
16
36
 
17
37
  module_function
18
38
 
19
39
  def extract(html, quality: :originals)
20
- url = from_json_ld(html) || from_open_graph(html) || from_raw_pattern(html)
40
+ url = from_json_ld(html) || from_open_graph(html) || from_srcset(html) || from_raw_pattern(html)
21
41
  return nil unless url
22
42
 
23
43
  apply_quality(url, quality)
@@ -28,18 +48,49 @@ module PinterestDL
28
48
  end
29
49
 
30
50
  def from_open_graph(html)
31
- PinterestDL::Extractors::Meta.content(html, 'og:image')
51
+ PinterestDL::Extractors::Meta.content(html, 'og:image') ||
52
+ PinterestDL::Extractors::Meta.content(html, 'twitter:image:src') ||
53
+ PinterestDL::Extractors::Meta.content(html, 'twitter:image')
54
+ end
55
+
56
+ def from_srcset(html)
57
+ candidates = []
58
+ html.to_s.scan(/srcset=["']([^"']+)["']/i).each do |(srcset)|
59
+ srcset.split(',').each do |entry|
60
+ parts = entry.strip.split(/\s+/)
61
+ url = parts[0]
62
+ next unless url&.match?(%r{\Ahttps://i\d*\.pinimg\.com/}i)
63
+
64
+ scale = parts[1].to_s[/\A(\d+)[wx]\z/i, 1].to_i
65
+ candidates << [scale, url]
66
+ end
67
+ end
68
+ return nil if candidates.empty?
69
+
70
+ candidates.max_by(&:first).last
32
71
  end
33
72
 
34
73
  def from_raw_pattern(html)
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
37
- )
38
- match && match[0]
74
+ matches = html.to_s.scan(PINIMG_URL_REGEX)
75
+ return nil if matches.empty?
76
+
77
+ matches.max_by { |u| score_url_quality(u) }
78
+ end
79
+
80
+ def score_url_quality(url)
81
+ bucket = url.to_s[%r{i\d*\.pinimg\.com/([^/]+)/}i, 1].to_s.downcase
82
+ return QUALITY_RANK[bucket] if QUALITY_RANK.key?(bucket)
83
+
84
+ if (m = bucket.match(/\A(\d+)x(\d+)?\z/))
85
+ w = m[1].to_i
86
+ h = (m[2] || m[1]).to_i
87
+ return [w * h / 10_000, 90].min
88
+ end
89
+ 1
39
90
  end
40
91
 
41
92
  def apply_quality(url, quality)
42
- return url unless url.to_s.match?(%r{i\d*\.pinimg\.com}i)
93
+ return url unless url.to_s.match?(/i\d*\.pinimg\.com/i)
43
94
 
44
95
  target = QUALITY_PATH[quality.to_sym]
45
96
  return url unless target
@@ -48,4 +99,4 @@ module PinterestDL
48
99
  end
49
100
  end
50
101
  end
51
- end
102
+ end
@@ -1,20 +1,43 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'json'
4
+ require_relative 'image'
4
5
 
5
6
  module PinterestDL
6
7
  module Extractors
7
8
  module PinData
8
- SCRIPT_PATTERN =
9
- %r{<script[^>]*(?:id=["']__PWS_[A-Z_]+__["']|data-relay-response=["']true["'])[^>]*>(.*?)</script>}m.freeze
9
+ SCRIPT_PATTERN = %r{
10
+ <script[^>]*(?:
11
+ id\s*=\s*["'](?:__PWS_[A-Z0-9_]+__|__NEXT_DATA__|initial-state)["'] |
12
+ data-relay-response\s*=\s*["']true["'] |
13
+ data-pinterest-state\s*=\s*["']true["']
14
+ )[^>]*>(.*?)</script>
15
+ }mix
16
+
17
+ WINDOW_STATE_PATTERN = %r{
18
+ window\.(?:__INITIAL_STATE__|__PWS_DATA__|__PWS_INITIAL_PROPS__)\s*=\s*(\{.*?\})\s*;?\s*</script>
19
+ }mix
20
+
21
+ IMAGE_BUCKET_PRIORITY = {
22
+ 'orig' => 1_000_000_000,
23
+ 'originals' => 1_000_000_000,
24
+ '1200x' => 12_000_000,
25
+ '736x' => 7_360_000,
26
+ '600x' => 6_000_000,
27
+ '564x' => 5_640_000,
28
+ '474x' => 4_740_000,
29
+ '236x' => 2_360_000,
30
+ '170x' => 1_700_000,
31
+ '136x136' => 18_496,
32
+ '60x60' => 3_600
33
+ }.freeze
10
34
 
11
35
  module_function
12
36
 
13
37
  def extract(html, pin_id = nil)
14
38
  found = nil
15
- html.to_s.scan(SCRIPT_PATTERN).each do |(raw)|
16
- data = safe_parse(raw)
17
- pin = data && find_pin_node(data, pin_id)
39
+ each_script_payload(html) do |data|
40
+ pin = find_pin_node(data, pin_id)
18
41
  next unless pin
19
42
 
20
43
  result = build_result(pin)
@@ -27,14 +50,18 @@ module PinterestDL
27
50
 
28
51
  def extract_pins(html, quality: :originals)
29
52
  pins = []
30
- html.to_s.scan(SCRIPT_PATTERN).each do |(raw)|
31
- stack = [safe_parse(raw)]
53
+ seen = {}
54
+ each_script_payload(html) do |data|
55
+ stack = [data]
32
56
  until stack.empty?
33
57
  node = stack.pop
34
58
  case node
35
59
  when Hash
36
60
  pin = build_pin_hash(node, quality: quality)
37
- pins << pin if pin
61
+ if pin && !seen[pin[:id]]
62
+ seen[pin[:id]] = true
63
+ pins << pin
64
+ end
38
65
  stack.concat(node.values)
39
66
  when Array
40
67
  stack.concat(node)
@@ -44,21 +71,41 @@ module PinterestDL
44
71
  pins
45
72
  end
46
73
 
74
+ def each_script_payload(html)
75
+ return enum_for(:each_script_payload, html) unless block_given?
76
+
77
+ text = html.to_s
78
+ text.scan(SCRIPT_PATTERN).each do |(raw)|
79
+ parsed = safe_parse(raw)
80
+ yield parsed if parsed
81
+ end
82
+ text.scan(WINDOW_STATE_PATTERN).each do |(raw)|
83
+ parsed = safe_parse(raw)
84
+ yield parsed if parsed
85
+ end
86
+ end
87
+
47
88
  def build_pin_hash(raw, quality: :originals)
48
89
  return nil unless raw.is_a?(Hash)
49
90
  return nil if raw['type'] && raw['type'] != 'pin'
50
91
 
51
- id = raw['id']
92
+ id = raw['id'] || raw['pin_id']
93
+ return nil if id.nil? || id.to_s.strip.empty?
94
+
52
95
  img = best_image_url(raw)
53
96
  video = first_video_url(raw)
54
- return nil unless id && (img || video)
97
+ return nil unless img || video
98
+
99
+ title = extract_text_field(raw['title']) || extract_text_field(raw['grid_title'])
100
+ description = extract_text_field(raw['description']) || extract_text_field(raw['closeup_unified_description'])
101
+ creator = extract_creator(raw)
55
102
 
56
103
  {
57
104
  id: id.to_s,
58
105
  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'),
106
+ title: title,
107
+ description: description,
108
+ creator: creator,
62
109
  image_url: img && PinterestDL::Extractors::Image.apply_quality(img, quality),
63
110
  video_url: video
64
111
  }
@@ -68,30 +115,95 @@ module PinterestDL
68
115
  {
69
116
  image_url: best_image_url(pin),
70
117
  video_url: first_video_url(pin),
71
- title: pin['title'] || pin['grid_title'],
72
- description: pin['description'],
73
- creator: pin.dig('pinner', 'username') || pin.dig('pinner', 'full_name')
118
+ title: extract_text_field(pin['title']) || extract_text_field(pin['grid_title']),
119
+ description: extract_text_field(pin['description']) || extract_text_field(pin['closeup_unified_description']),
120
+ creator: extract_creator(pin)
74
121
  }
75
122
  end
76
123
 
124
+ def extract_text_field(val)
125
+ case val
126
+ when String then val
127
+ when Hash then val['text'] || val['format']
128
+ end
129
+ end
130
+
131
+ def extract_creator(pin)
132
+ pin.dig('pinner', 'username') ||
133
+ pin.dig('pinner', 'full_name') ||
134
+ pin.dig('native_creator', 'username') ||
135
+ pin.dig('origin_pinner', 'username')
136
+ end
137
+
77
138
  def best_image_url(pin)
78
139
  return nil unless pin.is_a?(Hash)
79
140
 
80
- orig = pin.dig('images', 'orig', 'url')
81
- return orig if orig
141
+ orig = pin.dig('images', 'orig', 'url') || pin.dig('images', 'originals', 'url')
142
+ return orig if orig.is_a?(String) && !orig.empty?
143
+
144
+ images = pin['images'] || pin['image_spec']
145
+ if images.is_a?(Hash)
146
+ candidates = images.filter_map do |bucket_key, entry|
147
+ next unless entry.is_a?(Hash) && entry['url'].is_a?(String) && !entry['url'].empty?
148
+
149
+ [score_image_variant(bucket_key.to_s, entry), entry['url']]
150
+ end
151
+ return candidates.max_by(&:first).last unless candidates.empty?
152
+ elsif images.is_a?(Array)
153
+ candidates = images.filter_map do |entry|
154
+ next unless entry.is_a?(Hash) && entry['url'].is_a?(String) && !entry['url'].empty?
155
+
156
+ [score_image_variant('', entry), entry['url']]
157
+ end
158
+ return candidates.max_by(&:first).last unless candidates.empty?
159
+ end
160
+
161
+ story_img = deep_find_image(pin['story_pin_data'])
162
+ return story_img if story_img
82
163
 
83
- images = pin['images']
84
- return nil unless images.is_a?(Hash)
164
+ pin['image_large_url'] || pin['image_medium_url']
165
+ end
85
166
 
86
- images.values.filter_map { |v| v['url'] if v.is_a?(Hash) }.last
167
+ def score_image_variant(bucket_key, entry)
168
+ key = bucket_key.to_s.downcase
169
+ priority = IMAGE_BUCKET_PRIORITY[key] || 0
170
+ width = entry['width'].to_i
171
+ height = entry['height'].to_i
172
+ area = width.positive? && height.positive? ? (width * height) : 0
173
+ url_score = Image.score_url_quality(entry['url']) * 1_000
174
+ priority + area + url_score
87
175
  end
88
176
 
89
- def parse_embedded_json(html)
90
- html.to_s.scan(SCRIPT_PATTERN).each do |(raw)|
91
- parsed = safe_parse(raw)
92
- return parsed if parsed
177
+ def deep_find_image(node)
178
+ return nil unless node
179
+
180
+ stack = [node]
181
+ best = nil
182
+ best_score = -1
183
+ until stack.empty?
184
+ current = stack.pop
185
+ case current
186
+ when Hash
187
+ if current['images'].is_a?(Hash)
188
+ url = best_image_url(current)
189
+ if url
190
+ score = Image.score_url_quality(url)
191
+ if score > best_score
192
+ best = url
193
+ best_score = score
194
+ end
195
+ end
196
+ end
197
+ stack.concat(current.values)
198
+ when Array
199
+ stack.concat(current)
200
+ end
93
201
  end
94
- nil
202
+ best
203
+ end
204
+
205
+ def parse_embedded_json(html)
206
+ each_script_payload(html).first
95
207
  end
96
208
 
97
209
  def find_pin_node(data, pin_id = nil)
@@ -102,7 +214,8 @@ module PinterestDL
102
214
  case node
103
215
  when Hash
104
216
  if pin_id
105
- matches << node if node['id'].to_s == pin_id.to_s && has_media?(node)
217
+ node_id = (node['id'] || node['pin_id']).to_s
218
+ matches << node if node_id == pin_id.to_s && has_media?(node)
106
219
  elsif pin_like?(node)
107
220
  return node
108
221
  end
@@ -119,7 +232,11 @@ module PinterestDL
119
232
  end
120
233
 
121
234
  def has_media?(node)
122
- node['images'].is_a?(Hash) || node['videos'].is_a?(Hash) || node['story_pin_data'].is_a?(Hash)
235
+ node['images'].is_a?(Hash) ||
236
+ node['images'].is_a?(Array) ||
237
+ node['videos'].is_a?(Hash) ||
238
+ node['story_pin_data'].is_a?(Hash) ||
239
+ node.key?('image_large_url')
123
240
  end
124
241
 
125
242
  def first_video_url(pin)
@@ -127,15 +244,19 @@ module PinterestDL
127
244
 
128
245
  video_list = pin.dig('videos', 'video_list')
129
246
  video_list = deep_find(pin['story_pin_data'], 'video_list') unless video_list.is_a?(Hash)
247
+ video_list = deep_find(pin['CloseupContent'], 'video_list') unless video_list.is_a?(Hash)
130
248
  best_video(video_list)
131
249
  end
132
250
 
133
251
  def best_video(video_list)
134
252
  return nil unless video_list.is_a?(Hash)
135
253
 
136
- formats = video_list.values.select { |v| v.is_a?(Hash) && v['url'] }
254
+ formats = video_list.values.select { |v| v.is_a?(Hash) && v['url'].is_a?(String) && !v['url'].empty? }
137
255
  mp4s = formats.select { |v| v['url'].include?('.mp4') }
138
- best = mp4s.max_by { |v| v['width'].to_i * v['height'].to_i }
256
+ best = mp4s.max_by do |v|
257
+ area = v['width'].to_i * v['height'].to_i
258
+ area.positive? ? area : Video.score_video_url(v['url'])
259
+ end
139
260
  return best['url'] if best
140
261
 
141
262
  hls = formats.find { |v| v['url'].include?('.m3u8') }
@@ -151,6 +272,8 @@ module PinterestDL
151
272
  end
152
273
 
153
274
  def deep_find(node, key)
275
+ return nil unless node
276
+
154
277
  stack = [node]
155
278
  until stack.empty?
156
279
  current = stack.pop
@@ -167,7 +290,9 @@ module PinterestDL
167
290
  end
168
291
 
169
292
  def safe_parse(raw)
170
- JSON.parse(raw)
293
+ return nil if raw.nil?
294
+
295
+ JSON.parse(raw.to_s.strip)
171
296
  rescue JSON::ParserError
172
297
  nil
173
298
  end
@@ -1,12 +1,18 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'json'
4
+
3
5
  module PinterestDL
4
6
  module Extractors
5
7
  module Video
6
8
  module_function
7
9
 
8
10
  def extract(html)
9
- url = from_json_ld(html) || from_open_graph(html) || from_content_url(html) || from_raw_pattern(html)
11
+ url = from_json_ld(html) ||
12
+ from_open_graph(html) ||
13
+ from_video_tag(html) ||
14
+ from_content_url(html) ||
15
+ from_raw_pattern(html)
10
16
  return nil unless url
11
17
 
12
18
  unescape(url)
@@ -17,7 +23,16 @@ module PinterestDL
17
23
  end
18
24
 
19
25
  def from_open_graph(html)
20
- PinterestDL::Extractors::Meta.content(html, 'og:video')
26
+ PinterestDL::Extractors::Meta.content(html, 'og:video') ||
27
+ PinterestDL::Extractors::Meta.content(html, 'og:video:secure_url') ||
28
+ PinterestDL::Extractors::Meta.content(html, 'og:video:url')
29
+ end
30
+
31
+ def from_video_tag(html)
32
+ html.to_s.scan(/<(?:video|source)\b[^>]*\bsrc=["']([^"']+\.mp4[^"']*)["'][^>]*>/i).each do |(src)|
33
+ return src if src.include?('pinimg.com')
34
+ end
35
+ nil
21
36
  end
22
37
 
23
38
  def from_content_url(html)
@@ -27,8 +42,21 @@ module PinterestDL
27
42
 
28
43
  def from_raw_pattern(html)
29
44
  clean = html.to_s.gsub('\\u002F', '/').gsub('\\/', '/')
30
- match = clean.match(%r{https://v\d*\.pinimg\.com/videos/[^"'\s\\<>]+?\.mp4})
31
- match && match[0]
45
+ matches = clean.scan(%r{https://v\d*\.pinimg\.com/videos/[^"'\s\\<>]+?\.mp4})
46
+ return nil if matches.empty?
47
+
48
+ matches.max_by { |u| score_video_url(u) }
49
+ end
50
+
51
+ def score_video_url(url)
52
+ str = url.to_s
53
+ return 1080 if str.include?('/1080p/') || str.include?('_1080w')
54
+ return 720 if str.include?('/720p/') || str.include?('_720w') || str.include?('/expMp4/')
55
+ return 540 if str.include?('/540p/')
56
+ return 480 if str.include?('/480p/')
57
+ return 360 if str.include?('/360p/')
58
+
59
+ 100
32
60
  end
33
61
 
34
62
  def unescape(url)
@@ -40,10 +68,11 @@ module PinterestDL
40
68
  module_function
41
69
 
42
70
  def content(html, key)
71
+ escaped = Regexp.escape(key)
43
72
  html.to_s.scan(/<meta\b[^>]*>/i).each do |tag|
44
- next unless tag.match?(/(?:property|name)=["']#{Regexp.escape(key)}["']/i)
73
+ next unless tag.match?(/\b(?:property|name|itemprop)\s*=\s*["']#{escaped}["']/i)
45
74
 
46
- match = tag.match(/content=["']([^"']+)["']/i)
75
+ match = tag.match(/\bcontent\s*=\s*["']([^"']+)["']/i)
47
76
  return match[1] if match
48
77
  end
49
78
  nil
@@ -54,7 +83,7 @@ module PinterestDL
54
83
  module_function
55
84
 
56
85
  def content_url(html, type)
57
- html.to_s.scan(%r{<script[^>]*type=["']application/ld\+json["'][^>]*>(.*?)</script>}m).each do |(raw)|
86
+ html.to_s.scan(%r{<script[^>]*type\s*=\s*["']application/ld\+json["'][^>]*>(.*?)</script>}mi).each do |(raw)|
58
87
  found = find_type_url(safe_parse(raw), type)
59
88
  return found if found
60
89
  end
@@ -67,8 +96,11 @@ module PinterestDL
67
96
  current = stack.pop
68
97
  case current
69
98
  when Hash
70
- return current['contentUrl'] if current['@type'] == type && current['contentUrl']
71
-
99
+ node_types = Array(current['@type']).map(&:to_s)
100
+ if node_types.include?(type)
101
+ url = current['contentUrl'] || current['url']
102
+ return url if url.is_a?(String) && !url.empty?
103
+ end
72
104
  stack.concat(current.values)
73
105
  when Array
74
106
  stack.concat(current)
@@ -78,7 +110,7 @@ module PinterestDL
78
110
  end
79
111
 
80
112
  def safe_parse(raw)
81
- JSON.parse(raw)
113
+ JSON.parse(raw.to_s.strip)
82
114
  rescue JSON::ParserError
83
115
  nil
84
116
  end