Greasy Fork 还支持 简体中文。

HTML5 Video Player Enhance

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

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

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