HTML5 Video Player Enhance

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

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

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