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,345 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'time'
4
+ require 'uri'
5
+ require_relative 'security'
6
+
7
+ module PinterestDL
8
+ class CookieJar
9
+ Cookie = Struct.new(:name, :value, :domain, :host_only, :path, :secure, :http_only, :expires, :same_site, keyword_init: true) do
10
+ def expired?(now = Time.now)
11
+ !expires.nil? && expires <= now
12
+ end
13
+
14
+ def matches?(uri, now: Time.now)
15
+ return false if expired?(now)
16
+ return false if secure && uri.scheme.to_s.downcase != 'https'
17
+
18
+ host = Security.clean_host(uri.host)
19
+ return false unless domain_matches?(host)
20
+
21
+ req_path = uri.path.to_s.empty? ? '/' : uri.path.to_s
22
+ path_matches?(req_path)
23
+ end
24
+
25
+ def domain_matches?(host)
26
+ target_domain = domain.to_s.downcase.sub(/\A\./, '')
27
+ return false if target_domain.empty?
28
+ return true if host == target_domain
29
+ return true if target_domain == 'pinterest.com' && Security.pinterest_host?(host)
30
+ return false if host_only
31
+
32
+ host.end_with?(".#{target_domain}")
33
+ end
34
+
35
+ def path_matches?(req_path)
36
+ cookie_path = path.to_s.empty? ? '/' : path.to_s
37
+ return true if req_path == cookie_path
38
+ return true if req_path.start_with?(cookie_path) && cookie_path.end_with?('/')
39
+ return true if req_path.start_with?("#{cookie_path}/")
40
+
41
+ false
42
+ end
43
+ end
44
+
45
+ def initialize
46
+ @entries = []
47
+ @mutex = Mutex.new
48
+ end
49
+
50
+ def initialize_copy(other)
51
+ super
52
+ @mutex = Mutex.new
53
+ @entries = other.entries_snapshot.map(&:dup)
54
+ end
55
+
56
+ def entries_snapshot
57
+ @mutex.synchronize { @entries.map(&:dup) }
58
+ end
59
+
60
+ def clear
61
+ @mutex.synchronize { @entries.clear }
62
+ end
63
+
64
+ def empty?
65
+ @mutex.synchronize { @entries.empty? }
66
+ end
67
+
68
+ def set_from_header(set_cookie_fields, origin_url)
69
+ fields = Array(set_cookie_fields).flatten.compact
70
+ return if fields.empty?
71
+
72
+ uri = URI.parse(origin_url.to_s)
73
+ @mutex.synchronize do
74
+ fields.each do |raw_line|
75
+ cookie = parse_set_cookie(raw_line, uri)
76
+ upsert_unlocked(cookie) if cookie
77
+ end
78
+ end
79
+ rescue URI::InvalidURIError
80
+ nil
81
+ end
82
+
83
+ def load_raw(raw_cookies, default_domain: '.pinterest.com')
84
+ return if raw_cookies.nil? || raw_cookies.to_s.strip.empty?
85
+
86
+ text = raw_cookies.to_s.strip
87
+ if File.file?(text)
88
+ load_netscape_file(text)
89
+ else
90
+ load_cookie_string(text, default_domain: default_domain)
91
+ end
92
+ end
93
+
94
+ def load_cookie_string(cookie_str, default_domain: '.pinterest.com')
95
+ @mutex.synchronize do
96
+ cookie_str.to_s.split(';').each do |pair|
97
+ name, value = pair.strip.split('=', 2)
98
+ next if name.nil? || value.nil? || name.strip.empty?
99
+
100
+ cookie = Cookie.new(
101
+ name: name.strip,
102
+ value: value.strip,
103
+ domain: default_domain.sub(/\A\./, ''),
104
+ host_only: false,
105
+ path: '/',
106
+ secure: false,
107
+ http_only: false,
108
+ expires: nil,
109
+ same_site: nil
110
+ )
111
+ upsert_unlocked(cookie)
112
+ end
113
+ end
114
+ end
115
+
116
+ def load_netscape_file(file_path)
117
+ @mutex.synchronize do
118
+ File.foreach(file_path) { |line| load_netscape_line_unlocked(line) }
119
+ end
120
+ end
121
+
122
+ def load_netscape_line_unlocked(line)
123
+ stripped = line.strip
124
+ return if stripped.empty?
125
+
126
+ http_only = stripped.start_with?('#HttpOnly_')
127
+ return if stripped.start_with?('#') && !http_only
128
+
129
+ stripped = stripped.sub(/\A#HttpOnly_/, '') if http_only
130
+ fields = stripped.split("\t")
131
+
132
+ if fields.size >= 7
133
+ cookie = build_netscape_cookie(fields, http_only)
134
+ upsert_unlocked(cookie) if cookie
135
+ elsif stripped.include?('=') && !stripped.include?("\t")
136
+ load_cookie_pairs_unlocked(stripped)
137
+ end
138
+ end
139
+
140
+ def build_netscape_cookie(fields, http_only)
141
+ domain, include_subdomains, path, secure_flag, expiry_raw, name, value = fields
142
+ normalized_domain = domain.sub(/\A\./, '')
143
+
144
+ return unless Security.pinterest_host?(normalized_domain)
145
+
146
+ expiry = expiry_raw.to_i
147
+ Cookie.new(
148
+ name: name.strip,
149
+ value: value.to_s.strip,
150
+ domain: normalized_domain.downcase,
151
+ host_only: include_subdomains.to_s.upcase != 'TRUE' && !domain.start_with?('.'),
152
+ path: path.to_s.empty? ? '/' : path.strip,
153
+ secure: secure_flag.to_s.upcase == 'TRUE',
154
+ http_only: http_only,
155
+ expires: expiry.positive? ? Time.at(expiry) : nil,
156
+ same_site: nil
157
+ )
158
+ end
159
+
160
+ def load_cookie_pairs_unlocked(raw_cookies)
161
+ raw_cookies.split(';').each do |pair|
162
+ name, value = pair.strip.split('=', 2)
163
+ next if name.nil? || value.nil? || name.empty?
164
+
165
+ upsert_unlocked(
166
+ Cookie.new(
167
+ name: name,
168
+ value: value,
169
+ domain: 'pinterest.com',
170
+ host_only: false,
171
+ path: '/',
172
+ secure: false,
173
+ http_only: false,
174
+ expires: nil,
175
+ same_site: nil
176
+ )
177
+ )
178
+ end
179
+ end
180
+
181
+ def header_for(url_or_uri, allow_local: false)
182
+ uri = url_or_uri.is_a?(URI) ? url_or_uri : URI.parse(url_or_uri.to_s)
183
+ return '' unless Security.cookie_eligible_host?(uri.host, allow_local: allow_local)
184
+
185
+ now = Time.now
186
+ matched = @mutex.synchronize do
187
+ @entries.reject! { |c| c.expired?(now) }
188
+ @entries
189
+ .select { |c| c.matches?(uri, now: now) }
190
+ .sort_by { |c| -c.path.to_s.length }
191
+ end
192
+
193
+ seen = {}
194
+ pairs = matched.each_with_object([]) do |cookie, acc|
195
+ next if seen[cookie.name]
196
+
197
+ seen[cookie.name] = true
198
+ acc << "#{cookie.name}=#{cookie.value}"
199
+ end
200
+ pairs.join('; ')
201
+ rescue URI::InvalidURIError
202
+ ''
203
+ end
204
+
205
+ def value_for(name, url_or_uri = 'https://www.pinterest.com', allow_local: true)
206
+ target = url_or_uri.to_s.strip.empty? ? 'https://www.pinterest.com' : url_or_uri.to_s
207
+ uri = target.is_a?(URI) ? target : URI.parse(target)
208
+ return nil unless Security.cookie_eligible_host?(uri.host, allow_local: allow_local)
209
+
210
+ now = Time.now
211
+ @mutex.synchronize do
212
+ @entries.reject! { |c| c.expired?(now) }
213
+ found = @entries
214
+ .select { |c| c.name == name.to_s && c.matches?(uri, now: now) }
215
+ .max_by { |c| c.path.to_s.length }
216
+ found&.value
217
+ end
218
+ rescue URI::InvalidURIError
219
+ nil
220
+ end
221
+
222
+ def to_cookie_string(domain: 'https://www.pinterest.com')
223
+ header_for(domain, allow_local: true)
224
+ end
225
+
226
+ private
227
+
228
+ def parse_set_cookie(raw_line, uri)
229
+ segments = raw_line.to_s.split(';').map(&:strip).reject(&:empty?)
230
+ return nil if segments.empty?
231
+
232
+ name, value = segments.shift.split('=', 2)
233
+ return nil if name.nil? || value.nil? || name.strip.empty?
234
+
235
+ origin_host = Security.clean_host(uri.host)
236
+ attrs = default_cookie_attributes(name, value, uri, origin_host)
237
+ state = { max_age_seen: false }
238
+
239
+ segments.each do |segment|
240
+ key, raw_value = segment.split('=', 2)
241
+ apply_cookie_attribute(attrs, key.to_s.strip.downcase, raw_value&.strip, origin_host, state)
242
+ end
243
+
244
+ normalize_pinterest_cookie_domain(attrs)
245
+ Cookie.new(**attrs)
246
+ end
247
+
248
+ def default_cookie_attributes(name, value, uri, origin_host)
249
+ {
250
+ name: name.strip,
251
+ value: value.strip,
252
+ domain: origin_host,
253
+ host_only: true,
254
+ path: default_cookie_path(uri.path),
255
+ secure: false,
256
+ http_only: false,
257
+ expires: nil,
258
+ same_site: nil
259
+ }
260
+ end
261
+
262
+ def apply_cookie_attribute(attrs, key, value, origin_host, state)
263
+ case key
264
+ when 'domain'
265
+ apply_cookie_domain(attrs, value, origin_host)
266
+ when 'path'
267
+ attrs[:path] = value && value.start_with?('/') ? value : '/'
268
+ when 'secure'
269
+ attrs[:secure] = true
270
+ when 'httponly'
271
+ attrs[:http_only] = true
272
+ when 'max-age'
273
+ apply_cookie_max_age(attrs, value, state)
274
+ when 'expires'
275
+ attrs[:expires] = parse_expiry(value) unless state[:max_age_seen]
276
+ when 'samesite'
277
+ attrs[:same_site] = value&.downcase
278
+ end
279
+ end
280
+
281
+ def apply_cookie_domain(attrs, value, origin_host)
282
+ return if value.nil? || value.empty?
283
+
284
+ normalized = value.downcase.sub(/\A\./, '').chomp('.')
285
+ return unless domain_allowed_for_origin?(normalized, origin_host)
286
+
287
+ attrs[:domain] = normalized
288
+ attrs[:host_only] = false
289
+ end
290
+
291
+ def apply_cookie_max_age(attrs, value, state)
292
+ seconds = Integer(value, 10)
293
+ attrs[:expires] = seconds <= 0 ? Time.at(0) : Time.now + seconds
294
+ state[:max_age_seen] = true
295
+ rescue ArgumentError, TypeError
296
+ nil
297
+ end
298
+
299
+ def normalize_pinterest_cookie_domain(attrs)
300
+ return unless Security.pinterest_host?(attrs[:domain]) && attrs[:host_only]
301
+
302
+ attrs[:domain] = 'pinterest.com'
303
+ attrs[:host_only] = false
304
+ end
305
+
306
+ def domain_allowed_for_origin?(cookie_domain, origin_host)
307
+ return false if cookie_domain.empty? || (!cookie_domain.include?('.') && origin_host != cookie_domain)
308
+ return true if origin_host == cookie_domain
309
+ return true if cookie_domain == 'pinterest.com' && Security.pinterest_host?(origin_host)
310
+
311
+ origin_host.end_with?(".#{cookie_domain}")
312
+ end
313
+
314
+ def default_cookie_path(uri_path)
315
+ path = uri_path.to_s
316
+ return '/' if path.empty? || !path.start_with?('/') || path == '/'
317
+
318
+ last_slash = path.rindex('/')
319
+ last_slash.nil? || last_slash.zero? ? '/' : path[0...last_slash]
320
+ end
321
+
322
+ def parse_expiry(raw)
323
+ return nil if raw.nil? || raw.empty?
324
+
325
+ Time.httpdate(raw)
326
+ rescue ArgumentError
327
+ begin
328
+ Time.parse(raw)
329
+ rescue ArgumentError
330
+ nil
331
+ end
332
+ end
333
+
334
+ def upsert_unlocked(cookie)
335
+ @entries.reject! do |existing|
336
+ existing.name == cookie.name &&
337
+ existing.domain == cookie.domain &&
338
+ existing.path == cookie.path
339
+ end
340
+ return if cookie.value.empty? || cookie.expired?
341
+
342
+ @entries << cookie
343
+ end
344
+ end
345
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+
5
+ module PinterestDL
6
+ class PartFile
7
+ attr_reader :path
8
+
9
+ def initialize(destination, resumable: false)
10
+ @path = if resumable
11
+ "#{destination}.part"
12
+ else
13
+ "#{destination}.part.#{Process.pid}.#{Thread.current.object_id}"
14
+ end
15
+ end
16
+
17
+ def finalize!(destination)
18
+ File.rename(path, destination)
19
+ end
20
+
21
+ def self.cleanup(path)
22
+ FileUtils.rm_f(path) if path && File.exist?(path)
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,194 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'net/http'
4
+ require_relative '../errors'
5
+ require_relative '../media_validator'
6
+
7
+ module PinterestDL
8
+ class ResponsePlan
9
+ CONTENT_RANGE_REGEX = %r{\Abytes\s+(\d+)-(\d+)/(\d+|\*)\z}i
10
+
11
+ def self.build(response, url:, resumed_offset:, max_size:, verify_content:)
12
+ new(
13
+ response,
14
+ url: url,
15
+ resumed_offset: resumed_offset,
16
+ max_size: max_size,
17
+ verify_content: verify_content
18
+ ).build
19
+ end
20
+
21
+ def initialize(response, url:, resumed_offset:, max_size:, verify_content:)
22
+ @response = response
23
+ @url = url
24
+ @resumed_offset = resumed_offset
25
+ @max_size = max_size
26
+ @verify_content = verify_content
27
+ end
28
+
29
+ def build
30
+ return empty_plan if @response.nil?
31
+
32
+ status_code = @response.respond_to?(:code) && @response.code ? @response.code.to_i : 200
33
+
34
+ if status_code == 416 || @response.is_a?(Net::HTTPRequestedRangeNotSatisfiable)
35
+ content_range = extract_header('content-range')
36
+ raise RangeNotSatisfiableError.new(
37
+ "Range not satisfiable for #{@url} (HTTP 416)",
38
+ url: @url,
39
+ status_code: 416,
40
+ content_range: content_range
41
+ )
42
+ end
43
+
44
+ content_type = extract_header('content-type')
45
+ MediaValidator.validate_content_type!(content_type, url: @url) if @verify_content
46
+
47
+ content_length = parse_content_length!(extract_header('content-length'))
48
+
49
+ is_partial = @response.is_a?(Net::HTTPPartialContent) || status_code == 206
50
+
51
+ if is_partial
52
+ unless @resumed_offset.positive?
53
+ raise InvalidResponseError.new(
54
+ "Unexpected HTTP 206 without Range request for #{@url}",
55
+ url: @url,
56
+ status_code: 206
57
+ )
58
+ end
59
+
60
+ range_info = parse_content_range!(
61
+ extract_header('content-range'),
62
+ expected_offset: @resumed_offset,
63
+ content_length: content_length
64
+ )
65
+
66
+ effective_offset = @resumed_offset
67
+ expected_body_bytes = range_info[:range_length]
68
+ final_total_size = range_info[:total_size] || (effective_offset + expected_body_bytes)
69
+ write_mode = 'ab'
70
+ else
71
+ effective_offset = 0
72
+ expected_body_bytes = content_length
73
+ final_total_size = content_length
74
+ write_mode = 'wb'
75
+ end
76
+
77
+ validate_max_size!(final_total_size)
78
+
79
+ {
80
+ is_partial: is_partial,
81
+ effective_offset: effective_offset,
82
+ expected_body_bytes: expected_body_bytes,
83
+ final_total_size: final_total_size,
84
+ write_mode: write_mode
85
+ }
86
+ end
87
+
88
+ private
89
+
90
+ def empty_plan
91
+ {
92
+ is_partial: false,
93
+ effective_offset: 0,
94
+ expected_body_bytes: nil,
95
+ final_total_size: nil,
96
+ write_mode: 'wb'
97
+ }
98
+ end
99
+
100
+ def parse_content_range!(header_value, expected_offset:, content_length:)
101
+ raw = header_value.to_s.strip
102
+
103
+ if raw.empty?
104
+ raise InvalidResponseError.new(
105
+ "Missing Content-Range header in HTTP 206 response from #{@url}",
106
+ url: @url,
107
+ status_code: 206
108
+ )
109
+ end
110
+
111
+ match = raw.match(CONTENT_RANGE_REGEX)
112
+
113
+ unless match
114
+ raise InvalidResponseError.new(
115
+ "Malformed Content-Range header #{raw.inspect} from #{@url}",
116
+ url: @url,
117
+ status_code: 206
118
+ )
119
+ end
120
+
121
+ range_start = match[1].to_i
122
+ range_end = match[2].to_i
123
+ total_token = match[3]
124
+ total_size = total_token == '*' ? nil : total_token.to_i
125
+
126
+ if range_start > range_end || (total_size && (total_size <= 0 || range_end >= total_size))
127
+ raise InvalidResponseError.new(
128
+ "Invalid byte range bounds in Content-Range #{raw.inspect} from #{@url}",
129
+ url: @url,
130
+ status_code: 206
131
+ )
132
+ end
133
+
134
+ if range_start != expected_offset
135
+ raise InvalidResponseError.new(
136
+ "Content-Range start (#{range_start}) does not match requested offset (#{expected_offset}) from #{@url}",
137
+ url: @url,
138
+ status_code: 206
139
+ )
140
+ end
141
+
142
+ range_length = (range_end - range_start) + 1
143
+
144
+ if content_length && content_length != range_length
145
+ raise InvalidResponseError.new(
146
+ "Content-Length (#{content_length}) does not match Content-Range length (#{range_length}) from #{@url}",
147
+ url: @url,
148
+ status_code: 206
149
+ )
150
+ end
151
+
152
+ {
153
+ range_start: range_start,
154
+ range_end: range_end,
155
+ range_length: range_length,
156
+ total_size: total_size
157
+ }
158
+ end
159
+
160
+ def parse_content_length!(value)
161
+ return nil if value.nil?
162
+
163
+ raw = value.to_s.strip
164
+
165
+ unless raw.match?(/\A\d+\z/)
166
+ raise InvalidResponseError.new(
167
+ "Invalid Content-Length header #{raw.inspect} from #{@url}",
168
+ url: @url
169
+ )
170
+ end
171
+
172
+ raw.to_i
173
+ end
174
+
175
+ def extract_header(name)
176
+ return nil unless @response.respond_to?(:[])
177
+
178
+ @response[name] ||
179
+ @response[name.downcase] ||
180
+ @response[name.split('-').map(&:capitalize).join('-')]
181
+ end
182
+
183
+ def validate_max_size!(final_total_size)
184
+ return unless @max_size && final_total_size && final_total_size > @max_size
185
+
186
+ raise FileTooLargeError.new(
187
+ "File at #{@url} (#{final_total_size} bytes) exceeds max_file_size (#{@max_size} bytes)",
188
+ url: @url,
189
+ max_size: @max_size,
190
+ actual_size: final_total_size
191
+ )
192
+ end
193
+ end
194
+ end