-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplayer.js
More file actions
1606 lines (1417 loc) · 61.8 KB
/
Copy pathplayer.js
File metadata and controls
1606 lines (1417 loc) · 61.8 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
/**
* Archive Film Club - Dedicated Player Page v2.0
* Immersive video player with rich playlist, quality selector, theater mode
*/
import { VideoService } from './src/js/services/VideoService.js';
import { PlaylistService } from './src/js/services/PlaylistService.js';
import { VideoProgressTracker } from './src/js/services/VideoProgressTracker.js';
import { BookmarkManager } from './src/js/services/BookmarkManager.js';
import { Toast } from './src/js/components/Toast.js';
import { AuthNav } from './src/js/components/AuthNav.js';
import { CollectionPicker } from './src/js/components/CollectionPicker.js';
import { PlayerUI } from './src/js/player/PlayerUI.js';
import { PlayerPlaylist } from './src/js/player/PlayerPlaylist.js';
import { PlayerComments } from './src/js/player/PlayerComments.js';
// Mount auth nav early
AuthNav.mount();
import {
escapeHtml,
sanitizeHtml,
extractValue,
formatRuntime,
formatTime,
formatFileSize
} from './src/js/utils/helpers.js';
class VideoPlayer {
constructor() {
this.videoService = new VideoService();
this.playlistService = new PlaylistService(this.videoService);
this.progressTracker = new VideoProgressTracker();
this.bookmarkManager = new BookmarkManager();
this.toast = new Toast();
this.ui = new PlayerUI();
this.playlist = new PlayerPlaylist(this.videoService, this.playlistService);
this.comments = new PlayerComments({ toast: this.toast });
const commentsEl = document.getElementById('commentsSection');
if (commentsEl) this.comments.mount(commentsEl);
this.siteSettings = this.loadSiteSettings();
this.videoId = null;
this.trackIndex = null;
this.metadata = null;
this.videoFiles = [];
this.allVideoFiles = []; // All files including quality variants
this.currentFileName = null;
this.descriptionExpanded = true;
// Tracks playlist indices that have failed to play in this session,
// so cascading auto-skip never re-tries a known-bad item.
this.failedPlaylistIndices = new Set();
// True once the CURRENT source has reached a playable state (canplay /
// playing). Reset on every (re)load. Drives two behaviours:
// 1. the mid-playback buffering spinner only appears after this is
// true, so it never stacks on the browser's own first-frame
// spinner (half of the "double spinner" bug);
// 2. the <video> error handler only auto-skips / falls back when a
// source FAILED TO LOAD (never became playable). A transient error
// while seeking an already-playing video must NOT skip the episode.
this._sourceCanPlay = false;
this.initElements();
this.setupEventListeners();
this.parseUrlAndLoad();
}
loadSiteSettings() {
const el = document.getElementById('siteSettingsConfig');
if (el) {
try { return JSON.parse(el.textContent); } catch (e) {}
}
return {};
}
initElements() {
this.videoWrapper = document.getElementById('videoWrapper');
this.playerLoader = document.getElementById('playerLoader');
this.videoTitle = document.getElementById('videoTitle');
this.videoCreator = document.getElementById('videoCreator');
this.videoDate = document.getElementById('videoDate');
this.videoMetaPills = document.getElementById('videoMetaPills');
this.videoTagsRow = document.getElementById('videoTagsRow');
this.archiveLink = document.getElementById('archiveLink');
this.descriptionSection = document.getElementById('descriptionSection');
this.descriptionToggle = document.getElementById('descriptionToggle');
this.descriptionContent = document.getElementById('descriptionContent');
this.downloadsPanel = document.getElementById('downloadsPanel');
this.downloadLinks = document.getElementById('downloadLinks');
this.shareBtn = document.getElementById('shareBtn');
this.bookmarkBtn = document.getElementById('bookmarkBtn');
this.saveToCollectionBtn = document.getElementById('saveToCollectionBtn');
this.downloadBtn = document.getElementById('downloadBtn');
this.reportBtn = document.getElementById('reportBtn');
this.closeDownloads = document.getElementById('closeDownloads');
this.upNextOverlay = document.getElementById('upNextOverlay');
this.upNextThumb = document.getElementById('upNextThumb');
if (this.upNextThumb) {
this.upNextThumb.addEventListener('error', () => {
this.upNextThumb.hidden = true;
});
this.upNextThumb.addEventListener('load', () => {
this.upNextThumb.hidden = false;
});
}
this.upNextTitle = document.getElementById('upNextTitle');
this.upNextCountdown = document.getElementById('upNextCountdown');
this.upNextPlay = document.getElementById('upNextPlay');
this.upNextCancel = document.getElementById('upNextCancel');
this.playerCinema = document.getElementById('playerCinema');
this.bufferingIndicator = document.getElementById('bufferingIndicator');
this.pipBtn = document.getElementById('pipBtn');
this.captionsBtn = document.getElementById('captionsBtn');
this.speedBtn = document.getElementById('speedBtn');
this.speedMenu = document.getElementById('speedMenu');
this.speedLabel = document.getElementById('speedLabel');
this.shortcutsHelp = document.getElementById('shortcutsHelp');
this.shortcutsHelpClose = document.getElementById('shortcutsHelpClose');
this._upNextTimer = null;
this.playbackRate = this._loadStoredNumber('playerPlaybackRate', 1);
this.preferredQualityLabel = this._loadStoredString('playerQualityLabel', null);
this.captionsEnabled = this._loadStoredString('playerCaptionsOn', '') === '1';
}
_loadStoredNumber(key, fallback) {
try {
const n = parseFloat(localStorage.getItem(key));
return Number.isFinite(n) && n > 0 ? n : fallback;
} catch (e) { return fallback; }
}
_loadStoredString(key, fallback) {
try {
const s = localStorage.getItem(key);
return s || fallback;
} catch (e) { return fallback; }
}
setupEventListeners() {
// Share
if (this.shareBtn) this.shareBtn.addEventListener('click', () => this.shareVideo());
// Report (links out to archive.org — we host no content)
if (this.reportBtn) this.reportBtn.addEventListener('click', () => this.openReportDialog());
// Bookmark
if (this.bookmarkBtn) this.bookmarkBtn.addEventListener('click', () => this.toggleBookmark());
// Save to collection
if (this.saveToCollectionBtn) {
this.saveToCollectionBtn.addEventListener('click', () => this.openCollectionPicker());
}
// Downloads
if (this.downloadBtn) this.downloadBtn.addEventListener('click', () => this.toggleDownloads());
if (this.closeDownloads) this.closeDownloads.addEventListener('click', () => this.hideDownloads());
// Description
if (this.descriptionToggle) this.descriptionToggle.addEventListener('click', () => this.toggleDescription());
// Keyboard
document.addEventListener('keydown', (e) => this.handleKeyboard(e));
// Popstate
window.addEventListener('popstate', () => this.parseUrlAndLoad());
// Episode navigation buttons
if (this.ui.prevEpisodeBtn) {
this.ui.prevEpisodeBtn.addEventListener('click', () => this.playPreviousEpisode());
}
if (this.ui.nextEpisodeBtn) {
this.ui.nextEpisodeBtn.addEventListener('click', () => this.playNextEpisode());
}
if (this.ui.sidebarPrevBtn) {
this.ui.sidebarPrevBtn.addEventListener('click', () => this.playPreviousEpisode());
}
if (this.ui.sidebarNextBtn) {
this.ui.sidebarNextBtn.addEventListener('click', () => this.playNextEpisode());
}
// Up Next overlay
if (this.upNextPlay) this.upNextPlay.addEventListener('click', () => this.confirmUpNext());
if (this.upNextCancel) this.upNextCancel.addEventListener('click', () => this.cancelUpNext());
// Mirror fullscreen state on the page so CSS can adapt the layout.
// Triggered by the native <video> fullscreen button or the `f` keyboard shortcut.
document.addEventListener('fullscreenchange', () => this._syncFullscreenState());
document.addEventListener('webkitfullscreenchange', () => this._syncFullscreenState());
// Playback speed menu
if (this.speedBtn) {
this.speedBtn.addEventListener('click', (e) => {
e.stopPropagation();
this._toggleSpeedMenu();
});
}
if (this.speedMenu) {
this.speedMenu.addEventListener('click', (e) => e.stopPropagation());
}
document.addEventListener('click', () => this._closeSpeedMenu());
// Picture-in-picture
if (this.pipBtn) {
this.pipBtn.addEventListener('click', () => this.togglePictureInPicture());
}
// Captions toggle
if (this.captionsBtn) {
this.captionsBtn.addEventListener('click', () => this.toggleCaptions());
}
// Keyboard shortcuts help overlay
if (this.shortcutsHelpClose) {
this.shortcutsHelpClose.addEventListener('click', () => this._hideShortcutsHelp());
}
if (this.shortcutsHelp) {
this.shortcutsHelp.addEventListener('click', (e) => {
if (e.target === this.shortcutsHelp) this._hideShortcutsHelp();
});
}
}
/**
* Fullscreen target is the cinema container, NOT the bare <video>:
* - keeps the Up Next overlay + shortcut indicator visible across episodes
* - keeps fullscreen alive when the playlist auto-advances, because
* VideoService now reuses the <video> element instead of replacing
* the wrapper's innerHTML.
*/
toggleFullscreen() {
const target = this.playerCinema || this.videoWrapper;
if (!target) return;
const fsEl = document.fullscreenElement || document.webkitFullscreenElement;
if (fsEl) {
const exit = document.exitFullscreen || document.webkitExitFullscreen;
if (exit) exit.call(document);
return;
}
const req = target.requestFullscreen || target.webkitRequestFullscreen;
if (!req) return;
const result = req.call(target);
if (result && typeof result.catch === 'function') {
result.catch(err => {
console.warn('[player] fullscreen request rejected:', err && err.message);
});
}
}
_syncFullscreenState() {
const fs = document.fullscreenElement || document.webkitFullscreenElement;
document.body.classList.toggle('player-is-fullscreen', !!fs);
// If the user entered fullscreen via the <video>'s native button
// (common on mobile/touch), fullscreen lives on the bare <video> and
// NOT on the cinema container. That breaks two things:
// 1) The Up Next overlay + shortcut indicator are siblings of the
// video, so they're invisible in fullscreen.
// 2) Swapping the <source> for the next episode forces the browser
// to drop fullscreen, so auto-advance kicks the user back out.
// Promote fullscreen to the cinema container — browsers allow
// re-requesting fullscreen on a different element while already in
// fullscreen, and the transition is seamless.
if (fs && this.playerCinema && fs !== this.playerCinema) {
this._promoteFullscreenToCinema();
}
}
// ========================================
// Picture-in-Picture
// ========================================
_currentVideoMeta() {
const meta = this.metadata && (this.metadata.metadata || this.metadata);
if (!meta) return null;
return {
title: extractValue(meta.title) || null,
creator: extractValue(meta.creator) || null,
};
}
async togglePictureInPicture() {
const video = this.videoWrapper?.querySelector('video');
if (!video || !document.pictureInPictureEnabled || video.disablePictureInPicture) {
this.toast.show('Picture-in-picture is not available', 'info');
return;
}
try {
if (document.pictureInPictureElement) {
await document.exitPictureInPicture();
} else {
await video.requestPictureInPicture();
}
} catch (e) {
console.warn('[player] PiP toggle failed:', e?.message);
}
}
// ========================================
// Captions / Subtitles
// ========================================
toggleCaptions() {
const video = this.videoWrapper?.querySelector('video');
if (!video || !video.textTracks || video.textTracks.length === 0) {
this.toast.show('No captions available for this video', 'info');
return;
}
this.captionsEnabled = !this.captionsEnabled;
try { localStorage.setItem('playerCaptionsOn', this.captionsEnabled ? '1' : '0'); } catch (e) {}
this._applyCaptionState(video);
this.ui.showShortcutIndicator(this.captionsEnabled ? 'Captions on' : 'Captions off');
}
/**
* Apply the persisted captions preference to whatever text tracks are
* currently mounted on the <video>. Called on every (re)attach so a
* fresh element after navigation respects the user's last choice.
*/
_applyCaptionState(videoEl) {
if (!videoEl || !videoEl.textTracks) return;
const tracks = videoEl.textTracks;
const hasAny = tracks.length > 0;
if (this.captionsBtn) {
this.captionsBtn.style.display = hasAny ? '' : 'none';
this.captionsBtn.classList.toggle('active', !!this.captionsEnabled && hasAny);
this.captionsBtn.setAttribute('aria-pressed', String(!!this.captionsEnabled && hasAny));
}
if (!hasAny) return;
// Prefer English when available, otherwise the first track.
let chosen = 0;
for (let i = 0; i < tracks.length; i++) {
const lang = (tracks[i].language || '').toLowerCase();
if (lang.startsWith('en')) { chosen = i; break; }
}
for (let i = 0; i < tracks.length; i++) {
tracks[i].mode = (this.captionsEnabled && i === chosen) ? 'showing' : 'disabled';
}
}
// ========================================
// Playback Speed
// ========================================
_applyPlaybackRate(videoEl) {
if (!videoEl) return;
try { videoEl.playbackRate = this.playbackRate || 1; } catch (e) {}
if (this.speedLabel) {
this.speedLabel.textContent = this._formatRateLabel(this.playbackRate || 1);
}
}
_formatRateLabel(rate) {
if (Math.abs(rate - 1) < 0.001) return '1x';
// Trim trailing zeros: 1.25x, 1.5x, 0.75x
return `${parseFloat(rate.toFixed(2))}x`;
}
setPlaybackRate(rate) {
this.playbackRate = rate;
try { localStorage.setItem('playerPlaybackRate', String(rate)); } catch (e) {}
const video = this.videoWrapper?.querySelector('video');
this._applyPlaybackRate(video);
this.ui.showShortcutIndicator(`Speed ${this._formatRateLabel(rate)}`);
this._renderSpeedMenu();
}
_toggleSpeedMenu() {
if (!this.speedMenu) return;
const opening = !this.speedMenu.classList.contains('open');
if (opening) this._renderSpeedMenu();
this.speedMenu.classList.toggle('open', opening);
}
_closeSpeedMenu() {
if (this.speedMenu) this.speedMenu.classList.remove('open');
}
_renderSpeedMenu() {
if (!this.speedMenu) return;
const steps = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
this.speedMenu.innerHTML = steps.map(s => {
const active = Math.abs(s - this.playbackRate) < 0.001;
const label = s === 1 ? 'Normal' : this._formatRateLabel(s);
return `<button class="quality-option ${active ? 'active' : ''}" data-rate="${s}">
<span>${label}</span>
</button>`;
}).join('');
this.speedMenu.querySelectorAll('[data-rate]').forEach(btn => {
btn.addEventListener('click', () => {
this._closeSpeedMenu();
this.setPlaybackRate(parseFloat(btn.dataset.rate));
});
});
}
// ========================================
// Buffering Indicator (mid-playback only)
// ========================================
_showBuffering() {
if (!this.bufferingIndicator) return;
// The big initial-load / switching loader owns the cinema — never stack
// the buffering spinner on top of it (this was the "double spinner" bug:
// both elements render the identical .loading-spinner markup).
if (this.playerLoader && this.playerLoader.style.display !== 'none') return;
// Suppress until the current source is actually playable, so this
// mid-playback spinner never overlaps the browser's own spinner drawn
// on the <video> while it buffers the very first frames.
if (!this._sourceCanPlay) return;
this.bufferingIndicator.classList.add('visible');
}
_hideBuffering() {
if (this.bufferingIndicator) this.bufferingIndicator.classList.remove('visible');
}
// ========================================
// Keyboard Shortcuts Help
// ========================================
_toggleShortcutsHelp() {
if (!this.shortcutsHelp) return;
if (this.shortcutsHelp.hidden) this._showShortcutsHelp();
else this._hideShortcutsHelp();
}
_showShortcutsHelp() {
if (!this.shortcutsHelp) return;
this.shortcutsHelp.hidden = false;
requestAnimationFrame(() => this.shortcutsHelp.classList.add('visible'));
}
_hideShortcutsHelp() {
if (!this.shortcutsHelp) return;
this.shortcutsHelp.classList.remove('visible');
setTimeout(() => { if (this.shortcutsHelp) this.shortcutsHelp.hidden = true; }, 180);
}
_promoteFullscreenToCinema() {
if (this._promotingFullscreen) return;
const target = this.playerCinema;
if (!target) return;
const req = target.requestFullscreen || target.webkitRequestFullscreen;
if (!req) return;
this._promotingFullscreen = true;
try {
const result = req.call(target);
if (result && typeof result.then === 'function') {
result.finally(() => { this._promotingFullscreen = false; });
} else {
this._promotingFullscreen = false;
}
} catch (e) {
this._promotingFullscreen = false;
}
}
// ========================================
// Keyboard Shortcuts
// ========================================
handleKeyboard(e) {
// Global shortcuts that should fire regardless of focus target.
if (e.key === 'Escape' && this.shortcutsHelp && !this.shortcutsHelp.hidden) {
e.preventDefault();
this._hideShortcutsHelp();
return;
}
if (e.key === '?') {
// Only intercept when not typing into a text input.
const tag = e.target.tagName;
if (tag !== 'INPUT' && tag !== 'TEXTAREA') {
e.preventDefault();
this._toggleShortcutsHelp();
return;
}
}
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'BUTTON') return;
const video = this.videoWrapper?.querySelector('video');
switch (e.key) {
case ' ':
case 'k':
if (!video) return;
e.preventDefault();
if (video.paused) {
video.play();
this.ui.showShortcutIndicator('Play', '<svg width="28" height="28" viewBox="0 0 24 24" fill="white"><path d="M5 3L19 12L5 21V3Z"/></svg>');
} else {
video.pause();
this.ui.showShortcutIndicator('Pause', '<svg width="28" height="28" viewBox="0 0 24 24" fill="white"><path d="M6 4H10V20H6V4ZM14 4H18V20H14V4Z"/></svg>');
}
break;
case 'f':
e.preventDefault();
this.toggleFullscreen();
break;
case 'm':
if (!video) return;
e.preventDefault();
video.muted = !video.muted;
this.ui.showShortcutIndicator(video.muted ? 'Muted' : 'Unmuted');
break;
case 't':
e.preventDefault();
this.ui.toggleTheaterMode();
break;
case 'ArrowLeft':
if (!video) return;
e.preventDefault();
this._seekBy(video, -5);
this.ui.showShortcutIndicator('-5s');
break;
case 'ArrowRight':
if (!video) return;
e.preventDefault();
this._seekBy(video, 5);
this.ui.showShortcutIndicator('+5s');
break;
case 'ArrowUp':
if (!video) return;
e.preventDefault();
video.volume = Math.min(1, video.volume + 0.1);
this.ui.showShortcutIndicator(`Volume ${Math.round(video.volume * 100)}%`);
break;
case 'ArrowDown':
if (!video) return;
e.preventDefault();
video.volume = Math.max(0, video.volume - 0.1);
this.ui.showShortcutIndicator(`Volume ${Math.round(video.volume * 100)}%`);
break;
case 'j':
if (!video) return;
e.preventDefault();
this._seekBy(video, -10);
this.ui.showShortcutIndicator('-10s');
break;
case 'l':
if (!video) return;
e.preventDefault();
this._seekBy(video, 10);
this.ui.showShortcutIndicator('+10s');
break;
case 'N':
if (e.shiftKey) {
e.preventDefault();
this.playNextEpisode();
}
break;
case 'P':
if (e.shiftKey) {
e.preventDefault();
this.playPreviousEpisode();
}
break;
case 'i':
e.preventDefault();
this.togglePictureInPicture();
break;
case 'c':
e.preventDefault();
this.toggleCaptions();
break;
case '>':
case '.':
if (!video) return;
if (e.key === '>' || e.shiftKey) {
e.preventDefault();
this._bumpPlaybackRate(+1);
}
break;
case '<':
case ',':
if (!video) return;
if (e.key === '<' || e.shiftKey) {
e.preventDefault();
this._bumpPlaybackRate(-1);
}
break;
}
}
/**
* Seek relative to the current position, in seconds (negative rewinds).
* Before metadata loads, `video.duration` is NaN — clamping to it would
* snap the video to 0, so an unknown duration is treated as "no upper
* bound" and the browser clamps to the seekable range itself.
*/
_seekBy(video, deltaSeconds) {
if (!video) return;
const upper = Number.isFinite(video.duration) ? video.duration : Infinity;
const target = (video.currentTime || 0) + deltaSeconds;
video.currentTime = Math.max(0, Math.min(upper, target));
}
_bumpPlaybackRate(direction) {
const steps = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
const currentIdx = steps.findIndex(s => Math.abs(s - this.playbackRate) < 0.001);
const safeIdx = currentIdx === -1 ? steps.indexOf(1) : currentIdx;
const nextIdx = Math.max(0, Math.min(steps.length - 1, safeIdx + direction));
this.setPlaybackRate(steps[nextIdx]);
}
// ========================================
// URL Parsing & Loading
// ========================================
parseUrlAndLoad() {
const params = new URLSearchParams(window.location.search);
// Sanitize to the same charset the server enforces (sanitizeArchiveId:
// [a-zA-Z0-9_.-]). The raw param is interpolated into innerHTML in a few
// places (download links, playlist thumbnails), so stripping HTML-meta
// characters here closes reflected-XSS via a crafted ?video= link. A
// "dirty" id would never resolve against archive.org anyway.
const videoId = (params.get('video') || '').replace(/[^a-zA-Z0-9_.\-]/g, '');
const track = params.get('track') ? parseInt(params.get('track'), 10) - 1 : null;
const timestamp = params.get('t') ? parseInt(params.get('t'), 10) : null;
if (!videoId) {
this.showError('No video specified. <a href="index.php">Browse videos</a>');
return;
}
this.videoId = videoId;
this.trackIndex = track;
this.requestedTimestamp = timestamp;
this.loadVideo();
}
async loadVideo() {
this.showLoader();
this.failedPlaylistIndices = new Set();
try {
const metadata = await this.videoService.getVideoMetadata(this.videoId);
this.metadata = metadata;
const meta = metadata.metadata || metadata;
this.updateVideoInfo(meta);
// Kick off comments load in the background — never blocks playback.
if (this.comments && this.videoId) {
this.comments.load(this.videoId).catch(() => {});
}
// Pre-compute the playable + deduplicated file list BEFORE we kick
// off playback, so multi-episode items load the requested track
// (or episode 1) instead of whatever the global "best quality"
// heuristic happens to pick.
const allFiles = this.videoService.getVideoFiles(
metadata.metadata ? metadata : { metadata, files: metadata.files }
);
const deduplicatedFiles = this.videoService.deduplicateVideoFiles(allFiles);
const isMultiEpisode = deduplicatedFiles.length > 1
&& this.videoService.hasMultipleUniqueVideos(deduplicatedFiles);
let initialFile = null;
let startIndex = 0;
if (isMultiEpisode) {
startIndex = (this.trackIndex !== null
&& this.trackIndex >= 0
&& this.trackIndex < deduplicatedFiles.length)
? this.trackIndex : 0;
initialFile = deduplicatedFiles[startIndex]?.name || null;
} else if (this.preferredQualityLabel) {
// Single-video case: honor the user's last picked quality so they
// don't have to re-select 1080p on every new video.
const ranked = allFiles.filter(f => (f.name || '').toLowerCase().endsWith('.mp4'));
const match = ranked.find(f => this.ui.getQualityLabel(f.name) === this.preferredQualityLabel);
if (match) initialFile = match.name;
}
// Load and play
const videoData = await this.videoService.loadNativeVideo(
this.videoId,
metadata,
this.videoWrapper,
initialFile,
this.getSavedVolume()
);
this.hideLoader();
this.currentFileName = videoData.selectedFile?.name;
this.setupVideoListeners(videoData.videoElement);
// Non-blocking resume
const progress = this.progressTracker.getProgress(this.videoId);
if (progress && videoData.videoElement && !this.requestedTimestamp) {
const timeStr = formatTime(progress.currentTime);
this.ui.showResumePrompt(timeStr, () => {
videoData.videoElement.currentTime = progress.currentTime;
});
}
// Apply requested timestamp
if (this.requestedTimestamp && videoData.videoElement) {
setTimeout(() => {
videoData.videoElement.currentTime = this.requestedTimestamp;
}, 300);
}
this.videoFiles = deduplicatedFiles;
this.allVideoFiles = videoData.videoFiles;
if (isMultiEpisode) {
this.setupPlaylist(meta, deduplicatedFiles, startIndex);
} else {
// Single video — make sure no playlist from a previous load lingers
// in the service, or the failed-to-load auto-skip would try to
// "advance to the next episode" of an item we're no longer playing.
this.playlistService.clearPlaylist();
}
// Quality selector for non-playlist single videos
if (!this.playlist.isVisible()) {
this.ui.buildQualityOptions(videoData.videoFiles, this.currentFileName, (filename) => {
this.switchQuality(filename);
});
}
// Downloads
this.buildDownloadLinks(deduplicatedFiles.length > 0 ? deduplicatedFiles : videoData.videoFiles);
// Bookmark state
this.updateBookmarkState();
} catch (err) {
console.warn('Native load failed, trying iframe:', err.message);
try {
this.videoService.loadIframeVideo(this.videoId, this.videoWrapper);
this.hideLoader();
if (this.metadata) {
const meta = this.metadata.metadata || this.metadata;
this.updateVideoInfo(meta);
}
} catch (iframeErr) {
this.showError('Failed to load video. <a href="index.php">Browse videos</a>');
}
}
}
// ========================================
// Video Info
// ========================================
updateVideoInfo(meta) {
const title = extractValue(meta.title) || this.videoId;
const creator = extractValue(meta.creator) || '';
const date = extractValue(meta.date) || '';
const description = extractValue(meta.description) || '';
document.title = `${title} - ${this.siteSettings.siteName || 'Archive Film Club'}`;
if (this.videoTitle) this.videoTitle.textContent = title;
if (this.videoCreator && creator) {
this.videoCreator.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="8" r="4" stroke="currentColor" stroke-width="2"/><path d="M4 20C4 16.6863 7.58172 14 12 14C16.4183 14 20 16.6863 20 20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg> ${escapeHtml(creator)}`;
}
if (this.videoDate && date) {
const formatted = new Date(date).toLocaleDateString();
this.videoDate.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><rect x="3" y="4" width="18" height="18" rx="2" stroke="currentColor" stroke-width="2"/><path d="M16 2V6M8 2V6M3 10H21" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg> ${formatted}`;
}
if (this.archiveLink) {
this.archiveLink.href = `https://archive.org/details/${this.videoId}`;
}
this._renderMetaPills(meta);
this._renderTags(meta);
if (description && description.length > 10) {
if (this.descriptionSection) this.descriptionSection.style.display = 'block';
if (this.descriptionContent) {
this.descriptionContent.innerHTML = sanitizeHtml(description);
this.descriptionContent.classList.add('expanded');
}
if (this.descriptionToggle) this.descriptionToggle.classList.add('expanded');
}
}
/**
* Render metadata pills (year, runtime, language, mediatype, license, downloads, rating).
* Pulls from Archive.org's metadata blob, which is loose JSON — every field
* may be a string or array, hence the extractValue helper.
*/
_renderMetaPills(meta) {
if (!this.videoMetaPills) return;
const pills = [];
const date = extractValue(meta.date) || '';
if (date) {
const year = String(date).slice(0, 4);
if (/^\d{4}$/.test(year)) pills.push({ icon: 'calendar', text: year });
}
const runtime = formatRuntime(extractValue(meta.runtime));
if (runtime) pills.push({ icon: 'clock', text: runtime });
const language = extractValue(meta.language);
if (language) pills.push({ icon: 'globe', text: this._titleCase(String(language)) });
const mediatype = extractValue(meta.mediatype);
if (mediatype && mediatype !== 'movies') {
pills.push({ icon: 'media', text: this._titleCase(String(mediatype)) });
}
const downloads = parseInt(extractValue(meta.downloads), 10);
if (!isNaN(downloads) && downloads > 0) {
pills.push({ icon: 'download', text: `${this._formatCount(downloads)} downloads` });
}
const reviews = parseInt(extractValue(meta.num_reviews), 10);
const avg = parseFloat(extractValue(meta.avg_rating));
if (!isNaN(avg) && avg > 0) {
const ratingText = !isNaN(reviews) && reviews > 0
? `${avg.toFixed(1)} (${reviews})`
: avg.toFixed(1);
pills.push({ icon: 'star', text: ratingText, tone: 'star' });
}
const license = String(extractValue(meta.licenseurl) || '').toLowerCase();
if (license.includes('publicdomain')) {
pills.push({ icon: 'shield', text: 'Public Domain', tone: 'success' });
} else if (license.includes('creativecommons')) {
pills.push({ icon: 'shield', text: 'Creative Commons', tone: 'accent' });
}
if (!pills.length) {
this.videoMetaPills.innerHTML = '';
this.videoMetaPills.style.display = 'none';
return;
}
const icons = {
calendar: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>',
clock: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',
globe: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 0 20a15.3 15.3 0 0 1 0-20z"/></svg>',
media: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="14" rx="2"/><path d="M22 8 16 12 22 16"/></svg>',
download: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>',
star: '<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="1" stroke-linejoin="round"><polygon points="12 2 15.1 8.6 22 9.6 17 14.4 18.2 21.3 12 18 5.8 21.3 7 14.4 2 9.6 8.9 8.6 12 2"/></svg>',
shield: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>',
};
this.videoMetaPills.style.display = 'flex';
this.videoMetaPills.innerHTML = pills.map(p =>
`<span class="player-meta-pill ${p.tone ? 'tone-' + p.tone : ''}">
${icons[p.icon] || ''}
<span>${escapeHtml(p.text)}</span>
</span>`
).join('');
}
/**
* Render up to 8 subject/topic tags as pills.
*/
_renderTags(meta) {
if (!this.videoTagsRow) return;
const subjects = meta.subject;
if (!subjects) {
this.videoTagsRow.innerHTML = '';
this.videoTagsRow.style.display = 'none';
return;
}
const list = Array.isArray(subjects)
? subjects
: String(subjects).split(/[;,]+/).map(s => s.trim()).filter(Boolean);
const seen = new Set();
const dedup = [];
for (const t of list) {
const k = t.toLowerCase();
if (k && !seen.has(k)) { seen.add(k); dedup.push(t); }
if (dedup.length >= 8) break;
}
if (!dedup.length) {
this.videoTagsRow.innerHTML = '';
this.videoTagsRow.style.display = 'none';
return;
}
this.videoTagsRow.style.display = 'flex';
this.videoTagsRow.innerHTML =
'<span class="player-tags-label">Topics</span>' +
dedup.map(t =>
`<a class="player-tag" href="index.php?q=${encodeURIComponent(t)}" title="Search ${escapeHtml(t)}">#${escapeHtml(t)}</a>`
).join('');
}
_formatCount(n) {
if (n >= 1_000_000) return (n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1) + 'M';
if (n >= 1000) return (n / 1000).toFixed(n >= 10_000 ? 0 : 1) + 'K';
return String(n);
}
_titleCase(s) {
if (!s) return '';
return s.charAt(0).toUpperCase() + s.slice(1);
}
// ========================================
// Video Event Listeners
// ========================================
setupVideoListeners(videoEl) {
if (!videoEl) return;
// Always re-apply the persisted playback rate when (re)attaching to a
// <video>. The element is reused across episode changes, so the rate
// survives — but a fresh page load needs to restore it from storage.
this._applyPlaybackRate(videoEl);
this._applyCaptionState(videoEl);
// Show / hide the PiP button based on browser support, evaluated per
// element to handle cross-origin or capability changes.
if (this.pipBtn) {
this.pipBtn.style.display = (document.pictureInPictureEnabled && !videoEl.disablePictureInPicture) ? '' : 'none';
}
// Reusing the <video> element across track changes means this gets
// called multiple times against the same node. Bail early on the
// second+ call so we don't stack pause/ended/volume listeners.
if (videoEl.dataset.afcListenersAttached === '1') return;
videoEl.dataset.afcListenersAttached = '1';
// Click-to-toggle-play. Native <video controls> doesn't do this on
// desktop, but every user trained on YouTube expects it. Filter out
// clicks on the native controls bar (bottom ~40px) so we don't
// intercept the user's seek/volume drags.
videoEl.addEventListener('click', (e) => {
const rect = videoEl.getBoundingClientRect();
const distFromBottom = rect.bottom - e.clientY;
if (distFromBottom < 50) return; // native controls area
if (videoEl.paused) {
videoEl.play().catch(() => {});
} else {
videoEl.pause();
}
});
// Double-click anywhere on the video toggles fullscreen.
videoEl.addEventListener('dblclick', (e) => {
const rect = videoEl.getBoundingClientRect();
const distFromBottom = rect.bottom - e.clientY;
if (distFromBottom < 50) return;
e.preventDefault();
this.toggleFullscreen();
});
// Buffering indicator — mid-playback stalls only. The initial-load
// spinner is handled separately by showLoader/hideLoader.
videoEl.addEventListener('waiting', () => this._showBuffering());
videoEl.addEventListener('stalled', () => this._showBuffering());
videoEl.addEventListener('playing', () => { this._sourceCanPlay = true; this._hideBuffering(); });
videoEl.addEventListener('canplay', () => { this._sourceCanPlay = true; this._hideBuffering(); });
videoEl.addEventListener('pause', () => this._hideBuffering());
// Reapply rate after any internal reset (some browsers reset rate on
// src change despite element reuse). Caption tracks are attached
// synchronously by VideoService but the textTracks list isn't fully
// populated until the browser has parsed the <track> elements, so
// re-sync captions on metadata load too.
videoEl.addEventListener('loadedmetadata', () => {
this._applyPlaybackRate(videoEl);
this._applyCaptionState(videoEl);
});
videoEl.addEventListener('pause', () => {
if (this.videoId && videoEl.currentTime && videoEl.duration) {
this.progressTracker.saveProgress(this.videoId, videoEl.currentTime, videoEl.duration, this._currentVideoMeta());
const idx = this.playlistService.getCurrentIndex();
if (this.playlist.isVisible() && this.playlistService.getPlaylist()) {
this.playlist.saveTrackProgress(idx, videoEl.currentTime, videoEl.duration);
}
}
});
// Periodically persist per-episode progress to drive playlist progress bars.
if (this._trackProgressInterval) clearInterval(this._trackProgressInterval);
this._trackProgressInterval = setInterval(() => {
if (!videoEl || videoEl.paused || !videoEl.duration) return;
const idx = this.playlistService.getCurrentIndex();
if (this.playlist.isVisible() && this.playlistService.getPlaylist()) {
this.playlist.saveTrackProgress(idx, videoEl.currentTime, videoEl.duration);
}
}, 5000);
videoEl.addEventListener('ended', () => {
if (this.videoId && videoEl.duration) {
this.progressTracker.saveProgress(this.videoId, videoEl.duration, videoEl.duration, this._currentVideoMeta());
}
const idx = this.playlistService.getCurrentIndex();
if (this.playlist.isVisible() && this.playlistService.getPlaylist()) {
this.playlist.markWatched(idx, videoEl.duration);
}
// Up Next overlay (only if there is a next + an actual playlist)
if (this.playlistService.hasNext()) {
this.showUpNext();
}