HTML5 Video Player Enhance

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

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

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