HTML5 Video Player Enhance

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

目前為 2021-06-28 提交的版本,檢視 最新版本

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