-
Notifications
You must be signed in to change notification settings - Fork 5
/
marathon.user.js
1861 lines (1833 loc) · 65.1 KB
/
marathon.user.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
// ==UserScript==
// @name Netflix Marathon (Pausable)
// @name:en Netflix Marathon (Pausable)
// @name:zh-CN Netflix 马拉松(可暂停)
// @name:zh-TW Netflix 馬拉松(可暫停)
// @name:ja Netflix Marathon(一時停止できます)
// @name:ko Netflix 마라톤(일시 중지 가능)
// @name:ar ماراثون Netflix (يمكن إيقافه مؤقتًا)
// @name:de Netflix-Marathon (pausierbar)
// @name:ru Netflix Marathon (пауза)
// @name:hi नेटफ्लिक्स मैराथन (रोकने योग्य)
// @namespace https://github.com/aminomancer
// @version 5.7.7
// @description A configurable script that automatically skips recaps, intros, credits, and ads, and clicks "next episode" prompts on Netflix, Amazon Prime Video, Hulu, HBO Max, Starz, Disney+, and Hotstar. Customizable hotkey to pause/resume the auto-skipping functionality. Alt + N for settings.
// @description:en A configurable script that automatically skips recaps, intros, credits, and ads, and clicks "next episode" prompts on Netflix, Amazon Prime Video, Hulu, HBO Max, Starz, Disney+, and Hotstar. Customizable hotkey to pause/resume the auto-skipping functionality. Alt + N for settings.
// @description:zh-CN 一个可配置的脚本,可自动跳过重述、介绍、演职员表和广告,并点击 Netflix、Amazon Prime Video、Hulu、HBO Max、Starz、Disney+ 和 Hotstar 上的“下一集”提示。 可自定义的热键暂停/恢复自动跳过功能。 Alt + N 进行设置。
// @description:zh-TW 一個可配置的腳本,可自動跳過重述、介紹、演職員表和廣告,並點擊 Netflix、Amazon Prime Video、Hulu、HBO Max、Starz、Disney+ 和 Hotstar 上的“下一集”提示。 可自定義的熱鍵暫停/恢復自動跳過功能。 Alt + N 進行設置。
// @description:ja 要約、イントロ、クレジット、広告を自動的にスキップし、Netflix、Amazon Prime Video、Hulu、HBO Max、Starz、Disney +、Hotstarの「次のエピソード」のプロンプトをクリックする構成可能なスクリプト。 自動スキップ機能を一時停止/再開するためのカスタマイズ可能なホットキー。 Alt + Nで設定します。
// @description:ko 요약, 소개, 크레딧 및 광고를 자동으로 건너뛰고 Netflix, Amazon Prime Video, Hulu, HBO Max, Starz, Disney+ 및 Hotstar에서 "다음 에피소드" 프롬프트를 클릭하는 구성 가능한 스크립트입니다. 자동 건너뛰기 기능을 일시 중지/재개하는 사용자 지정 가능한 단축키입니다. Alt + N은 설정입니다.
// @description:ar برنامج نصي قابل للتكوين يتخطى الملخصات والمقدمات والاعتمادات والإعلانات تلقائيًا وينقر على "الحلقة التالية" على Netflix و Amazon Prime Video و Hulu و HBO Max و Starz و Disney + و Hotstar. مفتاح التشغيل السريع القابل للتخصيص لإيقاف / استئناف وظيفة التخطي التلقائي. Alt + N للإعدادات.
// @description:de Ein konfigurierbares Skript, das automatisch Zusammenfassungen, Vorspänne, Abspänne und Werbung überspringt und bei Netflix, Amazon Prime Video, Hulu, HBO Max, Starz, Disney+ und Hotstar auf die Aufforderung "nächste Episode" klickt. Anpassbarer Hotkey zum Anhalten/Fortsetzen der Auto-Skipping-Funktion. Alt + N für Einstellungen.
// @description:ru Настраиваемый сценарий, который автоматически пропускает резюме, вступление, титры и рекламу, а также нажимает подсказки «следующий выпуск» на Netflix, Amazon Prime Video, Hulu, HBO Max, Starz, Disney + и Hotstar. Настраиваемая горячая клавиша для приостановки / возобновления функции автоматического пропуска. Alt + N для настроек.
// @description:hi एक विन्यास योग्य स्क्रिप्ट जो स्वचालित रूप से रिकैप, इंट्रो, क्रेडिट और विज्ञापनों को छोड़ देती है, और नेटफ्लिक्स, अमेज़ॅन प्राइम वीडियो, हुलु, एचबीओ मैक्स, स्टारज़, डिज़नी + और हॉटस्टार पर "अगला एपिसोड" पर क्लिक करती है। ऑटो-स्किपिंग कार्यक्षमता को रोकने/फिर से शुरू करने के लिए अनुकूलन योग्य हॉटकी। सेटिंग्स के लिए Alt + N।
// @author aminomancer
// @homepageURL https://github.com/aminomancer/Netflix-Marathon-Pausable
// @supportURL https://github.com/aminomancer/Netflix-Marathon-Pausable
// @downloadURL https://greasyfork.org/scripts/420475-netflix-marathon-pausable/code/Netflix%20Marathon%20(Pausable).user.js
// @icon https://cdn.jsdelivr.net/gh/aminomancer/Netflix-Marathon-Pausable@latest/icon-small.svg
// @license CC-BY-NC-SA-4.0
// @match http*://*.amazon.ae/*
// @match http*://*.amazon.ca/*
// @match http*://*.amazon.cn/*
// @match http*://*.amazon.co.jp/*
// @match http*://*.amazon.co.uk/*
// @match http*://*.amazon.com/*
// @match http*://*.amazon.com.au/*
// @match http*://*.amazon.com.br/*
// @match http*://*.amazon.com.mx/*
// @match http*://*.amazon.de/*
// @match http*://*.amazon.eg/*
// @match http*://*.amazon.es/*
// @match http*://*.amazon.fr/*
// @match http*://*.amazon.in/*
// @match http*://*.amazon.it/*
// @match http*://*.amazon.nl/*
// @match http*://*.amazon.pl/*
// @match http*://*.amazon.sa/*
// @match http*://*.amazon.se/*
// @match http*://*.amazon.sg/*
// @match http*://*.amazon.tr/*
// @match http*://*.disneyplus.com/*
// @match http*://*.starplus.com/*
// @match http*://play.hbomax.com/*
// @match http*://play.max.com/*
// @match http*://*.hotstar.com/*
// @match http*://*.hulu.com/*
// @match http*://*.netflix.com/*
// @match http*://*.primevideo.com/*
// @match http*://*.starz.com/*
// @match http*://*.starz.ca/*
// @match http*://*.starzplay.com/*
// @require https://greasyfork.org/scripts/420683-gm-config-sizzle/code/GM_config_sizzle.js?version=894369
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_addValueChangeListener
// @grant GM_listValues
// @grant GM_openInTab
// @grant GM.setValue
// @grant GM.getValue
// @grant GM.deleteValue
// @grant GM.listValues
// @grant GM.openInTab
// ==/UserScript==
/* global GM, GM_registerMenuCommand, GM_unregisterMenuCommand,
GM_getValue:writable, GM_setValue:writable, GM_deleteValue:writable,
GM_addValueChangeListener, GM_removeValueChangeListener, GM_listValues:writable,
GM_openInTab:writable, WebFontConfig:writable, GM_config, WebFont */
const options = {}; // where settings are stored during runtime
// check if the script handler is GM4, since if it is, we can't add a menu command
const GM4 =
typeof window.GM?.getValue === "function" &&
GM.info.scriptHandler === "Greasemonkey" &&
GM.info.version.split(".")[0] >= 4;
const cdnAddress =
"https://cdn.jsdelivr.net/gh/aminomancer/Netflix-Marathon-Pausable@latest";
let marathon;
/**
* pause execution for n milliseconds
* @param {Number} ms milliseconds
* @returns {Promise} a promise that resolves after n milliseconds
*/
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
/**
* @param {String} u a string to test the URL against
* @returns {Boolean} true if the URL matches the string
*/
const test = u => window.location.href.includes(u);
const getHost = () => {
const urlParts = window.location.hostname.split(".");
const host = urlParts
.filter(part => {
switch (part) {
case "amazon":
case "primevideo":
case "disneyplus":
case "starplus":
case "hotstar":
case "hulu":
case "hbomax":
case "max":
case "netflix":
case "starz":
case "starzplay":
return true;
default:
return false;
}
})
.join();
// aliases for some sites
switch (host) {
case "primevideo":
return "amazon";
case "starplus":
return "disneyplus";
case "max":
return "hbomax";
case "starzplay":
return "starz";
default:
return host;
}
};
const site = getHost();
// some basic localization for the settings menu. just the parts necessary to
// get to the readme, which has chinese, japanese, and arabic translations
const l10n = {
/**
* get the locale language code (e.g. "en" for English)
* @returns {String} the first part of the user's current ISO 639-1 code
*/
get lang() {
// memoize the language since it's unlikely to change during runtime
if (!this._lang) this._lang = navigator.language.split("-")[0];
return this._lang;
},
/**
* get the label for the support button in settings
* @returns {String}
*/
get text() {
if (this._text) return this._text;
switch (this.lang) {
case "zh":
this._text = "信息"; // chinese
break;
case "ja":
this._text = "助けて"; // japanese
break;
case "ko":
this._text = "기술 지원"; // korean
break;
case "ar":
this._text = "تعليمات"; // arabic
break;
case "de":
this._text = "Hilfe"; // german
break;
case "ru":
this._text = "помощь"; // russian
break;
case "hi":
this._text = "तकनीकी समर्थन"; // hindi
break;
default:
this._text = "Support"; // english etc.
}
return this._text;
},
/**
* get the tooltip for the support button in settings
* @returns {String}
*/
get title() {
if (this._title) return this._title;
switch (this.lang) {
case "zh":
this._title = "设置的信息和翻译";
break;
case "ja":
this._title = "設定の情報と翻訳";
break;
case "ko":
this._title = "설정에 대한 정보 및 번역";
break;
case "ar":
this._title = "معلومات وترجمات للإعدادات";
break;
case "de":
this._title = "Infos und Übersetzungen zu den Einstellungen";
break;
case "ru":
this._title = "Информация и переводы для настроек";
break;
case "hi":
this._title = "सेटिंग्स के लिए जानकारी और अनुवाद";
break;
default:
this._title = "Info and translations for the settings";
}
return this._title;
},
};
const methods = {
// contains the site-specific callbacks and various utility functions
sites: [
"amazon",
"disneyplus",
"hotstar",
"hulu",
"hbomax",
"netflix",
"starz",
],
// how many times to skip the site callback before checking for elements
// again. if this is 0, the callback will run when the interval fires. if an
// element is found, we add 5 to this value to skip the callback for 5 more
// intervals, since after pressing a button, there usually won't be anything
// else to skip for a while. if an element is not found, we start subtracting
// from this value until it reaches 0 and the callback can run again.
skips: 0,
/**
* getElementsByTagName
* @param {String} s tag name to search for
* @returns {Array} an array of elements with the given tag name
*/
byTag: (s, p = document) => p.getElementsByTagName(s),
/**
* getElementById
* @param {String} s element id to search for
* @returns {Element} the element with the given id
*/
byID: s => document.getElementById(s),
/**
* querySelector
* @param {String} s CSS selector e.g. ".class" or "#id"
* @returns {Element} the first element matching the given CSS selector
*/
qry: (s, p = document) => p.querySelector(s),
/**
* querySelectorAll
* @param {String} s CSS selector e.g. ".class" or "#id"
* @returns {Array} an array of elements matching the given CSS selector
*/
qryAll: (s, p = document) => p.querySelectorAll(s),
/**
* find react instance given a DOM node
* @param {Object} d usually a DOM node, but can be a react instance
* @returns {Object} the react instance
*/
reactInstance(d = 0) {
for (const [key, value] of Object.entries(d)) {
if (key.startsWith("__reactInternalInstance$")) return value;
}
return null;
},
/**
* find react fiber given a DOM node
* @param {Object} d usually a DOM node, but can be a react instance
* @returns {Object} the react fiber
*/
reactFiber(d = 0) {
for (const [key, value] of Object.entries(d)) {
if (key.startsWith("__reactFiber$")) return value;
}
return null;
},
/**
* determine if an element is visible
* @param {Element} el the element to check
* @returns {Boolean} true if the element is visible
*/
isVisible(el) {
if (!el) return false;
try {
const { visibility, display } = getComputedStyle(el);
return !!(
el.offsetParent &&
!["hidden", "collapse"].includes(visibility) &&
display !== "none"
);
} catch (e) {
return false;
}
},
/**
* ensure the controller is not paused
* @returns {Boolean} true if the controller is not paused
*/
get isReady() {
return this.controller?.pauseState === 1;
},
/**
* clicks the passed element and sets the count to 5
* @param {Element|String} s element or CSS selector string
*/
clk(s, fn = s => s.click()) {
if (typeof s === "string") s = this.qry(s);
try {
fn(s);
this.skips = 5;
} catch (e) {
this.skips = 2;
}
},
/**
* pass a CSS selector string to locate a react component and invoke its
* onPress method. a trick to get around the fact that HBO tries to stop
* adblockers and other extensions from invoking Element.click(), etc.
* @param {Element|String} s element or CSS selector string
*/
hboPress(s) {
this.clk(s, s => this.reactFiber(s).return.return.memoizedProps.onPress());
},
/** Same as above but for play.max.com */
maxPress(s) {
this.clk(s, s => this.reactFiber(s).return.memoizedProps.onClick());
},
/**
* set a bunch of attributes on an element
* @param {Element} element the element to set attributes on
* @param {{[key: string]: string|void}} attrs key/value pairs for attributes.
* if the value is undefined, the attribute is removed.
*/
maybeSetAttributes(element, attrs = 0) {
for (const [name, value] of Object.entries(attrs)) {
if (value === undefined) element.removeAttribute(name);
else element.setAttribute(name, value);
}
},
/**
* create an element with given parameters
* @param {Document} doc which doc to create the element in
* @param {String} tag an HTML tag name, like "button" or "p"
* @param {Object} props an object containing attribute name/value pairs, e.g.
* {class: ".bookmark-item", id: "bookmark-item-1"}
* @returns {Element} the created element
*/
create(doc, tag, props) {
const el = doc.createElement(tag);
this.maybeSetAttributes(el, props);
return el;
},
// these are the site-specific callback methods. they search for elements that
// skip stuff. when the script is not paused, they are invoked on a timer.
amazon() {
if (this.skips !== 0) {
this.skips -= 1;
return;
}
if (!this.byID("dv-web-player")?.offsetParent) {
return;
}
// memoize the element when we check for its existence so we don't have to
// evaluate the DOM twice.
let store;
if (
options.skipCredits &&
!options.watchCredits &&
(store = this.qry(".atvwebplayersdk-nextupcard-button")) &&
// if the next up card is an episode, click it. otherwise, it's probably a
// movie promo, in which case we only click it if the user has enabled the
// promoted setting.
(this.qry(".atvwebplayersdk-nextupcard-episode", store) ||
options.promoted)
) {
this.clk(store);
return;
}
if ((store = this.qry(".atvwebplayersdk-skipelement-button"))) {
// skip various things
this.clk(store);
return;
}
if ((store = this.qry(".adSkipButton"))) {
// skip ad
this.clk(store);
return;
}
if ((store = this.qry(".skipElement"))) {
// skip intro
this.clk(store);
return;
}
if ((store = this.qry(".fu4rd6c"))) {
// skip ad button on some versions of amazon.
this.clk(store);
}
},
netflix() {
if (this.skips !== 0) {
this.skips -= 1;
return;
}
let store;
if (
options.skipCredits &&
!options.watchCredits &&
(store = this.qry(
"[data-uia='next-episode-seamless-button-draining'], [data-uia='next-episode-seamless-button']"
))
) {
// next episode button
this.reactFiber(store)?.memoizedProps.onClick?.();
this.skips = 5;
return;
}
if (
options.watchCredits &&
(store = this.qry("[data-uia='watch-credits-seamless-button']"))
) {
// watch credits button
this.reactFiber(store)?.memoizedProps.onClick?.();
this.skips = 10;
return;
}
if (
options.promoted &&
options.skipCredits &&
!options.watchCredits &&
(store = this.qry(".PromotedVideo-actions")?.firstElementChild)
) {
// promoted video autoplay
this.clk(store);
return;
}
if ((store = this.qry(".watch-video--skip-content-button"))) {
// skip intro, recap, etc.
this.clk(store);
return;
}
if ((store = this.qry(".watch-video--skip-preplay-button"))) {
// not sure what this does but I found this while trying to reverse
// engineer the source code. please inform me if you know
this.clk(store);
}
},
disneyplus() {
if (this.skips !== 0) {
this.skips -= 1;
return;
}
if (!test("/video/")) return;
let store;
if ((store = this.qry(".skip__button"))) {
// skip intro, skip recap, skip credits, etc.
this.clk(store);
return;
}
if (
options.skipCredits &&
!options.watchCredits &&
(store = this.qry('button[data-testid="up-next-play-button"]'))
) {
let skip = false;
// if options.promoted is enabled, we can autoplay disneyplus'
// recommendations after a film or the last episode in a series.
if (options.promoted) {
skip = true;
} else {
const react = this.reactInstance(
this.qry('[data-gv2containerkey="playerUpNext"]')
);
// if we're in a TV series, skip regardless of options.promoted
skip = react?.return?.memoizedProps?.asset?.programType === "episode";
}
if (skip) this.clk(store);
// if we're not skipping, don't search again for a while since the buttons
// are unlikely to change during a promoted title display.
else this.skips = 5;
}
},
hotstar() {
if (this.skips !== 0) {
this.skips -= 1;
return;
}
if (!test("/id/")) return;
let store;
if (
(store = this.qry(
".binge-btn-wrapper.show-btn .binge-btn.primary.medium"
))
) {
// skip intro, skip recap.
this.clk(store);
return;
}
if (
options.skipCredits &&
!options.watchCredits &&
(store = this.qry(
".binge-btn-wrapper.show-btn .binge-btn.secondary.filler"
))
) {
// skip outro or next episode immediately.
this.clk(store);
}
},
hulu() {
if (this.skips !== 0) {
this.skips -= 1;
return;
}
if (!test("/watch/")) return;
const controls = this.qry(".ControlsContainer");
if (!controls) {
// this means the whole video interface is gone for some reason
this.skips = 10;
return;
}
const controlProps = this.reactInstance(controls)?.return?.memoizedProps;
if (!controlProps) return; // this shouldn't happen either
if (controlProps.isSkipButtonShown) {
// skip intro, skip recap, skip ad, etc.
this.clk(this.qry(".SkipButton button"));
return;
}
if (
options.skipCredits &&
!options.watchCredits &&
controlProps.isEndCardVisible &&
controlProps.endCardType !== "none"
) {
// next episode
this.clk(this.qry(".EndCardButton"));
return;
}
if (
options.skipCredits &&
!options.watchCredits &&
options.promoted &&
controlProps.isOverlayVisible &&
controlProps.endCardType === "legacy"
) {
// autoplay promoted title
this.clk(this.qry(".end-card__metadata-area-play-button"));
}
},
async hbomax() {
if (this.skips !== 0) {
this.skips -= 1;
return;
}
if (test("play.max.com/video/watch/")) {
const overlay = this.qry("#overlay-root");
if (!overlay) {
// this means the whole video interface is gone for some reason
this.skips = 10;
return;
}
let store;
if (
this.isVisible((store = this.qry('[data-testid="skip"]', overlay))) &&
(store = this.qry('button[data-testid="player-ux-skip-button"]', store))
) {
// skip intro, skip recap, skip ad, etc.
this.maxPress(store);
return;
}
if (
options.skipCredits &&
!options.watchCredits &&
this.isVisible(
(store = this.qry('[data-testid="up_next"]', overlay))
) &&
(store = this.qry(
'button[data-testid="player-ux-up-next-button"]',
store
))
) {
// next episode
const fiber = this.reactFiber(store.parentElement);
const nextEpisode = fiber?.return?.return?.memoizedProps?.nextEpisode;
if (
nextEpisode?.episodeNumber || // tv series
(options.promoted && nextEpisode?.id) // promoted film/series
) {
this.maxPress(store);
return;
}
}
// TODO - see if you can reproduce actual ads, where skip/seek controls
// are disabled. account has ads disabled so can't test. if you check the
// source code in the debugger, there's a requestSkip() method that's
// disabled for ads, but it should be possible to call the underlying
// mediator.skip() method instead, assuming we can get a reference to any
// of this stuff.
return;
}
if (test("/player/")) {
try {
const viewHandle = this.byID("rn-video");
const fiber = this.reactFiber(viewHandle);
const player = fiber.return.return.memoizedProps.videoPlayer;
const uiData = player._uiManager._uiState.uiData;
if (uiData.activeSkipAnnotation) {
// skip intro, skip recap, skip ad, etc.
this.hboPress('[data-testid="SkipButton"]');
return;
}
if (
options.skipCredits &&
!options.watchCredits &&
uiData.activeNextEpisodeInfo
) {
// next episode
try {
const interactionHandler =
viewHandle.parentElement.lastElementChild;
this.reactFiber(
interactionHandler
).return.return.memoizedProps.onMouseMove();
await sleep(400);
} finally {
if (this.isReady) this.hboPress('[data-testid="UpNextButton"]');
}
}
} catch (e) {
this.skips = 10;
}
}
},
starz() {
if (this.skips !== 0) {
this.skips -= 1;
return;
}
if (!test("/play/") || !this.byTag("starz-player")[0]) {
return;
}
let store;
if (
options.skipCredits &&
!options.watchCredits &&
(store = this.qry(".auto-roll-component.open .next-feature-image"))
) {
// next episode - this is the only one I know of
this.clk(store);
return;
}
if (this.qry(".preroll-prefix-container")) {
// skip to the end of the preroll ad
const video = this.qry("starz-video video");
if (video) {
video.currentTime = video.duration;
return;
}
}
if ((store = this.qry("starz-termsofuse-banner .close-button"))) {
// skip the terms of use banner since it keeps coming back
this.clk(store);
}
},
};
// creates an interval for a given callback manager (the methods object) and the
// various methods for interacting with the interval (pause, resume, etc.) and
// the popup that shows when the interval has been paused or resumed.
class MarathonController {
/**
* pausable interval utility
* @param {Object} handler object containing the site methods
* @param {Number} int how often to repeat the callback
* @return {Object} the controller object
*/
constructor(handler, int) {
this.callback = handler[site].bind(handler); // e.g. methods.amazon.bind(methods)
handler.controller = this; // for reference in the methods object
this.handler = handler; // e.g. methods
this.int = int; // can be changed in real-time and the next resume() call will use the new value
this.popup = document.createElement("div");
this.text = document.createTextNode("Marathon: Paused");
this.remainder = 0; // how much time is remaining on the interval when we pause it
this.fading = null; // 3 second timeout (by default), after which the popup fades
this.toggle = this.toggle.bind(this);
this.onInterval = this.onInterval.bind(this);
this.onPauseChange = this.onPauseChange.bind(this);
this.registerCommand("Pause Marathon", true); // initial creation of the menu command
GM_addValueChangeListener("Marathon:paused", this.onPauseChange);
// if popup is enabled in options, style it
if (options.pop) this.updatePopup();
this.time = Date.now();
switch (this.pauseState) {
case MarathonController.STATES.RUNNING:
this.timer = window.setTimeout(this.onInterval, this.int);
break;
case MarathonController.STATES.PAUSED:
this.registerCommand("Resume Marathon"); // update the menu command label
this.remainder = this.int - (Date.now() - this.time);
break;
default:
GM_setValue("Marathon:paused", MarathonController.STATES.RUNNING);
}
this.startCapturing();
}
static STATES = {
IDLE: 0,
RUNNING: 1,
PAUSED: 2,
};
/**
* check that the modifier keys pressed match those defined in user settings
* @param {KeyboardEvent} e
* @param {String} i which key settings to evaluate, ctrlKey or ctrlKey2
* @return {Boolean} true if the keys match, false otherwise
*/
static modTest(e, i = "") {
return ["ctrlKey", "altKey", "shiftKey", "metaKey"].every(
key => e[key] === options[`${key}${i}`]
);
}
/**
* Controller's event handler. only handles keydown currently.
* @param {UIEvent} e
*/
handleEvent(e) {
switch (e.type) {
case "keydown":
this.onKeyDown(e);
break;
default:
}
}
/**
* implementation for hotkeys
* @param {KeyboardEvent} e
*/
onKeyDown(e) {
if (e.repeat) return;
const { code, code2, hotkey, hotkey2 } = options;
switch (e.code) {
case code:
if (hotkey && MarathonController.modTest(e)) this.toggle();
else return;
break;
case code2:
if (hotkey2 && MarathonController.modTest(e, 2)) {
GM_config.isOpen ? GM_config.close() : GM_config.open();
} else {
return;
}
break;
default:
return;
}
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
}
// invoke the site handler, wait for it to complete, then restart the timer.
async onInterval() {
if (!options[site]) return;
try {
if (this.pauseState === MarathonController.STATES.RUNNING) {
await this.callback();
}
} finally {
window.clearTimeout(this.timer);
this.timer = window.setTimeout(this.onInterval, this.int);
}
}
/**
* pause the interval
* @param {String} msg string or null — determines the popup text
*/
pause(msg) {
if (this.pauseState === MarathonController.STATES.RUNNING) {
GM_setValue("Marathon:paused", MarathonController.STATES.PAUSED);
this.openPopup(msg);
}
}
/**
* resume the interval
* @param {String} msg string or null — determines the popup text
*/
async resume(msg) {
if (this.pauseState === MarathonController.STATES.PAUSED) {
GM_setValue("Marathon:paused", MarathonController.STATES.RUNNING);
this.openPopup(msg);
}
}
/**
* Control the interval in response to changes to the pause state
* @param {string} name value name - "Marathon:paused"
* @param {number|undefined} oldValue
* @param {number|undefined} newValue
*/
async onPauseChange(name, oldValue, newValue) {
this._pauseState = newValue;
if (oldValue === newValue || !options[site]) return;
switch (newValue) {
case MarathonController.STATES.RUNNING:
if (oldValue === MarathonController.STATES.PAUSED) {
this.registerCommand("Pause Marathon");
await sleep(this.remainder);
this.time = Date.now();
this.onInterval();
} else {
window.clearTimeout(this.timer);
this.timer = window.setTimeout(this.onInterval, this.int);
}
break;
case MarathonController.STATES.PAUSED:
this.registerCommand("Resume Marathon"); // update the menu command label
this.remainder = this.int - (Date.now() - this.time);
window.clearTimeout(this.timer);
break;
default:
}
}
get pauseState() {
if (this._pauseState === undefined) {
this._pauseState = GM_getValue(
"Marathon:paused",
MarathonController.STATES.IDLE
);
}
return this._pauseState;
}
// toggle the interval on/off.
toggle() {
if (!options[site]) return; // disable the pause/resume toggle when the site is disabled
switch (this.pauseState) {
case MarathonController.STATES.RUNNING:
this.pause("Paused"); // passing "Paused" tells openPopup to use the "Marathon: Paused" message
break;
case MarathonController.STATES.PAUSED:
this.resume("Resumed"); // passing "Resumed" => "Marathon: Resumed" message
break;
default:
}
}
/**
* opens the popup (and optionally schedules it to close)
* @param {String} msg what the popup should say
* @param {Boolean} [stayOpen] whether to keep the popup open until dismissed
* @returns {closedPromise|hide|null} if !stayOpen, returns a promise that
* resolves when the popup fades out. if stayOpen, returns a function
* that can be called to hide the popup, which returns a closing
* promise. returns null if popups are disabled or msg is not passed.
*/
openPopup(msg, stayOpen = false) {
// if popup is disabled in options, or no message was sent, do nothing
if (msg === undefined || !options.pop) return null;
const { style } = this.popup;
this.popup.textContent = `Marathon: ${msg}`;
style.transitionDuration = "0.2s";
style.opacity = "1";
window.clearTimeout(this.fading); // clear any existing fade timeout since we're about to set a new one
/** @typedef {Promise<undefined>} */
const closedPromise = new Promise(resolve =>
this.popup.addEventListener("transitionend", resolve, { once: true })
);
/** @typedef {function():closedPromise} */
const hide = () => {
style.transitionDuration = "1s";
style.opacity = "0";
return closedPromise;
};
if (stayOpen) return hide;
// schedule the popup to fade into oblivion
this.fading = window.setTimeout(hide, options.popDur);
return closedPromise;
}
// apply the basic popup style and place it in the body
setupPopup() {
if (this.isPopupSetup) return;
document.body.insertBefore(this.popup, document.body.firstElementChild);
this.popup.appendChild(this.text);
this.popup.style.cssText = `position:fixed;top:50%;right:3%;transform:translateY(-50%);z-index:2147483646;background-color:hsla(0,0%,6%,.8);background-image:url("${cdnAddress}/texture/noise-512x512.png");background-repeat:repeat;background-size:auto;background-attachment:local;-webkit-backdrop-filter:blur(7px);backdrop-filter:blur(7px);color:hsla(0,0%,97%,.95);padding:17px 19px;line-height:1em;border-radius:5px;pointer-events:none;letter-spacing:1px;transition:opacity .2s ease-in-out;opacity:0;`;
this.isPopupSetup = true;
}
// update the mutable popup attributes
updatePopup() {
this.setupPopup();
const { style } = this.popup;
style.fontFamily = options.font;
style.fontSize = `${options.fontSizeInt}px`;
style.fontWeight = options.fontWeight;
style.fontStyle = options.italic ? "italic" : "";
}
/**
* register a menu command with the script manager, or update an existing one
* @param {String} cap intended caption to display on the menu command
* @param {Boolean} firstRun we call this function at startup and every time
* we pause/unpause. on the first call, we register
* a command. on subsequent calls, we unregister the
* previous command and register a new one.
*/
registerCommand(cap, firstRun = false) {
if (GM4) return; // don't register a menu command if the script manager is greasemonkey 4.0+ since the function doesn't exist
if (!firstRun) GM_unregisterMenuCommand(this.caption); // this is how we switch the menu command from play to pause. we'd prefer to just have a single menu command and use a variable to determine its label and callback behavior, but the API doesn't support that afaik.
// don't register the pause/unpause menu command if the site is currently disabled
if (options[site]) {
GM_registerMenuCommand(cap, this.toggle);
this.caption = cap;
}
}
// start listening to key events
startCapturing() {
if (!this.capturing && (options.hotkey || options.hotkey2)) {
window.addEventListener("keydown", this, true);
this.capturing = true;
}
}
// stop listening to key events
stopCapturing() {
if (this.capturing) {
window.removeEventListener("keydown", this, true);
this.capturing = false;
}
}
}
// override API functions so we can animate the settings panel and auto-close it on save.
function extendGMC() {
// support fancy animations
GM_config.close = function close() {
window.clearTimeout(this.fading);
this.frame.setAttribute("closed", true);
this.onClose(); // Call the close() callback function
this.isOpen = false;
this.fading = window.setTimeout(() => {
this.clearSheets("Marathon");
// If frame is an iframe then remove it
if (this.frame.contentDocument) {
this.remove(this.frame);
this.frame = null;
} else {
// else wipe its content
this.frame.innerHTML = "";
this.frame.style.display = "none";
}
// Null out all the fields so we don't leak memory
const { fields } = this;
for (const value of Object.values(fields)) {
value.wrapper = null;
value.node = null;
}
}, 500);
};
GM_config.open = function open() {
window.clearTimeout(this.fading);
this.frame.removeAttribute("closed");
this.isOpen = true;
Object.getPrototypeOf(this).open.call(this);
};
// override write function to semi-publicly memoize the error state.
GM_config.write = function write(store, obj) {
const values = {};
const forgotten = {};
if (!obj) {
const { fields } = this;
for (const [id, field] of Object.entries(fields)) {
const value = field.toValue();
if (field.save) {
if (value != null) {
values[id] = value;
field.value = value;
} else {
this.error = true;
values[id] = field.value;
}
} else {
forgotten[id] = value;
}