Greasy Fork 还支持 简体中文。

HTML5 Video Player Enhance

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

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

  1. // ==UserScript==
  2. // @name HTML5 Video Player Enhance
  3. // @version 2.9.1a5
  4. // @description To enhance the functionality of HTML5 Video Player (h5player) supporting all websites using shortcut keys similar to PotPlayer.
  5. // @author CY Fung
  6. // @match http://*/*
  7. // @match https://*/*
  8. // @run-at document-start
  9. // @require https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js
  10. // @require https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.3.2/math.js
  11. // @namespace https://greasyfork.org/users/371179
  12. // @grant GM_getValue
  13. // @grant GM_setValue
  14. // ==/UserScript==
  15.  
  16.  
  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 $$() {
  25. 'use strict';
  26.  
  27. if (!document || !document.documentElement) return window.requestAnimationFrame($$);
  28.  
  29. let _debug_h5p_logging_ = false;
  30.  
  31. try {
  32. _debug_h5p_logging_ = +window.localStorage.getItem('_h5_player_sLogging_') > 0
  33. } catch (e) {}
  34.  
  35.  
  36.  
  37. const SHIFT = 1;
  38. const CTRL = 2;
  39. const ALT = 4;
  40. const TERMINATE = 0x842;
  41. const _sVersion_ = 1817;
  42. const str_postMsgData = '__postMsgData__'
  43. const DOM_ACTIVE_FOUND = 1;
  44. const DOM_ACTIVE_SRC_LOADED = 2;
  45. const DOM_ACTIVE_ONCE_PLAYED = 4;
  46. const DOM_ACTIVE_MOUSE_CLICK = 8;
  47. const DOM_ACTIVE_MOUSE_IN = 16;
  48. const DOM_ACTIVE_DELAYED_PAUSED = 32;
  49. const DOM_ACTIVE_INVALID_PARENT = 2048;
  50.  
  51.  
  52. let _endlessloop = null;
  53. const isIframe = (window.top !== window.self && window.top && window.self);
  54. const shadowRoots = [];
  55.  
  56. const getRoot = (elm) => elm.getRootNode instanceof Function ? elm.getRootNode() : (elm.ownerDocument || null);
  57.  
  58. const isShadowRoot = (elm) => (elm && ('host' in elm)) ? elm.nodeType == 11 && !!elm.host && elm.host.nodeType == 1 : null; //instanceof ShadowRoot
  59.  
  60. const timeupdateStore = []
  61. document.__h5p_boost_timeupdate_count = 0;
  62.  
  63. const playerConfs = {}
  64.  
  65. const $ws = {
  66. requestAnimationFrame,
  67. cancelAnimationFrame,
  68. MutationObserver
  69. }
  70. //throw Error if your browser is too outdated. (eg ES6 script, no such window object)
  71.  
  72. Element.prototype.__matches__ = (Element.prototype.matches || Element.prototype.matchesSelector ||
  73. Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector ||
  74. Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector ||
  75. Element.prototype.matches()); // throw Error if not supported
  76.  
  77.  
  78. Element.prototype.__requestPointerLock__ = (Element.prototype.requestPointerLock ||
  79. Element.prototype.mozRequestPointerLock || Element.prototype.webkitRequestPointerLock || function() {});
  80.  
  81. // Ask the browser to release the pointer
  82. Document.prototype.__exitPointerLock__ = (Document.prototype.exitPointerLock ||
  83. Document.prototype.mozExitPointerLock || Document.prototype.webkitExitPointerLock || function() {});
  84.  
  85.  
  86. function isSupportAdvancedEventListener() {
  87. if ('_b1750' in $$) return $$._b1750
  88. let prop = 0;
  89. document.createAttribute('z').addEventListener('', null, {
  90. get passive() {
  91. prop++;
  92. },
  93. get once() {
  94. prop++;
  95. }
  96. });
  97. return ($$._b1750 = prop == 2);
  98. }
  99.  
  100. // built-in hash - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  101. async function digestMessage(message) {
  102. return window.sha256(message)
  103. }
  104.  
  105. const dround = (x) => ~~(x + .5);
  106.  
  107. const jsonStringify_replacer = function(key, val) {
  108. if (val && (val instanceof Element || val instanceof Document)) return val.toString();
  109. return val; // return as is
  110. };
  111.  
  112. const jsonParse = function() {
  113. try {
  114. return JSON.parse.apply(this, arguments)
  115. } catch (e) {}
  116. return null;
  117. }
  118. const jsonStringify = function(obj) {
  119. try {
  120. return JSON.stringify.call(this, obj, jsonStringify_replacer)
  121. } catch (e) {}
  122. return null;
  123. }
  124.  
  125. function _postMsg() {
  126. //async is needed. or error handling for postMessage
  127. const [win, tag, ...data] = arguments;
  128. if (typeof tag == 'string') {
  129. let postMsgObj = {
  130. tag,
  131. passing: true,
  132. winOrder: _postMsg.a
  133. }
  134. try {
  135. let k = 'msg-' + (+new Date)
  136. win.document[str_postMsgData] = win.document[str_postMsgData] || {}
  137. win.document[str_postMsgData][k] = data; //direct
  138. postMsgObj.str = k;
  139. postMsgObj.stype = 1;
  140. } catch (e) {}
  141. if (!postMsgObj.stype) {
  142. postMsgObj.str = jsonStringify({
  143. d: data
  144. })
  145. if (postMsgObj.str && postMsgObj.str.length) postMsgObj.stype = 2;
  146. }
  147. if (!postMsgObj.stype) {
  148. postMsgObj.str = "" + data;
  149. postMsgObj.stype = 0;
  150. }
  151. win.postMessage(postMsgObj, '*');
  152. }
  153.  
  154. }
  155.  
  156. function postMsg() {
  157. let win = window;
  158. let a = 0;
  159. while (win = win.parent) {
  160. _postMsg.a = ++a;
  161. _postMsg(win, ...arguments)
  162. if (win == top) break;
  163. }
  164. }
  165.  
  166.  
  167. function crossBrowserTransition(type) {
  168. if (crossBrowserTransition['_result_' + type]) return crossBrowserTransition['_result_' + type]
  169. let el = document.createElement("fakeelement");
  170.  
  171. const capital = (x) => x[0].toUpperCase() + x.substr(1);
  172. const capitalType = capital(type);
  173.  
  174. const transitions = {
  175. [type]: `${type}end`,
  176. [`O${capitalType}`]: `o${capitalType}End`,
  177. [`Moz${capitalType}`]: `${type}end`,
  178. [`Webkit${capitalType}`]: `webkit${capitalType}End`,
  179. [`MS${capitalType}`]: `MS${capitalType}End`
  180. }
  181.  
  182. for (let styleProp in transitions) {
  183. if (el.style[styleProp] !== undefined) {
  184. return (crossBrowserTransition['_result_' + type] = transitions[styleProp]);
  185. }
  186. }
  187. }
  188.  
  189. function isInOperation(elm) {
  190. let elmInFocus = elm || document.activeElement;
  191. if (!elmInFocus) return false;
  192. let res1 = elmInFocus.__matches__(
  193. 'a[href],link[href],button,input:not([type="hidden"]),select,textarea,iframe,frame,menuitem,[draggable],[contenteditable]'
  194. );
  195. return res1;
  196. }
  197.  
  198. const fn_toString = (f, n = 50) => {
  199. let s = (f + "");
  200. if (s.length > 2 * n + 5) {
  201. s = s.substr(0, n) + ' ... ' + s.substr(-n);
  202. }
  203. return s
  204. };
  205.  
  206. function consoleLog() {
  207. if (!_debug_h5p_logging_) return;
  208. if (isIframe) postMsg('consoleLog', ...arguments);
  209. else console.log.apply(console, arguments);
  210. }
  211.  
  212. function consoleLogF() {
  213. if (isIframe) postMsg('consoleLog', ...arguments);
  214. else console.log.apply(console, arguments);
  215. }
  216.  
  217. class ResizeODM {
  218. static __init__() {
  219. this.__resizerCount__ = 0;
  220. this.__resizeListeners__ = {};
  221. }
  222. constructor() {
  223. let rm = this;
  224. ResizeODM.__resizerCount__++;
  225. let rpid = "rpid-" + ResizeODM.__resizerCount__;
  226. ResizeODM.__resizeListeners__[rpid] = [];
  227.  
  228. rm._resizer_listeners = ResizeODM.__resizeListeners__[rpid];
  229.  
  230. let odm = document.createElement('object');
  231. odm.setAttribute('_resizer_odm_', rpid);
  232. odm.setAttribute('style', 'display: block; position: absolute; top: -300vh; left: -300vw; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
  233. odm.onload = ResizeODM.objectLoad;
  234. odm.type = 'text/html';
  235. odm.data = 'about:blank';
  236. rm.odm = odm;
  237. rm.rpid = rpid;
  238. rm.odm.__rm__ = rm;
  239. }
  240.  
  241. static find(rsElm) {
  242. if (!rsElm) return null;
  243. let odm = [...rsElm.querySelectorAll('object[_resizer_odm_]')].filter(elm => elm.parentNode == rsElm)[0];
  244. if (!odm) return null;
  245.  
  246. return odm.__rm__ || null;
  247.  
  248. }
  249.  
  250. static resizeListener(e) {
  251. let odv = e.target || e.srcElement;
  252. let rm = odv._resizer_rm;
  253. if (rm.__resizeRAF__) $ws.cancelAnimationFrame(rm.__resizeRAF__);
  254. rm.__resizeRAF__ = $ws.requestAnimationFrame(function() {
  255. rm.__resizeRAF__ = 0;
  256. for (const fn of rm._resizer_listeners) fn.call(rm, e);
  257. });
  258. }
  259.  
  260. static objectLoad(e) {
  261. let odm = this;
  262. let rm = odm.__rm__;
  263. let odv = odm.contentDocument.defaultView
  264. odv._resizer_rm = rm;
  265. rm.odv = odv;
  266. odv.onresize = ResizeODM.resizeListener;
  267. }
  268.  
  269. resizeElement() {
  270. return this.odm.parentNode;
  271. }
  272.  
  273. // ResizeODM.relativeParent(rsElm);
  274.  
  275. relativeParent(rsElm, existingnode = null) {
  276. let odm = this.odm;
  277. rsElm = rsElm || odm.parentNode;
  278. let rpid = this.rpid;
  279. //if (getComputedStyle(rsElm).position == 'static') rsElm.style.position = 'relative';
  280. rsElm.insertBefore(odm, existingnode);
  281. }
  282.  
  283. listen(fn) {
  284. this._resizer_listeners.push(fn);
  285. }
  286.  
  287. unlisten(fn) {
  288. this._resizer_listeners.splice(this._resizer_listeners.indexOf(fn), 1);
  289. }
  290.  
  291. remove() {
  292. this._resizer_listeners.length = 0;
  293. this.odv.onresize = null;
  294. this.odm.onload = null;
  295. }
  296.  
  297. }
  298.  
  299. class AFLooperArray extends Array {
  300. constructor() {
  301. super();
  302. this.activeLoopsCount = 0;
  303. this.cid = 0;
  304. this.loopingFrame = this.loopingFrame.bind(this);
  305. }
  306.  
  307. loopingFrame() {
  308. if (!this.cid) return; //cancelled
  309. for (const opt of this) {
  310. if (opt.isFunctionLooping) opt.fn(opt);
  311. }
  312. this.cid = $ws.requestAnimationFrame(this.loopingFrame);
  313. }
  314.  
  315. get isArrayLooping() {
  316. return this.cid > 0;
  317. }
  318.  
  319. loopStart() {
  320. this.cid = $ws.requestAnimationFrame(this.loopingFrame);
  321. }
  322. loopStop() {
  323. if (this.cid) $ws.cancelAnimationFrame(this.cid);
  324. this.cid = 0;
  325. }
  326. appendLoop(fn) {
  327. if (typeof fn != 'function' || !this) return;
  328. const opt = new AFLooperFunc(fn, this);
  329. super.push(opt);
  330. return opt;
  331. }
  332. }
  333.  
  334. class AFLooperFunc {
  335. constructor(fn, bind) {
  336. this._looping = false;
  337. this.fn = fn;
  338. this.bind = bind;
  339. }
  340. get isFunctionLooping() {
  341. return this._looping;
  342. }
  343. loopingStart() {
  344. if (this._looping === false) {
  345. this._looping = true;
  346. if (++this.bind.activeLoopsCount == 1) this.bind.loopStart();
  347. }
  348. }
  349. loopingStop() {
  350. if (this._looping === true) {
  351. this._looping = false;
  352. if (--this.bind.activeLoopsCount == 0) this.bind.loopStop();
  353. }
  354. }
  355. }
  356.  
  357. function decimalEqual(a, b) {
  358. return Math.round(a * 100000000) == Math.round(b * 100000000)
  359. }
  360.  
  361. function nonZeroNum(a) {
  362. return a > 0 || a < 0;
  363. }
  364.  
  365. class PlayerConf {
  366.  
  367. get scaleFactor() {
  368. return this.mFactor * this.vFactor;
  369. }
  370.  
  371. cssTransform() {
  372.  
  373. const playerConf = this;
  374. const player = playerConf.domElement;
  375. if (!player) return;
  376. const videoScale = playerConf.scaleFactor;
  377. let {x,y}=playerConf.translate;
  378.  
  379. let [_x,_y]=((playerConf.rotate % 180) == 90)?[y,x]:[x,y];
  380.  
  381. if((playerConf.rotate % 360) == 270)_x = -_x;
  382. if((playerConf.rotate % 360) == 90)_y = -_y;
  383.  
  384. var s = [
  385. playerConf.rotate > 0 ? 'rotate(' + playerConf.rotate + 'deg)' : '',
  386. !decimalEqual(videoScale, 1.0) ? 'scale(' + videoScale + ')' : '',
  387. (nonZeroNum(_x) || nonZeroNum(_y)) ? `translate(${_x}px, ${_y}px)` : '',
  388. ];
  389.  
  390. console.log(playerConf,s)
  391.  
  392. player.style.transform = s.join(' ').trim()
  393.  
  394. }
  395.  
  396. constructor() {
  397.  
  398. this.translate = {
  399. x: 0,
  400. y: 0
  401. };
  402. this.rotate = 0;
  403. this.mFactor = 1.0;
  404. this.vFactor = 1.0;
  405. this.fps = 30;
  406. this.filter_key = {};
  407. this.filter_view_units = {
  408. 'hue-rotate': 'deg',
  409. 'blur': 'px'
  410. };
  411. this.filterReset();
  412.  
  413. }
  414.  
  415. setFilter(prop, f) {
  416.  
  417. let oldValue = this.filter_key[prop];
  418. if (typeof oldValue != 'number') return;
  419. let newValue = f(oldValue)
  420. if (oldValue != newValue) {
  421.  
  422. newValue = +newValue.toFixed(6); //javascript bug
  423.  
  424. }
  425.  
  426. this.filter_key[prop] = newValue
  427. this.filterSetup();
  428.  
  429. return newValue;
  430.  
  431.  
  432.  
  433. }
  434.  
  435. filterSetup(options) {
  436.  
  437. let ums = GM_getValue("unsharpen_mask")
  438. if (!ums) ums = ""
  439.  
  440. let view = ''
  441. let playerElm = $hs.player();
  442. if (!playerElm) return;
  443. for (let view_key in this.filter_key) {
  444. let filter_value = +((+this.filter_key[view_key] || 0).toFixed(3))
  445. let view_unit = this.filter_view_units[view_key] || ''
  446. view += `${view_key}(${filter_value}${view_unit}) `
  447. this.filter_key[view_key] = Number(+this.filter_key[view_key] || 0)
  448. }
  449. if (ums) view += `url("#_h5p_${ums}")`;
  450. if (options && options.grey) view += ' url("#grey1")';
  451. playerElm.style.filter = view; //performance in firefox is bad
  452. }
  453.  
  454. filterReset() {
  455. this.filter_key['brightness'] = 1.0
  456. this.filter_key['contrast'] = 1.0
  457. this.filter_key['saturate'] = 1.0
  458. this.filter_key['hue-rotate'] = 0.0
  459. this.filter_key['blur'] = 0.0
  460. this.filterSetup()
  461. }
  462.  
  463. }
  464.  
  465. class VideoListener {
  466.  
  467. constructor(shadowRoot) {
  468.  
  469. this.usable = false;
  470. this.observer = null;
  471. this.cid_delayed = 0;
  472.  
  473. this.rootElement = shadowRoot || window.document;
  474. if (this.rootElement && !this.rootElement.__videoListenerEnabled__) {
  475. this.rootElement.__videoListenerEnabled__ = true;
  476. this.usable = true;
  477. }
  478. }
  479.  
  480. listen(fn) {
  481. if (!this.usable) return;
  482. this.checkRoot = async (_, shadowRoot) => {
  483. shadowRoot = shadowRoot || this.rootElement;
  484. const videos = shadowRoot.querySelectorAll('VIDEO'); //shadowRoot don't have getElementsByTagName
  485. for (const video of videos) {
  486. if (!video._onceMutationReady) {
  487. video._onceMutationReady = true;
  488. fn(video); // single function
  489. }
  490. }
  491. };
  492. this.init_observer();
  493. this.checkOnce();
  494. this.checkRoot();
  495. }
  496. init_observer() {
  497. if (this.observer) return;
  498. this.mutationObserverCallback = this.mutationObserverCallback.bind(this);
  499. this.observer = new $ws.MutationObserver(this.mutationObserverCallback);
  500. this.observer.observe(this.rootElement, {
  501. childList: true,
  502. subtree: true
  503. })
  504. }
  505. mutationObserverCallback(mutationsList, observer) {
  506. for (const mutation of mutationsList) {
  507. for (const addedNode of mutation.addedNodes) {
  508. if (addedNode.nodeName == 'VIDEO' || addedNode.childElementCount > 0) {
  509. if (this.cid_delayed) $ws.cancelAnimationFrame(this.cid_delayed);
  510. this.cid_delayed = $ws.requestAnimationFrame(this.checkRoot);
  511. return;
  512. }
  513. }
  514. }
  515. }
  516.  
  517. async checkOnce() {
  518. let treeWalker = document.createTreeWalker(
  519. document.documentElement,
  520. NodeFilter.SHOW_ELEMENT, {
  521. acceptNode: (node) => (node.shadowRoot ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP)
  522. }
  523. );
  524. let nodeList = [];
  525. while (treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
  526. for (const node of nodeList) this.checkRoot(null, node.shadowRoot);
  527. }
  528.  
  529.  
  530. }
  531.  
  532. const Store = {
  533. prefix: '_h5_player',
  534. save: function(k, v) {
  535. if (!Store.available()) return false;
  536. if (typeof v != 'string') return false;
  537. Store.LS.setItem(Store.prefix + k, v)
  538. let sk = fn_toString(k + "", 30);
  539. let sv = fn_toString(v + "", 30);
  540. consoleLog(`localStorage Saved "${sk}" = "${sv}"`)
  541. return true;
  542.  
  543. },
  544. read: function(k) {
  545. if (!Store.available()) return false;
  546. let v = Store.LS.getItem(Store.prefix + k)
  547. let sk = fn_toString(k + "", 30);
  548. let sv = fn_toString(v + "", 30);
  549. consoleLog(`localStorage Read "${sk}" = "${sv}"`);
  550. return v;
  551.  
  552. },
  553. remove: function(k) {
  554.  
  555. if (!Store.available()) return false;
  556. Store.LS.removeItem(Store.prefix + k)
  557. let sk = fn_toString(k + "", 30);
  558. consoleLog(`localStorage Removed "${sk}"`)
  559. return true;
  560. },
  561. clearInvalid: function(sVersion) {
  562. if (!Store.available()) return false;
  563.  
  564. //let sVersion=1814;
  565. if (+Store.read('_sVersion_') < sVersion) {
  566. Store._keys()
  567. .filter(s => s.indexOf(Store.prefix) === 0)
  568. .forEach(key => window.localStorage.removeItem(key))
  569. Store.save('_sVersion_', sVersion + '')
  570. return 2;
  571. }
  572. return 1;
  573.  
  574. },
  575. available: function() {
  576. if (Store.LS) return true;
  577. if (!window) return false;
  578. const localStorage = window.localStorage;
  579. if (!localStorage) return false;
  580. if (typeof localStorage != 'object') return false;
  581. if (!('getItem' in localStorage)) return false;
  582. if (!('setItem' in localStorage)) return false;
  583. Store.LS = localStorage;
  584. return true;
  585.  
  586. },
  587. _keys: function() {
  588. return Object.keys(localStorage);
  589. },
  590. _setItem: function(key, value) {
  591. return localStorage.setItem(key, value)
  592. },
  593. _getItem: function(key) {
  594. return localStorage.getItem(key)
  595. },
  596. _removeItem: function(key) {
  597. return localStorage.removeItem(key)
  598. }
  599.  
  600. }
  601.  
  602. const domTool = {
  603. nopx: (x) => +x.replace('px', ''),
  604. cssWH: function(m, r) {
  605. if (!r) r = getComputedStyle(m, null);
  606. let c = (x) => +x.replace('px', '');
  607. return {
  608. w: m.offsetWidth || c(r.width),
  609. h: m.offsetHeight || c(r.height)
  610. }
  611. },
  612. _isActionBox_1: function(vEl, pEl) {
  613.  
  614. let vElCSS = domTool.cssWH(vEl);
  615. let vElCSSw = vElCSS.w;
  616. let vElCSSh = vElCSS.h;
  617.  
  618. let vElx = vEl;
  619. let res = [];
  620. let mLevel = 0;
  621. if (vEl && pEl && vEl != pEl && pEl.contains(vEl)) {
  622. while (vElx && vElx != pEl) {
  623. vElx = vElx.parentNode;
  624. let vElx_css = null;
  625. if (isShadowRoot(vElx)) {} else {
  626. vElx_css = getComputedStyle(vElx, null);
  627. let vElx_wp = domTool.nopx(vElx_css.paddingLeft) + domTool.nopx(vElx_css.paddingRight)
  628. vElCSSw += vElx_wp
  629. let vElx_hp = domTool.nopx(vElx_css.paddingTop) + domTool.nopx(vElx_css.paddingBottom)
  630. vElCSSh += vElx_hp
  631. }
  632. res.push({
  633. level: ++mLevel,
  634. padW: vElCSSw,
  635. padH: vElCSSh,
  636. elm: vElx,
  637. css: vElx_css
  638. })
  639.  
  640. }
  641. }
  642.  
  643. // in the array, each item is the parent of video player
  644. res.vEl_cssWH = vElCSS
  645.  
  646. return res;
  647.  
  648. },
  649. _isActionBox: function(vEl, walkRes, pEl_idx) {
  650.  
  651. function absDiff(w1, w2, h1, h2) {
  652. let w = (w1 - w2),
  653. h = h1 - h2;
  654. return [(w > 0 ? w : -w), (h > 0 ? h : -h)]
  655. }
  656.  
  657. function midPoint(rect) {
  658. return {
  659. x: (rect.left + rect.right) / 2,
  660. y: (rect.top + rect.bottom) / 2
  661. }
  662. }
  663.  
  664. let parentCount = walkRes.length;
  665. if (pEl_idx >= 0 && pEl_idx < parentCount) {} else {
  666. return;
  667. }
  668. let pElr = walkRes[pEl_idx]
  669. if (!pElr.css) {
  670. //shadowRoot
  671. return true;
  672. }
  673.  
  674. let pEl = pElr.elm;
  675.  
  676. //prevent activeElement==body
  677. let pElCSS = domTool.cssWH(pEl, pElr.css);
  678.  
  679. //check prediction of parent dimension
  680. let d1v = absDiff(pElCSS.w, pElr.padW, pElCSS.h, pElr.padH)
  681.  
  682. let d1x = d1v[0] < 10
  683. let d1y = d1v[1] < 10;
  684.  
  685. if (d1x && d1y) return true; //both edge along the container - fit size
  686. if (!d1x && !d1y) return false; //no edge along the container - body contain the video element, fixed width&height
  687.  
  688. //case: youtube video fullscreen
  689.  
  690. //check centre point
  691.  
  692. let pEl_rect = pEl.getBoundingClientRect()
  693. let vEl_rect = vEl.getBoundingClientRect()
  694.  
  695. let pEl_center = midPoint(pEl_rect)
  696. let vEl_center = midPoint(vEl_rect)
  697.  
  698. let d2v = absDiff(pEl_center.x, vEl_center.x, pEl_center.y, vEl_center.y);
  699.  
  700. let d2x = d2v[0] < 10;
  701. let d2y = d2v[1] < 10;
  702.  
  703. return (d2x && d2y);
  704.  
  705. },
  706. getRect: function(element) {
  707. let rect = element.getBoundingClientRect();
  708. let scroll = domTool.getScroll();
  709. return {
  710. pageX: rect.left + scroll.left,
  711. pageY: rect.top + scroll.top,
  712. screenX: rect.left,
  713. screenY: rect.top
  714. };
  715. },
  716. getScroll: function() {
  717. return {
  718. left: document.documentElement.scrollLeft || document.body.scrollLeft,
  719. top: document.documentElement.scrollTop || document.body.scrollTop
  720. };
  721. },
  722. getClient: function() {
  723. return {
  724. width: document.compatMode == 'CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth,
  725. height: document.compatMode == 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight
  726. };
  727. },
  728. addStyle: //GM_addStyle,
  729. function(css, head) {
  730. if (!head) {
  731. let _doc = document.documentElement;
  732. head = _doc.querySelector('head') || _doc.querySelector('html') || _doc;
  733. }
  734. let doc = head.ownerDocument;
  735. let style = doc.createElement('style');
  736. style.type = 'text/css';
  737. let node = doc.createTextNode(css);
  738. style.appendChild(node);
  739. head.appendChild(style);
  740. //console.log(document.head,style,'add style')
  741. return style;
  742. },
  743. eachParentNode: function(dom, fn) {
  744. let parent = dom.parentNode
  745. while (parent) {
  746. let isEnd = fn(parent, dom)
  747. parent = parent.parentNode
  748. if (isEnd) {
  749. break
  750. }
  751. }
  752. },
  753.  
  754. hideDom: function hideDom(selector) {
  755. let dom = document.querySelector(selector)
  756. if (dom) {
  757. $ws.requestAnimationFrame(function() {
  758. dom.style.opacity = 0;
  759. dom.style.transform = 'translate(-9999px)';
  760. dom = null;
  761. })
  762. }
  763. }
  764. };
  765.  
  766. const handle = {
  767.  
  768. afTipsDOM: async function(opts) {
  769.  
  770. let tipsDoms = $hs._cached_tipsDoms;
  771.  
  772. if (!tipsDoms || !tipsDoms.length) return;
  773. for (const tipsDom of tipsDoms) {
  774.  
  775. let wPlayer = tipsDom._playerBlockElm;
  776. if (wPlayer == null) {
  777. $hs.cacheTipsDoms();
  778. return;
  779. }
  780. let layoutBox = wPlayer.parentNode;
  781. if (layoutBox == null) { //i.e. removed
  782. playerConfs[tipsDom._playerVPID].domActive |= DOM_ACTIVE_INVALID_PARENT;
  783. $hs.cacheTipsDoms();
  784. return;
  785. }
  786. let p = [layoutBox.offsetWidth, layoutBox.offsetHeight, wPlayer.offsetWidth, wPlayer.offsetHeight];
  787.  
  788. if (tipsDom._cached_dimensions) {
  789. let changed = false;
  790. for (let i in p) {
  791. if (tipsDom._cached_dimensions[i] != p[i]) {
  792. changed = true;
  793. break;
  794. }
  795. }
  796. if (!changed) return;
  797. tipsDom._env_changed = (tipsDom._env_changed || 0) + 1;
  798. consoleLog('tipsDom Env changed', tipsDom.id)
  799. }
  800.  
  801. tipsDom._cached_dimensions = p;
  802.  
  803. if (!tipsDom.id) return;
  804. let player = layoutBox.querySelector(`[_h5player_tips="${tipsDom.id}"]`)
  805. if (!player) return;
  806.  
  807. $hs.fixNonBoxingVideoTipsPosition(tipsDom, player)
  808.  
  809. }
  810.  
  811. },
  812.  
  813. afBoostTimeUpdate: async function(opts) {
  814.  
  815.  
  816. let tupConf = timeupdateStore.currentPlayingConf
  817. if (!tupConf) return;
  818. let video = tupConf.videoElement;
  819. let time = video.currentTime;
  820. let fakeTimeUpdateEvent = tupConf.fakeTimeUpdateEvent[0];
  821. if (time !== tupConf.lastTime && fakeTimeUpdateEvent) {
  822. tupConf.lastTime = time;
  823. for (const fn of tupConf.eventHandlersRunner) {
  824. try {
  825. fn.apply(video, fakeTimeUpdateEvent)
  826. } catch (e) {}
  827. }
  828. //document.__h5p_boost_timeupdate_vtid=timeupdateStore.currentPlayingConf
  829. document.__h5p_boost_timeupdate_count = (document.__h5p_boost_timeupdate_count + 1) % 100000000;
  830. }
  831. },
  832. afPlaybackRecording: async function(opts) {
  833.  
  834. let qTime = +new Date;
  835. if (qTime >= opts.pTime) {
  836. opts.pTime = qTime + opts.timeDelta; //prediction of next Interval
  837. opts.savePlaybackProgress()
  838. }
  839.  
  840. },
  841. savePlaybackProgress: function() {
  842.  
  843. //this refer to endless's opts
  844. let player = this.player;
  845.  
  846. let _uid = this.player_uid; //_h5p_uid_encrypted
  847. if (!_uid) return;
  848.  
  849. let shallSave = true;
  850. let currentTimeToSave = ~~player.currentTime;
  851.  
  852. if (this._lastSave == currentTimeToSave) shallSave = false;
  853.  
  854. if (shallSave) {
  855.  
  856. this._lastSave = currentTimeToSave
  857.  
  858. //console.log('aasas',this.player_uid, shallSave, '_play_progress_'+_uid, currentTimeToSave)
  859.  
  860. Store.save('_play_progress_' + _uid, jsonStringify({
  861. 't': currentTimeToSave
  862. }))
  863.  
  864. }
  865.  
  866. },
  867. pr_updateUID: function() {
  868.  
  869. //this refer to endless's opts
  870.  
  871. let player = this.player;
  872.  
  873. let _uid = player.getAttribute('_h5p_uid_encrypted') || ''
  874. if (!_uid) return false;
  875. this.player_uid = _uid;
  876.  
  877. return true;
  878.  
  879. },
  880.  
  881. };
  882.  
  883. class Momentary extends Map {
  884. act(uniqueId, fn_start, fn_end, delay) {
  885. if (!uniqueId) return;
  886. uniqueId = uniqueId + "";
  887. const last_cid = this.get(uniqueId);
  888. if (last_cid > 0) clearTimeout(last_cid);
  889. fn_start();
  890. const new_cid = setTimeout(fn_end, delay)
  891. this.set(uniqueId, new_cid)
  892. }
  893. }
  894.  
  895. const momentary = new Momentary();
  896.  
  897. const $hs = {
  898.  
  899. /* 提示文本的字號 */
  900. fontSize: 16,
  901. enable: true,
  902. playerInstance: null,
  903. playbackRate: 1,
  904. /* 快進快退步長 */
  905. skipStep: 5,
  906. trigger_actionBoxes: [],
  907.  
  908. /* 獲取當前播放器的實例 */
  909. player: function() {
  910. let res = $hs.playerInstance || null;
  911. if (res && res.parentNode == null) {
  912. $hs.playerInstance = null;
  913. res = null;
  914. }
  915.  
  916. if (res == null) {
  917. for (let k in playerConfs) {
  918. let playerConf = playerConfs[k];
  919. if (playerConf && playerConf.domElement && playerConf.domElement.parentNode) return playerConf.domElement;
  920. }
  921. }
  922. return res;
  923. },
  924.  
  925. pictureInPicture: function(videoElm) {
  926. if (document.pictureInPictureElement) {
  927. document.exitPictureInPicture();
  928. } else if ('requestPictureInPicture' in videoElm) {
  929. videoElm.requestPictureInPicture()
  930. } else {
  931. $hs.tips('PIP is not supported.');
  932. }
  933. },
  934.  
  935. getPlayerConf: function(video) {
  936.  
  937. if (!video) return null;
  938. let vpid = video.getAttribute('_h5ppid') || null;
  939. if (!vpid) return null;
  940. return playerConfs[vpid] || null;
  941.  
  942. },
  943.  
  944. handlerVideoPlaying: function(evt) {
  945. const videoElm = evt.target || this || null;
  946. const playerConf = $hs.getPlayerConf(videoElm)
  947.  
  948. $hs._actionBoxSet(videoElm);
  949. if (playerConf) {
  950. if (playerConf.timeout_pause > 0) playerConf.timeout_pause = clearTimeout(playerConf.timeout_pause);
  951. playerConf.lastPauseAt = 0
  952. playerConf.domActive |= DOM_ACTIVE_ONCE_PLAYED;
  953. playerConf.domActive &= ~DOM_ACTIVE_DELAYED_PAUSED;
  954. }
  955.  
  956. $hs.swtichPlayerInstance();
  957.  
  958. $hs.switchCurrentPlayingConf();
  959.  
  960.  
  961. $hs.onVideoTriggering();
  962.  
  963. if (!$hs.enable) return $hs.tips(false);
  964.  
  965. if (videoElm._isThisPausedBefore_) consoleLog('resumed')
  966. let _pausedbefore_ = videoElm._isThisPausedBefore_
  967.  
  968. if (videoElm.playpause_cid) {
  969. clearTimeout(videoElm.playpause_cid);
  970. videoElm.playpause_cid = 0;
  971. }
  972. let _last_paused = videoElm._last_paused
  973. videoElm._last_paused = videoElm.paused
  974. if (_last_paused === !videoElm.paused) {
  975. videoElm.playpause_cid = setTimeout(() => {
  976. if (videoElm.paused === !_last_paused && !videoElm.paused && _pausedbefore_) {
  977. $hs.tips('Playback resumed', undefined, 2500)
  978. }
  979. }, 90)
  980. }
  981.  
  982. /* 播放的時候進行相關同步操作 */
  983.  
  984. if (!videoElm._record_continuous) {
  985.  
  986. /* 同步之前設定的播放速度 */
  987. $hs.setPlaybackRate()
  988.  
  989. if (!_endlessloop) _endlessloop = new AFLooperArray();
  990.  
  991. videoElm._record_continuous = _endlessloop.appendLoop(handle.afPlaybackRecording);
  992. videoElm._record_continuous._lastSave = -999;
  993.  
  994. videoElm._record_continuous.timeDelta = 2000;
  995. videoElm._record_continuous.player = videoElm
  996. videoElm._record_continuous.savePlaybackProgress = handle.savePlaybackProgress;
  997. videoElm._record_continuous.updateUID = handle.pr_updateUID;
  998.  
  999. videoElm._record_continuous.playingWithRecording = function() {
  1000. let player = this.player;
  1001. if (!player.paused && this.updateUID() && !this.isFunctionLooping) {
  1002. this.pTime = 0;
  1003. this.loopingStart();
  1004. }
  1005. }
  1006.  
  1007. }
  1008.  
  1009. videoElm._record_continuous.playingWithRecording(videoElm); //try to start recording
  1010.  
  1011. videoElm._isThisPausedBefore_ = false;
  1012.  
  1013. },
  1014. handlerVideoPause: function(evt) {
  1015.  
  1016. const videoElm = evt.target || this || null;
  1017.  
  1018. const playerConf = $hs.getPlayerConf(videoElm)
  1019. if (playerConf) {
  1020. playerConf.lastPauseAt = +new Date;
  1021. playerConf.timeout_pause = setTimeout(() => {
  1022. if (playerConf.lastPauseAt > 0) playerConf.domActive |= DOM_ACTIVE_DELAYED_PAUSED;
  1023. }, 600)
  1024. }
  1025.  
  1026. if (!$hs.enable) return $hs.tips(false);
  1027. consoleLog('pause')
  1028. videoElm._isThisPausedBefore_ = true;
  1029.  
  1030. let _last_paused = videoElm._last_paused
  1031. videoElm._last_paused = videoElm.paused
  1032. if (videoElm.playpause_cid) {
  1033. clearTimeout(videoElm.playpause_cid);
  1034. videoElm.playpause_cid = 0;
  1035. }
  1036. if (_last_paused === !videoElm.paused) {
  1037. videoElm.playpause_cid = setTimeout(() => {
  1038. if (videoElm.paused === !_last_paused && videoElm.paused) {
  1039. $hs._tips(videoElm, 'Playback paused', undefined, 2500)
  1040. }
  1041. }, 90)
  1042. }
  1043.  
  1044.  
  1045. if (videoElm._record_continuous && videoElm._record_continuous.isFunctionLooping) {
  1046. videoElm._record_continuous.savePlaybackProgress(); //savePlaybackProgress once before stopping //handle.savePlaybackProgress;
  1047. videoElm._record_continuous.loopingStop();
  1048. }
  1049.  
  1050.  
  1051. },
  1052. handlerVideoVolumeChange: function(evt) {
  1053.  
  1054. const videoElm = evt.target || this || null;
  1055.  
  1056. if (videoElm.volume >= 0) {} else {
  1057. return;
  1058. }
  1059. let cVol = videoElm.volume;
  1060. let cMuted = videoElm.muted;
  1061.  
  1062. if (cVol === videoElm._volume_p && cMuted === videoElm._muted_p) {
  1063. // nothing changed
  1064. } else if (cVol === videoElm._volume_p && cMuted !== videoElm._muted_p) {
  1065. // muted changed
  1066. } else { // cVol != pVol
  1067.  
  1068. // only volume changed
  1069.  
  1070. let shallShowTips = videoElm._volume >= 0; //prevent initialization
  1071.  
  1072. if (!cVol) {
  1073. videoElm.muted = true;
  1074. } else if (cMuted) {
  1075. videoElm.muted = false;
  1076. videoElm._volume = cVol;
  1077. } else if (!cMuted) {
  1078. videoElm._volume = cVol;
  1079. }
  1080. consoleLog('volume changed')
  1081.  
  1082. if (shallShowTips)
  1083. $hs._tips(videoElm, 'Volume: ' + dround(videoElm.volume * 100) + '%', undefined, 3000)
  1084.  
  1085. }
  1086.  
  1087. videoElm._volume_p = cVol
  1088. videoElm._muted_p = cMuted
  1089.  
  1090. },
  1091. handlerVideoLoadedMetaData: function(evt) {
  1092. const videoElm = evt.target || this || null;
  1093. consoleLog('video size', this.videoWidth + ' x ' + this.videoHeight);
  1094.  
  1095. let vpid = videoElm.getAttribute('_h5ppid') || null;
  1096. if (!vpid || !videoElm.currentSrc) return;
  1097.  
  1098. if ($hs.varSrcList[vpid] != videoElm.currentSrc) {
  1099. $hs.varSrcList[vpid] = videoElm.currentSrc;
  1100. $hs.videoSrcFound(videoElm);
  1101. $hs._actionBoxSet(videoElm);
  1102. }
  1103. if (!videoElm._onceVideoLoaded) {
  1104. videoElm._onceVideoLoaded = true;
  1105. videoElm.addEventListener('playing', $hs.handlerVideoPlaying)
  1106. videoElm.addEventListener('pause', $hs.handlerVideoPause);
  1107. videoElm.addEventListener("volumechange", $hs.handlerVideoVolumeChange);
  1108. playerConfs[vpid].domActive |= DOM_ACTIVE_SRC_LOADED;
  1109. }
  1110.  
  1111. },
  1112. handlerElementMouseEnter: function(evt) {
  1113. if ($hs.intVideoInitCount > 0) {} else {
  1114. return;
  1115. }
  1116.  
  1117. const actionBox = $hs.trigger_actionBoxes.filter(actionBox => (evt.target === actionBox || actionBox.contains(evt.target)))[0]
  1118. if (!actionBox) return;
  1119. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1120. const videoElm = getRoot(actionBox).querySelector(`VIDEO[_h5ppid="${vpid}"]`);
  1121. if (!videoElm) return;
  1122.  
  1123. $hs._actionBoxSet(videoElm);
  1124.  
  1125. const playerConf = $hs.getPlayerConf(videoElm)
  1126. if (playerConf) {
  1127. momentary.act("actionBoxMouseEnter",
  1128. () => {
  1129. playerConf.domActive |= DOM_ACTIVE_MOUSE_IN;
  1130. },
  1131. () => {
  1132. playerConf.domActive &= ~DOM_ACTIVE_MOUSE_IN;
  1133. },
  1134. 300)
  1135. }
  1136.  
  1137. },
  1138. handlerElementMouseDown: function(evt) {
  1139.  
  1140. if ($hs.intVideoInitCount > 0) {} else {
  1141. return;
  1142. }
  1143.  
  1144. const actionBox = $hs.trigger_actionBoxes.filter(actionBox => (evt.target === actionBox || actionBox.contains(evt.target)))[0]
  1145. if (!actionBox) return;
  1146. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1147. const videoElm = getRoot(actionBox).querySelector(`VIDEO[_h5ppid="${vpid}"]`);
  1148. if (!videoElm) return;
  1149.  
  1150. $hs._actionBoxSet(videoElm);
  1151.  
  1152. const playerConf = $hs.getPlayerConf(videoElm)
  1153. if (playerConf) {
  1154. momentary.act("actionBoxClicking",
  1155. () => {
  1156. playerConf.domActive |= DOM_ACTIVE_MOUSE_CLICK;
  1157. },
  1158. () => {
  1159. playerConf.domActive &= ~DOM_ACTIVE_MOUSE_CLICK;
  1160. },
  1161. 300)
  1162. }
  1163. $hs.swtichPlayerInstance();
  1164.  
  1165. },
  1166. handlerElementWheelTuneVolume: function(evt) { //shift + wheel
  1167.  
  1168. if ($hs.intVideoInitCount > 0) {} else {
  1169. return;
  1170. }
  1171.  
  1172. const actionBox = $hs.trigger_actionBoxes.filter(actionBox => (evt.target === actionBox || actionBox.contains(evt.target)))[0]
  1173. if (!actionBox) return;
  1174. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1175. const videoElm = getRoot(actionBox).querySelector(`VIDEO[_h5ppid="${vpid}"]`);
  1176. if (!videoElm) return;
  1177.  
  1178. if (!evt.shiftKey) return;
  1179. if (evt.deltaY) {
  1180. let player = $hs.player();
  1181. if (!player || player != videoElm) return;
  1182.  
  1183. if (evt.deltaY > 0) {
  1184.  
  1185. if ((player.muted && player.volume === 0) && player._volume > 0) {
  1186.  
  1187. player.muted = false;
  1188. player.volume = player._volume;
  1189. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  1190. player.muted = false;
  1191. }
  1192. $hs.tuneVolume(-0.05)
  1193.  
  1194. evt.stopPropagation()
  1195. evt.preventDefault()
  1196. return false
  1197.  
  1198. } else if (evt.deltaY < 0) {
  1199.  
  1200. if ((player.muted && player.volume === 0) && player._volume > 0) {
  1201. player.muted = false;
  1202. player.volume = player._volume;
  1203. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  1204. player.muted = false;
  1205. }
  1206. $hs.tuneVolume(+0.05)
  1207.  
  1208. evt.stopPropagation()
  1209. evt.preventDefault()
  1210. return false
  1211.  
  1212. }
  1213. }
  1214. },
  1215. debug01: function(evt, videoActive) {
  1216.  
  1217. if (!$hs.eventHooks) {
  1218. document.__h5p_eventhooks = ($hs.eventHooks = {
  1219. _debug_: []
  1220. });
  1221. }
  1222. $hs.eventHooks._debug_.push([videoActive, evt.type]);
  1223. // console.log('h5p eventhooks = document.__h5p_eventhooks')
  1224. },
  1225.  
  1226. swtichPlayerInstance: function() {
  1227.  
  1228. let newPlayerInstance = null;
  1229. const ONLY_PLAYING_NONE = 0x4A00;
  1230. const ONLY_PLAYING_MORE_THAN_ONE = 0x5A00;
  1231. let onlyPlayingInstance = ONLY_PLAYING_NONE;
  1232. for (let k in playerConfs) {
  1233. let playerConf = playerConfs[k] || {};
  1234. let {
  1235. domElement,
  1236. domActive
  1237. } = playerConf;
  1238. if (domElement) {
  1239. if (domActive & DOM_ACTIVE_INVALID_PARENT) continue;
  1240. if (!domElement.parentNode) {
  1241. playerConf.domActive |= DOM_ACTIVE_INVALID_PARENT;
  1242. continue;
  1243. }
  1244. if (domActive & DOM_ACTIVE_MOUSE_CLICK) {
  1245. newPlayerInstance = domElement
  1246. break;
  1247. }
  1248. if (domActive & DOM_ACTIVE_ONCE_PLAYED && (domActive & DOM_ACTIVE_DELAYED_PAUSED) == 0) {
  1249. if (onlyPlayingInstance == ONLY_PLAYING_NONE) onlyPlayingInstance = domElement;
  1250. else onlyPlayingInstance = ONLY_PLAYING_MORE_THAN_ONE;
  1251. }
  1252. }
  1253. }
  1254. if (newPlayerInstance == null && onlyPlayingInstance.nodeType == 1) {
  1255. newPlayerInstance = onlyPlayingInstance;
  1256. }
  1257.  
  1258. $hs.playerInstance = newPlayerInstance
  1259.  
  1260.  
  1261. },
  1262. switchCurrentPlayingConf: function() {
  1263. let player = $hs.player();
  1264. let res = null;
  1265. if (player) {
  1266. for (const tupConf of timeupdateStore) {
  1267. if (tupConf && tupConf.videoElement === player) {
  1268. res = tupConf
  1269. break;
  1270. }
  1271. }
  1272. }
  1273. timeupdateStore.currentPlayingConf = res
  1274.  
  1275. },
  1276. handlerElementDblClick: function(evt) {
  1277.  
  1278. if ($hs.intVideoInitCount > 0) {} else {
  1279. return;
  1280. }
  1281.  
  1282. if (document.readyState != "complete") return;
  1283.  
  1284. const actionBox = $hs.trigger_actionBoxes.filter(actionBox => (evt.target === actionBox || actionBox.contains(evt.target)))[0]
  1285. if (!actionBox) return;
  1286. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1287. const videoElm = getRoot(actionBox).querySelector(`VIDEO[_h5ppid="${vpid}"]`);
  1288. if (!videoElm) return;
  1289.  
  1290. $hs._actionBoxSet(videoElm);
  1291.  
  1292. const playerConf = $hs.getPlayerConf(videoElm)
  1293. if (playerConf) {
  1294. momentary.act("actionBoxClicking",
  1295. () => {
  1296. playerConf.domActive |= DOM_ACTIVE_MOUSE_CLICK;
  1297. },
  1298. () => {
  1299. playerConf.domActive &= ~DOM_ACTIVE_MOUSE_CLICK;
  1300. },
  1301. 600)
  1302. }
  1303. $hs.swtichPlayerInstance()
  1304.  
  1305. $hs.onVideoTriggering()
  1306.  
  1307. $hs.callFullScreenBtn();
  1308.  
  1309. evt.stopPropagation()
  1310. evt.preventDefault()
  1311. return false
  1312.  
  1313. },
  1314. handlerDocFocusOut: function(e) {
  1315. let doc = this;
  1316. $hs.focusFxLock = true;
  1317. $ws.requestAnimationFrame(function() {
  1318. $hs.focusFxLock = false;
  1319. if (!$hs.enable) $hs.tips(false);
  1320. else
  1321. if (!doc.hasFocus() && $hs.player() && !$hs.isLostFocus) {
  1322. $hs.isLostFocus = true;
  1323. consoleLog('doc.focusout')
  1324. //$hs.tips('focus is lost', -1);
  1325. }
  1326. });
  1327. },
  1328. handlerDocFocusIn: function(e) {
  1329. let doc = this;
  1330. if ($hs.focusFxLock) return;
  1331. $ws.requestAnimationFrame(function() {
  1332.  
  1333. if ($hs.focusFxLock) return;
  1334. if (!$hs.enable) $hs.tips(false);
  1335. else
  1336. if (doc.hasFocus() && $hs.player() && $hs.isLostFocus) {
  1337. $hs.isLostFocus = false;
  1338. consoleLog('doc.focusin')
  1339. $hs.tips(false);
  1340.  
  1341. }
  1342. });
  1343. },
  1344.  
  1345. handlerWinMessage: async function(e) {
  1346. let tag, ed;
  1347. if (typeof e.data == 'object' && typeof e.data.tag == 'string') {
  1348. tag = e.data.tag;
  1349. ed = e.data
  1350. } else {
  1351. return;
  1352. }
  1353. let msg = null,
  1354. success = 0;
  1355. switch (tag) {
  1356. case 'consoleLog':
  1357. let msg_str = ed.str;
  1358. let msg_stype = ed.stype;
  1359. if (msg_stype === 1) {
  1360. msg = (document[str_postMsgData] || {})[msg_str] || [];
  1361. success = 1;
  1362. } else if (msg_stype === 2) {
  1363. msg = jsonParse(msg_str);
  1364. if (msg && msg.d) {
  1365. success = 2;
  1366. msg = msg.d;
  1367. }
  1368. } else {
  1369. msg = msg_str
  1370. }
  1371. let p = (ed.passing && ed.winOrder) ? [' | from win-' + ed.winOrder] : [];
  1372. if (success) {
  1373. console.log(...msg, ...p)
  1374. //document[ed.data]=null; // also delete the information
  1375. } else {
  1376. console.log('msg--', msg, ...p, ed);
  1377. }
  1378. break;
  1379.  
  1380. }
  1381. },
  1382.  
  1383. isInActiveMode: function(activeElm, player) {
  1384.  
  1385. if (activeElm == player) {
  1386. return true;
  1387. }
  1388.  
  1389. if ($hs.trigger_actionBoxes[0]) {
  1390. let actionBox = $hs.trigger_actionBoxes[0];
  1391. if (activeElm == actionBox || actionBox.contains(activeElm)) {
  1392. return true;
  1393. }
  1394.  
  1395. }
  1396.  
  1397. let _checkingPass = false;
  1398.  
  1399. if (!player) return;
  1400. let layoutBox = $hs.getPlayerBlockElement(player).parentNode;
  1401. if (layoutBox && layoutBox.parentNode && layoutBox.contains(activeElm)) {
  1402. let rpid = player.getAttribute('_h5ppid') || "NULL";
  1403. let actionBox = layoutBox.parentNode.querySelector(`[_h5p_actionbox_="${rpid}"]`); //the box can be layoutBox
  1404. if (actionBox && actionBox.contains(activeElm)) _checkingPass = true;
  1405. }
  1406.  
  1407. return _checkingPass
  1408. },
  1409.  
  1410.  
  1411. toolCheckFullScreen: function(doc) {
  1412. if (typeof doc.fullScreen == 'boolean') return doc.fullScreen;
  1413. if (typeof doc.webkitIsFullScreen == 'boolean') return doc.webkitIsFullScreen;
  1414. if (typeof doc.mozFullScreen == 'boolean') return doc.mozFullScreen;
  1415. return null;
  1416. },
  1417.  
  1418. toolFormatCT: function(u) {
  1419.  
  1420. let w = Math.round(u, 0)
  1421. let a = w % 60
  1422. w = (w - a) / 60
  1423. let b = w % 60
  1424. w = (w - b) / 60
  1425. let str = ("0" + b).substr(-2) + ":" + ("0" + a).substr(-2);
  1426. if (w) str = w + ":" + str
  1427.  
  1428. return str
  1429.  
  1430. },
  1431.  
  1432. makeFocus: function(player, evt) {
  1433. setTimeout(function() {
  1434. let rpid = player.getAttribute('_h5ppid');
  1435. let actionBox = getRoot(player).querySelector(`[_h5p_actionbox_="${rpid}"]`);
  1436.  
  1437. //console.log('p',rpid, player,actionBox,document.activeElement)
  1438. if (actionBox && actionBox != document.activeElement && !actionBox.contains(document.activeElement)) {
  1439. consoleLog('make focus on', actionBox)
  1440. actionBox.focus();
  1441.  
  1442. }
  1443.  
  1444. }, 300)
  1445. },
  1446.  
  1447. getActionBlockElement: function(player, layoutBox) {
  1448.  
  1449. if (!player || !layoutBox) return null;
  1450.  
  1451.  
  1452. let walkRes = domTool._isActionBox_1(player, layoutBox);
  1453. let parentCount = walkRes.length;
  1454. let actionBox = null;
  1455. if (parentCount - 1 >= 0 && domTool._isActionBox(player, walkRes, parentCount - 1)) {
  1456. actionBox = walkRes[parentCount - 1].elm;
  1457. } else if (parentCount - 2 >= 0 && domTool._isActionBox(player, walkRes, parentCount - 2)) {
  1458. actionBox = walkRes[parentCount - 2].elm;
  1459. } else {
  1460. actionBox = player;
  1461. }
  1462.  
  1463.  
  1464. let search = $hs.videoFullscreenBtns(actionBox, 4);
  1465. if (search && search.elements.length > 0) actionBox = search.container;
  1466.  
  1467. return actionBox;
  1468.  
  1469.  
  1470. },
  1471.  
  1472. _actionBoxSet: function(player) {
  1473.  
  1474. if (!player) return null;
  1475. let vpid = player.getAttribute('_h5ppid');
  1476. if (!vpid) return null;
  1477.  
  1478. let layoutBox = $hs.getPlayerBlockElement(player).parentNode;
  1479. let actionBox = $hs.getActionBlockElement(player, layoutBox);
  1480.  
  1481.  
  1482. //console.log('actionbox search:', actionBox)
  1483.  
  1484. if (actionBox && actionBox.getAttribute('_h5p_actionbox_') != vpid) {
  1485. consoleLog('D-1', actionBox);
  1486. for (const previousActionboxes of getRoot(player).querySelectorAll(`[_h5p_actionbox_="${vpid}"]`)) {
  1487. //change of parentNode
  1488. previousActionboxes.removeAttribute('_h5p_actionbox_');
  1489. }
  1490. actionBox.setAttribute('_h5p_actionbox_', vpid);
  1491. $hs.trigger_actionBoxes = [actionBox];
  1492.  
  1493. if (!actionBox.hasAttribute('tabindex')) actionBox.setAttribute('tabindex', '-1');
  1494.  
  1495.  
  1496.  
  1497. }
  1498. return actionBox;
  1499. },
  1500.  
  1501. videoSrcFound: function(player) {
  1502.  
  1503. // src loaded
  1504.  
  1505. if (!player) return;
  1506. let vpid = player.getAttribute('_h5ppid') || null;
  1507. if (!vpid || !player.currentSrc) return;
  1508.  
  1509. player._isThisPausedBefore_ = false;
  1510.  
  1511. player.removeAttribute('_h5p_uid_encrypted');
  1512.  
  1513. if (player._record_continuous) player._record_continuous._lastSave = -999; //first time must save
  1514.  
  1515. let uid_A = location.pathname.replace(/[^\d+]/g, '') + '.' + location.search.replace(/[^\d+]/g, '');
  1516. let _uid = location.hostname.replace('www.', '').toLowerCase() + '!' + location.pathname.toLowerCase() + 'A' + uid_A + 'W' + player.videoWidth + 'H' + player.videoHeight + 'L' + (player.duration << 0);
  1517.  
  1518. digestMessage(_uid).then(function(_uid_encrypted) {
  1519.  
  1520. let d = +new Date;
  1521.  
  1522. let recordedTime = null;
  1523.  
  1524. ;
  1525. (function() {
  1526. //read the last record only;
  1527.  
  1528. let k1 = '_h5_player_play_progress_';
  1529. let k1n = '_play_progress_';
  1530. let k2 = _uid_encrypted;
  1531. let k3 = k1 + k2;
  1532. let k3n = k1n + k2;
  1533. let m2 = Store._keys().filter(key => key.substr(0, k3.length) == k3); //all progress records for this video
  1534. let m2v = m2.map(keyName => +(keyName.split('+')[1] || '0'))
  1535. let m2vMax = Math.max(0, ...m2v)
  1536. if (!m2vMax) recordedTime = null;
  1537. else {
  1538. let _json_recordedTime = null;
  1539. _json_recordedTime = Store.read(k3n + '+' + m2vMax);
  1540. if (!_json_recordedTime) _json_recordedTime = {};
  1541. else _json_recordedTime = jsonParse(_json_recordedTime);
  1542. if (typeof _json_recordedTime == 'object') recordedTime = _json_recordedTime;
  1543. else recordedTime = null;
  1544. recordedTime = typeof recordedTime == 'object' ? recordedTime.t : recordedTime;
  1545. if (typeof recordedTime == 'number' && (+recordedTime >= 0 || +recordedTime <= 0)) {
  1546.  
  1547. } else if (typeof recordedTime == 'string' && recordedTime.length > 0 && (+recordedTime >= 0 || +recordedTime <= 0)) {
  1548. recordedTime = +recordedTime
  1549. } else {
  1550. recordedTime = null
  1551. }
  1552. }
  1553. if (recordedTime !== null) {
  1554. player._h5player_lastrecord_ = recordedTime;
  1555. } else {
  1556. player._h5player_lastrecord_ = null;
  1557. }
  1558. if (player._h5player_lastrecord_ > 5) {
  1559. consoleLog('last record playing', player._h5player_lastrecord_);
  1560. setTimeout(function() {
  1561. $hs._tips(player, `Press Shift-R to restore Last Playback: ${$hs.toolFormatCT(player._h5player_lastrecord_)}`, 5000, 4000)
  1562. }, 1000)
  1563. }
  1564.  
  1565. })();
  1566. // delay the recording by 5.4s => prevent ads or mis operation
  1567. setTimeout(function() {
  1568.  
  1569. let k1 = '_h5_player_play_progress_';
  1570. let k1n = '_play_progress_';
  1571. let k2 = _uid_encrypted;
  1572. let k3 = k1 + k2;
  1573. let k3n = k1n + k2;
  1574.  
  1575. //re-read all the localStorage keys
  1576. let m1 = Store._keys().filter(key => key.substr(0, k1.length) == k1); //all progress records in this site
  1577. let p = m1.length + 1;
  1578.  
  1579. for (const key of m1) { //all progress records for this video
  1580. if (key.substr(0, k3.length) == k3) {
  1581. Store._removeItem(key); //remove previous record for the current video
  1582. p--;
  1583. }
  1584. }
  1585.  
  1586. if (recordedTime !== null) {
  1587. Store.save(k3n + '+' + d, jsonStringify({
  1588. 't': recordedTime
  1589. })) //prevent loss of last record
  1590. }
  1591.  
  1592. const _record_max_ = 48;
  1593. const _record_keep_ = 26;
  1594.  
  1595. if (p > _record_max_) {
  1596. //exisiting 48 records for one site;
  1597. //keep only 26 records
  1598.  
  1599. const comparator = (a, b) => (a.t < b.t ? -1 : a.t > b.t ? 1 : 0);
  1600.  
  1601. m1
  1602. .map(keyName => ({
  1603. keyName,
  1604. t: +(keyName.split('+')[1] || '0')
  1605. }))
  1606. .sort(comparator)
  1607. .slice(0, -_record_keep_)
  1608. .forEach((item) => localStorage.removeItem(item.keyName));
  1609.  
  1610. consoleLog(`stored progress: reduced to ${_record_keep_}`)
  1611. }
  1612.  
  1613. player.setAttribute('_h5p_uid_encrypted', _uid_encrypted + '+' + d);
  1614.  
  1615. //try to start recording
  1616. if (player._record_continuous) player._record_continuous.playingWithRecording();
  1617.  
  1618. }, 5400);
  1619.  
  1620. })
  1621.  
  1622. },
  1623. bindDocEvents: function(rootNode) {
  1624. if (!rootNode._onceBindedDocEvents) {
  1625.  
  1626. rootNode._onceBindedDocEvents = true;
  1627. rootNode.addEventListener('keydown', $hs.handlerRootKeyDownEvent, true)
  1628. document._debug_rootNode_ = rootNode;
  1629.  
  1630. rootNode.addEventListener('mouseenter', $hs.handlerElementMouseEnter, true)
  1631. rootNode.addEventListener('mousedown', $hs.handlerElementMouseDown, true)
  1632. rootNode.addEventListener('dblclick', $hs.handlerElementDblClick, true)
  1633. rootNode.addEventListener('wheel', $hs.handlerElementWheelTuneVolume, {
  1634. passive: false
  1635. });
  1636. // wheel - bubble events to keep it simple (i.e. it must be passive:false & capture:false)
  1637.  
  1638. }
  1639. },
  1640. fireGlobalInit: function() {
  1641. if ($hs.intVideoInitCount != 1) return;
  1642. if (!$hs.varSrcList) $hs.varSrcList = {};
  1643. $hs.isLostFocus = null;
  1644. try {
  1645. //iframe may not be able to control top window
  1646. //error; just ignore with async
  1647. let topDoc = window.top && window.top.document ? window.top.document : null;
  1648. if (topDoc) {
  1649. topDoc.addEventListener('focusout', $hs.handlerDocFocusOut, true)
  1650. topDoc.addEventListener('focusin', $hs.handlerDocFocusIn, true)
  1651. }
  1652.  
  1653. } catch (e) {}
  1654. Store.clearInvalid(_sVersion_)
  1655. },
  1656. onVideoTriggering: function() {
  1657.  
  1658.  
  1659. // initialize a single video player - h5Player.playerInstance
  1660.  
  1661. /**
  1662. * 初始化播放器實例
  1663. */
  1664. let player = $hs.playerInstance
  1665. if (!player) return
  1666.  
  1667. let vpid = player.getAttribute('_h5ppid');
  1668.  
  1669. if (!vpid) return;
  1670.  
  1671. let firstTime = !!$hs.initTips()
  1672. if (firstTime) {
  1673. // first time to trigger this player
  1674. if (!player.hasAttribute('playsinline')) player.setAttribute('playsinline', 'playsinline');
  1675. if (!player.hasAttribute('x-webkit-airplay')) player.setAttribute('x-webkit-airplay', 'deny');
  1676. if (!player.hasAttribute('preload')) player.setAttribute('preload', 'auto');
  1677. //player.style['image-rendering'] = 'crisp-edges';
  1678. $hs.playbackRate = $hs.getPlaybackRate()
  1679. }
  1680.  
  1681. },
  1682. getPlaybackRate: function() {
  1683. let playbackRate = Store.read('_playback_rate_') || $hs.playbackRate
  1684. return Number(Number(playbackRate).toFixed(1))
  1685. },
  1686. getPlayerBlockElement: function(player) {
  1687. //without checkActiveBox, just a DOM for you to append tipsDom
  1688.  
  1689. let layoutBox = null,
  1690. wPlayer = null
  1691.  
  1692. if (!player || !player.offsetHeight || !player.offsetWidth || !player.parentNode) {
  1693. return null;
  1694. }
  1695.  
  1696. function search_nodes() {
  1697.  
  1698. wPlayer = player; // NOT NULL
  1699. layoutBox = wPlayer.parentNode; // NOT NULL
  1700.  
  1701. while (layoutBox.parentNode && layoutBox.nodeType == 1 && layoutBox.offsetHeight == 0) {
  1702. wPlayer = layoutBox; // NOT NULL
  1703. layoutBox = layoutBox.parentNode; // NOT NULL
  1704. }
  1705. //container must be with offsetHeight
  1706.  
  1707. while (layoutBox.parentNode && layoutBox.nodeType == 1 && layoutBox.offsetHeight < player.offsetHeight) {
  1708. wPlayer = layoutBox; // NOT NULL
  1709. layoutBox = layoutBox.parentNode; // NOT NULL
  1710. }
  1711. //container must have height >= player height
  1712.  
  1713. }
  1714.  
  1715. search_nodes();
  1716.  
  1717. if (layoutBox.nodeType == 11) {
  1718.  
  1719.  
  1720. //shadowRoot without html and body
  1721. let shadowChild, shadowElm_container, shadowElm_head, shadowElm_html;
  1722. let rootNode = getRoot(player);
  1723. if (rootNode.querySelectorAll('html,body').length < 2) {
  1724.  
  1725. shadowElm_container = player.ownerDocument.createElement('BODY')
  1726. rootNode.insertBefore(shadowElm_container, rootNode.firstChild)
  1727.  
  1728. while (shadowChild = shadowElm_container.nextSibling) shadowElm_container.appendChild(shadowChild);
  1729.  
  1730. shadowElm_head = rootNode.insertBefore(player.ownerDocument.createElement('HEAD'), shadowElm_container)
  1731.  
  1732. shadowElm_html = rootNode.insertBefore(player.ownerDocument.createElement('HTML'), shadowElm_head)
  1733.  
  1734. shadowElm_container.setAttribute('style', 'padding:0;margin:0;border:0; box-sizing: border-box;')
  1735. shadowElm_html.setAttribute('style', 'padding:0;margin:0;border:0; box-sizing: border-box;')
  1736.  
  1737. shadowElm_html.appendChild(shadowElm_head)
  1738. shadowElm_html.appendChild(shadowElm_container)
  1739.  
  1740. }
  1741.  
  1742. search_nodes();
  1743.  
  1744. }
  1745.  
  1746. //condition:
  1747. //!layoutBox.parentNode || layoutBox.nodeType != 1 || layoutBox.offsetHeight > player.offsetHeight
  1748.  
  1749. // layoutBox is a node contains <video> and offsetHeight>=video.offsetHeight
  1750. // wPlayer is a HTML Element (nodeType==1)
  1751. // you can insert the DOM element into the layoutBox
  1752.  
  1753. if (layoutBox && wPlayer && layoutBox.nodeType === 1 && wPlayer.parentNode == layoutBox) return wPlayer;
  1754. throw 'unknown error';
  1755.  
  1756. },
  1757. getCommonContainer: function(elm1, elm2) {
  1758.  
  1759. let box1 = elm1;
  1760. let box2 = elm2;
  1761.  
  1762. while (box1 && box2) {
  1763. if (box1.contains(box2) || box2.contains(box1)) {
  1764. break;
  1765. }
  1766. box1 = box1.parentNode;
  1767. box2 = box2.parentNode;
  1768. }
  1769.  
  1770. let layoutBox = null;
  1771.  
  1772. box1 = (box1 && box1.contains(elm2)) ? box1 : null;
  1773. box2 = (box2 && box2.contains(elm1)) ? box2 : null;
  1774.  
  1775. if (box1 && box2) layoutBox = box1.contains(box2) ? box2 : box1;
  1776. else layoutBox = box1 || box2 || null;
  1777.  
  1778. return layoutBox
  1779.  
  1780. },
  1781. change_layoutBox: function(tipsDom) {
  1782. let player = $hs.player()
  1783. if (!player) return;
  1784. let wPlayer = $hs.getPlayerBlockElement(player);
  1785. let layoutBox = wPlayer.parentNode;
  1786.  
  1787. if ((layoutBox && layoutBox.nodeType == 1) && (!tipsDom.parentNode || tipsDom.parentNode !== layoutBox)) {
  1788.  
  1789. consoleLog('changed_layoutBox')
  1790. layoutBox.insertBefore(tipsDom, wPlayer);
  1791.  
  1792. }
  1793. },
  1794.  
  1795. queryFullscreenBtnsIndependant: function(parentNode, returnElementsOnly) {
  1796.  
  1797. let btns = [];
  1798. for (const elm of parentNode.querySelectorAll('[class*="full"][class*="screen"]')) {
  1799. let className = (elm.getAttribute('class') || "");
  1800. if (/\b(fullscreen|full-screen)\b/i.test(className.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  1801.  
  1802. let hasClickListeners = null,
  1803. childElementCount = null,
  1804. isVisible = null;
  1805.  
  1806.  
  1807. if ('_listeners' in elm) {
  1808.  
  1809. hasClickListeners = elm._listeners && elm._listeners.click && elm._listeners.click.funcCount > 0
  1810.  
  1811. }
  1812.  
  1813. if ('childElementCount' in elm) {
  1814.  
  1815. childElementCount = elm.childElementCount;
  1816.  
  1817. }
  1818. if ('offsetParent' in elm) {
  1819. isVisible = !!elm.offsetParent; //works with parent/self display none; not work with visiblity hidden / opacity0
  1820.  
  1821. }
  1822.  
  1823. if (hasClickListeners) {
  1824. let btn = {
  1825. elm,
  1826. isVisible,
  1827. hasClickListeners,
  1828. childElementCount,
  1829. isContained: null
  1830. };
  1831.  
  1832.  
  1833. btns.push(returnElementsOnly ? elm : btn)
  1834.  
  1835. }
  1836.  
  1837. }
  1838. }
  1839. return btns;
  1840.  
  1841. },
  1842. exclusiveElements: function(elms) {
  1843.  
  1844. //not containing others
  1845. let res = [];
  1846.  
  1847. for (const roleElm of elms) {
  1848.  
  1849. let isContained = false;
  1850. for (const testElm of elms) {
  1851. if (testElm != roleElm && roleElm.contains(testElm)) {
  1852. isContained = true;
  1853. break;
  1854. }
  1855. }
  1856. if (!isContained) res.push(roleElm)
  1857. }
  1858. return res;
  1859.  
  1860. },
  1861. videoFullscreenBtns: function(startPoint, searchCount) {
  1862.  
  1863.  
  1864. let c = 0,
  1865. p = startPoint,
  1866. q = null;
  1867. while (p && (++c <= searchCount)) {
  1868.  
  1869. if (p.querySelectorAll('video').length !== 1) break;
  1870.  
  1871. let elmFullscreenBtns = $hs.queryFullscreenBtnsIndependant(p, true);
  1872. if (elmFullscreenBtns.length > 0) {
  1873.  
  1874. let exclusiveFullscreenBtns = $hs.exclusiveElements(elmFullscreenBtns)
  1875. if (exclusiveFullscreenBtns.length > 0) {
  1876. return {
  1877. container: p,
  1878. elements: exclusiveFullscreenBtns
  1879. };
  1880.  
  1881. }
  1882. }
  1883.  
  1884.  
  1885. q = p;
  1886. p = p.parentNode;
  1887. }
  1888.  
  1889. return null;
  1890.  
  1891.  
  1892.  
  1893.  
  1894. },
  1895. callFullScreenBtn: function() {
  1896.  
  1897. let player = $hs.player()
  1898. if (!player || !player.ownerDocument || !('exitFullscreen' in player.ownerDocument)) return;
  1899.  
  1900. let btnElement = null;
  1901.  
  1902. let vpid = player.getAttribute('_h5ppid') || null;
  1903.  
  1904. if (!vpid) return;
  1905.  
  1906.  
  1907. const chFull = $hs.toolCheckFullScreen(player.ownerDocument);
  1908.  
  1909.  
  1910.  
  1911.  
  1912. if (chFull === true) {
  1913. player.ownerDocument.exitFullscreen();
  1914. } else if (chFull === false) {
  1915.  
  1916.  
  1917. let actionBox = getRoot(player).querySelector(`[_h5p_actionbox_="${vpid}"]`);
  1918.  
  1919. if (actionBox) {
  1920.  
  1921. let exclusiveFullscreenBtns = $hs.videoFullscreenBtns(actionBox, 1);
  1922. let btnElements = exclusiveFullscreenBtns ? exclusiveFullscreenBtns.elements : null;
  1923. if (btnElements && btnElements.length > 0) {
  1924.  
  1925. //consoleLog('fullscreen btn', btnElements)
  1926.  
  1927. const lens_elemsClassName = btnElements.map(elm => elm.className.length)
  1928. const j_elemsClassName = Math.min(...lens_elemsClassName)
  1929. let btnElement_idx = lens_elemsClassName.lastIndexOf(j_elemsClassName)
  1930. // pick the last btn if there is more than one
  1931. btnElement = btnElements[btnElement_idx];
  1932. window.requestAnimationFrame(() => btnElement.click());
  1933. //consoleLog('original fullscreen')
  1934.  
  1935. }
  1936. }
  1937.  
  1938.  
  1939. }
  1940.  
  1941. if (chFull === null || (chFull === false && !btnElement)) {
  1942.  
  1943. let layoutBox = $hs.getPlayerBlockElement(player).parentNode;
  1944.  
  1945. let gPlayer = null;
  1946. if (!layoutBox || !layoutBox.parentNode) {
  1947. consoleLog('the container for DOM fullscreen cannot be found')
  1948. return;
  1949. }
  1950. gPlayer = layoutBox.parentNode.querySelector(`[_h5p_actionbox_="${vpid}"]`); //the box can be layoutBox
  1951.  
  1952. consoleLog('DOM fullscreen', gPlayer)
  1953. try {
  1954. gPlayer.requestFullscreen() //known bugs : TypeError: fullscreen error
  1955. } catch (e) {
  1956. consoleLogF('fullscreen error', e)
  1957. }
  1958.  
  1959.  
  1960. }
  1961.  
  1962.  
  1963.  
  1964.  
  1965. },
  1966. /* 設置播放速度 */
  1967. setPlaybackRate: function(num, flagTips) {
  1968. let player = $hs.player()
  1969. let curPlaybackRate
  1970. if (num) {
  1971. num = +num
  1972. if (num > 0) { // also checking the type of variable
  1973. curPlaybackRate = num < 0.1 ? 0.1 : +(num.toFixed(1))
  1974. } else {
  1975. console.error('h5player: 播放速度轉換出錯')
  1976. return false
  1977. }
  1978. } else {
  1979. curPlaybackRate = $hs.getPlaybackRate()
  1980. }
  1981. /* 記錄播放速度的信息 */
  1982.  
  1983. let changed = curPlaybackRate !== player.playbackRate;
  1984.  
  1985. if (curPlaybackRate !== player.playbackRate) {
  1986.  
  1987. Store.save('_playback_rate_', curPlaybackRate + '')
  1988. $hs.playbackRate = curPlaybackRate
  1989. player.playbackRate = curPlaybackRate
  1990. /* 本身處於1被播放速度的時候不再提示 */
  1991. //if (!num && curPlaybackRate === 1) return;
  1992.  
  1993. }
  1994.  
  1995. flagTips = (flagTips < 0) ? false : (flagTips > 0) ? true : changed;
  1996. if (flagTips) $hs.tips('Playback speed: ' + player.playbackRate + 'x')
  1997. },
  1998. tuneCurrentTime: function(amount, flagTips) {
  1999. let _amount = +(+amount).toFixed(1);
  2000. let player = $hs.player();
  2001. if (_amount >= 0 || _amount < 0) {} else {
  2002. return;
  2003. }
  2004.  
  2005. let newCurrentTime = player.currentTime + _amount;
  2006. if (newCurrentTime < 0) newCurrentTime = 0;
  2007. if (newCurrentTime > player.duration) newCurrentTime = player.duration;
  2008.  
  2009. let changed = newCurrentTime != player.currentTime && newCurrentTime >= 0 && newCurrentTime <= player.duration;
  2010.  
  2011. if (changed) {
  2012. //player.currentTime = newCurrentTime;
  2013. player.pause();
  2014. let t_ch = (Math.random() / 5 + .75);
  2015. player.currentTime = newCurrentTime * t_ch + player.currentTime * (1.0 - t_ch);
  2016. setTimeout(() => {
  2017. player.play();
  2018. player.currentTime = newCurrentTime;
  2019. }, 33);
  2020. flagTips = (flagTips < 0) ? false : (flagTips > 0) ? true : changed;
  2021. $hs.tips(false);
  2022. if (flagTips) {
  2023. if (_amount > 0) $hs.tips(_amount + ' Sec. Forward', undefined, 3000);
  2024. else $hs.tips(-_amount + ' Sec. Backward', undefined, 3000)
  2025. }
  2026. }
  2027.  
  2028. },
  2029. tuneVolume: function(amount) {
  2030. let _amount = +(+amount).toFixed(2);
  2031.  
  2032. let player = $hs.player()
  2033.  
  2034. let newVol = player.volume + _amount;
  2035. if (newVol < 0) newVol = 0;
  2036. if (newVol > 1) newVol = 1;
  2037. let chVol = player.volume !== newVol && newVol >= 0 && newVol <= 1;
  2038.  
  2039. if (chVol) {
  2040.  
  2041. if (_amount > 0 && player.volume < 1) {
  2042. player.volume = newVol // positive
  2043. } else if (_amount < 0 && player.volume > 0) {
  2044. player.volume = newVol // negative
  2045. }
  2046. $hs.tips(false);
  2047. $hs.tips('Volume: ' + dround(player.volume * 100) + '%', undefined)
  2048. }
  2049. },
  2050. switchPlayStatus: function() {
  2051. let player = $hs.player()
  2052. if (player.paused) {
  2053. player.play()
  2054. if (player._isThisPausedBefore_) {
  2055. $hs.tips(false);
  2056. $hs.tips('Playback resumed', undefined, 2500)
  2057. }
  2058. } else {
  2059. player.pause()
  2060. $hs.tips(false);
  2061. $hs.tips('Playback paused', undefined, 2500)
  2062. }
  2063. },
  2064. tipsClassName: 'html_player_enhance_tips',
  2065. _tips: function(player, str, duration, order) {
  2066.  
  2067.  
  2068. if (!player.getAttribute('_h5player_tips')) $hs.initTips();
  2069.  
  2070. let tipsSelector = '#' + (player.getAttribute('_h5player_tips') || $hs.tipsClassName) //if this attribute still doesnt exist, set it to the base cls name
  2071. let tipsDom = getRoot(player).querySelector(tipsSelector)
  2072. if (!tipsDom) {
  2073. consoleLog('init h5player tips dom error...')
  2074. return false
  2075. }
  2076. $hs.change_layoutBox(tipsDom);
  2077.  
  2078. if (str === false) {
  2079. tipsDom.innerText = '';
  2080. tipsDom.setAttribute('_potTips_', '0')
  2081. } else {
  2082. order = order || 1000
  2083. tipsDom.tipsOrder = tipsDom.tipsOrder || 0;
  2084.  
  2085. let shallDisplay = true
  2086. if (order < tipsDom.tipsOrder && getComputedStyle(tipsDom).opacity > 0) shallDisplay = false
  2087.  
  2088. if (shallDisplay) {
  2089.  
  2090. tipsDom._playerElement = player;
  2091. tipsDom._playerVPID = player.getAttribute('_h5ppid');
  2092. tipsDom._playerBlockElm = $hs.getPlayerBlockElement(player)
  2093. tipsDom._env_changed = 0;
  2094.  
  2095. if (!_endlessloop) _endlessloop = new AFLooperArray();
  2096. tipsDom._cached_dimensions = null;
  2097. if (!$hs.__updateTips) {
  2098. $hs.__updateTips = _endlessloop.appendLoop(handle.afTipsDOM)
  2099. $hs.__updateTips.loopingStart();
  2100. }
  2101.  
  2102. if (duration === undefined) duration = 2000
  2103. tipsDom.innerText = str
  2104.  
  2105. tipsDom.setAttribute('_potTips_', '2')
  2106.  
  2107. $hs.fixNonBoxingVideoTipsPosition(tipsDom, player);
  2108.  
  2109. if (duration > 0) {
  2110. $ws.requestAnimationFrame(() => tipsDom.setAttribute('_potTips_', '1'))
  2111. } else {
  2112. order = -1;
  2113. }
  2114.  
  2115. tipsDom.tipsOrder = order
  2116.  
  2117. }
  2118.  
  2119. }
  2120.  
  2121. $hs.cacheTipsDoms();
  2122. },
  2123. tips: function(str, duration, order) {
  2124. let player = $hs.player()
  2125. if (!player) {
  2126. consoleLog('h5Player Tips:', str)
  2127. return true
  2128. }
  2129.  
  2130. return $hs._tips(player, str, duration, order)
  2131.  
  2132. },
  2133. listOfTipsDom: [],
  2134. cacheTipsDoms: function() {
  2135. $hs._cached_tipsDoms = $hs.getPotTips(['1', '2']); //48673
  2136. },
  2137. getPotTips: function(arr) {
  2138. const res = [];
  2139. for (const tipsDom of $hs.listOfTipsDom) {
  2140. if (tipsDom && tipsDom.nodeType > 0 && tipsDom.parentNode && tipsDom.ownerDocument) {
  2141. if (tipsDom._playerBlockElm && tipsDom._playerBlockElm.parentNode) {
  2142. const potTipsAttr = tipsDom.getAttribute('_potTips_')
  2143. if (arr.indexOf(potTipsAttr) >= 0) res.push(tipsDom)
  2144. }
  2145. }
  2146. }
  2147. return res;
  2148. },
  2149. initTips: function() {
  2150. /* 設置提示DOM的樣式 */
  2151. let player = $hs.player()
  2152. let shadowRoot = getRoot(player);
  2153. let doc = player.ownerDocument;
  2154. //console.log((document.documentElement.qq=player),shadowRoot,'xax')
  2155. let parentNode = player.parentNode
  2156. let tcn = player.getAttribute('_h5player_tips') || ($hs.tipsClassName + '_' + (+new Date));
  2157. player.setAttribute('_h5player_tips', tcn)
  2158. if (shadowRoot.querySelector('#' + tcn)) return false;
  2159.  
  2160. if (!shadowRoot._onceAddedCSS) {
  2161. shadowRoot._onceAddedCSS = true;
  2162.  
  2163. let cssStyle = `
  2164. [_potTips_="1"]{
  2165. animation: 2s linear 0s normal forwards 1 delayHide;
  2166. }
  2167. [_potTips_="0"]{
  2168. opacity:0; transform:translate(-9999px);
  2169. }
  2170. [_potTips_="2"]{
  2171. opacity:.95; transform: translate(0,0);
  2172. }
  2173.  
  2174. @keyframes delayHide{
  2175. 0%, 99% { opacity:0.95; transform: translate(0,0); }
  2176. 100% { opacity:0; transform:translate(-9999px); }
  2177. }
  2178. ` + `
  2179. [_potTips_]{
  2180. font-weight: bold !important;
  2181. position: absolute !important;
  2182. z-index: 999 !important;
  2183. font-size: ${$hs.fontSize || 16}px !important;
  2184. padding: 0px !important;
  2185. border:none !important;
  2186. background: rgba(0,0,0,0) !important;
  2187. color:#738CE6 !important;
  2188. text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;
  2189. top: 50%;
  2190. left: 50%;
  2191. max-width:500px;max-height:50px;
  2192. border-radius:3px;
  2193. font-family: 'microsoft yahei', Verdana, Geneva, sans-serif;
  2194. -webkit-user-select: none;
  2195. -moz-user-select: none;
  2196. -ms-user-select: none;
  2197. user-select: none;
  2198. -webkit-touch-callout: none;
  2199. -webkit-user-select: none;
  2200. -khtml-user-drag: none;
  2201. -khtml-user-select: none;
  2202. -moz-user-select: none;
  2203. -moz-user-select: -moz-none;
  2204. -ms-user-select: none;
  2205. pointer-events: none;
  2206. user-select: none;
  2207. }
  2208. `.replace(/\r\n/g, '');
  2209.  
  2210. let cssContainer = (shadowRoot.querySelector('head') || shadowRoot.querySelector('html') || document.documentElement);
  2211.  
  2212. domTool.addStyle(cssStyle, cssContainer);
  2213.  
  2214. }
  2215.  
  2216. let tipsDom = doc.createElement('div')
  2217.  
  2218. tipsDom.addEventListener(crossBrowserTransition('animation'), function(e) {
  2219. if (this.getAttribute('_potTips_') == '1') {
  2220. this.setAttribute('_potTips_', '0')
  2221. $hs.cacheTipsDoms();
  2222. }
  2223. })
  2224.  
  2225. tipsDom.id = tcn;
  2226. tipsDom.setAttribute('_potTips_', '0');
  2227. $hs.listOfTipsDom.push(tipsDom);
  2228. $hs.change_layoutBox(tipsDom);
  2229.  
  2230. return true;
  2231. },
  2232.  
  2233. responsiveSizing: function(container, elm) {
  2234.  
  2235. let gcssP = getComputedStyle(container);
  2236.  
  2237. let gcssE = getComputedStyle(elm);
  2238.  
  2239. //console.log(gcssE.left,gcssP.width)
  2240. let elmBound = {
  2241. left: parseFloat(gcssE.left) / parseFloat(gcssP.width),
  2242. width: parseFloat(gcssE.width) / parseFloat(gcssP.width),
  2243. top: parseFloat(gcssE.top) / parseFloat(gcssP.height),
  2244. height: parseFloat(gcssE.height) / parseFloat(gcssP.height)
  2245. };
  2246.  
  2247. let elm00 = [elmBound.left, elmBound.top];
  2248. let elm01 = [elmBound.left + elmBound.width, elmBound.top];
  2249. let elm10 = [elmBound.left, elmBound.top + elmBound.height];
  2250. let elm11 = [elmBound.left + elmBound.width, elmBound.top + elmBound.height];
  2251.  
  2252. return {
  2253. elm00,
  2254. elm01,
  2255. elm10,
  2256. elm11,
  2257. plw: elmBound.width,
  2258. plh: elmBound.height
  2259. };
  2260.  
  2261. },
  2262.  
  2263. fixNonBoxingVideoTipsPosition: function(tipsDom, player) {
  2264.  
  2265. if (!tipsDom || !player) return;
  2266.  
  2267. let ct = $hs.getCommonContainer(tipsDom, player)
  2268.  
  2269. if (!ct) return;
  2270.  
  2271. //relative
  2272.  
  2273. let elm00 = $hs.responsiveSizing(ct, player).elm00;
  2274.  
  2275. if (isNaN(elm00[0]) || isNaN(elm00[1])) {
  2276.  
  2277. [tipsDom.style.left, tipsDom.style.top] = [player.style.left, player.style.top];
  2278. //eg auto
  2279. } else {
  2280.  
  2281. let rlm00 = elm00.map(t => (t * 100).toFixed(2) + '%');
  2282. [tipsDom.style.left, tipsDom.style.top] = rlm00;
  2283.  
  2284. }
  2285.  
  2286. // absolute
  2287.  
  2288. let _offset = {
  2289. left: 10,
  2290. top: 15
  2291. };
  2292.  
  2293. let customOffset = {
  2294. left: _offset.left,
  2295. top: _offset.top
  2296. };
  2297. let p = tipsDom.getBoundingClientRect();
  2298. let q = player.getBoundingClientRect();
  2299. let currentPos = [p.left, p.top];
  2300.  
  2301. let targetPos = [q.left + player.offsetWidth * 0 + customOffset.left, q.top + player.offsetHeight * 0 + customOffset.top];
  2302.  
  2303. let mL = +tipsDom.style.marginLeft.replace('px', '') || 0;
  2304. if (isNaN(mL)) mL = 0;
  2305. let mT = +tipsDom.style.marginTop.replace('px', '') || 0;
  2306. if (isNaN(mT)) mT = 0;
  2307.  
  2308. let z1 = -(currentPos[0] - targetPos[0]);
  2309. let z2 = -(currentPos[1] - targetPos[1]);
  2310.  
  2311. if (z1 || z2) {
  2312.  
  2313. let y1 = z1 + mL;
  2314. let y2 = z2 + mT;
  2315.  
  2316. tipsDom.style.marginLeft = y1 + 'px';
  2317. tipsDom.style.marginTop = y2 + 'px';
  2318.  
  2319. }
  2320. },
  2321.  
  2322. playerTrigger: function(player, event) {
  2323. if (!player || !event) return
  2324. const pCode = event.code;
  2325. let keyAsm = (event.shiftKey ? SHIFT : 0) | ((event.ctrlKey || event.metaKey) ? CTRL : 0) | (event.altKey ? ALT : 0);
  2326.  
  2327.  
  2328. let vpid = player.getAttribute('_h5ppid') || null;
  2329. if (!vpid) return;
  2330. let playerConf = playerConfs[vpid]
  2331. if (!playerConf) return;
  2332.  
  2333. //shift + key
  2334. if (keyAsm == SHIFT) {
  2335. // 網頁FULLSCREEN
  2336. if (pCode === 'Enter') {
  2337. $hs.callFullScreenBtn()
  2338. return TERMINATE
  2339. } else if (pCode == 'KeyF') {
  2340. //change unsharpen filter
  2341.  
  2342. let resList = ["unsharpen3_05", "unsharpen3_10", "unsharpen5_05", "unsharpen5_10", "unsharpen9_05", "unsharpen9_10"]
  2343. let res = (prompt("Enter the unsharpen mask\n(" + resList.map(x => '"' + x + '"').join(', ') + ")", "unsharpen9_05") || "").toLowerCase();
  2344. if (resList.indexOf(res) < 0) res = ""
  2345. GM_setValue("unsharpen_mask", res)
  2346. for (const el of document.querySelectorAll('video[_h5p_uid_encrypted]')) {
  2347. if (el.style.filter == "" || el.style.filter) {
  2348. let filterStr1 = el.style.filter.replace(/\s*url\(\"#_h5p_unsharpen[\d\_]+\"\)/, '');
  2349. let filterStr2 = (res.length > 0 ? ' url("#_h5p_' + res + '")' : '')
  2350. el.style.filter = filterStr1 + filterStr2;
  2351. }
  2352. }
  2353. return TERMINATE
  2354.  
  2355. }
  2356. // 進入或退出畫中畫模式
  2357. else if (pCode == 'KeyP') {
  2358. $hs.pictureInPicture(player)
  2359.  
  2360. return TERMINATE
  2361. } else if (pCode == 'KeyR') {
  2362. if (player._h5player_lastrecord_ !== null && (player._h5player_lastrecord_ >= 0 || player._h5player_lastrecord_ <= 0)) {
  2363. $hs.setPlayProgress(player, player._h5player_lastrecord_)
  2364.  
  2365. return TERMINATE
  2366. }
  2367.  
  2368. } else if (pCode == 'KeyO') {
  2369. let _debug_h5p_logging_ch = false;
  2370. try {
  2371. Store._setItem('_h5_player_sLogging_', 1 - Store._getItem('_h5_player_sLogging_'))
  2372. _debug_h5p_logging_ = +Store._getItem('_h5_player_sLogging_') > 0;
  2373. _debug_h5p_logging_ch = true;
  2374. } catch (e) {
  2375.  
  2376. }
  2377. consoleLogF('_debug_h5p_logging_', !!_debug_h5p_logging_, 'changed', _debug_h5p_logging_ch)
  2378.  
  2379. if (_debug_h5p_logging_ch) {
  2380.  
  2381. return TERMINATE
  2382. }
  2383. } else if (pCode == 'KeyT') {
  2384. if (/^blob/i.test(player.currentSrc)) {
  2385. alert(`The current video is ${player.currentSrc}\nSorry, it cannot be opened in PotPlayer.`);
  2386. } else {
  2387. let confirm_res = confirm(`The current video is ${player.currentSrc}\nDo you want to open it in PotPlayer?`);
  2388. if (confirm_res) window.open('potplayer://' + player.currentSrc, '_blank');
  2389. }
  2390. return TERMINATE
  2391. }
  2392.  
  2393.  
  2394.  
  2395. let videoScale = playerConf.vFactor;
  2396.  
  2397. function tipsForVideoScaling() {
  2398.  
  2399. playerConf.vFactor = +videoScale.toFixed(1);
  2400.  
  2401. playerConf.cssTransform();
  2402. let tipsMsg = `視頻縮放率:${ +(videoScale * 100).toFixed(2) }%`
  2403. if (playerConf.translate.x) {
  2404. tipsMsg += `,水平位移:${playerConf.translate.x}px`
  2405. }
  2406. if (playerConf.translate.y) {
  2407. tipsMsg += `,垂直位移:${playerConf.translate.y}px`
  2408. }
  2409. $hs.tips(false);
  2410. $hs.tips(tipsMsg)
  2411.  
  2412.  
  2413. }
  2414.  
  2415. // 視頻畫面縮放相關事件
  2416.  
  2417. switch (pCode) {
  2418. // shift+X:視頻縮小 -0.1
  2419. case 'KeyX':
  2420. videoScale -= 0.1
  2421. if (videoScale < 0.1) videoScale = 0.1;
  2422. tipsForVideoScaling();
  2423. return TERMINATE
  2424. break
  2425. // shift+C:視頻放大 +0.1
  2426. case 'KeyC':
  2427. videoScale += 0.1
  2428. if (videoScale > 16) videoScale = 16;
  2429. tipsForVideoScaling();
  2430. return TERMINATE
  2431. break
  2432. // shift+Z:視頻恢復正常大小
  2433. case 'KeyZ':
  2434. videoScale = 1.0
  2435. playerConf.translate.x=0;
  2436. playerConf.translate.y=0;
  2437. tipsForVideoScaling();
  2438. return TERMINATE
  2439. break
  2440. case 'ArrowRight':
  2441. playerConf.translate.x += 10
  2442. tipsForVideoScaling();
  2443. return TERMINATE
  2444. break
  2445. case 'ArrowLeft':
  2446. playerConf.translate.x -= 10
  2447. tipsForVideoScaling();
  2448. return TERMINATE
  2449. break
  2450. case 'ArrowUp':
  2451. playerConf.translate.y -= 10
  2452. tipsForVideoScaling();
  2453. return TERMINATE
  2454. break
  2455. case 'ArrowDown':
  2456. playerConf.translate.y += 10
  2457. tipsForVideoScaling();
  2458. return TERMINATE
  2459. break
  2460.  
  2461. }
  2462.  
  2463. }
  2464. // 防止其它無關組合鍵衝突
  2465. if (!keyAsm) {
  2466. let kControl = null
  2467. let newPBR, oldPBR, nv;
  2468. switch (pCode) {
  2469. // 方向鍵右→:快進3秒
  2470. case 'ArrowRight':
  2471. $hs.tuneCurrentTime($hs.skipStep);
  2472. return TERMINATE;
  2473. break;
  2474. // 方向鍵左←:後退3秒
  2475. case 'ArrowLeft':
  2476. $hs.tuneCurrentTime(-$hs.skipStep);
  2477. return TERMINATE;
  2478. break;
  2479. // 方向鍵上↑:音量升高 1%
  2480. case 'ArrowUp':
  2481. if ((player.muted && player.volume === 0) && player._volume > 0) {
  2482.  
  2483. player.muted = false;
  2484. player.volume = player._volume;
  2485. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  2486. player.muted = false;
  2487. }
  2488. $hs.tuneVolume(0.01);
  2489. return TERMINATE;
  2490. break;
  2491. // 方向鍵下↓:音量降低 1%
  2492. case 'ArrowDown':
  2493.  
  2494. if ((player.muted && player.volume === 0) && player._volume > 0) {
  2495.  
  2496. player.muted = false;
  2497. player.volume = player._volume;
  2498. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  2499. player.muted = false;
  2500. }
  2501. $hs.tuneVolume(-0.01);
  2502. return TERMINATE;
  2503. break;
  2504. // 空格鍵:暫停/播放
  2505. case 'Space':
  2506. $hs.switchPlayStatus();
  2507. return TERMINATE;
  2508. break;
  2509. // 按鍵X:減速播放 -0.1
  2510. case 'KeyX':
  2511. if (player.playbackRate > 0) {
  2512. $hs.tips(false);
  2513. $hs.setPlaybackRate(player.playbackRate - 0.1);
  2514. return TERMINATE
  2515. }
  2516. break;
  2517. // 按鍵C:加速播放 +0.1
  2518. case 'KeyC':
  2519. if (player.playbackRate < 16) {
  2520. $hs.tips(false);
  2521. $hs.setPlaybackRate(player.playbackRate + 0.1);
  2522. return TERMINATE
  2523. }
  2524.  
  2525. break;
  2526. // 按鍵Z:正常速度播放
  2527. case 'KeyZ':
  2528. $hs.tips(false);
  2529. oldPBR = player.playbackRate;
  2530. if (oldPBR != 1.0) {
  2531. player._playbackRate_z = oldPBR;
  2532. newPBR = 1.0;
  2533. } else if (player._playbackRate_z != 1.0) {
  2534. newPBR = player._playbackRate_z || 1.0;
  2535. player._playbackRate_z = 1.0;
  2536. } else {
  2537. newPBR = 1.0
  2538. player._playbackRate_z = 1.0;
  2539. }
  2540. $hs.setPlaybackRate(newPBR, 1)
  2541. return TERMINATE
  2542. break;
  2543. // 按鍵F:下一幀
  2544. case 'KeyF':
  2545. if (window.location.hostname === 'www.netflix.com') return /* netflix 的F鍵是FULLSCREEN的意思 */
  2546. $hs.tips(false);
  2547. if (!player.paused) player.pause()
  2548. player.currentTime += +(1 / playerConf.fps)
  2549. $hs.tips('Jump to: Next frame')
  2550. return TERMINATE
  2551. break;
  2552. // 按鍵D:上一幀
  2553. case 'KeyD':
  2554. $hs.tips(false);
  2555. if (!player.paused) player.pause()
  2556. player.currentTime -= +(1 / playerConf.fps)
  2557. $hs.tips('Jump to: Previous frame')
  2558. return TERMINATE
  2559. break;
  2560. // 按鍵E:亮度增加%
  2561. case 'KeyE':
  2562. $hs.tips(false);
  2563. nv = playerConf.setFilter('brightness', (v) => v + 0.1);
  2564. $hs.tips('Brightness: ' + dround(nv * 100) + '%')
  2565. return TERMINATE
  2566. break;
  2567. // 按鍵W:亮度減少%
  2568. case 'KeyW':
  2569. $hs.tips(false);
  2570. nv = playerConf.setFilter('brightness', (v) => v > 0.1 ? v - 0.1 : 0);
  2571. $hs.tips('Brightness: ' + dround(nv * 100) + '%')
  2572. return TERMINATE
  2573. break;
  2574. // 按鍵T:對比度增加%
  2575. case 'KeyT':
  2576. $hs.tips(false);
  2577. nv = playerConf.setFilter('contrast', (v) => v + 0.1);
  2578. $hs.tips('Contrast: ' + dround(nv * 100) + '%')
  2579. return TERMINATE
  2580. break;
  2581. // 按鍵R:對比度減少%
  2582. case 'KeyR':
  2583. $hs.tips(false);
  2584. nv = playerConf.setFilter('contrast', (v) => v > 0.1 ? v - 0.1 : 0);
  2585. $hs.tips('Contrast: ' + dround(nv * 100) + '%')
  2586. return TERMINATE
  2587. break;
  2588. // 按鍵U:飽和度增加%
  2589. case 'KeyU':
  2590. $hs.tips(false);
  2591. nv = playerConf.setFilter('saturate', (v) => v + 0.1);
  2592. $hs.tips('Saturate: ' + dround(nv * 100) + '%')
  2593. return TERMINATE
  2594. break;
  2595. // 按鍵Y:飽和度減少%
  2596. case 'KeyY':
  2597. $hs.tips(false);
  2598. nv = playerConf.setFilter('saturate', (v) => v > 0.1 ? v - 0.1 : 0);
  2599. $hs.tips('Saturate: ' + dround(nv * 100) + '%')
  2600. return TERMINATE
  2601. break;
  2602. // 按鍵O:色相增加 1 度
  2603. case 'KeyO':
  2604. $hs.tips(false);
  2605. nv = playerConf.setFilter('hue-rotate', (v) => v + 1);
  2606. $hs.tips('Hue: ' + nv + ' deg')
  2607. return TERMINATE
  2608. break;
  2609. // 按鍵I:色相減少 1 度
  2610. case 'KeyI':
  2611. $hs.tips(false);
  2612. nv = playerConf.setFilter('hue-rotate', (v) => v - 1);
  2613. $hs.tips('Hue: ' + nv + ' deg')
  2614. return TERMINATE
  2615. break;
  2616. // 按鍵K:模糊增加 0.1 px
  2617. case 'KeyK':
  2618. $hs.tips(false);
  2619. nv = playerConf.setFilter('blur', (v) => v + 0.1);
  2620. $hs.tips('Blur: ' + nv + ' px')
  2621. return TERMINATE
  2622. break;
  2623. // 按鍵J:模糊減少 0.1 px
  2624. case 'KeyJ':
  2625. $hs.tips(false);
  2626. nv = playerConf.setFilter('blur', (v) => v > 0.1 ? v - 0.1 : 0);
  2627. $hs.tips('Blur: ' + nv + ' px')
  2628. return TERMINATE
  2629. break;
  2630. // 按鍵Q:圖像復位
  2631. case 'KeyQ':
  2632. $hs.tips(false);
  2633. playerConf.filterReset();
  2634. $hs.tips('Video Filter Reset')
  2635. return TERMINATE
  2636. break;
  2637. // 按鍵S:畫面旋轉 90 度
  2638. case 'KeyS':
  2639. $hs.tips(false);
  2640. playerConf.rotate += 90
  2641. if (playerConf.rotate % 360 === 0) playerConf.rotate = 0;
  2642. var _actionBox = $hs.trigger_actionBoxes.filter(actionBox => (player === actionBox || actionBox.contains(player)))[0];
  2643. if (_actionBox) {
  2644. if (!_actionBox.__originalWidth || !_actionBox.__originalHeight) {
  2645. _actionBox.__originalWidth = _actionBox.getBoundingClientRect().width;
  2646. _actionBox.__originalHeight = _actionBox.getBoundingClientRect().height;
  2647. }
  2648.  
  2649. if (_actionBox.__originalWidth && _actionBox.__originalHeight) {
  2650.  
  2651. var boxW = _actionBox.__originalWidth;
  2652. var boxH = _actionBox.__originalHeight;
  2653.  
  2654.  
  2655. if ((playerConf.rotate % 180) == 90) {
  2656. playerConf.mFactor = boxH / boxW;
  2657. } else {
  2658. playerConf.mFactor = 1.0;
  2659. }
  2660.  
  2661.  
  2662. playerConf.cssTransform();
  2663.  
  2664. $hs.tips('Rotation:' + playerConf.rotate + ' deg')
  2665.  
  2666. }
  2667.  
  2668. }
  2669. return TERMINATE
  2670. break;
  2671. // 按鍵迴車,進入FULLSCREEN
  2672. case 'Enter':
  2673. //t.callFullScreenBtn();
  2674. break;
  2675. case 'KeyN':
  2676. $hs.pictureInPicture(player);
  2677. return TERMINATE
  2678. break;
  2679. case 'KeyM':
  2680. //console.log('m!', player.volume,player._volume)
  2681.  
  2682. if (player.volume >= 0) {
  2683.  
  2684. if (!player.volume || player.muted) {
  2685.  
  2686. let newVol = player.volume || player._volume || 0.5;
  2687. if (player.volume !== newVol) {
  2688. player.volume = newVol;
  2689. }
  2690. player.muted = false;
  2691. $hs.tips(false);
  2692. $hs.tips('Mute: Off', undefined);
  2693.  
  2694. } else {
  2695.  
  2696. player._volume = player.volume;
  2697. player._volume_p = player.volume;
  2698. //player.volume = 0;
  2699. player.muted = true;
  2700. $hs.tips(false);
  2701. $hs.tips('Mute: On', undefined);
  2702.  
  2703. }
  2704.  
  2705. }
  2706.  
  2707. return TERMINATE
  2708. break;
  2709. default:
  2710. // 按1-4設置播放速度 49-52;97-100
  2711. let numKey = +(event.key)
  2712.  
  2713. if (numKey >= 1 && numKey <= 4) {
  2714. $hs.tips(false);
  2715. $hs.setPlaybackRate(numKey, 1)
  2716. return TERMINATE
  2717. }
  2718. }
  2719.  
  2720. }
  2721. },
  2722.  
  2723. handlerPlayerMouseMove: function(e) {
  2724. let player = $hs.player();
  2725. let rootNode = getRoot(player);
  2726.  
  2727. if (rootNode.pointerLockElement != player) {
  2728. player.removeEventListener('mousemove', $hs.handlerPlayerMouseMove)
  2729. return;
  2730. }
  2731.  
  2732. let movementX = e.movementX || e.mozMovementX || e.webkitMovementX || 0,
  2733. movementY = e.movementY || e.mozMovementY || e.webkitMovementY || 0;
  2734.  
  2735. player.__xyOffset.x += movementX
  2736. player.__xyOffset.y += movementY
  2737. let ld = Math.sqrt(screen.width * screen.width + screen.height * screen.height) * .1
  2738. let md = Math.sqrt(player.__xyOffset.x * player.__xyOffset.x + player.__xyOffset.y * player.__xyOffset.y);
  2739. if (md > ld) $hs.playerActionLeave();
  2740.  
  2741. },
  2742.  
  2743. playerActionEnter: function() {
  2744. let player = $hs.player();
  2745.  
  2746. if (player) {
  2747. player.__requestPointerLock__();
  2748. player.__xyOffset = {
  2749. x: 0,
  2750. y: 0
  2751. };
  2752. player.addEventListener('mousemove', $hs.handlerPlayerMouseMove)
  2753. }
  2754. },
  2755.  
  2756. playerActionLeave: function() {
  2757. let player = $hs.player();
  2758. if (player) player.removeEventListener('mousemove', $hs.handlerPlayerMouseMove)
  2759. document.__exitPointerLock__();
  2760. },
  2761.  
  2762. /* 按鍵響應方法 */
  2763. handlerRootKeyDownEvent: function(event) {
  2764. if ($hs.intVideoInitCount > 0) {} else {
  2765. return;
  2766. }
  2767. // DOM Standard - either .key or .code
  2768. // Here we adopt .code (physical layout)
  2769.  
  2770. let pCode = event.code;
  2771. if (typeof pCode != 'string') return;
  2772.  
  2773. let player = $hs.player()
  2774.  
  2775. if (!player) return; // no video tag
  2776.  
  2777. let rootNode = getRoot(player);
  2778.  
  2779. let keyAsm = (event.shiftKey ? SHIFT : 0) | ((event.ctrlKey || event.metaKey) ? CTRL : 0) | (event.altKey ? ALT : 0);
  2780.  
  2781. if (!keyAsm && pCode == 'Escape' && (document.fullscreenElement || rootNode.pointerLockElement)) {
  2782. setTimeout(() => {
  2783. if (document.fullscreenElement) {
  2784. document.exitFullscreen();
  2785. } else if (document.pointerLockElement) {
  2786. $hs.playerActionLeave();
  2787. }
  2788. }, 700);
  2789. return;
  2790. }
  2791.  
  2792. if (isInOperation(event.target)) return;
  2793.  
  2794. //console.log('K01')
  2795.  
  2796. /* 切換插件的可用狀態 */
  2797. // Shift-`
  2798. if (keyAsm == SHIFT && pCode == 'Backquote') {
  2799. $hs.enable = !$hs.enable;
  2800. $hs.tips(false);
  2801. if ($hs.enable) {
  2802. $hs.tips('啟用h5Player插件')
  2803. } else {
  2804. $hs.tips('禁用h5Player插件')
  2805. }
  2806. // 阻止事件冒泡
  2807. event.stopPropagation()
  2808. event.preventDefault()
  2809. return false
  2810. }
  2811. if (!$hs.enable) {
  2812. consoleLog('h5Player 已禁用~')
  2813. return false
  2814. }
  2815.  
  2816. /* 非全局模式下,不聚焦則不執行快捷鍵的操作 */
  2817.  
  2818. if (!keyAsm && pCode == 'Enter' && !isInOperation()) { //not NumberpadEnter
  2819. if (!rootNode.pointerLockElement && !document.fullscreenElement) {
  2820. if (rootNode.pointerLockElement != player) {
  2821. $hs.playerActionEnter();
  2822.  
  2823. // 阻止事件冒泡
  2824. event.stopPropagation()
  2825. event.preventDefault()
  2826. return false
  2827. }
  2828. } else if (rootNode.pointerLockElement && !document.fullscreenElement) {
  2829. $hs.playerActionLeave();
  2830.  
  2831. // 阻止事件冒泡
  2832. event.stopPropagation()
  2833. event.preventDefault()
  2834. return false
  2835. } else if (document.fullscreenElement) {
  2836. document.exitFullscreen();
  2837.  
  2838. // 阻止事件冒泡
  2839. event.stopPropagation()
  2840. event.preventDefault()
  2841. return false
  2842. }
  2843. }
  2844.  
  2845. let hv = (elm) => (elm && (elm == player || elm.contains(player)) ? elm : null);
  2846.  
  2847. let _checkingPass;
  2848.  
  2849. let plm = null;
  2850. if (rootNode.activeElement && !rootNode.pointerLockElement && !document.fullscreenElement) {
  2851. // the active element may or may not contains the player
  2852. // but the player box (player->parent->parent->...) shall contains the active element (and the player)
  2853. // so if the active element is inside the layoutbox, okay!
  2854. // ps. layoutbox may be much larger than the activeelement, then it is not overlapping case.
  2855.  
  2856. plm = rootNode.activeElement
  2857.  
  2858. //console.log('activeElement', plm)
  2859. _checkingPass = $hs.isInActiveMode(rootNode.activeElement, player);
  2860. } else {
  2861. plm = hv(rootNode.pointerLockElement) || hv(document.fullscreenElement)
  2862. _checkingPass = !!plm
  2863. }
  2864.  
  2865.  
  2866. if (_checkingPass) {
  2867.  
  2868. if (isInOperation()) return;
  2869.  
  2870.  
  2871. let res = $hs.playerTrigger(player, event)
  2872. if (res == TERMINATE) {
  2873. event.stopPropagation()
  2874. event.preventDefault()
  2875. return false
  2876. }
  2877.  
  2878. }
  2879. },
  2880. /* 設置播放進度 */
  2881. setPlayProgress: function(player, curTime) {
  2882. if (!player) return
  2883. if (!curTime || Number.isNaN(curTime)) return
  2884. player.currentTime = curTime
  2885. if (curTime > 3) {
  2886. $hs.tips(false);
  2887. $hs.tips(`Playback Jumps to ${$hs.toolFormatCT(curTime)}`)
  2888. if (player.paused) player.play();
  2889. }
  2890. }
  2891. }
  2892.  
  2893. function makeFilter(arr, k) {
  2894. let res = ""
  2895. for (const e of arr) {
  2896. for (const d of e) {
  2897. res += " " + (1.0 * d * k).toFixed(9)
  2898. }
  2899. }
  2900. return res.trim()
  2901. }
  2902.  
  2903. function _add_filter(rootElm) {
  2904. let rootView = null;
  2905. if (rootElm && rootElm.nodeType > 0) {
  2906. while (rootElm.parentNode && rootElm.parentNode.nodeType === 1) rootElm = rootElm.parentNode;
  2907. rootView = rootElm.querySelector('body') || rootElm;
  2908. } else {
  2909. return;
  2910. }
  2911.  
  2912. if (rootView && rootView.querySelector && !rootView.querySelector('#_h5player_section_')) {
  2913.  
  2914. let svgFilterElm = document.createElement('section')
  2915. svgFilterElm.style.position = 'fixed';
  2916. svgFilterElm.style.left = '-999px';
  2917. svgFilterElm.style.width = '1px';
  2918. svgFilterElm.style.top = '-999px';
  2919. svgFilterElm.style.height = '1px';
  2920. svgFilterElm.id = '_h5player_section_'
  2921. let svgXML = `
  2922. <svg id='_h5p_image' version="1.1" xmlns="http://www.w3.org/2000/svg">
  2923. <defs>
  2924. <filter id="_h5p_sharpen1">
  2925. <feConvolveMatrix filterRes="100 100" style="color-interpolation-filters:sRGB" order="3" kernelMatrix="` + `
  2926. -0.3 -0.3 -0.3
  2927. -0.3 3.4 -0.3
  2928. -0.3 -0.3 -0.3`.replace(/[\n\r]+/g, ' ').trim() + `" preserveAlpha="true"/>
  2929. </filter>
  2930. <filter id="_h5p_unsharpen1">
  2931. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  2932. makeFilter([
  2933. [1, 4, 6, 4, 1],
  2934. [4, 16, 24, 16, 4],
  2935. [6, 24, -476, 24, 6],
  2936. [4, 16, 24, 16, 4],
  2937. [1, 4, 6, 4, 1]
  2938. ], -1 / 256) + `" preserveAlpha="false"/>
  2939. </filter>
  2940. <filter id="_h5p_unsharpen3_05">
  2941. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="3" kernelMatrix="` +
  2942. makeFilter(
  2943. [
  2944. [0.025, 0.05, 0.025],
  2945. [0.05, -1.1, 0.05],
  2946. [0.025, 0.05, 0.025]
  2947. ], -1 / .8) + `" preserveAlpha="false"/>
  2948. </filter>
  2949. <filter id="_h5p_unsharpen3_10">
  2950. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="3" kernelMatrix="` +
  2951. makeFilter(
  2952. [
  2953. [0.05, 0.1, 0.05],
  2954. [0.1, -1.4, 0.1],
  2955. [0.05, 0.1, 0.05]
  2956. ], -1 / .8) + `" preserveAlpha="false"/>
  2957. </filter>
  2958. <filter id="_h5p_unsharpen5_05">
  2959. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  2960. makeFilter(
  2961. [
  2962. [0.025, 0.1, 0.15, 0.1, 0.025],
  2963. [0.1, 0.4, 0.6, 0.4, 0.1],
  2964. [0.15, 0.6, -18.3, 0.6, 0.15],
  2965. [0.1, 0.4, 0.6, 0.4, 0.1],
  2966. [0.025, 0.1, 0.15, 0.1, 0.025]
  2967. ], -1 / 12.8) + `" preserveAlpha="false"/>
  2968. </filter>
  2969. <filter id="_h5p_unsharpen5_10">
  2970. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  2971. makeFilter(
  2972. [
  2973. [0.05, 0.2, 0.3, 0.2, 0.05],
  2974. [0.2, 0.8, 1.2, 0.8, 0.2],
  2975. [0.3, 1.2, -23.8, 1.2, 0.3],
  2976. [0.2, 0.8, 1.2, 0.8, 0.2],
  2977. [0.05, 0.2, 0.3, 0.2, 0.05]
  2978. ], -1 / 12.8) + `" preserveAlpha="false"/>
  2979. </filter>
  2980. <filter id="_h5p_unsharpen9_05">
  2981. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="9" kernelMatrix="` +
  2982. makeFilter(
  2983. [
  2984. [0.025, 0.2, 0.7, 1.4, 1.75, 1.4, 0.7, 0.2, 0.025],
  2985. [0.2, 1.6, 5.6, 11.2, 14, 11.2, 5.6, 1.6, 0.2],
  2986. [0.7, 5.6, 19.6, 39.2, 49, 39.2, 19.6, 5.6, 0.7],
  2987. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  2988. [1.75, 14, 49, 98, -4792.7, 98, 49, 14, 1.75],
  2989. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  2990. [0.7, 5.6, 19.6, 39.2, 49, 39.2, 19.6, 5.6, 0.7],
  2991. [0.2, 1.6, 5.6, 11.2, 14, 11.2, 5.6, 1.6, 0.2],
  2992. [0.025, 0.2, 0.7, 1.4, 1.75, 1.4, 0.7, 0.2, 0.025]
  2993. ], -1 / 3276.8) + `" preserveAlpha="false"/>
  2994. </filter>
  2995. <filter id="_h5p_unsharpen9_10">
  2996. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="9" kernelMatrix="` +
  2997. makeFilter(
  2998. [
  2999. [0.05, 0.4, 1.4, 2.8, 3.5, 2.8, 1.4, 0.4, 0.05],
  3000. [0.4, 3.2, 11.2, 22.4, 28, 22.4, 11.2, 3.2, 0.4],
  3001. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3002. [2.8, 22.4, 78.4, 156.8, 196, 156.8, 78.4, 22.4, 2.8],
  3003. [3.5, 28, 98, 196, -6308.6, 196, 98, 28, 3.5],
  3004. [2.8, 22.4, 78.4, 156.8, 196, 156.8, 78.4, 22.4, 2.8],
  3005. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3006. [0.4, 3.2, 11.2, 22.4, 28, 22.4, 11.2, 3.2, 0.4],
  3007. [0.05, 0.4, 1.4, 2.8, 3.5, 2.8, 1.4, 0.4, 0.05]
  3008. ], -1 / 3276.8) + `" preserveAlpha="false"/>
  3009. </filter>
  3010. <filter id="_h5p_grey1">
  3011. <feColorMatrix values="0.3333 0.3333 0.3333 0 0
  3012. 0.3333 0.3333 0.3333 0 0
  3013. 0.3333 0.3333 0.3333 0 0
  3014. 0 0 0 1 0"/>
  3015. <feColorMatrix type="saturate" values="0" />
  3016. </filter>
  3017. </defs>
  3018. </svg>
  3019. `;
  3020.  
  3021. svgFilterElm.innerHTML = svgXML.replace(/[\r\n\s]+/g, ' ').trim();
  3022.  
  3023. rootView.appendChild(svgFilterElm);
  3024. }
  3025.  
  3026. }
  3027.  
  3028. /**
  3029. * 某些網頁用了attachShadow closed mode,需要open才能獲取video標籤,例如百度雲盤
  3030. * 解決參考:
  3031. * https://developers.google.com/web/fundamentals/web-components/shadowdom?hl=zh-cn#closed
  3032. * https://stackoverflow.com/questions/54954383/override-element-prototype-attachshadow-using-chrome-extension
  3033. */
  3034.  
  3035. const initForShadowRoot = async (shadowRoot) => {
  3036. try {
  3037. if (shadowRoot && shadowRoot.nodeType > 0 && 'querySelectorAll' in shadowRoot) {
  3038. $hs.bindDocEvents(shadowRoot);
  3039. new VideoListener(shadowRoot).listen(handlerVideoFound)
  3040. shadowRoots.push(shadowRoot)
  3041. }
  3042. } catch (e) {
  3043. console.log('h5Player: initForShadowRoot failed')
  3044. }
  3045. }
  3046.  
  3047. function hackAttachShadow() { // attachShadow - DOM Standard
  3048.  
  3049. let _prototype_ = window && window.HTMLElement ? window.HTMLElement.prototype : null;
  3050. if (_prototype_ && typeof _prototype_.attachShadow == 'function') {
  3051.  
  3052. let _attachShadow = _prototype_.attachShadow
  3053.  
  3054. hackAttachShadow = null
  3055. _prototype_.attachShadow = function() {
  3056. let arg = [...arguments];
  3057. if (arg[0] && arg[0].mode) arg[0].mode = 'open';
  3058. let shadowRoot = _attachShadow.apply(this, arg);
  3059. initForShadowRoot(shadowRoot);
  3060. return shadowRoot
  3061. };
  3062.  
  3063. _prototype_.attachShadow.toString = () => _attachShadow.toString();
  3064.  
  3065. }
  3066.  
  3067. }
  3068.  
  3069. function hackCreateShadowRoot() { // createShadowRoot - Deprecated
  3070.  
  3071. let _prototype_ = window && window.HTMLElement ? window.HTMLElement.prototype : null;
  3072. if (_prototype_ && typeof _prototype_.createShadowRoot == 'function') {
  3073.  
  3074. let _createShadowRoot = _prototype_.createShadowRoot;
  3075.  
  3076. hackCreateShadowRoot = null
  3077. _prototype_.createShadowRoot = function() {
  3078. const shadowRoot = _createShadowRoot.apply(this, arguments);
  3079. initForShadowRoot(shadowRoot);
  3080. return shadowRoot;
  3081. };
  3082. _prototype_.createShadowRoot.toString = () => _createShadowRoot.toString();
  3083.  
  3084. }
  3085. }
  3086.  
  3087. /* 事件偵聽hack */
  3088. function hackEventListener() {
  3089. if (!window.EventTarget) return;
  3090. const eventTargetPrototype = window.EventTarget.prototype;
  3091. let _addEventListener = eventTargetPrototype.addEventListener;
  3092. let _removeEventListener = eventTargetPrototype.removeEventListener;
  3093. if (typeof _addEventListener == 'function' && typeof _removeEventListener == 'function') {} else return;
  3094. hackEventListener = null;
  3095.  
  3096. class Listeners {
  3097.  
  3098. constructor(dom, type) {
  3099. this._dom = dom;
  3100. this._type = type;
  3101. this.listenersCount = 0;
  3102. this.hashList = {};
  3103. }
  3104. get baseFunc() {
  3105. if (this._dom && this._type) {
  3106. return this._dom['on' + this._type];
  3107. }
  3108. }
  3109. get funcCount() {
  3110. if (this._dom && this._type) {
  3111. return (typeof this.baseFunc == 'function') * 1 + (this.listenersCount || 0)
  3112. }
  3113. }
  3114.  
  3115.  
  3116. }
  3117.  
  3118.  
  3119.  
  3120. let hackedEvtCount = 0;
  3121.  
  3122.  
  3123. function timeupdateHack() {
  3124.  
  3125.  
  3126. let evtTarget = this;
  3127.  
  3128. if (typeof arguments[1] != 'function' || typeof arguments[0] != 'string') throw '';
  3129. const type = arguments[0];
  3130. const fn = arguments[1];
  3131. if (type != 'timeupdate') throw '';
  3132.  
  3133. //console.log('timeupdate detection')
  3134.  
  3135.  
  3136.  
  3137.  
  3138. let tupId = evtTarget.getAttribute('_h5p_tup_');
  3139.  
  3140. if (tupId === null) { // 0 1 2 ...
  3141.  
  3142. const fakeTimeUpdateEvent = [];
  3143.  
  3144. evtTarget.setAttribute('_h5p_tup_', tupId = timeupdateStore.length); // 0, 1, 2...
  3145. timeupdateStore.push({
  3146. videoElement: evtTarget,
  3147. eventHandlersCapture: [],
  3148. eventHandlersBubbles: [],
  3149. eventHandlersRunner: [],
  3150. fakeTimeUpdateEvent,
  3151. lastTime: -1
  3152. });
  3153.  
  3154. const gn = (event) => {
  3155. console.log('h5Player - boost timeupdate is enabled')
  3156. fakeTimeUpdateEvent.push(event);
  3157. };
  3158. _addEventListener.call(evtTarget, type, gn, {
  3159. capture: true,
  3160. passive: true,
  3161. once: true
  3162. })
  3163.  
  3164.  
  3165. } else {
  3166. tupId = +tupId;
  3167.  
  3168. }
  3169.  
  3170.  
  3171. const tupConf = timeupdateStore[tupId];
  3172. let useCapture = false;
  3173. const thirdArg = arguments[2];
  3174. switch (typeof thirdArg) {
  3175. case 'boolean':
  3176. if (thirdArg === true) useCapture = true;
  3177. break;
  3178. case 'object':
  3179. if (thirdArg && thirdArg.capture === true) useCapture = true;
  3180. break;
  3181. }
  3182. if (useCapture) tupConf.eventHandlersCapture.push(fn);
  3183. else tupConf.eventHandlersBubbles.push(fn);
  3184. tupConf.eventHandlersRunner = tupConf.eventHandlersCapture.concat(tupConf.eventHandlersBubbles);
  3185.  
  3186.  
  3187. if (!$hs._onceTimeUpdateHack) {
  3188. $hs._onceTimeUpdateHack = true;
  3189. if (!_endlessloop) _endlessloop = new AFLooperArray();
  3190. let opts = _endlessloop.appendLoop(handle.afBoostTimeUpdate)
  3191. opts.loopingStart();
  3192. }
  3193.  
  3194.  
  3195. return _addEventListener.apply(this, arguments)
  3196.  
  3197. }
  3198.  
  3199. let watchList = ['timeupdate', 'click'];
  3200.  
  3201. eventTargetPrototype.addEventListener = function() {
  3202.  
  3203. let arg = arguments
  3204. let type = arg[0]
  3205. let listener = arg[1]
  3206.  
  3207. if (!this || !(this instanceof EventTarget) || typeof type != 'string' || typeof listener != 'function') {
  3208. return _addEventListener.apply(this, arguments)
  3209. //unknown bug?
  3210. }
  3211.  
  3212. if (watchList.indexOf(type) < 0) return _addEventListener.apply(this, arguments);
  3213.  
  3214.  
  3215. let res;
  3216. if (type == 'timeupdate' && this.nodeType == 1 && this.nodeName == "VIDEO" && isSupportAdvancedEventListener()) {
  3217. res = timeupdateHack.apply(this, arg)
  3218. } else {
  3219. res = _addEventListener.apply(this, arg)
  3220. }
  3221.  
  3222.  
  3223. let boolCapture = (arg[2] && typeof arg[2] == 'object') ? (arg[2].capture === true) : (arg[2] === true)
  3224.  
  3225. this._listeners = this._listeners || {}
  3226. this._listeners[type] = this._listeners[type] || new Listeners(this, type)
  3227. let uid = 100000 + (++hackedEvtCount);
  3228. let listenerObj = {
  3229. listener,
  3230. options: arg[2],
  3231. uid: uid,
  3232. useCapture: boolCapture
  3233. }
  3234. this._listeners[type].hashList[uid + ''] = listenerObj;
  3235. this._listeners[type].listenersCount++;
  3236. return res;
  3237. }
  3238. // hack removeEventListener
  3239. eventTargetPrototype.removeEventListener = function() {
  3240.  
  3241. let arg = arguments
  3242. let type = arg[0]
  3243. let listener = arg[1]
  3244.  
  3245. if (!this || !(this instanceof EventTarget) || typeof type != 'string' || typeof listener != 'function') {
  3246. return _removeEventListener.apply(this, arguments)
  3247. //unknown bug?
  3248. }
  3249.  
  3250. if (watchList.indexOf(type) < 0) return _removeEventListener.apply(this, arguments);
  3251.  
  3252. let boolCapture = (arg[2] && typeof arg[2] == 'object') ? (arg[2].capture === true) : (arg[2] === true)
  3253.  
  3254. let defaultRemoval = true;
  3255. if (this._listeners && this._listeners[type] && this._listeners[type].hashList) {
  3256. let hashList = this._listeners[type].hashList
  3257. for (let k in hashList) {
  3258. if (hashList[k].listener === listener && hashList[k].useCapture == boolCapture) {
  3259. delete hashList[k];
  3260. this._listeners[type].listenersCount--;
  3261. break;
  3262. }
  3263. }
  3264. }
  3265. if (defaultRemoval) return _removeEventListener.apply(this, arg);
  3266. }
  3267. eventTargetPrototype.addEventListener.toString = () => _addEventListener.toString();
  3268. eventTargetPrototype.removeEventListener.toString = () => _removeEventListener.toString();
  3269.  
  3270.  
  3271. }
  3272.  
  3273. function handlerVideoFound(video) {
  3274.  
  3275. if (!video) return;
  3276. if (video.getAttribute('_h5ppid')) return;
  3277. let alabel = video.getAttribute('aria-label')
  3278. if (alabel && typeof alabel == "string" && alabel.toUpperCase() == "GIF") return;
  3279.  
  3280.  
  3281. consoleLog('handlerVideoFound', video)
  3282.  
  3283. $hs.intVideoInitCount = ($hs.intVideoInitCount || 0) + 1;
  3284. let vpid = 'h5p-' + $hs.intVideoInitCount
  3285. consoleLog(' - HTML5 Video is detected -', `Number of Videos: ${$hs.intVideoInitCount}`)
  3286. if ($hs.intVideoInitCount === 1) $hs.fireGlobalInit();
  3287. video.setAttribute('_h5ppid', vpid)
  3288.  
  3289.  
  3290. playerConfs[vpid] = new PlayerConf();
  3291. playerConfs[vpid].domElement = video;
  3292. playerConfs[vpid].domActive = DOM_ACTIVE_FOUND;
  3293.  
  3294. let rootNode = getRoot(video);
  3295.  
  3296. if (rootNode.host) $hs.getPlayerBlockElement(video); // shadowing
  3297. let rootElm = rootNode.querySelector('head') || rootNode.querySelector('html') || document.documentElement //48763
  3298. _add_filter(rootElm) // either main document or shadow node
  3299.  
  3300. video.addEventListener('loadedmetadata', $hs.handlerVideoLoadedMetaData, true);
  3301.  
  3302. }
  3303.  
  3304.  
  3305. ResizeODM.__init__();
  3306.  
  3307. hackAttachShadow()
  3308. hackCreateShadowRoot()
  3309. hackEventListener()
  3310.  
  3311.  
  3312. window.addEventListener('message', $hs.handlerWinMessage, false);
  3313. $hs.bindDocEvents(document);
  3314. new VideoListener(document.documentElement).listen(handlerVideoFound)
  3315.  
  3316. let windowsLD = (function() {
  3317. let ls_res = [];
  3318. try {
  3319. ls_res = [!!window.localStorage, !!window.top.localStorage];
  3320. } catch (e) {}
  3321. try {
  3322. let winp = window;
  3323. let winc = 0;
  3324. while (winp !== window.top && winp && ++winc) winp = winp.parentNode;
  3325. ls_res.push(winc);
  3326. } catch (e) {}
  3327. return ls_res;
  3328. })();
  3329.  
  3330. consoleLogF('- h5Player Plugin Loaded -', ...windowsLD)
  3331.  
  3332. function isInCrossOriginFrame() {
  3333. let result = true;
  3334. try {
  3335. if (window.top.localStorage || window.top.location.href) result = false;
  3336. } catch (e) {}
  3337. return result
  3338. }
  3339.  
  3340. if (isInCrossOriginFrame()) consoleLog('cross origin frame detected');
  3341.  
  3342.  
  3343. })();