HTML5 Video Player Enhance

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

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

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

QingJ © 2025

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