HTML5 Video Player Enhance

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

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

  1. // ==UserScript==
  2. // @name HTML5 Video Player Enhance
  3. // @version 2.9.4.17
  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://gf.qytechs.cn/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) {
  2275. let player = $hs.player()
  2276. if (!player) return;
  2277. let wPlayer = $hs.getPlayerBlockElement(player, true);
  2278. let layoutBox = wPlayer.parentNode;
  2279.  
  2280. if ((layoutBox && layoutBox.nodeType == 1) && (!tipsDom.parentNode || tipsDom.parentNode !== layoutBox)) {
  2281.  
  2282. consoleLog('changed_layoutBox')
  2283. layoutBox.insertBefore(tipsDom, wPlayer);
  2284.  
  2285. }
  2286. },
  2287.  
  2288. _hasEventListener: function(elm, p) {
  2289. if (typeof elm['on' + p] == 'function') return true;
  2290. let listeners = $hs._getEventListeners(elm)
  2291. if (listeners) {
  2292. const cache = listeners[p]
  2293. return cache && cache.count > 0
  2294. }
  2295. return false;
  2296. },
  2297.  
  2298. _getEventListeners: function(elmNode) {
  2299.  
  2300.  
  2301. let listeners = wmListeners.get(elmNode);
  2302.  
  2303. if (listeners && typeof listeners == 'object') return listeners;
  2304.  
  2305. return null;
  2306.  
  2307. },
  2308.  
  2309. queryFullscreenBtnsIndependant: function(parentNode) {
  2310.  
  2311. let btns = [];
  2312.  
  2313. function elmCallback(elm) {
  2314.  
  2315. let hasClickListeners = null,
  2316. childElementCount = null,
  2317. isVisible = null,
  2318. btnElm = elm;
  2319. var pElm = elm;
  2320. while (pElm && pElm.nodeType === 1 && pElm != parentNode && pElm.querySelector('video') === null) {
  2321.  
  2322. let funcTest = $hs._hasEventListener(pElm, 'click');
  2323. funcTest = funcTest || $hs._hasEventListener(pElm, 'mousedown');
  2324. funcTest = funcTest || $hs._hasEventListener(pElm, 'mouseup');
  2325.  
  2326. if (funcTest) {
  2327. hasClickListeners = true
  2328. btnElm = pElm;
  2329. break;
  2330. }
  2331.  
  2332. pElm = pElm.parentNode;
  2333. }
  2334. if (btns.indexOf(btnElm) >= 0) return; //btn>a.fullscreen-1>b.fullscreen-2>c.fullscreen-3
  2335.  
  2336.  
  2337. if ('childElementCount' in elm) {
  2338.  
  2339. childElementCount = elm.childElementCount;
  2340.  
  2341. }
  2342. if ('offsetParent' in elm) {
  2343. isVisible = !!elm.offsetParent; //works with parent/self display none; not work with visiblity hidden / opacity0
  2344.  
  2345. }
  2346.  
  2347. if (hasClickListeners) {
  2348. let btn = {
  2349. elm,
  2350. btnElm,
  2351. isVisible,
  2352. hasClickListeners,
  2353. childElementCount,
  2354. isContained: null
  2355. };
  2356.  
  2357. //console.log('btnElm', btnElm)
  2358.  
  2359. btns.push(btnElm)
  2360.  
  2361. }
  2362. }
  2363.  
  2364.  
  2365. for (const elm of parentNode.querySelectorAll('[class*="full"][class*="screen"]')) {
  2366. let className = (elm.getAttribute('class') || "");
  2367. if (/\b(fullscreen|full-screen)\b/i.test(className.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  2368. elmCallback(elm)
  2369. }
  2370. }
  2371.  
  2372.  
  2373. for (const elm of parentNode.querySelectorAll('[id*="full"][id*="screen"]')) {
  2374. let idName = (elm.getAttribute('id') || "");
  2375. if (/\b(fullscreen|full-screen)\b/i.test(idName.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  2376. elmCallback(elm)
  2377. }
  2378. }
  2379.  
  2380. for (const elm of parentNode.querySelectorAll('[name*="full"][name*="screen"]')) {
  2381. let nName = (elm.getAttribute('name') || "");
  2382. if (/\b(fullscreen|full-screen)\b/i.test(nName.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  2383. elmCallback(elm)
  2384. }
  2385. }
  2386.  
  2387. parentNode=null;
  2388.  
  2389. return btns;
  2390.  
  2391. },
  2392. exclusiveElements: function(elms) {
  2393.  
  2394. //not containing others
  2395. let res = [];
  2396.  
  2397. for (const roleElm of elms) {
  2398.  
  2399. let isContained = false;
  2400. for (const testElm of elms) {
  2401. if (testElm != roleElm && roleElm.contains(testElm)) {
  2402. isContained = true;
  2403. break;
  2404. }
  2405. }
  2406. if (!isContained) res.push(roleElm)
  2407. }
  2408. return res;
  2409.  
  2410. },
  2411.  
  2412. getWithFullscreenBtn: function(actionBoxRelation) {
  2413.  
  2414.  
  2415.  
  2416. //console.log('callFullScreenBtn', 300)
  2417.  
  2418. if (actionBoxRelation && actionBoxRelation.actionBox) {
  2419. let actionBox = actionBoxRelation.actionBox;
  2420. let btnElements = actionBoxRelation.fullscreenBtns;
  2421.  
  2422. // console.log('callFullScreenBtn', 400)
  2423. if (btnElements && btnElements.length > 0) {
  2424.  
  2425. // console.log('callFullScreenBtn', 500, btnElements, actionBox.contains(btnElements[0]))
  2426.  
  2427. let btnElement_idx = btnElements._only_idx;
  2428.  
  2429. if (btnElement_idx >= 0) {
  2430.  
  2431. } else if (btnElements.length === 1) {
  2432. btnElement_idx = 0;
  2433. } else if (btnElements.length > 1) {
  2434. //web-fullscreen-on/off ; fullscreen-on/off ....
  2435.  
  2436. const strList = btnElements.map(elm => [elm.className || 'null', elm.id || 'null', elm.name || 'null'].join('-').replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))
  2437.  
  2438. const filterOutScores = new Array(strList.length).fill(0);
  2439. const filterInScores = new Array(strList.length).fill(0);
  2440. const filterScores = new Array(strList.length).fill(0);
  2441. for (const [j, str] of strList.entries()) {
  2442. if (/\b(fullscreen|full-screen)\b/i.test(str)) filterInScores[j] += 1
  2443. if (/\b(web-fullscreen|web-full-screen)\b/i.test(str)) filterOutScores[j] += 1
  2444. if (/\b(fullscreen-on|full-screen-on)\b/i.test(str)) filterInScores[j] += 1
  2445. if (/\b(fullscreen-off|full-screen-off)\b/i.test(str)) filterOutScores[j] += 1
  2446. if (/\b(on-fullscreen|on-full-screen)\b/i.test(str)) filterInScores[j] += 1
  2447. if (/\b(off-fullscreen|off-full-screen)\b/i.test(str)) filterOutScores[j] += 1
  2448. }
  2449.  
  2450. let maxScore = -1e7;
  2451. for (const [j, str] of strList.entries()) {
  2452. filterScores[j] = filterInScores[j] * 3 - filterOutScores[j] * 2
  2453. if (filterScores[j] > maxScore) maxScore = filterScores[j];
  2454. }
  2455. btnElement_idx = filterScores.indexOf(maxScore)
  2456. if (btnElement_idx < 0) btnElement_idx = 0; //unknown
  2457. }
  2458.  
  2459. btnElements._only_idx = btnElement_idx
  2460.  
  2461.  
  2462. //consoleLog('original fullscreen')
  2463. return btnElements[btnElement_idx];
  2464.  
  2465. }
  2466.  
  2467.  
  2468. }
  2469. return null
  2470. },
  2471.  
  2472. callFullScreenBtn: function() {
  2473. console.log('callFullScreenBtn')
  2474.  
  2475.  
  2476.  
  2477. let player = $hs.player()
  2478. if (!player || !player.ownerDocument || !('exitFullscreen' in player.ownerDocument)) return;
  2479.  
  2480. let btnElement = null;
  2481.  
  2482. let vpid = player.getAttribute('_h5ppid') || null;
  2483.  
  2484. if (!vpid) return;
  2485.  
  2486.  
  2487. const chFull = $hs.toolCheckFullScreen(player.ownerDocument);
  2488.  
  2489.  
  2490.  
  2491. if (chFull === true) {
  2492. player.ownerDocument.exitFullscreen();
  2493. return;
  2494. }
  2495.  
  2496. let actionBoxRelation = $hs.actionBoxRelations[vpid];
  2497.  
  2498.  
  2499. let asyncRes = Promise.resolve(actionBoxRelation)
  2500. if (chFull === false) asyncRes = asyncRes.then($hs.getWithFullscreenBtn);
  2501. else asyncRes = asyncRes.then(() => null)
  2502.  
  2503. asyncRes.then((btnElement) => {
  2504.  
  2505. if (btnElement) {
  2506.  
  2507. window.requestAnimationFrame(() => btnElement.click());
  2508. player=null;
  2509. actionBoxRelation=null;
  2510. return;
  2511. }
  2512.  
  2513. let fsElm = getRoot(player).querySelector(`[_h5p_fsElm_="${vpid}"]`); //it is set in fullscreenchange
  2514.  
  2515. let gPlayer = fsElm
  2516.  
  2517. if (gPlayer) {
  2518.  
  2519. } else if (actionBoxRelation && actionBoxRelation.actionBox) {
  2520. gPlayer = actionBoxRelation.actionBox;
  2521. } else if (actionBoxRelation && actionBoxRelation.layoutBox) {
  2522. gPlayer = actionBoxRelation.layoutBox;
  2523. } else {
  2524. gPlayer = player;
  2525. }
  2526.  
  2527.  
  2528. player=null;
  2529. actionBoxRelation=null;
  2530.  
  2531. if (gPlayer != fsElm && !fsElm) {
  2532. delayCall('$$videoReset_fsElm', function() {
  2533. gPlayer.removeAttribute('_h5p_fsElm_')
  2534. }, 500)
  2535. }
  2536.  
  2537. console.log('DOM fullscreen', gPlayer)
  2538. try {
  2539. const res = gPlayer.requestFullscreen()
  2540. if (res && res.constructor.name == "Promise") res.catch((e) => 0)
  2541. } catch (e) {
  2542. console.log('DOM fullscreen Error', e)
  2543. }
  2544.  
  2545.  
  2546.  
  2547.  
  2548.  
  2549. })
  2550.  
  2551.  
  2552.  
  2553.  
  2554. },
  2555. /* 設置播放速度 */
  2556. setPlaybackRate: function(num, flagTips) {
  2557. let player = $hs.player()
  2558. let curPlaybackRate
  2559. if (num) {
  2560. num = +num
  2561. if (num > 0) { // also checking the type of variable
  2562. curPlaybackRate = num < 0.1 ? 0.1 : +(num.toFixed(1))
  2563. } else {
  2564. console.error('h5player: 播放速度轉換出錯')
  2565. return false
  2566. }
  2567. } else {
  2568. curPlaybackRate = $hs.getPlaybackRate()
  2569. }
  2570. /* 記錄播放速度的信息 */
  2571.  
  2572. let changed = curPlaybackRate !== player.playbackRate;
  2573.  
  2574. if (curPlaybackRate !== player.playbackRate) {
  2575.  
  2576. Store.save('_playback_rate_', curPlaybackRate + '')
  2577. $hs.playbackRate = curPlaybackRate
  2578. player.playbackRate = curPlaybackRate
  2579. /* 本身處於1被播放速度的時候不再提示 */
  2580. //if (!num && curPlaybackRate === 1) return;
  2581.  
  2582. }
  2583.  
  2584. flagTips = (flagTips < 0) ? false : (flagTips > 0) ? true : changed;
  2585. if (flagTips) $hs.tips('Playback speed: ' + player.playbackRate + 'x')
  2586. },
  2587. tuneCurrentTimeTips: function(_amount, changed) {
  2588.  
  2589. $hs.tips(false);
  2590. if (changed) {
  2591. if (_amount > 0) $hs.tips(_amount + ' Sec. Forward', undefined, 3000);
  2592. else $hs.tips(-_amount + ' Sec. Backward', undefined, 3000)
  2593. }
  2594. },
  2595. tuneCurrentTime: function(amount) {
  2596. let _amount = +(+amount).toFixed(1);
  2597. let player = $hs.player();
  2598. if (_amount >= 0 || _amount < 0) {} else {
  2599. return;
  2600. }
  2601.  
  2602. let newCurrentTime = player.currentTime + _amount;
  2603. if (newCurrentTime < 0) newCurrentTime = 0;
  2604. if (newCurrentTime > player.duration) newCurrentTime = player.duration;
  2605.  
  2606. let changed = newCurrentTime != player.currentTime && newCurrentTime >= 0 && newCurrentTime <= player.duration;
  2607.  
  2608. if (changed) {
  2609. //player.currentTime = newCurrentTime;
  2610. //player.pause();
  2611.  
  2612.  
  2613. const video = player;
  2614. var isPlaying = video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA;
  2615.  
  2616. if (isPlaying) {
  2617. player.pause();
  2618. $hs.ccad = $hs.ccad || function() {
  2619. if (player.paused) player.play();
  2620. };
  2621. player.addEventListener('seeked', $hs.ccad, {
  2622. passive: true,
  2623. capture: true,
  2624. once: true
  2625. });
  2626.  
  2627. }
  2628.  
  2629.  
  2630.  
  2631.  
  2632. player.currentTime = +newCurrentTime.toFixed(0)
  2633.  
  2634. $hs.tuneCurrentTimeTips(_amount, changed)
  2635.  
  2636.  
  2637. }
  2638.  
  2639. },
  2640. tuneVolume: function(amount) {
  2641.  
  2642. let player = $hs.player()
  2643.  
  2644. let intAmount = Math.round(amount*100)
  2645.  
  2646. let intOldVol = Math.round(player.volume*100)
  2647. let intNewVol = intOldVol+intAmount
  2648.  
  2649.  
  2650. //0.53 -> 0.55
  2651.  
  2652. //0.53 / 0.05 =10.6 => 11 => 11*0.05 = 0.55
  2653.  
  2654. intNewVol = Math.round(intNewVol/intAmount)*intAmount
  2655. if(intAmount>0 && intNewVol-intOldVol>intAmount) intNewVol-=intAmount;
  2656. else if(intAmount<0 && intNewVol-intOldVol<intAmount) intNewVol-=intAmount;
  2657.  
  2658.  
  2659. let _amount = intAmount/100;
  2660. let oldVol=intOldVol/100;
  2661. let newVol =intNewVol/100;
  2662.  
  2663.  
  2664. if (newVol < 0) newVol = 0;
  2665. if (newVol > 1) newVol = 1;
  2666. let chVol = oldVol !== newVol && newVol >= 0 && newVol <= 1;
  2667.  
  2668. if (chVol) {
  2669.  
  2670. if (_amount > 0 && oldVol < 1) {
  2671. player.volume = newVol // positive
  2672. } else if (_amount < 0 && oldVol > 0) {
  2673. player.volume = newVol // negative
  2674. }
  2675. $hs.tips(false);
  2676. $hs.tips('Volume: ' + dround(player.volume * 100) + '%', undefined)
  2677. }
  2678. },
  2679. switchPlayStatus: function() {
  2680. let player = $hs.player()
  2681. if (player.paused) {
  2682. player.play()
  2683. if (player._isThisPausedBefore_) {
  2684. $hs.tips(false);
  2685. $hs.tips('Playback resumed', undefined, 2500)
  2686. }
  2687. } else {
  2688. player.pause()
  2689. $hs.tips(false);
  2690. $hs.tips('Playback paused', undefined, 2500)
  2691. }
  2692. },
  2693. tipsClassName: 'html_player_enhance_tips',
  2694. _tips: function(player, str, duration, order) {
  2695.  
  2696.  
  2697. let useCache=true;
  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===false && tipsDom._playerElement === player)){
  2733.  
  2734. $hs.change_layoutBox(tipsDom);
  2735. tipsDom._playerElement = player;
  2736. tipsDom._playerVPID = player.getAttribute('_h5ppid');
  2737. tipsDom._playerBlockElm = $hs.getPlayerBlockElement(player, true)
  2738. useCache=false;
  2739.  
  2740. }
  2741.  
  2742. $hs.pendingTips = $hs.pendingTips||{};
  2743. $hs.pendingTips[tipsDom._playerVPID]=tipsDom
  2744.  
  2745. if (duration === undefined) duration = 2000
  2746.  
  2747.  
  2748. tipsDom.setAttribute('data-h5p-pot-tips',str);
  2749.  
  2750.  
  2751.  
  2752.  
  2753.  
  2754. const withFadeOut = duration > 0 && (player.paused || !($hs.mouseDownAt && $hs.mouseDownAt.insideVideo===player));
  2755.  
  2756.  
  2757. !(function(tipsDom, withFadeOut){
  2758. const vpid = tipsDom._playerVPID
  2759. window.requestAnimationFrame(function(){
  2760. tipsDom.setAttribute('_h5p_animate','0');
  2761. if(!withFadeOut) return;
  2762. window.requestAnimationFrame(function(){
  2763. const tipsDom = $hs.pendingTips?$hs.pendingTips[vpid]:null;
  2764. if(!tipsDom)return;
  2765. tipsDom.setAttribute('_h5p_animate','1');
  2766. delete $hs.pendingTips[vpid]
  2767.  
  2768. })
  2769. })
  2770. })(tipsDom, withFadeOut);
  2771.  
  2772.  
  2773.  
  2774. if ( !(duration > 0) ) {
  2775. order = -1;
  2776. }
  2777.  
  2778. tipsDom.tipsOrder = order
  2779.  
  2780.  
  2781.  
  2782. }
  2783.  
  2784. }
  2785.  
  2786. return tipsDom;
  2787.  
  2788. }).then((tipsDom) => {
  2789. if (tipsDom === false) return false;
  2790.  
  2791. if(useCache) return;
  2792. if (window.ResizeObserver && tipsDom._playerBlockElm.parentNode) { // tipsDom._playerBlockElm.parentNode == null => bug
  2793. //observe not fire twice for the same element.
  2794. if (!$hs.observer_resizeVideos) $hs.observer_resizeVideos = new ResizeObserver(hanlderResizeVideo)
  2795. $hs.observer_resizeVideos.observe(tipsDom._playerBlockElm.parentNode)
  2796. $hs.observer_resizeVideos.observe(tipsDom._playerBlockElm)
  2797. $hs.observer_resizeVideos.observe(player)
  2798. }
  2799.  
  2800. if(!$hs.mouseDownAt){
  2801. //ensure function called
  2802. window.requestAnimationFrame(() => $hs.fixNonBoxingVideoTipsPosition(tipsDom, player))
  2803.  
  2804. }
  2805.  
  2806. })
  2807.  
  2808. },
  2809. tips: function(str, duration, order) {
  2810. let player = $hs.player()
  2811. if (!player) {
  2812. consoleLog('h5Player Tips:', str)
  2813. } else {
  2814. $hs._tips(player, str, duration, order)
  2815.  
  2816. }
  2817.  
  2818. },
  2819. initTips: function() {
  2820. /* 設置提示DOM的樣式 */
  2821. let player = $hs.player()
  2822. let shadowRoot = getRoot(player);
  2823. let doc = player.ownerDocument;
  2824. //console.log((document.documentElement.qq=player),shadowRoot,'xax')
  2825. let parentNode = player.parentNode
  2826. let tcn = player.getAttribute('_h5player_tips') || ($hs.tipsClassName + '_' + (+new Date));
  2827. player.setAttribute('_h5player_tips', tcn)
  2828. if (shadowRoot.querySelector('#' + tcn)) return false;
  2829.  
  2830. if (!shadowRoot._onceAddedCSS) {
  2831. shadowRoot._onceAddedCSS = true;
  2832.  
  2833. let cssStyle = `
  2834. [data-h5p-pot-tips][_h5p_animate="1"]{
  2835. animation: 2s linear 0s normal forwards 1 delayHide;
  2836. }
  2837. [data-h5p-pot-tips][_h5p_animate="0"]{
  2838. opacity:.95; transform: translate(0,0);
  2839. }
  2840.  
  2841. @keyframes delayHide{
  2842. 0%, 99% { opacity:0.95; transform: translate(0,0); }
  2843. 100% { opacity:0; transform:translate(-9999px); }
  2844. }
  2845. ` + `
  2846. [data-h5p-pot-tips]{
  2847. font-weight: bold !important;
  2848. position: absolute !important;
  2849. z-index: 999 !important;
  2850. font-size: ${$hs.fontSize || 16}px !important;
  2851. padding: 0px !important;
  2852. border:none !important;
  2853. background: rgba(0,0,0,0) !important;
  2854. color:#738CE6 !important;
  2855. text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;
  2856. top: 50%;
  2857. left: 50%;
  2858. max-width:500px;max-height:50px;
  2859. border-radius:3px;
  2860. font-family: 'microsoft yahei', Verdana, Geneva, sans-serif;
  2861. pointer-events: none;
  2862. }
  2863. [data-h5p-pot-tips]::before{
  2864. content:attr(data-h5p-pot-tips);
  2865. display:inline-block;
  2866. position:relative;
  2867.  
  2868. }
  2869. body div[data-h5p-pot-tips]{
  2870. -webkit-user-select: none !important;
  2871. -moz-user-select: none !important;
  2872. -ms-user-select: none !important;
  2873. user-select: none !important;
  2874. -webkit-touch-callout: none !important;
  2875. -webkit-user-select: none !important;
  2876. -khtml-user-drag: none !important;
  2877. -khtml-user-select: none !important;
  2878. -moz-user-select: none !important;
  2879. -moz-user-select: -moz-none !important;
  2880. -ms-user-select: none !important;
  2881. user-select: none !important;
  2882. }
  2883. .ytp-chrome-bottom+span#volumeUI:last-child:empty{
  2884. display:none;
  2885. }
  2886. `.replace(/\r\n/g, '');
  2887.  
  2888.  
  2889. let cssContainer = domAppender(shadowRoot);
  2890.  
  2891.  
  2892. if (!cssContainer) {
  2893. cssContainer = makeNoRoot(shadowRoot)
  2894. }
  2895.  
  2896. domTool.addStyle(cssStyle, cssContainer);
  2897.  
  2898. }
  2899.  
  2900. let tipsDom = doc.createElement('div')
  2901.  
  2902. $hs.handler_tipsDom_animation = $hs.handler_tipsDom_animation || function(e) {
  2903. this._tips_display_none=true;
  2904. }
  2905.  
  2906. tipsDom.addEventListener(crossBrowserTransition('animation'), $hs.handler_tipsDom_animation, $mb.eh_bubble_passive())
  2907.  
  2908. tipsDom.id = tcn;
  2909. tipsDom.setAttribute('data-h5p-pot-tips','');
  2910. tipsDom.setAttribute('_h5p_animate','0');
  2911. tipsDom._tips_display_none=true;
  2912. $hs.change_layoutBox(tipsDom);
  2913.  
  2914. return true;
  2915. },
  2916.  
  2917. responsiveSizing: function(container, elm) {
  2918.  
  2919. let gcssP = getComputedStyle(container);
  2920.  
  2921. let gcssE = getComputedStyle(elm);
  2922.  
  2923. //console.log(gcssE.left,gcssP.width)
  2924. let elmBound = {
  2925. left: parseFloat(gcssE.left) / parseFloat(gcssP.width),
  2926. width: parseFloat(gcssE.width) / parseFloat(gcssP.width),
  2927. top: parseFloat(gcssE.top) / parseFloat(gcssP.height),
  2928. height: parseFloat(gcssE.height) / parseFloat(gcssP.height)
  2929. };
  2930.  
  2931. let elm00 = [elmBound.left, elmBound.top];
  2932. let elm01 = [elmBound.left + elmBound.width, elmBound.top];
  2933. let elm10 = [elmBound.left, elmBound.top + elmBound.height];
  2934. let elm11 = [elmBound.left + elmBound.width, elmBound.top + elmBound.height];
  2935.  
  2936. return {
  2937. elm00,
  2938. elm01,
  2939. elm10,
  2940. elm11,
  2941. plw: elmBound.width,
  2942. plh: elmBound.height
  2943. };
  2944.  
  2945. },
  2946.  
  2947. fixNonBoxingVideoTipsPosition: function(tipsDom, player) {
  2948.  
  2949. if (!tipsDom || !player) return;
  2950.  
  2951. let ct = $hs.getCommonContainer(tipsDom, player)
  2952.  
  2953. if (!ct) return;
  2954.  
  2955. //relative
  2956.  
  2957. let elm00 = $hs.responsiveSizing(ct, player).elm00;
  2958.  
  2959. if (isNaN(elm00[0]) || isNaN(elm00[1])) {
  2960.  
  2961. [tipsDom.style.left, tipsDom.style.top] = [player.style.left, player.style.top];
  2962. //eg auto
  2963. } else {
  2964.  
  2965. let rlm00 = elm00.map(t => (t * 100).toFixed(2) + '%');
  2966. [tipsDom.style.left, tipsDom.style.top] = rlm00;
  2967.  
  2968. }
  2969.  
  2970. // absolute
  2971.  
  2972. let _offset = {
  2973. left: 10,
  2974. top: 15
  2975. };
  2976.  
  2977. let customOffset = {
  2978. left: _offset.left,
  2979. top: _offset.top
  2980. };
  2981. let p = tipsDom.getBoundingClientRect();
  2982. let q = player.getBoundingClientRect();
  2983. let currentPos = [p.left, p.top];
  2984.  
  2985. let targetPos = [q.left + player.offsetWidth * 0 + customOffset.left, q.top + player.offsetHeight * 0 + customOffset.top];
  2986.  
  2987. let mL = +tipsDom.style.marginLeft.replace('px', '') || 0;
  2988. if (isNaN(mL)) mL = 0;
  2989. let mT = +tipsDom.style.marginTop.replace('px', '') || 0;
  2990. if (isNaN(mT)) mT = 0;
  2991.  
  2992. let z1 = -(currentPos[0] - targetPos[0]);
  2993. let z2 = -(currentPos[1] - targetPos[1]);
  2994.  
  2995. if (z1 || z2) {
  2996.  
  2997. let y1 = z1 + mL;
  2998. let y2 = z2 + mT;
  2999.  
  3000. tipsDom.style.marginLeft = y1 + 'px';
  3001. tipsDom.style.marginTop = y2 + 'px';
  3002.  
  3003. }
  3004. },
  3005.  
  3006. playerTrigger: function(player, event) {
  3007.  
  3008.  
  3009.  
  3010. if (!player || !event) return
  3011. const pCode = event.code;
  3012. let keyAsm = (event.shiftKey ? SHIFT : 0) | ((event.ctrlKey || event.metaKey) ? CTRL : 0) | (event.altKey ? ALT : 0);
  3013.  
  3014.  
  3015.  
  3016.  
  3017. let vpid = player.getAttribute('_h5ppid') || null;
  3018. if (!vpid) return;
  3019. let playerConf = playerConfs[vpid]
  3020. if (!playerConf) return;
  3021.  
  3022. //shift + key
  3023. if (keyAsm == SHIFT) {
  3024. // 網頁FULLSCREEN
  3025. if (pCode === 'Enter') {
  3026. //$hs.callFullScreenBtn()
  3027. //return TERMINATE
  3028. } else if (pCode == 'KeyF') {
  3029. //change unsharpen filter
  3030.  
  3031. let resList = ["unsharpen3_05", "unsharpen3_10", "unsharpen5_05", "unsharpen5_10", "unsharpen9_05", "unsharpen9_10"]
  3032. let res = (prompt("Enter the unsharpen mask\n(" + resList.map(x => '"' + x + '"').join(', ') + ")", "unsharpen9_05") || "").toLowerCase();
  3033. if (resList.indexOf(res) < 0) res = ""
  3034. GM_setValue("unsharpen_mask", res)
  3035. for (const el of document.querySelectorAll('video[_h5p_uid_encrypted]')) {
  3036. if (el.style.filter == "" || el.style.filter) {
  3037. let filterStr1 = el.style.filter.replace(/\s*url\(\"#_h5p_unsharpen[\d\_]+\"\)/, '');
  3038. let filterStr2 = (res.length > 0 ? ' url("#_h5p_' + res + '")' : '')
  3039. el.style.filter = filterStr1 + filterStr2;
  3040. }
  3041. }
  3042. return TERMINATE
  3043.  
  3044. }
  3045. // 進入或退出畫中畫模式
  3046. else if (pCode == 'KeyP') {
  3047. $hs.pictureInPicture(player)
  3048.  
  3049. return TERMINATE
  3050. } else if (pCode == 'KeyR') {
  3051. if (player._h5player_lastrecord_ !== null && (player._h5player_lastrecord_ >= 0 || player._h5player_lastrecord_ <= 0)) {
  3052. $hs.setPlayProgress(player, player._h5player_lastrecord_)
  3053.  
  3054. return TERMINATE
  3055. }
  3056.  
  3057. } else if (pCode == 'KeyO') {
  3058. let _debug_h5p_logging_ch = false;
  3059. try {
  3060. Store._setItem('_h5_player_sLogging_', 1 - Store._getItem('_h5_player_sLogging_'))
  3061. _debug_h5p_logging_ = +Store._getItem('_h5_player_sLogging_') > 0;
  3062. _debug_h5p_logging_ch = true;
  3063. } catch (e) {
  3064.  
  3065. }
  3066. consoleLogF('_debug_h5p_logging_', !!_debug_h5p_logging_, 'changed', _debug_h5p_logging_ch)
  3067.  
  3068. if (_debug_h5p_logging_ch) {
  3069.  
  3070. return TERMINATE
  3071. }
  3072. } else if (pCode == 'KeyT') {
  3073. if (/^blob/i.test(player.currentSrc)) {
  3074. alert(`The current video is ${player.currentSrc}\nSorry, it cannot be opened in PotPlayer.`);
  3075. } else {
  3076. let confirm_res = confirm(`The current video is ${player.currentSrc}\nDo you want to open it in PotPlayer?`);
  3077. if (confirm_res) window.open('potplayer://' + player.currentSrc, '_blank');
  3078. }
  3079. return TERMINATE
  3080. }
  3081.  
  3082.  
  3083.  
  3084. let videoScale = playerConf.vFactor;
  3085.  
  3086. function tipsForVideoScaling() {
  3087.  
  3088. playerConf.vFactor = +videoScale.toFixed(1);
  3089.  
  3090. playerConf.cssTransform();
  3091. let tipsMsg = `視頻縮放率:${ +(videoScale * 100).toFixed(2) }%`
  3092. if (playerConf.translate.x) {
  3093. tipsMsg += `,水平位移:${playerConf.translate.x}px`
  3094. }
  3095. if (playerConf.translate.y) {
  3096. tipsMsg += `,垂直位移:${playerConf.translate.y}px`
  3097. }
  3098. $hs.tips(false);
  3099. $hs.tips(tipsMsg)
  3100.  
  3101.  
  3102. }
  3103.  
  3104. // 視頻畫面縮放相關事件
  3105.  
  3106. switch (pCode) {
  3107. // shift+X:視頻縮小 -0.1
  3108. case 'KeyX':
  3109. videoScale -= 0.1
  3110. if (videoScale < 0.1) videoScale = 0.1;
  3111. tipsForVideoScaling();
  3112. return TERMINATE
  3113. break
  3114. // shift+C:視頻放大 +0.1
  3115. case 'KeyC':
  3116. videoScale += 0.1
  3117. if (videoScale > 16) videoScale = 16;
  3118. tipsForVideoScaling();
  3119. return TERMINATE
  3120. break
  3121. // shift+Z:視頻恢復正常大小
  3122. case 'KeyZ':
  3123. videoScale = 1.0
  3124. playerConf.translate.x = 0;
  3125. playerConf.translate.y = 0;
  3126. tipsForVideoScaling();
  3127. return TERMINATE
  3128. break
  3129. case 'ArrowRight':
  3130. playerConf.translate.x += 10
  3131. tipsForVideoScaling();
  3132. return TERMINATE
  3133. break
  3134. case 'ArrowLeft':
  3135. playerConf.translate.x -= 10
  3136. tipsForVideoScaling();
  3137. return TERMINATE
  3138. break
  3139. case 'ArrowUp':
  3140. playerConf.translate.y -= 10
  3141. tipsForVideoScaling();
  3142. return TERMINATE
  3143. break
  3144. case 'ArrowDown':
  3145. playerConf.translate.y += 10
  3146. tipsForVideoScaling();
  3147. return TERMINATE
  3148. break
  3149.  
  3150. }
  3151.  
  3152. }
  3153. // 防止其它無關組合鍵衝突
  3154. if (!keyAsm) {
  3155. let kControl = null
  3156. let newPBR, oldPBR, nv, numKey;
  3157. switch (pCode) {
  3158. // 方向鍵右→:快進3秒
  3159. case 'ArrowRight':
  3160. if (1) {
  3161. let aCurrentTime = player.currentTime;
  3162. window.requestAnimationFrame(() => {
  3163. let diff = player.currentTime - aCurrentTime
  3164. diff = Math.round(diff * 5) / 5;
  3165. if (Math.abs(diff) < 0.8) {
  3166. $hs.tuneCurrentTime(+$hs.skipStep);
  3167. } else {
  3168. $hs.tuneCurrentTimeTips(diff, true)
  3169. }
  3170. })
  3171. //if(document.domain.indexOf('youtube.com')>=0){}else{
  3172. //$hs.tuneCurrentTime($hs.skipStep);
  3173. //return TERMINATE;
  3174. //}
  3175. }
  3176. break;
  3177. // 方向鍵左←:後退3秒
  3178. case 'ArrowLeft':
  3179.  
  3180. if (1) {
  3181. let aCurrentTime = player.currentTime;
  3182. window.requestAnimationFrame(() => {
  3183. let diff = player.currentTime - aCurrentTime
  3184. diff = Math.round(diff * 5) / 5;
  3185. if (Math.abs(diff) < 0.8) {
  3186. $hs.tuneCurrentTime(-$hs.skipStep);
  3187. } else {
  3188. $hs.tuneCurrentTimeTips(diff, true)
  3189. }
  3190. })
  3191. //if(document.domain.indexOf('youtube.com')>=0){}else{
  3192. //
  3193. //return TERMINATE;
  3194. //}
  3195. }
  3196. break;
  3197. // 方向鍵上↑:音量升高 1%
  3198. case 'ArrowUp':
  3199. if ((player.muted && player.volume === 0) && player._volume > 0) {
  3200.  
  3201. player.muted = false;
  3202. player.volume = player._volume;
  3203. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  3204. player.muted = false;
  3205. }
  3206. $hs.tuneVolume(0.01);
  3207. return TERMINATE;
  3208. break;
  3209. // 方向鍵下↓:音量降低 1%
  3210. case 'ArrowDown':
  3211.  
  3212. if ((player.muted && player.volume === 0) && player._volume > 0) {
  3213.  
  3214. player.muted = false;
  3215. player.volume = player._volume;
  3216. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  3217. player.muted = false;
  3218. }
  3219. $hs.tuneVolume(-0.01);
  3220. return TERMINATE;
  3221. break;
  3222. // 空格鍵:暫停/播放
  3223. case 'Space':
  3224. $hs.switchPlayStatus();
  3225. return TERMINATE;
  3226. break;
  3227. // 按鍵X:減速播放 -0.1
  3228. case 'KeyX':
  3229. if (player.playbackRate > 0) {
  3230. $hs.tips(false);
  3231. $hs.setPlaybackRate(player.playbackRate - 0.1);
  3232. return TERMINATE
  3233. }
  3234. break;
  3235. // 按鍵C:加速播放 +0.1
  3236. case 'KeyC':
  3237. if (player.playbackRate < 16) {
  3238. $hs.tips(false);
  3239. $hs.setPlaybackRate(player.playbackRate + 0.1);
  3240. return TERMINATE
  3241. }
  3242.  
  3243. break;
  3244. // 按鍵Z:正常速度播放
  3245. case 'KeyZ':
  3246. $hs.tips(false);
  3247. oldPBR = player.playbackRate;
  3248. if (oldPBR != 1.0) {
  3249. player._playbackRate_z = oldPBR;
  3250. newPBR = 1.0;
  3251. } else if (player._playbackRate_z != 1.0) {
  3252. newPBR = player._playbackRate_z || 1.0;
  3253. player._playbackRate_z = 1.0;
  3254. } else {
  3255. newPBR = 1.0
  3256. player._playbackRate_z = 1.0;
  3257. }
  3258. $hs.setPlaybackRate(newPBR, 1)
  3259. return TERMINATE
  3260. break;
  3261. // 按鍵F:下一幀
  3262. case 'KeyF':
  3263. if (window.location.hostname === 'www.netflix.com') return /* netflix 的F鍵是FULLSCREEN的意思 */
  3264. $hs.tips(false);
  3265. if (!player.paused) player.pause()
  3266. player.currentTime += +(1 / playerConf.fps)
  3267. $hs.tips('Jump to: Next frame')
  3268. return TERMINATE
  3269. break;
  3270. // 按鍵D:上一幀
  3271. case 'KeyD':
  3272. $hs.tips(false);
  3273. if (!player.paused) player.pause()
  3274. player.currentTime -= +(1 / playerConf.fps)
  3275. $hs.tips('Jump to: Previous frame')
  3276. return TERMINATE
  3277. break;
  3278. // 按鍵E:亮度增加%
  3279. case 'KeyE':
  3280. $hs.tips(false);
  3281. nv = playerConf.setFilter('brightness', (v) => v + 0.1);
  3282. $hs.tips('Brightness: ' + dround(nv * 100) + '%')
  3283. return TERMINATE
  3284. break;
  3285. // 按鍵W:亮度減少%
  3286. case 'KeyW':
  3287. $hs.tips(false);
  3288. nv = playerConf.setFilter('brightness', (v) => v > 0.1 ? v - 0.1 : 0);
  3289. $hs.tips('Brightness: ' + dround(nv * 100) + '%')
  3290. return TERMINATE
  3291. break;
  3292. // 按鍵T:對比度增加%
  3293. case 'KeyT':
  3294. $hs.tips(false);
  3295. nv = playerConf.setFilter('contrast', (v) => v + 0.1);
  3296. $hs.tips('Contrast: ' + dround(nv * 100) + '%')
  3297. return TERMINATE
  3298. break;
  3299. // 按鍵R:對比度減少%
  3300. case 'KeyR':
  3301. $hs.tips(false);
  3302. nv = playerConf.setFilter('contrast', (v) => v > 0.1 ? v - 0.1 : 0);
  3303. $hs.tips('Contrast: ' + dround(nv * 100) + '%')
  3304. return TERMINATE
  3305. break;
  3306. // 按鍵U:飽和度增加%
  3307. case 'KeyU':
  3308. $hs.tips(false);
  3309. nv = playerConf.setFilter('saturate', (v) => v + 0.1);
  3310. $hs.tips('Saturate: ' + dround(nv * 100) + '%')
  3311. return TERMINATE
  3312. break;
  3313. // 按鍵Y:飽和度減少%
  3314. case 'KeyY':
  3315. $hs.tips(false);
  3316. nv = playerConf.setFilter('saturate', (v) => v > 0.1 ? v - 0.1 : 0);
  3317. $hs.tips('Saturate: ' + dround(nv * 100) + '%')
  3318. return TERMINATE
  3319. break;
  3320. // 按鍵O:色相增加 1 度
  3321. case 'KeyO':
  3322. $hs.tips(false);
  3323. nv = playerConf.setFilter('hue-rotate', (v) => v + 1);
  3324. $hs.tips('Hue: ' + nv + ' deg')
  3325. return TERMINATE
  3326. break;
  3327. // 按鍵I:色相減少 1 度
  3328. case 'KeyI':
  3329. $hs.tips(false);
  3330. nv = playerConf.setFilter('hue-rotate', (v) => v - 1);
  3331. $hs.tips('Hue: ' + nv + ' deg')
  3332. return TERMINATE
  3333. break;
  3334. // 按鍵K:模糊增加 0.1 px
  3335. case 'KeyK':
  3336. $hs.tips(false);
  3337. nv = playerConf.setFilter('blur', (v) => v + 0.1);
  3338. $hs.tips('Blur: ' + nv + ' px')
  3339. return TERMINATE
  3340. break;
  3341. // 按鍵J:模糊減少 0.1 px
  3342. case 'KeyJ':
  3343. $hs.tips(false);
  3344. nv = playerConf.setFilter('blur', (v) => v > 0.1 ? v - 0.1 : 0);
  3345. $hs.tips('Blur: ' + nv + ' px')
  3346. return TERMINATE
  3347. break;
  3348. // 按鍵Q:圖像復位
  3349. case 'KeyQ':
  3350. $hs.tips(false);
  3351. playerConf.filterReset();
  3352. $hs.tips('Video Filter Reset')
  3353. return TERMINATE
  3354. break;
  3355. // 按鍵S:畫面旋轉 90 度
  3356. case 'KeyS':
  3357. $hs.tips(false);
  3358. playerConf.rotate += 90
  3359. if (playerConf.rotate % 360 === 0) playerConf.rotate = 0;
  3360. if (!playerConf.videoHeight || !playerConf.videoWidth) {
  3361. playerConf.videoWidth = playerConf.domElement.videoWidth;
  3362. playerConf.videoHeight = playerConf.domElement.videoHeight;
  3363. }
  3364. if (playerConf.videoWidth > 0 && playerConf.videoHeight > 0) {
  3365.  
  3366.  
  3367. if ((playerConf.rotate % 180) == 90) {
  3368. playerConf.mFactor = playerConf.videoHeight / playerConf.videoWidth;
  3369. } else {
  3370. playerConf.mFactor = 1.0;
  3371. }
  3372.  
  3373.  
  3374. playerConf.cssTransform();
  3375.  
  3376. $hs.tips('Rotation:' + playerConf.rotate + ' deg')
  3377.  
  3378. }
  3379.  
  3380. return TERMINATE
  3381. break;
  3382. // 按鍵迴車,進入FULLSCREEN
  3383. case 'Enter':
  3384. //t.callFullScreenBtn();
  3385. break;
  3386. case 'KeyN':
  3387. $hs.pictureInPicture(player);
  3388. return TERMINATE
  3389. break;
  3390. case 'KeyM':
  3391. //console.log('m!', player.volume,player._volume)
  3392.  
  3393. if (player.volume >= 0) {
  3394.  
  3395. if (!player.volume || player.muted) {
  3396.  
  3397. let newVol = player.volume || player._volume || 0.5;
  3398. if (player.volume !== newVol) {
  3399. player.volume = newVol;
  3400. }
  3401. player.muted = false;
  3402. $hs.tips(false);
  3403. $hs.tips('Mute: Off', undefined);
  3404.  
  3405. } else {
  3406.  
  3407. player._volume = player.volume;
  3408. player._volume_p = player.volume;
  3409. //player.volume = 0;
  3410. player.muted = true;
  3411. $hs.tips(false);
  3412. $hs.tips('Mute: On', undefined);
  3413.  
  3414. }
  3415.  
  3416. }
  3417.  
  3418. return TERMINATE
  3419. break;
  3420. default:
  3421. // 按1-4設置播放速度 49-52;97-100
  3422. numKey = +(event.key)
  3423.  
  3424. if (numKey >= 1 && numKey <= 4) {
  3425. $hs.tips(false);
  3426. $hs.setPlaybackRate(numKey, 1)
  3427. return TERMINATE
  3428. }
  3429. }
  3430.  
  3431. }
  3432. },
  3433.  
  3434. handlerPlayerLockedMouseMove: function(e) {
  3435. //console.log(4545)
  3436.  
  3437. const player = $hs.mointoringVideo;
  3438.  
  3439. if (!player) return;
  3440.  
  3441.  
  3442. $hs.mouseMoveCount += Math.sqrt(e.movementX * e.movementX + e.movementY * e.movementY);
  3443.  
  3444. delayCall('$$VideoClearMove', function() {
  3445. $hs.mouseMoveCount = $hs.mouseMoveCount * 0.4;
  3446. }, 100)
  3447.  
  3448. delayCall('$$VideoClearMove2', function() {
  3449. $hs.mouseMoveCount = $hs.mouseMoveCount * 0.1;
  3450. }, 400)
  3451.  
  3452. if ($hs.mouseMoveCount > $hs.mouseMoveMax) {
  3453. $hs.hcMouseShowWithMonitoring(player)
  3454. }
  3455.  
  3456. },
  3457.  
  3458. hcMouseHideAndStartMointoring: function(player) {
  3459.  
  3460. delayCall('$$hcMouseMove', function() {
  3461. $hs.mouseMoveCount = 0;
  3462.  
  3463. Promise.resolve($hs._hcMouseHidePre(player)).then(r => {
  3464. if(r){
  3465. $hs.mouseMoveMax = Math.sqrt(player.clientWidth * player.clientWidth + player.clientHeight * player.clientHeight) * 0.06;
  3466.  
  3467. player.ownerDocument.removeEventListener('mousemove', $hs.handlerPlayerLockedMouseMove, $mb.eh_capture_passive());
  3468. $hs.mointoringVideo = player;
  3469. player.ownerDocument.addEventListener('mousemove', $hs.handlerPlayerLockedMouseMove, $mb.eh_capture_passive())
  3470. }
  3471.  
  3472. player=null;
  3473.  
  3474. })
  3475.  
  3476. }, 1)
  3477.  
  3478.  
  3479. },
  3480.  
  3481. _hcMouseHidePre:function(player){
  3482. if (player.paused === true) {
  3483. $hs.hcShowMouseAndRemoveMointoring(player);
  3484. return;
  3485. }
  3486. if ($hs.mouseEnteredElement) {
  3487. const elm = $hs.mouseEnteredElement;
  3488. switch (getComputedStyle(elm).getPropertyValue('cursor')) {
  3489. case 'grab':
  3490. case 'pointer':
  3491. return;
  3492. }
  3493. if(elm.hasAttribute('alt'))return;
  3494. if(elm.getAttribute('aria-hidden')=='true')return;
  3495. }
  3496. Promise.resolve().then(() => {
  3497. if(!$hs.mouseDownAt) player.ownerDocument.querySelector('html').setAttribute('_h5p_hide_cursor', '');
  3498. player=null;
  3499. })
  3500. return true;
  3501. },
  3502.  
  3503. hcDelayMouseHideAndStartMointoring: function(player) {
  3504. delayCall('$$hcMouseMove', function() {
  3505. $hs.mouseMoveCount = 0;
  3506. Promise.resolve($hs._hcMouseHidePre(player)).then(r => {
  3507. if(r){
  3508. $hs.mouseMoveMax = Math.sqrt(player.clientWidth * player.clientWidth + player.clientHeight * player.clientHeight) * 0.06;
  3509. $hs.mointoringVideo = player;
  3510. player.ownerDocument.addEventListener('mousemove', $hs.handlerPlayerLockedMouseMove, $mb.eh_capture_passive())
  3511. }
  3512. player=null;
  3513. })
  3514. }, 1240)
  3515. },
  3516.  
  3517. hcMouseShowWithMonitoring: function(player) {
  3518. delayCall('$$hcMouseMove', function() {
  3519. $hs.mouseMoveCount = 0;
  3520. $hs._hcMouseHidePre(player)
  3521. }, 1240)
  3522. $hs.mouseMoveCount = 0;
  3523. player.ownerDocument.querySelector('html').removeAttribute('_h5p_hide_cursor')
  3524. },
  3525.  
  3526. hcShowMouseAndRemoveMointoring: function(player) {
  3527. delayCall('$$hcMouseMove')
  3528. $hs.mouseMoveCount = 0;
  3529. Promise.resolve().then(() => {
  3530. player.ownerDocument.removeEventListener('mousemove', $hs.handlerPlayerLockedMouseMove, $mb.eh_capture_passive())
  3531. $hs.mointoringVideo = null;
  3532. player.ownerDocument.querySelector('html').removeAttribute('_h5p_hide_cursor')
  3533. })
  3534.  
  3535. },
  3536.  
  3537.  
  3538. focusHookVDoc: null,
  3539. focusHookVId: '',
  3540.  
  3541.  
  3542. handlerElementFocus: function(event) {
  3543.  
  3544. function notAtVideo() {
  3545. if ($hs.focusHookVDoc) $hs.focusHookVDoc = null
  3546. if ($hs.focusHookVId) $hs.focusHookVId = ''
  3547. }
  3548.  
  3549. const hookVideo = $hs.focusHookVDoc && $hs.focusHookVId ? $hs.focusHookVDoc.querySelector(`VIDEO[_h5ppid=${$hs.focusHookVId}]`) : null
  3550.  
  3551. if (hookVideo && (event.target == hookVideo || event.target.contains(hookVideo))) {
  3552. } else {
  3553. notAtVideo();
  3554. }
  3555.  
  3556. },
  3557.  
  3558. handlerFullscreenChanged: function(event) {
  3559.  
  3560.  
  3561. let videoElm = null,
  3562. videosQuery = null;
  3563. if (event && event.target) {
  3564. if (event.target.nodeName == "VIDEO") videoElm = event.target;
  3565. else if (videosQuery = event.target.querySelectorAll("VIDEO")) {
  3566. if (videosQuery.length === 1) videoElm = videosQuery[0]
  3567. }
  3568. }
  3569.  
  3570. if (videoElm) {
  3571. const player = videoElm;
  3572. const vpid = player.getAttribute('_h5ppid')
  3573. event.target.setAttribute('_h5p_fsElm_', vpid)
  3574. function hookTheActionedVideo() {
  3575. $hs.focusHookVDoc = getRoot(player)
  3576. $hs.focusHookVId = vpid
  3577. }
  3578. hookTheActionedVideo();
  3579. window.setTimeout(function() {
  3580. hookTheActionedVideo()
  3581. }, 300)
  3582. window.setTimeout(()=>{
  3583. const chFull = $hs.toolCheckFullScreen(player.ownerDocument);
  3584. if (chFull) {
  3585. $hs.hcMouseHideAndStartMointoring(player);
  3586. } else {
  3587. $hs.hcShowMouseAndRemoveMointoring(player);
  3588. }
  3589. });
  3590. } else {
  3591. $hs.focusHookVDoc = null
  3592. $hs.focusHookVId = ''
  3593. }
  3594. },
  3595.  
  3596. /*
  3597. handlerOverrideMouseMove:function(evt){
  3598.  
  3599.  
  3600. if(evt&&evt.target){}else{return;}
  3601. const targetElm = evt.target;
  3602.  
  3603. if(targetElm.nodeName=="VIDEO"){
  3604. evt.preventDefault();
  3605. evt.stopPropagation();
  3606. evt.stopImmediatePropagation();
  3607. }
  3608.  
  3609. },*/
  3610.  
  3611. /* 按鍵響應方法 */
  3612. handlerRootKeyDownEvent: function(event) {
  3613.  
  3614. function notAtVideo() {
  3615. if ($hs.focusHookVDoc) $hs.focusHookVDoc = null
  3616. if ($hs.focusHookVId) $hs.focusHookVId = ''
  3617. }
  3618.  
  3619.  
  3620.  
  3621.  
  3622. if ($hs.intVideoInitCount > 0) {} else {
  3623. // return notAtVideo();
  3624. }
  3625.  
  3626.  
  3627.  
  3628. // $hs.lastKeyDown = event.timeStamp
  3629.  
  3630.  
  3631. // DOM Standard - either .key or .code
  3632. // Here we adopt .code (physical layout)
  3633.  
  3634. let pCode = event.code;
  3635. if (typeof pCode != 'string') return;
  3636. let player = $hs.player()
  3637. if (!player) return; // no video tag
  3638.  
  3639. let rootNode = getRoot(player);
  3640. let isRequiredListen = false;
  3641.  
  3642. let keyAsm = (event.shiftKey ? SHIFT : 0) | ((event.ctrlKey || event.metaKey) ? CTRL : 0) | (event.altKey ? ALT : 0);
  3643.  
  3644.  
  3645. if (document.fullscreenElement) {
  3646. isRequiredListen = true;
  3647.  
  3648.  
  3649. if (!keyAsm && pCode == 'Escape') {
  3650. window.setTimeout(() => {
  3651. if (document.fullscreenElement) {
  3652. document.exitFullscreen();
  3653. }
  3654. }, 700);
  3655. return;
  3656. }
  3657.  
  3658.  
  3659. }
  3660.  
  3661. const actionBoxRelation = $hs.getActionBoxRelationFromDOM(event.target)
  3662. let hookVideo = null;
  3663.  
  3664. if (actionBoxRelation) {
  3665. $hs.focusHookVDoc = getRoot(actionBoxRelation.player);
  3666. $hs.focusHookVId = actionBoxRelation.player.getAttribute('_h5ppid');
  3667. hookVideo = actionBoxRelation.player;
  3668. } else {
  3669. hookVideo = $hs.focusHookVDoc && $hs.focusHookVId ? $hs.focusHookVDoc.querySelector(`VIDEO[_h5ppid=${$hs.focusHookVId}]`) : null
  3670. }
  3671.  
  3672. if (hookVideo) isRequiredListen = true;
  3673.  
  3674. //console.log('root key', isRequiredListen, event.target, hookVideo)
  3675.  
  3676. if (!isRequiredListen) return;
  3677.  
  3678. //console.log('K01')
  3679.  
  3680. /* 切換插件的可用狀態 */
  3681. // Shift-`
  3682. if (keyAsm == SHIFT && pCode == 'Backquote') {
  3683. $hs.enable = !$hs.enable;
  3684. $hs.tips(false);
  3685. if ($hs.enable) {
  3686. $hs.tips('啟用h5Player插件')
  3687. } else {
  3688. $hs.tips('禁用h5Player插件')
  3689. }
  3690. // 阻止事件冒泡
  3691. event.stopPropagation()
  3692. event.preventDefault()
  3693. return false
  3694. }
  3695. if (!$hs.enable) {
  3696. consoleLog('h5Player 已禁用~')
  3697. return false
  3698. }
  3699.  
  3700. /* 非全局模式下,不聚焦則不執行快捷鍵的操作 */
  3701.  
  3702. if (!keyAsm && pCode == 'Enter') { //not NumberpadEnter
  3703.  
  3704. Promise.resolve(player).then((player) => {
  3705. $hs._actionBoxObtain(player);
  3706. }).then(() => {
  3707. $hs.callFullScreenBtn()
  3708. })
  3709. event.stopPropagation()
  3710. event.preventDefault()
  3711. return false
  3712. }
  3713.  
  3714.  
  3715.  
  3716. let res = $hs.playerTrigger(player, event)
  3717. if (res == TERMINATE) {
  3718. event.stopPropagation()
  3719. event.preventDefault()
  3720. return false
  3721. }
  3722.  
  3723. },
  3724. /* 設置播放進度 */
  3725. setPlayProgress: function(player, curTime) {
  3726. if (!player) return
  3727. if (!curTime || Number.isNaN(curTime)) return
  3728. player.currentTime = curTime
  3729. if (curTime > 3) {
  3730. $hs.tips(false);
  3731. $hs.tips(`Playback Jumps to ${$hs.toolFormatCT(curTime)}`)
  3732. if (player.paused) player.play();
  3733. }
  3734. }
  3735. }
  3736.  
  3737. function makeFilter(arr, k) {
  3738. let res = ""
  3739. for (const e of arr) {
  3740. for (const d of e) {
  3741. res += " " + (1.0 * d * k).toFixed(9)
  3742. }
  3743. }
  3744. return res.trim()
  3745. }
  3746.  
  3747. function _add_filter(rootElm) {
  3748. let rootView = null;
  3749. if (rootElm && rootElm.nodeType > 0) {
  3750. while (rootElm.parentNode && rootElm.parentNode.nodeType === 1) rootElm = rootElm.parentNode;
  3751. rootView = rootElm.querySelector('body') || rootElm;
  3752. } else {
  3753. return;
  3754. }
  3755.  
  3756. if (rootView && rootView.querySelector && !rootView.querySelector('#_h5player_section_')) {
  3757.  
  3758. let svgFilterElm = document.createElement('section')
  3759. svgFilterElm.style.position = 'fixed';
  3760. svgFilterElm.style.left = '-999px';
  3761. svgFilterElm.style.width = '1px';
  3762. svgFilterElm.style.top = '-999px';
  3763. svgFilterElm.style.height = '1px';
  3764. svgFilterElm.id = '_h5player_section_'
  3765. let svgXML = `
  3766. <svg id='_h5p_image' version="1.1" xmlns="http://www.w3.org/2000/svg">
  3767. <defs>
  3768. <filter id="_h5p_sharpen1">
  3769. <feConvolveMatrix filterRes="100 100" style="color-interpolation-filters:sRGB" order="3" kernelMatrix="` + `
  3770. -0.3 -0.3 -0.3
  3771. -0.3 3.4 -0.3
  3772. -0.3 -0.3 -0.3`.replace(/[\n\r]+/g, ' ').trim() + `" preserveAlpha="true"/>
  3773. </filter>
  3774. <filter id="_h5p_unsharpen1">
  3775. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  3776. makeFilter([
  3777. [1, 4, 6, 4, 1],
  3778. [4, 16, 24, 16, 4],
  3779. [6, 24, -476, 24, 6],
  3780. [4, 16, 24, 16, 4],
  3781. [1, 4, 6, 4, 1]
  3782. ], -1 / 256) + `" preserveAlpha="false"/>
  3783. </filter>
  3784. <filter id="_h5p_unsharpen3_05">
  3785. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="3" kernelMatrix="` +
  3786. makeFilter(
  3787. [
  3788. [0.025, 0.05, 0.025],
  3789. [0.05, -1.1, 0.05],
  3790. [0.025, 0.05, 0.025]
  3791. ], -1 / .8) + `" preserveAlpha="false"/>
  3792. </filter>
  3793. <filter id="_h5p_unsharpen3_10">
  3794. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="3" kernelMatrix="` +
  3795. makeFilter(
  3796. [
  3797. [0.05, 0.1, 0.05],
  3798. [0.1, -1.4, 0.1],
  3799. [0.05, 0.1, 0.05]
  3800. ], -1 / .8) + `" preserveAlpha="false"/>
  3801. </filter>
  3802. <filter id="_h5p_unsharpen5_05">
  3803. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  3804. makeFilter(
  3805. [
  3806. [0.025, 0.1, 0.15, 0.1, 0.025],
  3807. [0.1, 0.4, 0.6, 0.4, 0.1],
  3808. [0.15, 0.6, -18.3, 0.6, 0.15],
  3809. [0.1, 0.4, 0.6, 0.4, 0.1],
  3810. [0.025, 0.1, 0.15, 0.1, 0.025]
  3811. ], -1 / 12.8) + `" preserveAlpha="false"/>
  3812. </filter>
  3813. <filter id="_h5p_unsharpen5_10">
  3814. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  3815. makeFilter(
  3816. [
  3817. [0.05, 0.2, 0.3, 0.2, 0.05],
  3818. [0.2, 0.8, 1.2, 0.8, 0.2],
  3819. [0.3, 1.2, -23.8, 1.2, 0.3],
  3820. [0.2, 0.8, 1.2, 0.8, 0.2],
  3821. [0.05, 0.2, 0.3, 0.2, 0.05]
  3822. ], -1 / 12.8) + `" preserveAlpha="false"/>
  3823. </filter>
  3824. <filter id="_h5p_unsharpen9_05">
  3825. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="9" kernelMatrix="` +
  3826. makeFilter(
  3827. [
  3828. [0.025, 0.2, 0.7, 1.4, 1.75, 1.4, 0.7, 0.2, 0.025],
  3829. [0.2, 1.6, 5.6, 11.2, 14, 11.2, 5.6, 1.6, 0.2],
  3830. [0.7, 5.6, 19.6, 39.2, 49, 39.2, 19.6, 5.6, 0.7],
  3831. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3832. [1.75, 14, 49, 98, -4792.7, 98, 49, 14, 1.75],
  3833. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3834. [0.7, 5.6, 19.6, 39.2, 49, 39.2, 19.6, 5.6, 0.7],
  3835. [0.2, 1.6, 5.6, 11.2, 14, 11.2, 5.6, 1.6, 0.2],
  3836. [0.025, 0.2, 0.7, 1.4, 1.75, 1.4, 0.7, 0.2, 0.025]
  3837. ], -1 / 3276.8) + `" preserveAlpha="false"/>
  3838. </filter>
  3839. <filter id="_h5p_unsharpen9_10">
  3840. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="9" kernelMatrix="` +
  3841. makeFilter(
  3842. [
  3843. [0.05, 0.4, 1.4, 2.8, 3.5, 2.8, 1.4, 0.4, 0.05],
  3844. [0.4, 3.2, 11.2, 22.4, 28, 22.4, 11.2, 3.2, 0.4],
  3845. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3846. [2.8, 22.4, 78.4, 156.8, 196, 156.8, 78.4, 22.4, 2.8],
  3847. [3.5, 28, 98, 196, -6308.6, 196, 98, 28, 3.5],
  3848. [2.8, 22.4, 78.4, 156.8, 196, 156.8, 78.4, 22.4, 2.8],
  3849. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3850. [0.4, 3.2, 11.2, 22.4, 28, 22.4, 11.2, 3.2, 0.4],
  3851. [0.05, 0.4, 1.4, 2.8, 3.5, 2.8, 1.4, 0.4, 0.05]
  3852. ], -1 / 3276.8) + `" preserveAlpha="false"/>
  3853. </filter>
  3854. <filter id="_h5p_grey1">
  3855. <feColorMatrix values="0.3333 0.3333 0.3333 0 0
  3856. 0.3333 0.3333 0.3333 0 0
  3857. 0.3333 0.3333 0.3333 0 0
  3858. 0 0 0 1 0"/>
  3859. <feColorMatrix type="saturate" values="0" />
  3860. </filter>
  3861. </defs>
  3862. </svg>
  3863. `;
  3864.  
  3865. svgFilterElm.innerHTML = svgXML.replace(/[\r\n\s]+/g, ' ').trim();
  3866.  
  3867. rootView.appendChild(svgFilterElm);
  3868. }
  3869.  
  3870. }
  3871.  
  3872. /**
  3873. * 某些網頁用了attachShadow closed mode,需要open才能獲取video標籤,例如百度雲盤
  3874. * 解決參考:
  3875. * https://developers.google.com/web/fundamentals/web-components/shadowdom?hl=zh-cn#closed
  3876. * https://stackoverflow.com/questions/54954383/override-element-prototype-attachshadow-using-chrome-extension
  3877. */
  3878.  
  3879. const initForShadowRoot = async (shadowRoot) => {
  3880. try {
  3881. if (shadowRoot && shadowRoot.nodeType > 0 && shadowRoot.mode == 'open' && 'querySelectorAll' in shadowRoot) {
  3882. if (!shadowRoot.host.hasAttribute('_h5p_shadowroot_')) {
  3883. shadowRoot.host.setAttribute('_h5p_shadowroot_', '')
  3884.  
  3885. $hs.bindDocEvents(shadowRoot);
  3886. captureVideoEvents(shadowRoot);
  3887.  
  3888. shadowRoots.push(shadowRoot)
  3889. }
  3890. }
  3891. } catch (e) {
  3892. console.log('h5Player: initForShadowRoot failed')
  3893. }
  3894. }
  3895.  
  3896. function hackAttachShadow() { // attachShadow - DOM Standard
  3897.  
  3898. let _prototype_ = window && window.HTMLElement ? window.HTMLElement.prototype : null;
  3899. if (_prototype_ && typeof _prototype_.attachShadow == 'function') {
  3900.  
  3901. let _attachShadow = _prototype_.attachShadow
  3902.  
  3903. hackAttachShadow = null
  3904. _prototype_.attachShadow = function() {
  3905. let arg = [...arguments];
  3906. if (arg[0] && arg[0].mode) arg[0].mode = 'open';
  3907. let shadowRoot = _attachShadow.apply(this, arg);
  3908. initForShadowRoot(shadowRoot);
  3909. return shadowRoot
  3910. };
  3911.  
  3912. _prototype_.attachShadow.toString = () => _attachShadow.toString();
  3913.  
  3914. }
  3915.  
  3916. }
  3917.  
  3918. function hackCreateShadowRoot() { // createShadowRoot - Deprecated
  3919.  
  3920. let _prototype_ = window && window.HTMLElement ? window.HTMLElement.prototype : null;
  3921. if (_prototype_ && typeof _prototype_.createShadowRoot == 'function') {
  3922.  
  3923. let _createShadowRoot = _prototype_.createShadowRoot;
  3924.  
  3925. hackCreateShadowRoot = null
  3926. _prototype_.createShadowRoot = function() {
  3927. const shadowRoot = _createShadowRoot.apply(this, arguments);
  3928. initForShadowRoot(shadowRoot);
  3929. return shadowRoot;
  3930. };
  3931. _prototype_.createShadowRoot.toString = () => _createShadowRoot.toString();
  3932.  
  3933. }
  3934. }
  3935.  
  3936.  
  3937.  
  3938.  
  3939. /* 事件偵聽hack */
  3940. function hackEventListener() {
  3941. if (!window.Node) return;
  3942. const _prototype = window.Node.prototype;
  3943. let _addEventListener = _prototype.addEventListener;
  3944. let _removeEventListener = _prototype.removeEventListener;
  3945. if (typeof _addEventListener == 'function' && typeof _removeEventListener == 'function') {} else return;
  3946. hackEventListener = null;
  3947.  
  3948.  
  3949.  
  3950. let hackedEvtCount = 0;
  3951.  
  3952. const options_passive_capture = {
  3953. passive: true,
  3954. capture: true
  3955. }
  3956. const options_passive_bubble = {
  3957. passive: true,
  3958. capture: false
  3959. }
  3960.  
  3961. let phListeners = Promise.resolve();
  3962.  
  3963. let phActioners = Promise.resolve();
  3964. let phActionersCount = 0;
  3965.  
  3966.  
  3967.  
  3968. _prototype.addEventListener = function addEventListener() {
  3969. //console.log(3321,arguments[0])
  3970. const args = arguments
  3971. const type = args[0]
  3972. const listener = args[1]
  3973.  
  3974. if (!this || !(this instanceof Node) || typeof type != 'string' || typeof listener != 'function') {
  3975. // if (!this || !(this instanceof EventTarget) || typeof type != 'string' || typeof listener != 'function') {
  3976. return _addEventListener.apply(this, args)
  3977. //unknown bug?
  3978. }
  3979.  
  3980. let bClickAction = false;
  3981. switch (type) {
  3982. case 'load':
  3983. case 'beforeunload':
  3984. case 'DOMContentLoaded':
  3985. return _addEventListener.apply(this, args);
  3986. break;
  3987. case 'touchstart':
  3988. case 'touchmove':
  3989. case 'wheel':
  3990. case 'mousewheel':
  3991. case 'timeupdate':
  3992. if($mb.stable_isSupportPassiveEventListener()){
  3993. if (!(args[2] && typeof args[2] == 'object')) {
  3994. const fs = (listener + "");
  3995. if (fs.indexOf('{ [native code] }') < 0 && fs.indexOf('.preventDefault()') < 0) {
  3996. //make default passive if not set
  3997. const options = args[2] === true ? options_passive_capture : options_passive_bubble
  3998. args[2] = options
  3999. if (args.length < 3) args.length = 3;
  4000. }
  4001. }
  4002. if (args[2] && args[2].passive === true) {
  4003. const nType = `__nListener|${type}__`;
  4004. const nListener = listener[nType] || function() {
  4005. let _listener = listener;
  4006. let _this = this;
  4007. let _arguments = arguments;
  4008. let calling = () => {
  4009. phActioners = phActioners.then(() => {
  4010. _listener.apply(_this, _arguments);
  4011. phActionersCount--;
  4012. _listener=null;
  4013. _this=null;
  4014. _arguments=null;
  4015. calling=null;
  4016. })
  4017. }
  4018. Promise.resolve().then(() => {
  4019. if (phActionersCount === 0) {
  4020. phActionersCount++
  4021. window.requestAnimationFrame(calling)
  4022. } else {
  4023. phActionersCount++
  4024. calling();
  4025. }
  4026. })
  4027. };
  4028. listener[nType] = nListener;
  4029. args[1] = nListener;
  4030. args[2].passive = true;
  4031. args[2] = args[2];
  4032. }
  4033. }
  4034. break;
  4035. case 'mouseout':
  4036. case 'mouseover':
  4037. case 'focusin':
  4038. case 'focusout':
  4039. case 'mouseenter':
  4040. case 'mouseleave':
  4041. case 'mousemove':
  4042. /*if (this.nodeType === 1 && this.nodeName != "BODY" && this.nodeName != "HTML") {
  4043. const nType = `__nListener|${type}__`
  4044. const nListener = listener[nType] || function() {
  4045. window.requestAnimationFrame(() => listener.apply(this, arguments))
  4046. }
  4047. listener[nType] = nListener;
  4048. args[1] = nListener;
  4049. }*/
  4050. break;
  4051. case 'click':
  4052. case 'mousedown':
  4053. case 'mouseup':
  4054. bClickAction = true;
  4055. break;
  4056. default:
  4057. return _addEventListener.apply(this, args);
  4058. }
  4059.  
  4060.  
  4061. if (bClickAction) {
  4062.  
  4063.  
  4064. let res;
  4065. res = _addEventListener.apply(this, args)
  4066.  
  4067. phListeners = phListeners.then(() => {
  4068.  
  4069. let listeners = wmListeners.get(this);
  4070. if (!listeners) wmListeners.set(this, listeners = {});
  4071.  
  4072. let lh = new ListenerHandle(args[1], args[2])
  4073.  
  4074. listeners[type] = listeners[type] || new Listeners()
  4075.  
  4076. listeners[type].add(lh)
  4077. listeners[type]._count++;
  4078.  
  4079. })
  4080.  
  4081. return res
  4082.  
  4083.  
  4084. } else if (args[2] && args[2].passive) {
  4085.  
  4086. const nType = `__nListener|${type}__`
  4087. const nListener = listener[nType] || function() {
  4088. return Promise.resolve().then(() => listener.apply(this, arguments))
  4089. }
  4090.  
  4091. listener[nType] = nListener;
  4092. args[1] = nListener;
  4093.  
  4094. }
  4095.  
  4096. return _addEventListener.apply(this, args);
  4097.  
  4098.  
  4099. }
  4100. // hack removeEventListener
  4101. _prototype.removeEventListener = function removeEventListener() {
  4102.  
  4103. let args = arguments
  4104. let type = args[0]
  4105. let listener = args[1]
  4106.  
  4107.  
  4108. if (!this || !(this instanceof Node) || typeof type != 'string' || typeof listener != 'function') {
  4109. return _removeEventListener.apply(this, args)
  4110. //unknown bug?
  4111. }
  4112.  
  4113. let bClickAction = false;
  4114. switch (type) {
  4115. case 'load':
  4116. case 'beforeunload':
  4117. case 'DOMContentLoaded':
  4118. return _removeEventListener.apply(this, args);
  4119. break;
  4120. case 'mousewheel':
  4121. case 'touchstart':
  4122. case 'wheel':
  4123. case 'timeupdate':
  4124. if($mb.stable_isSupportPassiveEventListener()){
  4125. if (!(args[2] && typeof args[2] == 'object')) {
  4126. const fs = (listener + "");
  4127. if (fs.indexOf('{ [native code] }') < 0 && fs.indexOf('.preventDefault()') < 0) {
  4128. //make default passive if not set
  4129. const options = args[2] === true ? options_passive_capture : options_passive_bubble
  4130. args[2] = options
  4131. if (args.length < 3) args.length = 3;
  4132. }
  4133. }
  4134. }
  4135. break;
  4136. case 'mouseout':
  4137. case 'mouseover':
  4138. case 'focusin':
  4139. case 'focusout':
  4140. case 'mouseenter':
  4141. case 'mouseleave':
  4142. case 'mousemove':
  4143.  
  4144. break;
  4145. case 'click':
  4146. case 'mousedown':
  4147. case 'mouseup':
  4148. bClickAction = true;
  4149. break;
  4150. default:
  4151. return _removeEventListener.apply(this, args);
  4152. }
  4153.  
  4154. if (bClickAction) {
  4155.  
  4156.  
  4157. phListeners = phListeners.then(() => {
  4158. const listeners = wmListeners.get(this);
  4159. if (listeners) {
  4160. const lh_removal = new ListenerHandle(args[1], args[2])
  4161.  
  4162. listeners[type].remove(lh_removal)
  4163. }
  4164. })
  4165. return _removeEventListener.apply(this, args);
  4166.  
  4167.  
  4168. } else {
  4169. const nType = `__nListener|${type}__`
  4170. if (typeof listener[nType] == 'function') args[1] = listener[nType]
  4171. return _removeEventListener.apply(this, args);
  4172. }
  4173.  
  4174.  
  4175.  
  4176.  
  4177. }
  4178. _prototype.addEventListener.toString = () => _addEventListener.toString();
  4179. _prototype.removeEventListener.toString = () => _removeEventListener.toString();
  4180.  
  4181.  
  4182. }
  4183.  
  4184.  
  4185. function initShadowRoots(rootDoc) {
  4186. function onReady() {
  4187. var treeWalker = rootDoc.createTreeWalker(
  4188. rootDoc.documentElement,
  4189. NodeFilter.SHOW_ELEMENT, {
  4190. acceptNode: (node) => (node.shadowRoot ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP)
  4191. }
  4192. );
  4193. var nodeList = [];
  4194. while (treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
  4195. for (const node of nodeList) {
  4196. initForShadowRoot(node.shadowRoot)
  4197. }
  4198. }
  4199. if (rootDoc.readyState !== 'loading') {
  4200. onReady();
  4201. } else {
  4202. rootDoc.addEventListener('DOMContentLoaded', onReady, false);
  4203. }
  4204. }
  4205.  
  4206. function captureVideoEvents(rootDoc) {
  4207.  
  4208. var g = function(evt) {
  4209.  
  4210.  
  4211. var domElement = evt.target || this || null
  4212. if (domElement && domElement.nodeType == 1 && domElement.nodeName == "VIDEO") {
  4213. var video = domElement
  4214. if (!domElement.getAttribute('_h5ppid')) handlerVideoFound(video);
  4215. if (domElement.getAttribute('_h5ppid')) {
  4216. switch (evt.type) {
  4217. case 'loadedmetadata':
  4218. return $hs.handlerVideoLoadedMetaData.call(video, evt);
  4219. // case 'playing':
  4220. // return $hs.handlerVideoPlaying.call(video, evt);
  4221. // case 'pause':
  4222. // return $hs.handlerVideoPause.call(video, evt);
  4223. // case 'volumechange':
  4224. // return $hs.handlerVideoVolumeChange.call(video, evt);
  4225. }
  4226. }
  4227. }
  4228.  
  4229.  
  4230. }
  4231.  
  4232. // using capture phase
  4233. rootDoc.addEventListener('loadedmetadata', g, $mb.eh_capture_passive());
  4234.  
  4235. }
  4236.  
  4237. function handlerVideoFound(video) {
  4238.  
  4239. if (!video) return;
  4240. if (video.getAttribute('_h5ppid')) return;
  4241. let alabel = video.getAttribute('aria-label')
  4242. if (alabel && typeof alabel == "string" && alabel.toUpperCase() == "GIF") return;
  4243. const videoOpacity = video.style.opacity+''
  4244. if (videoOpacity.length>0 && +videoOpacity < 0.1)return; // google search
  4245.  
  4246.  
  4247. consoleLog('handlerVideoFound', video)
  4248.  
  4249. $hs.intVideoInitCount = ($hs.intVideoInitCount || 0) + 1;
  4250. let vpid = 'h5p-' + $hs.intVideoInitCount
  4251. consoleLog(' - HTML5 Video is detected -', `Number of Videos: ${$hs.intVideoInitCount}`)
  4252. if ($hs.intVideoInitCount === 1) $hs.fireGlobalInit();
  4253. video.setAttribute('_h5ppid', vpid)
  4254.  
  4255.  
  4256. playerConfs[vpid] = new PlayerConf();
  4257. playerConfs[vpid].domElement = video;
  4258. playerConfs[vpid].domActive = DOM_ACTIVE_FOUND;
  4259.  
  4260. let rootNode = getRoot(video);
  4261.  
  4262. if (rootNode.host) $hs.getPlayerBlockElement(video); // shadowing
  4263. let rootElm = domAppender(rootNode) || document.documentElement //48763
  4264. _add_filter(rootElm) // either main document or shadow node
  4265.  
  4266.  
  4267.  
  4268. video.addEventListener('playing', $hs.handlerVideoPlaying, $mb.eh_capture_passive());
  4269. video.addEventListener('pause', $hs.handlerVideoPause, $mb.eh_capture_passive());
  4270. video.addEventListener('volumechange', $hs.handlerVideoVolumeChange, $mb.eh_capture_passive());
  4271.  
  4272.  
  4273.  
  4274.  
  4275. }
  4276.  
  4277.  
  4278. hackAttachShadow()
  4279. hackCreateShadowRoot()
  4280. hackEventListener()
  4281.  
  4282.  
  4283. window.addEventListener('message', $hs.handlerWinMessage, false);
  4284. $hs.bindDocEvents(document);
  4285. captureVideoEvents(document);
  4286. initShadowRoots(document);
  4287.  
  4288.  
  4289. let windowsLD = (function() {
  4290. let ls_res = [];
  4291. try {
  4292. ls_res = [!!window.localStorage, !!window.top.localStorage];
  4293. } catch (e) {}
  4294. try {
  4295. let winp = window;
  4296. let winc = 0;
  4297. while (winp !== window.top && winp && ++winc) winp = winp.parentNode;
  4298. ls_res.push(winc);
  4299. } catch (e) {}
  4300. return ls_res;
  4301. })();
  4302.  
  4303. consoleLogF('- h5Player Plugin Loaded -', ...windowsLD)
  4304.  
  4305. function isInCrossOriginFrame() {
  4306. let result = true;
  4307. try {
  4308. if (window.top.localStorage || window.top.location.href) result = false;
  4309. } catch (e) {}
  4310. return result
  4311. }
  4312.  
  4313. if (isInCrossOriginFrame()) consoleLog('cross origin frame detected');
  4314.  
  4315.  
  4316. const $bv = {
  4317.  
  4318. boostVideoPerformanceActivate: function() {
  4319. if ($bz.boosted) return;
  4320. $bz.boosted = true;
  4321. },
  4322.  
  4323.  
  4324. boostVideoPerformanceDeactivate: function() {
  4325. if (!$bz.boosted) return;
  4326. $bz.boosted = false;
  4327. }
  4328.  
  4329. }
  4330.  
  4331.  
  4332.  
  4333. })();
  4334.  
  4335. })(window.unsafeWindow, window);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址