-
Notifications
You must be signed in to change notification settings - Fork 5
/
page.js
6020 lines (5651 loc) · 226 KB
/
page.js
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
/*
FlagPlayer - A lightweight YouTube frontend
Copyright (C) 2019 Seneral
Licensed under AGPLv3
See https://github.com/Seneral/FlagPlayer for details
*/
"use strict";
/* ------------------------------------ */
/* ---- TABLE OF CONTENTS ------------- */
/*
-- HTML
-- Variables
Control Functions
-- Init
-- Preferences
-- Page Content
-- Paged Content
-- Home
-- Playlist
-- Search
-- Channel
- Media
-- Media State
-- Media Playback
Database
YouTube
- Page Navigation
- YouTube Extraction
-- Playlist
-- Search
-- Channel
-- Watch
-- Related Videos
-- Comments
- Stream Decoding
UI Content
-- UI Layout
-- UI State
-- Formatting
-- UI Settings
-- UI Home
-- UI Player
-- UI Video
-- UI Related
-- UI Comments
-- UI Search
-- UI Channel
-- UI Playlist
UI Interactivity
-- UI Helpers
-- UI Controls
-- UI Generic
-- UI Timeline
-- UI Control Bar
-- UI Handlers
UI Callbacks
-- DOM Handlers
-- Button Handlers
-- Mouse Handlers
-- Keyboard Handlers
-- Media Handlers
Media Functions
-- Streams
-- State
-- Playback
Utility Functions
-- Requests
-- Experimental
-- HTML Bin
Data
*/
/* ------------------------------------ */
function I (i) { return document.getElementById(i); }
function S (i,v) { localStorage.setItem(i,v); }
function G (i) { return localStorage.getItem(i); }
function setDisplay (i,v) { I(i).style.display = v; }
Element.prototype.toggleAttr = function toggleAttr(name) {
if (this.hasAttribute(name)) {
this.removeAttribute(name);
return false;
}
this.setAttribute(name, "");
return true;
};
/* -------------------- */
/* ---- HTML ---------- */
/* -------------------- */
// Container
var ht_container = I("container");
var ht_content = I("content");
var ht_mobile = I("mobile");
var ht_main = I("main");
var ht_side = I("side");
// Sections
var sec_player = I("player");
var sec_playlist = I("playlist");
var sec_video = I("video");
var sec_related = I("related");
var sec_comments = I("comments");
var sec_search = I("search");
var sec_banner = I("banner");
var sec_channel = I("channel");
var sec_home = I("home");
var sec_cache = I("cache");
// Main media elements
var videoMedia = I("videoMedia");
var audioMedia = I("audioMedia");
var controlBar = I("controlBar");
// Frequently accessed control bar elements
var timeLabel = I("timeLabel");
var timelineControl = I("tlControl");
var timelinePosition = I("tlPosition");
var timelineProgress = I("tlProgress");
var timelinePeeking = I("tlPeeking");
var timelineBuffered = I("tlBuffered");
// Other
var ht_playlistVideos = I("plVideos");
/* -------------------- */
/* ---- VARIABLES ----- */
/* -------------------- */
/* SERVICE WORKER */
var sw_current;
var sw_updated;
var sw_refreshing;
/* DATABASE */
var db_database;
var db_loading = false;
var db_accessCallbacks = [];
var db_indexLoading = false;
var db_indexCallbacks = [];
var db_playlists; // [ { listID, title, description, author, count, thumbID, videos [ videoID ] } ]
var db_cachedVideos;
/* PAGE STATE */
var Page = { None: 0, Home: 1, Media: 2, Search: 3, Channel: 4, Playlist: 5, Cache: 6 }
var ct_page = Page.Home;
var ct_pagePlaylist;
var ct_view; // explicit view request (cache, media, etc)
var ct_temp = { fullscreen: false, options: false, settings: false, loop: false, } // options: player; settings: page
var ct_pagedContent = []; // id, container, autoTrigger, triggerDistance, aborted, loading, loadFunc, page, data
var ct_isDesktop;
var ct_pref = {};
var ct_shareData = {};
/* MEDIA STATE */
var State = { None: 0, Loading: 1, PreStart: 2, Started: 3, Ended: 4, Error: 5 }
var md_state = State.None; // Lifetime: loading - prestart (if autoplay denied) - started - ended
var md_sources = undefined; // { video: url, audio: url }
var md_paused = true; // Current state or intent
var md_flags = { buffering: false, seeking: false } // Only valid during State.Started
var md_isPlaying = function () { return md_sources && md_state == State.Started && !md_paused && !md_flags.buffering && !md_flags.seeking; };
var md_curTime = 0, md_totalTime = 0;
var md_errorText = "An Error occured!"; // Error message if md_state == State.Error
var md_pref = {}; // volume, muted, playlistRandom, autoplay, dash, dashVideo, dashContainer, legacyVideo
/* YOUTUBE CONTENT */
var yt_url; // URL of respective youtube content
var yt_page; // cookies {}, secrets {}, initialData {}, playerConfig {}, videoDetail {}, html "", object {}, unavailable
// secrets: csn, xsrfToken, idToken, innertubeAPIKey, clientName, clientVersion, pageCL, pageLabel, variantsChecksum, visitorData, ...
// Playlist
var yt_playlistID;
var yt_playlist; // listID, title, author, views, description, videos [ video {} ]
// video: title, videoID, length, thumbnailURL, addedDate, uploadedDate, uploader {}, views, likes, dislikes, comments, tags []
// uploader: name, channelID, url
// Video
var yt_videoID;
var yt_video; // ageRestricted, blocked, meta {}, streams [ stream {} ], related {}, commentData {}
// meta: title, description, uploader {}, uploadedDate, thumbnailURL, length, views, likes, dislikes, metadatata[{ name, data }], category
// uploader: name, url, channelID, userID, profileImg, badge, subscribers
// stream: url, itag, hasVideo, hasAudio, isDash, mimeType, container, isLive, isStereo,
// vCodec, vBR (Bitrate), vResX, vResY, vFPS,
// aCodec, aBR (Bitrate), aSR (Sample Rate), aChannels
// Search
var yt_searchTerms;
var yt_searchResults; // hits, videos [video {}]
// video: title, videoID, length, thumbnailURL, addedDate, uploadedDate, uploader {}, views, likes, dislikes, comments, tags []
// uploader: name, channelID, url
// Channel
var yt_channelID; // channel, user
var yt_channel; // meta {}, upload {}
// meta: title, channelID, profileImg, bannerImg, url, subscribers, description, links { title icon link }
// upload: videos [video {}], conToken
// video: title, videoID, views, length, thumbnailURL uploadedTimeAgoText
/* TEMPORARY STATE */
var ct_online; // Flag if last request suceeded
var ct_isAdvancedCorsHost; // Boolean: Supports cookie-passing for (with others) comments
var ct_traversedHistory; // Prevent messing with history when traversing
var ct_timerAutoplay; // Timer ID for video end autoplay timer
var ct_autoplayNotification; // A notification whose notOnClose action will trigger ct_nextVideo
var ui_cntControlBar; // For control bar retraction when mouse is unmoving
var ui_timerIndicator; // Timer ID for the current temporary indicator (pause/plax) on the video screen
var ui_dragSlider; // Currently dragging a slider?
var ui_dragSliderElement; // Currently dragged slider element
var ui_plScrollPos; // Scroll Position of Playlist window - cached in order to prevent forced reflow during adaptive loading
var ui_plScrollDirty; // Dirty flag if scroll position has changed while playlist was collapsed
var ht_placeholder; // Playlist Element Placeholder used for initializing a playlist
var md_timerSyncMedia; // Timer ID for next media sync attempt (dash only)
var md_timerCheckBuffering; // Timer ID for next media buffering check (and start video when ready)
var md_cntBufferPause; // Count of intervals (50ms) in which buffered amount did not change
var md_lastBuffer; // Last known buffered amount, used because buffered events don't always fire
var md_attemptPlayStarted; // Flag to prevent multiple simultaneous start play attempts
var md_attemptPause; // Flag to indicate play start attempt is to be aborted
/* CONSTANTS */
const BASE_URL = location.protocol + '//' + location.host + location.pathname;
const LANG_INTERFACE = "en;q=0.9";
const LANG_CONTENT = "en;q=0.9"; // content language (auto-translate) - * should remove translation
const VIRT_CACHE = "https://flagplayer.seneral.dev/caches/vd-"; // Virtual adress used for caching. Doesn't actually exist, but needs to be https
const HOST_YT = "https://www.youtube.com";
const HOST_YT_MOBILE = "https://m.youtube.com";
const HOST_YT_IMG = "https://i.ytimg.com/vi/"; // https://i.ytimg.com/vi/ or https://img.youtube.com/vi/
const HOST_CORS = "https://flagplayer-cors.seneral.dev/"; // Default value only
//"http://localhost:8080/";
// Some public hosts (Some might be down), DO NOT SUPPORT COMMENTS due to custom headers to forward
//"https://proxy.cors.sh/"
//"https://cors-anywhere.herokuapp.com/";
//"http://allow-any-origin.appspot.com/";
//"https://secret-ocean-49799.herokuapp.com/";
//"https://test.cors.workers.dev/";
//"https://crossorigin.me/"
//endregion
/* -------------------------------------------------------------------------------------------------------------- */
/* ----------------- SERVICE WORKER ----------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------- */
function sw_install () {
// Setup service worker for caching control
if ("serviceWorker" in navigator) {
navigator.serviceWorker.oncontrollerchange = function () {
if (sw_refreshing) return;
window.location.reload();
sw_refreshing = true;
};
navigator.serviceWorker.register("./sw.js").then(function(registration) {
// Get current service worker
sw_current = navigator.serviceWorker.controller;
if (sw_current) console.log("Successfully installed service worker: Caching and Offline Mode are available!");
else console.log("Successfully installed service worker: Caching and Offline Mode are available after reload!");
// Check for updates
registration.onupdatefound = function () {
if (!navigator.serviceWorker.controller)
return; // not an update, but initial installation
console.log("Found new service worker version!");
var update = function () {
sw_updated = registration.waiting || registration.active;
var not = ui_setNotification("newVersionPanel", 'A new version is available! <button>Update now</button>');
not.children[0].onclick = function() {
sw_updated.postMessage({ action: "skipWaiting" });
not.notClose();
};
console.log("New service worker version ready for activation!");
};
var installing = registration.installing;
if (installing) { // wait until installed to update
installing.onstatechange = function () {
if (installing.state == "installed" || installing.state == "active")
update();
};
}
else update();
};
if (registration.waiting) // Trigger after initial detection
registration.onupdatefound();
}, function(e) {
console.warn("Failed to install service worker: Caching and Offline Mode will be unavailable!");
});
}
}
/* -------------------------------------------------------------------------------------------------------------- */
/* ----------------- CONTROL FUNCTIONS -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------- */
//region
/* -------------------- */
/* ---- INIT ---------- */
/* -------------------- */
Object.defineProperties(Array.prototype, {
// Add method to array prototype to extract (find by existence and return) a member of a list
extract: {
value: function (fn) {
for (let x of this) {
var res = fn(x);
if (res != undefined)
return res;
}
},
enumerable: false
},
// Add method to array prototype to gather (filter by existence and map) members of a list
gather: {
value: function (fn) {
var arr = [];
for (let x of this) {
var res = fn(x);
if (res != undefined)
arr.push(res);
}
return arr;
},
enumerable: false
},
});
function ct_init () {
ct_loadPreferences();
ui_updatePageLayout();
ui_initStates();
ct_newPageState();
ui_setupEventHandlers();
ct_readParameters();
ct_loadContent();
sw_install();
}
/* -------------------- */
/* ---- PREFERENCES --- */
/* -------------------- */
function ct_loadPreferences () {
// Playback options
md_pref = {};
md_pref.dash = true;//G("prefDash") == "false"? false : true;
md_pref.legacyVideo = G("prefLegacyVideo") || "BEST"; // NONE - BEST - WORST - <Resolution>
md_pref.dashVideo = G("prefDashVideo") || "72030"; // NONE - BEST - WORST - <Resolution*100+FPS>
md_pref.dashAudio = G("prefDashAudio") || "160"; // NONE - BEST - WORST - <Bitrate>
md_pref.dashContainer = G("prefDashContainer") || "webm"; // webm - mp4
md_pref.vCodec = G("prefCodec") || "vp"; // vp, avc, av01
md_pref.muted = G("prefMuted") == "true"? true : false;
md_pref.volume = G("prefVolume") != undefined? parseFloat(G("prefVolume")) : 1;
// Page Settings
ct_pref = {};
ct_pref.playlistRandom = G("prefPlaylistRandom") == "false"? false : true;
ct_pref.autoplay = G("prefAutoplay") == "false"? false : true;
ct_pref.theme = G("prefTheme") || "DARK";
ct_pref.corsAPIHost = G("prefCorsAPIHost") || HOST_CORS;
if (ct_pref.corsAPIHost.includes("flagplayer-cors.herokuapp.com"))
ct_pref.corsAPIHost = HOST_CORS; // Was old host, not available anymore
else if (!ct_pref.corsAPIHost.includes("localhost") && ct_pref.corsAPIHost != HOST_CORS)
{ // Might have switched to a public host, notify users that new official servers are available
var not = ui_setNotification("newCORSServer", 'An official CORS backend is available again! <button>Use official backend</button> <br/> Public CORS hosts do not support custom headers required for comment loading and are a shared resource.');
not.children[0].onclick = function() {
ct_pref.corsAPIHost = HOST_CORS;
ct_savePreferences();
not.notClose();
};
}
if (!ct_pref.corsAPIHost.endsWith('/'))
ct_pref.corsAPIHost += '/';
ct_pref.relatedVideos = G("prefRelated") || "ALL";
ct_pref.filterCategories = (G("prefFilterCategories") || "").split(",").map(c => parseInt(c));
ct_pref.filterHideCompletely = G("prefFilterHideCompletely") == "false"? false : true;
ct_pref.loadComments = G("prefLoadComments") == "false"? false : true;
ct_pref.cacheAudioQuality = G("prefCacheAudioQuality") || "128";
ct_pref.cacheForceUse = G("prefCacheForceUse") == "false"? false : true;
ct_pref.smallPlayer = G("prefPlayerSmall") == "true"? true : false;
}
function ct_savePreferences () {
// Playback Options
//S("prefDash", md_pref.dash);
if (md_sources) {
S("prefLegacyVideo", md_pref.legacyVideo);
S("prefDashVideo", md_pref.dashVideo);
S("prefDashAudio", md_pref.dashAudio);
S("prefDashContainer", md_pref.dashContainer);
S("prefCodec", md_pref.vCodec);
}
S("prefMuted", md_pref.muted);
S("prefVolume", md_pref.volume);
// Page Settings
S("prefAutoplay", ct_pref.autoplay);
S("prefPlaylistRandom", ct_pref.playlistRandom);
S("prefTheme", ct_pref.theme);
S("prefRelated", ct_pref.relatedVideos);
S("prefFilterCategories", ct_pref.filterCategories.join(","));
S("prefFilterHideCompletely", ct_pref.filterHideCompletely);
S("prefLoadComments", ct_pref.loadComments);
S("prefCorsAPIHost", ct_pref.corsAPIHost);
S("prefCacheAudioQuality", ct_pref.cacheAudioQuality);
S("prefCacheForceUse", ct_pref.cacheForceUse);
S("prefPlayerSmall", ct_pref.smallPlayer);
}
/* -------------------- */
/* ---- PAGE CONTENT -- */
/* -------------------- */
function ct_readParameters () {
var params = new URLSearchParams(window.location.search);
// Read parameters from URL
ct_view = params.get("view");
yt_playlistID = params.get("list");
yt_videoID = params.get("v");
yt_channelID = { channel: params.get("ch"), channelName: params.get("c"), user: params.get("u") };
yt_searchTerms = params.get("q");
ct_shareData = params.get("shURL") || params.get("shText") || params.get("shTitle");
// Validate parameters
if (yt_videoID && yt_videoID.length != 11)
yt_videoID = undefined;
if (!yt_channelID.user && !yt_channelID.channelName && !(yt_channelID.channel && yt_channelID.channel.length == 24 && yt_channelID.channel.startsWith("UC")))
yt_channelID = undefined;
yt_searchTerms = yt_searchTerms? decodeURIComponent(yt_searchTerms) : undefined;
}
function ct_resetContent () {
ct_page = Page.None;
ct_view = undefined;
ct_shareData = undefined;
// Discard main content (not including playlist)
ct_resetSearch();
ct_resetChannel();
ct_mediaUnload();
ui_resetHome();
ui_resetCache();
// If on mobile, collapse playlist
if (!ct_isDesktop) sec_playlist.setAttribute("collapsed", "");
}
function ct_loadContent () {
// Primary Content
if (ct_shareData && ct_shareData.length > 1) {
ct_navSearch(ct_shareData, true);
return;
} else if (ct_view == "cache") {
ct_page = Page.Cache;
ct_loadCache();
} else if (yt_videoID) {
ct_page = Page.Media;
ct_loadMedia ();
} else if (yt_channelID) {
ct_page = Page.Channel;
ct_loadChannel();
} else if (yt_searchTerms) {
ct_page = Page.Search;
ct_loadSearch();
//} else if (yt_playlistID) {
// ct_page = Page.Playlist;
} else {
ct_page = Page.Home;
ct_loadHome();
}
ui_setupHome();
// Secondary Content (can be primary)
if (yt_playlistID) {
ct_pagePlaylist = true;
ct_loadPlaylist();
} else {
ct_pagePlaylist = false;
}
ct_updatePageState();
}
function ct_newPageState () { // Register new page
history.pushState({}, "FlagPlayer");
}
function ct_updatePageState () { // Update page with new information
var url = new URL(window.location.href);
var state = history && history.state? history.state : {};
yt_url = HOST_YT;
url.searchParams.delete("shTitle");
url.searchParams.delete("shText");
url.searchParams.delete("shURL");
if (ct_page == Page.Home)
state.title = "Home | FlagPlayer";
if (ct_page == Page.Cache) {
state.title = "Cache | FlagPlayer";
url.searchParams.set("view", "cache");
} else if (url.searchParams.get("view") == "cache")
url.searchParams.delete("view");
if (ct_page == Page.Media) {
if (yt_video && yt_video.loaded) state.title = yt_video.meta.title + " | FlagPlayer";
else if (!state.title) state.title = "Loading | FlagPlayer";
url.searchParams.set("v", yt_videoID);
yt_url += "/watch?v=" + yt_videoID;
} else url.searchParams.delete("v");
if (ct_page == Page.Channel) {
if (yt_channel && yt_channel.meta) state.title = yt_channel.meta.name + " | FlagPlayer";
else if (!state.title) state.title = "Channel | FlagPlayer";
if (yt_channelID.user) {
url.searchParams.set("u", yt_channelID.user);
url.searchParams.delete("c");
url.searchParams.delete("ch");
yt_url += "/user/" + yt_channelID.user;
} else if (yt_channelID.channelName) {
url.searchParams.set("c", yt_channelID.channelName);
url.searchParams.delete("u");
url.searchParams.delete("ch");
yt_url += "/c/" + yt_channelID.channelName;
} else if (yt_channelID.channel) {
url.searchParams.set("ch", yt_channelID.channel);
url.searchParams.delete("u");
url.searchParams.delete("c");
yt_url += "/channel/" + yt_channelID.channel;
}
} else {
url.searchParams.delete("u");
url.searchParams.delete("c");
url.searchParams.delete("ch");
}
if (ct_page == Page.Search) {
state.title = "'" + yt_searchTerms + "' - Search | FlagPlayer";
url.searchParams.set("q", encodeURIComponent(yt_searchTerms));
yt_url += "/results?search_query=" + encodeURIComponent(yt_searchTerms);
} else url.searchParams.delete("q");
if (ct_pagePlaylist) {
url.searchParams.set("list", yt_playlistID);
if (ct_page == Page.Playlist) yt_url += "/playlist?list=" + yt_playlistID;
if (ct_page == Page.Media) yt_url += "&list=" + yt_playlistID;
(I("youtubePLLink") || {}).href = HOST_YT + "/playlist?list=" + yt_playlistID;
} else url.searchParams.delete("list");
// TODO: only delete if not for current video
url.searchParams.delete("t");
// Update state
state.title = state.title || "FlagPlayer";
document.title = state.title;
if (history && history.replaceState) history.replaceState(state, state.title, url.href);
else window.location = url; // Triggers reload, not perfect but better than no link update
[].forEach.call(document.getElementsByClassName("youtubeLink"), function (l) { l.href = yt_url });
}
function ct_getNavLink(navID) {
var i = navID.indexOf("=");
if (i != -1) {
var link = BASE_URL + "?";
// Prepend current playlist ID
if (navID.substring(0, i) != "list" && yt_playlistID)
link += "list=" + yt_playlistID + "&";
// Add parameter
link += navID.substring(0, i) + "=" + navID.substring(i+1, navID.length);
return link;
}
else return BASE_URL + (yt_playlistID? "?list=" + yt_playlistID : "");
}
function ct_beforeNav () {
ct_resetContent();
}
function ct_performNav (inNewState) {
//window.scrollTo(0, 0);
document.body.scrollTop = 0;
//container.scrollTop = 0;
//content.scrollTop = 0;
if (!inNewState)
ct_newPageState();
ct_loadContent();
}
/* -------------------- */
/* ---- PAGED CONTENT - */
/* -------------------- */
function ct_registerPagedContent(id, container, loadFunc, trigger, data, showLoader) {
ct_removePagedContent(id);
var pagedContent = {
id: id,
container: container,
autoTrigger: Number.isInteger(trigger)? true : trigger,
triggerDistance: Number.isInteger(trigger)? trigger : undefined,
loadFunc: loadFunc,
loading: false,
index: 0,
data: data,
loader: showLoader
};
ct_pagedContent.push(pagedContent);
return pagedContent;
}
function ct_removePagedContent(id) {
var i;
while ((i = ct_pagedContent.findIndex(p => p.id == id)) >= 0) {
ct_abortPagedContent(ct_pagedContent[i]);
ct_pagedContent.splice(i, 1);
}
}
function ct_removePagedContentAll(id) {
for (var i = 0; i < ct_pagedContent.length; i++) {
if (ct_pagedContent[i].id.startsWith(id)) {
ct_abortPagedContent(ct_pagedContent[i]);
ct_pagedContent.splice(i, 1);
}
}
}
function ct_abortPagedContent(pagedContent) {
if (pagedContent.loading)
{
pagedContent.aborted = true;
if (pagedContent.loader)
ui_removeLoadingIndicator(pagedContent.container);
}
}
function ct_getPagedContent(id) {
return ct_pagedContent.find(p => p.id == id);
}
function ct_checkPagedContent() {
for (var i = 0; i < ct_pagedContent.length; i++) {
var pagedContent = ct_pagedContent[i];
if (pagedContent.loading || !pagedContent.autoTrigger) continue;
var rect = pagedContent.container.getBoundingClientRect();
var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
if (!pagedContent.triggerDistance || rect.bottom - viewportHeight <= pagedContent.triggerDistance)
ct_triggerPagedContent(pagedContent);
}
}
function ct_triggerPagedContent(pagedContent) {
if (!pagedContent) return;
if (pagedContent.aborted)
return;
if (pagedContent.loading)
return;
pagedContent.loading = true;
if (pagedContent.loader)
ui_addLoadingIndicator(pagedContent.container);
// Perform content loading
pagedContent.loadFunc(pagedContent.data, pagedContent)
.then(function(hasContinuation){
if (pagedContent.aborted)
return;
if (pagedContent.loader)
ui_removeLoadingIndicator(pagedContent.container);
if (!hasContinuation) {
ct_pagedContent.splice(ct_pagedContent.findIndex(p => p == pagedContent), 1);
return;
}
// Continue
pagedContent.loading = false;
if (pagedContent.autoTrigger && pagedContent.triggerDistance == undefined)
ct_checkPagedContent();
}).catch (function (error) {
console.error("Paged content failed: ", error);
});
}
/* -------------------- */
/* ---- HOME ---------- */
/* -------------------- */
function ct_navHome() {
ct_beforeNav();
ct_performNav();
}
function ct_loadHome () {
ui_setupHome();
}
/* -------------------- */
/* ---- CACHE --------- */
/* -------------------- */
function ct_navCache () {
ct_beforeNav();
ct_view = "cache";
ct_performNav();
}
function ct_loadCache () {
db_getCachedVideos().then(ui_setupCache);
db_requestPersistence().then(function(persistence) {
if (!persistence) I("cachePersistence").style.display = "";
});
}
function ct_cacheVideo(video) {
if (I(notID) != undefined) return; // Already started
var videoID = video.videoID;
var notID = 'cache-' + videoID;
var abort = false;
var type = "normal"; // "normal" - normal is better but uses more cors server resources as all cached audio is directed over it
ui_setNotification(notID, "Caching " + videoID + "...").notOnClose = function() { abort = true; };
db_cacheStream(video, type, function(bytesReceived, bytesTotal) {
// Not called if type == opaque
if (abort) return false;
ui_setNotification(notID, "Caching " + videoID + ": " + ui_shortenBytes(bytesReceived) + "/" + ui_shortenBytes(bytesTotal));
return true;
}).then(function(cache) {
var not = ui_setNotification(notID, "Caching " + videoID + ": " + (cache.size? ui_shortenBytes(cache.size) : "Done, unknown size") + " - " +
'<button>View Cache</button>', 3000);
not.notContent.children[0].onclick = function() { not.notClose(); ct_navCache(); };
video.mediaCache = cache;
// In case current view is cache, update the view
db_getCachedVideos().then(ui_setupCache);
}).catch(function(e) {
if (!abort) ui_setNotification(notID, "Caching " + videoID + ": " + (e?.message || "Unknown Error"));
});
}
/* -------------------- */
/* ---- PLAYLIST ------ */
/* -------------------- */
function ct_loadPlaylist (plID) {
if (!plID) plID = yt_playlistID;
if (yt_playlist && plID == yt_playlistID) return;
yt_playlistID = plID;
yt_playlist = undefined;
ui_resetPlaylist();
ui_setupPlaylist();
ct_pagePlaylist = true;
ct_updatePageState();
db_loadPlaylist(plID)
.then(function (playlist) {
if (plID != yt_playlistID) return Promise.resolve(); // Changed while loading
yt_playlist = playlist;
ui_addToPlaylist(0);
ui_setPlaylistFinished();
console.log("YT Playlist:", yt_playlist);
})
.catch(function() {
if (plID != yt_playlistID) return Promise.resolve(); // Changed while loading
ui_setPlaylistSaved(false);
return yt_loadPlaylistData(yt_playlistID, false)
.then(function(playlist) {
if (plID != yt_playlistID) return Promise.resolve(); // Changed while loading
ui_setPlaylistFinished ();
console.log("YT Playlist:", yt_playlist);
});
});
}
function ct_savePlaylist () {
if (!yt_playlist) return;
db_updatePlaylist(yt_playlist)
.then(function() {
ui_setupHome();
ui_setPlaylistSaved(true);
db_requestPersistence();
});
}
function ct_removePlaylist () {
if (!yt_playlist) return;
db_removePlaylist(yt_playlist.listID).then(function () {
ui_setPlaylistSaved (false);
ui_setupHome();
});
}
function ct_updatePlaylist () {
if (yt_playlistID) {
var plID = yt_playlistID;
yt_playlist = undefined;
ui_resetPlaylist();
ui_setupPlaylist();
yt_loadPlaylistData(plID, false)
.then(function(playlist) {
if (plID == yt_playlistID) ui_setPlaylistFinished();
db_updatePlaylist(playlist)
.then(ui_setupHome);
});
}
}
function ct_resetPlaylist () {
ct_newPageState();
ct_pagePlaylist = false;
yt_playlistID = undefined;
yt_playlist = undefined;
ui_resetPlaylist();
ct_updatePageState();
}
function ct_getVideoPlIndex () { // Return -1 on fail so that pos+1 will be 0
return !yt_playlist? -1 : yt_playlist.videos.findIndex(v => v.videoID == yt_videoID);
}
/* -------------------- */
/* ---- SEARCH -------- */
/* -------------------- */
function ct_navSearch(searchTerms, inNewState) {
var plMatch = searchTerms.match(/(PL[a-zA-Z0-9_-]{32})/) || searchTerms.match(/list=([a-zA-Z0-9_-]{20,})(?:&|$)/) || searchTerms.match(/^([A-Z]{2}[a-zA-Z0-9_-]{20,})$/);
var chMatch = searchTerms.match(/(UC[a-zA-Z0-9_-]{22})/);
var cMatch = searchTerms.match(/c\/([a-zA-Z0-9_-]+)/);
var uMatch = searchTerms.match(/user\/([a-zA-Z0-9_-]+)/);
var vdMatch = searchTerms.match(/v=([a-zA-Z0-9_-]{11})/) || searchTerms.match(/youtu.be\/([a-zA-Z0-9_-]{11})/);
if (plMatch) ct_loadPlaylist(plMatch[1]);
if (!plMatch || vdMatch) {
ct_beforeNav();
if (vdMatch) yt_videoID = vdMatch[1];
else if (chMatch) yt_channelID = { channel: chMatch[1] };
else if (uMatch) yt_channelID = { user: uMatch[1] };
else if (cMatch) yt_channelID = { channelName: cMatch[1] };
else yt_searchTerms = searchTerms;
ct_performNav(inNewState);
}
}
function ct_loadSearch() {
yt_loadSearchPage(yt_searchTerms);
ui_setupSearch();
}
function ct_resetSearch () {
ct_removePagedContent("SC");
ui_resetSearch();
yt_searchTerms = undefined;
yt_searchResults = undefined;
}
/* -------------------- */
/* ---- CHANNEL ------- */
/* -------------------- */
function ct_navChannel(channel) {
ct_beforeNav();
yt_channelID = channel;
ct_performNav();
}
function ct_loadChannel() {
ui_addLoadingIndicator(sec_channel, false);
yt_loadChannelData(yt_channelID, false)
// Initiate further control
.then(function() {
ct_online = true;
console.log("YT Channel:", yt_channel);
ct_updatePageState();
ui_removeLoadingIndicator(sec_channel);
ui_setChannelMetadata();
ui_setupChannelTabs();
// Browse tabs need to load first to get continuation data - wait and then update UI
if (yt_channel.uploads.loadingTabs) {
yt_channel.uploads.loadingTabs.forEach(function (tabLoader) {
tabLoader.then(ui_fillChannelTab);
});
}
// Make sure paged content gets loaded if visible
ct_checkPagedContent();
})
// Handle different errors while loading
.catch(function(error) {
ui_removeLoadingIndicator(sec_channel);
if (!error) return; // Silent fail when request has gone stale (new page loaded before this finished)
if (error instanceof NetworkError) {
console.error("Network Error! Could not load Channel Page!");
}
else {
console.error("Error " + error.name + " while loading Channel Page: " + error.message);
}
ui_setChannelError(error);
});
}
function ct_resetChannel () {
ct_removePagedContentAll("CH");
ui_resetChannelMetadata();
ui_resetChannelUploads();
yt_channelID = undefined;
yt_channel = undefined;
}
/* ------------------------------------------------- */
/* ----- MEDIA ------------------------------------- */
/* ------------------------------------------------- */
function ct_nextVideo() {
var newVideo;
if (yt_playlist) {
var playlist = yt_playlist.videos.filter (v => !v.unavailable);
// Only show cached videos if offline
if (!ct_online) playlist = playlist.filter (v => v.cache != undefined);
// If none cached, still flip through uncache videos
if (playlist.length == 0) playlist = yt_playlist.videos;
// Filter out current video to prevent duplicate playback
var index = playlist.findIndex(v => v.videoID == yt_videoID);
if (playlist.length > 1 && index >= 0)
playlist.splice(index, 1);
// Choose random video
if (playlist.length == 0) index = -1;
else if (ct_pref.playlistRandom) index = Math.floor (Math.random() * playlist.length);
else index = index % playlist.length; // Already removed current
newVideo = index >= 0? playlist[index] : undefined;
}
else if (yt_video && yt_video.related) {
newVideo = yt_video.related.videos[0];
}
if (newVideo) ct_navVideo(newVideo.videoID);
else ui_updatePlayerState();
}
function ct_navVideo(videoID) {
ct_beforeNav();
yt_videoID = videoID;
ct_performNav();
}
function ct_canPlay () {
return !ct_temp.settings;// && document.visibilityState == "visible";
}
function ct_loadMedia () {
var loadingID = yt_videoID;
// Load and display cached data
var cacheLoad = db_getVideo(yt_videoID).then(function (video) {
if (!yt_video || loadingID != yt_videoID) return Promise.reject();
yt_video.cachedMetadata = true;
yt_video.mediaCache = video.cache;
if (yt_video.meta != undefined) return Promise.resolve();
yt_video.meta = {
title: video.title,
uploader: {
name: video.uploader.name,
channelID: video.uploader.channelID,
},
uploadedDate: video.uploadedDate,
thumbnailURL: video.thumbnailURL,
length: video.length,
views: video.views,
likes: video.likes,
dislikes: video.dislikes,
};
ui_setVideoMetadata();
return Promise.resolve();
}).catch(function() {});
// Load, parse and display online video data
yt_loadVideoData(yt_videoID, false)
// Initiate further control
.then(function() {
ct_online = true;
if (yt_video.unavailable)
throw new PlaybackError(10, "Video is unavailable!", false);
if (yt_video.blocked)
throw new PlaybackError(11, "Video is blocked in your country!", false);
if (yt_video.ageRestricted)
throw new PlaybackError(12, "Video is age restricted!", false);
if (yt_video.status != "OK")
throw new PlaybackError(13, "Playability Status: " + yt_video.status, false);
if (yt_video.streams.length == 0)
throw new ParseError(103, "Failed to parse streams!");
console.log("YT Video:", yt_video);
ct_mediaLoaded();
ct_updatePageState();
ui_setVideoMetadata();
ui_setupMediaSession();
// Related Videos
ui_addRelatedVideos(0);
if (yt_video.related.continuation && ct_isAdvancedCorsHost)
ct_registerPagedContent("RV", I("relatedContainer"), yt_loadMoreRelatedVideos, ct_isDesktop? 100 : false, yt_video.related, true);
// Comments
if (yt_video.comments.continuation && ct_isAdvancedCorsHost && ct_pref.loadComments) {
yt_video.comments.container = I("vdCommentList");
ct_registerPagedContent("CM", I("vdCommentList"), yt_loadMoreComments, 100, yt_video.comments, true);
}
ct_checkPagedContent();
})
// Handle different errors while loading
.catch(function(error) {
if (!error) return; // Silent fail when request has gone stale (new page loaded before this finished)
if (error instanceof NetworkError)
ct_online = false;
cacheLoad.then(function() {
if (yt_video.mediaCache != undefined) {
console.error(error.name + (error.code? " " + error.code : "") + ": " + error.status + " ", error.stack);
console.warn("Error while loading ... Using cache fallback!");
yt_video.streams = [];
ct_mediaLoaded();
ct_updatePageState();
//ui_setVideoMetadata(); // Already done in cacheLoad
ui_setupMediaSession();
} else { // Metadata IS cached
ct_updatePageState();
ui_setVideoMetadata();
ct_mediaError(error);