This repository has been archived by the owner on Oct 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 598
/
quality-controls.js
702 lines (555 loc) · 19.9 KB
/
quality-controls.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
//////// Event Handling ////////
// run event on document object
function fireEvent(data, type) {
var event; // The custom event that will be created
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent(type, true, true);
} else {
event = document.createEventObject();
event.eventType = type;
}
event.eventName = type;
event.data = data;
if (document.createEvent) {
document.dispatchEvent(event);
} else {
document.fireEvent("on" + event.eventType, event);
}
}
//////// End Event Handling ///////
//////// Localization //////////
function getCurrentLanguage() {
var language = navigator.languages && navigator.languages[0] || // Chrome / Firefox
navigator.language || // All browsers
navigator.userLanguage; // IE <= 10
return language;
}
function detectLanguage() {
var language = getCurrentLanguage();
return language.split('-')[0].toLowerCase();
}
function base64Decode(str) {
var decoded = str;
try {
decoded = window.atob(str);
} catch (e) {
}
return decoded;
}
function localize(str) {
var ruHash = {
'Quality': "Качество",
};
var userLang = detectLanguage();
console.log("current language is " + userLang + " " + str);
var curHash = {}; // don't translate if language not detected
switch (userLang) {
case "ru":
case "uk":
curHash = ruHash;
break;
}
var result = curHash[str] || str;
return result;
}
//////// End Localization //////////
///// Helpers //////
function firstRun() {
if (!arguments.callee.done)
return arguments.callee.done = true;
return false;
}
function setOnInterfaceVisible(fn) {
var up = 38;
var down = 40;
var left = 37;
var right = 39;
var enter = 13;
var esc = 27;
var container = document.getElementById('watch');
container.addEventListener('keydown', function(event){
var keyCode = event.keyCode;
console.log('setOnInterfaceVisible pre handler called');
var mainRow = querySelector('#transport-controls');
var firstMoveSet = keyCode == enter || keyCode == esc;
var secondMoveSet = keyCode == left || keyCode == right || keyCode == up || keyCode == down;
var isInterfaceVisible = !hasClass(mainRow, 'hidden');
if (isInterfaceVisible && firstMoveSet)
return;
if (!isInterfaceVisible && secondMoveSet)
return;
console.log('setOnInterfaceVisible handler called');
fn(event);
});
}
function setVisibility(obj, isVisible) {
if (obj == null)
return;
obj.style.display = isVisible ? '' : 'none';
}
function setEnabled(obj, isEnabled) {
if (obj == null)
return;
isEnabled ? removeClass(obj, 'disabled') : addClass(obj, 'disabled');
}
/////////////////////////////////////////////////
function getVideoPlayerPlayButton() {
return document.querySelector('.icon-player-play');
}
// function delayUntilPlayerBeInitialized(fn) {
// delayTillElementBeInitialized(fn, getVideoPlayerPlayButton, true);
// }
function getExitDialogOKButton() {
return document.getElementById('dialog-ok-button');
}
// function delayUnitlExitDialogBeInitialized(fn) {
// delayTillElementBeInitialized(fn, getExitDialogOKButton, true);
// }
///////////////////////////////////////////////
/////////////////////////////
var observeDOM = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
eventListenerSupported = window.addEventListener;
return function(obj, callback){
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
callback(obj);
});
// have the observer observe foo for changes in children
obs.observe( obj, { childList:true, subtree:true });
}
else if( eventListenerSupported ){
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
}
}
})();
///////////////////////////
function createElement(html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.firstChild;
}
function addClass(el, className) {
if (el == null)
return;
if (el.classList) {
var names = className.split(' ');
for (var i = 0; i < names.length; i++) {
el.classList.add(names[i]);
}
} else {
el.className += ' ' + className;
}
}
function removeClass(el, className) {
if (el == null)
return;
if (el.classList) {
var names = className.split(' ');
for (var i = 0; i < names.length; i++) {
el.classList.remove(names[i]);
}
} else {
el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
}
function hasClass( elem, klass ) {
return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}
function hasId( elem, id ) {
return (" " + elem.id + " " ).indexOf( " " + id + " " ) > -1;
}
//Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
return (el.offsetParent === null)
}
function isInterfaceHidden() {
var controls = document.querySelector('#transport-controls');
return hasClass(controls, 'hidden');
}
function addEventListenerAll(type, fn, objArr) {
for (var i = 0; i < objArr.length; i++) {
objArr[i].addEventListener(type, fn);
}
}
function removeEventListenerAll(type, fn, objArr) {
for (var i = 0; i < objArr.length; i++) {
objArr[i].removeEventListener(type, fn);
}
}
function append(parent, elem) {
parent.appendChild(elem);
}
function querySelector(selector) {
return document.querySelector(selector);
}
function querySelectorAll(selector) {
return document.querySelectorAll(selector);
}
function remove(el) {
if (!el)
return;
el.parentNode.removeChild(el);
}
function prepend(parent, elems) {
if (!parent || !elems)
return;
parent.insertBefore(elems, parent.firstChild);
}
function put(key, value) {
if (!window.globalMap)
window.globalMap = {};
window.globalMap[key] = value;
}
function get(key) {
if (!window.globalMap)
return null;
return window.globalMap[key];
}
function removeEventListenerAll(el, type, fnArr) {
for (var i = 0; i < fnArr.length; i++) {
el.removeEventListener(type, fnArr[i]);
}
}
function addEventListenerAll(el, type, fnArr) {
for (var i = 0; i < fnArr.length; i++) {
el.addEventListener(type, fnArr[i]);
}
}
////// End Helpers //////
function createQualityToggleButton() {
return createElement(
'<div id="transport-more-button" class="my-button toggle-button quality-toggle-buton" tabindex="-1"> \
<span>' + localize('Quality') + '</span> \
</div>');
}
function createQualityButtonsRow(videoFormats) {
// NOTE: styling buttons-list: fixing obvious layout mess
var container = createElement('<div id="buttons-list" class=" list" data-enable-sounds="false" tabindex="-1" style="position: relative; overflow: hidden; height: 100%;"></div>');
var container2 = createElement('<div class="new-list-container horizontal" style="margin-left: 0em;"></div>');
for (var idx in videoFormats) {
var textColor = '';
var disabledClass = '';
if (videoFormats[idx].selected){
textColor = 'color: red';
disabledClass = 'disabled';
}
var el = createElement('<div class="my-button toggle-button ' + disabledClass + '" tabindex="-1" data-format-name="' + videoFormats[idx].name + '" style="min-width: 2.3em; width: initial; ' + textColor + '">' + videoFormats[idx].name + '</div>')
append(container2, el);
append(container, container2);
}
return container;
}
///// Remote Controller Navigation Handling /////
function sortButtons(nodes) {
// sort buttons based on horizontal position on screen
function compareByOffset(a, b) {
if (a.offsetLeft < b.offsetLeft)
return -1;
if (a.offsetLeft > b.offsetLeft)
return 1;
return 0;
}
// move transport-more-button to the left
// NOTE: has unproper sort among Options buttons
function compareById(a, b) {
var leftId = a.getAttribute('id');
var rightId = b.getAttribute('id');
var leftContains = leftId ? leftId.indexOf('transport-more-button') >= 0 : false;
var rightContains = rightId ? rightId.indexOf('transport-more-button') >= 0 : false;
if (leftContains && rightContains)
return 0;
if (rightContains)
return 1;
return 0;
}
var objArr = Array.prototype.slice.call(nodes);
return objArr.sort(compareByOffset);
}
function addArrowKeysHandling(container) {
if (!container)
return;
// classes:
// focused - button highlighted
// selected - button will have next focus
// disabled - button not active
var buttons = container.querySelectorAll('.button, .toggle-button');
buttons = sortButtons(buttons); // convert to array and sort
if (!buttons)
console.log('Houston we have problems: cant find buttons');
var listener1 = function (event) {
var buttons = container.querySelectorAll('.button, .toggle-button');
buttons = sortButtons(buttons); // convert to array and sort
arrowKeysListener(event, buttons)
};
var listener2 = function (event) {
var buttons = container.querySelectorAll('.button, .toggle-button');
buttons = sortButtons(buttons); // convert to array and sort
moveOutListener(event, buttons)
};
// var listener3 = function (event) {resetButtonsState(null, buttons)};
addEventListenerAll(container, 'keydown', [listener1, listener2]);
var onDomChanged = function(el) {
console.log('onDomChanged');
// refill buttons
buttons = container.querySelectorAll('.button, .toggle-button');
buttons = sortButtons(buttons); // convert to array and sort
// reattach handlers
// remove event handlers when content is changed
removeEventListenerAll(container, 'keydown', [listener1, listener2]);
addEventListenerAll(container, 'keydown', [listener1, listener2]);
showHideCustomElements();
};
observeDOM(container, onDomChanged);
// reset state of buttons that managed in this script
setOnInterfaceVisible(function(ev){resetButtonsState(null, buttons);});
}
function showHideCustomElements() {
var testElem = document.querySelector('.icon-bug_report.toggle-button');
var mainButton = document.querySelector('.quality-toggle-buton');
setVisibility(mainButton, testElem == null);
setEnabled(mainButton, testElem == null);
}
function moveOutListener(event, objArr) {
// console.log('moveOutListener fired');
var up = 38;
var down = 40;
var esc = 27;
var keyCode = event.keyCode;
if (keyCode != up && keyCode != down && keyCode != esc) {
return;
}
console.log('moveOutListener');
if (keyCode == esc) {
// fix hide interface on esc key
setTimeout(function(){resetButtonsState(event.currentTarget, objArr)}, 500);
return;
}
resetButtonsState(event.currentTarget, objArr);
}
// reset state of buttons that managed in this script
function resetButtonsState(container, objArr) {
console.log('resetButtonsState called');
var focusedAll = objArr;
for (var i = 0; i < focusedAll.length; i++) {
if (hasClass(focusedAll[i], 'my-disabled'))
removeClass(focusedAll[i], 'disabled my-disabled');
if (hasId(focusedAll[i], 'transport-more-button'))
removeFocus(focusedAll[i]);
if (hasClass(focusedAll[i], 'my-button'))
removeFocus(focusedAll[i]);
}
hideQualityControls();
}
function hideQualityControls() {
// TODO: rewrite
// Are quality buttons shown?
if (get('buttons-list') == null) {
return;
}
var backedButtons = get('buttons-list');
put('buttons-list', null);
var parent = querySelector('.controls-row'); // root container
var qualityRow = parent.querySelector('#buttons-list');
remove(qualityRow);
prepend(parent, backedButtons);
var buttons = qualityRow.querySelectorAll('.button, .toggle-button');
for (var i = 0; i < buttons.length; i++) {
removeFocus(buttons[i]);
}
}
function arrowKeysListener(event, objArr) {
var left = 37;
var right = 39;
var keyCode = event.keyCode;
if (event.keyCode != left && event.keyCode != right) {
return;
}
switch(keyCode) {
case left:
var obj = getNextLeftFocus(objArr, event.target);
if (obj)
swapFocus(event.target, obj);
break;
case right:
var obj = getNextRightFocus(objArr, event.target);
if (obj)
swapFocus(event.target, obj);
break;
}
event.stopPropagation(); // I will handle this event
}
function getNextLeftFocus(objArr, currentFocus) {
var currIdx = objArr.indexOf(currentFocus);
if (currIdx == -1)
return null;
if (currIdx == 0)
return null;
var prevObj;
for (var i = (currIdx - 1); i >= 0; i--) {
prevObj = objArr[i];
if (!hasClass(prevObj, 'disabled'))
break;
prevObj = null;
}
if (!prevObj)
return null;
return prevObj;
}
function getNextRightFocus(objArr, currentFocus) {
var currIdx = objArr.indexOf(currentFocus);
if (currIdx == -1)
return null;
if (currIdx == (objArr.length - 1))
return null;
var nextObj;
for (var i = (currIdx + 1); i < objArr.length; i++) {
nextObj = objArr[i];
if (!hasClass(nextObj, 'disabled'))
break;
nextObj = null;
}
if (!nextObj)
return null;
return nextObj;
}
function addFocus(elem) {
if (!elem)
return;
addClass(elem, 'focused');
addClass(elem, 'selected');
elem.focus();
}
function removeFocus(elem) {
removeClass(elem, 'focused');
removeClass(elem, 'selected');
}
function swapFocus(oldFocus, newFocus) {
removeFocus(oldFocus);
addFocus(newFocus);
if (isHidden(newFocus)) {
console.log("Houston we have probles here!");
}
}
///// End Remote Controller Navigation Handling /////
///// Event Handlers /////
function qualityButtonRowOnClick(event) {
if (event.keyCode != 13) // enter/click
return;
console.log('switchResolution ' + event.target.dataset.formatName);
if (window.app)
window.app.switchResolution(event.target.dataset.formatName);
event.stopPropagation();
}
function setupAutoHide() {
var checkInterfaceHidden = function(){
console.log('checking that interface is hidden');
if (isInterfaceHidden()) {
clearInterval(interval);
hideQualityControls();
}
};
var interval = setInterval(checkInterfaceHidden, 500);
console.log('setupAutoHide');
}
function qualityToggleButtonOnClick(event, qualityButtonRow) {
if (event.keyCode != 13) // enter or click
return;
if (get('buttons-list')) { // hide
var elems = get('buttons-list');
put('buttons-list', null);
removeClass(querySelector('#transport-more-button'), 'disabled my-disabled');
} else { // show
var buttonList = querySelector('#buttons-list');
put('buttons-list', buttonList);
var elems = qualityButtonRow;
addClass(querySelector('#transport-more-button'), 'disabled my-disabled');
setupAutoHide();
}
var buttons = querySelector('#buttons-list');
remove(buttons);
var parent = querySelector('.controls-row'); // root container
prepend(parent, elems);
// I'll handle event myself
event.stopPropagation();
}
function transportMoreButtonOnClick(event, qualityToggleButton) {
if (event.keyCode != 13) // enter or click
return;
if (hasClass(qualityToggleButton, 'disabled')) {
removeClass(qualityToggleButton, 'disabled my-disabled');
} else {
addClass(qualityToggleButton, 'disabled my-disabled');
}
}
function removePreviouslyCreatedButtons() {
var button = get('quality-toggle-buton');
remove(button);
}
function setupQualityButtons(videoFormats) {
if (!videoFormats.length)
return;
// removePreviouslyCreatedButtons
remove(get('quality-toggle-buton'));
// create and add my toggle-button
var qualityToggleButton = createQualityToggleButton();
var parentContainer = querySelector('.controls-row');
append(parentContainer, qualityToggleButton);
var qualityButtonsRow = createQualityButtonsRow(videoFormats);
// save
put('quality-toggle-buton', qualityToggleButton);
var qualityOnClick = function(event){qualityButtonRowOnClick(event)};
var toggleOnClick = function(event){qualityToggleButtonOnClick(event, qualityButtonsRow)};
// attach event handler to my toggle-button
qualityToggleButton.addEventListener('keyup', toggleOnClick);
// attach event handler to quality-button-row
qualityButtonsRow.addEventListener('keyup', qualityOnClick);
}
///// End Event Handlers /////
function notifyAboutSupportedVideoFormats(formats) {
console.log("Supported formats are: ", formats);
}
function addQualityControls() {
if (window.addQualityControlsDone)
return;
// setup default, before 'videoformats' event is fired
setupQualityButtons([{name: '144p'},{name: '360p'},{name: '720p'},{name: '1080p'},{name: 'Auto', selected: true}]);
document.addEventListener('videoformats', function(event){console.log('videoformats event fired'); setupQualityButtons(event.data)});
// var transportMoreButton = querySelector('#transport-more-button');
// transportMoreButton.addEventListener('keyup', function(event){transportMoreButtonOnClick(event, qualityToggleButton)});
// add arrow keys handling
// TODO: not done
addArrowKeysHandling(querySelector('.controls-row'));
window.addQualityControlsDone = true;
}
///////////////////////////////////////////////////
function init() {
// add quality settings to video
delayUntilPlayerBeInitialized(addQualityControls, true);
console.log('injecting quality-controls.js into ' + document.location.href);
}
function waitTillInit(modName, callback, depName) {
if (window[modName] === 'ok') {
console.log(modName + ': module already initialized');
return;
}
window[modName] = 'ok';
if (window[depName] || !depName) {
console.log(modName + ': all deps initialized. perform callback');
callback();
return;
}
var interval = setInterval(function() {
console.log(modName + ': check that all deps are initialized');
if (window[depName]) {
console.log(modName + ': all deps initialized. perform callback');
callback();
clearInterval(interval);
}
}, 100);
}
waitTillInit('quality-controls.js', init, 'common.js');