// ==UserScript== // @name HTML5 Video Player Enhance // @version 2.9.0a2 // @description To enhance the functionality of HTML5 Video Player (h5player) supporting all websites using shortcut keys similar to PotPlayer. // @author CY Fung // @match http://*/* // @match https://*/* // @run-at document-start // @require https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js // @require https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.3.2/math.js // @namespace https://greasyfork.org/users/371179 // @grant GM_getValue // @grant GM_setValue // @downloadURL none // ==/UserScript== /** * Remarks * fullscreen and pointerLock buggy in shadowRoot * Space Pause not success * shift F key issue **/ (function $$($hs) { 'use strict'; if (!document || !document.documentElement) return window.requestAnimationFrame($$); let _debug_h5p_logging_ = false; try { _debug_h5p_logging_ = +window.localStorage.getItem('_h5_player_sLogging_') > 0 } catch (e) { } const SHIFT = 1; const CTRL = 2; const ALT = 4; const TERMINATE = 0x842; const _sVersion_ = 1817; const str_postMsgData = '__postMsgData__' const _ell_timeupdatefs = []; let _endlessloop = null; const isIframe = (window.top !== window.self && window.top && window.self); window.__MutationObserver = window.MutationObserver || window.WebKitMutationObserver || null; const shadowRoots = []; const getRoot = (elm) => elm.getRootNode instanceof Function ? elm.getRootNode() : (elm.ownerDocument || null); const isShadowRoot = (elm) => (elm && ('host' in elm)) ? elm.nodeType == 11 && !!elm.host && elm.host.nodeType == 1 : null; //instanceof ShadowRoot Element.prototype.__matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s) { var matches = ('getRootNode' in this ? this.getRootNode() : this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) {} return i > -1; }; Element.prototype.__requestPointerLock = Element.prototype.requestPointerLock || Element.prototype.mozRequestPointerLock || Element.prototype.webkitRequestPointerLock; // Ask the browser to release the pointer Document.prototype.__exitPointerLock = Document.prototype.exitPointerLock || Document.prototype.mozExitPointerLock || Document.prototype.webkitExitPointerLock; // built-in hash - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest async function digestMessage(message) { return window.sha256(message) } //https://gist.github.com/joyrexus/7304146 // requestAnimationFrame() shim by Paul Irish let requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element) { return window.setTimeout(callback, 1000 / 60); }; let cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || clearInterval; const dround = function(x) { return ~~(x + .5) } const jsonStringify_replacer = function(key, val) { // convert RegExp to string if (val && (val instanceof Element || val instanceof Document)) { return toString.call(val); } else if (name === 'st12131r') { // return undefined; // remove from result } else { return val; // return as is } }; const jsonParse = function() { try { return JSON.parse.apply(this, arguments) } catch (e) {} return null; } const jsonStringify = function() { let value = arguments[0]; let replacer = arguments[1]; replacer = jsonStringify_replacer; let space = arguments[2]; let arg = [value, replacer, space] if (arguments.length <= 2) arg.length = 2; try { return JSON.stringify.apply(this, arg) } catch (e) {} return null; } function _postMsg() { //async is needed. or error handling for postMessage const [win, tag, ...data] = arguments; if (typeof tag == 'string') { let postMsgObj = { tag, passing: true, winOrder: _postMsg.a } try { var k = 'msg-' + (+new Date) win.document[str_postMsgData] = win.document[str_postMsgData] || {} win.document[str_postMsgData][k] = data; //direct postMsgObj.str = k; postMsgObj.stype = 1; } catch (e) {} if (!postMsgObj.stype) { postMsgObj.str = jsonStringify({ d: data }) if (postMsgObj.str && postMsgObj.str.length) postMsgObj.stype = 2; } if (!postMsgObj.stype) { postMsgObj.str = "" + data; postMsgObj.stype = 0; } win.postMessage(postMsgObj, '*'); } } function postMsg() { let win = window; var a = 0; while (win = win.parent) { _postMsg.a = ++a; _postMsg(win, ...arguments) if (win == top) break; } } function lowerKeyCode(keyCode) { if (keyCode >= 65 && keyCode <= 90) keyCode += 32; return keyCode } function whichTransitionEvent(type) { if (whichTransitionEvent['_result_' + type]) return whichTransitionEvent['_result_' + type] var el = document.createElement("fakeelement"); const capital = (x) => x[0].toUpperCase() + x.substr(1); const capitalType = capital(type); const transitions = { [type]: `${type}end`, [`O${capitalType}`]: `o${capitalType}End`, [`Moz${capitalType}`]: `${type}end`, [`Webkit${capitalType}`]: `webkit${capitalType}End`, [`MS${capitalType}`]: `MS${capitalType}End` } for (var styleProp in transitions) { if (el.style[styleProp] !== undefined) { return (whichTransitionEvent['_result_' + type] = transitions[styleProp]); } } } class ResizeODM { static __init__() { this.__resizerCount__ = 0; this.__resizeListeners__ = {}; } constructor() { let rm = this; ResizeODM.__resizerCount__++; let rpid = "rpid-" + ResizeODM.__resizerCount__; ResizeODM.__resizeListeners__[rpid] = []; rm._resizer_listeners = ResizeODM.__resizeListeners__[rpid]; var odm = document.createElement('object'); odm.setAttribute('_resizer_odm_', rpid); odm.setAttribute('style', 'display: block; position: absolute; top: -300vh; left: -300vw; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;'); odm.onload = ResizeODM.objectLoad; odm.type = 'text/html'; odm.data = 'about:blank'; rm.odm = odm; rm.rpid = rpid; rm.odm.__rm__ = rm; } static find(rsElm) { if (!rsElm) return null; let odm = [...rsElm.querySelectorAll('object[_resizer_odm_]')].filter(elm => elm.parentNode == rsElm)[0]; if (!odm) return null; return odm.__rm__ || null; } static resizeListener(e) { let odv = e.target || e.srcElement; let rm = odv._resizer_rm; if (rm.__resizeRAF__) cancelAnimationFrame(rm.__resizeRAF__); rm.__resizeRAF__ = requestAnimationFrame(function() { rm.__resizeRAF__ = 0; rm._resizer_listeners.forEach(fn => fn.call(rm, e)); }); } static objectLoad(e) { let odm = this; let rm = odm.__rm__; let odv = odm.contentDocument.defaultView odv._resizer_rm = rm; rm.odv = odv; odv.onresize = ResizeODM.resizeListener; } resizeElement() { return this.odm.parentNode; } // ResizeODM.relativeParent(rsElm); relativeParent(rsElm, existingnode = null) { let odm = this.odm; rsElm = rsElm || odm.parentNode; let rpid = this.rpid; //if (getComputedStyle(rsElm).position == 'static') rsElm.style.position = 'relative'; rsElm.insertBefore(odm, existingnode); } listen(fn) { this._resizer_listeners.push(fn); } unlisten(fn) { this._resizer_listeners.splice(this._resizer_listeners.indexOf(fn), 1); } remove() { this._resizer_listeners.length = 0; this.odv.onresize = null; this.odm.onload = null; } } function isInOperation(elm) { let elmInFocus = elm || document.activeElement; if (!elmInFocus) return false; let res1 = elmInFocus.__matches( 'a[href],link[href],button,input:not([type="hidden"]),select,textarea,iframe,frame,menuitem,[draggable],[contenteditable]' ); return res1; } class SimEvent extends Event { constructor(typeArg, eventInit, customType) { super(typeArg, eventInit); this.__customType = customType; } get type() { return this.__customType; } } const _evtOB_create = function(_EVT, d) { let keys = Object.keys(_EVT.prototype); let res = function Event(m) { let o = this keys.forEach(k => (k in m && !(k in o)) ? o[k] = m[k] : null); Object.assign(o, d); } return res } _evtOB_create._timeupdate = function() { if (_evtOB_create.__timeupdate) return _evtOB_create.__timeupdate; let res = _evtOB_create(Event, { isTrusted: true, type: 'timeupdate' }) return _evtOB_create.__timeupdate = res; } const sim_arg_1_fn = function(f, evtOB) { return function(e) { let o = new evtOB(e); let arg = [...arguments]; arg[0] = o; return f.apply(this, arg); } } const fn_toString = (f, n = 50) => { let s = (f + ""); if (s.length > 2 * n + 5) { s = s.substr(0, n) + ' ... ' + s.substr(-n); } return s }; class EndlessLoop { constructor() { this.activeLoopsCount = 0; this.loops = []; this.cid = 0; this._loop = () => { if (!this.cid) return; //cancelled this.loops.forEach(loop => loop.opt.looping ? loop.fn(loop.opt) : null); this.cid = requestAnimationFrame(this._loop); } } loopStart() { this.looping = true; this.cid = requestAnimationFrame(this._loop); } loopStop() { if (this.cid) cancelAnimationFrame(this.cid); this.cid = 0; this.looping = false; } append(fn) { const opt = new EndlessLoopOpts(this); this.loops.push({ fn, opt }); return opt; } } class EndlessLoopOpts { constructor(ell) { this._looping = false; this._ell = ell; } _loop() { this._ell.loops.some(loop => loop.opt === this && loop.opt.looping ? (loop.fn(loop.opt), true) : null); } get looping() { return this._looping; } loopingStart() { if (this._looping === false) { this._looping = true; this._ell.activeLoopsCount++; if (this._ell.activeLoopsCount == 1) this._ell.loopStart(); } } loopingStop() { if (this._looping === true) { this._looping = false; this._ell.activeLoopsCount--; if (this._ell.activeLoopsCount == 0) this._ell.loopStop(); } } } function consoleLog() { if (!_debug_h5p_logging_) return; if (isIframe) postMsg('consoleLog', ...arguments); else console.log.apply(console, arguments); } function consoleLogF() { if (isIframe) postMsg('consoleLog', ...arguments); else console.log.apply(console, arguments); } const Store = { prefix: '_h5_player', save: function(k, v) { if (!Store.available()) return false; if (typeof v != 'string') return false; Store.LS.setItem(Store.prefix + k, v) let sk = fn_toString(k + "", 30); let sv = fn_toString(v + "", 30); consoleLog(`localStorage Saved "${sk}" = "${sv}"`) return true; }, read: function(k) { if (!Store.available()) return false; let v = Store.LS.getItem(Store.prefix + k) let sk = fn_toString(k + "", 30); let sv = fn_toString(v + "", 30); consoleLog(`localStorage Read "${sk}" = "${sv}"`); return v; }, remove: function(k) { if (!Store.available()) return false; Store.LS.removeItem(Store.prefix + k) let sk = fn_toString(k + "", 30); consoleLog(`localStorage Removed "${sk}"`) return true; }, clearInvalid: function(sVersion) { if (!Store.available()) return false; //let sVersion=1814; if (+Store.read('_sVersion_') < sVersion) { Object.keys(localStorage).filter(s => s.indexOf(Store.prefix) === 0).forEach(key => window.localStorage.removeItem(key)) Store.save('_sVersion_', sVersion + '') return 2; } return 1; }, available: function() { if (Store.LS) return true; if (!window) return false; const localStorage = window.localStorage; if (!localStorage) return false; if (typeof localStorage != 'object') return false; if (!('getItem' in localStorage)) return false; if (!('setItem' in localStorage)) return false; Store.LS = localStorage; return true; } } const domTool = { nopx: (x) => +x.replace('px', ''), cssWH: function(m) { let r = getComputedStyle(m, null); let c = (x) => +x.replace('px', ''); return { w: m.offsetWidth || c(r.width), h: m.offsetHeight || c(r.height) } }, _cssWH: function(m, r) { let c = (x) => +x.replace('px', ''); return { w: m.offsetWidth || c(r.width), h: m.offsetHeight || c(r.height) } }, _isActionBox_1: function(vEl, pEl) { let vElCSS = domTool.cssWH(vEl); let vElCSSw = vElCSS.w; let vElCSSh = vElCSS.h; let vElx = vEl; let res = []; let mLevel = 0; if (vEl && pEl && vEl != pEl && pEl.contains(vEl)) { while (vElx && vElx != pEl) { vElx = vElx.parentNode; let vElx_css = null; if (isShadowRoot(vElx)) {} else { vElx_css = getComputedStyle(vElx, null); let vElx_wp = domTool.nopx(vElx_css.paddingLeft) + domTool.nopx(vElx_css.paddingRight) vElCSSw += vElx_wp let vElx_hp = domTool.nopx(vElx_css.paddingTop) + domTool.nopx(vElx_css.paddingBottom) vElCSSh += vElx_hp } res.push({ level: ++mLevel, padW: vElCSSw, padH: vElCSSh, elm: vElx, css: vElx_css }) } } // in the array, each item is the parent of video player res.vEl_cssWH = vElCSS return res; }, _isActionBox: function(vEl, walkRes, pEl_idx) { function absDiff(w1, w2, h1, h2) { let w = (w1 - w2), h = h1 - h2; return [(w > 0 ? w : -w), (h > 0 ? h : -h)] } function midPoint(rect) { return { x: (rect.left + rect.right) / 2, y: (rect.top + rect.bottom) / 2 } } let parentCount = walkRes.length; if (pEl_idx >= 0 && pEl_idx < parentCount) {} else { return; } let pElr = walkRes[pEl_idx] if (!pElr.css) { //shadowRoot return true; } let pEl = pElr.elm; //prevent activeElement==body let pElCSS = domTool._cssWH(pEl, pElr.css); //let vElCSS=walkRes.vEl_cssWH; //check prediction of parent dimension let d1v = absDiff(pElCSS.w, pElr.padW, pElCSS.h, pElr.padH) let d1x = d1v[0] < 10 let d1y = d1v[1] < 10; if (d1x && d1y) return true; //both edge along the container - fit size if (!d1x && !d1y) return false; //no edge along the container - body contain the video element, fixed width&height //case: youtube video fullscreen //check centre point let pEl_rect = pEl.getBoundingClientRect() let vEl_rect = vEl.getBoundingClientRect() let pEl_center = midPoint(pEl_rect) let vEl_center = midPoint(vEl_rect) let d2v = absDiff(pEl_center.x, vEl_center.x, pEl_center.y, vEl_center.y); let d2x = d2v[0] < 10; let d2y = d2v[1] < 10; return (d2x && d2y); }, getRect: function(element) { let rect = element.getBoundingClientRect(); let scroll = domTool.getScroll(); return { pageX: rect.left + scroll.left, pageY: rect.top + scroll.top, screenX: rect.left, screenY: rect.top }; }, isHalfFullClient: function(element) { var client = domTool.getClient(); var rect = domTool.getRect(element); if ((Math.abs(client.width - element.offsetWidth) < 21 && rect.screenX < 20) || (Math.abs(client.height - element.offsetHeight) < 21 && rect.screenY < 10)) { if (Math.abs(element.offsetWidth / 2 + rect.screenX - client.width / 2) < 10 && Math.abs(element.offsetHeight / 2 + rect.screenY - client.height / 2) < 10) { return true; } else { return false; } } else { return false; } }, isAllFullClient: function(element) { var client = domTool.getClient(); var rect = domTool.getRect(element); if ((Math.abs(client.width - element.offsetWidth) < 21 && rect.screenX < 20) && (Math.abs(client.height - element.offsetHeight) < 21 && rect.screenY < 10)) { return true; } else { return false; } }, getScroll: function() { return { left: document.documentElement.scrollLeft || document.body.scrollLeft, top: document.documentElement.scrollTop || document.body.scrollTop }; }, getClient: function() { return { width: document.compatMode == 'CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth, height: document.compatMode == 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight }; }, addStyle: //GM_addStyle, function(css, head) { if (!head) { let _doc = document.documentElement; head = _doc.querySelector('head') || _doc.querySelector('html') || _doc; } let doc = head.ownerDocument; let style = doc.createElement('style'); style.type = 'text/css'; let node = doc.createTextNode(css); style.appendChild(node); head.appendChild(style); //console.log(document.head,style,'add style') return style; }, eachParentNode: function(dom, fn) { let parent = dom.parentNode while (parent) { let isEnd = fn(parent, dom) parent = parent.parentNode if (isEnd) { break } } }, hideDom: function hideDom(selector) { let dom = document.querySelector(selector) if (dom) { requestAnimationFrame(function() { dom.style.opacity = 0; dom.style.transform = 'translate(-9999px)'; dom = null; }) } } }; const handle = { timeupdatef_ell: async function(opts) { let video = opts.video; let time = video.currentTime; if (time !== opts.lastTime) { opts.lastTime = time; video.dispatchEvent(opts.evt); } }, playbackELL: async (opts) => { let qTime = +new Date; if (qTime >= opts.pTime) { opts.pTime = qTime + opts.timeDelta; //prediction of next Interval opts.playbackRecord() } }, playbackRecord: async function() { //this refer to endless's opts let player = this.player; let _uid = this.player_uid; //_h5p_uid_encrypted if (!_uid) return; let shallSave = true; let currentTimeToSave = ~~player.currentTime; if (this._lastSave == currentTimeToSave) shallSave = false; if (shallSave) { this._lastSave = currentTimeToSave //console.log('aasas',this.player_uid, shallSave, '_play_progress_'+_uid, currentTimeToSave) Store.save('_play_progress_' + _uid, jsonStringify({ 't': currentTimeToSave })) } }, pr_updateUID: function() { //this refer to endless's opts let player = this.player; let _uid = player.getAttribute('_h5p_uid_encrypted') || '' if (!_uid) return false; this.player_uid = _uid; return true; }, }; class VideoListener { usable = false; observer = null; asyncCheckFunc = null; cid_asyncCheckFunc = 0; constructor(shadowRoot) { this.rootElement = shadowRoot || window.document; if (this.rootElement && !this.rootElement.__videoListenerEnabled__) { this.rootElement.__videoListenerEnabled__ = true; this.usable = true; } } delayCheck() { if (this.cid_asyncCheckFunc) cancelAnimationFrame(this.cid_asyncCheckFunc); this.cid_asyncCheckFunc = requestAnimationFrame(this.asyncCheckFunc); } listen(fn) { if (!this.usable) return; this.init_observer(); this.fn = fn; // single function this.checkOnce(); this.checkEach(); } init_observer() { if (this.observer) return; this.asyncCheckFunc = () => this.checkEach(); this.observer = new window.__MutationObserver(this.mutationObserverCallback); this.observer.observe(this.rootElement, { childList: true, subtree: true }) this.observer.videoListener = this; } mutationObserverCallback(mutations, observer) { if (mutations && 'length' in mutations) { var requireChecking = Array.prototype.some.call(mutations, mutation => { let addedNodes = mutation.addedNodes; if (!addedNodes || !addedNodes.length) return false; return Array.prototype.some.call(addedNodes, addedNode => { return (addedNode.nodeName == 'VIDEO' || addedNode.childElementCount > 0) }); }); if (requireChecking) observer.videoListener.delayCheck(); } } async checkOnce() { var treeWalker = document.createTreeWalker( document.documentElement, NodeFilter.SHOW_ELEMENT, { acceptNode: (node) => (node.shadowRoot ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP) } ); var nodeList = []; while (treeWalker.nextNode()) nodeList.push(treeWalker.currentNode); nodeList.forEach(node => this._checkRoot(node.shadowRoot)) } async checkEach() { this._checkRoot(this.rootElement); } _checkRoot(shadowRoot) { let videos = shadowRoot.querySelectorAll('VIDEO'); //shadowRoot don't have getElementsByTagName for (let video of videos) { if (!video._onceMutationReady) { video._onceMutationReady = true; video.setAttribute('h5p_observed', '1'); this.fn(video); } } } } const _keyMap = function(arr, obj) { let res = {}; arr.forEach((key) => (res[key] = key.charCodeAt(0))); Object.assign(res, obj); return res; } $hs = { pictureInPicture: function(videoElm) { if (document.pictureInPictureElement) { document.exitPictureInPicture(); } else if ('requestPictureInPicture' in videoElm) { videoElm.requestPictureInPicture() } else { $hs.tips('PIP is not supported.'); } }, bindEventsToElm: function(elm, funcProp) { if (elm._action_eventsBind !== funcProp) { elm._action_eventsBind = funcProp; elm[funcProp]('mouseenter', $hs.handlerElementMouseEnter) elm[funcProp]('mousedown', $hs.handlerElementMouseDown) elm[funcProp]('dblclick', $hs.handlerElementDblClick, true) elm[funcProp]('wheel', $hs.handlerElementWheelTuneVolume); } }, handlerVideoPlaying: function(evt) { $hs._actionBoxSet(evt.target); $hs.playerInstance = evt.target; $hs.onVideoTriggering(); if (!$hs.enable) return $hs.tips(false); let player = this; if (player._isThisPausedBefore_) consoleLog('resumed') let _pausedbefore_ = player._isThisPausedBefore_ if (player.playpause_cid) { clearTimeout(player.playpause_cid); player.playpause_cid = 0; } let _last_paused = player._last_paused player._last_paused = player.paused if (_last_paused === !player.paused) { player.playpause_cid = setTimeout(() => { if (player.paused === !_last_paused && !player.paused && _pausedbefore_) { $hs.tips('Playback resumed', undefined, 2500) } }, 90) } /* 播放的時候進行相關同步操作 */ if (!player._record_continuous) { /* 同步之前設定的播放速度 */ $hs.setPlaybackRate() if (!_endlessloop) _endlessloop = new EndlessLoop(); player._record_continuous = _endlessloop.append(handle.playbackELL); player._record_continuous._lastSave = -999; player._record_continuous.timeDelta = 2000; player._record_continuous.player = player player._record_continuous.playbackRecord = handle.playbackRecord; player._record_continuous.updateUID = handle.pr_updateUID; player._record_continuous.playingWithRecording = function() { let player = this.player; if (!player.paused && this.updateUID() && !this.looping) { this.pTime = 0; this.loopingStart(); } } } player._record_continuous.playingWithRecording(player); //try to start recording _ell_timeupdatefs.forEach(opts => opts.loopingStart()); player._isThisPausedBefore_ = false; }, handlerVideoPause: function() { if (!$hs.enable) return $hs.tips(false); let player = this; consoleLog('pause') player._isThisPausedBefore_ = true; let _last_paused = player._last_paused player._last_paused = player.paused if (player.playpause_cid) { clearTimeout(player.playpause_cid); player.playpause_cid = 0; } if (_last_paused === !player.paused) { player.playpause_cid = setTimeout(() => { if (player.paused === !_last_paused && player.paused) { $hs.tips('Playback paused', undefined, 2500) } }, 90) } if (player._record_continuous && player._record_continuous.looping) { player._record_continuous.playbackRecord(); //playbackRecord once before stopping //handle.playbackRecord; player._record_continuous.loopingStop(); } _ell_timeupdatefs.forEach(opts => opts.loopingStop()); }, handlerVideoVolumeChange: function() { if (this.volume >= 0) {} else { return; } let cVol = this.volume; let cMuted = this.muted; if (cVol === this._volume_p && cMuted === this._muted_p) { // nothing changed } else if (cVol === this._volume_p && cMuted !== this._muted_p) { // muted changed } else { // cVol != pVol // only volume changed let shallShowTips = this._volume >= 0; //prevent initialization if (!cVol) { this.muted = true; } else if (cMuted) { this.muted = false; this._volume = cVol; } else if (!cMuted) { this._volume = cVol; } consoleLog('volume changed') let player = this; if (shallShowTips) $hs.tips('Volume: ' + dround(player.volume * 100) + '%', undefined, 3000) } this._volume_p = cVol this._muted_p = cMuted }, handlerVideoLoadedMetaData: function() { consoleLog('video size', this.videoWidth + ' x ' + this.videoHeight); let player = this let vpid = player.getAttribute('_h5ppid') || null; if (!vpid || !player.currentSrc) return; if ($hs.varSrcList[vpid] != player.currentSrc) { $hs.varSrcList[vpid] = player.currentSrc; $hs.videoSrcFound(player); $hs._actionBoxSet(player); } if (!player._onceVideoLoaded) { player._onceVideoLoaded = true; player.addEventListener('playing', $hs.handlerVideoPlaying) player.addEventListener('pause', $hs.handlerVideoPause); player.addEventListener("volumechange", $hs.handlerVideoVolumeChange); } }, handlerElementMouseEnter: function(evt) { let player = evt.target; if (player.nodeName != "VIDEO") player = player.querySelector('video[_h5ppid]'); if (player) $hs._actionBoxSet(player); }, handlerElementMouseDown: function(evt) { let player = this; //evt.target may be something else if (player.nodeName != "VIDEO") player = player.querySelector('video[_h5ppid]'); if (!player) return; let { layoutBox, wPlayer } = $hs.getLayoutBox(player); if (layoutBox && layoutBox.contains(evt.target)) { $hs.makeFocus(player, evt) } }, handlerElementWheelTuneVolume: function(evt) { if (!evt.shiftKey) return; if (evt.deltaY) { let player = $hs.player(); if (!$hs || !player) return; if (evt.deltaY > 0) { if ((player.muted && player.volume === 0) && player._volume > 0) { player.muted = false; player.volume = player._volume; } else if (player.muted && (player.volume > 0 || !player._volume)) { player.muted = false; } $hs.tuneVolume(-0.05) evt.stopPropagation() evt.preventDefault() return false } else if (evt.deltaY < 0) { if ((player.muted && player.volume === 0) && player._volume > 0) { player.muted = false; player.volume = player._volume; } else if (player.muted && (player.volume > 0 || !player._volume)) { player.muted = false; } $hs.tuneVolume(+0.05) evt.stopPropagation() evt.preventDefault() return false } } }, handlerElementDblClick: function(evt) { consoleLog('dblclick', this, evt.target) if (this.nodeName == 'VIDEO' && evt.target.nodeName == 'VIDEO' && this.getAttribute('_h5p_actionbox_')) { return; } if (document.readyState != "complete") return; let elm = (evt.target != this && this.contains(evt.target)) ? this : evt.target; // www.tucao.one ; evt.target = bullet curtain; this = actionbox let vpid = elm.getAttribute('_h5p_actionbox_') || elm.getAttribute('_h5ppid') || null; if (!vpid) return; let player = getRoot(elm).querySelector(`[_h5ppid="${vpid}"]`); $hs._actionBoxSet(player) $hs.playerInstance = player $hs.onVideoTriggering() $hs.callFullScreenBtn(); evt.stopPropagation() evt.preventDefault() return false }, handlerDocFocusOut: function(e) { let doc = this; $hs.focusFxLock = true; requestAnimationFrame(function() { $hs.focusFxLock = false; if (!$hs.enable) $hs.tips(false); else if (!doc.hasFocus() && $hs.player() && !$hs.isLostFocus) { $hs.isLostFocus = true; consoleLog('doc.focusout') //$hs.tips('focus is lost', -1); } }); }, handlerDocFocusIn: function(e) { let doc = this; if ($hs.focusFxLock) return; requestAnimationFrame(function() { if ($hs.focusFxLock) return; if (!$hs.enable) $hs.tips(false); else if (doc.hasFocus() && $hs.player() && $hs.isLostFocus) { $hs.isLostFocus = false; consoleLog('doc.focusin') $hs.tips(false); } }); }, handlerWinMessage: async function(e) { let tag, ed; if (typeof e.data == 'object' && typeof e.data.tag == 'string') { tag = e.data.tag; ed = e.data } else { return; } let msg = null, success = 0; switch (tag) { case 'consoleLog': var msg_str = ed.str; var msg_stype = ed.stype; if (msg_stype === 1) { msg = (document[str_postMsgData] || {})[msg_str] || []; success = 1; } else if (msg_stype === 2) { msg = jsonParse(msg_str); if (msg && msg.d) { success = 2; msg = msg.d; } } else { msg = msg_str } var p = (ed.passing && ed.winOrder) ? [' | from win-' + ed.winOrder] : []; if (success) { console.log(...msg, ...p) //document[ed.data]=null; // also delete the information } else { console.log('msg--', msg, ...p, ed); } break; } }, isInActiveMode: function(activeElm, player) { if (activeElm == player) { return true; } let _checkingPass = false; let { layoutBox, wPlayer } = $hs.getLayoutBox(player); if (layoutBox && layoutBox.parentNode && layoutBox.contains(activeElm)) { let rpid = player.getAttribute('_h5ppid') || "NULL"; let actionBox = layoutBox.parentNode.querySelector(`[_h5p_actionbox_="${rpid}"]`); //the box can be layoutBox if (actionBox && actionBox.contains(activeElm)) _checkingPass = true; } return _checkingPass }, toolCheckFullScreen: function(doc) { if (typeof doc.fullScreen == 'boolean') return doc.fullScreen; if (typeof doc.webkitIsFullScreen == 'boolean') return doc.webkitIsFullScreen; if (typeof doc.mozFullScreen == 'boolean') return doc.mozFullScreen; return null; }, toolFormatCT: function(u) { let w = Math.round(u, 0) let a = w % 60 w = (w - a) / 60 let b = w % 60 w = (w - b) / 60 let str = ("0" + b).substr(-2) + ":" + ("0" + a).substr(-2); if (w) str = w + ":" + str return str }, /* 提示文本的字號 */ fontSize: 16, enable: true, playerInstance: null, translate: { x: 0, y: 0 }, playbackRate: 1, /* 快進快退步長 */ skipStep: 5, /* 獲取當前播放器的實例 */ player: function() { return $hs.playerInstance || $hs.getPlayerList()[0] }, /* 每個網頁可能存在的多個video播放器 */ getPlayerList: function() { let list = [...document.querySelectorAll('video')]; shadowRoots.forEach(shadowRoot => list.push(...shadowRoot.querySelectorAll('video'))); return list }, getPlayerWrapDom: function() { let player = $hs.player() if (!player || !player.getBoundingClientRect) return let wrapDom = null let layoutBox = player.getBoundingClientRect() if (layoutBox.width && layoutBox.height) { domTool.eachParentNode(player, function(parent) { if (parent === document || !parent.getBoundingClientRect) return let parentBox = parent.getBoundingClientRect() if (parentBox.width === layoutBox.width && parentBox.height === layoutBox.height) { wrapDom = parent } }) } return wrapDom }, makeFocus: function(player, evt) { setTimeout(function() { let rpid = player.getAttribute('_h5ppid'); let actionBox = getRoot(player).querySelector(`[_h5p_actionbox_="${rpid}"]`); //console.log('p',rpid, player,actionBox,document.activeElement) if (actionBox && actionBox != document.activeElement && !actionBox.contains(document.activeElement)) { consoleLog('make focus on', actionBox) actionBox.focus(); } }, 300) }, _actionBoxSet: function(player) { if (!player) return null; let vpid = player.getAttribute('_h5ppid'); if (!vpid) return null; let { layoutBox, wPlayer } = $hs.getLayoutBox(player) if (!layoutBox) return null; let walkRes = domTool._isActionBox_1(player, layoutBox); let parentCount = walkRes.length; let actionBox = null; if (parentCount - 1 >= 0 && domTool._isActionBox(player, walkRes, parentCount - 1)) { actionBox = walkRes[parentCount - 1].elm; } else if (parentCount - 2 >= 0 && domTool._isActionBox(player, walkRes, parentCount - 2)) { actionBox = walkRes[parentCount - 2].elm; } else { actionBox = player; } if (actionBox && actionBox.getAttribute('_h5p_actionbox_') != vpid) { consoleLog('D-1', actionBox); for (let elm_of_vpid of getRoot(player).querySelectorAll(`[_h5p_actionbox_="${vpid}"]`)) { //change of parentNode elm_of_vpid.removeAttribute('_h5p_actionbox_'); $hs.bindEventsToElm(elm_of_vpid, 'removeEventListener'); } actionBox.setAttribute('_h5p_actionbox_', vpid); if (!actionBox.hasAttribute('tabindex')) actionBox.setAttribute('tabindex', '-1'); $hs.bindEventsToElm(actionBox, 'addEventListener'); let elm = player; while (elm && elm != actionBox) { if (elm.hasAttribute('tabindex')) $hs.bindEventsToElm(elm, 'addEventListener'); elm = elm.parentNode } } return actionBox; }, videoSrcFound: function(player) { // src loaded if (!player) return; let vpid = player.getAttribute('_h5ppid') || null; if (!vpid || !player.currentSrc) return; player._isThisPausedBefore_ = false; player.removeAttribute('_h5p_uid_encrypted'); if (player._record_continuous) player._record_continuous._lastSave = -999; //first time must save let uid_A = location.pathname.replace(/[^\d+]/g, '') + '.' + location.search.replace(/[^\d+]/g, ''); let _uid = location.hostname.replace('www.', '').toLowerCase() + '!' + location.pathname.toLowerCase() + 'A' + uid_A + 'W' + player.videoWidth + 'H' + player.videoHeight + 'L' + (player.duration << 0); digestMessage(_uid).then(function(_uid_encrypted) { let d = +new Date; let recordedTime = null; ; (function() { //read the last record only; let k1 = '_h5_player_play_progress_'; let k1n = '_play_progress_'; let k2 = _uid_encrypted; let k3 = k1 + k2; let k3n = k1n + k2; let m2 = Object.keys(localStorage).filter(key => key.substr(0, k3.length) == k3); //all progress records for this video let m2v = m2.map(keyName => +(keyName.split('+')[1] || '0')) let m2vMax = Math.max(0, ...m2v) if (!m2vMax) recordedTime = null; else { let _json_recordedTime = null; _json_recordedTime = Store.read(k3n + '+' + m2vMax); if (!_json_recordedTime) _json_recordedTime = {}; else _json_recordedTime = jsonParse(_json_recordedTime); if (typeof _json_recordedTime == 'object') recordedTime = _json_recordedTime; else recordedTime = null; recordedTime = typeof recordedTime == 'object' ? recordedTime.t : recordedTime; if (typeof recordedTime == 'number' && (+recordedTime >= 0 || +recordedTime <= 0)) { } else if (typeof recordedTime == 'string' && recordedTime.length > 0 && (+recordedTime >= 0 || +recordedTime <= 0)) { recordedTime = +recordedTime } else { recordedTime = null } } if (recordedTime !== null) { player._h5player_lastrecord_ = recordedTime; } else { player._h5player_lastrecord_ = null; } if (player._h5player_lastrecord_ > 5) { consoleLog('last record playing', player._h5player_lastrecord_); setTimeout(function() { let tmp_player = $hs.playerInstance; $hs.playerInstance = player; $hs.tips(`Press Shift-R to restore Last Playback: ${$hs.toolFormatCT(player._h5player_lastrecord_)}`, 5000, 4000) $hs.playerInstance = tmp_player }, 1000) } })(); // delay the recording by 5.4s => prevent ads or mis operation setTimeout(function() { let k1 = '_h5_player_play_progress_'; let k1n = '_play_progress_'; let k2 = _uid_encrypted; let k3 = k1 + k2; let k3n = k1n + k2; //re-read all the localStorage keys let m1 = Object.keys(localStorage).filter(key => key.substr(0, k1.length) == k1); //all progress records in this site let p = m1.length + 1; let m2 = m1.filter(key => key.substr(0, k3.length) == k3) //all progress records for this video m2.forEach(key => localStorage.removeItem(key), p--); //remove previous record for the current video if (recordedTime !== null) { Store.save(k3n + '+' + d, jsonStringify({ 't': recordedTime })) //prevent loss of last record } const _record_max_ = 48; const _record_keep_ = 26; if (p > _record_max_) { //exisiting 48 records for one site; //keep only 26 records const comparator = (a, b) => (a.t < b.t ? -1 : a.t > b.t ? 1 : 0); m1 .map(keyName => ({ keyName, t: +(keyName.split('+')[1] || '0') })) .sort(comparator) .slice(0, -_record_keep_) .forEach((item) => localStorage.removeItem(item.keyName)); consoleLog(`stored progress: reduced to ${_record_keep_}`) } player.setAttribute('_h5p_uid_encrypted', _uid_encrypted + '+' + d); //try to start recording if (player._record_continuous) player._record_continuous.playingWithRecording(); }, 5400); }) }, bindKeyEvents: function(rootNode) { if (!rootNode._onceBindedKeyEvents) { rootNode._onceBindedKeyEvents = true; rootNode.addEventListener('keydown', $hs.handlerRootKeyDownEvent, true) document._debug_rootNode_ = rootNode; } }, fireGlobalInit: function() { /* 綁定鍵盤事件 */ if ($hs.intVideoInitCount != 1) return; if (!$hs.varSrcList) $hs.varSrcList = {}; $hs.isLostFocus = null; consoleLog('keydown bind'); try { //iframe may not be able to control top window //error; just ignore with asycn let topDoc = window.top && window.top.document ? window.top.document : null; if (topDoc) { topDoc.addEventListener('focusout', $hs.handlerDocFocusOut, true) topDoc.addEventListener('focusin', $hs.handlerDocFocusIn, true) } } catch (e) {} Store.clearInvalid(_sVersion_) }, onVideoTriggering: function() { // initialize a single video player - h5Player.playerInstance /** * 初始化播放器實例 */ let player = $hs.playerInstance if (!player) return let vpid = player.getAttribute('_h5ppid'); if (!vpid) return; let firstTime = !!$hs.initTips() if (firstTime) { // first time to trigger this player if (!player.hasAttribute('playsinline')) player.setAttribute('playsinline', 'playsinline'); if (!player.hasAttribute('x-webkit-airplay')) player.setAttribute('x-webkit-airplay', 'deny'); if (!player.hasAttribute('preload')) player.setAttribute('preload', 'auto'); player.style['image-rendering'] = 'crisp-edges'; $hs.filter.reset() $hs.playbackRate = $hs.getPlaybackRate() } }, getPlaybackRate: function() { let playbackRate = Store.read('_playback_rate_') || $hs.playbackRate return Number(Number(playbackRate).toFixed(1)) }, getLayoutBox: function(player, skipPlayer) { //without checkActiveBox, just a DOM for you to append tipsDom var layoutBox = null, wPlayer = null if (!player || !player.offsetHeight || !player.offsetWidth) { return { layoutBox, wPlayer }; } if (!player.parentNode) { return { layoutBox, wPlayer }; } function search_nodes() { wPlayer = player; // NOT NULL layoutBox = wPlayer.parentNode; // NOT NULL while (layoutBox.parentNode && layoutBox.nodeType == 1 && layoutBox.offsetHeight == 0) { wPlayer = layoutBox; // NOT NULL layoutBox = layoutBox.parentNode; // NOT NULL } while (layoutBox.parentNode && layoutBox.nodeType == 1 && layoutBox.offsetHeight < player.offsetHeight) { wPlayer = layoutBox; // NOT NULL layoutBox = layoutBox.parentNode; // NOT NULL } } search_nodes(); if (layoutBox.nodeType == 11) { //shadowRoot without html and body let shadowChild, shadowElm_container, shadowElm_head, shadowElm_html; let rootNode = getRoot(player); if (rootNode.querySelectorAll('html,body').length < 2) { shadowElm_container = player.ownerDocument.createElement('BODY') rootNode.insertBefore(shadowElm_container, rootNode.firstChild) while (shadowChild = shadowElm_container.nextSibling) shadowElm_container.appendChild(shadowChild); shadowElm_head = rootNode.insertBefore(player.ownerDocument.createElement('HEAD'), shadowElm_container) shadowElm_html = rootNode.insertBefore(player.ownerDocument.createElement('HTML'), shadowElm_head) shadowElm_container.setAttribute('style', 'padding:0;margin:0;border:0; box-sizing: border-box;') shadowElm_html.setAttribute('style', 'padding:0;margin:0;border:0; box-sizing: border-box;') shadowElm_html.appendChild(shadowElm_head) shadowElm_html.appendChild(shadowElm_container) } search_nodes(); } //condition: //!layoutBox.parentNode || layoutBox.nodeType != 1 || layoutBox.offsetHeight > player.offsetHeight // layoutBox is a node contains