HTML5 Video Player Enhance

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

目前为 2021-06-19 提交的版本。查看 最新版本

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