HTML5 Video Player Enhance

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

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

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