-
Notifications
You must be signed in to change notification settings - Fork 6
/
content2.js
1552 lines (1393 loc) · 60.5 KB
/
content2.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
//load this after a video is found
var prevAction = '',
fileName = '', //global variable with name of skip file, minus extension
cuts = [], //global variable containing the cuts, each array element is an object with this format {startTime,endTime,text,action}
offsets = {}, //to contain offsets for different sources. Initialized with first time or screenshot
speedMode = 1,
subsClass = '',
sliderValues = ['0','0','0','0','0','0'],
fadeTimer;
const deltaT = 1/24, //seconds for one frame at 24 fps
accel = 2; //determined experimentally;
//directly defined global variables for DOM elements. Needed by Firefox
var VStabs = document.getElementById('VStabs'),
VSloadLink = document.getElementById('VSloadLink'),
VSsyncLink = document.getElementById('VSsyncLink'),
VSfilterLink = document.getElementById('VSfilterLink'),
VSeditLink = document.getElementById('VSeditLink'),
VSLoadTab = document.getElementById('VSLoadTab'),
VSsyncTab = document.getElementById('VSsyncTab'),
VSfilterTab = document.getElementById('VSfilterTab'),
VSeditTab = document.getElementById('VSeditTab'),
VSlogo2 = document.getElementById('VSlogo2'),
VSloadDone = document.getElementById('VSloadDone'),
VSfineMode = document.getElementById('VSfineMode'),
VSaltMode = document.getElementById('VSaltMode'),
VSsyncDone = document.getElementById('VSsyncDone'),
VSfilterDone = document.getElementById('VSfilterDone'),
VSmsg1 = document.getElementById('VSmsg1'),
VSmsg2 = document.getElementById('VSmsg2'),
VSmsg3 = document.getElementById('VSmsg3'),
VSmsg4 = document.getElementById('VSmsg4'),
VSsyncMsg = document.getElementById('VSsyncMsg'),
VSskipFile = document.getElementById('VSskipFile'),
VSscreenShot = document.getElementById('VSscreenShot'),
VSfilters = document.getElementById('VSfilters'),
VSsexNum = document.getElementById('VSsexNum'),
VSviolenceNum = document.getElementById('VSviolenceNum'),
VScurseNum = document.getElementById('VScurseNum'),
VSboozeNum = document.getElementById('VSboozeNum'),
VSscareNum = document.getElementById('VSscareNum'),
VSotherNum = document.getElementById('VSotherNum'),
VSrubricText = document.getElementById('VSrubricText'),
VSautoProfanity = document.getElementById('VSautoProfanity'),
VSsubFile = document.getElementById('VSsubFile'),
VSblockList = document.getElementById('VSblockList'),
VSfineMode2 = document.getElementById('VSfineMode2'),
VSshotFile = document.getElementById('VSshotFile'),
VSshotFileBtn = document.getElementById('VSshotFileBtn'),
VSshotFileLabel = document.getElementById('VSshotFileLabel'),
VSsaveFile = document.getElementById('VSsaveFile'),
VSskipBox = document.getElementById('VSskipBox');
//subtitles in different services
var subsClasses = {
youtube:'.caption-window',
amazon:'.atvwebplayersdk-captions-text',
netflix:'.player-timedtext',
sling:'.bmpui-ui-subtitle-overlay',
redbox:'.cc-text-container',
plex:'.libjass-subs',
vudu:'.subtitles',
hulu123:'.vjs-text-track-display',
hulu:'.closed-caption-container',
hbo:'.__player-cc-root',
starz:'.cue-list',
crackle:'.clpp-subtitles-container',
epix:'.fp-captions',
showtime:'.closed-captioning-text',
pluto:'.captions',
tubi:'#captionsComponent', //actually not a class, but it should work
roku:'.vjs-text-track-cue',
peacock:'.video-player__subtitles',
kanopy:'.vjs-text-track-cue',
apple:'#mySubtitles', //added by content1
hoopla: '.clpp-text-cue',
cwtv: '.jw-text-track-cue'
};
for(var service in subsClasses){
if(serviceName.includes(service)){
subsClass = subsClasses[service];
break
}
}
//blanks/unblanks subtitles for different services
function blankSubs(isBlank){
if(subsClass){
if(serviceName == 'apple'){
var subs = mySubtitles //element defined in content1
}else{
var subs = document.querySelector(subsClass) //special cases
}
if(subs){
subs.style.opacity = isBlank ? 0 : '' //blank/unblank subs here
}
}else if(myVideo.textTracks.length > 0){ //HTML5 general case
myVideo.textTracks[0].mode = isBlank ? 'disabled' : 'showing'
}
}
//similar to jQuery ready(), from youmightnotneedjquery.com
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
//for screenshots
var canvas = document.createElement('canvas');
canvas.width = 320;
canvas.height = 240;
var ctx = canvas.getContext('2d'),
allowShots = '', //to avoid checking for tainted over and over
shotRatio; //of the screenshot
//to check when canvas is tainted, from Duncan @ StackOverflow
function isTainted(ctx) {
try {
var pixels = ctx.getImageData(0, 0, canvas.width, canvas.height),
sum = 0;
for(var i = 0; i < pixels.data.length; i+=4){ //add all the pixel values, excluding alpha channel; black screen will give zero
sum += pixels.data[i] + pixels.data[i+1] + pixels.data[i+2]
}
return !sum;
} catch(err) {
return true;
}
}
//to make a screenshot
function makeShot(){
if(allowShots == 'no') return false; //skip whole process if not allowed
myVideo.pause();
canvas.width = myVideo.videoWidth / myVideo.videoHeight * canvas.height;
try {
ctx.drawImage(myVideo, 0, 0, canvas.width, canvas.height) //crashes rather than fails in Firefox, due to CORS
} catch (err) {
allowShots = 'no';
return false
}
if(allowShots == 'yes') return canvas.toDataURL('image/jpeg'); //no need to check for tainted if it's allowed
if(isTainted(ctx)){ //check that screenshots are allowed
allowShots = 'no';
return false
}else{
allowShots = 'yes';
return canvas.toDataURL('image/jpeg') // can also use 'image/png' but the file is 10x bigger
}
}
//get image data at current time; returns an array
function imageData(source){
if(allowShots == 'no') return false;
canvas.width = source.clientWidth / source.clientHeight * canvas.height;
try {
ctx.drawImage(source, 0, 0, canvas.width, canvas.height) //crashes in Firefox for certain sites
} catch (err) {
allowShots = 'no';
return false
}
if(allowShots == 'yes') return ctx.getImageData(0,0,canvas.width,canvas.height).data;
if(isTainted(ctx)){
allowShots = 'no';
return false
}else{
allowShots = 'yes';
return ctx.getImageData(0,0,canvas.width,canvas.height).data
}
}
//get the absolute error between the screenShot and the video
function errorCalc(){
var videoData = imageData(myVideo),
length = Math.min(shotData.length,videoData.length);
var error = 0;
if(!videoData) return false; //in case the service does not allow screenshots
for(var i = 0; i < length; i += 4){ //every pixel takes 4 data points: R, G, B, alpha, in the 0 to 255 range; alpha data ignored
error += Math.abs(videoData[i] - shotData[i])+ Math.abs(videoData[i+1] - shotData[i+1]) + Math.abs(videoData[i+2] - shotData[i+2]) //all channels abs
}
return error / length
}
var errorData = [[],[]], //for automatic shot finding
shotData;
//process to get the error between the video and the screenshot as a double array of times and errors, starting 2 seconds before current video time, and move to best
function findShot(){
if(VSscreenShot.src == ''){
VSmsg3.textContent = chrome.i18n.getMessage('screenshotFirst');
return
}
if(!isSuper) toggleTopShot();
if(!imageData(myVideo)){ //bail out early if it's not going to work
VSautoBtn.disabled = true;
VSmsg2.textContent = chrome.i18n.getMessage('autosyncFail')
}else{
shotData = imageData(VSshot); //previously defined global variables
errorData = [[],[]];
var endTime = myVideo.currentTime,
startTime = endTime - 1.5;
goToTime(startTime);
myVideo.volume = 0;
myVideo.playbackRate = accel;
myVideo.play();
var collection = setInterval(function () { //collect data every deltaT seconds
var error = errorCalc()
if(error === false){ //no screenshots allowed so bail out and send message
clearInterval(collection);
VSautoBtn.disabled = true;
VSmsg2.textContent = chrome.i18n.getMessage('autosyncFail')
return
}
errorData[0].push(myVideo.currentTime);
errorData[1].push(error)
}, deltaT*1000/accel);
setTimeout(function(){
clearInterval(collection);
myVideo.pause();
myVideo.playbackRate = 1;
goToTime(minTime(errorData) + deltaT/2*accel); //scrub video to position of minimum error, plus extra time as fix
myVideo.volume = 1;
VSfineMode.checked = true;
VSfineMode2.checked = true;
VSmsg2.textContent = chrome.i18n.getMessage('autosyncDone')
},2500/accel) //do all this for 2.5 seconds so it catches 1.5 second before and 1 after. Results will be in errorData array
}
}
//find time for minimum error; errorData is a double list of errors and time
function minTime(errorData){
var minError = 5000, //sufficiently large to be larger than any error in errorData
lastTime = errorData[0][0],
minIndex = 0,
lastIndex = errorData[0].length - 1;
for(var i = 1; i <= lastIndex; i++){ //first find index for the minimum error in the array, ignoring first one
if(errorData[1][i] < minError && errorData[0][i] != lastTime){
minError = errorData[1][i];
minIndex = i
}
lastTime = errorData[0][i] //to get beyond stuck time at the beginning
}
return errorData[0][minIndex] //time for minimum error in the data array
}
//moves play to requested time
function goToTime(time){
if(serviceName == 'netflix'){ //Netflix will crash with the normal seek instruction. By Dmitry Paloskin at StackOverflow. Must be executed in page context
// executeOnPageSpace('videoPlayer = netflix.appContext.state.playerApp.getAPI().videoPlayer;sessions = videoPlayer.getAllPlayerSessionIds();player = videoPlayer.getVideoPlayerBySessionId(sessions[sessions.length-1]);player.seek(' + time*1000 + ')')
var script = document.createElement('script');
script.src = chrome.runtime.getURL('go2netflix.js?') + new URLSearchParams({seconds: time}); //Manifest v3 admits injected scripts only via file
document.documentElement.appendChild(script);
script.remove();
}else{ //everyone else is HTML5 compliant, except perhaps for ad time
myVideo.currentTime = (badAds.indexOf(serviceName) != -1) ? time + adSeconds : time
}
}
//show filter settings as soon as the video goes full screen, and when the mouse is moved on fullscreen
window.onresize = function(){
if(((screen.availWidth || screen.width-30) <= window.outerWidth) && VSstatus){ //it's fullscreen now
showSettings();
fadeTimer = setTimeout(function(){
VSstatus.style.display = 'none';
},3300);
ready(function(){
var fullElement = document.fullscreenElement;
if(fullElement && fullElement.firstChild != VSinterface){ //copy interface to fullscreen element if not done before
document.getElementById('VSbox').remove();
fullElement.appendChild(VSinterface);
}
replaceInterface();
resetStyles();
reBlackTxt()
})
}else{ //no longer fullscreen
VSstatus.style.display = 'none';
ready(function(){
document.getElementById('VSbox').remove();
document.body.appendChild(VSinterface);
replaceInterface();
resetStyles()
})
}
reGrayBtns(); //fixes kanopy bug
}
window.onmousemove = function(){
if(((screen.availWidth || screen.width-30) <= window.outerWidth) && VSstatus){ //display selected filters in fullscreen
clearTimeout(fadeTimer);
fadeTimer = null;
showSettings();
if(VScontrol.style.display == 'none') VSlogo.style.display = 'block';
if(!fadeTimer) fadeTimer = setTimeout(function(){
VSstatus.style.display = 'none';
VSlogo.style.display = 'none'
},4000)
}else if(VScontrol.style.display == 'none'){ //display button to load interface
clearTimeout(fadeTimer);
fadeTimer = null;
VSlogo.style.display = 'block';
if(!fadeTimer) fadeTimer = setTimeout(function(){
VSlogo.style.display = 'none'
},4000)
}
}
//this displays the filter settings on the full screen video
function showSettings(){
VSstatus.textContent = '';
var spacer = document.createTextNode("\u00A0\u00A0"); //two non-breaking spaces
if(cuts.length == 0){
VSstatus.appendChild(spacer);
var text = document.createTextNode(chrome.i18n.getMessage('noEditsLoaded'));
VSstatus.appendChild(text);
VSstatus.appendChild(spacer);
}else{
var keyWords = chrome.i18n.getMessage('categories').split(','),
output = [];
for(var i = 0; i < keyWords.length; i++){
if(sliderValues[i] != '0') output.push(keyWords[i])
}
if(output.length == 0){
VSstatus.appendChild(spacer);
var text = document.createTextNode(chrome.i18n.getMessage('noFiltersEngaged'));
VSstatus.appendChild(text);
VSstatus.appendChild(spacer);
}else{
VSstatus.appendChild(spacer);
var text = document.createTextNode(chrome.i18n.getMessage('VideoSkipOn'));
VSstatus.appendChild(text);
VSstatus.appendChild(spacer);
var filters = document.createElement('b');
filters.textContent = output.join(', ');
VSstatus.appendChild(filters);
VSstatus.appendChild(spacer);
}
}
VSstatus.style.display = ''
};
//move interface to good position
function replaceInterface(){
VSstatus.style.top = '80px'; //reposition elements
VSstatus.style.left = ((serviceName == 'netflix') ? 0 : myVideo.offsetLeft) + myVideo.offsetWidth - VSwidth + 'px';
document.getElementById('VSbox').style.top = '130px';
document.getElementById('VSbox').style.left = ((serviceName == 'netflix') ? 0 : myVideo.offsetLeft) + myVideo.offsetWidth - VSwidth + 'px';
if(VSlogo.style.display == 'none' && VScontrol.style.display == 'none') VSlogo.style.display = 'block' //return from full screen
}
//to make elements draggable, from W3schools
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
elmnt.onmousedown = dragMouseDown;
elmnt.addEventListener('contextmenu', function(e) { //disable right-click menu
e.preventDefault();
e.stopPropagation();
return false;
}, false);
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
e.stopPropagation();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
if((VSaltMode.checked != (!!e.altKey || e.button == 2)) && (elmnt == VSblurBox || elmnt == VSshot)){ //alt combinations or right-click resizes, regular moves
document.onmousemove = elementResize
}else{
document.onmousemove = elementDrag
}
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
e.stopPropagation();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
if(elmnt == VSlogo || elmnt == VStabs){ //drag whole interface
VSinterface.style.top = (VSinterface.offsetTop - pos2) + "px";
VSinterface.style.left = (VSinterface.offsetLeft - pos1) + "px";
}else{
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
}
function elementResize(e) {
e = e || window.event;
e.preventDefault();
e.stopPropagation();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
//get the element center
var centerX = elmnt.offsetLeft + elmnt.clientWidth / 2,
centerY = elmnt.offsetTop + elmnt.clientHeight / 2;
// set the element's new size, four cases depending of where the mouse is:
if(pos3 >= centerX && pos4 >= centerY){ //lower right
elmnt.style.height = (elmnt.clientHeight - pos2) + "px";
elmnt.style.width = (elmnt.clientWidth - pos1) + "px";
}else if(pos3 < centerX && pos4 >= centerY){ //lower left
elmnt.style.height = (elmnt.clientHeight - pos2) + "px";
elmnt.style.width = (elmnt.clientWidth + pos1) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}else if(pos3 >= centerX && pos4 < centerY){ //upper right
elmnt.style.height = (elmnt.clientHeight + pos2) + "px";
elmnt.style.width = (elmnt.clientWidth - pos1) + "px";
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
}else{ //upper left
elmnt.style.height = (elmnt.clientHeight + pos2) + "px";
elmnt.style.width = (elmnt.clientWidth + pos1) + "px";
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}
//apply the above to the blur box, the screenshot, and the interface
dragElement(VSblurBox);
dragElement(VSshot);
dragElement(VSlogo);
dragElement(VStabs);
//to close the interface panel from the X or the logo
function closePanel(){
VSlogo.style.display = 'block';
VScontrol.style.display = 'none';
fadeTimer = setTimeout(function(){
VSlogo.style.display = 'none'
},4000)
}
//to open the interface panel
function openPanel(){
VSlogo.style.display = 'none';
VScontrol.style.display = 'block'
}
VSlogo.addEventListener('click',openPanel);
/////////code from former videoskip.js///////////
const sliders = VSfilters.querySelectorAll('input'); //slider elements as an array
const badAds = ["amazon", "pluto"]; //list of services that change video timing with their ads
if(badAds.indexOf(serviceName) != -1){
alert(serviceName + chrome.i18n.getMessage('badAds')) //warn user about movies with ads from this service
}
const badTrailers = ["apple"]; //list of services that change video timing with trailers
if(badTrailers.indexOf(serviceName) != -1){
alert(serviceName + chrome.i18n.getMessage('badTrailers')) //warn user about movies with trailers from this service
}
const ua = navigator.userAgent.toLowerCase(); //to choose fastest filter method, per https://jsben.ch/5qRcU
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') == -1){ var isSafari = true
}else{ var isChrome = true }
}else if(typeof InstallTrigger !== 'undefined'){var isFirefox = true
}else if (document.documentMode || /Edge/.test(navigator.userAgent)){var isEdge = true
}
//loads the skips file
function loadFileAsURL(){
var fileToLoad = VSskipFile.files[0],
fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var URLFromFileLoaded = fileLoadedEvent.target.result;
var extension = fileToLoad.name.slice(-4);
if(extension == ".skp"){
var data = URLFromFileLoaded.split('data:image/jpeg;base64,'); //separate skips from screenshot
var data1 = data[0].split('{'); //separate skips from offsets
fileName = fileToLoad.name.slice(0,-4).replace(/ \[[a-z0-9\-]*\]/,''); //remove extension and service list
VSskipBox.value = data1[0].trim();
if(data1[1]) offsets = JSON.parse('{' + data1[1].trim()); //make offsets object
if(data[1]) VSscreenShot.src = 'data:image/jpeg;base64,' + data[1]; //extract screenshot
resizedShot(VSscreenShot.src, 240, true); //remove black bands, if any
if(!VSloadLink.textContent.match('✔')) VSloadLink.textContent += " ✔";
VSloadDone.textContent = chrome.i18n.getMessage('tabDone');
VSlogo2.style.display = 'none';
ready(function(){ //give it some time to load before data is extracted to memory and sent; also set switches
cuts = PF_SRT.parse(VSskipBox.value);
setSliders();
applyOffset() //this includes setActions at the end
})
}else{
VSmsg1.textContent = chrome.i18n.getMessage('wrongFile')
}
VSskipFile.type = '';
VSskipFile.type = 'file' //reset file input
};
fileReader.readAsText(fileToLoad)
}
//similar, to load subtitles for auto profanity filter
function loadSub(){
var fileToLoad = VSsubFile.files[0],
fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var URLFromFileLoaded = fileLoadedEvent.target.result;
var extension = fileToLoad.name.slice(-4);
if(extension == ".vtt" || extension == ".srt"){ //allow only .vtt and .srt formats
var subs = URLFromFileLoaded; //get subs in text format, to be edited
subs = subs.replace(/(\d),(\d)/g,'$1.$2'); //convert decimal commas to periods
autoBeepGen(subs)
}
VSssubFile.type = '';
VSsubFile.type = 'file' //reset file input
};
fileReader.readAsText(fileToLoad)
}
//makes silenced profanity skips timed to subtitles with words in blockList
function autoBeepGen(subs){
var blockListExp = new RegExp(VSblockList.textContent.replace(/, +/g,'|'),"g");
var subObj = PF_SRT.parse(subs); //similar in structure to cuts, with keys: startTime, endTime, text, action (empty)
writeIn('\n\n');
for(var i = 0; i < subObj.length; i++){
var word = subObj[i].text.toLowerCase().match(blockListExp);
if(word){ //word found in block list; add extra .3s buffer in case there are two in a row
writeIn(toHMS(subObj[i].startTime - 0.15) + ' --> ' + toHMS(subObj[i].endTime + 0.15) + '\nprofane word 1 (' + word[0] + ')\n\n',false)
}
}
var initialData = VSskipBox.value.trim().split('\n').slice(0,2); //first two lines containing screenshot timing
cuts = PF_SRT.parse(VSskipBox.value);
cuts.sort(function(a, b){return a.startTime - b.startTime;});
times2box();
if(initalData) VSskipBox.value = initialData.join('\n') + '\n\n' + VSskipBox.value;
VScurseNum.value = 3;
setActions();
makeTimeLabels()
}
//loads the screen shot from file, if the direct take didn't work
function loadShot(){
var fileToLoad = VSshotFile.files[0],
fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var URLFromFileLoaded = fileLoadedEvent.target.result;
resizedShot(URLFromFileLoaded, 240, VSblackBands.checked) //resize to standard height 240 px into screenshot, asynchronous function
};
if(fileToLoad){
fileReader.readAsDataURL(fileToLoad);
VSmsg4.textContent = chrome.i18n.getMessage('shotLoaded');
VSsyncLink.style.display = '';
VSsyncTab.style.display = ''
}else{
VSmsg4.textContent = chrome.i18n.getMessage('shotCanceled')
}
}
// Takes a data URI and returns the Data URI corresponding to the resized image at the wanted size. Black band removal optional. Adapted from a function by Pierrick Martellière at StackOverflow
function resizedShot(dataURIin, wantedHeight, removeBands){ //width will be calculated to maintain aspect ratio
// We create an image to receive the Data URI
var img = document.createElement('img');
// When the event "onload" is triggered we can resize the image.
img.onload = function() {
// We create a canvas and get its context.
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// We set the dimensions of the canvas.
var inputWidth = this.width,
inputHeight = this.height;
canvas.width = inputWidth;
canvas.height = inputHeight;
ctx.drawImage(this, 0, 0, inputWidth, inputHeight);
//Cropping process starts here
if(removeBands){
var inputData = ctx.getImageData(0,0,canvas.width,canvas.height),
data = inputData.data,
pixels = inputWidth * inputHeight,
westIndex = pixels * 2, //starting indices for pixels at cardinal points
eastIndex = westIndex - 4,
northIndex = inputWidth * 2,
southIndex = pixels * 4 - inputWidth * 2,
trueLeft = 0, trueRight = inputWidth,
trueTop = 0, trueBottom = inputHeight,
threshold = 5; //top and bottom lines may have spurious content;
//now scan middle horizontal line to determine true width; start on edges
for(var i = 0; i < inputWidth / 2; i++){
if(data[westIndex]+data[westIndex+1]+data[westIndex+2] > threshold) break;
trueLeft++;
westIndex += 4
}
for(var i = 0; i < inputWidth / 2; i++){
if(data[eastIndex]+data[eastIndex+1]+data[eastIndex+2] > threshold) break;
trueRight--;
eastIndex -= 4
}
//same for height
for(var i = 0; i < inputHeight / 2; i++){
if(data[northIndex]+data[northIndex+1]+data[northIndex+2] > threshold) break;
trueTop++;
northIndex += inputWidth * 4
}
for(var i = 0; i < inputHeight / 2; i++){
if(data[southIndex]+data[southIndex+1]+data[southIndex+2] > threshold) break;
trueBottom--;
southIndex -= inputWidth * 4
}
//these are the true dimensions
var trueWidth = trueRight - trueLeft,
trueHeight = trueBottom - trueTop;
//resize canvas
canvas.height = wantedHeight;
canvas.width = wantedHeight * trueWidth / trueHeight;
ctx.drawImage(img, trueLeft, trueTop, trueRight-trueLeft, trueBottom-trueTop, 0, 0, canvas.width, canvas.height)
}else{ //no black bars: only resize
canvas.height = wantedHeight;
canvas.width = wantedHeight * inputWidth / inputHeight;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
}
VSscreenShot.src = canvas.toDataURL('image/jpeg');
};
// We put the Data URI in the image's src attribute
img.src = dataURIin;
}
//to download data to a file, from StackOverflow
function download(data, name, type) {
var a = document.createElement("a");
var file = new Blob([data], {"type": type}),
url = URL.createObjectURL(file);
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0)
}
//to parse the content of the skip box in something close to .srt format, from StackOverflow
var PF_SRT = function() {
//SRT format
var pattern = /([\d:,.]+)\s*-*\>\s*([\d:,.]+)\s*\n([\s\S]*?(?=\n+\s*\d|\n{2}))?/gm; //no item number, can use decimal dot instead of comma, malformed arrows, no extra lines
var _regExp;
var init = function() {
_regExp = new RegExp(pattern);
};
var parse = function(f) {
if (typeof(f) != "string")
throw "Sorry, the parser accepts only strings";
var result = [];
if (f == null)
return _subtitles;
f = f.replace(/\r\n|\r|\n/g, '\n') + '\n\n';
while ((matches = pattern.exec(f)) != null) {
result.push(toLineObj(matches));
}
return result;
}
var toLineObj = function(group) {
return {
startTime: fromHMS(group[1]), //load timings in seconds
endTime: fromHMS(group[2]),
text: group[3],
action: '' //no action by default, to be filled later
};
}
init();
return {
parse: parse
}
}();
//to put seconds into hour:minute:second format
function toHMS(seconds) {
var hours = Math.floor(seconds / 3600);
seconds -= hours * 3600;
var minutes = Math.floor(seconds / 60);
minutes = (minutes >= 10) ? minutes : "0" + minutes;
seconds = Math.floor((seconds % 60) * 100) / 100; //precision is 0.01 s
seconds = (seconds >= 10) ? seconds : "0" + seconds;
return hours + ":" + minutes + ":" + seconds;
}
//the opposite: hour:minute:second string to decimal seconds
function fromHMS(timeString){
timeString = timeString.replace(/,/,"."); //in .srt format decimal seconds use a comma
var time = timeString.split(":");
if(time.length == 3){ //has hours
return parseInt(time[0])*3600 + parseInt(time[1])*60 + parseFloat(time[2])
}else if(time.length == 2){ //minutes and seconds
return parseInt(time[0])*60 + parseFloat(time[1])
}else{ //only seconds
return parseFloat(time[0])
}
}
const syncFix = 1/24; //use a time that is actually 1 frame earlier than reported when dealing with the screenshot
//shift all times so the screenshot has correct timing in the video
function syncTimes(){
if(timeLabels.length == 0){
VSmsg2.textContent = chrome.i18n.getMessage('noTimeInBox');
return
}else if(timeLabels[0].length < 1){
VSmsg2.textContent = chrome.i18n.getMessage('noTimeInBox');
return
}
var initialData = VSskipBox.value.trim().split('\n').slice(0,2), //first two lines
shotTime = fromHMS(initialData[0]),
seconds = shotTime ? trueTime() - shotTime : 0;
seconds -= syncFix; //apply fix
for(var i = 0; i < cuts.length; i++){
cuts[i].startTime += seconds;
cuts[i].endTime += seconds
}
times2box(); //put shifted times in the box
if(shotTime != null){ //reconstruct initial data, if present
initialData[0] = toHMS(shotTime + seconds);
VSskipBox.value = initialData.join('\n') + '\n\n' + VSskipBox.value
}
for(var service in offsets){ //adjust offsets
offsets[service] -= seconds;
if(Math.abs(offsets[service]) < deltaT) offsets[service] = 0
}
offsets[serviceName] = 0; //key for current source set to zero regardless
ready(function(){
setActions();
makeTimeLabels();
if(!VSsyncLink.textContent.match('✔')) VSsyncLink.textContent += " ✔";
VSsyncDone.textContent = chrome.i18n.getMessage('tabDone');
VSmsg3.textContent = chrome.i18n.getMessage('offsetApplied');
VSfilterLink.click(); //go on to filter tab
ready(save2file)
})
}
//shift all times according to offset in loaded skip file; different enough from previous to justify a new function
function applyOffset(){
var initialData = VSskipBox.value.trim().split('\n').slice(0,2), //first two lines
shotTime = fromHMS(initialData[0]);
var offset = offsets[serviceName];
if(typeof offset != 'undefined'){ //there is an offset for the current source, so shift all times
for(var i = 0; i < cuts.length; i++){
cuts[i].startTime += offset;
cuts[i].endTime += offset
}
times2box(); //put shifted times in the box
if(shotTime){ //reconstruct initial data, if present, shifting the shot time as well
initialData[0] = toHMS(shotTime + offset);
VSskipBox.value = initialData.join('\n') + '\n\n' + VSskipBox.value
}
setActions();
makeTimeLabels();
VSsyncTab.style.display = 'none'; //close sync tab if it was open
VSsyncLink.style.display = 'none';
VSmsg3.textContent = chrome.i18n.getMessage('offsetApplied');
for(var service in offsets){ //adjust offsets
offsets[service] -= offset
}
VSfilterLink.click() //open filter tab
}else{ //no offset found, so scrub to shot time and superimpose
offsets[serviceName] = 0; //initialize offset
setActions();
makeTimeLabels();
goToTime(shotTime);
VSsyncTab.style.display = '';
VSsyncLink.style.display = '';
VSsyncMsg.textContent = initialData[1];
VSsyncLink.click() //go to sync tab
}
}
//puts data from the cuts array into VSskipBox
function times2box(){
var text = '';
for(var i = 0; i < cuts.length; i++){
text += toHMS(cuts[i].startTime) + ' --> ' + toHMS(cuts[i].endTime) + '\n' + cuts[i].text + '\n\n'
}
VSskipBox.value = text.trim()
}
//insert string in box, at cursor or replacing selection
function writeIn(string,isScrub){
var start = VSskipBox.selectionStart,
end = VSskipBox.selectionEnd,
newEnd = start + string.length;
VSskipBox.value = VSskipBox.value.slice(0,start) + string + VSskipBox.value.slice(end,VSskipBox.length);
if(isScrub){
VSskipBox.setSelectionRange(start,newEnd)
}else{
VSskipBox.setSelectionRange(newEnd,newEnd);
}
VSskipBox.focus();
ready(function(){
cuts = PF_SRT.parse(VSskipBox.value);
setActions();
makeTimeLabels()
})
}
//insert things in box
function writeTime(){
writeIn(toHMS(trueTime()),false)
}
//insert quick silence
function writeSilence(){
writeIn(toHMS(trueTime() - 0.7) + ' --> ' + toHMS(trueTime()) + '\profane word 1\n\n',false)
}
//insert box position as percentage of video dimensions
function writePosition(){
if(isBlur){
var x = getBlurPos();
for(var i = 0; i < 4; i++) x[i] = x[i].toPrecision(4);
writeIn('[' + x[0] + ',' + x[1] + ',' + x[2] + ',' + x[3] + ']',false)
}
}
//gets index of a particular HMS time in the box, by location; returns null if the cursor is not on a time label
function getTimeIndex(){
var start = VSskipBox.selectionStart,
end = VSskipBox.selectionEnd;
for(var i = 0; i < timeLabels[0].length; i++){
if(timeLabels[1][i] <= start && timeLabels[2][i] >= end) return i
}
}
//scrub video by a given amount
function shiftTime(increment){
if(myVideo.paused){
if(serviceName == 'netflix'){ //Netflix does not allow super-short increments
if(Math.abs(increment) < 0.1) increment = (increment < 0) ? -0.055 : 0.055;
goToTime(trueTime() + increment);
myVideo.pause()
}else{
goToTime(trueTime() + increment)
}
}else{
myVideo.pause()
}
}
//called by forward buttons
function fwdSkip(){
if(VSaltMode.checked){ //special mode for shifting auto profanity skips, in case subtitle file was off
shiftProfSkips(true)
}else{
if(VSskipBox.selectionStart != VSskipBox.selectionEnd){ //when a time is selected in the box, change that too
var index = getTimeIndex(),
tol = 0.02;
if(index != null){
VSskipBox.setSelectionRange(timeLabels[1][index],timeLabels[2][index]);
var selectedTime = fromHMS(timeLabels[0][index]);
var timeShift = VSfineMode.checked ? deltaT : deltaT*12;
shiftTime(timeShift);
writeIn(toHMS(trueTime()),true);
VSskipBox.focus()
}
}else{ //scrub by a small amount
var timeShift = VSfineMode.checked ? deltaT : deltaT*12;
shiftTime(timeShift);
}
}
}
//called by back buttons
function backSkip(){
if(VSaltMode.checked){ //special mode for shifting auto profanity skips, in case subtitle file was off
shiftProfSkips(true)
}else{
if(VSskipBox.selectionStart != VSskipBox.selectionEnd){ //when a time is selected in the box, change that too
var index = getTimeIndex(),
tol = 0.02;
if(index != null){
VSskipBox.setSelectionRange(timeLabels[1][index],timeLabels[2][index]);
var selectedTime = fromHMS(timeLabels[0][index]);
var timeShift = VSfineMode.checked ? - deltaT : - deltaT*12;
shiftTime(timeShift);
writeIn(toHMS(trueTime()),true);
VSskipBox.focus()
}
}else{ //scrub by a small amount
var timeShift = VSfineMode.checked ? - deltaT : - deltaT*12;
shiftTime(timeShift)
}
}
}
//called by fast forward buttons
function fFwdToggle(){
VSskipBox.selectionStart = VSskipBox.selectionEnd; //clear selection, if any
if(myVideo.paused){ //if paused, restart at normal speed
speedMode = 1;
myVideo.volume = 1;
myVideo.playbackRate = 1
myVideo.play()
}else{ //if playing, toggle speed
if(speedMode == 1){
speedMode = 2;
myVideo.volume = 0;
myVideo.playbackRate = 16
}else{
speedMode = 0;
myVideo.volume = 1;
myVideo.playbackRate = 1;
myVideo.pause()
}
}
VSskipBox.focus();
}
//called by the above, to shift auto-generated profanity skips
function shiftProfSkips(isFwd){
var timeShift = 0,
isFine = VSfineMode.checked,
initialData = VSskipBox.value.trim().split('\n').slice(0,2); //first two lines
for(var i = 0; i < cuts.length; i++){
if(cuts[i].text.match(/profane word \(/)){ //do it only for auto-generated skips
timeShift = (isFine ? deltaT : deltaT*12)*(isFwd ? 1 : -1);
cuts[i].startTime += timeShift;
cuts[i].endTime += timeShift
}
}
times2box();
if(initialData) VSskipBox.value = initialData.join('\n') + '\n\n' + VSskipBox.value
}
//scrub to first time in the box, unless a time is selected
function scrub2shot(){
if(timeLabels.length == 0){
VSmsg4.textContent = chrome.i18n.getMessage('noTimeInBox');
return
}else if(timeLabels[0].length < 1){
VSmsg4.textContent = chrome.i18n.getMessage('noTimeInBox');
return
}
var index = getTimeIndex();
if(index != null){
VSskipBox.setSelectionRange(timeLabels[2][index],timeLabels[2][index]); //deselect if previously selected
myVideo.pause();
goToTime(fromHMS(timeLabels[0][index]));
VSskipBox.focus()
}else{ //scrub to 1st time
myVideo.pause();
goToTime(fromHMS(timeLabels[0][0]))
}
}
var isSuper = false; //keeps track of whether or not there is a superimposed screenshot
//put the screenshot on top of the video so a perfect match can be found, and back
function toggleTopShot(){
if(VSscreenShot.src == ''){
isSuper = false;
VSmsg2.textContent = chrome.i18n.getMessage('noSuperimpose');
}
if(!isSuper){ //add overlay
isSuper = true;
if(VSscreenShot.src){
VSshot.src = VSscreenShot.src;
var videoRatio = myVideo.clientWidth / myVideo.clientHeight,
shotRatio = VSscreenShot.width/VSscreenShot.height;
if(videoRatio <= shotRatio){ //possible black bars at top and bottom
VSshot.width = myVideo.clientWidth;
VSshot.height = VSshot.width / shotRatio;
VSshot.style.top = myVideo.offsetTop + myVideo.clientHeight/2 - VSshot.height/2 + 'px';