-
-
Notifications
You must be signed in to change notification settings - Fork 301
/
content.ts
2671 lines (2250 loc) · 100 KB
/
content.ts
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
import Config from "./config";
import {
ActionType,
Category,
CategorySkipOption,
ChannelIDInfo,
ChannelIDStatus,
ContentContainer,
HashedValue,
Keybind,
PageType,
ScheduledTime,
SegmentUUID,
SkipToTimeParams,
SponsorHideType,
SponsorSourceType,
SponsorTime,
StorageChangesObject,
ToggleSkippable,
VideoID,
VideoInfo,
} from "./types";
import Utils from "./utils";
import PreviewBar, { PreviewBarSegment } from "./js-components/previewBar";
import SkipNotice from "./render/SkipNotice";
import SkipNoticeComponent from "./components/SkipNoticeComponent";
import SubmissionNotice from "./render/SubmissionNotice";
import { Message, MessageResponse, VoteResponse } from "./messageTypes";
import { SkipButtonControlBar } from "./js-components/skipButtonControlBar";
import { getStartTimeFromUrl } from "./utils/urlParser";
import { findValidElement, getControls, getExistingChapters, getHashParams, isVisible } from "./utils/pageUtils";
import { isSafari, keybindEquals } from "./utils/configUtils";
import { CategoryPill } from "./render/CategoryPill";
import { AnimationUtils } from "./utils/animationUtils";
import { GenericUtils } from "./utils/genericUtils";
import { logDebug } from "./utils/logger";
import { importTimes } from "./utils/exporter";
import { ChapterVote } from "./render/ChapterVote";
import { openWarningDialog } from "./utils/warnings";
import { Tooltip } from "./render/Tooltip";
import { noRefreshFetchingChaptersAllowed } from "./utils/licenseKey";
import { waitFor } from "@ajayyy/maze-utils";
import { getFormattedTime } from "@ajayyy/maze-utils/lib/formating";
const utils = new Utils();
// Hack to get the CSS loaded on permission-based sites (Invidious)
utils.wait(() => Config.config !== null, 5000, 10).then(addCSS);
const skipBuffer = 0.003;
//was sponsor data found when doing SponsorsLookup
let sponsorDataFound = false;
//the actual sponsorTimes if loaded and UUIDs associated with them
let sponsorTimes: SponsorTime[] = [];
let existingChaptersImported = false;
//what video id are these sponsors for
let sponsorVideoID: VideoID = null;
// List of open skip notices
const skipNotices: SkipNotice[] = [];
let activeSkipKeybindElement: ToggleSkippable = null;
let retryFetchTimeout: NodeJS.Timeout = null;
let shownSegmentFailedToFetchWarning = false;
// JSON video info
let videoInfo: VideoInfo = null;
// Page Type - browse/watch etc...
let pageType: PageType;
// if video is live or premiere
let isLivePremiere: boolean
// The channel this video is about
let channelIDInfo: ChannelIDInfo;
// Locked Categories in this tab, like: ["sponsor","intro","outro"]
let lockedCategories: Category[] = [];
// Used to calculate a more precise "virtual" video time
const lastKnownVideoTime: { videoTime: number; preciseTime: number; fromPause: boolean; approximateDelay: number } = {
videoTime: null,
preciseTime: null,
fromPause: false,
approximateDelay: null,
};
// It resumes with a slightly later time on chromium
let lastTimeFromWaitingEvent: number = null;
const lastNextChapterKeybind = {
time: 0,
date: 0
};
// Skips are scheduled to ensure precision.
// Skips are rescheduled every seeking event.
// Skips are canceled every seeking event
let currentSkipSchedule: NodeJS.Timeout = null;
let currentSkipInterval: NodeJS.Timeout = null;
let currentVirtualTimeInterval: NodeJS.Timeout = null;
/** Has the sponsor been skipped */
let sponsorSkipped: boolean[] = [];
//the video
let video: HTMLVideoElement;
let videoMuted = false; // Has it been attempted to be muted
let videoMutationObserver: MutationObserver = null;
let waitingForNewVideo = false;
// List of videos that have had event listeners added to them
const videosWithEventListeners: HTMLVideoElement[] = [];
const controlsWithEventListeners: HTMLElement[] = []
// This misleading variable name will be fixed soon
let onInvidious: boolean;
let onMobileYouTube: boolean;
//the video id of the last preview bar update
let lastPreviewBarUpdate: VideoID;
// Is the video currently being switched
let switchingVideos = null;
// Used by the play and playing listeners to make sure two aren't
// called at the same time
let lastCheckTime = 0;
let lastCheckVideoTime = -1;
//is this channel whitelised from getting sponsors skipped
let channelWhitelisted = false;
let waitingForChannelID = false;
let previewBar: PreviewBar = null;
// Skip to highlight button
let skipButtonControlBar: SkipButtonControlBar = null;
// For full video sponsors/selfpromo
let categoryPill: CategoryPill = null;
/** Element containing the player controls on the YouTube player. */
let controls: HTMLElement | null = null;
/** Contains buttons created by `createButton()`. */
const playerButtons: Record<string, {button: HTMLButtonElement; image: HTMLImageElement; setupListener: boolean}> = {};
// Direct Links after the config is loaded
utils.wait(() => Config.config !== null, 1000, 1).then(() => videoIDChange(getYouTubeVideoID(document)));
// wait for hover preview to appear, and refresh attachments if ever found
utils.waitForElement(".ytp-inline-preview-ui").then(() => refreshVideoAttachments());
utils.waitForElement("a.ytp-title-link[data-sessionlink='feature=player-title']")
.then(() => videoIDChange(getYouTubeVideoID(document)));
addPageListeners();
addHotkeyListener();
/** Segments created by the user which have not yet been submitted. */
let sponsorTimesSubmitting: SponsorTime[] = [];
let loadedPreloadedSegment = false;
//becomes true when isInfoFound is called
//this is used to close the popup on YouTube when the other popup opens
let popupInitialised = false;
let submissionNotice: SubmissionNotice = null;
// If there is an advert playing (or about to be played), this is true
let isAdPlaying = false;
let lastResponseStatus: number;
let retryCount = 0;
let lookupWaiting = false;
// Contains all of the functions and variables needed by the skip notice
const skipNoticeContentContainer: ContentContainer = () => ({
vote,
dontShowNoticeAgain,
unskipSponsorTime,
sponsorTimes,
sponsorTimesSubmitting,
skipNotices,
v: video,
sponsorVideoID,
reskipSponsorTime,
updatePreviewBar,
onMobileYouTube,
sponsorSubmissionNotice: submissionNotice,
resetSponsorSubmissionNotice,
updateEditButtonsOnPlayer,
previewTime,
videoInfo,
getRealCurrentTime: getRealCurrentTime,
lockedCategories,
channelIDInfo
});
// value determining when to count segment as skipped and send telemetry to server (percent based)
const manualSkipPercentCount = 0.5;
//get messages from the background script and the popup
chrome.runtime.onMessage.addListener(messageListener);
function messageListener(request: Message, sender: unknown, sendResponse: (response: MessageResponse) => void): void | boolean {
//messages from popup script
switch(request.message){
case "update":
videoIDChange(getYouTubeVideoID(document));
break;
case "sponsorStart":
startOrEndTimingNewSegment()
sendResponse({
creatingSegment: isSegmentCreationInProgress(),
});
break;
case "isInfoFound":
//send the sponsor times along with if it's found
sendResponse({
found: sponsorDataFound,
status: lastResponseStatus,
sponsorTimes: sponsorTimes,
time: video.currentTime,
onMobileYouTube
});
if (!request.updating && popupInitialised && document.getElementById("sponsorBlockPopupContainer") != null) {
//the popup should be closed now that another is opening
closeInfoMenu();
}
popupInitialised = true;
break;
case "getVideoID":
sendResponse({
videoID: sponsorVideoID,
});
break;
case "getChannelID":
sendResponse({
channelID: channelIDInfo.id
});
break;
case "isChannelWhitelisted":
sendResponse({
value: channelWhitelisted
});
break;
case "whitelistChange":
channelWhitelisted = request.value;
sponsorsLookup();
break;
case "submitTimes":
submitSponsorTimes();
break;
case "refreshSegments":
// update video on refresh if videoID invalid
if (!sponsorVideoID) videoIDChange(getYouTubeVideoID(document));
// fetch segments
sponsorsLookup(false);
break;
case "unskip":
unskipSponsorTime(sponsorTimes.find((segment) => segment.UUID === request.UUID), null, true);
break;
case "reskip":
reskipSponsorTime(sponsorTimes.find((segment) => segment.UUID === request.UUID), true);
break;
case "submitVote":
vote(request.type, request.UUID).then((response) => sendResponse(response));
return true;
case "hideSegment":
utils.getSponsorTimeFromUUID(sponsorTimes, request.UUID).hidden = request.type;
utils.addHiddenSegment(sponsorVideoID, request.UUID, request.type);
updatePreviewBar();
if (skipButtonControlBar?.isEnabled()
&& sponsorTimesSubmitting.every((s) => s.hidden !== SponsorHideType.Visible || s.actionType !== ActionType.Poi)) {
skipButtonControlBar.disable();
}
break;
case "closePopup":
closeInfoMenu();
break;
case "copyToClipboard":
navigator.clipboard.writeText(request.text);
break;
case "importSegments": {
const importedSegments = importTimes(request.data, video.duration);
let addedSegments = false;
for (const segment of importedSegments) {
if (!sponsorTimesSubmitting.some(
(s) => Math.abs(s.segment[0] - segment.segment[0]) < 1
&& Math.abs(s.segment[1] - segment.segment[1]) < 1)) {
if (segment.category === "chapter" && !utils.getCategorySelection("chapter")) {
segment.category = "chooseACategory" as Category;
segment.actionType = ActionType.Skip;
segment.description = "";
}
sponsorTimesSubmitting.push(segment);
addedSegments = true;
}
}
if (addedSegments) {
Config.config.unsubmittedSegments[sponsorVideoID] = sponsorTimesSubmitting;
Config.forceSyncUpdate("unsubmittedSegments");
updateEditButtonsOnPlayer();
updateSponsorTimesSubmitting(false);
submitSponsorTimes();
}
sendResponse({
importedSegments
});
break;
}
case "keydown":
(document.body || document).dispatchEvent(new KeyboardEvent('keydown', {
key: request.key,
keyCode: request.keyCode,
code: request.code,
which: request.which,
shiftKey: request.shiftKey,
ctrlKey: request.ctrlKey,
altKey: request.altKey,
metaKey: request.metaKey
}));
break;
}
sendResponse({});
}
/**
* Called when the config is updated
*/
function contentConfigUpdateListener(changes: StorageChangesObject) {
for (const key in changes) {
switch(key) {
case "hideVideoPlayerControls":
case "hideInfoButtonPlayerControls":
case "hideDeleteButtonPlayerControls":
updateVisibilityOfPlayerControlsButton()
break;
case "categorySelections":
sponsorsLookup();
break;
}
}
}
if (!Config.configSyncListeners.includes(contentConfigUpdateListener)) {
Config.configSyncListeners.push(contentConfigUpdateListener);
}
function resetValues() {
lastCheckTime = 0;
lastCheckVideoTime = -1;
retryCount = 0;
sponsorTimes = [];
existingChaptersImported = false;
sponsorSkipped = [];
lastResponseStatus = 0;
shownSegmentFailedToFetchWarning = false;
sponsorVideoID = null;
videoInfo = null;
pageType = null;
channelWhitelisted = false;
channelIDInfo = {
status: ChannelIDStatus.Fetching,
id: null
};
lockedCategories = [];
isLivePremiere = false;
//empty the preview bar
if (previewBar !== null) {
previewBar.clear();
}
//reset sponsor data found check
sponsorDataFound = false;
if (switchingVideos === null) {
// When first loading a video, it is not switching videos
switchingVideos = false;
} else {
switchingVideos = true;
logDebug("Setting switching videos to true (reset data)");
}
// Reset advert playing flag
isAdPlaying = false;
skipButtonControlBar?.disable();
categoryPill?.setVisibility(false);
for (let i = 0; i < skipNotices.length; i++) {
skipNotices.pop()?.close();
}
}
async function videoIDChange(id: string): Promise<void> {
// don't switch to invalid value
if (!id && sponsorVideoID && !document?.URL?.includes("youtube.com/clip/")) return;
//if the id has not changed return unless the video element has changed
if (sponsorVideoID === id && (isVisible(video) || !video)) return;
resetValues();
sponsorVideoID = id;
//id is not valid
if (!id) return;
// Wait for options to be ready
await utils.wait(() => Config.config !== null, 5000, 1);
// If enabled, it will check if this video is private or unlisted and double check with the user if the sponsors should be looked up
if (Config.config.checkForUnlistedVideos) {
const shouldContinue = confirm("SponsorBlock: You have the setting 'Ignore Unlisted/Private Videos' enabled."
+ " Due to a change in how segment fetching works, this setting is not needed anymore as it cannot leak your video ID to the server."
+ " It instead sends just the first 4 characters of a longer hash of the videoID to the server, and filters through a subset of the database."
+ " More info about this implementation can be found here: https://github.com/ajayyy/SponsorBlockServer/issues/25"
+ "\n\nPlease click okay to confirm that you acknowledge this and continue using SponsorBlock.");
if (shouldContinue) {
Config.config.checkForUnlistedVideos = false;
} else {
return;
}
}
// Update whitelist data when the video data is loaded
whitelistCheck();
//setup the preview bar
if (previewBar === null) {
if (onMobileYouTube) {
// Mobile YouTube workaround
const observer = new MutationObserver(handleMobileControlsMutations);
let controlsContainer = null;
utils.wait(() => {
controlsContainer = document.getElementById("player-control-container")
return controlsContainer !== null
}).then(() => {
observer.observe(document.getElementById("player-control-container"), {
attributes: true,
childList: true,
subtree: true
});
}).catch();
} else {
utils.wait(getControls).then(createPreviewBar);
}
}
// Notify the popup about the video change
chrome.runtime.sendMessage({
message: "videoChanged",
videoID: sponsorVideoID,
whitelisted: channelWhitelisted
});
sponsorsLookup();
// Make sure all player buttons are properly added
updateVisibilityOfPlayerControlsButton();
// Clear unsubmitted segments from the previous video
sponsorTimesSubmitting = [];
updateSponsorTimesSubmitting();
}
function handleMobileControlsMutations(): void {
updateVisibilityOfPlayerControlsButton();
skipButtonControlBar?.updateMobileControls();
if (previewBar !== null) {
if (document.body.contains(previewBar.container)) {
const progressBarBackground = document.querySelector<HTMLElement>(".progress-bar-background");
if (progressBarBackground !== null) {
updatePreviewBarPositionMobile(progressBarBackground);
}
return;
} else {
// The container does not exist anymore, remove that old preview bar
previewBar.remove();
previewBar = null;
}
}
// Create the preview bar if needed (the function hasn't returned yet)
createPreviewBar();
}
/**
* Creates a preview bar on the video
*/
function createPreviewBar(): void {
if (previewBar !== null) return;
const progressElementOptions = [{
// For mobile YouTube
selector: ".progress-bar-background",
isVisibleCheck: true
}, {
// For new mobile YouTube (#1287)
selector: ".progress-bar-line",
isVisibleCheck: true
}, {
// For Desktop YouTube
selector: ".ytp-progress-bar",
isVisibleCheck: true
}, {
// For Desktop YouTube
selector: ".no-model.cue-range-marker",
isVisibleCheck: true
}, {
// For Invidious/VideoJS
selector: ".vjs-progress-holder",
isVisibleCheck: false
}, {
// For Youtube Music
// there are two sliders, one for volume and one for progress - both called #progressContainer
selector: "#progress-bar>#sliderContainer>div>#sliderBar>#progressContainer",
}, {
// For piped
selector: ".shaka-ad-markers",
isVisibleCheck: false
}
];
for (const option of progressElementOptions) {
const allElements = document.querySelectorAll(option.selector) as NodeListOf<HTMLElement>;
const el = option.isVisibleCheck ? findValidElement(allElements) : allElements[0];
if (el) {
const chapterVote = new ChapterVote(voteAsync);
previewBar = new PreviewBar(el, onMobileYouTube, onInvidious, chapterVote, () => importExistingChapters(false));
updatePreviewBar();
break;
}
}
}
/**
* Triggered every time the video duration changes.
* This happens when the resolution changes or at random time to clear memory.
*/
function durationChangeListener(): void {
updateAdFlag();
updatePreviewBar();
}
/**
* Triggered once the video is ready.
* This is mainly to attach to embedded players who don't have a video element visible.
*/
function videoOnReadyListener(): void {
createPreviewBar();
updatePreviewBar();
updateVisibilityOfPlayerControlsButton()
}
function cancelSponsorSchedule(): void {
logDebug("Pausing skipping");
if (currentSkipSchedule !== null) {
clearTimeout(currentSkipSchedule);
currentSkipSchedule = null;
}
if (currentSkipInterval !== null) {
clearInterval(currentSkipInterval);
currentSkipInterval = null;
}
}
/**
* @param currentTime Optional if you don't want to use the actual current time
*/
function startSponsorSchedule(includeIntersectingSegments = false, currentTime?: number, includeNonIntersectingSegments = true): void {
cancelSponsorSchedule();
// Don't skip if advert playing and reset last checked time
if (isAdPlaying) {
// Reset lastCheckVideoTime
lastCheckVideoTime = -1;
lastCheckTime = 0;
logDebug("[SB] Ad playing, pausing skipping");
return;
}
// ensure we are on the correct video
const newVideoID = getYouTubeVideoID(document);
if (newVideoID !== sponsorVideoID) {
videoIDChange(newVideoID);
return;
}
logDebug(`Considering to start skipping: ${!video}, ${video?.paused}`);
if (!video) return;
if (currentTime === undefined || currentTime === null) {
currentTime = getVirtualTime();
}
clearWaitingTime();
lastTimeFromWaitingEvent = null;
updateActiveSegment(currentTime);
if (video.paused) return;
const skipInfo = getNextSkipIndex(currentTime, includeIntersectingSegments, includeNonIntersectingSegments);
const currentSkip = skipInfo.array[skipInfo.index];
const skipTime: number[] = [currentSkip?.scheduledTime, skipInfo.array[skipInfo.endIndex]?.segment[1]];
const timeUntilSponsor = skipTime?.[0] - currentTime;
const videoID = sponsorVideoID;
if (videoMuted && !inMuteSegment(currentTime, skipInfo.index !== -1
&& timeUntilSponsor < skipBuffer && shouldAutoSkip(currentSkip))) {
video.muted = false;
videoMuted = false;
for (const notice of skipNotices) {
// So that the notice can hide buttons
notice.unmutedListener(currentTime);
}
}
logDebug(`Ready to start skipping: ${skipInfo.index} at ${currentTime}`);
if (skipInfo.index === -1) return;
if (Config.config.disableSkipping || channelWhitelisted || (channelIDInfo.status === ChannelIDStatus.Fetching && Config.config.forceChannelCheck)){
return;
}
if (incorrectVideoCheck()) return;
// Find all indexes in between the start and end
let skippingSegments = [skipInfo.array[skipInfo.index]];
if (skipInfo.index !== skipInfo.endIndex) {
skippingSegments = [];
for (const segment of skipInfo.array) {
if (shouldAutoSkip(segment) &&
segment.segment[0] >= skipTime[0] && segment.segment[1] <= skipTime[1]
&& segment.segment[0] === segment.scheduledTime) { // Don't include artifical scheduled segments (end times for mutes)
skippingSegments.push(segment);
}
}
}
logDebug(`Next step in starting skipping: ${!shouldSkip(currentSkip)}, ${!sponsorTimesSubmitting?.some((segment) => segment.segment === currentSkip.segment)}`);
const skippingFunction = (forceVideoTime?: number) => {
let forcedSkipTime: number = null;
let forcedIncludeIntersectingSegments = false;
let forcedIncludeNonIntersectingSegments = true;
if (incorrectVideoCheck(videoID, currentSkip)) return;
forceVideoTime ||= Math.max(video.currentTime, getVirtualTime());
if ((shouldSkip(currentSkip) || sponsorTimesSubmitting?.some((segment) => segment.segment === currentSkip.segment))) {
if (forceVideoTime >= skipTime[0] - skipBuffer && forceVideoTime < skipTime[1]) {
skipToTime({
v: video,
skipTime,
skippingSegments,
openNotice: skipInfo.openNotice
});
// These are segments that start at the exact same time but need seperate notices
for (const extra of skipInfo.extraIndexes) {
const extraSkip = skipInfo.array[extra];
if (shouldSkip(extraSkip)) {
skipToTime({
v: video,
skipTime: [extraSkip.scheduledTime, extraSkip.segment[1]],
skippingSegments: [extraSkip],
openNotice: skipInfo.openNotice
});
}
}
if (utils.getCategorySelection(currentSkip.category)?.option === CategorySkipOption.ManualSkip
|| currentSkip.actionType === ActionType.Mute) {
forcedSkipTime = skipTime[0] + 0.001;
} else {
forcedSkipTime = skipTime[1];
forcedIncludeIntersectingSegments = true;
forcedIncludeNonIntersectingSegments = false;
}
} else {
forcedSkipTime = forceVideoTime + 0.001;
}
} else {
forcedSkipTime = forceVideoTime + 0.001;
}
startSponsorSchedule(forcedIncludeIntersectingSegments, forcedSkipTime, forcedIncludeNonIntersectingSegments);
};
if (timeUntilSponsor < skipBuffer) {
skippingFunction(currentTime);
} else {
const delayTime = timeUntilSponsor * 1000 * (1 / video.playbackRate);
if (delayTime < 300) {
// Use interval instead of timeout near the end to combat imprecise video time
const startIntervalTime = performance.now();
const startVideoTime = Math.max(currentTime, video.currentTime);
let startWaitingForReportedTimeToChange = true;
const reportedVideoTimeAtStart = video.currentTime;
logDebug(`Starting setInterval skipping ${video.currentTime} to skip at ${skipTime[0]}`);
currentSkipInterval = setInterval(() => {
// Estimate delay, but only take the current time right after a change
// Current time remains the same for many "frames" on Firefox
if (utils.isFirefox() && !lastKnownVideoTime.fromPause && startWaitingForReportedTimeToChange
&& reportedVideoTimeAtStart !== video.currentTime) {
startWaitingForReportedTimeToChange = false;
const delay = getVirtualTime() - video.currentTime;
if (delay > 0) lastKnownVideoTime.approximateDelay = delay;
}
const intervalDuration = performance.now() - startIntervalTime;
if (intervalDuration + skipBuffer * 1000 >= delayTime || video.currentTime >= skipTime[0]) {
clearInterval(currentSkipInterval);
if (!utils.isFirefox() && !video.muted) {
// Workaround for more accurate skipping on Chromium
video.muted = true;
video.muted = false;
}
skippingFunction(Math.max(video.currentTime, startVideoTime + video.playbackRate * Math.max(delayTime, intervalDuration) / 1000));
}
}, 1);
} else {
logDebug(`Starting timeout to skip ${video.currentTime} to skip at ${skipTime[0]}`);
// Schedule for right before to be more precise than normal timeout
currentSkipSchedule = setTimeout(skippingFunction, Math.max(0, delayTime - 150));
}
}
}
function getVirtualTime(): number {
const virtualTime = lastTimeFromWaitingEvent ?? (lastKnownVideoTime.videoTime !== null ?
(performance.now() - lastKnownVideoTime.preciseTime) * video.playbackRate / 1000 + lastKnownVideoTime.videoTime : null);
if (Config.config.useVirtualTime && !isSafari() && virtualTime
&& Math.abs(virtualTime - video.currentTime) < 0.2 && video.currentTime !== 0) {
return virtualTime;
} else {
return video.currentTime;
}
}
function inMuteSegment(currentTime: number, includeOverlap: boolean): boolean {
const checkFunction = (segment) => segment.actionType === ActionType.Mute
&& segment.segment[0] <= currentTime
&& (segment.segment[1] > currentTime || (includeOverlap && segment.segment[1] + 0.02 > currentTime));
return sponsorTimes?.some(checkFunction) || sponsorTimesSubmitting.some(checkFunction);
}
/**
* This makes sure the videoID is still correct and if the sponsorTime is included
*/
function incorrectVideoCheck(videoID?: string, sponsorTime?: SponsorTime): boolean {
const currentVideoID = getYouTubeVideoID(document);
if (currentVideoID !== (videoID || sponsorVideoID) || (sponsorTime
&& (!sponsorTimes || !sponsorTimes?.some((time) => time.segment === sponsorTime.segment))
&& !sponsorTimesSubmitting.some((time) => time.segment === sponsorTime.segment))) {
// Something has really gone wrong
console.error("[SponsorBlock] The videoID recorded when trying to skip is different than what it should be.");
console.error("[SponsorBlock] VideoID recorded: " + sponsorVideoID + ". Actual VideoID: " + currentVideoID);
// Video ID change occured
videoIDChange(currentVideoID);
return true;
} else {
return false;
}
}
function setupVideoMutationListener() {
const videoContainer = document.querySelector(".html5-video-container");
if (!videoContainer || videoMutationObserver !== null || onInvidious) return;
videoMutationObserver = new MutationObserver(refreshVideoAttachments);
videoMutationObserver.observe(videoContainer, {
attributes: true,
childList: true,
subtree: true
});
}
async function refreshVideoAttachments(): Promise<void> {
if (waitingForNewVideo) return;
waitingForNewVideo = true;
const newVideo = await utils.waitForElement("video", true) as HTMLVideoElement;
waitingForNewVideo = false;
video = newVideo;
if (!videosWithEventListeners.includes(video)) {
videosWithEventListeners.push(video);
setupVideoListeners();
setupSkipButtonControlBar();
setupCategoryPill();
}
if (previewBar && !utils.findReferenceNode()?.contains(previewBar.container)) {
previewBar.remove();
previewBar = null;
createPreviewBar();
}
videoIDChange(getYouTubeVideoID(document));
}
function setupVideoListeners() {
//wait until it is loaded
video.addEventListener('loadstart', videoOnReadyListener)
video.addEventListener('durationchange', durationChangeListener);
if (!Config.config.disableSkipping) {
switchingVideos = false;
let startedWaiting = false;
let lastPausedAtZero = true;
video.addEventListener('play', () => {
// If it is not the first event, then the only way to get to 0 is if there is a seek event
// This check makes sure that changing the video resolution doesn't cause the extension to think it
// gone back to the begining
if (video.readyState <= HTMLMediaElement.HAVE_CURRENT_DATA
&& video.currentTime === 0) return;
updateVirtualTime();
if (switchingVideos || lastPausedAtZero) {
switchingVideos = false;
logDebug("Setting switching videos to false");
// If already segments loaded before video, retry to skip starting segments
if (sponsorTimes) startSkipScheduleCheckingForStartSponsors();
}
lastPausedAtZero = false;
// Check if an ad is playing
updateAdFlag();
// Make sure it doesn't get double called with the playing event
if (Math.abs(lastCheckVideoTime - video.currentTime) > 0.3
|| (lastCheckVideoTime !== video.currentTime && Date.now() - lastCheckTime > 2000)) {
lastCheckTime = Date.now();
lastCheckVideoTime = video.currentTime;
startSponsorSchedule();
}
});
video.addEventListener('playing', () => {
updateVirtualTime();
lastPausedAtZero = false;
if (startedWaiting) {
startedWaiting = false;
logDebug(`[SB] Playing event after buffering: ${Math.abs(lastCheckVideoTime - video.currentTime) > 0.3
|| (lastCheckVideoTime !== video.currentTime && Date.now() - lastCheckTime > 2000)}`);
}
if (switchingVideos) {
switchingVideos = false;
logDebug("Setting switching videos to false");
// If already segments loaded before video, retry to skip starting segments
if (sponsorTimes) startSkipScheduleCheckingForStartSponsors();
}
// Make sure it doesn't get double called with the play event
if (Math.abs(lastCheckVideoTime - video.currentTime) > 0.3
|| (lastCheckVideoTime !== video.currentTime && Date.now() - lastCheckTime > 2000)) {
lastCheckTime = Date.now();
lastCheckVideoTime = video.currentTime;
startSponsorSchedule();
}
});
video.addEventListener('seeking', () => {
lastKnownVideoTime.fromPause = false;
if (!video.paused){
// Reset lastCheckVideoTime
lastCheckTime = Date.now();
lastCheckVideoTime = video.currentTime;
updateVirtualTime();
clearWaitingTime();
startSponsorSchedule();
} else {
updateActiveSegment(video.currentTime);
if (video.currentTime === 0) {
lastPausedAtZero = true;
}
}
});
video.addEventListener('ratechange', () => {
updateVirtualTime();
clearWaitingTime();
startSponsorSchedule();
});
// Used by videospeed extension (https://github.com/igrigorik/videospeed/pull/740)
video.addEventListener('videoSpeed_ratechange', () => {
updateVirtualTime();
clearWaitingTime();
startSponsorSchedule();
});
const stoppedPlayback = () => {
// Reset lastCheckVideoTime
lastCheckVideoTime = -1;
lastCheckTime = 0;
lastKnownVideoTime.videoTime = null;
lastKnownVideoTime.preciseTime = null;
updateWaitingTime();
cancelSponsorSchedule();
};
video.addEventListener('pause', () => {
lastKnownVideoTime.fromPause = true;
stoppedPlayback();
});
video.addEventListener('waiting', () => {
logDebug("[SB] Not skipping due to buffering");
startedWaiting = true;
stoppedPlayback();
});
startSponsorSchedule();
}
}
function updateVirtualTime() {
if (currentVirtualTimeInterval) clearInterval(currentVirtualTimeInterval);
lastKnownVideoTime.videoTime = video.currentTime;
lastKnownVideoTime.preciseTime = performance.now();
// If on Firefox, wait for the second time change (time remains fixed for many "frames" for privacy reasons)
if (utils.isFirefox()) {
let count = 0;
let lastTime = lastKnownVideoTime.videoTime;
currentVirtualTimeInterval = setInterval(() => {
if (lastTime !== video.currentTime) {
count++;
lastTime = video.currentTime;
}
if (count > 1) {
const delay = lastKnownVideoTime.fromPause && lastKnownVideoTime.approximateDelay ?
lastKnownVideoTime.approximateDelay : 0;
lastKnownVideoTime.videoTime = video.currentTime + delay;
lastKnownVideoTime.preciseTime = performance.now();
clearInterval(currentVirtualTimeInterval);
currentVirtualTimeInterval = null;
}
}, 1);
}
}
function updateWaitingTime(): void {
lastTimeFromWaitingEvent = video.currentTime;
}
function clearWaitingTime(): void {
lastTimeFromWaitingEvent = null;
}
function setupSkipButtonControlBar() {