Greasy Fork 支持简体中文。

HTML5 Video Player Enhance

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

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

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