From 392a13ddc2edb7c06ff8d6880ca83116ebb44eaf Mon Sep 17 00:00:00 2001 From: Toil <62353659+ilyhalight@users.noreply.github.com> Date: Wed, 7 Aug 2024 03:34:50 +0300 Subject: [PATCH] auto hide vot button on init --- changelog.md | 1 + dist/vot-min.user.js | 2 +- dist/vot.user.js | 1 + src/index.js | 1 + 4 files changed, 4 insertions(+), 1 deletion(-) diff --git a/changelog.md b/changelog.md index cddfe605..ab0b159f 100644 --- a/changelog.md +++ b/changelog.md @@ -6,6 +6,7 @@ # 1.6.x +- Теперь, после инициализации кнопка скрывается, а не ждет пока вы куда-нибудь нажмете/наведетесь на видео - Исправлена ошибка из-за которой кнопка не исчезала на Pornhub (#700) - Добавлена поддержка Poketube (#726) - Исправлена работа Peertube diff --git a/dist/vot-min.user.js b/dist/vot-min.user.js index 4a4176fd..a5c007fe 100644 --- a/dist/vot-min.user.js +++ b/dist/vot-min.user.js @@ -221,7 +221,7 @@ >${n}`,this.subtitlesContainer))}processTokens(t){if(t.at(-1).alignRange.end<=this.maxLength)return t;let e=[],o=[],n=0;for(const i of t)n+=i.text.length,o.push(i),n>this.maxLength&&(e.push(this.trimChunk(o)),o=[],n=0);o.length&&e.push(this.trimChunk(o));const i=1e3*this.video.currentTime;return e.find((t=>t[0].startMs{const o=this.highlightWords&&(e>t.startMs+t.durationMs/2||e>t.startMs-100&&t.startMs+t.durationMs/2-e<275);return It`${t.text.replace("\\n","
")}
`}))}debounce(t,e){let o;return(...n)=>{clearTimeout(o),o=setTimeout((()=>t.apply(this,n)),e)}}release(){document.removeEventListener("mousedown",this.onMouseDownBound),document.removeEventListener("mouseup",this.onMouseUpBound),document.removeEventListener("mousemove",this.onMouseMoveBound),this.video?.removeEventListener("timeupdate",this.onTimeUpdateBound),this.resizeObserver.disconnect(),this.subtitlesContainer.remove()}}o("./node_modules/requestidlecallback-polyfill/index.js");class Ue{constructor(){this.listeners=new Set}hasListener(t){return this.listeners.has(t)}dispatchToListener(t,...e){try{t(...e)}catch(t){console.error("[VOT]",t)}}addListener(t){if(this.hasListener(t))throw new Error("[VOT] The listener has already been added.");this.listeners.add(t)}removeListener(t){if(!this.hasListener(t))throw new Error("[VOT] The listener has not been added yet.");this.listeners.delete(t)}dispatch(...t){for(const e of Array.from(this.listeners))this.dispatchToListener(e,...t)}}function je(t){return Array.from(t).flatMap((t=>t instanceof HTMLVideoElement?[t]:t instanceof HTMLElement?Array.from(t.querySelectorAll("video")):t.shadowRoot?Array.from(t.shadowRoot.querySelectorAll("video")):[]))}const We=/advertise|promo|sponsor|banner|commercial|preroll|midroll|postroll|ad-container|sponsored/i;const Ge=t.getParser(window.navigator.userAgent).getResult(),Je=["Violentmonkey","FireMonkey","Greasemonkey","AdGuard","OrangeMonkey"],Ye=["playing","ratechange","play","waiting","pause"];function Ke(t,e){return t.map((t=>({label:H.get("langs")[t]??t.toUpperCase(),value:t,selected:e===t})))}class Ze{translateFromLang="en";translateToLang=R;timer;videoData="";firstPlay=!0;audio=new Audio;audioContext=new(window.AudioContext||window.webkitAudioContext);gainNode=this.audioContext.createGain();hls=D();votClient;videoTranslations=[];videoTranslationTTL=7200;cachedTranslation;downloadTranslationUrl=null;downloadSubtitlesUrl=null;autoRetry;streamPing;votOpts;volumeOnStart;tempOriginalVolume;tempVolume;firstSyncVolume=!0;subtitlesList=[];subtitlesListVideoId=null;videoLastSrcObject=null;dragging;constructor(t,e,o){I.log("[VideoHandler] add video:",t,"container:",e,this),this.video=t,this.container=e,this.site=o,this.stopTranslationBound=this.stopTranslation.bind(this),this.handleVideoEventBound=this.handleVideoEvent.bind(this),this.changeOpacityOnEventBound=this.changeOpacityOnEvent.bind(this),this.resetTimerBound=this.resetTimer.bind(this),this.init()}async translateVideoImpl(t,e,o,n=null){if(clearTimeout(this.autoRetry),I.log(t,`Translate video (requestLang: ${e}, responseLang: ${o})`),await it(this.site,this.video)!==t.videoId)return null;try{const i=await this.votClient.translateVideo({videoData:t,requestLang:e,responseLang:o,translationHelp:n});if(I.log("Translate video result",i),i.translated&&i.remainingTime<1)return I.log("Video translation finished with this data: ",i),i;await this.updateTranslationErrorMsg(i.remainingTime>0?function(t){const e=Math.floor(t/60),o=Math.floor(t%60);return e>=60?H.get("translationTakeMoreThanHour"):1===e||0===e&&o>0?H.get("translationTakeAboutMinute"):11!==e&&e%10==1?H.get("translationTakeApproximatelyMinute2").replace("{0}",e):![12,13,14].includes(e)&&[2,3,4].includes(e%10)?H.get("translationTakeApproximatelyMinute").replace("{0}",e):H.get("translationTakeApproximatelyMinutes").replace("{0}",e)}(i.remainingTime):i.message??H.get("translationTakeFewMinutes"))}catch(t){return console.error("[VOT] Failed to translate video",t),await this.updateTranslationErrorMsg(t.data?.message??t),null}return new Promise((i=>{const a=this.subtitlesList.some((t=>"yandex"===t.source))?2e4:3e4;this.autoRetry=setTimeout((async()=>{const a=await this.translateVideoImpl(t,e,o,n);(!a||a.translated&&a.remainingTime<1)&&i(a)}),a)}))}async translateStreamImpl(t,e,o){if(clearTimeout(this.autoRetry),I.log(t,`Translate stream (requestLang: ${e}, responseLang: ${o})`),await it(this.site,this.video)!==t.videoId)return null;try{const n=await this.votClient.translateStream({videoData:t,requestLang:e,responseLang:o});if(I.log("Translate stream result",n),!n.translated&&10===n.interval)return await this.updateTranslationErrorMsg(H.get("translationTakeFewMinutes")),new Promise((i=>{this.autoRetry=setTimeout((async()=>{const n=await this.translateStreamImpl(t,e,o);n&&!n.translated&&10===n.interval||i(n)}),1e3*n.interval)}));if(n.message)throw I.log(`Stream translation aborted! Message: ${n.message}`),new rt("streamNoConnectionToServer");if(!n.result)throw I.log("Failed to find translation result! Data:",n),new rt("audioNotReceived");return I.log("Stream translated successfully. Running...",n),this.streamPing=setInterval((async()=>{I.log("Ping stream translation",n.pingId),this.votClient.pingStream({pingId:n.pingId})}),1e3*n.interval),n}catch(t){return console.error("[VOT] Failed to translate stream",t),await this.updateTranslationErrorMsg(t.data?.message??t),null}}async autoTranslate(){if(this.site.host,this.firstPlay&&1===this.data.autoTranslate&&this.videoData.videoId){this.firstPlay=!1;try{await this.translateExecutor(this.videoData.videoId)}catch(t){console.error("[VOT]",t),this.transformBtn("error","VOTLocalizedError"===t?.name?t.localizedMessage:t)}}}async init(){if(this.initialized)return;const t={autoTranslate:_.get("autoTranslate",0,!0),dontTranslateLanguage:_.get("dontTranslateLanguage",R),dontTranslateYourLang:_.get("dontTranslateYourLang",1,!0),autoSetVolumeYandexStyle:_.get("autoSetVolumeYandexStyle",1,!0),autoVolume:_.get("autoVolume",ee,!0),buttonPos:_.get("buttonPos","default"),showVideoSlider:_.get("showVideoSlider",1,!0),syncVolume:_.get("syncVolume",0,!0),subtitlesMaxLength:_.get("subtitlesMaxLength",300,!0),highlightWords:_.get("highlightWords",0,!0),subtitlesFontSize:_.get("subtitlesFontSize",20,!0),subtitlesOpacity:_.get("subtitlesOpacity",20,!0),responseLanguage:_.get("responseLanguage",R),defaultVolume:_.get("defaultVolume",100,!0),audioProxy:_.get("audioProxy",0,!0),showPiPButton:_.get("showPiPButton",0,!0),translateAPIErrors:_.get("translateAPIErrors",1,!0),translationService:_.get("translationService",oe),detectService:_.get("detectService",ne),m3u8ProxyHost:_.get("m3u8ProxyHost",Qt),translateProxyEnabled:_.get("translateProxyEnabled",0,!0),proxyWorkerHost:_.get("proxyWorkerHost",Xt),audioBooster:_.get("audioBooster",0,!0)};this.data=Object.fromEntries(await Promise.all(Object.entries(t).map((async([t,e])=>[t,await e])))),console.log("[db] data from db: ",this.data),0===this.data.translateProxyEnabled&&GM_info?.scriptHandler&&Je.includes(GM_info.scriptHandler)&&(this.data.translateProxyEnabled=1,await _.set("translateProxyEnabled",1),I.log("translateProxyEnabled",this.data.translateProxyEnabled)),I.log("Extension compatibility passed..."),this.votOpts={headers:1===this.data.translateProxyEnabled?{}:{"sec-ch-ua":null,"sec-ch-ua-mobile":null,"sec-ch-ua-platform":null},fetchFn:q,hostVOT:te,host:1===this.data.translateProxyEnabled?this.data.proxyWorkerHost:"api.browser.yandex.ru"},this.votClient=new(1===this.data.translateProxyEnabled?ut:dt)(this.votOpts),this.subtitlesWidget=new He(this.video,this.container,this.site),this.subtitlesWidget.setMaxLength(this.data.subtitlesMaxLength),this.subtitlesWidget.setHighlightWords(this.data.highlightWords),this.subtitlesWidget.setFontSize(this.data.subtitlesFontSize),this.subtitlesWidget.setOpacity(this.data.subtitlesOpacity),this.audio.crossOrigin="anonymous",this.gainNode.connect(this.audioContext.destination),this.audioSource=this.audioContext.createMediaElementSource(this.audio),this.audioSource.connect(this.gainNode),this.initUI(),this.initUIEvents();const e=!this.video.src&&!this.video.currentSrc&&!this.video.srcObject;this.votButton.container.hidden=e,e?this.votMenu.container.hidden=!0:(this.videoData=await this.getVideoData(),this.setSelectMenuValues(this.videoData.detectedLanguage,this.data.responseLanguage??"ru")),await this.updateSubtitles(),await this.changeSubtitlesLang("disabled"),await this.autoTranslate(),this.translateToLang=this.data.responseLanguage??"ru",this.initExtraEvents(),this.initialized=!0}transformBtn(t="none",e){this.votButton.container.dataset.status=t;const o="error"===t&&e.includes(H.get("translationTake"));this.setLoadingBtn(o),this.votButton.label.textContent=e,this.votButton.container.title="error"===t?e:""}setLoadingBtn(t=!1){this.votButton.container.dataset.loading=t}initUI(){this.votButton=Me.createVOTButton(H.get("translateVideo")),this.data?.buttonPos&&"default"!==this.data?.buttonPos&&this.container.clientWidth&&this.container.clientWidth>550?(this.votButton.container.dataset.direction="column",this.votButton.container.dataset.position=this.data?.buttonPos):(this.votButton.container.dataset.direction="row",this.votButton.container.dataset.position="default"),this.container.appendChild(this.votButton.container),this.votButton.pipButton.hidden=!B()||!this.data?.showPiPButton,this.votButton.separator2.hidden=!B()||!this.data?.showPiPButton,this.votButton.container.addEventListener("click",(t=>{t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation()})),this.votMenu=Me.createVOTMenu(H.get("VOTSettings")),this.votMenu.container.dataset.position=this.container.clientWidth&&this.container.clientWidth>550?this.data?.buttonPos:"default",this.container.appendChild(this.votMenu.container),this.votDownloadButton=Me.createIconButton(_t``}))}debounce(t,e){let o;return(...n)=>{clearTimeout(o),o=setTimeout((()=>t.apply(this,n)),e)}}release(){document.removeEventListener("mousedown",this.onMouseDownBound),document.removeEventListener("mouseup",this.onMouseUpBound),document.removeEventListener("mousemove",this.onMouseMoveBound),this.video?.removeEventListener("timeupdate",this.onTimeUpdateBound),this.resizeObserver.disconnect(),this.subtitlesContainer.remove()}}o("./node_modules/requestidlecallback-polyfill/index.js");class Ue{constructor(){this.listeners=new Set}hasListener(t){return this.listeners.has(t)}dispatchToListener(t,...e){try{t(...e)}catch(t){console.error("[VOT]",t)}}addListener(t){if(this.hasListener(t))throw new Error("[VOT] The listener has already been added.");this.listeners.add(t)}removeListener(t){if(!this.hasListener(t))throw new Error("[VOT] The listener has not been added yet.");this.listeners.delete(t)}dispatch(...t){for(const e of Array.from(this.listeners))this.dispatchToListener(e,...t)}}function je(t){return Array.from(t).flatMap((t=>t instanceof HTMLVideoElement?[t]:t instanceof HTMLElement?Array.from(t.querySelectorAll("video")):t.shadowRoot?Array.from(t.shadowRoot.querySelectorAll("video")):[]))}const We=/advertise|promo|sponsor|banner|commercial|preroll|midroll|postroll|ad-container|sponsored/i;const Ge=t.getParser(window.navigator.userAgent).getResult(),Je=["Violentmonkey","FireMonkey","Greasemonkey","AdGuard","OrangeMonkey"],Ye=["playing","ratechange","play","waiting","pause"];function Ke(t,e){return t.map((t=>({label:H.get("langs")[t]??t.toUpperCase(),value:t,selected:e===t})))}class Ze{translateFromLang="en";translateToLang=R;timer;videoData="";firstPlay=!0;audio=new Audio;audioContext=new(window.AudioContext||window.webkitAudioContext);gainNode=this.audioContext.createGain();hls=D();votClient;videoTranslations=[];videoTranslationTTL=7200;cachedTranslation;downloadTranslationUrl=null;downloadSubtitlesUrl=null;autoRetry;streamPing;votOpts;volumeOnStart;tempOriginalVolume;tempVolume;firstSyncVolume=!0;subtitlesList=[];subtitlesListVideoId=null;videoLastSrcObject=null;dragging;constructor(t,e,o){I.log("[VideoHandler] add video:",t,"container:",e,this),this.video=t,this.container=e,this.site=o,this.stopTranslationBound=this.stopTranslation.bind(this),this.handleVideoEventBound=this.handleVideoEvent.bind(this),this.changeOpacityOnEventBound=this.changeOpacityOnEvent.bind(this),this.resetTimerBound=this.resetTimer.bind(this),this.init()}async translateVideoImpl(t,e,o,n=null){if(clearTimeout(this.autoRetry),I.log(t,`Translate video (requestLang: ${e}, responseLang: ${o})`),await it(this.site,this.video)!==t.videoId)return null;try{const i=await this.votClient.translateVideo({videoData:t,requestLang:e,responseLang:o,translationHelp:n});if(I.log("Translate video result",i),i.translated&&i.remainingTime<1)return I.log("Video translation finished with this data: ",i),i;await this.updateTranslationErrorMsg(i.remainingTime>0?function(t){const e=Math.floor(t/60),o=Math.floor(t%60);return e>=60?H.get("translationTakeMoreThanHour"):1===e||0===e&&o>0?H.get("translationTakeAboutMinute"):11!==e&&e%10==1?H.get("translationTakeApproximatelyMinute2").replace("{0}",e):![12,13,14].includes(e)&&[2,3,4].includes(e%10)?H.get("translationTakeApproximatelyMinute").replace("{0}",e):H.get("translationTakeApproximatelyMinutes").replace("{0}",e)}(i.remainingTime):i.message??H.get("translationTakeFewMinutes"))}catch(t){return console.error("[VOT] Failed to translate video",t),await this.updateTranslationErrorMsg(t.data?.message??t),null}return new Promise((i=>{const a=this.subtitlesList.some((t=>"yandex"===t.source))?2e4:3e4;this.autoRetry=setTimeout((async()=>{const a=await this.translateVideoImpl(t,e,o,n);(!a||a.translated&&a.remainingTime<1)&&i(a)}),a)}))}async translateStreamImpl(t,e,o){if(clearTimeout(this.autoRetry),I.log(t,`Translate stream (requestLang: ${e}, responseLang: ${o})`),await it(this.site,this.video)!==t.videoId)return null;try{const n=await this.votClient.translateStream({videoData:t,requestLang:e,responseLang:o});if(I.log("Translate stream result",n),!n.translated&&10===n.interval)return await this.updateTranslationErrorMsg(H.get("translationTakeFewMinutes")),new Promise((i=>{this.autoRetry=setTimeout((async()=>{const n=await this.translateStreamImpl(t,e,o);n&&!n.translated&&10===n.interval||i(n)}),1e3*n.interval)}));if(n.message)throw I.log(`Stream translation aborted! Message: ${n.message}`),new rt("streamNoConnectionToServer");if(!n.result)throw I.log("Failed to find translation result! Data:",n),new rt("audioNotReceived");return I.log("Stream translated successfully. Running...",n),this.streamPing=setInterval((async()=>{I.log("Ping stream translation",n.pingId),this.votClient.pingStream({pingId:n.pingId})}),1e3*n.interval),n}catch(t){return console.error("[VOT] Failed to translate stream",t),await this.updateTranslationErrorMsg(t.data?.message??t),null}}async autoTranslate(){if(this.site.host,this.firstPlay&&1===this.data.autoTranslate&&this.videoData.videoId){this.firstPlay=!1;try{await this.translateExecutor(this.videoData.videoId)}catch(t){console.error("[VOT]",t),this.transformBtn("error","VOTLocalizedError"===t?.name?t.localizedMessage:t)}}}async init(){if(this.initialized)return;const t={autoTranslate:_.get("autoTranslate",0,!0),dontTranslateLanguage:_.get("dontTranslateLanguage",R),dontTranslateYourLang:_.get("dontTranslateYourLang",1,!0),autoSetVolumeYandexStyle:_.get("autoSetVolumeYandexStyle",1,!0),autoVolume:_.get("autoVolume",ee,!0),buttonPos:_.get("buttonPos","default"),showVideoSlider:_.get("showVideoSlider",1,!0),syncVolume:_.get("syncVolume",0,!0),subtitlesMaxLength:_.get("subtitlesMaxLength",300,!0),highlightWords:_.get("highlightWords",0,!0),subtitlesFontSize:_.get("subtitlesFontSize",20,!0),subtitlesOpacity:_.get("subtitlesOpacity",20,!0),responseLanguage:_.get("responseLanguage",R),defaultVolume:_.get("defaultVolume",100,!0),audioProxy:_.get("audioProxy",0,!0),showPiPButton:_.get("showPiPButton",0,!0),translateAPIErrors:_.get("translateAPIErrors",1,!0),translationService:_.get("translationService",oe),detectService:_.get("detectService",ne),m3u8ProxyHost:_.get("m3u8ProxyHost",Qt),translateProxyEnabled:_.get("translateProxyEnabled",0,!0),proxyWorkerHost:_.get("proxyWorkerHost",Xt),audioBooster:_.get("audioBooster",0,!0)};this.data=Object.fromEntries(await Promise.all(Object.entries(t).map((async([t,e])=>[t,await e])))),console.log("[db] data from db: ",this.data),0===this.data.translateProxyEnabled&&GM_info?.scriptHandler&&Je.includes(GM_info.scriptHandler)&&(this.data.translateProxyEnabled=1,await _.set("translateProxyEnabled",1),I.log("translateProxyEnabled",this.data.translateProxyEnabled)),I.log("Extension compatibility passed..."),this.votOpts={headers:1===this.data.translateProxyEnabled?{}:{"sec-ch-ua":null,"sec-ch-ua-mobile":null,"sec-ch-ua-platform":null},fetchFn:q,hostVOT:te,host:1===this.data.translateProxyEnabled?this.data.proxyWorkerHost:"api.browser.yandex.ru"},this.votClient=new(1===this.data.translateProxyEnabled?ut:dt)(this.votOpts),this.subtitlesWidget=new He(this.video,this.container,this.site),this.subtitlesWidget.setMaxLength(this.data.subtitlesMaxLength),this.subtitlesWidget.setHighlightWords(this.data.highlightWords),this.subtitlesWidget.setFontSize(this.data.subtitlesFontSize),this.subtitlesWidget.setOpacity(this.data.subtitlesOpacity),this.audio.crossOrigin="anonymous",this.gainNode.connect(this.audioContext.destination),this.audioSource=this.audioContext.createMediaElementSource(this.audio),this.audioSource.connect(this.gainNode),this.initUI(),this.initUIEvents();const e=!this.video.src&&!this.video.currentSrc&&!this.video.srcObject;this.votButton.container.hidden=e,e?this.votMenu.container.hidden=!0:(this.videoData=await this.getVideoData(),this.setSelectMenuValues(this.videoData.detectedLanguage,this.data.responseLanguage??"ru")),await this.updateSubtitles(),await this.changeSubtitlesLang("disabled"),await this.autoTranslate(),this.translateToLang=this.data.responseLanguage??"ru",this.initExtraEvents(),this.initialized=!0}transformBtn(t="none",e){this.votButton.container.dataset.status=t;const o="error"===t&&e.includes(H.get("translationTake"));this.setLoadingBtn(o),this.votButton.label.textContent=e,this.votButton.container.title="error"===t?e:""}setLoadingBtn(t=!1){this.votButton.container.dataset.loading=t}initUI(){this.votButton=Me.createVOTButton(H.get("translateVideo")),this.votButton.container.style.opacity=0,this.data?.buttonPos&&"default"!==this.data?.buttonPos&&this.container.clientWidth&&this.container.clientWidth>550?(this.votButton.container.dataset.direction="column",this.votButton.container.dataset.position=this.data?.buttonPos):(this.votButton.container.dataset.direction="row",this.votButton.container.dataset.position="default"),this.container.appendChild(this.votButton.container),this.votButton.pipButton.hidden=!B()||!this.data?.showPiPButton,this.votButton.separator2.hidden=!B()||!this.data?.showPiPButton,this.votButton.container.addEventListener("click",(t=>{t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation()})),this.votMenu=Me.createVOTMenu(H.get("VOTSettings")),this.votMenu.container.dataset.position=this.container.clientWidth&&this.container.clientWidth>550?this.data?.buttonPos:"default",this.container.appendChild(this.votMenu.container),this.votDownloadButton=Me.createIconButton(_t`