HTML5 Video Player Enhance

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

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

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