HTML5 Video Player Enhance

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

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

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