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