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,423 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'uri'
5
+ require_relative '../extractors/image'
6
+
7
+ module PinterestDL
8
+ module TUI
9
+ class DownloadQueue
10
+ PauseSignal = Class.new(StandardError)
11
+ CancelSignal = Class.new(StandardError)
12
+ DEFAULT_WORKERS = 2
13
+ DEFAULT_AUTO_CLEAR_DELAY = 2.5
14
+
15
+ Item = Struct.new(
16
+ :id, :pin_id, :title, :url, :filename, :dest_path, :media_type, :quality,
17
+ :status, :bytes_received, :total_bytes, :speed, :eta, :error_message,
18
+ :started_at, :finished_at,
19
+ keyword_init: true
20
+ ) do
21
+ def progress_ratio
22
+ return 1.0 if status == :completed
23
+ return 0.0 unless total_bytes&.positive?
24
+
25
+ [[bytes_received.to_f / total_bytes, 0.0].max, 1.0].min
26
+ end
27
+
28
+ def percent
29
+ (progress_ratio * 100).round
30
+ end
31
+ end
32
+
33
+ def initialize(session:, output_dir: './downloads', on_update: nil, workers: DEFAULT_WORKERS)
34
+ @session = session
35
+ @output_dir = output_dir
36
+ @on_update = on_update
37
+ @items = []
38
+ @next_id = 1
39
+ @completed_total = 0
40
+ @control_flags = {}
41
+ @mutex = Mutex.new
42
+ @work_queue = Queue.new
43
+ @running = true
44
+ @workers = start_workers([workers.to_i, 1].max)
45
+ end
46
+
47
+ def items
48
+ @mutex.synchronize { @items.map(&:dup) }
49
+ end
50
+
51
+ def active_speed
52
+ @mutex.synchronize do
53
+ @items.select { |i| i.status == :downloading }.sum(&:speed)
54
+ end
55
+ end
56
+
57
+ def active_count
58
+ @mutex.synchronize { @items.count { |i| %i[downloading queued].include?(i.status) } }
59
+ end
60
+
61
+ def failed_count
62
+ @mutex.synchronize { @items.count { |i| i.status == :failed } }
63
+ end
64
+
65
+ def completed_count
66
+ @mutex.synchronize { @completed_total }
67
+ end
68
+
69
+ def prune_completed(ttl: DEFAULT_AUTO_CLEAR_DELAY)
70
+ now = monotonic_now
71
+ pruned = @mutex.synchronize do
72
+ before = @items.size
73
+ @items.reject! do |item|
74
+ if item.status == :completed && item.finished_at && (now - item.finished_at) >= ttl
75
+ @control_flags.delete(item.id)
76
+ true
77
+ else
78
+ false
79
+ end
80
+ end
81
+ before != @items.size
82
+ end
83
+ notify_update if pruned
84
+ pruned
85
+ end
86
+
87
+ def enqueue(pin, quality: :originals, video_quality: :best, output_dir: @output_dir)
88
+ url, media_type = resolve_media_url(pin, quality: quality, video_quality: video_quality)
89
+ raise ArgumentError, 'Pin has no downloadable media URL' if url.to_s.strip.empty?
90
+
91
+ FileUtils.mkdir_p(output_dir)
92
+ filename = build_filename(pin, url, media_type)
93
+ dest_path = File.join(output_dir, filename)
94
+
95
+ item = @mutex.synchronize do
96
+ created = Item.new(
97
+ id: @next_id,
98
+ pin_id: pin[:id].to_s,
99
+ title: pin[:title].to_s,
100
+ url: url,
101
+ filename: filename,
102
+ dest_path: dest_path,
103
+ media_type: media_type,
104
+ quality: media_type == :video ? video_quality : quality,
105
+ status: :queued,
106
+ bytes_received: 0,
107
+ total_bytes: nil,
108
+ speed: 0.0,
109
+ eta: nil,
110
+ error_message: nil
111
+ )
112
+ @next_id += 1
113
+ @items << created
114
+ @control_flags[created.id] = nil
115
+ created.dup
116
+ end
117
+
118
+ @work_queue << item.id
119
+ notify_update
120
+ item
121
+ end
122
+
123
+ def enqueue_batch(pins, quality: :originals, video_quality: :best, output_dir: @output_dir)
124
+ queued = []
125
+ Array(pins).each do |pin|
126
+ queued << enqueue(pin, quality: quality, video_quality: video_quality, output_dir: output_dir)
127
+ rescue ArgumentError
128
+ next
129
+ end
130
+ queued
131
+ end
132
+
133
+ def pause(item_id)
134
+ changed = @mutex.synchronize do
135
+ item = find_item_unlocked(item_id)
136
+ return false unless item
137
+
138
+ if item.status == :queued
139
+ item.status = :paused
140
+ @control_flags[item_id] = :pause
141
+ true
142
+ elsif item.status == :downloading
143
+ @control_flags[item_id] = :pause
144
+ true
145
+ else
146
+ false
147
+ end
148
+ end
149
+ notify_update if changed
150
+ changed
151
+ end
152
+
153
+ def resume(item_id)
154
+ requeue = @mutex.synchronize do
155
+ item = find_item_unlocked(item_id)
156
+ return false unless item && %i[paused failed].include?(item.status)
157
+
158
+ item.status = :queued
159
+ item.error_message = nil
160
+ @control_flags[item_id] = nil
161
+ true
162
+ end
163
+ if requeue
164
+ @work_queue << item_id
165
+ notify_update
166
+ end
167
+ requeue
168
+ end
169
+
170
+ def cancel(item_id)
171
+ changed = @mutex.synchronize do
172
+ item = find_item_unlocked(item_id)
173
+ return false unless item
174
+
175
+ if %i[queued paused].include?(item.status)
176
+ item.status = :cancelled
177
+ item.speed = 0.0
178
+ item.eta = nil
179
+ @control_flags[item_id] = :cancel
180
+ cleanup_part_file(item.dest_path)
181
+ true
182
+ elsif item.status == :downloading
183
+ @control_flags[item_id] = :cancel
184
+ true
185
+ else
186
+ false
187
+ end
188
+ end
189
+ notify_update if changed
190
+ changed
191
+ end
192
+
193
+ def remove(item_id)
194
+ removed = @mutex.synchronize do
195
+ item = find_item_unlocked(item_id)
196
+ return false unless item
197
+
198
+ @control_flags[item_id] = :cancel if item.status == :downloading
199
+ cleanup_part_file(item.dest_path)
200
+ @items.delete(item)
201
+ @control_flags.delete(item_id)
202
+ true
203
+ end
204
+ notify_update if removed
205
+ removed
206
+ end
207
+
208
+ def shutdown
209
+ @mutex.synchronize do
210
+ @running = false
211
+ @control_flags.each_key { |k| @control_flags[k] ||= :pause }
212
+ end
213
+ @workers.size.times { @work_queue << nil }
214
+ @workers.each { |w| w.join(2) }
215
+ end
216
+
217
+ private
218
+
219
+ def start_workers(count)
220
+ Array.new(count) do
221
+ Thread.new do
222
+ Thread.current.report_on_exception = false
223
+ while (item_id = @work_queue.pop)
224
+ break unless running?
225
+
226
+ process_item(item_id)
227
+ end
228
+ end
229
+ end
230
+ end
231
+
232
+ def running?
233
+ @mutex.synchronize { @running }
234
+ end
235
+
236
+ def process_item(item_id)
237
+ snapshot = @mutex.synchronize do
238
+ item = find_item_unlocked(item_id)
239
+ next nil unless item&.status == :queued
240
+
241
+ item.status = :downloading
242
+ item.started_at = monotonic_now
243
+ item.error_message = nil
244
+ @control_flags[item_id] = nil
245
+ item.dup
246
+ end
247
+ return unless snapshot
248
+
249
+ notify_update
250
+ execute_real_download(snapshot)
251
+ end
252
+
253
+ def execute_real_download(snapshot)
254
+ @session.download(
255
+ snapshot.url,
256
+ path: snapshot.dest_path,
257
+ overwrite: true,
258
+ resume: true
259
+ ) do |progress|
260
+ check_control_signal!(snapshot.id)
261
+ update_item_progress(snapshot.id, progress)
262
+ end
263
+
264
+ mark_completed(snapshot.id, snapshot.dest_path)
265
+ rescue PauseSignal
266
+ mark_paused(snapshot.id)
267
+ rescue CancelSignal
268
+ cleanup_part_file(snapshot.dest_path)
269
+ mark_cancelled(snapshot.id)
270
+ rescue PinterestDL::Error, StandardError => e
271
+ flag = @mutex.synchronize { @control_flags[snapshot.id] }
272
+ if flag == :pause
273
+ mark_paused(snapshot.id)
274
+ elsif flag == :cancel
275
+ cleanup_part_file(snapshot.dest_path)
276
+ mark_cancelled(snapshot.id)
277
+ else
278
+ mark_failed(snapshot.id, e.message)
279
+ end
280
+ end
281
+
282
+ def check_control_signal!(item_id)
283
+ flag = @mutex.synchronize { @control_flags[item_id] }
284
+ raise PauseSignal if flag == :pause
285
+ raise CancelSignal if flag == :cancel
286
+ end
287
+
288
+ def update_item_progress(item_id, progress)
289
+ received = progress.is_a?(Hash) ? progress[:received].to_i : progress.to_i
290
+ total = progress.is_a?(Hash) ? progress[:total] : nil
291
+ speed = progress.is_a?(Hash) ? progress[:speed].to_f : 0.0
292
+ remaining = total&.positive? ? [total - received, 0].max : nil
293
+ eta = remaining && speed.positive? ? (remaining.to_f / speed) : nil
294
+
295
+ @mutex.synchronize do
296
+ item = find_item_unlocked(item_id)
297
+ next unless item
298
+
299
+ item.bytes_received = received
300
+ item.total_bytes = total if total&.positive?
301
+ item.speed = speed
302
+ item.eta = eta
303
+ end
304
+ notify_update
305
+ end
306
+
307
+ def mark_completed(item_id, dest_path)
308
+ final_size = File.exist?(dest_path) ? File.size(dest_path) : nil
309
+ @mutex.synchronize do
310
+ item = find_item_unlocked(item_id)
311
+ next unless item
312
+
313
+ item.status = :completed
314
+ item.bytes_received = final_size if final_size
315
+ item.total_bytes = final_size if final_size
316
+ item.speed = 0.0
317
+ item.eta = 0.0
318
+ item.finished_at = monotonic_now
319
+ @completed_total += 1
320
+ end
321
+ notify_update
322
+ end
323
+
324
+ def mark_paused(item_id)
325
+ @mutex.synchronize do
326
+ item = find_item_unlocked(item_id)
327
+ next unless item
328
+
329
+ item.status = :paused
330
+ item.speed = 0.0
331
+ item.eta = nil
332
+ end
333
+ notify_update
334
+ end
335
+
336
+ def mark_cancelled(item_id)
337
+ @mutex.synchronize do
338
+ item = find_item_unlocked(item_id)
339
+ next unless item
340
+
341
+ item.status = :cancelled
342
+ item.speed = 0.0
343
+ item.eta = nil
344
+ end
345
+ notify_update
346
+ end
347
+
348
+ def mark_failed(item_id, message)
349
+ @mutex.synchronize do
350
+ item = find_item_unlocked(item_id)
351
+ next unless item
352
+
353
+ item.status = :failed
354
+ item.speed = 0.0
355
+ item.eta = nil
356
+ item.error_message = message.to_s
357
+ end
358
+ notify_update
359
+ end
360
+
361
+ def resolve_media_url(pin, quality:, video_quality:)
362
+ if !pin[:video_url].to_s.empty?
363
+ url = apply_video_quality(pin[:video_url], video_quality)
364
+ [url, :video]
365
+ else
366
+ raw = pin[:image_url].to_s
367
+ url = raw.empty? ? '' : Extractors::Image.apply_quality(raw, quality)
368
+ [url, :image]
369
+ end
370
+ end
371
+
372
+ def apply_video_quality(url, video_quality)
373
+ return url if video_quality == :best || video_quality.nil?
374
+
375
+ str = url.to_s
376
+ case video_quality.to_sym
377
+ when :'720p' then str.sub(%r{/(?:1080p|480p|360p)/}, '/720p/')
378
+ when :'480p' then str.sub(%r{/(?:1080p|720p|360p)/}, '/480p/')
379
+ when :'1080p' then str.sub(%r{/(?:720p|480p|360p)/}, '/1080p/')
380
+ else str
381
+ end
382
+ end
383
+
384
+ def build_filename(pin, url, media_type)
385
+ default_ext = media_type == :video ? '.mp4' : '.jpg'
386
+ ext = begin
387
+ found = File.extname(URI.parse(url).path.to_s)
388
+ found.match?(/\A\.[A-Za-z0-9]{2,5}\z/) ? found : default_ext
389
+ rescue URI::InvalidURIError
390
+ default_ext
391
+ end
392
+ raw_title = pin[:title].to_s.strip.downcase.gsub(/[^a-z0-9]+/, '_').gsub(/\A_|_\z/, '')
393
+ pin_id = pin[:id].to_s.gsub(/[^A-Za-z0-9_-]/, '')
394
+ stem = if !raw_title.empty?
395
+ raw_title[0, 24]
396
+ elsif !pin_id.empty?
397
+ "pin_#{pin_id}"
398
+ else
399
+ "pin_#{Time.now.to_i}"
400
+ end
401
+ suffix = pin_id.empty? ? '' : "_#{pin_id[-6, 6] || pin_id}"
402
+ "#{stem}#{suffix}#{ext}"
403
+ end
404
+
405
+ def cleanup_part_file(dest_path)
406
+ part = "#{dest_path}.part"
407
+ FileUtils.rm_f(part) if File.exist?(part)
408
+ end
409
+
410
+ def find_item_unlocked(item_id)
411
+ @items.find { |i| i.id == item_id }
412
+ end
413
+
414
+ def notify_update
415
+ @on_update&.call
416
+ end
417
+
418
+ def monotonic_now
419
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
420
+ end
421
+ end
422
+ end
423
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PinterestDL
4
+ module TUI
5
+ class Icons
6
+ def initialize(theme:)
7
+ @theme = theme
8
+ end
9
+
10
+ def wifi(status)
11
+ case status
12
+ when :online
13
+ "#{@theme.paint('ᯤ', color: :green, bold: true)} #{@theme.paint('Online', color: :green, bold: true)}"
14
+ when :proxy
15
+ "#{@theme.paint('ᯤ', color: :cyan, bold: true)} #{@theme.paint('Proxy', color: :cyan, bold: true)}"
16
+ when :rate_limited
17
+ "#{@theme.paint('ᯤ', color: :yellow, bold: true)} #{@theme.paint('429', color: :yellow, bold: true)}"
18
+ when :checking
19
+ "#{@theme.paint('ᯤ', color: :purple, bold: true)} #{@theme.paint('Sync', color: :purple, bold: true)}"
20
+ else
21
+ "#{@theme.paint('ᯤ', color: :red, bold: true)} #{@theme.paint('Offline', color: :red, bold: true)}"
22
+ end
23
+ end
24
+
25
+ def signal_bars(active: true)
26
+ return '╷││┃' if @theme.color_mode == :mono
27
+
28
+ if active
29
+ "#{@theme.paint('╷', color: :purple)}" \
30
+ "#{@theme.paint('│', color: :cyan)}" \
31
+ "#{@theme.paint('│', color: :green)}" \
32
+ "#{@theme.paint('┃', color: :green, bold: true)}"
33
+ else
34
+ "#{@theme.paint('╷', color: :border_dim)}" \
35
+ "#{@theme.paint('│', color: :purple)}" \
36
+ "#{@theme.paint('│', color: :purple, bold: true)}" \
37
+ "#{@theme.paint('┃', color: :cyan)}"
38
+ end
39
+ end
40
+
41
+ def search
42
+ @theme.paint('⌕', color: :pink, bold: true)
43
+ end
44
+
45
+ def image
46
+ @theme.paint('⊞', color: :purple, bold: true)
47
+ end
48
+
49
+ def video
50
+ @theme.paint('▸', color: :pink, bold: true)
51
+ end
52
+
53
+ def quality_glyph
54
+ @theme.paint('★', color: :yellow, bold: true)
55
+ end
56
+
57
+ def size_glyph
58
+ @theme.paint('⊞', color: :cyan, bold: true)
59
+ end
60
+
61
+ def format_glyph
62
+ @theme.paint('◈', color: :purple, bold: true)
63
+ end
64
+
65
+ def creator_glyph
66
+ @theme.paint('◉', color: :pink, bold: true)
67
+ end
68
+
69
+ def clock_glyph
70
+ @theme.paint('◉', color: :pink, bold: true)
71
+ end
72
+
73
+ def download
74
+ @theme.paint('↓', color: :pink, bold: true)
75
+ end
76
+
77
+ def pause
78
+ @theme.paint('║', color: :purple, bold: true)
79
+ end
80
+
81
+ def resume
82
+ @theme.paint('▸', color: :green, bold: true)
83
+ end
84
+
85
+ def trash
86
+ @theme.paint('✕', color: :red, bold: true)
87
+ end
88
+
89
+ def check
90
+ @theme.paint('✓', color: :green, bold: true)
91
+ end
92
+
93
+ def placeholder_canvas(width:, height:, label:, video: false)
94
+ w = [width.to_i, 4].max
95
+ h = [height.to_i, 2].max
96
+ mid = h / 2
97
+ Array.new(h) do |row|
98
+ if video && row.zero? && w >= 4
99
+ badge = @theme.paint(' ▸ ', color: :white, background: :pink, bold: true)
100
+ pad = [w - 3, 0].max
101
+ @theme.fit("#{' ' * pad}#{badge}", w)
102
+ elsif row == mid
103
+ txt = @theme.truncate(label, [w - 2, 1].max)
104
+ pad = [(w - @theme.visible_length(txt)) / 2, 0].max
105
+ @theme.fit((' ' * pad) + @theme.paint(txt, color: :dim_text), w)
106
+ else
107
+ @theme.fit('', w)
108
+ end
109
+ end
110
+ end
111
+ end
112
+ end
113
+ end