From 84eed2fa1335f3660271a247a48e8b880a5e7e39 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 15 Jul 2019 22:54:41 +0200 Subject: [PATCH 01/52] Import/export settings --- src/manifest.json | 3 ++ src/options/GeneralSettings.vue | 76 ++++++++++++++++++++++++++++++--- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/src/manifest.json b/src/manifest.json index 9106a71..7eb5243 100644 --- a/src/manifest.json +++ b/src/manifest.json @@ -55,5 +55,8 @@ ], "permissions": [ "tabs", "storage", "activeTab", "", "webNavigation" + ], + "optional_permissions": [ + "downloads" ] } diff --git a/src/options/GeneralSettings.vue b/src/options/GeneralSettings.vue index 3f5b465..a22ff5d 100644 --- a/src/options/GeneralSettings.vue +++ b/src/options/GeneralSettings.vue @@ -116,13 +116,31 @@
- Reset settings + Import, export, reset settings
-
- + Settings import failed. The settings file is probably corrupted. +
+
+
+ + +
+
@@ -132,6 +150,7 @@ import Button from '../common/components/Button'; import Stretch from '../common/enums/stretch.enum'; import ExtensionMode from '../common/enums/extension-mode.enum'; import VideoAlignment from '../common/enums/video-alignment.enum'; +import BrowserDetect from '../ext/conf/BrowserDetect'; export default { components: { @@ -146,6 +165,7 @@ export default { ExtensionMode: ExtensionMode, VideoAlignment: VideoAlignment, stretchThreshold: 0, + corruptedSettingsWarning: false, } }, created () { @@ -178,8 +198,54 @@ export default { resetSettings() { this.settings.active = JSON.parse(JSON.stringify(this.settings.default)); this.settings.save(); + }, + exportSettings() { + browser.permissions.request({permissions: ['downloads']}); + const blob = new Blob([JSON.stringify(this.settings.active)], {type: 'application/json'}); + const fileUrl = URL.createObjectURL(blob); + if (BrowserDetect.firefox) { + browser.downloads.download({saveAs: true, filename: 'ultrawidify-settings.json', url: fileUrl}); + } + }, + async importSettings($event) { + let file, text, settingsObj; + this.corruptedSettingsWarning = false; + + try { + file = $event.target.files[0]; + } catch (e) { + console.error("error grabbing a file!"); + this.corruptedSettingsWarning = true; + return; + } + + try { + text = await file.text(); + settingsObj = JSON.parse(text); + } catch (e) { + console.error("error parsing file to json"); + this.corruptedSettingsWarning = true; + return; + } + + // validate settings + for (const key in this.settings.default) { + if (!settingsObj[key]) { + console.error("corrupted settings!") + this.corruptedSettingsWarning = true; + return; + } + } + + this.settings.active = settingsObj; + this.settings.save(); } } } + From 060d644487fdd2d1eb0a08c8d72b5735b5c15ff8 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 15 Jul 2019 23:17:55 +0200 Subject: [PATCH 02/52] Version update --- src/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/manifest.json b/src/manifest.json index 7eb5243..8c48f66 100644 --- a/src/manifest.json +++ b/src/manifest.json @@ -2,7 +2,7 @@ "manifest_version": 2, "name": "Ultrawidify", "description": "Removes black bars on ultrawide videos and offers advanced options to fix aspect ratio.", - "version": "4.2.1", + "version": "4.2.2", "applications": { "gecko": { "id": "{cf02b1a7-a01a-4e37-a609-516a283f1ed3}" From e08a7eea74cb0ec5a34c2f75df2588f3df323284 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Mon, 15 Jul 2019 23:18:12 +0200 Subject: [PATCH 03/52] Export settings but for chrome. Also some fixes for FF --- src/options/GeneralSettings.vue | 49 ++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/src/options/GeneralSettings.vue b/src/options/GeneralSettings.vue index a22ff5d..2daee9f 100644 --- a/src/options/GeneralSettings.vue +++ b/src/options/GeneralSettings.vue @@ -119,7 +119,12 @@ Import, export, reset settings
-
+ Exporting settings requires the 'downloads' permission. (If you want to export settings without granting 'downloads' permission, you can copy-paste settings from 'Super advanced settings' tab) +
+
Settings import failed. The settings file is probably corrupted. @@ -165,7 +170,8 @@ export default { ExtensionMode: ExtensionMode, VideoAlignment: VideoAlignment, stretchThreshold: 0, - corruptedSettingsWarning: false, + corruptedSettingsError: false, + downloadPermissionError: false, } }, created () { @@ -199,23 +205,46 @@ export default { this.settings.active = JSON.parse(JSON.stringify(this.settings.default)); this.settings.save(); }, - exportSettings() { - browser.permissions.request({permissions: ['downloads']}); + async exportSettings() { + this.downloadPermissionError = false; + const blob = new Blob([JSON.stringify(this.settings.active)], {type: 'application/json'}); const fileUrl = URL.createObjectURL(blob); - if (BrowserDetect.firefox) { - browser.downloads.download({saveAs: true, filename: 'ultrawidify-settings.json', url: fileUrl}); + + try { + if (BrowserDetect.firefox) { + await browser.permissions.request({permissions: ['downloads']}); + browser.downloads.download({saveAs: true, filename: 'ultrawidify-settings.json', url: fileUrl}); + } else if (BrowserDetect.chrome) { + const ths = this; + + chrome.permissions.request( + {permissions: ['downloads']}, + (granted) => { + if (granted) { + ths.exportSettingsChrome(fileUrl); + } else { + ths.downloadPermissionError = true + } + } + ) + } + } catch (e) { + this.downloadPermissionError = true; } }, + exportSettingsChrome(fileUrl){ + chrome.downloads.download({saveAs: true, filename: 'ultrawidify-settings.json', url: fileUrl}); + }, async importSettings($event) { let file, text, settingsObj; - this.corruptedSettingsWarning = false; + this.corruptedSettingsError = false; try { file = $event.target.files[0]; } catch (e) { console.error("error grabbing a file!"); - this.corruptedSettingsWarning = true; + this.corruptedSettingsError = true; return; } @@ -224,7 +253,7 @@ export default { settingsObj = JSON.parse(text); } catch (e) { console.error("error parsing file to json"); - this.corruptedSettingsWarning = true; + this.corruptedSettingsError = true; return; } @@ -232,7 +261,7 @@ export default { for (const key in this.settings.default) { if (!settingsObj[key]) { console.error("corrupted settings!") - this.corruptedSettingsWarning = true; + this.corruptedSettingsError = true; return; } } From 9072183dd1dd6a727cdc0cfca974507d41e12ab6 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Tue, 16 Jul 2019 20:59:12 +0200 Subject: [PATCH 04/52] Added logger --- src/ext/lib/Logger.js | 103 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 src/ext/lib/Logger.js diff --git a/src/ext/lib/Logger.js b/src/ext/lib/Logger.js new file mode 100644 index 0000000..08b6d0b --- /dev/null +++ b/src/ext/lib/Logger.js @@ -0,0 +1,103 @@ +class Logger { + constructor(conf) { + this.conf = conf; + this.history = []; + this.startTime = performance.now(); + } + + clear() { + this.log = []; + this.startTime = performance.now(); + } + + setConf(conf) { + this.conf = conf; + } + + // allow syncing of start times between bg and page scripts. + // may result in negative times in the log file, but that doesn't + // really matter + getStartTime() { + return this.startTime; + } + setStartTime(startTime) { + if (startTime) { + this.startTime = startTime; + } else { + this.startTime = performance.now(); + } + } + + getLogFileString() { + let logfileStr = ''; + let logTs = ''; // number of seconds since extension started on a given page¸ + for (let i = 0; i < this.history.length; i++) { + logTs = ((this.history[i].ts - Math.floor(this.performance.now)) / 3).toFixed(3); + logfileStr = `${logfileStr}[@${logTs}] -- ${this.history[i].message}\n` + } + + return logfileStr; + } + + // level is unused as of now, but this may change in the future + log(level, component, ...message) { + if (this.conf.logToFile) { + if (this.conf.fileOptions[component]) { + let ts = performance.now(); + if (ts <= this.history[this.history.length - 1]) { + ts = this.history[this.history.length - 1] + 0.00001; + } + + this.history.push({ + ts: ts, + message: JSON.stringify(message), + }) + } + } + if (this.conf.logToConsole) { + if (this.conf.consoleOptions[component]) { + console.log(...message); + } + } + } + + // leaves a noticeable mark in the file log at the time it got triggered, as well as + // at the intervals of 1s and .5s before the trigger moment + cahen() { + if (this.conf.logToFile) { + let ts = performance.now(); + let secondMark = ts - 1000; + let halfSecondMark = ts - 500; + let i = this.history.length(); + + // correct ts _after_ secondMark and halfSecondMark were determined + if (ts <= this.history[this.history.length - 1]) { + ts = this.history[this.history.length - 1] + 0.00001; + } + + this.history.push({ + ts: ts, + message: "-------------------------------------- CAHEN --------------------------------------" + }); + + // find the spot for the half second mark. In this case, we don't really particularly care whether timestamps + // are duped due to cahen warnings + while (this.history[i--].ts > halfSecondMark) {} + this.history.push({ + ts: halfSecondMark, + message: "-------------------------------------- 0.5s to CAHEN --------------------------------------" + }); + + // repeat for one second warning + while (this.history[i--].ts > secondMark) {} + this.history.push({ + ts: secondMark, + message: "-------------------------------------- 1s to CAHEN --------------------------------------" + }); + } + } + + +} + +export default Logger; From f0fa6aa9a84d9a159453ed5f66146bd21bea3937 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Tue, 16 Jul 2019 22:46:16 +0200 Subject: [PATCH 05/52] Replaced console.logs with logger in ArDetect. Other places still need changing. --- src/ext/lib/Logger.js | 20 +++- src/ext/lib/ar-detect/ArDetector.js | 163 ++++++++-------------------- 2 files changed, 66 insertions(+), 117 deletions(-) diff --git a/src/ext/lib/Logger.js b/src/ext/lib/Logger.js index 08b6d0b..fe3546c 100644 --- a/src/ext/lib/Logger.js +++ b/src/ext/lib/Logger.js @@ -39,10 +39,26 @@ class Logger { return logfileStr; } + canLog(component) { + if (component.length) { + for (const c in component) { + if (this.conf.fileOptions[component]) { + return this.conf.fileOptions[component]; + } + } + } + return this.conf.fileOptions[component]; + } + // level is unused as of now, but this may change in the future + // levels: 'info', 'warn', 'error' log(level, component, ...message) { + + if (!this.conf) { + return; + } if (this.conf.logToFile) { - if (this.conf.fileOptions[component]) { + if (this.canLog(component)) { let ts = performance.now(); if (ts <= this.history[this.history.length - 1]) { ts = this.history[this.history.length - 1] + 0.00001; @@ -55,7 +71,7 @@ class Logger { } } if (this.conf.logToConsole) { - if (this.conf.consoleOptions[component]) { + if (this.canLog(component)) { console.log(...message); } } diff --git a/src/ext/lib/ar-detect/ArDetector.js b/src/ext/lib/ar-detect/ArDetector.js index 37bbe18..4675d0f 100644 --- a/src/ext/lib/ar-detect/ArDetector.js +++ b/src/ext/lib/ar-detect/ArDetector.js @@ -10,7 +10,8 @@ import AspectRatio from '../../../common/enums/aspect-ratio.enum'; class ArDetector { - constructor(videoData){ + constructor(videoData, logger){ + this.logger = logger; this.conf = videoData; this.video = videoData.video; this.settings = videoData.settings; @@ -35,9 +36,7 @@ class ArDetector { this._nextTick = false; this.canDoFallbackMode = false; - if (Debug.init) { - console.log("[ArDetector::ctor] creating new ArDetector. arid:", this.arid); - } + this.logger.log('info', 'init', `[ArDetector::ctor] creating new ArDetector. arid: ${this.arid}`); } setManualTick(manualTick) { @@ -49,9 +48,7 @@ class ArDetector { } init(){ - if (Debug.debug || Debug.init) { - console.log("[ArDetect::init] Initializing autodetection. arid:", this.arid); - } + this.logger.log('info', 'init', `[ArDetect::init] <@${this.arid}> Initializing autodetection.`); try { if (this.settings.canStartAutoAr()) { @@ -60,36 +57,27 @@ class ArDetector { throw "Settings prevent autoar from starting" } } catch (e) { - if (Debug.debug) { - console.log("%c[ArDetect::init] INITIALIZATION FAILED!\n", _ard_console_stop, e); - } + this.logger.log('error', 'init', `%c[ArDetect::init] <@${this.arid}> Initialization failed.`, _ard_console_stop, e); } } destroy(){ - if(Debug.debug || Debug.init) { - console.log(`[ArDetect::destroy] `) - } + this.logger.log('info', 'init', `%c[ArDetect::destroy] <@${this.arid}> Destroying aard.`, _ard_console_stop, e); // this.debugCanvas.destroy(); this.stop(); } setup(cwidth, cheight){ - if(Debug.debug || Debug.init) { - console.log("[ArDetect::setup] Starting autodetection setup. arid:", this.arid); - } - + this.logger.log('info', 'init', `[ArDetect::setup] <@${this.arid}> Starting autodetection setup.`); // // [-1] check for zero-width and zero-height videos. If we detect this, we kick the proverbial // can some distance down the road. This problem will prolly fix itself soon. We'll also // not do any other setup until this issue is fixed // if(this.video.videoWidth === 0 || this.video.videoHeight === 0 ){ - if(Debug.debug){ - console.log("[ArDetector::setup] video has no width or height!", this.video.videoWidth,"×", this.video.videoHeight) - } + this.logger.log('warn', 'debug', `[ArDetect::setup] <@${this.arid}> This video has zero width or zero height. Dimensions: ${this.video.videoWidth} × ${this.video.videoHeight}`); + this.scheduleInitRestart(); - return; } @@ -169,9 +157,7 @@ class ArDetector { // if (this.fallbackMode) { - if(Debug.debug) { - console.log("%c[ArDetect::setup] WARNING: CANVAS RESET DETECTED - recalculating guardLine", "background: #000; color: #ff2" ) - } + this.logger.log('warn', 'debug', `[ArDetect::setup] <@${this.arid}> WARNING: CANVAS RESET DETECTED/we're in fallback mode - recalculating guardLine`, "background: #000; color: #ff2"); // blackbar, imagebar this.guardLine.reset(); } @@ -213,9 +199,8 @@ class ArDetector { } start() { - if (Debug.debug) { - console.log("%c[ArDetect::setup] Starting automatic aspect ratio detection.", _ard_console_start); - } + this.logger.log('info', 'debug', `"%c[ArDetect::start] <@${this.arid}> Starting automatic aspect ratio detection`, _ard_console_start); + if (this.conf.resizer.lastAr.type === AspectRatio.Automatic) { // ensure first autodetection will run in any case this.conf.resizer.setLastAr({type: AspectRatio.Automatic, ratio: this.getDefaultAr()}); @@ -225,7 +210,6 @@ class ArDetector { this.main(); this._halted = false; this._paused = false; - } unpause() { @@ -243,9 +227,7 @@ class ArDetector { } stop(){ - if(Debug.debug){ - console.log("%c[ArDetect::_ard_stop] Stopping automatic aspect ratio detection", _ard_console_stop); - } + this.logger.log('info', 'debug', `"%c[ArDetect::stop] <@${this.arid}> Stopping automatic aspect ratio detection`, _ard_console_stop); this._halted = true; // this.conf.resizer.setArLastAr(); } @@ -263,21 +245,15 @@ class ArDetector { let exitedRetries = 10; while (!this._exited && exitedRetries --> 0) { - if (Debug.debug) { - console.log("[ArDetector::main] We are trying to start another instance of autodetection on current video, but the previous instance hasn't exited yet. Waiting for old instance to exit ...") - } + this.logger.log('warn', 'debug', `[ArDetect::main] <@${this.arid}> We are trying to start another instance of autodetection on current video, but the previous instance hasn't exited yet. Waiting for old instance to exit ...`); await this.sleep(this.settings.active.arDetect.timers.tickrate); } if (!this._exited) { - if (Debug.debug) { - console.log("[ArDetector::main] Previous instance didn't exit in time. Not starting a new one.") - } + this.logger.log('error', 'debug', `[ArDetect::main] <@${this.arid}> Previous instance didn't exit in time. Not starting a new one.`); return; } - if (Debug.debug) { - console.log("%c[ArDetect::main] Main autodetection loop started.", _ard_console_start); - } + this.logger.log('info', 'debug', `%c[ArDetect::main] <@${this.arid}> Previous instance didn't exit in time. Not starting a new one.`); // we need to unhalt: this._halted = false; @@ -304,9 +280,7 @@ class ArDetector { try { this.frameCheck(); } catch (e) { - if (Debug.debug) { - console.log("%c[ArDetector::main] Frame check failed:", "color: #000, background: #f00", e); - } + this.logger.log('error', 'debug', `%c[ArDetect::main] <@${this.arid}> Frame check failed:`, "color: #000, background: #f00", e); } if (Debug.performanceMetrics) { @@ -320,9 +294,7 @@ class ArDetector { await this.sleep(this.settings.active.arDetect.timers.tickrate); } - if (Debug.debug) { - console.log(`%c[ArDetect::main] Main autodetection loop exited. Halted? ${this._halted}`, _ard_console_stop); - } + this.logger.log('info', 'debug', `%c[ArDetect::main] <@${this.arid}> Main autodetection loop exited. Halted? ${this._halted}`, _ard_console_stop); this._exited = true; } @@ -367,8 +339,10 @@ class ArDetector { this.setupTimer = setTimeout(function(){ ths.setupTimer = null; try{ - ths.main(); - }catch(e){console.log("[ArDetector::scheduleInitRestart] Failed to start init(). Error:",e)} + ths.main(); + } catch(e) { + this.logger('error', 'debug', `[ArDetector::scheduleInitRestart] <@${this.arid}> Failed to start main(). Error:`,e); + } ths = null; }, timeout @@ -393,9 +367,8 @@ class ArDetector { } canvasReadyForDrawWindow(){ - if(Debug.debug) - console.log("%c[ArDetect::_ard_canvasReadyForDrawWindow] (?)", "color: #44f", this.canvas.height == window.innerHeight, "(ard_height:", this.canvas.height, "| window height:", window.innerHeight, ")"); - + this.logger.log('info', 'debug', `%c[ArDetect::canvasReadyForDrawWindow] <@${this.arid}> canvas is ${this.canvas.height === window.innerHeight ? '' : 'NOT '}ready for drawWindow(). Canvas height: ${this.canvas.height}px; window inner height: ${window.innerHeight}px.`) + return this.canvas.height == window.innerHeight } @@ -405,9 +378,9 @@ class ArDetector { if( execTime > this.settings.active.arDetect.autoDisable.maxExecutionTime ){ // this.detectionTimeoutEventCount++; - if(Debug.debug){ - console.log("[ArDetect::getTimeout] Exec time exceeded maximum allowed execution time. This has now happened " + this.detectionTimeoutEventCount + " times in a row."); - } + // if(Debug.debug){ + // console.log("[ArDetect::getTimeout] Exec time exceeded maximum allowed execution time. This has now happened " + this.detectionTimeoutEventCount + " times in a row."); + // } // if( this.detectionTimeoutEventCount >= this.settings.active.arDetect.autoDisable.consecutiveTimeoutCount ){ // if (Debug.debug){ @@ -482,9 +455,7 @@ class ArDetector { var trueHeight = this.canvas.height * zoomFactor - letterbox; if(edges.top > 1 && edges.top <= this.settings.active.arDetect.fallbackMode.noTriggerZonePx ){ - if(Debug.debug && Debug.debugArDetect) { - console.log("Edge is in the no-trigger zone. Aspect ratio change is not triggered.") - } + this.logger.log('info', 'arDetect', `%c[ArDetect::calculateArFromEdges] <@${this.arid}> Edge is in the no-trigger zone. Aspect ratio change is not triggered.`) return; } @@ -499,7 +470,6 @@ class ArDetector { } processAr(trueAr){ - let actualHeight = 0; // purely for fallback mode this.detectedAr = trueAr; // poglejmo, če se je razmerje stranic spremenilo @@ -520,33 +490,22 @@ class ArDetector { // ali je sprememba v mejah dovoljenega? Če da -> fertik // is ar variance within acceptable levels? If yes -> we done - if(Debug.debug && Debug.debugArDetect) - console.log("%c[ArDetect::processAr] new aspect ratio varies from the old one by this much:\n","color: #aaf","old Ar", lastAr.ar, "current ar", trueAr, "arDiff (absolute):",arDiff,"ar diff (relative to new ar)", arDiff_percent); - + this.logger.log('info', 'arDetect', `%c[ArDetect::processAr] <@${this.arid}> New aspect ratio varies from the old one by this much:\n`,"color: #aaf","old Ar", lastAr.ar, "current ar", trueAr, "arDiff (absolute):",arDiff,"ar diff (relative to new ar)", arDiff_percent); + if (arDiff < trueAr * this.settings.active.arDetect.allowedArVariance){ - if(Debug.debug && Debug.debugArDetect) - console.log("%c[ArDetect::processAr] aspect ratio change denied — diff %:", "background: #740; color: #fa2", arDiff_percent) - + this.logger.log('info', 'arDetect', `%c[ArDetect::processAr] <@${this.arid}> Aspect ratio change denied — diff %: ${arDiff_percent}`, "background: #740; color: #fa2"); return; } - else if(Debug.debug && Debug.debugArDetect){ - console.log("%c[ArDetect::processAr] aspect ratio change accepted — diff %:", "background: #153; color: #4f9", arDiff_percent) - } - } - - if(Debug.debug) { - - console.log("%c[ArDetect::processAr] Triggering aspect ratio change. New aspect ratio: ", _ard_console_change, trueAr); + this.logger.log('info', 'arDetect', `%c[ArDetect::processAr] <@${this.arid}> aspect ratio change accepted — diff %: ${arDiff_percent}`, "background: #153; color: #4f9"); } + this.logger.log('info', 'debug', `%c[ArDetect::processAr] <@${this.arid}> Triggering aspect ratio change. New aspect ratio: ${trueAr}`, _ard_console_change); this.conf.resizer.setAr({type: AspectRatio.Automatic, ratio: trueAr}, {type: AspectRatio.Automatic, ratio: trueAr}); } frameCheck(){ if(! this.video){ - if(Debug.debug || Debug.warnings_critical) { - console.log("[ArDetect::frameCheck] Video went missing. Destroying current instance of videoData.") - } + this.logger.log('error', 'debug', `%c[ArDetect::frameCheck] <@${this.arid}> Video went missing. Destroying current instance of videoData.`); this.conf.destroy(); return; } @@ -565,9 +524,8 @@ class ArDetector { this.blackframeContext.drawImage(this.video, 0, 0, this.blackframeCanvas.width, this.blackframeCanvas.height); this.fallbackMode = false; } catch (e) { - if(Debug.debug && Debug.debugArDetect) { - console.log(`%c[ArDetect::frameCheck] can't draw image on canvas. ${this.canDoFallbackMode ? 'Trying canvas.drawWindow instead' : 'Doing nothing as browser doesn\'t support fallback mode.'}`, "color:#000; backgroud:#f51;", e); - } + this.logger.log('error', 'arDetect', `%c[ArDetect::frameCheck] <@${this.arid}> %c[ArDetect::frameCheck] can't draw image on canvas. ${this.canDoFallbackMode ? 'Trying canvas.drawWindow instead' : 'Doing nothing as browser doesn\'t support fallback mode.'}`, "color:#000; backgroud:#f51;", e); + // nothing to see here, really, if fallback mode isn't supported by browser if (! this.canDoFallbackMode) { return; @@ -598,23 +556,19 @@ class ArDetector { try { this.context.drawWindow(window, this.canvasDrawWindowHOffset, 0, this.canvas.width, this.canvas.height, "rgba(0,0,128,1)"); } catch (e) { - console.log(`%c[ArDetect::frameCheck] can't draw image on canvas with fallback mode either. This error is prolly only temporary.`, "color:#000; backgroud:#f51;", e); + this.logger.log('error', 'arDetect', `%c[ArDetect::frameCheck] can't draw image on canvas with fallback mode either. This error is prolly only temporary.`, "color:#000; backgroud:#f51;", e); return; // it's prolly just a fluke, so we do nothing special here } // draw blackframe sample from our main sample: this.blackframeContext.drawImage(this.canvas, this.blackframeCanvas.width, this.blackframeCanvas.height) - if (Debug.debug) { - console.log("%c[ArDetect::frameCheck] canvas.drawImage seems to have worked", "color:#000; backgroud:#2f5;"); - } + this.logger.log('info', 'arDetect_verbose', `%c[ArDetect::frameCheck] canvas.drawImage seems to have worked`, "color:#000; backgroud:#2f5;"); } const bfanalysis = this.blackframeTest(); if (bfanalysis.isBlack) { // we don't do any corrections on frames confirmed black - if (Debug.debug && Debug.arDetect) { - console.log("%c[ArDetect::frameCheck] Black frame analysis suggests this frame is black or too dark. Doing nothing,", "color: #fa3", bfanalysis); - } + this.logger.log('info', 'arDetect_verbose', `%c[ArDetect::frameCheck] Black frame analysis suggests this frame is black or too dark. Doing nothing.`, "color: #fa3", bfanalysis); return; } else { // if (Debug.debug && Debug.arDetect) { @@ -640,10 +594,8 @@ class ArDetector { this.guardLine.reset(); this.noLetterboxCanvasReset = true; + this.logger.log('info', 'arDetect_verbose', `%c[ArDetect::frameCheck] Letterbox not detected in fast test. Letterbox is either gone or we manually corrected aspect ratio. Nothing will be done.`, "color: #fa3"); - if (Debug.debug && Debug.arDetect) { - console.log("%c[ArDetect::frameCheck] Letterbox not detected in fast test. Letterbox is either gone or we manually corrected aspect ratio. Nothing will be done.", "color: #fa3"); - } return; } @@ -660,10 +612,7 @@ class ArDetector { // če ni padla nobena izmed funkcij, potem se razmerje stranic ni spremenilo // if both succeed, then aspect ratio hasn't changed. if (!guardLineOut.imageFail && !guardLineOut.blackbarFail) { - if(Debug.debug && Debug.debugArDetect){ - console.log(`%c[ArDetect::frameCheck] guardLine tests were successful. (no imagefail and no blackbarfail)\n`, "color: #afa", guardLineOut); - } - + this.logger.log('info', 'arDetect_verbose', `%c[ArDetect::frameCheck] guardLine tests were successful. (no imagefail and no blackbarfail)\n`, "color: #afa", guardLineOut); return; } @@ -700,25 +649,20 @@ class ArDetector { if(guardLineOut.blackbarFail || guardLineOut.imageFail){ if(this.edgeDetector.findBars(imageData, null, EdgeDetectPrimaryDirection.HORIZONTAL).status === 'ar_known'){ - if(Debug.debug && guardLineOut.blackbarFail){ - console.log("[ArDetect::frameCheck] Detected blackbar violation and pillarbox. Resetting to default aspect ratio."); - } if(guardLineOut.blackbarFail){ + this.logger.log('info', 'arDetect', `[ArDetect::frameCheck] Detected blackbar violation and pillarbox. Resetting to default aspect ratio.`); this.conf.resizer.setAr({type: AspectRatio.Automatic, ratio: this.getDefaultAr()}); this.guardLine.reset(); } - triggerTimeout = this.getTimeout(baseTimeout, startTime); this.scheduleFrameCheck(triggerTimeout); return; } } } catch(e) { - if(Debug.debug) { - console.log("[ArDetect.js::frameCheck] something went wrong when checking for pillarbox. Error:\n", e) - } + this.logger.log('info', 'arDetect', `[ArDetect::frameCheck] something went wrong while checking for pillarbox. Error:\n`, e); } // pa poglejmo, kje se končajo črne letvice na vrhu in na dnu videa. @@ -729,19 +673,12 @@ class ArDetector { var edgePost = this.edgeDetector.findBars(imageData, sampleCols, EdgeDetectPrimaryDirection.VERTICAL, EdgeDetectQuality.IMPROVED, guardLineOut, bfanalysis); - if(Debug.debug && Debug.debugArDetect){ - console.log(`%c[ArDetect::frameCheck] edgeDetector returned this\n`, "color: #aaf", edgePost); - } - // console.log("SAMPLES:", blackbarSamples, "candidates:", edgeCandidates, "post:", edgePost,"\n\nblack level:", this.blackLevel, "tresh:", this.blackLevel + this.settings.active.arDetect.blackbar.threshold); + this.logger.log('info', 'arDetect_verbose', `%c[ArDetect::frameCheck] edgeDetector returned this\n`, "color: #aaf", edgePost); if (edgePost.status !== EdgeStatus.AR_KNOWN){ // rob ni bil zaznan, zato ne naredimo ničesar. // no edge was detected. Let's leave things as they were - - if (Debug.debug && Debug.arDetect) { - console.log("%c[ArDetect::frameCheck] Edge wasn't detected with findBars", "color: #fa3", edgePost, "EdgeStatus.AR_KNOWN:", EdgeStatus.AR_KNOWN); - } - + this.logger.log('info', 'arDetect_verbose', `%c[ArDetect::frameCheck] Edge wasn't detected with findBars`, "color: #fa3", edgePost, "EdgeStatus.AR_KNOWN:", EdgeStatus.AR_KNOWN); return; } @@ -762,9 +699,8 @@ class ArDetector { // return; // } - if(Debug.debug && Debug.debugArDetect){ - console.log(`%c[ArDetect::frameCheck] Triggering aspect ration change! new ar: ${newAr}`, "color: #aaf"); - } + this.logger.log('info', 'arDetect_verbose', `%c[ArDetect::frameCheck] Triggering aspect ration change! new ar: ${newAr}`, "color: #aaf"); + this.processAr(newAr); // we also know edges for guardline, so set them. @@ -800,10 +736,7 @@ class ArDetector { blackframeTest() { if (this.blackLevel === undefined) { - if (Debug.debug && Debug.debugArDetect) { - console.log("[ArDetect::frameCheck] black level undefined, resetting"); - } - + this.logger.log('info', 'arDetect_verbose', "[ArDetect::blackframeTest] black level undefined, resetting"); this.resetBlackLevel(); } From 338afad417266298b7e2dc8e9139338aeb59a31d Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Thu, 18 Jul 2019 21:25:58 +0200 Subject: [PATCH 06/52] Replace consoles in ext with custom logger --- src/ext/conf/ExtConfPatches.js | 40 +++++++ src/ext/conf/ExtensionConf.js | 1 + src/ext/lib/ActionHandler.js | 49 +++----- src/ext/lib/Logger.js | 32 ++++- src/ext/lib/comms/CommsClient.js | 39 +++---- src/ext/lib/video-data/PageInfo.js | 50 +++----- src/ext/lib/video-data/PlayerData.js | 50 +++----- src/ext/lib/video-data/VideoData.js | 30 ++--- src/ext/lib/video-transform/Resizer.js | 143 +++++++---------------- src/ext/lib/video-transform/Scaler.js | 39 ++----- src/ext/lib/video-transform/Stretcher.js | 28 ++--- src/ext/lib/video-transform/Zoom.js | 19 +-- src/ext/uw.js | 39 +++---- 13 files changed, 229 insertions(+), 330 deletions(-) diff --git a/src/ext/conf/ExtConfPatches.js b/src/ext/conf/ExtConfPatches.js index d6b87f3..d0ee11c 100644 --- a/src/ext/conf/ExtConfPatches.js +++ b/src/ext/conf/ExtConfPatches.js @@ -2,6 +2,46 @@ // version: {ExtensionConf object, but only properties that get overwritten} const ExtensionConfPatch = { + '4.3.0': { + sites: { + "old.reddit.com" : { + type: 'testing', + DOM: { + player: { + manual: true, + useRelativeAncestor: false, + querySelectors: '.media-preview-content' + } + }, + css: '', + }, + "www.reddit.com" : { + type: 'testing', + DOM: { + player: { + manual: true, + useRelativeAncestor: false, + querySelectors: '.media-preview-content' + } + }, + css: '', + }, + "www.youtube.com" : { + DOM: { + player: { + manual: true, + querySelectors: "#movie_player, #player", + additionalCss: "", + useRelativeAncestor: false, + playerNodeCss: "", + } + } + }, + "www.netflix.com" : { + arPersistance: true + } + } + }, '4.2.1': { sites: { "old.reddit.com" : { diff --git a/src/ext/conf/ExtensionConf.js b/src/ext/conf/ExtensionConf.js index 9a4d4ec..ebfea0a 100644 --- a/src/ext/conf/ExtensionConf.js +++ b/src/ext/conf/ExtensionConf.js @@ -915,6 +915,7 @@ whatsNewChecked: true, stretch: Stretch.Default, videoAlignment: VideoAlignment.Default, keyboardShortcutsEnabled: ExtensionMode.Default, + arPersistence: true, // persist aspect ratio between different videos autoarPreventConditions: { // prevents autoar on following conditions videoStyleString: { // if video style string thing does anything of what follows containsProperty: { // if video style string has any of these properties (listed as keys) diff --git a/src/ext/lib/ActionHandler.js b/src/ext/lib/ActionHandler.js index 44cb9bd..dfd2ded 100644 --- a/src/ext/lib/ActionHandler.js +++ b/src/ext/lib/ActionHandler.js @@ -4,18 +4,17 @@ import ExtensionMode from '../../common/enums/extension-mode.enum'; class ActionHandler { - constructor(pageInfo) { + constructor(pageInfo, logger) { this.pageInfo = pageInfo; this.settings = pageInfo.settings; this.inputs = ['input', 'select', 'button', 'textarea']; this.keyboardLocalDisabled = false; + this.logger = logger; } init() { - if (Debug.debug) { - console.log("[ActionHandler::init] starting init"); - } + this.logger.log('info', 'debug', "[ActionHandler::init] starting init"); this.keyUpActions = []; this.keyDownActions = []; @@ -105,15 +104,13 @@ class ActionHandler { document.addEventListener('keyup', (event) => ths.handleKeyup(event) ); this.pageInfo.setActionHandler(this); - if (Debug.debug) { - console.log("[ActionHandler::init] initialization complete"); - } + + this.logger.log('info', 'debug', "[ActionHandler::init] initialization complete"); } registerHandleMouse(videoData) { - if (Debug.debug && Debug.mousemove) { - console.log("[ActionHandler::registerHandleMouse] registering handle mouse for videodata:", videoData) - } + this.logger.log('info', ['actionHandler', 'mousemove'], "[ActionHandler::registerHandleMouse] registering handle mouse for videodata:", videoData) + var ths = this; if (videoData.player && videoData.player.element) { videoData.player.element.addEventListener('mousemove', (event) => ths.handleMouseMove(event, videoData)); @@ -133,10 +130,10 @@ class ActionHandler { preventAction() { var activeElement = document.activeElement; - if(Debug.debug && Debug.keyboard) { - Debug.debug = false; // temp disable to avoid recursing; + if(this.logger.canLog('keyboard')) { + this.logger.pause(); // temp disable to avoid recursing; - console.log("[ActionHandler::preventAction] Testing whether we're in a textbox or something. Detailed rundown of conditions:\n" + + this.logger.log('info', 'keyboard', "[ActionHandler::preventAction] Testing whether we're in a textbox or something. Detailed rundown of conditions:\n" + "is full screen? (yes->allow):", PlayerData.isFullScreen(), "\nis tag one of defined inputs? (yes->prevent):", this.inputs.indexOf(activeElement.tagName.toLocaleLowerCase()) !== -1, "\nis role = textbox? (yes -> prevent):", activeElement.getAttribute("role") === "textbox", @@ -151,7 +148,7 @@ class ActionHandler { "insta-fail inputs:", this.inputs ); - Debug.debug = true; // undisable + this.logger.resume(); // undisable } // lately youtube has allowed you to read and write comments while watching video in @@ -187,15 +184,11 @@ class ActionHandler { } execAction(actions, event, videoData) { - if(Debug.debug && Debug.keyboard ){ - console.log("%c[ActionHandler::execAction] Trying to find and execute action for event. Actions/event: ", "color: #ff0", actions, event); - } + this.logger.log('info', 'keyboard', "%c[ActionHandler::execAction] Trying to find and execute action for event. Actions/event: ", "color: #ff0", actions, event); for (var action of actions) { if (this.isActionMatch(action.shortcut, event)) { - if(Debug.debug && Debug.keyboard ){ - console.log("%c[ActionHandler::execAction] found an action associated with keypress/event: ", "color: #ff0", action); - } + this.logger.log('info', 'keyboard', "%c[ActionHandler::execAction] found an action associated with keypress/event: ", "color: #ff0", action); for (var cmd of action.cmd) { if (action.scope === 'page') { @@ -243,14 +236,10 @@ class ActionHandler { handleKeyup(event) { - if(Debug.debug && Debug.keyboard ){ - console.log("%c[ActionHandler::handleKeyup] we pressed a key: ", "color: #ff0", event.key , " | keyup: ", event.keyup, "event:", event); - } + this.logger.log('info', 'keyboard', "%c[ActionHandler::handleKeyup] we pressed a key: ", "color: #ff0", event.key , " | keyup: ", event.keyup, "event:", event); if (this.preventAction()) { - if (Debug.debug && Debug.keyboard) { - console.log("[ActionHandler::handleKeyup] we are in a text box or something. Doing nothing."); - } + this.logger.log('info', 'keyboard', "[ActionHandler::handleKeyup] we are in a text box or something. Doing nothing."); return; } @@ -263,9 +252,7 @@ class ActionHandler { } if (this.preventAction()) { - if (Debug.debug && Debug.keyboard) { - console.log("[ActionHandler::handleKeydown] we are in a text box or something. Doing nothing."); - } + this.logger.log('info', 'keyboard', "[ActionHandler::handleKeydown] we are in a text box or something. Doing nothing."); return; } @@ -273,9 +260,7 @@ class ActionHandler { } handleMouseMove(event, videoData) { - if (Debug.debug && Debug.mousemove) { - console.log("[ActionHandler::handleMouseMove] mouse move is being handled.\nevent:", event, "\nvideo data:", videoData); - } + this.logger.log('info', 'keyboard', "[ActionHandler::handleMouseMove] mouse move is being handled.\nevent:", event, "\nvideo data:", videoData); videoData.panHandler(event); this.execAction(this.mouseMoveActions, event, videoData) } diff --git a/src/ext/lib/Logger.js b/src/ext/lib/Logger.js index fe3546c..d6786b5 100644 --- a/src/ext/lib/Logger.js +++ b/src/ext/lib/Logger.js @@ -3,6 +3,7 @@ class Logger { this.conf = conf; this.history = []; this.startTime = performance.now(); + this.temp_disable = false; } clear() { @@ -39,7 +40,34 @@ class Logger { return logfileStr; } + pause() { + this.temp_disable = true; + } + resume() { + this.temp_disable = false; + } + canLog(component) { + return this.canLogFile(component) || this.canLogConsole(component); + } + + canLogFile(component) { + if (!this.conf.fileOptions.enabled || this.temp_disable) { + return false; + } + if (component.length ) { + for (const c in component) { + if (this.conf.fileOptions[component]) { + return this.conf.fileOptions[component]; + } + } + } + return this.conf.fileOptions[component]; + } + canLogConsole(component) { + if (!this.conf.consoleOptions.enabled || this.temp_disable) { + return false; + } if (component.length) { for (const c in component) { if (this.conf.fileOptions[component]) { @@ -58,7 +86,7 @@ class Logger { return; } if (this.conf.logToFile) { - if (this.canLog(component)) { + if (this.canLogFile(component)) { let ts = performance.now(); if (ts <= this.history[this.history.length - 1]) { ts = this.history[this.history.length - 1] + 0.00001; @@ -71,7 +99,7 @@ class Logger { } } if (this.conf.logToConsole) { - if (this.canLog(component)) { + if (this.canLogConsole(component)) { console.log(...message); } } diff --git a/src/ext/lib/comms/CommsClient.js b/src/ext/lib/comms/CommsClient.js index 5b2a5e1..d8d5b82 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) { + constructor(name, settings, logger) { if (BrowserDetect.firefox) { this.port = browser.runtime.connect({name: name}); } else if (BrowserDetect.chrome) { @@ -18,6 +18,7 @@ class CommsClient { this.settings = settings; this.pageInfo = undefined; this.commsId = (Math.random() * 20).toFixed(0); + this.logger = logger; } destroy() { @@ -32,9 +33,7 @@ class CommsClient { this.pageInfo = pageInfo; - if(Debug.debug) { - console.log(`[CommsClient::setPageInfo] <${this.commsId}>`, "SETTING PAGEINFO —", this.pageInfo, this) - } + this.logger.log('info', 'debug', `[CommsClient::setPageInfo] <${this.commsId}>`, "SETTING PAGEINFO —", this.pageInfo, this) var ths = this; this._listener = m => ths.processReceivedMessage(m); @@ -46,17 +45,13 @@ class CommsClient { } processReceivedMessage(message){ - if(Debug.debug && Debug.comms){ - console.log(`[CommsClient.js::processMessage] <${this.commsId}> Received message from background script!`, message); - } + this.logger.log('info', 'comms', `[CommsClient.js::processMessage] <${this.commsId}> Received message from background script!`, message); if (!this.pageInfo || !this.settings.active) { - if(Debug.debug && Debug.comms){ - console.log(`[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 - ); - } + 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; } @@ -135,13 +130,11 @@ class CommsClient { } async requestSettings(){ - if(Debug.debug){ - console.log("%c[CommsClient::requestSettings] sending request for congif!", "background: #11D; color: #aad"); - } + this.logger.log('info', 'comms', "%c[CommsClient::requestSettings] sending request for congif!", "background: #11D; color: #aad"); + var response = await this.sendMessage_nonpersistent({cmd: 'get-config'}); - if(Debug.debug){ - console.log("%c[CommsClient::requestSettings] received settings response!", "background: #11D; color: #aad", response); - } + + this.logger.log('info', 'comms', "%c[CommsClient::requestSettings] received settings response!", "background: #11D; color: #aad", response); if(! response || response.extensionConf){ return Promise.resolve(false); @@ -156,9 +149,7 @@ class CommsClient { } registerVideo(){ - if (Debug.debug && Debug.comms) { - console.log(`[CommsClient::registerVideo] <${this.commsId}>`, "Registering video for current page."); - } + 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"}); @@ -173,9 +164,7 @@ class CommsClient { } unregisterVideo(){ - if (Debug.debug && Debug.comms) { - console.log(`[CommsClient::unregisterVideo] <${this.commsId}>`, "Unregistering video for current page."); - } + this.logger.log('info', 'comms', `[CommsClient::unregisterVideo] <${this.commsId}>`, "Unregistering video for current page."); this.port.postMessage({cmd: "noVideo"}); // ayymd } diff --git a/src/ext/lib/video-data/PageInfo.js b/src/ext/lib/video-data/PageInfo.js index 5aeac23..ad470b6 100644 --- a/src/ext/lib/video-data/PageInfo.js +++ b/src/ext/lib/video-data/PageInfo.js @@ -9,7 +9,7 @@ if(Debug.debug) class PageInfo { - constructor(comms, settings, extensionMode, readOnly = false){ + constructor(comms, settings, logger, extensionMode, readOnly = false){ this.hasVideos = false; this.siteDisabled = false; this.videos = []; @@ -20,6 +20,8 @@ class PageInfo { this.extensionMode = extensionMode; this.readOnly = readOnly; + this.logger = logger; + if (comms){ this.comms = comms; } @@ -42,9 +44,7 @@ class PageInfo { } destroy() { - if(Debug.debug || Debug.init){ - console.log("[PageInfo::destroy] destroying all videos!") - } + this.logger.log('info', ['debug', 'init'], "[PageInfo::destroy] destroying all videos!") if(this.rescanTimer){ clearTimeout(this.rescanTimer); } @@ -118,9 +118,7 @@ class PageInfo { this.hasVideos = false; if(rescanReason == RescanReason.PERIODIC){ - if (Debug.debug && Debug.videoRescan && Debug.periodic) { - console.log("[PageInfo::rescan] Scheduling normal rescan:") - } + this.logger.log('info', 'videoRescan', "[PageInfo::rescan] Scheduling normal rescan.") this.scheduleRescan(RescanReason.PERIODIC); } return; @@ -169,18 +167,14 @@ class PageInfo { if (videoExists) { continue; } else { - if (Debug.debug && Debug.periodic && Debug.videoRescan) { - console.log("[PageInfo::rescan] found new video candidate:", video, "NOTE:: Video initialization starts here:\n--------------------------------\n") - } + this.logger.log('info', 'videoRescan', "[PageInfo::rescan] found new video candidate:", video, "NOTE:: Video initialization starts here:\n--------------------------------\n") - v = new VideoData(video, this.settings, this); + v = new VideoData(video, this.settings, this, logger); // console.log("[PageInfo::rescan] v is:", v) v.initArDetection(); this.videos.push(v); - if(Debug.debug && Debug.periodic && Debug.videoRescan){ - console.log("[PageInfo::rescan] END VIDEO INITIALIZATION\n\n\n-------------------------------------\nvideos[] is now this:", this.videos,"\n\n\n\n\n\n\n\n") - } + this.logger.log('info', 'videoRescan', "END VIDEO INITIALIZATION\n\n\n-------------------------------------\nvideos[] is now this:", this.videos,"\n\n\n\n\n\n\n\n") } } @@ -212,9 +206,7 @@ class PageInfo { // if we encounter a fuckup, we can assume that no videos were found on the page. We destroy all videoData // objects to prevent multiple initalization (which happened, but I don't know why). No biggie if we destroyed // videoData objects in error — they'll be back in the next rescan - if (Debug.debug) { - console.log("rescan error: — destroying all videoData objects",e); - } + this.logger.log('error', 'debug', "rescan error: — destroying all videoData objects",e); for (const v of this.videos) { v.destroy(); } @@ -249,9 +241,7 @@ class PageInfo { ths = null; }, this.settings.active.pageInfo.timeouts.rescan, RescanReason.PERIODIC) } catch(e) { - if(Debug.debug){ - console.log("[PageInfo::scheduleRescan] scheduling rescan failed. Here's why:",e) - } + this.logger.log('error', 'debug', "[PageInfo::scheduleRescan] scheduling rescan failed. Here's why:",e) } } @@ -269,17 +259,13 @@ class PageInfo { ths = null; }, this.settings.active.pageInfo.timeouts.urlCheck) } catch(e){ - if(Debug.debug){ - console.error("[PageInfo::scheduleUrlCheck] scheduling URL check failed. Here's why:",e) - } + this.logger.log('error', 'debug', "[PageInfo::scheduleUrlCheck] scheduling URL check failed. Here's why:",e) } } ghettoUrlCheck() { if (this.lastUrl != window.location.href){ - if(Debug.debug && Debug.periodic){ - console.log("[PageInfo::ghettoUrlCheck] URL has changed. Triggering a rescan!"); - } + this.logger.log('error', 'videoRescan', "[PageInfo::ghettoUrlCheck] URL has changed. Triggering a rescan!"); this.rescan(RescanReason.URL_CHANGE); this.lastUrl = window.location.href; @@ -343,7 +329,7 @@ class PageInfo { startArDetection(playingOnly){ if (Debug.debug) { - console.log('[PageInfo::startArDetection()] starting automatic ar detection!') + this.logger.log('info', 'debug', '[PageInfo::startArDetection()] starting automatic ar detection!') } if (playingOnly) { for(var vd of this.videos){ @@ -373,16 +359,12 @@ class PageInfo { } setAr(ar, playingOnly){ - if (Debug.debug) { - console.log('[PageInfo::setAr] aspect ratio:', ar, "playing only?", playingOnly) - } + this.logger.log('info', 'debug', '[PageInfo::setAr] aspect ratio:', ar, "playing only?", playingOnly) if (ar.type !== AspectRatio.Automatic) { this.stopArDetection(playingOnly); } else { - if (Debug.debug) { - console.log('[PageInfo::setAr] aspect ratio is auto'); - } + this.logger.log('info', 'debug', '[PageInfo::setAr] aspect ratio is auto'); try { for (var vd of this.videos) { @@ -391,7 +373,7 @@ class PageInfo { } } } catch (e) { - console.log("???", e); + this.logger.log('error', 'debug', "???", e); } this.initArDetection(playingOnly); this.startArDetection(playingOnly); diff --git a/src/ext/lib/video-data/PlayerData.js b/src/ext/lib/video-data/PlayerData.js index 1b654bf..4f51bba 100644 --- a/src/ext/lib/video-data/PlayerData.js +++ b/src/ext/lib/video-data/PlayerData.js @@ -33,7 +33,7 @@ if(Debug.debug) */ class PlayerData { - constructor(videoData) { + constructor(videoData, logger) { this.videoData = videoData; this.video = videoData.video; this.settings = videoData.settings; @@ -41,6 +41,7 @@ class PlayerData { this.element = undefined; this.dimensions = undefined; this.overlayNode = undefined; + this.logger = logger; if (this.extensionMode === ExtensionMode.Enabled) { this.getPlayerDimensions(); @@ -117,9 +118,7 @@ class PlayerData { } unmarkPlayer() { - if (Debug.debug) { - console.log("[PlayerData::unmarkPlayer] unmarking player!") - } + this.logger.log('info', 'debug', "[PlayerData::unmarkPlayer] unmarking player!") if (this.playerIdElement) { this.playerIdElement.remove(); } @@ -146,9 +145,7 @@ class PlayerData { try{ ths.ghettoWatcher(); } catch(e) { - if (Debug.debug) { - console.log("[PlayerData::scheduleGhettoWatcher] Scheduling failed. Error:",e) - } + this.logger.log('info', 'debug', "[PlayerData::scheduleGhettoWatcher] Scheduling failed. Error:",e) ths.scheduleGhettoWatcher(1000); } @@ -160,9 +157,7 @@ class PlayerData { ghettoWatcherFull() { if(this.checkPlayerSizeChange()){ - if(Debug.debug){ - console.log("[uw::ghettoOnChange] change detected"); - } + this.logger.log('info', 'debug', "[uw::ghettoOnChange] change detected"); this.getPlayerDimensions(); if(! this.element ){ @@ -179,9 +174,7 @@ class PlayerData { // trick it into doing that if(this.dimensions.fullscreen != PlayerData.isFullScreen()) { - if(Debug.debug){ - console.log("[PlayerData::ghettoWatcher] fullscreen switch detected (basic change detection failed)"); - } + this.logger.log('info', 'debug', "[PlayerData::ghettoWatcher] fullscreen switch detected (basic change detection failed)"); this.getPlayerDimensions(); @@ -238,9 +231,7 @@ class PlayerData { let element = this.video.parentNode; if(! element ){ - if(Debug.debug) { - console.log("[PlayerDetect::_pd_getPlayer] element is not valid, doing nothing.", element) - } + this.logger.log('info', 'debug', "[PlayerDetect::_pd_getPlayer] element is not valid, doing nothing.", element) if(this.element) { const ths = this; } @@ -306,16 +297,11 @@ class PlayerData { grows = trustCandidateAfterGrows; - if(Debug.debug){ - console.log("Found new candidate for player. Dimensions: w:", candidate_width, "h:",candidate_height, "node:", playerCandidateNode); - } + this.logger.log('info', 'debug', "Found new candidate for player. Dimensions: w:", candidate_width, "h:",candidate_height, "node:", playerCandidateNode); } } else if(grows --<= 0){ - - if(Debug.debug && Debug.playerDetect){ - console.log("Current element grew in comparrison to the child. We probably found the player. breaking loop, returning current result"); - } + this.logger.log('info', 'playerDetect', "Current element grew in comparrison to the child. We probably found the player. breaking loop, returning current result"); break; } @@ -334,9 +320,7 @@ class PlayerData { const element = this.getPlayer(isFullScreen); if(! element ){ - if(Debug.debug) { - console.log("[PlayerDetect::getPlayerDimensions] element is not valid, doing nothing.", element) - } + this.logger.log('error', 'debug', "[PlayerDetect::getPlayerDimensions] element is not valid, doing nothing.", element) this.element = undefined; this.dimensions = undefined; return; @@ -367,7 +351,7 @@ class PlayerData { } checkPlayerSizeChange(){ - if(Debug.debug){ + if (this.logger.canLog('debug')){ if(this.element == undefined){ // return true; } @@ -378,18 +362,18 @@ class PlayerData { if (this.dimensions && this.dimensions.fullscreen){ if(! PlayerData.isFullScreen()){ - console.log("[PlayerDetect] player size changed. reason: exited fullscreen"); + this.logger.log('info', 'debug', "[PlayerDetect] player size changed. reason: exited fullscreen"); } } - if(! this.element && Debug.debug && Debug.playerDetect) { - console.log("[PlayerDetect] player element isnt defined"); + if(! this.element) { + this.logger.log('info', 'playerDetect', "[PlayerDetect] player element isnt defined"); } if ( this.element && ( this.dimensions.width != this.element.offsetWidth || this.dimensions.height != this.element.offsetHeight ) ) { - console.log("[PlayerDetect] player size changed. reason: dimension change. Old dimensions?", this.dimensions.width, this.dimensions.height, "new dimensions:", this.element.offsetWidth, this.element.offsetHeight); + this.logger.log('info', 'debug', "[PlayerDetect] player size changed. reason: dimension change. Old dimensions?", this.dimensions.width, this.dimensions.height, "new dimensions:", this.element.offsetWidth, this.element.offsetHeight); } } @@ -417,9 +401,7 @@ class PlayerData { return false; } - if(Debug.debug) { - console.log("[PlayerData::checkFullscreenChange] this.dimensions is not defined. Assuming fs change happened and setting default values.") - } + this.logger.log('info', 'debug', "[PlayerData::checkFullscreenChange] this.dimensions is not defined. Assuming fs change happened and setting default values.") this.dimensions = { fullscreen: isFs, diff --git a/src/ext/lib/video-data/VideoData.js b/src/ext/lib/video-data/VideoData.js index f738985..9c84d99 100644 --- a/src/ext/lib/video-data/VideoData.js +++ b/src/ext/lib/video-data/VideoData.js @@ -5,35 +5,31 @@ import ArDetector from '../ar-detect/ArDetector'; class VideoData { - constructor(video, settings, pageInfo){ + constructor(video, settings, pageInfo, logger){ this.arSetupComplete = false; this.video = video; this.destroyed = false; this.settings = settings; this.pageInfo = pageInfo; this.extensionMode = pageInfo.extensionMode; - + this.logger = logger; // POZOR: VRSTNI RED JE POMEMBEN (arDetect mora bit zadnji) // NOTE: ORDERING OF OBJ INITIALIZATIONS IS IMPORTANT (arDetect needs to go last) - this.player = new PlayerData(this); - this.resizer = new Resizer(this); + this.player = new PlayerData(this, logger); + this.resizer = new Resizer(this, logger); - this.arDetector = new ArDetector(this); // this starts Ar detection. needs optional parameter that prevets ardetdctor from starting + this.arDetector = new ArDetector(this, logger); // this starts Ar detection. needs optional parameter that prevets ardetdctor from starting // player dimensions need to be in: // this.player.dimensions // apply default align and stretch - if (Debug.init) { - console.log("%c[VideoData::ctor] Initial resizer reset!", {background: '#afd', color: '#132'}); - } + this.logger.log('info', 'debug', "%c[VideoData::ctor] Initial resizer reset!", {background: '#afd', color: '#132'}); this.resizer.reset(); this.vdid = (Math.random()*100).toFixed(); - if (Debug.init) { - console.log("[VideoData::ctor] Created videoData with vdid", this.vdid,"\nextension mode:", this.extensionMode); - } + this.logger.log('info', 'init', "[VideoData::ctor] Created videoData with vdid", this.vdid,"\nextension mode:", this.extensionMode); this.pageInfo.initMouseActionHandler(this); } @@ -61,9 +57,7 @@ class VideoData { } startArDetection() { - if (Debug.debug) { - console.log("[VideoData::startArDetection] starting AR detection") - } + this.logger.log('info', 'debug', "[VideoData::startArDetection] starting AR detection") if(this.destroyed) { throw {error: 'VIDEO_DATA_DESTROYED', data: {videoData: this}}; } @@ -87,9 +81,7 @@ class VideoData { } destroy() { - if(Debug.debug || Debug.init){ - console.log(`[VideoData::destroy] received destroy command`); - } + this.logger.log('info', ['debug', 'init'], `[VideoData::destroy] received destroy command`); this.pause(); this.destroyed = true; @@ -133,9 +125,7 @@ class VideoData { this.player.start(); } } catch (e) { - if(Debug.debug){ - console.log("[VideoData.js::resume] cannot resume for reasons. Will destroy videoData. Error here:", e); - } + this.logger.log('error', 'debug', "[VideoData.js::resume] cannot resume for reasons. Will destroy videoData. Error here:", e); this.destroy(); } } diff --git a/src/ext/lib/video-transform/Resizer.js b/src/ext/lib/video-transform/Resizer.js index 33977a3..fa2b773 100644 --- a/src/ext/lib/video-transform/Resizer.js +++ b/src/ext/lib/video-transform/Resizer.js @@ -14,15 +14,17 @@ if(Debug.debug) { class Resizer { - constructor(videoData) { + constructor(videoData, logger) { this.conf = videoData; this.video = videoData.video; this.settings = videoData.settings; this.extensionMode = videoData.extensionMode; - this.scaler = new Scaler(this.conf); - this.stretcher = new Stretcher(this.conf); - this.zoom = new Zoom(this.conf); + this.logger = logger; + + this.scaler = new Scaler(this.conf, logger); + this.stretcher = new Stretcher(this.conf, logger); + this.zoom = new Zoom(this.conf, logger); this.cssCheckDisabled = false; @@ -50,7 +52,7 @@ class Resizer { this.resizerId = (Math.random(99)*100).toFixed(0); if (this.settings.active.pan) { - console.log("can pan:", this.settings.active.miscSettings.mousePan.enabled, "(default:", this.settings.active.miscSettings.mousePan.enabled, ")") + this.logger.log('info', 'debug', "can pan:", this.settings.active.miscSettings.mousePan.enabled, "(default:", this.settings.active.miscSettings.mousePan.enabled, ")") this.canPan = this.settings.active.miscSettings.mousePan.enabled; } else { this.canPan = false; @@ -68,9 +70,7 @@ class Resizer { } destroy(){ - if(Debug.debug || Debug.init){ - console.log(`[Resizer::destroy] received destroy command.`); - } + this.logger.log('info', ['debug', 'init'], `[Resizer::destroy] received destroy command.`); this.destroyed = true; this.stopCssWatcher(); } @@ -86,9 +86,7 @@ class Resizer { var ratioOut; if (!this.conf.video) { - if (Debug.debug) { - console.log("[Scaler.js::modeToAr] No video??",this.conf.video, "killing videoData"); - } + this.logger.log('info', 'debug', "[Scaler.js::modeToAr] No video??",this.conf.video, "killing videoData"); this.conf.destroy(); return null; } @@ -97,9 +95,7 @@ class Resizer { if (! this.conf.player.dimensions) { ratioOut = screen.width / screen.height; } else { - if (Debug.debug && Debug.resizer) { - console.log(`[Resizer::calculateRatioForLegacyOptions] Player dimensions:`, this.conf.player.dimensions.width ,'x', this.conf.player.dimensions.height,'aspect ratio:', this.conf.player.dimensions.width / this.conf.player.dimensions.height) - } + this.logger.log('info', 'debug', `[Resizer::calculateRatioForLegacyOptions] Player dimensions:`, this.conf.player.dimensions.width ,'x', this.conf.player.dimensions.height,'aspect ratio:', this.conf.player.dimensions.width / this.conf.player.dimensions.height) ratioOut = this.conf.player.dimensions.width / this.conf.player.dimensions.height; } @@ -118,9 +114,7 @@ class Resizer { ar.ratio = ratioOut < fileAr ? ratioOut : fileAr; } else if(ar.type === AspectRatio.Reset){ - if(Debug.debug){ - console.log("[Scaler.js::modeToAr] Using original aspect ratio -", fileAr); - } + this.logger.log('info', 'debug', "[Scaler.js::modeToAr] Using original aspect ratio -", fileAr); ar.ratio = fileAr; } else { return null; @@ -135,9 +129,7 @@ class Resizer { return; } - if(Debug.debug){ - console.log('[Resizer::setAr] trying to set ar. New ar:', ar) - } + this.logger.log('info', 'debug', '[Resizer::setAr] trying to set ar. New ar:', ar) if (ar == null) { return; @@ -166,17 +158,13 @@ class Resizer { // check if property value is on the list of allowed values // if it's not, we aren't allowed to start aard if (bannedProperties[prop].allowedValues.indexOf(styleValue) === -1) { - if (Debug.debug) { - console.log("%c[Resizer::setAr] video style contains forbidden css property/value combo: ", "color: #900, background: #100", prop, " — we aren't allowed to start autoar.") - } + this.logger.log('error', 'debug', "%c[Resizer::setAr] video style contains forbidden css property/value combo: ", "color: #900, background: #100", prop, " — we aren't allowed to start autoar.") return; } } else { // no allowed values, no problem. We have forbidden property // and this means aard can't start. - if (Debug.debug) { - console.log("%c[Resizer::setAr] video style contains forbidden css property: ", "color: #900, background: #100", prop, " — we aren't allowed to start autoar.") - } + this.logger.log('info', 'debug', "%c[Resizer::setAr] video style contains forbidden css property: ", "color: #900, background: #100", prop, " — we aren't allowed to start autoar.") return; } } @@ -195,9 +183,7 @@ class Resizer { // I'm not sure whether they do. Check that. ar = this.calculateRatioForLegacyOptions(ar); if (! ar) { - if (Debug.debug && Debug.resizer) { - console.log(`[Resizer::setAr] <${this.resizerId}> Something wrong with ar or the player. Doing nothing.`); - } + this.logger.log('info', 'resizer', `[Resizer::setAr] <${this.resizerId}> Something wrong with ar or the player. Doing nothing.`); return; } this.lastAr = {type: ar.type, ratio: ar.ratio} @@ -238,16 +224,12 @@ class Resizer { var stretchFactors = this.scaler.calculateCrop(ar); if(! stretchFactors || stretchFactors.error){ - if(Debug.debug){ - console.log("[Resizer::setAr] failed to set AR due to problem with calculating crop. Error:", (stretchFactors ? stretchFactors.error : stretchFactors)); - } + this.logger.log('error', 'debug', "[Resizer::setAr] failed to set AR due to problem with calculating crop. Error:", (stretchFactors ? stretchFactors.error : stretchFactors)); if (stretchFactors.error === 'no_video'){ this.conf.destroy(); } if (stretchFactors.error === 'illegal_video_dimensions') { - if(Debug.debug){ - console.log("[Resizer::setAr] Illegal video dimensions found. We will pause everything."); - } + this.logger.log('error', 'debug', "[Resizer::setAr] Illegal video dimensions found. We will pause everything."); // if we get illegal video dimensions, cssWatcher goes nuts. This is harmful, // so we stop it until that sorts itself out this.stopCssWatcher(); @@ -260,25 +242,17 @@ class Resizer { this.stretcher.applyConditionalStretch(stretchFactors, ar.ratio); } - if (Debug.debug) { - console.log("[Resizer::setAr] Processed stretch factors for ", this.stretcher.mode === Stretch.NoStretch ? 'stretch-free crop.' : 'crop with conditional stretch.', 'Stretch factors are:', stretchFactors); - } + this.logger.log('info', 'debug', "[Resizer::setAr] Processed stretch factors for ", this.stretcher.mode === Stretch.NoStretch ? 'stretch-free crop.' : 'crop with conditional stretch.', 'Stretch factors are:', stretchFactors); } else if (this.stretcher.mode === Stretch.Hybrid) { var stretchFactors = this.stretcher.calculateStretch(ar.ratio); - if (Debug.debug) { - console.log('[Resizer::setAr] Processed stretch factors for hybrid stretch/crop. Stretch factors are:', stretchFactors); - } + this.logger.log('info', 'debug', '[Resizer::setAr] Processed stretch factors for hybrid stretch/crop. Stretch factors are:', stretchFactors); } else if (this.stretcher.mode === Stretch.Basic) { var stretchFactors = this.stretcher.calculateBasicStretch(); - if (Debug.debug) { - console.log('[Resizer::setAr] Processed stretch factors for basic stretch. Stretch factors are:', stretchFactors); - } + this.logger.log('info', 'debug', '[Resizer::setAr] Processed stretch factors for basic stretch. Stretch factors are:', stretchFactors); } else { var stretchFactors = {xFactor: 1, yFactor: 1} - if (Debug.debug) { - console.log('[Resizer::setAr] Okay wtf happened? If you see this, something has gone wrong', stretchFactors,"\n------[ i n f o d u m p ]------\nstretcher:", this.stretcher); - } + this.logger.log('error', 'debug', '[Resizer::setAr] Okay wtf happened? If you see this, something has gone wrong', stretchFactors,"\n------[ i n f o d u m p ]------\nstretcher:", this.stretcher); } this.zoom.applyZoom(stretchFactors); @@ -320,10 +294,7 @@ class Resizer { const relativeX = (event.pageX - player.offsetLeft) / player.offsetWidth; const relativeY = (event.pageY - player.offsetTop) / player.offsetHeight; - if (Debug.debug && Debug.mousemove) { - console.log("[Resizer::panHandler] mousemove.pageX, pageY:", event.pageX, event.pageY, - "\nrelativeX/Y:", relativeX, relativeY) - } + this.logger.log('info', 'mousemove', "[Resizer::panHandler] mousemove.pageX, pageY:", event.pageX, event.pageY, "\nrelativeX/Y:", relativeX, relativeY) this.setPan(relativeX, relativeY); } @@ -343,9 +314,6 @@ class Resizer { this.pan.relativeOffsetX = -(relativeMousePosX * 1.1) + 0.55; this.pan.relativeOffsetY = -(relativeMousePosY * 1.1) + 0.55; } - // if(Debug.debug){ - // console.log("[Resizer::setPan] relative cursor pos:", relativeMousePosX, ",",relativeMousePosY, " | new pan obj:", this.pan) - // } this.restore(); } @@ -355,9 +323,7 @@ class Resizer { } startCssWatcher(){ - if(Debug.debug) { - console.log("[Resizer.js::startCssWatcher] starting css watcher. Is resizer destroyed?", this.destroyed); - } + this.logger.log('info', 'cssWatcher', "[Resizer.js::startCssWatcher] starting css watcher. Is resizer destroyed?", this.destroyed); if (this.destroyed) { return; } @@ -399,25 +365,19 @@ class Resizer { ths.cssCheck(); } } catch (e) { - if(Debug.debug) { - console.log("[Resizer.js::scheduleCssWatcher] Css check failed. Error:", e); - } + this.logger.log('error', 'debug', "[Resizer.js::scheduleCssWatcher] Css check failed. Error:", e); } }, timeout); } stopCssWatcher() { - if (Debug.debug) { - console.log(`[Resizer.js] <${this.resizerId}> STOPPING CSS WATCHER!`) - } + this.logger.log('info', 'cssWatcher', `[Resizer.js] <${this.resizerId}> STOPPING CSS WATCHER!`) this.cssCheckDisabled = true; clearInterval(this.cssWatcherTimeout); } restore() { - if(Debug.debug){ - console.log("[Resizer::restore] attempting to restore aspect ratio. this & settings:", {'a_lastAr': this.lastAr, 'this': this, "settings": this.settings} ); - } + this.logger.log('info', 'debug', "[Resizer::restore] attempting to restore aspect ratio. this & settings:", {'a_lastAr': this.lastAr, 'this': this, "settings": this.settings} ); // this is true until we verify that css has actually been applied this.restore_wd = true; @@ -481,9 +441,7 @@ class Resizer { computeOffsets(stretchFactors){ - if (Debug.debug) { - console.log("[Resizer::computeOffsets] video will be aligned to ", this.settings.active.sites['@global'].videoAlignment); - } + this.logger.log('info', 'debug', "[Resizer::computeOffsets] video will be aligned to ", this.settings.active.sites['@global'].videoAlignment); const wdiff = this.conf.player.dimensions.width - this.conf.video.offsetWidth; const hdiff = this.conf.player.dimensions.height - this.conf.video.offsetHeight; @@ -512,16 +470,14 @@ class Resizer { } } - if(Debug.debug) { - console.log("[Resizer::_res_computeOffsets] calculated offsets:\n\n", - '---- data in ----\n', - 'player dimensions:', {w: this.conf.player.dimensions.width, h: this.conf.player.dimensions.height}, - 'video dimensions: ', {w: this.conf.video.offsetWidth, h: this.conf.video.offsetHeight}, - 'stretch factors: ', stretchFactors, - 'pan & zoom: ', this.pan, this.zoom, - '\n\n---- data out ----\n', - 'translate:', translate); - } + this.logger.log('info', 'debug', "[Resizer::_res_computeOffsets] calculated offsets:\n\n", + '---- data in ----\n', + 'player dimensions:', {w: this.conf.player.dimensions.width, h: this.conf.player.dimensions.height}, + 'video dimensions: ', {w: this.conf.video.offsetWidth, h: this.conf.video.offsetHeight}, + 'stretch factors: ', stretchFactors, + 'pan & zoom: ', this.pan, this.zoom, + '\n\n---- data out ----\n', + 'translate:', translate); return translate; } @@ -583,18 +539,13 @@ class Resizer { // apply extra CSS here. In case of duplicated properties, extraCss overrides // default styleString if (! this.video) { - if(Debug.debug) { - console.log("[Resizer::applyCss] Video went missing, doing nothing."); - - } + this.logger.log('warn', 'debug', "[Resizer::applyCss] Video went missing, doing nothing."); this.conf.destroy(); return; } - if (Debug.debug && Debug.resizer) { - console.log("[Resizer::applyCss] will apply css.", {stretchFactors, translate}); - } + this.logger.log('info', 'resizer', "[Resizer::applyCss] will apply css.", {stretchFactors, translate}); // save stuff for quick tests (before we turn numbers into css values): this.currentVideoSettings = { @@ -633,8 +584,7 @@ class Resizer { if (this.restore_wd) { if (!this.video){ - if(Debug.debug) - console.log("[Resizer::_res_setStyleString] Video element went missing, nothing to do here.") + this.logger.log('warn', 'debug', "[Resizer::_res_setStyleString] Video element went missing, nothing to do here.") return; } @@ -658,14 +608,13 @@ class Resizer { // } } else{ - if(Debug.debug) - console.log("[Resizer::_res_setStyleString] css applied. Style string:", styleString); + this.logger.log('info', 'resizer', "[Resizer::_res_setStyleString] css applied. Style string:", styleString); } } cssCheck(){ if (this.cssCheckDisabled) { - throw "fucking dont" + // throw "fucking dont" return; } // this means we haven't set our CSS yet, or that we changed video. @@ -676,17 +625,13 @@ class Resizer { // this means video went missing. videoData will be re-initialized when the next video is found if (!this.video){ - if(Debug.debug && Debug.resizer) { - console.log("[Resizer::cssCheck] no video detecting, issuing destroy command"); - } + this.logger.log('info', 'cssWatcher', "[Resizer::cssCheck] no video detecting, issuing destroy command"); this.conf.destroy(); return; } if(this.destroyed) { - if(Debug.debug && Debug.resizer) { - console.log("[Resizer::cssCheck] destroyed flag is set, we shouldnt be running"); - } + this.logger.log('info', 'cssWatcher', "[Resizer::cssCheck] destroyed flag is set, we shouldnt be running"); this.stopCssWatcher(); return; } @@ -705,9 +650,7 @@ class Resizer { cssValid &= this.currentPlayerStyleString === playerStyleString; } if (!cssValid){ - if(Debug.debug && Debug.resizer) { - console.log(`%c[Resizer::cssCheck] something touched our style string. We need to re-apply the style.`, {background: '#ddf', color: '#007'}); - } + this.logger.log('info', 'cssWatcher', `%c[Resizer::cssCheck] something touched our style string. We need to re-apply the style.`, {background: '#ddf', color: '#007'}); this.restore(); this.scheduleCssWatcher(10); diff --git a/src/ext/lib/video-transform/Scaler.js b/src/ext/lib/video-transform/Scaler.js index 85a7d59..4e899cf 100644 --- a/src/ext/lib/video-transform/Scaler.js +++ b/src/ext/lib/video-transform/Scaler.js @@ -9,8 +9,9 @@ class Scaler { // internal variables // functions - constructor(videoData) { + constructor(videoData, logger) { this.conf = videoData; + this.logger = logger; } @@ -25,9 +26,7 @@ class Scaler { var ratioOut; if (!this.conf.video) { - if(Debug.debug){ - console.log("[Scaler.js::modeToAr] No video??",this.conf.video, "killing videoData"); - } + this.logger.log('error', 'debug', "[Scaler.js::modeToAr] No video??",this.conf.video, "killing videoData"); this.conf.destroy(); return null; } @@ -59,9 +58,7 @@ class Scaler { return ratioOut; } else if(ar.type === AspectRatio.Reset){ - if(Debug.debug){ - console.log("[Scaler.js::modeToAr] Using original aspect ratio -", fileAr) - } + this.logger.log('info', 'debug', "[Scaler.js::modeToAr] Using original aspect ratio -", fileAr) ar.ar = fileAr; return fileAr; } @@ -71,9 +68,7 @@ class Scaler { calculateCrop(ar) { if(!this.conf.video){ - if (Debug.debug) { - console.log("[Scaler::calculateCrop] ERROR — no video detected. Conf:", this.conf, "video:", this.conf.video, "video dimensions:", this.conf.video && this.conf.video.videoWidth, '×', this.conf.video && this.conf.video.videoHeight); - } + this.logger.log('info', 'debug', "[Scaler::calculateCrop] ERROR — no video detected. Conf:", this.conf, "video:", this.conf.video, "video dimensions:", this.conf.video && this.conf.video.videoWidth, '×', this.conf.video && this.conf.video.videoHeight); this.conf.destroy(); return {error: "no_video"}; @@ -81,9 +76,7 @@ class Scaler { if (this.conf.video.videoWidth == 0 || this.conf.video.videoHeight == 0) { // that's illegal, but not illegal enough to just blast our shit to high hell // mr officer will let you go with a warning this time around - if (Debug.debug) { - console.log("[Scaler::calculateCrop] Video has illegal dimensions. Video dimensions:", this.conf.video && this.conf.video.videoWidth, '×', this.conf.video && this.conf.video.videoHeight); - } + this.logger.log('error', 'debug', "[Scaler::calculateCrop] Video has illegal dimensions. Video dimensions:", this.conf.video && this.conf.video.videoWidth, '×', this.conf.video && this.conf.video.videoHeight); return {error: "illegal_video_dimensions"}; } @@ -94,20 +87,14 @@ class Scaler { // handle fuckie-wuckies if (!ar.ratio){ - if (Debug.debug && Debug.scaler) { - console.log("[Scaler::calculateCrop] no ar?", ar.ratio, " -- we were given this mode:", ar); - } + this.logger.log('error', 'scaler', "[Scaler::calculateCrop] no ar?", ar.ratio, " -- we were given this mode:", ar); return {error: "no_ar", ratio: ar.ratio}; } - if (Debug.debug && Debug.scaler) { - console.log("[Scaler::calculateCrop] trying to set ar. args are: ar->",ar.ratio,"; this.conf.player.dimensions->",this.conf.player.dimensions.width, "×", this.conf.player.dimensions.height, "| obj:", this.conf.player.dimensions); - } + this.logger.log('info', 'scaler', "[Scaler::calculateCrop] trying to set ar. args are: ar->",ar.ratio,"; this.conf.player.dimensions->",this.conf.player.dimensions.width, "×", this.conf.player.dimensions.height, "| obj:", this.conf.player.dimensions); if( (! this.conf.player.dimensions) || this.conf.player.dimensions.width === 0 || this.conf.player.dimensions.height === 0 ){ - if (Debug.debug && Debug.scaler) { - console.log("[Scaler::calculateCrop] ERROR — no (or invalid) this.conf.player.dimensions:",this.conf.player.dimensions); - } + this.logger.log('error', 'scaler', "[Scaler::calculateCrop] ERROR — no (or invalid) this.conf.player.dimensions:",this.conf.player.dimensions); return {error: "this.conf.player.dimensions_error"}; } @@ -124,9 +111,7 @@ class Scaler { } - if (Debug.debug && Debug.scaler) { - console.log("[Scaler::calculateCrop] ar is " ,ar.ratio, ", file ar is", fileAr, ", this.conf.player.dimensions are ", this.conf.player.dimensions.width, "×", this.conf.player.dimensions.height, "| obj:", this.conf.player.dimensions); - } + this.logger.log('info', 'scaler', "[Scaler::calculateCrop] ar is " ,ar.ratio, ", file ar is", fileAr, ", this.conf.player.dimensions are ", this.conf.player.dimensions.width, "×", this.conf.player.dimensions.height, "| obj:", this.conf.player.dimensions); var videoDimensions = { xFactor: 1, @@ -152,9 +137,7 @@ class Scaler { videoDimensions.yFactor = videoDimensions.xFactor; } - if (Debug.debug && Debug.scaler) { - console.log("[Scaler::calculateCrop] Crop factor calculated — ", videoDimensions.xFactor); - } + this.logger.log('info', 'scaler', "[Scaler::calculateCrop] Crop factor calculated — ", videoDimensions.xFactor); return videoDimensions; } diff --git a/src/ext/lib/video-transform/Stretcher.js b/src/ext/lib/video-transform/Stretcher.js index 10c737b..5cbfa9c 100644 --- a/src/ext/lib/video-transform/Stretcher.js +++ b/src/ext/lib/video-transform/Stretcher.js @@ -1,4 +1,3 @@ -import Debug from '../../conf/Debug'; import Stretch from '../../../common/enums/stretch.enum'; // računa vrednosti za transform-scale (x, y) @@ -11,10 +10,11 @@ class Stretcher { // functions - constructor(videoData) { + constructor(videoData, logger) { this.conf = videoData; this.settings = videoData.settings; this.mode = this.settings.getDefaultStretchMode(window.location.hostname); + this.logger = logger; } setStretchMode(stretchMode) { @@ -120,9 +120,7 @@ class Stretcher { stretchFactors.xFactor = playerAr / videoAr; stretchFactors.yFactor = actualAr / videoAr; - if(Debug.debug){ - console.log("[Stretcher.js::calculateStretch] stretching strategy 1") - } + this.logger.log('info', 'stretcher', "[Stretcher.js::calculateStretch] stretching strategy 1") } else if ( actualAr >= videoAr) { // VERIFIED WORKS @@ -132,18 +130,14 @@ class Stretcher { stretchFactors.xFactor = playerAr / videoAr; stretchFactors.yFactor = actualAr / videoAr; - if(Debug.debug){ - console.log("[Stretcher.js::calculateStretch] stretching strategy 2") - } + this.logger.log('info', 'stretcher', "[Stretcher.js::calculateStretch] stretching strategy 2") } else { // NEEDS CHECKING // player > video > actual — double pillarbox stretchFactors.xFactor = actualAr / playerAr; stretchFactors.yFactor = 1; - if(Debug.debug){ - console.log("[Stretcher.js::calculateStretch] stretching strategy 3") - } + this.logger.log('info', 'stretcher', "[Stretcher.js::calculateStretch] stretching strategy 3") } } else { // player adds LETTERBOX @@ -156,9 +150,7 @@ class Stretcher { stretchFactors.xFactor = actualAr / playerAr; stretchFactors.yFactor = videoAr / playerAr; - if(Debug.debug){ - console.log("[Stretcher.js::calculateStretch] stretching strategy 4") - } + this.logger.log('info', 'stretcher', "[Stretcher.js::calculateStretch] stretching strategy 4") } else if ( actualAr < videoAr ) { // NEEDS CHECKING @@ -168,9 +160,7 @@ class Stretcher { stretchFactors.xFactor = actualAr / playerAr; stretchFActors.yFactor = actualAr / playerAr; - if(Debug.debug){ - console.log("[Stretcher.js::calculateStretch] stretching strategy 5") - } + this.logger.log('info', 'stretcher', "[Stretcher.js::calculateStretch] stretching strategy 5") } else { // VERIFIED CORRECT @@ -179,9 +169,7 @@ class Stretcher { stretchFactors.xFactor = 1; stretchFactors.yFactor = actualAr / playerAr; - if(Debug.debug){ - console.log("[Stretcher.js::calculateStretch] stretching strategy 6") - } + this.logger.log('info', 'stretcher', "[Stretcher.js::calculateStretch] stretching strategy 6") } } diff --git a/src/ext/lib/video-transform/Zoom.js b/src/ext/lib/video-transform/Zoom.js index 16ba9eb..649b2fb 100644 --- a/src/ext/lib/video-transform/Zoom.js +++ b/src/ext/lib/video-transform/Zoom.js @@ -5,13 +5,14 @@ import Debug from '../../conf/Debug'; class Zoom { // functions - constructor(videoData) { + constructor(videoData, logger) { this.scale = 1; this.logScale = 0; this.scaleStep = 0.1; this.minScale = -1; // 50% (log2(0.5) = -1) this.maxScale = 3; // 800% (log2(8) = 3) this.conf = videoData; + this.logger = logger; } reset(){ @@ -30,18 +31,14 @@ class Zoom { this.scale = Math.pow(2, this.logScale); - if (Debug.debug) { - console.log("[Zoom::zoomStep] changing zoom by", amount, ". New zoom level:", this.scale); - } + this.logger.log('info', 'debug', "[Zoom::zoomStep] changing zoom by", amount, ". New zoom level:", this.scale); this.conf.restoreAr(); this.conf.announceZoom(this.scale); } setZoom(scale, no_announce){ - if (Debug.debug) { - console.log("[Zoom::setZoom] Setting zoom to", scale, "!"); - } + this.logger.log('info', 'debug', "[Zoom::setZoom] Setting zoom to", scale, "!"); // NOTE: SCALE IS NOT LOGARITHMIC if(scale < Math.pow(2, this.minScale)) { @@ -62,16 +59,12 @@ class Zoom { if (!stretchFactors) { return; } - if (Debug.debug) { - console.log("[Zoom::setZoom] Applying zoom. Stretch factors pre:", stretchFactors, " —> scale:", this.scale); - } + this.logger.log('info', 'debug', "[Zoom::setZoom] Applying zoom. Stretch factors pre:", stretchFactors, " —> scale:", this.scale); stretchFactors.xFactor *= this.scale; stretchFactors.yFactor *= this.scale; - if (Debug.debug) { - console.log("[Zoom::setZoom] Applying zoom. Stretch factors post:", stretchFactors); - } + this.logger.log('info', 'debug', "[Zoom::setZoom] Applying zoom. Stretch factors post:", stretchFactors); } } diff --git a/src/ext/uw.js b/src/ext/uw.js index b553026..1a4b599 100644 --- a/src/ext/uw.js +++ b/src/ext/uw.js @@ -5,6 +5,7 @@ import Settings from './lib/Settings'; import ActionHandler from './lib/ActionHandler'; import CommsClient from './lib/comms/CommsClient'; import PageInfo from './lib/video-data/PageInfo'; +import Logger from './lib/Logger'; if(Debug.debug){ console.log("\n\n\n\n\n\n ——— Sᴛλʀᴛɪɴɢ Uʟᴛʀᴀᴡɪᴅɪꜰʏ ———\n << ʟᴏᴀᴅɪɴɢ ᴍᴀɪɴ ꜰɪʟᴇ >>\n\n\n\n"); @@ -30,6 +31,7 @@ class UW { this.comms = undefined; this.settings = undefined; this.actionHandler = undefined; + this.logger = undefined; } async init(){ @@ -39,9 +41,8 @@ class UW { // init() is re-run any time settings change if (this.pageInfo) { - if(Debug.debug){ - console.log("[uw::init] Destroying existing pageInfo", 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) { @@ -54,51 +55,45 @@ class UW { await this.settings.init(); } - this.comms = new CommsClient('content-client-port', this.settings); + if (!this.logger) { + this.logger = new Logger(this.settings.getLoggingOptions); + } + + this.comms = new CommsClient('content-client-port', this.settings, this.logger); // če smo razširitev onemogočili v nastavitvah, ne naredimo ničesar // If extension is soft-disabled, don't do shit var extensionMode = this.settings.getExtensionMode(); - if(Debug.debug) { - console.log("[uw::init] Extension mode:" + (extensionMode < 0 ? "disabled" : extensionMode == '1' ? 'basic' : 'full')); - } + this.logger.log('info', 'debug', "[uw::init] Extension mode:" + (extensionMode < 0 ? "disabled" : extensionMode == '1' ? 'basic' : 'full')); const isSiteDisabled = extensionMode === ExtensionMode.Disabled if (isSiteDisabled) { if (this.settings.getExtensionMode('@global') === ExtensionMode.Disabled) { - if (Debug.debug) { - console.log("[uw::init] EXTENSION DISABLED, THEREFORE WONT BE STARTED") - } + this.logger.log('info', 'debug', "[uw::init] EXTENSION DISABLED, THEREFORE WONT BE STARTED") return; } } try { - this.pageInfo = new PageInfo(this.comms, this.settings, extensionMode, isSiteDisabled); - if(Debug.debug){ - console.log("[uw.js::setup] pageInfo initialized. Here's the object:", this.pageInfo); - } + this.pageInfo = new PageInfo(this.comms, this.settings, this.logger, extensionMode, isSiteDisabled); + this.logger.log('info', 'debug', "[uw.js::setup] pageInfo initialized. Here's the object:", this.pageInfo); this.comms.setPageInfo(this.pageInfo); - if(Debug.debug) { - console.log("[uw.js::setup] will try to initate ActionHandler. Settings are:", this.settings, this.settings.active) - } + this.logger.log('info', 'debug', "[uw.js::setup] will try to initate ActionHandler. Settings are:", this.settings, this.settings.active) // start action handler only if extension is enabled for this site if (!isSiteDisabled) { - this.actionHandler = new ActionHandler(this.pageInfo); + this.actionHandler = new ActionHandler(this.pageInfo, this.logger); this.actionHandler.init(); - if(Debug.debug) { - console.log("[uw.js::setup] ActionHandler initiated:", this.actionHandler); - } + this.logger.log('info', 'debug', "[uw.js::setup] ActionHandler initiated:", this.actionHandler); } } catch (e) { - console.log("[uw::init] FAILED TO START EXTENSION. Error:", e); + this.logger.log('error', 'debug', "[uw::init] FAILED TO START EXTENSION. Error:", e); } From f41ffb315511095ea88ea2ff1f6477b04f794d98 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Sat, 20 Jul 2019 21:33:15 +0200 Subject: [PATCH 07/52] Readme updates for 4.3.0, version bump --- CHANGELOG.md | 11 ++++++++++- package.json | 2 +- src/popup/panels/WhatsNewPanel.vue | 8 ++++---- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac7fefb..c882050 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,16 @@ * Settings page looks ugly af right now. Maybe fix it some time later -### v4.2.1 (current) +### v4.3.0 (future release) + +* Added user-friendly way to export/import settings +* Reworked logging + +### v4.2.2 (current) + +* Fixed player detection on reddit (for videos from v.reddit) + +### v4.2.1 * Fixed bug where custom CSS didn't get applied to pages ### v4.2.0 diff --git a/package.json b/package.json index f421378..0ac84f1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ultravidify", - "version": "4.2.1", + "version": "4.3.0", "description": "Aspect ratio fixer for youtube that works around some people's disability to properly encode 21:9 (and sometimes, 16:9) videos.", "author": "Tamius Han ", "scripts": { diff --git a/src/popup/panels/WhatsNewPanel.vue b/src/popup/panels/WhatsNewPanel.vue index 4f62e9d..1a6ff74 100644 --- a/src/popup/panels/WhatsNewPanel.vue +++ b/src/popup/panels/WhatsNewPanel.vue @@ -2,17 +2,17 @@

What's new

Full changelog for older versions is available here.

-

4.2.2

+

4.3.0

+ This update mostly contains things that have the potential to make my life easier when solving issues.
    -
  • Fixed alignment issues for reddit on videos from v.reddit
  • +
  • User-friendly way of importing-exporting settings (exporting settings requires 'download' permission)
  • +
  • Reworked logging (basic). Logging can be enabled at runtime and and logs saved to a file. (Saving logs requires 'download' permission)
  • Some people reported issues with inconsistent video alignment on youtube. While I've not been able to make that bug happen to me, (which means I haven't been able to fix it either), reports describe behaviour similar to what was going on with Iridium. Examining the Iridium issue revealed an issue that could be potentially blamed for this behaviour. That issue was fixed. Since I've never been able to make this problem happen to me, I'm not being able to verify whether that issue is gone. If you're still experiencing issues with inconsistent video alignment, please contact me via github, reddit or email. See 'Report a problem' tab for more details.
- -
+ + diff --git a/src/popup/panels/SiteDetailsPanel.vue b/src/popup/panels/SiteDetailsPanel.vue index 8b5f659..aaea12d 100644 --- a/src/popup/panels/SiteDetailsPanel.vue +++ b/src/popup/panels/SiteDetailsPanel.vue @@ -1,5 +1,36 @@ From 6d564e2f984c90530f27764af65e9692873a3977 Mon Sep 17 00:00:00 2001 From: Tamius Han Date: Tue, 13 Aug 2019 22:31:25 +0200 Subject: [PATCH 09/52] Readied some things for the player selector thing, but in content scripts --- src/ext/lib/PlayerPickerHelper.js | 189 ++++++++++++++++++++++++++ src/popup/panels/SiteDetailsPanel.vue | 18 ++- 2 files changed, 204 insertions(+), 3 deletions(-) create mode 100644 src/ext/lib/PlayerPickerHelper.js diff --git a/src/ext/lib/PlayerPickerHelper.js b/src/ext/lib/PlayerPickerHelper.js new file mode 100644 index 0000000..e03eed2 --- /dev/null +++ b/src/ext/lib/PlayerPickerHelper.js @@ -0,0 +1,189 @@ +class PlayerPickerHelper { + constructor (settings, callbacks) { + this.settings = settings; + this.videos = document.selectElementsByTagName('video'); + this.selectedParentIndex = this.findPlayerForVideos(settings, this.videos)[0]; + this.savedCss = []; + this.markVideos(); + this.markIndexForAll(index); + this.markInitialQuerySelectors(); + } + + + + /* + * + * Internal functions + * + */ + saveBorder(element) { + if (this.savedCss.findIndex(x => x.element === element) !== -1) { + this.savedCss.push({element: element, border: element.style.border}); + } + } + restoreBorders() { + for (const e of this.savedCss) { + e.element.style.border = e.border; + } + } + + findPlayerForVideos(settings, videos) { + const playerIndexes = []; + for (const v of videos) { + playerIndexes.push(this.findPlayerForVideo(settings, v)); + } + return playerIndexes; + } + + findPlayerForVideo(settings, video) { + const host = window.location.host; + let element = video.parentNode; + + if (this.settings.active.sites[host] + && this.settings.active.sites[host].DOM + && this.settings.active.sites[host].DOM.player + && this.settings.active.sites[host].DOM.player.manual) { + if (this.settings.active.sites[host].DOM.player.useRelativeAncestor + && this.settings.active.sites[host].DOM.player.videoAncestor) { + + return this.settings.active.sites[host].DOM.player.videoAncestor; + } else if (this.settings.active.sites[host].DOM.player.querySelectors) { + const allSelectors = document.querySelectorAll(this.settings.active.sites[host].DOM.player.querySelectors); + let elementIndex = 1; + while (element && !this.collectionHas(allSelectors, element)) { + element = element.parentNode; + elementIndex++; + } + return elementIndex; + } + } + + let elementIndex = 0; + + var trustCandidateAfterGrows = 2; // if candidate_width or candidate_height increases in either dimensions this many + // times, we say we found our player. (This number ignores weird elements) + // in case our