HTML5 Video Player Enhance

To enhance the functionality of HTML5 Video Player (h5player) supporting all websites using shortcut keys similar to PotPlayer.

当前为 2021-06-22 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HTML5 Video Player Enhance
  3. // @version 2.9.4.4
  4. // @description To enhance the functionality of HTML5 Video Player (h5player) supporting all websites using shortcut keys similar to PotPlayer.
  5. // @author CY Fung
  6. // @match http://*/*
  7. // @match https://*/*
  8. // @run-at document-start
  9. // @require https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js
  10. // @require https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.3.2/math.js
  11. // @namespace https://greasyfork.org/users/371179
  12. // @grant GM_getValue
  13. // @grant GM_setValue
  14. // @grant GM_addStyle
  15. // @grant unsafeWindow
  16. // ==/UserScript==
  17. /**
  18. * Remarks
  19. * This script support modern browser only with ES6+.
  20. * fullscreen and pointerLock buggy in shadowRoot
  21. * Space Pause not success
  22. * shift F key issue
  23. **/
  24. !(function($winUnsafe, $winSafe) {
  25. 'use strict';
  26.  
  27. const window = $winUnsafe || $winSafe
  28. const document = window.document
  29. const $$uWin = $winUnsafe || $winSafe;
  30.  
  31. const $rAf = $$uWin.requestAnimationFrame;
  32. const $cAf = $$uWin.cancelAnimationFrame;
  33.  
  34.  
  35. const $$setTimeout = $$uWin.setTimeout
  36. const $$clearTimeout = $$uWin.clearTimeout
  37. const $$requestAnimationFrame = $$uWin.requestAnimationFrame;
  38. const $$cancelAnimationFrame = $$uWin.cancelAnimationFrame;
  39.  
  40. const $qmt = ($$uWin.queueMicrotask ? $$uWin.queueMicrotask : function(callback) {
  41. Promise.resolve()
  42. .then(callback)
  43. .catch(e => setTimeout(() => {
  44. throw e;
  45. })); // report exceptions
  46. }).bind($$uWin)
  47.  
  48. const $bz = {
  49. boosted: false
  50. }
  51.  
  52.  
  53. window.setTimeout = function() {
  54. let f = arguments[0]
  55. let d = arguments[1] || 0;
  56. if ($bz.boosted && typeof f == 'function' && arguments.length <= 2) {
  57. // f : function arguments.length = 1 or 2
  58. // setTimeout(f,d)
  59.  
  60. if (d < 40) return (($$requestAnimationFrame.call(this, f) << 1) | 1) || 0;
  61. return ($$setTimeout.call(this, f, d) << 1) || 0;
  62.  
  63. }
  64. return ($$setTimeout.apply(this, arguments) << 1) || 0
  65. }
  66.  
  67. window.clearTimeout = function() {
  68. const kid = arguments[0]
  69. const cid = kid >> 1;
  70. if (cid > 0) {
  71. if (kid & 1) {
  72. $$cancelAnimationFrame.call(this, cid);
  73. } else {
  74. $$clearTimeout.call(this, cid)
  75. }
  76. }
  77. }
  78.  
  79.  
  80. const $ws = {
  81. requestAnimationFrame,
  82. cancelAnimationFrame,
  83. MutationObserver,
  84. setInterval,
  85. clearInterval,
  86. EventTarget
  87. }
  88. //throw Error if your browser is too outdated. (eg ES6 script, no such window object)
  89.  
  90.  
  91. !(function $$() {
  92. 'use strict';
  93.  
  94. if (!document || !document.documentElement) return window.requestAnimationFrame($$);
  95.  
  96. const setTimeout = window.setTimeout
  97. const clearTimeout = window.clearTimeout
  98.  
  99. const prettyElm = function(elm) {
  100. if (!elm || !elm.nodeName) return null;
  101. const eId = elm.id || null;
  102. const eClsName = elm.className || null;
  103. return [elm.nodeName.toLowerCase(), typeof eId == 'string' ? "#" + eId : '', typeof eClsName == 'string' ? '.' + eClsName.replace(/\s+/g, '.') : ''].join('').trim();
  104. }
  105.  
  106. const delayCall = function(p, f, d) {
  107. if (delayCall[p] > 0) clearTimeout(delayCall[p])
  108. delayCall[p] = setTimeout(f, d)
  109. }
  110.  
  111. HTMLVideoElement.prototype.__isPlaying = function() {
  112. const video = this;
  113. return video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA;
  114. }
  115.  
  116.  
  117.  
  118. let _debug_h5p_logging_ = false;
  119.  
  120. try {
  121. _debug_h5p_logging_ = +window.localStorage.getItem('_h5_player_sLogging_') > 0
  122. } catch (e) {}
  123.  
  124.  
  125.  
  126. const SHIFT = 1;
  127. const CTRL = 2;
  128. const ALT = 4;
  129. const TERMINATE = 0x842;
  130. const _sVersion_ = 1817;
  131. const str_postMsgData = '__postMsgData__'
  132. const DOM_ACTIVE_FOUND = 1;
  133. const DOM_ACTIVE_SRC_LOADED = 2;
  134. const DOM_ACTIVE_ONCE_PLAYED = 4;
  135. const DOM_ACTIVE_MOUSE_CLICK = 8;
  136. const DOM_ACTIVE_MOUSE_IN = 16;
  137. const DOM_ACTIVE_DELAYED_PAUSED = 32;
  138. const DOM_ACTIVE_INVALID_PARENT = 2048;
  139.  
  140. var console = {};
  141.  
  142. console.log = function() {
  143. window.console.log(...['[h5p]', ...arguments])
  144. }
  145. console.error = function() {
  146. window.console.error(...['[h5p]', ...arguments])
  147. }
  148.  
  149. function makeNoRoot(shadowRoot) {
  150. const doc = shadowRoot.ownerDocument || document;
  151. const htmlInShadowRoot = doc.createElement('noroot'); // pseudo element
  152. const childNodes = [...shadowRoot.childNodes]
  153. shadowRoot.insertBefore(htmlInShadowRoot, shadowRoot.firstChild)
  154. for (const childNode of childNodes) htmlInShadowRoot.appendChild(childNode);
  155. return shadowRoot.querySelector('noroot');
  156. }
  157.  
  158. let _endlessloop = null;
  159. const isIframe = (window.top !== window.self && window.top && window.self);
  160. const shadowRoots = [];
  161.  
  162. const _getRoot = Element.prototype.getRootNode || HTMLElement.prototype.getRootNode || function() {
  163. let elm = this;
  164. while (elm) {
  165. if ('host' in elm) return elm;
  166. elm = elm.parentNode;
  167. }
  168. return elm;
  169. }
  170.  
  171. const getRoot = (elm) => _getRoot.call(elm);
  172.  
  173. const isShadowRoot = (elm) => (elm && ('host' in elm)) ? elm.nodeType == 11 && !!elm.host && elm.host.nodeType == 1 : null; //instanceof ShadowRoot
  174.  
  175.  
  176. const domAppender = (d) => d.querySelector('head') || d.querySelector('html') || d.querySelector('noroot') || null;
  177.  
  178. const playerConfs = {}
  179.  
  180. const hanlderResizeVideo = (entries) => {
  181. const detected_changes = {};
  182. for (let entry of entries) {
  183. const player = entry.target.nodeName == "VIDEO" ? entry.target : entry.target.querySelector("VIDEO[_h5ppid]");
  184. if (!player) continue;
  185. const vpid = player.getAttribute('_h5ppid');
  186. if (!vpid) continue;
  187. if (vpid in detected_changes) continue;
  188. detected_changes[vpid] = true;
  189. const wPlayer = $hs.getPlayerBlockElement(player, true)
  190. if (!wPlayer) continue;
  191. const layoutBox = wPlayer.parentNode
  192. if (!layoutBox) continue;
  193. const tipsDom = layoutBox.querySelector('[_potTips_]');
  194. if (!tipsDom) continue;
  195.  
  196. $hs.fixNonBoxingVideoTipsPosition(tipsDom, player);
  197. window.requestAnimationFrame(() => $hs.fixNonBoxingVideoTipsPosition(tipsDom, player))
  198.  
  199. }
  200. };
  201.  
  202. const $mb = {
  203.  
  204.  
  205. nightly_isSupportQueueMicrotask: function() {
  206.  
  207. if ('_isSupportQueueMicrotask' in $mb) return $mb._isSupportQueueMicrotask;
  208.  
  209. $mb._isSupportQueueMicrotask = false;
  210. $mb.queueMicrotask = window.queueMicrotask;
  211. if (typeof $mb.queueMicrotask == 'function') {
  212. $mb._isSupportQueueMicrotask = true;
  213. }
  214.  
  215. return $mb._isSupportQueueMicrotask;
  216.  
  217. },
  218.  
  219. stable_isSupportAdvancedEventListener: function() {
  220.  
  221. if ('_isSupportAdvancedEventListener' in $mb) return $mb._isSupportAdvancedEventListener
  222. let prop = 0;
  223. document.createAttribute('z').addEventListener('z', () => 0, {
  224. get passive() {
  225. prop++;
  226. },
  227. get once() {
  228. prop++;
  229. }
  230. });
  231. return ($mb._isSupportAdvancedEventListener = (prop == 2));
  232. },
  233.  
  234. stable_isSupportPassiveEventListener: function() {
  235.  
  236. if ('_isSupportPassiveEventListener' in $mb) return $mb._isSupportPassiveEventListener
  237. let prop = 0;
  238. document.createAttribute('z').addEventListener('z', () => 0, {
  239. get passive() {
  240. prop++;
  241. }
  242. });
  243. return ($mb._isSupportPassiveEventListener = (prop == 1));
  244. },
  245.  
  246. eh_capture_passive: () => ($mb._eh_capture_passive = $mb._eh_capture_passive || ($mb.stable_isSupportPassiveEventListener() ? {
  247. capture: true,
  248. passive: true
  249. } : true)),
  250.  
  251. eh_bubble_passive: () => ($mb._eh_capture_passive = $mb._eh_capture_passive || ($mb.stable_isSupportPassiveEventListener() ? {
  252. capture: false,
  253. passive: true
  254. } : false))
  255.  
  256. }
  257.  
  258.  
  259.  
  260. Element.prototype.__matches__ = (Element.prototype.matches || Element.prototype.matchesSelector ||
  261. Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector ||
  262. Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector ||
  263. Element.prototype.matches()); // throw Error if not supported
  264.  
  265. // built-in hash - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  266. async function digestMessage(message) {
  267. return $winSafe.sha256(message)
  268. }
  269.  
  270. const dround = (x) => ~~(x + .5);
  271.  
  272. const jsonStringify_replacer = function(key, val) {
  273. if (val && (val instanceof Element || val instanceof Document)) return val.toString();
  274. return val; // return as is
  275. };
  276.  
  277. const jsonParse = function() {
  278. try {
  279. return JSON.parse.apply(this, arguments)
  280. } catch (e) {}
  281. return null;
  282. }
  283. const jsonStringify = function(obj) {
  284. try {
  285. return JSON.stringify.call(this, obj, jsonStringify_replacer)
  286. } catch (e) {}
  287. return null;
  288. }
  289.  
  290. function _postMsg() {
  291. //async is needed. or error handling for postMessage
  292. const [win, tag, ...data] = arguments;
  293. if (typeof tag == 'string') {
  294. let postMsgObj = {
  295. tag,
  296. passing: true,
  297. winOrder: _postMsg.a
  298. }
  299. try {
  300. let k = 'msg-' + (+new Date)
  301. win.document[str_postMsgData] = win.document[str_postMsgData] || {}
  302. win.document[str_postMsgData][k] = data; //direct
  303. postMsgObj.str = k;
  304. postMsgObj.stype = 1;
  305. } catch (e) {}
  306. if (!postMsgObj.stype) {
  307. postMsgObj.str = jsonStringify({
  308. d: data
  309. })
  310. if (postMsgObj.str && postMsgObj.str.length) postMsgObj.stype = 2;
  311. }
  312. if (!postMsgObj.stype) {
  313. postMsgObj.str = "" + data;
  314. postMsgObj.stype = 0;
  315. }
  316. win.postMessage(postMsgObj, '*');
  317. }
  318.  
  319. }
  320.  
  321. function postMsg() {
  322. let win = window;
  323. let a = 0;
  324. while ((win = win.parent) && ('postMessage' in win)) {
  325. _postMsg.a = ++a;
  326. _postMsg(win, ...arguments)
  327. if (win == top) break;
  328. }
  329. }
  330.  
  331.  
  332. function crossBrowserTransition(type) {
  333. if (crossBrowserTransition['_result_' + type]) return crossBrowserTransition['_result_' + type]
  334. let el = document.createElement("fakeelement");
  335.  
  336. const capital = (x) => x[0].toUpperCase() + x.substr(1);
  337. const capitalType = capital(type);
  338.  
  339. const transitions = {
  340. [type]: `${type}end`,
  341. [`O${capitalType}`]: `o${capitalType}End`,
  342. [`Moz${capitalType}`]: `${type}end`,
  343. [`Webkit${capitalType}`]: `webkit${capitalType}End`,
  344. [`MS${capitalType}`]: `MS${capitalType}End`
  345. }
  346.  
  347. for (let styleProp in transitions) {
  348. if (el.style[styleProp] !== undefined) {
  349. return (crossBrowserTransition['_result_' + type] = transitions[styleProp]);
  350. }
  351. }
  352. }
  353.  
  354. function isInOperation(elm) {
  355. let elmInFocus = elm || document.activeElement;
  356. if (!elmInFocus) return false;
  357. let res1 = elmInFocus.__matches__(
  358. 'a[href],link[href],button,input:not([type="hidden"]),select,textarea,iframe,frame,menuitem,[draggable],[contenteditable]'
  359. );
  360. return res1;
  361. }
  362.  
  363. const fn_toString = (f, n = 50) => {
  364. let s = (f + "");
  365. if (s.length > 2 * n + 5) {
  366. s = s.substr(0, n) + ' ... ' + s.substr(-n);
  367. }
  368. return s
  369. };
  370.  
  371. function consoleLog() {
  372. if (!_debug_h5p_logging_) return;
  373. if (isIframe) postMsg('consoleLog', ...arguments);
  374. else console.log.apply(console, arguments);
  375. }
  376.  
  377. function consoleLogF() {
  378. if (isIframe) postMsg('consoleLog', ...arguments);
  379. else console.log.apply(console, arguments);
  380. }
  381.  
  382. class AFLooperArray extends Array {
  383. constructor() {
  384. super();
  385. this.activeLoopsCount = 0;
  386. this.cid = 0;
  387. this.loopingFrame = this.loopingFrame.bind(this);
  388. }
  389.  
  390. loopingFrame() {
  391. if (!this.cid) return; //cancelled
  392. for (const opt of this) {
  393. if (opt.isFunctionLooping) opt.fn();
  394. }
  395. }
  396.  
  397. get isArrayLooping() {
  398. return this.cid > 0;
  399. }
  400.  
  401. loopStart() {
  402. this.cid = $ws.setInterval(this.loopingFrame, 300);
  403. }
  404. loopStop() {
  405. if (this.cid) $ws.clearInterval(this.cid);
  406. this.cid = 0;
  407. }
  408. appendLoop(fn) {
  409. if (typeof fn != 'function' || !this) return;
  410. const opt = new AFLooperFunc(fn, this);
  411. super.push(opt);
  412. return opt;
  413. }
  414. }
  415.  
  416. class AFLooperFunc {
  417. constructor(fn, bind) {
  418. this._looping = false;
  419. this.bind = bind;
  420. this.fn = fn;
  421. }
  422. get isFunctionLooping() {
  423. return this._looping;
  424. }
  425. loopingStart() {
  426. if (this._looping === false) {
  427. this._looping = true;
  428. if (++this.bind.activeLoopsCount == 1) this.bind.loopStart();
  429. }
  430. }
  431. loopingStop() {
  432. if (this._looping === true) {
  433. this._looping = false;
  434. if (--this.bind.activeLoopsCount == 0) this.bind.loopStop();
  435. }
  436. }
  437. }
  438.  
  439. function decimalEqual(a, b) {
  440. return Math.round(a * 100000000) == Math.round(b * 100000000)
  441. }
  442.  
  443. function nonZeroNum(a) {
  444. return a > 0 || a < 0;
  445. }
  446.  
  447. class PlayerConf {
  448.  
  449. get scaleFactor() {
  450. return this.mFactor * this.vFactor;
  451. }
  452.  
  453. cssTransform() {
  454.  
  455. const playerConf = this;
  456. const player = playerConf.domElement;
  457. if (!player) return;
  458. const videoScale = playerConf.scaleFactor;
  459.  
  460. let {
  461. x,
  462. y
  463. } = playerConf.translate;
  464.  
  465. let [_x, _y] = ((playerConf.rotate % 180) == 90) ? [y, x] : [x, y];
  466.  
  467.  
  468. if ((playerConf.rotate % 360) == 270) _x = -_x;
  469. if ((playerConf.rotate % 360) == 90) _y = -_y;
  470.  
  471. var s = [
  472. playerConf.rotate > 0 ? 'rotate(' + playerConf.rotate + 'deg)' : '',
  473. !decimalEqual(videoScale, 1.0) ? 'scale(' + videoScale + ')' : '',
  474. (nonZeroNum(_x) || nonZeroNum(_y)) ? `translate(${_x}px, ${_y}px)` : '',
  475. ];
  476.  
  477. player.style.transform = s.join(' ').trim()
  478.  
  479. }
  480.  
  481. constructor() {
  482.  
  483. this.translate = {
  484. x: 0,
  485. y: 0
  486. };
  487. this.rotate = 0;
  488. this.mFactor = 1.0;
  489. this.vFactor = 1.0;
  490. this.fps = 30;
  491. this.filter_key = {};
  492. this.filter_view_units = {
  493. 'hue-rotate': 'deg',
  494. 'blur': 'px'
  495. };
  496. this.filterReset();
  497.  
  498. }
  499.  
  500. setFilter(prop, f) {
  501.  
  502. let oldValue = this.filter_key[prop];
  503. if (typeof oldValue != 'number') return;
  504. let newValue = f(oldValue)
  505. if (oldValue != newValue) {
  506.  
  507. newValue = +newValue.toFixed(6); //javascript bug
  508.  
  509. }
  510.  
  511. this.filter_key[prop] = newValue
  512. this.filterSetup();
  513.  
  514. return newValue;
  515.  
  516.  
  517.  
  518. }
  519.  
  520. filterSetup(options) {
  521.  
  522. let ums = GM_getValue("unsharpen_mask")
  523. if (!ums) ums = ""
  524.  
  525. let view = []
  526. let playerElm = $hs.player();
  527. if (!playerElm) return;
  528. for (let view_key in this.filter_key) {
  529. let filter_value = +((+this.filter_key[view_key] || 0).toFixed(3))
  530. let addTo = true;
  531. switch (view_key) {
  532. case 'brightness':
  533. /* fall through */
  534. case 'contrast':
  535. /* fall through */
  536. case 'saturate':
  537. if (decimalEqual(filter_value, 1.0)) addTo = false;
  538. break;
  539. case 'hue-rotate':
  540. /* fall through */
  541. case 'blur':
  542. if (decimalEqual(filter_value, 0.0)) addTo = false;
  543. break;
  544. }
  545. let view_unit = this.filter_view_units[view_key] || ''
  546. if (addTo) view.push(`${view_key}(${filter_value}${view_unit})`)
  547. this.filter_key[view_key] = Number(+this.filter_key[view_key] || 0)
  548. }
  549. if (ums) view.push(`url("#_h5p_${ums}")`);
  550. if (options && options.grey) view.push('url("#grey1")');
  551. playerElm.style.filter = view.join(' ').trim(); //performance in firefox is bad
  552. }
  553.  
  554. filterReset() {
  555. this.filter_key['brightness'] = 1.0
  556. this.filter_key['contrast'] = 1.0
  557. this.filter_key['saturate'] = 1.0
  558. this.filter_key['hue-rotate'] = 0.0
  559. this.filter_key['blur'] = 0.0
  560. this.filterSetup()
  561. }
  562.  
  563. }
  564.  
  565. const Store = {
  566. prefix: '_h5_player',
  567. save: function(k, v) {
  568. if (!Store.available()) return false;
  569. if (typeof v != 'string') return false;
  570. Store.LS.setItem(Store.prefix + k, v)
  571. let sk = fn_toString(k + "", 30);
  572. let sv = fn_toString(v + "", 30);
  573. consoleLog(`localStorage Saved "${sk}" = "${sv}"`)
  574. return true;
  575.  
  576. },
  577. read: function(k) {
  578. if (!Store.available()) return false;
  579. let v = Store.LS.getItem(Store.prefix + k)
  580. let sk = fn_toString(k + "", 30);
  581. let sv = fn_toString(v + "", 30);
  582. consoleLog(`localStorage Read "${sk}" = "${sv}"`);
  583. return v;
  584.  
  585. },
  586. remove: function(k) {
  587.  
  588. if (!Store.available()) return false;
  589. Store.LS.removeItem(Store.prefix + k)
  590. let sk = fn_toString(k + "", 30);
  591. consoleLog(`localStorage Removed "${sk}"`)
  592. return true;
  593. },
  594. clearInvalid: function(sVersion) {
  595. if (!Store.available()) return false;
  596.  
  597. //let sVersion=1814;
  598. if (+Store.read('_sVersion_') < sVersion) {
  599. Store._keys()
  600. .filter(s => s.indexOf(Store.prefix) === 0)
  601. .forEach(key => window.localStorage.removeItem(key))
  602. Store.save('_sVersion_', sVersion + '')
  603. return 2;
  604. }
  605. return 1;
  606.  
  607. },
  608. available: function() {
  609. if (Store.LS) return true;
  610. if (!window) return false;
  611. const localStorage = window.localStorage;
  612. if (!localStorage) return false;
  613. if (typeof localStorage != 'object') return false;
  614. if (!('getItem' in localStorage)) return false;
  615. if (!('setItem' in localStorage)) return false;
  616. Store.LS = localStorage;
  617. return true;
  618.  
  619. },
  620. _keys: function() {
  621. return Object.keys(localStorage);
  622. },
  623. _setItem: function(key, value) {
  624. return localStorage.setItem(key, value)
  625. },
  626. _getItem: function(key) {
  627. return localStorage.getItem(key)
  628. },
  629. _removeItem: function(key) {
  630. return localStorage.removeItem(key)
  631. }
  632.  
  633. }
  634.  
  635. const domTool = {
  636. nopx: (x) => +x.replace('px', ''),
  637. cssWH: function(m, r) {
  638. if (!r) r = getComputedStyle(m, null);
  639. let c = (x) => +x.replace('px', '');
  640. return {
  641. w: m.offsetWidth || c(r.width),
  642. h: m.offsetHeight || c(r.height)
  643. }
  644. },
  645. _isActionBox_1: function(vEl, pEl) {
  646.  
  647. const vElCSS = domTool.cssWH(vEl);
  648. let vElCSSw = vElCSS.w;
  649. let vElCSSh = vElCSS.h;
  650.  
  651. let vElx = vEl;
  652. const res = [];
  653. //let mLevel = 0;
  654. if (vEl && pEl && vEl != pEl && pEl.contains(vEl)) {
  655. while (vElx && vElx != pEl) {
  656. vElx = vElx.parentNode;
  657. let vElx_css = null;
  658. if (isShadowRoot(vElx)) {} else {
  659. vElx_css = getComputedStyle(vElx, null);
  660. let vElx_wp = domTool.nopx(vElx_css.paddingLeft) + domTool.nopx(vElx_css.paddingRight)
  661. vElCSSw += vElx_wp
  662. let vElx_hp = domTool.nopx(vElx_css.paddingTop) + domTool.nopx(vElx_css.paddingBottom)
  663. vElCSSh += vElx_hp
  664. }
  665. res.push({
  666. //level: ++mLevel,
  667. padW: vElCSSw,
  668. padH: vElCSSh,
  669. elm: vElx,
  670. css: vElx_css
  671. })
  672.  
  673. }
  674. }
  675.  
  676. // in the array, each item is the parent of video player
  677. //res.vEl_cssWH = vElCSS
  678.  
  679. return res;
  680.  
  681. },
  682. _isActionBox: function(vEl, walkRes, pEl_idx) {
  683.  
  684. function absDiff(w1, w2, h1, h2) {
  685. const w = (w1 - w2),
  686. h = h1 - h2;
  687. return [(w > 0 ? w : -w), (h > 0 ? h : -h)]
  688. }
  689.  
  690. function midPoint(rect) {
  691. return {
  692. x: (rect.left + rect.right) / 2,
  693. y: (rect.top + rect.bottom) / 2
  694. }
  695. }
  696.  
  697. const parentCount = walkRes.length;
  698. if (pEl_idx >= 0 && pEl_idx < parentCount) {} else {
  699. return;
  700. }
  701. const pElr = walkRes[pEl_idx]
  702. if (!pElr.css) {
  703. //shadowRoot
  704. return true;
  705. }
  706.  
  707. const pEl = pElr.elm;
  708.  
  709. //prevent activeElement==body
  710. const pElCSS = domTool.cssWH(pEl, pElr.css);
  711.  
  712. //check prediction of parent dimension
  713. const d1v = absDiff(pElCSS.w, pElr.padW, pElCSS.h, pElr.padH)
  714.  
  715. const d1x = d1v[0] < 10
  716. const d1y = d1v[1] < 10;
  717.  
  718. if (d1x && d1y) return true; //both edge along the container - fit size
  719. if (!d1x && !d1y) return false; //no edge along the container - body contain the video element, fixed width&height
  720.  
  721. //case: youtube video fullscreen
  722.  
  723. //check centre point
  724.  
  725. const pEl_rect = pEl.getBoundingClientRect()
  726. const vEl_rect = vEl.getBoundingClientRect()
  727.  
  728. const pEl_center = midPoint(pEl_rect)
  729. const vEl_center = midPoint(vEl_rect)
  730.  
  731. const d2v = absDiff(pEl_center.x, vEl_center.x, pEl_center.y, vEl_center.y);
  732.  
  733. const d2x = d2v[0] < 10;
  734. const d2y = d2v[1] < 10;
  735.  
  736. return (d2x && d2y);
  737.  
  738. },
  739. getRect: function(element) {
  740. let rect = element.getBoundingClientRect();
  741. let scroll = domTool.getScroll();
  742. return {
  743. pageX: rect.left + scroll.left,
  744. pageY: rect.top + scroll.top,
  745. screenX: rect.left,
  746. screenY: rect.top
  747. };
  748. },
  749. getScroll: function() {
  750. return {
  751. left: document.documentElement.scrollLeft || document.body.scrollLeft,
  752. top: document.documentElement.scrollTop || document.body.scrollTop
  753. };
  754. },
  755. getClient: function() {
  756. return {
  757. width: document.compatMode == 'CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth,
  758. height: document.compatMode == 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight
  759. };
  760. },
  761. addStyle: //GM_addStyle,
  762. function(css, head) {
  763. if (!head) {
  764. let _doc = document.documentElement;
  765. head = domAppender(_doc);
  766. }
  767. let doc = head.ownerDocument;
  768. let style = doc.createElement('style');
  769. style.type = 'text/css';
  770. style.textContent = css;
  771. head.appendChild(style);
  772. //console.log(document.head,style,'add style')
  773. return style;
  774. },
  775. eachParentNode: function(dom, fn) {
  776. let parent = dom.parentNode
  777. while (parent) {
  778. let isEnd = fn(parent, dom)
  779. parent = parent.parentNode
  780. if (isEnd) {
  781. break
  782. }
  783. }
  784. },
  785.  
  786. hideDom: function hideDom(selector) {
  787. let dom = document.querySelector(selector)
  788. if (dom) {
  789. $ws.requestAnimationFrame(function() {
  790. dom.style.opacity = 0;
  791. dom.style.transform = 'translate(-9999px)';
  792. dom = null;
  793. })
  794. }
  795. }
  796. };
  797.  
  798. const handle = {
  799.  
  800.  
  801. afPlaybackRecording: async function() {
  802. const opts = this;
  803.  
  804. let qTime = +new Date;
  805. if (qTime >= opts.pTime) {
  806. opts.pTime = qTime + opts.timeDelta; //prediction of next Interval
  807. opts.savePlaybackProgress()
  808. }
  809.  
  810. },
  811. savePlaybackProgress: function() {
  812.  
  813. //this refer to endless's opts
  814. let player = this.player;
  815.  
  816. let _uid = this.player_uid; //_h5p_uid_encrypted
  817. if (!_uid) return;
  818.  
  819. let shallSave = true;
  820. let currentTimeToSave = ~~player.currentTime;
  821.  
  822. if (this._lastSave == currentTimeToSave) shallSave = false;
  823.  
  824. if (shallSave) {
  825.  
  826. this._lastSave = currentTimeToSave
  827.  
  828. //console.log('aasas',this.player_uid, shallSave, '_play_progress_'+_uid, currentTimeToSave)
  829.  
  830. Store.save('_play_progress_' + _uid, jsonStringify({
  831. 't': currentTimeToSave
  832. }))
  833.  
  834. }
  835. //console.log('playback logged')
  836.  
  837. },
  838. playingWithRecording: function() {
  839. let player = this.player;
  840. if (!player.paused && !this.isFunctionLooping) {
  841. let player = this.player;
  842. let _uid = player.getAttribute('_h5p_uid_encrypted') || ''
  843. if (_uid) {
  844. this.player_uid = _uid;
  845. this.pTime = 0;
  846. this.loopingStart();
  847. }
  848. }
  849. }
  850.  
  851. };
  852.  
  853. class Momentary extends Map {
  854. act(uniqueId, fn_start, fn_end, delay) {
  855. if (!uniqueId) return;
  856. uniqueId = uniqueId + "";
  857. const last_cid = this.get(uniqueId);
  858. if (last_cid > 0) clearTimeout(last_cid);
  859. fn_start();
  860. const new_cid = setTimeout(fn_end, delay)
  861. this.set(uniqueId, new_cid)
  862. }
  863. }
  864.  
  865. const momentary = new Momentary();
  866.  
  867. const $hs = {
  868.  
  869. /* 提示文本的字號 */
  870. fontSize: 16,
  871. enable: true,
  872. playerInstance: null,
  873. playbackRate: 1,
  874. /* 快進快退步長 */
  875. skipStep: 5,
  876.  
  877. /* 獲取當前播放器的實例 */
  878. player: function() {
  879. let res = $hs.playerInstance || null;
  880. if (res && res.parentNode == null) {
  881. $hs.playerInstance = null;
  882. res = null;
  883. }
  884.  
  885. if (res == null) {
  886. for (let k in playerConfs) {
  887. let playerConf = playerConfs[k];
  888. if (playerConf && playerConf.domElement && playerConf.domElement.parentNode) return playerConf.domElement;
  889. }
  890. }
  891. return res;
  892. },
  893.  
  894. pictureInPicture: function(videoElm) {
  895. if (document.pictureInPictureElement) {
  896. document.exitPictureInPicture();
  897. } else if ('requestPictureInPicture' in videoElm) {
  898. videoElm.requestPictureInPicture()
  899. } else {
  900. $hs.tips('PIP is not supported.');
  901. }
  902. },
  903.  
  904. getPlayerConf: function(video) {
  905.  
  906. if (!video) return null;
  907. let vpid = video.getAttribute('_h5ppid') || null;
  908. if (!vpid) return null;
  909. return playerConfs[vpid] || null;
  910.  
  911. },
  912. debug01: function(evt, videoActive) {
  913.  
  914. if (!$hs.eventHooks) {
  915. document.__h5p_eventhooks = ($hs.eventHooks = {
  916. _debug_: []
  917. });
  918. }
  919. $hs.eventHooks._debug_.push([videoActive, evt.type]);
  920. // console.log('h5p eventhooks = document.__h5p_eventhooks')
  921. },
  922.  
  923. swtichPlayerInstance: function() {
  924.  
  925. let newPlayerInstance = null;
  926. const ONLY_PLAYING_NONE = 0x4A00;
  927. const ONLY_PLAYING_MORE_THAN_ONE = 0x5A00;
  928. let onlyPlayingInstance = ONLY_PLAYING_NONE;
  929. for (let k in playerConfs) {
  930. let playerConf = playerConfs[k] || {};
  931. let {
  932. domElement,
  933. domActive
  934. } = playerConf;
  935. if (domElement) {
  936. if (domActive & DOM_ACTIVE_INVALID_PARENT) continue;
  937. if (!domElement.parentNode) {
  938. playerConf.domActive |= DOM_ACTIVE_INVALID_PARENT;
  939. continue;
  940. }
  941. if (domActive & DOM_ACTIVE_MOUSE_CLICK) {
  942. newPlayerInstance = domElement
  943. break;
  944. }
  945. if (domActive & DOM_ACTIVE_ONCE_PLAYED && (domActive & DOM_ACTIVE_DELAYED_PAUSED) == 0) {
  946. if (onlyPlayingInstance == ONLY_PLAYING_NONE) onlyPlayingInstance = domElement;
  947. else onlyPlayingInstance = ONLY_PLAYING_MORE_THAN_ONE;
  948. }
  949. }
  950. }
  951. if (newPlayerInstance == null && onlyPlayingInstance.nodeType == 1) {
  952. newPlayerInstance = onlyPlayingInstance;
  953. }
  954.  
  955. $hs.playerInstance = newPlayerInstance
  956.  
  957.  
  958. },
  959.  
  960. mouseMoveCount: 0,
  961.  
  962. handlerVideoPlaying: function(evt) {
  963. const videoElm = evt.target || this || null;
  964.  
  965. if (!videoElm || videoElm.nodeName != "VIDEO") return;
  966.  
  967. const vpid = videoElm.getAttribute('_h5ppid')
  968.  
  969. if (!vpid) return;
  970.  
  971.  
  972.  
  973. Promise.resolve().then(() => {
  974.  
  975. if ($hs.cid_playHook > 0) clearTimeout($hs.cid_playHook);
  976. $hs.cid_playHook = setTimeout(function() {
  977. let onlyPlayed = null;
  978. for (var k in playerConfs) {
  979. if (k == vpid) {
  980. if (playerConfs[k].domElement.paused === false) onlyPlayed = true;
  981. } else if (playerConfs[k].domElement.paused === false) {
  982. onlyPlayed = false;
  983. break;
  984. }
  985. }
  986. if (onlyPlayed === true) {
  987. $hs.focusHookVDoc = getRoot(videoElm)
  988. $hs.focusHookVId = vpid
  989. }
  990. $bv.boostVideoPerformanceActivate();
  991.  
  992. }, 100)
  993.  
  994. }).then(() => {
  995.  
  996. const playerConf = $hs.getPlayerConf(videoElm)
  997.  
  998. $hs._actionBoxObtain(videoElm);
  999. if (playerConf) {
  1000. if (playerConf.timeout_pause > 0) playerConf.timeout_pause = clearTimeout(playerConf.timeout_pause);
  1001. playerConf.lastPauseAt = 0
  1002. playerConf.domActive |= DOM_ACTIVE_ONCE_PLAYED;
  1003. playerConf.domActive &= ~DOM_ACTIVE_DELAYED_PAUSED;
  1004. }
  1005.  
  1006. }).then(() => {
  1007.  
  1008. $hs.swtichPlayerInstance();
  1009.  
  1010.  
  1011.  
  1012. $hs.onVideoTriggering();
  1013.  
  1014. }).then(() => {
  1015.  
  1016. if (!$hs.enable) return $hs.tips(false);
  1017.  
  1018. if (videoElm._isThisPausedBefore_) consoleLog('resumed')
  1019. let _pausedbefore_ = videoElm._isThisPausedBefore_
  1020.  
  1021. if (videoElm.playpause_cid) {
  1022. clearTimeout(videoElm.playpause_cid);
  1023. videoElm.playpause_cid = 0;
  1024. }
  1025. let _last_paused = videoElm._last_paused
  1026. videoElm._last_paused = videoElm.paused
  1027. if (_last_paused === !videoElm.paused) {
  1028. videoElm.playpause_cid = setTimeout(() => {
  1029. if (videoElm.paused === !_last_paused && !videoElm.paused && _pausedbefore_) {
  1030. $hs.tips('Playback resumed', undefined, 2500)
  1031. }
  1032. }, 90)
  1033. }
  1034.  
  1035. /* 播放的時候進行相關同步操作 */
  1036.  
  1037. if (!videoElm._record_continuous) {
  1038.  
  1039. /* 同步之前設定的播放速度 */
  1040. $hs.setPlaybackRate()
  1041.  
  1042. if (!_endlessloop) _endlessloop = new AFLooperArray();
  1043.  
  1044. videoElm._record_continuous = _endlessloop.appendLoop(handle.afPlaybackRecording);
  1045. videoElm._record_continuous._lastSave = -999;
  1046.  
  1047. videoElm._record_continuous.timeDelta = 2000;
  1048. videoElm._record_continuous.player = videoElm
  1049. videoElm._record_continuous.savePlaybackProgress = handle.savePlaybackProgress;
  1050. videoElm._record_continuous.playingWithRecording = handle.playingWithRecording;
  1051. }
  1052.  
  1053. videoElm._record_continuous.playingWithRecording(videoElm); //try to start recording
  1054.  
  1055. videoElm._isThisPausedBefore_ = false;
  1056.  
  1057. })
  1058.  
  1059. },
  1060. handlerVideoPause: function(evt) {
  1061.  
  1062. const videoElm = evt.target || this || null;
  1063.  
  1064. if (!videoElm || videoElm.nodeName != "VIDEO") return;
  1065.  
  1066. const vpid = videoElm.getAttribute('_h5ppid')
  1067.  
  1068. if (!vpid) return;
  1069.  
  1070.  
  1071. Promise.resolve().then(() => {
  1072.  
  1073. if ($hs.cid_playHook > 0) clearTimeout($hs.cid_playHook);
  1074. $hs.cid_playHook = setTimeout(function() {
  1075. let allPaused = true;
  1076. for (var k in playerConfs) {
  1077. if (playerConfs[k].domElement.paused === false) {
  1078. allPaused = false;
  1079. break;
  1080. }
  1081. }
  1082. if (allPaused) {
  1083. $hs.focusHookVDoc = getRoot(videoElm)
  1084. $hs.focusHookVId = vpid
  1085. }
  1086. $bv.boostVideoPerformanceDeactivate();
  1087. }, 100)
  1088.  
  1089. }).then(() => {
  1090.  
  1091. const playerConf = $hs.getPlayerConf(videoElm)
  1092. if (playerConf) {
  1093. playerConf.lastPauseAt = +new Date;
  1094. playerConf.timeout_pause = setTimeout(() => {
  1095. if (playerConf.lastPauseAt > 0) playerConf.domActive |= DOM_ACTIVE_DELAYED_PAUSED;
  1096. }, 600)
  1097. }
  1098.  
  1099. }).then(() => {
  1100.  
  1101. if (!$hs.enable) return $hs.tips(false);
  1102. consoleLog('pause')
  1103. videoElm._isThisPausedBefore_ = true;
  1104.  
  1105. let _last_paused = videoElm._last_paused
  1106. videoElm._last_paused = videoElm.paused
  1107. if (videoElm.playpause_cid) {
  1108. clearTimeout(videoElm.playpause_cid);
  1109. videoElm.playpause_cid = 0;
  1110. }
  1111. if (_last_paused === !videoElm.paused) {
  1112. videoElm.playpause_cid = setTimeout(() => {
  1113. if (videoElm.paused === !_last_paused && videoElm.paused) {
  1114. $hs._tips(videoElm, 'Playback paused', undefined, 2500)
  1115. }
  1116. }, 90)
  1117. }
  1118.  
  1119.  
  1120. if (videoElm._record_continuous && videoElm._record_continuous.isFunctionLooping) {
  1121. setTimeout(function() {
  1122. if (videoElm.paused === true && !videoElm._record_continuous.isFunctionLooping) videoElm._record_continuous.savePlaybackProgress(); //savePlaybackProgress once before stopping //handle.savePlaybackProgress;
  1123. }, 380)
  1124. videoElm._record_continuous.loopingStop();
  1125. }
  1126.  
  1127.  
  1128. })
  1129.  
  1130.  
  1131. },
  1132. handlerVideoVolumeChange: function(evt) {
  1133.  
  1134. const videoElm = evt.target || this || null;
  1135.  
  1136. if(videoElm.nodeName!="VIDEO")return;
  1137. if (videoElm.volume >= 0) {} else {
  1138. return;
  1139. }
  1140.  
  1141. if($hs._volume_change_counter>0)return;
  1142. $hs._volume_change_counter=($hs._volume_change_counter||0)+1
  1143.  
  1144. window.requestAnimationFrame(function(){
  1145.  
  1146. Promise.resolve().then(() => {
  1147.  
  1148. let makeTips = false;
  1149.  
  1150. let cVol = videoElm.volume;
  1151. let cMuted = videoElm.muted;
  1152.  
  1153. if (cVol === videoElm._volume_p && cMuted === videoElm._muted_p) {
  1154. // nothing changed
  1155. } else if (cVol === videoElm._volume_p && cMuted !== videoElm._muted_p) {
  1156. // muted changed
  1157. } else { // cVol != pVol
  1158.  
  1159. // only volume changed
  1160.  
  1161. let shallShowTips = videoElm._volume >= 0; //prevent initialization
  1162.  
  1163. if (!cVol) {
  1164. videoElm.muted = true;
  1165. } else if (cMuted) {
  1166. videoElm.muted = false;
  1167. videoElm._volume = cVol;
  1168. } else if (!cMuted) {
  1169. videoElm._volume = cVol;
  1170. }
  1171. consoleLog('volume changed');
  1172.  
  1173. if (shallShowTips) makeTips =true;
  1174.  
  1175. }
  1176.  
  1177. videoElm._volume_p = cVol;
  1178. videoElm._muted_p = cMuted;
  1179.  
  1180. return makeTips;
  1181.  
  1182. }).then((makeTips)=>{
  1183.  
  1184. if(makeTips) $hs._tips(videoElm, 'Volume: ' + dround(videoElm.volume * 100) + '%', undefined, 3000);
  1185.  
  1186. $hs._volume_change_counter=0;
  1187.  
  1188. })
  1189.  
  1190. })
  1191.  
  1192.  
  1193.  
  1194. },
  1195. handlerVideoLoadedMetaData: function(evt) {
  1196. const videoElm = evt.target || this || null;
  1197.  
  1198. if (!videoElm || videoElm.nodeName != "VIDEO") return;
  1199.  
  1200. Promise.resolve().then(() => {
  1201.  
  1202. consoleLog('video size', videoElm.videoWidth + ' x ' + videoElm.videoHeight);
  1203.  
  1204. let vpid = videoElm.getAttribute('_h5ppid') || null;
  1205. if (!vpid || !videoElm.currentSrc) return;
  1206.  
  1207. if ($hs.varSrcList[vpid] != videoElm.currentSrc) {
  1208. $hs.varSrcList[vpid] = videoElm.currentSrc;
  1209. $hs.videoSrcFound(videoElm);
  1210. $hs._actionBoxObtain(videoElm);
  1211. }
  1212. if (!videoElm._onceVideoLoaded) {
  1213. videoElm._onceVideoLoaded = true;
  1214. playerConfs[vpid].domActive |= DOM_ACTIVE_SRC_LOADED;
  1215. }
  1216. })
  1217.  
  1218. },
  1219. handlerElementMouseEnter: function(evt) {
  1220. if ($hs.intVideoInitCount > 0) {} else {
  1221. return;
  1222. }
  1223.  
  1224.  
  1225. Promise.resolve().then(() => {
  1226.  
  1227. const actionBoxRelation = $hs.getActionBoxRelationFromDOM(evt.target);
  1228. if (!actionBoxRelation) return;
  1229. const actionBox = actionBoxRelation.actionBox
  1230. if (!actionBox) return;
  1231. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1232. const videoElm = actionBoxRelation.player;
  1233. if (!videoElm) return;
  1234.  
  1235. $hs._actionBoxObtain(videoElm);
  1236.  
  1237.  
  1238. return videoElm;
  1239.  
  1240. }).then(videoElm => {
  1241.  
  1242. if (!videoElm) return;
  1243.  
  1244.  
  1245. const playerConf = $hs.getPlayerConf(videoElm)
  1246. if (playerConf) {
  1247. momentary.act("actionBoxMouseEnter",
  1248. () => {
  1249. playerConf.domActive |= DOM_ACTIVE_MOUSE_IN;
  1250. },
  1251. () => {},
  1252. 300)
  1253. }
  1254.  
  1255.  
  1256. delayCall('$$VideoMouseMove', function() {
  1257.  
  1258.  
  1259. if (!$hs.cursorHidden) {
  1260. if (playerConf.domActive & DOM_ACTIVE_MOUSE_IN) $hs.playerActionEnter(videoElm);
  1261. }
  1262. }, 1240)
  1263.  
  1264. })
  1265.  
  1266. },
  1267. handlerElementMouseLeave: function(evt) {
  1268. if ($hs.intVideoInitCount > 0) {} else {
  1269. return;
  1270. }
  1271.  
  1272.  
  1273. Promise.resolve().then(() => {
  1274.  
  1275. const actionBoxRelation = $hs.getActionBoxRelationFromDOM(evt.target);
  1276. if (!actionBoxRelation) return;
  1277. const actionBox = actionBoxRelation.actionBox
  1278. if (!actionBox) return;
  1279. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1280. const videoElm = actionBoxRelation.player;
  1281. if (!videoElm) return;
  1282.  
  1283. $hs._actionBoxObtain(videoElm);
  1284.  
  1285. return videoElm
  1286.  
  1287. }).then((videoElm) => {
  1288.  
  1289. if (!videoElm) return;
  1290.  
  1291. const playerConf = $hs.getPlayerConf(videoElm)
  1292. if (playerConf) {
  1293. momentary.act("actionBoxMouseEnter",
  1294. () => {
  1295. playerConf.domActive &= ~DOM_ACTIVE_MOUSE_IN;
  1296. },
  1297. () => {},
  1298. 300)
  1299. }
  1300.  
  1301.  
  1302. $hs.playerActionLeave()
  1303.  
  1304. })
  1305.  
  1306.  
  1307. },
  1308. handlerElementMouseDown: function(evt) {
  1309.  
  1310. if ($hs.intVideoInitCount > 0) {} else {
  1311. return;
  1312. }
  1313.  
  1314. Promise.resolve().then(() => {
  1315.  
  1316.  
  1317. if (document.readyState != "complete") return;
  1318.  
  1319.  
  1320. function notAtVideo() {
  1321. if ($hs.focusHookVDoc) $hs.focusHookVDoc = null
  1322. if ($hs.focusHookVId) $hs.focusHookVId = ''
  1323. }
  1324.  
  1325.  
  1326. const actionBoxRelation = $hs.getActionBoxRelationFromDOM(evt.target);
  1327. if (!actionBoxRelation) return notAtVideo();
  1328. const actionBox = actionBoxRelation.actionBox
  1329. if (!actionBox) return notAtVideo();
  1330. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1331. const videoElm = actionBoxRelation.player;
  1332. if (!videoElm) return notAtVideo();
  1333.  
  1334. if (vpid) {
  1335. $hs.focusHookVDoc = getRoot(videoElm)
  1336. $hs.focusHookVId = vpid
  1337. }
  1338.  
  1339.  
  1340.  
  1341. $hs._actionBoxObtain(videoElm);
  1342.  
  1343. return videoElm
  1344.  
  1345. }).then((videoElm) => {
  1346.  
  1347. if (!videoElm) return;
  1348.  
  1349. const playerConf = $hs.getPlayerConf(videoElm)
  1350. if (playerConf) {
  1351. momentary.act("actionBoxClicking",
  1352. () => {
  1353. playerConf.domActive |= DOM_ACTIVE_MOUSE_CLICK;
  1354. },
  1355. () => {
  1356. playerConf.domActive &= ~DOM_ACTIVE_MOUSE_CLICK;
  1357. },
  1358. 300)
  1359. }
  1360. $hs.swtichPlayerInstance();
  1361.  
  1362. })
  1363.  
  1364. },
  1365. handlerElementWheelTuneVolume: function(evt) { //shift + wheel
  1366.  
  1367. if ($hs.intVideoInitCount > 0) {} else {
  1368. return;
  1369. }
  1370.  
  1371. const actionBoxRelation = $hs.getActionBoxRelationFromDOM(evt.target);
  1372. if (!actionBoxRelation) return;
  1373. const actionBox = actionBoxRelation.actionBox
  1374. if (!actionBox) return;
  1375. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1376. const videoElm = actionBoxRelation.player;
  1377. if (!videoElm) return;
  1378.  
  1379.  
  1380. if (!evt.shiftKey) return;
  1381. if (evt.deltaY) {
  1382. let player = $hs.player();
  1383. if (!player || player != videoElm) return;
  1384.  
  1385. if (evt.deltaY > 0) {
  1386.  
  1387. Promise.resolve().then(() => {
  1388.  
  1389.  
  1390. $hs._actionBoxObtain(videoElm);
  1391.  
  1392. if ((player.muted && player.volume === 0) && player._volume > 0) {
  1393.  
  1394. player.muted = false;
  1395. player.volume = player._volume;
  1396. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  1397. player.muted = false;
  1398. }
  1399. $hs.tuneVolume(-0.05)
  1400.  
  1401. })
  1402.  
  1403. evt.stopPropagation()
  1404. evt.preventDefault()
  1405. return false
  1406.  
  1407. } else if (evt.deltaY < 0) {
  1408.  
  1409. Promise.resolve().then(() => {
  1410.  
  1411.  
  1412. $hs._actionBoxObtain(videoElm);
  1413.  
  1414. if ((player.muted && player.volume === 0) && player._volume > 0) {
  1415. player.muted = false;
  1416. player.volume = player._volume;
  1417. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  1418. player.muted = false;
  1419. }
  1420. $hs.tuneVolume(+0.05)
  1421.  
  1422. })
  1423.  
  1424. evt.stopPropagation()
  1425. evt.preventDefault()
  1426. return false
  1427.  
  1428. }
  1429. }
  1430. },
  1431. handlerDocFocusOut: function(e) {
  1432. let doc = this;
  1433. $hs.focusFxLock = true;
  1434. $ws.requestAnimationFrame(function() {
  1435. $hs.focusFxLock = false;
  1436. if (!$hs.enable) $hs.tips(false);
  1437. else
  1438. if (!doc.hasFocus() && $hs.player() && !$hs.isLostFocus) {
  1439. $hs.isLostFocus = true;
  1440. consoleLog('doc.focusout')
  1441. //$hs.tips('focus is lost', -1);
  1442. }
  1443. });
  1444. },
  1445. handlerDocFocusIn: function(e) {
  1446. let doc = this;
  1447. if ($hs.focusFxLock) return;
  1448. $ws.requestAnimationFrame(function() {
  1449.  
  1450. if ($hs.focusFxLock) return;
  1451. if (!$hs.enable) $hs.tips(false);
  1452. else
  1453. if (doc.hasFocus() && $hs.player() && $hs.isLostFocus) {
  1454. $hs.isLostFocus = false;
  1455. consoleLog('doc.focusin')
  1456. $hs.tips(false);
  1457.  
  1458. }
  1459. });
  1460. },
  1461.  
  1462. handlerWinMessage: async function(e) {
  1463. let tag, ed;
  1464. if (typeof e.data == 'object' && typeof e.data.tag == 'string') {
  1465. tag = e.data.tag;
  1466. ed = e.data
  1467. } else {
  1468. return;
  1469. }
  1470. let msg = null,
  1471. success = 0;
  1472. let msg_str, msg_stype, p
  1473. switch (tag) {
  1474. case 'consoleLog':
  1475. msg_str = ed.str;
  1476. msg_stype = ed.stype;
  1477. if (msg_stype === 1) {
  1478. msg = (document[str_postMsgData] || {})[msg_str] || [];
  1479. success = 1;
  1480. } else if (msg_stype === 2) {
  1481. msg = jsonParse(msg_str);
  1482. if (msg && msg.d) {
  1483. success = 2;
  1484. msg = msg.d;
  1485. }
  1486. } else {
  1487. msg = msg_str
  1488. }
  1489. p = (ed.passing && ed.winOrder) ? [' | from win-' + ed.winOrder] : [];
  1490. if (success) {
  1491. console.log(...msg, ...p)
  1492. //document[ed.data]=null; // also delete the information
  1493. } else {
  1494. console.log('msg--', msg, ...p, ed);
  1495. }
  1496. break;
  1497.  
  1498. }
  1499. },
  1500.  
  1501. isInActiveMode: function(activeElm, player) {
  1502.  
  1503. console.log('check active mode', activeElm, player)
  1504. if (activeElm == player) {
  1505. return true;
  1506. }
  1507.  
  1508. for (let vpid in $hs.actionBoxRelations) {
  1509. const actionBox = $hs.actionBoxRelations[vpid].actionBox
  1510. if (actionBox && actionBox.parentNode) {
  1511. if (activeElm == actionBox || actionBox.contains(activeElm)) {
  1512. return true;
  1513. }
  1514. }
  1515. }
  1516.  
  1517. let _checkingPass = false;
  1518.  
  1519. if (!player) return;
  1520. let layoutBox = $hs.getPlayerBlockElement(player).parentNode;
  1521. if (layoutBox && layoutBox.parentNode && layoutBox.contains(activeElm)) {
  1522. let rpid = player.getAttribute('_h5ppid') || "NULL";
  1523. let actionBox = layoutBox.parentNode.querySelector(`[_h5p_actionbox_="${rpid}"]`); //the box can be layoutBox
  1524. if (actionBox && actionBox.contains(activeElm)) _checkingPass = true;
  1525. }
  1526.  
  1527. return _checkingPass
  1528. },
  1529.  
  1530.  
  1531. toolCheckFullScreen: function(doc) {
  1532. if (typeof doc.fullScreen == 'boolean') return doc.fullScreen;
  1533. if (typeof doc.webkitIsFullScreen == 'boolean') return doc.webkitIsFullScreen;
  1534. if (typeof doc.mozFullScreen == 'boolean') return doc.mozFullScreen;
  1535. return null;
  1536. },
  1537.  
  1538. toolFormatCT: function(u) {
  1539.  
  1540. let w = Math.round(u, 0)
  1541. let a = w % 60
  1542. w = (w - a) / 60
  1543. let b = w % 60
  1544. w = (w - b) / 60
  1545. let str = ("0" + b).substr(-2) + ":" + ("0" + a).substr(-2);
  1546. if (w) str = w + ":" + str
  1547.  
  1548. return str
  1549.  
  1550. },
  1551.  
  1552. makeFocus: function(player, evt) {
  1553. setTimeout(function() {
  1554. let rpid = player.getAttribute('_h5ppid');
  1555. let actionBox = getRoot(player).querySelector(`[_h5p_actionbox_="${rpid}"]`);
  1556.  
  1557. //console.log('p',rpid, player,actionBox,document.activeElement)
  1558. if (actionBox && actionBox != document.activeElement && !actionBox.contains(document.activeElement)) {
  1559. consoleLog('make focus on', actionBox)
  1560. actionBox.focus();
  1561.  
  1562. }
  1563.  
  1564. }, 300)
  1565. },
  1566.  
  1567. loopOutwards: function(startPoint, maxStep) {
  1568.  
  1569.  
  1570. let c = 0,
  1571. p = startPoint,
  1572. q = null;
  1573. while (p && (++c <= maxStep)) {
  1574. if (p.querySelectorAll('video').length !== 1) {
  1575. return q;
  1576. break;
  1577. }
  1578. q = p;
  1579. p = p.parentNode;
  1580. }
  1581.  
  1582. return p || q || null;
  1583.  
  1584. },
  1585.  
  1586. getActionBlockElement: function(player, layoutBox) {
  1587.  
  1588. //player, $hs.getPlayerBlockElement(player).parentNode;
  1589. //player, player.parentNode .... player.parentNode.parentNode.parentNode
  1590.  
  1591. //layoutBox: a container element containing video and with innerHeight>=player.innerHeight [skipped wrapping]
  1592. //layoutBox parentSize > layoutBox Size
  1593.  
  1594. //actionBox: a container with video and controls
  1595. //can be outside layoutbox (bilibili)
  1596. //assume maximum 3 layers
  1597.  
  1598.  
  1599. let outerLayout = $hs.loopOutwards(layoutBox, 3); //i.e. layoutBox.parent.parent.parent
  1600.  
  1601. const allFullScreenBtns = $hs.queryFullscreenBtnsIndependant(outerLayout)
  1602. let actionBox = null;
  1603.  
  1604. // console.log('fa0a', allFullScreenBtns.length, layoutBox)
  1605. if (allFullScreenBtns.length > 0) {
  1606. // console.log('faa', allFullScreenBtns.length)
  1607.  
  1608. for (const possibleFullScreenBtn of allFullScreenBtns) possibleFullScreenBtn.setAttribute('__h5p_fsb__', '');
  1609. let pElm = player.parentNode;
  1610. let fullscreenBtns = null;
  1611. while (pElm && pElm.parentNode) {
  1612. fullscreenBtns = pElm.querySelectorAll('[__h5p_fsb__]');
  1613. if (fullscreenBtns.length > 0) {
  1614. break;
  1615. }
  1616. pElm = pElm.parentNode;
  1617. }
  1618. for (const possibleFullScreenBtn of allFullScreenBtns) possibleFullScreenBtn.removeAttribute('__h5p_fsb__');
  1619. if (fullscreenBtns && fullscreenBtns.length > 0) {
  1620. actionBox = pElm;
  1621. fullscreenBtns = $hs.exclusiveElements(fullscreenBtns);
  1622. return {
  1623. actionBox,
  1624. fullscreenBtns
  1625. };
  1626. }
  1627. }
  1628.  
  1629. let walkRes = domTool._isActionBox_1(player, layoutBox);
  1630. //walkRes.elm = player... player.parentNode.parentNode (i.e. wPlayer)
  1631. let parentCount = walkRes.length;
  1632.  
  1633. if (parentCount - 1 >= 0 && domTool._isActionBox(player, walkRes, parentCount - 1)) {
  1634. actionBox = walkRes[parentCount - 1].elm;
  1635. } else if (parentCount - 2 >= 0 && domTool._isActionBox(player, walkRes, parentCount - 2)) {
  1636. actionBox = walkRes[parentCount - 2].elm;
  1637. } else {
  1638. actionBox = player;
  1639. }
  1640.  
  1641. return {
  1642. actionBox,
  1643. fullscreenBtns: []
  1644. };
  1645.  
  1646.  
  1647.  
  1648.  
  1649. },
  1650.  
  1651. actionBoxRelations: {},
  1652.  
  1653. actionBoxRelationClearNodes: function(rootNode, vpid) {
  1654.  
  1655. if (!rootNode || !vpid) return;
  1656. for (const subtreeElm of rootNode.querySelectorAll(`[_h5p_mr_="${vpid}"]`)) subtreeElm.setAttribute('_h5p_mr_', 'none')
  1657.  
  1658.  
  1659. },
  1660.  
  1661. actionBoxMutationCallback: function(mutations, observer) {
  1662. for (const mutation of mutations) {
  1663.  
  1664.  
  1665. const vpid = mutation.target.getAttribute('_h5p_mf_');
  1666. if (!vpid) continue;
  1667.  
  1668. const actionBoxRelation = $hs.actionBoxRelations[vpid];
  1669. if (!actionBoxRelation) continue;
  1670.  
  1671. const removedNodes = mutation.removedNodes;
  1672. if (removedNodes && removedNodes.length > 0) {
  1673. for (const node of removedNodes) {
  1674. if (node.nodeType == 1) {
  1675. actionBoxRelation.mutationRemovalsCount++
  1676. node.removeAttribute('_h5p_mf_');
  1677. }
  1678. }
  1679.  
  1680. }
  1681.  
  1682. const addedNodes = mutation.addedNodes;
  1683. if (addedNodes && addedNodes.length > 0) {
  1684. for (const node of addedNodes) {
  1685. if (node.nodeType == 1) {
  1686. actionBoxRelation.mutationAdditionsCount++
  1687. }
  1688. }
  1689.  
  1690. }
  1691. }
  1692. },
  1693.  
  1694.  
  1695. getActionBoxRelationFromDOM: function(elm) {
  1696.  
  1697. //assume action boxes are mutually exclusive
  1698.  
  1699. for (let vpid in $hs.actionBoxRelations) {
  1700. const actionBoxRelation = $hs.actionBoxRelations[vpid];
  1701. const actionBox = actionBoxRelation.actionBox
  1702. //console.log('ab', actionBox)
  1703. if (actionBox && actionBox.parentNode) {
  1704. if (elm == actionBox || actionBox.contains(elm)) {
  1705. return actionBoxRelation;
  1706. }
  1707. }
  1708. }
  1709.  
  1710.  
  1711. return null;
  1712.  
  1713. },
  1714.  
  1715.  
  1716.  
  1717. _actionBoxObtain: function(player) {
  1718.  
  1719. if (!player) return null;
  1720. let vpid = player.getAttribute('_h5ppid');
  1721. if (!vpid) return null;
  1722. if (!player.parentNode) return null;
  1723.  
  1724. let actionBoxRelation = $hs.actionBoxRelations[vpid],
  1725. layoutBox = null,
  1726. actionBox = null,
  1727. boxSearchResult = null,
  1728. fullscreenBtns = null,
  1729. wPlayer = null;
  1730.  
  1731. function a() {
  1732. wPlayer = $hs.getPlayerBlockElement(player);
  1733. layoutBox = wPlayer.parentNode;
  1734. boxSearchResult = $hs.getActionBlockElement(player, layoutBox);
  1735. actionBox = boxSearchResult.actionBox
  1736. fullscreenBtns = boxSearchResult.fullscreenBtns
  1737. }
  1738.  
  1739. function setDOM_mflag(startElm, endElm, vpid) {
  1740. if (!startElm || !endElm) return;
  1741. if (startElm == endElm) startElm.setAttribute('_h5p_mf_', vpid)
  1742. else if (endElm.contains(startElm)) {
  1743.  
  1744. let p = startElm
  1745. while (p) {
  1746. p.setAttribute('_h5p_mf_', vpid)
  1747. if (p == endElm) break;
  1748. p = p.parentNode
  1749. }
  1750.  
  1751. }
  1752. }
  1753.  
  1754. function b(domNodes) {
  1755.  
  1756. actionBox.setAttribute('_h5p_actionbox_', vpid);
  1757. if (!$hs.actionBoxMutationObserver) $hs.actionBoxMutationObserver = new MutationObserver($hs.actionBoxMutationCallback);
  1758.  
  1759. console.log('Major Mutation on Player Container')
  1760. const actionRelation = {
  1761. player: player,
  1762. wPlayer: wPlayer,
  1763. layoutBox: layoutBox,
  1764. actionBox: actionBox,
  1765. mutationRemovalsCount: 0,
  1766. mutationAdditionsCount: 0,
  1767. fullscreenBtns: fullscreenBtns,
  1768. pContainer: domNodes[domNodes.length - 1], // the block Element as the entire player (including control btns) having size>=video
  1769. ppContainer: domNodes[domNodes.length - 1].parentNode, // reference to the webpage
  1770. }
  1771.  
  1772.  
  1773. const pContainer = actionRelation.pContainer;
  1774. setDOM_mflag(player, pContainer, vpid)
  1775. for (const btn of fullscreenBtns) setDOM_mflag(btn, pContainer, vpid)
  1776.  
  1777. $hs.actionBoxRelations[vpid] = actionRelation
  1778.  
  1779.  
  1780. $hs.actionBoxMutationObserver.observe(pContainer, {
  1781. childList: true,
  1782. subtree: true
  1783. });
  1784. }
  1785.  
  1786. if (actionBoxRelation) {
  1787. //console.log('ddx', actionBoxRelation.mutationCount)
  1788. if (actionBoxRelation.pContainer && actionBoxRelation.pContainer.parentNode && actionBoxRelation.pContainer.parentNode === actionBoxRelation.ppContainer) {
  1789.  
  1790. if (actionBoxRelation.mutationRemovalsCount === 0 && actionBoxRelation.mutationAdditionsCount === 0) return actionBoxRelation.actionBox
  1791.  
  1792. // if (actionBoxRelation.mutationCount === 0 && actionBoxRelation.fullscreenBtns.every(btn=>actionBoxRelation.actionBox.contains(btn))) return actionBoxRelation.actionBox
  1793. console.log('Minor Mutation on Player Container', actionBoxRelation ? actionBoxRelation.mutationRemovalsCount : null, actionBoxRelation ? actionBoxRelation.mutationAdditionsCount : null)
  1794. a();
  1795. if (actionBox == actionBoxRelation.actionBox && layoutBox == actionBoxRelation.layoutBox && wPlayer == actionBoxRelation.wPlayer) {
  1796. //pContainer remains the same as actionBox and layoutBox remain unchanged
  1797. actionBoxRelation.ppContainer = actionBoxRelation.pContainer.parentNode; //just update the reference
  1798. if (actionBoxRelation.ppContainer) { //in case removed from DOM
  1799. actionBoxRelation.mutationRemovalsCount = 0;
  1800. actionBoxRelation.mutationAdditionsCount = 0;
  1801. actionBoxRelation.fullscreenBtns = fullscreenBtns;
  1802. return actionBox;
  1803. }
  1804. }
  1805. }
  1806.  
  1807. const elms = (getRoot(actionBoxRelation.pContainer) || document).querySelectorAll(`[_h5p_mf_="${vpid}"]`)
  1808. for (const elm of elms) elm.removeAttribute('_h5p_mf_')
  1809. actionBoxRelation.pContainer.removeAttribute('_h5p_mf_')
  1810. for (var k in actionBoxRelation) delete actionBoxRelation[k]
  1811. actionBoxRelation = null;
  1812. delete $hs.actionBoxRelations[vpid]
  1813. }
  1814.  
  1815. if (boxSearchResult == null) a();
  1816. if (actionBox) {
  1817. const domNodes = [];
  1818. let pElm = player;
  1819. let containing = 0;
  1820. while (pElm) {
  1821. domNodes.push(pElm);
  1822. if (pElm === actionBox) containing |= 1;
  1823. if (pElm === layoutBox) containing |= 2;
  1824. if (containing === 3) {
  1825. b(domNodes);
  1826. return actionBox
  1827. }
  1828. pElm = pElm.parentNode;
  1829. }
  1830. }
  1831.  
  1832. return null;
  1833.  
  1834.  
  1835. // if (!actionBox.hasAttribute('tabindex')) actionBox.setAttribute('tabindex', '-1');
  1836.  
  1837.  
  1838.  
  1839.  
  1840. },
  1841.  
  1842. videoSrcFound: function(player) {
  1843.  
  1844. // src loaded
  1845.  
  1846. if (!player) return;
  1847. let vpid = player.getAttribute('_h5ppid') || null;
  1848. if (!vpid || !player.currentSrc) return;
  1849.  
  1850. player._isThisPausedBefore_ = false;
  1851.  
  1852. player.removeAttribute('_h5p_uid_encrypted');
  1853.  
  1854. if (player._record_continuous) player._record_continuous._lastSave = -999; //first time must save
  1855.  
  1856. let uid_A = location.pathname.replace(/[^\d+]/g, '') + '.' + location.search.replace(/[^\d+]/g, '');
  1857. let _uid = location.hostname.replace('www.', '').toLowerCase() + '!' + location.pathname.toLowerCase() + 'A' + uid_A + 'W' + player.videoWidth + 'H' + player.videoHeight + 'L' + (player.duration << 0);
  1858.  
  1859. digestMessage(_uid).then(function(_uid_encrypted) {
  1860.  
  1861. let d = +new Date;
  1862.  
  1863. let recordedTime = null;
  1864.  
  1865. ;
  1866. (function() {
  1867. //read the last record only;
  1868.  
  1869. let k1 = '_h5_player_play_progress_';
  1870. let k1n = '_play_progress_';
  1871. let k2 = _uid_encrypted;
  1872. let k3 = k1 + k2;
  1873. let k3n = k1n + k2;
  1874. let m2 = Store._keys().filter(key => key.substr(0, k3.length) == k3); //all progress records for this video
  1875. let m2v = m2.map(keyName => +(keyName.split('+')[1] || '0'))
  1876. let m2vMax = Math.max(0, ...m2v)
  1877. if (!m2vMax) recordedTime = null;
  1878. else {
  1879. let _json_recordedTime = null;
  1880. _json_recordedTime = Store.read(k3n + '+' + m2vMax);
  1881. if (!_json_recordedTime) _json_recordedTime = {};
  1882. else _json_recordedTime = jsonParse(_json_recordedTime);
  1883. if (typeof _json_recordedTime == 'object') recordedTime = _json_recordedTime;
  1884. else recordedTime = null;
  1885. recordedTime = typeof recordedTime == 'object' ? recordedTime.t : recordedTime;
  1886. if (typeof recordedTime == 'number' && (+recordedTime >= 0 || +recordedTime <= 0)) {
  1887.  
  1888. } else if (typeof recordedTime == 'string' && recordedTime.length > 0 && (+recordedTime >= 0 || +recordedTime <= 0)) {
  1889. recordedTime = +recordedTime
  1890. } else {
  1891. recordedTime = null
  1892. }
  1893. }
  1894. if (recordedTime !== null) {
  1895. player._h5player_lastrecord_ = recordedTime;
  1896. } else {
  1897. player._h5player_lastrecord_ = null;
  1898. }
  1899. if (player._h5player_lastrecord_ > 5) {
  1900. consoleLog('last record playing', player._h5player_lastrecord_);
  1901. setTimeout(function() {
  1902. $hs._tips(player, `Press Shift-R to restore Last Playback: ${$hs.toolFormatCT(player._h5player_lastrecord_)}`, 5000, 4000)
  1903. }, 1000)
  1904. }
  1905.  
  1906. })();
  1907. // delay the recording by 5.4s => prevent ads or mis operation
  1908. setTimeout(function() {
  1909.  
  1910. let k1 = '_h5_player_play_progress_';
  1911. let k1n = '_play_progress_';
  1912. let k2 = _uid_encrypted;
  1913. let k3 = k1 + k2;
  1914. let k3n = k1n + k2;
  1915.  
  1916. //re-read all the localStorage keys
  1917. let m1 = Store._keys().filter(key => key.substr(0, k1.length) == k1); //all progress records in this site
  1918. let p = m1.length + 1;
  1919.  
  1920. for (const key of m1) { //all progress records for this video
  1921. if (key.substr(0, k3.length) == k3) {
  1922. Store._removeItem(key); //remove previous record for the current video
  1923. p--;
  1924. }
  1925. }
  1926.  
  1927. if (recordedTime !== null) {
  1928. Store.save(k3n + '+' + d, jsonStringify({
  1929. 't': recordedTime
  1930. })) //prevent loss of last record
  1931. }
  1932.  
  1933. const _record_max_ = 48;
  1934. const _record_keep_ = 26;
  1935.  
  1936. if (p > _record_max_) {
  1937. //exisiting 48 records for one site;
  1938. //keep only 26 records
  1939.  
  1940. const comparator = (a, b) => (a.t < b.t ? -1 : a.t > b.t ? 1 : 0);
  1941.  
  1942. m1
  1943. .map(keyName => ({
  1944. keyName,
  1945. t: +(keyName.split('+')[1] || '0')
  1946. }))
  1947. .sort(comparator)
  1948. .slice(0, -_record_keep_)
  1949. .forEach((item) => localStorage.removeItem(item.keyName));
  1950.  
  1951. consoleLog(`stored progress: reduced to ${_record_keep_}`)
  1952. }
  1953.  
  1954. player.setAttribute('_h5p_uid_encrypted', _uid_encrypted + '+' + d);
  1955.  
  1956. //try to start recording
  1957. if (player._record_continuous) player._record_continuous.playingWithRecording();
  1958.  
  1959. }, 5400);
  1960.  
  1961. })
  1962.  
  1963. },
  1964. bindDocEvents: function(rootNode) {
  1965. if (!rootNode._onceBindedDocEvents) {
  1966.  
  1967. rootNode._onceBindedDocEvents = true;
  1968. rootNode.addEventListener('keydown', $hs.handlerRootKeyDownEvent, true)
  1969. document._debug_rootNode_ = rootNode;
  1970.  
  1971. rootNode.addEventListener('mouseenter', $hs.handlerElementMouseEnter, true)
  1972. rootNode.addEventListener('mouseleave', $hs.handlerElementMouseLeave, true)
  1973. rootNode.addEventListener('mousedown', $hs.handlerElementMouseDown, true)
  1974. rootNode.addEventListener('wheel', $hs.handlerElementWheelTuneVolume, {
  1975. passive: false
  1976. });
  1977.  
  1978. // wheel - bubble events to keep it simple (i.e. it must be passive:false & capture:false)
  1979.  
  1980.  
  1981. rootNode.addEventListener('focus', $hs.handlerElementFocus, $mb.eh_capture_passive())
  1982. rootNode.addEventListener('fullscreenchange', $hs.handlerFullscreenChanged, true)
  1983.  
  1984. //rootNode.addEventListener('mousemove', $hs.handlerOverrideMouseMove, {capture:true, passive:false})
  1985.  
  1986. }
  1987. },
  1988. fireGlobalInit: function() {
  1989. if ($hs.intVideoInitCount != 1) return;
  1990. if (!$hs.varSrcList) $hs.varSrcList = {};
  1991. $hs.isLostFocus = null;
  1992. try {
  1993. //iframe may not be able to control top window
  1994. //error; just ignore with async
  1995. let topDoc = window.top && window.top.document ? window.top.document : null;
  1996. if (topDoc) {
  1997. topDoc.addEventListener('focusout', $hs.handlerDocFocusOut, true)
  1998. topDoc.addEventListener('focusin', $hs.handlerDocFocusIn, true)
  1999. }
  2000.  
  2001. } catch (e) {}
  2002. Store.clearInvalid(_sVersion_)
  2003.  
  2004.  
  2005. Promise.resolve().then(()=>{
  2006.  
  2007. GM_addStyle(`
  2008. .ytp-chrome-bottom+span#volumeUI:last-child:empty{
  2009. display:none;
  2010. }
  2011. html[_h5p_hide_cursor] *{
  2012. cursor:none !important;
  2013. }
  2014. `)
  2015. })
  2016.  
  2017. },
  2018. onVideoTriggering: function() {
  2019.  
  2020.  
  2021. // initialize a single video player - h5Player.playerInstance
  2022.  
  2023. /**
  2024. * 初始化播放器實例
  2025. */
  2026. let player = $hs.playerInstance
  2027. if (!player) return
  2028.  
  2029. let vpid = player.getAttribute('_h5ppid');
  2030.  
  2031. if (!vpid) return;
  2032.  
  2033. let firstTime = !!$hs.initTips()
  2034. if (firstTime) {
  2035. // first time to trigger this player
  2036. if (!player.hasAttribute('playsinline')) player.setAttribute('playsinline', 'playsinline');
  2037. if (!player.hasAttribute('x-webkit-airplay')) player.setAttribute('x-webkit-airplay', 'deny');
  2038. if (!player.hasAttribute('preload')) player.setAttribute('preload', 'auto');
  2039. //player.style['image-rendering'] = 'crisp-edges';
  2040. $hs.playbackRate = $hs.getPlaybackRate()
  2041. }
  2042.  
  2043. },
  2044. getPlaybackRate: function() {
  2045. let playbackRate = Store.read('_playback_rate_') || $hs.playbackRate
  2046. return Number(Number(playbackRate).toFixed(1))
  2047. },
  2048. getPlayerBlockElement: function(player, useCache) {
  2049.  
  2050. let layoutBox = null,
  2051. wPlayer = null
  2052.  
  2053. if (!player || !player.offsetHeight || !player.offsetWidth || !player.parentNode) {
  2054. return null;
  2055. }
  2056.  
  2057.  
  2058. if (useCache === true) {
  2059. let vpid = player.getAttribute('_h5ppid');
  2060. let actionBoxRelation = $hs.actionBoxRelations[vpid]
  2061. if (actionBoxRelation && actionBoxRelation.mutationRemovalsCount === 0) {
  2062. return actionBoxRelation.wPlayer
  2063. }
  2064. }
  2065.  
  2066.  
  2067. //without checkActiveBox, just a DOM for you to append tipsDom
  2068.  
  2069. function oWH(elm) {
  2070. return [elm.offsetWidth, elm.offsetHeight].join(',');
  2071. }
  2072.  
  2073. function search_nodes() {
  2074.  
  2075. wPlayer = player; // NOT NULL
  2076. layoutBox = wPlayer.parentNode; // NOT NULL
  2077.  
  2078. while (layoutBox.parentNode && layoutBox.nodeType == 1 && layoutBox.offsetHeight == 0) {
  2079. wPlayer = layoutBox; // NOT NULL
  2080. layoutBox = layoutBox.parentNode; // NOT NULL
  2081. }
  2082. //container must be with offsetHeight
  2083.  
  2084. while (layoutBox.parentNode && layoutBox.nodeType == 1 && layoutBox.offsetHeight < player.offsetHeight) {
  2085. wPlayer = layoutBox; // NOT NULL
  2086. layoutBox = layoutBox.parentNode; // NOT NULL
  2087. }
  2088. //container must have height >= player height
  2089.  
  2090. const layoutOWH = oWH(layoutBox)
  2091. //const playerOWH=oWH(player)
  2092.  
  2093. //skip all inner wraps
  2094. while (layoutBox.parentNode && layoutBox.nodeType == 1 && oWH(layoutBox.parentNode) == layoutOWH) {
  2095. wPlayer = layoutBox; // NOT NULL
  2096. layoutBox = layoutBox.parentNode; // NOT NULL
  2097. }
  2098.  
  2099. // oWH of layoutBox.parentNode != oWH of layoutBox and layoutBox.offsetHeight >= player.offsetHeight
  2100.  
  2101. }
  2102.  
  2103. search_nodes();
  2104.  
  2105. if (layoutBox.nodeType == 11) {
  2106. makeNoRoot(layoutBox);
  2107. search_nodes();
  2108. }
  2109.  
  2110.  
  2111.  
  2112. //condition:
  2113. //!layoutBox.parentNode || layoutBox.nodeType != 1 || layoutBox.offsetHeight > player.offsetHeight
  2114.  
  2115. // layoutBox is a node contains <video> and offsetHeight>=video.offsetHeight
  2116. // wPlayer is a HTML Element (nodeType==1)
  2117. // you can insert the DOM element into the layoutBox
  2118.  
  2119. if (layoutBox && wPlayer && layoutBox.nodeType === 1 && wPlayer.parentNode == layoutBox && layoutBox.parentNode) return wPlayer;
  2120. throw 'unknown error';
  2121.  
  2122. },
  2123. getCommonContainer: function(elm1, elm2) {
  2124.  
  2125. let box1 = elm1;
  2126. let box2 = elm2;
  2127.  
  2128. while (box1 && box2) {
  2129. if (box1.contains(box2) || box2.contains(box1)) {
  2130. break;
  2131. }
  2132. box1 = box1.parentNode;
  2133. box2 = box2.parentNode;
  2134. }
  2135.  
  2136. let layoutBox = null;
  2137.  
  2138. box1 = (box1 && box1.contains(elm2)) ? box1 : null;
  2139. box2 = (box2 && box2.contains(elm1)) ? box2 : null;
  2140.  
  2141. if (box1 && box2) layoutBox = box1.contains(box2) ? box2 : box1;
  2142. else layoutBox = box1 || box2 || null;
  2143.  
  2144. return layoutBox
  2145.  
  2146. },
  2147. change_layoutBox: function(tipsDom) {
  2148. let player = $hs.player()
  2149. if (!player) return;
  2150. let wPlayer = $hs.getPlayerBlockElement(player, true);
  2151. let layoutBox = wPlayer.parentNode;
  2152.  
  2153. if ((layoutBox && layoutBox.nodeType == 1) && (!tipsDom.parentNode || tipsDom.parentNode !== layoutBox)) {
  2154.  
  2155. consoleLog('changed_layoutBox')
  2156. layoutBox.insertBefore(tipsDom, wPlayer);
  2157.  
  2158. }
  2159. },
  2160.  
  2161. _hasEventListener: function(elm, p) {
  2162.  
  2163. if (elm && elm._listeners) {
  2164.  
  2165. const cache = elm._listeners[p]
  2166. return cache && cache.funcCount > 0
  2167.  
  2168. }
  2169. return false;
  2170.  
  2171. },
  2172.  
  2173. queryFullscreenBtnsIndependant: function(parentNode) {
  2174.  
  2175. let btns = [];
  2176.  
  2177. function elmCallback(elm) {
  2178.  
  2179. let hasClickListeners = null,
  2180. childElementCount = null,
  2181. isVisible = null,
  2182. btnElm = elm;
  2183. var pElm = elm;
  2184. while (pElm && pElm.nodeType === 1 && pElm != parentNode && pElm.querySelector('video') === null) {
  2185.  
  2186. let funcTest = typeof pElm.onclick == 'function' || $hs._hasEventListener(pElm, 'click');
  2187. funcTest = funcTest || typeof pElm.onmousedown == 'function' || $hs._hasEventListener(pElm, 'mousedown');
  2188. funcTest = funcTest || typeof pElm.onmouseup == 'function' || $hs._hasEventListener(pElm, 'mouseup');
  2189.  
  2190. if (funcTest) {
  2191. hasClickListeners = true
  2192. btnElm = pElm;
  2193. break;
  2194. }
  2195.  
  2196. pElm = pElm.parentNode;
  2197. }
  2198. if (btns.indexOf(btnElm) >= 0) return; //btn>a.fullscreen-1>b.fullscreen-2>c.fullscreen-3
  2199.  
  2200. if ('_listeners' in elm) {
  2201.  
  2202. //hasClickListeners = elm._listeners && elm._listeners.click && elm._listeners.click.funcCount > 0
  2203.  
  2204. }
  2205.  
  2206. if ('childElementCount' in elm) {
  2207.  
  2208. childElementCount = elm.childElementCount;
  2209.  
  2210. }
  2211. if ('offsetParent' in elm) {
  2212. isVisible = !!elm.offsetParent; //works with parent/self display none; not work with visiblity hidden / opacity0
  2213.  
  2214. }
  2215.  
  2216. if (hasClickListeners) {
  2217. let btn = {
  2218. elm,
  2219. btnElm,
  2220. isVisible,
  2221. hasClickListeners,
  2222. childElementCount,
  2223. isContained: null
  2224. };
  2225.  
  2226. //console.log('btnElm', btnElm)
  2227.  
  2228. btns.push(btnElm)
  2229.  
  2230. }
  2231. }
  2232.  
  2233.  
  2234. for (const elm of parentNode.querySelectorAll('[class*="full"][class*="screen"]')) {
  2235. let className = (elm.getAttribute('class') || "");
  2236. if (/\b(fullscreen|full-screen)\b/i.test(className.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  2237. elmCallback(elm)
  2238. }
  2239. }
  2240.  
  2241.  
  2242. for (const elm of parentNode.querySelectorAll('[id*="full"][id*="screen"]')) {
  2243. let idName = (elm.getAttribute('id') || "");
  2244. if (/\b(fullscreen|full-screen)\b/i.test(idName.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  2245. elmCallback(elm)
  2246. }
  2247. }
  2248.  
  2249. for (const elm of parentNode.querySelectorAll('[name*="full"][name*="screen"]')) {
  2250. let nName = (elm.getAttribute('name') || "");
  2251. if (/\b(fullscreen|full-screen)\b/i.test(nName.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  2252. elmCallback(elm)
  2253. }
  2254. }
  2255.  
  2256.  
  2257. return btns;
  2258.  
  2259. },
  2260. exclusiveElements: function(elms) {
  2261.  
  2262. //not containing others
  2263. let res = [];
  2264.  
  2265. for (const roleElm of elms) {
  2266.  
  2267. let isContained = false;
  2268. for (const testElm of elms) {
  2269. if (testElm != roleElm && roleElm.contains(testElm)) {
  2270. isContained = true;
  2271. break;
  2272. }
  2273. }
  2274. if (!isContained) res.push(roleElm)
  2275. }
  2276. return res;
  2277.  
  2278. },
  2279.  
  2280. getWithFullscreenBtn: function(actionBoxRelation) {
  2281.  
  2282.  
  2283.  
  2284. console.log('callFullScreenBtn', 300)
  2285.  
  2286. if (actionBoxRelation && actionBoxRelation.actionBox) {
  2287. let actionBox = actionBoxRelation.actionBox;
  2288. let btnElements = actionBoxRelation.fullscreenBtns;
  2289.  
  2290. console.log('callFullScreenBtn', 400)
  2291. if (btnElements && btnElements.length > 0) {
  2292.  
  2293. console.log('callFullScreenBtn', 500, btnElements, actionBox.contains(btnElements[0]))
  2294.  
  2295. let btnElement_idx = btnElements._only_idx;
  2296.  
  2297. if (btnElement_idx >= 0) {
  2298.  
  2299. } else if (btnElements.length === 1) {
  2300. btnElement_idx = 0;
  2301. } else if (btnElements.length > 1) {
  2302. //web-fullscreen-on/off ; fullscreen-on/off ....
  2303.  
  2304. const strList = btnElements.map(elm => [elm.className || 'null', elm.id || 'null', elm.name || 'null'].join('-').replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))
  2305.  
  2306. const filterOutScores = new Array(strList.length).fill(0);
  2307. const filterInScores = new Array(strList.length).fill(0);
  2308. const filterScores = new Array(strList.length).fill(0);
  2309. for (const [j, str] of strList.entries()) {
  2310. if (/\b(fullscreen|full-screen)\b/i.test(str)) filterInScores[j] += 1
  2311. if (/\b(web-fullscreen|web-full-screen)\b/i.test(str)) filterOutScores[j] += 1
  2312. if (/\b(fullscreen-on|full-screen-on)\b/i.test(str)) filterInScores[j] += 1
  2313. if (/\b(fullscreen-off|full-screen-off)\b/i.test(str)) filterOutScores[j] += 1
  2314. if (/\b(on-fullscreen|on-full-screen)\b/i.test(str)) filterInScores[j] += 1
  2315. if (/\b(off-fullscreen|off-full-screen)\b/i.test(str)) filterOutScores[j] += 1
  2316. }
  2317.  
  2318. let maxScore = -1e7;
  2319. for (const [j, str] of strList.entries()) {
  2320. filterScores[j] = filterInScores[j] * 3 - filterOutScores[j] * 2
  2321. if (filterScores[j] > maxScore) maxScore = filterScores[j];
  2322. }
  2323. btnElement_idx = filterScores.indexOf(maxScore)
  2324. if (btnElement_idx < 0) btnElement_idx = 0; //unknown
  2325. }
  2326.  
  2327. btnElements._only_idx = btnElement_idx
  2328.  
  2329.  
  2330. //consoleLog('original fullscreen')
  2331. return btnElements[btnElement_idx];
  2332.  
  2333. }
  2334.  
  2335.  
  2336. }
  2337. return null
  2338. },
  2339.  
  2340. callFullScreenBtn: function() {
  2341. console.log('callFullScreenBtn')
  2342.  
  2343.  
  2344.  
  2345. let player = $hs.player()
  2346. if (!player || !player.ownerDocument || !('exitFullscreen' in player.ownerDocument)) return;
  2347.  
  2348. let btnElement = null;
  2349.  
  2350. let vpid = player.getAttribute('_h5ppid') || null;
  2351.  
  2352. if (!vpid) return;
  2353.  
  2354.  
  2355. const chFull = $hs.toolCheckFullScreen(player.ownerDocument);
  2356.  
  2357.  
  2358.  
  2359. if (chFull === true) {
  2360. player.ownerDocument.exitFullscreen();
  2361. return;
  2362. }
  2363.  
  2364. let actionBoxRelation = $hs.actionBoxRelations[vpid];
  2365.  
  2366.  
  2367. let asyncRes = Promise.resolve(actionBoxRelation)
  2368. if (chFull === false) asyncRes = asyncRes.then($hs.getWithFullscreenBtn);
  2369. else asyncRes = asyncRes.then(() => null)
  2370.  
  2371. asyncRes.then((btnElement) => {
  2372.  
  2373. if (btnElement) {
  2374.  
  2375. window.requestAnimationFrame(() => btnElement.click());
  2376. return;
  2377. }
  2378.  
  2379. let fsElm = getRoot(player).querySelector(`[_h5p_fsElm_="${vpid}"]`); //it is set in fullscreenchange
  2380.  
  2381. let gPlayer = fsElm
  2382.  
  2383. if (gPlayer) {
  2384.  
  2385. } else if (actionBoxRelation && actionBoxRelation.actionBox) {
  2386. gPlayer = actionBoxRelation.actionBox;
  2387. } else if (actionBoxRelation && actionBoxRelation.layoutBox) {
  2388. gPlayer = actionBoxRelation.layoutBox;
  2389. } else {
  2390. gPlayer = player;
  2391. }
  2392.  
  2393.  
  2394. if (gPlayer != fsElm && !fsElm) {
  2395. delayCall('$$videoReset_fsElm', function() {
  2396. gPlayer.removeAttribute('_h5p_fsElm_')
  2397. }, 500)
  2398. }
  2399.  
  2400. console.log('DOM fullscreen', gPlayer)
  2401. try {
  2402. const res = gPlayer.requestFullscreen()
  2403. if (res && res.constructor.name == "Promise") res.catch((e) => 0)
  2404. } catch (e) {
  2405. console.log('DOM fullscreen Error', e)
  2406. }
  2407.  
  2408.  
  2409. })
  2410.  
  2411.  
  2412.  
  2413.  
  2414. },
  2415. /* 設置播放速度 */
  2416. setPlaybackRate: function(num, flagTips) {
  2417. let player = $hs.player()
  2418. let curPlaybackRate
  2419. if (num) {
  2420. num = +num
  2421. if (num > 0) { // also checking the type of variable
  2422. curPlaybackRate = num < 0.1 ? 0.1 : +(num.toFixed(1))
  2423. } else {
  2424. console.error('h5player: 播放速度轉換出錯')
  2425. return false
  2426. }
  2427. } else {
  2428. curPlaybackRate = $hs.getPlaybackRate()
  2429. }
  2430. /* 記錄播放速度的信息 */
  2431.  
  2432. let changed = curPlaybackRate !== player.playbackRate;
  2433.  
  2434. if (curPlaybackRate !== player.playbackRate) {
  2435.  
  2436. Store.save('_playback_rate_', curPlaybackRate + '')
  2437. $hs.playbackRate = curPlaybackRate
  2438. player.playbackRate = curPlaybackRate
  2439. /* 本身處於1被播放速度的時候不再提示 */
  2440. //if (!num && curPlaybackRate === 1) return;
  2441.  
  2442. }
  2443.  
  2444. flagTips = (flagTips < 0) ? false : (flagTips > 0) ? true : changed;
  2445. if (flagTips) $hs.tips('Playback speed: ' + player.playbackRate + 'x')
  2446. },
  2447. tuneCurrentTimeTips:function(_amount, changed){
  2448.  
  2449. $hs.tips(false);
  2450. if (changed) {
  2451. if (_amount > 0) $hs.tips(_amount + ' Sec. Forward', undefined, 3000);
  2452. else $hs.tips(-_amount + ' Sec. Backward', undefined, 3000)
  2453. }
  2454. },
  2455. tuneCurrentTime: function(amount) {
  2456. let _amount = +(+amount).toFixed(1);
  2457. let player = $hs.player();
  2458. if (_amount >= 0 || _amount < 0) {} else {
  2459. return;
  2460. }
  2461.  
  2462. let newCurrentTime = player.currentTime + _amount;
  2463. if (newCurrentTime < 0) newCurrentTime = 0;
  2464. if (newCurrentTime > player.duration) newCurrentTime = player.duration;
  2465.  
  2466. let changed = newCurrentTime != player.currentTime && newCurrentTime >= 0 && newCurrentTime <= player.duration;
  2467.  
  2468. if (changed) {
  2469. //player.currentTime = newCurrentTime;
  2470. //player.pause();
  2471.  
  2472.  
  2473. const video = player;
  2474. var isPlaying = video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA;
  2475.  
  2476. if (isPlaying) {
  2477. player.pause();
  2478. $hs.ccad = $hs.ccad || function() {
  2479. if (player.paused) player.play();
  2480. };
  2481. player.addEventListener('seeked', $hs.ccad, {
  2482. passive: true,
  2483. capture: true,
  2484. once: true
  2485. });
  2486.  
  2487. }
  2488.  
  2489.  
  2490.  
  2491.  
  2492. player.currentTime = +newCurrentTime.toFixed(0)
  2493.  
  2494. $hs.tuneCurrentTimeTips(_amount, changed)
  2495.  
  2496. }
  2497.  
  2498. },
  2499. tuneVolume: function(amount) {
  2500. let _amount = +(+amount).toFixed(2);
  2501.  
  2502. let player = $hs.player()
  2503.  
  2504. let newVol = player.volume + _amount;
  2505. if (newVol < 0) newVol = 0;
  2506. if (newVol > 1) newVol = 1;
  2507. let chVol = player.volume !== newVol && newVol >= 0 && newVol <= 1;
  2508.  
  2509. if (chVol) {
  2510.  
  2511. if (_amount > 0 && player.volume < 1) {
  2512. player.volume = newVol // positive
  2513. } else if (_amount < 0 && player.volume > 0) {
  2514. player.volume = newVol // negative
  2515. }
  2516. $hs.tips(false);
  2517. $hs.tips('Volume: ' + dround(player.volume * 100) + '%', undefined)
  2518. }
  2519. },
  2520. switchPlayStatus: function() {
  2521. let player = $hs.player()
  2522. if (player.paused) {
  2523. player.play()
  2524. if (player._isThisPausedBefore_) {
  2525. $hs.tips(false);
  2526. $hs.tips('Playback resumed', undefined, 2500)
  2527. }
  2528. } else {
  2529. player.pause()
  2530. $hs.tips(false);
  2531. $hs.tips('Playback paused', undefined, 2500)
  2532. }
  2533. },
  2534. tipsClassName: 'html_player_enhance_tips',
  2535. _tips: function(player, str, duration, order) {
  2536.  
  2537. Promise.resolve().then(()=>{
  2538.  
  2539.  
  2540. if (!player.getAttribute('_h5player_tips')) $hs.initTips();
  2541.  
  2542. }).then(()=>{
  2543.  
  2544. let tipsSelector = '#' + (player.getAttribute('_h5player_tips') || $hs.tipsClassName) //if this attribute still doesnt exist, set it to the base cls name
  2545. let tipsDom = getRoot(player).querySelector(tipsSelector)
  2546. if (!tipsDom) {
  2547. consoleLog('init h5player tips dom error...')
  2548. return false
  2549. }
  2550. $hs.change_layoutBox(tipsDom);
  2551.  
  2552. return tipsDom
  2553.  
  2554. }).then((tipsDom)=>{
  2555. if(tipsDom===false)return false;
  2556.  
  2557. if (str === false) {
  2558. tipsDom.textContent = '';
  2559. tipsDom.setAttribute('_potTips_', '0')
  2560. } else {
  2561. order = order || 1000
  2562. tipsDom.tipsOrder = tipsDom.tipsOrder || 0;
  2563.  
  2564. let shallDisplay = true
  2565. if (order < tipsDom.tipsOrder && getComputedStyle(tipsDom).opacity > 0) shallDisplay = false
  2566.  
  2567. if (shallDisplay) {
  2568. tipsDom._playerElement = player;
  2569. tipsDom._playerVPID = player.getAttribute('_h5ppid');
  2570. tipsDom._playerBlockElm = $hs.getPlayerBlockElement(player, true)
  2571.  
  2572. if (duration === undefined) duration = 2000
  2573. tipsDom.textContent = str
  2574. tipsDom.setAttribute('_potTips_', '2')
  2575.  
  2576. if (duration > 0) {
  2577. $ws.requestAnimationFrame(() => tipsDom.setAttribute('_potTips_', '1'))
  2578. } else {
  2579. order = -1;
  2580. }
  2581.  
  2582. tipsDom.tipsOrder = order
  2583.  
  2584. }
  2585.  
  2586. }
  2587.  
  2588. return tipsDom;
  2589.  
  2590. }).then((tipsDom)=>{
  2591. if(tipsDom===false)return false;
  2592.  
  2593. if (window.ResizeObserver && tipsDom._playerBlockElm.parentNode) { // tipsDom._playerBlockElm.parentNode == null => bug
  2594. //observe not fire twice for the same element.
  2595. if (!$hs.observer_resizeVideos) $hs.observer_resizeVideos = new ResizeObserver(hanlderResizeVideo)
  2596. $hs.observer_resizeVideos.observe(tipsDom._playerBlockElm.parentNode)
  2597. $hs.observer_resizeVideos.observe(tipsDom._playerBlockElm)
  2598. $hs.observer_resizeVideos.observe(player)
  2599. }
  2600. //ensure function called
  2601. window.requestAnimationFrame(() => $hs.fixNonBoxingVideoTipsPosition(tipsDom, player))
  2602.  
  2603. })
  2604.  
  2605. },
  2606. tips: function(str, duration, order) {
  2607. let player = $hs.player()
  2608. if (!player) {
  2609. consoleLog('h5Player Tips:', str)
  2610. }else{
  2611. $hs._tips(player, str, duration, order)
  2612.  
  2613. }
  2614.  
  2615. },
  2616. listOfTipsDom: [],
  2617. getPotTips: function(arr) {
  2618. const res = [];
  2619. for (const tipsDom of $hs.listOfTipsDom) {
  2620. if (tipsDom && tipsDom.nodeType > 0 && tipsDom.parentNode && tipsDom.ownerDocument) {
  2621. if (tipsDom._playerBlockElm && tipsDom._playerBlockElm.parentNode) {
  2622. const potTipsAttr = tipsDom.getAttribute('_potTips_')
  2623. if (arr.indexOf(potTipsAttr) >= 0) res.push(tipsDom)
  2624. }
  2625. }
  2626. }
  2627. return res;
  2628. },
  2629. initTips: function() {
  2630. /* 設置提示DOM的樣式 */
  2631. let player = $hs.player()
  2632. let shadowRoot = getRoot(player);
  2633. let doc = player.ownerDocument;
  2634. //console.log((document.documentElement.qq=player),shadowRoot,'xax')
  2635. let parentNode = player.parentNode
  2636. let tcn = player.getAttribute('_h5player_tips') || ($hs.tipsClassName + '_' + (+new Date));
  2637. player.setAttribute('_h5player_tips', tcn)
  2638. if (shadowRoot.querySelector('#' + tcn)) return false;
  2639.  
  2640. if (!shadowRoot._onceAddedCSS) {
  2641. shadowRoot._onceAddedCSS = true;
  2642.  
  2643. let cssStyle = `
  2644. [_potTips_="1"]{
  2645. animation: 2s linear 0s normal forwards 1 delayHide;
  2646. }
  2647. [_potTips_="0"]{
  2648. opacity:0; transform:translate(-9999px);
  2649. }
  2650. [_potTips_="2"]{
  2651. opacity:.95; transform: translate(0,0);
  2652. }
  2653.  
  2654. @keyframes delayHide{
  2655. 0%, 99% { opacity:0.95; transform: translate(0,0); }
  2656. 100% { opacity:0; transform:translate(-9999px); }
  2657. }
  2658. ` + `
  2659. [_potTips_]{
  2660. font-weight: bold !important;
  2661. position: absolute !important;
  2662. z-index: 999 !important;
  2663. font-size: ${$hs.fontSize || 16}px !important;
  2664. padding: 0px !important;
  2665. border:none !important;
  2666. background: rgba(0,0,0,0) !important;
  2667. color:#738CE6 !important;
  2668. text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;
  2669. top: 50%;
  2670. left: 50%;
  2671. max-width:500px;max-height:50px;
  2672. border-radius:3px;
  2673. font-family: 'microsoft yahei', Verdana, Geneva, sans-serif;
  2674. pointer-events: none;
  2675. }
  2676. body div[_potTips_]{
  2677. -webkit-user-select: none !important;
  2678. -moz-user-select: none !important;
  2679. -ms-user-select: none !important;
  2680. user-select: none !important;
  2681. -webkit-touch-callout: none !important;
  2682. -webkit-user-select: none !important;
  2683. -khtml-user-drag: none !important;
  2684. -khtml-user-select: none !important;
  2685. -moz-user-select: none !important;
  2686. -moz-user-select: -moz-none !important;
  2687. -ms-user-select: none !important;
  2688. user-select: none !important;
  2689. }
  2690. .ytp-chrome-bottom+span#volumeUI:last-child:empty{
  2691. display:none;
  2692. }
  2693. `.replace(/\r\n/g, '');
  2694.  
  2695.  
  2696. let cssContainer = domAppender(shadowRoot);
  2697.  
  2698.  
  2699. if (!cssContainer) {
  2700. cssContainer = makeNoRoot(shadowRoot)
  2701. }
  2702.  
  2703. domTool.addStyle(cssStyle, cssContainer);
  2704.  
  2705. }
  2706.  
  2707. let tipsDom = doc.createElement('div')
  2708.  
  2709. $hs.handler_tipsDom_animation = $hs.handler_tipsDom_animation || function(e) {
  2710. if (this.getAttribute('_potTips_') == '1') {
  2711. this.setAttribute('_potTips_', '0')
  2712. }
  2713. }
  2714.  
  2715. tipsDom.addEventListener(crossBrowserTransition('animation'), $hs.handler_tipsDom_animation, $mb.eh_bubble_passive())
  2716.  
  2717. tipsDom.id = tcn;
  2718. tipsDom.setAttribute('_potTips_', '0');
  2719. $hs.listOfTipsDom.push(tipsDom);
  2720. $hs.change_layoutBox(tipsDom);
  2721.  
  2722. return true;
  2723. },
  2724.  
  2725. responsiveSizing: function(container, elm) {
  2726.  
  2727. let gcssP = getComputedStyle(container);
  2728.  
  2729. let gcssE = getComputedStyle(elm);
  2730.  
  2731. //console.log(gcssE.left,gcssP.width)
  2732. let elmBound = {
  2733. left: parseFloat(gcssE.left) / parseFloat(gcssP.width),
  2734. width: parseFloat(gcssE.width) / parseFloat(gcssP.width),
  2735. top: parseFloat(gcssE.top) / parseFloat(gcssP.height),
  2736. height: parseFloat(gcssE.height) / parseFloat(gcssP.height)
  2737. };
  2738.  
  2739. let elm00 = [elmBound.left, elmBound.top];
  2740. let elm01 = [elmBound.left + elmBound.width, elmBound.top];
  2741. let elm10 = [elmBound.left, elmBound.top + elmBound.height];
  2742. let elm11 = [elmBound.left + elmBound.width, elmBound.top + elmBound.height];
  2743.  
  2744. return {
  2745. elm00,
  2746. elm01,
  2747. elm10,
  2748. elm11,
  2749. plw: elmBound.width,
  2750. plh: elmBound.height
  2751. };
  2752.  
  2753. },
  2754.  
  2755. fixNonBoxingVideoTipsPosition: function(tipsDom, player) {
  2756.  
  2757. if (!tipsDom || !player) return;
  2758.  
  2759. let ct = $hs.getCommonContainer(tipsDom, player)
  2760.  
  2761. if (!ct) return;
  2762.  
  2763. //relative
  2764.  
  2765. let elm00 = $hs.responsiveSizing(ct, player).elm00;
  2766.  
  2767. if (isNaN(elm00[0]) || isNaN(elm00[1])) {
  2768.  
  2769. [tipsDom.style.left, tipsDom.style.top] = [player.style.left, player.style.top];
  2770. //eg auto
  2771. } else {
  2772.  
  2773. let rlm00 = elm00.map(t => (t * 100).toFixed(2) + '%');
  2774. [tipsDom.style.left, tipsDom.style.top] = rlm00;
  2775.  
  2776. }
  2777.  
  2778. // absolute
  2779.  
  2780. let _offset = {
  2781. left: 10,
  2782. top: 15
  2783. };
  2784.  
  2785. let customOffset = {
  2786. left: _offset.left,
  2787. top: _offset.top
  2788. };
  2789. let p = tipsDom.getBoundingClientRect();
  2790. let q = player.getBoundingClientRect();
  2791. let currentPos = [p.left, p.top];
  2792.  
  2793. let targetPos = [q.left + player.offsetWidth * 0 + customOffset.left, q.top + player.offsetHeight * 0 + customOffset.top];
  2794.  
  2795. let mL = +tipsDom.style.marginLeft.replace('px', '') || 0;
  2796. if (isNaN(mL)) mL = 0;
  2797. let mT = +tipsDom.style.marginTop.replace('px', '') || 0;
  2798. if (isNaN(mT)) mT = 0;
  2799.  
  2800. let z1 = -(currentPos[0] - targetPos[0]);
  2801. let z2 = -(currentPos[1] - targetPos[1]);
  2802.  
  2803. if (z1 || z2) {
  2804.  
  2805. let y1 = z1 + mL;
  2806. let y2 = z2 + mT;
  2807.  
  2808. tipsDom.style.marginLeft = y1 + 'px';
  2809. tipsDom.style.marginTop = y2 + 'px';
  2810.  
  2811. }
  2812. },
  2813.  
  2814. playerTrigger: function(player, event) {
  2815.  
  2816.  
  2817.  
  2818. if (!player || !event) return
  2819. const pCode = event.code;
  2820. let keyAsm = (event.shiftKey ? SHIFT : 0) | ((event.ctrlKey || event.metaKey) ? CTRL : 0) | (event.altKey ? ALT : 0);
  2821.  
  2822.  
  2823.  
  2824.  
  2825. let vpid = player.getAttribute('_h5ppid') || null;
  2826. if (!vpid) return;
  2827. let playerConf = playerConfs[vpid]
  2828. if (!playerConf) return;
  2829.  
  2830. //shift + key
  2831. if (keyAsm == SHIFT) {
  2832. // 網頁FULLSCREEN
  2833. if (pCode === 'Enter') {
  2834. //$hs.callFullScreenBtn()
  2835. //return TERMINATE
  2836. } else if (pCode == 'KeyF') {
  2837. //change unsharpen filter
  2838.  
  2839. let resList = ["unsharpen3_05", "unsharpen3_10", "unsharpen5_05", "unsharpen5_10", "unsharpen9_05", "unsharpen9_10"]
  2840. let res = (prompt("Enter the unsharpen mask\n(" + resList.map(x => '"' + x + '"').join(', ') + ")", "unsharpen9_05") || "").toLowerCase();
  2841. if (resList.indexOf(res) < 0) res = ""
  2842. GM_setValue("unsharpen_mask", res)
  2843. for (const el of document.querySelectorAll('video[_h5p_uid_encrypted]')) {
  2844. if (el.style.filter == "" || el.style.filter) {
  2845. let filterStr1 = el.style.filter.replace(/\s*url\(\"#_h5p_unsharpen[\d\_]+\"\)/, '');
  2846. let filterStr2 = (res.length > 0 ? ' url("#_h5p_' + res + '")' : '')
  2847. el.style.filter = filterStr1 + filterStr2;
  2848. }
  2849. }
  2850. return TERMINATE
  2851.  
  2852. }
  2853. // 進入或退出畫中畫模式
  2854. else if (pCode == 'KeyP') {
  2855. $hs.pictureInPicture(player)
  2856.  
  2857. return TERMINATE
  2858. } else if (pCode == 'KeyR') {
  2859. if (player._h5player_lastrecord_ !== null && (player._h5player_lastrecord_ >= 0 || player._h5player_lastrecord_ <= 0)) {
  2860. $hs.setPlayProgress(player, player._h5player_lastrecord_)
  2861.  
  2862. return TERMINATE
  2863. }
  2864.  
  2865. } else if (pCode == 'KeyO') {
  2866. let _debug_h5p_logging_ch = false;
  2867. try {
  2868. Store._setItem('_h5_player_sLogging_', 1 - Store._getItem('_h5_player_sLogging_'))
  2869. _debug_h5p_logging_ = +Store._getItem('_h5_player_sLogging_') > 0;
  2870. _debug_h5p_logging_ch = true;
  2871. } catch (e) {
  2872.  
  2873. }
  2874. consoleLogF('_debug_h5p_logging_', !!_debug_h5p_logging_, 'changed', _debug_h5p_logging_ch)
  2875.  
  2876. if (_debug_h5p_logging_ch) {
  2877.  
  2878. return TERMINATE
  2879. }
  2880. } else if (pCode == 'KeyT') {
  2881. if (/^blob/i.test(player.currentSrc)) {
  2882. alert(`The current video is ${player.currentSrc}\nSorry, it cannot be opened in PotPlayer.`);
  2883. } else {
  2884. let confirm_res = confirm(`The current video is ${player.currentSrc}\nDo you want to open it in PotPlayer?`);
  2885. if (confirm_res) window.open('potplayer://' + player.currentSrc, '_blank');
  2886. }
  2887. return TERMINATE
  2888. }
  2889.  
  2890.  
  2891.  
  2892. let videoScale = playerConf.vFactor;
  2893.  
  2894. function tipsForVideoScaling() {
  2895.  
  2896. playerConf.vFactor = +videoScale.toFixed(1);
  2897.  
  2898. playerConf.cssTransform();
  2899. let tipsMsg = `視頻縮放率:${ +(videoScale * 100).toFixed(2) }%`
  2900. if (playerConf.translate.x) {
  2901. tipsMsg += `,水平位移:${playerConf.translate.x}px`
  2902. }
  2903. if (playerConf.translate.y) {
  2904. tipsMsg += `,垂直位移:${playerConf.translate.y}px`
  2905. }
  2906. $hs.tips(false);
  2907. $hs.tips(tipsMsg)
  2908.  
  2909.  
  2910. }
  2911.  
  2912. // 視頻畫面縮放相關事件
  2913.  
  2914. switch (pCode) {
  2915. // shift+X:視頻縮小 -0.1
  2916. case 'KeyX':
  2917. videoScale -= 0.1
  2918. if (videoScale < 0.1) videoScale = 0.1;
  2919. tipsForVideoScaling();
  2920. return TERMINATE
  2921. break
  2922. // shift+C:視頻放大 +0.1
  2923. case 'KeyC':
  2924. videoScale += 0.1
  2925. if (videoScale > 16) videoScale = 16;
  2926. tipsForVideoScaling();
  2927. return TERMINATE
  2928. break
  2929. // shift+Z:視頻恢復正常大小
  2930. case 'KeyZ':
  2931. videoScale = 1.0
  2932. playerConf.translate.x = 0;
  2933. playerConf.translate.y = 0;
  2934. tipsForVideoScaling();
  2935. return TERMINATE
  2936. break
  2937. case 'ArrowRight':
  2938. playerConf.translate.x += 10
  2939. tipsForVideoScaling();
  2940. return TERMINATE
  2941. break
  2942. case 'ArrowLeft':
  2943. playerConf.translate.x -= 10
  2944. tipsForVideoScaling();
  2945. return TERMINATE
  2946. break
  2947. case 'ArrowUp':
  2948. playerConf.translate.y -= 10
  2949. tipsForVideoScaling();
  2950. return TERMINATE
  2951. break
  2952. case 'ArrowDown':
  2953. playerConf.translate.y += 10
  2954. tipsForVideoScaling();
  2955. return TERMINATE
  2956. break
  2957.  
  2958. }
  2959.  
  2960. }
  2961. // 防止其它無關組合鍵衝突
  2962. if (!keyAsm) {
  2963. let kControl = null
  2964. let newPBR, oldPBR, nv, numKey;
  2965. switch (pCode) {
  2966. // 方向鍵右→:快進3秒
  2967. case 'ArrowRight':
  2968. if(1){
  2969. let aCurrentTime= player.currentTime;
  2970. window.requestAnimationFrame(()=>{
  2971. let diff=player.currentTime-aCurrentTime
  2972. diff=Math.round(diff*5)/5;
  2973. if(Math.abs(diff)<0.8){
  2974. $hs.tuneCurrentTime(+$hs.skipStep);
  2975. }else{
  2976. $hs.tuneCurrentTimeTips(diff, true)
  2977. }
  2978. })
  2979. //if(document.domain.indexOf('youtube.com')>=0){}else{
  2980. //$hs.tuneCurrentTime($hs.skipStep);
  2981. //return TERMINATE;
  2982. //}
  2983. }
  2984. break;
  2985. // 方向鍵左←:後退3秒
  2986. case 'ArrowLeft':
  2987.  
  2988. if(1){
  2989. let aCurrentTime= player.currentTime;
  2990. window.requestAnimationFrame(()=>{
  2991. let diff=player.currentTime-aCurrentTime
  2992. diff=Math.round(diff*5)/5;
  2993. if(Math.abs(diff)<0.8){
  2994. $hs.tuneCurrentTime(-$hs.skipStep);
  2995. }else{
  2996. $hs.tuneCurrentTimeTips(diff, true)
  2997. }
  2998. })
  2999. //if(document.domain.indexOf('youtube.com')>=0){}else{
  3000. //
  3001. //return TERMINATE;
  3002. //}
  3003. }
  3004. break;
  3005. // 方向鍵上↑:音量升高 1%
  3006. case 'ArrowUp':
  3007. if ((player.muted && player.volume === 0) && player._volume > 0) {
  3008.  
  3009. player.muted = false;
  3010. player.volume = player._volume;
  3011. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  3012. player.muted = false;
  3013. }
  3014. $hs.tuneVolume(0.01);
  3015. return TERMINATE;
  3016. break;
  3017. // 方向鍵下↓:音量降低 1%
  3018. case 'ArrowDown':
  3019.  
  3020. if ((player.muted && player.volume === 0) && player._volume > 0) {
  3021.  
  3022. player.muted = false;
  3023. player.volume = player._volume;
  3024. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  3025. player.muted = false;
  3026. }
  3027. $hs.tuneVolume(-0.01);
  3028. return TERMINATE;
  3029. break;
  3030. // 空格鍵:暫停/播放
  3031. case 'Space':
  3032. $hs.switchPlayStatus();
  3033. return TERMINATE;
  3034. break;
  3035. // 按鍵X:減速播放 -0.1
  3036. case 'KeyX':
  3037. if (player.playbackRate > 0) {
  3038. $hs.tips(false);
  3039. $hs.setPlaybackRate(player.playbackRate - 0.1);
  3040. return TERMINATE
  3041. }
  3042. break;
  3043. // 按鍵C:加速播放 +0.1
  3044. case 'KeyC':
  3045. if (player.playbackRate < 16) {
  3046. $hs.tips(false);
  3047. $hs.setPlaybackRate(player.playbackRate + 0.1);
  3048. return TERMINATE
  3049. }
  3050.  
  3051. break;
  3052. // 按鍵Z:正常速度播放
  3053. case 'KeyZ':
  3054. $hs.tips(false);
  3055. oldPBR = player.playbackRate;
  3056. if (oldPBR != 1.0) {
  3057. player._playbackRate_z = oldPBR;
  3058. newPBR = 1.0;
  3059. } else if (player._playbackRate_z != 1.0) {
  3060. newPBR = player._playbackRate_z || 1.0;
  3061. player._playbackRate_z = 1.0;
  3062. } else {
  3063. newPBR = 1.0
  3064. player._playbackRate_z = 1.0;
  3065. }
  3066. $hs.setPlaybackRate(newPBR, 1)
  3067. return TERMINATE
  3068. break;
  3069. // 按鍵F:下一幀
  3070. case 'KeyF':
  3071. if (window.location.hostname === 'www.netflix.com') return /* netflix 的F鍵是FULLSCREEN的意思 */
  3072. $hs.tips(false);
  3073. if (!player.paused) player.pause()
  3074. player.currentTime += +(1 / playerConf.fps)
  3075. $hs.tips('Jump to: Next frame')
  3076. return TERMINATE
  3077. break;
  3078. // 按鍵D:上一幀
  3079. case 'KeyD':
  3080. $hs.tips(false);
  3081. if (!player.paused) player.pause()
  3082. player.currentTime -= +(1 / playerConf.fps)
  3083. $hs.tips('Jump to: Previous frame')
  3084. return TERMINATE
  3085. break;
  3086. // 按鍵E:亮度增加%
  3087. case 'KeyE':
  3088. $hs.tips(false);
  3089. nv = playerConf.setFilter('brightness', (v) => v + 0.1);
  3090. $hs.tips('Brightness: ' + dround(nv * 100) + '%')
  3091. return TERMINATE
  3092. break;
  3093. // 按鍵W:亮度減少%
  3094. case 'KeyW':
  3095. $hs.tips(false);
  3096. nv = playerConf.setFilter('brightness', (v) => v > 0.1 ? v - 0.1 : 0);
  3097. $hs.tips('Brightness: ' + dround(nv * 100) + '%')
  3098. return TERMINATE
  3099. break;
  3100. // 按鍵T:對比度增加%
  3101. case 'KeyT':
  3102. $hs.tips(false);
  3103. nv = playerConf.setFilter('contrast', (v) => v + 0.1);
  3104. $hs.tips('Contrast: ' + dround(nv * 100) + '%')
  3105. return TERMINATE
  3106. break;
  3107. // 按鍵R:對比度減少%
  3108. case 'KeyR':
  3109. $hs.tips(false);
  3110. nv = playerConf.setFilter('contrast', (v) => v > 0.1 ? v - 0.1 : 0);
  3111. $hs.tips('Contrast: ' + dround(nv * 100) + '%')
  3112. return TERMINATE
  3113. break;
  3114. // 按鍵U:飽和度增加%
  3115. case 'KeyU':
  3116. $hs.tips(false);
  3117. nv = playerConf.setFilter('saturate', (v) => v + 0.1);
  3118. $hs.tips('Saturate: ' + dround(nv * 100) + '%')
  3119. return TERMINATE
  3120. break;
  3121. // 按鍵Y:飽和度減少%
  3122. case 'KeyY':
  3123. $hs.tips(false);
  3124. nv = playerConf.setFilter('saturate', (v) => v > 0.1 ? v - 0.1 : 0);
  3125. $hs.tips('Saturate: ' + dround(nv * 100) + '%')
  3126. return TERMINATE
  3127. break;
  3128. // 按鍵O:色相增加 1 度
  3129. case 'KeyO':
  3130. $hs.tips(false);
  3131. nv = playerConf.setFilter('hue-rotate', (v) => v + 1);
  3132. $hs.tips('Hue: ' + nv + ' deg')
  3133. return TERMINATE
  3134. break;
  3135. // 按鍵I:色相減少 1 度
  3136. case 'KeyI':
  3137. $hs.tips(false);
  3138. nv = playerConf.setFilter('hue-rotate', (v) => v - 1);
  3139. $hs.tips('Hue: ' + nv + ' deg')
  3140. return TERMINATE
  3141. break;
  3142. // 按鍵K:模糊增加 0.1 px
  3143. case 'KeyK':
  3144. $hs.tips(false);
  3145. nv = playerConf.setFilter('blur', (v) => v + 0.1);
  3146. $hs.tips('Blur: ' + nv + ' px')
  3147. return TERMINATE
  3148. break;
  3149. // 按鍵J:模糊減少 0.1 px
  3150. case 'KeyJ':
  3151. $hs.tips(false);
  3152. nv = playerConf.setFilter('blur', (v) => v > 0.1 ? v - 0.1 : 0);
  3153. $hs.tips('Blur: ' + nv + ' px')
  3154. return TERMINATE
  3155. break;
  3156. // 按鍵Q:圖像復位
  3157. case 'KeyQ':
  3158. $hs.tips(false);
  3159. playerConf.filterReset();
  3160. $hs.tips('Video Filter Reset')
  3161. return TERMINATE
  3162. break;
  3163. // 按鍵S:畫面旋轉 90 度
  3164. case 'KeyS':
  3165. $hs.tips(false);
  3166. playerConf.rotate += 90
  3167. if (playerConf.rotate % 360 === 0) playerConf.rotate = 0;
  3168. if (!playerConf.videoHeight || !playerConf.videoWidth) {
  3169. playerConf.videoWidth = playerConf.domElement.videoWidth;
  3170. playerConf.videoHeight = playerConf.domElement.videoHeight;
  3171. }
  3172. if (playerConf.videoWidth > 0 && playerConf.videoHeight > 0) {
  3173.  
  3174.  
  3175. if ((playerConf.rotate % 180) == 90) {
  3176. playerConf.mFactor = playerConf.videoHeight / playerConf.videoWidth;
  3177. } else {
  3178. playerConf.mFactor = 1.0;
  3179. }
  3180.  
  3181.  
  3182. playerConf.cssTransform();
  3183.  
  3184. $hs.tips('Rotation:' + playerConf.rotate + ' deg')
  3185.  
  3186. }
  3187.  
  3188. return TERMINATE
  3189. break;
  3190. // 按鍵迴車,進入FULLSCREEN
  3191. case 'Enter':
  3192. //t.callFullScreenBtn();
  3193. break;
  3194. case 'KeyN':
  3195. $hs.pictureInPicture(player);
  3196. return TERMINATE
  3197. break;
  3198. case 'KeyM':
  3199. //console.log('m!', player.volume,player._volume)
  3200.  
  3201. if (player.volume >= 0) {
  3202.  
  3203. if (!player.volume || player.muted) {
  3204.  
  3205. let newVol = player.volume || player._volume || 0.5;
  3206. if (player.volume !== newVol) {
  3207. player.volume = newVol;
  3208. }
  3209. player.muted = false;
  3210. $hs.tips(false);
  3211. $hs.tips('Mute: Off', undefined);
  3212.  
  3213. } else {
  3214.  
  3215. player._volume = player.volume;
  3216. player._volume_p = player.volume;
  3217. //player.volume = 0;
  3218. player.muted = true;
  3219. $hs.tips(false);
  3220. $hs.tips('Mute: On', undefined);
  3221.  
  3222. }
  3223.  
  3224. }
  3225.  
  3226. return TERMINATE
  3227. break;
  3228. default:
  3229. // 按1-4設置播放速度 49-52;97-100
  3230. numKey = +(event.key)
  3231.  
  3232. if (numKey >= 1 && numKey <= 4) {
  3233. $hs.tips(false);
  3234. $hs.setPlaybackRate(numKey, 1)
  3235. return TERMINATE
  3236. }
  3237. }
  3238.  
  3239. }
  3240. },
  3241.  
  3242. handlerPlayerLockedMouseMove: function(e) {
  3243. //console.log(4545)
  3244.  
  3245. let player = $hs.player();
  3246. if (!player) return;
  3247. Promise.resolve().then(() => {
  3248.  
  3249.  
  3250.  
  3251.  
  3252. $hs.mouseMoveCount += Math.sqrt(e.movementX * e.movementX + e.movementY * e.movementY);
  3253. //console.log($hs.mouseMoveCount)
  3254. if ($hs.mouseMoveCount > $hs.mouseMoveMax) {
  3255. $hs.mouseMoveCount = 0;
  3256. if ($hs.cursorHidden) {
  3257.  
  3258. return 1;
  3259.  
  3260. }
  3261.  
  3262.  
  3263. } else {
  3264. //console.log($hs.mouseMoveCount)
  3265.  
  3266.  
  3267. return 2;
  3268.  
  3269. }
  3270.  
  3271. }).then(ayRes => {
  3272.  
  3273. if (ayRes == 1) {
  3274.  
  3275.  
  3276. delayCall('$$VideoMouseMove', function() {
  3277. if (!$hs.cursorHidden) {
  3278. const playerConf = $hs.getPlayerConf(player)
  3279. $hs.playerActionEnter(player);
  3280. }
  3281. }, 1240)
  3282. $hs.playerActionLeave()
  3283.  
  3284. } else if (ayRes == 2) {
  3285.  
  3286. delayCall('$$VideoClearMove', function() {
  3287. $hs.mouseMoveCount = $hs.mouseMoveCount * 0.4;
  3288. }, 100)
  3289.  
  3290. delayCall('$$VideoClearMove2', function() {
  3291. $hs.mouseMoveCount = 0;
  3292. }, 400)
  3293.  
  3294. }
  3295.  
  3296.  
  3297.  
  3298. })
  3299.  
  3300.  
  3301.  
  3302.  
  3303. },
  3304.  
  3305. playerActionEnter: function(player) {
  3306. if (player && !$hs.cursorHidden) {
  3307. const last = function(a, k) {
  3308. return a[a.length - 1 - (k || 0)]
  3309. }
  3310.  
  3311. Promise.resolve().then(() => {
  3312. if (player.paused === false) player.ownerDocument.querySelector('html').setAttribute('_h5p_hide_cursor', '')
  3313. else if (player.paused === true) player.ownerDocument.querySelector('html').removeAttribute('_h5p_hide_cursor')
  3314. $hs.cursorHidden = player;
  3315.  
  3316. $hs.mouseMoveCount = 0;
  3317. $hs.mouseMoveMax = Math.sqrt(player.clientWidth * player.clientWidth + player.clientHeight * player.clientHeight) * 0.06;
  3318.  
  3319. }).then(() => {
  3320.  
  3321. player.ownerDocument.addEventListener('mousemove', $hs.handlerPlayerLockedMouseMove, $mb.eh_capture_passive())
  3322.  
  3323. })
  3324. }
  3325. },
  3326.  
  3327. focusHookVDoc: null,
  3328. focusHookVId: '',
  3329.  
  3330. playerActionLeave: function() {
  3331. let player = $hs.player();
  3332. if ($hs.cursorHidden) {
  3333. const last = function(a, k) {
  3334. return a[a.length - 1 - (k || 0)]
  3335. }
  3336.  
  3337.  
  3338. Promise.resolve().then(() => {
  3339.  
  3340. if (player) {
  3341. player.ownerDocument.removeEventListener('mousemove', $hs.handlerPlayerLockedMouseMove, {
  3342. passive: true,
  3343. capture: true
  3344. })
  3345. }
  3346.  
  3347. }).then(() => {
  3348. $hs.cursorHidden = null;
  3349. $hs.mouseMoveCount = 0;
  3350. player.ownerDocument.querySelector('html').removeAttribute('_h5p_hide_cursor')
  3351.  
  3352. })
  3353.  
  3354. }
  3355. },
  3356.  
  3357. handlerElementFocus: function(event) {
  3358.  
  3359. function notAtVideo() {
  3360. if ($hs.focusHookVDoc) $hs.focusHookVDoc = null
  3361. if ($hs.focusHookVId) $hs.focusHookVId = ''
  3362. }
  3363.  
  3364. const hookVideo = $hs.focusHookVDoc && $hs.focusHookVId ? $hs.focusHookVDoc.querySelector(`VIDEO[_h5ppid=${$hs.focusHookVId}]`) : null
  3365.  
  3366.  
  3367. if (hookVideo && (event.target == hookVideo || event.target.contains(hookVideo))) {
  3368.  
  3369.  
  3370. } else {
  3371.  
  3372. notAtVideo();
  3373.  
  3374.  
  3375. }
  3376.  
  3377. },
  3378.  
  3379. handlerFullscreenChanged: function(event) {
  3380.  
  3381.  
  3382. let videoElm = null,
  3383. videosQuery = null;
  3384. if (event && event.target) {
  3385.  
  3386. if (event.target.nodeName == "VIDEO") videoElm = event.target;
  3387. else if (videosQuery = event.target.querySelectorAll("VIDEO")) {
  3388. if (videosQuery.length === 1) videoElm = videosQuery[0]
  3389. }
  3390.  
  3391.  
  3392. }
  3393.  
  3394. if (videoElm) {
  3395.  
  3396.  
  3397. const player = videoElm;
  3398. const vpid = player.getAttribute('_h5ppid')
  3399.  
  3400.  
  3401. event.target.setAttribute('_h5p_fsElm_', vpid)
  3402.  
  3403.  
  3404. function hookTheActionedVideo() {
  3405. $hs.focusHookVDoc = getRoot(player)
  3406. $hs.focusHookVId = vpid
  3407. }
  3408.  
  3409.  
  3410. hookTheActionedVideo();
  3411. setTimeout(function() {
  3412. hookTheActionedVideo()
  3413. }, 500)
  3414.  
  3415.  
  3416.  
  3417. function hideCursor() {
  3418. const chFull = $hs.toolCheckFullScreen(player.ownerDocument);
  3419.  
  3420. if (chFull) {
  3421.  
  3422. $hs.playerActionEnter(player);
  3423. } else {
  3424.  
  3425. $hs.playerActionLeave();
  3426. }
  3427. }
  3428.  
  3429. //$rAf.call(window,hideCursor);
  3430. setTimeout(hideCursor);
  3431.  
  3432.  
  3433.  
  3434. } else {
  3435.  
  3436. $hs.focusHookVDoc = null
  3437. $hs.focusHookVId = ''
  3438.  
  3439. }
  3440.  
  3441.  
  3442. },
  3443.  
  3444. /*
  3445. handlerOverrideMouseMove:function(evt){
  3446.  
  3447.  
  3448. if(evt&&evt.target){}else{return;}
  3449. const targetElm = evt.target;
  3450.  
  3451. if(targetElm.nodeName=="VIDEO"){
  3452. evt.preventDefault();
  3453. evt.stopPropagation();
  3454. evt.stopImmediatePropagation();
  3455. }
  3456.  
  3457. },*/
  3458.  
  3459. /* 按鍵響應方法 */
  3460. handlerRootKeyDownEvent: function(event) {
  3461.  
  3462. function notAtVideo() {
  3463. if ($hs.focusHookVDoc) $hs.focusHookVDoc = null
  3464. if ($hs.focusHookVId) $hs.focusHookVId = ''
  3465. }
  3466.  
  3467.  
  3468.  
  3469.  
  3470. if ($hs.intVideoInitCount > 0) {} else {
  3471. // return notAtVideo();
  3472. }
  3473.  
  3474.  
  3475.  
  3476. // $hs.lastKeyDown = event.timeStamp
  3477.  
  3478.  
  3479. // DOM Standard - either .key or .code
  3480. // Here we adopt .code (physical layout)
  3481.  
  3482. let pCode = event.code;
  3483. if (typeof pCode != 'string') return;
  3484. let player = $hs.player()
  3485. if (!player) return; // no video tag
  3486.  
  3487. let rootNode = getRoot(player);
  3488. let isRequiredListen = false;
  3489.  
  3490. let keyAsm = (event.shiftKey ? SHIFT : 0) | ((event.ctrlKey || event.metaKey) ? CTRL : 0) | (event.altKey ? ALT : 0);
  3491.  
  3492.  
  3493. if (document.fullscreenElement || rootNode.pointerLockElement) {
  3494. isRequiredListen = true;
  3495.  
  3496.  
  3497. if (!keyAsm && pCode == 'Escape') {
  3498. setTimeout(() => {
  3499. if (document.fullscreenElement) {
  3500. document.exitFullscreen();
  3501. } else if (document.pointerLockElement) {
  3502. $hs.playerActionLeave();
  3503. }
  3504. }, 700);
  3505. return;
  3506. }
  3507.  
  3508.  
  3509. }
  3510.  
  3511. const actionBoxRelation = $hs.getActionBoxRelationFromDOM(event.target)
  3512. let hookVideo = null;
  3513.  
  3514. if (actionBoxRelation) {
  3515. $hs.focusHookVDoc = getRoot(actionBoxRelation.player);
  3516. $hs.focusHookVId = actionBoxRelation.player.getAttribute('_h5ppid');
  3517. hookVideo = actionBoxRelation.player;
  3518. } else {
  3519. hookVideo = $hs.focusHookVDoc && $hs.focusHookVId ? $hs.focusHookVDoc.querySelector(`VIDEO[_h5ppid=${$hs.focusHookVId}]`) : null
  3520. }
  3521.  
  3522. if (hookVideo) isRequiredListen = true;
  3523.  
  3524. //console.log('root key', isRequiredListen, event.target, hookVideo)
  3525.  
  3526. if (!isRequiredListen) return;
  3527.  
  3528. //console.log('K01')
  3529.  
  3530. /* 切換插件的可用狀態 */
  3531. // Shift-`
  3532. if (keyAsm == SHIFT && pCode == 'Backquote') {
  3533. $hs.enable = !$hs.enable;
  3534. $hs.tips(false);
  3535. if ($hs.enable) {
  3536. $hs.tips('啟用h5Player插件')
  3537. } else {
  3538. $hs.tips('禁用h5Player插件')
  3539. }
  3540. // 阻止事件冒泡
  3541. event.stopPropagation()
  3542. event.preventDefault()
  3543. return false
  3544. }
  3545. if (!$hs.enable) {
  3546. consoleLog('h5Player 已禁用~')
  3547. return false
  3548. }
  3549.  
  3550. /* 非全局模式下,不聚焦則不執行快捷鍵的操作 */
  3551.  
  3552. if (!keyAsm && pCode == 'Enter') { //not NumberpadEnter
  3553.  
  3554. $hs._actionBoxObtain(player); //ted - sub tree not calling?
  3555. $hs.callFullScreenBtn()
  3556. event.stopPropagation()
  3557. event.preventDefault()
  3558. return false
  3559. }
  3560.  
  3561.  
  3562.  
  3563. let res = $hs.playerTrigger(player, event)
  3564. if (res == TERMINATE) {
  3565. event.stopPropagation()
  3566. event.preventDefault()
  3567. return false
  3568. }
  3569.  
  3570. },
  3571. /* 設置播放進度 */
  3572. setPlayProgress: function(player, curTime) {
  3573. if (!player) return
  3574. if (!curTime || Number.isNaN(curTime)) return
  3575. player.currentTime = curTime
  3576. if (curTime > 3) {
  3577. $hs.tips(false);
  3578. $hs.tips(`Playback Jumps to ${$hs.toolFormatCT(curTime)}`)
  3579. if (player.paused) player.play();
  3580. }
  3581. }
  3582. }
  3583.  
  3584. function makeFilter(arr, k) {
  3585. let res = ""
  3586. for (const e of arr) {
  3587. for (const d of e) {
  3588. res += " " + (1.0 * d * k).toFixed(9)
  3589. }
  3590. }
  3591. return res.trim()
  3592. }
  3593.  
  3594. function _add_filter(rootElm) {
  3595. let rootView = null;
  3596. if (rootElm && rootElm.nodeType > 0) {
  3597. while (rootElm.parentNode && rootElm.parentNode.nodeType === 1) rootElm = rootElm.parentNode;
  3598. rootView = rootElm.querySelector('body') || rootElm;
  3599. } else {
  3600. return;
  3601. }
  3602.  
  3603. if (rootView && rootView.querySelector && !rootView.querySelector('#_h5player_section_')) {
  3604.  
  3605. let svgFilterElm = document.createElement('section')
  3606. svgFilterElm.style.position = 'fixed';
  3607. svgFilterElm.style.left = '-999px';
  3608. svgFilterElm.style.width = '1px';
  3609. svgFilterElm.style.top = '-999px';
  3610. svgFilterElm.style.height = '1px';
  3611. svgFilterElm.id = '_h5player_section_'
  3612. let svgXML = `
  3613. <svg id='_h5p_image' version="1.1" xmlns="http://www.w3.org/2000/svg">
  3614. <defs>
  3615. <filter id="_h5p_sharpen1">
  3616. <feConvolveMatrix filterRes="100 100" style="color-interpolation-filters:sRGB" order="3" kernelMatrix="` + `
  3617. -0.3 -0.3 -0.3
  3618. -0.3 3.4 -0.3
  3619. -0.3 -0.3 -0.3`.replace(/[\n\r]+/g, ' ').trim() + `" preserveAlpha="true"/>
  3620. </filter>
  3621. <filter id="_h5p_unsharpen1">
  3622. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  3623. makeFilter([
  3624. [1, 4, 6, 4, 1],
  3625. [4, 16, 24, 16, 4],
  3626. [6, 24, -476, 24, 6],
  3627. [4, 16, 24, 16, 4],
  3628. [1, 4, 6, 4, 1]
  3629. ], -1 / 256) + `" preserveAlpha="false"/>
  3630. </filter>
  3631. <filter id="_h5p_unsharpen3_05">
  3632. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="3" kernelMatrix="` +
  3633. makeFilter(
  3634. [
  3635. [0.025, 0.05, 0.025],
  3636. [0.05, -1.1, 0.05],
  3637. [0.025, 0.05, 0.025]
  3638. ], -1 / .8) + `" preserveAlpha="false"/>
  3639. </filter>
  3640. <filter id="_h5p_unsharpen3_10">
  3641. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="3" kernelMatrix="` +
  3642. makeFilter(
  3643. [
  3644. [0.05, 0.1, 0.05],
  3645. [0.1, -1.4, 0.1],
  3646. [0.05, 0.1, 0.05]
  3647. ], -1 / .8) + `" preserveAlpha="false"/>
  3648. </filter>
  3649. <filter id="_h5p_unsharpen5_05">
  3650. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  3651. makeFilter(
  3652. [
  3653. [0.025, 0.1, 0.15, 0.1, 0.025],
  3654. [0.1, 0.4, 0.6, 0.4, 0.1],
  3655. [0.15, 0.6, -18.3, 0.6, 0.15],
  3656. [0.1, 0.4, 0.6, 0.4, 0.1],
  3657. [0.025, 0.1, 0.15, 0.1, 0.025]
  3658. ], -1 / 12.8) + `" preserveAlpha="false"/>
  3659. </filter>
  3660. <filter id="_h5p_unsharpen5_10">
  3661. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  3662. makeFilter(
  3663. [
  3664. [0.05, 0.2, 0.3, 0.2, 0.05],
  3665. [0.2, 0.8, 1.2, 0.8, 0.2],
  3666. [0.3, 1.2, -23.8, 1.2, 0.3],
  3667. [0.2, 0.8, 1.2, 0.8, 0.2],
  3668. [0.05, 0.2, 0.3, 0.2, 0.05]
  3669. ], -1 / 12.8) + `" preserveAlpha="false"/>
  3670. </filter>
  3671. <filter id="_h5p_unsharpen9_05">
  3672. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="9" kernelMatrix="` +
  3673. makeFilter(
  3674. [
  3675. [0.025, 0.2, 0.7, 1.4, 1.75, 1.4, 0.7, 0.2, 0.025],
  3676. [0.2, 1.6, 5.6, 11.2, 14, 11.2, 5.6, 1.6, 0.2],
  3677. [0.7, 5.6, 19.6, 39.2, 49, 39.2, 19.6, 5.6, 0.7],
  3678. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3679. [1.75, 14, 49, 98, -4792.7, 98, 49, 14, 1.75],
  3680. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3681. [0.7, 5.6, 19.6, 39.2, 49, 39.2, 19.6, 5.6, 0.7],
  3682. [0.2, 1.6, 5.6, 11.2, 14, 11.2, 5.6, 1.6, 0.2],
  3683. [0.025, 0.2, 0.7, 1.4, 1.75, 1.4, 0.7, 0.2, 0.025]
  3684. ], -1 / 3276.8) + `" preserveAlpha="false"/>
  3685. </filter>
  3686. <filter id="_h5p_unsharpen9_10">
  3687. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="9" kernelMatrix="` +
  3688. makeFilter(
  3689. [
  3690. [0.05, 0.4, 1.4, 2.8, 3.5, 2.8, 1.4, 0.4, 0.05],
  3691. [0.4, 3.2, 11.2, 22.4, 28, 22.4, 11.2, 3.2, 0.4],
  3692. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3693. [2.8, 22.4, 78.4, 156.8, 196, 156.8, 78.4, 22.4, 2.8],
  3694. [3.5, 28, 98, 196, -6308.6, 196, 98, 28, 3.5],
  3695. [2.8, 22.4, 78.4, 156.8, 196, 156.8, 78.4, 22.4, 2.8],
  3696. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3697. [0.4, 3.2, 11.2, 22.4, 28, 22.4, 11.2, 3.2, 0.4],
  3698. [0.05, 0.4, 1.4, 2.8, 3.5, 2.8, 1.4, 0.4, 0.05]
  3699. ], -1 / 3276.8) + `" preserveAlpha="false"/>
  3700. </filter>
  3701. <filter id="_h5p_grey1">
  3702. <feColorMatrix values="0.3333 0.3333 0.3333 0 0
  3703. 0.3333 0.3333 0.3333 0 0
  3704. 0.3333 0.3333 0.3333 0 0
  3705. 0 0 0 1 0"/>
  3706. <feColorMatrix type="saturate" values="0" />
  3707. </filter>
  3708. </defs>
  3709. </svg>
  3710. `;
  3711.  
  3712. svgFilterElm.innerHTML = svgXML.replace(/[\r\n\s]+/g, ' ').trim();
  3713.  
  3714. rootView.appendChild(svgFilterElm);
  3715. }
  3716.  
  3717. }
  3718.  
  3719. /**
  3720. * 某些網頁用了attachShadow closed mode,需要open才能獲取video標籤,例如百度雲盤
  3721. * 解決參考:
  3722. * https://developers.google.com/web/fundamentals/web-components/shadowdom?hl=zh-cn#closed
  3723. * https://stackoverflow.com/questions/54954383/override-element-prototype-attachshadow-using-chrome-extension
  3724. */
  3725.  
  3726. const initForShadowRoot = async (shadowRoot) => {
  3727. try {
  3728. if (shadowRoot && shadowRoot.nodeType > 0 && shadowRoot.mode == 'open' && 'querySelectorAll' in shadowRoot) {
  3729. if (!shadowRoot.host.hasAttribute('_h5p_shadowroot_')) {
  3730. shadowRoot.host.setAttribute('_h5p_shadowroot_', '')
  3731.  
  3732. $hs.bindDocEvents(shadowRoot);
  3733. captureVideoEvents(shadowRoot);
  3734.  
  3735. shadowRoots.push(shadowRoot)
  3736. }
  3737. }
  3738. } catch (e) {
  3739. console.log('h5Player: initForShadowRoot failed')
  3740. }
  3741. }
  3742.  
  3743. function hackAttachShadow() { // attachShadow - DOM Standard
  3744.  
  3745. let _prototype_ = window && window.HTMLElement ? window.HTMLElement.prototype : null;
  3746. if (_prototype_ && typeof _prototype_.attachShadow == 'function') {
  3747.  
  3748. let _attachShadow = _prototype_.attachShadow
  3749.  
  3750. hackAttachShadow = null
  3751. _prototype_.attachShadow = function() {
  3752. let arg = [...arguments];
  3753. if (arg[0] && arg[0].mode) arg[0].mode = 'open';
  3754. let shadowRoot = _attachShadow.apply(this, arg);
  3755. initForShadowRoot(shadowRoot);
  3756. return shadowRoot
  3757. };
  3758.  
  3759. _prototype_.attachShadow.toString = () => _attachShadow.toString();
  3760.  
  3761. }
  3762.  
  3763. }
  3764.  
  3765. function hackCreateShadowRoot() { // createShadowRoot - Deprecated
  3766.  
  3767. let _prototype_ = window && window.HTMLElement ? window.HTMLElement.prototype : null;
  3768. if (_prototype_ && typeof _prototype_.createShadowRoot == 'function') {
  3769.  
  3770. let _createShadowRoot = _prototype_.createShadowRoot;
  3771.  
  3772. hackCreateShadowRoot = null
  3773. _prototype_.createShadowRoot = function() {
  3774. const shadowRoot = _createShadowRoot.apply(this, arguments);
  3775. initForShadowRoot(shadowRoot);
  3776. return shadowRoot;
  3777. };
  3778. _prototype_.createShadowRoot.toString = () => _createShadowRoot.toString();
  3779.  
  3780. }
  3781. }
  3782.  
  3783.  
  3784.  
  3785.  
  3786. /* 事件偵聽hack */
  3787. function hackEventListener() {
  3788. if (!window.Node) return;
  3789. const _prototype = window.Node.prototype;
  3790. let _addEventListener = _prototype.addEventListener;
  3791. let _removeEventListener = _prototype.removeEventListener;
  3792. if (typeof _addEventListener == 'function' && typeof _removeEventListener == 'function') {} else return;
  3793. hackEventListener = null;
  3794.  
  3795. class Listeners {
  3796.  
  3797. constructor(dom, type) {
  3798. Object.defineProperty(this, '_dom', {
  3799. value: dom,
  3800. writable: true,
  3801. enumerable: false,
  3802. configurable: true
  3803. });
  3804.  
  3805. Object.defineProperty(this, '_type', {
  3806. value: type,
  3807. writable: true,
  3808. enumerable: false,
  3809. configurable: true
  3810. });
  3811.  
  3812.  
  3813. Object.defineProperty(this, '_lastId', {
  3814. value: 0,
  3815. writable: true,
  3816. enumerable: false,
  3817. configurable: true
  3818. });
  3819.  
  3820.  
  3821. Object.defineProperty(this, '_count', {
  3822. value: 0,
  3823. writable: true,
  3824. enumerable: false,
  3825. configurable: true
  3826. });
  3827.  
  3828.  
  3829.  
  3830.  
  3831. }
  3832. get baseFunc() {
  3833. if (this._dom && this._type) {
  3834. return this._dom['on' + this._type];
  3835. }
  3836. }
  3837. get funcCount() {
  3838. if (this._dom && this._type) {
  3839. return (typeof this.baseFunc == 'function') * 1 + (this.length || 0)
  3840. }
  3841. }
  3842. makeId() {
  3843.  
  3844. return ++this._lastId
  3845. }
  3846.  
  3847. add(lh) {
  3848.  
  3849. this[++this._lastId] = lh;
  3850.  
  3851. }
  3852.  
  3853. remove(lh_removal) {
  3854.  
  3855. for (let k in this) {
  3856. let lh = this[k]
  3857. if (lh && lh.constructor == ListenerHandle && lh_removal.isEqual(lh)) {
  3858. delete this[k];
  3859. this._count--;
  3860. }
  3861. }
  3862.  
  3863.  
  3864. }
  3865.  
  3866.  
  3867.  
  3868. }
  3869.  
  3870.  
  3871. class ListenerHandle {
  3872. constructor(func, options) {
  3873. this.func = func
  3874. this.options = options
  3875. }
  3876.  
  3877. isEqual(anotherLH) {
  3878.  
  3879. if (this.func != anotherLH.func) return false;
  3880. if (this.options === anotherLH.options) return true;
  3881. if (this.options && anotherLH.options && typeof this.options == 'object' && typeof anotherLH.options == 'object') {} else {
  3882. return false;
  3883. }
  3884.  
  3885. return this.uOpt() == anotherLH.uOpt()
  3886.  
  3887.  
  3888.  
  3889. }
  3890. uOpt() {
  3891. let opt1 = "";
  3892. for (var k in this.options) {
  3893. opt1 += ", " + k + " : " + (typeof this[k] == 'boolean' ? this[k] : "N/A");
  3894. }
  3895.  
  3896. return opt1;
  3897.  
  3898.  
  3899. }
  3900.  
  3901.  
  3902. }
  3903.  
  3904.  
  3905.  
  3906. let hackedEvtCount = 0;
  3907.  
  3908. const options_passive_capture = {
  3909. passive: true,
  3910. capture: true
  3911. }
  3912. const options_passive_bubble = {
  3913. passive: true,
  3914. capture: false
  3915. }
  3916.  
  3917. const wmListeners = new WeakMap();
  3918. let phListeners = Promise.resolve();
  3919.  
  3920. let phActioners = Promise.resolve();
  3921. let phActionersCount = 0;
  3922.  
  3923. _prototype.addEventListener = function() {
  3924. //console.log(3321,arguments[0])
  3925. const args = arguments
  3926. const type = args[0]
  3927. const listener = args[1]
  3928.  
  3929. if (!this || !(this instanceof Node) || typeof type != 'string' || typeof listener != 'function') {
  3930. // if (!this || !(this instanceof EventTarget) || typeof type != 'string' || typeof listener != 'function') {
  3931. return _addEventListener.apply(this, args)
  3932. //unknown bug?
  3933. }
  3934.  
  3935. let bClickAction = false;
  3936. switch (type) {
  3937. case 'load':
  3938. case 'beforeunload':
  3939. case 'DOMContentLoaded':
  3940. return _addEventListener.apply(this, args);
  3941. break;
  3942. case 'mousewheel':
  3943. case 'touchstart':
  3944. case 'wheel':
  3945. case 'timeupdate':
  3946. if (!(args[2] && typeof args[2] == 'object')) {
  3947. const options = args[2] === true ? options_passive_capture : options_passive_bubble
  3948. args[2] = options
  3949. }
  3950. if(1){
  3951. const nType = `__nListener|${type}__`;
  3952. const nListener = listener[nType] || function() {
  3953. const _listener = listener;
  3954. const _this = this;
  3955. const _arguments = arguments;
  3956. const calling=() => {
  3957. phActioners=phActioners.then(()=>{
  3958. _listener.apply(_this, _arguments);
  3959. phActionersCount--;
  3960. })
  3961. }
  3962. if(phActionersCount===0){
  3963. phActionersCount++
  3964. window.requestAnimationFrame(calling)
  3965. }else{
  3966. phActionersCount++
  3967. calling();
  3968. }
  3969. };
  3970. listener[nType] = nListener;
  3971. args[1] = nListener;
  3972. }
  3973. break;
  3974. case 'mouseout':
  3975. case 'mouseover':
  3976. case 'focusin':
  3977. case 'focusout':
  3978. case 'mouseenter':
  3979. case 'mouseleave':
  3980. case 'mousemove':
  3981. if (this.nodeType === 1 && this.nodeName != "BODY" && this.nodeName != "HTML") {
  3982. const nType = `__nListener|${type}__`
  3983. const nListener = listener[nType] || function() {
  3984. window.requestAnimationFrame(() => listener.apply(this, arguments))
  3985. }
  3986. listener[nType] = nListener;
  3987. args[1] = nListener;
  3988. }
  3989. break;
  3990. case 'click':
  3991. case 'mousedown':
  3992. case 'mouseup':
  3993. bClickAction = true;
  3994. break;
  3995. default:
  3996. return _addEventListener.apply(this, args);
  3997. }
  3998.  
  3999.  
  4000. if (bClickAction) {
  4001.  
  4002.  
  4003. let res;
  4004. res = _addEventListener.apply(this, args)
  4005.  
  4006. phListeners=phListeners.then(()=>{
  4007.  
  4008. let listeners = wmListeners.get(this);
  4009. if (!listeners) wmListeners.set(this, listeners = {});
  4010.  
  4011. let lh = new ListenerHandle(args[1], args[2])
  4012.  
  4013. listeners[type] = listeners[type] || new Listeners(this, type)
  4014.  
  4015. listeners[type].add(lh)
  4016. listeners[type]._count++;
  4017.  
  4018. })
  4019.  
  4020. return res
  4021.  
  4022.  
  4023. } else if (arguments[2] && arguments[2].passive) {
  4024.  
  4025. const nType = `__nListener|${type}__`
  4026. const nListener = listener[nType] || function() {
  4027. return Promise.resolve().then(() => listener.apply(this, arguments))
  4028. }
  4029.  
  4030. listener[nType] = nListener;
  4031. args[1] = nListener;
  4032.  
  4033. }
  4034.  
  4035.  
  4036. return _addEventListener.apply(this, args);
  4037.  
  4038.  
  4039. }
  4040. // hack removeEventListener
  4041. _prototype.removeEventListener = function() {
  4042.  
  4043. let args = arguments
  4044. let type = args[0]
  4045. let listener = args[1]
  4046.  
  4047.  
  4048. if (!this || !(this instanceof Node) || typeof type != 'string' || typeof listener != 'function') {
  4049. return _removeEventListener.apply(this, arguments)
  4050. //unknown bug?
  4051. }
  4052.  
  4053. let bClickAction = false;
  4054. switch (type) {
  4055. case 'load':
  4056. case 'beforeunload':
  4057. case 'DOMContentLoaded':
  4058. return _removeEventListener.apply(this, args);
  4059. break;
  4060. case 'mousewheel':
  4061. case 'touchstart':
  4062. case 'wheel':
  4063. case 'timeupdate':
  4064. if (!(args[2] && typeof args[2] == 'object')) {
  4065. const options = args[2] === true ? options_passive_capture : options_passive_bubble
  4066. args[2] = options
  4067. }
  4068. break;
  4069. case 'mouseout':
  4070. case 'mouseover':
  4071. case 'focusin':
  4072. case 'focusout':
  4073. case 'mouseenter':
  4074. case 'mouseleave':
  4075. case 'mousemove':
  4076.  
  4077. break;
  4078. case 'click':
  4079. case 'mousedown':
  4080. case 'mouseup':
  4081. bClickAction = true;
  4082. break;
  4083. default:
  4084. return _removeEventListener.apply(this, args);
  4085. }
  4086.  
  4087. if (bClickAction) {
  4088.  
  4089.  
  4090. phListeners=phListeners.then(()=>{
  4091. let listeners = wmListeners.get(this);
  4092. if (listeners) {
  4093. let lh_removal = new ListenerHandle(args[1], args[2])
  4094.  
  4095. listeners[type].remove(lh_removal)
  4096. }
  4097. })
  4098. return _removeEventListener.apply(this, args);
  4099.  
  4100.  
  4101. } else {
  4102. const nType = `__nListener|${type}__`
  4103. if (typeof listener[nType] == 'function') arguments[1] = listener[nType]
  4104. return _removeEventListener.apply(this, arguments);
  4105. }
  4106.  
  4107.  
  4108.  
  4109.  
  4110. }
  4111. _prototype.addEventListener.toString = () => _addEventListener.toString();
  4112. _prototype.removeEventListener.toString = () => _removeEventListener.toString();
  4113.  
  4114.  
  4115. }
  4116.  
  4117.  
  4118. function initShadowRoots(rootDoc) {
  4119. function onReady() {
  4120. var treeWalker = rootDoc.createTreeWalker(
  4121. rootDoc.documentElement,
  4122. NodeFilter.SHOW_ELEMENT, {
  4123. acceptNode: (node) => (node.shadowRoot ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP)
  4124. }
  4125. );
  4126. var nodeList = [];
  4127. while (treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
  4128. for (const node of nodeList) {
  4129. initForShadowRoot(node.shadowRoot)
  4130. }
  4131. }
  4132. if (rootDoc.readyState !== 'loading') {
  4133. onReady();
  4134. } else {
  4135. rootDoc.addEventListener('DOMContentLoaded', onReady, false);
  4136. }
  4137. }
  4138.  
  4139. function captureVideoEvents(rootDoc) {
  4140.  
  4141. var g = function(evt) {
  4142.  
  4143.  
  4144. var domElement = evt.target || this || null
  4145. if (domElement && domElement.nodeType == 1 && domElement.nodeName == "VIDEO") {
  4146. var video = domElement
  4147. if (!domElement.getAttribute('_h5ppid')) handlerVideoFound(video);
  4148. if (domElement.getAttribute('_h5ppid')) {
  4149. switch (evt.type) {
  4150. case 'loadedmetadata':
  4151. return $hs.handlerVideoLoadedMetaData.call(video, evt);
  4152. // case 'playing':
  4153. // return $hs.handlerVideoPlaying.call(video, evt);
  4154. // case 'pause':
  4155. // return $hs.handlerVideoPause.call(video, evt);
  4156. // case 'volumechange':
  4157. // return $hs.handlerVideoVolumeChange.call(video, evt);
  4158. }
  4159. }
  4160. }
  4161.  
  4162.  
  4163. }
  4164.  
  4165. // using capture phase
  4166. rootDoc.addEventListener('loadedmetadata', g, $mb.eh_capture_passive());
  4167.  
  4168. }
  4169.  
  4170. function handlerVideoFound(video) {
  4171.  
  4172. if (!video) return;
  4173. if (video.getAttribute('_h5ppid')) return;
  4174. let alabel = video.getAttribute('aria-label')
  4175. if (alabel && typeof alabel == "string" && alabel.toUpperCase() == "GIF") return;
  4176.  
  4177.  
  4178. consoleLog('handlerVideoFound', video)
  4179.  
  4180. $hs.intVideoInitCount = ($hs.intVideoInitCount || 0) + 1;
  4181. let vpid = 'h5p-' + $hs.intVideoInitCount
  4182. consoleLog(' - HTML5 Video is detected -', `Number of Videos: ${$hs.intVideoInitCount}`)
  4183. if ($hs.intVideoInitCount === 1) $hs.fireGlobalInit();
  4184. video.setAttribute('_h5ppid', vpid)
  4185.  
  4186.  
  4187. playerConfs[vpid] = new PlayerConf();
  4188. playerConfs[vpid].domElement = video;
  4189. playerConfs[vpid].domActive = DOM_ACTIVE_FOUND;
  4190.  
  4191. let rootNode = getRoot(video);
  4192.  
  4193. if (rootNode.host) $hs.getPlayerBlockElement(video); // shadowing
  4194. let rootElm = domAppender(rootNode) || document.documentElement //48763
  4195. _add_filter(rootElm) // either main document or shadow node
  4196.  
  4197.  
  4198.  
  4199. video.addEventListener('playing', $hs.handlerVideoPlaying, $mb.eh_capture_passive());
  4200. video.addEventListener('pause', $hs.handlerVideoPause, $mb.eh_capture_passive());
  4201. video.addEventListener('volumechange', $hs.handlerVideoVolumeChange, $mb.eh_capture_passive());
  4202.  
  4203.  
  4204.  
  4205.  
  4206. }
  4207.  
  4208.  
  4209. hackAttachShadow()
  4210. hackCreateShadowRoot()
  4211. hackEventListener()
  4212.  
  4213.  
  4214. window.addEventListener('message', $hs.handlerWinMessage, false);
  4215. $hs.bindDocEvents(document);
  4216. captureVideoEvents(document);
  4217. initShadowRoots(document);
  4218.  
  4219.  
  4220. let windowsLD = (function() {
  4221. let ls_res = [];
  4222. try {
  4223. ls_res = [!!window.localStorage, !!window.top.localStorage];
  4224. } catch (e) {}
  4225. try {
  4226. let winp = window;
  4227. let winc = 0;
  4228. while (winp !== window.top && winp && ++winc) winp = winp.parentNode;
  4229. ls_res.push(winc);
  4230. } catch (e) {}
  4231. return ls_res;
  4232. })();
  4233.  
  4234. consoleLogF('- h5Player Plugin Loaded -', ...windowsLD)
  4235.  
  4236. function isInCrossOriginFrame() {
  4237. let result = true;
  4238. try {
  4239. if (window.top.localStorage || window.top.location.href) result = false;
  4240. } catch (e) {}
  4241. return result
  4242. }
  4243.  
  4244. if (isInCrossOriginFrame()) consoleLog('cross origin frame detected');
  4245.  
  4246.  
  4247. const $bv = {
  4248.  
  4249. boostVideoPerformanceActivate: function() {
  4250. if ($bz.boosted) return;
  4251. $bz.boosted = true;
  4252. },
  4253.  
  4254.  
  4255. boostVideoPerformanceDeactivate: function() {
  4256. if (!$bz.boosted) return;
  4257. $bz.boosted = false;
  4258. }
  4259.  
  4260. }
  4261.  
  4262.  
  4263.  
  4264. })();
  4265.  
  4266. })(window.unsafeWindow, window);