From 4c416013190dccc80f0911b2d72495548819a738 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Sun, 8 Mar 2020 16:37:45 +0100 Subject: [PATCH 01/19] spin UI to a separate file --- src/ext/uw-ui.js | 160 ++++++++++++++++++++++++++++++++++++++++++++++ src/ext/uw.js | 120 ++-------------------------------- webpack.config.js | 1 + 3 files changed, 168 insertions(+), 113 deletions(-) create mode 100644 src/ext/uw-ui.js diff --git a/src/ext/uw-ui.js b/src/ext/uw-ui.js new file mode 100644 index 0000000..c7a78b2 --- /dev/null +++ b/src/ext/uw-ui.js @@ -0,0 +1,160 @@ +// vue dependency imports + +import Vue from 'vue'; +import Vuex from 'vuex'; +import VuexWebExtensions from 'vuex-webextensions'; +import LoggerUi from '../csui/LoggerUi'; + +class UwUi { + + async init() { + // initialize vuejs + try { + Vue.prototype.$browser = global.browser; + Vue.use(Vuex); + this.vuexStore = new Vuex.Store({ + plugins: [VuexWebExtensions({ + persistentStates: [ + 'uwLog', + 'showLogger', + ], + })], + state: { + uwLog: '', + showLogger: false, + }, + mutations: { + 'uw-set-log'(state, payload) { + state['uwLog'] = payload; + }, + 'uw-show-logger'(state) { + state['showLogger'] = true; + }, + 'uw-hide-logger'(state) { + state['showLogger'] = false; + } + }, + actions: { + 'uw-set-log' ({commit}, payload) { + commit('uw-set-log', payload); + }, + 'uw-show-logger'({commit}) { + commit('uw-show-logger'); + }, + 'uw-hide-logger'({commit}) { + commit('uw-hide-logger'); + } + } + }); + console.log("successfully vued") + } catch (e) { + console.error("wasnt vued,", e); + } + + // setup logger + try { + if (!this.logger) { + const loggingOptions = { + isContentScript: true, + allowLogging: true, + useConfFromStorage: true, + fileOptions: { + enabled: false + }, + consoleOptions: { + "enabled": true, + "debug": true, + "init": true, + "settings": true, + "keyboard": true, + "mousemove": false, + "actionHandler": true, + "comms": true, + "playerDetect": true, + "resizer": true, + "scaler": true, + "stretcher": true, + // "videoRescan": true, + // "playerRescan": true, + "arDetect": true, + "arDetect_verbose": true + }, + allowBlacklistedOrigins: { + 'periodicPlayerCheck': false, + 'periodicVideoStyleChangeCheck': false, + 'handleMouseMove': false + } + }; + this.logger = new Logger(); + await this.logger.init(loggingOptions); + + if (this.logger.isLoggingAllowed()) { + console.info("[uw::init] Logging is allowed! Initalizing vue and UI!"); + this.initVue(); + this.initUi(); + this.logger.setVuexStore(this.vuexStore); + } + + // show popup if logging to file is enabled + if (this.logger.isLoggingToFile()) { + console.info('[uw::init] Logging to file is enabled. Will show popup!'); + try { + this.vuexStore.dispatch('uw-show-logger'); + } catch (e) { + console.error('[uw::init] Failed to open popup!', e) + } + } + } + } catch (e) { + console.error("logger initialization failed"); + } + + + await this.initLoggerUi(); + this.showLogger(); + } + + async initLoggerUi() { + console.log("CREATING UI"); + const random = Math.round(Math.random() * 69420); + const uwid = `uw-ui-root-${random}`; + + const rootDiv = document.createElement('div'); + rootDiv.setAttribute("style", "position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 999999; background-color: #ff0000;"); + rootDiv.setAttribute("id", uwid); + + document.body.appendChild(rootDiv); + + try { + new Vue({ + el: `#${uwid}`, + components: { + LoggerUi: LoggerUi + }, + store: this.vuexStore, + render(h) { + return h('logger-ui'); + } + }); + } catch (e) { + console.error("e:", e) + } + console.log("new vue was newed") + } + + async showLogger() { + console.log("SHOWING LOGGER!") + this.vuexStore.dispatch('uw-show-logger'); + } + hideLogger() { + // if either of these two is false, then we know that UI doesn't exist + // since UI doesn't exist, we don't need to dispatch uw-hide-logger + if (this.vueInitiated && this.uiInitiated) { + this.vuexStore.dispatch('uw-hide-logger'); + } + } +} + +console.log("init ui") +var uwui = new UwUi(); +uwui.init(); diff --git a/src/ext/uw.js b/src/ext/uw.js index 03b608b..7e978e3 100644 --- a/src/ext/uw.js +++ b/src/ext/uw.js @@ -7,26 +7,9 @@ import CommsClient from './lib/comms/CommsClient'; import PageInfo from './lib/video-data/PageInfo'; import Logger from './lib/Logger'; -// vue dependency imports -import Vue from 'vue'; -import Vuex from 'vuex'; -import VuexWebExtensions from 'vuex-webextensions'; - -global.browser = require('webextension-polyfill'); -import LoggerUi from '../csui/LoggerUi'; if(Debug.debug){ - console.log("\n\n\n\n\n\n ——— Sᴛλʀᴛɪɴɢ Uʟᴛʀᴀᴡɪᴅɪꜰʏ ———\n << ʟᴏᴀᴅɪɴɢ ᴍᴀɪɴ ꜰɪʟᴇ >>\n\n\n\n"); - try { - if(window.self !== window.top){ - console.log("%cWe aren't in an iframe.", "color: #afc, background: #174"); - } - else{ - console.log("%cWe are in an iframe!", "color: #fea, background: #d31", window.self, window.top); - } - } catch (e) { - console.log("%cWe are in an iframe!", "color: #fea, background: #d31"); - } + console.log("Sᴛλʀᴛɪɴɢ Uʟᴛʀᴀᴡɪᴅɪꜰʏ UI"); } if (BrowserDetect.edge) { @@ -40,9 +23,7 @@ class UW { this.settings = undefined; this.actionHandler = undefined; this.logger = undefined; - this.vuexStore = {}; this.uiInitiated = false; - this.vueInitiated = false; } reloadSettings() { @@ -51,9 +32,9 @@ class UW { } async init(){ - if (Debug.debug) { + // if (Debug.debug) { console.log("[uw::main] loading configuration ..."); - } + // } // logger init is the first thing that needs to run try { @@ -114,17 +95,10 @@ class UW { } // init() is re-run any time settings change - if (this.pageInfo) { - // if this executes, logger must have been initiated at some point before this point - this.logger.log('info', 'debug', "[uw::init] Destroying existing pageInfo", this.pageInfo); - this.pageInfo.destroy(); - } if (this.comms) { this.comms.destroy(); } - if (!this.settings) { - var ths = this; this.settings = new Settings({ onSettingsChanged: () => this.reloadSettings(), logger: this.logger @@ -132,12 +106,8 @@ class UW { await this.settings.init(); } - this.comms = new CommsClient('content-client-port', this.settings, this.logger); + this.comms = new CommsClient('content-ui-port', this.settings, this.logger); - // add showPopup, hidePopup listener to comms - this.comms.subscribe('show-logger', () => this.showLogger()); - this.comms.subscribe('hide-logger', () => this.hideLogger()); - // če smo razširitev onemogočili v nastavitvah, ne naredimo ničesar // If extension is soft-disabled, don't do shit @@ -172,87 +142,11 @@ class UW { } catch (e) { this.logger.log('error', 'debug', "[uw::init] FAILED TO START EXTENSION. Error:", e); } + + console.log("....") } - initVue() { - Vue.prototype.$browser = global.browser; - Vue.use(Vuex); - this.vuexStore = new Vuex.Store({ - plugins: [VuexWebExtensions({ - persistentStates: [ - 'uwLog', - 'showLogger', - ], - })], - state: { - uwLog: '', - showLogger: false, - }, - mutations: { - 'uw-set-log'(state, payload) { - state['uwLog'] = payload; - }, - 'uw-show-logger'(state) { - state['showLogger'] = true; - }, - 'uw-hide-logger'(state) { - state['showLogger'] = false; - } - }, - actions: { - 'uw-set-log' ({commit}, payload) { - commit('uw-set-log', payload); - }, - 'uw-show-logger'({commit}) { - commit('uw-show-logger'); - }, - 'uw-hide-logger'({commit}) { - commit('uw-hide-logger'); - } - } - }) - } - - initUi() { - console.log("CREATING UI"); - const random = Math.round(Math.random() * 69420); - const uwid = `uw-ui-root-${random}`; - - const rootDiv = document.createElement('div'); - rootDiv.setAttribute("style", "position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 999999; background-color: #ff0000;"); - rootDiv.setAttribute("id", uwid); - - document.body.appendChild(rootDiv); - - new Vue({ - el: `#${uwid}`, - components: { - LoggerUi - }, - store: this.vuexStore, - render(h) { - return h('logger-ui'); - } - }) - } - - showLogger() { - if (! this.vueInitiated) { - this.initVue(); - } - if (!this.uiInitiated) { - this.initUi(); - } - - this.vuexStore.dispatch('uw-show-logger'); - } - hideLogger() { - // if either of these two is false, then we know that UI doesn't exist - // since UI doesn't exist, we don't need to dispatch uw-hide-logger - if (this.vueInitiated && this.uiInitiated) { - this.vuexStore.dispatch('uw-hide-logger'); - } - } + } var main = new UW(); diff --git a/webpack.config.js b/webpack.config.js index e5145ad..75be6a5 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -12,6 +12,7 @@ const config = { context: __dirname + '/src', entry: { 'ext/uw': './ext/uw.js', + 'ext/uw-ui': './ext/uw-ui.js', 'ext/uw-bg': './ext/uw-bg.js', 'popup/popup': './popup/popup.js', 'options/options': './options/options.js', From c26744b9d9b9cf1c7d88b7744f08388fd9994c90 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Sun, 8 Mar 2020 16:49:20 +0100 Subject: [PATCH 02/19] handleMessage _always_ tries to execute command, even if it has forwarding flags set. Command is executed before forwarding. --- src/ext/lib/comms/CommsServer.js | 27 ++++++++++++++++++--------- src/ext/uw-bg.js | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/ext/lib/comms/CommsServer.js b/src/ext/lib/comms/CommsServer.js index adb5486..fc4197e 100644 --- a/src/ext/lib/comms/CommsServer.js +++ b/src/ext/lib/comms/CommsServer.js @@ -133,6 +133,15 @@ class CommsServer { } } + subscribe(command, callback) { + console.log("subscribing to command:", command, "with callback", callback) + if (!this.commands[command]) { + this.commands[command] = [callback]; + } else { + this.commands[command].push(callback); + } + } + async getCurrentTabHostname() { const activeTab = await this._getActiveTab(); @@ -243,35 +252,35 @@ class CommsServer { } - execCmd(message, portOrSender, sendResponse) { + async execCmd(message, portOrSender, sendResponse) { + console.log("got a command to exec:", message.cmd, message, this.commands[message.cmd], this.commands) this.logger.log( 'info', 'comms', '[CommsServer.js::execCmd] Received message', message, ". Port/sender:", portOrSender, "sendResponse:", sendResponse, "\nThere is ", this.commands[message.cmd]?.length ?? 0, " command(s) for action", message.cmd ); - for (const c of this.commands[message.cmd]) { - c(message, portOrSender, sendResponse); + if (this.commands[message.cmd]) { + for (const c of this.commands[message.cmd]) { + await c(message, portOrSender, sendResponse); + } } } - handleMessage(message, portOrSender, sendResponse) { + async handleMessage(message, portOrSender, sendResponse) { + await this.execCmd(message, portOrSender, sendResponse); + if (message.forwardToContentScript) { this.logger.log('info', 'comms', "[CommsServer.js::processReceivedMessage] Message has 'forward to content script' flag set. Forwarding message as is. Message:", message); this.sendToFrame(message, message.targetTab, message.targetFrame); - return; } if (message.forwardToAll) { this.logger.log('info', 'comms', "[CommsServer.js::processReceivedMessage] Message has 'forward to all' flag set. Forwarding message as is. Message:", message); this.sendToAll(message); - return; } if (message.forwardToActive) { this.logger.log('info', 'comms', "[CommsServer.js::processReceivedMessage] Message has 'forward to active' flag set. Forwarding message as is. Message:", message); this.sendToActive(message); - return; } - - this.execCmd(message, portOrSender, sendResponse); } async processReceivedMessage(message, port){ diff --git a/src/ext/uw-bg.js b/src/ext/uw-bg.js index 42cd0ce..562534d 100644 --- a/src/ext/uw-bg.js +++ b/src/ext/uw-bg.js @@ -49,6 +49,7 @@ class UWServer { this.settings = new Settings({logger: this.logger}); await this.settings.init(); this.comms = new CommsServer(this); + this.comms.subscribe('show-logger', async () => await this.initUi()); var ths = this; if(BrowserDetect.firefox) { @@ -198,6 +199,26 @@ class UWServer { this.selectedSubitem[menu] = subitem; } + async initUi() { + try { + if (BrowserDetect.firefox) { + console.log("") + browser.tabs.executeScript({ + file: '/ext/uw-ui.js', + allFrames: true, + }); + } else if (BrowserDetect.chrome) { + chrome.tabs.executeScript({ + file: '/ext/uw-ui.js', + allFrames: true, + }); + } + } catch (e) { + console.error("UI initialization failed. Reason:", e); + this.logger.log('ERROR', 'uwbg', 'UI initialization failed. Reason:', e); + } + } + async getCurrentTab() { if (BrowserDetect.firefox) { return (await browser.tabs.query({active: true, currentWindow: true}))[0]; From 92c4ba0c696ff7d90cd6e98de3287871169ec563 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Sun, 8 Mar 2020 17:13:44 +0100 Subject: [PATCH 03/19] Remove paginfo and command declarations out of comms --- src/ext/lib/comms/CommsClient.js | 68 ++---------------- src/ext/uw-ui.js | 117 +++++++++++++++++++------------ src/ext/uw.js | 31 +++++++- 3 files changed, 107 insertions(+), 109 deletions(-) diff --git a/src/ext/lib/comms/CommsClient.js b/src/ext/lib/comms/CommsClient.js index 142c2c0..bd194ad 100644 --- a/src/ext/lib/comms/CommsClient.js +++ b/src/ext/lib/comms/CommsClient.js @@ -2,7 +2,7 @@ import Debug from '../../conf/Debug'; import BrowserDetect from '../../conf/BrowserDetect'; class CommsClient { - constructor(name, settings, logger) { + constructor(name, logger, commands) { this.logger = logger; if (BrowserDetect.firefox) { @@ -24,46 +24,15 @@ class CommsClient { } ); - var ths = this; - this._listener = m => ths.processReceivedMessage(m); + this._listener = m => this.processReceivedMessage(m); this.port.onMessage.addListener(this._listener); - this.settings = settings; - this.pageInfo = undefined; this.commsId = (Math.random() * 20).toFixed(0); - this.commands = { - 'get-current-zoom': [() => this.pageInfo.requestCurrentZoom()], - 'set-ar': [(message) => this.pageInfo.setAr({type: message.arg, ratio: message.customArg}, message.playing)], - 'set-alignment': [(message) => { - this.pageInfo.setVideoAlignment(message.arg, message.playing); - this.pageInfo.restoreAr(); - }], - 'set-stretch': [(message) => this.pageInfo.setStretchMode(message.arg, message.playing, message.customArg)], - 'set-keyboard': [(message) => this.pageInfo.setKeyboardShortcutsEnabled(message.arg)], - 'autoar-start': [(message) => { - if (message.enabled !== false) { - this.pageInfo.initArDetection(message.playing); - this.pageInfo.startArDetection(message.playing); - } else { - this.pageInfo.stopArDetection(message.playing); - } - }], - 'pause-processing': [(message) => this.pageInfo.pauseProcessing(message.playing)], - 'resume-processing': [(message) => this.pageInfo.resumeProcessing(message.autoArStatus, message.playing)], - 'set-zoom': [(message) => this.pageInfo.setZoom(message.arg, true, message.playing)], - 'change-zoom': [(message) => this.pageInfo.zoomStep(message.arg, message.playing)], - 'mark-player': [(message) => this.pageInfo.markPlayer(message.name, message.color)], - 'unmark-player': [() => this.pageInfo.unmarkPlayer()], - 'autoar-set-manual-tick': [(message) => this.pageInfo.setManualTick(message.arg)], - 'autoar-tick': [() => this.pageInfo.tick()], - 'set-ar-persistence': [() => this.pageInfo.setArPersistence(message.arg)], - }; + this.commands = commands; } destroy() { - this.pageInfo = null; - this.settings = null; if (!BrowserDetect.edge) { // edge is a very special browser made by outright morons. this.port.onMessage.removeListener(this._listener); } @@ -77,32 +46,9 @@ class CommsClient { } } - setPageInfo(pageInfo){ - - this.pageInfo = pageInfo; - - this.logger.log('info', 'debug', `[CommsClient::setPageInfo] <${this.commsId}>`, "setting pageinfo"); - - var ths = this; - this._listener = m => ths.processReceivedMessage(m); - if (!BrowserDetect.edge) { - this.port.onMessage.removeListener(this._listener); - } - this.port.onMessage.addListener(this._listener); - - } - processReceivedMessage(message){ this.logger.log('info', 'comms', `[CommsClient.js::processMessage] <${this.commsId}> Received message from background script!`, message); - if (!this.pageInfo || !this.settings.active) { - this.logger.log('info', 'comms', `[CommsClient.js::processMessage] <${this.commsId}> this.pageInfo (or settings) not defined. Extension is probably disabled for this site.\npageInfo:`, this.pageInfo, - "\nsettings.active:", this.settings.active, - "\nnobj:", this - ); - return; - } - if (this.commands[message.cmd]) { for (const c of this.commands[message.cmd]) { c(message); @@ -165,13 +111,7 @@ class CommsClient { registerVideo(){ this.logger.log('info', 'comms', `[CommsClient::registerVideo] <${this.commsId}>`, "Registering video for current page."); - if (this.pageInfo) { - if (this.pageInfo.hasVideo()) { - this.port.postMessage({cmd: "has-video"}); - } - } else { - // this.port.postMessage({cmd: "has-video"}); - } + this.port.postMessage({cmd: "has-video"}); } sendPerformanceUpdate(message){ diff --git a/src/ext/uw-ui.js b/src/ext/uw-ui.js index c7a78b2..ca840a3 100644 --- a/src/ext/uw-ui.js +++ b/src/ext/uw-ui.js @@ -7,49 +7,49 @@ import LoggerUi from '../csui/LoggerUi'; class UwUi { + constructor() { + this.loggerUiInitiated = false; + this.playerUiInitiated = false; + } + async init() { // initialize vuejs - try { - Vue.prototype.$browser = global.browser; - Vue.use(Vuex); - this.vuexStore = new Vuex.Store({ - plugins: [VuexWebExtensions({ - persistentStates: [ - 'uwLog', - 'showLogger', - ], - })], - state: { - uwLog: '', - showLogger: false, + Vue.prototype.$browser = global.browser; + Vue.use(Vuex); + this.vuexStore = new Vuex.Store({ + plugins: [VuexWebExtensions({ + persistentStates: [ + 'uwLog', + 'showLogger', + ], + })], + state: { + uwLog: '', + showLogger: false, + }, + mutations: { + 'uw-set-log'(state, payload) { + state['uwLog'] = payload; }, - mutations: { - 'uw-set-log'(state, payload) { - state['uwLog'] = payload; - }, - 'uw-show-logger'(state) { - state['showLogger'] = true; - }, - 'uw-hide-logger'(state) { - state['showLogger'] = false; - } + 'uw-show-logger'(state) { + state['showLogger'] = true; }, - actions: { - 'uw-set-log' ({commit}, payload) { - commit('uw-set-log', payload); - }, - 'uw-show-logger'({commit}) { - commit('uw-show-logger'); - }, - 'uw-hide-logger'({commit}) { - commit('uw-hide-logger'); - } + 'uw-hide-logger'(state) { + state['showLogger'] = false; } - }); - console.log("successfully vued") - } catch (e) { - console.error("wasnt vued,", e); - } + }, + actions: { + 'uw-set-log' ({commit}, payload) { + commit('uw-set-log', payload); + }, + 'uw-show-logger'({commit}) { + commit('uw-show-logger'); + }, + 'uw-hide-logger'({commit}) { + commit('uw-hide-logger'); + } + } + }); // setup logger try { @@ -109,9 +109,23 @@ class UwUi { console.error("logger initialization failed"); } + // we also need to know settings (there's UI-related things in the settings — or rather, there will be UI-related things + // in settings once in-player UI is implemented + // If comms exist, we need to destroy it + if (this.comms) { + this.comms.destroy(); + } + if (!this.settings) { + this.settings = new Settings({ + onSettingsChanged: () => this.reloadSettings(), + logger: this.logger + }); + await this.settings.init(); + } + + this.comms = new CommsClient('content-ui-port', this.settings, this.logger); + - await this.initLoggerUi(); - this.showLogger(); } async initLoggerUi() { @@ -155,6 +169,23 @@ class UwUi { } } -console.log("init ui") -var uwui = new UwUi(); -uwui.init(); +// leave a mark, so this script won't get executed more than once on a given page +const markerId = 'ultrawidify-marker-5aeaf521-7afe-447f-9a17-3428f62d0970'; + +console.log("will init ui") + + +if (! document.getElementById(markerId)) { + console.log("init hasn't happened before") + const markerDiv = document.createElement('div'); + markerDiv.setAttribute("style", "display: none"); + markerDiv.setAttribute('id', markerId); + + document.body.appendChild(markerDiv); + + var uwui = new UwUi(); + uwui.init(); +} else { + console.info("UI has already been initiated once, so we aren't doing it again"); +} + diff --git a/src/ext/uw.js b/src/ext/uw.js index 7e978e3..f1ca0bb 100644 --- a/src/ext/uw.js +++ b/src/ext/uw.js @@ -24,6 +24,34 @@ class UW { this.actionHandler = undefined; this.logger = undefined; this.uiInitiated = false; + + this.commsHandlers = { + 'get-current-zoom': [() => this.pageInfo.requestCurrentZoom()], + 'set-ar': [(message) => this.pageInfo.setAr({type: message.arg, ratio: message.customArg}, message.playing)], + 'set-alignment': [(message) => { + this.pageInfo.setVideoAlignment(message.arg, message.playing); + this.pageInfo.restoreAr(); + }], + 'set-stretch': [(message) => this.pageInfo.setStretchMode(message.arg, message.playing, message.customArg)], + 'set-keyboard': [(message) => this.pageInfo.setKeyboardShortcutsEnabled(message.arg)], + 'autoar-start': [(message) => { + if (message.enabled !== false) { + this.pageInfo.initArDetection(message.playing); + this.pageInfo.startArDetection(message.playing); + } else { + this.pageInfo.stopArDetection(message.playing); + } + }], + 'pause-processing': [(message) => this.pageInfo.pauseProcessing(message.playing)], + 'resume-processing': [(message) => this.pageInfo.resumeProcessing(message.autoArStatus, message.playing)], + 'set-zoom': [(message) => this.pageInfo.setZoom(message.arg, true, message.playing)], + 'change-zoom': [(message) => this.pageInfo.zoomStep(message.arg, message.playing)], + 'mark-player': [(message) => this.pageInfo.markPlayer(message.name, message.color)], + 'unmark-player': [() => this.pageInfo.unmarkPlayer()], + 'autoar-set-manual-tick': [(message) => this.pageInfo.setManualTick(message.arg)], + 'autoar-tick': [() => this.pageInfo.tick()], + 'set-ar-persistence': [() => this.pageInfo.setArPersistence(message.arg)], + } } reloadSettings() { @@ -106,7 +134,7 @@ class UW { await this.settings.init(); } - this.comms = new CommsClient('content-ui-port', this.settings, this.logger); + this.comms = new CommsClient('content-ui-port', this.logger, this.commsHandlers); // če smo razširitev onemogočili v nastavitvah, ne naredimo ničesar // If extension is soft-disabled, don't do shit @@ -127,7 +155,6 @@ class UW { try { this.pageInfo = new PageInfo(this.comms, this.settings, this.logger, extensionMode, isSiteDisabled); this.logger.log('info', 'debug', "[uw.js::setup] pageInfo initialized."); - this.comms.setPageInfo(this.pageInfo); this.logger.log('info', 'debug', "[uw.js::setup] will try to initate ActionHandler."); From e681a64f55a8de1665a9452b62b66af7ac936f84 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Sun, 8 Mar 2020 18:34:30 +0100 Subject: [PATCH 04/19] remove unnecessary code --- src/ext/lib/comms/CommsClient.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/ext/lib/comms/CommsClient.js b/src/ext/lib/comms/CommsClient.js index bd194ad..69352cb 100644 --- a/src/ext/lib/comms/CommsClient.js +++ b/src/ext/lib/comms/CommsClient.js @@ -56,10 +56,6 @@ class CommsClient { } } - async sleep(n){ - return new Promise( (resolve, reject) => setTimeout(resolve, n) ); - } - async sendMessage_nonpersistent(message){ message = JSON.parse(JSON.stringify(message)); // vue quirk. We should really use vue store instead From d8181431ff8e9fcc3cda796f0083242b21e676c3 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Sun, 8 Mar 2020 18:38:09 +0100 Subject: [PATCH 05/19] Block show-logger until ui is initiated --- src/ext/uw-bg.js | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/ext/uw-bg.js b/src/ext/uw-bg.js index 562534d..4790ae0 100644 --- a/src/ext/uw-bg.js +++ b/src/ext/uw-bg.js @@ -4,6 +4,8 @@ import CommsServer from './lib/comms/CommsServer'; import Settings from './lib/Settings'; import Logger from './lib/Logger'; +import sleep from '../common/js/utils'; + var BgVars = { arIsActive: true, hasVideos: false, @@ -50,6 +52,8 @@ class UWServer { await this.settings.init(); this.comms = new CommsServer(this); this.comms.subscribe('show-logger', async () => await this.initUi()); + this.comms.subscribe('init-vue', async () => await this.initUi()); + var ths = this; if(BrowserDetect.firefox) { @@ -202,19 +206,19 @@ class UWServer { async initUi() { try { if (BrowserDetect.firefox) { - console.log("") - browser.tabs.executeScript({ + await browser.tabs.executeScript({ file: '/ext/uw-ui.js', allFrames: true, }); } else if (BrowserDetect.chrome) { - chrome.tabs.executeScript({ - file: '/ext/uw-ui.js', - allFrames: true, - }); + await new Promise( resolve => + chrome.tabs.executeScript({ + file: '/ext/uw-ui.js', + allFrames: true, + }, () => resolve()) + ); } } catch (e) { - console.error("UI initialization failed. Reason:", e); this.logger.log('ERROR', 'uwbg', 'UI initialization failed. Reason:', e); } } From 5cc90ea36893f9a72e613d74773e3978e76cf28e Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Sun, 8 Mar 2020 18:38:36 +0100 Subject: [PATCH 06/19] Fix problems with uw-ui --- src/ext/uw-ui.js | 138 +++++++++++++++++++++++++++++------------------ 1 file changed, 85 insertions(+), 53 deletions(-) diff --git a/src/ext/uw-ui.js b/src/ext/uw-ui.js index ca840a3..c6b5229 100644 --- a/src/ext/uw-ui.js +++ b/src/ext/uw-ui.js @@ -1,55 +1,38 @@ // vue dependency imports - import Vue from 'vue'; import Vuex from 'vuex'; import VuexWebExtensions from 'vuex-webextensions'; import LoggerUi from '../csui/LoggerUi'; +// extension classes +import Logger from './lib/Logger'; +import Settings from './lib/Settings'; +import CommsClient from './lib/comms/CommsClient'; + class UwUi { constructor() { + this.vueInitiated = false; this.loggerUiInitiated = false; this.playerUiInitiated = false; + + this.vuexStore = null; + + this.commsHandlers = { + 'show-logger': [() => this.showLogger()], + 'hide-logger': [() => this.hideLogger()], + } } async init() { - // initialize vuejs - Vue.prototype.$browser = global.browser; - Vue.use(Vuex); - this.vuexStore = new Vuex.Store({ - plugins: [VuexWebExtensions({ - persistentStates: [ - 'uwLog', - 'showLogger', - ], - })], - state: { - uwLog: '', - showLogger: false, - }, - mutations: { - 'uw-set-log'(state, payload) { - state['uwLog'] = payload; - }, - 'uw-show-logger'(state) { - state['showLogger'] = true; - }, - 'uw-hide-logger'(state) { - state['showLogger'] = false; - } - }, - actions: { - 'uw-set-log' ({commit}, payload) { - commit('uw-set-log', payload); - }, - 'uw-show-logger'({commit}) { - commit('uw-show-logger'); - }, - 'uw-hide-logger'({commit}) { - commit('uw-hide-logger'); - } - } - }); + // IMPORTANT NOTICE — we do not check for whether extension is enabled or not, + // since this script only gets executed either: + // * as a direct result of user action (logger UI) + // * if video/player is detected (which can only happen if extension is enabled + // for that particular site) + + // initialize vuejs, but only once (check handled in initVue()) + this.initVue(); // setup logger try { @@ -106,7 +89,7 @@ class UwUi { } } } catch (e) { - console.error("logger initialization failed"); + console.error("logger initialization failed. Error:", e); } // we also need to know settings (there's UI-related things in the settings — or rather, there will be UI-related things @@ -123,9 +106,56 @@ class UwUi { await this.settings.init(); } - this.comms = new CommsClient('content-ui-port', this.settings, this.logger); + this.comms = new CommsClient('content-ui-port', this.logger, this.commsHandlers); + console.log("UI INIT COMPLETE ——————————————————————"); + } + initVue() { + // never init twice + if (this.vueInitiated) { + return; + } + + Vue.prototype.$browser = global.browser; + Vue.use(Vuex); + this.vuexStore = new Vuex.Store({ + plugins: [VuexWebExtensions({ + persistentStates: [ + 'uwLog', + 'showLogger', + ], + })], + state: { + uwLog: '', + showLogger: false, + }, + mutations: { + 'uw-set-log'(state, payload) { + state['uwLog'] = payload; + }, + 'uw-show-logger'(state) { + state['showLogger'] = true; + }, + 'uw-hide-logger'(state) { + state['showLogger'] = false; + } + }, + actions: { + 'uw-set-log' ({commit}, payload) { + commit('uw-set-log', payload); + }, + 'uw-show-logger'({commit}) { + commit('uw-show-logger'); + }, + 'uw-hide-logger'({commit}) { + commit('uw-hide-logger'); + } + } + }); + + // make sure we don't init twice + this.vueInitiated = true; } async initLoggerUi() { @@ -151,19 +181,26 @@ class UwUi { } }); } catch (e) { - console.error("e:", e) + console.error("Error while initiating vue:", e) } - console.log("new vue was newed") + + this.loggerUiInitiated = true; } async showLogger() { console.log("SHOWING LOGGER!") - this.vuexStore.dispatch('uw-show-logger'); + if (!this.loggerUiInitiated) { + await this.initLoggerUi(); + } + + try { + this.vuexStore.dispatch('uw-show-logger'); + } catch (e) { + console.error('Failed to dispatch vuex store', e) + } } hideLogger() { - // if either of these two is false, then we know that UI doesn't exist - // since UI doesn't exist, we don't need to dispatch uw-hide-logger - if (this.vueInitiated && this.uiInitiated) { + if (this.vueInitiated && this.vuexStore !== undefined) { this.vuexStore.dispatch('uw-hide-logger'); } } @@ -172,20 +209,15 @@ class UwUi { // leave a mark, so this script won't get executed more than once on a given page const markerId = 'ultrawidify-marker-5aeaf521-7afe-447f-9a17-3428f62d0970'; -console.log("will init ui") - - +// if this script has already been executed, don't execute it again. if (! document.getElementById(markerId)) { - console.log("init hasn't happened before") const markerDiv = document.createElement('div'); markerDiv.setAttribute("style", "display: none"); markerDiv.setAttribute('id', markerId); document.body.appendChild(markerDiv); - var uwui = new UwUi(); + const uwui = new UwUi(); uwui.init(); -} else { - console.info("UI has already been initiated once, so we aren't doing it again"); } From 6ea2b0488dff25e7fdb8b7a26b8853bcbae4d8c3 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Sun, 8 Mar 2020 18:43:53 +0100 Subject: [PATCH 07/19] Fix console errors --- src/ext/lib/Settings.js | 1 - src/ext/lib/comms/CommsServer.js | 2 -- src/ext/uw-bg.js | 2 -- src/ext/uw-ui.js | 4 ---- src/ext/uw.js | 4 ++-- 5 files changed, 2 insertions(+), 11 deletions(-) diff --git a/src/ext/lib/Settings.js b/src/ext/lib/Settings.js index a145867..76a0f8d 100644 --- a/src/ext/lib/Settings.js +++ b/src/ext/lib/Settings.js @@ -156,7 +156,6 @@ class Settings { try { updateFn(this.active, this.getDefaultSettings()); } catch (e) { - console.log("!!!!", e) this.logger.log('error', 'settings', '[Settings::applySettingsPatches] Failed to execute update function. Keeping settings object as-is. Error:', e); } } diff --git a/src/ext/lib/comms/CommsServer.js b/src/ext/lib/comms/CommsServer.js index fc4197e..3d15c00 100644 --- a/src/ext/lib/comms/CommsServer.js +++ b/src/ext/lib/comms/CommsServer.js @@ -134,7 +134,6 @@ class CommsServer { } subscribe(command, callback) { - console.log("subscribing to command:", command, "with callback", callback) if (!this.commands[command]) { this.commands[command] = [callback]; } else { @@ -253,7 +252,6 @@ class CommsServer { async execCmd(message, portOrSender, sendResponse) { - console.log("got a command to exec:", message.cmd, message, this.commands[message.cmd], this.commands) this.logger.log( 'info', 'comms', '[CommsServer.js::execCmd] Received message', message, ". Port/sender:", portOrSender, "sendResponse:", sendResponse, "\nThere is ", this.commands[message.cmd]?.length ?? 0, diff --git a/src/ext/uw-bg.js b/src/ext/uw-bg.js index 4790ae0..0fa8680 100644 --- a/src/ext/uw-bg.js +++ b/src/ext/uw-bg.js @@ -237,8 +237,6 @@ class UWServer { const ctab = await this.getCurrentTab(); - console.log('Current tab:', ctab); - if (!ctab || !ctab.id) { return { host: 'INVALID SITE', diff --git a/src/ext/uw-ui.js b/src/ext/uw-ui.js index c6b5229..e543b1b 100644 --- a/src/ext/uw-ui.js +++ b/src/ext/uw-ui.js @@ -107,8 +107,6 @@ class UwUi { } this.comms = new CommsClient('content-ui-port', this.logger, this.commsHandlers); - - console.log("UI INIT COMPLETE ——————————————————————"); } initVue() { @@ -159,7 +157,6 @@ class UwUi { } async initLoggerUi() { - console.log("CREATING UI"); const random = Math.round(Math.random() * 69420); const uwid = `uw-ui-root-${random}`; @@ -188,7 +185,6 @@ class UwUi { } async showLogger() { - console.log("SHOWING LOGGER!") if (!this.loggerUiInitiated) { await this.initLoggerUi(); } diff --git a/src/ext/uw.js b/src/ext/uw.js index f1ca0bb..3e8a121 100644 --- a/src/ext/uw.js +++ b/src/ext/uw.js @@ -60,9 +60,9 @@ class UW { } async init(){ - // if (Debug.debug) { + if (Debug.debug) { console.log("[uw::main] loading configuration ..."); - // } + } // logger init is the first thing that needs to run try { From 80c14f72be1c2040468442eb0e94661dc643e771 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Sun, 8 Mar 2020 18:47:01 +0100 Subject: [PATCH 08/19] comment out dead imports and code --- src/ext/lib/ar-detect/ArDetector.js | 2 +- src/ext/lib/video-data/PageInfo.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ext/lib/ar-detect/ArDetector.js b/src/ext/lib/ar-detect/ArDetector.js index 6bd4e36..3c05561 100644 --- a/src/ext/lib/ar-detect/ArDetector.js +++ b/src/ext/lib/ar-detect/ArDetector.js @@ -5,7 +5,7 @@ import EdgeStatus from './edge-detect/enums/EdgeStatusEnum'; import EdgeDetectPrimaryDirection from './edge-detect/enums/EdgeDetectPrimaryDirectionEnum'; import EdgeDetectQuality from './edge-detect/enums/EdgeDetectQualityEnum'; import GuardLine from './GuardLine'; -import DebugCanvas from './DebugCanvas'; +// import DebugCanvas from './DebugCanvas'; import VideoAlignment from '../../../common/enums/video-alignment.enum'; import AspectRatio from '../../../common/enums/aspect-ratio.enum'; diff --git a/src/ext/lib/video-data/PageInfo.js b/src/ext/lib/video-data/PageInfo.js index f248686..5f2fa5a 100644 --- a/src/ext/lib/video-data/PageInfo.js +++ b/src/ext/lib/video-data/PageInfo.js @@ -40,7 +40,7 @@ class PageInfo { } // try getting default crop immediately. - const cropModePersistence = this.settings.getDefaultCropPersistenceMode(window.location.host); + // const cropModePersistence = this.settings.getDefaultCropPersistenceMode(window.location.host); // try { // if (cropModePersistence === CropModePersistence.Forever) { From b3fce146f52d6a9193090f88334082c10ef8f99e Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 9 Mar 2020 19:11:08 +0100 Subject: [PATCH 09/19] Fix port naming --- src/ext/uw.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ext/uw.js b/src/ext/uw.js index 3e8a121..d82dc31 100644 --- a/src/ext/uw.js +++ b/src/ext/uw.js @@ -134,7 +134,7 @@ class UW { await this.settings.init(); } - this.comms = new CommsClient('content-ui-port', this.logger, this.commsHandlers); + this.comms = new CommsClient('content-main-port', this.logger, this.commsHandlers); // če smo razširitev onemogočili v nastavitvah, ne naredimo ničesar // If extension is soft-disabled, don't do shit From 26757c0b2d55d9eabd8d9d95a98643761905fbe5 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 9 Mar 2020 19:11:23 +0100 Subject: [PATCH 10/19] Remove redundant code --- src/ext/lib/comms/CommsClient.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/ext/lib/comms/CommsClient.js b/src/ext/lib/comms/CommsClient.js index 69352cb..4cb1c0e 100644 --- a/src/ext/lib/comms/CommsClient.js +++ b/src/ext/lib/comms/CommsClient.js @@ -9,8 +9,6 @@ class CommsClient { this.port = browser.runtime.connect({name: name}); } else if (BrowserDetect.chrome) { this.port = chrome.runtime.connect({name: name}); - } else if (BrowserDetect.edge) { - this.port = browser.runtime.connect({name: name}) } this.logger.onLogEnd( From bbc4247893bb2bff3ecbc980f71f4d513484f94f Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 9 Mar 2020 19:39:24 +0100 Subject: [PATCH 11/19] Don't overwrite existing ports on connect --- src/ext/lib/comms/CommsServer.js | 52 ++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/src/ext/lib/comms/CommsServer.js b/src/ext/lib/comms/CommsServer.js index 3d15c00..9432340 100644 --- a/src/ext/lib/comms/CommsServer.js +++ b/src/ext/lib/comms/CommsServer.js @@ -12,7 +12,7 @@ class CommsServer { var ths = this; if (BrowserDetect.firefox) { - browser.runtime.onConnect.addListener(p => ths.onConnect(p)); + browser.runtime.onConnect.addListener(p => this.onConnect(p)); browser.runtime.onMessage.addListener((m, sender) => ths.processReceivedMessage_nonpersistent(m, sender)); } else { chrome.runtime.onConnect.addListener(p => ths.onConnect(p)); @@ -166,9 +166,11 @@ class CommsServer { } sendToAll(message){ - for(var p of this.ports){ - for(var frame in p){ - p[frame].postMessage(message); + for(const tab of this.ports){ + for(const frame in tab){ + for (const port in tab[frame]) { + tab[frame][port].postMessage(message); + } } } } @@ -186,6 +188,12 @@ class CommsServer { } } + async sendToContentScripts(message, tab, frame) { + for (const port in this.ports[tab][frame]) { + this.ports[tab][frame][port].postMessage(message); + } + } + async sendToFrame(message, tab, frame) { this.logger.log('info', 'comms', `%c[CommsServer::sendToFrame] attempting to send message to tab ${tab}, frame ${frame}`, "background: #dda; color: #11D", message); @@ -204,7 +212,7 @@ class CommsServer { this.logger.log('info', 'comms', `%c[CommsServer::sendToFrame] attempting to send message to tab ${tab}, frame ${frame}`, "background: #dda; color: #11D", message); try { - this.ports[tab][frame].postMessage(message); + this.sendToContentScripts(message, tab, frame); } catch (e) { this.logger.log('error', 'comms', `%c[CommsServer::sendToFrame] Sending message failed. Reason:`, "background: #dda; color: #11D", e); } @@ -213,21 +221,20 @@ class CommsServer { async sendToActive(message) { this.logger.log('info', 'comms', "%c[CommsServer::sendToActive] trying to send a message to active tab. Message:", "background: #dda; color: #11D", message); - var tabs = await this._getActiveTab(); + const tabs = await this._getActiveTab(); this.logger.log('info', 'comms', "[CommsServer::_sendToActive] currently active tab(s)?", tabs); - for (var key in this.ports[tabs[0].id]) { - this.logger.log('info', 'comms', "key?", key, this.ports[tabs[0].id]); + for (const frame in this.ports[tabs[0].id]) { + this.logger.log('info', 'comms', "key?", frame, this.ports[tabs[0].id]); } - for (var key in this.ports[tabs[0].id]) { - this.ports[tabs[0].id][key].postMessage(message); + for (const frame in this.ports[tabs[0].id]) { + this.sendToContentScripts(message, tabs[0].id, frame); + this.ports[tabs[0].id][frame].postMessage(message); } } onConnect(port){ - var ths = this; - // poseben primer | special case if (port.name === 'popup-port') { this.popupPort = port; @@ -237,15 +244,22 @@ class CommsServer { var tabId = port.sender.tab.id; var frameId = port.sender.frameId; - if(! this.ports[tabId]){ + if (! this.ports[tabId]){ this.ports[tabId] = {}; } - this.ports[tabId][frameId] = port; - this.ports[tabId][frameId].onMessage.addListener( (m,p) => ths.processReceivedMessage(m, p)); - this.ports[tabId][frameId].onDisconnect.addListener( (p) => { - delete ths.ports[p.sender.tab.id][p.sender.frameId]; - if(Object.keys(ths.ports[p.sender.tab.id]).length === 0){ - ths.ports[tabId] = undefined; + if (! this.ports[tabId][frameId]) { + this.ports[tabId][frameId] = {}; + } + this.ports[tabId][frameId][port.name] = port; + this.ports[tabId][frameId][port.name].onMessage.addListener( (m,p) => ths.processReceivedMessage(m, p)); + + this.ports[tabId][frameId][port.name].onDisconnect.addListener( (p) => { + delete this.ports[p.sender.tab.id][p.sender.frameId][port.name]; + if (Object.keys(this.ports[tabId][frameId].length === 0)) { + delete this.ports[tabId][frameId]; + if(Object.keys(this.ports[p.sender.tab.id]).length === 0) { + delete this.ports[tabId]; + } } }); } From eee7d622b8e9a60df6c51e68a3d783917d02dc19 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 9 Mar 2020 19:41:15 +0100 Subject: [PATCH 12/19] Revert logging oopsie whoopsie --- src/ext/uw.js | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/ext/uw.js b/src/ext/uw.js index d82dc31..cf43eee 100644 --- a/src/ext/uw.js +++ b/src/ext/uw.js @@ -9,7 +9,17 @@ import Logger from './lib/Logger'; if(Debug.debug){ - console.log("Sᴛλʀᴛɪɴɢ Uʟᴛʀᴀᴡɪᴅɪꜰʏ UI"); + console.log("\n\n\n\n\n\n ——— Sᴛλʀᴛɪɴɢ Uʟᴛʀᴀᴡɪᴅɪꜰʏ ———\n << ʟᴏᴀᴅɪɴɢ ᴍᴀɪɴ ꜰɪʟᴇ >>\n\n\n\n"); + try { + if(window.self !== window.top){ + console.log("%cWe aren't in an iframe.", "color: #afc, background: #174"); + } + else{ + console.log("%cWe are in an iframe!", "color: #fea, background: #d31", window.self, window.top); + } + } catch (e) { + console.log("%cWe are in an iframe!", "color: #fea, background: #d31"); + } } if (BrowserDetect.edge) { From 5b417d3f475253c97c63a9daabde294553edb5bd Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 9 Mar 2020 21:29:00 +0100 Subject: [PATCH 13/19] cosmetic fix --- src/ext/lib/comms/CommsClient.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ext/lib/comms/CommsClient.js b/src/ext/lib/comms/CommsClient.js index 4cb1c0e..a569601 100644 --- a/src/ext/lib/comms/CommsClient.js +++ b/src/ext/lib/comms/CommsClient.js @@ -119,7 +119,7 @@ class CommsClient { announceZoom(scale){ this.port.postMessage({cmd: "announce-zoom", zoom: scale}); - this.registerVideo() + this.registerVideo(); } From 0edb5d5c4fa06c2368edf69d270d33e7540ec1c3 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 9 Mar 2020 21:29:10 +0100 Subject: [PATCH 14/19] add words to dictionary --- .vscode/settings.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.vscode/settings.json b/.vscode/settings.json index a972a99..a3fb1d6 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -16,6 +16,7 @@ "resizer", "textbox", "videodata", + "vuex", "youtube" ], "cSpell.ignoreWords": [ From 2a1419eb53a002b267169e8f1fc2990468143231 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 9 Mar 2020 21:29:24 +0100 Subject: [PATCH 15/19] Fix uw script --- src/ext/uw.js | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/ext/uw.js b/src/ext/uw.js index cf43eee..c7fd89e 100644 --- a/src/ext/uw.js +++ b/src/ext/uw.js @@ -113,9 +113,6 @@ class UW { if (this.logger.isLoggingAllowed()) { console.info("[uw::init] Logging is allowed! Initalizing vue and UI!"); - this.initVue(); - this.initUi(); - this.logger.setVuexStore(this.vuexStore); } // show popup if logging to file is enabled @@ -179,8 +176,6 @@ class UW { } catch (e) { this.logger.log('error', 'debug', "[uw::init] FAILED TO START EXTENSION. Error:", e); } - - console.log("....") } From cf1cc3d87a83476fdcbed77bb258659fe65026d7 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 9 Mar 2020 21:29:39 +0100 Subject: [PATCH 16/19] Fix logger popup initialization. --- src/ext/lib/comms/CommsServer.js | 25 +++++++++------- src/ext/uw-bg.js | 49 ++++++++++++++++++++++++++++++-- src/ext/uw-ui.js | 20 +++++++++++-- 3 files changed, 79 insertions(+), 15 deletions(-) diff --git a/src/ext/lib/comms/CommsServer.js b/src/ext/lib/comms/CommsServer.js index 9432340..72c8067 100644 --- a/src/ext/lib/comms/CommsServer.js +++ b/src/ext/lib/comms/CommsServer.js @@ -9,14 +9,12 @@ class CommsServer { this.ports = []; this.popupPort = null; - var ths = this; - if (BrowserDetect.firefox) { browser.runtime.onConnect.addListener(p => this.onConnect(p)); - browser.runtime.onMessage.addListener((m, sender) => ths.processReceivedMessage_nonpersistent(m, sender)); + browser.runtime.onMessage.addListener((m, sender) => this.processReceivedMessage_nonpersistent(m, sender)); } else { chrome.runtime.onConnect.addListener(p => ths.onConnect(p)); - chrome.runtime.onMessage.addListener((m, sender, callback) => ths.processReceivedMessage_nonpersistent(m, sender, callback)); + chrome.runtime.onMessage.addListener((m, sender, callback) => this.processReceivedMessage_nonpersistent(m, sender, callback)); } // commands — functions that handle incoming messages @@ -230,7 +228,6 @@ class CommsServer { for (const frame in this.ports[tabs[0].id]) { this.sendToContentScripts(message, tabs[0].id, frame); - this.ports[tabs[0].id][frame].postMessage(message); } } @@ -238,7 +235,7 @@ class CommsServer { // poseben primer | special case if (port.name === 'popup-port') { this.popupPort = port; - this.popupPort.onMessage.addListener( (m,p) => ths.processReceivedMessage(m,p)); + this.popupPort.onMessage.addListener( (m,p) => this.processReceivedMessage(m,p)); return; } @@ -251,10 +248,14 @@ class CommsServer { this.ports[tabId][frameId] = {}; } this.ports[tabId][frameId][port.name] = port; - this.ports[tabId][frameId][port.name].onMessage.addListener( (m,p) => ths.processReceivedMessage(m, p)); + this.ports[tabId][frameId][port.name].onMessage.addListener( (m,p) => this.processReceivedMessage(m, p)); - this.ports[tabId][frameId][port.name].onDisconnect.addListener( (p) => { - delete this.ports[p.sender.tab.id][p.sender.frameId][port.name]; + this.ports[tabId][frameId][port.name].onDisconnect.addListener( (p) => { + try { + delete this.ports[p.sender.tab.id][p.sender.frameId][port.name]; + } catch (e) { + // no biggie if the thing above doesn't exist. + } if (Object.keys(this.ports[tabId][frameId].length === 0)) { delete this.ports[tabId][frameId]; if(Object.keys(this.ports[p.sender.tab.id]).length === 0) { @@ -273,7 +274,11 @@ class CommsServer { ); if (this.commands[message.cmd]) { for (const c of this.commands[message.cmd]) { - await c(message, portOrSender, sendResponse); + try { + await c(message, portOrSender, sendResponse); + } catch (e) { + this.logger.log('error', 'debug', "[CommsServer.js::execCmd] failed to execute command.", e) + } } } } diff --git a/src/ext/uw-bg.js b/src/ext/uw-bg.js index 0fa8680..22a493f 100644 --- a/src/ext/uw-bg.js +++ b/src/ext/uw-bg.js @@ -4,7 +4,15 @@ import CommsServer from './lib/comms/CommsServer'; import Settings from './lib/Settings'; import Logger from './lib/Logger'; -import sleep from '../common/js/utils'; +import { sleep } from '../common/js/utils'; + +// we need vue in bg script, so we can get vuex. +// and we need vuex so popup will be initialized +// after the first click without resorting to ugly, +// dirty hacks +import Vue from 'vue'; +import Vuex from 'vuex'; +import VuexWebExtensions from 'vuex-webextensions'; var BgVars = { arIsActive: true, @@ -29,6 +37,8 @@ class UWServer { 'siteSettings': undefined, 'videoSettings': undefined, } + + this.uiLoggerInitialized = false; } async setup() { @@ -51,8 +61,9 @@ class UWServer { this.settings = new Settings({logger: this.logger}); await this.settings.init(); this.comms = new CommsServer(this); - this.comms.subscribe('show-logger', async () => await this.initUi()); + this.comms.subscribe('show-logger', async () => await this.initUiAndShowLogger()); this.comms.subscribe('init-vue', async () => await this.initUi()); + this.comms.subscribe('uwui-vue-initialized', () => this.uiLoggerInitialized = true); var ths = this; @@ -103,6 +114,10 @@ class UWServer { extractHostname(url){ var hostname; + if (!url) { + return ""; + } + // extract hostname if (url.indexOf("://") > -1) { //find & remove protocol (http, ftp, etc.) and get hostname hostname = url.split('/')[2]; @@ -218,11 +233,41 @@ class UWServer { }, () => resolve()) ); } + } catch (e) { this.logger.log('ERROR', 'uwbg', 'UI initialization failed. Reason:', e); } } + async initUiAndShowLogger() { + // this implementation is less than optimal and very hacky, but it should work + // just fine for our use case. + this.uiLoggerInitialized = false; + + await this.initUi(); + + await new Promise( async (resolve, reject) => { + // if content script doesn't give us a response within 5 seconds, something is + // obviously wrong and we stop waiting, + + // oh and btw, resolve/reject do not break the loops, so we need to do that + // ourselves: + // https://stackoverflow.com/questions/55207256/will-resolve-in-promise-loop-break-loop-iteration + let isRejected = false; + setTimeout( async () => {isRejected = true; reject()}, 5000); + + // check whether UI has been initiated on the FE. If it was, we resolve the + // promise and off we go + while (!isRejected) { + if (this.uiLoggerInitialized) { + resolve(); + return; // remember the bit about resolve() not breaking the loop? + } + await sleep(100); + } + }) + } + async getCurrentTab() { if (BrowserDetect.firefox) { return (await browser.tabs.query({active: true, currentWindow: true}))[0]; diff --git a/src/ext/uw-ui.js b/src/ext/uw-ui.js index e543b1b..d3607bc 100644 --- a/src/ext/uw-ui.js +++ b/src/ext/uw-ui.js @@ -8,6 +8,7 @@ import LoggerUi from '../csui/LoggerUi'; import Logger from './lib/Logger'; import Settings from './lib/Settings'; import CommsClient from './lib/comms/CommsClient'; +import Comms from './lib/comms/Comms'; class UwUi { @@ -31,8 +32,8 @@ class UwUi { // * if video/player is detected (which can only happen if extension is enabled // for that particular site) - // initialize vuejs, but only once (check handled in initVue()) - this.initVue(); + // NOTE: we need to setup logger and comms _before_ initializing vue (unless we're starting) + // because logger settings say we should // setup logger try { @@ -74,7 +75,7 @@ class UwUi { if (this.logger.isLoggingAllowed()) { console.info("[uw::init] Logging is allowed! Initalizing vue and UI!"); this.initVue(); - this.initUi(); + this.initLoggerUi(); this.logger.setVuexStore(this.vuexStore); } @@ -107,11 +108,17 @@ class UwUi { } this.comms = new CommsClient('content-ui-port', this.logger, this.commsHandlers); + + // initialize vuejs, but only once (check handled in initVue()) + // we need to initialize this _after_ initializing comms. + this.initVue(); } initVue() { // never init twice if (this.vueInitiated) { + // let background script know it can proceed with sending 'show-logger' command. + Comms.sendMessage({cmd: 'uwui-vue-initialized'}); return; } @@ -154,6 +161,9 @@ class UwUi { // make sure we don't init twice this.vueInitiated = true; + + // let background script know it can proceed with sending 'show-logger' command. + Comms.sendMessage({cmd: 'uwui-vue-initialized'}); } async initLoggerUi() { @@ -188,6 +198,7 @@ class UwUi { if (!this.loggerUiInitiated) { await this.initLoggerUi(); } + try { this.vuexStore.dispatch('uw-show-logger'); @@ -215,5 +226,8 @@ if (! document.getElementById(markerId)) { const uwui = new UwUi(); uwui.init(); +} else { + // let background script know it can proceed with sending 'show-logger' command. + Comms.sendMessage({cmd: 'uwui-vue-initialized'}); } From a81c5765e1d86d020632eaf1c968030536984587 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 9 Mar 2020 21:41:31 +0100 Subject: [PATCH 17/19] Minor fixes for chrome --- src/ext/lib/comms/CommsServer.js | 2 +- src/ext/uw-bg.js | 5 ++--- src/popup/panels/VideoPanel.vue | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/ext/lib/comms/CommsServer.js b/src/ext/lib/comms/CommsServer.js index 72c8067..e2d8b56 100644 --- a/src/ext/lib/comms/CommsServer.js +++ b/src/ext/lib/comms/CommsServer.js @@ -13,7 +13,7 @@ class CommsServer { browser.runtime.onConnect.addListener(p => this.onConnect(p)); browser.runtime.onMessage.addListener((m, sender) => this.processReceivedMessage_nonpersistent(m, sender)); } else { - chrome.runtime.onConnect.addListener(p => ths.onConnect(p)); + chrome.runtime.onConnect.addListener(p => this.onConnect(p)); chrome.runtime.onMessage.addListener((m, sender, callback) => this.processReceivedMessage_nonpersistent(m, sender, callback)); } diff --git a/src/ext/uw-bg.js b/src/ext/uw-bg.js index 22a493f..767e8f5 100644 --- a/src/ext/uw-bg.js +++ b/src/ext/uw-bg.js @@ -66,11 +66,10 @@ class UWServer { this.comms.subscribe('uwui-vue-initialized', () => this.uiLoggerInitialized = true); - var ths = this; if(BrowserDetect.firefox) { - browser.tabs.onActivated.addListener(function(m) {ths.onTabSwitched(m)}); + browser.tabs.onActivated.addListener(function(m) {this.onTabSwitched(m)}); } else if (BrowserDetect.chrome) { - chrome.tabs.onActivated.addListener(function(m) {ths.onTabSwitched(m)}); + chrome.tabs.onActivated.addListener(function(m) {this.onTabSwitched(m)}); } } diff --git a/src/popup/panels/VideoPanel.vue b/src/popup/panels/VideoPanel.vue index a75d401..ae9a741 100644 --- a/src/popup/panels/VideoPanel.vue +++ b/src/popup/panels/VideoPanel.vue @@ -157,7 +157,7 @@ export default { }, methods: { async openOptionsPage() { - browser.runtime.openOptionsPage(); + (browser ?? chrome).runtime.openOptionsPage(); }, execAction(action) { this.exec.exec(action, 'page', this.frame); From 3f51048c1a106eb6acd697c147614adb70348438 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 9 Mar 2020 22:06:34 +0100 Subject: [PATCH 18/19] Patch notes --- CHANGELOG.md | 9 ++++++++- src/popup/panels/WhatsNewPanel.vue | 27 +++++++++++++++++++++++---- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ab94cc..5521f21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,14 @@ QoL improvements for me: * logging: allow to enable logging at will and export said logs to a file -### v4.4.5 (current) +### v4.4.6 (current) + +* Ensured that Vue part of the content script (logger UI) only loads when necessary in order to fix breakage on certain sites (#96). +* Disabling (or enabling, if running in whitelist-only mode) specific sites used to not work (#91). This issue appears to have been fixed. +* Default stretch mode for sites is now probably being observed, too (#94). +* It's been almost a month and Chrome Web Store still hasn't finished the review of the 4.4.4.1 (and 4.4.4.2) revisions because when it comes to incompetence, it's hard to expect anything less from Google. I've did some proverbial yelling at the support in hopes that Chrome version will finally see an update (disclaimer: when I said yelling I really mean a polite request, because support staff doesn't deserve abuse because a different department is utter shite at doing their jobs). + +### v4.4.5 * Extension no longer requires `allTabs` and `webNavigation` permissions * Some CSS on the debugger popup was not scoped, causing issues with some sites. diff --git a/src/popup/panels/WhatsNewPanel.vue b/src/popup/panels/WhatsNewPanel.vue index 9244c83..b467ca9 100644 --- a/src/popup/panels/WhatsNewPanel.vue +++ b/src/popup/panels/WhatsNewPanel.vue @@ -2,12 +2,31 @@

What's new

Full changelog for older versions is available here.

-

4.4.5

+

4.4.6

    -
  • Extension no longer requires allTabs and webNavigation permissions
  • -
  • Some CSS on the logger popup was not scoped, causing display issues with some sites (#92)
  • -
  • Fix some additional issues with video alignment when changing videos on autoplay
  • +
  • Ensured that Vue part of the content script (logger UI) only loads when necessary in order to fix breakage on certain sites (#96).
  • +
  • Disabling (or enabling, if running in whitelist-only mode) specific sites used to not work (#91). This issue appears to have been fixed.
  • +
  • Default stretch mode for sites is now probably being observed, too (#94).
+ +