-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1964 lines (1671 loc) · 74.2 KB
/
Copy pathscript.js
File metadata and controls
1964 lines (1671 loc) · 74.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* FinFetcher 🦭
* Frontend JavaScript for video/music download application.
*/
// State
let currentMode = 'video';
let currentUrl = '';
let videoDuration = 0;
let cachedVideoInfo = null;
let cachedInfoUrl = null;
let canSelfUpdate = true;
let flipperClipperAvailable = false;
let pendingPassToFlipperClipper = false;
let destinationRequest = null;
// True only while the download stream is open, which is the only window in
// which /api/download/cancel has anything to act on
let downloadInFlight = false;
// Initialize - check for ffmpeg first
checkSetup();
/**
* Read a Server-Sent-Event stream, buffering across reads.
* A network chunk can split an event in half, so events are only parsed once a
* complete "\n\n" terminated block has arrived — otherwise a status or error
* event landing on a chunk boundary is silently lost.
* Return false from onEvent to stop reading early.
*/
async function readEventStream(response, onEvent) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
while (true) {
const { value, done } = await reader.read();
buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
const events = buffer.split('\n\n');
// The last piece is an incomplete event — keep it for the next read
buffer = done ? '' : events.pop();
for (const event of events) {
const line = event.trim();
if (!line.startsWith('data: ')) continue;
let data;
try {
data = JSON.parse(line.substring(6));
} catch (e) {
continue; // malformed event - skip it, keep reading
}
if (onEvent(data) === false) return;
}
if (done) return;
}
} finally {
try { reader.cancel(); } catch (e) { /* stream already closed */ }
}
}
async function checkSetup() {
try {
const response = await fetch('/api/setup/check');
const data = await response.json();
if (data.installed) {
// FFmpeg is installed, show main app
showMainApp();
} else {
// Show setup screen
showSetupScreen();
}
} catch (e) {
console.error('Setup check failed:', e);
// If check fails, try to show main app anyway
showMainApp();
}
}
function showSetupScreen() {
document.getElementById('setupScreen').classList.remove('hidden');
document.getElementById('mainContainer').classList.add('hidden');
}
async function showMainApp() {
document.getElementById('setupScreen').classList.add('hidden');
document.getElementById('mainContainer').classList.remove('hidden');
// Initialize main app
selectMode(currentMode);
loadVersion();
checkFlipperClipper();
// Only check for updates if the user hasn't turned that off
const settings = await loadUpdateSettings();
if (!settings || settings.auto_check_updates !== false) {
checkForUpdates({ bypassCooldown: true });
restartUpdateCheckTimer();
}
}
async function installFFmpeg() {
const buttons = document.getElementById('setupButtons');
const progress = document.getElementById('setupProgress');
const progressFill = document.getElementById('setupProgressFill');
const status = document.getElementById('setupStatus');
const note = document.querySelector('.setup-note');
// Hide buttons, show progress
buttons.classList.add('hidden');
progress.classList.remove('hidden');
if (note) note.classList.add('hidden');
// Put the setup screen back so the user can retry or browse manually
const showFailure = (message) => {
status.textContent = message;
status.style.color = '#ff6b6b';
buttons.classList.remove('hidden');
progress.classList.add('hidden');
if (note) note.classList.remove('hidden');
};
try {
const response = await fetch('/api/setup/install-sync', { method: 'POST' });
let settled = false;
await readEventStream(response, (data) => {
// Update progress bar
progressFill.style.width = data.percent + '%';
status.textContent = data.status;
// Check for completion
if (data.success === true) {
settled = true;
setTimeout(() => {
showMainApp();
}, 1000);
return false;
} else if (data.success === false) {
settled = true;
showFailure('Installation failed. Please try again or browse manually.');
return false;
}
});
// Stream ended without telling us either way — don't strand the user
if (!settled) {
showFailure('Installation ended unexpectedly. Please try again or browse manually.');
}
} catch (e) {
console.error('Install error:', e);
showFailure('Error: ' + e.message);
}
}
async function browseFFmpeg() {
try {
const path = await window.pywebview.api.select_folder();
if (path) {
const response = await fetch('/api/setup/browse', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: path })
});
const data = await response.json();
if (data.success) {
showMainApp();
} else {
alert(data.error || 'FFmpeg not found in selected folder. Please select a folder containing ffmpeg.exe');
}
}
} catch (e) {
console.error('Browse error:', e);
alert('Error selecting folder: ' + e.message);
}
}
async function exitApp() {
try {
await fetch('/api/setup/exit', { method: 'POST' });
} catch (e) {
// App should be closing
}
}
// Load version from version.txt
async function loadVersion() {
try {
const response = await fetch('/version.txt');
const version = (await response.text()).trim();
document.getElementById('versionDisplay').textContent = `v${version} · Made by Kiera`;
} catch (e) {
document.getElementById('versionDisplay').textContent = 'v1.0.0 · Made by Kiera';
}
}
// Fetch video info when URL input loses focus
document.getElementById('urlInput').addEventListener('blur', async (e) => {
const url = e.target.value.trim();
if (url && url !== currentUrl) {
currentUrl = url;
const info = await fetchVideoInfo(url);
// Only mark the cache valid for the URL that actually produced it —
// clicking Download blurs the input, so this fetch is still in flight
cachedVideoInfo = info;
cachedInfoUrl = info ? url : null;
}
});
function selectMode(mode) {
currentMode = mode;
document.querySelectorAll('.option-card').forEach(card => {
card.classList.remove('selected');
if (card.dataset.mode === mode) {
card.classList.add('selected');
}
});
// Hide advanced options and download location toggle for stream mode
const advancedOptions = document.querySelector('.advanced-options');
const downloadLocationToggle = document.getElementById('downloadLocationToggle');
const downloadBtn = document.getElementById('downloadBtn');
if (mode === 'stream') {
advancedOptions.style.display = 'none';
if (downloadLocationToggle) downloadLocationToggle.style.display = 'none';
downloadBtn.textContent = 'Stream';
} else {
advancedOptions.style.display = '';
if (downloadLocationToggle) downloadLocationToggle.style.display = '';
downloadBtn.textContent = 'Download';
}
// Stream mode has no download to stop, and the mode cards stay clickable
// while one is running, so the control has to follow the mode as well
updateCancelVisibility();
updateFlipperClipperVisibility();
}
async function checkFlipperClipper() {
try {
const response = await fetch('/api/integrations/flipperclipper');
const data = await response.json();
flipperClipperAvailable = response.ok && data.installed === true;
} catch (e) {
flipperClipperAvailable = false;
}
updateFlipperClipperVisibility();
}
function updateFlipperClipperVisibility() {
const button = document.getElementById('flipperClipperBtn');
const show = flipperClipperAvailable && currentMode === 'video';
button.classList.toggle('hidden', !show);
}
// Cancel is only offered when there is something to cancel. Anything else
// would POST to a backend with no running download and then sit on
// "Cancelling..." waiting for a stream event that never comes.
function updateCancelVisibility() {
const cancelBtn = document.getElementById('cancelBtn');
const show = downloadInFlight && currentMode !== 'stream';
cancelBtn.classList.toggle('hidden', !show);
}
function toggleAdvanced() {
document.getElementById('advancedContent').classList.toggle('hidden');
const chevron = document.querySelector('.advanced-header .chevron');
chevron.textContent = chevron.textContent === '▼' ? '▲' : '▼';
}
function toggleTrimInputs() {
const isChecked = document.getElementById('trimToggle').checked;
const inputs = document.getElementById('trimInputs');
inputs.classList.toggle('hidden', !isChecked);
}
function log(message) {
const container = document.getElementById('logContainer');
const entry = document.createElement('div');
entry.className = 'log-entry';
entry.textContent = `> ${message}`;
container.appendChild(entry);
container.scrollTop = container.scrollHeight;
}
async function fetchVideoInfo(url, preserveState = false) {
try {
document.getElementById('urlStatus').textContent = "🦭 Your seal is fetching...";
document.querySelector('#logContainer').innerHTML = "<div class='log-entry'>> Your seal is diving for metadata...</div>";
document.getElementById('previewPanel').classList.add('hidden');
const response = await fetch('/api/info', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: url })
});
const data = await response.json();
if (data.error) throw new Error(data.error);
videoDuration = data.duration || 0;
if (!preserveState) {
initializeSlider();
}
// Populate quality dropdown from available formats
const qualitySelect = document.getElementById('qualitySelect');
const previousValue = preserveState ? qualitySelect.value : null;
qualitySelect.innerHTML = '<option value="max">Max (4K/8K)</option><option value="1080p">1080p Compatible</option>';
if (data.formats && data.formats.length > 0) {
const heights = [...new Set(data.formats.map(f => f.height).filter(h => h && h >= 144))].sort((a, b) => b - a);
if (heights.length > 0) {
qualitySelect.innerHTML = '<option value="max">Max (Best)</option>';
heights.forEach(h => {
const opt = document.createElement('option');
opt.value = h + 'p';
opt.textContent = `${h}p`;
qualitySelect.appendChild(opt);
});
}
}
// Restore previous selection if still available
if (previousValue && Array.from(qualitySelect.options).some(o => o.value === previousValue)) {
qualitySelect.value = previousValue;
}
// Populate preview panel
populatePreviewPanel(data);
document.getElementById('urlStatus').textContent = "✅ Ready to download";
document.querySelector('#logContainer').innerHTML = "<div class='log-entry'>> Ready to download! ✅</div>";
return data;
} catch (e) {
console.error(e);
recordError(e.message);
document.getElementById('urlStatus').textContent = "❌ Your seal couldn't find that";
log(`Your seal couldn't find that: ${e.message}`);
document.getElementById('previewPanel').classList.add('hidden');
return null;
}
}
function populatePreviewPanel(data) {
const panel = document.getElementById('previewPanel');
const thumb = document.getElementById('previewThumb');
const title = document.getElementById('previewTitle');
const singleVideoMeta = document.getElementById('singleVideoMeta');
const duration = document.getElementById('previewDuration');
const size = document.getElementById('previewSize');
const playlistDropdown = document.getElementById('playlistDropdown');
const singleVideoOptions = document.getElementById('singleVideoOptions');
// Set thumbnail
if (data.thumbnail) {
thumb.src = data.thumbnail;
thumb.style.display = 'block';
} else {
thumb.style.display = 'none';
}
// Set title
title.textContent = data.title || 'Unknown Title';
// Handle playlist vs single video
if (data.is_playlist && data.entries) {
// Playlist mode
singleVideoMeta.classList.add('hidden');
playlistDropdown.classList.remove('hidden');
document.getElementById('playlistCount').textContent = `${data.entries_count} videos in playlist`;
// Disable Quality and Trim for playlists
singleVideoOptions.classList.add('disabled-for-playlist');
// The greyed-out styling doesn't clear the control, so a trim left over
// from a previous single video would still be submitted with the playlist
const playlistTrimToggle = document.getElementById('trimToggle');
playlistTrimToggle.checked = false;
toggleTrimInputs();
// Populate playlist entries
const entriesContainer = document.getElementById('playlistEntries');
entriesContainer.innerHTML = '';
// Built with textContent, never innerHTML — entry titles come from the
// remote site and would otherwise execute as HTML in this window.
data.entries.forEach((entry, index) => {
const entryEl = document.createElement('div');
entryEl.className = 'playlist-entry';
const header = document.createElement('div');
header.className = 'playlist-entry-header';
const entryTitle = document.createElement('span');
entryTitle.className = 'playlist-entry-title';
entryTitle.textContent = `${index + 1}. ${entry.title}`;
const entryDuration = document.createElement('span');
entryDuration.className = 'playlist-entry-duration';
entryDuration.textContent = formatTime(entry.duration || 0);
header.appendChild(entryTitle);
header.appendChild(entryDuration);
entryEl.appendChild(header);
entriesContainer.appendChild(entryEl);
});
} else {
// Single video mode
singleVideoMeta.classList.remove('hidden');
playlistDropdown.classList.add('hidden');
// Enable Quality and Trim for single videos
singleVideoOptions.classList.remove('disabled-for-playlist');
// Set duration and size
duration.textContent = formatTime(data.duration || 0);
size.textContent = data.size_formatted || '~Unknown';
}
// Show panel
panel.classList.remove('hidden');
}
async function initiateDownload(passToFlipperClipper = false) {
const urlInput = document.getElementById('urlInput');
const url = urlInput.value.trim();
if (!url) {
alert("Please enter a YouTube URL");
return;
}
// Handle stream mode separately
if (currentMode === 'stream') {
startStream(url);
return;
}
pendingPassToFlipperClipper = passToFlipperClipper;
document.getElementById('downloadBtn').disabled = true;
document.getElementById('flipperClipperBtn').disabled = true;
document.getElementById('downloadBtn').textContent = "Starting...";
// Use cached info only if it was fetched for this exact URL
currentUrl = url;
let data = cachedVideoInfo;
if (url !== cachedInfoUrl || !cachedVideoInfo) {
data = await fetchVideoInfo(url, true);
cachedVideoInfo = data;
cachedInfoUrl = data ? url : null;
}
if (data) {
if (data.is_playlist) {
document.getElementById('playlistModal').classList.remove('hidden');
} else {
startDownload('single', pendingPassToFlipperClipper);
}
} else {
resetUI();
}
}
function confirmDownload(type) {
document.getElementById('playlistModal').classList.add('hidden');
startDownload(type, pendingPassToFlipperClipper);
}
// --- Trim Slider Functions ---
function initializeSlider() {
const rangeStart = document.getElementById('rangeStart');
const rangeEnd = document.getElementById('rangeEnd');
const trimToggle = document.getElementById('trimToggle');
// No usable duration (playlist, live stream, some direct links) means the
// slider can only ever produce 00:00 → 00:00, so don't offer trimming
if (!videoDuration || videoDuration <= 0) {
// Collapse the range too, so a leftover max from the previous video
// can't clamp anything the user types into the time boxes
rangeStart.max = 0;
rangeEnd.max = 0;
rangeStart.value = 0;
rangeEnd.value = 0;
trimToggle.checked = false;
trimToggle.disabled = true;
trimToggle.title = 'Trimming needs a video with a known duration';
toggleTrimInputs();
return;
}
trimToggle.disabled = false;
trimToggle.title = '';
rangeStart.max = videoDuration;
rangeEnd.max = videoDuration;
rangeStart.value = 0;
rangeEnd.value = videoDuration;
updateSlider();
}
function updateSlider(handle) {
const rangeStart = document.getElementById('rangeStart');
const rangeEnd = document.getElementById('rangeEnd');
const startVal = parseInt(rangeStart.value);
const endVal = parseInt(rangeEnd.value);
// Prevent handles from crossing
if (endVal < startVal) {
if (handle === 'start') {
rangeStart.value = endVal;
} else {
rangeEnd.value = startVal;
}
}
const min = parseInt(rangeStart.min);
const max = parseInt(rangeStart.max);
// Degenerate range (unknown duration) — writing back would clobber whatever
// the user typed with 00:00 and the fill percentage would be NaN
if (!(max > min)) return;
const currentStart = parseInt(rangeStart.value);
const currentEnd = parseInt(rangeEnd.value);
// Update visual fill
const fill = document.getElementById('sliderFill');
const percentStart = ((currentStart - min) / (max - min)) * 100;
const percentEnd = ((currentEnd - min) / (max - min)) * 100;
fill.style.left = percentStart + "%";
fill.style.width = (percentEnd - percentStart) + "%";
// Sync text inputs
document.getElementById('trimStart').value = formatTime(currentStart);
document.getElementById('trimEnd').value = formatTime(currentEnd);
}
function updateFromText() {
const startText = document.getElementById('trimStart').value;
const endText = document.getElementById('trimEnd').value;
const startSec = parseTime(startText);
const endSec = parseTime(endText);
if (startSec !== null) document.getElementById('rangeStart').value = startSec;
if (endSec !== null) document.getElementById('rangeEnd').value = endSec;
updateSlider(null);
}
function formatTime(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
if (h > 0) {
return `${h}:${pad(m)}:${pad(s)}`;
}
return `${pad(m)}:${pad(s)}`;
}
function pad(num) {
return num.toString().padStart(2, '0');
}
function parseTime(timeStr) {
if (!timeStr) return 0;
const parts = timeStr.split(':').map(Number);
if (parts.some(isNaN)) return null;
let seconds = 0;
if (parts.length === 3) {
seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
} else if (parts.length === 2) {
seconds = parts[0] * 60 + parts[1];
} else if (parts.length === 1) {
seconds = parts[0];
}
return seconds;
}
// --- Download Functions ---
async function startDownload(type, passToFlipperClipper = false) {
const progressArea = document.getElementById('progressArea');
progressArea.classList.remove('hidden');
document.getElementById('downloadBtn').textContent = "Downloading...";
log(`Starting ${type} download...`);
log(`Mode: ${currentMode}`);
// Collect options before folder dialog (pywebview can cause UI state issues)
const logToFile = document.getElementById('logToggle').checked;
const quality = document.getElementById('qualitySelect').value;
// Trimming applies to a single file only — never send it with a playlist
const trim = type !== 'playlist' && document.getElementById('trimToggle').checked;
let trimStart = null;
let trimEnd = null;
if (trim) {
trimStart = document.getElementById('trimStart').value.trim();
trimEnd = document.getElementById('trimEnd').value.trim();
if (!trimStart || !trimEnd) {
alert("Please enter start and end times for trimming (e.g. 00:30, 01:45)");
resetUI();
return;
}
const startSec = parseTime(trimStart);
const endSec = parseTime(trimEnd);
if (startSec === null || endSec === null || endSec <= startSec) {
alert("Please enter a valid trim range — the end time must be after the start time.");
resetUI();
return;
}
}
let savePath = null;
const locationToggle = document.getElementById('locationToggle');
if (locationToggle && locationToggle.checked) {
log("Select download folder...");
try {
savePath = await window.pywebview.api.select_folder();
if (!savePath) {
log("Download cancelled (no folder selected).");
resetUI();
return;
}
log(`Saving to: ${savePath}`);
} catch (e) {
log("Error selecting folder: " + e);
}
}
// Start download request.
// Cancel goes up NOW, not once the response starts arriving: the backend
// registers the job before it returns the stream, and a streaming response
// does not resolve fetch() until its first event — which, for a trimmed
// download, is not until ffmpeg has finished. Waiting for that is what left
// the window with a "Downloading..." button and no way to stop it.
downloadInFlight = true;
updateCancelVisibility();
try {
const response = await fetch('/api/download', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: currentUrl,
mode: currentMode,
type: type,
save_path: savePath,
log_to_file: logToFile,
quality: quality,
trim_start: trimStart,
trim_end: trimEnd,
pass_to_flipperclipper: passToFlipperClipper
})
});
if (!response.ok) {
// The backend rejected the request outright — that's JSON, not a stream
const err = await response.json().catch(() => ({}));
const reason = err.error || `HTTP ${response.status}`;
log("Error: " + reason);
recordError(reason);
} else {
await readEventStream(response, (msg) => {
if (msg.destination_request) {
destinationRequest = msg.destination_request;
document.getElementById('destinationPaths').textContent = destinationRequest.paths.join('\n');
document.getElementById('destinationError').textContent = '';
document.getElementById('destinationModal').classList.remove('hidden');
document.getElementById('destinationCancel').focus();
document.getElementById('downloadBtn').textContent = 'Waiting for destination...';
}
if (msg.log) {
log(msg.log);
}
if (msg.status === 'completed') {
log("Download Complete! ✅");
}
// A stopped download is not a finished one. Keep reading rather
// than returning false — the backend still reports its cleanup
// after this, and the stream ends on its own.
if (msg.status === 'cancelled') {
log("Download cancelled.");
}
// The reason came through as msg.error just before this; this
// is only the marker that the run is over and it failed
if (msg.status === 'error') {
log("Download failed.");
}
// The download's own failures are the ones worth keeping for
// the debug panel — an ffmpeg exit code or a refused fetch
// reaches the user here and nowhere else, and until this was
// recorded "Last Error" still read "No errors recorded"
// while the log plainly showed one.
if (msg.error) {
log("Error: " + msg.error);
recordError(msg.error);
}
});
}
} catch (e) {
log("Network Error: " + e.message);
recordError(`Network error during download: ${e.message}`);
}
// Always re-enable the UI once the stream is over, however it ended
resetUI();
}
async function chooseDownloadDestination(action) {
if (!destinationRequest) return;
const activeRequest = destinationRequest;
const buttons = document.querySelectorAll('#destinationModal button');
buttons.forEach(button => button.disabled = true);
try {
let path = null;
if (action === 'folder') {
path = await window.pywebview.api.select_folder();
if (!path) return;
}
const response = await fetch('/api/download/destination', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: activeRequest.id, action, path })
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Could not choose the destination.');
if (destinationRequest === activeRequest) {
destinationRequest = null;
document.getElementById('destinationModal').classList.add('hidden');
document.getElementById('downloadBtn').textContent = 'Downloading...';
}
} catch (error) {
document.getElementById('destinationError').textContent = error.message;
} finally {
buttons.forEach(button => button.disabled = false);
}
}
async function cancelDownload() {
const cancelBtn = document.getElementById('cancelBtn');
// A second click would only fire a second POST, so the button reports the
// request instead of staying live. It is disabled rather than hidden so the
// user can still see that the cancel is being dealt with.
if (cancelBtn.disabled) return;
cancelBtn.disabled = true;
cancelBtn.textContent = "Cancelling...";
log("Cancelling download...");
// The button is left alone on success: the stream reports the cancellation,
// and resetUI restores the idle state once it closes.
const failed = (reason) => {
log("Couldn't cancel: " + reason);
cancelBtn.disabled = false;
cancelBtn.textContent = "Cancel";
};
try {
const response = await fetch('/api/download/cancel', { method: 'POST' });
const data = await response.json().catch(() => ({}));
if (!response.ok) {
failed(data.error || `HTTP ${response.status}`);
} else if (!data.success) {
// 200 without success means the backend has no download to stop,
// so reporting the status code would say nothing useful
failed(data.error || 'the download was not stopped');
}
} catch (e) {
failed(e.message);
}
}
function resetUI() {
destinationRequest = null;
document.getElementById('destinationModal').classList.add('hidden');
document.getElementById('downloadBtn').disabled = false;
document.getElementById('downloadBtn').textContent = "Download";
const flipperClipperBtn = document.getElementById('flipperClipperBtn');
flipperClipperBtn.disabled = false;
flipperClipperBtn.textContent = "Pass to FlipperClipper";
pendingPassToFlipperClipper = false;
toggleTrimInputs();
// However the stream ended, there is no longer anything to cancel
downloadInFlight = false;
const cancelBtn = document.getElementById('cancelBtn');
cancelBtn.disabled = false;
cancelBtn.textContent = "Cancel";
updateCancelVisibility();
// Ensure Advanced Options visibility matches chevron state
const advancedContent = document.getElementById('advancedContent');
const chevron = document.querySelector('.advanced-header .chevron');
if (chevron.textContent === '▲') {
advancedContent.classList.remove('hidden');
}
// Restore button text based on mode
document.getElementById('downloadBtn').textContent = currentMode === 'stream' ? 'Stream' : 'Download';
}
// --- Streaming Functions ---
async function startStream(url) {
const streamModal = document.getElementById('streamModal');
const streamTitle = document.getElementById('streamTitle');
const streamPlayer = document.getElementById('streamPlayer');
const streamStatus = document.getElementById('streamStatus');
const downloadBtn = document.getElementById('downloadBtn');
// Show modal immediately with loading state
streamModal.classList.remove('hidden');
streamTitle.textContent = 'Loading...';
streamStatus.textContent = '🦭 Your seal is fetching the stream...';
streamStatus.className = 'stream-status loading';
streamPlayer.src = '';
downloadBtn.disabled = true;
downloadBtn.textContent = 'Streaming...';
try {
const response = await fetch('/api/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: url })
});
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
// Set video source and title
streamTitle.textContent = data.title || 'Video';
streamPlayer.src = data.stream_url;
streamStatus.textContent = '';
streamStatus.className = 'stream-status';
// Handle video errors
streamPlayer.onerror = () => {
streamStatus.textContent = '❌ Playback error. Try a different video or download instead.';
streamStatus.className = 'stream-status error';
};
// Reset button when video starts
streamPlayer.onplay = () => {
downloadBtn.disabled = false;
downloadBtn.textContent = 'Stream';
};
} catch (e) {
console.error('Stream error:', e);
recordError(e.message);
streamTitle.textContent = 'Stream Error';
streamStatus.textContent = `❌ ${e.message}`;
streamStatus.className = 'stream-status error';
downloadBtn.disabled = false;
downloadBtn.textContent = 'Stream';
}
}
function closeStream() {
const streamModal = document.getElementById('streamModal');
const streamPlayer = document.getElementById('streamPlayer');
// Stop and clear video
streamPlayer.pause();
streamPlayer.src = '';
// Hide modal
streamModal.classList.add('hidden');
// Reset button
document.getElementById('downloadBtn').disabled = false;
document.getElementById('downloadBtn').textContent = 'Stream';
}
// --- Settings Modal & Auto-Update Functions ---
let pendingUpdate = null;
let selectedRelease = null;
let currentChannel = 'stable';
function toggleSettings() {
const modal = document.getElementById('settingsModal');
const isHidden = modal.classList.contains('hidden');
if (isHidden) {
modal.classList.remove('hidden');
// Load releases for the current tab
fetchReleases(currentChannel);
loadDownloadSettings();
} else {
modal.classList.add('hidden');
}
}
// Top-level Updates/Downloads sections. Kept separate from switchUpdateTab
// because that one writes the channel preference to disk as a side effect.
function switchSettingsSection(section) {
document.querySelectorAll('.settings-tab[data-section]').forEach(tab => {
tab.classList.toggle('active', tab.dataset.section === section);
});
document.getElementById('settingsSectionUpdates').classList.toggle('hidden', section !== 'updates');
document.getElementById('settingsSectionDownloads').classList.toggle('hidden', section !== 'downloads');
}
function switchUpdateTab(channel) {
currentChannel = channel;
// Match on data-channel, not the bare .settings-tab class — the top-level
// section tabs share that class and would be deactivated here
document.querySelectorAll('.settings-tab[data-channel]').forEach(tab => {
tab.classList.toggle('active', tab.dataset.channel === channel);
});
// Save channel preference
saveUpdateSettings();
// Fetch releases for this channel
fetchReleases(channel);
}
// Release rows are built with textContent, never innerHTML — versions, branch
// names and error strings all arrive over the network
function showReleasesMessage(listEl, message) {
listEl.innerHTML = '';
const messageEl = document.createElement('div');
messageEl.className = 'releases-loading';
messageEl.textContent = message;
listEl.appendChild(messageEl);
}
// Why a release cannot be installed from in here, or null when it can be.
//
// is_installer is false only for the bare-exe builds up to 1.2.4: running one
// of those would launch the old version out of the updates folder and change
// nothing, so apply_update refuses it — after the whole download. The row has
// to say so first.
//
// Both channels supply the key: releases get it from _is_installer_name reading
// the asset name, alpha builds from the artifact name (see update_artifacts).
function releaseBlockedReason(release) {
if (!release.exe_asset) return 'No download attached to this release.';
if (release.exe_asset.is_installer === false) {
return 'Predates the FinFetcher installer, so it cannot replace an installed copy. Install it from GitHub instead.';
}
return null;
}
// "Last checked 3:41 PM" under the tabs — the answer to "is this list
// current?", which is the question the refresh button exists for
function renderCheckedAt(iso) {
const el = document.getElementById('releasesCheckedAt');
if (!el) return;
if (!iso) { el.textContent = ''; return; }
const when = new Date(iso);
el.textContent = isNaN(when) ? '' :
`Last checked ${when.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}`;
}
function buildReleaseRow(label, badges, dateText, note) {
const row = document.createElement('div');
row.className = 'release-row';
const info = document.createElement('div');
info.className = 'release-info';
const versionEl = document.createElement('span');
versionEl.className = 'release-version';
versionEl.textContent = label;
info.appendChild(versionEl);
badges.forEach(badge => {
const badgeEl = document.createElement('span');
badgeEl.className = `release-badge ${badge.className}`;
badgeEl.textContent = badge.text;
info.appendChild(badgeEl);
});
const dateEl = document.createElement('span');
dateEl.className = 'release-date';
dateEl.textContent = dateText;