pinterest-dl 2.4.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,498 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../session'
4
+ require_relative 'theme'
5
+ require_relative 'icons'
6
+ require_relative 'terminal'
7
+ require_relative 'preview'
8
+ require_relative 'download_queue'
9
+ require_relative 'state'
10
+ require_relative 'renderer'
11
+
12
+ module PinterestDL
13
+ module TUI
14
+ class App
15
+ attr_reader :state, :queue, :terminal, :renderer, :preview
16
+
17
+ def initialize(session: nil, terminal: nil, theme: nil, output_dir: './downloads',
18
+ external_preview: true, search_limit: State::DEFAULT_SEARCH_LIMIT)
19
+ @session = session || TUI.build_auto_session
20
+ @terminal = terminal || Terminal.new
21
+ @theme = theme || Theme.new
22
+ @icons = Icons.new(theme: @theme)
23
+ @mutex = Mutex.new
24
+ @dirty = true
25
+ @resized = false
26
+ @running = false
27
+ @bg_threads = []
28
+ @preview = Preview.new(
29
+ theme: @theme,
30
+ icons: @icons,
31
+ session: @session,
32
+ external_tools: external_preview,
33
+ graphics_protocol: @terminal.graphics_protocol,
34
+ on_ready: -> { mark_dirty }
35
+ )
36
+ @state = State.new(
37
+ output_dir: output_dir,
38
+ proxy_enabled: !@session.config.proxy.to_s.empty?,
39
+ search_limit: search_limit
40
+ )
41
+ @renderer = Renderer.new(theme: @theme, icons: @icons, preview: @preview)
42
+ @queue = DownloadQueue.new(session: @session, output_dir: output_dir, on_update: -> { mark_dirty })
43
+ end
44
+
45
+ def run
46
+ @running = true
47
+ prev_winch = install_resize_handler
48
+ @terminal.with_screen do
49
+ render_if_dirty
50
+ event_loop
51
+ end
52
+ ensure
53
+ restore_resize_handler(prev_winch)
54
+ shutdown
55
+ end
56
+
57
+ def handle_key(key)
58
+ return :quit if key == :ctrl_c
59
+ return handle_mouse(key) if key.is_a?(Hash) && key[:type] == :mouse
60
+
61
+ @mutex.synchronize { @state.status_message = nil }
62
+ if %i[search add_url set_limit].include?(@state.mode)
63
+ handle_input_key(key)
64
+ elsif @state.mode == :help
65
+ handle_help_key(key)
66
+ else
67
+ handle_normal_key(key)
68
+ end
69
+ end
70
+
71
+ def handle_mouse(event)
72
+ return :continue unless event[:pressed]
73
+
74
+ case event[:button]
75
+ when :wheel_up
76
+ @mutex.synchronize { @state.move_gallery(:up) }
77
+ return :continue
78
+ when :wheel_down
79
+ @mutex.synchronize { @state.move_gallery(:down) }
80
+ return :continue
81
+ end
82
+
83
+ region = @renderer.region_at(event[:x], event[:y])
84
+ return :continue unless region
85
+
86
+ dispatch_mouse_region(region, event[:button])
87
+ :continue
88
+ end
89
+
90
+ def render_frame
91
+ width, height = @terminal.size
92
+ items = @queue.items
93
+ speed = @queue.active_speed
94
+ @mutex.synchronize do
95
+ @renderer.render(@state, queue_items: items, width: width, height: height, active_speed: speed)
96
+ end
97
+ end
98
+
99
+ def perform_search(query, async: true)
100
+ clean = query.to_s.strip
101
+ return if clean.empty?
102
+
103
+ @mutex.synchronize do
104
+ @state.search_query = clean
105
+ @state.loading = true
106
+ @state.error_banner = nil
107
+ @state.status_message = nil
108
+ @state.network_status = :checking
109
+ @dirty = true
110
+ end
111
+
112
+ work = proc { execute_search_query(clean) }
113
+ async ? spawn_background(&work) : work.call
114
+ end
115
+
116
+ def perform_add_url(url, async: true)
117
+ clean = url.to_s.strip
118
+ return if clean.empty?
119
+
120
+ @mutex.synchronize do
121
+ @state.loading = true
122
+ @state.error_banner = nil
123
+ @state.status_message = nil
124
+ @state.network_status = :checking
125
+ @dirty = true
126
+ end
127
+
128
+ work = proc { execute_url_load(clean) }
129
+ async ? spawn_background(&work) : work.call
130
+ end
131
+
132
+ def apply_search_limit(value, async: true)
133
+ new_limit, active_query = @mutex.synchronize do
134
+ lim = @state.update_search_limit(value)
135
+ @state.status_message = "Search limit set to #{lim}"
136
+ [lim, @state.search_query.dup]
137
+ end
138
+ perform_search(active_query, async: async) unless active_query.empty?
139
+ new_limit
140
+ end
141
+
142
+ def enqueue_batch_download
143
+ pins, img_q, vid_q, out_dir = @mutex.synchronize do
144
+ selected = @state.selected_batch_pins
145
+ targets = selected.empty? ? @state.pins.dup : selected
146
+ [targets, @state.image_quality, @state.video_quality, @state.output_dir]
147
+ end
148
+ return [] if pins.empty?
149
+
150
+ queued = @queue.enqueue_batch(pins, quality: img_q, video_quality: vid_q, output_dir: out_dir)
151
+ @mutex.synchronize do
152
+ @state.clear_selection!
153
+ @state.queue_selected_index = [@queue.items.size - 1, 0].max
154
+ @state.error_banner = nil
155
+ @state.status_message = "Added #{queued.size} item(s) to Download Queue -> #{out_dir}"
156
+ end
157
+ queued
158
+ rescue StandardError => e
159
+ @mutex.synchronize { @state.error_banner = e.message }
160
+ []
161
+ end
162
+
163
+ def shutdown
164
+ @running = false
165
+ @preview.shutdown
166
+ @queue.shutdown
167
+ @bg_threads.each { |t| t.join(0.5) }
168
+ end
169
+
170
+ private
171
+
172
+ def event_loop
173
+ last_clock_min = Time.now.min
174
+ while @running
175
+ if @resized
176
+ @resized = false
177
+ @preview.clear_ueberzug
178
+ @preview.clear_cache
179
+ @terminal.clear_screen
180
+ mark_dirty
181
+ end
182
+
183
+ if @queue.prune_completed
184
+ @mutex.synchronize do
185
+ @state.queue_selected_index = [[@state.queue_selected_index, @queue.items.size - 1].min, 0].max
186
+ end
187
+ mark_dirty
188
+ end
189
+
190
+ key = @terminal.read_key(timeout: 0.08)
191
+ if key
192
+ action = handle_key(key)
193
+ break if action == :quit
194
+
195
+ mark_dirty
196
+ else
197
+ now_min = Time.now.min
198
+ if now_min != last_clock_min || @queue.active_count.positive?
199
+ last_clock_min = now_min
200
+ mark_dirty
201
+ end
202
+ end
203
+ render_if_dirty
204
+ end
205
+ end
206
+
207
+ def dispatch_mouse_region(region, button)
208
+ case region[:action]
209
+ when :search_box
210
+ open_prompt(:search, @state.search_query)
211
+ when :limit_box
212
+ open_prompt(:set_limit, @state.search_limit.to_s)
213
+ when :search_submit
214
+ %i[search add_url set_limit].include?(@state.mode) ? submit_input_buffer : open_prompt(:search, @state.search_query)
215
+ when :category
216
+ @mutex.synchronize { @state.mode = :normal }
217
+ activate_category(region[:value])
218
+ when :card_select
219
+ @mutex.synchronize do
220
+ @state.mode = :normal
221
+ @state.selected_index = region[:value]
222
+ @state.toggle_pin_selection
223
+ end
224
+ when :card
225
+ @mutex.synchronize do
226
+ @state.mode = :normal
227
+ @state.selected_index = region[:value]
228
+ @state.toggle_pin_selection if button == :right
229
+ end
230
+ when :preview_prev
231
+ @mutex.synchronize { @state.move_gallery(:left) }
232
+ when :preview_next
233
+ @mutex.synchronize { @state.move_gallery(:right) }
234
+ when :quality_prev
235
+ @mutex.synchronize { @state.cycle_quality!(-1) }
236
+ when :quality_next
237
+ @mutex.synchronize { @state.cycle_quality!(1) }
238
+ when :download_current
239
+ enqueue_selected_pin
240
+ when :download_batch
241
+ enqueue_batch_download
242
+ when :queue_select
243
+ @mutex.synchronize { @state.queue_selected_index = region[:value] }
244
+ when :queue_pause
245
+ toggle_queue_pause
246
+ when :queue_remove
247
+ remove_selected_download
248
+ end
249
+ end
250
+
251
+ def handle_input_key(key)
252
+ case key
253
+ when :escape
254
+ @mutex.synchronize { @state.mode = :normal }
255
+ when :enter
256
+ submit_input_buffer
257
+ when :backspace
258
+ @mutex.synchronize { @state.input_buffer = @state.input_buffer[0...-1].to_s }
259
+ when String
260
+ if key.valid_encoding? && key.length == 1 && key.ord >= 32
261
+ @mutex.synchronize do
262
+ next if @state.mode == :set_limit && !key.match?(/\A\d\z/)
263
+
264
+ @state.input_buffer = "#{@state.input_buffer}#{key}"
265
+ end
266
+ end
267
+ end
268
+ :continue
269
+ end
270
+
271
+ def submit_input_buffer
272
+ mode, value = @mutex.synchronize do
273
+ m = @state.mode
274
+ v = @state.input_buffer.strip
275
+ @state.mode = :normal
276
+ [m, v]
277
+ end
278
+ return if value.empty?
279
+
280
+ case mode
281
+ when :search then perform_search(value)
282
+ when :add_url then perform_add_url(value)
283
+ when :set_limit then apply_search_limit(value.to_i)
284
+ end
285
+ end
286
+
287
+ def handle_help_key(key)
288
+ return :quit if %w[q Q].include?(key)
289
+
290
+ @mutex.synchronize { @state.mode = :normal } if %i[escape enter].include?(key) || key == '?'
291
+ :continue
292
+ end
293
+
294
+ def handle_normal_key(key)
295
+ case key
296
+ when 'q', 'Q' then return :quit
297
+ when '?'
298
+ @mutex.synchronize { @state.mode = :help }
299
+ when '/'
300
+ open_prompt(:search, @state.search_query)
301
+ when 'l', 'L'
302
+ open_prompt(:set_limit, @state.search_limit.to_s)
303
+ when 'a', 'A'
304
+ open_prompt(:add_url, '')
305
+ when '1', '2', '3', '4', '5', '6', '7', '8'
306
+ activate_category(key.to_i - 1)
307
+ when :tab
308
+ activate_category((@state.category_index + 1) % State::CATEGORIES.size)
309
+ when :shift_tab
310
+ activate_category((@state.category_index - 1) % State::CATEGORIES.size)
311
+ when :up, 'k' then @mutex.synchronize { @state.move_gallery(:up) }
312
+ when :down, 'j' then @mutex.synchronize { @state.move_gallery(:down) }
313
+ when :left, 'h' then @mutex.synchronize { @state.move_gallery(:left) }
314
+ when :right then @mutex.synchronize { @state.move_gallery(:right) }
315
+ when ' ' then @mutex.synchronize { @state.toggle_pin_selection }
316
+ when 's', 'S', :ctrl_a then @mutex.synchronize { @state.toggle_select_all_visible! }
317
+ when 'b', 'B' then enqueue_batch_download
318
+ when 'v', 'V' then @mutex.synchronize { @state.cycle_quality!(1) }
319
+ when 'd', 'D', :enter then enqueue_selected_pin
320
+ when 'p', 'P' then pause_selected_download
321
+ when 'r', 'R' then resume_selected_download
322
+ when :delete, :backspace then remove_selected_download
323
+ end
324
+ :continue
325
+ end
326
+
327
+ def open_prompt(mode, initial)
328
+ @mutex.synchronize do
329
+ @state.mode = mode
330
+ @state.input_buffer = initial.to_s.dup
331
+ end
332
+ end
333
+
334
+ def activate_category(index)
335
+ cat = @mutex.synchronize { @state.select_category(index) }
336
+ if cat[:query]
337
+ perform_search(cat[:query])
338
+ elsif !@state.search_query.empty? && @state.pins.empty?
339
+ perform_search(@state.search_query)
340
+ end
341
+ end
342
+
343
+ def enqueue_selected_pin
344
+ pin, img_q, vid_q, out_dir = @mutex.synchronize do
345
+ [@state.selected_pin, @state.image_quality, @state.video_quality, @state.output_dir]
346
+ end
347
+ return unless pin
348
+
349
+ @queue.enqueue(pin, quality: img_q, video_quality: vid_q, output_dir: out_dir)
350
+ @mutex.synchronize do
351
+ @state.queue_selected_index = [@queue.items.size - 1, 0].max
352
+ @state.error_banner = nil
353
+ @state.status_message = "Added to Download Queue (#{img_q}) -> #{out_dir}"
354
+ end
355
+ rescue StandardError => e
356
+ @mutex.synchronize { @state.error_banner = e.message }
357
+ end
358
+
359
+ def toggle_queue_pause
360
+ item = selected_queue_item
361
+ return unless item
362
+
363
+ if %i[paused failed].include?(item.status)
364
+ @queue.resume(item.id)
365
+ else
366
+ @queue.pause(item.id)
367
+ end
368
+ end
369
+
370
+ def pause_selected_download
371
+ item = selected_queue_item
372
+ @queue.pause(item.id) if item
373
+ end
374
+
375
+ def resume_selected_download
376
+ item = selected_queue_item
377
+ @queue.resume(item.id) if item
378
+ end
379
+
380
+ def remove_selected_download
381
+ item = selected_queue_item
382
+ return unless item
383
+
384
+ removed = @queue.remove(item.id)
385
+ @mutex.synchronize { @state.queue_selected_index = [(@state.queue_selected_index - 1), 0].max } if removed
386
+ end
387
+
388
+ def selected_queue_item
389
+ items = @queue.items
390
+ return nil if items.empty?
391
+
392
+ idx = @mutex.synchronize { @state.queue_selected_index }
393
+ items[idx] || items.last
394
+ end
395
+
396
+ def execute_search_query(query)
397
+ search_type, limit = @mutex.synchronize { [@state.search_type_for_active_category, @state.search_limit] }
398
+ pins = @session.search(query, limit: limit, type: search_type)
399
+ apply_loaded_pins(pins)
400
+ rescue RateLimitError => e
401
+ record_network_error(:rate_limited, "Rate limited (HTTP 429): #{e.message}")
402
+ rescue NetworkError => e
403
+ record_network_error(:offline, "Network error: #{e.message}")
404
+ rescue PinterestDL::Error, StandardError => e
405
+ record_network_error(:online, e.message)
406
+ end
407
+
408
+ def execute_url_load(url)
409
+ limit = @mutex.synchronize { @state.search_limit }
410
+ pins = if url.match?(PinterestDL::PIN_URL_PATTERN)
411
+ media = @session.get_media(url, quality: @state.image_quality)
412
+ pin_id = url[%r{/pin/(?:[^/?#]*--)?(\d+)}, 1] || Time.now.to_i.to_s
413
+ [{
414
+ id: pin_id,
415
+ pin_url: url,
416
+ title: "Pin #{pin_id}",
417
+ description: url,
418
+ creator: '',
419
+ image_url: media[:image_url],
420
+ video_url: media[:video_url]
421
+ }]
422
+ else
423
+ @session.board(url, limit: limit)
424
+ end
425
+ @mutex.synchronize { @state.search_query = url }
426
+ apply_loaded_pins(pins)
427
+ rescue RateLimitError => e
428
+ record_network_error(:rate_limited, "Rate limited (HTTP 429): #{e.message}")
429
+ rescue NetworkError => e
430
+ record_network_error(:offline, "Network error: #{e.message}")
431
+ rescue PinterestDL::Error, StandardError => e
432
+ record_network_error(:online, e.message)
433
+ end
434
+
435
+ def apply_loaded_pins(pins)
436
+ @mutex.synchronize do
437
+ @state.replace_pins(pins)
438
+ @state.loading = false
439
+ @state.network_status = @session.config.proxy.to_s.empty? ? :online : :proxy
440
+ @state.error_banner = nil
441
+ @dirty = true
442
+ end
443
+ end
444
+
445
+ def record_network_error(net_status, message)
446
+ @mutex.synchronize do
447
+ @state.loading = false
448
+ @state.network_status = net_status
449
+ @state.error_banner = message.to_s
450
+ @dirty = true
451
+ end
452
+ end
453
+
454
+ def spawn_background(&block)
455
+ thread = Thread.new do
456
+ Thread.current.report_on_exception = false
457
+ block.call
458
+ end
459
+ @bg_threads << thread
460
+ @bg_threads.select!(&:alive?)
461
+ thread
462
+ end
463
+
464
+ def render_if_dirty
465
+ should_render = @mutex.synchronize do
466
+ val = @dirty
467
+ @dirty = false
468
+ val
469
+ end
470
+ return unless should_render
471
+
472
+ frame = render_frame
473
+ @terminal.render_frame(frame, overlays: @renderer.kitty_overlays)
474
+ @preview.sync_ueberzug(@renderer.ueberzug_placements)
475
+ end
476
+
477
+ def mark_dirty
478
+ @mutex.synchronize { @dirty = true }
479
+ end
480
+
481
+ def install_resize_handler
482
+ return nil unless Signal.list.key?('WINCH')
483
+
484
+ Signal.trap('WINCH') { @resized = true }
485
+ rescue ArgumentError, NotImplementedError
486
+ nil
487
+ end
488
+
489
+ def restore_resize_handler(previous)
490
+ return unless previous && Signal.list.key?('WINCH')
491
+
492
+ Signal.trap('WINCH', previous)
493
+ rescue ArgumentError, NotImplementedError
494
+ nil
495
+ end
496
+ end
497
+ end
498
+ end